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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/LICENSE +17 -10
  2. package/README.md +51 -27
  3. package/dist/chunk-CNktS9qV.js +17 -0
  4. package/dist/defineMacro-BLIR6k-j.d.ts +475 -0
  5. package/dist/defineMacro-BTXvS8nI.js +106 -0
  6. package/dist/defineMacro-BTXvS8nI.js.map +1 -0
  7. package/dist/defineMacro-Bv9R_9a2.cjs +123 -0
  8. package/dist/defineMacro-Bv9R_9a2.cjs.map +1 -0
  9. package/dist/extractStringsFromNodes-Cja-xxx5.js +29 -0
  10. package/dist/extractStringsFromNodes-Cja-xxx5.js.map +1 -0
  11. package/dist/extractStringsFromNodes-DKgDjFO0.cjs +34 -0
  12. package/dist/extractStringsFromNodes-DKgDjFO0.cjs.map +1 -0
  13. package/dist/extractStringsFromNodes-p4mX1TQD.d.ts +14 -0
  14. package/dist/factory-CZNOGI-N.js +283 -0
  15. package/dist/factory-CZNOGI-N.js.map +1 -0
  16. package/dist/factory-DG1CVkEb.cjs +300 -0
  17. package/dist/factory-DG1CVkEb.cjs.map +1 -0
  18. package/dist/factory.cjs +29 -0
  19. package/dist/factory.d.ts +62 -0
  20. package/dist/factory.js +3 -0
  21. package/dist/index-BzjwdK2M.d.ts +2433 -0
  22. package/dist/index.cjs +444 -2180
  23. package/dist/index.cjs.map +1 -1
  24. package/dist/index.d.ts +94 -3408
  25. package/dist/index.js +395 -2101
  26. package/dist/index.js.map +1 -1
  27. package/dist/macros.cjs +117 -0
  28. package/dist/macros.cjs.map +1 -0
  29. package/dist/macros.d.ts +59 -0
  30. package/dist/macros.js +115 -0
  31. package/dist/macros.js.map +1 -0
  32. package/dist/operationParams-BZ07xDm0.d.ts +204 -0
  33. package/dist/response-KUdWiDWw.js +658 -0
  34. package/dist/response-KUdWiDWw.js.map +1 -0
  35. package/dist/response-hnSw2NKE.cjs +1027 -0
  36. package/dist/response-hnSw2NKE.cjs.map +1 -0
  37. package/dist/types-DyDzizSf.d.ts +364 -0
  38. package/dist/types.cjs +0 -0
  39. package/dist/types.d.ts +6 -0
  40. package/dist/types.js +1 -0
  41. package/dist/utils-BLJwyza-.cjs +912 -0
  42. package/dist/utils-BLJwyza-.cjs.map +1 -0
  43. package/dist/utils-CF_-Pn_c.js +770 -0
  44. package/dist/utils-CF_-Pn_c.js.map +1 -0
  45. package/dist/utils.cjs +36 -0
  46. package/dist/utils.d.ts +358 -0
  47. package/dist/utils.js +4 -0
  48. package/dist/visitor-DJ6ZEJvq.js +548 -0
  49. package/dist/visitor-DJ6ZEJvq.js.map +1 -0
  50. package/dist/visitor-DpKZ9Tk0.cjs +654 -0
  51. package/dist/visitor-DpKZ9Tk0.cjs.map +1 -0
  52. package/package.json +21 -6
  53. package/src/constants.ts +19 -64
  54. package/src/dedupe.ts +239 -0
  55. package/src/defineMacro.ts +132 -0
  56. package/src/dialect.ts +53 -0
  57. package/src/factory.ts +67 -678
  58. package/src/guards.ts +10 -92
  59. package/src/index.ts +13 -44
  60. package/src/infer.ts +16 -14
  61. package/src/macros/index.ts +3 -0
  62. package/src/macros/macroDiscriminatorEnum.ts +44 -0
  63. package/src/macros/macroEnumName.ts +25 -0
  64. package/src/macros/macroSimplifyUnion.ts +50 -0
  65. package/src/mocks.ts +7 -127
  66. package/src/node.ts +128 -0
  67. package/src/nodes/base.ts +5 -12
  68. package/src/nodes/code.ts +165 -74
  69. package/src/nodes/content.ts +56 -0
  70. package/src/nodes/file.ts +97 -36
  71. package/src/nodes/function.ts +216 -156
  72. package/src/nodes/http.ts +1 -35
  73. package/src/nodes/index.ts +23 -15
  74. package/src/nodes/input.ts +140 -0
  75. package/src/nodes/operation.ts +122 -68
  76. package/src/nodes/output.ts +23 -0
  77. package/src/nodes/parameter.ts +33 -3
  78. package/src/nodes/property.ts +36 -3
  79. package/src/nodes/requestBody.ts +61 -0
  80. package/src/nodes/response.ts +58 -13
  81. package/src/nodes/schema.ts +93 -17
  82. package/src/printer.ts +48 -42
  83. package/src/registry.ts +75 -0
  84. package/src/signature.ts +207 -0
  85. package/src/types.ts +8 -68
  86. package/src/utils/codegen.ts +104 -0
  87. package/src/utils/extractStringsFromNodes.ts +34 -0
  88. package/src/utils/fileMerge.ts +184 -0
  89. package/src/utils/index.ts +11 -0
  90. package/src/utils/operationParams.ts +353 -0
  91. package/src/utils/refs.ts +138 -0
  92. package/src/utils/schemaGraph.ts +169 -0
  93. package/src/utils/schemaMerge.ts +34 -0
  94. package/src/utils/schemaTraversal.ts +86 -0
  95. package/src/utils/strings.ts +139 -0
  96. package/src/visitor.ts +227 -289
  97. package/dist/chunk--u3MIqq1.js +0 -8
  98. package/src/nodes/root.ts +0 -64
  99. package/src/refs.ts +0 -67
  100. package/src/resolvers.ts +0 -45
  101. package/src/transformers.ts +0 -159
  102. package/src/utils.ts +0 -915
