@kubb/ast 5.0.0-beta.6 → 5.0.0-beta.61

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 (102) hide show
  1. package/LICENSE +17 -10
  2. package/README.md +51 -27
  3. package/dist/chunk-CNktS9qV.js +17 -0
  4. package/dist/defineMacro-BLIR6k-j.d.ts +475 -0
  5. package/dist/defineMacro-BTXvS8nI.js +106 -0
  6. package/dist/defineMacro-BTXvS8nI.js.map +1 -0
  7. package/dist/defineMacro-Bv9R_9a2.cjs +123 -0
  8. package/dist/defineMacro-Bv9R_9a2.cjs.map +1 -0
  9. package/dist/extractStringsFromNodes-Cja-xxx5.js +29 -0
  10. package/dist/extractStringsFromNodes-Cja-xxx5.js.map +1 -0
  11. package/dist/extractStringsFromNodes-DKgDjFO0.cjs +34 -0
  12. package/dist/extractStringsFromNodes-DKgDjFO0.cjs.map +1 -0
  13. package/dist/extractStringsFromNodes-p4mX1TQD.d.ts +14 -0
  14. package/dist/factory-CZNOGI-N.js +283 -0
  15. package/dist/factory-CZNOGI-N.js.map +1 -0
  16. package/dist/factory-DG1CVkEb.cjs +300 -0
  17. package/dist/factory-DG1CVkEb.cjs.map +1 -0
  18. package/dist/factory.cjs +29 -0
  19. package/dist/factory.d.ts +62 -0
  20. package/dist/factory.js +3 -0
  21. package/dist/index-BzjwdK2M.d.ts +2433 -0
  22. package/dist/index.cjs +444 -2180
  23. package/dist/index.cjs.map +1 -1
  24. package/dist/index.d.ts +94 -3408
  25. package/dist/index.js +395 -2101
  26. package/dist/index.js.map +1 -1
  27. package/dist/macros.cjs +117 -0
  28. package/dist/macros.cjs.map +1 -0
  29. package/dist/macros.d.ts +59 -0
  30. package/dist/macros.js +115 -0
  31. package/dist/macros.js.map +1 -0
  32. package/dist/operationParams-BZ07xDm0.d.ts +204 -0
  33. package/dist/response-KUdWiDWw.js +658 -0
  34. package/dist/response-KUdWiDWw.js.map +1 -0
  35. package/dist/response-hnSw2NKE.cjs +1027 -0
  36. package/dist/response-hnSw2NKE.cjs.map +1 -0
  37. package/dist/types-DyDzizSf.d.ts +364 -0
  38. package/dist/types.cjs +0 -0
  39. package/dist/types.d.ts +6 -0
  40. package/dist/types.js +1 -0
  41. package/dist/utils-BLJwyza-.cjs +912 -0
  42. package/dist/utils-BLJwyza-.cjs.map +1 -0
  43. package/dist/utils-CF_-Pn_c.js +770 -0
  44. package/dist/utils-CF_-Pn_c.js.map +1 -0
  45. package/dist/utils.cjs +36 -0
  46. package/dist/utils.d.ts +358 -0
  47. package/dist/utils.js +4 -0
  48. package/dist/visitor-DJ6ZEJvq.js +548 -0
  49. package/dist/visitor-DJ6ZEJvq.js.map +1 -0
  50. package/dist/visitor-DpKZ9Tk0.cjs +654 -0
  51. package/dist/visitor-DpKZ9Tk0.cjs.map +1 -0
  52. package/package.json +21 -6
  53. package/src/constants.ts +19 -64
  54. package/src/dedupe.ts +239 -0
  55. package/src/defineMacro.ts +132 -0
  56. package/src/dialect.ts +53 -0
  57. package/src/factory.ts +67 -678
  58. package/src/guards.ts +10 -92
  59. package/src/index.ts +13 -44
  60. package/src/infer.ts +16 -14
  61. package/src/macros/index.ts +3 -0
  62. package/src/macros/macroDiscriminatorEnum.ts +44 -0
  63. package/src/macros/macroEnumName.ts +25 -0
  64. package/src/macros/macroSimplifyUnion.ts +50 -0
  65. package/src/mocks.ts +7 -127
  66. package/src/node.ts +128 -0
  67. package/src/nodes/base.ts +5 -12
  68. package/src/nodes/code.ts +165 -74
  69. package/src/nodes/content.ts +56 -0
  70. package/src/nodes/file.ts +97 -36
  71. package/src/nodes/function.ts +216 -156
  72. package/src/nodes/http.ts +1 -35
  73. package/src/nodes/index.ts +23 -15
  74. package/src/nodes/input.ts +140 -0
  75. package/src/nodes/operation.ts +122 -68
  76. package/src/nodes/output.ts +23 -0
  77. package/src/nodes/parameter.ts +33 -3
  78. package/src/nodes/property.ts +36 -3
  79. package/src/nodes/requestBody.ts +61 -0
  80. package/src/nodes/response.ts +58 -13
  81. package/src/nodes/schema.ts +93 -17
  82. package/src/printer.ts +48 -42
  83. package/src/registry.ts +75 -0
  84. package/src/signature.ts +207 -0
  85. package/src/types.ts +8 -68
  86. package/src/utils/codegen.ts +104 -0
  87. package/src/utils/extractStringsFromNodes.ts +34 -0
  88. package/src/utils/fileMerge.ts +184 -0
  89. package/src/utils/index.ts +11 -0
  90. package/src/utils/operationParams.ts +353 -0
  91. package/src/utils/refs.ts +138 -0
  92. package/src/utils/schemaGraph.ts +169 -0
  93. package/src/utils/schemaMerge.ts +34 -0
  94. package/src/utils/schemaTraversal.ts +86 -0
  95. package/src/utils/strings.ts +139 -0
  96. package/src/visitor.ts +227 -289
  97. package/dist/chunk--u3MIqq1.js +0 -8
  98. package/src/nodes/root.ts +0 -64
  99. package/src/refs.ts +0 -67
  100. package/src/resolvers.ts +0 -45
  101. package/src/transformers.ts +0 -159
  102. package/src/utils.ts +0 -915
