@kubb/ast 5.0.0-beta.9 → 5.0.0-beta.93

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -6,6 +6,15 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
6
  var __getOwnPropNames = Object.getOwnPropertyNames;
7
7
  var __getProtoOf = Object.getPrototypeOf;
8
8
  var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __exportAll = (all, no_symbols) => {
10
+ let target = {};
11
+ for (var name in all) __defProp(target, name, {
12
+ get: all[name],
13
+ enumerable: true
14
+ });
15
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
16
+ return target;
17
+ };
9
18
  var __copyProps = (to, from, except, desc) => {
10
19
  if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
20
  key = keys[i];
@@ -29,31 +38,10 @@ const visitorDepths = {
29
38
  shallow: "shallow",
30
39
  deep: "deep"
31
40
  };
32
- const nodeKinds = {
33
- input: "Input",
34
- output: "Output",
35
- operation: "Operation",
36
- schema: "Schema",
37
- property: "Property",
38
- parameter: "Parameter",
39
- response: "Response",
40
- functionParameter: "FunctionParameter",
41
- parameterGroup: "ParameterGroup",
42
- functionParameters: "FunctionParameters",
43
- type: "Type",
44
- file: "File",
45
- import: "Import",
46
- export: "Export",
47
- source: "Source",
48
- text: "Text",
49
- break: "Break"
50
- };
51
41
  /**
52
42
  * Schema type discriminators used by all AST schema nodes.
53
43
  *
54
- * These values serve as stable discriminators across the AST (e.g., `schema.type === schemaTypes.object`).
55
- * Grouped by category: primitives (`string`, `number`, `boolean`), structural types (`object`, `array`, `union`),
56
- * and format-specific types (`date`, `uuid`, `email`). Use `isScalarPrimitive()` to check for scalar types.
44
+ * Each value is a stable discriminator across the AST (for example `schema.type === schemaTypes.object`).
57
45
  */
58
46
  const schemaTypes = {
59
47
  /**
@@ -73,7 +61,7 @@ const schemaTypes = {
73
61
  */
74
62
  bigint: "bigint",
75
63
  /**
76
- * Boolean value
64
+ * Boolean value.
77
65
  */
78
66
  boolean: "boolean",
79
67
  /**
@@ -161,929 +149,341 @@ const schemaTypes = {
161
149
  */
162
150
  never: "never"
163
151
  };
152
+ //#endregion
153
+ //#region src/guards.ts
164
154
  /**
165
- * Scalar primitive schema types used for union simplification and type narrowing.
166
- *
167
- * Use `isScalarPrimitive()` to safely check whether a type is a scalar primitive.
168
- */
169
- const SCALAR_PRIMITIVE_TYPES = new Set([
170
- "string",
171
- "number",
172
- "integer",
173
- "bigint",
174
- "boolean"
175
- ]);
176
- /**
177
- * Type guard that returns `true` when `type` is a scalar primitive schema type.
155
+ * Narrows a `SchemaNode` to the variant that matches `type`.
178
156
  *
179
- * Use this to check if a schema type can be directly assigned without wrapping (e.g., `string | number | boolean`).
157
+ * @example
158
+ * ```ts
159
+ * const schema = createSchema({ type: 'string' })
160
+ * const stringNode = narrowSchema(schema, 'string') // StringSchemaNode | null
161
+ * ```
180
162
  */
181
- function isScalarPrimitive(type) {
182
- return SCALAR_PRIMITIVE_TYPES.has(type);
163
+ function narrowSchema(node, type) {
164
+ return node?.type === type ? node : null;
183
165
  }
184
166
  /**
185
- * HTTP method identifiers used by operation nodes.
167
+ * Narrows an `OperationNode` to an `HttpOperationNode` so `method` and `path` are present.
186
168
  *
187
- * Includes all standard HTTP methods (GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS, TRACE).
169
+ * @example
170
+ * ```ts
171
+ * if (isHttpOperationNode(node)) {
172
+ * console.log(node.method, node.path)
173
+ * }
174
+ * ```
188
175
  */
189
- const httpMethods = {
190
- get: "GET",
191
- post: "POST",
192
- put: "PUT",
193
- patch: "PATCH",
194
- delete: "DELETE",
195
- head: "HEAD",
196
- options: "OPTIONS",
197
- trace: "TRACE"
198
- };
199
- /**
200
- * Common MIME types used in request/response content negotiation.
201
- *
202
- * Covers JSON, XML, form data, PDFs, images, audio, and video formats.
203
- * Use these as keys when serializing request/response bodies.
204
- */
205
- const mediaTypes = {
206
- applicationJson: "application/json",
207
- applicationXml: "application/xml",
208
- applicationFormUrlEncoded: "application/x-www-form-urlencoded",
209
- applicationOctetStream: "application/octet-stream",
210
- applicationPdf: "application/pdf",
211
- applicationZip: "application/zip",
212
- applicationGraphql: "application/graphql",
213
- multipartFormData: "multipart/form-data",
214
- textPlain: "text/plain",
215
- textHtml: "text/html",
216
- textCsv: "text/csv",
217
- textXml: "text/xml",
218
- imagePng: "image/png",
219
- imageJpeg: "image/jpeg",
220
- imageGif: "image/gif",
221
- imageWebp: "image/webp",
222
- imageSvgXml: "image/svg+xml",
223
- audioMpeg: "audio/mpeg",
224
- videoMp4: "video/mp4"
225
- };
176
+ function isHttpOperationNode(node) {
177
+ return node.protocol === "http" || node.method !== void 0 && node.path !== void 0;
178
+ }
226
179
  //#endregion
227
- //#region ../../internals/utils/src/casing.ts
180
+ //#region src/defineNode.ts
228
181
  /**
229
- * Shared implementation for camelCase and PascalCase conversion.
230
- * Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)
231
- * and capitalizes each word according to `pascal`.
232
- *
233
- * When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.
182
+ * Visitor callback names, one per traversable node kind, in traversal order.
183
+ * Kept in sync with the keys of `Visitor` in `visitor.ts`.
234
184
  */
235
- function toCamelOrPascal(text, pascal) {
236
- 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) => {
237
- if (word.length > 1 && word === word.toUpperCase()) return word;
238
- if (i === 0 && !pascal) return word.charAt(0).toLowerCase() + word.slice(1);
239
- return word.charAt(0).toUpperCase() + word.slice(1);
240
- }).join("").replace(/[^a-zA-Z0-9]/g, "");
241
- }
185
+ const visitorKeys = [
186
+ "input",
187
+ "output",
188
+ "operation",
189
+ "schema",
190
+ "property",
191
+ "parameter",
192
+ "response"
193
+ ];
242
194
  /**
243
- * Splits `text` on `.` and applies `transformPart` to each segment.
244
- * The last segment receives `isLast = true`, all earlier segments receive `false`.
245
- * Segments are joined with `/` to form a file path.
246
- *
247
- * Only splits on dots followed by a letter so that version numbers
248
- * embedded in operationIds (e.g. `v2025.0`) are kept intact.
249
- *
250
- * Empty segments are filtered before joining. They arise when the text starts with
251
- * a dot followed immediately by a letter (e.g. `..Schema` splits into `['..', 'Schema']`
252
- * and `'..'` transforms to an empty string). Without this filter the join would produce
253
- * a leading `/`, which `path.resolve` would interpret as an absolute path, allowing
254
- * generated files to escape the configured output directory.
195
+ * Builds a type guard that matches nodes of the given `kind`.
255
196
  */
256
- function applyToFileParts(text, transformPart) {
257
- const parts = text.split(/\.(?=[a-zA-Z])/);
258
- return parts.map((part, i) => transformPart(part, i === parts.length - 1)).filter(Boolean).join("/");
259
- }
260
- /**
261
- * Converts `text` to camelCase.
262
- * When `isFile` is `true`, dot-separated segments are each cased independently and joined with `/`.
263
- *
264
- * @example
265
- * camelCase('hello-world') // 'helloWorld'
266
- * camelCase('pet.petId', { isFile: true }) // 'pet/petId'
267
- */
268
- function camelCase(text, { isFile, prefix = "", suffix = "" } = {}) {
269
- if (isFile) return applyToFileParts(text, (part, isLast) => camelCase(part, isLast ? {
270
- prefix,
271
- suffix
272
- } : {}));
273
- return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false);
197
+ function isKind(kind) {
198
+ return (node) => node?.kind === kind;
274
199
  }
275
200
  /**
276
- * Converts `text` to PascalCase.
277
- * When `isFile` is `true`, the last dot-separated segment is PascalCased and earlier segments are camelCased.
201
+ * Defines a node once and derives its `create` builder, `is` guard, and traversal
202
+ * metadata. `create` merges `defaults`, the `build` hook (or the raw input), and the
203
+ * `kind`, so node construction lives in one place without scattered `as` casts.
278
204
  *
279
- * @example
280
- * pascalCase('hello-world') // 'HelloWorld'
281
- * pascalCase('pet.petId', { isFile: true }) // 'pet/PetId'
282
- */
283
- function pascalCase(text, { isFile, prefix = "", suffix = "" } = {}) {
284
- if (isFile) return applyToFileParts(text, (part, isLast) => isLast ? pascalCase(part, {
285
- prefix,
286
- suffix
287
- }) : camelCase(part));
288
- return toCamelOrPascal(`${prefix} ${text} ${suffix}`, true);
289
- }
290
- //#endregion
291
- //#region ../../internals/utils/src/reserved.ts
292
- /**
293
- * JavaScript and Java reserved words.
294
- * @link https://github.com/jonschlinkert/reserved/blob/master/index.js
295
- */
296
- const reservedWords = new Set([
297
- "abstract",
298
- "arguments",
299
- "boolean",
300
- "break",
301
- "byte",
302
- "case",
303
- "catch",
304
- "char",
305
- "class",
306
- "const",
307
- "continue",
308
- "debugger",
309
- "default",
310
- "delete",
311
- "do",
312
- "double",
313
- "else",
314
- "enum",
315
- "eval",
316
- "export",
317
- "extends",
318
- "false",
319
- "final",
320
- "finally",
321
- "float",
322
- "for",
323
- "function",
324
- "goto",
325
- "if",
326
- "implements",
327
- "import",
328
- "in",
329
- "instanceof",
330
- "int",
331
- "interface",
332
- "let",
333
- "long",
334
- "native",
335
- "new",
336
- "null",
337
- "package",
338
- "private",
339
- "protected",
340
- "public",
341
- "return",
342
- "short",
343
- "static",
344
- "super",
345
- "switch",
346
- "synchronized",
347
- "this",
348
- "throw",
349
- "throws",
350
- "transient",
351
- "true",
352
- "try",
353
- "typeof",
354
- "var",
355
- "void",
356
- "volatile",
357
- "while",
358
- "with",
359
- "yield",
360
- "Array",
361
- "Date",
362
- "hasOwnProperty",
363
- "Infinity",
364
- "isFinite",
365
- "isNaN",
366
- "isPrototypeOf",
367
- "length",
368
- "Math",
369
- "name",
370
- "NaN",
371
- "Number",
372
- "Object",
373
- "prototype",
374
- "String",
375
- "toString",
376
- "undefined",
377
- "valueOf"
378
- ]);
379
- /**
380
- * Returns `true` when `name` is a syntactically valid JavaScript variable name.
205
+ * @example Simple node
206
+ * ```ts
207
+ * const importDef = defineNode<ImportNode>({ kind: 'Import' })
208
+ * const createImport = importDef.create
209
+ * ```
381
210
  *
382
- * @example
211
+ * @example Node with a build hook
383
212
  * ```ts
384
- * isValidVarName('status') // true
385
- * isValidVarName('class') // false (reserved word)
386
- * isValidVarName('42foo') // false (starts with digit)
213
+ * const propertyDef = defineNode<PropertyNode, UserPropertyNode>({
214
+ * kind: 'Property',
215
+ * build: (props) => ({ ...props, required: props.required ?? false }),
216
+ * children: ['schema'],
217
+ * visitorKey: 'property',
218
+ * })
387
219
  * ```
388
220
  */
389
- function isValidVarName(name) {
390
- if (!name || reservedWords.has(name)) return false;
391
- return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name);
221
+ function defineNode(config) {
222
+ const { kind, defaults, build, children, visitorKey } = config;
223
+ function create(input) {
224
+ const base = build ? build(input) : input;
225
+ const node = {
226
+ kind,
227
+ ...defaults,
228
+ ...base
229
+ };
230
+ node.kind = kind;
231
+ return node;
232
+ }
233
+ return {
234
+ kind,
235
+ create,
236
+ is: isKind(kind),
237
+ children,
238
+ visitorKey
239
+ };
392
240
  }
393
241
  //#endregion
394
- //#region ../../internals/utils/src/string.ts
242
+ //#region src/nodes/code.ts
395
243
  /**
396
- * Strips the file extension from a path or file name.
397
- * Only removes the last `.ext` segment when the dot is not part of a directory name.
398
- *
399
- * @example
400
- * trimExtName('petStore.ts') // 'petStore'
401
- * trimExtName('/src/models/pet.ts') // '/src/models/pet'
402
- * trimExtName('/project.v2/gen/pet.ts') // '/project.v2/gen/pet'
403
- * trimExtName('noExtension') // 'noExtension'
244
+ * Definition for the {@link ConstNode}.
404
245
  */
405
- function trimExtName(text) {
406
- const dotIndex = text.lastIndexOf(".");
407
- if (dotIndex > 0 && !text.includes("/", dotIndex)) return text.slice(0, dotIndex);
408
- return text;
409
- }
410
- //#endregion
411
- //#region src/guards.ts
246
+ const constDef = defineNode({ kind: "Const" });
412
247
  /**
413
- * Narrows a `SchemaNode` to the variant that matches `type`.
248
+ * Definition for the {@link TypeNode}.
249
+ */
250
+ const typeDef = defineNode({ kind: "Type" });
251
+ /**
252
+ * Definition for the {@link FunctionNode}.
253
+ */
254
+ const functionDef = defineNode({ kind: "Function" });
255
+ /**
256
+ * Definition for the {@link ArrowFunctionNode}.
257
+ */
258
+ const arrowFunctionDef = defineNode({ kind: "ArrowFunction" });
259
+ /**
260
+ * Definition for the {@link TextNode}.
261
+ */
262
+ const textDef = defineNode({
263
+ kind: "Text",
264
+ build: (value) => ({ value })
265
+ });
266
+ /**
267
+ * Definition for the {@link BreakNode}.
268
+ */
269
+ const breakDef = defineNode({
270
+ kind: "Break",
271
+ build: () => ({})
272
+ });
273
+ /**
274
+ * Definition for the {@link JsxNode}.
275
+ */
276
+ const jsxDef = defineNode({
277
+ kind: "Jsx",
278
+ build: (value) => ({ value })
279
+ });
280
+ /**
281
+ * Creates a `ConstNode` representing a TypeScript `const` declaration.
414
282
  *
415
- * @example
283
+ * @example Exported constant with type and `as const`
416
284
  * ```ts
417
- * const schema = createSchema({ type: 'string' })
418
- * const stringNode = narrowSchema(schema, 'string') // StringSchemaNode | undefined
285
+ * createConst({ name: 'pets', export: true, type: 'Pet[]', asConst: true })
286
+ * // export const pets: Pet[] = ... as const
419
287
  * ```
420
288
  */
421
- function narrowSchema(node, type) {
422
- return node?.type === type ? node : void 0;
423
- }
424
- function isKind(kind) {
425
- return (node) => node.kind === kind;
426
- }
289
+ const createConst = constDef.create;
427
290
  /**
428
- * Returns `true` when the input is an `InputNode`.
291
+ * Creates a `TypeNode` representing a TypeScript `type` alias declaration.
429
292
  *
430
293
  * @example
431
294
  * ```ts
432
- * if (isInputNode(node)) {
433
- * console.log(node.schemas.length)
434
- * }
295
+ * createType({ name: 'Pet', export: true })
296
+ * // export type Pet = ...
435
297
  * ```
436
298
  */
437
- const isInputNode = isKind("Input");
299
+ const createType = typeDef.create;
438
300
  /**
439
- * Returns `true` when the input is an `OutputNode`.
301
+ * Creates a `FunctionNode` representing a TypeScript `function` declaration.
440
302
  *
441
303
  * @example
442
304
  * ```ts
443
- * if (isOutputNode(node)) {
444
- * console.log(node.files.length)
445
- * }
305
+ * createFunction({ name: 'fetchPet', export: true, async: true, returnType: 'Pet' })
306
+ * // export async function fetchPet(): Promise<Pet> { ... }
446
307
  * ```
447
308
  */
448
- const isOutputNode = isKind("Output");
309
+ const createFunction = functionDef.create;
449
310
  /**
450
- * Returns `true` when the input is an `OperationNode`.
311
+ * Creates an `ArrowFunctionNode` representing a TypeScript arrow function.
451
312
  *
452
313
  * @example
453
314
  * ```ts
454
- * if (isOperationNode(node)) {
455
- * console.log(node.operationId)
456
- * }
315
+ * createArrowFunction({ name: 'double', export: true, params: 'n: number', singleLine: true })
316
+ * // export const double = (n: number) => ...
457
317
  * ```
458
318
  */
459
- const isOperationNode = isKind("Operation");
319
+ const createArrowFunction = arrowFunctionDef.create;
460
320
  /**
461
- * Returns `true` when the input is a `SchemaNode`.
321
+ * Creates a {@link TextNode} representing a raw string fragment in the source output.
462
322
  *
463
323
  * @example
464
324
  * ```ts
465
- * if (isSchemaNode(node)) {
466
- * console.log(node.type)
467
- * }
325
+ * createText('return fetch(id)')
326
+ * // { kind: 'Text', value: 'return fetch(id)' }
468
327
  * ```
469
328
  */
