Debian Codegraph @

openapi_vocabulary/vocabulary.go

raw
1 // Copyright 2025 Princess B33f Heavy Industries / Dave Shanley
2 // SPDX-License-Identifier: MIT
3
4 package openapi_vocabulary
5
6 import (
7 "github.com/santhosh-tekuri/jsonschema/v6"
8 )
9
10 // OpenAPIVocabularyURL is the vocabulary URL for OpenAPI-specific keywords
11 const OpenAPIVocabularyURL = "https://pb33f.io/openapi-validator/vocabulary"
12
13 // VersionType represents OpenAPI specification versions
14 type VersionType int
15
16 const (
17 // Version30 represents OpenAPI 3.0.x
18 Version30 VersionType = iota
19 Version31
20 Version32
21 )
22
23 // NewOpenAPIVocabulary creates a vocabulary for OpenAPI-specific keywords
24 // version determines which keywords are allowed/forbidden
25 func NewOpenAPIVocabulary(version VersionType) *jsonschema.Vocabulary {
26 return NewOpenAPIVocabularyWithCoercion(version, false)
27 }
28
29 // NewOpenAPIVocabularyWithCoercion creates a vocabulary with optional scalar coercion
30 func NewOpenAPIVocabularyWithCoercion(version VersionType, allowCoercion bool) *jsonschema.Vocabulary {
31 return &jsonschema.Vocabulary{
32 URL: OpenAPIVocabularyURL,
33 Schema: nil, // We don't validate the vocabulary schema itself
34 Compile: func(ctx *jsonschema.CompilerContext, obj map[string]any) (jsonschema.SchemaExt, error) {
35 return compileOpenAPIKeywords(ctx, obj, version, allowCoercion)
36 },
37 }
38 }
39
40 // compileOpenAPIKeywords compiles all OpenAPI-specific keywords found in the schema object
41 func compileOpenAPIKeywords(ctx *jsonschema.CompilerContext,
42 obj map[string]any,
43 version VersionType,
44 allowCoercion bool,
45 ) (jsonschema.SchemaExt, error) {
46 var extensions []jsonschema.SchemaExt
47
48 if ext, err := CompileNullable(ctx, obj, version); err != nil {
49 return nil, err
50 } else if ext != nil {
51 extensions = append(extensions, ext)
52 }
53
54 if ext, err := CompileDiscriminator(ctx, obj, version); err != nil {
55 return nil, err
56 } else if ext != nil {
57 extensions = append(extensions, ext)
58 }
59
60 if ext, err := CompileExample(ctx, obj, version); err != nil {
61 return nil, err
62 } else if ext != nil {
63 extensions = append(extensions, ext)
64 }
65
66 if ext, err := CompileDeprecated(ctx, obj, version); err != nil {
67 return nil, err
68 } else if ext != nil {
69 extensions = append(extensions, ext)
70 }
71
72 if ext, err := CompileCoercion(ctx, obj, allowCoercion); err != nil {
73 return nil, err
74 } else if ext != nil {
75 extensions = append(extensions, ext)
76 }
77
78 if len(extensions) == 0 {
79 return nil, nil
80 }
81
82 return &combinedExtension{extensions: extensions}, nil
83 }
84
85 // combinedExtension combines multiple OpenAPI extensions into one
86 type combinedExtension struct {
87 extensions []jsonschema.SchemaExt
88 }
89
90 func (c *combinedExtension) Validate(ctx *jsonschema.ValidatorContext, v any) {
91 for _, ext := range c.extensions {
92 ext.Validate(ctx, v)
93 }
94 }