@kubb/ast 5.0.0-beta.5 → 5.0.0-beta.50

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.
Files changed (48) hide show
  1. package/LICENSE +17 -10
  2. package/README.md +28 -19
  3. package/dist/index.cjs +878 -788
  4. package/dist/index.cjs.map +1 -1
  5. package/dist/index.d.ts +33 -3326
  6. package/dist/index.js +863 -750
  7. package/dist/index.js.map +1 -1
  8. package/dist/types-BaaNZbSi.d.ts +3581 -0
  9. package/dist/types.cjs +0 -0
  10. package/dist/types.d.ts +2 -0
  11. package/dist/types.js +1 -0
  12. package/dist/utils-BIcKgbbc.js +626 -0
  13. package/dist/utils-BIcKgbbc.js.map +1 -0
  14. package/dist/utils-CMRZrT-w.cjs +794 -0
  15. package/dist/utils-CMRZrT-w.cjs.map +1 -0
  16. package/dist/utils.cjs +18 -0
  17. package/dist/utils.d.ts +205 -0
  18. package/dist/utils.js +2 -0
  19. package/package.json +13 -5
  20. package/src/constants.ts +10 -49
  21. package/src/dedupe.ts +200 -0
  22. package/src/dialect.ts +58 -0
  23. package/src/dispatch.ts +53 -0
  24. package/src/factory.ts +154 -21
  25. package/src/guards.ts +18 -48
  26. package/src/index.ts +11 -8
  27. package/src/infer.ts +16 -14
  28. package/src/nodes/base.ts +2 -0
  29. package/src/nodes/code.ts +22 -28
  30. package/src/nodes/content.ts +37 -0
  31. package/src/nodes/file.ts +17 -15
  32. package/src/nodes/function.ts +11 -11
  33. package/src/nodes/http.ts +1 -35
  34. package/src/nodes/index.ts +10 -12
  35. package/src/nodes/operation.ts +98 -62
  36. package/src/nodes/response.ts +21 -14
  37. package/src/nodes/root.ts +72 -10
  38. package/src/nodes/schema.ts +18 -15
  39. package/src/printer.ts +44 -38
  40. package/src/resolvers.ts +5 -19
  41. package/src/signature.ts +232 -0
  42. package/src/transformers.ts +21 -16
  43. package/src/types.ts +8 -18
  44. package/src/{utils.ts → utils/ast.ts} +125 -84
  45. package/src/utils/index.ts +295 -0
  46. package/src/visitor.ts +239 -281
  47. package/src/refs.ts +0 -67
  48. /package/dist/{chunk--u3MIqq1.js → chunk-C0LytTxp.js} +0 -0
@@ -0,0 +1,232 @@
1
+ import { hash } from 'node:crypto'
2
+ import type { SchemaNode } from './nodes/index.ts'
3
+ import { extractRefName } from './utils/index.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 = hash('sha256', describeShape(node), '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
+ }
@@ -2,7 +2,7 @@ import { isScalarPrimitive } from './constants.ts'
2
2
  import { createProperty, createSchema } from './factory.ts'
3
3
  import { narrowSchema } from './guards.ts'
4
4
  import type { SchemaNode } from './nodes/schema.ts'
5
- import { enumPropName } from './resolvers.ts'
5
+ import { enumPropName } from './utils/index.ts'
6
6
 
7
7
  /**
8
8
  * Replaces a discriminator property's schema with a string enum of allowed values.
@@ -73,25 +73,30 @@ export function setDiscriminatorEnum({
73
73
  * ])
74
74
  * ```
75
75
  */
76
- export function mergeAdjacentObjects(members: Array<SchemaNode>): Array<SchemaNode> {
77
- return members.reduce<Array<SchemaNode>>((acc, member) => {
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 previous = acc.at(-1)
81
- const previousObject = previous ? narrowSchema(previous, 'object') : undefined
82
-
83
- if (previousObject && !previousObject.name) {
84
- acc[acc.length - 1] = createSchema({
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
- return acc
88
+ continue
89
89
  }
90
90
  }
91
+ if (acc !== undefined) yield acc
92
+ acc = member
93
+ }
91
94
 
92
- acc.push(member)
93
- return acc
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: undefined }
153
+ return { ...propNode, name: null }
149
154
  }
150
155
 
151
156
  if (enumNode) {
package/src/types.ts CHANGED
@@ -1,37 +1,32 @@
1
- export type { VisitorDepth } from './constants.ts'
1
+ export type { DedupePlan } from './dedupe.ts'
2
+ export type { SchemaDialect } from './dialect.ts'
3
+ export type { DispatchRule } from './dispatch.ts'
2
4
  export type { DistributiveOmit } from './factory.ts'
3
- export type { InferSchema, InferSchemaNode, ParserOptions } from './infer.ts'
5
+ export type { InferSchemaNode, ParserOptions } from './infer.ts'
4
6
  export type {
5
7
  ArraySchemaNode,
6
8
  ArrowFunctionNode,
7
- BaseNode,
8
- BreakNode,
9
9
  CodeNode,
10
- ComplexSchemaType,
11
10
  ConstNode,
12
11
  DateSchemaNode,
13
12
  DatetimeSchemaNode,
14
13
  EnumSchemaNode,
15
- EnumValueNode,
16
14
  ExportNode,
17
15
  FileNode,
18
- FormatStringSchemaNode,
19
16
  FunctionNode,
20
17
  FunctionNodeType,
21
18
  FunctionParameterNode,
22
19
  FunctionParametersNode,
23
20
  FunctionParamNode,
24
21
  HttpMethod,
25
- HttpStatusCode,
22
+ HttpOperationNode,
26
23
  ImportNode,
27
24
  InputMeta,
28
25
  InputNode,
26
+ InputStreamNode,
29
27
  IntersectionSchemaNode,
30
- Ipv4SchemaNode,
31
- Ipv6SchemaNode,
32
28
  JSDocNode,
33
29
  JsxNode,
34
- MediaType,
35
30
  Node,
36
31
  NodeKind,
37
32
  NumberSchemaNode,
@@ -46,25 +41,20 @@ export type {
46
41
  PropertyNode,
47
42
  RefSchemaNode,
48
43
  ResponseNode,
49
- ScalarSchemaNode,
50
44
  ScalarSchemaType,
51
45
  SchemaNode,
52
46
  SchemaNodeByType,
53
47
  SchemaType,
54
48
  SourceNode,
55
- SpecialSchemaType,
56
49
  StatusCode,
57
50
  StringSchemaNode,
58
51
  TextNode,
59
52
  TimeSchemaNode,
60
- TypeDeclarationNode,
61
53
  TypeNode,
62
54
  UnionSchemaNode,
63
55
  UrlSchemaNode,
64
56
  } from './nodes/index.ts'
65
- export type { RefMap } from './refs.ts'
66
- export type { AsyncVisitor, CollectOptions, CollectVisitor, ParentOf, TransformOptions, Visitor, VisitorContext, WalkOptions } from './visitor.ts'
57
+ export type { ParentOf, Visitor, VisitorContext } from './visitor.ts'
67
58
  export type { Printer, PrinterFactoryOptions, PrinterPartial } from './printer.ts'
68
- export type { ScalarPrimitive } from './constants.ts'
69
- export type { OperationParamsResolver } from './utils.ts'
59
+ export type { OperationParamsResolver } from './utils/ast.ts'
70
60
  export type { UserFileNode } from './factory.ts'