Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
31306df
Load standalone Draft 2020-12 schema resources with authored origins
daveshanley Nov 25, 2026
02596d6
Compare authored standalone schema constraints with resource-local paths
daveshanley Nov 25, 2026
23aaeb8
Pre-index schema collections before resolving shared references
daveshanley Nov 25, 2026
360c29c
Preserve resource identity and authored annotations in schema edits
daveshanley Nov 25, 2026
590fd23
Expose authored reference keywords and protect schema source identities
daveshanley Nov 25, 2026
56ee217
Use the repository assertion module in schema tests
daveshanley Nov 25, 2026
bebaaa8
Read JSON Schema coordinates directly from the authored JSON
daveshanley Nov 25, 2026
9edea59
Round-trip native file paths and Windows drives through schema URIs
daveshanley Nov 25, 2026
9edd659
Share typed JSON value identity with native schema comparisons
daveshanley Nov 25, 2026
6f24017
Recognize Draft 2020-12 keyword overrides in schema rules
daveshanley Nov 25, 2026
3950faf
Validate native schema inputs against the bundled Draft 2020-12 meta-…
daveshanley Nov 25, 2026
f924b13
Classify authored schema edits across typed values and resolved uses
daveshanley Nov 25, 2026
5039ecc
Preserve matched schema filenames for one-sided changes
daveshanley Nov 25, 2026
ac02b3a
Resolve external collection dependencies from the configured base
daveshanley Nov 25, 2026
a7d54e8
Keep exact numbers when validating JSON-compatible YAML schemas
daveshanley Nov 25, 2026
b2b7054
Carry schema membership and reference semantics across operand moves
daveshanley Nov 25, 2026
5dfe0dd
Resolve virtual schema bases against the host drive
daveshanley Nov 25, 2026
7a43a44
Validate repeated property schema shapes once per map
daveshanley Nov 25, 2026
c99ee8d
Retain every diagnostic path for invalid repeated schemas
daveshanley Nov 25, 2026
ced2603
Test native schema validation and report source identity
daveshanley Nov 26, 2026
5b05888
Cover schema comparison boundaries and preserve dependency names
daveshanley Nov 26, 2026
8b21b33
Cover authored schema parsing and preserve lookup for scalar roots
daveshanley Nov 26, 2026
2a7bc65
Exercise schema loading, reference resolution and native path contracts
daveshanley Nov 26, 2026
18f9f3f
Keep native schema filenames when resolving an explicit base URL
daveshanley Nov 26, 2026
e36828c
Report schema child traversal errors during comparison
daveshanley Nov 26, 2026
3b07cb1
Redact schema reference diagnostics and validate edited map keys
daveshanley Nov 26, 2026
18eb810
Tighten native schema verdicts, diagnostics and numeric bounds
daveshanley Nov 26, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ This repo is a library, not an app. The root package exposes the public entry po
| `datamodel/` | Spec parsing/version detection, schemas, and `DocumentConfiguration` |
| `bundler/` | Inline and composed bundling, ref rewrite/composition, origin tracking |
| `what-changed/` | Unified diff engine for OAS2 and OAS3+, plus breaking-change rule config/report helpers |
| `jsonschema/` | Native Draft 2020-12 documents and collections, resource matching, and authored changes from the shared schema comparator |
| `overlay/` | OpenAPI Overlay application engine |
| `arazzo/` | Arazzo parsing, resolution, validation, and workflow execution engine |
| `renderer/` | Schema/mock sample generation |
Expand Down
38 changes: 38 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,44 @@ See all the documentation at https://pb33f.io/libopenapi/
- [About libopenapi](https://pb33f.io/libopenapi/about/)
- [Migrating: breaking API changes by version](MIGRATING.md)

### Comparing standalone JSON Schemas

Use the `jsonschema` package to compare Draft 2020-12 schemas. Pass the source
name so relative references resolve against the correct file. Pass `true` to
`Load` to select this dialect for an unmarked schema or a boolean root.

```go
before, err := jsonschema.Load(original, "before/customer.json", nil, true)
if err != nil {
return err
}
defer before.Release()
after, err := jsonschema.Load(modified, "after/customer.json", nil, true)
if err != nil {
return err
}
defer after.Release()
changes, err := jsonschema.Compare(before, after, nil)
```

`Compare` returns a nil report for equal schemas. For a collection, use
`jsonschema.LoadCollection` with a map of relative filenames to source bytes
and the directory for that snapshot. It registers each member before resolving
references. Each change carries its resource ID, local JSONPath, and source
locations. Releases and breaking-rule overrides work the same for either input.

The third argument to `Compare` holds explicit overrides only. A rule replaces
the verdict for its keyword in both directions, so pass `nil` for the
direction-aware defaults and never the merged default rules.

Draft 2020-12 is the only supported dialect. These inputs return an error:

- a `$schema` that names another dialect
- a `$dynamicRef` that needs dynamic scope resolution
- a schema without `$schema` that uses a keyword from an earlier draft, such as
`definitions` or `dependencies`
- YAML anchors, aliases, and keys that are not strings

### Generating TypeScript models

`generator/typescript` renders the component schemas of an OpenAPI document as
Expand Down
91 changes: 91 additions & 0 deletions datamodel/schema_node.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
// Copyright 2026 Princess B33f Heavy Industries / Dave Shanley
// SPDX-License-Identifier: MIT

package datamodel

import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"strings"

"github.com/pb33f/go-yaml"
"github.com/pb33f/libopenapi/internal/jsonnode"
)

