@kubb/ast 5.0.0-beta.7 → 5.0.0-beta.71

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 (65) hide show
  1. package/LICENSE +17 -10
  2. package/README.md +53 -27
  3. package/dist/defineMacro-5Dvct8k_.cjs +114 -0
  4. package/dist/defineMacro-5Dvct8k_.cjs.map +1 -0
  5. package/dist/defineMacro-BXpTwp0y.d.ts +466 -0
  6. package/dist/defineMacro-VfsvblGi.js +98 -0
  7. package/dist/defineMacro-VfsvblGi.js.map +1 -0
  8. package/dist/index-DJEyS5y6.d.ts +2428 -0
  9. package/dist/index.cjs +198 -2239
  10. package/dist/index.cjs.map +1 -1
  11. package/dist/index.d.ts +98 -3400
  12. package/dist/index.js +149 -2160
  13. package/dist/index.js.map +1 -1
  14. package/dist/macros.cjs +130 -0
  15. package/dist/macros.cjs.map +1 -0
  16. package/dist/macros.d.ts +61 -0
  17. package/dist/macros.js +128 -0
  18. package/dist/macros.js.map +1 -0
  19. package/dist/operationParams-BaY12i2I.d.ts +148 -0
  20. package/dist/refs-D18OeCgb.js +117 -0
  21. package/dist/refs-D18OeCgb.js.map +1 -0
  22. package/dist/refs-DuP3_Leg.cjs +157 -0
  23. package/dist/refs-DuP3_Leg.cjs.map +1 -0
  24. package/dist/rolldown-runtime-CNktS9qV.js +17 -0
  25. package/dist/types-BsP1SK9j.d.ts +244 -0
  26. package/dist/types.cjs +0 -0
  27. package/dist/types.d.ts +5 -0
  28. package/dist/types.js +1 -0
  29. package/dist/utils.cjs +803 -0
  30. package/dist/utils.cjs.map +1 -0
  31. package/dist/utils.d.ts +354 -0
  32. package/dist/utils.js +777 -0
  33. package/dist/utils.js.map +1 -0
  34. package/dist/visitor-CQdSiClY.cjs +1749 -0
  35. package/dist/visitor-CQdSiClY.cjs.map +1 -0
  36. package/dist/visitor-dcVC5TOW.js +1313 -0
  37. package/dist/visitor-dcVC5TOW.js.map +1 -0
  38. package/package.json +17 -5
  39. package/dist/chunk--u3MIqq1.js +0 -8
  40. package/src/constants.ts +0 -228
  41. package/src/factory.ts +0 -742
  42. package/src/guards.ts +0 -110
  43. package/src/index.ts +0 -46
  44. package/src/infer.ts +0 -130
  45. package/src/mocks.ts +0 -176
  46. package/src/nodes/base.ts +0 -56
  47. package/src/nodes/code.ts +0 -304
  48. package/src/nodes/file.ts +0 -230
  49. package/src/nodes/function.ts +0 -223
  50. package/src/nodes/http.ts +0 -119
  51. package/src/nodes/index.ts +0 -86
  52. package/src/nodes/operation.ts +0 -111
  53. package/src/nodes/output.ts +0 -26
  54. package/src/nodes/parameter.ts +0 -41
  55. package/src/nodes/property.ts +0 -34
  56. package/src/nodes/response.ts +0 -43
  57. package/src/nodes/root.ts +0 -64
  58. package/src/nodes/schema.ts +0 -656
  59. package/src/printer.ts +0 -250
  60. package/src/refs.ts +0 -67
  61. package/src/resolvers.ts +0 -45
  62. package/src/transformers.ts +0 -159
  63. package/src/types.ts +0 -70
  64. package/src/utils.ts +0 -915
  65. package/src/visitor.ts +0 -592