@@ -0,0 +1,770 @@
1
+ import "./chunk-CNktS9qV.js";
2
+ import { d as resolveRefName, h as INDENT, m as narrowSchema, n as collectLazy, t as collect, u as resolveGroupType } from "./visitor-DJ6ZEJvq.js";
3
+ import { J as camelCase, X as createSchema, _ as createIndexedAccessType, g as createFunctionParameters, h as createFunctionParameter, y as createTypeLiteral } from "./response-KUdWiDWw.js";
4
+ //#region ../../internals/utils/src/promise.ts
5
+ /**
6
+ * Wraps `factory` with a keyed cache backed by the provided store.
7
+ *
8
+ * Pass a `WeakMap` for object keys (results are GC-eligible when the key is
9
+ * collected) or a `Map` for primitive keys. For multi-argument functions,
10
+ * nest two `memoize` calls — the outer keyed by the first argument, the
11
+ * inner (created once per outer miss) keyed by the second.
12
+ *
13
+ * Because the cache is owned by the caller, it can be shared, inspected, or
14
+ * cleared independently of the memoized function.
15
+ *
16
+ * @example Single WeakMap key
17
+ * ```ts
18
+ * const cache = new WeakMap<SchemaNode, Set<string>>()
19
+ * const getRefs = memoize(cache, (node) => collectRefs(node))
20
+ * ```
21
+ *
22
+ * @example Single Map key (primitive)
23
+ * ```ts
24
+ * const cache = new Map<string, Resolver>()
25
+ * const getResolver = memoize(cache, (name) => buildResolver(name))
26
+ * ```
27
+ *
28
+ * @example Two-level (object + primitive)
29
+ * ```ts
30
+ * const outer = new WeakMap<Params[], Map<string, Params[]>>()
31
+ * const fn = memoize(outer, (params) => memoize(new Map(), (key) => transform(params, key)))
32
+ * fn(params)('camelcase')
33
+ * ```
34
+ */
35
+ function memoize(store, factory) {
36
+ return (key) => {
37
+ if (store.has(key)) return store.get(key);
38
+ const value = factory(key);
39
+ store.set(key, value);
40
+ return value;
41
+ };
42
+ }
43
+ //#endregion
44
+ //#region ../../internals/utils/src/reserved.ts
45
+ /**
46
+ * JavaScript and Java reserved words.
47
+ * @link https://github.com/jonschlinkert/reserved/blob/master/index.js
48
+ */
49
+ const reservedWords = new Set([
50
+ "abstract",
51
+ "arguments",
52
+ "boolean",
53
+ "break",
54
+ "byte",
55
+ "case",
56
+ "catch",
57
+ "char",
58
+ "class",
59
+ "const",
60
+ "continue",
61
+ "debugger",
62
+ "default",
63
+ "delete",
64
+ "do",
65
+ "double",
66
+ "else",
67
+ "enum",
68
+ "eval",
69
+ "export",
70
+ "extends",
71
+ "false",
72
+ "final",
73
+ "finally",
74
+ "float",
75
+ "for",
76
+ "function",
77
+ "goto",
78
+ "if",
79
+ "implements",
80
+ "import",
81
+ "in",
82
+ "instanceof",
83
+ "int",
84
+ "interface",
85
+ "let",
86
+ "long",
87
+ "native",
88
+ "new",
89
+ "null",
90
+ "package",
91
+ "private",
92
+ "protected",
93
+ "public",
94
+ "return",
95
+ "short",
96
+ "static",
97
+ "super",
98
+ "switch",
99
+ "synchronized",
100
+ "this",
101
+ "throw",
102
+ "throws",
103
+ "transient",
104
+ "true",
105
+ "try",
106
+ "typeof",
107
+ "var",
108
+ "void",
109
+ "volatile",
110
+ "while",
111
+ "with",
112
+ "yield",
113
+ "Array",
114
+ "Date",
115
+ "hasOwnProperty",
116
+ "Infinity",
117
+ "isFinite",
118
+ "isNaN",
119
+ "isPrototypeOf",
120
+ "length",
121
+ "Math",
122
+ "name",
123
+ "NaN",
124
+ "Number",
125
+ "Object",
126
+ "prototype",
127
+ "String",
128
+ "toString",
129
+ "undefined",
130
+ "valueOf"
131
+ ]);
132
+ /**
133
+ * Returns `true` when `name` is a syntactically valid JavaScript variable name.
134
+ *
135
+ * @example
136
+ * ```ts
137
+ * isValidVarName('status') // true
138
+ * isValidVarName('class') // false (reserved word)
139
+ * isValidVarName('42foo') // false (starts with digit)
140
+ * ```
141
+ */
142
+ function isValidVarName(name) {
143
+ if (!name || reservedWords.has(name)) return false;
144
+ return isIdentifier(name);
145
+ }
146
+ /**
147
+ * Returns `true` when `name` is syntactically a valid identifier, ignoring reserved words.
148
+ *
149
+ * Reserved words and globals (`class`, `name`, `Date`, …) are valid as bare object-literal keys
150
+ * even though they are not valid variable names, so use this (not {@link isValidVarName}) when
151
+ * deciding whether an object key needs quoting.
152
+ *
153
+ * @example
154
+ * ```ts
155
+ * isIdentifier('name') // true
156
+ * isIdentifier('x-total')// false
157
+ * ```
158
+ */
159
+ function isIdentifier(name) {
160
+ return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name);
161
+ }
162
+ //#endregion
163
+ //#region ../../internals/utils/src/string.ts
164
+ /**
165
+ * Wraps a value in single quotes for emitting a single-quoted JavaScript string literal, escaping
166
+ * any backslash or single quote in the content.
167
+ *
168
+ * @example
169
+ * ```ts
170
+ * singleQuote('foo') // "'foo'"
171
+ * singleQuote("o'clock") // "'o\\'clock'"
172
+ * ```
173
+ */
174
+ function singleQuote(value) {
175
+ if (value === void 0 || value === null) return "''";
176
+ return `'${String(value).replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
177
+ }
178
+ //#endregion
179
+ //#region src/utils/codegen.ts
180
+ /**
181
+ * Builds a JSDoc comment block from an array of lines, returning `fallback` when there are no
182
+ * comments so callers always get a usable string.
183
+ *
184
+ * @example
185
+ * ```ts
186
+ * buildJSDoc(['@type string', '@example hello'])
187
+ * // '/**\n * @type string\n * @example hello\n *\/\n '
188
+ * ```
189
+ */
190
+ function buildJSDoc(comments, options = {}) {
191
+ const { indent = " * ", suffix = "\n ", fallback = " " } = options;
192
+ if (comments.length === 0) return fallback;
193
+ return `/**\n${comments.map((c) => `${indent}${c}`).join("\n")}\n */${suffix}`;
194
+ }
195
+ /**
196
+ * Indents every non-empty line of `text` by one indent level, leaving blank lines empty.
197
+ */
198
+ function indentLines(text) {
199
+ if (!text) return "";
200
+ return text.split("\n").map((line) => line.trim() ? `${INDENT}${line}` : "").join("\n");
201
+ }
202
+ /**
203
+ * Renders an object key, quoting it with single quotes only when it is not a valid identifier.
204
+ * Reserved words and globals (`name`, `class`, …) are valid bare keys and stay unquoted.
205
+ *
206
+ * @example
207
+ * ```ts
208
+ * objectKey('name') // 'name'
209
+ * objectKey('x-total') // "'x-total'"
210
+ * ```
211
+ */
212
+ function objectKey(name) {
213
+ return isIdentifier(name) ? name : singleQuote(name);
214
+ }
215
+ /**
216
+ * Assembles a multi-line object literal from already-rendered `entries`, indenting each entry one
217
+ * level and closing the brace at column zero. Nested objects built the same way indent cumulatively,
218
+ * so callers never re-parse the generated code. A trailing comma is added per entry to match the
219
+ * formatter's multi-line style.
220
+ *
221
+ * @example
222
+ * ```ts
223
+ * buildObject(['id: z.number()', 'name: z.string()'])
224
+ * // '{\n id: z.number(),\n name: z.string(),\n}'
225
+ * ```
226
+ */
227
+ function buildObject(entries) {
228
+ if (entries.length === 0) return "{}";
229
+ return `{\n${entries.map((entry) => `${indentLines(entry)},`).join("\n")}\n}`;
230
+ }
231
+ /**
232
+ * Assembles a bracketed list (array by default) from already-rendered `items`. Keeps everything on
233
+ * one line when no item spans multiple lines, and otherwise puts each item on its own line, indented
234
+ * one level with a trailing comma and the closing bracket at column zero. Use it for `z.union([…])`,
235
+ * `z.array([…])`, and similar member lists so objects inside them nest correctly.
236
+ *
237
+ * @example
238
+ * ```ts
239
+ * buildList(['z.string()', 'z.number()'])
240
+ * // '[z.string(), z.number()]'
241
+ * ```
242
+ */
243
+ function buildList(items, brackets = ["[", "]"]) {
244
+ const [open, close] = brackets;
245
+ if (items.length === 0) return `${open}${close}`;
246
+ if (!items.some((item) => item.includes("\n"))) return `${open}${items.join(", ")}${close}`;
247
+ return `${open}\n${items.map((item) => `${indentLines(item)},`).join("\n")}\n${close}`;
248
+ }
249
+ //#endregion
250
+ //#region src/utils/schemaMerge.ts
251
+ /**
252
+ * Merges a run of adjacent anonymous object members into one. Named or non-object members break the
253
+ * run and pass through. Stays a construction-time helper, not a macro, so callers keep control of the
254
+ * member boundaries (such as keeping synthetic discriminant objects out of a run).
255
+ *
256
+ * @example
257
+ * ```ts
258
+ * const merged = [...mergeAdjacentObjectsLazy([objectA, objectB])]
259
+ * ```
260
+ */
261
+ function* mergeAdjacentObjectsLazy(members) {
262
+ let acc;
263
+ for (const member of members) {
264
+ const objectMember = narrowSchema(member, "object");
265
+ if (objectMember && !objectMember.name && acc !== void 0) {
266
+ const accObject = narrowSchema(acc, "object");
267
+ if (accObject && !accObject.name) {
268
+ acc = createSchema({
269
+ ...accObject,
270
+ properties: [...accObject.properties ?? [], ...objectMember.properties ?? []]
271
+ });
272
+ continue;
273
+ }
274
+ }
275
+ if (acc !== void 0) yield acc;
276
+ acc = member;
277
+ }
278
+ if (acc !== void 0) yield acc;
279
+ }
280
+ //#endregion
281
+ //#region src/utils/strings.ts
282
+ /**
283
+ * Strips a single matching pair of `"..."`, `'...'`, or `` `...` `` from both ends of `text`.
284
+ * Returns the string unchanged when no balanced quote pair is found.
285
+ *
286
+ * @example
287
+ * ```ts
288
+ * trimQuotes('"hello"') // 'hello'
289
+ * trimQuotes('hello') // 'hello'
290
+ * ```
291
+ */
292
+ function trimQuotes(text) {
293
+ if (text.length >= 2) {
294
+ const first = text[0];
295
+ const last = text[text.length - 1];
296
+ if (first === "\"" && last === "\"" || first === "'" && last === "'" || first === "`" && last === "`") return text.slice(1, -1);
297
+ }
298
+ return text;
299
+ }
300
+ /**
301
+ * Serializes a primitive to a single-quoted string literal, stripping any surrounding quotes first.
302
+ *
303
+ * Escaping runs through `JSON.stringify`, then the result switches to single quotes so the generated
304
+ * code matches the repo style without a formatter.
305
+ *
306
+ * @example
307
+ * ```ts
308
+ * stringify('hello') // "'hello'"
309
+ * stringify('"hello"') // "'hello'"
310
+ * ```
311
+ */
312
+ function stringify(value) {
313
+ if (value === void 0 || value === null) return "''";
314
+ return `'${JSON.stringify(trimQuotes(value.toString())).slice(1, -1).replace(/\\"/g, "\"").replace(/'/g, "\\'")}'`;
315
+ }
316
+ /**
317
+ * Escapes characters that are not allowed inside JS string literals, covering quotes, backslashes,
318
+ * and the Unicode line terminators U+2028 and U+2029.
319
+ *
320
+ * @see http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.4
321
+ *
322
+ * @example
323
+ * ```ts
324
+ * jsStringEscape('say "hi"\nbye') // 'say \\"hi\\"\\nbye'
325
+ * ```
326
+ */
327
+ function jsStringEscape(input) {
328
+ return `${input}`.replace(/["'\\\n\r\u2028\u2029]/g, (character) => {
329
+ switch (character) {
330
+ case "\"":
331
+ case "'":
332
+ case "\\": return `\\${character}`;
333
+ case "\n": return "\\n";
334
+ case "\r": return "\\r";
335
+ case "\u2028": return "\\u2028";
336
+ case "\u2029": return "\\u2029";
337
+ default: return "";
338
+ }
339
+ });
340
+ }
341
+ /**
342
+ * Converts a pattern string into a `new RegExp(...)` constructor call or a regex literal string.
343
+ * Inline flags expressed as a `^(?im)` prefix are extracted and applied to the resulting expression.
344
+ * Pass `null` as the second argument to emit a `/pattern/flags` literal instead.
345
+ *
346
+ * @example
347
+ * ```ts
348
+ * toRegExpString('^(?im)foo') // 'new RegExp("^foo", "im")'
349
+ * toRegExpString('^(?im)foo', null) // '/^foo/im'
350
+ * ```
351
+ */
352
+ function toRegExpString(text, func = "RegExp") {
353
+ const raw = trimQuotes(text);
354
+ const match = raw.match(/^\^(\(\?([igmsuy]+)\))/i);
355
+ const replacementTarget = match?.[1] ?? "";
356
+ const matchedFlags = match?.[2];
357
+ const cleaned = raw.replace(/^\\?\//, "").replace(/\\?\/$/, "").replace(replacementTarget, "");
358
+ const { source, flags } = new RegExp(cleaned, matchedFlags);
359
+ if (func === null) return `/${source}/${flags}`;
360
+ return `new ${func}(${JSON.stringify(source)}${flags ? `, ${JSON.stringify(flags)}` : ""})`;
361
+ }
362
+ /**
363
+ * Renders a plain object as multi-line `key: value` source for embedding in generated code. Nested
364
+ * objects recurse with fixed indentation, so the result drops straight into an object literal
365
+ * without re-parsing.
366
+ *
367
+ * @example
368
+ * ```ts
369
+ * stringifyObject({ foo: 'bar', nested: { a: 1 } })
370
+ * // 'foo: bar,\nnested: {\n a: 1\n }'
371
+ * ```
372
+ */
373
+ function stringifyObject(value) {
374
+ return Object.entries(value).map(([key, val]) => {
375
+ if (val !== null && typeof val === "object") return `${key}: {\n ${stringifyObject(val)}\n }`;
376
+ return `${key}: ${val}`;
377
+ }).filter(Boolean).join(",\n");
378
+ }
379
+ /**
380
+ * Renders a dotted path or string array as an optional-chaining accessor expression rooted at
381
+ * `accessor`. Returns `null` for an empty path.
382
+ *
383
+ * @example
384
+ * ```ts
385
+ * getNestedAccessor('pagination.next.id', 'lastPage')
386
+ * // "lastPage?.['pagination']?.['next']?.['id']"
387
+ * ```
388
+ */
389
+ function getNestedAccessor(param, accessor) {
390
+ const parts = Array.isArray(param) ? param : param.split(".");
391
+ if (parts.length === 0 || parts.length === 1 && parts[0] === "") return null;
392
+ return `${accessor}?.['${`${parts.join("']?.['")}']`}`;
393
+ }
394
+ //#endregion
395
+ //#region src/utils/schemaGraph.ts
396
+ /**
397
+ * Collects every named schema referenced transitively from a node through its ref edges.
398
+ *
399
+ * Refs are followed by name only, so the resolved `node.schema` is never traversed inline.
400
+ *
401
+ * @example Collect refs from a single schema
402
+ * ```ts
403
+ * const names = collectReferencedSchemaNames(petSchema)
404
+ * // → Set { 'Category', 'Tag' }
405
+ * ```
406
+ *
407
+ * @example Accumulate refs from multiple schemas into one set
408
+ * ```ts
409
+ * const out = new Set<string>()
410
+ * for (const schema of schemas) {
411
+ * collectReferencedSchemaNames(schema, out)
412
+ * }
413
+ * ```
414
+ */
415
+ const collectSchemaRefs = memoize(/* @__PURE__ */ new WeakMap(), (node) => {
416
+ const refs = /* @__PURE__ */ new Set();
417
+ collect(node, { schema(child) {
418
+ if (child.type === "ref") {
419
+ const name = resolveRefName(child);
420
+ if (name) refs.add(name);
421
+ }
422
+ } });
423
+ return refs;
424
+ });
425
+ function collectReferencedSchemaNames(node, out = /* @__PURE__ */ new Set()) {
426
+ if (!node) return out;
427
+ for (const name of collectSchemaRefs(node)) out.add(name);
428
+ return out;
429
+ }
430
+ /**
431
+ * Collects the names of all top-level schemas transitively used by a set of operations.
432
+ *
433
+ * An operation uses a schema when its parameters, request body, or responses reference it, directly
434
+ * or through other named schemas. The walk is iterative, so reference cycles are safe.
435
+ *
436
+ * Pair it with `include` filters so schemas reachable only from excluded operations stay ungenerated.
437
+ *
438
+ * @example Only generate schemas referenced by included operations
439
+ * ```ts
440
+ * const includedOps = operations.filter((op) => resolver.resolveOptions(op, { options, include }) !== null)
441
+ * const allowed = collectUsedSchemaNames(includedOps, schemas)
442
+ *
443
+ * for (const schema of schemas) {
444
+ * if (schema.name && !allowed.has(schema.name)) continue
445
+ * // … generate schema
446
+ * }
447
+ * ```
448
+ */
449
+ const collectUsedSchemaNamesMemo = memoize(/* @__PURE__ */ new WeakMap(), (ops) => memoize(/* @__PURE__ */ new WeakMap(), (schemas) => computeUsedSchemaNames(ops, schemas)));
450
+ function computeUsedSchemaNames(operations, schemas) {
451
+ const schemaMap = /* @__PURE__ */ new Map();
452
+ for (const schema of schemas) if (schema.name) schemaMap.set(schema.name, schema);
453
+ const result = /* @__PURE__ */ new Set();
454
+ function visitSchema(schema) {
455
+ const directRefs = collectReferencedSchemaNames(schema);
456
+ for (const name of directRefs) if (!result.has(name)) {
457
+ result.add(name);
458
+ const namedSchema = schemaMap.get(name);
459
+ if (namedSchema) visitSchema(namedSchema);
460
+ }
461
+ }
462
+ for (const op of operations) for (const schema of collectLazy(op, {
463
+ depth: "shallow",
464
+ schema: (node) => node
465
+ })) visitSchema(schema);
466
+ return result;
467
+ }
468
+ function collectUsedSchemaNames(operations, schemas) {
469
+ return collectUsedSchemaNamesMemo(operations)(schemas);
470
+ }
471
+ const EMPTY_CIRCULAR_SET = /* @__PURE__ */ new Set();
472
+ const findCircularSchemasMemo = memoize(/* @__PURE__ */ new WeakMap(), (schemas) => {
473
+ const graph = /* @__PURE__ */ new Map();
474
+ for (const schema of schemas) {
475
+ if (!schema.name) continue;
476
+ graph.set(schema.name, collectReferencedSchemaNames(schema));
477
+ }
478
+ const circular = /* @__PURE__ */ new Set();
479
+ for (const start of graph.keys()) {
480
+ const visited = /* @__PURE__ */ new Set();
481
+ const stack = [...graph.get(start) ?? []];
482
+ while (stack.length > 0) {
483
+ const node = stack.pop();
484
+ if (node === start) {
485
+ circular.add(start);
486
+ break;
487
+ }
488
+ if (visited.has(node)) continue;
489
+ visited.add(node);
490
+ const next = graph.get(node);
491
+ if (next) for (const r of next) stack.push(r);
492
+ }
493
+ }
494
+ return circular;
495
+ });
496
+ /**
497
+ * Finds every schema that takes part in a circular dependency chain, including direct self-loops.
498
+ *
499
+ * Wrap the returned schema positions in a deferred construct (a lazy getter or `z.lazy(() => …)`) so
500
+ * the generated code does not recurse forever. Refs are followed by name only, so the walk stays
501
+ * linear in the size of the schema graph.
502
+ *
503
+ * @note Call this once on the full graph, then check individual schemas with `containsCircularRef()`.
504
+ */
505
+ function findCircularSchemas(schemas) {
506
+ if (schemas.length === 0) return EMPTY_CIRCULAR_SET;
507
+ return findCircularSchemasMemo(schemas);
508
+ }
509
+ /**
510
+ * Returns `true` when a schema, or anything nested inside it, references a circular schema.
511
+ *
512
+ * Pass `excludeName` to skip refs to a specific schema, which helps when self-references are handled
513
+ * on their own. Pair it with `findCircularSchemas()` to decide where lazy wrappers go.
514
+ *
515
+ * @note Stops at the first matching circular ref.
516
+ */
517
+ function containsCircularRef(node, { circularSchemas, excludeName }) {
518
+ if (!node || circularSchemas.size === 0) return false;
519
+ for (const _ of collectLazy(node, { schema(child) {
520
+ if (child.type !== "ref") return null;
521
+ const name = resolveRefName(child);
522
+ return name && name !== excludeName && circularSchemas.has(name) ? true : null;
523
+ } })) return true;
524
+ return false;
525
+ }
526
+ //#endregion
527
+ //#region src/utils/schemaTraversal.ts
528
+ /**
529
+ * Maps each property of an object schema to its transformed output. Pairs every result with the
530
+ * original property so the printer keeps full control over modifiers, getters, and key syntax.
531
+ *
532
+ * @example
533
+ * ```ts
534
+ * const entries = mapSchemaProperties(node, (schema) => this.transform(schema))
535
+ * // entries: [{ name: 'id', property, output: 'z.number()' }, ...]
536
+ * ```
537
+ */
538
+ function mapSchemaProperties(node, transform) {
539
+ return node.properties.map((property) => ({
540
+ name: property.name,
541
+ property,
542
+ output: transform(property.schema)
543
+ }));
544
+ }
545
+ /**
546
+ * Maps each member of a union or intersection schema to its transformed output, pairing every
547
+ * result with the original member.
548
+ */
549
+ function mapSchemaMembers(node, transform) {
550
+ return (node.members ?? []).map((schema) => ({
551
+ schema,
552
+ output: transform(schema)
553
+ }));
554
+ }
555
+ /**
556
+ * Maps each item of an array or tuple schema to its transformed output, pairing every result with
557
+ * the original item.
558
+ */
559
+ function mapSchemaItems(node, transform) {
560
+ return (node.items ?? []).map((schema) => ({
561
+ schema,
562
+ output: transform(schema)
563
+ }));
564
+ }
565
+ /**
566
+ * Emits a lazy getter for a circular-ref property position, `get name() { return body }`. The key
567
+ * is quoted only when it is not a valid identifier. Used by the string printers to defer evaluation
568
+ * of a recursive schema until first access.
569
+ *
570
+ * @example
571
+ * ```ts
572
+ * lazyGetter({ name: 'parent', body: 'z.lazy(() => Pet)' })
573
+ * // "get parent() { return z.lazy(() => Pet) }"
574
+ * ```
575
+ */
576
+ function lazyGetter({ name, body }) {
577
+ return `get ${objectKey(name)}() { return ${body} }`;
578
+ }
579
+ //#endregion
580
+ //#region src/utils/operationParams.ts
581
+ /**
582
+ * Applies casing rules to parameter names and returns a new array without mutating the input.
583
+ *
584
+ * Run it before handing parameters to schema builders so output property keys get the right casing
585
+ * while `OperationNode.parameters` stays intact for other consumers. When `casing` is unset, the
586
+ * original array is returned unchanged.
587
+ */
588
+ const caseParamsMemo = memoize(/* @__PURE__ */ new WeakMap(), (params) => memoize(/* @__PURE__ */ new Map(), (casing) => params.map((param) => {
589
+ const transformed = casing === "camelcase" || !isValidVarName(param.name) ? camelCase(param.name) : param.name;
590
+ return {
591
+ ...param,
592
+ name: transformed
593
+ };
594
+ })));
595
+ function caseParams(params, casing) {
596
+ if (!casing) return params;
597
+ return caseParamsMemo(params)(casing);
598
+ }
599
+ /**
600
+ * Resolves the {@link TypeExpression} for an individual parameter.
601
+ *
602
+ * Without a resolver, it falls back to the schema primitive (a plain type-name string). When the
603
+ * parameter belongs to a named group, it emits an {@link IndexedAccessTypeNode} like
604
+ * `GroupParams['petId']`, otherwise the resolved individual name.
605
+ */
606
+ function resolveParamType({ node, param, resolver }) {
607
+ if (!resolver) return param.schema.primitive ?? "unknown";
608
+ const individualName = resolver.resolveParamName(node, param);
609
+ const groupLocation = param.in === "path" || param.in === "query" || param.in === "header" ? param.in : void 0;
610
+ const groupResolvers = {
611
+ path: resolver.resolvePathParamsName,
612
+ query: resolver.resolveQueryParamsName,
613
+ header: resolver.resolveHeaderParamsName
614
+ };
615
+ const groupName = groupLocation ? groupResolvers[groupLocation].call(resolver, node, param) : void 0;
616
+ if (groupName && groupName !== individualName) return createIndexedAccessType({
617
+ objectType: groupName,
618
+ indexType: param.name
619
+ });
620
+ return individualName;
621
+ }
622
+ /**
623
+ * Converts an `OperationNode` into function parameters for code generation.
624
+ *
625
+ * Centralizes parameter grouping logic for all plugins. `paramsType` chooses between one
626
+ * destructured object parameter (`object`) and separate top-level parameters (`inline`), while
627
+ * `pathParamsType` controls how path params render in inline mode. Provide a `resolver` for type
628
+ * name resolution and `extraParams` for plugin-specific trailing parameters such as an `options` object.
629
+ */
630
+ function createOperationParams(node, options) {
631
+ const { paramsType, pathParamsType, paramsCasing, resolver, pathParamsDefault, extraParams = [], paramNames, typeWrapper } = options;
632
+ const dataName = paramNames?.data ?? "data";
633
+ const paramsName = paramNames?.params ?? "params";
634
+ const headersName = paramNames?.headers ?? "headers";
635
+ const pathName = paramNames?.path ?? "pathParams";
636
+ const wrapType = (type) => typeWrapper ? typeWrapper(type) : type;
637
+ const wrapTypeExpression = (type) => typeof type === "string" ? wrapType(type) : type;
638
+ const casedParams = caseParams(node.parameters, paramsCasing);
639
+ const pathParams = casedParams.filter((p) => p.in === "path");
640
+ const queryParams = casedParams.filter((p) => p.in === "query");
641
+ const headerParams = casedParams.filter((p) => p.in === "header");
642
+ const toProperty = (param) => ({
643
+ name: param.name,
644
+ type: wrapTypeExpression(resolveParamType({
645
+ node,
646
+ param,
647
+ resolver
648
+ })),
649
+ optional: !param.required
650
+ });
651
+ const emptyObjectDefault = (props) => props.every((p) => p.optional) ? "{}" : void 0;
652
+ const bodyType = node.requestBody?.content?.[0]?.schema ? wrapType(resolver?.resolveDataName(node) ?? "unknown") : void 0;
653
+ const bodyProperty = bodyType ? [{
654
+ name: dataName,
655
+ type: bodyType,
656
+ optional: !(node.requestBody?.required ?? false)
657
+ }] : [];
658
+ const trailingGroups = [{
659
+ name: paramsName,
660
+ node,
661
+ params: queryParams,
662
+ groupType: resolveGroupType({
663
+ node,
664
+ params: queryParams,
665
+ group: "query",
666
+ resolver
667
+ }),
668
+ resolver,
669
+ wrapType
670
+ }, {
671
+ name: headersName,
672
+ node,
673
+ params: headerParams,
674
+ groupType: resolveGroupType({
675
+ node,
676
+ params: headerParams,
677
+ group: "header",
678
+ resolver
679
+ }),
680
+ resolver,
681
+ wrapType
682
+ }];
683
+ const params = [];
684
+ if (paramsType === "object") {
685
+ const children = [
686
+ ...pathParams.map(toProperty),
687
+ ...bodyProperty,
688
+ ...trailingGroups.flatMap(buildGroupProperty)
689
+ ];
690
+ if (children.length) params.push(createFunctionParameter({
691
+ properties: children,
692
+ default: emptyObjectDefault(children)
693
+ }));
694
+ } else {
695
+ if (pathParamsType === "inlineSpread" && pathParams.length) {
696
+ const spreadType = resolver?.resolvePathParamsName(node, pathParams[0]);
697
+ params.push(createFunctionParameter({
698
+ name: pathName,
699
+ type: spreadType ? wrapType(spreadType) : void 0,
700
+ rest: true
701
+ }));
702
+ } else if (pathParamsType === "inline") params.push(...pathParams.map((p) => createFunctionParameter(toProperty(p))));
703
+ else if (pathParams.length) {
704
+ const pathChildren = pathParams.map(toProperty);
705
+ params.push(createFunctionParameter({
706
+ properties: pathChildren,
707
+ default: pathParamsDefault ?? emptyObjectDefault(pathChildren)
708
+ }));
709
+ }
710
+ params.push(...bodyProperty.map((p) => createFunctionParameter(p)));
711
+ params.push(...trailingGroups.flatMap(buildGroupParam));
712
+ }
713
+ params.push(...extraParams);
714
+ return createFunctionParameters({ params });
715
+ }
716
+ /**
717
+ * Builds the property descriptor for a query or header group.
718
+ * Returns an empty array when there are no params to emit.
719
+ *
720
+ * A pre-resolved `groupType` emits `name: GroupType`. Otherwise it builds an inline
721
+ * {@link TypeLiteralNode} from the individual params.
722
+ */
723
+ function buildGroupProperty({ name, node, params, groupType, resolver, wrapType }) {
724
+ if (groupType) return [{
725
+ name,
726
+ type: typeof groupType.type === "string" ? wrapType(groupType.type) : groupType.type,
727
+ optional: groupType.optional
728
+ }];
729
+ if (params.length) return [{
730
+ name,
731
+ type: buildTypeLiteral({
732
+ node,
733
+ params,
734
+ resolver
735
+ }),
736
+ optional: params.every((p) => !p.required)
737
+ }];
738
+ return [];
739
+ }
740
+ /**
741
+ * Builds a single {@link FunctionParameterNode} for a query or header group.
742
+ * Returns an empty array when there are no params to emit.
743
+ *
744
+ * A pre-resolved `groupType` emits `name: GroupType`. Otherwise it builds an inline
745
+ * {@link TypeLiteralNode} from the individual params.
746
+ */
747
+ function buildGroupParam(args) {
748
+ return buildGroupProperty(args).map((p) => createFunctionParameter(p));
749
+ }
750
+ /**
751
+ * Builds a {@link TypeLiteralNode} for an inline anonymous type grouping named fields.
752
+ *
753
+ * Used when query or header parameters have no dedicated group type name.
754
+ * Each language printer renders this appropriately (TypeScript: `{ petId: string; name?: string }`).
755
+ */
756
+ function buildTypeLiteral({ node, params, resolver }) {
757
+ return createTypeLiteral({ members: params.map((p) => ({
758
+ name: p.name,
759
+ type: resolveParamType({
760
+ node,
761
+ param: p,
762
+ resolver
763
+ }),
764
+ optional: !p.required
765
+ })) });
766
+ }
767
+ //#endregion
768
+ export { objectKey as C, buildObject as S, toRegExpString as _, resolveParamType as a, buildJSDoc as b, mapSchemaMembers as c, containsCircularRef as d, findCircularSchemas as f, stringifyObject as g, stringify as h, createOperationParams as i, mapSchemaProperties as l, jsStringEscape as m, buildTypeLiteral as n, lazyGetter as o, getNestedAccessor as p, caseParams as r, mapSchemaItems as s, buildGroupParam as t, collectUsedSchemaNames as u, trimQuotes as v, isValidVarName as w, buildList as x, mergeAdjacentObjectsLazy as y };
769
+
770
+ //# sourceMappingURL=utils-CF_-Pn_c.js.map