@kubb/ast 5.0.0-beta.56 → 5.0.0-beta.58

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/README.md +13 -9
  2. package/dist/{types-BL7RpQAE.d.ts → ast-ClnJg9BN.d.ts} +1630 -2443
  3. package/dist/chunk-CNktS9qV.js +17 -0
  4. package/dist/extractStringsFromNodes-Bn9cOos9.d.ts +14 -0
  5. package/dist/factory-C5gHvtLU.js +138 -0
  6. package/dist/factory-C5gHvtLU.js.map +1 -0
  7. package/dist/factory-JN-Ylfl6.cjs +155 -0
  8. package/dist/factory-JN-Ylfl6.cjs.map +1 -0
  9. package/dist/factory.cjs +31 -0
  10. package/dist/factory.d.ts +62 -0
  11. package/dist/factory.js +3 -0
  12. package/dist/index.cjs +56 -1751
  13. package/dist/index.cjs.map +1 -1
  14. package/dist/index.d.ts +6 -47
  15. package/dist/index.js +7 -1697
  16. package/dist/index.js.map +1 -1
  17. package/dist/types-CB2oY8Dw.d.ts +769 -0
  18. package/dist/types.d.ts +4 -2
  19. package/dist/utils-C8bWAzhv.cjs +2696 -0
  20. package/dist/utils-C8bWAzhv.cjs.map +1 -0
  21. package/dist/utils-DN4XLVqz.js +2099 -0
  22. package/dist/utils-DN4XLVqz.js.map +1 -0
  23. package/dist/utils.cjs +12 -1
  24. package/dist/utils.d.ts +21 -2
  25. package/dist/utils.js +2 -2
  26. package/package.json +5 -1
  27. package/src/dedupe.ts +1 -1
  28. package/src/factory.ts +22 -764
  29. package/src/guards.ts +1 -53
  30. package/src/index.ts +20 -39
  31. package/src/mocks.ts +6 -1
  32. package/src/node.ts +128 -0
  33. package/src/nodes/base.ts +3 -12
  34. package/src/nodes/code.ts +115 -0
  35. package/src/nodes/content.ts +19 -0
  36. package/src/nodes/file.ts +54 -0
  37. package/src/nodes/function.ts +222 -147
  38. package/src/nodes/index.ts +11 -3
  39. package/src/nodes/input.ts +37 -0
  40. package/src/nodes/operation.ts +59 -1
  41. package/src/nodes/output.ts +23 -0
  42. package/src/nodes/parameter.ts +33 -0
  43. package/src/nodes/property.ts +36 -0
  44. package/src/nodes/requestBody.ts +23 -1
  45. package/src/nodes/response.ts +39 -1
  46. package/src/nodes/schema.ts +72 -0
  47. package/src/printer.ts +3 -3
  48. package/src/registry.ts +70 -0
  49. package/src/transformers.ts +2 -2
  50. package/src/types.ts +6 -4
  51. package/src/utils/ast.ts +103 -243
  52. package/src/utils/extractStringsFromNodes.ts +34 -0
  53. package/src/utils/index.ts +44 -0
  54. package/src/visitor.ts +3 -47
  55. package/dist/chunk-C0LytTxp.js +0 -8
  56. package/dist/utils-0p8ZO287.js +0 -570
  57. package/dist/utils-0p8ZO287.js.map +0 -1
  58. package/dist/utils-cdQ6Pzyi.cjs +0 -726
  59. package/dist/utils-cdQ6Pzyi.cjs.map +0 -1
package/dist/index.js CHANGED
@@ -1,1697 +1,7 @@
1
- import "./chunk-C0LytTxp.js";
2
- import { _ as httpMethods, a as enumPropName, b as visitorDepths, g as camelCase, h as isValidVarName, o as extractRefName, v as isScalarPrimitive, y as schemaTypes } from "./utils-0p8ZO287.js";
1
+ import "./chunk-CNktS9qV.js";
2
+ import { $ as contentDef, A as collect, Ct as functionParametersDef, Dt as isHttpOperationNode, Et as typeLiteralDef, F as responseDef, Ft as httpMethods, G as inputDef, It as isScalarPrimitive, L as parameterDef, Lt as schemaTypes, M as transform, Mt as schemaDef, N as walk, Nt as defineNode, Ot as narrowSchema, Pt as syncOptionality, Q as sourceDef, St as functionParameterDef, Tt as objectBindingPatternDef, U as requestBodyDef, V as operationDef, X as fileDef, Y as exportDef, Z as importDef, a as enumPropName, dt as functionDef, ft as jsxDef, gt as propertyDef, ht as createProperty, j as collectLazy, jt as createSchema, kt as extractStringsFromNodes, mt as typeDef, nt as breakDef, o as extractRefName, pt as textDef, rt as constDef, tt as arrowFunctionDef, wt as indexedAccessTypeDef, z as outputDef } from "./utils-DN4XLVqz.js";
3
+ import { n as factory_exports } from "./factory-C5gHvtLU.js";
3
4
  import { hash } from "node:crypto";