// DecodeSchemaNode reads one JSON or YAML schema and preserves authored positions.
func DecodeSchemaNode(data []byte) (*yaml.Node, error) {
var doc *yaml.Node
if json.Valid(data) {
var ok bool
doc, ok = jsonnode.ParseJSON(data)
if !ok {
return nil, fmt.Errorf("invalid JSON schema document")
}
} else {
decoder := yaml.NewDecoder(bytes.NewReader(data))
doc = new(yaml.Node)
if err := decoder.Decode(doc); err != nil {
return nil, fmt.Errorf("invalid schema document: %w", err)
}
var extra yaml.Node
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
if err != nil {
return nil, err
}
return nil, fmt.Errorf("expected one schema document")
}
}
if err := checkSchemaKeys(doc); err != nil {
return nil, err
}
return doc, nil
}

// Check keys in linear time on wide property maps. Every YAML mapping in a JSON
// document, including objects inside examples, has unique string keys.
func checkSchemaKeys(n *yaml.Node) error {
switch n.Kind {
case yaml.MappingNode:
seen := make(map[string]int, len(n.Content)/2)
for i := 0; i < len(n.Content); i += 2 {
key := n.Content[i]
if key.Kind != yaml.ScalarNode || key.Tag != "!!str" {
return fmt.Errorf("line %d: JSON object keys must be strings (quote the key in YAML)", key.Line)
}
if line, ok := seen[key.Value]; ok {
return fmt.Errorf("line %d: mapping key %q already defined at line %d", key.Line, key.Value, line)
}
seen[key.Value] = key.Line
if err := checkSchemaKeys(n.Content[i+1]); err != nil {
return err
}
}
case yaml.DocumentNode, yaml.SequenceNode:
for _, child := range n.Content {
if err := checkSchemaKeys(child); err != nil {
return err
}
}
case yaml.ScalarNode:
// YAML's resolver tags a number outside float64 range as a plain string.
// Keep the JSON numeric type when the authored token is a JSON number.
if n.Tag == "!!str" && n.Style == 0 && n.Value != "" &&
(n.Value[0] == '-' || n.Value[0] >= '0' && n.Value[0] <= '9') && json.Valid([]byte(n.Value)) {
n.Tag = "!!int"
if strings.ContainsAny(n.Value, ".eE") {
n.Tag = "!!float"
}
}
switch n.Tag {
case "!!str", "!!bool", "!!int", "!!float", "!!null":
default:
return fmt.Errorf("line %d: unsupported JSON scalar %s", n.Line, n.Tag)
}
default:
return fmt.Errorf("line %d: expected JSON-compatible YAML", n.Line)
}
return nil
}
71 changes: 71 additions & 0 deletions datamodel/schema_node_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
// Copyright 2026 Princess B33f Heavy Industries / Dave Shanley
// SPDX-License-Identifier: MIT

package datamodel

import (
"errors"
"io"
"strings"
"testing"

"github.com/pb33f/go-yaml"
"github.com/pb33f/testify/require"
)

func TestDecodeSchemaNodeReadsOneDocument(t *testing.T) {
for _, tc := range []struct{ name, source, message string }{
{"empty", "", "invalid schema document"},
{"malformed YAML", "properties: [\n", "invalid schema document"},
{"second document", "type: string\n---\nfalse\n", "expected one schema document"},
{"malformed second document", "type: string\n---\nenum: [1\n", "yaml:"},
{"malformed JSON string", "{\"title\":\"\xff\"}", "invalid JSON schema document"},
{"duplicate escaped JSON key", "{\n \"properties\": {\n \"name\": true,\n \"na\\u006de\": false}}", `line 4: mapping key "name" already defined at line 3`},
{"duplicate inside YAML example", "examples:\n - name: first\n name: second\n", `line 3: mapping key "name" already defined at line 2`},
{"numeric YAML key", "properties:\n 42: false\n", "line 2: JSON object keys must be strings (quote the key in YAML)"},
{"complex YAML key", "properties:\n ? [a,b]\n : false\n", "line 2: JSON object keys must be strings"},
{"YAML timestamp", "const: 2026-11-25\n", "line 1: unsupported JSON scalar !!timestamp"},
{"YAML alias", "$defs: &shape {}\nproperties:\n x: *shape\n", "line 3: expected JSON-compatible YAML"},
} {
t.Run(tc.name, func(t *testing.T) {
doc, err := DecodeSchemaNode([]byte(tc.source))
require.Nil(t, doc)
require.ErrorContains(t, err, tc.message)
if tc.source == "" {
require.ErrorIs(t, err, io.EOF)
}
})
}
}

