@kubb/ast 5.0.0-beta.59 → 5.0.0-beta.60

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.
@@ -0,0 +1,1645 @@
1
+ const require_response = require("./response-DS5S3IG4.cjs");
2
+ //#region src/constants.ts
3
+ const visitorDepths = {
4
+ shallow: "shallow",
5
+ deep: "deep"
6
+ };
7
+ /**
8
+ * Schema type discriminators used by all AST schema nodes.
9
+ *
10
+ * Each value is a stable discriminator across the AST (for example `schema.type === schemaTypes.object`).
11
+ * Call `isScalarPrimitive()` to check for the scalar types.
12
+ */
13
+ const schemaTypes = {
14
+ /**
15
+ * Text value.
16
+ */
17
+ string: "string",
18
+ /**
19
+ * Floating-point number (`float`, `double`).
20
+ */
21
+ number: "number",
22
+ /**
23
+ * Whole number (`int32`). Use `bigint` for `int64`.
24
+ */
25
+ integer: "integer",
26
+ /**
27
+ * 64-bit integer (`int64`). Only used when `integerType` is set to `'bigint'`.
28
+ */
29
+ bigint: "bigint",
30
+ /**
31
+ * Boolean value.
32
+ */
33
+ boolean: "boolean",
34
+ /**
35
+ * Explicit null value.
36
+ */
37
+ null: "null",
38
+ /**
39
+ * Any value (no type restriction).
40
+ */
41
+ any: "any",
42
+ /**
43
+ * Unknown value (must be narrowed before usage).
44
+ */
45
+ unknown: "unknown",
46
+ /**
47
+ * No return value (`void`).
48
+ */
49
+ void: "void",
50
+ /**
51
+ * Object with named properties.
52
+ */
53
+ object: "object",
54
+ /**
55
+ * Sequential list of items.
56
+ */
57
+ array: "array",
58
+ /**
59
+ * Fixed-length list with position-specific items.
60
+ */
61
+ tuple: "tuple",
62
+ /**
63
+ * "One of" multiple schema members.
64
+ */
65
+ union: "union",
66
+ /**
67
+ * "All of" multiple schema members.
68
+ */
69
+ intersection: "intersection",
70
+ /**
71
+ * Enum schema.
72
+ */
73
+ enum: "enum",
74
+ /**
75
+ * Reference to another schema.
76
+ */
77
+ ref: "ref",
78
+ /**
79
+ * Calendar date (for example `2026-03-24`).
80
+ */
81
+ date: "date",
82
+ /**
83
+ * Date-time value (for example `2026-03-24T09:00:00Z`).
84
+ */
85
+ datetime: "datetime",
86
+ /**
87
+ * Time-only value (for example `09:00:00`).
88
+ */
89
+ time: "time",
90
+ /**
91
+ * UUID value.
92
+ */
93
+ uuid: "uuid",
94
+ /**
95
+ * Email address value.
96
+ */
97
+ email: "email",
98
+ /**
99
+ * URL value.
100
+ */
101
+ url: "url",
102
+ /**
103
+ * IPv4 address value.
104
+ */
105
+ ipv4: "ipv4",
106
+ /**
107
+ * IPv6 address value.
108
+ */
109
+ ipv6: "ipv6",
110
+ /**
111
+ * Binary/blob value.
112
+ */
113
+ blob: "blob",
114
+ /**
115
+ * Impossible value (`never`).
116
+ */
117
+ never: "never"
118
+ };
119
+ /**
120
+ * Scalar primitive schema types used for union simplification and type narrowing.
121
+ */
122
+ const SCALAR_PRIMITIVE_TYPES = new Set([
123
+ "string",
124
+ "number",
125
+ "integer",
126
+ "bigint",
127
+ "boolean"
128
+ ]);
129
+ /**
130
+ * Returns `true` when `type` is a scalar primitive that can be assigned without wrapping
131
+ * (for example `string | number | boolean`).
132
+ */
133
+ function isScalarPrimitive(type) {
134
+ return SCALAR_PRIMITIVE_TYPES.has(type);
135
+ }
136
+ /**
137
+ * HTTP method identifiers used by operation nodes.
138
+ */
139
+ const httpMethods = {
140
+ get: "GET",
141
+ post: "POST",
142
+ put: "PUT",
143
+ patch: "PATCH",
144
+ delete: "DELETE",
145
+ head: "HEAD",
146
+ options: "OPTIONS",
147
+ trace: "TRACE"
148
+ };
149
+ /**
150
+ * One indentation level, derived from {@link INDENT_SIZE}.
151
+ */
152
+ const INDENT = Array.from({ length: 2 }, () => " ").join("");
153
+ //#endregion
154
+ //#region ../../internals/utils/src/promise.ts
155
+ /**
156
+ * Wraps `factory` with a keyed cache backed by the provided store.
157
+ *
158
+ * Pass a `WeakMap` for object keys (results are GC-eligible when the key is
159
+ * collected) or a `Map` for primitive keys. For multi-argument functions,
160
+ * nest two `memoize` calls — the outer keyed by the first argument, the
161
+ * inner (created once per outer miss) keyed by the second.
162
+ *
163
+ * Because the cache is owned by the caller, it can be shared, inspected, or
164
+ * cleared independently of the memoized function.
165
+ *
166
+ * @example Single WeakMap key
167
+ * ```ts
168
+ * const cache = new WeakMap<SchemaNode, Set<string>>()
169
+ * const getRefs = memoize(cache, (node) => collectRefs(node))
170
+ * ```
171
+ *
172
+ * @example Single Map key (primitive)
173
+ * ```ts
174
+ * const cache = new Map<string, Resolver>()
175
+ * const getResolver = memoize(cache, (name) => buildResolver(name))
176
+ * ```
177
+ *
178
+ * @example Two-level (object + primitive)
179
+ * ```ts
180
+ * const outer = new WeakMap<Params[], Map<string, Params[]>>()
181
+ * const fn = memoize(outer, (params) => memoize(new Map(), (key) => transform(params, key)))
182
+ * fn(params)('camelcase')
183
+ * ```
184
+ */
185
+ function memoize(store, factory) {
186
+ return (key) => {
187
+ if (store.has(key)) return store.get(key);
188
+ const value = factory(key);
189
+ store.set(key, value);
190
+ return value;
191
+ };
192
+ }
193
+ //#endregion
194
+ //#region ../../internals/utils/src/reserved.ts
195
+ /**
196
+ * JavaScript and Java reserved words.
197
+ * @link https://github.com/jonschlinkert/reserved/blob/master/index.js
198
+ */
199
+ const reservedWords = new Set([
200
+ "abstract",
201
+ "arguments",
202
+ "boolean",
203
+ "break",
204
+ "byte",
205
+ "case",
206
+ "catch",
207
+ "char",
208
+ "class",
209
+ "const",
210
+ "continue",
211
+ "debugger",
212
+ "default",
213
+ "delete",
214
+ "do",
215
+ "double",
216
+ "else",
217
+ "enum",
218
+ "eval",
219
+ "export",
220
+ "extends",
221
+ "false",
222
+ "final",
223
+ "finally",
224
+ "float",
225
+ "for",
226
+ "function",
227
+ "goto",
228
+ "if",
229
+ "implements",
230
+ "import",
231
+ "in",
232
+ "instanceof",
233
+ "int",
234
+ "interface",
235
+ "let",
236
+ "long",
237
+ "native",
238
+ "new",
239
+ "null",
240
+ "package",
241
+ "private",
242
+ "protected",
243
+ "public",
244
+ "return",
245
+ "short",
246
+ "static",
247
+ "super",
248
+ "switch",
249
+ "synchronized",
250
+ "this",
251
+ "throw",
252
+ "throws",
253
+ "transient",
254
+ "true",
255
+ "try",
256
+ "typeof",
257
+ "var",
258
+ "void",
259
+ "volatile",
260
+ "while",
261
+ "with",
262
+ "yield",
263
+ "Array",
264
+ "Date",
265
+ "hasOwnProperty",
266
+ "Infinity",
267
+ "isFinite",
268
+ "isNaN",
269
+ "isPrototypeOf",
270
+ "length",
271
+ "Math",
272
+ "name",
273
+ "NaN",
274
+ "Number",
275
+ "Object",
276
+ "prototype",
277
+ "String",
278
+ "toString",
279
+ "undefined",
280
+ "valueOf"
281
+ ]);
282
+ /**
283
+ * Returns `true` when `name` is a syntactically valid JavaScript variable name.
284
+ *
285
+ * @example
286
+ * ```ts
287
+ * isValidVarName('status') // true
288
+ * isValidVarName('class') // false (reserved word)
289
+ * isValidVarName('42foo') // false (starts with digit)
290
+ * ```
291
+ */
292
+ function isValidVarName(name) {
293
+ if (!name || reservedWords.has(name)) return false;
294
+ return isIdentifier(name);
295
+ }
296
+ /**
297
+ * Returns `true` when `name` is syntactically a valid identifier, ignoring reserved words.
298
+ *
299
+ * Reserved words and globals (`class`, `name`, `Date`, …) are valid as bare object-literal keys
300
+ * even though they are not valid variable names, so use this (not {@link isValidVarName}) when
301
+ * deciding whether an object key needs quoting.
302
+ *
303
+ * @example
304
+ * ```ts
305
+ * isIdentifier('name') // true
306
+ * isIdentifier('x-total')// false
307
+ * ```
308
+ */
309
+ function isIdentifier(name) {
310
+ return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name);
311
+ }
312
+ //#endregion
313
+ //#region ../../internals/utils/src/string.ts
314
+ /**
315
+ * Wraps a value in single quotes for emitting a single-quoted JavaScript string literal, escaping
316
+ * any backslash or single quote in the content.
317
+ *
318
+ * @example
319
+ * ```ts
320
+ * singleQuote('foo') // "'foo'"
321
+ * singleQuote("o'clock") // "'o\\'clock'"
322
+ * ```
323
+ */
324
+ function singleQuote(value) {
325
+ if (value === void 0 || value === null) return "''";
326
+ return `'${String(value).replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
327
+ }
328
+ //#endregion
329
+ //#region src/utils/codegen.ts
330
+ /**
331
+ * Builds a JSDoc comment block from an array of lines, returning `fallback` when there are no
332
+ * comments so callers always get a usable string.
333
+ *
334
+ * @example
335
+ * ```ts
336
+ * buildJSDoc(['@type string', '@example hello'])
337
+ * // '/**\n * @type string\n * @example hello\n *\/\n '
338
+ * ```
339
+ */
340
+ function buildJSDoc(comments, options = {}) {
341
+ const { indent = " * ", suffix = "\n ", fallback = " " } = options;
342
+ if (comments.length === 0) return fallback;
343
+ return `/**\n${comments.map((c) => `${indent}${c}`).join("\n")}\n */${suffix}`;
344
+ }
345
+ /**
346
+ * Indents every non-empty line of `text` by one indent level, leaving blank lines empty.
347
+ */
348
+ function indentLines(text) {
349
+ if (!text) return "";
350
+ return text.split("\n").map((line) => line.trim() ? `${INDENT}${line}` : "").join("\n");
351
+ }
352
+ /**
353
+ * Renders an object key, quoting it with single quotes only when it is not a valid identifier.
354
+ * Reserved words and globals (`name`, `class`, …) are valid bare keys and stay unquoted.
355
+ *
356
+ * @example
357
+ * ```ts
358
+ * objectKey('name') // 'name'
359
+ * objectKey('x-total') // "'x-total'"
360
+ * ```
361
+ */
362
+ function objectKey(name) {
363
+ return isIdentifier(name) ? name : singleQuote(name);
364
+ }
365
+ /**
366
+ * Assembles a multi-line object literal from already-rendered `entries`, indenting each entry one
367
+ * level and closing the brace at column zero. Nested objects built the same way indent cumulatively,
368
+ * so callers never re-parse the generated code. A trailing comma is added per entry to match the
369
+ * formatter's multi-line style.
370
+ *
371
+ * @example
372
+ * ```ts
373
+ * buildObject(['id: z.number()', 'name: z.string()'])
374
+ * // '{\n id: z.number(),\n name: z.string(),\n}'
375
+ * ```
376
+ */
377
+ function buildObject(entries) {
378
+ if (entries.length === 0) return "{}";
379
+ return `{\n${entries.map((entry) => `${indentLines(entry)},`).join("\n")}\n}`;
380
+ }
381
+ /**
382
+ * Assembles a bracketed list (array by default) from already-rendered `items`. Keeps everything on
383
+ * one line when no item spans multiple lines, and otherwise puts each item on its own line, indented
384
+ * one level with a trailing comma and the closing bracket at column zero. Use it for `z.union([…])`,
385
+ * `z.array([…])`, and similar member lists so objects inside them nest correctly.
386
+ *
387
+ * @example
388
+ * ```ts
389
+ * buildList(['z.string()', 'z.number()'])
390
+ * // '[z.string(), z.number()]'
391
+ * ```
392
+ */
393
+ function buildList(items, brackets = ["[", "]"]) {
394
+ const [open, close] = brackets;
395
+ if (items.length === 0) return `${open}${close}`;
396
+ if (!items.some((item) => item.includes("\n"))) return `${open}${items.join(", ")}${close}`;
397
+ return `${open}\n${items.map((item) => `${indentLines(item)},`).join("\n")}\n${close}`;
398
+ }
399
+ //#endregion
400
+ //#region src/guards.ts
401
+ /**
402
+ * Narrows a `SchemaNode` to the variant that matches `type`.
403
+ *
404
+ * @example
405
+ * ```ts
406
+ * const schema = createSchema({ type: 'string' })
407
+ * const stringNode = narrowSchema(schema, 'string') // StringSchemaNode | null
408
+ * ```
409
+ */
410
+ function narrowSchema(node, type) {
411
+ return node?.type === type ? node : null;
412
+ }
413
+ /**
414
+ * Narrows an `OperationNode` to an `HttpOperationNode` so `method` and `path` are present.
415
+ *
416
+ * @example
417
+ * ```ts
418
+ * if (isHttpOperationNode(node)) {
419
+ * console.log(node.method, node.path)
420
+ * }
421
+ * ```
422
+ */
423
+ function isHttpOperationNode(node) {
424
+ return node.protocol === "http" || node.method !== void 0 && node.path !== void 0;
425
+ }
426
+ //#endregion
427
+ //#region src/utils/refs.ts
428
+ const plainStringTypes = new Set([
429
+ "string",
430
+ "uuid",
431
+ "email",
432
+ "url",
433
+ "datetime"
434
+ ]);
435
+ /**
436
+ * Returns the last path segment of a reference string.
437
+ *
438
+ * @example
439
+ * ```ts
440
+ * extractRefName('#/components/schemas/Pet') // 'Pet'
441
+ * ```
442
+ */
443
+ function extractRefName(ref) {
444
+ return ref.split("/").at(-1) ?? ref;
445
+ }
446
+ /**
447
+ * Resolves the schema name of a ref node, falling back through `ref` → `name` → nested `schema.name`.
448
+ *
449
+ * Returns `null` for non-ref nodes or when no name resolves.
450
+ *
451
+ * @example
452
+ * ```ts
453
+ * resolveRefName({ kind: 'Schema', type: 'ref', ref: '#/components/schemas/Pet' })
454
+ * // => 'Pet'
455
+ * ```
456
+ */
457
+ function resolveRefName(node) {
458
+ if (!node || node.type !== "ref") return null;
459
+ if (node.ref) return extractRefName(node.ref) ?? node.name ?? node.schema?.name ?? null;
460
+ return node.name ?? node.schema?.name ?? null;
461
+ }
462
+ /**
463
+ * Builds a PascalCase child schema name by joining a parent name and property name.
464
+ * Returns `null` when there is no parent to nest under.
465
+ *
466
+ * @example
467
+ * ```ts
468
+ * childName('Order', 'shipping_address') // 'OrderShippingAddress'
469
+ * childName(undefined, 'params') // null
470
+ * ```
471
+ */
472
+ function childName(parentName, propName) {
473
+ return parentName ? require_response.pascalCase([parentName, propName].join(" ")) : null;
474
+ }
475
+ /**
476
+ * Builds a PascalCase enum name from the parent name, property name, and a suffix, skipping any
477
+ * empty parts.
478
+ *
479
+ * @example
480
+ * ```ts
481
+ * enumPropName('Order', 'status', 'enum') // 'OrderStatusEnum'
482
+ * ```
483
+ */
484
+ function enumPropName(parentName, propName, enumSuffix) {
485
+ return require_response.pascalCase([
486
+ parentName,
487
+ propName,
488
+ enumSuffix
489
+ ].filter(Boolean).join(" "));
490
+ }
491
+ /**
492
+ * Type guard that returns `true` when a schema emits as a plain `string` type.
493
+ *
494
+ * Covers `string`, `uuid`, `email`, `url`, and `datetime` types. For `date` and `time`
495
+ * types, returns `true` only when `representation` is `'string'` rather than `'date'`.
496
+ */
497
+ function isStringType(node) {
498
+ if (plainStringTypes.has(node.type)) return true;
499
+ const temporal = narrowSchema(node, "date") ?? narrowSchema(node, "time");
500
+ if (temporal) return temporal.representation !== "date";
501
+ return false;
502
+ }
503
+ /**
504
+ * Derives a {@link ParamGroupType} for a query or header group from the resolver.
505
+ *
506
+ * Returns `null` when there is no resolver, no params, or the group name equals the
507
+ * individual param name (so there is no real group to emit).
508
+ */
509
+ function resolveGroupType({ node, params, group, resolver }) {
510
+ if (!resolver || !params.length) return null;
511
+ const firstParam = params[0];
512
+ const groupName = (group === "query" ? resolver.resolveQueryParamsName : resolver.resolveHeaderParamsName).call(resolver, node, firstParam);
513
+ if (groupName === resolver.resolveParamName(node, firstParam)) return null;
514
+ return {
515
+ type: groupName,
516
+ optional: params.every((p) => !p.required)
517
+ };
518
+ }
519
+ //#endregion
520
+ //#region src/transformers.ts
521
+ /**
522
+ * Replaces a discriminator property's schema with a string enum of allowed values.
523
+ *
524
+ * If `node` is not an object schema, or if the property does not exist, the input
525
+ * node is returned as-is.
526
+ *
527
+ * @example
528
+ * ```ts
529
+ * const schema = createSchema({
530
+ * type: 'object',
531
+ * properties: [createProperty({ name: 'type', required: true, schema: createSchema({ type: 'string' }) })],
532
+ * })
533
+ * const result = setDiscriminatorEnum({ node: schema, propertyName: 'type', values: ['dog', 'cat'] })
534
+ * ```
535
+ */
536
+ function setDiscriminatorEnum({ node, propertyName, values, enumName }) {
537
+ const objectNode = narrowSchema(node, "object");
538
+ if (!objectNode?.properties?.length) return node;
539
+ if (!objectNode.properties.some((prop) => prop.name === propertyName)) return node;
540
+ return require_response.createSchema({
541
+ ...objectNode,
542
+ properties: objectNode.properties.map((prop) => {
543
+ if (prop.name !== propertyName) return prop;
544
+ return require_response.createProperty({
545
+ ...prop,
546
+ schema: require_response.createSchema({
547
+ type: "enum",
548
+ primitive: "string",
549
+ enumValues: values,
550
+ name: enumName,
551
+ readOnly: prop.schema.readOnly,
552
+ writeOnly: prop.schema.writeOnly
553
+ })
554
+ });
555
+ })
556
+ });
557
+ }
558
+ /**
559
+ * Merges adjacent anonymous object members into a single anonymous object member.
560
+ *
561
+ * @example
562
+ * ```ts
563
+ * const merged = mergeAdjacentObjects([
564
+ * createSchema({ type: 'object', properties: [createProperty({ name: 'a', schema: createSchema({ type: 'string' }) })] }),
565
+ * createSchema({ type: 'object', properties: [createProperty({ name: 'b', schema: createSchema({ type: 'number' }) })] }),
566
+ * ])
567
+ * ```
568
+ */
569
+ function* mergeAdjacentObjectsLazy(members) {
570
+ let acc;
571
+ for (const member of members) {
572
+ const objectMember = narrowSchema(member, "object");
573
+ if (objectMember && !objectMember.name && acc !== void 0) {
574
+ const accObject = narrowSchema(acc, "object");
575
+ if (accObject && !accObject.name) {
576
+ acc = require_response.createSchema({
577
+ ...accObject,
578
+ properties: [...accObject.properties ?? [], ...objectMember.properties ?? []]
579
+ });
580
+ continue;
581
+ }
582
+ }
583
+ if (acc !== void 0) yield acc;
584
+ acc = member;
585
+ }
586
+ if (acc !== void 0) yield acc;
587
+ }
588
+ /**
589
+ * Removes enum members that are covered by broader scalar primitives in the same union.
590
+ *
591
+ * @example
592
+ * ```ts
593
+ * const simplified = simplifyUnion([
594
+ * createSchema({ type: 'enum', primitive: 'string', enumValues: ['active'] }),
595
+ * createSchema({ type: 'string' }),
596
+ * ])
597
+ * // keeps only string member
598
+ * ```
599
+ */
600
+ function simplifyUnion(members) {
601
+ const scalarPrimitives = new Set(members.filter((member) => isScalarPrimitive(member.type)).map((m) => m.type));
602
+ if (!scalarPrimitives.size) return members;
603
+ return members.filter((member) => {
604
+ const enumNode = narrowSchema(member, "enum");
605
+ if (!enumNode) return true;
606
+ const primitive = enumNode.primitive;
607
+ if (!primitive) return true;
608
+ if ((enumNode.namedEnumValues?.length ?? enumNode.enumValues?.length ?? 0) <= 1) return true;
609
+ if (scalarPrimitives.has(primitive)) return false;
610
+ if ((primitive === "integer" || primitive === "number") && (scalarPrimitives.has("integer") || scalarPrimitives.has("number"))) return false;
611
+ return true;
612
+ });
613
+ }
614
+ function setEnumName(propNode, parentName, propName, enumSuffix) {
615
+ const enumNode = narrowSchema(propNode, "enum");
616
+ if (enumNode?.primitive === "boolean") return {
617
+ ...propNode,
618
+ name: null
619
+ };
620
+ if (enumNode) return {
621
+ ...propNode,
622
+ name: enumPropName(parentName, propName, enumSuffix)
623
+ };
624
+ return propNode;
625
+ }
626
+ /**
627
+ * Merges a ref node with its resolved schema, giving usage-site fields precedence.
628
+ *
629
+ * Usage-site fields (`description`, `readOnly`, `nullable`, `deprecated`) on the ref node override
630
+ * the same fields in the resolved `node.schema`. Non-ref nodes are returned unchanged.
631
+ *
632
+ * @example
633
+ * ```ts
634
+ * // Ref with description override
635
+ * const ref = createSchema({ type: 'ref', ref: '#/components/schemas/Pet', description: 'A cute pet' })
636
+ * const merged = syncSchemaRef(ref) // merges with resolved Pet schema
637
+ * ```
638
+ */
639
+ function syncSchemaRef(node) {
640
+ const ref = narrowSchema(node, "ref");
641
+ if (!ref) return node;
642
+ if (!ref.schema) return node;
643
+ const { kind: _kind, type: _type, name: _name, ref: _ref, schema: _schema, ...overrides } = ref;
644
+ const definedOverrides = Object.fromEntries(Object.entries(overrides).filter(([, v]) => v !== void 0));
645
+ return require_response.createSchema({
646
+ ...ref.schema,
647
+ ...definedOverrides
648
+ });
649
+ }
650
+ //#endregion
651
+ //#region src/utils/strings.ts
652
+ /**
653
+ * Strips a single matching pair of `"..."`, `'...'`, or `` `...` `` from both ends of `text`.
654
+ * Returns the string unchanged when no balanced quote pair is found.
655
+ *
656
+ * @example
657
+ * ```ts
658
+ * trimQuotes('"hello"') // 'hello'
659
+ * trimQuotes('hello') // 'hello'
660
+ * ```
661
+ */
662
+ function trimQuotes(text) {
663
+ if (text.length >= 2) {
664
+ const first = text[0];
665
+ const last = text[text.length - 1];
666
+ if (first === "\"" && last === "\"" || first === "'" && last === "'" || first === "`" && last === "`") return text.slice(1, -1);
667
+ }
668
+ return text;
669
+ }
670
+ /**
671
+ * Serializes a primitive to a single-quoted string literal, stripping any surrounding quotes first.
672
+ *
673
+ * Escaping runs through `JSON.stringify`, then the result switches to single quotes so the generated
674
+ * code matches the repo style without a formatter.
675
+ *
676
+ * @example
677
+ * ```ts
678
+ * stringify('hello') // "'hello'"
679
+ * stringify('"hello"') // "'hello'"
680
+ * ```
681
+ */
682
+ function stringify(value) {
683
+ if (value === void 0 || value === null) return "''";
684
+ return `'${JSON.stringify(trimQuotes(value.toString())).slice(1, -1).replace(/\\"/g, "\"").replace(/'/g, "\\'")}'`;
685
+ }
686
+ /**
687
+ * Escapes characters that are not allowed inside JS string literals, covering quotes, backslashes,
688
+ * and the Unicode line terminators U+2028 and U+2029.
689
+ *
690
+ * @see http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.4
691
+ *
692
+ * @example
693
+ * ```ts
694
+ * jsStringEscape('say "hi"\nbye') // 'say \\"hi\\"\\nbye'
695
+ * ```
696
+ */
697
+ function jsStringEscape(input) {
698
+ return `${input}`.replace(/["'\\\n\r\u2028\u2029]/g, (character) => {
699
+ switch (character) {
700
+ case "\"":
701
+ case "'":
702
+ case "\\": return `\\${character}`;
703
+ case "\n": return "\\n";
704
+ case "\r": return "\\r";
705
+ case "\u2028": return "\\u2028";
706
+ case "\u2029": return "\\u2029";
707
+ default: return "";
708
+ }
709
+ });
710
+ }
711
+ /**
712
+ * Converts a pattern string into a `new RegExp(...)` constructor call or a regex literal string.
713
+ * Inline flags expressed as a `^(?im)` prefix are extracted and applied to the resulting expression.
714
+ * Pass `null` as the second argument to emit a `/pattern/flags` literal instead.
715
+ *
716
+ * @example
717
+ * ```ts
718
+ * toRegExpString('^(?im)foo') // 'new RegExp("^foo", "im")'
719
+ * toRegExpString('^(?im)foo', null) // '/^foo/im'
720
+ * ```
721
+ */
722
+ function toRegExpString(text, func = "RegExp") {
723
+ const raw = trimQuotes(text);
724
+ const match = raw.match(/^\^(\(\?([igmsuy]+)\))/i);
725
+ const replacementTarget = match?.[1] ?? "";
726
+ const matchedFlags = match?.[2];
727
+ const cleaned = raw.replace(/^\\?\//, "").replace(/\\?\/$/, "").replace(replacementTarget, "");
728
+ const { source, flags } = new RegExp(cleaned, matchedFlags);
729
+ if (func === null) return `/${source}/${flags}`;
730
+ return `new ${func}(${JSON.stringify(source)}${flags ? `, ${JSON.stringify(flags)}` : ""})`;
731
+ }
732
+ /**
733
+ * Renders a plain object as multi-line `key: value` source for embedding in generated code. Nested
734
+ * objects recurse with fixed indentation, so the result drops straight into an object literal
735
+ * without re-parsing.
736
+ *
737
+ * @example
738
+ * ```ts
739
+ * stringifyObject({ foo: 'bar', nested: { a: 1 } })
740
+ * // 'foo: bar,\nnested: {\n a: 1\n }'
741
+ * ```
742
+ */
743
+ function stringifyObject(value) {
744
+ return Object.entries(value).map(([key, val]) => {
745
+ if (val !== null && typeof val === "object") return `${key}: {\n ${stringifyObject(val)}\n }`;
746
+ return `${key}: ${val}`;
747
+ }).filter(Boolean).join(",\n");
748
+ }
749
+ /**
750
+ * Renders a dotted path or string array as an optional-chaining accessor expression rooted at
751
+ * `accessor`. Returns `null` for an empty path.
752
+ *
753
+ * @example
754
+ * ```ts
755
+ * getNestedAccessor('pagination.next.id', 'lastPage')
756
+ * // "lastPage?.['pagination']?.['next']?.['id']"
757
+ * ```
758
+ */
759
+ function getNestedAccessor(param, accessor) {
760
+ const parts = Array.isArray(param) ? param : param.split(".");
761
+ if (parts.length === 0 || parts.length === 1 && parts[0] === "") return null;
762
+ return `${accessor}?.['${`${parts.join("']?.['")}']`}`;
763
+ }
764
+ //#endregion
765
+ //#region src/registry.ts
766
+ /**
767
+ * Every node definition. Adding a node means adding its `defineNode` to one
768
+ * `nodes/*.ts` file and listing it here. The visitor tables in `visitor.ts` derive from it.
769
+ */
770
+ const nodeDefs = [
771
+ require_response.inputDef,
772
+ require_response.outputDef,
773
+ require_response.operationDef,
774
+ require_response.requestBodyDef,
775
+ require_response.contentDef,
776
+ require_response.responseDef,
777
+ require_response.schemaDef,
778
+ require_response.propertyDef,
779
+ require_response.parameterDef,
780
+ require_response.functionParameterDef,
781
+ require_response.functionParametersDef,
782
+ require_response.typeLiteralDef,
783
+ require_response.indexedAccessTypeDef,
784
+ require_response.objectBindingPatternDef,
785
+ require_response.constDef,
786
+ require_response.typeDef,
787
+ require_response.functionDef,
788
+ require_response.arrowFunctionDef,
789
+ require_response.textDef,
790
+ require_response.breakDef,
791
+ require_response.jsxDef,
792
+ require_response.importDef,
793
+ require_response.exportDef,
794
+ require_response.sourceDef,
795
+ require_response.fileDef
796
+ ];
797
+ //#endregion
798
+ //#region src/visitor.ts
799
+ /**
800
+ * Child node fields per node kind, in traversal order (Babel's `VISITOR_KEYS`).
801
+ * Derived from each definition's `children`.
802
+ */
803
+ const VISITOR_KEYS = Object.fromEntries(nodeDefs.flatMap((def) => def.children ? [[def.kind, def.children]] : []));
804
+ /**
805
+ * Maps a node kind to the matching visitor callback name. Derived from each
806
+ * definition's `visitorKey`.
807
+ */
808
+ const VISITOR_KEY_BY_KIND = Object.fromEntries(nodeDefs.flatMap((def) => def.visitorKey ? [[def.kind, def.visitorKey]] : []));
809
+ /**
810
+ * Per-kind builders rerun after children are rebuilt. Derived from each
811
+ * definition's `rebuild` flag.
812
+ */
813
+ const nodeRebuilders = Object.fromEntries(nodeDefs.flatMap((def) => def.rebuild ? [[def.kind, def.create]] : []));
814
+ /**
815
+ * Creates a small async concurrency limiter.
816
+ *
817
+ * At most `concurrency` tasks are in flight at once. Extra tasks are queued.
818
+ *
819
+ * @example
820
+ * ```ts
821
+ * const limit = createLimit(2)
822
+ * for (const task of [taskA, taskB, taskC]) {
823
+ * await limit(() => task())
824
+ * }
825
+ * // only 2 tasks run at the same time
826
+ * ```
827
+ */
828
+ function createLimit(concurrency) {
829
+ let active = 0;
830
+ const queue = [];
831
+ function next() {
832
+ if (active < concurrency && queue.length > 0) {
833
+ active++;
834
+ queue.shift()();
835
+ }
836
+ }
837
+ return function limit(fn) {
838
+ return new Promise((resolve, reject) => {
839
+ queue.push(() => {
840
+ Promise.resolve(fn()).then(resolve, reject).finally(() => {
841
+ active--;
842
+ next();
843
+ });
844
+ });
845
+ next();
846
+ });
847
+ };
848
+ }
849
+ const visitorKeysByKind = VISITOR_KEYS;
850
+ /**
851
+ * Returns `true` when `value` is an AST node (an object carrying a `kind`).
852
+ */
853
+ function isNode(value) {
854
+ return typeof value === "object" && value !== null && "kind" in value;
855
+ }
856
+ /**
857
+ * Returns the immediate traversable children of `node` based on {@link VISITOR_KEYS}.
858
+ *
859
+ * `Schema` children are only included when `recurse` is `true`. Shallow mode skips them.
860
+ *
861
+ * @example
862
+ * ```ts
863
+ * const children = getChildren(operationNode, true)
864
+ * // returns parameters, the request body, and responses
865
+ * ```
866
+ */
867
+ function* getChildren(node, recurse) {
868
+ if (node.kind === "Schema" && !recurse) return;
869
+ const keys = visitorKeysByKind[node.kind];
870
+ if (!keys) return;
871
+ const record = node;
872
+ for (const key of keys) {
873
+ const value = record[key];
874
+ if (Array.isArray(value)) {
875
+ for (const item of value) if (isNode(item)) yield item;
876
+ } else if (isNode(value)) yield value;
877
+ }
878
+ }
879
+ /**
880
+ * Runs the visitor callback that matches `node.kind` with the traversal
881
+ * context. The result is a replacement node, a collected value, or `undefined`
882
+ * when no callback is registered for the kind.
883
+ *
884
+ * Shared by `walk`, `transform`, and `collectLazy` so node-kind dispatch lives
885
+ * in one place. `TResult` is the caller's expected return: the same node type
886
+ * for `transform`, the collected value type for `collectLazy`, ignored for `walk`.
887
+ */
888
+ function applyVisitor(node, visitor, parent) {
889
+ const key = VISITOR_KEY_BY_KIND[node.kind];
890
+ if (!key) return void 0;
891
+ const fn = visitor[key];
892
+ return fn?.(node, { parent });
893
+ }
894
+ /**
895
+ * Async depth-first traversal for side effects. Visitor return values are
896
+ * ignored. Use `transform` when you want to rewrite nodes.
897
+ *
898
+ * Sibling nodes at each depth run concurrently up to `options.concurrency`
899
+ * (defaults to `WALK_CONCURRENCY`). Higher values overlap I/O-bound visitor
900
+ * work. Lower values reduce memory pressure.
901
+ *
902
+ * @example Log every operation
903
+ * ```ts
904
+ * await walk(root, {
905
+ * operation(node) {
906
+ * console.log(node.operationId)
907
+ * },
908
+ * })
909
+ * ```
910
+ *
911
+ * @example Only visit the root node
912
+ * ```ts
913
+ * await walk(root, { depth: 'shallow', input: () => {} })
914
+ * ```
915
+ */
916
+ async function walk(node, options) {
917
+ return _walk(node, options, (options.depth ?? visitorDepths.deep) === visitorDepths.deep, createLimit(options.concurrency ?? 30), void 0);
918
+ }
919
+ async function _walk(node, visitor, recurse, limit, parent) {
920
+ await limit(() => applyVisitor(node, visitor, parent));
921
+ const children = Array.from(getChildren(node, recurse));
922
+ if (children.length === 0) return;
923
+ await Promise.all(children.map((child) => _walk(child, visitor, recurse, limit, node)));
924
+ }
925
+ function transform(node, options) {
926
+ const { depth, parent, ...visitor } = options;
927
+ const recurse = (depth ?? visitorDepths.deep) === visitorDepths.deep;
928
+ const rebuilt = transformChildren(applyVisitor(node, visitor, parent) ?? node, options, recurse);
929
+ if (rebuilt === node) return node;
930
+ const rebuild = nodeRebuilders[rebuilt.kind];
931
+ return rebuild ? rebuild(rebuilt) : rebuilt;
932
+ }
933
+ /**
934
+ * Immutably rebuilds a node's children using {@link VISITOR_KEYS}, transforming
935
+ * each child node and leaving non-node values (e.g. `additionalProperties: true`) intact.
936
+ * `Schema` children are skipped in shallow mode.
937
+ */
938
+ function transformChildren(node, options, recurse) {
939
+ if (node.kind === "Schema" && !recurse) return node;
940
+ const keys = visitorKeysByKind[node.kind];
941
+ if (!keys) return node;
942
+ const record = node;
943
+ const childOptions = {
944
+ ...options,
945
+ parent: node
946
+ };
947
+ let updates;
948
+ for (const key of keys) {
949
+ if (!(key in record)) continue;
950
+ const value = record[key];
951
+ if (Array.isArray(value)) {
952
+ let changed = false;
953
+ const mapped = value.map((item) => {
954
+ if (!isNode(item)) return item;
955
+ const next = transform(item, childOptions);
956
+ if (next !== item) changed = true;
957
+ return next;
958
+ });
959
+ if (changed) (updates ??= {})[key] = mapped;
960
+ } else if (isNode(value)) {
961
+ const next = transform(value, childOptions);
962
+ if (next !== value) (updates ??= {})[key] = next;
963
+ }
964
+ }
965
+ return updates ? {
966
+ ...node,
967
+ ...updates
968
+ } : node;
969
+ }
970
+ /**
971
+ * Lazy depth-first collection pass. Yields every non-null value returned by
972
+ * the visitor callbacks. Use `collect` for the eager array form.
973
+ *
974
+ * @example Collect every operationId
975
+ * ```ts
976
+ * const ids: string[] = []
977
+ * for (const id of collectLazy<string>(root, {
978
+ * operation(node) {
979
+ * return node.operationId
980
+ * },
981
+ * })) {
982
+ * ids.push(id)
983
+ * }
984
+ * ```
985
+ */
986
+ function* collectLazy(node, options) {
987
+ const { depth, parent, ...visitor } = options;
988
+ const recurse = (depth ?? visitorDepths.deep) === visitorDepths.deep;
989
+ const v = applyVisitor(node, visitor, parent);
990
+ if (v != null) yield v;
991
+ for (const child of getChildren(node, recurse)) yield* collectLazy(child, {
992
+ ...options,
993
+ parent: node
994
+ });
995
+ }
996
+ /**
997
+ * Eager depth-first collection pass. Gathers every non-null value the visitor
998
+ * callbacks return into an array.
999
+ *
1000
+ * @example Collect every operationId
1001
+ * ```ts
1002
+ * const ids = collect<string>(root, {
1003
+ * operation(node) {
1004
+ * return node.operationId
1005
+ * },
1006
+ * })
1007
+ * ```
1008
+ */
1009
+ function collect(node, options) {
1010
+ return Array.from(collectLazy(node, options));
1011
+ }
1012
+ //#endregion
1013
+ //#region src/utils/schemaGraph.ts
1014
+ /**
1015
+ * Collects every named schema referenced transitively from a node through its ref edges.
1016
+ *
1017
+ * Refs are followed by name only, so the resolved `node.schema` is never traversed inline.
1018
+ *
1019
+ * @example Collect refs from a single schema
1020
+ * ```ts
1021
+ * const names = collectReferencedSchemaNames(petSchema)
1022
+ * // → Set { 'Category', 'Tag' }
1023
+ * ```
1024
+ *
1025
+ * @example Accumulate refs from multiple schemas into one set
1026
+ * ```ts
1027
+ * const out = new Set<string>()
1028
+ * for (const schema of schemas) {
1029
+ * collectReferencedSchemaNames(schema, out)
1030
+ * }
1031
+ * ```
1032
+ */
1033
+ const collectSchemaRefs = memoize(/* @__PURE__ */ new WeakMap(), (node) => {
1034
+ const refs = /* @__PURE__ */ new Set();
1035
+ collect(node, { schema(child) {
1036
+ if (child.type === "ref") {
1037
+ const name = resolveRefName(child);
1038
+ if (name) refs.add(name);
1039
+ }
1040
+ } });
1041
+ return refs;
1042
+ });
1043
+ function collectReferencedSchemaNames(node, out = /* @__PURE__ */ new Set()) {
1044
+ if (!node) return out;
1045
+ for (const name of collectSchemaRefs(node)) out.add(name);
1046
+ return out;
1047
+ }
1048
+ /**
1049
+ * Collects the names of all top-level schemas transitively used by a set of operations.
1050
+ *
1051
+ * An operation uses a schema when its parameters, request body, or responses reference it, directly
1052
+ * or through other named schemas. The walk is iterative, so reference cycles are safe.
1053
+ *
1054
+ * Pair it with `include` filters so schemas reachable only from excluded operations stay ungenerated.
1055
+ *
1056
+ * @example Only generate schemas referenced by included operations
1057
+ * ```ts
1058
+ * const includedOps = operations.filter((op) => resolver.resolveOptions(op, { options, include }) !== null)
1059
+ * const allowed = collectUsedSchemaNames(includedOps, schemas)
1060
+ *
1061
+ * for (const schema of schemas) {
1062
+ * if (schema.name && !allowed.has(schema.name)) continue
1063
+ * // … generate schema
1064
+ * }
1065
+ * ```
1066
+ */
1067
+ const collectUsedSchemaNamesMemo = memoize(/* @__PURE__ */ new WeakMap(), (ops) => memoize(/* @__PURE__ */ new WeakMap(), (schemas) => computeUsedSchemaNames(ops, schemas)));
1068
+ function computeUsedSchemaNames(operations, schemas) {
1069
+ const schemaMap = /* @__PURE__ */ new Map();
1070
+ for (const schema of schemas) if (schema.name) schemaMap.set(schema.name, schema);
1071
+ const result = /* @__PURE__ */ new Set();
1072
+ function visitSchema(schema) {
1073
+ const directRefs = collectReferencedSchemaNames(schema);
1074
+ for (const name of directRefs) if (!result.has(name)) {
1075
+ result.add(name);
1076
+ const namedSchema = schemaMap.get(name);
1077
+ if (namedSchema) visitSchema(namedSchema);
1078
+ }
1079
+ }
1080
+ for (const op of operations) for (const schema of collectLazy(op, {
1081
+ depth: "shallow",
1082
+ schema: (node) => node
1083
+ })) visitSchema(schema);
1084
+ return result;
1085
+ }
1086
+ function collectUsedSchemaNames(operations, schemas) {
1087
+ return collectUsedSchemaNamesMemo(operations)(schemas);
1088
+ }
1089
+ const EMPTY_CIRCULAR_SET = /* @__PURE__ */ new Set();
1090
+ const findCircularSchemasMemo = memoize(/* @__PURE__ */ new WeakMap(), (schemas) => {
1091
+ const graph = /* @__PURE__ */ new Map();
1092
+ for (const schema of schemas) {
1093
+ if (!schema.name) continue;
1094
+ graph.set(schema.name, collectReferencedSchemaNames(schema));
1095
+ }
1096
+ const circular = /* @__PURE__ */ new Set();
1097
+ for (const start of graph.keys()) {
1098
+ const visited = /* @__PURE__ */ new Set();
1099
+ const stack = [...graph.get(start) ?? []];
1100
+ while (stack.length > 0) {
1101
+ const node = stack.pop();
1102
+ if (node === start) {
1103
+ circular.add(start);
1104
+ break;
1105
+ }
1106
+ if (visited.has(node)) continue;
1107
+ visited.add(node);
1108
+ const next = graph.get(node);
1109
+ if (next) for (const r of next) stack.push(r);
1110
+ }
1111
+ }
1112
+ return circular;
1113
+ });
1114
+ /**
1115
+ * Finds every schema that takes part in a circular dependency chain, including direct self-loops.
1116
+ *
1117
+ * Wrap the returned schema positions in a deferred construct (a lazy getter or `z.lazy(() => …)`) so
1118
+ * the generated code does not recurse forever. Refs are followed by name only, so the walk stays
1119
+ * linear in the size of the schema graph.
1120
+ *
1121
+ * @note Call this once on the full graph, then check individual schemas with `containsCircularRef()`.
1122
+ */
1123
+ function findCircularSchemas(schemas) {
1124
+ if (schemas.length === 0) return EMPTY_CIRCULAR_SET;
1125
+ return findCircularSchemasMemo(schemas);
1126
+ }
1127
+ /**
1128
+ * Returns `true` when a schema, or anything nested inside it, references a circular schema.
1129
+ *
1130
+ * Pass `excludeName` to skip refs to a specific schema, which helps when self-references are handled
1131
+ * on their own. Pair it with `findCircularSchemas()` to decide where lazy wrappers go.
1132
+ *
1133
+ * @note Stops at the first matching circular ref.
1134
+ */
1135
+ function containsCircularRef(node, { circularSchemas, excludeName }) {
1136
+ if (!node || circularSchemas.size === 0) return false;
1137
+ for (const _ of collectLazy(node, { schema(child) {
1138
+ if (child.type !== "ref") return null;
1139
+ const name = resolveRefName(child);
1140
+ return name && name !== excludeName && circularSchemas.has(name) ? true : null;
1141
+ } })) return true;
1142
+ return false;
1143
+ }
1144
+ //#endregion
1145
+ //#region src/utils/schemaTraversal.ts
1146
+ /**
1147
+ * Maps each property of an object schema to its transformed output. Pairs every result with the
1148
+ * original property so the printer keeps full control over modifiers, getters, and key syntax.
1149
+ *
1150
+ * @example
1151
+ * ```ts
1152
+ * const entries = mapSchemaProperties(node, (schema) => this.transform(schema))
1153
+ * // entries: [{ name: 'id', property, output: 'z.number()' }, ...]
1154
+ * ```
1155
+ */
1156
+ function mapSchemaProperties(node, transform) {
1157
+ return node.properties.map((property) => ({
1158
+ name: property.name,
1159
+ property,
1160
+ output: transform(property.schema)
1161
+ }));
1162
+ }
1163
+ /**
1164
+ * Maps each member of a union or intersection schema to its transformed output, pairing every
1165
+ * result with the original member.
1166
+ */
1167
+ function mapSchemaMembers(node, transform) {
1168
+ return (node.members ?? []).map((schema) => ({
1169
+ schema,
1170
+ output: transform(schema)
1171
+ }));
1172
+ }
1173
+ /**
1174
+ * Maps each item of an array or tuple schema to its transformed output, pairing every result with
1175
+ * the original item.
1176
+ */
1177
+ function mapSchemaItems(node, transform) {
1178
+ return (node.items ?? []).map((schema) => ({
1179
+ schema,
1180
+ output: transform(schema)
1181
+ }));
1182
+ }
1183
+ /**
1184
+ * Emits a lazy getter for a circular-ref property position, `get name() { return body }`. The key
1185
+ * is quoted only when it is not a valid identifier. Used by the string printers to defer evaluation
1186
+ * of a recursive schema until first access.
1187
+ *
1188
+ * @example
1189
+ * ```ts
1190
+ * lazyGetter({ name: 'parent', body: 'z.lazy(() => Pet)' })
1191
+ * // "get parent() { return z.lazy(() => Pet) }"
1192
+ * ```
1193
+ */
1194
+ function lazyGetter({ name, body }) {
1195
+ return `get ${objectKey(name)}() { return ${body} }`;
1196
+ }
1197
+ //#endregion
1198
+ //#region src/utils/operationParams.ts
1199
+ /**
1200
+ * Applies casing rules to parameter names and returns a new array without mutating the input.
1201
+ *
1202
+ * Run it before handing parameters to schema builders so output property keys get the right casing
1203
+ * while `OperationNode.parameters` stays intact for other consumers. When `casing` is unset, the
1204
+ * original array is returned unchanged.
1205
+ */
1206
+ const caseParamsMemo = memoize(/* @__PURE__ */ new WeakMap(), (params) => memoize(/* @__PURE__ */ new Map(), (casing) => params.map((param) => {
1207
+ const transformed = casing === "camelcase" || !isValidVarName(param.name) ? require_response.camelCase(param.name) : param.name;
1208
+ return {
1209
+ ...param,
1210
+ name: transformed
1211
+ };
1212
+ })));
1213
+ function caseParams(params, casing) {
1214
+ if (!casing) return params;
1215
+ return caseParamsMemo(params)(casing);
1216
+ }
1217
+ /**
1218
+ * Resolves the {@link TypeExpression} for an individual parameter.
1219
+ *
1220
+ * Without a resolver, it falls back to the schema primitive (a plain type-name string). When the
1221
+ * parameter belongs to a named group, it emits an {@link IndexedAccessTypeNode} like
1222
+ * `GroupParams['petId']`, otherwise the resolved individual name.
1223
+ */
1224
+ function resolveParamType({ node, param, resolver }) {
1225
+ if (!resolver) return param.schema.primitive ?? "unknown";
1226
+ const individualName = resolver.resolveParamName(node, param);
1227
+ const groupLocation = param.in === "path" || param.in === "query" || param.in === "header" ? param.in : void 0;
1228
+ const groupResolvers = {
1229
+ path: resolver.resolvePathParamsName,
1230
+ query: resolver.resolveQueryParamsName,
1231
+ header: resolver.resolveHeaderParamsName
1232
+ };
1233
+ const groupName = groupLocation ? groupResolvers[groupLocation].call(resolver, node, param) : void 0;
1234
+ if (groupName && groupName !== individualName) return require_response.createIndexedAccessType({
1235
+ objectType: groupName,
1236
+ indexType: param.name
1237
+ });
1238
+ return individualName;
1239
+ }
1240
+ /**
1241
+ * Converts an `OperationNode` into function parameters for code generation.
1242
+ *
1243
+ * Centralizes parameter grouping logic for all plugins. `paramsType` chooses between one
1244
+ * destructured object parameter (`object`) and separate top-level parameters (`inline`), while
1245
+ * `pathParamsType` controls how path params render in inline mode. Provide a `resolver` for type
1246
+ * name resolution and `extraParams` for plugin-specific trailing parameters such as an `options` object.
1247
+ */
1248
+ function createOperationParams(node, options) {
1249
+ const { paramsType, pathParamsType, paramsCasing, resolver, pathParamsDefault, extraParams = [], paramNames, typeWrapper } = options;
1250
+ const dataName = paramNames?.data ?? "data";
1251
+ const paramsName = paramNames?.params ?? "params";
1252
+ const headersName = paramNames?.headers ?? "headers";
1253
+ const pathName = paramNames?.path ?? "pathParams";
1254
+ const wrapType = (type) => typeWrapper ? typeWrapper(type) : type;
1255
+ const wrapTypeExpression = (type) => typeof type === "string" ? wrapType(type) : type;
1256
+ const casedParams = caseParams(node.parameters, paramsCasing);
1257
+ const pathParams = casedParams.filter((p) => p.in === "path");
1258
+ const queryParams = casedParams.filter((p) => p.in === "query");
1259
+ const headerParams = casedParams.filter((p) => p.in === "header");
1260
+ const toProperty = (param) => ({
1261
+ name: param.name,
1262
+ type: wrapTypeExpression(resolveParamType({
1263
+ node,
1264
+ param,
1265
+ resolver
1266
+ })),
1267
+ optional: !param.required
1268
+ });
1269
+ const emptyObjectDefault = (props) => props.every((p) => p.optional) ? "{}" : void 0;
1270
+ const bodyType = node.requestBody?.content?.[0]?.schema ? wrapType(resolver?.resolveDataName(node) ?? "unknown") : void 0;
1271
+ const bodyProperty = bodyType ? [{
1272
+ name: dataName,
1273
+ type: bodyType,
1274
+ optional: !(node.requestBody?.required ?? false)
1275
+ }] : [];
1276
+ const trailingGroups = [{
1277
+ name: paramsName,
1278
+ node,
1279
+ params: queryParams,
1280
+ groupType: resolveGroupType({
1281
+ node,
1282
+ params: queryParams,
1283
+ group: "query",
1284
+ resolver
1285
+ }),
1286
+ resolver,
1287
+ wrapType
1288
+ }, {
1289
+ name: headersName,
1290
+ node,
1291
+ params: headerParams,
1292
+ groupType: resolveGroupType({
1293
+ node,
1294
+ params: headerParams,
1295
+ group: "header",
1296
+ resolver
1297
+ }),
1298
+ resolver,
1299
+ wrapType
1300
+ }];
1301
+ const params = [];
1302
+ if (paramsType === "object") {
1303
+ const children = [
1304
+ ...pathParams.map(toProperty),
1305
+ ...bodyProperty,
1306
+ ...trailingGroups.flatMap(buildGroupProperty)
1307
+ ];
1308
+ if (children.length) params.push(require_response.createFunctionParameter({
1309
+ properties: children,
1310
+ default: emptyObjectDefault(children)
1311
+ }));
1312
+ } else {
1313
+ if (pathParamsType === "inlineSpread" && pathParams.length) {
1314
+ const spreadType = resolver?.resolvePathParamsName(node, pathParams[0]);
1315
+ params.push(require_response.createFunctionParameter({
1316
+ name: pathName,
1317
+ type: spreadType ? wrapType(spreadType) : void 0,
1318
+ rest: true
1319
+ }));
1320
+ } else if (pathParamsType === "inline") params.push(...pathParams.map((p) => require_response.createFunctionParameter(toProperty(p))));
1321
+ else if (pathParams.length) {
1322
+ const pathChildren = pathParams.map(toProperty);
1323
+ params.push(require_response.createFunctionParameter({
1324
+ properties: pathChildren,
1325
+ default: pathParamsDefault ?? emptyObjectDefault(pathChildren)
1326
+ }));
1327
+ }
1328
+ params.push(...bodyProperty.map((p) => require_response.createFunctionParameter(p)));
1329
+ params.push(...trailingGroups.flatMap(buildGroupParam));
1330
+ }
1331
+ params.push(...extraParams);
1332
+ return require_response.createFunctionParameters({ params });
1333
+ }
1334
+ /**
1335
+ * Builds the property descriptor for a query or header group.
1336
+ * Returns an empty array when there are no params to emit.
1337
+ *
1338
+ * A pre-resolved `groupType` emits `name: GroupType`. Otherwise it builds an inline
1339
+ * {@link TypeLiteralNode} from the individual params.
1340
+ */
1341
+ function buildGroupProperty({ name, node, params, groupType, resolver, wrapType }) {
1342
+ if (groupType) return [{
1343
+ name,
1344
+ type: typeof groupType.type === "string" ? wrapType(groupType.type) : groupType.type,
1345
+ optional: groupType.optional
1346
+ }];
1347
+ if (params.length) return [{
1348
+ name,
1349
+ type: buildTypeLiteral({
1350
+ node,
1351
+ params,
1352
+ resolver
1353
+ }),
1354
+ optional: params.every((p) => !p.required)
1355
+ }];
1356
+ return [];
1357
+ }
1358
+ /**
1359
+ * Builds a single {@link FunctionParameterNode} for a query or header group.
1360
+ * Returns an empty array when there are no params to emit.
1361
+ *
1362
+ * A pre-resolved `groupType` emits `name: GroupType`. Otherwise it builds an inline
1363
+ * {@link TypeLiteralNode} from the individual params.
1364
+ */
1365
+ function buildGroupParam(args) {
1366
+ return buildGroupProperty(args).map((p) => require_response.createFunctionParameter(p));
1367
+ }
1368
+ /**
1369
+ * Builds a {@link TypeLiteralNode} for an inline anonymous type grouping named fields.
1370
+ *
1371
+ * Used when query or header parameters have no dedicated group type name.
1372
+ * Each language printer renders this appropriately (TypeScript: `{ petId: string; name?: string }`).
1373
+ */
1374
+ function buildTypeLiteral({ node, params, resolver }) {
1375
+ return require_response.createTypeLiteral({ members: params.map((p) => ({
1376
+ name: p.name,
1377
+ type: resolveParamType({
1378
+ node,
1379
+ param: p,
1380
+ resolver
1381
+ }),
1382
+ optional: !p.required
1383
+ })) });
1384
+ }
1385
+ //#endregion
1386
+ Object.defineProperty(exports, "buildGroupParam", {
1387
+ enumerable: true,
1388
+ get: function() {
1389
+ return buildGroupParam;
1390
+ }
1391
+ });
1392
+ Object.defineProperty(exports, "buildJSDoc", {
1393
+ enumerable: true,
1394
+ get: function() {
1395
+ return buildJSDoc;
1396
+ }
1397
+ });
1398
+ Object.defineProperty(exports, "buildList", {
1399
+ enumerable: true,
1400
+ get: function() {
1401
+ return buildList;
1402
+ }
1403
+ });
1404
+ Object.defineProperty(exports, "buildObject", {
1405
+ enumerable: true,
1406
+ get: function() {
1407
+ return buildObject;
1408
+ }
1409
+ });
1410
+ Object.defineProperty(exports, "buildTypeLiteral", {
1411
+ enumerable: true,
1412
+ get: function() {
1413
+ return buildTypeLiteral;
1414
+ }
1415
+ });
1416
+ Object.defineProperty(exports, "caseParams", {
1417
+ enumerable: true,
1418
+ get: function() {
1419
+ return caseParams;
1420
+ }
1421
+ });
1422
+ Object.defineProperty(exports, "childName", {
1423
+ enumerable: true,
1424
+ get: function() {
1425
+ return childName;
1426
+ }
1427
+ });
1428
+ Object.defineProperty(exports, "collect", {
1429
+ enumerable: true,
1430
+ get: function() {
1431
+ return collect;
1432
+ }
1433
+ });
1434
+ Object.defineProperty(exports, "collectLazy", {
1435
+ enumerable: true,
1436
+ get: function() {
1437
+ return collectLazy;
1438
+ }
1439
+ });
1440
+ Object.defineProperty(exports, "collectUsedSchemaNames", {
1441
+ enumerable: true,
1442
+ get: function() {
1443
+ return collectUsedSchemaNames;
1444
+ }
1445
+ });
1446
+ Object.defineProperty(exports, "containsCircularRef", {
1447
+ enumerable: true,
1448
+ get: function() {
1449
+ return containsCircularRef;
1450
+ }
1451
+ });
1452
+ Object.defineProperty(exports, "createOperationParams", {
1453
+ enumerable: true,
1454
+ get: function() {
1455
+ return createOperationParams;
1456
+ }
1457
+ });
1458
+ Object.defineProperty(exports, "enumPropName", {
1459
+ enumerable: true,
1460
+ get: function() {
1461
+ return enumPropName;
1462
+ }
1463
+ });
1464
+ Object.defineProperty(exports, "extractRefName", {
1465
+ enumerable: true,
1466
+ get: function() {
1467
+ return extractRefName;
1468
+ }
1469
+ });
1470
+ Object.defineProperty(exports, "findCircularSchemas", {
1471
+ enumerable: true,
1472
+ get: function() {
1473
+ return findCircularSchemas;
1474
+ }
1475
+ });
1476
+ Object.defineProperty(exports, "getNestedAccessor", {
1477
+ enumerable: true,
1478
+ get: function() {
1479
+ return getNestedAccessor;
1480
+ }
1481
+ });
1482
+ Object.defineProperty(exports, "httpMethods", {
1483
+ enumerable: true,
1484
+ get: function() {
1485
+ return httpMethods;
1486
+ }
1487
+ });
1488
+ Object.defineProperty(exports, "isHttpOperationNode", {
1489
+ enumerable: true,
1490
+ get: function() {
1491
+ return isHttpOperationNode;
1492
+ }
1493
+ });
1494
+ Object.defineProperty(exports, "isStringType", {
1495
+ enumerable: true,
1496
+ get: function() {
1497
+ return isStringType;
1498
+ }
1499
+ });
1500
+ Object.defineProperty(exports, "isValidVarName", {
1501
+ enumerable: true,
1502
+ get: function() {
1503
+ return isValidVarName;
1504
+ }
1505
+ });
1506
+ Object.defineProperty(exports, "jsStringEscape", {
1507
+ enumerable: true,
1508
+ get: function() {
1509
+ return jsStringEscape;
1510
+ }
1511
+ });
1512
+ Object.defineProperty(exports, "lazyGetter", {
1513
+ enumerable: true,
1514
+ get: function() {
1515
+ return lazyGetter;
1516
+ }
1517
+ });
1518
+ Object.defineProperty(exports, "mapSchemaItems", {
1519
+ enumerable: true,
1520
+ get: function() {
1521
+ return mapSchemaItems;
1522
+ }
1523
+ });
1524
+ Object.defineProperty(exports, "mapSchemaMembers", {
1525
+ enumerable: true,
1526
+ get: function() {
1527
+ return mapSchemaMembers;
1528
+ }
1529
+ });
1530
+ Object.defineProperty(exports, "mapSchemaProperties", {
1531
+ enumerable: true,
1532
+ get: function() {
1533
+ return mapSchemaProperties;
1534
+ }
1535
+ });
1536
+ Object.defineProperty(exports, "mergeAdjacentObjectsLazy", {
1537
+ enumerable: true,
1538
+ get: function() {
1539
+ return mergeAdjacentObjectsLazy;
1540
+ }
1541
+ });
1542
+ Object.defineProperty(exports, "narrowSchema", {
1543
+ enumerable: true,
1544
+ get: function() {
1545
+ return narrowSchema;
1546
+ }
1547
+ });
1548
+ Object.defineProperty(exports, "nodeDefs", {
1549
+ enumerable: true,
1550
+ get: function() {
1551
+ return nodeDefs;
1552
+ }
1553
+ });
1554
+ Object.defineProperty(exports, "objectKey", {
1555
+ enumerable: true,
1556
+ get: function() {
1557
+ return objectKey;
1558
+ }
1559
+ });
1560
+ Object.defineProperty(exports, "resolveGroupType", {
1561
+ enumerable: true,
1562
+ get: function() {
1563
+ return resolveGroupType;
1564
+ }
1565
+ });
1566
+ Object.defineProperty(exports, "resolveParamType", {
1567
+ enumerable: true,
1568
+ get: function() {
1569
+ return resolveParamType;
1570
+ }
1571
+ });
1572
+ Object.defineProperty(exports, "resolveRefName", {
1573
+ enumerable: true,
1574
+ get: function() {
1575
+ return resolveRefName;
1576
+ }
1577
+ });
1578
+ Object.defineProperty(exports, "schemaTypes", {
1579
+ enumerable: true,
1580
+ get: function() {
1581
+ return schemaTypes;
1582
+ }
1583
+ });
1584
+ Object.defineProperty(exports, "setDiscriminatorEnum", {
1585
+ enumerable: true,
1586
+ get: function() {
1587
+ return setDiscriminatorEnum;
1588
+ }
1589
+ });
1590
+ Object.defineProperty(exports, "setEnumName", {
1591
+ enumerable: true,
1592
+ get: function() {
1593
+ return setEnumName;
1594
+ }
1595
+ });
1596
+ Object.defineProperty(exports, "simplifyUnion", {
1597
+ enumerable: true,
1598
+ get: function() {
1599
+ return simplifyUnion;
1600
+ }
1601
+ });
1602
+ Object.defineProperty(exports, "stringify", {
1603
+ enumerable: true,
1604
+ get: function() {
1605
+ return stringify;
1606
+ }
1607
+ });
1608
+ Object.defineProperty(exports, "stringifyObject", {
1609
+ enumerable: true,
1610
+ get: function() {
1611
+ return stringifyObject;
1612
+ }
1613
+ });
1614
+ Object.defineProperty(exports, "syncSchemaRef", {
1615
+ enumerable: true,
1616
+ get: function() {
1617
+ return syncSchemaRef;
1618
+ }
1619
+ });
1620
+ Object.defineProperty(exports, "toRegExpString", {
1621
+ enumerable: true,
1622
+ get: function() {
1623
+ return toRegExpString;
1624
+ }
1625
+ });
1626
+ Object.defineProperty(exports, "transform", {
1627
+ enumerable: true,
1628
+ get: function() {
1629
+ return transform;
1630
+ }
1631
+ });
1632
+ Object.defineProperty(exports, "trimQuotes", {
1633
+ enumerable: true,
1634
+ get: function() {
1635
+ return trimQuotes;
1636
+ }
1637
+ });
1638
+ Object.defineProperty(exports, "walk", {
1639
+ enumerable: true,
1640
+ get: function() {
1641
+ return walk;
1642
+ }
1643
+ });
1644
+
1645
+ //# sourceMappingURL=utils-D83JA6Xx.cjs.map