From 9b1ad0715538d0a673ae2ce5f05b0a8c4a4f2015 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 12 Nov 2026 18:14:36 +0000 Subject: [PATCH] feat: package union, what generated code decodes unions and tagged structs with openapi-codegen writes the same JSON helpers into every library it generates: choosing a union's alternative, reading a discriminator first, checking a tagged struct's tag. They move here, unchanged but for their exported names, with tests of their own. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019QCb1AfnATvpBQCH3PrX7Y --- union/union.go | 758 ++++++++++++++++++++++++++++++++++++++++++++ union/union_test.go | 562 ++++++++++++++++++++++++++++++++ 2 files changed, 1320 insertions(+) create mode 100644 union/union.go create mode 100644 union/union_test.go diff --git a/union/union.go b/union/union.go new file mode 100644 index 0000000..00a8f35 --- /dev/null +++ b/union/union.go @@ -0,0 +1,758 @@ +// Package union holds what the code openapi-codegen generates decodes and encodes unions and tagged structs with: +// JSON values of several alternatives, of which the code chooses one by a discriminator, by the members an +// alternative requires and declares, or by a tag. It is generated code's, not an API of its own, and changes as the +// generator needs. +package union + +import ( + "bytes" + "encoding/json/jsontext" + "encoding/json/v2" + "errors" + "fmt" + "maps" + "slices" + "strconv" +) + +// Strict reports whether dec rejects members the specification does not know, as it does unless told otherwise. +func Strict(dec *jsontext.Decoder) bool { + v, ok := json.GetOption(dec.Options(), json.RejectUnknownMembers) + return v || !ok +} + +// UnknownName reports a member no part of the type declares, as encoding/json reports one of a struct. +func UnknownName(name string) error { + return &json.SemanticError{JSONKind: jsontext.KindString, Err: fmt.Errorf("%w %q", json.ErrUnknownName, name)} +} + +// Missing reports a member the type needs and the object lacks. +func Missing(name string) error { + return &json.SemanticError{JSONKind: jsontext.KindBeginObject, Err: fmt.Errorf("missing object member name %q", name)} +} + +// UnknownValue reports a value of the discriminator that names no alternative. +func UnknownValue(name, value string) error { + return &json.SemanticError{JSONKind: jsontext.KindString, JSONValue: jsontext.Value(strconv.Quote(value)), Err: fmt.Errorf("unknown value of %q", name)} +} + +// FirstMember reads the opening of a JSON object and its member name, which must have a string value. It returns +// the string, the value as written, and the decoder to read the object's further members from: dec itself when name +// comes first, the fast way, and otherwise one over the object read whole, with name moved to the front. +func FirstMember(dec *jsontext.Decoder, name string) (string, jsontext.Value, *jsontext.Decoder, error) { + if tok, err := dec.ReadToken(); err != nil { + return "", nil, nil, err + } else if tok.Kind() != jsontext.KindBeginObject { + return "", nil, nil, &json.SemanticError{JSONKind: tok.Kind(), Err: errors.New("want an object")} + } + + if dec.PeekKind() == jsontext.KindEndObject { + return "", nil, nil, Missing(name) + } + + tok, err := dec.ReadToken() + if err != nil { + return "", nil, nil, err + } + + if got := tok.String(); got != name { + // read the rest of the object, and start again with name first + var buf bytes.Buffer + + enc := jsontext.NewEncoder(&buf) + if err := enc.WriteToken(jsontext.BeginObject); err != nil { + return "", nil, nil, err + } + + if err := enc.WriteToken(jsontext.String(got)); err != nil { + return "", nil, nil, err + } + + for dec.PeekKind() != jsontext.KindEndObject { + val, err := dec.ReadValue() + if err != nil { + return "", nil, nil, err + } + + if err := enc.WriteValue(val); err != nil { + return "", nil, nil, err + } + + if dec.PeekKind() == jsontext.KindEndObject { + break + } + + tok, err := dec.ReadToken() + if err != nil { + return "", nil, nil, err + } + + if err := enc.WriteToken(tok); err != nil { + return "", nil, nil, err + } + } + + if _, err := dec.ReadToken(); err != nil { // the end of the object + return "", nil, nil, err + } + + if err := enc.WriteToken(jsontext.EndObject); err != nil { + return "", nil, nil, err + } + + ordered, err := First(buf.Bytes(), name, "") + if err != nil { + return "", nil, nil, err + } + + return FirstMember(jsontext.NewDecoder(bytes.NewReader(ordered), dec.Options()), name) + } + + val, err := dec.ReadValue() + if err != nil { + return "", nil, nil, err + } + + var tag string + if err := json.Unmarshal(val, &tag); err != nil { + return "", nil, nil, &json.SemanticError{JSONKind: val.Kind(), Err: fmt.Errorf("member %q is not a string", name)} + } + + return tag, val.Clone(), dec, nil +} + +// MembersFrom decodes the first member, already read, and every further member of the object dec is in, each +// into the field decode declares for it; a member it does not declare is an error, unless dec is lenient. +func MembersFrom(dec *jsontext.Decoder, firstName string, first jsontext.Value, decode func(*jsontext.Decoder, string) (bool, error)) error { + strict := Strict(dec) + + if ok, err := decode(jsontext.NewDecoder(bytes.NewReader(first), dec.Options()), firstName); err != nil { + return err + } else if !ok && strict { + return UnknownName(firstName) + } + + for dec.PeekKind() != jsontext.KindEndObject { + tok, err := dec.ReadToken() + if err != nil { + return err + } + + name := tok.String() // a token is void once the decoder reads on + + if ok, err := decode(dec, name); err != nil { + return err + } else if !ok && strict { + return UnknownName(name) + } else if !ok { + if err := dec.SkipValue(); err != nil { + return err + } + } + } + + _, err := dec.ReadToken() + + return err +} + +// Part is one of the parts an object decodes into: the members it declares and how it decodes one of them. +type Part struct { + Members map[string]bool + Decode func(*jsontext.Decoder, string) (bool, error) +} + +// PartsFrom is MembersFrom for an object that several parts declare members of. A member one part declares +// decodes straight from dec; one several declare is read once and decoded into each. +func PartsFrom(dec *jsontext.Decoder, firstName string, first jsontext.Value, parts []Part) error { + member := func(name string, val jsontext.Value) error { + var declaring []Part + for _, p := range parts { + if p.Members[name] { + declaring = append(declaring, p) + } + } + + switch { + case len(declaring) > 0: + case Strict(dec): + return UnknownName(name) + case val == nil: + return dec.SkipValue() + default: + return nil + } + + if val == nil && len(declaring) == 1 { + _, err := declaring[0].Decode(dec, name) + return err + } + + if val == nil { + v, err := dec.ReadValue() + if err != nil { + return err + } + + val = v.Clone() + } + + for _, p := range declaring { + if _, err := p.Decode(jsontext.NewDecoder(bytes.NewReader(val), dec.Options()), name); err != nil { + return err + } + } + + return nil + } + + if err := member(firstName, first); err != nil { + return err + } + + for dec.PeekKind() != jsontext.KindEndObject { + tok, err := dec.ReadToken() + if err != nil { + return err + } + + if err := member(tok.String(), nil); err != nil { + return err + } + } + + _, err := dec.ReadToken() + + return err +} + +// First returns the JSON object raw with its member name first, as decoding by a discriminator wants it. If value +// is known, the member must have it, and is written in if raw lacks it or leaves it empty. raw is returned as it is if +// all is in order. +func First(raw jsontext.Value, name, value string) (jsontext.Value, error) { + dec := jsontext.NewDecoder(bytes.NewReader(raw)) + if _, err := dec.ReadToken(); err != nil { + return nil, err + } + + if dec.PeekKind() != jsontext.KindEndObject { + tok, err := dec.ReadToken() + if err != nil { + return nil, err + } + + if tok.String() == name { + if value == "" { + return raw, nil + } + + val, err := dec.ReadToken() + if err != nil { + return nil, err + } + + switch got := val.String(); got { + case value: + return raw, nil + case "": // left for the union to fill in, below + default: + return nil, &json.SemanticError{Err: fmt.Errorf("member %q is %q, want %q", name, got, value)} + } + } + } + + names, err := Members(raw) + if err != nil { + return nil, err + } + + var first jsontext.Value + switch { + case slices.Contains(names, name): + if first, err = Select(raw, map[string]bool{name: true}); err != nil { + return nil, err + } + + if value == "" { + break + } + + got, err := MemberString(first, name) + switch { + case err != nil: + return nil, err + case got == "": // left empty: the union knows what it holds + rest := make(map[string]bool, len(names)) + for _, n := range names { + rest[n] = n != name + } + + if raw, err = Select(raw, rest); err != nil { + return nil, err + } + + if first, err = json.Marshal(map[string]string{name: value}); err != nil { + return nil, err + } + case got != value: + return nil, &json.SemanticError{Err: fmt.Errorf("member %q is %q, want %q", name, got, value)} + } + case value != "": + member, err := json.Marshal(map[string]string{name: value}) + if err != nil { + return nil, err + } + + first = member + default: + return nil, Missing(name) + } + + return Merge(first, raw) +} + +// MemberString returns the string value of the member name of the JSON object raw, reading no further than it. +func MemberString(raw jsontext.Value, name string) (string, error) { + dec := jsontext.NewDecoder(bytes.NewReader(raw)) + if tok, err := dec.ReadToken(); err != nil { + return "", err + } else if tok.Kind() != jsontext.KindBeginObject { + return "", &json.SemanticError{JSONKind: tok.Kind(), Err: errors.New("want an object")} + } + + for dec.PeekKind() != jsontext.KindEndObject { + tok, err := dec.ReadToken() + if err != nil { + return "", err + } + + if tok.String() != name { + if err := dec.SkipValue(); err != nil { + return "", err + } + + continue + } + + val, err := dec.ReadToken() + if err != nil { + return "", err + } + + if val.Kind() != jsontext.KindString { + return "", &json.SemanticError{JSONKind: val.Kind(), Err: fmt.Errorf("member %q is not a string", name)} + } + + return val.String(), nil + } + + return "", Missing(name) +} + +// Members returns the names of the members of the JSON object raw, in order. +func Members(raw jsontext.Value) ([]string, error) { + dec := jsontext.NewDecoder(bytes.NewReader(raw)) + if tok, err := dec.ReadToken(); err != nil { + return nil, err + } else if tok.Kind() != jsontext.KindBeginObject { + return nil, &json.SemanticError{JSONKind: tok.Kind(), Err: errors.New("want an object")} + } + + var names []string + for dec.PeekKind() != jsontext.KindEndObject { + tok, err := dec.ReadToken() + if err != nil { + return nil, err + } + + names = append(names, tok.String()) + + if err := dec.SkipValue(); err != nil { + return nil, err + } + } + + return names, nil +} + +// Select returns the JSON object raw with only the members keep holds. +func Select(raw jsontext.Value, keep map[string]bool) (jsontext.Value, error) { + dec := jsontext.NewDecoder(bytes.NewReader(raw)) + if _, err := dec.ReadToken(); err != nil { + return nil, err + } + + var buf bytes.Buffer + + enc := jsontext.NewEncoder(&buf) + if err := enc.WriteToken(jsontext.BeginObject); err != nil { + return nil, err + } + + for dec.PeekKind() != jsontext.KindEndObject { + tok, err := dec.ReadToken() + if err != nil { + return nil, err + } + + name := tok.String() // a token is void once the decoder reads on + + val, err := dec.ReadValue() + if err != nil { + return nil, err + } + + if !keep[name] { + continue + } + + if err := enc.WriteToken(jsontext.String(name)); err != nil { + return nil, err + } + + if err := enc.WriteValue(val); err != nil { + return nil, err + } + } + + if err := enc.WriteToken(jsontext.EndObject); err != nil { + return nil, err + } + + return bytes.TrimSpace(buf.Bytes()), nil +} + +// Merge returns the members of the JSON objects a and b in one object. A member both hold must have the same +// value in each. +func Merge(a, b jsontext.Value) (jsontext.Value, error) { + var buf bytes.Buffer + + enc := jsontext.NewEncoder(&buf) + if err := enc.WriteToken(jsontext.BeginObject); err != nil { + return nil, err + } + + written := map[string]jsontext.Value{} + for _, raw := range []jsontext.Value{a, b} { + dec := jsontext.NewDecoder(bytes.NewReader(raw)) + if _, err := dec.ReadToken(); err != nil { + return nil, err + } + + for dec.PeekKind() != jsontext.KindEndObject { + tok, err := dec.ReadToken() + if err != nil { + return nil, err + } + + name := tok.String() // a token is void once the decoder reads on + + val, err := dec.ReadValue() + if err != nil { + return nil, err + } + + if prev, ok := written[name]; ok { + if err := prev.Canonicalize(); err != nil { + return nil, err + } + + cur := val.Clone() + if err := cur.Canonicalize(); err != nil { + return nil, err + } + + if !bytes.Equal(prev, cur) { + return nil, &json.SemanticError{Err: fmt.Errorf("member %q is %s in one part and %s in another", name, prev, cur)} + } + + continue + } + + written[name] = val.Clone() + + if err := enc.WriteToken(jsontext.String(name)); err != nil { + return nil, err + } + + if err := enc.WriteValue(val); err != nil { + return nil, err + } + } + } + + if err := enc.WriteToken(jsontext.EndObject); err != nil { + return nil, err + } + + return bytes.TrimSpace(buf.Bytes()), nil +} + +// Variant is an alternative of a union: its value of the discriminator, the members it declares and those it +// requires. +type Variant struct { + Value string + Members map[string]bool + Required []string + // Nullable are the members of Required that may be null. + Nullable map[string]bool + // Pinned are the members it allows one value for, written as compact JSON. + Pinned map[string]string + // Enums are the members it allows the values of an enum for, written so. + Enums map[string][]string +} + +// EnumsFit reports whether each member of the JSON object raw that enums names has one of the values it allows, +// written as compact JSON. +func EnumsFit(raw jsontext.Value, enums map[string][]string) bool { + if len(enums) == 0 { + return true + } + + dec := jsontext.NewDecoder(bytes.NewReader(raw)) + if tok, err := dec.ReadToken(); err != nil || tok.Kind() != jsontext.KindBeginObject { + return false + } + + for dec.PeekKind() != jsontext.KindEndObject { + tok, err := dec.ReadToken() + if err != nil { + return false + } + + name := tok.String() + + val, err := dec.ReadValue() + if err != nil { + return false + } + + if allowed, ok := enums[name]; ok { + got := val.Clone() + if err := got.Compact(); err != nil || !slices.Contains(allowed, string(got)) { + return false + } + } + } + + return true +} + +// EnumPasses are whether to check enums in each attempt at choosing an alternative: strict, always; leniently, +// first, then not, should no alternative fit, as an API may add a value to an enum. +func EnumPasses(strict bool) []bool { + if strict { + return []bool{true} + } + + return []bool{true, false} +} + +// Fits reports whether the JSON value raw has the members required, and those of pinned it has with the value +// each pins, written as compact JSON. A member that is null is there only where nullable allows it to be. Any value +// fits where nothing is required or pinned. +func Fits(raw jsontext.Value, required []string, nullable map[string]bool, pinned map[string]string) bool { + if len(required) == 0 && len(pinned) == 0 { + return true + } + + if raw.Kind() != jsontext.KindBeginObject { + return false + } + + dec := jsontext.NewDecoder(bytes.NewReader(raw)) + if _, err := dec.ReadToken(); err != nil { + return false + } + + present := map[string]bool{} + + for dec.PeekKind() != jsontext.KindEndObject { + tok, err := dec.ReadToken() + if err != nil { + return false + } + + name := tok.String() + + val, err := dec.ReadValue() + if err != nil { + return false + } + + present[name] = val.Kind() != jsontext.KindNull || nullable[name] + + if want, ok := pinned[name]; ok { + got := val.Clone() + if err := got.Compact(); err != nil || string(got) != want { + return false + } + } + } + + for _, r := range required { + if !present[r] { + return false + } + } + + return true +} + +// ChooseVariants returns the alternatives the JSON object raw is: the one its discriminator names, if there is +// one, else those whose required members it has and whose members it holds, besides those of plain. Every member +// must belong to plain or to a chosen alternative. Not strict, a member nothing declares is left out of the choice, +// and of several alternatives of a oneOf the first is chosen. +func ChooseVariants(raw jsontext.Value, discriminator string, variants []Variant, plain map[string]bool, oneOf, strict bool) ([]int, error) { + names, err := Members(raw) + if err != nil { + return nil, err + } + + if !strict { + names = slices.DeleteFunc(names, func(n string) bool { + return !plain[n] && !slices.ContainsFunc(variants, func(v Variant) bool { return v.Members[n] }) + }) + } + + present := make(map[string]bool, len(names)) + for _, n := range names { + present[n] = true + } + + var chosen []int + if discriminator != "" { + tag, err := MemberString(raw, discriminator) + if err != nil { + return nil, err + } + + for i, v := range variants { + if v.Value == tag { + chosen = append(chosen, i) + } + } + + if len(chosen) == 0 { + return nil, UnknownValue(discriminator, tag) + } + } else { + variants: + for i, v := range variants { + if !Fits(raw, v.Required, v.Nullable, v.Pinned) { + continue variants + } + + for _, n := range names { + if !plain[n] && !v.Members[n] { + continue variants + } + } + + chosen = append(chosen, i) + } + + // a member outside its enum rules an alternative out; leniently, only while another fits + fit := slices.DeleteFunc(slices.Clone(chosen), func(i int) bool { return !EnumsFit(raw, variants[i].Enums) }) + if len(fit) > 0 || strict { + chosen = fit + } + + switch { + case len(chosen) == 0: + return nil, &json.SemanticError{Err: errors.New("matches none of its alternatives")} + case oneOf && len(chosen) > 1 && strict: + return nil, &json.SemanticError{Err: fmt.Errorf("matches %d of its alternatives, want exactly one", len(chosen))} + case oneOf: + chosen = chosen[:1] + } + } + + for _, n := range names { + if plain[n] { + continue + } + + known := false + for _, i := range chosen { + known = known || variants[i].Members[n] + } + + if !known { + return nil, UnknownName(n) + } + } + + return chosen, nil +} + +// TagNeed is how an alternative needs a member of its own. +type TagNeed int + +const ( + TagOptional TagNeed = iota + TagRequired + TagRequiredOrNull +) + +// CheckTag reports an error unless set, the members of an alternative's own whose fields are set, holds only +// members of the alternative the value tag of the tag name names, and the members it requires are there: in present, +// the members of the object decoded, null ones included, or, encoding, with present nil, in set, where a member that +// may be null cannot be told from one left out. Not strict, set may hold others too. +func CheckTag(name, tag string, tags map[string]map[string]TagNeed, set, present []string, strict bool) error { + members, ok := tags[tag] + switch { + case tag == "": + return Missing(name) + case !ok: + return UnknownValue(name, tag) + } + + for _, s := range set { + if _, ok := members[s]; strict && !ok { + return &json.SemanticError{JSONKind: jsontext.KindBeginObject, Err: fmt.Errorf("%s %q does not allow member %q", name, tag, s)} + } + } + + for _, m := range slices.Sorted(maps.Keys(members)) { + switch need := members[m]; { + case present != nil && need != TagOptional && !slices.Contains(present, m), + present == nil && need == TagRequired && !slices.Contains(set, m): + return Missing(m) + } + } + + return nil +} + +// InferTag returns the value of a tag whose alternative is the one of tags that set, the members of an +// alternative's own that are set, names: the one set member is a value whose alternative allows all of set. +func InferTag(tags map[string]map[string]TagNeed, set []string) (string, bool) { + tag := "" + + for _, s := range set { + members, ok := tags[s] + if !ok || !allIn(set, members) { + continue + } + + if tag != "" { + return "", false + } + + tag = s + } + + return tag, tag != "" +} + +// allIn reports whether every one of names is a key of m. +func allIn(names []string, m map[string]TagNeed) bool { + for _, n := range names { + if _, ok := m[n]; !ok { + return false + } + } + + return true +} diff --git a/union/union_test.go b/union/union_test.go new file mode 100644 index 0000000..61bab5f --- /dev/null +++ b/union/union_test.go @@ -0,0 +1,562 @@ +package union_test + +import ( + "encoding/json/jsontext" + "encoding/json/v2" + "errors" + "slices" + "strings" + "testing" + + "github.com/go-api-libs/api/union" +) + +func decoder(s string, opts ...jsontext.Options) *jsontext.Decoder { + return jsontext.NewDecoder(strings.NewReader(s), opts...) +} + +func wantErr(t *testing.T, err error, contains string) { + t.Helper() + + if err == nil { + t.Fatalf("got no error, want one with %q", contains) + } + + if !strings.Contains(err.Error(), contains) { + t.Fatalf("got %v, want one with %q", err, contains) + } +} + +func TestStrict(t *testing.T) { + if !union.Strict(decoder(`{}`)) { + t.Error("a decoder told nothing: not strict") + } + + if union.Strict(decoder(`{}`, json.RejectUnknownMembers(false))) { + t.Error("a lenient decoder: strict") + } + + if !union.Strict(decoder(`{}`, json.RejectUnknownMembers(true))) { + t.Error("a strict decoder: not strict") + } +} + +func TestErrors(t *testing.T) { + for _, tc := range []struct { + err error + contains string + }{ + {union.UnknownName("x"), `unknown object member name "x"`}, + {union.Missing("x"), `missing object member name "x"`}, + {union.UnknownValue("type", "y"), `unknown value of "type"`}, + } { + if _, ok := errors.AsType[*json.SemanticError](tc.err); !ok { + t.Errorf("%v: not a *json.SemanticError", tc.err) + } + + wantErr(t, tc.err, tc.contains) + } + + if !errors.Is(union.UnknownName("x"), json.ErrUnknownName) { + t.Error("UnknownName is not json.ErrUnknownName") + } +} + +func TestFirstMember(t *testing.T) { + t.Run("first, the fast way", func(t *testing.T) { + dec := decoder(`{"type":"a","x":1}`) + + tag, val, rest, err := union.FirstMember(dec, "type") + if err != nil || tag != "a" || string(val) != `"a"` || rest != dec { + t.Fatalf("got %q, %s, same decoder %v, %v", tag, val, rest == dec, err) + } + + if tok, err := rest.ReadToken(); err != nil || tok.String() != "x" { + t.Fatalf("then got %v, %v, want member x", tok, err) + } + }) + + t.Run("later, moved to the front", func(t *testing.T) { + tag, _, rest, err := union.FirstMember(decoder(`{"x":1,"y":[2],"type":"a"}`), "type") + if err != nil || tag != "a" { + t.Fatalf("got %q, %v", tag, err) + } + + var names []string + for rest.PeekKind() != jsontext.KindEndObject { + tok, err := rest.ReadToken() + if err != nil { + t.Fatal(err) + } + + names = append(names, tok.String()) + + if err := rest.SkipValue(); err != nil { + t.Fatal(err) + } + } + + if !slices.Equal(names, []string{"x", "y"}) { + t.Errorf("then got %q, want the rest in order", names) + } + }) + + for _, tc := range []struct { + name, in, contains string + }{ + {"not an object", `[1]`, "want an object"}, + {"empty", `{}`, `missing object member name "type"`}, + {"not a string", `{"type":1}`, `member "type" is not a string`}, + {"later, and missing", `{"x":1}`, `missing object member name "type"`}, + {"broken", `{"type"`, "EOF"}, + {"nothing", ``, "EOF"}, + {"broken later", `{"x":1,`, "EOF"}, + } { + t.Run(tc.name, func(t *testing.T) { + _, _, _, err := union.FirstMember(decoder(tc.in), "type") + wantErr(t, err, tc.contains) + }) + } +} + +// fields decodes the members it is given into a map, and declares only those of declared. +type fields struct { + declared map[string]bool + got map[string]string + fail string +} + +func (f *fields) decode(dec *jsontext.Decoder, name string) (bool, error) { + if !f.declared[name] { + return false, nil + } + + if name == f.fail { + return true, errors.New("cannot decode " + name) + } + + val, err := dec.ReadValue() + if err != nil { + return true, err + } + + if f.got == nil { + f.got = map[string]string{} + } + + f.got[name] = string(val) + + return true, nil +} + +func TestMembersFrom(t *testing.T) { + read := func(s string, opts ...jsontext.Options) (*jsontext.Decoder, string, jsontext.Value) { + dec := decoder(s, opts...) + _, _ = dec.ReadToken() + tok, _ := dec.ReadToken() + name := tok.String() + val, _ := dec.ReadValue() + + return dec, name, val.Clone() + } + + t.Run("decodes each member", func(t *testing.T) { + f := &fields{declared: map[string]bool{"a": true, "b": true}} + + dec, name, val := read(`{"a":1,"b":"x"}`) + if err := union.MembersFrom(dec, name, val, f.decode); err != nil { + t.Fatal(err) + } + + if f.got["a"] != "1" || f.got["b"] != `"x"` { + t.Errorf("got %v", f.got) + } + }) + + t.Run("strict, a member not declared", func(t *testing.T) { + f := &fields{declared: map[string]bool{"a": true}} + dec, name, val := read(`{"a":1,"c":2}`) + wantErr(t, union.MembersFrom(dec, name, val, f.decode), `"c"`) + + dec, name, val = read(`{"c":2}`) + wantErr(t, union.MembersFrom(dec, name, val, f.decode), `"c"`) + }) + + t.Run("leniently, a member not declared is skipped", func(t *testing.T) { + f := &fields{declared: map[string]bool{"a": true}} + + dec, name, val := read(`{"a":1,"c":{"d":[3]}}`, json.RejectUnknownMembers(false)) + if err := union.MembersFrom(dec, name, val, f.decode); err != nil { + t.Fatal(err) + } + + if len(f.got) != 1 { + t.Errorf("got %v", f.got) + } + }) + + t.Run("a member that does not decode", func(t *testing.T) { + f := &fields{declared: map[string]bool{"a": true, "b": true}, fail: "b"} + dec, name, val := read(`{"a":1,"b":2}`) + wantErr(t, union.MembersFrom(dec, name, val, f.decode), "cannot decode b") + + f.fail = "a" + dec, name, val = read(`{"a":1,"b":2}`) + wantErr(t, union.MembersFrom(dec, name, val, f.decode), "cannot decode a") + }) +} + +func TestPartsFrom(t *testing.T) { + read := func(s string, opts ...jsontext.Options) (*jsontext.Decoder, string, jsontext.Value) { + dec := decoder(s, opts...) + _, _ = dec.ReadToken() + tok, _ := dec.ReadToken() + name := tok.String() + val, _ := dec.ReadValue() + + return dec, name, val.Clone() + } + + parts := func(a, b *fields) []union.Part { + return []union.Part{{Members: a.declared, Decode: a.decode}, {Members: b.declared, Decode: b.decode}} + } + + t.Run("each member into the parts that declare it", func(t *testing.T) { + a := &fields{declared: map[string]bool{"type": true, "id": true}} + b := &fields{declared: map[string]bool{"type": true, "text": true}} + + dec, name, val := read(`{"type":"p","id":1,"text":"hi"}`) + if err := union.PartsFrom(dec, name, val, parts(a, b)); err != nil { + t.Fatal(err) + } + + if a.got["type"] != `"p"` || b.got["type"] != `"p"` || a.got["id"] != "1" || b.got["text"] != `"hi"` { + t.Errorf("got %v and %v", a.got, b.got) + } + }) + + t.Run("a later member several parts declare", func(t *testing.T) { + a := &fields{declared: map[string]bool{"type": true, "id": true}} + b := &fields{declared: map[string]bool{"type": true, "id": true}} + + dec, name, val := read(`{"type":"p","id":1}`) + if err := union.PartsFrom(dec, name, val, parts(a, b)); err != nil { + t.Fatal(err) + } + + if a.got["id"] != "1" || b.got["id"] != "1" { + t.Errorf("got %v and %v", a.got, b.got) + } + }) + + t.Run("strict, a member no part declares", func(t *testing.T) { + a := &fields{declared: map[string]bool{"type": true}} + b := &fields{declared: map[string]bool{}} + dec, name, val := read(`{"type":"p","new":1}`) + wantErr(t, union.PartsFrom(dec, name, val, parts(a, b)), `"new"`) + }) + + t.Run("leniently, a member no part declares is skipped", func(t *testing.T) { + a := &fields{declared: map[string]bool{"id": true}} + b := &fields{declared: map[string]bool{}} + + dec, name, val := read(`{"type":"p","new":[1],"id":2}`, json.RejectUnknownMembers(false)) + if err := union.PartsFrom(dec, name, val, parts(a, b)); err != nil { + t.Fatal(err) + } + + if a.got["id"] != "2" { + t.Errorf("got %v", a.got) + } + }) + + t.Run("a member that does not decode", func(t *testing.T) { + a := &fields{declared: map[string]bool{"type": true, "id": true}, fail: "id"} + b := &fields{declared: map[string]bool{"type": true, "id": true}} + dec, name, val := read(`{"type":"p","id":1}`) + wantErr(t, union.PartsFrom(dec, name, val, parts(a, b)), "cannot decode id") + + a = &fields{declared: map[string]bool{"type": true, "id": true}, fail: "id"} + b = &fields{declared: map[string]bool{"type": true}} + dec, name, val = read(`{"type":"p","id":1}`) + wantErr(t, union.PartsFrom(dec, name, val, parts(a, b)), "cannot decode id") + }) + + t.Run("broken", func(t *testing.T) { + a := &fields{declared: map[string]bool{"type": true, "id": true}} + b := &fields{declared: map[string]bool{"id": true}} + dec, name, val := read(`{"type":"p","id":`) + wantErr(t, union.PartsFrom(dec, name, val, parts(a, b)), "EOF") + + dec, name, val = read(`{"type":"p",`) + wantErr(t, union.PartsFrom(dec, name, val, parts(a, b)), "EOF") + }) +} + +func TestFirst(t *testing.T) { + for _, tc := range []struct { + name, raw, value, want string + }{ + {"first already", `{"type":"a","x":1}`, "", `{"type":"a","x":1}`}, + {"first with the value", `{"type":"a","x":1}`, "a", `{"type":"a","x":1}`}, + {"later", `{"x":1,"type":"a"}`, "", `{"type":"a","x":1}`}, + {"later with the value", `{"x":1,"type":"a"}`, "a", `{"type":"a","x":1}`}, + {"left empty first", `{"type":"","x":1}`, "a", `{"type":"a","x":1}`}, + {"left empty later", `{"x":1,"type":""}`, "a", `{"type":"a","x":1}`}, + {"left out, the value known", `{"x":1}`, "a", `{"type":"a","x":1}`}, + {"left out of an empty object", `{}`, "a", `{"type":"a"}`}, + } { + t.Run(tc.name, func(t *testing.T) { + got, err := union.First(jsontext.Value(tc.raw), "type", tc.value) + if err != nil || string(got) != tc.want { + t.Fatalf("got %s, %v, want %s", got, err, tc.want) + } + }) + } + + for _, tc := range []struct { + name, raw, value, contains string + }{ + {"another value first", `{"type":"b"}`, "a", `member "type" is "b", want "a"`}, + {"another value later", `{"x":1,"type":"b"}`, "a", `member "type" is "b", want "a"`}, + {"not a string later", `{"x":1,"type":1}`, "a", `member "type" is not a string`}, + {"left out, the value not known", `{"x":1}`, "", `missing object member name "type"`}, + {"broken", `{"x"`, "", "EOF"}, + {"nothing", ``, "", "EOF"}, + } { + t.Run(tc.name, func(t *testing.T) { + _, err := union.First(jsontext.Value(tc.raw), "type", tc.value) + wantErr(t, err, tc.contains) + }) + } +} + +func TestMemberString(t *testing.T) { + if got, err := union.MemberString(jsontext.Value(`{"x":[1],"type":"a","y":2}`), "type"); err != nil || got != "a" { + t.Fatalf("got %q, %v", got, err) + } + + for in, contains := range map[string]string{ + `[1]`: "want an object", + `{"type":1}`: `member "type" is not a string`, + `{"x":1}`: `missing object member name "type"`, + `{"x":`: "EOF", + `{"type":`: "EOF", + `{"x":1,"y"`: "EOF", + ``: "EOF", + `{"x":[1,2,]`: "invalid", + } { + _, err := union.MemberString(jsontext.Value(in), "type") + wantErr(t, err, contains) + } +} + +func TestMembers(t *testing.T) { + if got, err := union.Members(jsontext.Value(`{"b":1,"a":{"c":2}}`)); err != nil || !slices.Equal(got, []string{"b", "a"}) { + t.Fatalf("got %q, %v", got, err) + } + + for in, contains := range map[string]string{`[1]`: "want an object", `{"a":`: "EOF", ``: "EOF", `{"a"`: "EOF"} { + _, err := union.Members(jsontext.Value(in)) + wantErr(t, err, contains) + } +} + +func TestSelect(t *testing.T) { + got, err := union.Select(jsontext.Value(`{"a":1,"b":[2],"c":3}`), map[string]bool{"a": true, "c": true}) + if err != nil || string(got) != `{"a":1,"c":3}` { + t.Fatalf("got %s, %v", got, err) + } + + for _, in := range []string{``, `{"a":`, `{"a"`} { + if _, err := union.Select(jsontext.Value(in), nil); err == nil { + t.Errorf("%q: got no error", in) + } + } +} + +func TestMerge(t *testing.T) { + got, err := union.Merge(jsontext.Value(`{"a":1,"b":{"x":1,"y":2}}`), jsontext.Value(`{"b":{"y":2,"x":1},"c":3}`)) + if err != nil || string(got) != `{"a":1,"b":{"x":1,"y":2},"c":3}` { + t.Fatalf("got %s, %v", got, err) + } + + _, err = union.Merge(jsontext.Value(`{"a":1}`), jsontext.Value(`{"a":2}`)) + wantErr(t, err, `member "a" is 1 in one part and 2 in another`) + + for _, tc := range [][2]string{{``, `{}`}, {`{}`, `{"a":`}, {`{"a"`, `{}`}} { + if _, err := union.Merge(jsontext.Value(tc[0]), jsontext.Value(tc[1])); err == nil { + t.Errorf("%q and %q: got no error", tc[0], tc[1]) + } + } +} + +func TestEnumsFit(t *testing.T) { + enums := map[string][]string{"color": {`"red"`, `"blue"`}} + + for raw, want := range map[string]bool{ + `{"color":"red","x":1}`: true, + `{"color": "blue"}`: true, + `{"x":1}`: true, + `{"color":"green"}`: false, + `[1]`: false, + `{"color"`: false, + `{"x":`: false, + } { + if got := union.EnumsFit(jsontext.Value(raw), enums); got != want { + t.Errorf("%s: got %v, want %v", raw, got, want) + } + } + + if !union.EnumsFit(jsontext.Value(`"anything"`), nil) { + t.Error("no enums: does not fit") + } +} + +func TestEnumPasses(t *testing.T) { + if got := union.EnumPasses(true); !slices.Equal(got, []bool{true}) { + t.Errorf("strict: got %v", got) + } + + if got := union.EnumPasses(false); !slices.Equal(got, []bool{true, false}) { + t.Errorf("lenient: got %v", got) + } +} + +func TestFits(t *testing.T) { + for _, tc := range []struct { + name string + raw string + required []string + nullable map[string]bool + pinned map[string]string + want bool + }{ + {"nothing asked", `"any"`, nil, nil, nil, true}, + {"not an object", `[1]`, []string{"a"}, nil, nil, false}, + {"required there", `{"a":1,"b":2}`, []string{"a"}, nil, nil, true}, + {"required missing", `{"b":2}`, []string{"a"}, nil, nil, false}, + {"required null", `{"a":null}`, []string{"a"}, nil, nil, false}, + {"required null, and it may be", `{"a":null}`, []string{"a"}, map[string]bool{"a": true}, nil, true}, + {"pinned to its value", `{"kind": "x"}`, nil, nil, map[string]string{"kind": `"x"`}, true}, + {"pinned to another", `{"kind":"y"}`, nil, nil, map[string]string{"kind": `"x"`}, false}, + {"pinned, left out", `{"a":1}`, nil, nil, map[string]string{"kind": `"x"`}, true}, + {"broken", `{"a":`, []string{"a"}, nil, nil, false}, + {"broken name", `{"a"`, []string{"a"}, nil, nil, false}, + } { + if got := union.Fits(jsontext.Value(tc.raw), tc.required, tc.nullable, tc.pinned); got != tc.want { + t.Errorf("%s: got %v, want %v", tc.name, got, tc.want) + } + } +} + +func TestChooseVariants(t *testing.T) { + cat := union.Variant{Value: "cat", Members: map[string]bool{"kind": true, "meow": true}, Required: []string{"meow"}} + dog := union.Variant{Value: "dog", Members: map[string]bool{"kind": true, "bark": true}, Required: []string{"bark"}} + pet := union.Variant{Value: "pet", Members: map[string]bool{"kind": true, "meow": true, "bark": true}} + red := union.Variant{Value: "red", Members: map[string]bool{"color": true}, Enums: map[string][]string{"color": {`"red"`}}} + blue := union.Variant{Value: "blue", Members: map[string]bool{"color": true}, Enums: map[string][]string{"color": {`"blue"`}}} + plain := map[string]bool{"id": true} + + for _, tc := range []struct { + name string + raw string + discriminator string + variants []union.Variant + oneOf, strict bool + want []int + }{ + {"by the discriminator", `{"kind":"dog","bark":true}`, "kind", []union.Variant{cat, dog}, true, true, []int{1}}, + {"by the members required", `{"meow":true,"id":1}`, "", []union.Variant{cat, dog}, true, true, []int{0}}, + {"oneOf, leniently the first of several", `{"meow":true}`, "", []union.Variant{cat, pet}, true, false, []int{0}}, + {"anyOf, all that fit", `{"meow":true}`, "", []union.Variant{cat, pet}, false, true, []int{0, 1}}, + {"by its enum", `{"color":"blue"}`, "", []union.Variant{red, blue}, true, true, []int{1}}, + {"leniently, outside every enum", `{"color":"green"}`, "", []union.Variant{red, blue}, true, false, []int{0}}, + {"leniently, a member nothing declares", `{"meow":true,"new":1}`, "", []union.Variant{cat, dog}, true, false, []int{0}}, + } { + got, err := union.ChooseVariants(jsontext.Value(tc.raw), tc.discriminator, tc.variants, plain, tc.oneOf, tc.strict) + if err != nil || !slices.Equal(got, tc.want) { + t.Errorf("%s: got %v, %v, want %v", tc.name, got, err, tc.want) + } + } + + for _, tc := range []struct { + name, raw, discriminator string + variants []union.Variant + oneOf, strict bool + contains string + }{ + {"a value of the discriminator none has", `{"kind":"cow"}`, "kind", []union.Variant{cat, dog}, true, true, `unknown value of "kind"`}, + {"without the discriminator", `{"meow":true}`, "kind", []union.Variant{cat, dog}, true, true, `missing object member name "kind"`}, + {"none fits", `{"moo":true}`, "", []union.Variant{cat, dog}, true, false, "matches none of its alternatives"}, + {"oneOf, strict, several fit", `{"meow":true}`, "", []union.Variant{cat, pet}, true, true, "matches 2 of its alternatives, want exactly one"}, + {"strict, outside every enum", `{"color":"green"}`, "", []union.Variant{red, blue}, true, true, "matches none of its alternatives"}, + {"strict, a member the chosen does not declare", `{"kind":"cat","meow":true,"bark":true}`, "kind", []union.Variant{cat, dog}, true, true, `"bark"`}, + {"not an object", `[1]`, "", []union.Variant{cat}, true, true, "want an object"}, + } { + _, err := union.ChooseVariants(jsontext.Value(tc.raw), tc.discriminator, tc.variants, plain, tc.oneOf, tc.strict) + if err == nil || !strings.Contains(err.Error(), tc.contains) { + t.Errorf("%s: got %v, want an error with %q", tc.name, err, tc.contains) + } + } +} + +func TestCheckTag(t *testing.T) { + tags := map[string]map[string]union.TagNeed{ + "text": {"text": union.TagRequired, "color": union.TagOptional}, + "image": {"image": union.TagRequiredOrNull}, + } + + for _, tc := range []struct { + name string + tag string + set, present []string + strict bool + contains string // empty for no error + }{ + {"decoded, all there", "text", []string{"text"}, []string{"type", "text"}, true, ""}, + {"decoded, a member that may be null, null", "image", nil, []string{"type", "image"}, true, ""}, + {"decoded, a required member missing", "text", nil, []string{"type"}, true, `missing object member name "text"`}, + {"decoded, a member that may be null, missing", "image", nil, []string{"type"}, true, `missing object member name "image"`}, + {"encoded, all there", "text", []string{"text", "color"}, nil, true, ""}, + {"encoded, a member that may be null, left out", "image", nil, nil, true, ""}, + {"encoded, a required member left out", "text", []string{"color"}, nil, true, `missing object member name "text"`}, + {"strict, another alternative's member", "text", []string{"text", "image"}, nil, true, `type "text" does not allow member "image"`}, + {"leniently, another alternative's member", "text", []string{"text", "image"}, nil, false, ""}, + {"no tag", "", nil, nil, true, `missing object member name "type"`}, + {"a tag none has", "video", nil, nil, true, `unknown value of "type"`}, + } { + err := union.CheckTag("type", tc.tag, tags, tc.set, tc.present, tc.strict) + switch { + case tc.contains == "" && err != nil: + t.Errorf("%s: %v", tc.name, err) + case tc.contains != "" && (err == nil || !strings.Contains(err.Error(), tc.contains)): + t.Errorf("%s: got %v, want an error with %q", tc.name, err, tc.contains) + } + } +} + +func TestInferTag(t *testing.T) { + tags := map[string]map[string]union.TagNeed{ + "text": {"text": union.TagRequired, "color": union.TagOptional}, + "image": {"image": union.TagRequired}, + "color": {"color": union.TagRequired}, + } + + for _, tc := range []struct { + set []string + want string + }{ + {[]string{"image"}, "image"}, + {[]string{"text", "color"}, "text"}, + {[]string{"text", "image"}, ""}, + {[]string{"color"}, "color"}, + {nil, ""}, + {[]string{"other"}, ""}, + } { + got, ok := union.InferTag(tags, tc.set) + if got != tc.want || ok != (tc.want != "") { + t.Errorf("%q: got %q, %v, want %q", tc.set, got, ok, tc.want) + } + } +}