From ae05865cd28879ee680ecae8358e47232cf3e55b Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 13:18:16 +0000 Subject: [PATCH 1/2] feat: the transform helpers libraries wrote for themselves MoveToComponents, SchemaRef, RenameSchemasFunc and MergeSchemas, which go-api-libs/notion and pixellab each wrote to shape their specification, and RemoveNullAlternatives and RemoveEmptyJSON, which undo what FastAPI writes. Both libraries generate the same specification and code with these as with their own. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019QCb1AfnATvpBQCH3PrX7Y --- README.md | 7 +- README/tail.md | 7 +- components.go | 92 +++++++++++++++++ remove.go | 96 ++++++++++++++++++ transform_test.go | 246 ++++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 446 insertions(+), 2 deletions(-) create mode 100644 components.go create mode 100644 remove.go create mode 100644 transform_test.go diff --git a/README.md b/README.md index 8c9c1fa..207ee47 100644 --- a/README.md +++ b/README.md @@ -244,7 +244,12 @@ node being changed. `RenameSchemas`) - ✅ Repointing every reference to a duplicate component onto the one that survives, and removing the duplicate (`RedirectSchema`, `RedirectSchemas`) -- ✅ Moving inline definitions into `components`, replacing each with a reference (`ExtractSchema`) +- ✅ Moving inline definitions into `components`, replacing each with a reference (`ExtractSchema`), or one + of them by name (`MoveToComponents`), and referring to a component (`SchemaRef`) +- ✅ Renaming every component by a rule, such as dropping a suffix (`RenameSchemasFunc`) +- ✅ Putting one schema in place of several near-duplicates, and every reference with it (`MergeSchemas`) +- ✅ Undoing what generators such as FastAPI write: an optional value as an `anyOf` with null + (`RemoveNullAlternatives`), an empty JSON beside a download's own media type (`RemoveEmptyJSON`) - ✅ Counting the references to each component (`CountReferences`), and describing them where they are used (`DescribeReferences`) - ✅ Removing the components an edit left without a reference diff --git a/README/tail.md b/README/tail.md index b667782..ad5efa2 100644 --- a/README/tail.md +++ b/README/tail.md @@ -10,7 +10,12 @@ node being changed. `RenameSchemas`) - ✅ Repointing every reference to a duplicate component onto the one that survives, and removing the duplicate (`RedirectSchema`, `RedirectSchemas`) -- ✅ Moving inline definitions into `components`, replacing each with a reference (`ExtractSchema`) +- ✅ Moving inline definitions into `components`, replacing each with a reference (`ExtractSchema`), or one + of them by name (`MoveToComponents`), and referring to a component (`SchemaRef`) +- ✅ Renaming every component by a rule, such as dropping a suffix (`RenameSchemasFunc`) +- ✅ Putting one schema in place of several near-duplicates, and every reference with it (`MergeSchemas`) +- ✅ Undoing what generators such as FastAPI write: an optional value as an `anyOf` with null + (`RemoveNullAlternatives`), an empty JSON beside a download's own media type (`RemoveEmptyJSON`) - ✅ Counting the references to each component (`CountReferences`), and describing them where they are used (`DescribeReferences`) - ✅ Removing the components an edit left without a reference diff --git a/components.go b/components.go new file mode 100644 index 0000000..0520ce7 --- /dev/null +++ b/components.go @@ -0,0 +1,92 @@ +package edit + +import ( + "maps" + "slices" + + "github.com/MarkRosemaker/openapi" +) + +// SchemaRef is a reference to the component schema name, as a schema to put where the component is wanted. +func SchemaRef(doc *openapi.Document, name string) *openapi.Schema { + return &openapi.Schema{Ref: &openapi.SchemaRef{Identifier: schemaRefPrefix + name, Value: doc.Components.Schemas[name]}} +} + +// MoveToComponents moves s, a schema written out inline, into components.schemas as name, and puts a reference to it +// in its place: a way to name what a document spells out where it uses it. It returns the moved schema. +// +// It moves nothing, and reports false, if s is a reference already, or name is taken or could not be referenced: +// so that a pass naming many schemas can offer each a name and leave alone what has one. +func MoveToComponents(doc *openapi.Document, s *openapi.Schema, name string) (*openapi.Schema, bool) { + if s.Ref != nil || doc.Components.Schemas[name] != nil || !reComponentKey.MatchString(name) { + return nil, false + } + + moved := new(openapi.Schema) + moved.Replace(s) + doc.Components.Schemas.Set(name, moved) + s.Replace(SchemaRef(doc, name)) + + return moved, true +} + +// RenameSchemasFunc renames each component schema to what rename makes of its name, as [RenameSchemas] does, such as to +// drop a suffix every name carries. A name rename leaves as it is stays. +// +// It fails, changing nothing, for the reasons RenameSchemas does. +func RenameSchemasFunc(doc *openapi.Document, rename func(string) string) error { + to := map[string]string{} + + for name := range doc.Components.Schemas.ByIndex() { + if newName := rename(name); newName != name { + to[name] = newName + } + } + + return RenameSchemas(doc, to) +} + +// MergeSchemas puts merged in components.schemas as name in place of the schemas members, and points every reference +// to one of them at it, as [RedirectSchemas] does: the step after working out the one schema that allows what several +// near-duplicates did. name may be one of members, whose place it then takes; otherwise it must be free. +// +// It fails, changing nothing, if a member is not in components.schemas ([ErrSchemaNotFound]), or name is taken by a +// schema that is no member ([ErrSchemaExists]) or could not be referenced ([ErrInvalidSchemaName]). +func MergeSchemas(doc *openapi.Document, name string, merged *openapi.Schema, members ...string) error { + schemas := doc.Components.Schemas + + for _, m := range members { + if _, ok := schemas[m]; !ok { + return &ErrSchemaNotFound{Name: m} + } + } + + switch { + case !reComponentKey.MatchString(name): + return &ErrInvalidSchemaName{Name: name} + case schemas[name] != nil && !slices.Contains(members, name): + return &ErrSchemaExists{Name: name} + } + + to := make(map[string]string, len(members)) + for _, m := range members { + to[m] = name + } + + // a member of the name keeps its place, with merged in it, and the others are redirected to it + schemas.Set(name, merged) + delete(to, name) + + // the references to name itself, if a member, now find merged + WalkSchemas(doc, func(s *openapi.Schema) { + if s.Ref != nil && s.Ref.Identifier == schemaRefPrefix+name { + s.Ref.Value = merged + } + }) + + if len(to) == 0 { + return nil + } + + return RedirectSchemas(doc, maps.Clone(to)) +} diff --git a/remove.go b/remove.go new file mode 100644 index 0000000..bd86841 --- /dev/null +++ b/remove.go @@ -0,0 +1,96 @@ +package edit + +import ( + "encoding/json/v2" + "maps" + "slices" + "strings" + + "github.com/MarkRosemaker/openapi" +) + +// RemoveNullAlternatives takes null out of every anyOf, and the anyOf with it where one alternative is left, which +// then takes its place, keeping the title, description and default the anyOf had. FastAPI, for one, writes every +// optional value as an anyOf of its type and null, where what the API means is a value that may be left out. +// +// A reference left alone gets the anyOf's example, if what it refers to has none. +func RemoveNullAlternatives(doc *openapi.Document) { + WalkSchemas(doc, removeNull) +} + +func removeNull(s *openapi.Schema) { + alts := s.AnyOf[:0] + for _, alt := range s.AnyOf { + if alt.Type != openapi.TypeNull { + alts = append(alts, alt) + } + } + + if len(alts) == len(s.AnyOf) { + return + } + + if s.AnyOf = alts; len(alts) != 1 { + return + } + + only := alts[0] + if only.Ref != nil { + if only.Ref.Value != nil && only.Ref.Value.Example == nil { + only.Ref.Value.Example = s.Example + } + + s.Replace(&openapi.Schema{Ref: only.Ref, Title: s.Title, Description: s.Description, Default: s.Default}) + + return + } + + title, description, def := s.Title, s.Description, s.Default + s.Replace(only) + s.Title, s.Description = title, description + + if len(def) > 0 { + s.Default = def + } +} + +// RemoveEmptyJSON removes, from every response that has another media type, the JSON whose schema says nothing of +// the value: FastAPI, for one, declares an empty JSON beside the media type a download really has, such as a ZIP or a +// GIF, which would leave a client unable to read the download. A media type without a schema, as a download's often +// is, is no empty JSON. +func RemoveEmptyJSON(doc *openapi.Document) { + for _, item := range doc.Paths.ByIndex() { + for _, op := range item.Operations { + for _, rsp := range op.Responses.ByIndex() { + if rsp.Value == nil { + continue + } + + content := rsp.Value.Content + if !slices.ContainsFunc(slices.Collect(maps.Keys(content)), func(mr openapi.MediaRange) bool { + return !emptyJSON(mr, content[mr]) + }) { + continue + } + + maps.DeleteFunc(content, emptyJSON) + } + } + } +} + +// emptyJSON reports whether mt, of the media range mr, is JSON of a schema of no keywords. +func emptyJSON(mr openapi.MediaRange, mt *openapi.MediaType) bool { + if mt == nil || mt.Schema == nil { + return false + } + + media := strings.TrimSpace(strings.SplitN(string(mr), ";", 2)[0]) + if media != "application/json" && !strings.HasSuffix(media, "+json") { + return false + } + + b, err := json.Marshal(mt.Schema) + + return err == nil && string(b) == "{}" +} diff --git a/transform_test.go b/transform_test.go new file mode 100644 index 0000000..592d8c1 --- /dev/null +++ b/transform_test.go @@ -0,0 +1,246 @@ +package edit_test + +import ( + "encoding/json/v2" + "errors" + "slices" + "strings" + "testing" + + "github.com/MarkRosemaker/openapi" + edit "github.com/MarkRosemaker/openapi-edit" +) + +// parse reads a document of the paths and schemas given, as JSON. +func parse(t *testing.T, paths, schemas string) *openapi.Document { + t.Helper() + + doc, err := openapi.LoadFromData([]byte(`{"openapi":"3.1.0","info":{"title":"t","version":"1"},"paths":` + paths + + `,"components":{"schemas":` + schemas + `}}`)) + if err != nil { + t.Fatal(err) + } + + return doc +} + +// written is the schema as it is written, compact. +func written(t *testing.T, s *openapi.Schema) string { + t.Helper() + + b, err := json.Marshal(s) + if err != nil { + t.Fatal(err) + } + + return string(b) +} + +func TestSchemaRef(t *testing.T) { + doc := parse(t, `{}`, `{"Pet":{"type":"object"}}`) + + ref := edit.SchemaRef(doc, "Pet") + if ref.Ref.Identifier != "#/components/schemas/Pet" || ref.Ref.Value != doc.Components.Schemas["Pet"] { + t.Errorf("got %+v", ref.Ref) + } +} + +func TestMoveToComponents(t *testing.T) { + doc := parse(t, `{}`, `{ + "Pet":{"type":"object","properties":{"owner":{"type":"object","properties":{"name":{"type":"string"}}},"kind":{"$ref":"#/components/schemas/Kind"}}}, + "Kind":{"type":"string"} + }`) + owner := doc.Components.Schemas["Pet"].Properties["owner"] + + moved, ok := edit.MoveToComponents(doc, owner, "Owner") + if !ok || doc.Components.Schemas["Owner"] != moved || moved.Properties["name"] == nil { + t.Fatalf("got %v, %+v", ok, moved) + } + + if owner.Ref == nil || owner.Ref.Identifier != "#/components/schemas/Owner" || owner.Ref.Value != moved { + t.Errorf("left %s in its place", written(t, owner)) + } + + for _, tc := range []struct { + name string + s *openapi.Schema + as string + }{ + {"a reference", doc.Components.Schemas["Pet"].Properties["kind"], "Other"}, + {"a name taken", &openapi.Schema{Type: openapi.TypeString}, "Kind"}, + {"a name no reference could have", &openapi.Schema{Type: openapi.TypeString}, "no/name"}, + } { + if _, ok := edit.MoveToComponents(doc, tc.s, tc.as); ok { + t.Errorf("%s: moved", tc.name) + } + } +} + +func TestRenameSchemasFunc(t *testing.T) { + doc := parse(t, `{}`, `{ + "PetRequest":{"type":"object","properties":{"owner":{"$ref":"#/components/schemas/OwnerRequest"}}}, + "OwnerRequest":{"type":"object"}, + "Kind":{"type":"string"} + }`) + + if err := edit.RenameSchemasFunc(doc, func(n string) string { return strings.TrimSuffix(n, "Request") }); err != nil { + t.Fatal(err) + } + + if got := slices.Collect(func(yield func(string) bool) { + for n := range doc.Components.Schemas.ByIndex() { + if !yield(n) { + return + } + } + }); !slices.Equal(got, []string{"Pet", "Owner", "Kind"}) { + t.Errorf("got %q", got) + } + + if ref := doc.Components.Schemas["Pet"].Properties["owner"].Ref; ref.Identifier != "#/components/schemas/Owner" { + t.Errorf("reference left at %s", ref.Identifier) + } + + doc = parse(t, `{}`, `{"PetRequest":{"type":"object"},"Pet":{"type":"object"}}`) + + var exists *edit.ErrSchemaExists + if err := edit.RenameSchemasFunc(doc, func(n string) string { return strings.TrimSuffix(n, "Request") }); !errors.As(err, &exists) { + t.Errorf("onto a name taken: got %v", err) + } +} + +func TestMergeSchemas(t *testing.T) { + const schemas = `{ + "Holder":{"type":"object","properties":{"a":{"$ref":"#/components/schemas/SizeA"},"b":{"$ref":"#/components/schemas/SizeB"}}}, + "SizeA":{"type":"integer","maximum":10}, + "SizeB":{"type":"integer","maximum":20} + }` + + t.Run("under a new name", func(t *testing.T) { + doc := parse(t, `{}`, schemas) + merged := &openapi.Schema{Type: openapi.TypeInteger} + + if err := edit.MergeSchemas(doc, "Size", merged, "SizeA", "SizeB"); err != nil { + t.Fatal(err) + } + + holder := doc.Components.Schemas["Holder"] + for _, p := range []string{"a", "b"} { + if ref := holder.Properties[p].Ref; ref.Identifier != "#/components/schemas/Size" || ref.Value != merged { + t.Errorf("%s refers to %s", p, ref.Identifier) + } + } + + if doc.Components.Schemas["SizeA"] != nil || doc.Components.Schemas["SizeB"] != nil { + t.Error("the members are still there") + } + }) + + t.Run("under a member's name", func(t *testing.T) { + doc := parse(t, `{}`, schemas) + merged := &openapi.Schema{Type: openapi.TypeInteger} + + if err := edit.MergeSchemas(doc, "SizeA", merged, "SizeA", "SizeB"); err != nil { + t.Fatal(err) + } + + holder := doc.Components.Schemas["Holder"] + for _, p := range []string{"a", "b"} { + if ref := holder.Properties[p].Ref; ref.Identifier != "#/components/schemas/SizeA" || ref.Value != merged { + t.Errorf("%s refers to %s", p, ref.Identifier) + } + } + + if doc.Components.Schemas["SizeA"] != merged || doc.Components.Schemas["SizeB"] != nil { + t.Error("not merged in the member's place") + } + }) + + t.Run("fails", func(t *testing.T) { + doc := parse(t, `{}`, schemas) + merged := &openapi.Schema{Type: openapi.TypeInteger} + + var notFound *edit.ErrSchemaNotFound + if err := edit.MergeSchemas(doc, "Size", merged, "SizeA", "SizeC"); !errors.As(err, ¬Found) { + t.Errorf("a member not there: got %v", err) + } + + var exists *edit.ErrSchemaExists + if err := edit.MergeSchemas(doc, "Holder", merged, "SizeA", "SizeB"); !errors.As(err, &exists) { + t.Errorf("a name taken: got %v", err) + } + + var invalid *edit.ErrInvalidSchemaName + if err := edit.MergeSchemas(doc, "no/name", merged, "SizeA"); !errors.As(err, &invalid) { + t.Errorf("a name no reference could have: got %v", err) + } + + if doc.Components.Schemas["Size"] != nil || doc.Components.Schemas["SizeA"] == nil { + t.Error("changed the document") + } + }) +} + +func TestRemoveNullAlternatives(t *testing.T) { + doc := parse(t, `{}`, `{ + "Pet":{"type":"object","properties":{ + "name":{"title":"Name","description":"what it is called","default":"Rex","anyOf":[{"type":"string","maxLength":9},{"type":"null"}]}, + "owner":{"description":"who has it","example":{"id":1},"anyOf":[{"$ref":"#/components/schemas/Owner"},{"type":"null"}]}, + "tag":{"anyOf":[{"type":"string"},{"type":"integer"},{"type":"null"}]}, + "size":{"anyOf":[{"type":"string"},{"type":"integer"}]} + }}, + "Owner":{"type":"object","properties":{"id":{"type":"integer"}}} + }`) + + edit.RemoveNullAlternatives(doc) + + props := doc.Components.Schemas["Pet"].Properties + for prop, want := range map[string]string{ + "name": `{"title":"Name","description":"what it is called","type":"string","maxLength":9,"default":"Rex"}`, + "owner": `{"description":"who has it","$ref":"#/components/schemas/Owner"}`, + "tag": `{"anyOf":[{"type":"string"},{"type":"integer"}]}`, + "size": `{"anyOf":[{"type":"string"},{"type":"integer"}]}`, + } { + if got := written(t, props[prop]); got != want { + t.Errorf("%s: got %s\nwant %s", prop, got, want) + } + } + + if ex := string(doc.Components.Schemas["Owner"].Example); ex != `{"id":1}` { + t.Errorf("Owner has the example %s, want the one of the anyOf", ex) + } +} + +func TestRemoveEmptyJSON(t *testing.T) { + doc := parse(t, `{ + "/download":{"get":{"responses":{ + "200":{"description":"a zip","content":{"application/json":{"schema":{}},"application/zip":{"schema":{"type":"string","format":"binary"}}}}, + "201":{"description":"a file without a schema","content":{"application/json; charset=utf-8":{"schema":{}},"application/octet-stream":{}}}, + "202":{"description":"JSON of its own","content":{"application/json":{"schema":{"type":"object"}},"text/plain":{"schema":{}}}}, + "204":{"description":"nothing else","content":{"application/json":{"schema":{}}}} + }}}, + "/other":{"get":{"responses":{"200":{"description":"no content"}}}} + }`, `{}`) + + edit.RemoveEmptyJSON(doc) + + content := map[string][]string{} + for code, rsp := range doc.Paths["/download"].Get.Responses.ByIndex() { + for mr := range rsp.Value.Content { + content[string(code)] = append(content[string(code)], string(mr)) + } + + slices.Sort(content[string(code)]) + } + + for code, want := range map[string][]string{ + "200": {"application/zip"}, + "201": {"application/octet-stream"}, + "202": {"application/json", "text/plain"}, + "204": {"application/json"}, + } { + if !slices.Equal(content[code], want) { + t.Errorf("%s: got %q, want %q", code, content[code], want) + } + } +} From 2ad28ad6acc7bd05c4c3b336ed5f716d0318dc02 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 14:20:34 +0000 Subject: [PATCH 2/2] Keep only the helpers more than one library uses SchemaRef and RenameSchemasFunc stay: notion and pixellab both build references and rename by a rule. MoveToComponents is notion's alone, and MergeSchemas is Replace and RedirectSchemas. RemoveNullAlternatives is no longer needed, now that codegen and flatten read X or null as X, and RemoveEmptyJSON is pixellab's alone. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019QCb1AfnATvpBQCH3PrX7Y --- README.md | 7 +- README/tail.md | 7 +- components.go | 70 +------------ components_test.go | 66 ++++++++++++ remove.go | 96 ------------------ transform_test.go | 246 --------------------------------------------- 6 files changed, 71 insertions(+), 421 deletions(-) create mode 100644 components_test.go delete mode 100644 remove.go delete mode 100644 transform_test.go diff --git a/README.md b/README.md index 207ee47..1e2fa41 100644 --- a/README.md +++ b/README.md @@ -244,12 +244,9 @@ node being changed. `RenameSchemas`) - ✅ Repointing every reference to a duplicate component onto the one that survives, and removing the duplicate (`RedirectSchema`, `RedirectSchemas`) -- ✅ Moving inline definitions into `components`, replacing each with a reference (`ExtractSchema`), or one - of them by name (`MoveToComponents`), and referring to a component (`SchemaRef`) +- ✅ Moving inline definitions into `components`, replacing each with a reference (`ExtractSchema`), and + referring to a component (`SchemaRef`) - ✅ Renaming every component by a rule, such as dropping a suffix (`RenameSchemasFunc`) -- ✅ Putting one schema in place of several near-duplicates, and every reference with it (`MergeSchemas`) -- ✅ Undoing what generators such as FastAPI write: an optional value as an `anyOf` with null - (`RemoveNullAlternatives`), an empty JSON beside a download's own media type (`RemoveEmptyJSON`) - ✅ Counting the references to each component (`CountReferences`), and describing them where they are used (`DescribeReferences`) - ✅ Removing the components an edit left without a reference diff --git a/README/tail.md b/README/tail.md index ad5efa2..4f5905f 100644 --- a/README/tail.md +++ b/README/tail.md @@ -10,12 +10,9 @@ node being changed. `RenameSchemas`) - ✅ Repointing every reference to a duplicate component onto the one that survives, and removing the duplicate (`RedirectSchema`, `RedirectSchemas`) -- ✅ Moving inline definitions into `components`, replacing each with a reference (`ExtractSchema`), or one - of them by name (`MoveToComponents`), and referring to a component (`SchemaRef`) +- ✅ Moving inline definitions into `components`, replacing each with a reference (`ExtractSchema`), and + referring to a component (`SchemaRef`) - ✅ Renaming every component by a rule, such as dropping a suffix (`RenameSchemasFunc`) -- ✅ Putting one schema in place of several near-duplicates, and every reference with it (`MergeSchemas`) -- ✅ Undoing what generators such as FastAPI write: an optional value as an `anyOf` with null - (`RemoveNullAlternatives`), an empty JSON beside a download's own media type (`RemoveEmptyJSON`) - ✅ Counting the references to each component (`CountReferences`), and describing them where they are used (`DescribeReferences`) - ✅ Removing the components an edit left without a reference diff --git a/components.go b/components.go index 0520ce7..1fa6ecf 100644 --- a/components.go +++ b/components.go @@ -1,35 +1,12 @@ package edit -import ( - "maps" - "slices" - - "github.com/MarkRosemaker/openapi" -) +import "github.com/MarkRosemaker/openapi" // SchemaRef is a reference to the component schema name, as a schema to put where the component is wanted. func SchemaRef(doc *openapi.Document, name string) *openapi.Schema { return &openapi.Schema{Ref: &openapi.SchemaRef{Identifier: schemaRefPrefix + name, Value: doc.Components.Schemas[name]}} } -// MoveToComponents moves s, a schema written out inline, into components.schemas as name, and puts a reference to it -// in its place: a way to name what a document spells out where it uses it. It returns the moved schema. -// -// It moves nothing, and reports false, if s is a reference already, or name is taken or could not be referenced: -// so that a pass naming many schemas can offer each a name and leave alone what has one. -func MoveToComponents(doc *openapi.Document, s *openapi.Schema, name string) (*openapi.Schema, bool) { - if s.Ref != nil || doc.Components.Schemas[name] != nil || !reComponentKey.MatchString(name) { - return nil, false - } - - moved := new(openapi.Schema) - moved.Replace(s) - doc.Components.Schemas.Set(name, moved) - s.Replace(SchemaRef(doc, name)) - - return moved, true -} - // RenameSchemasFunc renames each component schema to what rename makes of its name, as [RenameSchemas] does, such as to // drop a suffix every name carries. A name rename leaves as it is stays. // @@ -45,48 +22,3 @@ func RenameSchemasFunc(doc *openapi.Document, rename func(string) string) error return RenameSchemas(doc, to) } - -// MergeSchemas puts merged in components.schemas as name in place of the schemas members, and points every reference -// to one of them at it, as [RedirectSchemas] does: the step after working out the one schema that allows what several -// near-duplicates did. name may be one of members, whose place it then takes; otherwise it must be free. -// -// It fails, changing nothing, if a member is not in components.schemas ([ErrSchemaNotFound]), or name is taken by a -// schema that is no member ([ErrSchemaExists]) or could not be referenced ([ErrInvalidSchemaName]). -func MergeSchemas(doc *openapi.Document, name string, merged *openapi.Schema, members ...string) error { - schemas := doc.Components.Schemas - - for _, m := range members { - if _, ok := schemas[m]; !ok { - return &ErrSchemaNotFound{Name: m} - } - } - - switch { - case !reComponentKey.MatchString(name): - return &ErrInvalidSchemaName{Name: name} - case schemas[name] != nil && !slices.Contains(members, name): - return &ErrSchemaExists{Name: name} - } - - to := make(map[string]string, len(members)) - for _, m := range members { - to[m] = name - } - - // a member of the name keeps its place, with merged in it, and the others are redirected to it - schemas.Set(name, merged) - delete(to, name) - - // the references to name itself, if a member, now find merged - WalkSchemas(doc, func(s *openapi.Schema) { - if s.Ref != nil && s.Ref.Identifier == schemaRefPrefix+name { - s.Ref.Value = merged - } - }) - - if len(to) == 0 { - return nil - } - - return RedirectSchemas(doc, maps.Clone(to)) -} diff --git a/components_test.go b/components_test.go new file mode 100644 index 0000000..221c3ee --- /dev/null +++ b/components_test.go @@ -0,0 +1,66 @@ +package edit_test + +import ( + "errors" + "slices" + "strings" + "testing" + + "github.com/MarkRosemaker/openapi" + edit "github.com/MarkRosemaker/openapi-edit" +) + +// parse reads a document of the paths and schemas given, as JSON. +func parse(t *testing.T, paths, schemas string) *openapi.Document { + t.Helper() + + doc, err := openapi.LoadFromData([]byte(`{"openapi":"3.1.0","info":{"title":"t","version":"1"},"paths":` + paths + + `,"components":{"schemas":` + schemas + `}}`)) + if err != nil { + t.Fatal(err) + } + + return doc +} + +func TestSchemaRef(t *testing.T) { + doc := parse(t, `{}`, `{"Pet":{"type":"object"}}`) + + ref := edit.SchemaRef(doc, "Pet") + if ref.Ref.Identifier != "#/components/schemas/Pet" || ref.Ref.Value != doc.Components.Schemas["Pet"] { + t.Errorf("got %+v", ref.Ref) + } +} + +func TestRenameSchemasFunc(t *testing.T) { + doc := parse(t, `{}`, `{ + "PetRequest":{"type":"object","properties":{"owner":{"$ref":"#/components/schemas/OwnerRequest"}}}, + "OwnerRequest":{"type":"object"}, + "Kind":{"type":"string"} + }`) + + if err := edit.RenameSchemasFunc(doc, func(n string) string { return strings.TrimSuffix(n, "Request") }); err != nil { + t.Fatal(err) + } + + if got := slices.Collect(func(yield func(string) bool) { + for n := range doc.Components.Schemas.ByIndex() { + if !yield(n) { + return + } + } + }); !slices.Equal(got, []string{"Pet", "Owner", "Kind"}) { + t.Errorf("got %q", got) + } + + if ref := doc.Components.Schemas["Pet"].Properties["owner"].Ref; ref.Identifier != "#/components/schemas/Owner" { + t.Errorf("reference left at %s", ref.Identifier) + } + + doc = parse(t, `{}`, `{"PetRequest":{"type":"object"},"Pet":{"type":"object"}}`) + + var exists *edit.ErrSchemaExists + if err := edit.RenameSchemasFunc(doc, func(n string) string { return strings.TrimSuffix(n, "Request") }); !errors.As(err, &exists) { + t.Errorf("onto a name taken: got %v", err) + } +} diff --git a/remove.go b/remove.go deleted file mode 100644 index bd86841..0000000 --- a/remove.go +++ /dev/null @@ -1,96 +0,0 @@ -package edit - -import ( - "encoding/json/v2" - "maps" - "slices" - "strings" - - "github.com/MarkRosemaker/openapi" -) - -// RemoveNullAlternatives takes null out of every anyOf, and the anyOf with it where one alternative is left, which -// then takes its place, keeping the title, description and default the anyOf had. FastAPI, for one, writes every -// optional value as an anyOf of its type and null, where what the API means is a value that may be left out. -// -// A reference left alone gets the anyOf's example, if what it refers to has none. -func RemoveNullAlternatives(doc *openapi.Document) { - WalkSchemas(doc, removeNull) -} - -func removeNull(s *openapi.Schema) { - alts := s.AnyOf[:0] - for _, alt := range s.AnyOf { - if alt.Type != openapi.TypeNull { - alts = append(alts, alt) - } - } - - if len(alts) == len(s.AnyOf) { - return - } - - if s.AnyOf = alts; len(alts) != 1 { - return - } - - only := alts[0] - if only.Ref != nil { - if only.Ref.Value != nil && only.Ref.Value.Example == nil { - only.Ref.Value.Example = s.Example - } - - s.Replace(&openapi.Schema{Ref: only.Ref, Title: s.Title, Description: s.Description, Default: s.Default}) - - return - } - - title, description, def := s.Title, s.Description, s.Default - s.Replace(only) - s.Title, s.Description = title, description - - if len(def) > 0 { - s.Default = def - } -} - -// RemoveEmptyJSON removes, from every response that has another media type, the JSON whose schema says nothing of -// the value: FastAPI, for one, declares an empty JSON beside the media type a download really has, such as a ZIP or a -// GIF, which would leave a client unable to read the download. A media type without a schema, as a download's often -// is, is no empty JSON. -func RemoveEmptyJSON(doc *openapi.Document) { - for _, item := range doc.Paths.ByIndex() { - for _, op := range item.Operations { - for _, rsp := range op.Responses.ByIndex() { - if rsp.Value == nil { - continue - } - - content := rsp.Value.Content - if !slices.ContainsFunc(slices.Collect(maps.Keys(content)), func(mr openapi.MediaRange) bool { - return !emptyJSON(mr, content[mr]) - }) { - continue - } - - maps.DeleteFunc(content, emptyJSON) - } - } - } -} - -// emptyJSON reports whether mt, of the media range mr, is JSON of a schema of no keywords. -func emptyJSON(mr openapi.MediaRange, mt *openapi.MediaType) bool { - if mt == nil || mt.Schema == nil { - return false - } - - media := strings.TrimSpace(strings.SplitN(string(mr), ";", 2)[0]) - if media != "application/json" && !strings.HasSuffix(media, "+json") { - return false - } - - b, err := json.Marshal(mt.Schema) - - return err == nil && string(b) == "{}" -} diff --git a/transform_test.go b/transform_test.go deleted file mode 100644 index 592d8c1..0000000 --- a/transform_test.go +++ /dev/null @@ -1,246 +0,0 @@ -package edit_test - -import ( - "encoding/json/v2" - "errors" - "slices" - "strings" - "testing" - - "github.com/MarkRosemaker/openapi" - edit "github.com/MarkRosemaker/openapi-edit" -) - -// parse reads a document of the paths and schemas given, as JSON. -func parse(t *testing.T, paths, schemas string) *openapi.Document { - t.Helper() - - doc, err := openapi.LoadFromData([]byte(`{"openapi":"3.1.0","info":{"title":"t","version":"1"},"paths":` + paths + - `,"components":{"schemas":` + schemas + `}}`)) - if err != nil { - t.Fatal(err) - } - - return doc -} - -// written is the schema as it is written, compact. -func written(t *testing.T, s *openapi.Schema) string { - t.Helper() - - b, err := json.Marshal(s) - if err != nil { - t.Fatal(err) - } - - return string(b) -} - -func TestSchemaRef(t *testing.T) { - doc := parse(t, `{}`, `{"Pet":{"type":"object"}}`) - - ref := edit.SchemaRef(doc, "Pet") - if ref.Ref.Identifier != "#/components/schemas/Pet" || ref.Ref.Value != doc.Components.Schemas["Pet"] { - t.Errorf("got %+v", ref.Ref) - } -} - -func TestMoveToComponents(t *testing.T) { - doc := parse(t, `{}`, `{ - "Pet":{"type":"object","properties":{"owner":{"type":"object","properties":{"name":{"type":"string"}}},"kind":{"$ref":"#/components/schemas/Kind"}}}, - "Kind":{"type":"string"} - }`) - owner := doc.Components.Schemas["Pet"].Properties["owner"] - - moved, ok := edit.MoveToComponents(doc, owner, "Owner") - if !ok || doc.Components.Schemas["Owner"] != moved || moved.Properties["name"] == nil { - t.Fatalf("got %v, %+v", ok, moved) - } - - if owner.Ref == nil || owner.Ref.Identifier != "#/components/schemas/Owner" || owner.Ref.Value != moved { - t.Errorf("left %s in its place", written(t, owner)) - } - - for _, tc := range []struct { - name string - s *openapi.Schema - as string - }{ - {"a reference", doc.Components.Schemas["Pet"].Properties["kind"], "Other"}, - {"a name taken", &openapi.Schema{Type: openapi.TypeString}, "Kind"}, - {"a name no reference could have", &openapi.Schema{Type: openapi.TypeString}, "no/name"}, - } { - if _, ok := edit.MoveToComponents(doc, tc.s, tc.as); ok { - t.Errorf("%s: moved", tc.name) - } - } -} - -func TestRenameSchemasFunc(t *testing.T) { - doc := parse(t, `{}`, `{ - "PetRequest":{"type":"object","properties":{"owner":{"$ref":"#/components/schemas/OwnerRequest"}}}, - "OwnerRequest":{"type":"object"}, - "Kind":{"type":"string"} - }`) - - if err := edit.RenameSchemasFunc(doc, func(n string) string { return strings.TrimSuffix(n, "Request") }); err != nil { - t.Fatal(err) - } - - if got := slices.Collect(func(yield func(string) bool) { - for n := range doc.Components.Schemas.ByIndex() { - if !yield(n) { - return - } - } - }); !slices.Equal(got, []string{"Pet", "Owner", "Kind"}) { - t.Errorf("got %q", got) - } - - if ref := doc.Components.Schemas["Pet"].Properties["owner"].Ref; ref.Identifier != "#/components/schemas/Owner" { - t.Errorf("reference left at %s", ref.Identifier) - } - - doc = parse(t, `{}`, `{"PetRequest":{"type":"object"},"Pet":{"type":"object"}}`) - - var exists *edit.ErrSchemaExists - if err := edit.RenameSchemasFunc(doc, func(n string) string { return strings.TrimSuffix(n, "Request") }); !errors.As(err, &exists) { - t.Errorf("onto a name taken: got %v", err) - } -} - -func TestMergeSchemas(t *testing.T) { - const schemas = `{ - "Holder":{"type":"object","properties":{"a":{"$ref":"#/components/schemas/SizeA"},"b":{"$ref":"#/components/schemas/SizeB"}}}, - "SizeA":{"type":"integer","maximum":10}, - "SizeB":{"type":"integer","maximum":20} - }` - - t.Run("under a new name", func(t *testing.T) { - doc := parse(t, `{}`, schemas) - merged := &openapi.Schema{Type: openapi.TypeInteger} - - if err := edit.MergeSchemas(doc, "Size", merged, "SizeA", "SizeB"); err != nil { - t.Fatal(err) - } - - holder := doc.Components.Schemas["Holder"] - for _, p := range []string{"a", "b"} { - if ref := holder.Properties[p].Ref; ref.Identifier != "#/components/schemas/Size" || ref.Value != merged { - t.Errorf("%s refers to %s", p, ref.Identifier) - } - } - - if doc.Components.Schemas["SizeA"] != nil || doc.Components.Schemas["SizeB"] != nil { - t.Error("the members are still there") - } - }) - - t.Run("under a member's name", func(t *testing.T) { - doc := parse(t, `{}`, schemas) - merged := &openapi.Schema{Type: openapi.TypeInteger} - - if err := edit.MergeSchemas(doc, "SizeA", merged, "SizeA", "SizeB"); err != nil { - t.Fatal(err) - } - - holder := doc.Components.Schemas["Holder"] - for _, p := range []string{"a", "b"} { - if ref := holder.Properties[p].Ref; ref.Identifier != "#/components/schemas/SizeA" || ref.Value != merged { - t.Errorf("%s refers to %s", p, ref.Identifier) - } - } - - if doc.Components.Schemas["SizeA"] != merged || doc.Components.Schemas["SizeB"] != nil { - t.Error("not merged in the member's place") - } - }) - - t.Run("fails", func(t *testing.T) { - doc := parse(t, `{}`, schemas) - merged := &openapi.Schema{Type: openapi.TypeInteger} - - var notFound *edit.ErrSchemaNotFound - if err := edit.MergeSchemas(doc, "Size", merged, "SizeA", "SizeC"); !errors.As(err, ¬Found) { - t.Errorf("a member not there: got %v", err) - } - - var exists *edit.ErrSchemaExists - if err := edit.MergeSchemas(doc, "Holder", merged, "SizeA", "SizeB"); !errors.As(err, &exists) { - t.Errorf("a name taken: got %v", err) - } - - var invalid *edit.ErrInvalidSchemaName - if err := edit.MergeSchemas(doc, "no/name", merged, "SizeA"); !errors.As(err, &invalid) { - t.Errorf("a name no reference could have: got %v", err) - } - - if doc.Components.Schemas["Size"] != nil || doc.Components.Schemas["SizeA"] == nil { - t.Error("changed the document") - } - }) -} - -func TestRemoveNullAlternatives(t *testing.T) { - doc := parse(t, `{}`, `{ - "Pet":{"type":"object","properties":{ - "name":{"title":"Name","description":"what it is called","default":"Rex","anyOf":[{"type":"string","maxLength":9},{"type":"null"}]}, - "owner":{"description":"who has it","example":{"id":1},"anyOf":[{"$ref":"#/components/schemas/Owner"},{"type":"null"}]}, - "tag":{"anyOf":[{"type":"string"},{"type":"integer"},{"type":"null"}]}, - "size":{"anyOf":[{"type":"string"},{"type":"integer"}]} - }}, - "Owner":{"type":"object","properties":{"id":{"type":"integer"}}} - }`) - - edit.RemoveNullAlternatives(doc) - - props := doc.Components.Schemas["Pet"].Properties - for prop, want := range map[string]string{ - "name": `{"title":"Name","description":"what it is called","type":"string","maxLength":9,"default":"Rex"}`, - "owner": `{"description":"who has it","$ref":"#/components/schemas/Owner"}`, - "tag": `{"anyOf":[{"type":"string"},{"type":"integer"}]}`, - "size": `{"anyOf":[{"type":"string"},{"type":"integer"}]}`, - } { - if got := written(t, props[prop]); got != want { - t.Errorf("%s: got %s\nwant %s", prop, got, want) - } - } - - if ex := string(doc.Components.Schemas["Owner"].Example); ex != `{"id":1}` { - t.Errorf("Owner has the example %s, want the one of the anyOf", ex) - } -} - -func TestRemoveEmptyJSON(t *testing.T) { - doc := parse(t, `{ - "/download":{"get":{"responses":{ - "200":{"description":"a zip","content":{"application/json":{"schema":{}},"application/zip":{"schema":{"type":"string","format":"binary"}}}}, - "201":{"description":"a file without a schema","content":{"application/json; charset=utf-8":{"schema":{}},"application/octet-stream":{}}}, - "202":{"description":"JSON of its own","content":{"application/json":{"schema":{"type":"object"}},"text/plain":{"schema":{}}}}, - "204":{"description":"nothing else","content":{"application/json":{"schema":{}}}} - }}}, - "/other":{"get":{"responses":{"200":{"description":"no content"}}}} - }`, `{}`) - - edit.RemoveEmptyJSON(doc) - - content := map[string][]string{} - for code, rsp := range doc.Paths["/download"].Get.Responses.ByIndex() { - for mr := range rsp.Value.Content { - content[string(code)] = append(content[string(code)], string(mr)) - } - - slices.Sort(content[string(code)]) - } - - for code, want := range map[string][]string{ - "200": {"application/zip"}, - "201": {"application/octet-stream"}, - "202": {"application/json", "text/plain"}, - "204": {"application/json"}, - } { - if !slices.Equal(content[code], want) { - t.Errorf("%s: got %q, want %q", code, content[code], want) - } - } -}