@kubb/ast 5.0.0-beta.4 → 5.0.0-beta.41
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +28 -19
- package/dist/index.cjs +866 -395
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +33 -3310
- package/dist/index.js +859 -391
- package/dist/index.js.map +1 -1
- package/dist/types-CEIHPTfs.d.ts +3596 -0
- package/dist/types.cjs +0 -0
- package/dist/types.d.ts +2 -0
- package/dist/types.js +1 -0
- package/package.json +8 -4
- package/src/constants.ts +2 -52
- package/src/dedupe.ts +200 -0
- package/src/dialect.ts +58 -0
- package/src/dispatch.ts +53 -0
- package/src/factory.ts +133 -17
- package/src/guards.ts +18 -48
- package/src/index.ts +9 -5
- package/src/infer.ts +16 -14
- package/src/nodes/base.ts +2 -0
- package/src/nodes/code.ts +22 -22
- package/src/nodes/content.ts +37 -0
- package/src/nodes/file.ts +16 -14
- package/src/nodes/function.ts +11 -11
- package/src/nodes/index.ts +7 -3
- package/src/nodes/operation.ts +98 -62
- package/src/nodes/response.ts +21 -14
- package/src/nodes/root.ts +72 -10
- package/src/nodes/schema.ts +12 -9
- package/src/printer.ts +42 -36
- package/src/refs.ts +0 -54
- package/src/resolvers.ts +4 -4
- package/src/signature.ts +232 -0
- package/src/transformers.ts +20 -15
- package/src/types.ts +9 -2
- package/src/utils.ts +118 -77
- package/src/visitor.ts +237 -279
- /package/dist/{chunk--u3MIqq1.js → chunk-C0LytTxp.js} +0 -0
package/src/printer.ts
CHANGED
|
@@ -18,7 +18,7 @@ export type PrinterHandlerContext<TOutput, TOptions extends object> = {
|
|
|
18
18
|
* Recursively transform a nested `SchemaNode` to `TOutput` using the node-level handlers.
|
|
19
19
|
* Use `this.transform` inside `nodes` handlers and inside the `print` override.
|
|
20
20
|
*/
|
|
21
|
-
transform: (node: SchemaNode) => TOutput | null
|
|
21
|
+
transform: (node: SchemaNode) => TOutput | null
|
|
22
22
|
/**
|
|
23
23
|
* Options for this printer instance.
|
|
24
24
|
*/
|
|
@@ -40,13 +40,13 @@ export type PrinterHandlerContext<TOutput, TOptions extends object> = {
|
|
|
40
40
|
export type PrinterHandler<TOutput, TOptions extends object, T extends SchemaType = SchemaType> = (
|
|
41
41
|
this: PrinterHandlerContext<TOutput, TOptions>,
|
|
42
42
|
node: SchemaNodeByType[T],
|
|
43
|
-
) => TOutput | null
|
|
43
|
+
) => TOutput | null
|
|
44
44
|
|
|
45
45
|
/**
|
|
46
46
|
* Partial map of per-node-type handler overrides for a printer.
|
|
47
47
|
*
|
|
48
48
|
* Each key is a `SchemaType` string (e.g. `'date'`, `'string'`).
|
|
49
|
-
* Supply only the handlers you want to replace
|
|
49
|
+
* Supply only the handlers you want to replace. The printer's built-in
|
|
50
50
|
* defaults fill in the rest.
|
|
51
51
|
*
|
|
52
52
|
* @example
|
|
@@ -69,10 +69,10 @@ export type PrinterPartial<TOutput, TOptions extends object> = Partial<{
|
|
|
69
69
|
/**
|
|
70
70
|
* Generic shape used by `definePrinter`.
|
|
71
71
|
*
|
|
72
|
-
* - `TName`
|
|
73
|
-
* - `TOptions`
|
|
74
|
-
* - `TOutput`
|
|
75
|
-
* - `TPrintOutput`
|
|
72
|
+
* - `TName` unique string identifier (e.g. `'zod'`, `'ts'`)
|
|
73
|
+
* - `TOptions` options passed to and stored on the printer instance
|
|
74
|
+
* - `TOutput` the type emitted by node handlers
|
|
75
|
+
* - `TPrintOutput` type returned by public `print` (defaults to `TOutput`)
|
|
76
76
|
*
|
|
77
77
|
* @example
|
|
78
78
|
* ```ts
|
|
@@ -104,17 +104,17 @@ export type Printer<T extends PrinterFactoryOptions = PrinterFactoryOptions> = {
|
|
|
104
104
|
*/
|
|
105
105
|
options: T['options']
|
|
106
106
|
/**
|
|
107
|
-
* Node-level dispatcher
|
|
108
|
-
* Always dispatches through the `nodes` map
|
|
107
|
+
* Node-level dispatcher, converts a `SchemaNode` directly to `TOutput` using the `nodes` handlers.
|
|
108
|
+
* Always dispatches through the `nodes` map. Never calls the `print` override.
|
|
109
109
|
* Use this when you need the raw output (e.g. `ts.TypeNode`) without declaration wrapping.
|
|
110
110
|
*/
|
|
111
|
-
transform: (node: SchemaNode) => T['output'] | null
|
|
111
|
+
transform: (node: SchemaNode) => T['output'] | null
|
|
112
112
|
/**
|
|
113
113
|
* Public printer. If the builder provides a root-level `print`, this calls that
|
|
114
114
|
* higher-level function (which may produce full declarations).
|
|
115
115
|
* Otherwise, falls back to the node-level dispatcher.
|
|
116
116
|
*/
|
|
117
|
-
print: (node: SchemaNode) => T['printOutput'] | null
|
|
117
|
+
print: (node: SchemaNode) => T['printOutput'] | null
|
|
118
118
|
}
|
|
119
119
|
|
|
120
120
|
/**
|
|
@@ -143,28 +143,32 @@ type PrinterBuilder<T extends PrinterFactoryOptions> = (options: T['options']) =
|
|
|
143
143
|
/**
|
|
144
144
|
* Optional root-level print override. When provided, becomes the public `printer.print`.
|
|
145
145
|
* Use `this.transform(node)` inside this function to dispatch to the node-level handlers (`nodes`),
|
|
146
|
-
* not the override itself
|
|
146
|
+
* not the override itself, so recursion is safe.
|
|
147
147
|
*/
|
|
148
148
|
print?: (this: PrinterHandlerContext<T['output'], T['options']>, node: SchemaNode) => T['printOutput'] | null
|
|
149
149
|
}
|
|
150
|
-
|
|
151
150
|
/**
|
|
152
|
-
*
|
|
153
|
-
*
|
|
154
|
-
*
|
|
151
|
+
* Defines a schema printer: a function that takes a `SchemaNode` and emits
|
|
152
|
+
* code in your target language. Each plugin that produces code from schemas
|
|
153
|
+
* (TypeScript types, Zod schemas, Faker factories) ships a printer built
|
|
154
|
+
* with this helper.
|
|
155
155
|
*
|
|
156
156
|
* The builder receives resolved options and returns:
|
|
157
|
-
* - `name` — a unique identifier for the printer
|
|
158
|
-
* - `options` — options stored on the returned printer instance
|
|
159
|
-
* - `nodes` — a map of `SchemaType` → handler functions that convert a `SchemaNode` to `TOutput`
|
|
160
|
-
* - `print` _(optional)_ — top-level override exposed as `printer.print`
|
|
161
|
-
* - Inside this function, use `this.transform(node)` to dispatch to the `nodes` map
|
|
162
|
-
* - This keeps recursion safe and avoids self-calls
|
|
163
157
|
*
|
|
164
|
-
*
|
|
158
|
+
* - `name` unique identifier for the printer.
|
|
159
|
+
* - `options` stored on the returned printer instance.
|
|
160
|
+
* - `nodes` map of `SchemaType` → handler. Handlers return the rendered
|
|
161
|
+
* output (a string, a TypeScript AST node, ...) for that schema type.
|
|
162
|
+
* - `print` (optional), top-level override exposed as `printer.print`.
|
|
163
|
+
* Use `this.transform(node)` inside it to dispatch to `nodes` recursively.
|
|
165
164
|
*
|
|
166
|
-
*
|
|
165
|
+
* Without a `print` override, `printer.print` falls back to `printer.transform`
|
|
166
|
+
* (the node-level dispatcher).
|
|
167
|
+
*
|
|
168
|
+
* @example Tiny Zod printer
|
|
167
169
|
* ```ts
|
|
170
|
+
* import { definePrinter, type PrinterFactoryOptions } from '@kubb/ast'
|
|
171
|
+
*
|
|
168
172
|
* type PrinterZod = PrinterFactoryOptions<'zod', { strict?: boolean }, string>
|
|
169
173
|
*
|
|
170
174
|
* export const zodPrinter = definePrinter<PrinterZod>((options) => ({
|
|
@@ -173,7 +177,9 @@ type PrinterBuilder<T extends PrinterFactoryOptions> = (options: T['options']) =
|
|
|
173
177
|
* nodes: {
|
|
174
178
|
* string: () => 'z.string()',
|
|
175
179
|
* object(node) {
|
|
176
|
-
* const props = node.properties
|
|
180
|
+
* const props = node.properties
|
|
181
|
+
* .map((p) => `${p.name}: ${this.transform(p.schema)}`)
|
|
182
|
+
* .join(', ')
|
|
177
183
|
* return `z.object({ ${props} })`
|
|
178
184
|
* },
|
|
179
185
|
* },
|
|
@@ -194,7 +200,7 @@ export function definePrinter<T extends PrinterFactoryOptions = PrinterFactoryOp
|
|
|
194
200
|
* )
|
|
195
201
|
* ```
|
|
196
202
|
*/
|
|
197
|
-
export function createPrinterFactory<TNode, TKey extends string, TNodeByKey extends Partial<Record<TKey, TNode>>>(getKey: (node: TNode) => TKey |
|
|
203
|
+
export function createPrinterFactory<TNode, TKey extends string, TNodeByKey extends Partial<Record<TKey, TNode>>>(getKey: (node: TNode) => TKey | null) {
|
|
198
204
|
return function <T extends PrinterFactoryOptions>(
|
|
199
205
|
build: (options: T['options']) => {
|
|
200
206
|
name: T['name']
|
|
@@ -202,40 +208,40 @@ export function createPrinterFactory<TNode, TKey extends string, TNodeByKey exte
|
|
|
202
208
|
nodes: Partial<{
|
|
203
209
|
[K in TKey]: (
|
|
204
210
|
this: {
|
|
205
|
-
transform: (node: TNode) => T['output'] | null
|
|
211
|
+
transform: (node: TNode) => T['output'] | null
|
|
206
212
|
options: T['options']
|
|
207
213
|
},
|
|
208
214
|
node: TNodeByKey[K],
|
|
209
|
-
) => T['output'] | null
|
|
215
|
+
) => T['output'] | null
|
|
210
216
|
}>
|
|
211
217
|
print?: (
|
|
212
218
|
this: {
|
|
213
|
-
transform: (node: TNode) => T['output'] | null
|
|
219
|
+
transform: (node: TNode) => T['output'] | null
|
|
214
220
|
options: T['options']
|
|
215
221
|
},
|
|
216
222
|
node: TNode,
|
|
217
|
-
) => T['printOutput'] | null
|
|
223
|
+
) => T['printOutput'] | null
|
|
218
224
|
},
|
|
219
225
|
): (options?: T['options']) => {
|
|
220
226
|
name: T['name']
|
|
221
227
|
options: T['options']
|
|
222
|
-
transform: (node: TNode) => T['output'] | null
|
|
223
|
-
print: (node: TNode) => T['printOutput'] | null
|
|
228
|
+
transform: (node: TNode) => T['output'] | null
|
|
229
|
+
print: (node: TNode) => T['printOutput'] | null
|
|
224
230
|
} {
|
|
225
231
|
return (options) => {
|
|
226
232
|
const { name, options: resolvedOptions, nodes, print: printOverride } = build(options ?? ({} as T['options']))
|
|
227
233
|
|
|
228
234
|
const context = {
|
|
229
235
|
options: resolvedOptions,
|
|
230
|
-
transform: (node: TNode): T['output'] | null
|
|
236
|
+
transform: (node: TNode): T['output'] | null => {
|
|
231
237
|
const key = getKey(node)
|
|
232
|
-
if (key ===
|
|
238
|
+
if (key === null) return null
|
|
233
239
|
|
|
234
240
|
const handler = nodes[key]
|
|
235
241
|
|
|
236
242
|
if (!handler) return null
|
|
237
243
|
|
|
238
|
-
return (handler as (this: typeof context, node: TNode) => T['output'] | null
|
|
244
|
+
return (handler as (this: typeof context, node: TNode) => T['output'] | null).call(context, node)
|
|
239
245
|
},
|
|
240
246
|
}
|
|
241
247
|
|
|
@@ -243,7 +249,7 @@ export function createPrinterFactory<TNode, TKey extends string, TNodeByKey exte
|
|
|
243
249
|
name,
|
|
244
250
|
options: resolvedOptions,
|
|
245
251
|
transform: context.transform,
|
|
246
|
-
print: (printOverride ? printOverride.bind(context) : context.transform) as (node: TNode) => T['printOutput'] | null
|
|
252
|
+
print: (printOverride ? printOverride.bind(context) : context.transform) as (node: TNode) => T['printOutput'] | null,
|
|
247
253
|
}
|
|
248
254
|
}
|
|
249
255
|
}
|
package/src/refs.ts
CHANGED
|
@@ -1,11 +1,3 @@
|
|
|
1
|
-
import type { InputNode } from './nodes/root.ts'
|
|
2
|
-
import type { SchemaNode } from './nodes/schema.ts'
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* Lookup map from schema name to `SchemaNode`.
|
|
6
|
-
*/
|
|
7
|
-
export type RefMap = Map<string, SchemaNode>
|
|
8
|
-
|
|
9
1
|
/**
|
|
10
2
|
* Returns the last path segment of a reference string.
|
|
11
3
|
*
|
|
@@ -19,49 +11,3 @@ export type RefMap = Map<string, SchemaNode>
|
|
|
19
11
|
export function extractRefName(ref: string): string {
|
|
20
12
|
return ref.split('/').at(-1) ?? ref
|
|
21
13
|
}
|
|
22
|
-
|
|
23
|
-
/**
|
|
24
|
-
* Builds a `RefMap` from `input.schemas` using each schema's `name`.
|
|
25
|
-
*
|
|
26
|
-
* Unnamed schemas are skipped.
|
|
27
|
-
*
|
|
28
|
-
* @example
|
|
29
|
-
* ```ts
|
|
30
|
-
* const refMap = buildRefMap(input)
|
|
31
|
-
* const pet = refMap.get('Pet')
|
|
32
|
-
* ```
|
|
33
|
-
*/
|
|
34
|
-
export function buildRefMap(input: InputNode): RefMap {
|
|
35
|
-
const map: RefMap = new Map()
|
|
36
|
-
|
|
37
|
-
for (const schema of input.schemas) {
|
|
38
|
-
if (schema.name) {
|
|
39
|
-
map.set(schema.name, schema)
|
|
40
|
-
}
|
|
41
|
-
}
|
|
42
|
-
return map
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
/**
|
|
46
|
-
* Resolves a schema by name from a `RefMap`.
|
|
47
|
-
*
|
|
48
|
-
* @example
|
|
49
|
-
* ```ts
|
|
50
|
-
* const petSchema = resolveRef(refMap, 'Pet')
|
|
51
|
-
* ```
|
|
52
|
-
*/
|
|
53
|
-
export function resolveRef(refMap: RefMap, ref: string): SchemaNode | undefined {
|
|
54
|
-
return refMap.get(ref)
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
/**
|
|
58
|
-
* Converts a `RefMap` into a plain object.
|
|
59
|
-
*
|
|
60
|
-
* @example
|
|
61
|
-
* ```ts
|
|
62
|
-
* const refsObject = refMapToObject(refMap)
|
|
63
|
-
* ```
|
|
64
|
-
*/
|
|
65
|
-
export function refMapToObject(refMap: RefMap): Record<string, SchemaNode> {
|
|
66
|
-
return Object.fromEntries(refMap)
|
|
67
|
-
}
|
package/src/resolvers.ts
CHANGED
|
@@ -27,17 +27,17 @@ export function collectImports<TImport>({
|
|
|
27
27
|
}: {
|
|
28
28
|
node: SchemaNode
|
|
29
29
|
nameMapping: Map<string, string>
|
|
30
|
-
resolve: (schemaName: string) => TImport |
|
|
30
|
+
resolve: (schemaName: string) => TImport | null
|
|
31
31
|
}): Array<TImport> {
|
|
32
32
|
return collect<TImport>(node, {
|
|
33
|
-
schema(schemaNode): TImport |
|
|
33
|
+
schema(schemaNode): TImport | null {
|
|
34
34
|
const schemaRef = narrowSchema(schemaNode, 'ref')
|
|
35
|
-
if (!schemaRef?.ref) return
|
|
35
|
+
if (!schemaRef?.ref) return null
|
|
36
36
|
|
|
37
37
|
const rawName = extractRefName(schemaRef.ref)
|
|
38
38
|
const schemaName = nameMapping.get(rawName) ?? rawName
|
|
39
39
|
const result = resolve(schemaName)
|
|
40
|
-
if (!result) return
|
|
40
|
+
if (!result) return null
|
|
41
41
|
|
|
42
42
|
return result
|
|
43
43
|
},
|
package/src/signature.ts
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto'
|
|
2
|
+
import type { SchemaNode } from './nodes/index.ts'
|
|
3
|
+
import { extractRefName } from './refs.ts'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The shape-affecting flags shared by every node kind: base primitive, format, and `nullable`.
|
|
7
|
+
* Documentation and usage-slot flags (`optional`/`nullish`/`readOnly`/`writeOnly`) are
|
|
8
|
+
* intentionally excluded, they describe the property slot, not the type.
|
|
9
|
+
*/
|
|
10
|
+
function flagsDescriptor(node: SchemaNode): string {
|
|
11
|
+
return `${node.primitive ?? ''};${node.format ?? ''};${node.nullable ? 1 : 0}`
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function refTargetName(node: Extract<SchemaNode, { type: 'ref' }>): string {
|
|
15
|
+
if (node.ref) return extractRefName(node.ref)
|
|
16
|
+
return node.name ?? ''
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
type ScalarField = { kind: 'scalar'; key: string; prefix: string }
|
|
20
|
+
type BoolField = { kind: 'bool'; key: string; prefix: string }
|
|
21
|
+
type ChildField = { kind: 'child'; key: string; prefix: string }
|
|
22
|
+
type ChildrenField = { kind: 'children'; key: string; prefix: string }
|
|
23
|
+
type ObjectPropsField = { kind: 'objectProps' }
|
|
24
|
+
type AdditionalPropsField = { kind: 'additionalProps' }
|
|
25
|
+
type PatternPropsField = { kind: 'patternProps' }
|
|
26
|
+
type EnumValuesField = { kind: 'enumValues' }
|
|
27
|
+
type RefTargetField = { kind: 'refTarget' }
|
|
28
|
+
|
|
29
|
+
type ShapeField =
|
|
30
|
+
| ScalarField
|
|
31
|
+
| BoolField
|
|
32
|
+
| ChildField
|
|
33
|
+
| ChildrenField
|
|
34
|
+
| ObjectPropsField
|
|
35
|
+
| AdditionalPropsField
|
|
36
|
+
| PatternPropsField
|
|
37
|
+
| EnumValuesField
|
|
38
|
+
| RefTargetField
|
|
39
|
+
|
|
40
|
+
const arrayTupleFields: ReadonlyArray<ShapeField> = [
|
|
41
|
+
{ kind: 'children', key: 'items', prefix: 'i' },
|
|
42
|
+
{ kind: 'child', key: 'rest', prefix: 'r' },
|
|
43
|
+
{ kind: 'scalar', key: 'min', prefix: 'mn' },
|
|
44
|
+
{ kind: 'scalar', key: 'max', prefix: 'mx' },
|
|
45
|
+
{ kind: 'bool', key: 'unique', prefix: 'u' },
|
|
46
|
+
]
|
|
47
|
+
|
|
48
|
+
const numericFields: ReadonlyArray<ShapeField> = [
|
|
49
|
+
{ kind: 'scalar', key: 'min', prefix: 'mn' },
|
|
50
|
+
{ kind: 'scalar', key: 'max', prefix: 'mx' },
|
|
51
|
+
{ kind: 'scalar', key: 'exclusiveMinimum', prefix: 'emn' },
|
|
52
|
+
{ kind: 'scalar', key: 'exclusiveMaximum', prefix: 'emx' },
|
|
53
|
+
{ kind: 'scalar', key: 'multipleOf', prefix: 'mo' },
|
|
54
|
+
]
|
|
55
|
+
|
|
56
|
+
const rangeFields: ReadonlyArray<ShapeField> = [
|
|
57
|
+
{ kind: 'scalar', key: 'min', prefix: 'mn' },
|
|
58
|
+
{ kind: 'scalar', key: 'max', prefix: 'mx' },
|
|
59
|
+
]
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Maps each schema node `type` to the ordered list of shape-contributing fields.
|
|
63
|
+
* Node types absent from this map (scalar types like boolean, null, any, etc.) fall
|
|
64
|
+
* back to `${type}|${flags}` with no additional fields.
|
|
65
|
+
*/
|
|
66
|
+
const SHAPE_KEYS: Partial<Record<SchemaNode['type'], ReadonlyArray<ShapeField>>> = {
|
|
67
|
+
object: [
|
|
68
|
+
{ kind: 'objectProps' },
|
|
69
|
+
{ kind: 'additionalProps' },
|
|
70
|
+
{ kind: 'patternProps' },
|
|
71
|
+
{ kind: 'scalar', key: 'minProperties', prefix: 'mn' },
|
|
72
|
+
{ kind: 'scalar', key: 'maxProperties', prefix: 'mx' },
|
|
73
|
+
],
|
|
74
|
+
array: arrayTupleFields,
|
|
75
|
+
tuple: arrayTupleFields,
|
|
76
|
+
union: [
|
|
77
|
+
{ kind: 'scalar', key: 'strategy', prefix: 's' },
|
|
78
|
+
{ kind: 'scalar', key: 'discriminatorPropertyName', prefix: 'd' },
|
|
79
|
+
{ kind: 'children', key: 'members', prefix: 'm' },
|
|
80
|
+
],
|
|
81
|
+
intersection: [{ kind: 'children', key: 'members', prefix: 'm' }],
|
|
82
|
+
enum: [{ kind: 'enumValues' }],
|
|
83
|
+
ref: [{ kind: 'refTarget' }],
|
|
84
|
+
string: [
|
|
85
|
+
{ kind: 'scalar', key: 'min', prefix: 'mn' },
|
|
86
|
+
{ kind: 'scalar', key: 'max', prefix: 'mx' },
|
|
87
|
+
{ kind: 'scalar', key: 'pattern', prefix: 'pt' },
|
|
88
|
+
],
|
|
89
|
+
number: numericFields,
|
|
90
|
+
integer: numericFields,
|
|
91
|
+
bigint: numericFields,
|
|
92
|
+
url: [
|
|
93
|
+
{ kind: 'scalar', key: 'path', prefix: 'path' },
|
|
94
|
+
{ kind: 'scalar', key: 'min', prefix: 'mn' },
|
|
95
|
+
{ kind: 'scalar', key: 'max', prefix: 'mx' },
|
|
96
|
+
],
|
|
97
|
+
uuid: rangeFields,
|
|
98
|
+
email: rangeFields,
|
|
99
|
+
datetime: [
|
|
100
|
+
{ kind: 'bool', key: 'offset', prefix: 'o' },
|
|
101
|
+
{ kind: 'bool', key: 'local', prefix: 'l' },
|
|
102
|
+
],
|
|
103
|
+
date: [{ kind: 'scalar', key: 'representation', prefix: 'rep' }],
|
|
104
|
+
time: [{ kind: 'scalar', key: 'representation', prefix: 'rep' }],
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function serializeShapeField(field: ShapeField, node: SchemaNode, record: Record<string, unknown>): string {
|
|
108
|
+
switch (field.kind) {
|
|
109
|
+
case 'scalar':
|
|
110
|
+
return `${field.prefix}:${record[field.key] ?? ''}`
|
|
111
|
+
case 'bool':
|
|
112
|
+
return `${field.prefix}:${record[field.key] ? 1 : 0}`
|
|
113
|
+
case 'child': {
|
|
114
|
+
const child = record[field.key] as SchemaNode | undefined
|
|
115
|
+
return `${field.prefix}:${child ? signatureOf(child) : ''}`
|
|
116
|
+
}
|
|
117
|
+
case 'children': {
|
|
118
|
+
const children = (record[field.key] as Array<SchemaNode> | undefined) ?? []
|
|
119
|
+
return `${field.prefix}[${children.map((c) => signatureOf(c)).join(',')}]`
|
|
120
|
+
}
|
|
121
|
+
case 'objectProps': {
|
|
122
|
+
const obj = node as Extract<SchemaNode, { type: 'object' }>
|
|
123
|
+
const props = (obj.properties ?? []).map((prop) => `${prop.name}${prop.required ? '!' : '?'}${signatureOf(prop.schema)}`).join(',')
|
|
124
|
+
return `p[${props}]`
|
|
125
|
+
}
|
|
126
|
+
case 'additionalProps': {
|
|
127
|
+
const obj = node as Extract<SchemaNode, { type: 'object' }>
|
|
128
|
+
if (typeof obj.additionalProperties === 'boolean') return `ab:${obj.additionalProperties}`
|
|
129
|
+
if (obj.additionalProperties) return `as:${signatureOf(obj.additionalProperties)}`
|
|
130
|
+
return ''
|
|
131
|
+
}
|
|
132
|
+
case 'patternProps': {
|
|
133
|
+
const obj = node as Extract<SchemaNode, { type: 'object' }>
|
|
134
|
+
const pattern = obj.patternProperties
|
|
135
|
+
? Object.keys(obj.patternProperties)
|
|
136
|
+
.sort()
|
|
137
|
+
.map((key) => `${key}=${signatureOf(obj.patternProperties![key]!)}`)
|
|
138
|
+
.join(',')
|
|
139
|
+
: ''
|
|
140
|
+
return `pp[${pattern}]`
|
|
141
|
+
}
|
|
142
|
+
case 'enumValues': {
|
|
143
|
+
const en = node as Extract<SchemaNode, { type: 'enum' }>
|
|
144
|
+
let values = ''
|
|
145
|
+
if (en.namedEnumValues?.length) {
|
|
146
|
+
values = en.namedEnumValues.map((entry) => `${entry.name}=${entry.primitive}:${String(entry.value)}`).join(',')
|
|
147
|
+
} else if (en.enumValues?.length) {
|
|
148
|
+
values = en.enumValues.map((value) => `${value === null ? 'null' : typeof value}:${String(value)}`).join(',')
|
|
149
|
+
}
|
|
150
|
+
return `v[${values}]`
|
|
151
|
+
}
|
|
152
|
+
case 'refTarget': {
|
|
153
|
+
return `->${refTargetName(node as Extract<SchemaNode, { type: 'ref' }>)}`
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Builds the local, shape-only descriptor for a node: its kind, flags, constraints, and its
|
|
160
|
+
* children's signatures. {@link signatureOf} hashes this string. Children contribute their
|
|
161
|
+
* fixed-length signature rather than their own full descriptor, which keeps the result bounded.
|
|
162
|
+
*/
|
|
163
|
+
function describeShape(node: SchemaNode): string {
|
|
164
|
+
const flags = flagsDescriptor(node)
|
|
165
|
+
const fields = SHAPE_KEYS[node.type]
|
|
166
|
+
if (!fields) return `${node.type}|${flags}`
|
|
167
|
+
|
|
168
|
+
const record = node as unknown as Record<string, unknown>
|
|
169
|
+
const parts: Array<string> = [`${node.type}|${flags}`]
|
|
170
|
+
for (const field of fields) {
|
|
171
|
+
parts.push(serializeShapeField(field, node, record))
|
|
172
|
+
}
|
|
173
|
+
return parts.join('|')
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Persistent hash-consing cache: `SchemaNode` → signature digest, keyed by node identity.
|
|
178
|
+
*
|
|
179
|
+
* A `WeakMap` so entries are released once the node is garbage-collected, and so a node hashed
|
|
180
|
+
* during dedupe planning is not re-hashed when the same tree is rewritten during streaming
|
|
181
|
+
* (where `schemaSignature` and `applyDedupe` would otherwise each walk it from scratch). Reuse
|
|
182
|
+
* across calls is sound because a signature depends only on a node's content, and schema nodes
|
|
183
|
+
* are immutable once created, transforms allocate new objects rather than mutating in place.
|
|
184
|
+
*/
|
|
185
|
+
const signatureCache = new WeakMap<SchemaNode, string>()
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Hash-consing: each node's signature is a fixed-length digest of its local shape plus its
|
|
189
|
+
* children's digests (a Merkle hash). Children contribute their 64-char hash instead of their
|
|
190
|
+
* full nested descriptor, so a signature stays bounded regardless of subtree depth, and the
|
|
191
|
+
* digest is identical across calls because it depends only on content, never on traversal
|
|
192
|
+
* order. This keeps the keys built during planning consistent with the ones recomputed later
|
|
193
|
+
* during streaming. {@link signatureCache} memoizes node → digest across every computation.
|
|
194
|
+
*/
|
|
195
|
+
export function signatureOf(node: SchemaNode): string {
|
|
196
|
+
const cached = signatureCache.get(node)
|
|
197
|
+
if (cached !== undefined) return cached
|
|
198
|
+
const signature = createHash('sha256').update(describeShape(node)).digest('hex')
|
|
199
|
+
signatureCache.set(node, signature)
|
|
200
|
+
return signature
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* Computes a deterministic, shape-only signature (a fixed-length content hash) for a schema node.
|
|
205
|
+
*
|
|
206
|
+
* Two schemas share a signature when they are structurally identical, ignoring
|
|
207
|
+
* documentation (`name`, `title`, `description`, `example`, `default`, `deprecated`)
|
|
208
|
+
* and usage-slot flags (`optional`, `nullish`, `readOnly`, `writeOnly`). `nullable`
|
|
209
|
+
* is kept because it changes the produced type. `ref` nodes compare by target name,
|
|
210
|
+
* which also keeps the algorithm terminating on circular shapes.
|
|
211
|
+
*
|
|
212
|
+
* @example Two enums with different descriptions share a signature
|
|
213
|
+
* ```ts
|
|
214
|
+
* schemaSignature(createSchema({ type: 'enum', primitive: 'string', enumValues: ['a', 'b'], description: 'x' })) ===
|
|
215
|
+
* schemaSignature(createSchema({ type: 'enum', primitive: 'string', enumValues: ['a', 'b'] }))
|
|
216
|
+
* ```
|
|
217
|
+
*/
|
|
218
|
+
export function schemaSignature(node: SchemaNode): string {
|
|
219
|
+
return signatureOf(node)
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Returns `true` when two schema nodes are structurally identical under shape-only equality.
|
|
224
|
+
*
|
|
225
|
+
* @example
|
|
226
|
+
* ```ts
|
|
227
|
+
* isSchemaEqual(a, b) // a and b produce the same TypeScript type
|
|
228
|
+
* ```
|
|
229
|
+
*/
|
|
230
|
+
export function isSchemaEqual(a: SchemaNode, b: SchemaNode): boolean {
|
|
231
|
+
return schemaSignature(a) === schemaSignature(b)
|
|
232
|
+
}
|
package/src/transformers.ts
CHANGED
|
@@ -73,25 +73,30 @@ export function setDiscriminatorEnum({
|
|
|
73
73
|
* ])
|
|
74
74
|
* ```
|
|
75
75
|
*/
|
|
76
|
-
export function
|
|
77
|
-
|
|
76
|
+
export function* mergeAdjacentObjectsLazy(members: Iterable<SchemaNode>): Generator<SchemaNode, void, undefined> {
|
|
77
|
+
let acc: SchemaNode | undefined
|
|
78
|
+
|
|
79
|
+
for (const member of members) {
|
|
78
80
|
const objectMember = narrowSchema(member, 'object')
|
|
79
|
-
if (objectMember && !objectMember.name) {
|
|
80
|
-
const
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
...previousObject,
|
|
86
|
-
properties: [...(previousObject.properties ?? []), ...(objectMember.properties ?? [])],
|
|
81
|
+
if (objectMember && !objectMember.name && acc !== undefined) {
|
|
82
|
+
const accObject = narrowSchema(acc, 'object')
|
|
83
|
+
if (accObject && !accObject.name) {
|
|
84
|
+
acc = createSchema({
|
|
85
|
+
...accObject,
|
|
86
|
+
properties: [...(accObject.properties ?? []), ...(objectMember.properties ?? [])],
|
|
87
87
|
})
|
|
88
|
-
|
|
88
|
+
continue
|
|
89
89
|
}
|
|
90
90
|
}
|
|
91
|
+
if (acc !== undefined) yield acc
|
|
92
|
+
acc = member
|
|
93
|
+
}
|
|
91
94
|
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
+
if (acc !== undefined) yield acc
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export function mergeAdjacentObjects(members: Array<SchemaNode>): Array<SchemaNode> {
|
|
99
|
+
return [...mergeAdjacentObjectsLazy(members)]
|
|
95
100
|
}
|
|
96
101
|
|
|
97
102
|
/**
|
|
@@ -145,7 +150,7 @@ export function setEnumName(propNode: SchemaNode, parentName: string | null | un
|
|
|
145
150
|
const enumNode = narrowSchema(propNode, 'enum')
|
|
146
151
|
|
|
147
152
|
if (enumNode?.primitive === 'boolean') {
|
|
148
|
-
return { ...propNode, name:
|
|
153
|
+
return { ...propNode, name: null }
|
|
149
154
|
}
|
|
150
155
|
|
|
151
156
|
if (enumNode) {
|
package/src/types.ts
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
export type { VisitorDepth } from './constants.ts'
|
|
2
|
+
export type { BuildDedupePlanOptions, DedupeCanonical, DedupePlan } from './dedupe.ts'
|
|
3
|
+
export type { SchemaDialect } from './dialect.ts'
|
|
4
|
+
export type { DispatchRule } from './dispatch.ts'
|
|
2
5
|
export type { DistributiveOmit } from './factory.ts'
|
|
3
|
-
export type {
|
|
6
|
+
export type { InferSchemaNode, ParserOptions } from './infer.ts'
|
|
4
7
|
export type {
|
|
5
8
|
ArraySchemaNode,
|
|
6
9
|
ArrowFunctionNode,
|
|
@@ -21,11 +24,14 @@ export type {
|
|
|
21
24
|
FunctionParameterNode,
|
|
22
25
|
FunctionParametersNode,
|
|
23
26
|
FunctionParamNode,
|
|
27
|
+
GenericOperationNode,
|
|
24
28
|
HttpMethod,
|
|
29
|
+
HttpOperationNode,
|
|
25
30
|
HttpStatusCode,
|
|
26
31
|
ImportNode,
|
|
27
32
|
InputMeta,
|
|
28
33
|
InputNode,
|
|
34
|
+
InputStreamNode,
|
|
29
35
|
IntersectionSchemaNode,
|
|
30
36
|
Ipv4SchemaNode,
|
|
31
37
|
Ipv6SchemaNode,
|
|
@@ -37,6 +43,8 @@ export type {
|
|
|
37
43
|
NumberSchemaNode,
|
|
38
44
|
ObjectSchemaNode,
|
|
39
45
|
OperationNode,
|
|
46
|
+
OperationNodeBase,
|
|
47
|
+
OperationProtocol,
|
|
40
48
|
OutputNode,
|
|
41
49
|
ParameterGroupNode,
|
|
42
50
|
ParameterLocation,
|
|
@@ -62,7 +70,6 @@ export type {
|
|
|
62
70
|
UnionSchemaNode,
|
|
63
71
|
UrlSchemaNode,
|
|
64
72
|
} from './nodes/index.ts'
|
|
65
|
-
export type { RefMap } from './refs.ts'
|
|
66
73
|
export type { AsyncVisitor, CollectOptions, CollectVisitor, ParentOf, TransformOptions, Visitor, VisitorContext, WalkOptions } from './visitor.ts'
|
|
67
74
|
export type { Printer, PrinterFactoryOptions, PrinterPartial } from './printer.ts'
|
|
68
75
|
export type { ScalarPrimitive } from './constants.ts'
|