Add shared glossary validation

This commit is contained in:
2026-11-27 16:10:23 +00:00
parent a6c1bceb26
commit 66b7674e43
8 changed files with 480 additions and 1 deletions

View File

@@ -0,0 +1,85 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://forge.maximumdirect.net/eric/narratio-reference-catalog/schemas/glossary-v1.schema.json",
"title": "Glossary named collections v1",
"$ref": "#/$defs/document",
"$defs": {
"entry": {
"type": "object",
"required": [
"id",
"name",
"category"
],
"properties": {
"id": {
"type": "string",
"minLength": 1
},
"name": {
"type": "string",
"minLength": 1
},
"category": {
"type": "string",
"minLength": 1
},
"description": {
"type": "string"
},
"aliases": {
"type": "array",
"items": {
"type": "string",
"minLength": 1
}
},
"plural": {
"anyOf": [
{
"type": "string",
"minLength": 1
},
{
"type": "null"
}
]
}
},
"additionalProperties": true
},
"partialCollection": {
"type": "object",
"properties": {
"instruction": {
"type": "string"
},
"entries": {
"type": "array",
"items": {
"$ref": "#/$defs/entry"
}
}
},
"additionalProperties": false
},
"collection": {
"allOf": [
{
"$ref": "#/$defs/partialCollection"
},
{
"required": [
"entries"
]
}
]
},
"document": {
"type": "object",
"additionalProperties": {
"$ref": "#/$defs/collection"
}
}
}
}

View File

@@ -0,0 +1,159 @@
// Package glossary owns the shared native glossary representation and validation.
package glossary
import (
"bytes"
_ "embed"
"encoding/json"
"fmt"
"sort"
"sync"
"github.com/santhosh-tekuri/jsonschema/v6"
)
// Collection preserves an explicitly supplied empty instruction.
type Collection struct {
Instruction *string `yaml:"instruction,omitempty" json:"instruction,omitempty"`
Entries []Entry `yaml:"entries" json:"entries"`
}
// Entry retains native fields and any additional vocabulary metadata.
type Entry struct {
ID string `yaml:"id" json:"id"`
Name string `yaml:"name" json:"name"`
Category string `yaml:"category" json:"category"`
Description string `yaml:"description,omitempty" json:"description,omitempty"`
Aliases []string `yaml:"aliases,omitempty" json:"aliases,omitempty"`
Plural *string `yaml:"plural,omitempty" json:"plural,omitempty"`
Extra map[string]any `yaml:",inline" json:"-"`
}
// MarshalJSON retains extension fields when validating or serializing typed entries.
func (entry Entry) MarshalJSON() ([]byte, error) {
type fields Entry
b, err := json.Marshal(fields(entry))
if err != nil {
return nil, err
}
var result map[string]any
if err := json.Unmarshal(b, &result); err != nil {
return nil, err
}
for key, value := range entry.Extra {
if _, known := result[key]; !known {
result[key] = value
}
}
return json.Marshal(result)
}
// CatalogRevision identifies the upstream source of the embedded schema.
const CatalogRevision = "ecad94a5a53f87847b1fd81fd042eee9c8d3ea08"
//go:embed glossary-v1.schema.json
var schemaData []byte
const schemaURL = "https://forge.maximumdirect.net/eric/narratio-reference-catalog/schemas/glossary-v1.schema.json"
var compiled struct {
sync.Once
document, partial *jsonschema.Schema
err error
}
type offlineLoader struct{}
func (offlineLoader) Load(url string) (any, error) {
return nil, fmt.Errorf("schema resource unavailable: %s", url)
}
func schemas() (*jsonschema.Schema, *jsonschema.Schema, error) {
compiled.Do(func() {
var doc any
if compiled.err = json.Unmarshal(schemaData, &doc); compiled.err != nil {
return
}
c := jsonschema.NewCompiler()
c.UseLoader(offlineLoader{})
if compiled.err = c.AddResource(schemaURL, doc); compiled.err != nil {
return
}
if compiled.document, compiled.err = c.Compile(schemaURL); compiled.err != nil {
return
}
compiled.partial, compiled.err = c.Compile(schemaURL + "#/$defs/partialCollection")
})
return compiled.document, compiled.partial, compiled.err
}
// ValidatePartial validates a decoded collection contribution without requiring entries.
func ValidatePartial(value any) error {
_, schema, err := schemas()
if err != nil {
return fmt.Errorf("compile glossary schema: %w", err)
}
v, err := jsonValue(value)
if err != nil {
return err
}
if err := schema.Validate(v); err != nil {
return fmt.Errorf("glossary contribution: %w", err)
}
return nil
}
// ValidateDocument validates decoded complete named collections and their IDs.
func ValidateDocument(value any) error {
schema, _, err := schemas()
if err != nil {
return fmt.Errorf("compile glossary schema: %w", err)
}
v, err := jsonValue(value)
if err != nil {
return err
}
if err := schema.Validate(v); err != nil {
return fmt.Errorf("glossary document: %w", err)
}
doc := v.(map[string]any)
names := make([]string, 0, len(doc))
for name := range doc {
names = append(names, name)
}
sort.Strings(names)
for _, name := range names {
if err := uniqueIDs("collection "+name, doc[name]); err != nil {
return err
}
}
return nil
}
func jsonValue(value any) (any, error) {
data, err := json.Marshal(value)
if err != nil {
return nil, fmt.Errorf("encode glossary data: %w", err)
}
decoder := json.NewDecoder(bytes.NewReader(data))
decoder.UseNumber()
var result any
if err := decoder.Decode(&result); err != nil {
return nil, fmt.Errorf("decode glossary data: %w", err)
}
return result, nil
}
func uniqueIDs(context string, value any) error {
collection := value.(map[string]any)
entries, _ := collection["entries"].([]any)
seen := make(map[string]bool, len(entries))
for _, raw := range entries {
id := raw.(map[string]any)["id"].(string)
if seen[id] {
return fmt.Errorf("%s: duplicate entry id %q", context, id)
}
seen[id] = true
}
return nil
}

