| 1 | package net.minecraft.server.jsonrpc.api;
|
| 2 |
|
| 3 | import com.mojang.serialization.Codec;
|
| 4 | import com.mojang.serialization.MapCodec;
|
| 5 | import com.mojang.serialization.codecs.RecordCodecBuilder;
|
| 6 | import java.util.List;
|
| 7 | import java.util.Optional;
|
| 8 | import net.minecraft.resources.Identifier;
|
| 9 | import org.jspecify.annotations.Nullable;
|
| 10 |
|
| 11 | public record MethodInfo<Params, Result>(String description, Optional<ParamInfo<Params>> params, Optional<ResultInfo<Result>> result) {
|
| 12 | public MethodInfo(final String description, final @Nullable ParamInfo<Params> paramInfo, final @Nullable ResultInfo<Result> resultInfo) {
|
| 13 | this(description, Optional.ofNullable(paramInfo), Optional.ofNullable(resultInfo));
|
| 14 | }
|
| 15 |
|
| 16 | private static <Params> Optional<ParamInfo<Params>> toOptional(final List<ParamInfo<Params>> list) {
|
| 17 | return list.isEmpty() ? Optional.empty() : Optional.of(list.getFirst());
|
| 18 | }
|
| 19 |
|
| 20 | private static <Params> List<ParamInfo<Params>> toList(final Optional<ParamInfo<Params>> opt) {
|
| 21 | return opt.isPresent() ? List.of(opt.get()) : List.of();
|
| 22 | }
|
| 23 |
|
| 24 | private static <Params> Codec<Optional<ParamInfo<Params>>> paramsTypedCodec() {
|
| 25 | return ParamInfo.<Params>typedCodec().codec().listOf().xmap(MethodInfo::toOptional, MethodInfo::toList);
|
| 26 | }
|
| 27 |
|
| 28 | private static <Params, Result> MapCodec<MethodInfo<Params, Result>> typedCodec() {
|
| 29 | return RecordCodecBuilder.mapCodec(
|
| 30 | i -> i.group(
|
| 31 | Codec.STRING.fieldOf("description").forGetter(MethodInfo::description),
|
| 32 | paramsTypedCodec().fieldOf("params").forGetter(MethodInfo::params),
|
| 33 | ResultInfo.<Result>typedCodec().optionalFieldOf("result").forGetter(MethodInfo::result)
|
| 34 | )
|
| 35 | .apply(i, MethodInfo::new)
|
| 36 | );
|
| 37 | }
|
| 38 |
|
| 39 | public MethodInfo.Named<Params, Result> named(final Identifier name) {
|
| 40 | return new MethodInfo.Named<>(name, this);
|
| 41 | }
|
| 42 |
|
| 43 | public record Named<Params, Result>(Identifier name, MethodInfo<Params, Result> contents) {
|
| 44 | public static final Codec<MethodInfo.Named<?, ?>> CODEC = typedCodec();
|
| 45 |
|
| 46 | public static <Params, Result> Codec<MethodInfo.Named<Params, Result>> typedCodec() {
|
| 47 | return RecordCodecBuilder.create(
|
| 48 | i -> i.group(
|
| 49 | Identifier.CODEC.fieldOf("name").forGetter(MethodInfo.Named::name), MethodInfo.<Params, Result>typedCodec().forGetter(MethodInfo.Named::contents)
|
| 50 | )
|
| 51 | .apply(i, MethodInfo.Named::new)
|
| 52 | );
|
| 53 | }
|
| 54 | }
|
| 55 | }
|
| 56 |
|