470
- const isSchemaNode = isKind("Schema");
471
- //#endregion
472
- //#region src/refs.ts
329
+ const createText = textDef.create;
473
330
  /**
474
- * Returns the last path segment of a reference string.
475
- *
476
- * Example: `#/components/schemas/Pet` becomes `Pet`.
331
+ * Creates a {@link BreakNode} representing a line break in the source output.
477
332
  *
478
333
  * @example
479
334
  * ```ts
480
- * extractRefName('#/components/schemas/Pet') // 'Pet'
335
+ * createBreak()
336
+ * // { kind: 'Break' }
481
337
  * ```
482
338
  */
483
- function extractRefName(ref) {
484
- return ref.split("/").at(-1) ?? ref;
339
+ function createBreak() {
340
+ return breakDef.create();
485
341
  }
486
- //#endregion
487
- //#region src/visitor.ts
488
342
  /**
489
- * Creates a small async concurrency limiter.
490
- *
491
- * At most `concurrency` tasks are in flight at once. Extra tasks are queued.
343
+ * Creates a {@link JsxNode} representing a raw JSX fragment in the source output.
492
344
  *
493
345
  * @example
494
346
  * ```ts
495
- * const limit = createLimit(2)
496
- * for (const task of [taskA, taskB, taskC]) {
497
- * await limit(() => task())
498
- * }
499
- * // only 2 tasks run at the same time
347
+ * createJsx('<>\n <a href={href}>Open</a>\n</>')
348
+ * // { kind: 'Jsx', value: '<>\n <a href={href}>Open</a>\n</>' }
500
349
  * ```
501
350
  */
502
- function createLimit(concurrency) {
503
- let active = 0;
504
- const queue = [];
505
- function next() {
506
- if (active < concurrency && queue.length > 0) {
507
- active++;
508
- queue.shift()();
509
- }
510
- }
511
- return function limit(fn) {
512
- return new Promise((resolve, reject) => {
513
- queue.push(() => {
514
- Promise.resolve(fn()).then(resolve, reject).finally(() => {
515
- active--;
516
- next();
517
- });
518
- });
519
- next();
520
- });
521
- };
351
+ const createJsx = jsxDef.create;
352
+ //#endregion
353
+ //#region src/nodes/content.ts
354
+ /**
355
+ * Definition for the {@link ContentNode}.
356
+ */
357
+ const contentDef = defineNode({
358
+ kind: "Content",
359
+ children: ["schema"]
360
+ });
361
+ /**
362
+ * Creates a `ContentNode` for a single request-body or response content type.
363
+ */
364
+ const createContent = contentDef.create;
365
+ //#endregion
366
+ //#region ../../internals/utils/src/casing.ts
367
+ /**
368
+ * Shared implementation for camelCase and PascalCase conversion.
369
+ * Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)
370
+ * and capitalizes each word according to `pascal`.
371
+ *
372
+ * When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.
373
+ */
374
+ function toCamelOrPascal(text, pascal) {
375
+ 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) => {
376
+ if (word.length > 1 && word === word.toUpperCase()) return word;
377
+ return (i === 0 && !pascal ? word.charAt(0).toLowerCase() : word.charAt(0).toUpperCase()) + word.slice(1);
378
+ }).join("").replace(/[^a-zA-Z0-9]/g, "");
522
379
  }
523
380
  /**
524
- * Returns the immediate traversable children of `node`.
381
+ * Converts `text` to PascalCase.
525
382
  *
526
- * For `Schema` nodes, children (`properties`, `items`, `members`, and non-boolean
527
- * `additionalProperties`) are only included
528
- * when `recurse` is `true`; shallow mode skips them.
383
+ * @example Word boundaries
384
+ * `pascalCase('hello-world') // 'HelloWorld'`
529
385
  *
530
- * @example
531
- * ```ts
532
- * const children = getChildren(operationNode, true)
533
- * // returns parameters, requestBody schema (if present), and responses
534
- * ```
386
+ * @example With a suffix
387
+ * `pascalCase('tag', { suffix: 'schema' }) // 'TagSchema'`
535
388
  */