4
- import path from "node:path";
5
- //#region ../../internals/utils/src/fs.ts
6
- /**
7
- * Strips the file extension from a path or file name.
8
- * Only removes the last `.ext` segment when the dot is not part of a directory name.
9
- *
10
- * @example
11
- * trimExtName('petStore.ts') // 'petStore'
12
- * trimExtName('/src/models/pet.ts') // '/src/models/pet'
13
- * trimExtName('/project.v2/gen/pet.ts') // '/project.v2/gen/pet'
14
- * trimExtName('noExtension') // 'noExtension'
15
- */
16
- function trimExtName(text) {
17
- const dotIndex = text.lastIndexOf(".");
18
- if (dotIndex > 0 && !text.includes("/", dotIndex)) return text.slice(0, dotIndex);
19
- return text;
20
- }
21
- //#endregion
22
- //#region ../../internals/utils/src/promise.ts
23
- /**
24
- * Wraps `factory` with a keyed cache backed by the provided store.
25
- *
26
- * Pass a `WeakMap` for object keys (results are GC-eligible when the key is
27
- * collected) or a `Map` for primitive keys. For multi-argument functions,
28
- * nest two `memoize` calls — the outer keyed by the first argument, the
29
- * inner (created once per outer miss) keyed by the second.
30
- *
31
- * Because the cache is owned by the caller, it can be shared, inspected, or
32
- * cleared independently of the memoized function.
33
- *
34
- * @example Single WeakMap key
35
- * ```ts
36
- * const cache = new WeakMap<SchemaNode, Set<string>>()
37
- * const getRefs = memoize(cache, (node) => collectRefs(node))
38
- * ```
39
- *
40
- * @example Single Map key (primitive)
41
- * ```ts
42
- * const cache = new Map<string, Resolver>()
43
- * const getResolver = memoize(cache, (name) => buildResolver(name))
44
- * ```
45
- *
46
- * @example Two-level (object + primitive)
47
- * ```ts
48
- * const outer = new WeakMap<Params[], Map<string, Params[]>>()
49
- * const fn = memoize(outer, (params) => memoize(new Map(), (key) => transform(params, key)))
50
- * fn(params)('camelcase')
51
- * ```
52
- */
53
- function memoize(store, factory) {
54
- return (key) => {
55
- if (store.has(key)) return store.get(key);
56
- const value = factory(key);
57
- store.set(key, value);
58
- return value;
59
- };
60
- }
61
- //#endregion
62
- //#region src/guards.ts
63
- /**
64
- * Narrows a `SchemaNode` to the variant that matches `type`.
65
- *
66
- * @example
67
- * ```ts
68
- * const schema = createSchema({ type: 'string' })
69
- * const stringNode = narrowSchema(schema, 'string') // StringSchemaNode | null
70
- * ```
71
- */
72
- function narrowSchema(node, type) {
73
- return node?.type === type ? node : null;
74
- }
75
- function isKind(kind) {
76
- return (node) => node.kind === kind;
77
- }
78
- /**
79
- * Returns `true` when the input is an `InputNode`.
80
- *
81
- * @example
82
- * ```ts
83
- * if (isInputNode(node)) {
84
- * console.log(node.schemas.length)
85
- * }
86
- * ```
87
- */
88
- const isInputNode = isKind("Input");
89
- /**
90
- * Returns `true` when the input is an `OutputNode`.
91
- *
92
- * @example
93
- * ```ts
94
- * if (isOutputNode(node)) {
95
- * console.log(node.files.length)
96
- * }
97
- * ```
98
- */
99
- const isOutputNode = isKind("Output");
100
- /**
101
- * Returns `true` when the input is an `OperationNode`.
102
- *
103
- * @example
104
- * ```ts
105
- * if (isOperationNode(node)) {
106
- * console.log(node.operationId)
107
- * }
108
- * ```
109
- */
110
- const isOperationNode = isKind("Operation");
111
- /**
112
- * Narrows an `OperationNode` to an `HttpOperationNode`, guaranteeing `method` and `path`.
113
- *
114
- * @example
115
- * ```ts
116
- * if (isHttpOperationNode(node)) {
117
- * console.log(node.method, node.path)
118
- * }
119
- * ```
120
- */
121
- function isHttpOperationNode(node) {
122
- return node.protocol === "http" || node.method !== void 0 && node.path !== void 0;
123
- }
124
- /**
125
- * Returns `true` when the input is a `SchemaNode`.
126
- *
127
- * @example
128
- * ```ts
129
- * if (isSchemaNode(node)) {
130
- * console.log(node.type)
131
- * }
132
- * ```
133
- */
134
- const isSchemaNode = isKind("Schema");
135
- //#endregion
136
- //#region src/visitor.ts
137
- /**
138
- * Creates a small async concurrency limiter.
139
- *
140
- * At most `concurrency` tasks are in flight at once. Extra tasks are queued.
141
- *
142
- * @example
143
- * ```ts
144
- * const limit = createLimit(2)
145
- * for (const task of [taskA, taskB, taskC]) {
146
- * await limit(() => task())
147
- * }
148
- * // only 2 tasks run at the same time
149
- * ```
150
- */
151
- function createLimit(concurrency) {
152
- let active = 0;
153
- const queue = [];
154
- function next() {
155
- if (active < concurrency && queue.length > 0) {
156
- active++;
157
- queue.shift()();
158
- }
159
- }
160
- return function limit(fn) {
161
- return new Promise((resolve, reject) => {
162
- queue.push(() => {
163
- Promise.resolve(fn()).then(resolve, reject).finally(() => {
164
- active--;
165
- next();
166
- });
167
- });
168
- next();
169
- });
170
- };
171
- }
172
- const visitorKeysByKind = {
173
- Input: ["schemas", "operations"],
174
- Operation: [
175
- "parameters",
176
- "requestBody",
177
- "responses"
178
- ],
179
- RequestBody: ["content"],
180
- Content: ["schema"],
181
- Response: ["content"],
182
- Schema: [
183
- "properties",
184
- "items",
185
- "members",
186
- "additionalProperties"
187
- ],
188
- Property: ["schema"],
189
- Parameter: ["schema"]
190
- };
191
- /**
192
- * Returns `true` when `value` is an AST node (an object carrying a `kind`).
193
- */
194
- function isNode(value) {
195
- return typeof value === "object" && value !== null && "kind" in value;
196
- }
197
- /**
198
- * Returns the immediate traversable children of `node` based on {@link VISITOR_KEYS}.
199
- *
200
- * `Schema` children are only included when `recurse` is `true`. Shallow mode skips them.
201
- *
202
- * @example
203
- * ```ts
204
- * const children = getChildren(operationNode, true)
205
- * // returns parameters, the request body, and responses
206
- * ```
207
- */
208
- function* getChildren(node, recurse) {
209
- if (node.kind === "Schema" && !recurse) return;
210
- const keys = visitorKeysByKind[node.kind];
211
- if (!keys) return;
212
- const record = node;
213
- for (const key of keys) {
214
- const value = record[key];
215
- if (Array.isArray(value)) {
216
- for (const item of value) if (isNode(item)) yield item;
217
- } else if (isNode(value)) yield value;
218
- }
219
- }
220
- /**
221
- * Maps a node `kind` to the matching visitor callback name. Only the seven
222
- * traversable node kinds have an entry. Every other kind resolves to
223
- * `undefined` and is skipped.
224
- */
225
- const VISITOR_KEY_BY_KIND = {
226
- Input: "input",
227
- Output: "output",
228
- Operation: "operation",
229
- Schema: "schema",
230
- Property: "property",
231
- Parameter: "parameter",
232
- Response: "response"
233
- };
234
- /**
235
- * Invokes the visitor callback that matches `node.kind`, passing the traversal
236
- * context. Returns the callback's result (a replacement node, a collected
237
- * value, or `undefined` when no callback is registered for the kind).
238
- *
239
- * Shared by `walk`, `transform`, and `collectLazy` so node-kind dispatch lives
240
- * in one place. `TResult` is the caller's expected return: the same node type
241
- * for `transform`, the collected value type for `collectLazy`, ignored for `walk`.
242
- */
243
- function applyVisitor(node, visitor, parent) {
244
- const key = VISITOR_KEY_BY_KIND[node.kind];
245
- if (!key) return void 0;
246
- const fn = visitor[key];
247
- return fn?.(node, { parent });
248
- }
249
- /**
250
- * Async depth-first traversal for side effects. Visitor return values are
251
- * ignored. Use `transform` when you want to rewrite nodes.
252
- *
253
- * Sibling nodes at each depth run concurrently up to `options.concurrency`
254
- * (defaults to `WALK_CONCURRENCY`). Higher values overlap I/O-bound visitor
255
- * work. Lower values reduce memory pressure.
256
- *
257
- * @example Log every operation
258
- * ```ts
259
- * await walk(root, {
260
- * operation(node) {
261
- * console.log(node.operationId)
262
- * },
263
- * })
264
- * ```
265
- *
266
- * @example Only visit the root node
267
- * ```ts
268
- * await walk(root, { depth: 'shallow', input: () => {} })
269
- * ```
270
- */
271
- async function walk(node, options) {
272
- return _walk(node, options, (options.depth ?? visitorDepths.deep) === visitorDepths.deep, createLimit(options.concurrency ?? 30), void 0);
273
- }
274
- async function _walk(node, visitor, recurse, limit, parent) {
275
- await limit(() => applyVisitor(node, visitor, parent));
276
- const children = Array.from(getChildren(node, recurse));
277
- if (children.length === 0) return;
278
- await Promise.all(children.map((child) => _walk(child, visitor, recurse, limit, node)));
279
- }
280
- function transform(node, options) {
281
- const { depth, parent, ...visitor } = options;
282
- const recurse = (depth ?? visitorDepths.deep) === visitorDepths.deep;
283
- const rebuilt = transformChildren(applyVisitor(node, visitor, parent) ?? node, options, recurse);
284
- if (rebuilt === node) return node;
285
- const finalize = nodeFinalizers[rebuilt.kind];
286
- return finalize ? finalize(rebuilt) : rebuilt;
287
- }
288
- /**
289
- * Per-kind builders rerun after children are rebuilt. `Property`/`Parameter`
290
- * resync schema optionality against their `required` flag once the schema may
291
- * have changed.
292
- */
293
- const nodeFinalizers = {
294
- Property: (node) => createProperty(node),
295
- Parameter: (node) => createParameter(node)
296
- };
297
- /**
298
- * Immutably rebuilds a node's children using {@link VISITOR_KEYS}, transforming
299
- * each child node and leaving non-node values (e.g. `additionalProperties: true`) intact.
300
- * `Schema` children are skipped in shallow mode.
301
- */
302
- function transformChildren(node, options, recurse) {
303
- if (node.kind === "Schema" && !recurse) return node;
304
- const keys = visitorKeysByKind[node.kind];
305
- if (!keys) return node;
306
- const record = node;
307
- const childOptions = {
308
- ...options,
309
- parent: node
310
- };
311
- let updates;
312
- for (const key of keys) {
313
- if (!(key in record)) continue;
314
- const value = record[key];
315
- if (Array.isArray(value)) {
316
- let changed = false;
317
- const mapped = value.map((item) => {
318
- if (!isNode(item)) return item;
319
- const next = transform(item, childOptions);
320
- if (next !== item) changed = true;
321
- return next;
322
- });
323
- if (changed) (updates ??= {})[key] = mapped;
324
- } else if (isNode(value)) {
325
- const next = transform(value, childOptions);
326
- if (next !== value) (updates ??= {})[key] = next;
327
- }
328
- }
329
- return updates ? {
330
- ...node,
331
- ...updates
332
- } : node;
333
- }
334
- /**
335
- * Lazy depth-first collection pass. Yields every non-null value returned by
336
- * the visitor callbacks. Use `collect` for the eager array form.
337
- *
338
- * @example Collect every operationId
339
- * ```ts
340
- * const ids: string[] = []
341
- * for (const id of collectLazy<string>(root, {
342
- * operation(node) {
343
- * return node.operationId
344
- * },
345
- * })) {
346
- * ids.push(id)
347
- * }
348
- * ```
349
- */
350
- function* collectLazy(node, options) {
351
- const { depth, parent, ...visitor } = options;
352
- const recurse = (depth ?? visitorDepths.deep) === visitorDepths.deep;
353
- const v = applyVisitor(node, visitor, parent);
354
- if (v != null) yield v;
355
- for (const child of getChildren(node, recurse)) yield* collectLazy(child, {
356
- ...options,
357
- parent: node
358
- });
359
- }
360
- /**
361
- * Eager depth-first collection pass. Returns an array of every non-null value
362
- * the visitor callbacks return.
363
- *
364
- * @example Collect every operationId
365
- * ```ts
366
- * const ids = collect<string>(root, {
367
- * operation(node) {
368
- * return node.operationId
369
- * },
370
- * })
371
- * ```
372
- */
373
- function collect(node, options) {
374
- return Array.from(collectLazy(node, options));
375
- }
376
- //#endregion
377
- //#region src/utils/ast.ts
378
- const plainStringTypes = new Set([
379
- "string",
380
- "uuid",
381
- "email",
382
- "url",
383
- "datetime"
384
- ]);
385
- /**
386
- * Merges a ref node with its resolved schema, giving usage-site fields precedence.
387
- *
388
- * Usage-site fields (`description`, `readOnly`, `nullable`, `deprecated`) on the ref node
389
- * override the same fields in the resolved `node.schema`. Non-ref nodes are returned unchanged.
390
- *
391
- * @example
392
- * ```ts
393
- * // Ref with description override
394
- * const ref = createSchema({ type: 'ref', ref: '#/components/schemas/Pet', description: 'A cute pet' })
395
- * const merged = syncSchemaRef(ref) // merges with resolved Pet schema
396
- * ```
397
- */
398
- function syncSchemaRef(node) {
399
- const ref = narrowSchema(node, "ref");
400
- if (!ref) return node;
401
- if (!ref.schema) return node;
402
- const { kind: _kind, type: _type, name: _name, ref: _ref, schema: _schema, ...overrides } = ref;
403
- const definedOverrides = Object.fromEntries(Object.entries(overrides).filter(([, v]) => v !== void 0));
404
- return createSchema({
405
- ...ref.schema,
406
- ...definedOverrides
407
- });
408
- }
409
- /**
410
- * Type guard that returns `true` when a schema emits as a plain `string` type.
411
- *
412
- * Covers `string`, `uuid`, `email`, `url`, and `datetime` types. For `date` and `time`
413
- * types, returns `true` only when `representation` is `'string'` rather than `'date'`.
414
- */
415
- function isStringType(node) {
416
- if (plainStringTypes.has(node.type)) return true;
417
- const temporal = narrowSchema(node, "date") ?? narrowSchema(node, "time");
418
- if (temporal) return temporal.representation !== "date";
419
- return false;
420
- }
421
- /**
422
- * Applies casing rules to parameter names and returns a new parameter array.
423
- *
424
- * Use this before passing parameters to schema builders so output property keys match
425
- * the desired casing while preserving `OperationNode.parameters` for other consumers.
426
- * The input array is not mutated. When `casing` is not set, the original array is returned unchanged.
427
- */
428
- const caseParamsMemo = memoize(/* @__PURE__ */ new WeakMap(), (params) => memoize(/* @__PURE__ */ new Map(), (casing) => params.map((param) => {
429
- const transformed = casing === "camelcase" || !isValidVarName(param.name) ? camelCase(param.name) : param.name;
430
- return {
431
- ...param,
432
- name: transformed
433
- };
434
- })));
435
- function caseParams(params, casing) {
436
- if (!casing) return params;
437
- return caseParamsMemo(params)(casing);
438
- }
439
- /**
440
- * Creates a single-property object schema used as a discriminator literal.
441
- *
442
- * @example
443
- * ```ts
444
- * createDiscriminantNode({ propertyName: 'type', value: 'dog' })
445
- * // -> { type: 'object', properties: [{ name: 'type', required: true, schema: enum('dog') }] }
446
- * ```
447
- */
448
- function createDiscriminantNode({ propertyName, value }) {
449
- return createSchema({
450
- type: "object",
451
- primitive: "object",
452
- properties: [createProperty({
453
- name: propertyName,
454
- schema: createSchema({
455
- type: "enum",
456
- primitive: "string",
457
- enumValues: [value]
458
- }),
459
- required: true
460
- })]
461
- });
462
- }
463
- function resolveParamsType({ node, param, resolver }) {
464
- if (!resolver) return createParamsType({
465
- variant: "reference",
466
- name: param.schema.primitive ?? "unknown"
467
- });
468
- const individualName = resolver.resolveParamName(node, param);
469
- const groupLocation = param.in === "path" || param.in === "query" || param.in === "header" ? param.in : void 0;
470
- const groupResolvers = {
471
- path: resolver.resolvePathParamsName,
472
- query: resolver.resolveQueryParamsName,
473
- header: resolver.resolveHeaderParamsName
474
- };
475
- const groupName = groupLocation ? groupResolvers[groupLocation].call(resolver, node, param) : void 0;
476
- if (groupName && groupName !== individualName) return createParamsType({
477
- variant: "member",
478
- base: groupName,
479
- key: param.name
480
- });
481
- return createParamsType({
482
- variant: "reference",
483
- name: individualName
484
- });
485
- }
486
- /**
487
- * Converts an `OperationNode` into function parameters for code generation.
488
- *
489
- * Centralizes parameter grouping logic for all plugins. Provide a `resolver` for type name resolution
490
- * and `extraParams` for plugin-specific trailing parameters (e.g., `options` objects).
491
- * Supports three grouping modes: `object` (single destructured param), `inline` (separate params),
492
- * and `inlineSpread` (rest parameter). Use `CreateOperationParamsOptions` to fine-tune output.
493
- */
494
- function createOperationParams(node, options) {
495
- const { paramsType, pathParamsType, paramsCasing, resolver, pathParamsDefault, extraParams = [], paramNames, typeWrapper } = options;
496
- const dataName = paramNames?.data ?? "data";
497
- const paramsName = paramNames?.params ?? "params";
498
- const headersName = paramNames?.headers ?? "headers";
499
- const pathName = paramNames?.path ?? "pathParams";
500
- const wrapType = (type) => createParamsType({
501
- variant: "reference",
502
- name: typeWrapper ? typeWrapper(type) : type
503
- });
504
- const wrapTypeNode = (type) => type.kind === "ParamsType" && type.variant === "reference" ? wrapType(type.name) : type;
505
- const casedParams = caseParams(node.parameters, paramsCasing);
506
- const pathParams = casedParams.filter((p) => p.in === "path");
507
- const queryParams = casedParams.filter((p) => p.in === "query");
508
- const headerParams = casedParams.filter((p) => p.in === "header");
509
- const bodyType = node.requestBody?.content?.[0]?.schema ? wrapType(resolver?.resolveDataName(node) ?? "unknown") : void 0;
510
- const bodyRequired = node.requestBody?.required ?? false;
511
- const queryGroupType = resolver ? resolveGroupType({
512
- node,
513
- params: queryParams,
514
- groupMethod: resolver.resolveQueryParamsName,
515
- resolver
516
- }) : void 0;
517
- const headerGroupType = resolver ? resolveGroupType({
518
- node,
519
- params: headerParams,
520
- groupMethod: resolver.resolveHeaderParamsName,
521
- resolver
522
- }) : void 0;
523
- const params = [];
524
- if (paramsType === "object") {
525
- const children = [
526
- ...pathParams.map((p) => {
527
- const type = resolveParamsType({
528
- node,
529
- param: p,
530
- resolver
531
- });
532
- return createFunctionParameter({
533
- name: p.name,
534
- type: wrapTypeNode(type),
535
- optional: !p.required
536
- });
537
- }),
538
- ...bodyType ? [createFunctionParameter({
539
- name: dataName,
540
- type: bodyType,
541
- optional: !bodyRequired
542
- })] : [],
543
- ...buildGroupParam({
544
- name: paramsName,
545
- node,
546
- params: queryParams,
547
- groupType: queryGroupType,
548
- resolver,
549
- wrapType
550
- }),
551
- ...buildGroupParam({
552
- name: headersName,
553
- node,
554
- params: headerParams,
555
- groupType: headerGroupType,
556
- resolver,
557
- wrapType
558
- })
559
- ];
560
- if (children.length) params.push(createParameterGroup({
561
- properties: children,
562
- default: children.every((c) => c.optional) ? "{}" : void 0
563
- }));
564
- } else {
565
- if (pathParams.length) if (pathParamsType === "inlineSpread") {
566
- const spreadType = resolver?.resolvePathParamsName(node, pathParams[0]);
567
- params.push(createFunctionParameter({
568
- name: pathName,
569
- type: spreadType ? wrapType(spreadType) : void 0,
570
- rest: true
571
- }));
572
- } else {
573
- const pathChildren = pathParams.map((p) => {
574
- const type = resolveParamsType({
575
- node,
576
- param: p,
577
- resolver
578
- });
579
- return createFunctionParameter({
580
- name: p.name,
581
- type: wrapTypeNode(type),
582
- optional: !p.required
583
- });
584
- });
585
- params.push(createParameterGroup({
586
- properties: pathChildren,
587
- inline: pathParamsType === "inline",
588
- default: pathParamsDefault ?? (pathChildren.every((c) => c.optional) ? "{}" : void 0)
589
- }));
590
- }
591
- if (bodyType) params.push(createFunctionParameter({
592
- name: dataName,
593
- type: bodyType,
594
- optional: !bodyRequired
595
- }));
596
- params.push(...buildGroupParam({
597
- name: paramsName,
598
- node,
599
- params: queryParams,
600
- groupType: queryGroupType,
601
- resolver,
602
- wrapType
603
- }));
604
- params.push(...buildGroupParam({
605
- name: headersName,
606
- node,
607
- params: headerParams,
608
- groupType: headerGroupType,
609
- resolver,
610
- wrapType
611
- }));
612
- }
613
- params.push(...extraParams);
614
- return createFunctionParameters({ params });
615
- }
616
- /**
617
- * Builds a single {@link FunctionParameterNode} for a query or header group.
618
- * Returns an empty array when there are no params to emit.
619
- *
620
- * If a pre-resolved `groupType` is provided it emits `name: GroupType`.
621
- * Otherwise, it builds an inline struct from the individual params.
622
- */
623
- function buildGroupParam({ name, node, params, groupType, resolver, wrapType }) {
624
- if (groupType) return [createFunctionParameter({
625
- name,
626
- type: groupType.type.kind === "ParamsType" && groupType.type.variant === "reference" ? wrapType(groupType.type.name) : groupType.type,
627
- optional: groupType.optional
628
- })];
629
- if (params.length) return [createFunctionParameter({
630
- name,
631
- type: toStructType({
632
- node,
633
- params,
634
- resolver
635
- }),
636
- optional: params.every((p) => !p.required)
637
- })];
638
- return [];
639
- }
640
- /**
641
- * Derives a {@link ParamGroupType} from the resolver's group method.
642
- * Returns `null` when the group name equals the individual param name (no real group).
643
- */
644
- function resolveGroupType({ node, params, groupMethod, resolver }) {
645
- if (!params.length) return null;
646
- const firstParam = params[0];
647
- const groupName = groupMethod.call(resolver, node, firstParam);
648
- if (groupName === resolver.resolveParamName(node, firstParam)) return null;
649
- const allOptional = params.every((p) => !p.required);
650
- return {
651
- type: createParamsType({
652
- variant: "reference",
653
- name: groupName
654
- }),
655
- optional: allOptional
656
- };
657
- }
658
- /**
659
- * Builds a {@link TypeNode} with `variant: 'struct'` for an inline anonymous type grouping named fields.
660
- *
661
- * Used when query or header parameters have no dedicated group type name.
662
- * Each language printer renders this appropriately (TypeScript: `{ petId: string; name?: string }`).
663
- */
664
- function toStructType({ node, params, resolver }) {
665
- return createParamsType({
666
- variant: "struct",
667
- properties: params.map((p) => ({
668
- name: p.name,
669
- optional: !p.required,
670
- type: resolveParamsType({
671
- node,
672
- param: p,
673
- resolver
674
- })
675
- }))
676
- });
677
- }
678
- function sourceKey(source) {
679
- return `${source.name ?? extractStringsFromNodes(source.nodes)}:${source.isExportable ?? false}:${source.isTypeOnly ?? false}`;
680
- }
681
- function pathTypeKey(path, isTypeOnly) {
682
- return `${path}:${isTypeOnly ?? false}`;
683
- }
684
- function exportKey(path, name, isTypeOnly, asAlias) {
685
- return `${path}:${name ?? ""}:${isTypeOnly ?? false}:${asAlias ?? ""}`;
686
- }
687
- function importKey(path, name, isTypeOnly) {
688
- return `${path}:${name ?? ""}:${isTypeOnly ?? false}`;
689
- }
690
- /**
691
- * Computes a multi-level sort key for exports and imports:
692
- * non-array names first (wildcards/namespace aliases). Type-only before value. Alphabetical path. Unnamed before named.
693
- */
694
- function sortKey(node) {
695
- const isArray = Array.isArray(node.name) ? "1" : "0";
696
- const typeOnly = node.isTypeOnly ? "0" : "1";
697
- const hasName = node.name != null ? "1" : "0";
698
- const name = Array.isArray(node.name) ? node.name.toSorted().join("\0") : node.name ?? "";
699
- return `${isArray}:${typeOnly}:${node.path}:${hasName}:${name}`;
700
- }
701
- /**
702
- * Deduplicates and merges `SourceNode` objects by `name + isExportable + isTypeOnly`.
703
- *
704
- * Unnamed sources are deduplicated by object reference. Returns a deduplicated array in original order.
705
- */
706
- function combineSources(sources) {
707
- const seen = /* @__PURE__ */ new Map();
708
- for (const source of sources) {
709
- const key = sourceKey(source);
710
- if (!seen.has(key)) seen.set(key, source);
711
- }
712
- return [...seen.values()];
713
- }
714
- /**
715
- * Merges `incoming` names into `existing`, preserving order and dropping duplicates.
716
- *
717
- * Shared by `combineExports` and `combineImports` for the same-path name-merge case.
718
- */
719
- function mergeNameArrays(existing, incoming) {
720
- const merged = new Set(existing);
721
- for (const name of incoming) merged.add(name);
722
- return [...merged];
723
- }
724
- /**
725
- * Deduplicates and merges `ExportNode` objects by path and type.
726
- *
727
- * Named exports with the same path and `isTypeOnly` flag have their names merged into a single export.
728
- * Non-array exports are deduplicated by exact identity. Returns a sorted, deduplicated array.
729
- */
730
- function combineExports(exports) {
731
- const result = [];
732
- const namedByPath = /* @__PURE__ */ new Map();
733
- const seen = /* @__PURE__ */ new Set();
734
- const keyed = exports.map((node) => ({
735
- node,
736
- key: sortKey(node)
737
- }));
738
- keyed.sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
739
- for (const { node: curr } of keyed) {
740
- const { name, path, isTypeOnly, asAlias } = curr;
741
- if (Array.isArray(name)) {
742
- if (!name.length) continue;
743
- const key = pathTypeKey(path, isTypeOnly);
744
- const existing = namedByPath.get(key);
745
- if (existing && Array.isArray(existing.name)) existing.name = mergeNameArrays(existing.name, name);
746
- else {
747
- const newItem = {
748
- ...curr,
749
- name: [...new Set(name)]
750
- };
751
- result.push(newItem);
752
- namedByPath.set(key, newItem);
753
- }
754
- } else {
755
- const key = exportKey(path, name, isTypeOnly, asAlias);
756
- if (!seen.has(key)) {
757
- result.push(curr);
758
- seen.add(key);
759
- }
760
- }
761
- }
762
- return result;
763
- }
764
- /**
765
- * Deduplicates and merges `ImportNode` objects, filtering out unused imports.
766
- *
767
- * Retains imports that are referenced in `source` or re-exported. Imports with the same path and
768
- * `isTypeOnly` flag have their names merged. Returns a sorted, deduplicated, filtered array.
769
- *
770
- * @note Use this when combining imports from multiple files to avoid duplicate declarations.
771
- */
772
- function combineImports(imports, exports, source) {
773
- const exportedNames = new Set(exports.flatMap((e) => Array.isArray(e.name) ? e.name : e.name ? [e.name] : []));
774
- const isUsed = (importName) => !source || source.includes(importName) || exportedNames.has(importName);
775
- const importNameMemo = /* @__PURE__ */ new Map();
776
- const canonicalizeName = (n) => {
777
- if (typeof n === "string") return n;
778
- const key = `${n.propertyName}:${n.name ?? ""}`;
779
- if (!importNameMemo.has(key)) importNameMemo.set(key, n);
780
- return importNameMemo.get(key);
781
- };
782
- const pathsWithUsedNamedImport = /* @__PURE__ */ new Set();
783
- for (const node of imports) {
784
- if (!Array.isArray(node.name)) continue;
785
- if (node.name.some((item) => typeof item === "string" ? isUsed(item) : isUsed(item.name ?? item.propertyName))) pathsWithUsedNamedImport.add(node.path);
786
- }
787
- const result = [];
788
- const namedByPath = /* @__PURE__ */ new Map();
789
- const seen = /* @__PURE__ */ new Set();
790
- const keyed = imports.map((node) => ({
791
- node,
792
- key: sortKey(node)
793
- }));
794
- keyed.sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
795
- for (const { node: curr } of keyed) {
796
- if (curr.path === curr.root) continue;
797
- const { path, isTypeOnly } = curr;
798
- let { name } = curr;
799
- if (Array.isArray(name)) {
800
- name = [...new Set(name.map(canonicalizeName))].filter((item) => typeof item === "string" ? isUsed(item) : isUsed(item.name ?? item.propertyName));
801
- if (!name.length) continue;
802
- const key = pathTypeKey(path, isTypeOnly);
803
- const existing = namedByPath.get(key);
804
- if (existing && Array.isArray(existing.name)) existing.name = mergeNameArrays(existing.name, name);
805
- else {
806
- const newItem = {
807
- ...curr,
808
- name
809
- };
810
- result.push(newItem);
811
- namedByPath.set(key, newItem);
812
- }
813
- } else {
814
- if (name && !isUsed(name) && !pathsWithUsedNamedImport.has(path)) continue;
815
- const key = importKey(path, name, isTypeOnly);
816
- if (!seen.has(key)) {
817
- result.push(curr);
818
- seen.add(key);
819
- }
820
- }
821
- }
822
- return result;
823
- }
824
- /**
825
- * Extracts all string content from a `CodeNode` tree recursively.
826
- *
827
- * Collects text node values, identifier references in string fields (`params`, `generics`, `returnType`, `type`),
828
- * and nested node content. Used internally to build the full source string for import filtering.
829
- */
830
- function extractStringsFromNodes(nodes) {
831
- if (!nodes?.length) return "";
832
- return nodes.map((node) => {
833
- if (typeof node === "string") return node;
834
- if (node.kind === "Text") return node.value;
835
- if (node.kind === "Break") return "";
836
- if (node.kind === "Jsx") return node.value;
837
- const parts = [];
838
- if ("params" in node && node.params) parts.push(node.params);
839
- if ("generics" in node && node.generics) parts.push(Array.isArray(node.generics) ? node.generics.join(", ") : node.generics);
840
- if ("returnType" in node && node.returnType) parts.push(node.returnType);
841
- if ("type" in node && typeof node.type === "string") parts.push(node.type);
842
- const nested = extractStringsFromNodes(node.nodes);
843
- if (nested) parts.push(nested);
844
- return parts.join("\n");
845
- }).filter(Boolean).join("\n");
846
- }
847
- /**
848
- * Resolves the schema name of a ref node, falling back through `ref` → `name` → nested `schema.name`.
849
- *
850
- * Returns `null` for non-ref nodes or when no name can be resolved. Use this to get a schema's
851
- * identifier for type definitions or error messages.
852
- *
853
- * @example
854
- * ```ts
855
- * resolveRefName({ kind: 'Schema', type: 'ref', ref: '#/components/schemas/Pet' })
856
- * // => 'Pet'
857
- * ```
858
- */
859
- function resolveRefName(node) {
860
- if (!node || node.type !== "ref") return null;
861
- if (node.ref) return extractRefName(node.ref) ?? node.name ?? node.schema?.name ?? null;
862
- return node.name ?? node.schema?.name ?? null;
863
- }
864
- /**
865
- * Collects every named schema referenced (transitively) from a node via ref edges.
866
- *
867
- * Refs are followed by name only, the resolved `node.schema` is not traversed inline.
868
- * Use this to determine schema dependencies, build reference graphs, or detect what schemas need to be emitted.
869
- *
870
- * @example Collect refs from a single schema
871
- * ```ts
872
- * const names = collectReferencedSchemaNames(petSchema)
873
- * // → Set { 'Category', 'Tag' }
874
- * ```
875
- *
876
- * @example Accumulate refs from multiple schemas into one set
877
- * ```ts
878
- * const out = new Set<string>()
879
- * for (const schema of schemas) {
880
- * collectReferencedSchemaNames(schema, out)
881
- * }
882
- * ```
883
- */
884
- const collectSchemaRefs = memoize(/* @__PURE__ */ new WeakMap(), (node) => {
885
- const refs = /* @__PURE__ */ new Set();
886
- collect(node, { schema(child) {
887
- if (child.type === "ref") {
888
- const name = resolveRefName(child);
889
- if (name) refs.add(name);
890
- }
891
- } });
892
- return refs;
893
- });
894
- function collectReferencedSchemaNames(node, out = /* @__PURE__ */ new Set()) {
895
- if (!node) return out;
896
- for (const name of collectSchemaRefs(node)) out.add(name);
897
- return out;
898
- }
899
- /**
900
- * Collects the names of all top-level schemas transitively used by a set of operations.
901
- *
902
- * An operation uses a schema when any of its parameters, request body content, or responses
903
- * reference it, directly or indirectly through other named schemas.
904
- * The walk is iterative and safe against reference cycles.
905
- *
906
- * Use this together with `include` filters to determine which schemas from `components/schemas`
907
- * are reachable from the allowed operations, so that schemas used only by excluded operations
908
- * are not generated.
909
- *
910
- * @example Only generate schemas referenced by included operations
911
- * ```ts
912
- * const includedOps = operations.filter(op => resolver.resolveOptions(op, { options, include }) !== null)
913
- * const allowed = collectUsedSchemaNames(includedOps, schemas)
914
- *
915
- * for (const schema of schemas) {
916
- * if (schema.name && !allowed.has(schema.name)) continue
917
- * // … generate schema
918
- * }
919
- * ```
920
- *
921
- * @example Check whether a specific schema is needed
922
- * ```ts
923
- * const allowed = collectUsedSchemaNames(includedOps, schemas)
924
- * allowed.has('OrderStatus') // false when no included operation references OrderStatus
925
- * ```
926
- */
927
- const collectUsedSchemaNamesMemo = memoize(/* @__PURE__ */ new WeakMap(), (ops) => memoize(/* @__PURE__ */ new WeakMap(), (schemas) => computeUsedSchemaNames(ops, schemas)));
928
- function computeUsedSchemaNames(operations, schemas) {
929
- const schemaMap = /* @__PURE__ */ new Map();
930
- for (const schema of schemas) if (schema.name) schemaMap.set(schema.name, schema);
931
- const result = /* @__PURE__ */ new Set();
932
- function visitSchema(schema) {
933
- const directRefs = collectReferencedSchemaNames(schema);
934
- for (const name of directRefs) if (!result.has(name)) {
935
- result.add(name);
936
- const namedSchema = schemaMap.get(name);
937
- if (namedSchema) visitSchema(namedSchema);
938
- }
939
- }
940
- for (const op of operations) for (const schema of collectLazy(op, {
941
- depth: "shallow",
942
- schema: (node) => node
943
- })) visitSchema(schema);
944
- return result;
945
- }
946
- function collectUsedSchemaNames(operations, schemas) {
947
- return collectUsedSchemaNamesMemo(operations)(schemas);
948
- }
949
- const EMPTY_CIRCULAR_SET = /* @__PURE__ */ new Set();
950
- const findCircularSchemasMemo = memoize(/* @__PURE__ */ new WeakMap(), (schemas) => {
951
- const graph = /* @__PURE__ */ new Map();
952
- for (const schema of schemas) {
953
- if (!schema.name) continue;
954
- graph.set(schema.name, collectReferencedSchemaNames(schema));
955
- }
956
- const circular = /* @__PURE__ */ new Set();
957
- for (const start of graph.keys()) {
958
- const visited = /* @__PURE__ */ new Set();
959
- const stack = [...graph.get(start) ?? []];
960
- while (stack.length > 0) {
961
- const node = stack.pop();
962
- if (node === start) {
963
- circular.add(start);
964
- break;
965
- }
966
- if (visited.has(node)) continue;
967
- visited.add(node);
968
- const next = graph.get(node);
969
- if (next) for (const r of next) stack.push(r);
970
- }
971
- }
972
- return circular;
973
- });
974
- /**
975
- * Identifies all schemas that participate in circular dependency chains, including direct self-loops.
976
- *
977
- * Returns a Set of schema names with circular dependencies. Use this to wrap recursive schema positions
978
- * in deferred constructs (lazy getter, `z.lazy(() => …)`) to prevent infinite recursion when generated code runs.
979
- * Refs are followed by name only, keeping the algorithm linear in the schema graph size.
980
- *
981
- * @note Call this once on the full schema graph, then use `containsCircularRef()` to check individual schemas.
982
- */
983
- function findCircularSchemas(schemas) {
984
- if (schemas.length === 0) return EMPTY_CIRCULAR_SET;
985
- return findCircularSchemasMemo(schemas);
986
- }
987
- /**
988
- * Type guard returning `true` when a schema or anything nested within it contains a ref to a circular schema.
989
- *
990
- * Use `excludeName` to ignore refs to specific schemas (useful when self-references are handled separately).
991
- * Commonly used with `findCircularSchemas()` to detect where lazy wrappers are needed in code generation.
992
- *
993
- * @note Returns `true` for the first matching circular ref found. Use for fast dependency checks.
994
- */
995
- function containsCircularRef(node, { circularSchemas, excludeName }) {
996
- if (!node || circularSchemas.size === 0) return false;
997
- for (const _ of collectLazy(node, { schema(child) {
998
- if (child.type !== "ref") return null;
999
- const name = resolveRefName(child);
1000
- return name && name !== excludeName && circularSchemas.has(name) ? true : null;
1001
- } })) return true;
1002
- return false;
1003
- }
1004
- //#endregion
1005
- //#region src/factory.ts
1006
- /**
1007
- * Updates a schema's `optional` and `nullish` flags from a parent's `required`
1008
- * value and the schema's own `nullable`. Mirrors how OpenAPI parameters and
1009
- * object properties combine "required" and "nullable" into a single AST.
1010
- *
1011
- * - Non-required + non-nullable → `optional: true`.
1012
- * - Non-required + nullable → `nullish: true`.
1013
- * - Required → both flags cleared.
1014
- */
1015
- function syncOptionality(schema, required) {
1016
- const nullable = schema.nullable ?? false;
1017
- return {
1018
- ...schema,
1019
- optional: !required && !nullable ? true : void 0,
1020
- nullish: !required && nullable ? true : void 0
1021
- };
1022
- }
1023
- /**
1024
- * Identity-preserving node update: returns `node` unchanged when every field in
1025
- * `changes` already equals (by reference) the current value, otherwise a new node
1026
- * with the changes applied.
1027
- *
1028
- * Mirrors the TypeScript compiler's `factory.updateX` contract, pair it with the
1029
- * structural sharing in {@link transform} so a no-op rewrite doesn't allocate and
1030
- * downstream passes can detect "nothing changed" by identity. Comparison is
1031
- * shallow: a structurally-equal but newly-allocated array/object counts as a change.
1032
- *
1033
- * @example
1034
- * ```ts
1035
- * update(node, { name: node.name }) // -> same `node` reference
1036
- * update(node, { name: 'renamed' }) // -> new node, `name` replaced
1037
- * ```
1038
- */
1039
- function update(node, changes) {
1040
- for (const key in changes) if (changes[key] !== node[key]) return {
1041
- ...node,
1042
- ...changes
1043
- };
1044
- return node;
1045
- }
1046
- /**
1047
- * Creates an `InputNode` with stable defaults for `schemas` and `operations`.
1048
- *
1049
- * @example
1050
- * ```ts
1051
- * const input = createInput()
1052
- * // { kind: 'Input', schemas: [], operations: [] }
1053
- * ```
1054
- *
1055
- * @example
1056
- * ```ts
1057
- * const input = createInput({ schemas: [petSchema] })
1058
- * // keeps default operations: []
1059
- * ```
1060
- */
1061
- function createInput(overrides = {}) {
1062
- return {
1063
- schemas: [],
1064
- operations: [],
1065
- meta: {
1066
- circularNames: [],
1067
- enumNames: []
1068
- },
1069
- ...overrides,
1070
- kind: "Input"
1071
- };
1072
- }
1073
- /**
1074
- * Creates a streaming `InputNode<true>` from pre-built `AsyncIterable` sources.
1075
- *
1076
- * @example
1077
- * ```ts
1078
- * const node = createStreamInput(schemasIterable, operationsIterable, { title: 'My API' })
1079
- * ```
1080
- */
1081
- function createStreamInput(schemas, operations, meta) {
1082
- return {
1083
- kind: "Input",
1084
- schemas,
1085
- operations,
1086
- meta
1087
- };
1088
- }
1089
- /**
1090
- * Creates an `OutputNode` with a stable default for `files`.
1091
- *
1092
- * @example
1093
- * ```ts
1094
- * const output = createOutput()
1095
- * // { kind: 'Output', files: [] }
1096
- * ```
1097
- *
1098
- * @example
1099
- * ```ts
1100
- * const output = createOutput({ files: [petFile] })
1101
- * ```
1102
- */
1103
- function createOutput(overrides = {}) {
1104
- return {
1105
- files: [],
1106
- ...overrides,
1107
- kind: "Output"
1108
- };
1109
- }
1110
- /**
1111
- * Creates a `ContentNode` for a single request-body or response content type.
1112
- */
1113
- function createContent(props) {
1114
- return {
1115
- ...props,
1116
- kind: "Content"
1117
- };
1118
- }
1119
- /**
1120
- * Creates a `RequestBodyNode`, normalizing each content entry into a `ContentNode`.
1121
- */
1122
- function createRequestBody(props) {
1123
- return {
1124
- ...props,
1125
- kind: "RequestBody",
1126
- content: props.content?.map(createContent)
1127
- };
1128
- }
1129
- function createOperation(props) {
1130
- const { requestBody, ...rest } = props;
1131
- const isHttp = rest.method !== void 0 && rest.path !== void 0;
1132
- return {
1133
- tags: [],
1134
- parameters: [],
1135
- responses: [],
1136
- ...rest,
1137
- ...isHttp ? { protocol: "http" } : {},
1138
- kind: "Operation",
1139
- requestBody: requestBody ? createRequestBody(requestBody) : void 0
1140
- };
1141
- }
1142
- /**
1143
- * Maps schema `type` to its underlying `primitive`.
1144
- * Primitive types map to themselves. Special string formats map to `'string'`.
1145
- * Complex types (`ref`, `enum`, `union`, `intersection`, `tuple`, `blob`) are left unset.
1146
- */
1147
- const TYPE_TO_PRIMITIVE = {
1148
- string: "string",
1149
- number: "number",
1150
- integer: "integer",
1151
- bigint: "bigint",
1152
- boolean: "boolean",
1153
- null: "null",
1154
- any: "any",
1155
- unknown: "unknown",
1156
- void: "void",
1157
- never: "never",
1158
- object: "object",
1159
- array: "array",
1160
- date: "date",
1161
- uuid: "string",
1162
- email: "string",
1163
- url: "string",
1164
- datetime: "string",
1165
- time: "string"
1166
- };
1167
- function createSchema(props) {
1168
- const inferredPrimitive = TYPE_TO_PRIMITIVE[props.type];
1169
- if (props["type"] === "object") return {
1170
- properties: [],
1171
- primitive: "object",
1172
- ...props,
1173
- kind: "Schema"
1174
- };
1175
- return {
1176
- primitive: inferredPrimitive,
1177
- ...props,
1178
- kind: "Schema"
1179
- };
1180
- }
1181
- /**
1182
- * Creates a `PropertyNode`.
1183
- *
1184
- * `required` defaults to `false`.
1185
- * `schema.optional` and `schema.nullish` are derived from `required` and `schema.nullable`.
1186
- *
1187
- * @example
1188
- * ```ts
1189
- * const property = createProperty({
1190
- * name: 'status',
1191
- * schema: createSchema({ type: 'string' }),
1192
- * })
1193
- * // required=false, schema.optional=true
1194
- * ```
1195
- *
1196
- * @example
1197
- * ```ts
1198
- * const property = createProperty({
1199
- * name: 'status',
1200
- * required: true,
1201
- * schema: createSchema({ type: 'string', nullable: true }),
1202
- * })
1203
- * // required=true, no optional/nullish
1204
- * ```
1205
- */
1206
- function createProperty(props) {
1207
- const required = props.required ?? false;
1208
- return {
1209
- ...props,
1210
- kind: "Property",
1211
- required,
1212
- schema: syncOptionality(props.schema, required)
1213
- };
1214
- }
1215
- /**
1216
- * Creates a `ParameterNode`.
1217
- *
1218
- * `required` defaults to `false`.
1219
- * Nested schema flags are set from `required` and `schema.nullable`.
1220
- *
1221
- * @example
1222
- * ```ts
1223
- * const param = createParameter({
1224
- * name: 'petId',
1225
- * in: 'path',
1226
- * required: true,
1227
- * schema: createSchema({ type: 'string' }),
1228
- * })
1229
- * ```
1230
- *
1231
- * @example
1232
- * ```ts
1233
- * const param = createParameter({
1234
- * name: 'status',
1235
- * in: 'query',
1236
- * schema: createSchema({ type: 'string', nullable: true }),
1237
- * })
1238
- * // required=false, schema.nullish=true
1239
- * ```
1240
- */
1241
- function createParameter(props) {
1242
- const required = props.required ?? false;
1243
- return {
1244
- ...props,
1245
- kind: "Parameter",
1246
- required,
1247
- schema: syncOptionality(props.schema, required)
1248
- };
1249
- }
1250
- /**
1251
- * Creates a `ResponseNode`.
1252
- *
1253
- * Response body schemas live inside `content`. For convenience a single legacy `schema`
1254
- * (with optional `mediaType`/`keysToOmit`) is normalized into one `content` entry, so the same
1255
- * schema is never stored both at the node root and inside `content`.
1256
- *
1257
- * @example
1258
- * ```ts
1259
- * const response = createResponse({
1260
- * statusCode: '200',
1261
- * content: [{ contentType: 'application/json', schema: createSchema({ type: 'object', properties: [] }) }],
1262
- * })
1263
- * ```
1264
- */
1265
- function createResponse(props) {
1266
- const { schema, mediaType, keysToOmit, content, ...rest } = props;
1267
- const entries = content ?? (schema ? [{
1268
- contentType: mediaType ?? "application/json",
1269
- schema,
1270
- keysToOmit: keysToOmit ?? null
1271
- }] : void 0);
1272
- return {
1273
- ...rest,
1274
- kind: "Response",
1275
- content: entries?.map(createContent)
1276
- };
1277
- }
1278
- /**
1279
- * Creates a `FunctionParameterNode`.
1280
- *
1281
- * `optional` defaults to `false`.
1282
- *
1283
- * @example Required typed param
1284
- * ```ts
1285
- * createFunctionParameter({ name: 'petId', type: createParamsType({ variant: 'reference', name: 'string' }) })
1286
- * // → petId: string
1287
- * ```
1288
- *
1289
- * @example Optional param
1290
- * ```ts
1291
- * createFunctionParameter({ name: 'params', type: createParamsType({ variant: 'reference', name: 'QueryParams' }), optional: true })
1292
- * // → params?: QueryParams
1293
- * ```
1294
- *
1295
- * @example Param with default (implicitly optional. Cannot combine with `optional: true`)
1296
- * ```ts
1297
- * createFunctionParameter({ name: 'config', type: createParamsType({ variant: 'reference', name: 'RequestConfig' }), default: '{}' })
1298
- * // → config: RequestConfig = {}
1299
- * ```
1300
- */
1301
- function createFunctionParameter(props) {
1302
- return {
1303
- optional: false,
1304
- ...props,
1305
- kind: "FunctionParameter"
1306
- };
1307
- }
1308
- /**
1309
- * Creates a {@link TypeNode} representing a language-agnostic structured type expression.
1310
- *
1311
- * Use `variant: 'struct'` for inline anonymous types and `variant: 'member'` for a single
1312
- * named field accessed from a group type. Each language's printer renders the variant
1313
- * into its own syntax (TypeScript, Python, C#, Kotlin, …).
1314
- *
1315
- * @example Reference type (TypeScript: `QueryParams`)
1316
- * ```ts
1317
- * createParamsType({ variant: 'reference', name: 'QueryParams' })
1318
- * ```
1319
- *
1320
- * @example Struct type (TypeScript: `{ petId: string }`)
1321
- * ```ts
1322
- * createParamsType({ variant: 'struct', properties: [{ name: 'petId', optional: false, type: createParamsType({ variant: 'reference', name: 'string' }) }] })
1323
- * ```
1324
- *
1325
- * @example Member type (TypeScript: `DeletePetPathParams['petId']`)
1326
- * ```ts
1327
- * createParamsType({ variant: 'member', base: 'DeletePetPathParams', key: 'petId' })
1328
- * ```
1329
- */
1330
- function createParamsType(props) {
1331
- return {
1332
- ...props,
1333
- kind: "ParamsType"
1334
- };
1335
- }
1336
- /**
1337
- * Creates a `ParameterGroupNode` representing a group of related parameters treated as a unit.
1338
- *
1339
- * @example Grouped param (TypeScript declaration)
1340
- * ```ts
1341
- * createParameterGroup({
1342
- * properties: [
1343
- * createFunctionParameter({ name: 'id', type: createParamsType({ variant: 'reference', name: 'string' }), optional: false }),
1344
- * createFunctionParameter({ name: 'name', type: createParamsType({ variant: 'reference', name: 'string' }), optional: true }),
1345
- * ],
1346
- * default: '{}',
1347
- * })
1348
- * // declaration → { id, name? }: { id: string; name?: string } = {}
1349
- * // call → { id, name }
1350
- * ```
1351
- *
1352
- * @example Inline (spread), children emitted as individual top-level parameters
1353
- * ```ts
1354
- * createParameterGroup({
1355
- * properties: [createFunctionParameter({ name: 'petId', type: createParamsType({ variant: 'reference', name: 'string' }), optional: false })],
1356
- * inline: true,
1357
- * })
1358
- * // declaration → petId: string
1359
- * // call → petId
1360
- * ```
1361
- */
1362
- function createParameterGroup(props) {
1363
- return {
1364
- ...props,
1365
- kind: "ParameterGroup"
1366
- };
1367
- }
1368
- /**
1369
- * Creates a `FunctionParametersNode` from an ordered list of parameters.
1370
- *
1371
- * @example
1372
- * ```ts
1373
- * createFunctionParameters({
1374
- * params: [
1375
- * createFunctionParameter({ name: 'petId', type: createParamsType({ variant: 'reference', name: 'string' }), optional: false }),
1376
- * createFunctionParameter({ name: 'config', type: createParamsType({ variant: 'reference', name: 'RequestConfig' }), optional: false, default: '{}' }),
1377
- * ],
1378
- * })
1379
- * ```
1380
- *
1381
- * @example
1382
- * ```ts
1383
- * const empty = createFunctionParameters()
1384
- * // { kind: 'FunctionParameters', params: [] }
1385
- * ```
1386
- */
1387
- function createFunctionParameters(props = {}) {
1388
- return {
1389
- params: [],
1390
- ...props,
1391
- kind: "FunctionParameters"
1392
- };
1393
- }
1394
- /**
1395
- * Creates an `ImportNode` representing a language-agnostic import/dependency declaration.
1396
- *
1397
- * @example Named import
1398
- * ```ts
1399
- * createImport({ name: ['useState'], path: 'react' })
1400
- * // import { useState } from 'react'
1401
- * ```
1402
- *
1403
- * @example Type-only import
1404
- * ```ts
1405
- * createImport({ name: ['FC'], path: 'react', isTypeOnly: true })
1406
- * // import type { FC } from 'react'
1407
- * ```
1408
- */
1409
- function createImport(props) {
1410
- return {
1411
- ...props,
1412
- kind: "Import"
1413
- };
1414
- }
1415
- /**
1416
- * Creates an `ExportNode` representing a language-agnostic export/public API declaration.
1417
- *
1418
- * @example Named export
1419
- * ```ts
1420
- * createExport({ name: ['Pet'], path: './Pet' })
1421
- * // export { Pet } from './Pet'
1422
- * ```
1423
- *
1424
- * @example Wildcard export
1425
- * ```ts
1426
- * createExport({ path: './utils' })
1427
- * // export * from './utils'
1428
- * ```
1429
- */
1430
- function createExport(props) {
1431
- return {
1432
- ...props,
1433
- kind: "Export"
1434
- };
1435
- }
1436
- /**
1437
- * Creates a `SourceNode` representing a fragment of source code within a file.
1438
- *
1439
- * @example
1440
- * ```ts
1441
- * createSource({ name: 'Pet', nodes: [createText('export type Pet = { id: number }')], isExportable: true })
1442
- * ```
1443
- */
1444
- function createSource(props) {
1445
- return {
1446
- ...props,
1447
- kind: "Source"
1448
- };
1449
- }
1450
- /**
1451
- * Creates a fully resolved `FileNode` from a file input descriptor.
1452
- *
1453
- * Computes:
1454
- * - `id` SHA256 hash of the file path
1455
- * - `name` `baseName` without extension
1456
- * - `extname` extension extracted from `baseName`
1457
- *
1458
- * Deduplicates:
1459
- * - `sources` via `combineSources`
1460
- * - `exports` via `combineExports`
1461
- * - `imports` via `combineImports` (also filters unused imports)
1462
- *
1463
- * @throws {Error} when `baseName` has no extension.
1464
- *
1465
- * @example
1466
- * ```ts
1467
- * const file = createFile({
1468
- * baseName: 'petStore.ts',
1469
- * path: 'src/models/petStore.ts',
1470
- * sources: [createSource({ name: 'Pet', nodes: [createText('export type Pet = { id: number }')] })],
1471
- * imports: [createImport({ name: ['z'], path: 'zod' })],
1472
- * exports: [createExport({ name: ['Pet'], path: './petStore' })],
1473
- * })
1474
- * // file.id = SHA256 hash of 'src/models/petStore.ts'
1475
- * // file.name = 'petStore'
1476
- * // file.extname = '.ts'
1477
- * ```
1478
- */
1479
- function createFile(input) {
1480
- const extname = path.extname(input.baseName) || (input.baseName.startsWith(".") ? input.baseName : "");
1481
- if (!extname) throw new Error(`No extname found for ${input.baseName}`);
1482
- const source = (input.sources ?? []).flatMap((item) => item.nodes ?? []).map((node) => extractStringsFromNodes([node])).filter(Boolean).join("\n\n");
1483
- const resolvedExports = input.exports?.length ? combineExports(input.exports) : [];
1484
- const combinedImports = input.imports?.length ? combineImports(input.imports, resolvedExports, source || void 0) : [];
1485
- const localNames = new Set((input.sources ?? []).map((item) => item.name).filter((name) => Boolean(name)));
1486
- const nameOf = (item) => typeof item === "string" ? item : item.name ?? item.propertyName;
1487
- const resolvedImports = combinedImports.filter((imp) => imp.path !== input.path).flatMap((imp) => {
1488
- if (!Array.isArray(imp.name)) return typeof imp.name === "string" && localNames.has(imp.name) ? [] : [imp];
1489
- const kept = imp.name.filter((item) => !localNames.has(nameOf(item)));
1490
- if (!kept.length) return [];
1491
- return [kept.length === imp.name.length ? imp : {
1492
- ...imp,
1493
- name: kept
1494
- }];
1495
- });
1496
- const resolvedSources = input.sources?.length ? combineSources(input.sources) : [];
1497
- return {
1498
- kind: "File",
1499
- ...input,
1500
- id: hash("sha256", input.path, "hex"),
1501
- name: trimExtName(input.baseName),
1502
- extname,
1503
- imports: resolvedImports,
1504
- exports: resolvedExports,
1505
- sources: resolvedSources,
1506
- meta: input.meta ?? {}
1507
- };
1508
- }
1509
- /**
1510
- * Creates a `ConstNode` representing a TypeScript `const` declaration.
1511
- *
1512
- * Mirrors the `Const` component from `@kubb/renderer-jsx`.
1513
- * The component's `children` are represented as `nodes`.
1514
- *
1515
- * @example Simple constant
1516
- * ```ts
1517
- * createConst({ name: 'pet' })
1518
- * // const pet = ...
1519
- * ```
1520
- *
1521
- * @example Exported constant with type and `as const`
1522
- * ```ts
1523
- * createConst({ name: 'pets', export: true, type: 'Pet[]', asConst: true })
1524
- * // export const pets: Pet[] = ... as const
1525
- * ```
1526
- *
1527
- * @example With JSDoc and child nodes
1528
- * ```ts
1529
- * createConst({
1530
- * name: 'config',
1531
- * export: true,
1532
- * JSDoc: { comments: ['@description App configuration'] },
1533
- * nodes: [],
1534
- * })
1535
- * ```
1536
- */
1537
- function createConst(props) {
1538
- return {
1539
- ...props,
1540
- kind: "Const"
1541
- };
1542
- }
1543
- /**
1544
- * Creates a `TypeNode` representing a TypeScript `type` alias declaration.
1545
- *
1546
- * Mirrors the `Type` component from `@kubb/renderer-jsx`.
1547
- * The component's `children` are represented as `nodes`.
1548
- *
1549
- * @example Simple type alias
1550
- * ```ts
1551
- * createType({ name: 'Pet' })
1552
- * // type Pet = ...
1553
- * ```
1554
- *
1555
- * @example Exported type with JSDoc
1556
- * ```ts
1557
- * createType({
1558
- * name: 'PetStatus',
1559
- * export: true,
1560
- * JSDoc: { comments: ['@description Status of a pet'] },
1561
- * })
1562
- * // export type PetStatus = ...
1563
- * ```
1564
- */
1565
- function createType(props) {
1566
- return {
1567
- ...props,
1568
- kind: "Type"
1569
- };
1570
- }
1571
- /**
1572
- * Creates a `FunctionNode` representing a TypeScript `function` declaration.
1573
- *
1574
- * Mirrors the `Function` component from `@kubb/renderer-jsx`.
1575
- * The component's `children` are represented as `nodes`.
1576
- *
1577
- * @example Simple function
1578
- * ```ts
1579
- * createFunction({ name: 'getPet' })
1580
- * // function getPet() { ... }
1581
- * ```
1582
- *
1583
- * @example Exported async function with return type
1584
- * ```ts
1585
- * createFunction({ name: 'fetchPet', export: true, async: true, returnType: 'Pet' })
1586
- * // export async function fetchPet(): Promise<Pet> { ... }
1587
- * ```
1588
- *
1589
- * @example Function with generics and params
1590
- * ```ts
1591
- * createFunction({
1592
- * name: 'identity',
1593
- * export: true,
1594
- * generics: ['T'],
1595
- * params: 'value: T',
1596
- * returnType: 'T',
1597
- * })
1598
- * // export function identity<T>(value: T): T { ... }
1599
- * ```
1600
- */
1601
- function createFunction(props) {
1602
- return {
1603
- ...props,
1604
- kind: "Function"
1605
- };
1606
- }
1607
- /**
1608
- * Creates an `ArrowFunctionNode` representing a TypeScript arrow function.
1609
- *
1610
- * Mirrors the `Function.Arrow` component from `@kubb/renderer-jsx`.
1611
- * The component's `children` are represented as `nodes`.
1612
- *
1613
- * @example Simple arrow function
1614
- * ```ts
1615
- * createArrowFunction({ name: 'getPet' })
1616
- * // const getPet = () => { ... }
1617
- * ```
1618
- *
1619
- * @example Single-line exported arrow function
1620
- * ```ts
1621
- * createArrowFunction({ name: 'double', export: true, params: 'n: number', singleLine: true })
1622
- * // export const double = (n: number) => ...
1623
- * ```
1624
- *
1625
- * @example Async arrow function with generics
1626
- * ```ts
1627
- * createArrowFunction({
1628
- * name: 'fetchPet',
1629
- * export: true,
1630
- * async: true,
1631
- * generics: ['T'],
1632
- * params: 'id: string',
1633
- * returnType: 'T',
1634
- * })
1635
- * // export const fetchPet = async <T>(id: string): Promise<T> => { ... }
1636
- * ```
1637
- */
1638
- function createArrowFunction(props) {
1639
- return {
1640
- ...props,
1641
- kind: "ArrowFunction"
1642
- };
1643
- }
1644
- /**
1645
- * Creates a {@link TextNode} representing a raw string fragment in the source output.
1646
- *
1647
- * Use this instead of bare strings when building `nodes` arrays so that every
1648
- * entry in the array is a typed {@link CodeNode}.
1649
- *
1650
- * @example
1651
- * ```ts
1652
- * createText('return fetch(id)')
1653
- * // { kind: 'Text', value: 'return fetch(id)' }
1654
- * ```
1655
- */
1656
- function createText(value) {
1657
- return {
1658
- value,
1659
- kind: "Text"
1660
- };
1661
- }
1662
- /**
1663
- * Creates a {@link BreakNode} representing a line break in the source output.
1664
- *
1665
- * Corresponds to `<br/>` in JSX components. Prints as an empty string which,
1666
- * when joined with `\n` by `printNodes`, produces a blank line.
1667
- *
1668
- * @example
1669
- * ```ts
1670
- * createBreak()
1671
- * // { kind: 'Break' }
1672
- * ```
1673
- */
1674
- function createBreak() {
1675
- return { kind: "Break" };
1676
- }
1677
- /**
1678
- * Creates a {@link JsxNode} representing a raw JSX fragment in the source output.
1679
- *
1680
- * Use this to embed JSX markup (including fragments `<>…</>`) directly in generated code.
1681
- *
1682
- * @example
1683
- * ```ts
1684
- * createJsx('<>\n <a href={href}>Open</a>\n</>')
1685
- * // { kind: 'Jsx', value: '<>\n <a href={href}>Open</a>\n</>' }
1686
- * ```
1687
- */
1688
- function createJsx(value) {
1689
- return {
1690
- value,
1691
- kind: "Jsx"
1692
- };
1693
- }
1694
- //#endregion
1695
5
  //#region src/signature.ts
