Open History to see the last commit
1/**
2 * Type-safe helpers for walking arbitrary JSON Schema documents. Every
3 * accessor narrows from `unknown` so the strict no-unsafe-* lint rules hold
4 * even though schemas arrive as plain JSON.
5 */
6
7export type JsonValue =
8 | string
9 | number
10 | boolean
11 | null
12 | Array<JsonValue>
13 | { [key: string]: JsonValue }
14
15export type JsonObject = { [key: string]: JsonValue }
16
17export type SchemaNode = { readonly [key: string]: unknown }
18
19export function isSchemaNode(value: unknown): value is SchemaNode {
20 return typeof value === 'object' && value !== null && !Array.isArray(value)
21}
22
23export function isJsonObject(
24 value: JsonValue | undefined,
25): value is JsonObject {
26 return typeof value === 'object' && value !== null && !Array.isArray(value)
27}
28
29export function str(node: SchemaNode, key: string): string | undefined {
30 const value = node[key]
31 return typeof value === 'string' ? value : undefined
32}
33
34export function num(node: SchemaNode, key: string): number | undefined {
35 const value = node[key]
36 return typeof value === 'number' ? value : undefined
37}
38
39export function bool(node: SchemaNode, key: string): boolean | undefined {
40 const value = node[key]
41 return typeof value === 'boolean' ? value : undefined
42}
43
44export function arr(node: SchemaNode, key: string): Array<unknown> | undefined {
45 const value = node[key]
46 return Array.isArray(value) ? value : undefined
47}
48
49export function obj(node: SchemaNode, key: string): SchemaNode | undefined {
50 const value = node[key]
51 return isSchemaNode(value) ? value : undefined
52}
53
54/** Property map of an object schema, with non-object entries dropped. */
55export function properties(node: SchemaNode): Array<[string, SchemaNode]> {
56 const props = obj(node, 'properties')
57 if (props === undefined) return []
58 const out: Array<[string, SchemaNode]> = []
59 for (const [key, value] of Object.entries(props)) {
60 if (isSchemaNode(value)) out.push([key, value])
61 }
62 return out
63}
64
65export function requiredNames(node: SchemaNode): Set<string> {
66 const names = new Set<string>()
67 for (const entry of arr(node, 'required') ?? []) {
68 if (typeof entry === 'string') names.add(entry)
69 }
70 return names
71}
72
73/** `type` keyword, taking the first entry when it is an array. */
74export function schemaType(node: SchemaNode): string | undefined {
75 const single = str(node, 'type')
76 if (single !== undefined) return single
77 const many = arr(node, 'type')
78 const first = many?.find((t): t is string => typeof t === 'string')
79 return first
80}
81
82function isJsonValue(value: unknown): value is JsonValue {
83 if (value === null) return true
84 const kind = typeof value
85 if (kind === 'string' || kind === 'number' || kind === 'boolean') return true
86 if (Array.isArray(value)) return value.every(isJsonValue)
87 if (kind === 'object')
88 return Object.values(value as object).every(isJsonValue)
89 return false
90}
91
92export function asJsonValue(value: unknown): JsonValue | undefined {
93 return isJsonValue(value) ? value : undefined
94}
95
96export function enumValues(node: SchemaNode): Array<JsonValue> | undefined {
97 const values = arr(node, 'enum')
98 if (values === undefined) return undefined
99 const out: Array<JsonValue> = []
100 for (const value of values) {
101 const json = asJsonValue(value)
102 if (json !== undefined) out.push(json)
103 }
104 return out.length > 0 ? out : undefined
105}
106
107/** Follow `$ref: "#/$defs/Name"` chains against the root schema's `$defs`. */
108export function resolveRef(node: SchemaNode, root: SchemaNode): SchemaNode {
109 let current = node
110 for (let hop = 0; hop < 16; hop++) {
111 const ref = str(current, '$ref')
112 if (ref === undefined || !ref.startsWith('#/$defs/')) return current
113 const defs = obj(root, '$defs')
114 const target =
115 defs === undefined ? undefined : defs[ref.slice('#/$defs/'.length)]
116 if (!isSchemaNode(target)) return current
117 current = target
118 }
119 return current
120}
121
122/** anyOf/oneOf variants (resolved against root), or undefined. */
123export function variants(
124 node: SchemaNode,
125 root: SchemaNode,
126): Array<SchemaNode> | undefined {
127 const list = arr(node, 'anyOf') ?? arr(node, 'oneOf')
128 if (list === undefined) return undefined
129 const out = list.filter(isSchemaNode).map((v) => resolveRef(v, root))
130 return out.length > 0 ? out : undefined
131}
132
133/** A short human label for a schema, for variant tabs and array items. */
134export function schemaLabel(node: SchemaNode, fallback: string): string {
135 const title = str(node, 'title')
136 if (title !== undefined) return title
137 const constant = node['const']
138 if (typeof constant === 'string') return constant
139 const type = schemaType(node)
140 if (type === 'object') {
141 const props = properties(node)
142 const typeProp = props.find(([name]) => name === 'type')?.[1]
143 const tag = typeProp === undefined ? undefined : enumValues(typeProp)?.[0]
144 if (typeof tag === 'string') return tag
145 }
146 if (type !== undefined) return type
147 if (enumValues(node) !== undefined) return 'enum'
148 return fallback
149}
150
151/** Build a starter value for a schema: default → example → const → enum[0]
152 * → type seed. Objects seed required properties only. */
153export function seedValue(
154 node: SchemaNode,
155 root: SchemaNode,
156 depth = 0,
157): JsonValue {
158 if (depth > 12) return null
159 const resolved = resolveRef(node, root)
160 for (const key of ['default', 'const', 'example'] as const) {
161 const candidate = asJsonValue(resolved[key])
162 if (candidate !== undefined) return candidate
163 }
164 const options = enumValues(resolved)
165 if (options !== undefined && options[0] !== undefined) return options[0]
166 const variantList = variants(resolved, root)
167 if (variantList?.[0] !== undefined)
168 return seedValue(variantList[0], root, depth + 1)
169 switch (schemaType(resolved)) {
170 case 'string':
171 return ''
172 case 'integer':
173 case 'number':
174 return num(resolved, 'minimum') ?? 0
175 case 'boolean':
176 return false
177 case 'array': {
178 const minItems = num(resolved, 'minItems') ?? 0
179 const items = obj(resolved, 'items')
180 if (minItems > 0 && items !== undefined)
181 return Array.from({ length: minItems }, () =>
182 seedValue(items, root, depth + 1),
183 )
184 return []
185 }
186 case 'object': {
187 const out: JsonObject = {}
188 const required = requiredNames(resolved)
189 for (const [name, prop] of properties(resolved)) {
190 if (required.has(name))
191 out[name] = seedValue(resolveRef(prop, root), root, depth + 1)
192 }
193 return out
194 }
195 case 'null':
196 return null
197 default:
198 return null
199 }
200}
201
202/** Index of the variant whose shape best matches the current value. */
203export function matchVariant(
204 value: JsonValue | undefined,
205 variantList: Array<SchemaNode>,
206): number {
207 if (value === undefined) return 0
208 let best = 0
209 let bestScore = -1
210 variantList.forEach((variant, index) => {
211 let score = 0
212 const type = schemaType(variant)
213 const valueType = Array.isArray(value) ? 'array' : typeof value
214 if (type === valueType) score += 1
215 if (type === 'integer' && valueType === 'number') score += 1
216 const options = enumValues(variant)
217 if (options?.some((option) => option === value) === true) score += 2
218 if (isJsonObject(value) && type === 'object') {
219 const props = properties(variant)
220 for (const [name, prop] of props) {
221 if (name in value) {
222 score += 1
223 const tag = enumValues(prop)?.[0]
224 if (tag !== undefined && value[name] === tag) score += 3
225 }
226 }
227 }
228 if (score > bestScore) {
229 bestScore = score
230 best = index
231 }
232 })
233 return best
234}