Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

schema-view.ts

365 lines11.4 KB

1/**
2 * JSON Schema → property-table rows for the human-readable schema view.
3 * Pure and defensive: provider schemas vary wildly (hand-written OpenAPI,
4 * pydantic output, FAL's generated specs), so every accessor tolerates
5 * missing or oddly-typed fields and falls back to a generic label.
6 */
7​
8export type TypeClass =
9 | 'string'
10 | 'number'
11 | 'boolean'
12 | 'enum'
13 | 'object'
14 | 'array'
15 | 'union'
16​
17export interface PropRow {
18 name: string
19 required: boolean
20 typeLabel: string
21 /** `$defs` names that appear intact in `typeLabel`, longest first. */
22 typeRefs: Array<string>
23 typeClass: TypeClass
24 constraints: Array<string>
25 deprecated: boolean
26 description: string | null
27 children: Array<PropRow>
29​
30/** DOM id for a bundled `$defs` entry. Names are stable within one schema. */
31export function defDomId(name: string): string {
32 return `schema-def-${name.replaceAll(/[^A-Za-z0-9_-]/g, '_')}`
34​
35type SchemaNode = Record<string, unknown>
36​
37const MAX_DEPTH = 4
38const MAX_ENUM_SHOWN = 6
39const MAX_DESCRIPTION = 260
40​
41function isObject(value: unknown): value is SchemaNode {
42 return typeof value === 'object' && value !== null && !Array.isArray(value)
44​
45function refName(ref: string): string {
46 const last = ref.split('/').at(-1)
47 return last && last.length > 0 ? last : ref
49​
50function resolveRef(node: SchemaNode, defs: SchemaNode): SchemaNode {
51 const ref = node.$ref
52 if (typeof ref !== 'string') return node
53 const target = defs[refName(ref)]
54 return isObject(target) ? target : node
56​
57function firstParagraph(text: string): string {
58 const para = (text.split('\n\n')[0] ?? text).replaceAll(/\s+/g, ' ').trim()
59 return para.length > MAX_DESCRIPTION
60 ? `${para.slice(0, MAX_DESCRIPTION)}…`
61 : para
63​
64function formatValue(value: unknown): string {
65 // callers guard against undefined, so stringify always yields a string
66 const text = JSON.stringify(value)
67 return text.length > 32 ? `${text.slice(0, 32)}…` : text
69​
70/** Union members minus `{type:"null"}` / `null` markers. */
71function nonNullVariants(variants: Array<unknown>): Array<SchemaNode> {
72 return variants.filter(
73 (v): v is SchemaNode => isObject(v) && v.type !== 'null',
74 )
76​
77/** Short label for use inside union/array labels. */
78function shortLabel(node: SchemaNode, defs: SchemaNode): string {
79 if (typeof node.$ref === 'string') return refName(node.$ref)
80 if (Array.isArray(node.enum)) return 'enum'
81 if (node.const !== undefined) return formatValue(node.const)
82 const variants = node.anyOf ?? node.oneOf
83 if (Array.isArray(variants)) {
84 const real = nonNullVariants(variants)
85 const single = real.length === 1 ? real[0] : undefined
86 if (single !== undefined) return shortLabel(single, defs)
87 return real
88 .slice(0, 3)
89 .map((v) => shortLabel(v, defs))
90 .join(' | ')
91 }
92 if (node.type === 'array') {
93 const items = isObject(node.items) ? node.items : {}
94 return `${shortLabel(items, defs)}[]`
95 }
96 if (typeof node.type === 'string') {
97 if (node.type === 'object' && typeof node.title === 'string') {
98 return node.title
99 }
100 return node.type
101 }
102 if (typeof node.title === 'string') return node.title
103 return 'any'
105​
106function numericConstraints(node: SchemaNode): Array<string> {
107 const out: Array<string> = []
108 const min = node.minimum ?? node.exclusiveMinimum
109 const max = node.maximum ?? node.exclusiveMaximum
110 const minOp = node.minimum !== undefined ? '≤' : '<'
111 const maxOp = node.maximum !== undefined ? '≤' : '<'
112 if (typeof min === 'number' && typeof max === 'number') {
113 out.push(`${String(min)} ${minOp} n ${maxOp} ${String(max)}`)
114 } else if (typeof min === 'number') {
115 out.push(
116 node.minimum !== undefined ? `n ≥ ${String(min)}` : `n > ${String(min)}`,
117 )
118 } else if (typeof max === 'number') {
119 out.push(
120 node.maximum !== undefined ? `n ≤ ${String(max)}` : `n < ${String(max)}`,
121 )
122 }
123 if (typeof node.minLength === 'number') {
124 out.push(`length ≥ ${String(node.minLength)}`)
125 }
126 if (typeof node.maxLength === 'number') {
127 out.push(`length ≤ ${String(node.maxLength)}`)
128 }
129 if (typeof node.minItems === 'number') {
130 out.push(`items ≥ ${String(node.minItems)}`)
131 }
132 if (typeof node.maxItems === 'number') {
133 out.push(`items ≤ ${String(node.maxItems)}`)
134 }
135 return out
137​
138function enumConstraint(values: Array<unknown>): string {
139 const shown = values.slice(0, MAX_ENUM_SHOWN).map(formatValue)
140 const extra = values.length - MAX_ENUM_SHOWN
141 const list = shown.join(' | ').replaceAll('"', '')
142 return extra > 0 ? `${list} · +${String(extra)} more` : list
144​
145function childRows(
146 node: SchemaNode,
147 defs: SchemaNode,
148 depth: number,
149 seen: Set<string>,
150): Array<PropRow> {
151 if (depth >= MAX_DEPTH) return []
152 const properties = node.properties
153 if (!isObject(properties)) return []
154 const required = Array.isArray(node.required)
155 ? node.required.filter((r): r is string => typeof r === 'string')
156 : []
157 return propertyRows(properties, required, defs, depth, seen)
159​
160function buildRow(
161 name: string,
162 rawNode: unknown,
163 required: boolean,
164 defs: SchemaNode,
165 depth: number,
166 seen: Set<string>,
167): PropRow {
168 const node = isObject(rawNode) ? rawNode : {}
169 const ref = typeof node.$ref === 'string' ? refName(node.$ref) : null
170 const cycle = ref !== null && seen.has(ref)
171 const nextSeen = ref === null ? seen : new Set([...seen, ref])
172 const resolved = cycle ? node : resolveRef(node, defs)
173​
174 // annotations on the reference site win over the referenced definition
175 const description =
176 typeof node.description === 'string'
177 ? node.description
178 : typeof resolved.description === 'string'
179 ? resolved.description
180 : null
181 const deprecated = node.deprecated === true || resolved.deprecated === true
182​
183 const constraints: Array<string> = []
184 let typeLabel = 'any'
185 let typeClass: TypeClass = 'union'
186 let children: Array<PropRow> = []
187​
188 const variantsRaw = resolved.anyOf ?? resolved.oneOf ?? resolved.allOf
189 const enumValues = resolved.enum
190​
191 if (Array.isArray(enumValues)) {
192 typeLabel = 'enum'
193 typeClass = 'enum'
194 constraints.push(enumConstraint(enumValues))
195 } else if (resolved.const !== undefined) {
196 typeLabel = 'const'
197 typeClass = 'enum'
198 constraints.push(formatValue(resolved.const))
199 } else if (Array.isArray(variantsRaw) && !cycle) {
200 const real = nonNullVariants(variantsRaw)
201 const nullable = real.length < variantsRaw.length
202 const single = real.length === 1 ? real[0] : undefined
203 if (single !== undefined) {
204 const inner = buildRow(name, single, required, defs, depth, nextSeen)
205 if (nullable) inner.constraints.push('nullable')
206 if (inner.description === null) inner.description = description
207 inner.deprecated = inner.deprecated || deprecated
208 return { ...inner, required }
209 }
210 // `string | const | const…` unions (model-id lists) read as string
211 const allStringy = real.every((v) => {
212 const r = resolveRef(v, defs)
213 return r.type === 'string' || typeof r.const === 'string'
214 })
215 const consts = real.filter((v) => {
216 const r = resolveRef(v, defs)
217 return typeof r.const === 'string'
218 })
219 if (allStringy && consts.length > 0) {
220 typeLabel = 'string'
221 typeClass = 'string'
222 constraints.push(`${String(consts.length)} known values`)
223 } else {
224 typeLabel = real
225 .slice(0, 3)
226 .map((v) => shortLabel(resolveRef(v, defs), defs))
227 .join(' | ')
228 if (real.length > 3) typeLabel += ' | …'
229 typeClass = 'union'
230 }
231 if (nullable) constraints.push('nullable')
232 } else if (resolved.type === 'array') {
233 const items = isObject(resolved.items) ? resolved.items : {}
234 const itemsResolved = resolveRef(items, defs)
235 typeLabel = `${shortLabel(items, defs)}[]`
236 typeClass = 'array'
237 if (!cycle) children = childRows(itemsResolved, defs, depth + 1, nextSeen)
238 } else if (resolved.type === 'object' || isObject(resolved.properties)) {
239 typeLabel =
240 ref ?? (typeof resolved.title === 'string' ? 'object' : 'object')
241 typeClass = 'object'
242 if (!cycle) children = childRows(resolved, defs, depth + 1, nextSeen)
243 } else if (typeof resolved.type === 'string') {
244 typeLabel = resolved.type
245 typeClass =
246 resolved.type === 'string'
247 ? 'string'
248 : resolved.type === 'number' || resolved.type === 'integer'
249 ? 'number'
250 : resolved.type === 'boolean'
251 ? 'boolean'
252 : 'union'
253 } else if (ref !== null) {
254 typeLabel = ref
255 typeClass = 'object'
256 }
257​
258 constraints.push(...numericConstraints(resolved))
259 if (typeof resolved.format === 'string') {
260 constraints.push(`format: ${resolved.format}`)
261 }
262 if (resolved.default !== undefined) {
263 constraints.push(`default: ${formatValue(resolved.default)}`)
264 }
265​
266 return {
267 name,
268 required,
269 typeLabel,
270 typeRefs: refsInLabel(typeLabel, defs),
271 typeClass,
272 constraints,
273 deprecated,
274 description: description === null ? null : firstParagraph(description),
275 children,
276 }
278​
279/** `$defs` keys that occur as whole substrings, longest first so shorter names do not steal a prefix. */
280function refsInLabel(label: string, defs: SchemaNode): Array<string> {
281 const names = Object.keys(defs)
282 .filter((name) => name.length > 0 && label.includes(name))
283 .sort((a, b) => b.length - a.length || a.localeCompare(b))
284 const used: Array<string> = []
285 let rest = label
286 while (rest.length > 0) {
287 let at = -1
288 let hit = ''
289 for (const name of names) {
290 const index = rest.indexOf(name)
291 if (index === -1) continue
292 if (
293 at === -1 ||
294 index < at ||
295 (index === at && name.length > hit.length)
296 ) {
297 at = index
298 hit = name
299 }
300 }
301 if (at === -1 || hit === '') break
302 used.push(hit)
303 rest = rest.slice(at + hit.length)
304 }
305 return used
307​
308function propertyRows(
309 properties: SchemaNode,
310 required: Array<string>,
311 defs: SchemaNode,
312 depth: number,
313 seen: Set<string>,
314): Array<PropRow> {
315 const requiredSet = new Set(required)
316 return Object.entries(properties).map(([name, node]) =>
317 buildRow(name, node, requiredSet.has(name), defs, depth, seen),
318 )
320​
321export interface SchemaRows {
322 /** Required properties first, in schema order; then optional. */
323 rows: Array<PropRow>
324 /** One row per `$defs` entry, so a type name can link to its shape. */
325 definitions: Array<PropRow>
326 requiredCount: number
327 propertyCount: number
328 defsCount: number
329 /** Set when the schema isn't an object with properties (rare). */
330 fallback: boolean
332​
333/** Rows for a bundled endpoint schema (object root with `$defs` closure). */
334export function schemaToRows(schema: unknown): SchemaRows {
335 if (!isObject(schema) || !isObject(schema.properties)) {
336 return {
337 rows: [],
338 definitions: [],
339 requiredCount: 0,
340 propertyCount: 0,
341 defsCount: 0,
342 fallback: true,
343 }
344 }
345 const defs = isObject(schema.$defs) ? schema.$defs : {}
346 const required = Array.isArray(schema.required)
347 ? schema.required.filter((r): r is string => typeof r === 'string')
348 : []
349 const all = propertyRows(schema.properties, required, defs, 0, new Set())
350 const rows = [
351 ...all.filter((r) => r.required),
352 ...all.filter((r) => !r.required),
353 ]
354 const definitions = Object.keys(defs)
355 .sort((a, b) => a.localeCompare(b))
356 .map((name) => buildRow(name, defs[name], false, defs, 0, new Set()))
357 return {
358 rows,
359 definitions,
360 requiredCount: required.length,
361 propertyCount: all.length,
362 defsCount: definitions.length,
363 fallback: false,
364 }