1696
6
  /**
1697
7
  * The flags shared by every node kind that affect its type: `primitive`, `format`, `nullable`.
@@ -2140,11 +450,11 @@ function definePrinter(build) {
2140
450
  }
2141
451
  /**
2142
452
  * Generic printer-factory function used by `definePrinter` and `defineFunctionPrinter`.
2143
- **
453
+ *
2144
454
  * @example
2145
455
  * ```ts
2146
- * export const defineFunctionPrinter = createPrinterFactory<FunctionNode, FunctionNodeType, FunctionNodeByType>(
2147
- * (node) => kindToHandlerKey[node.kind],
456
+ * export const defineFunctionPrinter = createPrinterFactory<FunctionParamNode, FunctionParamKind, Partial<Record<FunctionParamKind, FunctionParamNode>>>(
457
+ * (node) => node.kind,
2148
458
  * )
2149
459
  * ```
2150
460
  */
@@ -2279,6 +589,6 @@ function setEnumName(propNode, parentName, propName, enumSuffix) {
2279
589
  return propNode;
2280
590
  }
2281
591
  //#endregion
2282
- export { applyDedupe, buildDedupePlan, caseParams, collect, collectUsedSchemaNames, containsCircularRef, createArrowFunction, createBreak, createConst, createDiscriminantNode, createExport, createFile, createFunction, createFunctionParameter, createFunctionParameters, createImport, createInput, createJsx, createOperation, createOperationParams, createOutput, createParameter, createParameterGroup, createParamsType, createPrinterFactory, createProperty, createResponse, createSchema, createSource, createStreamInput, createText, createType, definePrinter, defineSchemaDialect, extractStringsFromNodes, findCircularSchemas, httpMethods, isHttpOperationNode, isInputNode, isOperationNode, isOutputNode, isSchemaNode, isStringType, mergeAdjacentObjectsLazy, narrowSchema, schemaTypes, setDiscriminatorEnum, setEnumName, signatureOf, simplifyUnion, syncOptionality, syncSchemaRef, transform, update, walk };
592
+ export { applyDedupe, arrowFunctionDef, breakDef, buildDedupePlan, collect, constDef, contentDef, createPrinterFactory, defineNode, definePrinter, defineSchemaDialect, exportDef, extractStringsFromNodes, factory_exports as factory, fileDef, functionDef, functionParameterDef, functionParametersDef, httpMethods, importDef, indexedAccessTypeDef, inputDef, isHttpOperationNode, jsxDef, mergeAdjacentObjectsLazy, narrowSchema, objectBindingPatternDef, operationDef, outputDef, parameterDef, propertyDef, requestBodyDef, responseDef, schemaDef, schemaTypes, setDiscriminatorEnum, setEnumName, signatureOf, simplifyUnion, sourceDef, syncOptionality, textDef, transform, typeDef, typeLiteralDef, walk };
2283
593
 
2284
594
  //# sourceMappingURL=index.js.map