@@ -0,0 +1,1313 @@
1
+ import "./rolldown-runtime-CNktS9qV.js";
2
+ import { hash } from "node:crypto";
3
+ import path from "node:path";
4
+ //#region src/constants.ts
5
+ const visitorDepths = {
6
+ shallow: "shallow",
7
+ deep: "deep"
8
+ };
9
+ /**
10
+ * Schema type discriminators used by all AST schema nodes.
11
+ *
12
+ * Each value is a stable discriminator across the AST (for example `schema.type === schemaTypes.object`).
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
+ * One indentation level, derived from {@link INDENT_SIZE}.
122
+ */
123
+ const INDENT = Array.from({ length: 2 }, () => " ").join("");
124
+ //#endregion
125
+ //#region src/guards.ts
126
+ /**
127
+ * Narrows a `SchemaNode` to the variant that matches `type`.
128
+ *
129
+ * @example
130
+ * ```ts
131
+ * const schema = createSchema({ type: 'string' })
132
+ * const stringNode = narrowSchema(schema, 'string') // StringSchemaNode | null
133
+ * ```
134
+ */
135
+ function narrowSchema(node, type) {
136
+ return node?.type === type ? node : null;
137
+ }
138
+ /**
139
+ * Narrows an `OperationNode` to an `HttpOperationNode` so `method` and `path` are present.
140
+ *
141
+ * @example
142
+ * ```ts
143
+ * if (isHttpOperationNode(node)) {
144
+ * console.log(node.method, node.path)
145
+ * }
146
+ * ```
147
+ */
148
+ function isHttpOperationNode(node) {
149
+ return node.protocol === "http" || node.method !== void 0 && node.path !== void 0;
150
+ }
151
+ //#endregion
152
+ //#region src/defineNode.ts
153
+ /**
154
+ * Visitor callback names, one per traversable node kind, in traversal order.
155
+ * Kept in sync with the keys of `Visitor` in `visitor.ts`.
156
+ */
157
+ const visitorKeys = [
158
+ "input",
159
+ "output",
160
+ "operation",
161
+ "schema",
162
+ "property",
163
+ "parameter",
164
+ "response"
165
+ ];
166
+ /**
167
+ * Builds a type guard that matches nodes of the given `kind`.
168
+ */
169
+ function isKind(kind) {
170
+ return (node) => node?.kind === kind;
171
+ }
172
+ /**
173
+ * Defines a node once and derives its `create` builder, `is` guard, and traversal
174
+ * metadata. `create` merges `defaults`, the `build` hook (or the raw input), and the
175
+ * `kind`, so node construction lives in one place without scattered `as` casts.
176
+ *
177
+ * @example Simple node
178
+ * ```ts
179
+ * const importDef = defineNode<ImportNode>({ kind: 'Import' })
180
+ * const createImport = importDef.create
181
+ * ```
182
+ *
183
+ * @example Node with a build hook
184
+ * ```ts
185
+ * const propertyDef = defineNode<PropertyNode, UserPropertyNode>({
186
+ * kind: 'Property',
187
+ * build: (props) => ({ ...props, required: props.required ?? false }),
188
+ * children: ['schema'],
189
+ * visitorKey: 'property',
190
+ * })
191
+ * ```
192
+ */
193
+ function defineNode(config) {
194
+ const { kind, defaults, build, children, visitorKey } = config;
195
+ function create(input) {
196
+ const base = build ? build(input) : input;
197
+ return {
198
+ ...defaults,
199
+ ...base,
200
+ kind
201
+ };
202
+ }
203
+ return {
204
+ kind,
205
+ create,
206
+ is: isKind(kind),
207
+ children,
208
+ visitorKey
209
+ };
210
+ }
211
+ //#endregion
212
+ //#region src/nodes/code.ts
213
+ /**
214
+ * Definition for the {@link ConstNode}.
215
+ */
216
+ const constDef = defineNode({ kind: "Const" });
217
+ /**
218
+ * Definition for the {@link TypeNode}.
219
+ */
220
+ const typeDef = defineNode({ kind: "Type" });
221
+ /**
222
+ * Definition for the {@link FunctionNode}.
223
+ */
224
+ const functionDef = defineNode({ kind: "Function" });
225
+ /**
226
+ * Definition for the {@link ArrowFunctionNode}.
227
+ */
228
+ const arrowFunctionDef = defineNode({ kind: "ArrowFunction" });
229
+ /**
230
+ * Definition for the {@link TextNode}.
231
+ */
232
+ const textDef = defineNode({
233
+ kind: "Text",
234
+ build: (value) => ({ value })
235
+ });
236
+ /**
237
+ * Definition for the {@link BreakNode}.
238
+ */
239
+ const breakDef = defineNode({
240
+ kind: "Break",
241
+ build: () => ({})
242
+ });
243
+ /**
244
+ * Definition for the {@link JsxNode}.
245
+ */
246
+ const jsxDef = defineNode({
247
+ kind: "Jsx",
248
+ build: (value) => ({ value })
249
+ });
250
+ /**
251
+ * Creates a `ConstNode` representing a TypeScript `const` declaration.
252
+ *
253
+ * @example Exported constant with type and `as const`
254
+ * ```ts
255
+ * createConst({ name: 'pets', export: true, type: 'Pet[]', asConst: true })
256
+ * // export const pets: Pet[] = ... as const
257
+ * ```
258
+ */
259
+ const createConst = constDef.create;
260
+ /**
261
+ * Creates a `TypeNode` representing a TypeScript `type` alias declaration.
262
+ *
263
+ * @example
264
+ * ```ts
265
+ * createType({ name: 'Pet', export: true })
266
+ * // export type Pet = ...
267
+ * ```
268
+ */
269
+ const createType = typeDef.create;
270
+ /**
271
+ * Creates a `FunctionNode` representing a TypeScript `function` declaration.
272
+ *
273
+ * @example
274
+ * ```ts
275
+ * createFunction({ name: 'fetchPet', export: true, async: true, returnType: 'Pet' })
276
+ * // export async function fetchPet(): Promise<Pet> { ... }
277
+ * ```
278
+ */
279
+ const createFunction = functionDef.create;
280
+ /**
281
+ * Creates an `ArrowFunctionNode` representing a TypeScript arrow function.
282
+ *
283
+ * @example
284
+ * ```ts
285
+ * createArrowFunction({ name: 'double', export: true, params: 'n: number', singleLine: true })
286
+ * // export const double = (n: number) => ...
287
+ * ```
288
+ */
289
+ const createArrowFunction = arrowFunctionDef.create;
290
+ /**
291
+ * Creates a {@link TextNode} representing a raw string fragment in the source output.
292
+ *
293
+ * @example
294
+ * ```ts
295
+ * createText('return fetch(id)')
296
+ * // { kind: 'Text', value: 'return fetch(id)' }
297
+ * ```
298
+ */
299
+ const createText = textDef.create;
300
+ /**
301
+ * Creates a {@link BreakNode} representing a line break in the source output.
302
+ *
303
+ * @example
304
+ * ```ts
305
+ * createBreak()
306
+ * // { kind: 'Break' }
307
+ * ```
308
+ */
309
+ function createBreak() {
310
+ return breakDef.create();
311
+ }
312
+ /**
313
+ * Creates a {@link JsxNode} representing a raw JSX fragment in the source output.
314
+ *
315
+ * @example
316
+ * ```ts
317
+ * createJsx('<>\n <a href={href}>Open</a>\n</>')
318
+ * // { kind: 'Jsx', value: '<>\n <a href={href}>Open</a>\n</>' }
319
+ * ```
320
+ */
321
+ const createJsx = jsxDef.create;
322
+ //#endregion
323
+ //#region src/nodes/content.ts
324
+ /**
325
+ * Definition for the {@link ContentNode}.
326
+ */
327
+ const contentDef = defineNode({
328
+ kind: "Content",
329
+ children: ["schema"]
330
+ });
331
+ /**
332
+ * Creates a `ContentNode` for a single request-body or response content type.
333
+ */
334
+ const createContent = contentDef.create;
335
+ //#endregion
336
+ //#region ../../internals/utils/src/casing.ts
337
+ /**
338
+ * Shared implementation for camelCase and PascalCase conversion.
339
+ * Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)
340
+ * and capitalizes each word according to `pascal`.
341
+ *
342
+ * When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.
343
+ */
344
+ function toCamelOrPascal(text, pascal) {
345
+ return text.trim().replace(/([a-z\d])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").replace(/(\d)([a-z])/g, "$1 $2").split(/[\s\-_./\\:]+/).filter(Boolean).map((word, i) => {
346
+ if (word.length > 1 && word === word.toUpperCase()) return word;
347
+ return (i === 0 && !pascal ? word.charAt(0).toLowerCase() : word.charAt(0).toUpperCase()) + word.slice(1);
348
+ }).join("").replace(/[^a-zA-Z0-9]/g, "");
349
+ }
350
+ /**
351
+ * Converts `text` to camelCase.
352
+ *
353
+ * @example Word boundaries
354
+ * `camelCase('hello-world') // 'helloWorld'`
355
+ *
356
+ * @example With a prefix
357
+ * `camelCase('tag', { prefix: 'create' }) // 'createTag'`
358
+ */
359
+ function camelCase(text, { prefix = "", suffix = "" } = {}) {
360
+ return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false);
361
+ }
362
+ /**
363
+ * Converts `text` to PascalCase.
364
+ *
365
+ * @example Word boundaries
366
+ * `pascalCase('hello-world') // 'HelloWorld'`
367
+ *
368
+ * @example With a suffix
369
+ * `pascalCase('tag', { suffix: 'schema' }) // 'TagSchema'`
370
+ */
371
+ function pascalCase(text, { prefix = "", suffix = "" } = {}) {
372
+ return toCamelOrPascal(`${prefix} ${text} ${suffix}`, true);
373
+ }
374
+ //#endregion
375
+ //#region ../../internals/utils/src/fs.ts
376
+ /**
377
+ * Strips the file extension from a path or file name.
378
+ * Only removes the last `.ext` segment when the dot is not part of a directory name.
379
+ *
380
+ * @example
381
+ * trimExtName('petStore.ts') // 'petStore'
382
+ * trimExtName('/src/models/pet.ts') // '/src/models/pet'
383
+ * trimExtName('/project.v2/gen/pet.ts') // '/project.v2/gen/pet'
384
+ * trimExtName('noExtension') // 'noExtension'
385
+ */
386
+ function trimExtName(text) {
387
+ const dotIndex = text.lastIndexOf(".");
388
+ if (dotIndex > 0 && !text.includes("/", dotIndex)) return text.slice(0, dotIndex);
389
+ return text;
390
+ }
391
+ //#endregion
392
+ //#region src/utils/extractStringsFromNodes.ts
393
+ /**
394
+ * Extracts all string content from a `CodeNode` tree recursively.
395
+ *
396
+ * Collects text node values, identifier references in string fields (`params`, `generics`, `returnType`, `type`),
397
+ * and nested node content. Used to build the full source string for import filtering.
398
+ */
399
+ function extractStringsFromNodes(nodes) {
400
+ if (!nodes?.length) return "";
401
+ return nodes.map((node) => {
402
+ if (typeof node === "string") return node;
403
+ if (node.kind === "Text") return node.value;
404
+ if (node.kind === "Break") return "";
405
+ if (node.kind === "Jsx") return node.value;
406
+ const parts = [];
407
+ if ("params" in node && node.params) parts.push(node.params);
408
+ if ("generics" in node && node.generics) parts.push(Array.isArray(node.generics) ? node.generics.join(", ") : node.generics);
409
+ if ("returnType" in node && node.returnType) parts.push(node.returnType);
410
+ if ("type" in node && typeof node.type === "string") parts.push(node.type);
411
+ const nested = extractStringsFromNodes(node.nodes);
412
+ if (nested) parts.push(nested);
413
+ return parts.join("\n");
414
+ }).filter(Boolean).join("\n");
415
+ }
416
+ //#endregion
417
+ //#region src/utils/fileMerge.ts
418
+ function sourceKey(source) {
419
+ return `${source.name ?? extractStringsFromNodes(source.nodes)}:${source.isExportable ?? false}:${source.isTypeOnly ?? false}`;
420
+ }
421
+ function pathTypeKey(path, isTypeOnly) {
422
+ return `${path}:${isTypeOnly ?? false}`;
423
+ }
424
+ function exportKey(path, name, isTypeOnly, asAlias) {
425
+ return `${path}:${name ?? ""}:${isTypeOnly ?? false}:${asAlias ?? ""}`;
426
+ }
427
+ function importKey(path, name, isTypeOnly) {
428
+ return `${path}:${name ?? ""}:${isTypeOnly ?? false}`;
429
+ }
430
+ /**
431
+ * Computes a multi-level sort key for exports and imports:
432
+ * non-array names first (wildcards/namespace aliases). Type-only before value. Alphabetical path. Unnamed before named.
433
+ */
434
+ function sortKey(node) {
435
+ const isArray = Array.isArray(node.name) ? "1" : "0";
436
+ const typeOnly = node.isTypeOnly ? "0" : "1";
437
+ const hasName = node.name != null ? "1" : "0";
438
+ const name = Array.isArray(node.name) ? node.name.toSorted().join("\0") : node.name ?? "";
439
+ return `${isArray}:${typeOnly}:${node.path}:${hasName}:${name}`;
440
+ }
441
+ /**
442
+ * Deduplicates `SourceNode` objects by `name + isExportable + isTypeOnly`, keeping the first of each
443
+ * key. Unnamed sources fall back to their extracted node strings as the name part of the key. Returns
444
+ * the deduplicated array in original order.
445
+ */
446
+ function combineSources(sources) {
447
+ const seen = /* @__PURE__ */ new Map();
448
+ for (const source of sources) {
449
+ const key = sourceKey(source);
450
+ if (!seen.has(key)) seen.set(key, source);
451
+ }
452
+ return [...seen.values()];
453
+ }
454
+ /**
455
+ * Merges `incoming` names into `existing`, preserving order and dropping duplicates.
456
+ *
457
+ * Shared by `combineExports` and `combineImports` for the same-path name-merge case.
458
+ */
459
+ function mergeNameArrays(existing, incoming) {
460
+ const merged = new Set(existing);
461
+ for (const name of incoming) merged.add(name);
462
+ return [...merged];
463
+ }
464
+ /**
465
+ * Deduplicates and merges `ExportNode` objects by path and type.
466
+ *
467
+ * Named exports with the same path and `isTypeOnly` flag have their names merged into a single export.
468
+ * Non-array exports are deduplicated by exact identity. Returns a sorted, deduplicated array.
469
+ */
470
+ function combineExports(exports) {
471
+ const result = [];
472
+ const namedByPath = /* @__PURE__ */ new Map();
473
+ const seen = /* @__PURE__ */ new Set();
474
+ const keyed = exports.map((node) => ({
475
+ node,
476
+ key: sortKey(node)
477
+ }));
478
+ keyed.sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
479
+ for (const { node: curr } of keyed) {
480
+ const { name, path, isTypeOnly, asAlias } = curr;
481
+ if (Array.isArray(name)) {
482
+ if (!name.length) continue;
483
+ const key = pathTypeKey(path, isTypeOnly);
484
+ const existing = namedByPath.get(key);
485
+ if (existing && Array.isArray(existing.name)) existing.name = mergeNameArrays(existing.name, name);
486
+ else {
487
+ const newItem = {
488
+ ...curr,
489
+ name: [...new Set(name)]
490
+ };
491
+ result.push(newItem);
492
+ namedByPath.set(key, newItem);
493
+ }
494
+ } else {
495
+ const key = exportKey(path, name, isTypeOnly, asAlias);
496
+ if (!seen.has(key)) {
497
+ result.push(curr);
498
+ seen.add(key);
499
+ }
500
+ }
501
+ }
502
+ return result;
503
+ }
504
+ /**
505
+ * Deduplicates and merges `ImportNode` objects, filtering out unused imports.
506
+ *
507
+ * Retains imports that are referenced in `source` or re-exported. Imports with the same path and
508
+ * `isTypeOnly` flag have their names merged. Returns a sorted, deduplicated, filtered array.
509
+ */
510
+ function combineImports(imports, exports, source) {
511
+ const exportedNames = new Set(exports.flatMap((e) => Array.isArray(e.name) ? e.name : e.name ? [e.name] : []));
512
+ const isUsed = (importName) => !source || source.includes(importName) || exportedNames.has(importName);
513
+ const importNameMemo = /* @__PURE__ */ new Map();
514
+ const canonicalizeName = (n) => {
515
+ if (typeof n === "string") return n;
516
+ const key = `${n.propertyName}:${n.name ?? ""}`;
517
+ if (!importNameMemo.has(key)) importNameMemo.set(key, n);
518
+ return importNameMemo.get(key);
519
+ };
520
+ const pathsWithUsedNamedImport = /* @__PURE__ */ new Set();
521
+ for (const node of imports) {
522
+ if (!Array.isArray(node.name)) continue;
523
+ if (node.name.some((item) => typeof item === "string" ? isUsed(item) : isUsed(item.name ?? item.propertyName))) pathsWithUsedNamedImport.add(node.path);
524
+ }
525
+ const result = [];
526
+ const namedByPath = /* @__PURE__ */ new Map();
527
+ const seen = /* @__PURE__ */ new Set();
528
+ const keyed = imports.map((node) => ({
529
+ node,
530
+ key: sortKey(node)
531
+ }));
532
+ keyed.sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
533
+ for (const { node: curr } of keyed) {
534
+ if (curr.path === curr.root) continue;
535
+ const { path, isTypeOnly } = curr;
536
+ let { name } = curr;
537
+ if (Array.isArray(name)) {
538
+ name = [...new Set(name.map(canonicalizeName))].filter((item) => typeof item === "string" ? isUsed(item) : isUsed(item.name ?? item.propertyName));
539
+ if (!name.length) continue;
540
+ const key = pathTypeKey(path, isTypeOnly);
541
+ const existing = namedByPath.get(key);
542
+ if (existing && Array.isArray(existing.name)) existing.name = mergeNameArrays(existing.name, name);
543
+ else {
544
+ const newItem = {
545
+ ...curr,
546
+ name
547
+ };
548
+ result.push(newItem);
549
+ namedByPath.set(key, newItem);
550
+ }
551
+ } else {
552
+ if (name && !isUsed(name) && !pathsWithUsedNamedImport.has(path)) continue;
553
+ const key = importKey(path, name, isTypeOnly);
554
+ if (!seen.has(key)) {
555
+ result.push(curr);
556
+ seen.add(key);
557
+ }
558
+ }
559
+ }
560
+ return result;
561
+ }
562
+ //#endregion
563
+ //#region src/nodes/file.ts
564
+ /**
565
+ * Definition for the {@link ImportNode}.
566
+ */
567
+ const importDef = defineNode({ kind: "Import" });
568
+ /**
569
+ * Definition for the {@link ExportNode}.
570
+ */
571
+ const exportDef = defineNode({ kind: "Export" });
572
+ /**
573
+ * Definition for the {@link SourceNode}.
574
+ */
575
+ const sourceDef = defineNode({ kind: "Source" });
576
+ /**
577
+ * Definition for the {@link FileNode}. The fully resolved builder lives in
578
+ * `createFile`, so this definition only supplies the guard.
579
+ */
580
+ const fileDef = defineNode({ kind: "File" });
581
+ /**
582
+ * Creates an `ImportNode` representing a language-agnostic import/dependency declaration.
583
+ *
584
+ * @example Named import
585
+ * ```ts
586
+ * createImport({ name: ['useState'], path: 'react' })
587
+ * // import { useState } from 'react'
588
+ * ```
589
+ */
590
+ const createImport = importDef.create;
591
+ /**
592
+ * Creates an `ExportNode` representing a language-agnostic export/public API declaration.
593
+ *
594
+ * @example Named export
595
+ * ```ts
596
+ * createExport({ name: ['Pet'], path: './Pet' })
597
+ * // export { Pet } from './Pet'
598
+ * ```
599
+ */
600
+ const createExport = exportDef.create;
601
+ /**
602
+ * Creates a `SourceNode` representing a fragment of source code within a file.
603
+ *
604
+ * @example
605
+ * ```ts
606
+ * createSource({ name: 'Pet', nodes: [createText('export type Pet = { id: number }')], isExportable: true })
607
+ * ```
608
+ */
609
+ const createSource = sourceDef.create;
610
+ /**
611
+ * Creates a fully resolved `FileNode` from a file input descriptor.
612
+ *
613
+ * Computes:
614
+ * - `id` SHA256 hash of the file path
615
+ * - `name` `baseName` without extension
616
+ * - `extname` extension extracted from `baseName`
617
+ *
618
+ * Deduplicates:
619
+ * - `sources` via `combineSources`
620
+ * - `exports` via `combineExports`
621
+ * - `imports` via `combineImports` (also filters unused imports)
622
+ *
623
+ * @throws {Error} when `baseName` has no extension.
624
+ *
625
+ * @example
626
+ * ```ts
627
+ * const file = createFile({
628
+ * baseName: 'petStore.ts',
629
+ * path: 'src/models/petStore.ts',
630
+ * sources: [createSource({ name: 'Pet', nodes: [createText('export type Pet = { id: number }')] })],
631
+ * imports: [createImport({ name: ['z'], path: 'zod' })],
632
+ * exports: [createExport({ name: ['Pet'], path: './petStore' })],
633
+ * })
634
+ * // file.id = SHA256 hash of 'src/models/petStore.ts'
635
+ * // file.name = 'petStore'
636
+ * // file.extname = '.ts'
637
+ * ```
638
+ *
639
+ * @example Copy a real file into the output verbatim
640
+ * ```ts
641
+ * const file = createFile({
642
+ * baseName: 'client.ts',
643
+ * path: 'src/gen/client.ts',
644
+ * copy: '/abs/path/to/templates/client.ts',
645
+ * })
646
+ * ```
647
+ */
648
+ function createFile(input) {
649
+ const extname = path.extname(input.baseName) || (input.baseName.startsWith(".") ? input.baseName : "");
650
+ if (!extname) throw new Error(`No extname found for ${input.baseName}`);
651
+ const source = (input.sources ?? []).flatMap((item) => item.nodes ?? []).map((node) => extractStringsFromNodes([node])).filter(Boolean).join("\n\n");
652
+ const resolvedExports = input.exports?.length ? combineExports(input.exports) : [];
653
+ const combinedImports = input.imports?.length ? combineImports(input.imports, resolvedExports, source || void 0) : [];
654
+ const localNames = new Set((input.sources ?? []).map((item) => item.name).filter((name) => Boolean(name)));
655
+ const nameOf = (item) => typeof item === "string" ? item : item.name ?? item.propertyName;
656
+ const resolvedImports = combinedImports.filter((imp) => imp.path !== input.path).flatMap((imp) => {
657
+ if (!Array.isArray(imp.name)) return typeof imp.name === "string" && localNames.has(imp.name) ? [] : [imp];
658
+ const kept = imp.name.filter((item) => !localNames.has(nameOf(item)));
659
+ if (!kept.length) return [];
660
+ return [kept.length === imp.name.length ? imp : {
661
+ ...imp,
662
+ name: kept
663
+ }];
664
+ });
665
+ const resolvedSources = input.sources?.length ? combineSources(input.sources) : [];
666
+ return {
667
+ kind: "File",
668
+ ...input,
669
+ id: hash("sha256", input.path, "hex"),
670
+ name: trimExtName(input.baseName),
671
+ extname,
672
+ imports: resolvedImports,
673
+ exports: resolvedExports,
674
+ sources: resolvedSources,
675
+ meta: input.meta ?? {}
676
+ };
677
+ }
678
+ //#endregion
679
+ //#region src/nodes/function.ts
680
+ /**
681
+ * Definition for the {@link TypeLiteralNode}.
682
+ */
683
+ const typeLiteralDef = defineNode({ kind: "TypeLiteral" });
684
+ /**
685
+ * Definition for the {@link IndexedAccessTypeNode}.
686
+ */
687
+ const indexedAccessTypeDef = defineNode({ kind: "IndexedAccessType" });
688
+ /**
689
+ * Definition for the {@link ObjectBindingPatternNode}.
690
+ */
691
+ const objectBindingPatternDef = defineNode({ kind: "ObjectBindingPattern" });
692
+ /**
693
+ * Definition for the {@link FunctionParameterNode}. `optional` defaults to `false`.
694
+ * Passing `properties` builds a destructured group: an {@link ObjectBindingPatternNode} name
695
+ * paired with a {@link TypeLiteralNode} type.
696
+ */
697
+ const functionParameterDef = defineNode({
698
+ kind: "FunctionParameter",
699
+ build: (input) => {
700
+ if ("properties" in input) return {
701
+ name: createObjectBindingPattern({ elements: input.properties.map((p) => ({ name: p.name })) }),
702
+ type: createTypeLiteral({ members: input.properties.map((p) => ({
703
+ name: p.name,
704
+ type: p.type,
705
+ optional: p.optional ?? false
706
+ })) }),
707
+ optional: input.optional ?? false,
708
+ ...input.default !== void 0 ? { default: input.default } : {}
709
+ };
710
+ return {
711
+ optional: false,
712
+ ...input
713
+ };
714
+ }
715
+ });
716
+ /**
717
+ * Definition for the {@link FunctionParametersNode}.
718
+ */
719
+ const functionParametersDef = defineNode({
720
+ kind: "FunctionParameters",
721
+ defaults: { params: [] }
722
+ });
723
+ /**
724
+ * Creates a {@link TypeLiteralNode} representing an inline anonymous object type.
725
+ *
726
+ * @example
727
+ * ```ts
728
+ * createTypeLiteral({ members: [{ name: 'petId', type: 'string', optional: false }] })
729
+ * // { petId: string }
730
+ * ```
731
+ */
732
+ const createTypeLiteral = typeLiteralDef.create;
733
+ /**
734
+ * Creates an {@link IndexedAccessTypeNode} representing a single field accessed from a named type.
735
+ *
736
+ * @example
737
+ * ```ts
738
+ * createIndexedAccessType({ target: 'DeletePetPathParams', key: 'petId' })
739
+ * // DeletePetPathParams['petId']
740
+ * ```
741
+ */
742
+ const createIndexedAccessType = indexedAccessTypeDef.create;
743
+ /**
744
+ * Creates an {@link ObjectBindingPatternNode} for a destructured parameter binding.
745
+ *
746
+ * @example
747
+ * ```ts
748
+ * createObjectBindingPattern({ elements: [{ name: 'id' }, { name: 'name' }] })
749
+ * // { id, name }
750
+ * ```
751
+ */
752
+ const createObjectBindingPattern = objectBindingPatternDef.create;
753
+ /**
754
+ * Creates a `FunctionParameterNode`. `optional` defaults to `false`.
755
+ *
756
+ * @example Optional param
757
+ * ```ts
758
+ * createFunctionParameter({ name: 'params', type: 'QueryParams', optional: true })
759
+ * // → params?: QueryParams
760
+ * ```
761
+ *
762
+ * @example Destructured group
763
+ * ```ts
764
+ * createFunctionParameter({ properties: [{ name: 'id', type: 'string' }, { name: 'name', type: 'string', optional: true }], default: '{}' })
765
+ * // → { id, name }: { id: string; name?: string } = {}
766
+ * ```
767
+ *
768
+ * @example Destructured group typed from a single reference
769
+ * ```ts
770
+ * createFunctionParameter({ name: createObjectBindingPattern({ elements: [{ name: 'path' }] }), type: "Omit<Config, 'url'>", default: '{}' })
771
+ * // → { path }: Omit<Config, 'url'> = {}
772
+ * ```
773
+ */
774
+ const createFunctionParameter = functionParameterDef.create;
775
+ /**
776
+ * Creates a `FunctionParametersNode` from an ordered list of parameters.
777
+ *
778
+ * @example
779
+ * ```ts
780
+ * const empty = createFunctionParameters()
781
+ * // { kind: 'FunctionParameters', params: [] }
782
+ * ```
783
+ */
784
+ function createFunctionParameters(props = {}) {
785
+ return functionParametersDef.create(props);
786
+ }
787
+ //#endregion
788
+ //#region src/nodes/input.ts
789
+ /**
790
+ * Definition for the {@link InputNode}.
791
+ */
792
+ const inputDef = defineNode({
793
+ kind: "Input",
794
+ defaults: {
795
+ schemas: [],
796
+ operations: [],
797
+ meta: {
798
+ circularNames: [],
799
+ enumNames: []
800
+ }
801
+ },
802
+ children: ["schemas", "operations"],
803
+ visitorKey: "input"
804
+ });
805
+ /**
806
+ * Creates an `InputNode`. Pass `stream: true` for the streaming variant whose `schemas` and
807
+ * `operations` are `AsyncIterable` sources. Otherwise it builds the eager variant with array
808
+ * `schemas`/`operations`. Both variants get the defaulted `meta`.
809
+ *
810
+ * @example Eager
811
+ * ```ts
812
+ * const input = createInput()
813
+ * // { kind: 'Input', schemas: [], operations: [] }
814
+ * ```
815
+ *
816
+ * @example Streaming
817
+ * ```ts
818
+ * const node = createInput({ stream: true, schemas: schemasIterable, operations: operationsIterable, meta: { title: 'My API' } })
819
+ * ```
820
+ */
821
+ function createInput(options = {}) {
822
+ const { stream, ...overrides } = options;
823
+ if (stream) return {
824
+ kind: "Input",
825
+ meta: {
826
+ circularNames: [],
827
+ enumNames: []
828
+ },
829
+ ...overrides
830
+ };
831
+ return inputDef.create(overrides);
832
+ }
833
+ //#endregion
834
+ //#region src/nodes/requestBody.ts
835
+ /**
836
+ * Definition for the {@link RequestBodyNode}. Content entries are built upfront with
837
+ * {@link createContent}, mirroring how `parameters` and `responses` take prebuilt nodes.
838
+ */
839
+ const requestBodyDef = defineNode({
840
+ kind: "RequestBody",
841
+ children: ["content"]
842
+ });
843
+ /**
844
+ * Creates a `RequestBodyNode`.
845
+ */
846
+ const createRequestBody = requestBodyDef.create;
847
+ //#endregion
848
+ //#region src/nodes/operation.ts
849
+ /**
850
+ * Definition for the {@link OperationNode}. HTTP operations (those carrying both
851
+ * `method` and `path`) are tagged with `protocol: 'http'`, and the request body is
852
+ * normalized into a `RequestBodyNode`.
853
+ */
854
+ const operationDef = defineNode({
855
+ kind: "Operation",
856
+ build: (props) => {
857
+ const { requestBody, ...rest } = props;
858
+ const isHttp = rest.method !== void 0 && rest.path !== void 0;
859
+ return {
860
+ tags: [],
861
+ parameters: [],
862
+ responses: [],
863
+ ...rest,
864
+ ...isHttp ? { protocol: "http" } : {},
865
+ requestBody: requestBody ? createRequestBody(requestBody) : void 0
866
+ };
867
+ },
868
+ children: [
869
+ "parameters",
870
+ "requestBody",
871
+ "responses"
872
+ ],
873
+ visitorKey: "operation"
874
+ });
875
+ function createOperation(props) {
876
+ return operationDef.create(props);
877
+ }
878
+ //#endregion
879
+ //#region src/nodes/output.ts
880
+ /**
881
+ * Definition for the {@link OutputNode}.
882
+ */
883
+ const outputDef = defineNode({
884
+ kind: "Output",
885
+ defaults: { files: [] },
886
+ visitorKey: "output"
887
+ });
888
+ /**
889
+ * Creates an `OutputNode` with a stable default for `files`.
890
+ *
891
+ * @example
892
+ * ```ts
893
+ * const output = createOutput()
894
+ * // { kind: 'Output', files: [] }
895
+ * ```
896
+ */
897
+ function createOutput(overrides = {}) {
898
+ return outputDef.create(overrides);
899
+ }
900
+ //#endregion
901
+ //#region src/optionality.ts
902
+ /**
903
+ * Generic JSON Schema optionality: a non-required field is optional, and a
904
+ * non-required nullable field is nullish.
905
+ */
906
+ function optionality(schema, required) {
907
+ const nullable = schema.nullable ?? false;
908
+ return {
909
+ ...schema,
910
+ optional: !required && !nullable ? true : void 0,
911
+ nullish: !required && nullable ? true : void 0
912
+ };
913
+ }
914
+ //#endregion
915
+ //#region src/nodes/parameter.ts
916
+ /**
917
+ * Definition for the {@link ParameterNode}. `required` defaults to `false`, and the schema's
918
+ * `optional`/`nullish` flags are derived from it through {@link optionality}.
919
+ */
920
+ const parameterDef = defineNode({
921
+ kind: "Parameter",
922
+ build: (props) => {
923
+ const required = props.required ?? false;
924
+ return {
925
+ ...props,
926
+ required,
927
+ schema: optionality(props.schema, required)
928
+ };
929
+ },
930
+ children: ["schema"],
931
+ visitorKey: "parameter"
932
+ });
933
+ /**
934
+ * Creates a `ParameterNode`.
935
+ *
936
+ * @example
937
+ * ```ts
938
+ * const param = createParameter({
939
+ * name: 'petId',
940
+ * in: 'path',
941
+ * required: true,
942
+ * schema: createSchema({ type: 'string' }),
943
+ * })
944
+ * ```
945
+ */
946
+ const createParameter = parameterDef.create;
947
+ //#endregion
948
+ //#region src/nodes/property.ts
949
+ /**
950
+ * Definition for the {@link PropertyNode}. `required` defaults to `false`, and the schema's
951
+ * `optional`/`nullish` flags are derived from it through {@link optionality}.
952
+ */
953
+ const propertyDef = defineNode({
954
+ kind: "Property",
955
+ build: (props) => {
956
+ const required = props.required ?? false;
957
+ return {
958
+ ...props,
959
+ required,
960
+ schema: optionality(props.schema, required)
961
+ };
962
+ },
963
+ children: ["schema"],
964
+ visitorKey: "property"
965
+ });
966
+ /**
967
+ * Creates a `PropertyNode`.
968
+ *
969
+ * @example
970
+ * ```ts
971
+ * const property = createProperty({
972
+ * name: 'status',
973
+ * required: true,
974
+ * schema: createSchema({ type: 'string', nullable: true }),
975
+ * })
976
+ * // required=true, no optional/nullish
977
+ * ```
978
+ */
979
+ const createProperty = propertyDef.create;
980
+ //#endregion
981
+ //#region src/nodes/response.ts
982
+ /**
983
+ * Definition for the {@link ResponseNode}. A single legacy `schema` (with optional
984
+ * `mediaType`/`keysToOmit`) is normalized into one `content` entry.
985
+ */
986
+ const responseDef = defineNode({
987
+ kind: "Response",
988
+ build: (props) => {
989
+ const { schema, mediaType, keysToOmit, content, ...rest } = props;
990
+ const entries = content ?? (schema ? [createContent({
991
+ contentType: mediaType ?? "application/json",
992
+ schema,
993
+ keysToOmit: keysToOmit ?? null
994
+ })] : void 0);
995
+ return {
996
+ ...rest,
997
+ content: entries
998
+ };
999
+ },
1000
+ children: ["content"],
1001
+ visitorKey: "response"
1002
+ });
1003
+ /**
1004
+ * Creates a `ResponseNode`.
1005
+ *
1006
+ * @example
1007
+ * ```ts
1008
+ * const response = createResponse({
1009
+ * statusCode: '200',
1010
+ * content: [createContent({ contentType: 'application/json', schema: createSchema({ type: 'object', properties: [] }) })],
1011
+ * })
1012
+ * ```
1013
+ */
1014
+ const createResponse = responseDef.create;
1015
+ //#endregion
1016
+ //#region src/nodes/schema.ts
1017
+ /**
1018
+ * Maps schema `type` to its underlying `primitive`.
1019
+ * Primitive types map to themselves and special string formats map to `'string'`.
1020
+ * Any type not listed here (such as `ref`, `enum`, `union`, `intersection`, `tuple`, `ipv4`, `ipv6`, `blob`) has no `primitive`.
1021
+ */
1022
+ const TYPE_TO_PRIMITIVE = {
1023
+ string: "string",
1024
+ number: "number",
1025
+ integer: "integer",
1026
+ bigint: "bigint",
1027
+ boolean: "boolean",
1028
+ null: "null",
1029
+ any: "any",
1030
+ unknown: "unknown",
1031
+ void: "void",
1032
+ never: "never",
1033
+ object: "object",
1034
+ array: "array",
1035
+ date: "date",
1036
+ uuid: "string",
1037
+ email: "string",
1038
+ url: "string",
1039
+ datetime: "string",
1040
+ time: "string"
1041
+ };
1042
+ /**
1043
+ * Definition for the {@link SchemaNode}. Object schemas default `properties` to an
1044
+ * empty array, and `primitive` is inferred from `type` when not explicitly provided.
1045
+ */
1046
+ const schemaDef = defineNode({
1047
+ kind: "Schema",
1048
+ build: (props) => {
1049
+ if (props.type === "object") return {
1050
+ properties: [],
1051
+ primitive: "object",
1052
+ ...props
1053
+ };
1054
+ return {
1055
+ primitive: TYPE_TO_PRIMITIVE[props.type],
1056
+ ...props
1057
+ };
1058
+ },
1059
+ children: [
1060
+ "properties",
1061
+ "items",
1062
+ "members",
1063
+ "additionalProperties"
1064
+ ],
1065
+ visitorKey: "schema"
1066
+ });
1067
+ function createSchema(props) {
1068
+ return schemaDef.create(props);
1069
+ }
1070
+ //#endregion
1071
+ //#region src/registry.ts
1072
+ /**
1073
+ * Every node definition. Adding a node means adding its `defineNode` to one
1074
+ * `nodes/*.ts` file and listing it here. The visitor tables in `visitor.ts` derive from it.
1075
+ */
1076
+ const nodeDefs = [
1077
+ inputDef,
1078
+ outputDef,
1079
+ operationDef,
1080
+ requestBodyDef,
1081
+ contentDef,
1082
+ responseDef,
1083
+ schemaDef,
1084
+ propertyDef,
1085
+ parameterDef,
1086
+ functionParameterDef,
1087
+ functionParametersDef,
1088
+ typeLiteralDef,
1089
+ indexedAccessTypeDef,
1090
+ objectBindingPatternDef,
1091
+ constDef,
1092
+ typeDef,
1093
+ functionDef,
1094
+ arrowFunctionDef,
1095
+ textDef,
1096
+ breakDef,
1097
+ jsxDef,
1098
+ importDef,
1099
+ exportDef,
1100
+ sourceDef,
1101
+ fileDef
1102
+ ];
1103
+ //#endregion
1104
+ //#region src/visitor.ts
1105
+ /**
1106
+ * Child node fields per node kind, in traversal order (Babel's `VISITOR_KEYS`).
1107
+ * Derived from each definition's `children`.
1108
+ */
1109
+ const VISITOR_KEYS = Object.fromEntries(nodeDefs.flatMap((def) => def.children ? [[def.kind, def.children]] : []));
1110
+ /**
1111
+ * Maps a node kind to the matching visitor callback name. Derived from each
1112
+ * definition's `visitorKey`.
1113
+ */
1114
+ const VISITOR_KEY_BY_KIND = Object.fromEntries(nodeDefs.flatMap((def) => def.visitorKey ? [[def.kind, def.visitorKey]] : []));
1115
+ /**
1116
+ * Creates a small async concurrency limiter.
1117
+ *
1118
+ * At most `concurrency` tasks are in flight at once. Extra tasks are queued.
1119
+ *
1120
+ * @example
1121
+ * ```ts
1122
+ * const limit = createLimit(2)
1123
+ * for (const task of [taskA, taskB, taskC]) {
1124
+ * await limit(() => task())
1125
+ * }
1126
+ * // only 2 tasks run at the same time
1127
+ * ```
1128
+ */
1129
+ function createLimit(concurrency) {
1130
+ let active = 0;
1131
+ const queue = [];
1132
+ function next() {
1133
+ if (active < concurrency && queue.length > 0) {
1134
+ active++;
1135
+ queue.shift()();
1136
+ }
1137
+ }
1138
+ return function limit(fn) {
1139
+ return new Promise((resolve, reject) => {
1140
+ queue.push(() => {
1141
+ Promise.resolve(fn()).then(resolve, reject).finally(() => {
1142
+ active--;
1143
+ next();
1144
+ });
1145
+ });
1146
+ next();
1147
+ });
1148
+ };
1149
+ }
1150
+ const visitorKeysByKind = VISITOR_KEYS;
1151
+ /**
1152
+ * Returns `true` when `value` is an AST node (an object carrying a `kind`).
1153
+ */
1154
+ function isNode(value) {
1155
+ return typeof value === "object" && value !== null && "kind" in value;
1156
+ }
1157
+ /**
1158
+ * Returns the immediate traversable children of `node` based on {@link VISITOR_KEYS}.
1159
+ *
1160
+ * `Schema` children are only included when `recurse` is `true`. Shallow mode skips them.
1161
+ *
1162
+ * @example
1163
+ * ```ts
1164
+ * const children = getChildren(operationNode, true)
1165
+ * // returns parameters, the request body, and responses
1166
+ * ```
1167
+ */
1168
+ function* getChildren(node, recurse) {
1169
+ if (node.kind === "Schema" && !recurse) return;
1170
+ const keys = visitorKeysByKind[node.kind];
1171
+ if (!keys) return;
1172
+ const record = node;
1173
+ for (const key of keys) {
1174
+ const value = record[key];
1175
+ if (Array.isArray(value)) {
1176
+ for (const item of value) if (isNode(item)) yield item;
1177
+ } else if (isNode(value)) yield value;
1178
+ }
1179
+ }
1180
+ /**
1181
+ * Runs the visitor callback that matches `node.kind` with the traversal
1182
+ * context. The result is a replacement node, a collected value, or `undefined`
1183
+ * when no callback is registered for the kind.
1184
+ *
1185
+ * Shared by `walk`, `transform`, and `collectLazy` so node-kind dispatch lives
1186
+ * in one place. `TResult` is the caller's expected return: the same node type
1187
+ * for `transform`, the collected value type for `collectLazy`, ignored for `walk`.
1188
+ */
1189
+ function applyVisitor(node, visitor, parent) {
1190
+ const key = VISITOR_KEY_BY_KIND[node.kind];
1191
+ if (!key) return void 0;
1192
+ const fn = visitor[key];
1193
+ return fn?.(node, { parent });
1194
+ }
1195
+ /**
1196
+ * Async depth-first traversal for side effects. Visitor return values are
1197
+ * ignored. Use `transform` when you want to rewrite nodes.
1198
+ *
1199
+ * Sibling nodes at each depth run concurrently up to `options.concurrency`
1200
+ * (defaults to `WALK_CONCURRENCY`). Higher values overlap I/O-bound visitor
1201
+ * work. Lower values reduce memory pressure.
1202
+ *
1203
+ * @example Log every operation
1204
+ * ```ts
1205
+ * await walk(root, {
1206
+ * operation(node) {
1207
+ * console.log(node.operationId)
1208
+ * },
1209
+ * })
1210
+ * ```
1211
+ *
1212
+ * @example Only visit the root node
1213
+ * ```ts
1214
+ * await walk(root, { depth: 'shallow', input: () => {} })
1215
+ * ```
1216
+ */
1217
+ async function walk(node, options) {
1218
+ return _walk(node, options, (options.depth ?? visitorDepths.deep) === visitorDepths.deep, createLimit(options.concurrency ?? 30), void 0);
1219
+ }
1220
+ async function _walk(node, visitor, recurse, limit, parent) {
1221
+ await limit(() => applyVisitor(node, visitor, parent));
1222
+ const children = Array.from(getChildren(node, recurse));
1223
+ if (children.length === 0) return;
1224
+ await Promise.all(children.map((child) => _walk(child, visitor, recurse, limit, node)));
1225
+ }
1226
+ function transform(node, options) {
1227
+ const { depth, parent, ...visitor } = options;
1228
+ const recurse = (depth ?? visitorDepths.deep) === visitorDepths.deep;
1229
+ return transformChildren(applyVisitor(node, visitor, parent) ?? node, options, recurse);
1230
+ }
1231
+ /**
1232
+ * Immutably rebuilds a node's children using {@link VISITOR_KEYS}, transforming
1233
+ * each child node and leaving non-node values (e.g. `additionalProperties: true`) intact.
1234
+ * `Schema` children are skipped in shallow mode.
1235
+ */
1236
+ function transformChildren(node, options, recurse) {
1237
+ if (node.kind === "Schema" && !recurse) return node;
1238
+ const keys = visitorKeysByKind[node.kind];
1239
+ if (!keys) return node;
1240
+ const record = node;
1241
+ const childOptions = {
1242
+ ...options,
1243
+ parent: node
1244
+ };
1245
+ let updates;
1246
+ for (const key of keys) {
1247
+ if (!(key in record)) continue;
1248
+ const value = record[key];
1249
+ if (Array.isArray(value)) {
1250
+ let changed = false;
1251
+ const mapped = value.map((item) => {
1252
+ if (!isNode(item)) return item;
1253
+ const next = transform(item, childOptions);
1254
+ if (next !== item) changed = true;
1255
+ return next;
1256
+ });
1257
+ if (changed) (updates ??= {})[key] = mapped;
1258
+ } else if (isNode(value)) {
1259
+ const next = transform(value, childOptions);
1260
+ if (next !== value) (updates ??= {})[key] = next;
1261
+ }
1262
+ }
1263
+ return updates ? {
1264
+ ...node,
1265
+ ...updates
1266
+ } : node;
1267
+ }
1268
+ /**
1269
+ * Lazy depth-first collection pass. Yields every non-null value returned by
1270
+ * the visitor callbacks. Use `collect` for the eager array form.
1271
+ *
1272
+ * @example Collect every operationId
1273
+ * ```ts
1274
+ * const ids: string[] = []
1275
+ * for (const id of collectLazy<string>(root, {
1276
+ * operation(node) {
1277
+ * return node.operationId
1278
+ * },
1279
+ * })) {
1280
+ * ids.push(id)
1281
+ * }
1282
+ * ```
1283
+ */
1284
+ function* collectLazy(node, options) {
1285
+ const { depth, parent, ...visitor } = options;
1286
+ const recurse = (depth ?? visitorDepths.deep) === visitorDepths.deep;
1287
+ const v = applyVisitor(node, visitor, parent);
1288
+ if (v != null) yield v;
1289
+ for (const child of getChildren(node, recurse)) yield* collectLazy(child, {
1290
+ ...options,
1291
+ parent: node
1292
+ });
1293
+ }
1294
+ /**
1295
+ * Eager depth-first collection pass. Gathers every non-null value the visitor
1296
+ * callbacks return into an array.
1297
+ *
1298
+ * @example Collect every operationId
1299
+ * ```ts
1300
+ * const ids = collect<string>(root, {
1301
+ * operation(node) {
1302
+ * return node.operationId
1303
+ * },
1304
+ * })
1305
+ * ```
1306
+ */
1307
+ function collect(node, options) {
1308
+ return Array.from(collectLazy(node, options));
1309
+ }
1310
+ //#endregion
1311
+ export { createJsx as $, indexedAccessTypeDef as A, sourceDef as B, createFunctionParameter as C, createTypeLiteral as D, createObjectBindingPattern as E, createImport as F, createContent as G, camelCase as H, createSource as I, constDef as J, arrowFunctionDef as K, exportDef as L, typeLiteralDef as M, createExport as N, functionParameterDef as O, createFile as P, createFunction as Q, fileDef as R, inputDef as S, createIndexedAccessType as T, pascalCase as U, extractStringsFromNodes as V, contentDef as W, createBreak as X, createArrowFunction as Y, createConst as Z, createOperation as _, nodeDefs as a, typeDef as at, requestBodyDef as b, createResponse as c, isHttpOperationNode as ct, propertyDef as d, schemaTypes as dt, createText as et, createParameter as f, outputDef as g, createOutput as h, walk as i, textDef as it, objectBindingPatternDef as j, functionParametersDef as k, responseDef as l, narrowSchema as lt, optionality as m, collectLazy as n, functionDef as nt, createSchema as o, defineNode as ot, parameterDef as p, breakDef as q, transform as r, jsxDef as rt, schemaDef as s, visitorKeys as st, collect as t, createType as tt, createProperty as u, INDENT as ut, operationDef as v, createFunctionParameters as w, createInput as x, createRequestBody as y, importDef as z };
1312
+
1313
+ //# sourceMappingURL=visitor-dcVC5TOW.js.map