@@ -0,0 +1,548 @@
1
+ import "./chunk-CNktS9qV.js";
2
+ import { A as importDef, C as objectBindingPatternDef, F as breakDef, G as jsxDef, I as constDef, K as textDef, M as contentDef, O as exportDef, P as arrowFunctionDef, S as indexedAccessTypeDef, W as functionDef, X as createSchema, Y as pascalCase, Z as schemaDef, b as functionParameterDef, c as outputDef, f as requestBodyDef, i as propertyDef, j as sourceDef, k as fileDef, m as inputDef, n as responseDef, o as parameterDef, q as typeDef, u as operationDef, w as typeLiteralDef, x as functionParametersDef } from "./response-KUdWiDWw.js";
3
+ //#region src/constants.ts
4
+ const visitorDepths = {
5
+ shallow: "shallow",
6
+ deep: "deep"
7
+ };
8
+ /**
9
+ * Schema type discriminators used by all AST schema nodes.
10
+ *
11
+ * Each value is a stable discriminator across the AST (for example `schema.type === schemaTypes.object`).
12
+ * Call `isScalarPrimitive()` to check for the scalar types.
13
+ */
14
+ const schemaTypes = {
15
+ /**
16
+ * Text value.
17
+ */
18
+ string: "string",
19
+ /**
20
+ * Floating-point number (`float`, `double`).
21
+ */
22
+ number: "number",
23
+ /**
24
+ * Whole number (`int32`). Use `bigint` for `int64`.
25
+ */
26
+ integer: "integer",
27
+ /**
28
+ * 64-bit integer (`int64`). Only used when `integerType` is set to `'bigint'`.
29
+ */
30
+ bigint: "bigint",
31
+ /**
32
+ * Boolean value.
33
+ */
34
+ boolean: "boolean",
35
+ /**
36
+ * Explicit null value.
37
+ */
38
+ null: "null",
39
+ /**
40
+ * Any value (no type restriction).
41
+ */
42
+ any: "any",
43
+ /**
44
+ * Unknown value (must be narrowed before usage).
45
+ */
46
+ unknown: "unknown",
47
+ /**
48
+ * No return value (`void`).
49
+ */
50
+ void: "void",
51
+ /**
52
+ * Object with named properties.
53
+ */
54
+ object: "object",
55
+ /**
56
+ * Sequential list of items.
57
+ */
58
+ array: "array",
59
+ /**
60
+ * Fixed-length list with position-specific items.
61
+ */
62
+ tuple: "tuple",
63
+ /**
64
+ * "One of" multiple schema members.
65
+ */
66
+ union: "union",
67
+ /**
68
+ * "All of" multiple schema members.
69
+ */
70
+ intersection: "intersection",
71
+ /**
72
+ * Enum schema.
73
+ */
74
+ enum: "enum",
75
+ /**
76
+ * Reference to another schema.
77
+ */
78
+ ref: "ref",
79
+ /**
80
+ * Calendar date (for example `2026-03-24`).
81
+ */
82
+ date: "date",
83
+ /**
84
+ * Date-time value (for example `2026-03-24T09:00:00Z`).
85
+ */
86
+ datetime: "datetime",
87
+ /**
88
+ * Time-only value (for example `09:00:00`).
89
+ */
90
+ time: "time",
91
+ /**
92
+ * UUID value.
93
+ */
94
+ uuid: "uuid",
95
+ /**
96
+ * Email address value.
97
+ */
98
+ email: "email",
99
+ /**
100
+ * URL value.
101
+ */
102
+ url: "url",
103
+ /**
104
+ * IPv4 address value.
105
+ */
106
+ ipv4: "ipv4",
107
+ /**
108
+ * IPv6 address value.
109
+ */
110
+ ipv6: "ipv6",
111
+ /**
112
+ * Binary/blob value.
113
+ */
114
+ blob: "blob",
115
+ /**
116
+ * Impossible value (`never`).
117
+ */
118
+ never: "never"
119
+ };
120
+ /**
121
+ * Scalar primitive schema types used for union simplification and type narrowing.
122
+ */
123
+ const SCALAR_PRIMITIVE_TYPES = new Set([
124
+ "string",
125
+ "number",
126
+ "integer",
127
+ "bigint",
128
+ "boolean"
129
+ ]);
130
+ /**
131
+ * Returns `true` when `type` is a scalar primitive that can be assigned without wrapping
132
+ * (for example `string | number | boolean`).
133
+ */
134
+ function isScalarPrimitive(type) {
135
+ return SCALAR_PRIMITIVE_TYPES.has(type);
136
+ }
137
+ /**
138
+ * HTTP method identifiers used by operation nodes.
139
+ */
140
+ const httpMethods = {
141
+ get: "GET",
142
+ post: "POST",
143
+ put: "PUT",
144
+ patch: "PATCH",
145
+ delete: "DELETE",
146
+ head: "HEAD",
147
+ options: "OPTIONS",
148
+ trace: "TRACE"
149
+ };
150
+ /**
151
+ * One indentation level, derived from {@link INDENT_SIZE}.
152
+ */
153
+ const INDENT = Array.from({ length: 2 }, () => " ").join("");
154
+ //#endregion
155
+ //#region src/guards.ts
156
+ /**
157
+ * Narrows a `SchemaNode` to the variant that matches `type`.
158
+ *
159
+ * @example
160
+ * ```ts
161
+ * const schema = createSchema({ type: 'string' })
162
+ * const stringNode = narrowSchema(schema, 'string') // StringSchemaNode | null
163
+ * ```
164
+ */
165
+ function narrowSchema(node, type) {
166
+ return node?.type === type ? node : null;
167
+ }
168
+ /**
169
+ * Narrows an `OperationNode` to an `HttpOperationNode` so `method` and `path` are present.
170
+ *
171
+ * @example
172
+ * ```ts
173
+ * if (isHttpOperationNode(node)) {
174
+ * console.log(node.method, node.path)
175
+ * }
176
+ * ```
177
+ */
178
+ function isHttpOperationNode(node) {
179
+ return node.protocol === "http" || node.method !== void 0 && node.path !== void 0;
180
+ }
181
+ //#endregion
182
+ //#region src/utils/refs.ts
183
+ const plainStringTypes = new Set([
184
+ "string",
185
+ "uuid",
186
+ "email",
187
+ "url",
188
+ "datetime"
189
+ ]);
190
+ /**
191
+ * Returns the last path segment of a reference string.
192
+ *
193
+ * @example
194
+ * ```ts
195
+ * extractRefName('#/components/schemas/Pet') // 'Pet'
196
+ * ```
197
+ */
198
+ function extractRefName(ref) {
199
+ return ref.split("/").at(-1) ?? ref;
200
+ }
201
+ /**
202
+ * Resolves the schema name of a ref node, falling back through `ref` → `name` → nested `schema.name`.
203
+ *
204
+ * Returns `null` for non-ref nodes or when no name resolves.
205
+ *
206
+ * @example
207
+ * ```ts
208
+ * resolveRefName({ kind: 'Schema', type: 'ref', ref: '#/components/schemas/Pet' })
209
+ * // => 'Pet'
210
+ * ```
211
+ */
212
+ function resolveRefName(node) {
213
+ if (!node || node.type !== "ref") return null;
214
+ if (node.ref) return extractRefName(node.ref) ?? node.name ?? node.schema?.name ?? null;
215
+ return node.name ?? node.schema?.name ?? null;
216
+ }
217
+ /**
218
+ * Builds a PascalCase child schema name by joining a parent name and property name.
219
+ * Returns `null` when there is no parent to nest under.
220
+ *
221
+ * @example
222
+ * ```ts
223
+ * childName('Order', 'shipping_address') // 'OrderShippingAddress'
224
+ * childName(undefined, 'params') // null
225
+ * ```
226
+ */
227
+ function childName(parentName, propName) {
228
+ return parentName ? pascalCase([parentName, propName].join(" ")) : null;
229
+ }
230
+ /**
231
+ * Builds a PascalCase enum name from the parent name, property name, and a suffix, skipping any
232
+ * empty parts.
233
+ *
234
+ * @example
235
+ * ```ts
236
+ * enumPropName('Order', 'status', 'enum') // 'OrderStatusEnum'
237
+ * ```
238
+ */
239
+ function enumPropName(parentName, propName, enumSuffix) {
240
+ return pascalCase([
241
+ parentName,
242
+ propName,
243
+ enumSuffix
244
+ ].filter(Boolean).join(" "));
245
+ }
246
+ /**
247
+ * Merges a ref node with its resolved schema, giving usage-site fields precedence.
248
+ *
249
+ * Usage-site fields (`description`, `readOnly`, `nullable`, `deprecated`) on the ref node override
250
+ * the same fields in the resolved `node.schema`. Non-ref nodes are returned unchanged.
251
+ *
252
+ * @example
253
+ * ```ts
254
+ * const ref = createSchema({ type: 'ref', ref: '#/components/schemas/Pet', description: 'A cute pet' })
255
+ * const merged = syncSchemaRef(ref) // merges with resolved Pet schema
256
+ * ```
257
+ */
258
+ function syncSchemaRef(node) {
259
+ const ref = narrowSchema(node, "ref");
260
+ if (!ref) return node;
261
+ if (!ref.schema) return node;
262
+ const { kind: _kind, type: _type, name: _name, ref: _ref, schema: _schema, ...overrides } = ref;
263
+ const definedOverrides = Object.fromEntries(Object.entries(overrides).filter(([, v]) => v !== void 0));
264
+ return createSchema({
265
+ ...ref.schema,
266
+ ...definedOverrides
267
+ });
268
+ }
269
+ /**
270
+ * Type guard that returns `true` when a schema emits as a plain `string` type.
271
+ *
272
+ * Covers `string`, `uuid`, `email`, `url`, and `datetime` types. For `date` and `time`
273
+ * types, returns `true` only when `representation` is `'string'` rather than `'date'`.
274
+ */
275
+ function isStringType(node) {
276
+ if (plainStringTypes.has(node.type)) return true;
277
+ const temporal = narrowSchema(node, "date") ?? narrowSchema(node, "time");
278
+ if (temporal) return temporal.representation !== "date";
279
+ return false;
280
+ }
281
+ /**
282
+ * Derives a {@link ParamGroupType} for a query or header group from the resolver.
283
+ *
284
+ * Returns `null` when there is no resolver, no params, or the group name equals the
285
+ * individual param name (so there is no real group to emit).
286
+ */
287
+ function resolveGroupType({ node, params, group, resolver }) {
288
+ if (!resolver || !params.length) return null;
289
+ const firstParam = params[0];
290
+ const groupName = (group === "query" ? resolver.resolveQueryParamsName : resolver.resolveHeaderParamsName).call(resolver, node, firstParam);
291
+ if (groupName === resolver.resolveParamName(node, firstParam)) return null;
292
+ return {
293
+ type: groupName,
294
+ optional: params.every((p) => !p.required)
295
+ };
296
+ }
297
+ //#endregion
298
+ //#region src/registry.ts
299
+ /**
300
+ * Every node definition. Adding a node means adding its `defineNode` to one
301
+ * `nodes/*.ts` file and listing it here. The visitor tables in `visitor.ts` derive from it.
302
+ */
303
+ const nodeDefs = [
304
+ inputDef,
305
+ outputDef,
306
+ operationDef,
307
+ requestBodyDef,
308
+ contentDef,
309
+ responseDef,
310
+ schemaDef,
311
+ propertyDef,
312
+ parameterDef,
313
+ functionParameterDef,
314
+ functionParametersDef,
315
+ typeLiteralDef,
316
+ indexedAccessTypeDef,
317
+ objectBindingPatternDef,
318
+ constDef,
319
+ typeDef,
320
+ functionDef,
321
+ arrowFunctionDef,
322
+ textDef,
323
+ breakDef,
324
+ jsxDef,
325
+ importDef,
326
+ exportDef,
327
+ sourceDef,
328
+ fileDef
329
+ ];
330
+ //#endregion
331
+ //#region src/visitor.ts
332
+ /**
333
+ * Child node fields per node kind, in traversal order (Babel's `VISITOR_KEYS`).
334
+ * Derived from each definition's `children`.
335
+ */
336
+ const VISITOR_KEYS = Object.fromEntries(nodeDefs.flatMap((def) => def.children ? [[def.kind, def.children]] : []));
337
+ /**
338
+ * Maps a node kind to the matching visitor callback name. Derived from each
339
+ * definition's `visitorKey`.
340
+ */
341
+ const VISITOR_KEY_BY_KIND = Object.fromEntries(nodeDefs.flatMap((def) => def.visitorKey ? [[def.kind, def.visitorKey]] : []));
342
+ /**
343
+ * Per-kind builders rerun after children are rebuilt. Derived from each
344
+ * definition's `rebuild` flag.
345
+ */
346
+ const nodeRebuilders = Object.fromEntries(nodeDefs.flatMap((def) => def.rebuild ? [[def.kind, def.create]] : []));
347
+ /**
348
+ * Creates a small async concurrency limiter.
349
+ *
350
+ * At most `concurrency` tasks are in flight at once. Extra tasks are queued.
351
+ *
352
+ * @example
353
+ * ```ts
354
+ * const limit = createLimit(2)
355
+ * for (const task of [taskA, taskB, taskC]) {
356
+ * await limit(() => task())
357
+ * }
358
+ * // only 2 tasks run at the same time
359
+ * ```
360
+ */
361
+ function createLimit(concurrency) {
362
+ let active = 0;
363
+ const queue = [];
364
+ function next() {
365
+ if (active < concurrency && queue.length > 0) {
366
+ active++;
367
+ queue.shift()();
368
+ }
369
+ }
370
+ return function limit(fn) {
371
+ return new Promise((resolve, reject) => {
372
+ queue.push(() => {
373
+ Promise.resolve(fn()).then(resolve, reject).finally(() => {
374
+ active--;
375
+ next();
376
+ });
377
+ });
378
+ next();
379
+ });
380
+ };
381
+ }
382
+ const visitorKeysByKind = VISITOR_KEYS;
383
+ /**
384
+ * Returns `true` when `value` is an AST node (an object carrying a `kind`).
385
+ */
386
+ function isNode(value) {
387
+ return typeof value === "object" && value !== null && "kind" in value;
388
+ }
389
+ /**
390
+ * Returns the immediate traversable children of `node` based on {@link VISITOR_KEYS}.
391
+ *
392
+ * `Schema` children are only included when `recurse` is `true`. Shallow mode skips them.
393
+ *
394
+ * @example
395
+ * ```ts
396
+ * const children = getChildren(operationNode, true)
397
+ * // returns parameters, the request body, and responses
398
+ * ```
399
+ */
400
+ function* getChildren(node, recurse) {
401
+ if (node.kind === "Schema" && !recurse) return;
402
+ const keys = visitorKeysByKind[node.kind];
403
+ if (!keys) return;
404
+ const record = node;
405
+ for (const key of keys) {
406
+ const value = record[key];
407
+ if (Array.isArray(value)) {
408
+ for (const item of value) if (isNode(item)) yield item;
409
+ } else if (isNode(value)) yield value;
410
+ }
411
+ }
412
+ /**
413
+ * Runs the visitor callback that matches `node.kind` with the traversal
414
+ * context. The result is a replacement node, a collected value, or `undefined`
415
+ * when no callback is registered for the kind.
416
+ *
417
+ * Shared by `walk`, `transform`, and `collectLazy` so node-kind dispatch lives
418
+ * in one place. `TResult` is the caller's expected return: the same node type
419
+ * for `transform`, the collected value type for `collectLazy`, ignored for `walk`.
420
+ */
421
+ function applyVisitor(node, visitor, parent) {
422
+ const key = VISITOR_KEY_BY_KIND[node.kind];
423
+ if (!key) return void 0;
424
+ const fn = visitor[key];
425
+ return fn?.(node, { parent });
426
+ }
427
+ /**
428
+ * Async depth-first traversal for side effects. Visitor return values are
429
+ * ignored. Use `transform` when you want to rewrite nodes.
430
+ *
431
+ * Sibling nodes at each depth run concurrently up to `options.concurrency`
432
+ * (defaults to `WALK_CONCURRENCY`). Higher values overlap I/O-bound visitor
433
+ * work. Lower values reduce memory pressure.
434
+ *
435
+ * @example Log every operation
436
+ * ```ts
437
+ * await walk(root, {
438
+ * operation(node) {
439
+ * console.log(node.operationId)
440
+ * },
441
+ * })
442
+ * ```
443
+ *
444
+ * @example Only visit the root node
445
+ * ```ts
446
+ * await walk(root, { depth: 'shallow', input: () => {} })
447
+ * ```
448
+ */
449
+ async function walk(node, options) {
450
+ return _walk(node, options, (options.depth ?? visitorDepths.deep) === visitorDepths.deep, createLimit(options.concurrency ?? 30), void 0);
451
+ }
452
+ async function _walk(node, visitor, recurse, limit, parent) {
453
+ await limit(() => applyVisitor(node, visitor, parent));
454
+ const children = Array.from(getChildren(node, recurse));
455
+ if (children.length === 0) return;
456
+ await Promise.all(children.map((child) => _walk(child, visitor, recurse, limit, node)));
457
+ }
458
+ function transform(node, options) {
459
+ const { depth, parent, ...visitor } = options;
460
+ const recurse = (depth ?? visitorDepths.deep) === visitorDepths.deep;
461
+ const rebuilt = transformChildren(applyVisitor(node, visitor, parent) ?? node, options, recurse);
462
+ if (rebuilt === node) return node;
463
+ const rebuild = nodeRebuilders[rebuilt.kind];
464
+ return rebuild ? rebuild(rebuilt) : rebuilt;
465
+ }
466
+ /**
467
+ * Immutably rebuilds a node's children using {@link VISITOR_KEYS}, transforming
468
+ * each child node and leaving non-node values (e.g. `additionalProperties: true`) intact.
469
+ * `Schema` children are skipped in shallow mode.
470
+ */
471
+ function transformChildren(node, options, recurse) {
472
+ if (node.kind === "Schema" && !recurse) return node;
473
+ const keys = visitorKeysByKind[node.kind];
474
+ if (!keys) return node;
475
+ const record = node;
476
+ const childOptions = {
477
+ ...options,
478
+ parent: node
479
+ };
480
+ let updates;
481
+ for (const key of keys) {
482
+ if (!(key in record)) continue;
483
+ const value = record[key];
484
+ if (Array.isArray(value)) {
485
+ let changed = false;
486
+ const mapped = value.map((item) => {
487
+ if (!isNode(item)) return item;
488
+ const next = transform(item, childOptions);
489
+ if (next !== item) changed = true;
490
+ return next;
491
+ });
492
+ if (changed) (updates ??= {})[key] = mapped;
493
+ } else if (isNode(value)) {
494
+ const next = transform(value, childOptions);
495
+ if (next !== value) (updates ??= {})[key] = next;
496
+ }
497
+ }
498
+ return updates ? {
499
+ ...node,
500
+ ...updates
501
+ } : node;
502
+ }
503
+ /**
504
+ * Lazy depth-first collection pass. Yields every non-null value returned by
505
+ * the visitor callbacks. Use `collect` for the eager array form.
506
+ *
507
+ * @example Collect every operationId
508
+ * ```ts
509
+ * const ids: string[] = []
510
+ * for (const id of collectLazy<string>(root, {
511
+ * operation(node) {
512
+ * return node.operationId
513
+ * },
514
+ * })) {
515
+ * ids.push(id)
516
+ * }
517
+ * ```
518
+ */
519
+ function* collectLazy(node, options) {
520
+ const { depth, parent, ...visitor } = options;
521
+ const recurse = (depth ?? visitorDepths.deep) === visitorDepths.deep;
522
+ const v = applyVisitor(node, visitor, parent);
523
+ if (v != null) yield v;
524
+ for (const child of getChildren(node, recurse)) yield* collectLazy(child, {
525
+ ...options,
526
+ parent: node
527
+ });
528
+ }
529
+ /**
530
+ * Eager depth-first collection pass. Gathers every non-null value the visitor
531
+ * callbacks return into an array.
532
+ *
533
+ * @example Collect every operationId
534
+ * ```ts
535
+ * const ids = collect<string>(root, {
536
+ * operation(node) {
537
+ * return node.operationId
538
+ * },
539
+ * })
540
+ * ```
541
+ */
542
+ function collect(node, options) {
543
+ return Array.from(collectLazy(node, options));
544
+ }
545
+ //#endregion
546
+ export { isScalarPrimitive as _, nodeDefs as a, extractRefName as c, resolveRefName as d, syncSchemaRef as f, httpMethods as g, INDENT as h, walk as i, isStringType as l, narrowSchema as m, collectLazy as n, childName as o, isHttpOperationNode as p, transform as r, enumPropName as s, collect as t, resolveGroupType as u, schemaTypes as v };
547
+
548
+ //# sourceMappingURL=visitor-DJ6ZEJvq.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"visitor-DJ6ZEJvq.js","names":[],"sources":["../src/constants.ts","../src/guards.ts","../src/utils/refs.ts","../src/registry.ts","../src/visitor.ts"],"sourcesContent":["import type { HttpMethod } from './nodes/operation.ts'\nimport type { SchemaType } from './nodes/schema.ts'\n\n/**\n * Traversal depth for AST visitor utilities.\n *\n * - `'shallow'` visits only the immediate node, skipping children.\n * - `'deep'` recursively visits all descendant nodes.\n */\nexport type VisitorDepth = 'shallow' | 'deep'\n\nexport const visitorDepths = {\n shallow: 'shallow',\n deep: 'deep',\n} as const satisfies Record<VisitorDepth, VisitorDepth>\n\n/**\n * Schema type discriminators used by all AST schema nodes.\n *\n * Each value is a stable discriminator across the AST (for example `schema.type === schemaTypes.object`).\n * Call `isScalarPrimitive()` to check for the scalar types.\n */\nexport const schemaTypes = {\n /**\n * Text value.\n */\n string: 'string',\n /**\n * Floating-point number (`float`, `double`).\n */\n number: 'number',\n /**\n * Whole number (`int32`). Use `bigint` for `int64`.\n */\n integer: 'integer',\n /**\n * 64-bit integer (`int64`). Only used when `integerType` is set to `'bigint'`.\n */\n bigint: 'bigint',\n /**\n * Boolean value.\n */\n boolean: 'boolean',\n /**\n * Explicit null value.\n */\n null: 'null',\n /**\n * Any value (no type restriction).\n */\n any: 'any',\n /**\n * Unknown value (must be narrowed before usage).\n */\n unknown: 'unknown',\n /**\n * No return value (`void`).\n */\n void: 'void',\n /**\n * Object with named properties.\n */\n object: 'object',\n /**\n * Sequential list of items.\n */\n array: 'array',\n /**\n * Fixed-length list with position-specific items.\n */\n tuple: 'tuple',\n /**\n * \"One of\" multiple schema members.\n */\n union: 'union',\n /**\n * \"All of\" multiple schema members.\n */\n intersection: 'intersection',\n /**\n * Enum schema.\n */\n enum: 'enum',\n /**\n * Reference to another schema.\n */\n ref: 'ref',\n /**\n * Calendar date (for example `2026-03-24`).\n */\n date: 'date',\n /**\n * Date-time value (for example `2026-03-24T09:00:00Z`).\n */\n datetime: 'datetime',\n /**\n * Time-only value (for example `09:00:00`).\n */\n time: 'time',\n /**\n * UUID value.\n */\n uuid: 'uuid',\n /**\n * Email address value.\n */\n email: 'email',\n /**\n * URL value.\n */\n url: 'url',\n /**\n * IPv4 address value.\n */\n ipv4: 'ipv4',\n /**\n * IPv6 address value.\n */\n ipv6: 'ipv6',\n /**\n * Binary/blob value.\n */\n blob: 'blob',\n /**\n * Impossible value (`never`).\n */\n never: 'never',\n} as const satisfies Record<SchemaType, SchemaType>\n\nexport type ScalarPrimitive = 'string' | 'number' | 'integer' | 'bigint' | 'boolean'\n\n/**\n * Scalar primitive schema types used for union simplification and type narrowing.\n */\nconst SCALAR_PRIMITIVE_TYPES = new Set<ScalarPrimitive>(['string', 'number', 'integer', 'bigint', 'boolean'])\n\n/**\n * Returns `true` when `type` is a scalar primitive that can be assigned without wrapping\n * (for example `string | number | boolean`).\n */\nexport function isScalarPrimitive(type: string): type is ScalarPrimitive {\n return SCALAR_PRIMITIVE_TYPES.has(type as ScalarPrimitive)\n}\n\n/**\n * HTTP method identifiers used by operation nodes.\n */\nexport const httpMethods = {\n get: 'GET',\n post: 'POST',\n put: 'PUT',\n patch: 'PATCH',\n delete: 'DELETE',\n head: 'HEAD',\n options: 'OPTIONS',\n trace: 'TRACE',\n} as const satisfies Record<Lowercase<HttpMethod>, HttpMethod>\n\n/**\n * Default concurrency limit for the `walk()` traversal utility.\n *\n * Set to 30 to balance I/O-bound resolver parallelism against event-loop and memory pressure\n * during large spec traversals. Override it for different hardware constraints.\n *\n * @example\n * ```ts\n * import { walk, WALK_CONCURRENCY } from '@kubb/ast'\n *\n * walk(root, { concurrency: WALK_CONCURRENCY, root: () => {} })\n * ```\n */\nexport const WALK_CONCURRENCY = 30\n\n/**\n * Number of spaces in one indentation level when assembling multi-line code as strings.\n * Set to 2, 3, … to change the indent width used by `buildObject`/`buildList`.\n */\nconst INDENT_SIZE = 2\n\n/**\n * One indentation level, derived from {@link INDENT_SIZE}.\n */\nexport const INDENT = Array.from({ length: INDENT_SIZE }, () => ' ').join('')\n","import type { HttpOperationNode, OperationNode, SchemaNode, SchemaNodeByType } from './nodes/index.ts'\n\n/**\n * Narrows a `SchemaNode` to the variant that matches `type`.\n *\n * @example\n * ```ts\n * const schema = createSchema({ type: 'string' })\n * const stringNode = narrowSchema(schema, 'string') // StringSchemaNode | null\n * ```\n */\nexport function narrowSchema<T extends SchemaNode['type']>(node: SchemaNode | undefined, type: T): SchemaNodeByType[T] | null {\n return node?.type === type ? (node as SchemaNodeByType[T]) : null\n}\n\n/**\n * Narrows an `OperationNode` to an `HttpOperationNode` so `method` and `path` are present.\n *\n * @example\n * ```ts\n * if (isHttpOperationNode(node)) {\n * console.log(node.method, node.path)\n * }\n * ```\n */\nexport function isHttpOperationNode(node: OperationNode): node is HttpOperationNode {\n return node.protocol === 'http' || (node.method !== undefined && node.path !== undefined)\n}\n","import { pascalCase } from '@internals/utils'\nimport { narrowSchema } from '../guards.ts'\nimport type { OperationNode, ParameterNode, SchemaNode } from '../nodes/index.ts'\nimport { createSchema, type SchemaType } from '../nodes/schema.ts'\nimport type { OperationParamsResolver, ParamGroupType } from './operationParams.ts'\n\nconst plainStringTypes = new Set<SchemaType>(['string', 'uuid', 'email', 'url', 'datetime'] as const)\n\n/**\n * Returns the last path segment of a reference string.\n *\n * @example\n * ```ts\n * extractRefName('#/components/schemas/Pet') // 'Pet'\n * ```\n */\nexport function extractRefName(ref: string): string {\n return ref.split('/').at(-1) ?? ref\n}\n\n/**\n * Resolves the schema name of a ref node, falling back through `ref` → `name` → nested `schema.name`.\n *\n * Returns `null` for non-ref nodes or when no name resolves.\n *\n * @example\n * ```ts\n * resolveRefName({ kind: 'Schema', type: 'ref', ref: '#/components/schemas/Pet' })\n * // => 'Pet'\n * ```\n */\nexport function resolveRefName(node: SchemaNode | undefined): string | null {\n if (!node || node.type !== 'ref') return null\n if (node.ref) return extractRefName(node.ref) ?? node.name ?? node.schema?.name ?? null\n\n return node.name ?? node.schema?.name ?? null\n}\n\n/**\n * Builds a PascalCase child schema name by joining a parent name and property name.\n * Returns `null` when there is no parent to nest under.\n *\n * @example\n * ```ts\n * childName('Order', 'shipping_address') // 'OrderShippingAddress'\n * childName(undefined, 'params') // null\n * ```\n */\nexport function childName(parentName: string | null | undefined, propName: string): string | null {\n return parentName ? pascalCase([parentName, propName].join(' ')) : null\n}\n\n/**\n * Builds a PascalCase enum name from the parent name, property name, and a suffix, skipping any\n * empty parts.\n *\n * @example\n * ```ts\n * enumPropName('Order', 'status', 'enum') // 'OrderStatusEnum'\n * ```\n */\nexport function enumPropName(parentName: string | null | undefined, propName: string, enumSuffix: string): string {\n return pascalCase([parentName, propName, enumSuffix].filter(Boolean).join(' '))\n}\n\n/**\n * Merges a ref node with its resolved schema, giving usage-site fields precedence.\n *\n * Usage-site fields (`description`, `readOnly`, `nullable`, `deprecated`) on the ref node override\n * the same fields in the resolved `node.schema`. Non-ref nodes are returned unchanged.\n *\n * @example\n * ```ts\n * const ref = createSchema({ type: 'ref', ref: '#/components/schemas/Pet', description: 'A cute pet' })\n * const merged = syncSchemaRef(ref) // merges with resolved Pet schema\n * ```\n */\nexport function syncSchemaRef(node: SchemaNode): SchemaNode {\n const ref = narrowSchema(node, 'ref')\n\n if (!ref) return node\n if (!ref.schema) return node\n\n const { kind: _kind, type: _type, name: _name, ref: _ref, schema: _schema, ...overrides } = ref\n\n // Filter out undefined override values so they don't shadow the resolved schema's fields.\n const definedOverrides = Object.fromEntries(Object.entries(overrides).filter(([, v]) => v !== undefined))\n\n return createSchema({ ...ref.schema, ...definedOverrides })\n}\n\n/**\n * Type guard that returns `true` when a schema emits as a plain `string` type.\n *\n * Covers `string`, `uuid`, `email`, `url`, and `datetime` types. For `date` and `time`\n * types, returns `true` only when `representation` is `'string'` rather than `'date'`.\n */\nexport function isStringType(node: SchemaNode): boolean {\n if (plainStringTypes.has(node.type)) {\n return true\n }\n\n const temporal = narrowSchema(node, 'date') ?? narrowSchema(node, 'time')\n if (temporal) {\n return temporal.representation !== 'date'\n }\n\n return false\n}\n\n/**\n * Derives a {@link ParamGroupType} for a query or header group from the resolver.\n *\n * Returns `null` when there is no resolver, no params, or the group name equals the\n * individual param name (so there is no real group to emit).\n */\nexport function resolveGroupType({\n node,\n params,\n group,\n resolver,\n}: {\n node: OperationNode\n params: Array<ParameterNode>\n group: 'query' | 'header'\n resolver: OperationParamsResolver | undefined\n}): ParamGroupType | null {\n if (!resolver || !params.length) {\n return null\n }\n const firstParam = params[0]!\n const groupMethod = group === 'query' ? resolver.resolveQueryParamsName : resolver.resolveHeaderParamsName\n const groupName = groupMethod.call(resolver, node, firstParam)\n if (groupName === resolver.resolveParamName(node, firstParam)) {\n return null\n }\n return { type: groupName, optional: params.every((p) => !p.required) }\n}\n","import type { NodeDef } from './node.ts'\nimport { arrowFunctionDef, breakDef, constDef, functionDef, jsxDef, textDef, typeDef } from './nodes/code.ts'\nimport { contentDef } from './nodes/content.ts'\nimport { exportDef, fileDef, importDef, sourceDef } from './nodes/file.ts'\nimport { functionParameterDef, functionParametersDef, indexedAccessTypeDef, objectBindingPatternDef, typeLiteralDef } from './nodes/function.ts'\nimport { inputDef } from './nodes/input.ts'\nimport { operationDef } from './nodes/operation.ts'\nimport { outputDef } from './nodes/output.ts'\nimport { parameterDef } from './nodes/parameter.ts'\nimport { propertyDef } from './nodes/property.ts'\nimport { requestBodyDef } from './nodes/requestBody.ts'\nimport { responseDef } from './nodes/response.ts'\nimport { schemaDef } from './nodes/schema.ts'\n\n// Surface every def from one place so the package barrel re-exports them with `export * from './registry.ts'`.\n// Adding a node means adding its `defineNode` to a `nodes/*.ts` file and listing it in `nodeDefs` below, nothing else.\nexport {\n arrowFunctionDef,\n breakDef,\n constDef,\n contentDef,\n exportDef,\n fileDef,\n functionDef,\n functionParameterDef,\n functionParametersDef,\n importDef,\n indexedAccessTypeDef,\n inputDef,\n jsxDef,\n objectBindingPatternDef,\n operationDef,\n outputDef,\n parameterDef,\n propertyDef,\n requestBodyDef,\n responseDef,\n schemaDef,\n sourceDef,\n textDef,\n typeDef,\n typeLiteralDef,\n}\n\n/**\n * Every node definition. Adding a node means adding its `defineNode` to one\n * `nodes/*.ts` file and listing it here. The visitor tables in `visitor.ts` derive from it.\n */\nexport const nodeDefs = [\n inputDef,\n outputDef,\n operationDef,\n requestBodyDef,\n contentDef,\n responseDef,\n schemaDef,\n propertyDef,\n parameterDef,\n functionParameterDef,\n functionParametersDef,\n typeLiteralDef,\n indexedAccessTypeDef,\n objectBindingPatternDef,\n constDef,\n typeDef,\n functionDef,\n arrowFunctionDef,\n textDef,\n breakDef,\n jsxDef,\n importDef,\n exportDef,\n sourceDef,\n fileDef,\n] satisfies ReadonlyArray<NodeDef>\n","import type { VisitorDepth } from './constants.ts'\nimport { visitorDepths, WALK_CONCURRENCY } from './constants.ts'\nimport type { NodeDef } from './node.ts'\nimport type {\n ContentNode,\n InputNode,\n Node,\n NodeKind,\n OperationNode,\n OutputNode,\n ParameterNode,\n PropertyNode,\n RequestBodyNode,\n ResponseNode,\n SchemaNode,\n} from './nodes/index.ts'\nimport { nodeDefs } from './registry.ts'\n\n/**\n * Child node fields per node kind, in traversal order (Babel's `VISITOR_KEYS`).\n * Derived from each definition's `children`.\n */\nconst VISITOR_KEYS = Object.fromEntries(nodeDefs.flatMap((def) => (def.children ? [[def.kind, def.children] as const] : []))) as Partial<\n Record<NodeKind, ReadonlyArray<string>>\n>\n\n/**\n * Maps a node kind to the matching visitor callback name. Derived from each\n * definition's `visitorKey`.\n */\nconst VISITOR_KEY_BY_KIND = Object.fromEntries(nodeDefs.flatMap((def) => (def.visitorKey ? [[def.kind, def.visitorKey] as const] : []))) as Partial<\n Record<NodeKind, NonNullable<NodeDef['visitorKey']>>\n>\n\n/**\n * Per-kind builders rerun after children are rebuilt. Derived from each\n * definition's `rebuild` flag.\n */\nconst nodeRebuilders = Object.fromEntries(\n nodeDefs.flatMap((def) => (def.rebuild ? [[def.kind, def.create as unknown as (node: Node) => Node] as const] : [])),\n) as Partial<Record<NodeKind, (node: Node) => Node>>\n\n/**\n * Creates a small async concurrency limiter.\n *\n * At most `concurrency` tasks are in flight at once. Extra tasks are queued.\n *\n * @example\n * ```ts\n * const limit = createLimit(2)\n * for (const task of [taskA, taskB, taskC]) {\n * await limit(() => task())\n * }\n * // only 2 tasks run at the same time\n * ```\n */\nfunction createLimit(concurrency: number) {\n let active = 0\n const queue: Array<() => void> = []\n\n function next() {\n if (active < concurrency && queue.length > 0) {\n active++\n queue.shift()!()\n }\n }\n\n return function limit<T>(fn: () => Promise<T> | T): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n queue.push(() => {\n Promise.resolve(fn())\n .then(resolve, reject)\n .finally(() => {\n active--\n next()\n })\n })\n next()\n })\n }\n}\n\ntype LimitFn = ReturnType<typeof createLimit>\n\n/**\n * Ordered mapping of `[NodeType, ParentType]` pairs.\n *\n * `ParentOf` uses this map to find parent types.\n */\ntype ParentNodeMap = [\n [InputNode, undefined],\n [OutputNode, undefined],\n [OperationNode, InputNode],\n [RequestBodyNode, OperationNode],\n [ContentNode, RequestBodyNode | ResponseNode],\n [SchemaNode, InputNode | ContentNode | SchemaNode | PropertyNode | ParameterNode],\n [PropertyNode, SchemaNode],\n [ParameterNode, OperationNode],\n [ResponseNode, OperationNode],\n]\n\n/**\n * Resolves the parent node type for a given AST node type.\n *\n * Visitor context relies on this so `ctx.parent` is typed for each callback.\n *\n * @example\n * ```ts\n * type InputParent = ParentOf<InputNode>\n * // undefined\n * ```\n *\n * @example\n * ```ts\n * type PropertyParent = ParentOf<PropertyNode>\n * // SchemaNode\n * ```\n *\n * @example\n * ```ts\n * type SchemaParent = ParentOf<SchemaNode>\n * // InputNode | OperationNode | SchemaNode | PropertyNode | ParameterNode | ResponseNode\n * ```\n */\nexport type ParentOf<T extends Node, TEntries extends ReadonlyArray<[Node, unknown]> = ParentNodeMap> = TEntries extends [\n infer TEntry extends [Node, unknown],\n ...infer TRest extends ReadonlyArray<[Node, unknown]>,\n]\n ? T extends TEntry[0]\n ? TEntry[1]\n : ParentOf<T, TRest>\n : Node\n\n/**\n * Traversal context passed as the second argument to every visitor callback.\n * `parent` is typed from the current node type.\n *\n * @example\n * ```ts\n * const visitor: Visitor = {\n * schema(node, { parent }) {\n * // parent type is narrowed by node kind\n * },\n * }\n * ```\n */\nexport type VisitorContext<T extends Node = Node> = {\n /**\n * Parent node of the currently visited node.\n * For `InputNode`, this is `undefined`.\n */\n parent?: ParentOf<T>\n}\n\n/**\n * Synchronous visitor consumed by `transform`. Each optional callback runs\n * for the matching node type. Return a new node to replace it, or `undefined`\n * to leave it untouched.\n *\n * Plugins typically expose `transformer` so users can supply a `Visitor` that\n * rewrites the AST before printing.\n *\n * @example Prefix every operationId\n * ```ts\n * const visitor: Visitor = {\n * operation(node) {\n * return { ...node, operationId: `api_${node.operationId}` }\n * },\n * }\n * ```\n *\n * @example Strip schema descriptions\n * ```ts\n * const visitor: Visitor = {\n * schema(node) {\n * return { ...node, description: undefined }\n * },\n * }\n * ```\n */\nexport type Visitor = {\n input?(node: InputNode, context: VisitorContext<InputNode>): undefined | null | InputNode\n output?(node: OutputNode, context: VisitorContext<OutputNode>): undefined | null | OutputNode\n operation?(node: OperationNode, context: VisitorContext<OperationNode>): undefined | null | OperationNode\n schema?(node: SchemaNode, context: VisitorContext<SchemaNode>): undefined | null | SchemaNode\n property?(node: PropertyNode, context: VisitorContext<PropertyNode>): undefined | null | PropertyNode\n parameter?(node: ParameterNode, context: VisitorContext<ParameterNode>): undefined | null | ParameterNode\n response?(node: ResponseNode, context: VisitorContext<ResponseNode>): undefined | null | ResponseNode\n}\n\n/**\n * A visitor callback result that may be sync or async.\n */\ntype MaybePromise<T> = T | Promise<T>\n\n/**\n * Async visitor for `walk`. Synchronous `Visitor` objects are compatible.\n *\n * @example\n * ```ts\n * const visitor: AsyncVisitor = {\n * async operation(node) {\n * await Promise.resolve(node.operationId)\n * },\n * }\n * ```\n */\ntype AsyncVisitor = {\n input?(node: InputNode, context: VisitorContext<InputNode>): MaybePromise<undefined | null | InputNode>\n output?(node: OutputNode, context: VisitorContext<OutputNode>): MaybePromise<undefined | null | OutputNode>\n operation?(node: OperationNode, context: VisitorContext<OperationNode>): MaybePromise<undefined | null | OperationNode>\n schema?(node: SchemaNode, context: VisitorContext<SchemaNode>): MaybePromise<undefined | null | SchemaNode>\n property?(node: PropertyNode, context: VisitorContext<PropertyNode>): MaybePromise<undefined | null | PropertyNode>\n parameter?(node: ParameterNode, context: VisitorContext<ParameterNode>): MaybePromise<undefined | null | ParameterNode>\n response?(node: ResponseNode, context: VisitorContext<ResponseNode>): MaybePromise<undefined | null | ResponseNode>\n}\n\n/**\n * Visitor used by `collect`.\n *\n * @example\n * ```ts\n * const visitor: CollectVisitor<string> = {\n * operation(node) {\n * return node.operationId\n * },\n * }\n * ```\n */\ntype CollectVisitor<T> = {\n input?(node: InputNode, context: VisitorContext<InputNode>): T | null | undefined\n output?(node: OutputNode, context: VisitorContext<OutputNode>): T | null | undefined\n operation?(node: OperationNode, context: VisitorContext<OperationNode>): T | null | undefined\n schema?(node: SchemaNode, context: VisitorContext<SchemaNode>): T | null | undefined\n property?(node: PropertyNode, context: VisitorContext<PropertyNode>): T | null | undefined\n parameter?(node: ParameterNode, context: VisitorContext<ParameterNode>): T | null | undefined\n response?(node: ResponseNode, context: VisitorContext<ResponseNode>): T | null | undefined\n}\n\n/**\n * Options for `transform`.\n *\n * @example\n * ```ts\n * const options: TransformOptions = { depth: 'deep', schema: (node) => node }\n * ```\n *\n * @example\n * ```ts\n * // Only transform the current node, not nested children\n * const options: TransformOptions = { depth: 'shallow', schema: (node) => node }\n * ```\n */\nexport type TransformOptions = Visitor & {\n /**\n * Traversal depth.\n * @default 'deep'\n */\n depth?: VisitorDepth\n /**\n * Internal parent override used during recursion.\n */\n parent?: Node\n}\n\n/**\n * Options for `walk`.\n *\n * @example\n * ```ts\n * const options: WalkOptions = { depth: 'deep', concurrency: 10, root: () => {} }\n * ```\n */\nexport type WalkOptions = AsyncVisitor & {\n /**\n * Traversal depth.\n * @default 'deep'\n */\n depth?: VisitorDepth\n /**\n * Maximum number of sibling nodes visited concurrently.\n * @default 30\n */\n concurrency?: number\n}\n\n/**\n * Options for `collect`.\n *\n * @example\n * ```ts\n * const options: CollectOptions<string> = { depth: 'shallow', schema: () => undefined }\n * ```\n */\nexport type CollectOptions<T> = CollectVisitor<T> & {\n /**\n * Traversal depth.\n * @default 'deep'\n */\n depth?: VisitorDepth\n /**\n * Internal parent override used during recursion.\n */\n parent?: Node\n}\n\nconst visitorKeysByKind = VISITOR_KEYS as Record<string, ReadonlyArray<string> | undefined>\n\n/**\n * Returns `true` when `value` is an AST node (an object carrying a `kind`).\n */\nfunction isNode(value: unknown): value is Node {\n return typeof value === 'object' && value !== null && 'kind' in value\n}\n\n/**\n * Returns the immediate traversable children of `node` based on {@link VISITOR_KEYS}.\n *\n * `Schema` children are only included when `recurse` is `true`. Shallow mode skips them.\n *\n * @example\n * ```ts\n * const children = getChildren(operationNode, true)\n * // returns parameters, the request body, and responses\n * ```\n */\nfunction* getChildren(node: Node, recurse: boolean): Generator<Node, void, undefined> {\n if (node.kind === 'Schema' && !recurse) return\n\n const keys = visitorKeysByKind[node.kind]\n if (!keys) return\n\n const record = node as unknown as Record<string, unknown>\n for (const key of keys) {\n const value = record[key]\n if (Array.isArray(value)) {\n for (const item of value) if (isNode(item)) yield item\n } else if (isNode(value)) {\n yield value\n }\n }\n}\n\n/**\n * Runs the visitor callback that matches `node.kind` with the traversal\n * context. The result is a replacement node, a collected value, or `undefined`\n * when no callback is registered for the kind.\n *\n * Shared by `walk`, `transform`, and `collectLazy` so node-kind dispatch lives\n * in one place. `TResult` is the caller's expected return: the same node type\n * for `transform`, the collected value type for `collectLazy`, ignored for `walk`.\n */\nfunction applyVisitor<TResult>(node: Node, visitor: Visitor | AsyncVisitor | CollectVisitor<unknown>, parent: Node | undefined): TResult | null | undefined {\n const key = VISITOR_KEY_BY_KIND[node.kind]\n if (!key) return undefined\n\n const fn = visitor[key] as ((node: Node, context: VisitorContext) => TResult | null | undefined) | undefined\n\n return fn?.(node, { parent })\n}\n\n/**\n * Async depth-first traversal for side effects. Visitor return values are\n * ignored. Use `transform` when you want to rewrite nodes.\n *\n * Sibling nodes at each depth run concurrently up to `options.concurrency`\n * (defaults to `WALK_CONCURRENCY`). Higher values overlap I/O-bound visitor\n * work. Lower values reduce memory pressure.\n *\n * @example Log every operation\n * ```ts\n * await walk(root, {\n * operation(node) {\n * console.log(node.operationId)\n * },\n * })\n * ```\n *\n * @example Only visit the root node\n * ```ts\n * await walk(root, { depth: 'shallow', input: () => {} })\n * ```\n */\nexport async function walk(node: Node, options: WalkOptions): Promise<void> {\n const recurse = (options.depth ?? visitorDepths.deep) === visitorDepths.deep\n const limit = createLimit(options.concurrency ?? WALK_CONCURRENCY)\n\n return _walk(node, options, recurse, limit, undefined)\n}\n\nasync function _walk(node: Node, visitor: AsyncVisitor, recurse: boolean, limit: LimitFn, parent: Node | undefined): Promise<void> {\n await limit(() => applyVisitor(node, visitor, parent))\n\n // Visit siblings concurrently and let the shared `limit` cap how many callbacks\n // run at once. Awaiting each child sequentially here would serialize the whole\n // traversal and make `concurrency` inert. Every visitor callback would run one\n // at a time regardless of the limit.\n const children = Array.from(getChildren(node, recurse))\n if (children.length === 0) return\n\n await Promise.all(children.map((child) => _walk(child, visitor, recurse, limit, node)))\n}\n\n/**\n * Synchronous depth-first transform. Each visitor callback can return a\n * replacement node. Returning `undefined` keeps the original.\n *\n * The original tree is never mutated, a new tree is returned. Pass\n * `depth: 'shallow'` to skip recursion into children.\n *\n * @example Prefix every operationId\n * ```ts\n * const next = transform(root, {\n * operation(node) {\n * return { ...node, operationId: `prefixed_${node.operationId}` }\n * },\n * })\n * ```\n *\n * @example Replace only the root node\n * ```ts\n * const next = transform(root, {\n * depth: 'shallow',\n * input: (node) => ({ ...node, meta: { ...node.meta, title: 'Rewritten' } }),\n * })\n * ```\n */\nexport function transform(node: InputNode, options: TransformOptions): InputNode\nexport function transform(node: OutputNode, options: TransformOptions): OutputNode\nexport function transform(node: OperationNode, options: TransformOptions): OperationNode\nexport function transform(node: SchemaNode, options: TransformOptions): SchemaNode\nexport function transform(node: PropertyNode, options: TransformOptions): PropertyNode\nexport function transform(node: ParameterNode, options: TransformOptions): ParameterNode\nexport function transform(node: ResponseNode, options: TransformOptions): ResponseNode\nexport function transform(node: Node, options: TransformOptions): Node\nexport function transform(node: Node, options: TransformOptions): Node {\n const { depth, parent, ...visitor } = options\n const recurse = (depth ?? visitorDepths.deep) === visitorDepths.deep\n\n const visited = applyVisitor<Node>(node, visitor, parent) ?? node\n const rebuilt = transformChildren(visited, options, recurse)\n\n // Structural sharing: when the visitor and child rebuild both left this node\n // untouched, return the original reference so callers can detect \"nothing\n // changed\" by identity and ancestors can avoid reallocating.\n if (rebuilt === node) return node\n\n const rebuild = nodeRebuilders[rebuilt.kind]\n return rebuild ? rebuild(rebuilt) : rebuilt\n}\n\n/**\n * Immutably rebuilds a node's children using {@link VISITOR_KEYS}, transforming\n * each child node and leaving non-node values (e.g. `additionalProperties: true`) intact.\n * `Schema` children are skipped in shallow mode.\n */\nfunction transformChildren(node: Node, options: TransformOptions, recurse: boolean): Node {\n if (node.kind === 'Schema' && !recurse) return node\n\n const keys = visitorKeysByKind[node.kind]\n if (!keys) return node\n\n const record = node as unknown as Record<string, unknown>\n const childOptions = { ...options, parent: node }\n let updates: Record<string, unknown> | undefined\n\n for (const key of keys) {\n if (!(key in record)) continue\n const value = record[key]\n if (Array.isArray(value)) {\n let changed = false\n const mapped = value.map((item) => {\n if (!isNode(item)) return item\n const next = transform(item, childOptions)\n if (next !== item) changed = true\n return next\n })\n if (changed) (updates ??= {})[key] = mapped\n } else if (isNode(value)) {\n const next = transform(value, childOptions)\n if (next !== value) (updates ??= {})[key] = next\n }\n }\n\n return updates ? ({ ...node, ...updates } as Node) : node\n}\n/**\n * Lazy depth-first collection pass. Yields every non-null value returned by\n * the visitor callbacks. Use `collect` for the eager array form.\n *\n * @example Collect every operationId\n * ```ts\n * const ids: string[] = []\n * for (const id of collectLazy<string>(root, {\n * operation(node) {\n * return node.operationId\n * },\n * })) {\n * ids.push(id)\n * }\n * ```\n */\nexport function* collectLazy<T>(node: Node, options: CollectOptions<T>): Generator<T, void, undefined> {\n const { depth, parent, ...visitor } = options\n const recurse = (depth ?? visitorDepths.deep) === visitorDepths.deep\n\n const v = applyVisitor<T>(node, visitor, parent)\n if (v != null) yield v\n\n for (const child of getChildren(node, recurse)) {\n yield* collectLazy(child, { ...options, parent: node })\n }\n}\n\n/**\n * Eager depth-first collection pass. Gathers every non-null value the visitor\n * callbacks return into an array.\n *\n * @example Collect every operationId\n * ```ts\n * const ids = collect<string>(root, {\n * operation(node) {\n * return node.operationId\n * },\n * })\n * ```\n */\nexport function collect<T>(node: Node, options: CollectOptions<T>): Array<T> {\n return Array.from(collectLazy(node, options))\n}\n"],"mappings":";;;AAWA,MAAa,gBAAgB;CAC3B,SAAS;CACT,MAAM;AACR;;;;;;;AAQA,MAAa,cAAc;;;;CAIzB,QAAQ;;;;CAIR,QAAQ;;;;CAIR,SAAS;;;;CAIT,QAAQ;;;;CAIR,SAAS;;;;CAIT,MAAM;;;;CAIN,KAAK;;;;CAIL,SAAS;;;;CAIT,MAAM;;;;CAIN,QAAQ;;;;CAIR,OAAO;;;;CAIP,OAAO;;;;CAIP,OAAO;;;;CAIP,cAAc;;;;CAId,MAAM;;;;CAIN,KAAK;;;;CAIL,MAAM;;;;CAIN,UAAU;;;;CAIV,MAAM;;;;CAIN,MAAM;;;;CAIN,OAAO;;;;CAIP,KAAK;;;;CAIL,MAAM;;;;CAIN,MAAM;;;;CAIN,MAAM;;;;CAIN,OAAO;AACT;;;;AAOA,MAAM,yBAAyB,IAAI,IAAqB;CAAC;CAAU;CAAU;CAAW;CAAU;AAAS,CAAC;;;;;AAM5G,SAAgB,kBAAkB,MAAuC;CACvE,OAAO,uBAAuB,IAAI,IAAuB;AAC3D;;;;AAKA,MAAa,cAAc;CACzB,KAAK;CACL,MAAM;CACN,KAAK;CACL,OAAO;CACP,QAAQ;CACR,MAAM;CACN,SAAS;CACT,OAAO;AACT;;;;AA0BA,MAAa,SAAS,MAAM,KAAK,EAAE,QAAQ,EAAY,SAAS,GAAG,CAAC,CAAC,KAAK,EAAE;;;;;;;;;;;;AC3K5E,SAAgB,aAA2C,MAA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