View File

@@ -0,0 +1,63 @@
package glossary
import (
"encoding/json"
"strings"
"testing"
"gopkg.in/yaml.v3"
)
func TestValidation(t *testing.T) {
for _, tc := range []struct {
name, input string
partial, valid bool
}{
{"empty", "party: {entries: []}", false, true},
{"missing entries", "party: {instruction: hi}", false, false},
{"instruction only", "instruction: hi", true, true},
{"optional and extensions", "party: {entries: [{id: a, name: A, category: person, aliases: [Alias], plural: People, description: text, extra: {rank: 2}}]}", false, true},
{"missing category", "party: {entries: [{id: a, name: A}]}", false, false},
{"duplicate within collection", "party: {entries: [{id: a, name: A, category: person}, {id: a, name: B, category: person}]}", false, false},
{"same id across collections", "party: {entries: [{id: a, name: A, category: person}]}\nother: {entries: [{id: a, name: B, category: person}]}", false, true},
} {
t.Run(tc.name, func(t *testing.T) {
var value any
if err := yaml.Unmarshal([]byte(tc.input), &value); err != nil {
t.Fatal(err)
}
var err error
if tc.partial {
err = ValidatePartial(value)
} else {
err = ValidateDocument(value)
}
if (err == nil) != tc.valid {
t.Fatalf("valid=%v: %v", tc.valid, err)
}
if tc.name == "duplicate within collection" && !strings.Contains(err.Error(), "party") {
t.Fatal(err)
}
})
}
}
func TestTypedCollectionRetainsExtensionsAndEmptyInstruction(t *testing.T) {
var collection Collection
if err := yaml.Unmarshal([]byte("instruction: ''\nentries: [{id: a, name: A, category: person, source_note: test}]\n"), &collection); err != nil {
t.Fatal(err)
}
if collection.Instruction == nil || *collection.Instruction != "" || collection.Entries[0].Extra["source_note"] != "test" {
t.Fatalf("lost data: %+v", collection)
}
b, err := json.Marshal(map[string]Collection{"party": collection})
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(b), `"source_note":"test"`) || !strings.Contains(string(b), `"instruction":""`) {
t.Fatalf("lost data: %s", b)
}
if err := ValidateDocument(map[string]Collection{"party": collection}); err != nil {
t.Fatal(err)
}
}