536
- function getChildren(node, recurse) {
537
- switch (node.kind) {
538
- case "Input": return [...node.schemas, ...node.operations];
539
- case "Output": return [];
540
- case "Operation": return [
541
- ...node.parameters,
542
- ...node.requestBody?.content?.flatMap((c) => c.schema ? [c.schema] : []) ?? [],
543
- ...node.responses
544
- ];
545
- case "Schema": {
546
- const children = [];
547
- if (!recurse) return [];
548
- if ("properties" in node && node.properties.length > 0) children.push(...node.properties);
549
- if ("items" in node && node.items) children.push(...node.items);
550
- if ("members" in node && node.members) children.push(...node.members);
551
- if ("additionalProperties" in node && node.additionalProperties && node.additionalProperties !== true) children.push(node.additionalProperties);
552
- return children;
553
- }
554
- case "Property": return [node.schema];
555
- case "Parameter": return [node.schema];
556
- case "Response": return node.schema ? [node.schema] : [];
557
- case "FunctionParameter":
558
- case "ParameterGroup":
559
- case "FunctionParameters":
560
- case "Type": return [];
561
- default: return [];
562
- }
389
+ function pascalCase(text, { prefix = "", suffix = "" } = {}) {
390
+ return toCamelOrPascal(`${prefix} ${text} ${suffix}`, true);
563
391
  }
392
+ //#endregion
393
+ //#region ../../internals/utils/src/fs.ts
564
394
  /**
565
- * Depth-first traversal for side effects. Visitor return values are ignored.
566
- * Sibling nodes at each level are visited concurrently up to `options.concurrency`
567
- * (default: `WALK_CONCURRENCY`).
568
- *
569
- * @example
570
- * ```ts
571
- * await walk(root, {
572
- * operation(node) {
573
- * console.log(node.operationId)
574
- * },
575
- * })
576
- * ```
395
+ * Strips the file extension from a path or file name.
396
+ * Only removes the last `.ext` segment when the dot is not part of a directory name.
577
397
  *
578
398
  * @example
579
- * ```ts
580
- * // Visit only the current node
581
- * await walk(root, { depth: 'shallow', root: () => {} })
582
- * ```
399
+ * trimExtName('petStore.ts') // 'petStore'
400
+ * trimExtName('/src/models/pet.ts') // '/src/models/pet'
401
+ * trimExtName('/project.v2/gen/pet.ts') // '/project.v2/gen/pet'
402
+ * trimExtName('noExtension') // 'noExtension'
583
403
  */
584
- async function walk(node, options) {
585
- return _walk(node, options, (options.depth ?? visitorDepths.deep) === visitorDepths.deep, createLimit(options.concurrency ?? 30), void 0);
586
- }
587
- async function _walk(node, visitor, recurse, limit, parent) {
588
- switch (node.kind) {
589
- case "Input":
590
- await limit(() => visitor.input?.(node, { parent }));
591
- break;
592
- case "Output":
593
- await limit(() => visitor.output?.(node, { parent }));
594
- break;
595
- case "Operation":
596
- await limit(() => visitor.operation?.(node, { parent }));
597
- break;
598
- case "Schema":
599
- await limit(() => visitor.schema?.(node, { parent }));
600
- break;
601
- case "Property":
602
- await limit(() => visitor.property?.(node, { parent }));
603
- break;
604
- case "Parameter":
605
- await limit(() => visitor.parameter?.(node, { parent }));
606
- break;
607
- case "Response":
608
- await limit(() => visitor.response?.(node, { parent }));
609
- break;
610
- case "FunctionParameter":
611
- case "ParameterGroup":
612
- case "FunctionParameters": break;
613
- }
614
- const children = getChildren(node, recurse);
615
- for (const child of children) await _walk(child, visitor, recurse, limit, node);
616
- }
617
- function transform(node, options) {
618
- const { depth, parent, ...visitor } = options;
619
- const recurse = (depth ?? visitorDepths.deep) === visitorDepths.deep;
620
- switch (node.kind) {
621
- case "Input": {
622
- let input = node;
623
- const replaced = visitor.input?.(input, { parent });
624
- if (replaced) input = replaced;
625
- return {
626
- ...input,
627
- schemas: input.schemas.map((s) => transform(s, {
628
- ...options,
629
- parent: input
630
- })),
631
- operations: input.operations.map((op) => transform(op, {
632
- ...options,
633
- parent: input
634
- }))
635
- };
636
- }
637
- case "Output": {
638
- let output = node;
639
- const replaced = visitor.output?.(output, { parent });
640
- if (replaced) output = replaced;
641
- return output;
642
- }
643
- case "Operation": {
644
- let op = node;
645
- const replaced = visitor.operation?.(op, { parent });
646
- if (replaced) op = replaced;
647
- return {
648
- ...op,
649
- parameters: op.parameters.map((p) => transform(p, {
650
- ...options,
651
- parent: op
652
- })),
653
- requestBody: op.requestBody ? {
654
- ...op.requestBody,
655
- content: op.requestBody.content?.map((c) => ({
656
- ...c,
657
- schema: c.schema ? transform(c.schema, {
658
- ...options,
659
- parent: op
660
- }) : void 0
661
- }))
662
- } : void 0,
663
- responses: op.responses.map((r) => transform(r, {
664
- ...options,
665
- parent: op
666
- }))
667
- };
668
- }
669
- case "Schema": {
670
- let schema = node;
671
- const replaced = visitor.schema?.(schema, { parent });
672
- if (replaced) schema = replaced;
673
- const childOptions = {
674
- ...options,
675
- parent: schema
676
- };
677
- return {
678
- ...schema,
679
- ..."properties" in schema && recurse ? { properties: schema.properties.map((p) => transform(p, childOptions)) } : {},
680
- ..."items" in schema && recurse ? { items: schema.items?.map((i) => transform(i, childOptions)) } : {},
681
- ..."members" in schema && recurse ? { members: schema.members?.map((m) => transform(m, childOptions)) } : {},
682
- ..."additionalProperties" in schema && recurse && schema.additionalProperties && schema.additionalProperties !== true ? { additionalProperties: transform(schema.additionalProperties, childOptions) } : {}
683
- };
684
- }
685
- case "Property": {
686
- let prop = node;
687
- const replaced = visitor.property?.(prop, { parent });
688
- if (replaced) prop = replaced;
689
- return createProperty({
690
- ...prop,
691
- schema: transform(prop.schema, {
692
- ...options,
693
- parent: prop
694
- })
695
- });
696
- }
697
- case "Parameter": {
698
- let param = node;
699
- const replaced = visitor.parameter?.(param, { parent });
700
- if (replaced) param = replaced;
701
- return createParameter({
702
- ...param,
703
- schema: transform(param.schema, {
704
- ...options,
705
- parent: param
706
- })
707
- });
708
- }
709
- case "Response": {
710
- let response = node;
711
- const replaced = visitor.response?.(response, { parent });
712
- if (replaced) response = replaced;
713
- return {
714
- ...response,
715
- schema: transform(response.schema, {
716
- ...options,
717
- parent: response
718
- })
719
- };
720
- }
721
- case "FunctionParameter":
722
- case "ParameterGroup":
723
- case "FunctionParameters":
724
- case "Type": return node;
725
- default: return node;
726
- }
404
+ function trimExtName(text) {
405
+ const dotIndex = text.lastIndexOf(".");
406
+ if (dotIndex > 0 && !text.includes("/", dotIndex)) return text.slice(0, dotIndex);
407
+ return text;
727
408
  }
409
+ //#endregion
410
+ //#region ../../internals/utils/src/promise.ts
728
411
  /**
729
- * Runs a depth-first synchronous collection pass.
412
+ * Wraps `factory` with a keyed cache backed by the provided store.
730
413
  *
731
- * Non-`undefined` values returned by visitor callbacks are appended to the result.
414
+ * Pass a `WeakMap` for object keys (results are GC-eligible when the key is
415
+ * collected) or a `Map` for primitive keys. For multi-argument functions,
416
+ * nest two `memoize` calls — the outer keyed by the first argument, the
417
+ * inner (created once per outer miss) keyed by the second.
732
418
  *
733
- * @example
419
+ * Because the cache is owned by the caller, it can be shared, inspected, or
420
+ * cleared independently of the memoized function.
421
+ *
422
+ * @example Single WeakMap key
734
423
  * ```ts
735
- * const ids = collect(root, {
736
- * operation(node) {
737
- * return node.operationId
738
- * },
739
- * })
424
+ * const cache = new WeakMap<SchemaNode, Set<string>>()
425
+ * const getRefs = memoize(cache, (node) => collectRefs(node))
740
426
  * ```
741
427
  *
742
- * @example
428
+ * @example Single Map key (primitive)
743
429
  * ```ts
744
- * // Collect from only the current node
745
- * const values = collect(root, { depth: 'shallow', root: () => 'root' })
430
+ * const cache = new Map<string, Resolver>()
431
+ * const getResolver = memoize(cache, (name) => buildResolver(name))
746
432
  * ```
747
- */
748
- function collect(node, options) {
749
- const { depth, parent, ...visitor } = options;
750
- const recurse = (depth ?? visitorDepths.deep) === visitorDepths.deep;
751
- const results = [];
752
- let v;
753
- switch (node.kind) {
754
- case "Input":
755
- v = visitor.input?.(node, { parent });
756
- break;
757
- case "Output":
758
- v = visitor.output?.(node, { parent });
759
- break;
760
- case "Operation":
761
- v = visitor.operation?.(node, { parent });
762
- break;
763
- case "Schema":
764
- v = visitor.schema?.(node, { parent });
765
- break;
766
- case "Property":
767
- v = visitor.property?.(node, { parent });
768
- break;
769
- case "Parameter":
770
- v = visitor.parameter?.(node, { parent });
771
- break;
772
- case "Response":
773
- v = visitor.response?.(node, { parent });
774
- break;
775
- case "FunctionParameter":
776
- case "ParameterGroup":
777
- case "FunctionParameters": break;
778
- }
779
- if (v !== void 0) results.push(v);
780
- for (const child of getChildren(node, recurse)) for (const item of collect(child, {
781
- ...options,
782
- parent: node
783
- })) results.push(item);
784
- return results;
785
- }
786
- //#endregion
787
- //#region src/utils.ts
788
- const plainStringTypes = new Set([
789
- "string",
790
- "uuid",
791
- "email",
792
- "url",
793
- "datetime"
794
- ]);
795
- /**
796
- * Merges a ref node with its resolved schema, giving usage-site fields precedence.
797
- *
798
- * Usage-site fields (`description`, `readOnly`, `nullable`, `deprecated`) on the ref node
799
- * override the same fields in the resolved `node.schema`. Non-ref nodes are returned unchanged.
800
433
  *
801
- * @example
434
+ * @example Two-level (object + primitive)
802
435
  * ```ts
803
- * // Ref with description override
804
- * const ref = createSchema({ type: 'ref', ref: '#/components/schemas/Pet', description: 'A cute pet' })
805
- * const merged = syncSchemaRef(ref) // merges with resolved Pet schema
436
+ * const outer = new WeakMap<Params[], Map<string, Params[]>>()
437
+ * const fn = memoize(outer, (params) => memoize(new Map(), (key) => transform(params, key)))
438
+ * fn(params)('camelcase')
806
439
  * ```
807
440
  */
808
- function syncSchemaRef(node) {
809
- const ref = narrowSchema(node, "ref");
810
- if (!ref) return node;
811
- if (!ref.schema) return node;
812
- const { kind: _kind, type: _type, name: _name, ref: _ref, schema: _schema, ...overrides } = ref;
813
- const definedOverrides = Object.fromEntries(Object.entries(overrides).filter(([, v]) => v !== void 0));
814
- return createSchema({
815
- ...ref.schema,
816
- ...definedOverrides
817
- });
441
+ function memoize(store, factory) {
442
+ return (key) => {
443
+ if (store.has(key)) return store.get(key);
444
+ const value = factory(key);
445
+ store.set(key, value);
446
+ return value;
447
+ };
818
448
  }
449
+ //#endregion
450
+ //#region src/utils/extractStringsFromNodes.ts
819
451
  /**
820
- * Type guard that returns `true` when a schema emits as a plain `string` type.
452
+ * Extracts all string content from a `CodeNode` tree recursively.
821
453
  *
822
- * Covers `string`, `uuid`, `email`, `url`, and `datetime` types. For `date` and `time`
823
- * types, returns `true` only when `representation` is `'string'` rather than `'date'`.
454
+ * Collects text node values, identifier references in string fields (`params`, `generics`, `returnType`, `type`),
455
+ * and nested node content. Used to build the full source string for import filtering.
824
456
  */
825
- function isStringType(node) {
826
- if (plainStringTypes.has(node.type)) return true;
827
- const temporal = narrowSchema(node, "date") ?? narrowSchema(node, "time");
828
- if (temporal) return temporal.representation !== "date";
829
- return false;
830
- }
831
- /**
832
- * Applies casing rules to parameter names and returns a new parameter array.
833
- *
834
- * Use this before passing parameters to schema builders so output property keys match
835
- * the desired casing while preserving `OperationNode.parameters` for other consumers.
836
- * The input array is not mutated. When `casing` is not set, the original array is returned unchanged.
837
- */
838
- function caseParams(params, casing) {
839
- if (!casing) return params;
840
- return params.map((param) => {
841
- const transformed = casing === "camelcase" || !isValidVarName(param.name) ? camelCase(param.name) : param.name;
842
- return {
843
- ...param,
844
- name: transformed
845
- };
846
- });
847
- }
848
- /**
849
- * Creates a single-property object schema used as a discriminator literal.
850
- *
851
- * @example
852
- * ```ts
853
- * createDiscriminantNode({ propertyName: 'type', value: 'dog' })
854
- * // -> { type: 'object', properties: [{ name: 'type', required: true, schema: enum('dog') }] }
855
- * ```
856
- */
857
- function createDiscriminantNode({ propertyName, value }) {
858
- return createSchema({
859
- type: "object",
860
- primitive: "object",
861
- properties: [createProperty({
862
- name: propertyName,
863
- schema: createSchema({
864
- type: "enum",
865
- primitive: "string",
866
- enumValues: [value]
867
- }),
868
- required: true
869
- })]
870
- });
871
- }
872
- function resolveParamsType({ node, param, resolver }) {
873
- if (!resolver) return createParamsType({
874
- variant: "reference",
875
- name: param.schema.primitive ?? "unknown"
876
- });
877
- const individualName = resolver.resolveParamName(node, param);
878
- const groupLocation = param.in === "path" || param.in === "query" || param.in === "header" ? param.in : void 0;
879
- const groupResolvers = {
880
- path: resolver.resolvePathParamsName,
881
- query: resolver.resolveQueryParamsName,
882
- header: resolver.resolveHeaderParamsName
883
- };
884
- const groupName = groupLocation ? groupResolvers[groupLocation].call(resolver, node, param) : void 0;
885
- if (groupName && groupName !== individualName) return createParamsType({
886
- variant: "member",
887
- base: groupName,
888
- key: param.name
889
- });
890
- return createParamsType({
891
- variant: "reference",
892
- name: individualName
893
- });
894
- }
895
- /**
896
- * Converts an `OperationNode` into function parameters for code generation.
897
- *
898
- * Centralizes parameter grouping logic for all plugins. Provide a `resolver` for type name resolution
899
- * and `extraParams` for plugin-specific trailing parameters (e.g., `options` objects).
900
- * Supports three grouping modes: `object` (single destructured param), `inline` (separate params),
901
- * and `inlineSpread` (rest parameter). Use `CreateOperationParamsOptions` to fine-tune output.
902
- */
903
- function createOperationParams(node, options) {
904
- const { paramsType, pathParamsType, paramsCasing, resolver, pathParamsDefault, extraParams = [], paramNames, typeWrapper } = options;
905
- const dataName = paramNames?.data ?? "data";
906
- const paramsName = paramNames?.params ?? "params";
907
- const headersName = paramNames?.headers ?? "headers";
908
- const pathName = paramNames?.path ?? "pathParams";
909
- const wrapType = (type) => createParamsType({
910
- variant: "reference",
911
- name: typeWrapper ? typeWrapper(type) : type
912
- });
913
- const wrapTypeNode = (type) => type.kind === "ParamsType" && type.variant === "reference" ? wrapType(type.name) : type;
914
- const casedParams = caseParams(node.parameters, paramsCasing);
915
- const pathParams = casedParams.filter((p) => p.in === "path");
916
- const queryParams = casedParams.filter((p) => p.in === "query");
917
- const headerParams = casedParams.filter((p) => p.in === "header");
918
- const bodyType = node.requestBody?.content?.[0]?.schema ? wrapType(resolver?.resolveDataName(node) ?? "unknown") : void 0;
919
- const bodyRequired = node.requestBody?.required ?? false;
920
- const queryGroupType = resolver ? resolveGroupType({
921
- node,
922
- params: queryParams,
923
- groupMethod: resolver.resolveQueryParamsName,
924
- resolver
925
- }) : void 0;
926
- const headerGroupType = resolver ? resolveGroupType({
927
- node,
928
- params: headerParams,
929
- groupMethod: resolver.resolveHeaderParamsName,
930
- resolver
931
- }) : void 0;
932
- const params = [];
933
- if (paramsType === "object") {
934
- const children = [
935
- ...pathParams.map((p) => {
936
- const type = resolveParamsType({
937
- node,
938
- param: p,
939
- resolver
940
- });
941
- return createFunctionParameter({
942
- name: p.name,
943
- type: wrapTypeNode(type),
944
- optional: !p.required
945
- });
946
- }),
947
- ...bodyType ? [createFunctionParameter({
948
- name: dataName,
949
- type: bodyType,
950
- optional: !bodyRequired
951
- })] : [],
952
- ...buildGroupParam({
953
- name: paramsName,
954
- node,
955
- params: queryParams,
956
- groupType: queryGroupType,
957
- resolver,
958
- wrapType
959
- }),
960
- ...buildGroupParam({
961
- name: headersName,
962
- node,
963
- params: headerParams,
964
- groupType: headerGroupType,
965
- resolver,
966
- wrapType
967
- })
968
- ];
969
- if (children.length) params.push(createParameterGroup({
970
- properties: children,
971
- default: children.every((c) => c.optional) ? "{}" : void 0
972
- }));
973
- } else {
974
- if (pathParams.length) if (pathParamsType === "inlineSpread") {
975
- const spreadType = resolver?.resolvePathParamsName(node, pathParams[0]) ?? void 0;
976
- params.push(createFunctionParameter({
977
- name: pathName,
978
- type: spreadType ? wrapType(spreadType) : void 0,
979
- rest: true
980
- }));
981
- } else {
982
- const pathChildren = pathParams.map((p) => {
983
- const type = resolveParamsType({
984
- node,
985
- param: p,
986
- resolver
987
- });
988
- return createFunctionParameter({
989
- name: p.name,
990
- type: wrapTypeNode(type),
991
- optional: !p.required
992
- });
993
- });
994
- params.push(createParameterGroup({
995
- properties: pathChildren,
996
- inline: pathParamsType === "inline",
997
- default: pathParamsDefault ?? (pathChildren.every((c) => c.optional) ? "{}" : void 0)
998
- }));
457
+ function extractStringsFromNodes(nodes) {
458
+ if (!nodes?.length) return "";
459
+ const collected = [];
460
+ for (const node of nodes) {
461
+ if (typeof node === "string") {
462
+ if (node) collected.push(node);
463
+ continue;
999
464
  }
1000
- if (bodyType) params.push(createFunctionParameter({
1001
- name: dataName,
1002
- type: bodyType,
1003
- optional: !bodyRequired
1004
- }));
1005
- params.push(...buildGroupParam({
1006
- name: paramsName,
1007
- node,
1008
- params: queryParams,
1009
- groupType: queryGroupType,
1010
- resolver,
1011
- wrapType
1012
- }));
1013
- params.push(...buildGroupParam({
1014
- name: headersName,
1015
- node,
1016
- params: headerParams,
1017
- groupType: headerGroupType,
1018
- resolver,
1019
- wrapType
1020
- }));
465
+ if (node.kind === "Text") {
466
+ if (node.value) collected.push(node.value);
467
+ continue;
468
+ }
469
+ if (node.kind === "Break") continue;
470
+ if (node.kind === "Jsx") {
471
+ if (node.value) collected.push(node.value);
472
+ continue;
473
+ }
474
+ const parts = [];
475
+ if ("params" in node && node.params) parts.push(node.params);
476
+ if ("generics" in node && node.generics) parts.push(Array.isArray(node.generics) ? node.generics.join(", ") : node.generics);
477
+ if ("returnType" in node && node.returnType) parts.push(node.returnType);
478
+ if ("type" in node && typeof node.type === "string") parts.push(node.type);
479
+ const nested = extractStringsFromNodes(node.nodes);
480
+ if (nested) parts.push(nested);
481
+ if (parts.length) collected.push(parts.join("\n"));
1021
482
  }
1022
- params.push(...extraParams);
1023
- return createFunctionParameters({ params });
1024
- }
1025
- /**
1026
- * Builds a single {@link FunctionParameterNode} for a query or header group.
1027
- * Returns an empty array when there are no params to emit.
1028
- *
1029
- * If a pre-resolved `groupType` is provided it emits `name: GroupType`.
1030
- * Otherwise, it builds an inline struct from the individual params.
1031
- */
1032
- function buildGroupParam({ name, node, params, groupType, resolver, wrapType }) {
1033
- if (groupType) return [createFunctionParameter({
1034
- name,
1035
- type: groupType.type.kind === "ParamsType" && groupType.type.variant === "reference" ? wrapType(groupType.type.name) : groupType.type,
1036
- optional: groupType.optional
1037
- })];
1038
- if (params.length) return [createFunctionParameter({
1039
- name,
1040
- type: toStructType({
1041
- node,
1042
- params,
1043
- resolver
1044
- }),
1045
- optional: params.every((p) => !p.required)
1046
- })];
1047
- return [];
1048
- }
1049
- /**
1050
- * Derives a {@link ParamGroupType} from the resolver's group method.
1051
- * Returns `undefined` when the group name equals the individual param name (no real group).
1052
- */
1053
- function resolveGroupType({ node, params, groupMethod, resolver }) {
1054
- if (!params.length) return;
1055
- const firstParam = params[0];
1056
- const groupName = groupMethod.call(resolver, node, firstParam);
1057
- if (groupName === resolver.resolveParamName(node, firstParam)) return;
1058
- const allOptional = params.every((p) => !p.required);
1059
- return {
1060
- type: createParamsType({
1061
- variant: "reference",
1062
- name: groupName
1063
- }),
1064
- optional: allOptional
1065
- };
1066
- }
1067
- /**
1068
- * Builds a {@link TypeNode} with `variant: 'struct'` for an inline anonymous type grouping named fields.
1069
- *
1070
- * Used when query or header parameters have no dedicated group type name.
1071
- * Each language printer renders this appropriately (TypeScript: `{ petId: string; name?: string }`).
1072
- */
1073
- function toStructType({ node, params, resolver }) {
1074
- return createParamsType({
1075
- variant: "struct",
1076
- properties: params.map((p) => ({
1077
- name: p.name,
1078
- optional: !p.required,
1079
- type: resolveParamsType({
1080
- node,
1081
- param: p,
1082
- resolver
1083
- })
1084
- }))
1085
- });
483
+ return collected.join("\n");
1086
484
  }
485
+ //#endregion
486
+ //#region src/utils/combineFileMembers.ts
1087
487
  function sourceKey(source) {
1088
488
  return `${source.name ?? extractStringsFromNodes(source.nodes)}:${source.isExportable ?? false}:${source.isTypeOnly ?? false}`;
1089
489
  }
@@ -1098,19 +498,19 @@ function importKey(path, name, isTypeOnly) {
1098
498
  }
1099
499
  /**
1100
500
  * Computes a multi-level sort key for exports and imports:
1101
- * non-array names first (wildcards/namespace aliases); type-only before value; alphabetical path; unnamed before named.
501
+ * non-array names first (wildcards/namespace aliases). Type-only before value. Alphabetical path. Unnamed before named.
1102
502
  */
1103
503
  function sortKey(node) {
1104
504
  const isArray = Array.isArray(node.name) ? "1" : "0";
1105
505
  const typeOnly = node.isTypeOnly ? "0" : "1";
1106
506
  const hasName = node.name != null ? "1" : "0";
1107
- const name = Array.isArray(node.name) ? [...node.name].sort().join("\0") : node.name ?? "";
507
+ const name = Array.isArray(node.name) ? node.name.toSorted().join("\0") : node.name ?? "";
1108
508
  return `${isArray}:${typeOnly}:${node.path}:${hasName}:${name}`;
1109
509
  }
1110
510
  /**
1111
- * Deduplicates and merges `SourceNode` objects by `name + isExportable + isTypeOnly`.
1112
- *
1113
- * Unnamed sources are deduplicated by object reference. Returns a deduplicated array in original order.
511
+ * Deduplicates `SourceNode` objects by `name + isExportable + isTypeOnly`, keeping the first of each
512
+ * key. Unnamed sources fall back to their extracted node strings as the name part of the key. Returns
513
+ * the deduplicated array in original order.
1114
514
  */
1115
515
  function combineSources(sources) {
1116
516
  const seen = /* @__PURE__ */ new Map();
@@ -1121,6 +521,16 @@ function combineSources(sources) {
1121
521
  return [...seen.values()];
1122
522
  }
1123
523
  /**
524
+ * Merges `incoming` names into `existing`, preserving order and dropping duplicates.
525
+ *
526
+ * Shared by `combineExports` and `combineImports` for the same-path name-merge case.
527
+ */
528
+ function mergeNameArrays(existing, incoming) {
529
+ const merged = new Set(existing);
530
+ for (const name of incoming) merged.add(name);
531
+ return [...merged];
532
+ }
533
+ /**
1124
534
  * Deduplicates and merges `ExportNode` objects by path and type.
1125
535
  *
1126
536
  * Named exports with the same path and `isTypeOnly` flag have their names merged into a single export.
@@ -1141,11 +551,8 @@ function combineExports(exports) {
1141
551
  if (!name.length) continue;
1142
552
  const key = pathTypeKey(path, isTypeOnly);
1143
553
  const existing = namedByPath.get(key);
1144
- if (existing && Array.isArray(existing.name)) {
1145
- const merged = new Set(existing.name);
1146
- for (const n of name) merged.add(n);
1147
- existing.name = [...merged];
1148
- } else {
554
+ if (existing && Array.isArray(existing.name)) existing.name = mergeNameArrays(existing.name, name);
555
+ else {
1149
556
  const newItem = {
1150
557
  ...curr,
1151
558
  name: [...new Set(name)]
@@ -1168,8 +575,6 @@ function combineExports(exports) {
1168
575
  *
1169
576
  * Retains imports that are referenced in `source` or re-exported. Imports with the same path and
1170
577
  * `isTypeOnly` flag have their names merged. Returns a sorted, deduplicated, filtered array.
1171
- *
1172
- * @note Use this when combining imports from multiple files to avoid duplicate declarations.
1173
578
  */
1174
579
  function combineImports(imports, exports, source) {
1175
580
  const exportedNames = new Set(exports.flatMap((e) => Array.isArray(e.name) ? e.name : e.name ? [e.name] : []));
@@ -1181,6 +586,11 @@ function combineImports(imports, exports, source) {
1181
586
  if (!importNameMemo.has(key)) importNameMemo.set(key, n);
1182
587
  return importNameMemo.get(key);
1183
588
  };
589
+ const pathsWithUsedNamedImport = /* @__PURE__ */ new Set();
590
+ for (const node of imports) {
591
+ if (!Array.isArray(node.name)) continue;
592
+ if (node.name.some((item) => typeof item === "string" ? isUsed(item) : isUsed(item.name ?? item.propertyName))) pathsWithUsedNamedImport.add(node.path);
593
+ }
1184
594
  const result = [];
1185
595
  const namedByPath = /* @__PURE__ */ new Map();
1186
596
  const seen = /* @__PURE__ */ new Set();
@@ -1198,11 +608,8 @@ function combineImports(imports, exports, source) {
1198
608
  if (!name.length) continue;
1199
609
  const key = pathTypeKey(path, isTypeOnly);
1200
610
  const existing = namedByPath.get(key);
1201
- if (existing && Array.isArray(existing.name)) {
1202
- const merged = new Set(existing.name);
1203
- for (const n of name) merged.add(n);
1204
- existing.name = [...merged];
1205
- } else {
611
+ if (existing && Array.isArray(existing.name)) existing.name = mergeNameArrays(existing.name, name);
612
+ else {
1206
613
  const newItem = {
1207
614
  ...curr,
1208
615
  name
@@ -1211,7 +618,7 @@ function combineImports(imports, exports, source) {
1211
618
  namedByPath.set(key, newItem);
1212
619
  }
1213
620
  } else {
1214
- if (name && !isUsed(name)) continue;
621
+ if (name && !isUsed(name) && !pathsWithUsedNamedImport.has(path)) continue;
1215
622
  const key = importKey(path, name, isTypeOnly);
1216
623
  if (!seen.has(key)) {
1217
624
  result.push(curr);
@@ -1221,210 +628,218 @@ function combineImports(imports, exports, source) {
1221
628
  }
1222
629
  return result;
1223
630
  }
631
+ //#endregion
632
+ //#region src/nodes/file.ts
1224
633
  /**
1225
- * Extracts all string content from a `CodeNode` tree recursively.
1226
- *
1227
- * Collects text node values, identifier references in string fields (`params`, `generics`, `returnType`, `type`),
1228
- * and nested node content. Used internally to build the full source string for import filtering.
634
+ * Definition for the {@link ImportNode}.
1229
635
  */
1230
- function extractStringsFromNodes(nodes) {
1231
- if (!nodes?.length) return "";
1232
- return nodes.map((node) => {
1233
- if (typeof node === "string") return node;
1234
- if (node.kind === "Text") return node.value;
1235
- if (node.kind === "Break") return "";
1236
- if (node.kind === "Jsx") return node.value;
1237
- const parts = [];
1238
- if ("params" in node && node.params) parts.push(node.params);
1239
- if ("generics" in node && node.generics) parts.push(Array.isArray(node.generics) ? node.generics.join(", ") : node.generics);
1240
- if ("returnType" in node && node.returnType) parts.push(node.returnType);
1241
- if ("type" in node && typeof node.type === "string") parts.push(node.type);
1242
- const nested = extractStringsFromNodes(node.nodes);
1243
- if (nested) parts.push(nested);
1244
- return parts.join("\n");
1245
- }).filter(Boolean).join("\n");
1246
- }
636
+ const importDef = defineNode({ kind: "Import" });
1247
637
  /**
1248
- * Resolves the schema name of a ref node, falling back through `ref` → `name` → nested `schema.name`.
1249
- *
1250
- * Returns `undefined` for non-ref nodes or when no name can be resolved. Use this to get a schema's
1251
- * identifier for type definitions or error messages.
638
+ * Definition for the {@link ExportNode}.
639
+ */
640
+ const exportDef = defineNode({ kind: "Export" });
641
+ /**
642
+ * Definition for the {@link SourceNode}.
643
+ */
644
+ const sourceDef = defineNode({ kind: "Source" });
645
+ /**
646
+ * Definition for the {@link FileNode}. The fully resolved builder lives in
647
+ * `createFile`, so this definition only supplies the guard.
648
+ */
649
+ const fileDef = defineNode({ kind: "File" });
650
+ /**
651
+ * Creates an `ImportNode` representing a language-agnostic import/dependency declaration.
1252
652
  *
1253
- * @example
653
+ * @example Named import
1254
654
  * ```ts
1255
- * resolveRefName({ kind: 'Schema', type: 'ref', ref: '#/components/schemas/Pet' })
1256
- * // => 'Pet'
655
+ * createImport({ name: ['useState'], path: 'react' })
656
+ * // import { useState } from 'react'
1257
657
  * ```
1258
658
  */
1259
- function resolveRefName(node) {
1260
- if (!node || node.type !== "ref") return void 0;
1261
- if (node.ref) return extractRefName(node.ref) ?? node.name ?? node.schema?.name ?? void 0;
1262
- return node.name ?? node.schema?.name ?? void 0;
1263
- }
659
+ const createImport = importDef.create;
1264
660
  /**
1265
- * Collects every named schema referenced (transitively) from a node via ref edges.
1266
- *
1267
- * Refs are followed by name only — the resolved `node.schema` is not traversed inline.
1268
- * Use this to determine schema dependencies, build reference graphs, or detect what schemas need to be emitted.
661
+ * Creates an `ExportNode` representing a language-agnostic export/public API declaration.
1269
662
  *
1270
- * @example Collect refs from a single schema
663
+ * @example Named export
1271
664
  * ```ts
1272
- * const names = collectReferencedSchemaNames(petSchema)
1273
- * // Set { 'Category', 'Tag' }
665
+ * createExport({ name: ['Pet'], path: './Pet' })
666
+ * // export { Pet } from './Pet'
1274
667
  * ```
668
+ */
669
+ const createExport = exportDef.create;
670
+ /**
671
+ * Creates a `SourceNode` representing a fragment of source code within a file.
1275
672
  *
1276
- * @example Accumulate refs from multiple schemas into one set
673
+ * @example
1277
674
  * ```ts
1278
- * const out = new Set<string>()
1279
- * for (const schema of schemas) {
1280
- * collectReferencedSchemaNames(schema, out)
1281
- * }
675
+ * createSource({ name: 'Pet', nodes: [createText('export type Pet = { id: number }')], isExportable: true })
1282
676
  * ```
1283
677
  */
1284
- function collectReferencedSchemaNames(node, out = /* @__PURE__ */ new Set()) {
1285
- if (!node) return out;
1286
- collect(node, { schema(child) {
1287
- if (child.type === "ref") {
1288
- const name = resolveRefName(child);
1289
- if (name) out.add(name);
1290
- }
1291
- } });
1292
- return out;
1293
- }
678
+ const createSource = sourceDef.create;
1294
679
  /**
1295
- * Collects the names of all top-level schemas transitively used by a set of operations.
680
+ * Creates a fully resolved `FileNode` from a file input descriptor.
1296
681
  *
1297
- * An operation uses a schema when any of its parameters, request body content, or responses
1298
- * reference it directly or indirectly through other named schemas.
1299
- * The walk is iterative and safe against reference cycles.
682
+ * Computes:
683
+ * - `id` SHA256 hash of the file path
684
+ * - `name` `baseName` without extension
685
+ * - `extname` extension extracted from `baseName`
1300
686
  *
1301
- * Use this together with `include` filters to determine which schemas from `components/schemas`
1302
- * are reachable from the allowed operations, so that schemas used only by excluded operations
1303
- * are not generated.
687
+ * Deduplicates:
688
+ * - `sources` via `combineSources`
689
+ * - `exports` via `combineExports`
690
+ * - `imports` via `combineImports` (also filters unused imports)
1304
691
  *
1305
- * @example Only generate schemas referenced by included operations
1306
- * ```ts
1307
- * const includedOps = inputNode.operations.filter(op => resolver.resolveOptions(op, { options, include }) !== null)
1308
- * const allowed = collectUsedSchemaNames(includedOps, inputNode.schemas)
692
+ * @throws {Error} when `baseName` has no extension.
1309
693
  *
1310
- * for (const schema of inputNode.schemas) {
1311
- * if (schema.name && !allowed.has(schema.name)) continue
1312
- * // generate schema
1313
- * }
694
+ * @example
695
+ * ```ts
696
+ * const file = createFile({
697
+ * baseName: 'petStore.ts',
698
+ * path: 'src/models/petStore.ts',
699
+ * sources: [createSource({ name: 'Pet', nodes: [createText('export type Pet = { id: number }')] })],
700
+ * imports: [createImport({ name: ['z'], path: 'zod' })],
701
+ * exports: [createExport({ name: ['Pet'], path: './petStore' })],
702
+ * })
703
+ * // file.id = SHA256 hash of 'src/models/petStore.ts'
704
+ * // file.name = 'petStore'
705
+ * // file.extname = '.ts'
1314
706
  * ```
1315
707
  *
1316
- * @example Check whether a specific schema is needed
708
+ * @example Copy a real file into the output verbatim
1317
709
  * ```ts
1318
- * const allowed = collectUsedSchemaNames(includedOps, inputNode.schemas)
1319
- * allowed.has('OrderStatus') // false when no included operation references OrderStatus
710
+ * const file = createFile({
711
+ * baseName: 'client.ts',
712
+ * path: 'src/gen/client.ts',
713
+ * copy: '/abs/path/to/templates/client.ts',
714
+ * })
1320
715
  * ```
1321
716
  */
1322
- function collectUsedSchemaNames(operations, schemas) {
1323
- const schemaMap = /* @__PURE__ */ new Map();
1324
- for (const schema of schemas) if (schema.name) schemaMap.set(schema.name, schema);
1325
- const result = /* @__PURE__ */ new Set();
1326
- function visitSchema(schema) {
1327
- const directRefs = collectReferencedSchemaNames(schema);
1328
- for (const name of directRefs) if (!result.has(name)) {
1329
- result.add(name);
1330
- const namedSchema = schemaMap.get(name);
1331
- if (namedSchema) visitSchema(namedSchema);
1332
- }
1333
- }
1334
- for (const op of operations) for (const schema of collect(op, {
1335
- depth: "shallow",
1336
- schema: (node) => node
1337
- })) visitSchema(schema);
1338
- return result;
1339
- }
1340
- /**
1341
- * Identifies all schemas that participate in circular dependency chains, including direct self-loops.
1342
- *
1343
- * Returns a Set of schema names with circular dependencies. Use this to wrap recursive schema positions
1344
- * in deferred constructs (lazy getter, `z.lazy(() => …)`) to prevent infinite recursion when generated code runs.
1345
- * Refs are followed by name only, keeping the algorithm linear in the schema graph size.
1346
- *
1347
- * @note Call this once on the full schema graph, then use `containsCircularRef()` to check individual schemas.
1348
- */
1349
- function findCircularSchemas(schemas) {
1350
- const graph = /* @__PURE__ */ new Map();
1351
- for (const schema of schemas) {
1352
- if (!schema.name) continue;
1353
- graph.set(schema.name, collectReferencedSchemaNames(schema));
1354
- }
1355
- const circular = /* @__PURE__ */ new Set();
1356
- for (const start of graph.keys()) {
1357
- const visited = /* @__PURE__ */ new Set();
1358
- const stack = [...graph.get(start) ?? []];
1359
- while (stack.length > 0) {
1360
- const node = stack.pop();
1361
- if (node === start) {
1362
- circular.add(start);
1363
- break;
1364
- }
1365
- if (visited.has(node)) continue;
1366
- visited.add(node);
1367
- const next = graph.get(node);
1368
- if (next) for (const r of next) stack.push(r);
717
+ function createFile(input) {
718
+ const extname = node_path.default.extname(input.baseName);
719
+ if (!extname) throw new Error(`No extname found for ${input.baseName}`);
720
+ const resolvedExports = input.exports?.length ? combineExports(input.exports) : [];
721
+ const resolvedImports = (() => {
722
+ if (!input.imports?.length) return [];
723
+ const sourceParts = [];
724
+ const localNames = /* @__PURE__ */ new Set();
725
+ for (const item of input.sources ?? []) {
726
+ const extracted = item.nodes && extractStringsFromNodes(item.nodes);
727
+ if (extracted) sourceParts.push(extracted);
728
+ if (item.name) localNames.add(item.name);
1369
729
  }
1370
- }
1371
- return circular;
1372
- }
1373
- /**
1374
- * Type guard returning `true` when a schema or anything nested within it contains a ref to a circular schema.
1375
- *
1376
- * Use `excludeName` to ignore refs to specific schemas (useful when self-references are handled separately).
1377
- * Commonly used with `findCircularSchemas()` to detect where lazy wrappers are needed in code generation.
1378
- *
1379
- * @note Returns `true` for the first matching circular ref found; use for fast dependency checks.
1380
- */
1381
- function containsCircularRef(node, { circularSchemas, excludeName }) {
1382
- if (!node || circularSchemas.size === 0) return false;
1383
- return collect(node, { schema(child) {
1384
- if (child.type !== "ref") return void 0;
1385
- const name = resolveRefName(child);
1386
- return name && name !== excludeName && circularSchemas.has(name) ? true : void 0;
1387
- } }).length > 0;
730
+ const source = sourceParts.join("\n") || void 0;
731
+ const combinedImports = combineImports(input.imports, resolvedExports, source);
732
+ const nameOf = (item) => typeof item === "string" ? item : item.name ?? item.propertyName;
733
+ return combinedImports.flatMap((imp) => {
734
+ if (imp.path === input.path) return [];
735
+ if (!Array.isArray(imp.name)) return typeof imp.name === "string" && localNames.has(imp.name) ? [] : [imp];
736
+ const kept = imp.name.filter((item) => !localNames.has(nameOf(item)));
737
+ if (!kept.length) return [];
738
+ return [kept.length === imp.name.length ? imp : {
739
+ ...imp,
740
+ name: kept
741
+ }];
742
+ });
743
+ })();
744
+ const resolvedSources = input.sources?.length ? combineSources(input.sources) : [];
745
+ return {
746
+ kind: "File",
747
+ ...input,
748
+ id: (0, node_crypto.hash)("sha256", input.path, "hex"),
749
+ name: trimExtName(input.baseName),
750
+ extname,
751
+ imports: resolvedImports,
752
+ exports: resolvedExports,
753
+ sources: resolvedSources,
754
+ meta: input.meta ?? {}
755
+ };
1388
756
  }
1389
757
  //#endregion
1390
- //#region src/factory.ts
758
+ //#region src/nodes/input.ts
1391
759
  /**
1392
- * Syncs property/parameter schema optionality flags from `required` and `schema.nullable`.
1393
- *
1394
- * - `optional` is set for non-required, non-nullable schemas.
1395
- * - `nullish` is set for non-required, nullable schemas.
760
+ * Definition for the {@link InputNode}.
1396
761
  */
1397
- function syncOptionality(schema, required) {
1398
- const nullable = schema.nullable ?? false;
1399
- return {
1400
- ...schema,
1401
- optional: !required && !nullable ? true : void 0,
1402
- nullish: !required && nullable ? true : void 0
1403
- };
1404
- }
762
+ const inputDef = defineNode({
763
+ kind: "Input",
764
+ defaults: {
765
+ schemas: [],
766
+ operations: [],
767
+ meta: {
768
+ circularNames: [],
769
+ enumNames: []
770
+ }
771
+ },
772
+ children: ["schemas", "operations"],
773
+ visitorKey: "input"
774
+ });
1405
775
  /**
1406
- * Creates an `InputNode` with stable defaults for `schemas` and `operations`.
776
+ * Creates an `InputNode`, defaulting `schemas`/`operations` to empty arrays and `meta` per
777
+ * {@link inputDef}.
1407
778
  *
1408
779
  * @example
1409
780
  * ```ts
1410
781
  * const input = createInput()
1411
782
  * // { kind: 'Input', schemas: [], operations: [] }
1412
783
  * ```
1413
- *
1414
- * @example
1415
- * ```ts
1416
- * const input = createInput({ schemas: [petSchema] })
1417
- * // keeps default operations: []
1418
- * ```
1419
784
  */
1420
785
  function createInput(overrides = {}) {
1421
- return {
1422
- schemas: [],
1423
- operations: [],
1424
- ...overrides,
1425
- kind: "Input"
1426
- };
786
+ return inputDef.create(overrides);
787
+ }
788
+ //#endregion
789
+ //#region src/nodes/requestBody.ts
790
+ /**
791
+ * Definition for the {@link RequestBodyNode}. Content entries are built upfront with
792
+ * {@link createContent}, mirroring how `parameters` and `responses` take prebuilt nodes.
793
+ */
794
+ const requestBodyDef = defineNode({
795
+ kind: "RequestBody",
796
+ children: ["content"]
797
+ });
798
+ /**
799
+ * Creates a `RequestBodyNode`.
800
+ */
801
+ const createRequestBody = requestBodyDef.create;
802
+ //#endregion
803
+ //#region src/nodes/operation.ts
804
+ /**
805
+ * Definition for the {@link OperationNode}. HTTP operations (those carrying both
806
+ * `method` and `path`) are tagged with `protocol: 'http'`, and the request body is
807
+ * normalized into a `RequestBodyNode`.
808
+ */
809
+ const operationDef = defineNode({
810
+ kind: "Operation",
811
+ build: (props) => {
812
+ const { requestBody, ...rest } = props;
813
+ const isHttp = rest.method !== void 0 && rest.path !== void 0;
814
+ return {
815
+ tags: [],
816
+ parameters: [],
817
+ responses: [],
818
+ ...rest,
819
+ ...isHttp ? { protocol: "http" } : {},
820
+ requestBody: requestBody ? createRequestBody(requestBody) : void 0
821
+ };
822
+ },
823
+ children: [
824
+ "parameters",
825
+ "requestBody",
826
+ "responses"
827
+ ],
828
+ visitorKey: "operation"
829
+ });
830
+ function createOperation(props) {
831
+ return operationDef.create(props);
1427
832
  }
833
+ //#endregion
834
+ //#region src/nodes/output.ts
835
+ /**
836
+ * Definition for the {@link OutputNode}.
837
+ */
838
+ const outputDef = defineNode({
839
+ kind: "Output",
840
+ defaults: { files: [] },
841
+ visitorKey: "output"
842
+ });
1428
843
  /**
1429
844
  * Creates an `OutputNode` with a stable default for `files`.
1430
845
  *
@@ -1433,55 +848,131 @@ function createInput(overrides = {}) {
1433
848
  * const output = createOutput()
1434
849
  * // { kind: 'Output', files: [] }
1435
850
  * ```
1436
- *
1437
- * @example
1438
- * ```ts
1439
- * const output = createOutput({ files: [petFile] })
1440
- * ```
1441
851
  */
1442
852
  function createOutput(overrides = {}) {
853
+ return outputDef.create(overrides);
854
+ }
855
+ //#endregion
856
+ //#region src/optionality.ts
857
+ /**
858
+ * Generic JSON Schema optionality: a non-required field is optional, and a
859
+ * non-required nullable field is nullish.
860
+ */
861
+ function optionality(schema, required) {
862
+ const nullable = schema.nullable ?? false;
1443
863
  return {
1444
- files: [],
1445
- ...overrides,
1446
- kind: "Output"
864
+ ...schema,
865
+ optional: !required && !nullable ? true : void 0,
866
+ nullish: !required && nullable ? true : void 0
1447
867
  };
1448
868
  }
869
+ //#endregion
870
+ //#region src/nodes/parameter.ts
1449
871
  /**
1450
- * Creates an `OperationNode` with default empty arrays for `tags`, `parameters`, and `responses`.
872
+ * Definition for the {@link ParameterNode}. `required` defaults to `false`, and the schema's
873
+ * `optional`/`nullish` flags are derived from it through {@link optionality}.
874
+ */
875
+ const parameterDef = defineNode({
876
+ kind: "Parameter",
877
+ build: (props) => {
878
+ const required = props.required ?? false;
879
+ return {
880
+ ...props,
881
+ required,
882
+ schema: optionality(props.schema, required)
883
+ };
884
+ },
885
+ children: ["schema"],
886
+ visitorKey: "parameter"
887
+ });
888
+ /**
889
+ * Creates a `ParameterNode`.
1451
890
  *
1452
891
  * @example
1453
892
  * ```ts
1454
- * const operation = createOperation({
1455
- * operationId: 'getPetById',
1456
- * method: 'GET',
1457
- * path: '/pet/{petId}',
893
+ * const param = createParameter({
894
+ * name: 'petId',
895
+ * in: 'path',
896
+ * required: true,
897
+ * schema: createSchema({ type: 'string' }),
1458
898
  * })
1459
- * // tags, parameters, and responses are []
1460
899
  * ```
900
+ */
901
+ const createParameter = parameterDef.create;
902
+ //#endregion
903
+ //#region src/nodes/property.ts
904
+ /**
905
+ * Definition for the {@link PropertyNode}. `required` defaults to `false`, and the schema's
906
+ * `optional`/`nullish` flags are derived from it through {@link optionality}.
907
+ */
908
+ const propertyDef = defineNode({
909
+ kind: "Property",
910
+ build: (props) => {
911
+ const required = props.required ?? false;
912
+ return {
913
+ ...props,
914
+ required,
915
+ schema: optionality(props.schema, required)
916
+ };
917
+ },
918
+ children: ["schema"],
919
+ visitorKey: "property"
920
+ });
921
+ /**
922
+ * Creates a `PropertyNode`.
1461
923
  *
1462
924
  * @example
1463
925
  * ```ts
1464
- * const operation = createOperation({
1465
- * operationId: 'findPets',
1466
- * method: 'GET',
1467
- * path: '/pet/findByStatus',
1468
- * tags: ['pet'],
926
+ * const property = createProperty({
927
+ * name: 'status',
928
+ * required: true,
929
+ * schema: createSchema({ type: 'string', nullable: true }),
1469
930
  * })
931
+ * // required=true, no optional/nullish
1470
932
  * ```
1471
933
  */
1472
- function createOperation(props) {
1473
- return {
1474
- tags: [],
1475
- parameters: [],
1476
- responses: [],
1477
- ...props,
1478
- kind: "Operation"
1479
- };
1480
- }
934
+ const createProperty = propertyDef.create;
935
+ //#endregion
936
+ //#region src/nodes/response.ts
937
+ /**
938
+ * Definition for the {@link ResponseNode}. A single legacy `schema` (with optional
939
+ * `mediaType`/`keysToOmit`) is normalized into one `content` entry.
940
+ */
941
+ const responseDef = defineNode({
942
+ kind: "Response",
943
+ build: (props) => {
944
+ const { schema, mediaType, keysToOmit, content, ...rest } = props;
945
+ const entries = content ?? (schema ? [createContent({
946
+ contentType: mediaType ?? "application/json",
947
+ schema,
948
+ keysToOmit: keysToOmit ?? null
949
+ })] : void 0);
950
+ return {
951
+ ...rest,
952
+ content: entries
953
+ };
954
+ },
955
+ children: ["content"],
956
+ visitorKey: "response"
957
+ });
958
+ /**
959
+ * Creates a `ResponseNode`.
960
+ *
961
+ * @example
962
+ * ```ts
963
+ * const response = createResponse({
964
+ * statusCode: '200',
965
+ * content: [createContent({ contentType: 'application/json', schema: createSchema({ type: 'object', properties: [] }) })],
966
+ * })
967
+ * ```
968
+ */
969
+ const createResponse = responseDef.create;
970
+ //#endregion
971
+ //#region src/nodes/schema.ts
1481
972
  /**
1482
973
  * Maps schema `type` to its underlying `primitive`.
1483
- * Primitive types map to themselves; special string formats map to `'string'`.
1484
- * Complex types (`ref`, `enum`, `union`, `intersection`, `tuple`, `blob`) are left unset.
974
+ * Primitive types map to themselves and special string formats map to `'string'`.
975
+ * Any type not listed here (such as `ref`, `enum`, `union`, `intersection`, `tuple`, `ipv4`, `ipv6`, `blob`) has no `primitive`.
1485
976
  */
1486
977
  const TYPE_TO_PRIMITIVE = {
1487
978
  string: "string",
@@ -1503,692 +994,763 @@ const TYPE_TO_PRIMITIVE = {
1503
994
  datetime: "string",
1504
995
  time: "string"
1505
996
  };
997
+ /**
998
+ * Definition for the {@link SchemaNode}. Object schemas default `properties` to an
999
+ * empty array, and `primitive` is inferred from `type` when not explicitly provided.
1000
+ */
1001
+ const schemaDef = defineNode({
1002
+ kind: "Schema",
1003
+ build: (props) => {
1004
+ if (props.type === "object") return {
1005
+ properties: [],
1006
+ primitive: "object",
1007
+ ...props
1008
+ };
1009
+ return {
1010
+ primitive: TYPE_TO_PRIMITIVE[props.type],
1011
+ ...props
1012
+ };
1013
+ },
1014
+ children: [
1015
+ "properties",
1016
+ "items",
1017
+ "members",
1018
+ "additionalProperties"
1019
+ ],
1020
+ visitorKey: "schema"
1021
+ });
1506
1022
  function createSchema(props) {
1507
- const inferredPrimitive = TYPE_TO_PRIMITIVE[props.type];
1508
- if (props["type"] === "object") return {
1509
- properties: [],
1510
- primitive: "object",
1511
- ...props,
1512
- kind: "Schema"
1513
- };
1514
- return {
1515
- primitive: inferredPrimitive,
1516
- ...props,
1517
- kind: "Schema"
1518
- };
1023
+ return schemaDef.create(props);
1519
1024
  }
1025
+ //#endregion
1026
+ //#region src/registry.ts
1027
+ /**
1028
+ * Every node definition. Adding a node means adding its `defineNode` to one
1029
+ * `nodes/*.ts` file and listing it here. The visitor tables in `visitor.ts` derive from it.
1030
+ */
1031
+ const nodeDefs = [
1032
+ inputDef,
1033
+ outputDef,
1034
+ operationDef,
1035
+ requestBodyDef,
1036
+ contentDef,
1037
+ responseDef,
1038
+ schemaDef,
1039
+ propertyDef,
1040
+ parameterDef,
1041
+ constDef,
1042
+ typeDef,
1043
+ functionDef,
1044
+ arrowFunctionDef,
1045
+ textDef,
1046
+ breakDef,
1047
+ jsxDef,
1048
+ importDef,
1049
+ exportDef,
1050
+ sourceDef,
1051
+ fileDef
1052
+ ];
1053
+ //#endregion
1054
+ //#region src/visitor.ts
1520
1055
  /**
1521
- * Creates a `PropertyNode`.
1056
+ * Child node fields per node kind, in traversal order (Babel's `VISITOR_KEYS`).
1057
+ * Derived from each definition's `children`.
1058
+ */
1059
+ const VISITOR_KEYS = Object.fromEntries(nodeDefs.flatMap((def) => def.children ? [[def.kind, def.children]] : []));
1060
+ /**
1061
+ * Maps a node kind to the matching visitor callback name. Derived from each
1062
+ * definition's `visitorKey`.
1063
+ */
1064
+ const VISITOR_KEY_BY_KIND = Object.fromEntries(nodeDefs.flatMap((def) => def.visitorKey ? [[def.kind, def.visitorKey]] : []));
1065
+ const visitorKeysByKind = VISITOR_KEYS;
1066
+ /**
1067
+ * Returns `true` when `value` is an AST node (an object carrying a `kind`).
1068
+ */
1069
+ function isNode(value) {
1070
+ return typeof value === "object" && value !== null && typeof value.kind === "string";
1071
+ }
1072
+ /**
1073
+ * Returns the immediate traversable children of `node` based on {@link VISITOR_KEYS}.
1522
1074
  *
1523
- * `required` defaults to `false`.
1524
- * `schema.optional` and `schema.nullish` are derived from `required` and `schema.nullable`.
1075
+ * `Schema` children are only included when `recurse` is `true`. Shallow mode skips them.
1525
1076
  *
1526
1077
  * @example
1527
1078
  * ```ts
1528
- * const property = createProperty({
1529
- * name: 'status',
1530
- * schema: createSchema({ type: 'string' }),
1531
- * })
1532
- * // required=false, schema.optional=true
1533
- * ```
1079
+ * const children = getChildren(operationNode, true)
1080
+ * // returns parameters, the request body, and responses
1081
+ * ```
1082
+ */
1083
+ function* getChildren(node, recurse) {
1084
+ if (node.kind === "Schema" && !recurse) return;
1085
+ const keys = visitorKeysByKind[node.kind];
1086
+ if (!keys) return;
1087
+ const record = node;
1088
+ for (const key of keys) {
1089
+ const value = record[key];
1090
+ if (Array.isArray(value)) {
1091
+ for (const item of value) if (isNode(item)) yield item;
1092
+ } else if (isNode(value)) yield value;
1093
+ }
1094
+ }
1095
+ /**
1096
+ * Runs the visitor callback that matches `node.kind` with the traversal
1097
+ * context. The result is a replacement node, a collected value, or `undefined`
1098
+ * when no callback is registered for the kind.
1534
1099
  *
1535
- * @example
1536
- * ```ts
1537
- * const property = createProperty({
1538
- * name: 'status',
1539
- * required: true,
1540
- * schema: createSchema({ type: 'string', nullable: true }),
1541
- * })
1542
- * // required=true, no optional/nullish
1543
- * ```
1100
+ * Shared by `transform` and `collectLazy` so node-kind dispatch lives in one place.
1101
+ * `TResult` is the caller's expected return: the same node type for `transform`,
1102
+ * the collected value type for `collectLazy`.
1544
1103
  */
1545
- function createProperty(props) {
1546
- const required = props.required ?? false;
1547
- return {
1548
- ...props,
1549
- kind: "Property",
1550
- required,
1551
- schema: syncOptionality(props.schema, required)
1552
- };
1104
+ function applyVisitor(node, visitor, parent) {
1105
+ const key = VISITOR_KEY_BY_KIND[node.kind];
1106
+ if (!key) return void 0;
1107
+ const fn = visitor[key];
1108
+ return fn?.(node, { parent });
1109
+ }
1110
+ function transform(node, options) {
1111
+ const { depth, parent, ...visitor } = options;
1112
+ return transformNode(node, visitor, (depth ?? visitorDepths.deep) === visitorDepths.deep, parent);
1113
+ }
1114
+ /**
1115
+ * Visits a single node, then immutably rebuilds its children. Returns the original
1116
+ * reference when neither the visitor nor the child rebuild changed anything, so callers
1117
+ * can detect "nothing changed" by identity and ancestors avoid reallocating.
1118
+ */
1119
+ function transformNode(node, visitor, recurse, parent) {
1120
+ return transformChildren(applyVisitor(node, visitor, parent) ?? node, visitor, recurse);
1121
+ }
1122
+ /**
1123
+ * Immutably rebuilds a node's children using {@link VISITOR_KEYS}, transforming
1124
+ * each child node and leaving non-node values (e.g. `additionalProperties: true`) intact.
1125
+ * `Schema` children are skipped in shallow mode.
1126
+ */
1127
+ function transformChildren(node, visitor, recurse) {
1128
+ if (node.kind === "Schema" && !recurse) return node;
1129
+ const keys = visitorKeysByKind[node.kind];
1130
+ if (!keys) return node;
1131
+ const record = node;
1132
+ let updates;
1133
+ for (const key of keys) {
1134
+ if (!(key in record)) continue;
1135
+ const value = record[key];
1136
+ if (Array.isArray(value)) {
1137
+ let mapped;
1138
+ for (const [i, item] of value.entries()) {
1139
+ const next = isNode(item) ? transformNode(item, visitor, recurse, node) : item;
1140
+ if (mapped) {
1141
+ mapped.push(next);
1142
+ continue;
1143
+ }
1144
+ if (next !== item) mapped = [...value.slice(0, i), next];
1145
+ }
1146
+ if (mapped) (updates ??= {})[key] = mapped;
1147
+ } else if (isNode(value)) {
1148
+ const next = transformNode(value, visitor, recurse, node);
1149
+ if (next !== value) (updates ??= {})[key] = next;
1150
+ }
1151
+ }
1152
+ return updates ? {
1153
+ ...node,
1154
+ ...updates
1155
+ } : node;
1553
1156
  }
1554
1157
  /**
1555
- * Creates a `ParameterNode`.
1158
+ * Lazy depth-first collection pass. Yields every non-null value returned by
1159
+ * the visitor callbacks. Use `collect` for the eager array form.
1556
1160
  *
1557
- * `required` defaults to `false`.
1558
- * Nested schema flags are set from `required` and `schema.nullable`.
1559
- *
1560
- * @example
1161
+ * @example Collect every operationId
1561
1162
  * ```ts
1562
- * const param = createParameter({
1563
- * name: 'petId',
1564
- * in: 'path',
1565
- * required: true,
1566
- * schema: createSchema({ type: 'string' }),
1567
- * })
1163
+ * const ids: string[] = []
1164
+ * for (const id of collectLazy<string>(root, {
1165
+ * operation(node) {
1166
+ * return node.operationId
1167
+ * },
1168
+ * })) {
1169
+ * ids.push(id)
1170
+ * }
1568
1171
  * ```
1172
+ */
1173
+ function* collectLazy(node, options) {
1174
+ const { depth, parent, ...visitor } = options;
1175
+ yield* collectNode(node, visitor, (depth ?? visitorDepths.deep) === visitorDepths.deep, parent);
1176
+ }
1177
+ function* collectNode(node, visitor, recurse, parent) {
1178
+ const v = applyVisitor(node, visitor, parent);
1179
+ if (v != null) yield v;
1180
+ for (const child of getChildren(node, recurse)) yield* collectNode(child, visitor, recurse, node);
1181
+ }
1182
+ /**
1183
+ * Eager depth-first collection pass. Gathers every non-null value the visitor
1184
+ * callbacks return into an array.
1569
1185
  *
1570
- * @example
1186
+ * @example Collect every operationId
1571
1187
  * ```ts
1572
- * const param = createParameter({
1573
- * name: 'status',
1574
- * in: 'query',
1575
- * schema: createSchema({ type: 'string', nullable: true }),
1188
+ * const ids = collect<string>(root, {
1189
+ * operation(node) {
1190
+ * return node.operationId
1191
+ * },
1576
1192
  * })
1577
- * // required=false, schema.nullish=true
1578
1193
  * ```
1579
1194
  */
1580
- function createParameter(props) {
1581
- const required = props.required ?? false;
1582
- return {
1583
- ...props,
1584
- kind: "Parameter",
1585
- required,
1586
- schema: syncOptionality(props.schema, required)
1587
- };
1195
+ function collect(node, options) {
1196
+ return Array.from(collectLazy(node, options));
1197
+ }
1198
+ //#endregion
1199
+ //#region src/defineMacro.ts
1200
+ /**
1201
+ * Sort weight for an `enforce` hint. `pre` sorts before unmarked items and `post` after, so a plain
1202
+ * list keeps its authored order.
1203
+ */
1204
+ function enforceWeight(enforce) {
1205
+ if (enforce === "pre") return 0;
1206
+ if (enforce === "post") return 2;
1207
+ return 1;
1588
1208
  }
1589
1209
  /**
1590
- * Creates a `ResponseNode`.
1210
+ * Types a macro for inference and a single construction site, mirroring `definePlugin`.
1211
+ * Adds no runtime behavior.
1591
1212
  *
1592
1213
  * @example
1593
1214
  * ```ts
1594
- * const response = createResponse({
1595
- * statusCode: '200',
1596
- * description: 'Success',
1597
- * schema: createSchema({ type: 'object', properties: [] }),
1215
+ * const macroUntagged = defineMacro({
1216
+ * name: 'untagged',
1217
+ * operation(node) {
1218
+ * return node.tags?.length ? undefined : { ...node, tags: ['untagged'] }
1219
+ * },
1598
1220
  * })
1599
1221
  * ```
1600
1222
  */
1601
- function createResponse(props) {
1602
- return {
1603
- ...props,
1604
- kind: "Response"
1605
- };
1223
+ function defineMacro(macro) {
1224
+ return macro;
1606
1225
  }
1607
1226
  /**
1608
- * Creates a `FunctionParameterNode`.
1609
- *
1610
- * `optional` defaults to `false`.
1227
+ * Runs every macro's callback for one node kind in order, chaining the result so each macro sees
1228
+ * the previous macro's output. Returns `undefined` when nothing changed, so `transform` keeps the
1229
+ * original reference (structural sharing).
1230
+ */
1231
+ function chain({ macros, key, node, context }) {
1232
+ let current = node;
1233
+ for (const macro of macros) {
1234
+ const callback = macro[key];
1235
+ if (!callback) continue;
1236
+ if (macro.when && !macro.when(current)) continue;
1237
+ const next = callback(current, context);
1238
+ if (next != null) current = next;
1239
+ }
1240
+ return current === node ? void 0 : current;
1241
+ }
1242
+ /**
1243
+ * Folds an ordered list of macros into a single {@link Visitor} that `transform` (and the per-plugin
1244
+ * transform layer in `@kubb/core`) can run. Macros are stable-sorted by `enforce`, then applied
1245
+ * sequentially per node so later macros see earlier output. This differs from a plain visitor, which
1246
+ * has no names, ordering, or composition.
1611
1247
  *
1612
- * @example Required typed param
1248
+ * @example
1613
1249
  * ```ts
1614
- * createFunctionParameter({ name: 'petId', type: createParamsType({ variant: 'reference', name: 'string' }) })
1615
- * // petId: string
1250
+ * const visitor = composeMacros([macroSimplifyUnion, macroDiscriminatorEnum])
1251
+ * const next = transform(root, visitor)
1616
1252
  * ```
1253
+ */
1254
+ function composeMacros(macros) {
1255
+ const ordered = [...macros].sort((a, b) => enforceWeight(a.enforce) - enforceWeight(b.enforce));
1256
+ const visitor = {};
1257
+ for (const key of visitorKeys) {
1258
+ if (!ordered.some((macro) => typeof macro[key] === "function")) continue;
1259
+ const callback = (node, context) => chain({
1260
+ macros: ordered,
1261
+ key,
1262
+ node,
1263
+ context
1264
+ });
1265
+ visitor[key] = callback;
1266
+ }
1267
+ return visitor;
1268
+ }
1269
+ /**
1270
+ * Runs a list of macros over a node tree and returns the rewritten tree. Keeps `transform`'s
1271
+ * structural sharing, so an empty or no-op macro list returns the same reference. Pass
1272
+ * `depth: 'shallow'` to rewrite the root node only.
1617
1273
  *
1618
- * @example Optional param
1274
+ * @example
1619
1275
  * ```ts
1620
- * createFunctionParameter({ name: 'params', type: createParamsType({ variant: 'reference', name: 'QueryParams' }), optional: true })
1621
- * // → params?: QueryParams
1276
+ * const next = applyMacros(root, [macroIntegerToString])
1622
1277
  * ```
1623
1278
  *
1624
- * @example Param with default (implicitly optional; cannot combine with `optional: true`)
1279
+ * @example Apply to the root node only
1625
1280
  * ```ts
1626
- * createFunctionParameter({ name: 'config', type: createParamsType({ variant: 'reference', name: 'RequestConfig' }), default: '{}' })
1627
- * // → config: RequestConfig = {}
1281
+ * const named = applyMacros(node, [macroEnumName({ parentName, propName, enumSuffix })], { depth: 'shallow' })
1628
1282
  * ```
1629
1283
  */
1630
- function createFunctionParameter(props) {
1631
- return {
1632
- optional: false,
1633
- ...props,
1634
- kind: "FunctionParameter"
1635
- };
1284
+ function applyMacros(root, macros, options) {
1285
+ if (macros.length === 0) return root;
1286
+ return transform(root, {
1287
+ ...composeMacros(macros),
1288
+ ...options
1289
+ });
1636
1290
  }
1291
+ //#endregion
1292
+ //#region src/createPrinter.ts
1637
1293
  /**
1638
- * Creates a {@link TypeNode} representing a language-agnostic structured type expression.
1294
+ * Creates a schema printer: a function that takes a `SchemaNode` and emits
1295
+ * code in your target language. Each plugin that produces code from schemas
1296
+ * (TypeScript types, Zod schemas, Faker factories) ships a printer built
1297
+ * with this helper.
1639
1298
  *
1640
- * Use `variant: 'struct'` for inline anonymous types and `variant: 'member'` for a single
1641
- * named field accessed from a group type. Each language's printer renders the variant
1642
- * into its own syntax (TypeScript, Python, C#, Kotlin, …).
1299
+ * The builder receives resolved options and returns:
1643
1300
  *
1644
- * @example Reference type (TypeScript: `QueryParams`)
1645
- * ```ts
1646
- * createParamsType({ variant: 'reference', name: 'QueryParams' })
1647
- * ```
1301
+ * - `name` unique identifier for the printer.
1302
+ * - `options` stored on the returned printer instance.
1303
+ * - `nodes` map of `SchemaType` → handler. Handlers return the rendered
1304
+ * output (a string, a TypeScript AST node, ...) for that schema type.
1305
+ * - `overrides` (optional), user-supplied handlers that win over `nodes`.
1306
+ * An override can call `this.base(node)` to reuse the handler it replaced.
1307
+ * - `print` (optional), top-level override exposed as `printer.print`.
1308
+ * Use `this.transform(node)` inside it to dispatch to `nodes` recursively.
1648
1309
  *
1649
- * @example Struct type (TypeScript: `{ petId: string }`)
1650
- * ```ts
1651
- * createParamsType({ variant: 'struct', properties: [{ name: 'petId', optional: false, type: createParamsType({ variant: 'reference', name: 'string' }) }] })
1652
- * ```
1310
+ * Without a `print` override, `printer.print` falls back to `printer.transform`
1311
+ * (the node-level dispatcher).
1653
1312
  *
1654
- * @example Member type (TypeScript: `DeletePetPathParams['petId']`)
1313
+ * @example Tiny Zod printer
1655
1314
  * ```ts
1656
- * createParamsType({ variant: 'member', base: 'DeletePetPathParams', key: 'petId' })
1657
- * ```
1658
- */
1659
- function createParamsType(props) {
1660
- return {
1661
- ...props,
1662
- kind: "ParamsType"
1663
- };
1664
- }
1665
- /**
1666
- * Creates a `ParameterGroupNode` representing a group of related parameters treated as a unit.
1315
+ * import { createPrinter, type PrinterFactoryOptions } from '@kubb/ast'
1667
1316
  *
1668
- * @example Grouped param (TypeScript declaration)
1669
- * ```ts
1670
- * createParameterGroup({
1671
- * properties: [
1672
- * createFunctionParameter({ name: 'id', type: createParamsType({ variant: 'reference', name: 'string' }), optional: false }),
1673
- * createFunctionParameter({ name: 'name', type: createParamsType({ variant: 'reference', name: 'string' }), optional: true }),
1674
- * ],
1675
- * default: '{}',
1676
- * })
1677
- * // declaration → { id, name? }: { id: string; name?: string } = {}
1678
- * // call → { id, name }
1679
- * ```
1317
+ * type PrinterZod = PrinterFactoryOptions<'zod', { strict?: boolean }, string>
1680
1318
  *
1681
- * @example Inline (spread) children emitted as individual top-level parameters
1682
- * ```ts
1683
- * createParameterGroup({
1684
- * properties: [createFunctionParameter({ name: 'petId', type: createParamsType({ variant: 'reference', name: 'string' }), optional: false })],
1685
- * inline: true,
1686
- * })
1687
- * // declaration → petId: string
1688
- * // call → petId
1319
+ * export const zodPrinter = createPrinter<PrinterZod>((options) => ({
1320
+ * name: 'zod',
1321
+ * options: { strict: options.strict ?? true },
1322
+ * nodes: {
1323
+ * string: () => 'z.string()',
1324
+ * object(node) {
1325
+ * const props = node.properties
1326
+ * .map((p) => `${p.name}: ${this.transform(p.schema)}`)
1327
+ * .join(', ')
1328
+ * return `z.object({ ${props} })`
1329
+ * },
1330
+ * },
1331
+ * }))
1689
1332
  * ```
1690
1333
  */
1691
- function createParameterGroup(props) {
1692
- return {
1693
- ...props,
1694
- kind: "ParameterGroup"
1334
+ function createPrinter(build) {
1335
+ return (options) => {
1336
+ const { name, options: resolvedOptions, nodes, overrides, print: printOverride } = build(options ?? {});
1337
+ const merged = overrides ? {
1338
+ ...nodes,
1339
+ ...overrides
1340
+ } : nodes;
1341
+ const context = {
1342
+ options: resolvedOptions,
1343
+ transform: (node) => {
1344
+ const handler = merged[node.type];
1345
+ if (!handler) return null;
1346
+ return handler.call(context, node);
1347
+ },
1348
+ base: (node) => {
1349
+ const handler = nodes[node.type];
1350
+ if (!handler) return null;
1351
+ return handler.call(context, node);
1352
+ }
1353
+ };
1354
+ return {
1355
+ name,
1356
+ options: resolvedOptions,
1357
+ transform: context.transform,
1358
+ print: printOverride ? printOverride.bind(context) : context.transform
1359
+ };
1695
1360
  };
1696
1361
  }
1362
+ //#endregion
1363
+ //#region src/utils/mergeAdjacentSchemas.ts
1697
1364
  /**
1698
- * Creates a `FunctionParametersNode` from an ordered list of parameters.
1365
+ * Merges a run of adjacent anonymous object members into one. Named or non-object members break the
1366
+ * run and pass through unchanged. The merge follows member order, so callers control which members
1367
+ * combine by where they place them in the sequence.
1699
1368
  *
1700
1369
  * @example
1701
1370
  * ```ts
1702
- * createFunctionParameters({
1703
- * params: [
1704
- * createFunctionParameter({ name: 'petId', type: createParamsType({ variant: 'reference', name: 'string' }), optional: false }),
1705
- * createFunctionParameter({ name: 'config', type: createParamsType({ variant: 'reference', name: 'RequestConfig' }), optional: false, default: '{}' }),
1706
- * ],
1707
- * })
1371
+ * const merged = [...mergeAdjacentObjectsLazy([objectA, objectB])]
1708
1372
  * ```
1373
+ */
1374
+ function* mergeAdjacentObjectsLazy(members) {
1375
+ let acc;
1376
+ for (const member of members) {
1377
+ const objectMember = narrowSchema(member, "object");
1378
+ if (objectMember && !objectMember.name && acc !== void 0) {
1379
+ const accObject = narrowSchema(acc, "object");
1380
+ if (accObject && !accObject.name) {
1381
+ acc = createSchema({
1382
+ ...accObject,
1383
+ properties: [...accObject.properties ?? [], ...objectMember.properties ?? []]
1384
+ });
1385
+ continue;
1386
+ }
1387
+ }
1388
+ if (acc !== void 0) yield acc;
1389
+ acc = member;
1390
+ }
1391
+ if (acc !== void 0) yield acc;
1392
+ }
1393
+ //#endregion
1394
+ //#region src/utils/refs.ts
1395
+ const plainStringTypes = /* @__PURE__ */ new Set([
1396
+ "string",
1397
+ "uuid",
1398
+ "email",
1399
+ "url",
1400
+ "datetime"
1401
+ ]);
1402
+ /**
1403
+ * Returns the last path segment of a reference string.
1709
1404
  *
1710
1405
  * @example
1711
- * ```ts
1712
- * const empty = createFunctionParameters()
1713
- * // { kind: 'FunctionParameters', params: [] }
1714
- * ```
1406
+ * `extractRefName('#/components/schemas/Pet') // 'Pet'`
1715
1407
  */
1716
- function createFunctionParameters(props = {}) {
1717
- return {
1718
- params: [],
1719
- ...props,
1720
- kind: "FunctionParameters"
1721
- };
1408
+ function extractRefName(ref) {
1409
+ return ref.split("/").at(-1) ?? ref;
1722
1410
  }
1723
1411
  /**
1724
- * Creates an `ImportNode` representing a language-agnostic import/dependency declaration.
1412
+ * Resolves the schema name of a ref node. Uses the last segment of `ref` when set, otherwise falls
1413
+ * back to `name` then nested `schema.name`.
1725
1414
  *
1726
- * @example Named import
1727
- * ```ts
1728
- * createImport({ name: ['useState'], path: 'react' })
1729
- * // import { useState } from 'react'
1730
- * ```
1415
+ * Returns `null` for non-ref nodes or when no name resolves.
1731
1416
  *
1732
- * @example Type-only import
1733
- * ```ts
1734
- * createImport({ name: ['FC'], path: 'react', isTypeOnly: true })
1735
- * // import type { FC } from 'react'
1736
- * ```
1417
+ * @example
1418
+ * `resolveRefName({ kind: 'Schema', type: 'ref', ref: '#/components/schemas/Pet' }) // 'Pet'`
1737
1419
  */
1738
- function createImport(props) {
1739
- return {
1740
- ...props,
1741
- kind: "Import"
1742
- };
1420
+ function resolveRefName(node) {
1421
+ if (!node || node.type !== "ref") return null;
1422
+ if (node.ref) return extractRefName(node.ref) ?? node.name ?? node.schema?.name ?? null;
1423
+ return node.name ?? node.schema?.name ?? null;
1743
1424
  }
1744
1425
  /**
1745
- * Creates an `ExportNode` representing a language-agnostic export/public API declaration.
1426
+ * Builds a PascalCase child schema name by joining a parent name and property name.
1427
+ * Returns `null` when there is no parent to nest under.
1746
1428
  *
1747
- * @example Named export
1748
- * ```ts
1749
- * createExport({ name: ['Pet'], path: './Pet' })
1750
- * // export { Pet } from './Pet'
1751
- * ```
1429
+ * @example Nested under a parent
1430
+ * `childName('Order', 'shipping_address') // 'OrderShippingAddress'`
1752
1431
  *
1753
- * @example Wildcard export
1754
- * ```ts
1755
- * createExport({ path: './utils' })
1756
- * // export * from './utils'
1757
- * ```
1432
+ * @example No parent
1433
+ * `childName(undefined, 'params') // null`
1758
1434
  */
1759
- function createExport(props) {
1760
- return {
1761
- ...props,
1762
- kind: "Export"
1763
- };
1435
+ function childName(parentName, propName) {
1436
+ return parentName ? pascalCase([parentName, propName].join(" ")) : null;
1764
1437
  }
1765
1438
  /**
1766
- * Creates a `SourceNode` representing a fragment of source code within a file.
1439
+ * Builds a PascalCase enum name from the parent name, property name, and a suffix, skipping any
1440
+ * empty parts.
1767
1441
  *
1768
1442
  * @example
1769
- * ```ts
1770
- * createSource({ name: 'Pet', nodes: [createText('export type Pet = { id: number }')], isExportable: true })
1771
- * ```
1443
+ * `enumPropName('Order', 'status', 'enum') // 'OrderStatusEnum'`
1772
1444
  */
1773
- function createSource(props) {
1774
- return {
1775
- ...props,
1776
- kind: "Source"
1777
- };
1445
+ function enumPropName(parentName, propName, enumSuffix) {
1446
+ return pascalCase([
1447
+ parentName,
1448
+ propName,
1449
+ enumSuffix
1450
+ ].filter(Boolean).join(" "));
1778
1451
  }
1779
1452
  /**
1780
- * Creates a fully resolved `FileNode` from a file input descriptor.
1781
- *
1782
- * Computes:
1783
- * - `id` — SHA256 hash of the file path
1784
- * - `name` — `baseName` without extension
1785
- * - `extname` — extension extracted from `baseName`
1786
- *
1787
- * Deduplicates:
1788
- * - `sources` via `combineSources`
1789
- * - `exports` via `combineExports`
1790
- * - `imports` via `combineImports` (also filters unused imports)
1453
+ * Merges a ref node with its resolved schema, giving usage-site fields precedence.
1791
1454
  *
1792
- * @throws {Error} when `baseName` has no extension.
1455
+ * Every field set on the ref node except `kind`, `type`, `name`, `ref`, and `schema` overrides the
1456
+ * same field in the resolved `node.schema` (for example `description`, `nullable`, `readOnly`,
1457
+ * `deprecated`). Fields left `undefined` on the ref do not shadow the resolved schema. Non-ref
1458
+ * nodes and refs without a resolved `schema` are returned unchanged.
1793
1459
  *
1794
1460
  * @example
1795
1461
  * ```ts
1796
- * const file = createFile({
1797
- * baseName: 'petStore.ts',
1798
- * path: 'src/models/petStore.ts',
1799
- * sources: [createSource({ name: 'Pet', nodes: [createText('export type Pet = { id: number }')] })],
1800
- * imports: [createImport({ name: ['z'], path: 'zod' })],
1801
- * exports: [createExport({ name: ['Pet'], path: './petStore' })],
1802
- * })
1803
- * // file.id = SHA256 hash of 'src/models/petStore.ts'
1804
- * // file.name = 'petStore'
1805
- * // file.extname = '.ts'
1462
+ * const ref = createSchema({ type: 'ref', ref: '#/components/schemas/Pet', description: 'A cute pet' })
1463
+ * const merged = syncSchemaRef(ref) // merges with resolved Pet schema
1806
1464
  * ```
1807
1465
  */
1808
- function createFile(input) {
1809
- const extname = node_path.default.extname(input.baseName) || (input.baseName.startsWith(".") ? input.baseName : "");
1810
- if (!extname) throw new Error(`No extname found for ${input.baseName}`);
1811
- const source = (input.sources ?? []).flatMap((item) => item.nodes ?? []).map((node) => extractStringsFromNodes([node])).filter(Boolean).join("\n\n");
1812
- const resolvedExports = input.exports?.length ? combineExports(input.exports) : [];
1813
- const resolvedImports = input.imports?.length ? combineImports(input.imports, resolvedExports, source || void 0) : [];
1814
- const resolvedSources = input.sources?.length ? combineSources(input.sources) : [];
1815
- return {
1816
- kind: "File",
1817
- ...input,
1818
- id: (0, node_crypto.createHash)("sha256").update(input.path).digest("hex"),
1819
- name: trimExtName(input.baseName),
1820
- extname,
1821
- imports: resolvedImports,
1822
- exports: resolvedExports,
1823
- sources: resolvedSources,
1824
- meta: input.meta ?? {}
1825
- };
1466
+ function syncSchemaRef(node) {
1467
+ const ref = narrowSchema(node, "ref");
1468
+ if (!ref) return node;
1469
+ if (!ref.schema) return node;
1470
+ const { kind: _kind, type: _type, name: _name, ref: _ref, schema: _schema, ...overrides } = ref;
1471
+ const definedOverrides = Object.fromEntries(Object.entries(overrides).filter(([, v]) => v !== void 0));
1472
+ return createSchema({
1473
+ ...ref.schema,
1474
+ ...definedOverrides
1475
+ });
1826
1476
  }
1827
1477
  /**
1828
- * Creates a `ConstNode` representing a TypeScript `const` declaration.
1829
- *
1830
- * Mirrors the `Const` component from `@kubb/renderer-jsx`.
1831
- * The component's `children` are represented as `nodes`.
1832
- *
1833
- * @example Simple constant
1834
- * ```ts
1835
- * createConst({ name: 'pet' })
1836
- * // const pet = ...
1837
- * ```
1838
- *
1839
- * @example Exported constant with type and `as const`
1840
- * ```ts
1841
- * createConst({ name: 'pets', export: true, type: 'Pet[]', asConst: true })
1842
- * // export const pets: Pet[] = ... as const
1843
- * ```
1478
+ * Type guard that returns `true` when a schema emits as a plain `string` type.
1844
1479
  *
1845
- * @example With JSDoc and child nodes
1846
- * ```ts
1847
- * createConst({
1848
- * name: 'config',
1849
- * export: true,
1850
- * JSDoc: { comments: ['@description App configuration'] },
1851
- * nodes: [],
1852
- * })
1853
- * ```
1480
+ * Covers `string`, `uuid`, `email`, `url`, and `datetime` types. For `date` and `time`
1481
+ * types, returns `true` only when `representation` is `'string'` rather than `'date'`.
1854
1482
  */
1855
- function createConst(props) {
1856
- return {
1857
- ...props,
1858
- kind: "Const"
1859
- };
1483
+ function isStringType(node) {
1484
+ if (plainStringTypes.has(node.type)) return true;
1485
+ const temporal = narrowSchema(node, "date") ?? narrowSchema(node, "time");
1486
+ if (temporal) return temporal.representation !== "date";
1487
+ return false;
1860
1488
  }
1489
+ //#endregion
1490
+ //#region src/utils/schemaGraph.ts
1861
1491
  /**
1862
- * Creates a `TypeNode` representing a TypeScript `type` alias declaration.
1863
- *
1864
- * Mirrors the `Type` component from `@kubb/renderer-jsx`.
1865
- * The component's `children` are represented as `nodes`.
1866
- *
1867
- * @example Simple type alias
1868
- * ```ts
1869
- * createType({ name: 'Pet' })
1870
- * // type Pet = ...
1871
- * ```
1872
- *
1873
- * @example Exported type with JSDoc
1874
- * ```ts
1875
- * createType({
1876
- * name: 'PetStatus',
1877
- * export: true,
1878
- * JSDoc: { comments: ['@description Status of a pet'] },
1879
- * })
1880
- * // export type PetStatus = ...
1881
- * ```
1492
+ * Memoized inner pass that walks a single node and returns the names of every schema it references.
1882
1493
  */
1883
- function createType(props) {
1884
- return {
1885
- ...props,
1886
- kind: "Type"
1887
- };
1888
- }
1494
+ const collectSchemaRefs = memoize(/* @__PURE__ */ new WeakMap(), (node) => {
1495
+ const refs = /* @__PURE__ */ new Set();
1496
+ collect(node, { schema(child) {
1497
+ if (child.type === "ref") {
1498
+ const name = resolveRefName(child);
1499
+ if (name) refs.add(name);
1500
+ }
1501
+ } });
1502
+ return refs;
1503
+ });
1889
1504
  /**
1890
- * Creates a `FunctionNode` representing a TypeScript `function` declaration.
1505
+ * Collects the names of every ref found anywhere inside a node's own subtree.
1891
1506
  *
1892
- * Mirrors the `Function` component from `@kubb/renderer-jsx`.
1893
- * The component's `children` are represented as `nodes`.
1507
+ * Each ref contributes its name only, so the schema it points to is never traversed here. Pass `out`
1508
+ * to accumulate names from several nodes into one set.
1894
1509
  *
1895
- * @example Simple function
1896
- * ```ts
1897
- * createFunction({ name: 'getPet' })
1898
- * // function getPet() { ... }
1899
- * ```
1900
- *
1901
- * @example Exported async function with return type
1510
+ * @example Collect refs from a single schema
1902
1511
  * ```ts
1903
- * createFunction({ name: 'fetchPet', export: true, async: true, returnType: 'Pet' })
1904
- * // export async function fetchPet(): Promise<Pet> { ... }
1512
+ * const names = collectReferencedSchemaNames(petSchema)
1513
+ * // Set { 'Category', 'Tag' }
1905
1514
  * ```
1906
1515
  *
1907
- * @example Function with generics and params
1516
+ * @example Accumulate refs from multiple schemas into one set
1908
1517
  * ```ts
1909
- * createFunction({
1910
- * name: 'identity',
1911
- * export: true,
1912
- * generics: ['T'],
1913
- * params: 'value: T',
1914
- * returnType: 'T',
1915
- * })
1916
- * // export function identity<T>(value: T): T { ... }
1518
+ * const out = new Set<string>()
1519
+ * for (const schema of schemas) {
1520
+ * collectReferencedSchemaNames(schema, out)
1521
+ * }
1917
1522
  * ```
1918
1523
  */
1919
- function createFunction(props) {
1920
- return {
1921
- ...props,
1922
- kind: "Function"
1923
- };
1524
+ function collectReferencedSchemaNames(node, out = /* @__PURE__ */ new Set()) {
1525
+ if (!node) return out;
1526
+ for (const name of collectSchemaRefs(node)) out.add(name);
1527
+ return out;
1924
1528
  }
1925
1529
  /**
1926
- * Creates an `ArrowFunctionNode` representing a TypeScript arrow function.
1927
- *
1928
- * Mirrors the `Function.Arrow` component from `@kubb/renderer-jsx`.
1929
- * The component's `children` are represented as `nodes`.
1930
- *
1931
- * @example Simple arrow function
1932
- * ```ts
1933
- * createArrowFunction({ name: 'getPet' })
1934
- * // const getPet = () => { ... }
1935
- * ```
1936
- *
1937
- * @example Single-line exported arrow function
1938
- * ```ts
1939
- * createArrowFunction({ name: 'double', export: true, params: 'n: number', singleLine: true })
1940
- * // export const double = (n: number) => ...
1941
- * ```
1942
- *
1943
- * @example Async arrow function with generics
1944
- * ```ts
1945
- * createArrowFunction({
1946
- * name: 'fetchPet',
1947
- * export: true,
1948
- * async: true,
1949
- * generics: ['T'],
1950
- * params: 'id: string',
1951
- * returnType: 'T',
1952
- * })
1953
- * // export const fetchPet = async <T>(id: string): Promise<T> => { ... }
1954
- * ```
1530
+ * Memoized two-level cache keyed first on the operations array, then on the schemas array.
1955
1531
  */
1956
- function createArrowFunction(props) {
1957
- return {
1958
- ...props,
1959
- kind: "ArrowFunction"
1960
- };
1532
+ const collectUsedSchemaNamesMemo = memoize(/* @__PURE__ */ new WeakMap(), (ops) => memoize(/* @__PURE__ */ new WeakMap(), (schemas) => computeUsedSchemaNames(ops, schemas)));
1533
+ function computeUsedSchemaNames(operations, schemas) {
1534
+ const schemaMap = /* @__PURE__ */ new Map();
1535
+ for (const schema of schemas) if (schema.name) schemaMap.set(schema.name, schema);
1536
+ const result = /* @__PURE__ */ new Set();
1537
+ function visitSchema(schema) {
1538
+ const directRefs = collectReferencedSchemaNames(schema);
1539
+ for (const name of directRefs) if (!result.has(name)) {
1540
+ result.add(name);
1541
+ const namedSchema = schemaMap.get(name);
1542
+ if (namedSchema) visitSchema(namedSchema);
1543
+ }
1544
+ }
1545
+ for (const op of operations) for (const schema of collectLazy(op, {
1546
+ depth: "shallow",
1547
+ schema: (node) => node
1548
+ })) visitSchema(schema);
1549
+ return result;
1961
1550
  }
1962
1551
  /**
1963
- * Creates a {@link TextNode} representing a raw string fragment in the source output.
1552
+ * Collects the names of all top-level schemas transitively used by a set of operations.
1964
1553
  *
1965
- * Use this instead of bare strings when building `nodes` arrays so that every
1966
- * entry in the array is a typed {@link CodeNode}.
1554
+ * An operation uses a schema when its parameters, request body, or responses reference it, directly
1555
+ * or through other named schemas. Once a name is added to the result it is not revisited, so
1556
+ * reference cycles terminate.
1967
1557
  *
1968
- * @example
1558
+ * Pair it with `include` filters so schemas reachable only from excluded operations stay ungenerated.
1559
+ *
1560
+ * @example Only generate schemas referenced by included operations
1969
1561
  * ```ts
1970
- * createText('return fetch(id)')
1971
- * // { kind: 'Text', value: 'return fetch(id)' }
1562
+ * const includedOps = operations.filter((op) => resolver.default.options(op, { options, include }) !== null)
1563
+ * const allowed = collectUsedSchemaNames(includedOps, schemas)
1564
+ *
1565
+ * for (const schema of schemas) {
1566
+ * if (schema.name && !allowed.has(schema.name)) continue
1567
+ * // generate schema
1568
+ * }
1972
1569
  * ```
1973
1570
  */
1974
- function createText(value) {
1975
- return {
1976
- value,
1977
- kind: "Text"
1978
- };
1571
+ function collectUsedSchemaNames(operations, schemas) {
1572
+ return collectUsedSchemaNamesMemo(operations)(schemas);
1979
1573
  }
1574
+ const EMPTY_CIRCULAR_SET = /* @__PURE__ */ new Set();
1575
+ const findCircularSchemasMemo = memoize(/* @__PURE__ */ new WeakMap(), (schemas) => {
1576
+ const graph = /* @__PURE__ */ new Map();
1577
+ for (const schema of schemas) {
1578
+ if (!schema.name) continue;
1579
+ graph.set(schema.name, collectReferencedSchemaNames(schema));
1580
+ }
1581
+ const circular = /* @__PURE__ */ new Set();
1582
+ for (const start of graph.keys()) {
1583
+ const visited = /* @__PURE__ */ new Set();
1584
+ const stack = [...graph.get(start) ?? []];
1585
+ while (stack.length > 0) {
1586
+ const node = stack.pop();
1587
+ if (node === start) {
1588
+ circular.add(start);
1589
+ break;
1590
+ }
1591
+ if (visited.has(node)) continue;
1592
+ visited.add(node);
1593
+ const next = graph.get(node);
1594
+ if (next) for (const r of next) stack.push(r);
1595
+ }
1596
+ }
1597
+ return circular;
1598
+ });
1980
1599
  /**
1981
- * Creates a {@link BreakNode} representing a line break in the source output.
1600
+ * Finds every schema that takes part in a circular dependency chain, including direct self-loops.
1982
1601
  *
1983
- * Corresponds to `<br/>` in JSX components. Prints as an empty string which,
1984
- * when joined with `\n` by `printNodes`, produces a blank line.
1602
+ * Wrap the returned schema positions in a deferred construct (a lazy getter or `z.lazy(() => …)`) so
1603
+ * the generated code does not recurse forever. Refs are followed by name only, so the walk stays
1604
+ * linear in the size of the schema graph.
1985
1605
  *
1986
- * @example
1987
- * ```ts
1988
- * createBreak()
1989
- * // { kind: 'Break' }
1990
- * ```
1606
+ * @note Call this once on the full graph, then check individual schemas with `containsCircularRef()`.
1991
1607
  */
1992
- function createBreak() {
1993
- return { kind: "Break" };
1608
+ function findCircularSchemas(schemas) {
1609
+ if (schemas.length === 0) return EMPTY_CIRCULAR_SET;
1610
+ return findCircularSchemasMemo(schemas);
1994
1611
  }
1995
1612
  /**
1996
- * Creates a {@link JsxNode} representing a raw JSX fragment in the source output.
1613
+ * Returns `true` when a schema, or anything nested inside it, references a circular schema.
1997
1614
  *
1998
- * Use this to embed JSX markup (including fragments `<>…</>`) directly in generated code.
1615
+ * Pass `excludeName` to skip refs to a specific schema, which helps when self-references are handled
1616
+ * on their own. Pair it with `findCircularSchemas()` to decide where lazy wrappers go.
1999
1617
  *
2000
- * @example
2001
- * ```ts
2002
- * createJsx('<>\n <a href={href}>Open</a>\n</>')
2003
- * // { kind: 'Jsx', value: '<>\n <a href={href}>Open</a>\n</>' }
2004
- * ```
1618
+ * @note Stops at the first matching circular ref.
2005
1619
  */
2006
- function createJsx(value) {
2007
- return {
2008
- value,
2009
- kind: "Jsx"
2010
- };
1620
+ function containsCircularRef(node, { circularSchemas, excludeName }) {
1621
+ if (!node || circularSchemas.size === 0) return false;
1622
+ for (const _ of collectLazy(node, { schema(child) {
1623
+ if (child.type !== "ref") return null;
1624
+ const name = resolveRefName(child);
1625
+ return name && name !== excludeName && circularSchemas.has(name) ? true : null;
1626
+ } })) return true;
1627
+ return false;
2011
1628
  }
2012
1629
  //#endregion
2013
- //#region src/printer.ts
1630
+ //#region src/utils/schemaTraversal.ts
2014
1631
  /**
2015
- * Creates a schema printer factory.
2016
- *
2017
- * This function wraps a builder and makes options optional at call sites.
1632
+ * Maps each property of an object schema to its transformed output. Pairs every result with the
1633
+ * original property so the printer keeps full control over modifiers, getters, and key syntax.
2018
1634
  *
2019
- * The builder receives resolved options and returns:
2020
- * - `name` — a unique identifier for the printer
2021
- * - `options` — options stored on the returned printer instance
2022
- * - `nodes` — a map of `SchemaType` → handler functions that convert a `SchemaNode` to `TOutput`
2023
- * - `print` _(optional)_ — top-level override exposed as `printer.print`
2024
- * - Inside this function, use `this.transform(node)` to dispatch to the `nodes` map
2025
- * - This keeps recursion safe and avoids self-calls
2026
- *
2027
- * When no `print` override is provided, `printer.print` falls back to `printer.transform` (the node-level dispatcher).
2028
- *
2029
- * @example Basic usage — Zod schema printer
1635
+ * @example
2030
1636
  * ```ts
2031
- * type PrinterZod = PrinterFactoryOptions<'zod', { strict?: boolean }, string>
2032
- *
2033
- * export const zodPrinter = definePrinter<PrinterZod>((options) => ({
2034
- * name: 'zod',
2035
- * options: { strict: options.strict ?? true },
2036
- * nodes: {
2037
- * string: () => 'z.string()',
2038
- * object(node) {
2039
- * const props = node.properties.map(p => `${p.name}: ${this.transform(p.schema)}`).join(', ')
2040
- * return `z.object({ ${props} })`
2041
- * },
2042
- * },
2043
- * }))
1637
+ * const entries = mapSchemaProperties(node, (schema) => this.transform(schema))
1638
+ * // entries: [{ name: 'id', property, output: 'z.number()' }, ...]
2044
1639
  * ```
2045
1640
  */
2046
- function definePrinter(build) {
2047
- return createPrinterFactory((node) => node.type)(build);
1641
+ function mapSchemaProperties(node, transform) {
1642
+ return node.properties.map((property) => ({
1643
+ name: property.name,
1644
+ property,
1645
+ output: transform(property.schema)
1646
+ }));
2048
1647
  }
2049
1648
  /**
2050
- * Generic printer-factory function used by `definePrinter` and `defineFunctionPrinter`.
2051
- **
2052
- * @example
2053
- * ```ts
2054
- * export const defineFunctionPrinter = createPrinterFactory<FunctionNode, FunctionNodeType, FunctionNodeByType>(
2055
- * (node) => kindToHandlerKey[node.kind],
2056
- * )
2057
- * ```
1649
+ * Maps each member of a union or intersection schema to its transformed output, pairing every
1650
+ * result with the original member.
2058
1651
  */
2059
- function createPrinterFactory(getKey) {
2060
- return function(build) {
2061
- return (options) => {
2062
- const { name, options: resolvedOptions, nodes, print: printOverride } = build(options ?? {});
2063
- const context = {
2064
- options: resolvedOptions,
2065
- transform: (node) => {
2066
- const key = getKey(node);
2067
- if (key === void 0) return null;
2068
- const handler = nodes[key];
2069
- if (!handler) return null;
2070
- return handler.call(context, node);
2071
- }
2072
- };
2073
- return {
2074
- name,
2075
- options: resolvedOptions,
2076
- transform: context.transform,
2077
- print: printOverride ? printOverride.bind(context) : context.transform
2078
- };
2079
- };
2080
- };
2081
- }
2082
- //#endregion
2083
- //#region src/resolvers.ts
2084
- function findDiscriminator(mapping, ref) {
2085
- if (!mapping || !ref) return null;
2086
- return Object.entries(mapping).find(([, value]) => value === ref)?.[0] ?? null;
2087
- }
2088
- function childName(parentName, propName) {
2089
- return parentName ? pascalCase([parentName, propName].join(" ")) : null;
2090
- }
2091
- function enumPropName(parentName, propName, enumSuffix) {
2092
- return pascalCase([
2093
- parentName,
2094
- propName,
2095
- enumSuffix
2096
- ].filter(Boolean).join(" "));
1652
+ function mapSchemaMembers(node, transform) {
1653
+ return (node.members ?? []).map((schema) => ({
1654
+ schema,
1655
+ output: transform(schema)
1656
+ }));
2097
1657
  }
2098
1658
  /**
2099
- * Collects import entries for all `ref` schema nodes in `node`.
1659
+ * Maps each item of an array or tuple schema to its transformed output, pairing every result with
1660
+ * the original item.
2100
1661
  */
2101
- function collectImports({ node, nameMapping, resolve }) {
2102
- return collect(node, { schema(schemaNode) {
2103
- const schemaRef = narrowSchema(schemaNode, "ref");
2104
- if (!schemaRef?.ref) return;
2105
- const rawName = extractRefName(schemaRef.ref);
2106
- const result = resolve(nameMapping.get(rawName) ?? rawName);
2107
- if (!result) return;
2108
- return result;
2109
- } });
1662
+ function mapSchemaItems(node, transform) {
1663
+ return (node.items ?? []).map((schema) => ({
1664
+ schema,
1665
+ output: transform(schema)
1666
+ }));
2110
1667
  }
2111
1668
  //#endregion
2112
- //#region src/transformers.ts
1669
+ //#region src/macros/macroDiscriminatorEnum.ts
2113
1670
  /**
2114
- * Replaces a discriminator property's schema with a string enum of allowed values.
2115
- *
2116
- * If `node` is not an object schema, or if the property does not exist, the input
2117
- * node is returned as-is.
1671
+ * Builds a macro that replaces a discriminator property's schema with a string enum of the given
1672
+ * values. Object schemas that lack the property are returned unchanged.
2118
1673
  *
2119
1674
  * @example
2120
1675
  * ```ts
2121
- * const schema = createSchema({
2122
- * type: 'object',
2123
- * properties: [createProperty({ name: 'type', required: true, schema: createSchema({ type: 'string' }) })],
2124
- * })
2125
- * const result = setDiscriminatorEnum({ node: schema, propertyName: 'type', values: ['dog', 'cat'] })
2126
- * ```
2127
- */
2128
- function setDiscriminatorEnum({ node, propertyName, values, enumName }) {
2129
- const objectNode = narrowSchema(node, "object");
2130
- if (!objectNode?.properties?.length) return node;
2131
- if (!objectNode.properties.some((prop) => prop.name === propertyName)) return node;
2132
- return createSchema({
2133
- ...objectNode,
2134
- properties: objectNode.properties.map((prop) => {
2135
- if (prop.name !== propertyName) return prop;
2136
- return createProperty({
2137
- ...prop,
2138
- schema: createSchema({
2139
- type: "enum",
2140
- primitive: "string",
2141
- enumValues: values,
2142
- name: enumName,
2143
- readOnly: prop.schema.readOnly,
2144
- writeOnly: prop.schema.writeOnly
1676
+ * const macro = macroDiscriminatorEnum({ propertyName: 'type', values: ['dog', 'cat'] })
1677
+ * const next = applyMacros(objectSchema, [macro], { depth: 'shallow' })
1678
+ * ```
1679
+ */
1680
+ function macroDiscriminatorEnum({ propertyName, values, enumName }) {
1681
+ return defineMacro({
1682
+ name: "discriminator-enum",
1683
+ schema(node) {
1684
+ const objectNode = narrowSchema(node, "object");
1685
+ if (!objectNode?.properties?.length) return void 0;
1686
+ if (!objectNode.properties.some((prop) => prop.name === propertyName)) return void 0;
1687
+ return createSchema({
1688
+ ...objectNode,
1689
+ properties: objectNode.properties.map((prop) => {
1690
+ if (prop.name !== propertyName) return prop;
1691
+ return createProperty({
1692
+ ...prop,
1693
+ schema: createSchema({
1694
+ type: "enum",
1695
+ primitive: "string",
1696
+ enumValues: values,
1697
+ name: enumName,
1698
+ readOnly: prop.schema.readOnly,
1699
+ writeOnly: prop.schema.writeOnly
1700
+ })
1701
+ });
2145
1702
  })
2146
1703
  });
2147
- })
1704
+ }
2148
1705
  });
2149
1706
  }
1707
+ //#endregion
1708
+ //#region src/macros/macroEnumName.ts
2150
1709
  /**
2151
- * Merges adjacent anonymous object members into a single anonymous object member.
1710
+ * Builds a macro that names an inline enum schema from its parent and property name. Boolean enums
1711
+ * are left anonymous. Non-enum nodes are returned unchanged.
2152
1712
  *
2153
1713
  * @example
2154
1714
  * ```ts
2155
- * const merged = mergeAdjacentObjects([
2156
- * createSchema({ type: 'object', properties: [createProperty({ name: 'a', schema: createSchema({ type: 'string' }) })] }),
2157
- * createSchema({ type: 'object', properties: [createProperty({ name: 'b', schema: createSchema({ type: 'number' }) })] }),
2158
- * ])
1715
+ * const macro = macroEnumName({ parentName: 'Pet', propName: 'status', enumSuffix: 'enum' })
1716
+ * const named = applyMacros(propSchema, [macro], { depth: 'shallow' })
2159
1717
  * ```
2160
1718
  */
2161
- function mergeAdjacentObjects(members) {
2162
- return members.reduce((acc, member) => {
2163
- const objectMember = narrowSchema(member, "object");
2164
- if (objectMember && !objectMember.name) {
2165
- const previous = acc.at(-1);
2166
- const previousObject = previous ? narrowSchema(previous, "object") : void 0;
2167
- if (previousObject && !previousObject.name) {
2168
- acc[acc.length - 1] = createSchema({
2169
- ...previousObject,
2170
- properties: [...previousObject.properties ?? [], ...objectMember.properties ?? []]
2171
- });
2172
- return acc;
2173
- }
1719
+ function macroEnumName({ parentName, propName, enumSuffix }) {
1720
+ return defineMacro({
1721
+ name: "enum-name",
1722
+ schema(node) {
1723
+ const enumNode = narrowSchema(node, "enum");
1724
+ if (enumNode?.primitive === "boolean") return {
1725
+ ...node,
1726
+ name: null
1727
+ };
1728
+ if (enumNode) return {
1729
+ ...node,
1730
+ name: enumPropName(parentName, propName, enumSuffix)
1731
+ };
2174
1732
  }
2175
- acc.push(member);
2176
- return acc;
2177
- }, []);
1733
+ });
2178
1734
  }
1735
+ //#endregion
1736
+ //#region src/macros/macroSimplifyUnion.ts
2179
1737
  /**
2180
- * Removes enum members that are covered by broader scalar primitives in the same union.
2181
- *
2182
- * @example
2183
- * ```ts
2184
- * const simplified = simplifyUnion([
2185
- * createSchema({ type: 'enum', primitive: 'string', enumValues: ['active'] }),
2186
- * createSchema({ type: 'string' }),
2187
- * ])
2188
- * // keeps only string member
2189
- * ```
1738
+ * Scalar primitive schema types used for union simplification and type narrowing.
1739
+ */
1740
+ const SCALAR_PRIMITIVE_TYPES = /* @__PURE__ */ new Set([
1741
+ "string",
1742
+ "number",
1743
+ "integer",
1744
+ "bigint",
1745
+ "boolean"
1746
+ ]);
1747
+ function isScalarPrimitive(type) {
1748
+ return SCALAR_PRIMITIVE_TYPES.has(type);
1749
+ }
1750
+ /**
1751
+ * Filters union members, dropping enum members that a broader scalar primitive already covers.
2190
1752
  */
2191
- function simplifyUnion(members) {
1753
+ function simplifyUnionMembers(members) {
2192
1754
  const scalarPrimitives = new Set(members.filter((member) => isScalarPrimitive(member.type)).map((m) => m.type));
2193
1755
  if (!scalarPrimitives.size) return members;
2194
1756
  return members.filter((member) => {
@@ -2202,76 +1764,195 @@ function simplifyUnion(members) {
2202
1764
  return true;
2203
1765
  });
2204
1766
  }
2205
- function setEnumName(propNode, parentName, propName, enumSuffix) {
2206
- const enumNode = narrowSchema(propNode, "enum");
2207
- if (enumNode?.primitive === "boolean") return {
2208
- ...propNode,
2209
- name: void 0
2210
- };
2211
- if (enumNode) return {
2212
- ...propNode,
2213
- name: enumPropName(parentName, propName, enumSuffix)
1767
+ /**
1768
+ * Removes union members a broader scalar primitive already covers, such as a multi-value string enum
1769
+ * sitting next to a plain `string`. Single-value enums are kept.
1770
+ *
1771
+ * @example
1772
+ * ```ts
1773
+ * const next = applyMacros(unionSchema, [macroSimplifyUnion], { depth: 'shallow' })
1774
+ * ```
1775
+ */
1776
+ const macroSimplifyUnion = defineMacro({
1777
+ name: "simplify-union",
1778
+ schema(node) {
1779
+ const unionNode = narrowSchema(node, "union");
1780
+ if (!unionNode?.members?.length) return void 0;
1781
+ const simplified = simplifyUnionMembers(unionNode.members);
1782
+ if (simplified.length === unionNode.members.length) return void 0;
1783
+ return {
1784
+ ...unionNode,
1785
+ members: simplified
1786
+ };
1787
+ }
1788
+ });
1789
+ //#endregion
1790
+ //#region src/factory.ts
1791
+ var factory_exports = /* @__PURE__ */ __exportAll({
1792
+ createArrowFunction: () => createArrowFunction,
1793
+ createBreak: () => createBreak,
1794
+ createConst: () => createConst,
1795
+ createContent: () => createContent,
1796
+ createExport: () => createExport,
1797
+ createFile: () => createFile,
1798
+ createFunction: () => createFunction,
1799
+ createImport: () => createImport,
1800
+ createInput: () => createInput,
1801
+ createJsx: () => createJsx,
1802
+ createOperation: () => createOperation,
1803
+ createOutput: () => createOutput,
1804
+ createParameter: () => createParameter,
1805
+ createProperty: () => createProperty,
1806
+ createRequestBody: () => createRequestBody,
1807
+ createResponse: () => createResponse,
1808
+ createSchema: () => createSchema,
1809
+ createSource: () => createSource,
1810
+ createText: () => createText,
1811
+ createType: () => createType,
1812
+ update: () => update
1813
+ });
1814
+ /**
1815
+ * Identity-preserving node update: returns `node` unchanged when every field in
1816
+ * `changes` already equals (by reference) the current value, otherwise a new node
1817
+ * with the changes applied.
1818
+ *
1819
+ * Mirrors the TypeScript compiler's `factory.updateX` contract. Pair it with the
1820
+ * structural sharing in {@link transform} so a no-op rewrite does not allocate and
1821
+ * downstream passes can detect "nothing changed" by identity. Comparison is shallow,
1822
+ * so a structurally equal but newly allocated array or object counts as a change.
1823
+ *
1824
+ * @example
1825
+ * ```ts
1826
+ * update(node, { name: node.name }) // -> same `node` reference
1827
+ * update(node, { name: 'renamed' }) // -> new node, `name` replaced
1828
+ * ```
1829
+ */
1830
+ function update(node, changes) {
1831
+ for (const key in changes) if (changes[key] !== node[key]) return {
1832
+ ...node,
1833
+ ...changes
2214
1834
  };
2215
- return propNode;
1835
+ return node;
2216
1836
  }
2217
1837
  //#endregion
2218
- exports.caseParams = caseParams;
1838
+ //#region src/exports.ts
1839
+ var exports_exports = /* @__PURE__ */ __exportAll({
1840
+ applyMacros: () => applyMacros,
1841
+ arrowFunctionDef: () => arrowFunctionDef,
1842
+ breakDef: () => breakDef,
1843
+ childName: () => childName,
1844
+ collect: () => collect,
1845
+ collectUsedSchemaNames: () => collectUsedSchemaNames,
1846
+ combineExports: () => combineExports,
1847
+ combineImports: () => combineImports,
1848
+ combineSources: () => combineSources,
1849
+ composeMacros: () => composeMacros,
1850
+ constDef: () => constDef,
1851
+ containsCircularRef: () => containsCircularRef,
1852
+ contentDef: () => contentDef,
1853
+ createPrinter: () => createPrinter,
1854
+ defineMacro: () => defineMacro,
1855
+ defineNode: () => defineNode,
1856
+ enumPropName: () => enumPropName,
1857
+ exportDef: () => exportDef,
1858
+ extractRefName: () => extractRefName,
1859
+ extractStringsFromNodes: () => extractStringsFromNodes,
1860
+ factory: () => factory_exports,
1861
+ fileDef: () => fileDef,
1862
+ findCircularSchemas: () => findCircularSchemas,
1863
+ functionDef: () => functionDef,
1864
+ importDef: () => importDef,
1865
+ inputDef: () => inputDef,
1866
+ isHttpOperationNode: () => isHttpOperationNode,
1867
+ isStringType: () => isStringType,
1868
+ jsxDef: () => jsxDef,
1869
+ macroDiscriminatorEnum: () => macroDiscriminatorEnum,
1870
+ macroEnumName: () => macroEnumName,
1871
+ macroSimplifyUnion: () => macroSimplifyUnion,
1872
+ mapSchemaItems: () => mapSchemaItems,
1873
+ mapSchemaMembers: () => mapSchemaMembers,
1874
+ mapSchemaProperties: () => mapSchemaProperties,
1875
+ mergeAdjacentObjectsLazy: () => mergeAdjacentObjectsLazy,
1876
+ narrowSchema: () => narrowSchema,
1877
+ nodeDefs: () => nodeDefs,
1878
+ operationDef: () => operationDef,
1879
+ optionality: () => optionality,
1880
+ outputDef: () => outputDef,
1881
+ parameterDef: () => parameterDef,
1882
+ propertyDef: () => propertyDef,
1883
+ requestBodyDef: () => requestBodyDef,
1884
+ responseDef: () => responseDef,
1885
+ schemaDef: () => schemaDef,
1886
+ schemaTypes: () => schemaTypes,
1887
+ sourceDef: () => sourceDef,
1888
+ syncSchemaRef: () => syncSchemaRef,
1889
+ textDef: () => textDef,
1890
+ transform: () => transform,
1891
+ typeDef: () => typeDef
1892
+ });
1893
+ //#endregion
1894
+ exports.applyMacros = applyMacros;
1895
+ exports.arrowFunctionDef = arrowFunctionDef;
1896
+ Object.defineProperty(exports, "ast", {
1897
+ enumerable: true,
1898
+ get: function() {
1899
+ return exports_exports;
1900
+ }
1901
+ });
1902
+ exports.breakDef = breakDef;
2219
1903
  exports.childName = childName;
2220
1904
  exports.collect = collect;
2221
- exports.collectImports = collectImports;
2222
- exports.collectReferencedSchemaNames = collectReferencedSchemaNames;
2223
1905
  exports.collectUsedSchemaNames = collectUsedSchemaNames;
1906
+ exports.combineExports = combineExports;
1907
+ exports.combineImports = combineImports;
1908
+ exports.combineSources = combineSources;
1909
+ exports.composeMacros = composeMacros;
1910
+ exports.constDef = constDef;
2224
1911
  exports.containsCircularRef = containsCircularRef;
2225
- exports.createArrowFunction = createArrowFunction;
2226
- exports.createBreak = createBreak;
2227
- exports.createConst = createConst;
2228
- exports.createDiscriminantNode = createDiscriminantNode;
2229
- exports.createExport = createExport;
2230
- exports.createFile = createFile;
2231
- exports.createFunction = createFunction;
2232
- exports.createFunctionParameter = createFunctionParameter;
2233
- exports.createFunctionParameters = createFunctionParameters;
2234
- exports.createImport = createImport;
2235
- exports.createInput = createInput;
2236
- exports.createJsx = createJsx;
2237
- exports.createOperation = createOperation;
2238
- exports.createOperationParams = createOperationParams;
2239
- exports.createOutput = createOutput;
2240
- exports.createParameter = createParameter;
2241
- exports.createParameterGroup = createParameterGroup;
2242
- exports.createParamsType = createParamsType;
2243
- exports.createPrinterFactory = createPrinterFactory;
2244
- exports.createProperty = createProperty;
2245
- exports.createResponse = createResponse;
2246
- exports.createSchema = createSchema;
2247
- exports.createSource = createSource;
2248
- exports.createText = createText;
2249
- exports.createType = createType;
2250
- exports.definePrinter = definePrinter;
1912
+ exports.contentDef = contentDef;
1913
+ exports.createPrinter = createPrinter;
1914
+ exports.defineMacro = defineMacro;
1915
+ exports.defineNode = defineNode;
2251
1916
  exports.enumPropName = enumPropName;
1917
+ exports.exportDef = exportDef;
2252
1918
  exports.extractRefName = extractRefName;
2253
1919
  exports.extractStringsFromNodes = extractStringsFromNodes;
1920
+ Object.defineProperty(exports, "factory", {
1921
+ enumerable: true,
1922
+ get: function() {
1923
+ return factory_exports;
1924
+ }
1925
+ });
1926
+ exports.fileDef = fileDef;
2254
1927
  exports.findCircularSchemas = findCircularSchemas;
2255
- exports.findDiscriminator = findDiscriminator;
2256
- exports.httpMethods = httpMethods;
2257
- exports.isInputNode = isInputNode;
2258
- exports.isOperationNode = isOperationNode;
2259
- exports.isOutputNode = isOutputNode;
2260
- exports.isScalarPrimitive = isScalarPrimitive;
2261
- exports.isSchemaNode = isSchemaNode;
1928
+ exports.functionDef = functionDef;
1929
+ exports.importDef = importDef;
1930
+ exports.inputDef = inputDef;
1931
+ exports.isHttpOperationNode = isHttpOperationNode;
2262
1932
  exports.isStringType = isStringType;
2263
- exports.mediaTypes = mediaTypes;
2264
- exports.mergeAdjacentObjects = mergeAdjacentObjects;
1933
+ exports.jsxDef = jsxDef;
1934
+ exports.macroDiscriminatorEnum = macroDiscriminatorEnum;
1935
+ exports.macroEnumName = macroEnumName;
1936
+ exports.macroSimplifyUnion = macroSimplifyUnion;
1937
+ exports.mapSchemaItems = mapSchemaItems;
1938
+ exports.mapSchemaMembers = mapSchemaMembers;
1939
+ exports.mapSchemaProperties = mapSchemaProperties;
1940
+ exports.mergeAdjacentObjectsLazy = mergeAdjacentObjectsLazy;
2265
1941
  exports.narrowSchema = narrowSchema;
2266
- exports.nodeKinds = nodeKinds;
2267
- exports.resolveRefName = resolveRefName;
1942
+ exports.nodeDefs = nodeDefs;
1943
+ exports.operationDef = operationDef;
1944
+ exports.optionality = optionality;
1945
+ exports.outputDef = outputDef;
1946
+ exports.parameterDef = parameterDef;
1947
+ exports.propertyDef = propertyDef;
1948
+ exports.requestBodyDef = requestBodyDef;
1949
+ exports.responseDef = responseDef;
1950
+ exports.schemaDef = schemaDef;
2268
1951
  exports.schemaTypes = schemaTypes;
2269
- exports.setDiscriminatorEnum = setDiscriminatorEnum;
2270
- exports.setEnumName = setEnumName;
2271
- exports.simplifyUnion = simplifyUnion;
2272
- exports.syncOptionality = syncOptionality;
1952
+ exports.sourceDef = sourceDef;
2273
1953
  exports.syncSchemaRef = syncSchemaRef;
1954
+ exports.textDef = textDef;
2274
1955
  exports.transform = transform;
2275
- exports.walk = walk;
1956
+ exports.typeDef = typeDef;
2276
1957
 
2277
1958
  //# sourceMappingURL=index.cjs.map