func TestDecodeSchemaNodePreservesYAMLNumberTypes(t *testing.T) {
integer := strings.Repeat("9", 400)
doc, err := DecodeSchemaNode([]byte("examples:\n - " + integer + "\n - -1.5e5000\n - '1e5000'\n - 1GB\n...\n"))
require.NoError(t, err)
require.Equal(t, yaml.DocumentNode, doc.Kind)
require.Len(t, doc.Content, 1)
values := doc.Content[0].Content[1]
require.Equal(t, yaml.SequenceNode, values.Kind)
require.Len(t, values.Content, 4)
for i, want := range []struct{ value, tag string }{
{integer, "!!int"}, {"-1.5e5000", "!!float"}, {"1e5000", "!!str"}, {"1GB", "!!str"},
} {
node := values.Content[i]
require.Equal(t, want.value, node.Value)
require.Equal(t, want.tag, node.Tag)
require.Equal(t, i+2, node.Line)
require.Equal(t, 5, node.Column)
}
}

func TestUnsupportedSpecTypeDistinguishesSchemaFromInvalidAPI(t *testing.T) {
info, err := ExtractSpecInfo([]byte(`{"type":"object","properties":{"id":{"type":"string"}}}`))
require.ErrorIs(t, err, ErrUnsupportedSpecType)
require.ErrorIs(t, info.Error, ErrUnsupportedSpecType)
require.NotNil(t, info.RootNode)
for _, doc := range []string{"openapi: [", "openapi: '2.0.0'\n"} {
_, err = ExtractSpecInfo([]byte(doc))
require.Error(t, err)
require.False(t, errors.Is(err, ErrUnsupportedSpecType))
}
}
5 changes: 4 additions & 1 deletion datamodel/spec_info.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ const (
YAMLFileType = "yaml"
)

// ErrUnsupportedSpecType indicates a well-formed document with no API version marker.
var ErrUnsupportedSpecType = errors.New("spec type not supported by libopenapi, sorry")

// SpecInfo represents a 'ready-to-process' OpenAPI Document. The RootNode is the most important property
// used by the library, this contains the top of the document tree that every single low model is based off.
type SpecInfo struct {
Expand Down Expand Up @@ -382,7 +385,7 @@ func extractSpecInfoInternal(spec []byte, bypass bool, skipJSON bool) (*SpecInfo
return nil, err
}
}
specInfo.Error = errors.New("spec type not supported by libopenapi, sorry")
specInfo.Error = ErrUnsupportedSpecType
return specInfo, specInfo.Error
}
}
Expand Down
14 changes: 14 additions & 0 deletions datamodel/spec_info_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"github.com/pb33f/go-yaml"
"github.com/pb33f/libopenapi/utils"
"github.com/pb33f/testify/assert"
"github.com/pb33f/testify/require"
)

const (
Expand Down Expand Up @@ -545,6 +546,19 @@ func TestNormalizeJSONForYAMLParser_NoAllocation(t *testing.T) {

// TestExtractSpecInfo_JSON_EscapedSlashes tests issue #479
// JSON files containing \/ (escaped forward slash) should parse correctly
func TestDecodeSchemaNodePreservesJSONColumns(t *testing.T) {
for _, value := range []string{`"a\/b"`, `"\uD83D\uDE00"`, `"🙂"`, `"\uD800"`, `"line\nend"`} {
input := `{"description":` + value + `,"minimum":2}`
doc, err := DecodeSchemaNode([]byte(input))
require.NoError(t, err)
require.Equal(t, len([]rune(input))-1, doc.Content[0].Content[3].Column)
}
for _, input := range []string{"\ttrue", "{\"minimum\"\n:\t1e900}", "{\r\"maximum\":5}"} {
_, err := DecodeSchemaNode([]byte(input))
require.NoError(t, err)
}
}

func TestExtractSpecInfo_JSON_EscapedSlashes(t *testing.T) {
// Exact test case from issue #479
jsonWithEscapedSlash := `{"openapi":"3.0.0","info":{"title":"Escaped Slash Test","description":"This spec contains escaped forward slashes (\\/) that cause parsing issues","version":"1.0.0"},"paths":{"\/test":{"get":{"summary":"Test endpoint with escaped slashes","description":"The path \/test\/ contains escaped forward slashes","responses":{"200":{"description":"OK","content":{"application\/json":{"schema":{"type":"object","properties":{"url":{"type":"string","example":"https:\/\/example.com\/api\/test"},"path":{"type":"string","example":"\/users\/{id}\/profile"}}}}}}}}}}}`
Expand Down
67 changes: 67 additions & 0 deletions index/schema_index_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
// Copyright 2026 Princess B33f Heavy Industries / Dave Shanley
// SPDX-License-Identifier: MIT

package index

import (
"testing"

"github.com/pb33f/go-yaml"
"github.com/pb33f/testify/require"
)

func TestNewSchemaIndexMapsAuthoredSourceWithoutExtractingReferences(t *testing.T) {
var doc yaml.Node
require.NoError(t, yaml.Unmarshal([]byte("examples:\n - $ref: literal.json\nproperties:\n price:\n $ref: money.json\n $id: urn:price\n"), &doc))
config := CreateClosedAPIIndexConfig()
config.SpecAbsolutePath = "schemas/order.yaml"
config.Rolodex = NewRolodex(config)
idx := NewSchemaIndex(&doc, config)
require.Same(t, &doc, idx.GetRootNode())
require.Same(t, config.Rolodex, idx.GetRolodex())
require.Equal(t, "schemas/order.yaml", idx.GetSpecAbsolutePath())
require.Empty(t, idx.GetAllReferences())
require.Empty(t, idx.GetAllSchemaIds())
example := doc.Content[0].Content[1].Content[0].Content[1]
price := doc.Content[0].Content[3].Content[1]
ref := price.Content[1]
for _, value := range []*yaml.Node{example, ref} {
found, ok := idx.GetNode(value.Line, value.Column)
require.True(t, ok)
require.Same(t, value, found)
}
entry := &SchemaIdEntry{Id: price.Content[3].Value, SchemaNode: price, Index: idx}
require.NoError(t, idx.RegisterSchemaId(entry))
require.Same(t, price, idx.GetSchemaById("urn:price").SchemaNode)
idx.Release()
require.Nil(t, idx.GetSchemaById("urn:price"))
require.Nil(t, idx.GetRootNode())
require.Nil(t, idx.GetNodeMap())
_, ok := idx.GetNode(ref.Line, ref.Column)
require.False(t, ok)
require.Equal(t, "money.json", ref.Value)
idx.Release()
}

func TestNewSchemaIndexRootForms(t *testing.T) {
for _, source := range []string{"false", "{}"} {
var doc yaml.Node
require.NoError(t, yaml.Unmarshal([]byte("\n"+source), &doc))
for _, input := range []*yaml.Node{&doc, doc.Content[0]} {
idx := NewSchemaIndex(input, CreateClosedAPIIndexConfig())
require.Same(t, input, idx.GetRootNode())
got, ok := idx.GetNode(2, 1)
require.True(t, ok)
require.Same(t, doc.Content[0], got)
idx.Release()
}
}
for _, input := range []*yaml.Node{nil, {Kind: yaml.DocumentNode}} {
idx := NewSchemaIndex(input, CreateClosedAPIIndexConfig())
require.Same(t, input, idx.GetRootNode())
got, ok := idx.GetNode(1, 1)
require.Nil(t, got)
require.False(t, ok)
idx.Release()
}
}
12 changes: 12 additions & 0 deletions index/spec_index_build.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,18 @@ func NewSpecIndexWithConfig(rootNode *yaml.Node, config *SpecIndexConfig) *SpecI
return NewSpecIndexWithConfigAndContext(context.Background(), rootNode, config)
}

// NewSchemaIndex retains a standalone schema source. Its loader registers only
// schema-bearing positions, since arbitrary instance data can also contain $ref.
func NewSchemaIndex(rootNode *yaml.Node, config *SpecIndexConfig) *SpecIndex {
idx := NewSpecIndexWithConfig(nil, config)
idx.root = rootNode
if rootNode != nil && (rootNode.Kind != yaml.DocumentNode || len(rootNode.Content) > 0) {
idx.nodeMapCompleted = make(chan struct{})
idx.MapNodes(rootNode)
}
return idx
}

// NewSpecIndex creates a new SpecIndex with default configuration from the given root YAML node.
func NewSpecIndex(rootNode *yaml.Node) *SpecIndex {
index := new(SpecIndex)
Expand Down
Loading
Loading