@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.
- package/README.md +13 -9
- package/dist/{types-BL7RpQAE.d.ts → ast-ClnJg9BN.d.ts} +1630 -2443
- package/dist/chunk-CNktS9qV.js +17 -0
- package/dist/extractStringsFromNodes-Bn9cOos9.d.ts +14 -0
- package/dist/factory-C5gHvtLU.js +138 -0
- package/dist/factory-C5gHvtLU.js.map +1 -0
- package/dist/factory-JN-Ylfl6.cjs +155 -0
- package/dist/factory-JN-Ylfl6.cjs.map +1 -0
- package/dist/factory.cjs +31 -0
- package/dist/factory.d.ts +62 -0
- package/dist/factory.js +3 -0
- package/dist/index.cjs +56 -1751
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +6 -47
- package/dist/index.js +7 -1697
- package/dist/index.js.map +1 -1
- package/dist/types-CB2oY8Dw.d.ts +769 -0
- package/dist/types.d.ts +4 -2
- package/dist/utils-C8bWAzhv.cjs +2696 -0
- package/dist/utils-C8bWAzhv.cjs.map +1 -0
- package/dist/utils-DN4XLVqz.js +2099 -0
- package/dist/utils-DN4XLVqz.js.map +1 -0
- package/dist/utils.cjs +12 -1
- package/dist/utils.d.ts +21 -2
- package/dist/utils.js +2 -2
- package/package.json +5 -1
- package/src/dedupe.ts +1 -1
- package/src/factory.ts +22 -764
- package/src/guards.ts +1 -53
- package/src/index.ts +20 -39
- package/src/mocks.ts +6 -1
- package/src/node.ts +128 -0
- package/src/nodes/base.ts +3 -12
- package/src/nodes/code.ts +115 -0
- package/src/nodes/content.ts +19 -0
- package/src/nodes/file.ts +54 -0
- package/src/nodes/function.ts +222 -147
- package/src/nodes/index.ts +11 -3
- package/src/nodes/input.ts +37 -0
- package/src/nodes/operation.ts +59 -1
- package/src/nodes/output.ts +23 -0
- package/src/nodes/parameter.ts +33 -0
- package/src/nodes/property.ts +36 -0
- package/src/nodes/requestBody.ts +23 -1
- package/src/nodes/response.ts +39 -1
- package/src/nodes/schema.ts +72 -0
- package/src/printer.ts +3 -3
- package/src/registry.ts +70 -0
- package/src/transformers.ts +2 -2
- package/src/types.ts +6 -4
- package/src/utils/ast.ts +103 -243
- package/src/utils/extractStringsFromNodes.ts +34 -0
- package/src/utils/index.ts +44 -0
- package/src/visitor.ts +3 -47
- package/dist/chunk-C0LytTxp.js +0 -8
- package/dist/utils-0p8ZO287.js +0 -570
- package/dist/utils-0p8ZO287.js.map +0 -1
- package/dist/utils-cdQ6Pzyi.cjs +0 -726
- package/dist/utils-cdQ6Pzyi.cjs.map +0 -1
|
@@ -0,0 +1,2099 @@
|
|
|
1
|
+
import "./chunk-CNktS9qV.js";
|
|
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
|
+
* These values serve as stable discriminators across the AST (e.g., `schema.type === schemaTypes.object`).
|
|
11
|
+
* Grouped by category: primitives (`string`, `number`, `boolean`), structural types (`object`, `array`, `union`),
|
|
12
|
+
* and format-specific types (`date`, `uuid`, `email`). Use `isScalarPrimitive()` to check for scalar types.
|
|
13
|
+
*/
|
|
14
|
+
const schemaTypes = {
|
|
15
|
+
/**
|
|
16
|
+
* Text value.
|
|
17
|
+
*/
|
|
18
|
+
string: "string",
|
|
19
|
+
/**
|
|
20
|
+
* Floating-point number (`float`, `double`).
|
|
21
|
+
*/
|
|
22
|
+
number: "number",
|
|
23
|
+
/**
|
|
24
|
+
* Whole number (`int32`). Use `bigint` for `int64`.
|
|
25
|
+
*/
|
|
26
|
+
integer: "integer",
|
|
27
|
+
/**
|
|
28
|
+
* 64-bit integer (`int64`). Only used when `integerType` is set to `'bigint'`.
|
|
29
|
+
*/
|
|
30
|
+
bigint: "bigint",
|
|
31
|
+
/**
|
|
32
|
+
* Boolean value
|
|
33
|
+
*/
|
|
34
|
+
boolean: "boolean",
|
|
35
|
+
/**
|
|
36
|
+
* Explicit null value.
|
|
37
|
+
*/
|
|
38
|
+
null: "null",
|
|
39
|
+
/**
|
|
40
|
+
* Any value (no type restriction).
|
|
41
|
+
*/
|
|
42
|
+
any: "any",
|
|
43
|
+
/**
|
|
44
|
+
* Unknown value (must be narrowed before usage).
|
|
45
|
+
*/
|
|
46
|
+
unknown: "unknown",
|
|
47
|
+
/**
|
|
48
|
+
* No return value (`void`).
|
|
49
|
+
*/
|
|
50
|
+
void: "void",
|
|
51
|
+
/**
|
|
52
|
+
* Object with named properties.
|
|
53
|
+
*/
|
|
54
|
+
object: "object",
|
|
55
|
+
/**
|
|
56
|
+
* Sequential list of items.
|
|
57
|
+
*/
|
|
58
|
+
array: "array",
|
|
59
|
+
/**
|
|
60
|
+
* Fixed-length list with position-specific items.
|
|
61
|
+
*/
|
|
62
|
+
tuple: "tuple",
|
|
63
|
+
/**
|
|
64
|
+
* "One of" multiple schema members.
|
|
65
|
+
*/
|
|
66
|
+
union: "union",
|
|
67
|
+
/**
|
|
68
|
+
* "All of" multiple schema members.
|
|
69
|
+
*/
|
|
70
|
+
intersection: "intersection",
|
|
71
|
+
/**
|
|
72
|
+
* Enum schema.
|
|
73
|
+
*/
|
|
74
|
+
enum: "enum",
|
|
75
|
+
/**
|
|
76
|
+
* Reference to another schema.
|
|
77
|
+
*/
|
|
78
|
+
ref: "ref",
|
|
79
|
+
/**
|
|
80
|
+
* Calendar date (for example `2026-03-24`).
|
|
81
|
+
*/
|
|
82
|
+
date: "date",
|
|
83
|
+
/**
|
|
84
|
+
* Date-time value (for example `2026-03-24T09:00:00Z`).
|
|
85
|
+
*/
|
|
86
|
+
datetime: "datetime",
|
|
87
|
+
/**
|
|
88
|
+
* Time-only value (for example `09:00:00`).
|
|
89
|
+
*/
|
|
90
|
+
time: "time",
|
|
91
|
+
/**
|
|
92
|
+
* UUID value.
|
|
93
|
+
*/
|
|
94
|
+
uuid: "uuid",
|
|
95
|
+
/**
|
|
96
|
+
* Email address value.
|
|
97
|
+
*/
|
|
98
|
+
email: "email",
|
|
99
|
+
/**
|
|
100
|
+
* URL value.
|
|
101
|
+
*/
|
|
102
|
+
url: "url",
|
|
103
|
+
/**
|
|
104
|
+
* IPv4 address value.
|
|
105
|
+
*/
|
|
106
|
+
ipv4: "ipv4",
|
|
107
|
+
/**
|
|
108
|
+
* IPv6 address value.
|
|
109
|
+
*/
|
|
110
|
+
ipv6: "ipv6",
|
|
111
|
+
/**
|
|
112
|
+
* Binary/blob value.
|
|
113
|
+
*/
|
|
114
|
+
blob: "blob",
|
|
115
|
+
/**
|
|
116
|
+
* Impossible value (`never`).
|
|
117
|
+
*/
|
|
118
|
+
never: "never"
|
|
119
|
+
};
|
|
120
|
+
/**
|
|
121
|
+
* Scalar primitive schema types used for union simplification and type narrowing.
|
|
122
|
+
*
|
|
123
|
+
* Use `isScalarPrimitive()` to safely check whether a type is a scalar primitive.
|
|
124
|
+
*/
|
|
125
|
+
const SCALAR_PRIMITIVE_TYPES = new Set([
|
|
126
|
+
"string",
|
|
127
|
+
"number",
|
|
128
|
+
"integer",
|
|
129
|
+
"bigint",
|
|
130
|
+
"boolean"
|
|
131
|
+
]);
|
|
132
|
+
/**
|
|
133
|
+
* Type guard that returns `true` when `type` is a scalar primitive schema type.
|
|
134
|
+
*
|
|
135
|
+
* Use this to check if a schema type can be directly assigned without wrapping (e.g., `string | number | boolean`).
|
|
136
|
+
*/
|
|
137
|
+
function isScalarPrimitive(type) {
|
|
138
|
+
return SCALAR_PRIMITIVE_TYPES.has(type);
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* HTTP method identifiers used by operation nodes.
|
|
142
|
+
*
|
|
143
|
+
* Includes all standard HTTP methods (GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS, TRACE).
|
|
144
|
+
*/
|
|
145
|
+
const httpMethods = {
|
|
146
|
+
get: "GET",
|
|
147
|
+
post: "POST",
|
|
148
|
+
put: "PUT",
|
|
149
|
+
patch: "PATCH",
|
|
150
|
+
delete: "DELETE",
|
|
151
|
+
head: "HEAD",
|
|
152
|
+
options: "OPTIONS",
|
|
153
|
+
trace: "TRACE"
|
|
154
|
+
};
|
|
155
|
+
/**
|
|
156
|
+
* One indentation level, derived from {@link INDENT_SIZE}.
|
|
157
|
+
*/
|
|
158
|
+
const INDENT = Array.from({ length: 2 }, () => " ").join("");
|
|
159
|
+
//#endregion
|
|
160
|
+
//#region src/node.ts
|
|
161
|
+
/**
|
|
162
|
+
* Builds a type guard that matches nodes of the given `kind`.
|
|
163
|
+
*/
|
|
164
|
+
function isKind(kind) {
|
|
165
|
+
return (node) => node.kind === kind;
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* Updates a schema's `optional` and `nullish` flags from a parent's `required`
|
|
169
|
+
* value and the schema's own `nullable`. Mirrors how OpenAPI parameters and
|
|
170
|
+
* object properties combine "required" and "nullable" into a single AST.
|
|
171
|
+
*
|
|
172
|
+
* - Non-required + non-nullable → `optional: true`.
|
|
173
|
+
* - Non-required + nullable → `nullish: true`.
|
|
174
|
+
* - Required → both flags cleared.
|
|
175
|
+
*/
|
|
176
|
+
function syncOptionality(schema, required) {
|
|
177
|
+
const nullable = schema.nullable ?? false;
|
|
178
|
+
return {
|
|
179
|
+
...schema,
|
|
180
|
+
optional: !required && !nullable ? true : void 0,
|
|
181
|
+
nullish: !required && nullable ? true : void 0
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* Defines a node once and derives its `create` builder, `is` guard, and traversal
|
|
186
|
+
* metadata. `create` merges `defaults`, the `build` hook (or the raw input), and the
|
|
187
|
+
* `kind`, so node construction lives in one place without scattered `as` casts.
|
|
188
|
+
*
|
|
189
|
+
* Set `rebuild: true` when the `build` hook derives fields from children. After a
|
|
190
|
+
* transform rewrites those children, the registry reruns `create` so the derived
|
|
191
|
+
* fields stay correct.
|
|
192
|
+
*
|
|
193
|
+
* @example Simple node
|
|
194
|
+
* ```ts
|
|
195
|
+
* const importDef = defineNode<ImportNode>({ kind: 'Import' })
|
|
196
|
+
* const createImport = importDef.create
|
|
197
|
+
* ```
|
|
198
|
+
*
|
|
199
|
+
* @example Node with a build hook that is rerun on transform
|
|
200
|
+
* ```ts
|
|
201
|
+
* const propertyDef = defineNode<PropertyNode, UserPropertyNode>({
|
|
202
|
+
* kind: 'Property',
|
|
203
|
+
* build: (props) => ({ ...props, required: props.required ?? false }),
|
|
204
|
+
* children: ['schema'],
|
|
205
|
+
* visitorKey: 'property',
|
|
206
|
+
* rebuild: true,
|
|
207
|
+
* })
|
|
208
|
+
* ```
|
|
209
|
+
*/
|
|
210
|
+
function defineNode(config) {
|
|
211
|
+
const { kind, defaults, build, children, visitorKey, rebuild } = config;
|
|
212
|
+
function create(input) {
|
|
213
|
+
const base = build ? build(input) : input;
|
|
214
|
+
return {
|
|
215
|
+
...defaults,
|
|
216
|
+
...base,
|
|
217
|
+
kind
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
return {
|
|
221
|
+
kind,
|
|
222
|
+
create,
|
|
223
|
+
is: isKind(kind),
|
|
224
|
+
children,
|
|
225
|
+
visitorKey,
|
|
226
|
+
rebuild
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
//#endregion
|
|
230
|
+
//#region src/nodes/schema.ts
|
|
231
|
+
/**
|
|
232
|
+
* Maps schema `type` to its underlying `primitive`.
|
|
233
|
+
* Primitive types map to themselves. Special string formats map to `'string'`.
|
|
234
|
+
* Complex types (`ref`, `enum`, `union`, `intersection`, `tuple`, `blob`) are left unset.
|
|
235
|
+
*/
|
|
236
|
+
const TYPE_TO_PRIMITIVE = {
|
|
237
|
+
string: "string",
|
|
238
|
+
number: "number",
|
|
239
|
+
integer: "integer",
|
|
240
|
+
bigint: "bigint",
|
|
241
|
+
boolean: "boolean",
|
|
242
|
+
null: "null",
|
|
243
|
+
any: "any",
|
|
244
|
+
unknown: "unknown",
|
|
245
|
+
void: "void",
|
|
246
|
+
never: "never",
|
|
247
|
+
object: "object",
|
|
248
|
+
array: "array",
|
|
249
|
+
date: "date",
|
|
250
|
+
uuid: "string",
|
|
251
|
+
email: "string",
|
|
252
|
+
url: "string",
|
|
253
|
+
datetime: "string",
|
|
254
|
+
time: "string"
|
|
255
|
+
};
|
|
256
|
+
/**
|
|
257
|
+
* Definition for the {@link SchemaNode}. Object schemas default `properties` to an
|
|
258
|
+
* empty array, and `primitive` is inferred from `type` when not explicitly provided.
|
|
259
|
+
*/
|
|
260
|
+
const schemaDef = defineNode({
|
|
261
|
+
kind: "Schema",
|
|
262
|
+
build: (props) => {
|
|
263
|
+
if (props.type === "object") return {
|
|
264
|
+
properties: [],
|
|
265
|
+
primitive: "object",
|
|
266
|
+
...props
|
|
267
|
+
};
|
|
268
|
+
return {
|
|
269
|
+
primitive: TYPE_TO_PRIMITIVE[props.type],
|
|
270
|
+
...props
|
|
271
|
+
};
|
|
272
|
+
},
|
|
273
|
+
children: [
|
|
274
|
+
"properties",
|
|
275
|
+
"items",
|
|
276
|
+
"members",
|
|
277
|
+
"additionalProperties"
|
|
278
|
+
],
|
|
279
|
+
visitorKey: "schema"
|
|
280
|
+
});
|
|
281
|
+
function createSchema(props) {
|
|
282
|
+
return schemaDef.create(props);
|
|
283
|
+
}
|
|
284
|
+
//#endregion
|
|
285
|
+
//#region ../../internals/utils/src/casing.ts
|
|
286
|
+
/**
|
|
287
|
+
* Shared implementation for camelCase and PascalCase conversion.
|
|
288
|
+
* Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)
|
|
289
|
+
* and capitalizes each word according to `pascal`.
|
|
290
|
+
*
|
|
291
|
+
* When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.
|
|
292
|
+
*/
|
|
293
|
+
function toCamelOrPascal(text, pascal) {
|
|
294
|
+
return text.trim().replace(/([a-z\d])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").replace(/(\d)([a-z])/g, "$1 $2").split(/[\s\-_./\\:]+/).filter(Boolean).map((word, i) => {
|
|
295
|
+
if (word.length > 1 && word === word.toUpperCase()) return word;
|
|
296
|
+
return (i === 0 && !pascal ? word.charAt(0).toLowerCase() : word.charAt(0).toUpperCase()) + word.slice(1);
|
|
297
|
+
}).join("").replace(/[^a-zA-Z0-9]/g, "");
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* Converts `text` to camelCase.
|
|
301
|
+
*
|
|
302
|
+
* @example Word boundaries
|
|
303
|
+
* `camelCase('hello-world') // 'helloWorld'`
|
|
304
|
+
*
|
|
305
|
+
* @example With a prefix
|
|
306
|
+
* `camelCase('tag', { prefix: 'create' }) // 'createTag'`
|
|
307
|
+
*/
|
|
308
|
+
function camelCase(text, { prefix = "", suffix = "" } = {}) {
|
|
309
|
+
return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false);
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* Converts `text` to PascalCase.
|
|
313
|
+
*
|
|
314
|
+
* @example Word boundaries
|
|
315
|
+
* `pascalCase('hello-world') // 'HelloWorld'`
|
|
316
|
+
*
|
|
317
|
+
* @example With a suffix
|
|
318
|
+
* `pascalCase('tag', { suffix: 'schema' }) // 'TagSchema'`
|
|
319
|
+
*/
|
|
320
|
+
function pascalCase(text, { prefix = "", suffix = "" } = {}) {
|
|
321
|
+
return toCamelOrPascal(`${prefix} ${text} ${suffix}`, true);
|
|
322
|
+
}
|
|
323
|
+
//#endregion
|
|
324
|
+
//#region ../../internals/utils/src/promise.ts
|
|
325
|
+
/**
|
|
326
|
+
* Wraps `factory` with a keyed cache backed by the provided store.
|
|
327
|
+
*
|
|
328
|
+
* Pass a `WeakMap` for object keys (results are GC-eligible when the key is
|
|
329
|
+
* collected) or a `Map` for primitive keys. For multi-argument functions,
|
|
330
|
+
* nest two `memoize` calls — the outer keyed by the first argument, the
|
|
331
|
+
* inner (created once per outer miss) keyed by the second.
|
|
332
|
+
*
|
|
333
|
+
* Because the cache is owned by the caller, it can be shared, inspected, or
|
|
334
|
+
* cleared independently of the memoized function.
|
|
335
|
+
*
|
|
336
|
+
* @example Single WeakMap key
|
|
337
|
+
* ```ts
|
|
338
|
+
* const cache = new WeakMap<SchemaNode, Set<string>>()
|
|
339
|
+
* const getRefs = memoize(cache, (node) => collectRefs(node))
|
|
340
|
+
* ```
|
|
341
|
+
*
|
|
342
|
+
* @example Single Map key (primitive)
|
|
343
|
+
* ```ts
|
|
344
|
+
* const cache = new Map<string, Resolver>()
|
|
345
|
+
* const getResolver = memoize(cache, (name) => buildResolver(name))
|
|
346
|
+
* ```
|
|
347
|
+
*
|
|
348
|
+
* @example Two-level (object + primitive)
|
|
349
|
+
* ```ts
|
|
350
|
+
* const outer = new WeakMap<Params[], Map<string, Params[]>>()
|
|
351
|
+
* const fn = memoize(outer, (params) => memoize(new Map(), (key) => transform(params, key)))
|
|
352
|
+
* fn(params)('camelcase')
|
|
353
|
+
* ```
|
|
354
|
+
*/
|
|
355
|
+
function memoize(store, factory) {
|
|
356
|
+
return (key) => {
|
|
357
|
+
if (store.has(key)) return store.get(key);
|
|
358
|
+
const value = factory(key);
|
|
359
|
+
store.set(key, value);
|
|
360
|
+
return value;
|
|
361
|
+
};
|
|
362
|
+
}
|
|
363
|
+
//#endregion
|
|
364
|
+
//#region ../../internals/utils/src/reserved.ts
|
|
365
|
+
/**
|
|
366
|
+
* JavaScript and Java reserved words.
|
|
367
|
+
* @link https://github.com/jonschlinkert/reserved/blob/master/index.js
|
|
368
|
+
*/
|
|
369
|
+
const reservedWords = new Set([
|
|
370
|
+
"abstract",
|
|
371
|
+
"arguments",
|
|
372
|
+
"boolean",
|
|
373
|
+
"break",
|
|
374
|
+
"byte",
|
|
375
|
+
"case",
|
|
376
|
+
"catch",
|
|
377
|
+
"char",
|
|
378
|
+
"class",
|
|
379
|
+
"const",
|
|
380
|
+
"continue",
|
|
381
|
+
"debugger",
|
|
382
|
+
"default",
|
|
383
|
+
"delete",
|
|
384
|
+
"do",
|
|
385
|
+
"double",
|
|
386
|
+
"else",
|
|
387
|
+
"enum",
|
|
388
|
+
"eval",
|
|
389
|
+
"export",
|
|
390
|
+
"extends",
|
|
391
|
+
"false",
|
|
392
|
+
"final",
|
|
393
|
+
"finally",
|
|
394
|
+
"float",
|
|
395
|
+
"for",
|
|
396
|
+
"function",
|
|
397
|
+
"goto",
|
|
398
|
+
"if",
|
|
399
|
+
"implements",
|
|
400
|
+
"import",
|
|
401
|
+
"in",
|
|
402
|
+
"instanceof",
|
|
403
|
+
"int",
|
|
404
|
+
"interface",
|
|
405
|
+
"let",
|
|
406
|
+
"long",
|
|
407
|
+
"native",
|
|
408
|
+
"new",
|
|
409
|
+
"null",
|
|
410
|
+
"package",
|
|
411
|
+
"private",
|
|
412
|
+
"protected",
|
|
413
|
+
"public",
|
|
414
|
+
"return",
|
|
415
|
+
"short",
|
|
416
|
+
"static",
|
|
417
|
+
"super",
|
|
418
|
+
"switch",
|
|
419
|
+
"synchronized",
|
|
420
|
+
"this",
|
|
421
|
+
"throw",
|
|
422
|
+
"throws",
|
|
423
|
+
"transient",
|
|
424
|
+
"true",
|
|
425
|
+
"try",
|
|
426
|
+
"typeof",
|
|
427
|
+
"var",
|
|
428
|
+
"void",
|
|
429
|
+
"volatile",
|
|
430
|
+
"while",
|
|
431
|
+
"with",
|
|
432
|
+
"yield",
|
|
433
|
+
"Array",
|
|
434
|
+
"Date",
|
|
435
|
+
"hasOwnProperty",
|
|
436
|
+
"Infinity",
|
|
437
|
+
"isFinite",
|
|
438
|
+
"isNaN",
|
|
439
|
+
"isPrototypeOf",
|
|
440
|
+
"length",
|
|
441
|
+
"Math",
|
|
442
|
+
"name",
|
|
443
|
+
"NaN",
|
|
444
|
+
"Number",
|
|
445
|
+
"Object",
|
|
446
|
+
"prototype",
|
|
447
|
+
"String",
|
|
448
|
+
"toString",
|
|
449
|
+
"undefined",
|
|
450
|
+
"valueOf"
|
|
451
|
+
]);
|
|
452
|
+
/**
|
|
453
|
+
* Returns `true` when `name` is a syntactically valid JavaScript variable name.
|
|
454
|
+
*
|
|
455
|
+
* @example
|
|
456
|
+
* ```ts
|
|
457
|
+
* isValidVarName('status') // true
|
|
458
|
+
* isValidVarName('class') // false (reserved word)
|
|
459
|
+
* isValidVarName('42foo') // false (starts with digit)
|
|
460
|
+
* ```
|
|
461
|
+
*/
|
|
462
|
+
function isValidVarName(name) {
|
|
463
|
+
if (!name || reservedWords.has(name)) return false;
|
|
464
|
+
return isIdentifier(name);
|
|
465
|
+
}
|
|
466
|
+
/**
|
|
467
|
+
* Returns `true` when `name` is syntactically a valid identifier, ignoring reserved words.
|
|
468
|
+
*
|
|
469
|
+
* Reserved words and globals (`class`, `name`, `Date`, …) are valid as bare object-literal keys
|
|
470
|
+
* even though they are not valid variable names, so use this (not {@link isValidVarName}) when
|
|
471
|
+
* deciding whether an object key needs quoting.
|
|
472
|
+
*
|
|
473
|
+
* @example
|
|
474
|
+
* ```ts
|
|
475
|
+
* isIdentifier('name') // true
|
|
476
|
+
* isIdentifier('x-total')// false
|
|
477
|
+
* ```
|
|
478
|
+
*/
|
|
479
|
+
function isIdentifier(name) {
|
|
480
|
+
return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name);
|
|
481
|
+
}
|
|
482
|
+
//#endregion
|
|
483
|
+
//#region ../../internals/utils/src/string.ts
|
|
484
|
+
/**
|
|
485
|
+
* Wraps a value in single quotes for emitting a single-quoted JavaScript string literal, escaping
|
|
486
|
+
* any backslash or single quote in the content.
|
|
487
|
+
*
|
|
488
|
+
* @example
|
|
489
|
+
* ```ts
|
|
490
|
+
* singleQuote('foo') // "'foo'"
|
|
491
|
+
* singleQuote("o'clock") // "'o\\'clock'"
|
|
492
|
+
* ```
|
|
493
|
+
*/
|
|
494
|
+
function singleQuote(value) {
|
|
495
|
+
if (value === void 0 || value === null) return "''";
|
|
496
|
+
return `'${String(value).replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
|
|
497
|
+
}
|
|
498
|
+
//#endregion
|
|
499
|
+
//#region src/utils/extractStringsFromNodes.ts
|
|
500
|
+
/**
|
|
501
|
+
* Extracts all string content from a `CodeNode` tree recursively.
|
|
502
|
+
*
|
|
503
|
+
* Collects text node values, identifier references in string fields (`params`, `generics`, `returnType`, `type`),
|
|
504
|
+
* and nested node content. Used to build the full source string for import filtering.
|
|
505
|
+
*/
|
|
506
|
+
function extractStringsFromNodes(nodes) {
|
|
507
|
+
if (!nodes?.length) return "";
|
|
508
|
+
return nodes.map((node) => {
|
|
509
|
+
if (typeof node === "string") return node;
|
|
510
|
+
if (node.kind === "Text") return node.value;
|
|
511
|
+
if (node.kind === "Break") return "";
|
|
512
|
+
if (node.kind === "Jsx") return node.value;
|
|
513
|
+
const parts = [];
|
|
514
|
+
if ("params" in node && node.params) parts.push(node.params);
|
|
515
|
+
if ("generics" in node && node.generics) parts.push(Array.isArray(node.generics) ? node.generics.join(", ") : node.generics);
|
|
516
|
+
if ("returnType" in node && node.returnType) parts.push(node.returnType);
|
|
517
|
+
if ("type" in node && typeof node.type === "string") parts.push(node.type);
|
|
518
|
+
const nested = extractStringsFromNodes(node.nodes);
|
|
519
|
+
if (nested) parts.push(nested);
|
|
520
|
+
return parts.join("\n");
|
|
521
|
+
}).filter(Boolean).join("\n");
|
|
522
|
+
}
|
|
523
|
+
//#endregion
|
|
524
|
+
//#region src/guards.ts
|
|
525
|
+
/**
|
|
526
|
+
* Narrows a `SchemaNode` to the variant that matches `type`.
|
|
527
|
+
*
|
|
528
|
+
* @example
|
|
529
|
+
* ```ts
|
|
530
|
+
* const schema = createSchema({ type: 'string' })
|
|
531
|
+
* const stringNode = narrowSchema(schema, 'string') // StringSchemaNode | null
|
|
532
|
+
* ```
|
|
533
|
+
*/
|
|
534
|
+
function narrowSchema(node, type) {
|
|
535
|
+
return node?.type === type ? node : null;
|
|
536
|
+
}
|
|
537
|
+
/**
|
|
538
|
+
* Narrows an `OperationNode` to an `HttpOperationNode`, guaranteeing `method` and `path`.
|
|
539
|
+
*
|
|
540
|
+
* @example
|
|
541
|
+
* ```ts
|
|
542
|
+
* if (isHttpOperationNode(node)) {
|
|
543
|
+
* console.log(node.method, node.path)
|
|
544
|
+
* }
|
|
545
|
+
* ```
|
|
546
|
+
*/
|
|
547
|
+
function isHttpOperationNode(node) {
|
|
548
|
+
return node.protocol === "http" || node.method !== void 0 && node.path !== void 0;
|
|
549
|
+
}
|
|
550
|
+
//#endregion
|
|
551
|
+
//#region src/nodes/function.ts
|
|
552
|
+
/**
|
|
553
|
+
* Definition for the {@link TypeLiteralNode}.
|
|
554
|
+
*/
|
|
555
|
+
const typeLiteralDef = defineNode({ kind: "TypeLiteral" });
|
|
556
|
+
/**
|
|
557
|
+
* Creates a {@link TypeLiteralNode} representing an inline anonymous object type.
|
|
558
|
+
*
|
|
559
|
+
* @example
|
|
560
|
+
* ```ts
|
|
561
|
+
* createTypeLiteral({ members: [{ name: 'petId', type: 'string', optional: false }] })
|
|
562
|
+
* // { petId: string }
|
|
563
|
+
* ```
|
|
564
|
+
*/
|
|
565
|
+
const createTypeLiteral = typeLiteralDef.create;
|
|
566
|
+
/**
|
|
567
|
+
* Definition for the {@link IndexedAccessTypeNode}.
|
|
568
|
+
*/
|
|
569
|
+
const indexedAccessTypeDef = defineNode({ kind: "IndexedAccessType" });
|
|
570
|
+
/**
|
|
571
|
+
* Creates an {@link IndexedAccessTypeNode} representing a single field accessed from a named type.
|
|
572
|
+
*
|
|
573
|
+
* @example
|
|
574
|
+
* ```ts
|
|
575
|
+
* createIndexedAccessType({ objectType: 'DeletePetPathParams', indexType: 'petId' })
|
|
576
|
+
* // DeletePetPathParams['petId']
|
|
577
|
+
* ```
|
|
578
|
+
*/
|
|
579
|
+
const createIndexedAccessType = indexedAccessTypeDef.create;
|
|
580
|
+
/**
|
|
581
|
+
* Definition for the {@link ObjectBindingPatternNode}.
|
|
582
|
+
*/
|
|
583
|
+
const objectBindingPatternDef = defineNode({ kind: "ObjectBindingPattern" });
|
|
584
|
+
/**
|
|
585
|
+
* Creates an {@link ObjectBindingPatternNode} for a destructured parameter binding.
|
|
586
|
+
*
|
|
587
|
+
* @example
|
|
588
|
+
* ```ts
|
|
589
|
+
* createObjectBindingPattern({ elements: [{ name: 'id' }, { name: 'name' }] })
|
|
590
|
+
* // { id, name }
|
|
591
|
+
* ```
|
|
592
|
+
*/
|
|
593
|
+
const createObjectBindingPattern = objectBindingPatternDef.create;
|
|
594
|
+
/**
|
|
595
|
+
* Definition for the {@link FunctionParameterNode}. `optional` defaults to `false`.
|
|
596
|
+
* Passing `properties` builds a destructured group: an {@link ObjectBindingPatternNode} name
|
|
597
|
+
* paired with a {@link TypeLiteralNode} type.
|
|
598
|
+
*/
|
|
599
|
+
const functionParameterDef = defineNode({
|
|
600
|
+
kind: "FunctionParameter",
|
|
601
|
+
build: (input) => {
|
|
602
|
+
if ("properties" in input) return {
|
|
603
|
+
name: createObjectBindingPattern({ elements: input.properties.map((p) => ({ name: p.name })) }),
|
|
604
|
+
type: createTypeLiteral({ members: input.properties.map((p) => ({
|
|
605
|
+
name: p.name,
|
|
606
|
+
type: p.type,
|
|
607
|
+
optional: p.optional ?? false
|
|
608
|
+
})) }),
|
|
609
|
+
optional: input.optional ?? false,
|
|
610
|
+
...input.default !== void 0 ? { default: input.default } : {}
|
|
611
|
+
};
|
|
612
|
+
return {
|
|
613
|
+
optional: false,
|
|
614
|
+
...input
|
|
615
|
+
};
|
|
616
|
+
}
|
|
617
|
+
});
|
|
618
|
+
/**
|
|
619
|
+
* Creates a `FunctionParameterNode`. `optional` defaults to `false`.
|
|
620
|
+
*
|
|
621
|
+
* @example Optional param
|
|
622
|
+
* ```ts
|
|
623
|
+
* createFunctionParameter({ name: 'params', type: 'QueryParams', optional: true })
|
|
624
|
+
* // → params?: QueryParams
|
|
625
|
+
* ```
|
|
626
|
+
*
|
|
627
|
+
* @example Destructured group
|
|
628
|
+
* ```ts
|
|
629
|
+
* createFunctionParameter({ properties: [{ name: 'id', type: 'string' }, { name: 'name', type: 'string', optional: true }], default: '{}' })
|
|
630
|
+
* // → { id, name }: { id: string; name?: string } = {}
|
|
631
|
+
* ```
|
|
632
|
+
*/
|
|
633
|
+
const createFunctionParameter = functionParameterDef.create;
|
|
634
|
+
/**
|
|
635
|
+
* Definition for the {@link FunctionParametersNode}.
|
|
636
|
+
*/
|
|
637
|
+
const functionParametersDef = defineNode({
|
|
638
|
+
kind: "FunctionParameters",
|
|
639
|
+
defaults: { params: [] }
|
|
640
|
+
});
|
|
641
|
+
/**
|
|
642
|
+
* Creates a `FunctionParametersNode` from an ordered list of parameters.
|
|
643
|
+
*
|
|
644
|
+
* @example
|
|
645
|
+
* ```ts
|
|
646
|
+
* const empty = createFunctionParameters()
|
|
647
|
+
* // { kind: 'FunctionParameters', params: [] }
|
|
648
|
+
* ```
|
|
649
|
+
*/
|
|
650
|
+
function createFunctionParameters(props = {}) {
|
|
651
|
+
return functionParametersDef.create(props);
|
|
652
|
+
}
|
|
653
|
+
//#endregion
|
|
654
|
+
//#region src/nodes/property.ts
|
|
655
|
+
/**
|
|
656
|
+
* Definition for the {@link PropertyNode}. `required` defaults to `false` and the
|
|
657
|
+
* schema's `optional`/`nullish` flags are kept in sync with it.
|
|
658
|
+
*/
|
|
659
|
+
const propertyDef = defineNode({
|
|
660
|
+
kind: "Property",
|
|
661
|
+
build: (props) => {
|
|
662
|
+
const required = props.required ?? false;
|
|
663
|
+
return {
|
|
664
|
+
...props,
|
|
665
|
+
required,
|
|
666
|
+
schema: syncOptionality(props.schema, required)
|
|
667
|
+
};
|
|
668
|
+
},
|
|
669
|
+
children: ["schema"],
|
|
670
|
+
visitorKey: "property",
|
|
671
|
+
rebuild: true
|
|
672
|
+
});
|
|
673
|
+
/**
|
|
674
|
+
* Creates a `PropertyNode`.
|
|
675
|
+
*
|
|
676
|
+
* @example
|
|
677
|
+
* ```ts
|
|
678
|
+
* const property = createProperty({
|
|
679
|
+
* name: 'status',
|
|
680
|
+
* required: true,
|
|
681
|
+
* schema: createSchema({ type: 'string', nullable: true }),
|
|
682
|
+
* })
|
|
683
|
+
* // required=true, no optional/nullish
|
|
684
|
+
* ```
|
|
685
|
+
*/
|
|
686
|
+
const createProperty = propertyDef.create;
|
|
687
|
+
//#endregion
|
|
688
|
+
//#region src/nodes/code.ts
|
|
689
|
+
/**
|
|
690
|
+
* Definition for the {@link ConstNode}.
|
|
691
|
+
*/
|
|
692
|
+
const constDef = defineNode({ kind: "Const" });
|
|
693
|
+
/**
|
|
694
|
+
* Creates a `ConstNode` representing a TypeScript `const` declaration.
|
|
695
|
+
*
|
|
696
|
+
* @example Exported constant with type and `as const`
|
|
697
|
+
* ```ts
|
|
698
|
+
* createConst({ name: 'pets', export: true, type: 'Pet[]', asConst: true })
|
|
699
|
+
* // export const pets: Pet[] = ... as const
|
|
700
|
+
* ```
|
|
701
|
+
*/
|
|
702
|
+
const createConst = constDef.create;
|
|
703
|
+
/**
|
|
704
|
+
* Definition for the {@link TypeNode}.
|
|
705
|
+
*/
|
|
706
|
+
const typeDef = defineNode({ kind: "Type" });
|
|
707
|
+
/**
|
|
708
|
+
* Creates a `TypeNode` representing a TypeScript `type` alias declaration.
|
|
709
|
+
*
|
|
710
|
+
* @example
|
|
711
|
+
* ```ts
|
|
712
|
+
* createType({ name: 'Pet', export: true })
|
|
713
|
+
* // export type Pet = ...
|
|
714
|
+
* ```
|
|
715
|
+
*/
|
|
716
|
+
const createType = typeDef.create;
|
|
717
|
+
/**
|
|
718
|
+
* Definition for the {@link FunctionNode}.
|
|
719
|
+
*/
|
|
720
|
+
const functionDef = defineNode({ kind: "Function" });
|
|
721
|
+
/**
|
|
722
|
+
* Creates a `FunctionNode` representing a TypeScript `function` declaration.
|
|
723
|
+
*
|
|
724
|
+
* @example
|
|
725
|
+
* ```ts
|
|
726
|
+
* createFunction({ name: 'fetchPet', export: true, async: true, returnType: 'Pet' })
|
|
727
|
+
* // export async function fetchPet(): Promise<Pet> { ... }
|
|
728
|
+
* ```
|
|
729
|
+
*/
|
|
730
|
+
const createFunction = functionDef.create;
|
|
731
|
+
/**
|
|
732
|
+
* Definition for the {@link ArrowFunctionNode}.
|
|
733
|
+
*/
|
|
734
|
+
const arrowFunctionDef = defineNode({ kind: "ArrowFunction" });
|
|
735
|
+
/**
|
|
736
|
+
* Creates an `ArrowFunctionNode` representing a TypeScript arrow function.
|
|
737
|
+
*
|
|
738
|
+
* @example
|
|
739
|
+
* ```ts
|
|
740
|
+
* createArrowFunction({ name: 'double', export: true, params: 'n: number', singleLine: true })
|
|
741
|
+
* // export const double = (n: number) => ...
|
|
742
|
+
* ```
|
|
743
|
+
*/
|
|
744
|
+
const createArrowFunction = arrowFunctionDef.create;
|
|
745
|
+
/**
|
|
746
|
+
* Definition for the {@link TextNode}.
|
|
747
|
+
*/
|
|
748
|
+
const textDef = defineNode({
|
|
749
|
+
kind: "Text",
|
|
750
|
+
build: (value) => ({ value })
|
|
751
|
+
});
|
|
752
|
+
/**
|
|
753
|
+
* Creates a {@link TextNode} representing a raw string fragment in the source output.
|
|
754
|
+
*
|
|
755
|
+
* @example
|
|
756
|
+
* ```ts
|
|
757
|
+
* createText('return fetch(id)')
|
|
758
|
+
* // { kind: 'Text', value: 'return fetch(id)' }
|
|
759
|
+
* ```
|
|
760
|
+
*/
|
|
761
|
+
const createText = textDef.create;
|
|
762
|
+
/**
|
|
763
|
+
* Definition for the {@link BreakNode}.
|
|
764
|
+
*/
|
|
765
|
+
const breakDef = defineNode({
|
|
766
|
+
kind: "Break",
|
|
767
|
+
build: () => ({})
|
|
768
|
+
});
|
|
769
|
+
/**
|
|
770
|
+
* Creates a {@link BreakNode} representing a line break in the source output.
|
|
771
|
+
*
|
|
772
|
+
* @example
|
|
773
|
+
* ```ts
|
|
774
|
+
* createBreak()
|
|
775
|
+
* // { kind: 'Break' }
|
|
776
|
+
* ```
|
|
777
|
+
*/
|
|
778
|
+
function createBreak() {
|
|
779
|
+
return breakDef.create();
|
|
780
|
+
}
|
|
781
|
+
/**
|
|
782
|
+
* Definition for the {@link JsxNode}.
|
|
783
|
+
*/
|
|
784
|
+
const jsxDef = defineNode({
|
|
785
|
+
kind: "Jsx",
|
|
786
|
+
build: (value) => ({ value })
|
|
787
|
+
});
|
|
788
|
+
/**
|
|
789
|
+
* Creates a {@link JsxNode} representing a raw JSX fragment in the source output.
|
|
790
|
+
*
|
|
791
|
+
* @example
|
|
792
|
+
* ```ts
|
|
793
|
+
* createJsx('<>\n <a href={href}>Open</a>\n</>')
|
|
794
|
+
* // { kind: 'Jsx', value: '<>\n <a href={href}>Open</a>\n</>' }
|
|
795
|
+
* ```
|
|
796
|
+
*/
|
|
797
|
+
const createJsx = jsxDef.create;
|
|
798
|
+
//#endregion
|
|
799
|
+
//#region src/nodes/content.ts
|
|
800
|
+
/**
|
|
801
|
+
* Definition for the {@link ContentNode}.
|
|
802
|
+
*/
|
|
803
|
+
const contentDef = defineNode({
|
|
804
|
+
kind: "Content",
|
|
805
|
+
children: ["schema"]
|
|
806
|
+
});
|
|
807
|
+
/**
|
|
808
|
+
* Creates a `ContentNode` for a single request-body or response content type.
|
|
809
|
+
*/
|
|
810
|
+
const createContent = contentDef.create;
|
|
811
|
+
//#endregion
|
|
812
|
+
//#region src/nodes/file.ts
|
|
813
|
+
/**
|
|
814
|
+
* Definition for the {@link ImportNode}.
|
|
815
|
+
*/
|
|
816
|
+
const importDef = defineNode({ kind: "Import" });
|
|
817
|
+
/**
|
|
818
|
+
* Creates an `ImportNode` representing a language-agnostic import/dependency declaration.
|
|
819
|
+
*
|
|
820
|
+
* @example Named import
|
|
821
|
+
* ```ts
|
|
822
|
+
* createImport({ name: ['useState'], path: 'react' })
|
|
823
|
+
* // import { useState } from 'react'
|
|
824
|
+
* ```
|
|
825
|
+
*/
|
|
826
|
+
const createImport = importDef.create;
|
|
827
|
+
/**
|
|
828
|
+
* Definition for the {@link ExportNode}.
|
|
829
|
+
*/
|
|
830
|
+
const exportDef = defineNode({ kind: "Export" });
|
|
831
|
+
/**
|
|
832
|
+
* Creates an `ExportNode` representing a language-agnostic export/public API declaration.
|
|
833
|
+
*
|
|
834
|
+
* @example Named export
|
|
835
|
+
* ```ts
|
|
836
|
+
* createExport({ name: ['Pet'], path: './Pet' })
|
|
837
|
+
* // export { Pet } from './Pet'
|
|
838
|
+
* ```
|
|
839
|
+
*/
|
|
840
|
+
const createExport = exportDef.create;
|
|
841
|
+
/**
|
|
842
|
+
* Definition for the {@link SourceNode}.
|
|
843
|
+
*/
|
|
844
|
+
const sourceDef = defineNode({ kind: "Source" });
|
|
845
|
+
/**
|
|
846
|
+
* Creates a `SourceNode` representing a fragment of source code within a file.
|
|
847
|
+
*
|
|
848
|
+
* @example
|
|
849
|
+
* ```ts
|
|
850
|
+
* createSource({ name: 'Pet', nodes: [createText('export type Pet = { id: number }')], isExportable: true })
|
|
851
|
+
* ```
|
|
852
|
+
*/
|
|
853
|
+
const createSource = sourceDef.create;
|
|
854
|
+
/**
|
|
855
|
+
* Definition for the {@link FileNode}. The fully resolved builder lives in
|
|
856
|
+
* `createFile`, so this definition only supplies the guard.
|
|
857
|
+
*/
|
|
858
|
+
const fileDef = defineNode({ kind: "File" });
|
|
859
|
+
//#endregion
|
|
860
|
+
//#region src/nodes/input.ts
|
|
861
|
+
/**
|
|
862
|
+
* Definition for the {@link InputNode}.
|
|
863
|
+
*/
|
|
864
|
+
const inputDef = defineNode({
|
|
865
|
+
kind: "Input",
|
|
866
|
+
defaults: {
|
|
867
|
+
schemas: [],
|
|
868
|
+
operations: [],
|
|
869
|
+
meta: {
|
|
870
|
+
circularNames: [],
|
|
871
|
+
enumNames: []
|
|
872
|
+
}
|
|
873
|
+
},
|
|
874
|
+
children: ["schemas", "operations"],
|
|
875
|
+
visitorKey: "input"
|
|
876
|
+
});
|
|
877
|
+
/**
|
|
878
|
+
* Creates an `InputNode`. Pass `stream: true` for the streaming variant whose `schemas` and
|
|
879
|
+
* `operations` are `AsyncIterable` sources and whose `meta` is optional. Otherwise it builds the
|
|
880
|
+
* eager variant with array `schemas`/`operations` and the defaulted `meta`.
|
|
881
|
+
*
|
|
882
|
+
* @example Eager
|
|
883
|
+
* ```ts
|
|
884
|
+
* const input = createInput()
|
|
885
|
+
* // { kind: 'Input', schemas: [], operations: [] }
|
|
886
|
+
* ```
|
|
887
|
+
*
|
|
888
|
+
* @example Streaming
|
|
889
|
+
* ```ts
|
|
890
|
+
* const node = createInput({ stream: true, schemas: schemasIterable, operations: operationsIterable, meta: { title: 'My API' } })
|
|
891
|
+
* ```
|
|
892
|
+
*/
|
|
893
|
+
function createInput(options = {}) {
|
|
894
|
+
const { stream, ...overrides } = options;
|
|
895
|
+
if (stream) return {
|
|
896
|
+
kind: "Input",
|
|
897
|
+
...overrides
|
|
898
|
+
};
|
|
899
|
+
return inputDef.create(overrides);
|
|
900
|
+
}
|
|
901
|
+
//#endregion
|
|
902
|
+
//#region src/nodes/requestBody.ts
|
|
903
|
+
/**
|
|
904
|
+
* Definition for the {@link RequestBodyNode}, normalizing each content entry into a `ContentNode`.
|
|
905
|
+
*/
|
|
906
|
+
const requestBodyDef = defineNode({
|
|
907
|
+
kind: "RequestBody",
|
|
908
|
+
build: (props) => ({
|
|
909
|
+
...props,
|
|
910
|
+
content: props.content?.map(createContent)
|
|
911
|
+
}),
|
|
912
|
+
children: ["content"]
|
|
913
|
+
});
|
|
914
|
+
/**
|
|
915
|
+
* Creates a `RequestBodyNode`, normalizing each content entry into a `ContentNode`.
|
|
916
|
+
*/
|
|
917
|
+
const createRequestBody = requestBodyDef.create;
|
|
918
|
+
//#endregion
|
|
919
|
+
//#region src/nodes/operation.ts
|
|
920
|
+
/**
|
|
921
|
+
* Definition for the {@link OperationNode}. HTTP operations (those carrying both
|
|
922
|
+
* `method` and `path`) are tagged with `protocol: 'http'`, and the request body is
|
|
923
|
+
* normalized into a `RequestBodyNode`.
|
|
924
|
+
*/
|
|
925
|
+
const operationDef = defineNode({
|
|
926
|
+
kind: "Operation",
|
|
927
|
+
build: (props) => {
|
|
928
|
+
const { requestBody, ...rest } = props;
|
|
929
|
+
const isHttp = rest.method !== void 0 && rest.path !== void 0;
|
|
930
|
+
return {
|
|
931
|
+
tags: [],
|
|
932
|
+
parameters: [],
|
|
933
|
+
responses: [],
|
|
934
|
+
...rest,
|
|
935
|
+
...isHttp ? { protocol: "http" } : {},
|
|
936
|
+
requestBody: requestBody ? createRequestBody(requestBody) : void 0
|
|
937
|
+
};
|
|
938
|
+
},
|
|
939
|
+
children: [
|
|
940
|
+
"parameters",
|
|
941
|
+
"requestBody",
|
|
942
|
+
"responses"
|
|
943
|
+
],
|
|
944
|
+
visitorKey: "operation"
|
|
945
|
+
});
|
|
946
|
+
function createOperation(props) {
|
|
947
|
+
return operationDef.create(props);
|
|
948
|
+
}
|
|
949
|
+
//#endregion
|
|
950
|
+
//#region src/nodes/output.ts
|
|
951
|
+
/**
|
|
952
|
+
* Definition for the {@link OutputNode}.
|
|
953
|
+
*/
|
|
954
|
+
const outputDef = defineNode({
|
|
955
|
+
kind: "Output",
|
|
956
|
+
defaults: { files: [] },
|
|
957
|
+
visitorKey: "output"
|
|
958
|
+
});
|
|
959
|
+
/**
|
|
960
|
+
* Creates an `OutputNode` with a stable default for `files`.
|
|
961
|
+
*
|
|
962
|
+
* @example
|
|
963
|
+
* ```ts
|
|
964
|
+
* const output = createOutput()
|
|
965
|
+
* // { kind: 'Output', files: [] }
|
|
966
|
+
* ```
|
|
967
|
+
*/
|
|
968
|
+
function createOutput(overrides = {}) {
|
|
969
|
+
return outputDef.create(overrides);
|
|
970
|
+
}
|
|
971
|
+
//#endregion
|
|
972
|
+
//#region src/nodes/parameter.ts
|
|
973
|
+
/**
|
|
974
|
+
* Definition for the {@link ParameterNode}. `required` defaults to `false` and the
|
|
975
|
+
* schema's `optional`/`nullish` flags are kept in sync with it.
|
|
976
|
+
*/
|
|
977
|
+
const parameterDef = defineNode({
|
|
978
|
+
kind: "Parameter",
|
|
979
|
+
build: (props) => {
|
|
980
|
+
const required = props.required ?? false;
|
|
981
|
+
return {
|
|
982
|
+
...props,
|
|
983
|
+
required,
|
|
984
|
+
schema: syncOptionality(props.schema, required)
|
|
985
|
+
};
|
|
986
|
+
},
|
|
987
|
+
children: ["schema"],
|
|
988
|
+
visitorKey: "parameter",
|
|
989
|
+
rebuild: true
|
|
990
|
+
});
|
|
991
|
+
/**
|
|
992
|
+
* Creates a `ParameterNode`.
|
|
993
|
+
*
|
|
994
|
+
* @example
|
|
995
|
+
* ```ts
|
|
996
|
+
* const param = createParameter({
|
|
997
|
+
* name: 'petId',
|
|
998
|
+
* in: 'path',
|
|
999
|
+
* required: true,
|
|
1000
|
+
* schema: createSchema({ type: 'string' }),
|
|
1001
|
+
* })
|
|
1002
|
+
* ```
|
|
1003
|
+
*/
|
|
1004
|
+
const createParameter = parameterDef.create;
|
|
1005
|
+
//#endregion
|
|
1006
|
+
//#region src/nodes/response.ts
|
|
1007
|
+
/**
|
|
1008
|
+
* Definition for the {@link ResponseNode}. A single legacy `schema` (with optional
|
|
1009
|
+
* `mediaType`/`keysToOmit`) is normalized into one `content` entry.
|
|
1010
|
+
*/
|
|
1011
|
+
const responseDef = defineNode({
|
|
1012
|
+
kind: "Response",
|
|
1013
|
+
build: (props) => {
|
|
1014
|
+
const { schema, mediaType, keysToOmit, content, ...rest } = props;
|
|
1015
|
+
const entries = content ?? (schema ? [{
|
|
1016
|
+
contentType: mediaType ?? "application/json",
|
|
1017
|
+
schema,
|
|
1018
|
+
keysToOmit: keysToOmit ?? null
|
|
1019
|
+
}] : void 0);
|
|
1020
|
+
return {
|
|
1021
|
+
...rest,
|
|
1022
|
+
content: entries?.map(createContent)
|
|
1023
|
+
};
|
|
1024
|
+
},
|
|
1025
|
+
children: ["content"],
|
|
1026
|
+
visitorKey: "response"
|
|
1027
|
+
});
|
|
1028
|
+
/**
|
|
1029
|
+
* Creates a `ResponseNode`.
|
|
1030
|
+
*
|
|
1031
|
+
* @example
|
|
1032
|
+
* ```ts
|
|
1033
|
+
* const response = createResponse({
|
|
1034
|
+
* statusCode: '200',
|
|
1035
|
+
* content: [{ contentType: 'application/json', schema: createSchema({ type: 'object', properties: [] }) }],
|
|
1036
|
+
* })
|
|
1037
|
+
* ```
|
|
1038
|
+
*/
|
|
1039
|
+
const createResponse = responseDef.create;
|
|
1040
|
+
//#endregion
|
|
1041
|
+
//#region src/registry.ts
|
|
1042
|
+
/**
|
|
1043
|
+
* Every node definition. Adding a node means adding its `defineNode` to one
|
|
1044
|
+
* `nodes/*.ts` file and listing it here. The visitor tables below derive from it.
|
|
1045
|
+
*/
|
|
1046
|
+
const nodeDefs = [
|
|
1047
|
+
inputDef,
|
|
1048
|
+
outputDef,
|
|
1049
|
+
operationDef,
|
|
1050
|
+
requestBodyDef,
|
|
1051
|
+
contentDef,
|
|
1052
|
+
responseDef,
|
|
1053
|
+
schemaDef,
|
|
1054
|
+
propertyDef,
|
|
1055
|
+
parameterDef,
|
|
1056
|
+
functionParameterDef,
|
|
1057
|
+
functionParametersDef,
|
|
1058
|
+
typeLiteralDef,
|
|
1059
|
+
indexedAccessTypeDef,
|
|
1060
|
+
objectBindingPatternDef,
|
|
1061
|
+
constDef,
|
|
1062
|
+
typeDef,
|
|
1063
|
+
functionDef,
|
|
1064
|
+
arrowFunctionDef,
|
|
1065
|
+
textDef,
|
|
1066
|
+
breakDef,
|
|
1067
|
+
jsxDef,
|
|
1068
|
+
importDef,
|
|
1069
|
+
exportDef,
|
|
1070
|
+
sourceDef,
|
|
1071
|
+
fileDef
|
|
1072
|
+
];
|
|
1073
|
+
/**
|
|
1074
|
+
* Child node fields per node kind, in traversal order (Babel's `VISITOR_KEYS`).
|
|
1075
|
+
* Derived from each definition's `children`.
|
|
1076
|
+
*/
|
|
1077
|
+
const VISITOR_KEYS = Object.fromEntries(nodeDefs.flatMap((def) => def.children ? [[def.kind, def.children]] : []));
|
|
1078
|
+
/**
|
|
1079
|
+
* Maps a node kind to the matching visitor callback name. Derived from each
|
|
1080
|
+
* definition's `visitorKey`.
|
|
1081
|
+
*/
|
|
1082
|
+
const VISITOR_KEY_BY_KIND = Object.fromEntries(nodeDefs.flatMap((def) => def.visitorKey ? [[def.kind, def.visitorKey]] : []));
|
|
1083
|
+
/**
|
|
1084
|
+
* Per-kind builders rerun after children are rebuilt. Derived from each
|
|
1085
|
+
* definition's `rebuild` flag.
|
|
1086
|
+
*/
|
|
1087
|
+
const nodeRebuilders = Object.fromEntries(nodeDefs.flatMap((def) => def.rebuild ? [[def.kind, def.create]] : []));
|
|
1088
|
+
//#endregion
|
|
1089
|
+
//#region src/visitor.ts
|
|
1090
|
+
/**
|
|
1091
|
+
* Creates a small async concurrency limiter.
|
|
1092
|
+
*
|
|
1093
|
+
* At most `concurrency` tasks are in flight at once. Extra tasks are queued.
|
|
1094
|
+
*
|
|
1095
|
+
* @example
|
|
1096
|
+
* ```ts
|
|
1097
|
+
* const limit = createLimit(2)
|
|
1098
|
+
* for (const task of [taskA, taskB, taskC]) {
|
|
1099
|
+
* await limit(() => task())
|
|
1100
|
+
* }
|
|
1101
|
+
* // only 2 tasks run at the same time
|
|
1102
|
+
* ```
|
|
1103
|
+
*/
|
|
1104
|
+
function createLimit(concurrency) {
|
|
1105
|
+
let active = 0;
|
|
1106
|
+
const queue = [];
|
|
1107
|
+
function next() {
|
|
1108
|
+
if (active < concurrency && queue.length > 0) {
|
|
1109
|
+
active++;
|
|
1110
|
+
queue.shift()();
|
|
1111
|
+
}
|
|
1112
|
+
}
|
|
1113
|
+
return function limit(fn) {
|
|
1114
|
+
return new Promise((resolve, reject) => {
|
|
1115
|
+
queue.push(() => {
|
|
1116
|
+
Promise.resolve(fn()).then(resolve, reject).finally(() => {
|
|
1117
|
+
active--;
|
|
1118
|
+
next();
|
|
1119
|
+
});
|
|
1120
|
+
});
|
|
1121
|
+
next();
|
|
1122
|
+
});
|
|
1123
|
+
};
|
|
1124
|
+
}
|
|
1125
|
+
const visitorKeysByKind = VISITOR_KEYS;
|
|
1126
|
+
/**
|
|
1127
|
+
* Returns `true` when `value` is an AST node (an object carrying a `kind`).
|
|
1128
|
+
*/
|
|
1129
|
+
function isNode(value) {
|
|
1130
|
+
return typeof value === "object" && value !== null && "kind" in value;
|
|
1131
|
+
}
|
|
1132
|
+
/**
|
|
1133
|
+
* Returns the immediate traversable children of `node` based on {@link VISITOR_KEYS}.
|
|
1134
|
+
*
|
|
1135
|
+
* `Schema` children are only included when `recurse` is `true`. Shallow mode skips them.
|
|
1136
|
+
*
|
|
1137
|
+
* @example
|
|
1138
|
+
* ```ts
|
|
1139
|
+
* const children = getChildren(operationNode, true)
|
|
1140
|
+
* // returns parameters, the request body, and responses
|
|
1141
|
+
* ```
|
|
1142
|
+
*/
|
|
1143
|
+
function* getChildren(node, recurse) {
|
|
1144
|
+
if (node.kind === "Schema" && !recurse) return;
|
|
1145
|
+
const keys = visitorKeysByKind[node.kind];
|
|
1146
|
+
if (!keys) return;
|
|
1147
|
+
const record = node;
|
|
1148
|
+
for (const key of keys) {
|
|
1149
|
+
const value = record[key];
|
|
1150
|
+
if (Array.isArray(value)) {
|
|
1151
|
+
for (const item of value) if (isNode(item)) yield item;
|
|
1152
|
+
} else if (isNode(value)) yield value;
|
|
1153
|
+
}
|
|
1154
|
+
}
|
|
1155
|
+
/**
|
|
1156
|
+
* Invokes the visitor callback that matches `node.kind`, passing the traversal
|
|
1157
|
+
* context. Returns the callback's result (a replacement node, a collected
|
|
1158
|
+
* value, or `undefined` when no callback is registered for the kind).
|
|
1159
|
+
*
|
|
1160
|
+
* Shared by `walk`, `transform`, and `collectLazy` so node-kind dispatch lives
|
|
1161
|
+
* in one place. `TResult` is the caller's expected return: the same node type
|
|
1162
|
+
* for `transform`, the collected value type for `collectLazy`, ignored for `walk`.
|
|
1163
|
+
*/
|
|
1164
|
+
function applyVisitor(node, visitor, parent) {
|
|
1165
|
+
const key = VISITOR_KEY_BY_KIND[node.kind];
|
|
1166
|
+
if (!key) return void 0;
|
|
1167
|
+
const fn = visitor[key];
|
|
1168
|
+
return fn?.(node, { parent });
|
|
1169
|
+
}
|
|
1170
|
+
/**
|
|
1171
|
+
* Async depth-first traversal for side effects. Visitor return values are
|
|
1172
|
+
* ignored. Use `transform` when you want to rewrite nodes.
|
|
1173
|
+
*
|
|
1174
|
+
* Sibling nodes at each depth run concurrently up to `options.concurrency`
|
|
1175
|
+
* (defaults to `WALK_CONCURRENCY`). Higher values overlap I/O-bound visitor
|
|
1176
|
+
* work. Lower values reduce memory pressure.
|
|
1177
|
+
*
|
|
1178
|
+
* @example Log every operation
|
|
1179
|
+
* ```ts
|
|
1180
|
+
* await walk(root, {
|
|
1181
|
+
* operation(node) {
|
|
1182
|
+
* console.log(node.operationId)
|
|
1183
|
+
* },
|
|
1184
|
+
* })
|
|
1185
|
+
* ```
|
|
1186
|
+
*
|
|
1187
|
+
* @example Only visit the root node
|
|
1188
|
+
* ```ts
|
|
1189
|
+
* await walk(root, { depth: 'shallow', input: () => {} })
|
|
1190
|
+
* ```
|
|
1191
|
+
*/
|
|
1192
|
+
async function walk(node, options) {
|
|
1193
|
+
return _walk(node, options, (options.depth ?? visitorDepths.deep) === visitorDepths.deep, createLimit(options.concurrency ?? 30), void 0);
|
|
1194
|
+
}
|
|
1195
|
+
async function _walk(node, visitor, recurse, limit, parent) {
|
|
1196
|
+
await limit(() => applyVisitor(node, visitor, parent));
|
|
1197
|
+
const children = Array.from(getChildren(node, recurse));
|
|
1198
|
+
if (children.length === 0) return;
|
|
1199
|
+
await Promise.all(children.map((child) => _walk(child, visitor, recurse, limit, node)));
|
|
1200
|
+
}
|
|
1201
|
+
function transform(node, options) {
|
|
1202
|
+
const { depth, parent, ...visitor } = options;
|
|
1203
|
+
const recurse = (depth ?? visitorDepths.deep) === visitorDepths.deep;
|
|
1204
|
+
const rebuilt = transformChildren(applyVisitor(node, visitor, parent) ?? node, options, recurse);
|
|
1205
|
+
if (rebuilt === node) return node;
|
|
1206
|
+
const rebuild = nodeRebuilders[rebuilt.kind];
|
|
1207
|
+
return rebuild ? rebuild(rebuilt) : rebuilt;
|
|
1208
|
+
}
|
|
1209
|
+
/**
|
|
1210
|
+
* Immutably rebuilds a node's children using {@link VISITOR_KEYS}, transforming
|
|
1211
|
+
* each child node and leaving non-node values (e.g. `additionalProperties: true`) intact.
|
|
1212
|
+
* `Schema` children are skipped in shallow mode.
|
|
1213
|
+
*/
|
|
1214
|
+
function transformChildren(node, options, recurse) {
|
|
1215
|
+
if (node.kind === "Schema" && !recurse) return node;
|
|
1216
|
+
const keys = visitorKeysByKind[node.kind];
|
|
1217
|
+
if (!keys) return node;
|
|
1218
|
+
const record = node;
|
|
1219
|
+
const childOptions = {
|
|
1220
|
+
...options,
|
|
1221
|
+
parent: node
|
|
1222
|
+
};
|
|
1223
|
+
let updates;
|
|
1224
|
+
for (const key of keys) {
|
|
1225
|
+
if (!(key in record)) continue;
|
|
1226
|
+
const value = record[key];
|
|
1227
|
+
if (Array.isArray(value)) {
|
|
1228
|
+
let changed = false;
|
|
1229
|
+
const mapped = value.map((item) => {
|
|
1230
|
+
if (!isNode(item)) return item;
|
|
1231
|
+
const next = transform(item, childOptions);
|
|
1232
|
+
if (next !== item) changed = true;
|
|
1233
|
+
return next;
|
|
1234
|
+
});
|
|
1235
|
+
if (changed) (updates ??= {})[key] = mapped;
|
|
1236
|
+
} else if (isNode(value)) {
|
|
1237
|
+
const next = transform(value, childOptions);
|
|
1238
|
+
if (next !== value) (updates ??= {})[key] = next;
|
|
1239
|
+
}
|
|
1240
|
+
}
|
|
1241
|
+
return updates ? {
|
|
1242
|
+
...node,
|
|
1243
|
+
...updates
|
|
1244
|
+
} : node;
|
|
1245
|
+
}
|
|
1246
|
+
/**
|
|
1247
|
+
* Lazy depth-first collection pass. Yields every non-null value returned by
|
|
1248
|
+
* the visitor callbacks. Use `collect` for the eager array form.
|
|
1249
|
+
*
|
|
1250
|
+
* @example Collect every operationId
|
|
1251
|
+
* ```ts
|
|
1252
|
+
* const ids: string[] = []
|
|
1253
|
+
* for (const id of collectLazy<string>(root, {
|
|
1254
|
+
* operation(node) {
|
|
1255
|
+
* return node.operationId
|
|
1256
|
+
* },
|
|
1257
|
+
* })) {
|
|
1258
|
+
* ids.push(id)
|
|
1259
|
+
* }
|
|
1260
|
+
* ```
|
|
1261
|
+
*/
|
|
1262
|
+
function* collectLazy(node, options) {
|
|
1263
|
+
const { depth, parent, ...visitor } = options;
|
|
1264
|
+
const recurse = (depth ?? visitorDepths.deep) === visitorDepths.deep;
|
|
1265
|
+
const v = applyVisitor(node, visitor, parent);
|
|
1266
|
+
if (v != null) yield v;
|
|
1267
|
+
for (const child of getChildren(node, recurse)) yield* collectLazy(child, {
|
|
1268
|
+
...options,
|
|
1269
|
+
parent: node
|
|
1270
|
+
});
|
|
1271
|
+
}
|
|
1272
|
+
/**
|
|
1273
|
+
* Eager depth-first collection pass. Returns an array of every non-null value
|
|
1274
|
+
* the visitor callbacks return.
|
|
1275
|
+
*
|
|
1276
|
+
* @example Collect every operationId
|
|
1277
|
+
* ```ts
|
|
1278
|
+
* const ids = collect<string>(root, {
|
|
1279
|
+
* operation(node) {
|
|
1280
|
+
* return node.operationId
|
|
1281
|
+
* },
|
|
1282
|
+
* })
|
|
1283
|
+
* ```
|
|
1284
|
+
*/
|
|
1285
|
+
function collect(node, options) {
|
|
1286
|
+
return Array.from(collectLazy(node, options));
|
|
1287
|
+
}
|
|
1288
|
+
//#endregion
|
|
1289
|
+
//#region src/utils/ast.ts
|
|
1290
|
+
const plainStringTypes = new Set([
|
|
1291
|
+
"string",
|
|
1292
|
+
"uuid",
|
|
1293
|
+
"email",
|
|
1294
|
+
"url",
|
|
1295
|
+
"datetime"
|
|
1296
|
+
]);
|
|
1297
|
+
/**
|
|
1298
|
+
* Merges a ref node with its resolved schema, giving usage-site fields precedence.
|
|
1299
|
+
*
|
|
1300
|
+
* Usage-site fields (`description`, `readOnly`, `nullable`, `deprecated`) on the ref node
|
|
1301
|
+
* override the same fields in the resolved `node.schema`. Non-ref nodes are returned unchanged.
|
|
1302
|
+
*
|
|
1303
|
+
* @example
|
|
1304
|
+
* ```ts
|
|
1305
|
+
* // Ref with description override
|
|
1306
|
+
* const ref = createSchema({ type: 'ref', ref: '#/components/schemas/Pet', description: 'A cute pet' })
|
|
1307
|
+
* const merged = syncSchemaRef(ref) // merges with resolved Pet schema
|
|
1308
|
+
* ```
|
|
1309
|
+
*/
|
|
1310
|
+
function syncSchemaRef(node) {
|
|
1311
|
+
const ref = narrowSchema(node, "ref");
|
|
1312
|
+
if (!ref) return node;
|
|
1313
|
+
if (!ref.schema) return node;
|
|
1314
|
+
const { kind: _kind, type: _type, name: _name, ref: _ref, schema: _schema, ...overrides } = ref;
|
|
1315
|
+
const definedOverrides = Object.fromEntries(Object.entries(overrides).filter(([, v]) => v !== void 0));
|
|
1316
|
+
return createSchema({
|
|
1317
|
+
...ref.schema,
|
|
1318
|
+
...definedOverrides
|
|
1319
|
+
});
|
|
1320
|
+
}
|
|
1321
|
+
/**
|
|
1322
|
+
* Type guard that returns `true` when a schema emits as a plain `string` type.
|
|
1323
|
+
*
|
|
1324
|
+
* Covers `string`, `uuid`, `email`, `url`, and `datetime` types. For `date` and `time`
|
|
1325
|
+
* types, returns `true` only when `representation` is `'string'` rather than `'date'`.
|
|
1326
|
+
*/
|
|
1327
|
+
function isStringType(node) {
|
|
1328
|
+
if (plainStringTypes.has(node.type)) return true;
|
|
1329
|
+
const temporal = narrowSchema(node, "date") ?? narrowSchema(node, "time");
|
|
1330
|
+
if (temporal) return temporal.representation !== "date";
|
|
1331
|
+
return false;
|
|
1332
|
+
}
|
|
1333
|
+
/**
|
|
1334
|
+
* Applies casing rules to parameter names and returns a new parameter array.
|
|
1335
|
+
*
|
|
1336
|
+
* Use this before passing parameters to schema builders so output property keys match
|
|
1337
|
+
* the desired casing while preserving `OperationNode.parameters` for other consumers.
|
|
1338
|
+
* The input array is not mutated. When `casing` is not set, the original array is returned unchanged.
|
|
1339
|
+
*/
|
|
1340
|
+
const caseParamsMemo = memoize(/* @__PURE__ */ new WeakMap(), (params) => memoize(/* @__PURE__ */ new Map(), (casing) => params.map((param) => {
|
|
1341
|
+
const transformed = casing === "camelcase" || !isValidVarName(param.name) ? camelCase(param.name) : param.name;
|
|
1342
|
+
return {
|
|
1343
|
+
...param,
|
|
1344
|
+
name: transformed
|
|
1345
|
+
};
|
|
1346
|
+
})));
|
|
1347
|
+
function caseParams(params, casing) {
|
|
1348
|
+
if (!casing) return params;
|
|
1349
|
+
return caseParamsMemo(params)(casing);
|
|
1350
|
+
}
|
|
1351
|
+
/**
|
|
1352
|
+
* Creates a single-property object schema used as a discriminator literal.
|
|
1353
|
+
*
|
|
1354
|
+
* @example
|
|
1355
|
+
* ```ts
|
|
1356
|
+
* createDiscriminantNode({ propertyName: 'type', value: 'dog' })
|
|
1357
|
+
* // -> { type: 'object', properties: [{ name: 'type', required: true, schema: enum('dog') }] }
|
|
1358
|
+
* ```
|
|
1359
|
+
*/
|
|
1360
|
+
function createDiscriminantNode({ propertyName, value }) {
|
|
1361
|
+
return createSchema({
|
|
1362
|
+
type: "object",
|
|
1363
|
+
primitive: "object",
|
|
1364
|
+
properties: [createProperty({
|
|
1365
|
+
name: propertyName,
|
|
1366
|
+
schema: createSchema({
|
|
1367
|
+
type: "enum",
|
|
1368
|
+
primitive: "string",
|
|
1369
|
+
enumValues: [value]
|
|
1370
|
+
}),
|
|
1371
|
+
required: true
|
|
1372
|
+
})]
|
|
1373
|
+
});
|
|
1374
|
+
}
|
|
1375
|
+
/**
|
|
1376
|
+
* Resolves the {@link TypeExpression} for an individual parameter.
|
|
1377
|
+
*
|
|
1378
|
+
* Without a resolver, falls back to the schema primitive (a plain type-name string).
|
|
1379
|
+
* When the parameter belongs to a named group, emits an {@link IndexedAccessTypeNode}
|
|
1380
|
+
* (`GroupParams['petId']`); otherwise the resolved individual name as a plain string.
|
|
1381
|
+
*/
|
|
1382
|
+
function resolveParamType({ node, param, resolver }) {
|
|
1383
|
+
if (!resolver) return param.schema.primitive ?? "unknown";
|
|
1384
|
+
const individualName = resolver.resolveParamName(node, param);
|
|
1385
|
+
const groupLocation = param.in === "path" || param.in === "query" || param.in === "header" ? param.in : void 0;
|
|
1386
|
+
const groupResolvers = {
|
|
1387
|
+
path: resolver.resolvePathParamsName,
|
|
1388
|
+
query: resolver.resolveQueryParamsName,
|
|
1389
|
+
header: resolver.resolveHeaderParamsName
|
|
1390
|
+
};
|
|
1391
|
+
const groupName = groupLocation ? groupResolvers[groupLocation].call(resolver, node, param) : void 0;
|
|
1392
|
+
if (groupName && groupName !== individualName) return createIndexedAccessType({
|
|
1393
|
+
objectType: groupName,
|
|
1394
|
+
indexType: param.name
|
|
1395
|
+
});
|
|
1396
|
+
return individualName;
|
|
1397
|
+
}
|
|
1398
|
+
/**
|
|
1399
|
+
* Converts an `OperationNode` into function parameters for code generation.
|
|
1400
|
+
*
|
|
1401
|
+
* Centralizes parameter grouping logic for all plugins. `paramsType` chooses between one
|
|
1402
|
+
* destructured object parameter (`object`) and separate top-level parameters (`inline`), while
|
|
1403
|
+
* `pathParamsType` controls how path params render in inline mode. Provide a `resolver` for type
|
|
1404
|
+
* name resolution and `extraParams` for plugin-specific trailing parameters such as an `options` object.
|
|
1405
|
+
*/
|
|
1406
|
+
function createOperationParams(node, options) {
|
|
1407
|
+
const { paramsType, pathParamsType, paramsCasing, resolver, pathParamsDefault, extraParams = [], paramNames, typeWrapper } = options;
|
|
1408
|
+
const dataName = paramNames?.data ?? "data";
|
|
1409
|
+
const paramsName = paramNames?.params ?? "params";
|
|
1410
|
+
const headersName = paramNames?.headers ?? "headers";
|
|
1411
|
+
const pathName = paramNames?.path ?? "pathParams";
|
|
1412
|
+
const wrapType = (type) => typeWrapper ? typeWrapper(type) : type;
|
|
1413
|
+
const wrapTypeExpression = (type) => typeof type === "string" ? wrapType(type) : type;
|
|
1414
|
+
const casedParams = caseParams(node.parameters, paramsCasing);
|
|
1415
|
+
const pathParams = casedParams.filter((p) => p.in === "path");
|
|
1416
|
+
const queryParams = casedParams.filter((p) => p.in === "query");
|
|
1417
|
+
const headerParams = casedParams.filter((p) => p.in === "header");
|
|
1418
|
+
const toProperty = (param) => ({
|
|
1419
|
+
name: param.name,
|
|
1420
|
+
type: wrapTypeExpression(resolveParamType({
|
|
1421
|
+
node,
|
|
1422
|
+
param,
|
|
1423
|
+
resolver
|
|
1424
|
+
})),
|
|
1425
|
+
optional: !param.required
|
|
1426
|
+
});
|
|
1427
|
+
const emptyObjectDefault = (props) => props.every((p) => p.optional) ? "{}" : void 0;
|
|
1428
|
+
const bodyType = node.requestBody?.content?.[0]?.schema ? wrapType(resolver?.resolveDataName(node) ?? "unknown") : void 0;
|
|
1429
|
+
const bodyProperty = bodyType ? [{
|
|
1430
|
+
name: dataName,
|
|
1431
|
+
type: bodyType,
|
|
1432
|
+
optional: !(node.requestBody?.required ?? false)
|
|
1433
|
+
}] : [];
|
|
1434
|
+
const trailingGroups = [{
|
|
1435
|
+
name: paramsName,
|
|
1436
|
+
node,
|
|
1437
|
+
params: queryParams,
|
|
1438
|
+
groupType: resolveGroupType({
|
|
1439
|
+
node,
|
|
1440
|
+
params: queryParams,
|
|
1441
|
+
group: "query",
|
|
1442
|
+
resolver
|
|
1443
|
+
}),
|
|
1444
|
+
resolver,
|
|
1445
|
+
wrapType
|
|
1446
|
+
}, {
|
|
1447
|
+
name: headersName,
|
|
1448
|
+
node,
|
|
1449
|
+
params: headerParams,
|
|
1450
|
+
groupType: resolveGroupType({
|
|
1451
|
+
node,
|
|
1452
|
+
params: headerParams,
|
|
1453
|
+
group: "header",
|
|
1454
|
+
resolver
|
|
1455
|
+
}),
|
|
1456
|
+
resolver,
|
|
1457
|
+
wrapType
|
|
1458
|
+
}];
|
|
1459
|
+
const params = [];
|
|
1460
|
+
if (paramsType === "object") {
|
|
1461
|
+
const children = [
|
|
1462
|
+
...pathParams.map(toProperty),
|
|
1463
|
+
...bodyProperty,
|
|
1464
|
+
...trailingGroups.flatMap(buildGroupProperty)
|
|
1465
|
+
];
|
|
1466
|
+
if (children.length) params.push(createFunctionParameter({
|
|
1467
|
+
properties: children,
|
|
1468
|
+
default: emptyObjectDefault(children)
|
|
1469
|
+
}));
|
|
1470
|
+
} else {
|
|
1471
|
+
if (pathParamsType === "inlineSpread" && pathParams.length) {
|
|
1472
|
+
const spreadType = resolver?.resolvePathParamsName(node, pathParams[0]);
|
|
1473
|
+
params.push(createFunctionParameter({
|
|
1474
|
+
name: pathName,
|
|
1475
|
+
type: spreadType ? wrapType(spreadType) : void 0,
|
|
1476
|
+
rest: true
|
|
1477
|
+
}));
|
|
1478
|
+
} else if (pathParamsType === "inline") params.push(...pathParams.map((p) => createFunctionParameter(toProperty(p))));
|
|
1479
|
+
else if (pathParams.length) {
|
|
1480
|
+
const pathChildren = pathParams.map(toProperty);
|
|
1481
|
+
params.push(createFunctionParameter({
|
|
1482
|
+
properties: pathChildren,
|
|
1483
|
+
default: pathParamsDefault ?? emptyObjectDefault(pathChildren)
|
|
1484
|
+
}));
|
|
1485
|
+
}
|
|
1486
|
+
params.push(...bodyProperty.map((p) => createFunctionParameter(p)));
|
|
1487
|
+
params.push(...trailingGroups.flatMap(buildGroupParam));
|
|
1488
|
+
}
|
|
1489
|
+
params.push(...extraParams);
|
|
1490
|
+
return createFunctionParameters({ params });
|
|
1491
|
+
}
|
|
1492
|
+
/**
|
|
1493
|
+
* Builds the property descriptor for a query or header group.
|
|
1494
|
+
* Returns an empty array when there are no params to emit.
|
|
1495
|
+
*
|
|
1496
|
+
* A pre-resolved `groupType` emits `name: GroupType`. Otherwise it builds an inline
|
|
1497
|
+
* {@link TypeLiteralNode} from the individual params.
|
|
1498
|
+
*/
|
|
1499
|
+
function buildGroupProperty({ name, node, params, groupType, resolver, wrapType }) {
|
|
1500
|
+
if (groupType) return [{
|
|
1501
|
+
name,
|
|
1502
|
+
type: typeof groupType.type === "string" ? wrapType(groupType.type) : groupType.type,
|
|
1503
|
+
optional: groupType.optional
|
|
1504
|
+
}];
|
|
1505
|
+
if (params.length) return [{
|
|
1506
|
+
name,
|
|
1507
|
+
type: buildTypeLiteral({
|
|
1508
|
+
node,
|
|
1509
|
+
params,
|
|
1510
|
+
resolver
|
|
1511
|
+
}),
|
|
1512
|
+
optional: params.every((p) => !p.required)
|
|
1513
|
+
}];
|
|
1514
|
+
return [];
|
|
1515
|
+
}
|
|
1516
|
+
/**
|
|
1517
|
+
* Builds a single {@link FunctionParameterNode} for a query or header group.
|
|
1518
|
+
* Returns an empty array when there are no params to emit.
|
|
1519
|
+
*
|
|
1520
|
+
* A pre-resolved `groupType` emits `name: GroupType`. Otherwise it builds an inline
|
|
1521
|
+
* {@link TypeLiteralNode} from the individual params.
|
|
1522
|
+
*/
|
|
1523
|
+
function buildGroupParam(args) {
|
|
1524
|
+
return buildGroupProperty(args).map((p) => createFunctionParameter(p));
|
|
1525
|
+
}
|
|
1526
|
+
/**
|
|
1527
|
+
* Builds a {@link TypeLiteralNode} for an inline anonymous type grouping named fields.
|
|
1528
|
+
*
|
|
1529
|
+
* Used when query or header parameters have no dedicated group type name.
|
|
1530
|
+
* Each language printer renders this appropriately (TypeScript: `{ petId: string; name?: string }`).
|
|
1531
|
+
*/
|
|
1532
|
+
function buildTypeLiteral({ node, params, resolver }) {
|
|
1533
|
+
return createTypeLiteral({ members: params.map((p) => ({
|
|
1534
|
+
name: p.name,
|
|
1535
|
+
type: resolveParamType({
|
|
1536
|
+
node,
|
|
1537
|
+
param: p,
|
|
1538
|
+
resolver
|
|
1539
|
+
}),
|
|
1540
|
+
optional: !p.required
|
|
1541
|
+
})) });
|
|
1542
|
+
}
|
|
1543
|
+
function sourceKey(source) {
|
|
1544
|
+
return `${source.name ?? extractStringsFromNodes(source.nodes)}:${source.isExportable ?? false}:${source.isTypeOnly ?? false}`;
|
|
1545
|
+
}
|
|
1546
|
+
function pathTypeKey(path, isTypeOnly) {
|
|
1547
|
+
return `${path}:${isTypeOnly ?? false}`;
|
|
1548
|
+
}
|
|
1549
|
+
function exportKey(path, name, isTypeOnly, asAlias) {
|
|
1550
|
+
return `${path}:${name ?? ""}:${isTypeOnly ?? false}:${asAlias ?? ""}`;
|
|
1551
|
+
}
|
|
1552
|
+
function importKey(path, name, isTypeOnly) {
|
|
1553
|
+
return `${path}:${name ?? ""}:${isTypeOnly ?? false}`;
|
|
1554
|
+
}
|
|
1555
|
+
/**
|
|
1556
|
+
* Computes a multi-level sort key for exports and imports:
|
|
1557
|
+
* non-array names first (wildcards/namespace aliases). Type-only before value. Alphabetical path. Unnamed before named.
|
|
1558
|
+
*/
|
|
1559
|
+
function sortKey(node) {
|
|
1560
|
+
const isArray = Array.isArray(node.name) ? "1" : "0";
|
|
1561
|
+
const typeOnly = node.isTypeOnly ? "0" : "1";
|
|
1562
|
+
const hasName = node.name != null ? "1" : "0";
|
|
1563
|
+
const name = Array.isArray(node.name) ? node.name.toSorted().join("\0") : node.name ?? "";
|
|
1564
|
+
return `${isArray}:${typeOnly}:${node.path}:${hasName}:${name}`;
|
|
1565
|
+
}
|
|
1566
|
+
/**
|
|
1567
|
+
* Deduplicates and merges `SourceNode` objects by `name + isExportable + isTypeOnly`.
|
|
1568
|
+
*
|
|
1569
|
+
* Unnamed sources are deduplicated by object reference. Returns a deduplicated array in original order.
|
|
1570
|
+
*/
|
|
1571
|
+
function combineSources(sources) {
|
|
1572
|
+
const seen = /* @__PURE__ */ new Map();
|
|
1573
|
+
for (const source of sources) {
|
|
1574
|
+
const key = sourceKey(source);
|
|
1575
|
+
if (!seen.has(key)) seen.set(key, source);
|
|
1576
|
+
}
|
|
1577
|
+
return [...seen.values()];
|
|
1578
|
+
}
|
|
1579
|
+
/**
|
|
1580
|
+
* Merges `incoming` names into `existing`, preserving order and dropping duplicates.
|
|
1581
|
+
*
|
|
1582
|
+
* Shared by `combineExports` and `combineImports` for the same-path name-merge case.
|
|
1583
|
+
*/
|
|
1584
|
+
function mergeNameArrays(existing, incoming) {
|
|
1585
|
+
const merged = new Set(existing);
|
|
1586
|
+
for (const name of incoming) merged.add(name);
|
|
1587
|
+
return [...merged];
|
|
1588
|
+
}
|
|
1589
|
+
/**
|
|
1590
|
+
* Deduplicates and merges `ExportNode` objects by path and type.
|
|
1591
|
+
*
|
|
1592
|
+
* Named exports with the same path and `isTypeOnly` flag have their names merged into a single export.
|
|
1593
|
+
* Non-array exports are deduplicated by exact identity. Returns a sorted, deduplicated array.
|
|
1594
|
+
*/
|
|
1595
|
+
function combineExports(exports) {
|
|
1596
|
+
const result = [];
|
|
1597
|
+
const namedByPath = /* @__PURE__ */ new Map();
|
|
1598
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1599
|
+
const keyed = exports.map((node) => ({
|
|
1600
|
+
node,
|
|
1601
|
+
key: sortKey(node)
|
|
1602
|
+
}));
|
|
1603
|
+
keyed.sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
|
|
1604
|
+
for (const { node: curr } of keyed) {
|
|
1605
|
+
const { name, path, isTypeOnly, asAlias } = curr;
|
|
1606
|
+
if (Array.isArray(name)) {
|
|
1607
|
+
if (!name.length) continue;
|
|
1608
|
+
const key = pathTypeKey(path, isTypeOnly);
|
|
1609
|
+
const existing = namedByPath.get(key);
|
|
1610
|
+
if (existing && Array.isArray(existing.name)) existing.name = mergeNameArrays(existing.name, name);
|
|
1611
|
+
else {
|
|
1612
|
+
const newItem = {
|
|
1613
|
+
...curr,
|
|
1614
|
+
name: [...new Set(name)]
|
|
1615
|
+
};
|
|
1616
|
+
result.push(newItem);
|
|
1617
|
+
namedByPath.set(key, newItem);
|
|
1618
|
+
}
|
|
1619
|
+
} else {
|
|
1620
|
+
const key = exportKey(path, name, isTypeOnly, asAlias);
|
|
1621
|
+
if (!seen.has(key)) {
|
|
1622
|
+
result.push(curr);
|
|
1623
|
+
seen.add(key);
|
|
1624
|
+
}
|
|
1625
|
+
}
|
|
1626
|
+
}
|
|
1627
|
+
return result;
|
|
1628
|
+
}
|
|
1629
|
+
/**
|
|
1630
|
+
* Deduplicates and merges `ImportNode` objects, filtering out unused imports.
|
|
1631
|
+
*
|
|
1632
|
+
* Retains imports that are referenced in `source` or re-exported. Imports with the same path and
|
|
1633
|
+
* `isTypeOnly` flag have their names merged. Returns a sorted, deduplicated, filtered array.
|
|
1634
|
+
*
|
|
1635
|
+
* @note Use this when combining imports from multiple files to avoid duplicate declarations.
|
|
1636
|
+
*/
|
|
1637
|
+
function combineImports(imports, exports, source) {
|
|
1638
|
+
const exportedNames = new Set(exports.flatMap((e) => Array.isArray(e.name) ? e.name : e.name ? [e.name] : []));
|
|
1639
|
+
const isUsed = (importName) => !source || source.includes(importName) || exportedNames.has(importName);
|
|
1640
|
+
const importNameMemo = /* @__PURE__ */ new Map();
|
|
1641
|
+
const canonicalizeName = (n) => {
|
|
1642
|
+
if (typeof n === "string") return n;
|
|
1643
|
+
const key = `${n.propertyName}:${n.name ?? ""}`;
|
|
1644
|
+
if (!importNameMemo.has(key)) importNameMemo.set(key, n);
|
|
1645
|
+
return importNameMemo.get(key);
|
|
1646
|
+
};
|
|
1647
|
+
const pathsWithUsedNamedImport = /* @__PURE__ */ new Set();
|
|
1648
|
+
for (const node of imports) {
|
|
1649
|
+
if (!Array.isArray(node.name)) continue;
|
|
1650
|
+
if (node.name.some((item) => typeof item === "string" ? isUsed(item) : isUsed(item.name ?? item.propertyName))) pathsWithUsedNamedImport.add(node.path);
|
|
1651
|
+
}
|
|
1652
|
+
const result = [];
|
|
1653
|
+
const namedByPath = /* @__PURE__ */ new Map();
|
|
1654
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1655
|
+
const keyed = imports.map((node) => ({
|
|
1656
|
+
node,
|
|
1657
|
+
key: sortKey(node)
|
|
1658
|
+
}));
|
|
1659
|
+
keyed.sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
|
|
1660
|
+
for (const { node: curr } of keyed) {
|
|
1661
|
+
if (curr.path === curr.root) continue;
|
|
1662
|
+
const { path, isTypeOnly } = curr;
|
|
1663
|
+
let { name } = curr;
|
|
1664
|
+
if (Array.isArray(name)) {
|
|
1665
|
+
name = [...new Set(name.map(canonicalizeName))].filter((item) => typeof item === "string" ? isUsed(item) : isUsed(item.name ?? item.propertyName));
|
|
1666
|
+
if (!name.length) continue;
|
|
1667
|
+
const key = pathTypeKey(path, isTypeOnly);
|
|
1668
|
+
const existing = namedByPath.get(key);
|
|
1669
|
+
if (existing && Array.isArray(existing.name)) existing.name = mergeNameArrays(existing.name, name);
|
|
1670
|
+
else {
|
|
1671
|
+
const newItem = {
|
|
1672
|
+
...curr,
|
|
1673
|
+
name
|
|
1674
|
+
};
|
|
1675
|
+
result.push(newItem);
|
|
1676
|
+
namedByPath.set(key, newItem);
|
|
1677
|
+
}
|
|
1678
|
+
} else {
|
|
1679
|
+
if (name && !isUsed(name) && !pathsWithUsedNamedImport.has(path)) continue;
|
|
1680
|
+
const key = importKey(path, name, isTypeOnly);
|
|
1681
|
+
if (!seen.has(key)) {
|
|
1682
|
+
result.push(curr);
|
|
1683
|
+
seen.add(key);
|
|
1684
|
+
}
|
|
1685
|
+
}
|
|
1686
|
+
}
|
|
1687
|
+
return result;
|
|
1688
|
+
}
|
|
1689
|
+
/**
|
|
1690
|
+
* Resolves the schema name of a ref node, falling back through `ref` → `name` → nested `schema.name`.
|
|
1691
|
+
*
|
|
1692
|
+
* Returns `null` for non-ref nodes or when no name can be resolved. Use this to get a schema's
|
|
1693
|
+
* identifier for type definitions or error messages.
|
|
1694
|
+
*
|
|
1695
|
+
* @example
|
|
1696
|
+
* ```ts
|
|
1697
|
+
* resolveRefName({ kind: 'Schema', type: 'ref', ref: '#/components/schemas/Pet' })
|
|
1698
|
+
* // => 'Pet'
|
|
1699
|
+
* ```
|
|
1700
|
+
*/
|
|
1701
|
+
function resolveRefName(node) {
|
|
1702
|
+
if (!node || node.type !== "ref") return null;
|
|
1703
|
+
if (node.ref) return extractRefName(node.ref) ?? node.name ?? node.schema?.name ?? null;
|
|
1704
|
+
return node.name ?? node.schema?.name ?? null;
|
|
1705
|
+
}
|
|
1706
|
+
/**
|
|
1707
|
+
* Collects every named schema referenced (transitively) from a node via ref edges.
|
|
1708
|
+
*
|
|
1709
|
+
* Refs are followed by name only, the resolved `node.schema` is not traversed inline.
|
|
1710
|
+
* Use this to determine schema dependencies, build reference graphs, or detect what schemas need to be emitted.
|
|
1711
|
+
*
|
|
1712
|
+
* @example Collect refs from a single schema
|
|
1713
|
+
* ```ts
|
|
1714
|
+
* const names = collectReferencedSchemaNames(petSchema)
|
|
1715
|
+
* // → Set { 'Category', 'Tag' }
|
|
1716
|
+
* ```
|
|
1717
|
+
*
|
|
1718
|
+
* @example Accumulate refs from multiple schemas into one set
|
|
1719
|
+
* ```ts
|
|
1720
|
+
* const out = new Set<string>()
|
|
1721
|
+
* for (const schema of schemas) {
|
|
1722
|
+
* collectReferencedSchemaNames(schema, out)
|
|
1723
|
+
* }
|
|
1724
|
+
* ```
|
|
1725
|
+
*/
|
|
1726
|
+
const collectSchemaRefs = memoize(/* @__PURE__ */ new WeakMap(), (node) => {
|
|
1727
|
+
const refs = /* @__PURE__ */ new Set();
|
|
1728
|
+
collect(node, { schema(child) {
|
|
1729
|
+
if (child.type === "ref") {
|
|
1730
|
+
const name = resolveRefName(child);
|
|
1731
|
+
if (name) refs.add(name);
|
|
1732
|
+
}
|
|
1733
|
+
} });
|
|
1734
|
+
return refs;
|
|
1735
|
+
});
|
|
1736
|
+
function collectReferencedSchemaNames(node, out = /* @__PURE__ */ new Set()) {
|
|
1737
|
+
if (!node) return out;
|
|
1738
|
+
for (const name of collectSchemaRefs(node)) out.add(name);
|
|
1739
|
+
return out;
|
|
1740
|
+
}
|
|
1741
|
+
/**
|
|
1742
|
+
* Collects the names of all top-level schemas transitively used by a set of operations.
|
|
1743
|
+
*
|
|
1744
|
+
* An operation uses a schema when any of its parameters, request body content, or responses
|
|
1745
|
+
* reference it, directly or indirectly through other named schemas.
|
|
1746
|
+
* The walk is iterative and safe against reference cycles.
|
|
1747
|
+
*
|
|
1748
|
+
* Use this together with `include` filters to determine which schemas from `components/schemas`
|
|
1749
|
+
* are reachable from the allowed operations, so that schemas used only by excluded operations
|
|
1750
|
+
* are not generated.
|
|
1751
|
+
*
|
|
1752
|
+
* @example Only generate schemas referenced by included operations
|
|
1753
|
+
* ```ts
|
|
1754
|
+
* const includedOps = operations.filter(op => resolver.resolveOptions(op, { options, include }) !== null)
|
|
1755
|
+
* const allowed = collectUsedSchemaNames(includedOps, schemas)
|
|
1756
|
+
*
|
|
1757
|
+
* for (const schema of schemas) {
|
|
1758
|
+
* if (schema.name && !allowed.has(schema.name)) continue
|
|
1759
|
+
* // … generate schema
|
|
1760
|
+
* }
|
|
1761
|
+
* ```
|
|
1762
|
+
*
|
|
1763
|
+
* @example Check whether a specific schema is needed
|
|
1764
|
+
* ```ts
|
|
1765
|
+
* const allowed = collectUsedSchemaNames(includedOps, schemas)
|
|
1766
|
+
* allowed.has('OrderStatus') // false when no included operation references OrderStatus
|
|
1767
|
+
* ```
|
|
1768
|
+
*/
|
|
1769
|
+
const collectUsedSchemaNamesMemo = memoize(/* @__PURE__ */ new WeakMap(), (ops) => memoize(/* @__PURE__ */ new WeakMap(), (schemas) => computeUsedSchemaNames(ops, schemas)));
|
|
1770
|
+
function computeUsedSchemaNames(operations, schemas) {
|
|
1771
|
+
const schemaMap = /* @__PURE__ */ new Map();
|
|
1772
|
+
for (const schema of schemas) if (schema.name) schemaMap.set(schema.name, schema);
|
|
1773
|
+
const result = /* @__PURE__ */ new Set();
|
|
1774
|
+
function visitSchema(schema) {
|
|
1775
|
+
const directRefs = collectReferencedSchemaNames(schema);
|
|
1776
|
+
for (const name of directRefs) if (!result.has(name)) {
|
|
1777
|
+
result.add(name);
|
|
1778
|
+
const namedSchema = schemaMap.get(name);
|
|
1779
|
+
if (namedSchema) visitSchema(namedSchema);
|
|
1780
|
+
}
|
|
1781
|
+
}
|
|
1782
|
+
for (const op of operations) for (const schema of collectLazy(op, {
|
|
1783
|
+
depth: "shallow",
|
|
1784
|
+
schema: (node) => node
|
|
1785
|
+
})) visitSchema(schema);
|
|
1786
|
+
return result;
|
|
1787
|
+
}
|
|
1788
|
+
function collectUsedSchemaNames(operations, schemas) {
|
|
1789
|
+
return collectUsedSchemaNamesMemo(operations)(schemas);
|
|
1790
|
+
}
|
|
1791
|
+
const EMPTY_CIRCULAR_SET = /* @__PURE__ */ new Set();
|
|
1792
|
+
const findCircularSchemasMemo = memoize(/* @__PURE__ */ new WeakMap(), (schemas) => {
|
|
1793
|
+
const graph = /* @__PURE__ */ new Map();
|
|
1794
|
+
for (const schema of schemas) {
|
|
1795
|
+
if (!schema.name) continue;
|
|
1796
|
+
graph.set(schema.name, collectReferencedSchemaNames(schema));
|
|
1797
|
+
}
|
|
1798
|
+
const circular = /* @__PURE__ */ new Set();
|
|
1799
|
+
for (const start of graph.keys()) {
|
|
1800
|
+
const visited = /* @__PURE__ */ new Set();
|
|
1801
|
+
const stack = [...graph.get(start) ?? []];
|
|
1802
|
+
while (stack.length > 0) {
|
|
1803
|
+
const node = stack.pop();
|
|
1804
|
+
if (node === start) {
|
|
1805
|
+
circular.add(start);
|
|
1806
|
+
break;
|
|
1807
|
+
}
|
|
1808
|
+
if (visited.has(node)) continue;
|
|
1809
|
+
visited.add(node);
|
|
1810
|
+
const next = graph.get(node);
|
|
1811
|
+
if (next) for (const r of next) stack.push(r);
|
|
1812
|
+
}
|
|
1813
|
+
}
|
|
1814
|
+
return circular;
|
|
1815
|
+
});
|
|
1816
|
+
/**
|
|
1817
|
+
* Identifies all schemas that participate in circular dependency chains, including direct self-loops.
|
|
1818
|
+
*
|
|
1819
|
+
* Returns a Set of schema names with circular dependencies. Use this to wrap recursive schema positions
|
|
1820
|
+
* in deferred constructs (lazy getter, `z.lazy(() => …)`) to prevent infinite recursion when generated code runs.
|
|
1821
|
+
* Refs are followed by name only, keeping the algorithm linear in the schema graph size.
|
|
1822
|
+
*
|
|
1823
|
+
* @note Call this once on the full schema graph, then use `containsCircularRef()` to check individual schemas.
|
|
1824
|
+
*/
|
|
1825
|
+
function findCircularSchemas(schemas) {
|
|
1826
|
+
if (schemas.length === 0) return EMPTY_CIRCULAR_SET;
|
|
1827
|
+
return findCircularSchemasMemo(schemas);
|
|
1828
|
+
}
|
|
1829
|
+
/**
|
|
1830
|
+
* Type guard returning `true` when a schema or anything nested within it contains a ref to a circular schema.
|
|
1831
|
+
*
|
|
1832
|
+
* Use `excludeName` to ignore refs to specific schemas (useful when self-references are handled separately).
|
|
1833
|
+
* Commonly used with `findCircularSchemas()` to detect where lazy wrappers are needed in code generation.
|
|
1834
|
+
*
|
|
1835
|
+
* @note Returns `true` for the first matching circular ref found. Use for fast dependency checks.
|
|
1836
|
+
*/
|
|
1837
|
+
function containsCircularRef(node, { circularSchemas, excludeName }) {
|
|
1838
|
+
if (!node || circularSchemas.size === 0) return false;
|
|
1839
|
+
for (const _ of collectLazy(node, { schema(child) {
|
|
1840
|
+
if (child.type !== "ref") return null;
|
|
1841
|
+
const name = resolveRefName(child);
|
|
1842
|
+
return name && name !== excludeName && circularSchemas.has(name) ? true : null;
|
|
1843
|
+
} })) return true;
|
|
1844
|
+
return false;
|
|
1845
|
+
}
|
|
1846
|
+
//#endregion
|
|
1847
|
+
//#region src/utils/index.ts
|
|
1848
|
+
/**
|
|
1849
|
+
* Strips a single matching pair of `"..."`, `'...'`, or `` `...` `` from both ends of `text`.
|
|
1850
|
+
* Returns the string unchanged when no balanced quote pair is found.
|
|
1851
|
+
*
|
|
1852
|
+
* @example
|
|
1853
|
+
* ```ts
|
|
1854
|
+
* trimQuotes('"hello"') // 'hello'
|
|
1855
|
+
* trimQuotes('hello') // 'hello'
|
|
1856
|
+
* ```
|
|
1857
|
+
*/
|
|
1858
|
+
function trimQuotes(text) {
|
|
1859
|
+
if (text.length >= 2) {
|
|
1860
|
+
const first = text[0];
|
|
1861
|
+
const last = text[text.length - 1];
|
|
1862
|
+
if (first === "\"" && last === "\"" || first === "'" && last === "'" || first === "`" && last === "`") return text.slice(1, -1);
|
|
1863
|
+
}
|
|
1864
|
+
return text;
|
|
1865
|
+
}
|
|
1866
|
+
/**
|
|
1867
|
+
* Serializes a primitive value to a single-quoted string literal, stripping any surrounding quote
|
|
1868
|
+
* characters first. Escaping comes from `JSON.stringify`, then the quote style switches to single
|
|
1869
|
+
* quotes so generated code matches the repo style without a formatter.
|
|
1870
|
+
*
|
|
1871
|
+
* @example
|
|
1872
|
+
* ```ts
|
|
1873
|
+
* stringify('hello') // "'hello'"
|
|
1874
|
+
* stringify('"hello"') // "'hello'"
|
|
1875
|
+
* ```
|
|
1876
|
+
*/
|
|
1877
|
+
function stringify(value) {
|
|
1878
|
+
if (value === void 0 || value === null) return "''";
|
|
1879
|
+
return `'${JSON.stringify(trimQuotes(value.toString())).slice(1, -1).replace(/\\"/g, "\"").replace(/'/g, "\\'")}'`;
|
|
1880
|
+
}
|
|
1881
|
+
/**
|
|
1882
|
+
* Escapes characters that are not allowed inside JS string literals, covering quotes, backslashes,
|
|
1883
|
+
* and the Unicode line terminators U+2028 and U+2029.
|
|
1884
|
+
*
|
|
1885
|
+
* @see http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.4
|
|
1886
|
+
*
|
|
1887
|
+
* @example
|
|
1888
|
+
* ```ts
|
|
1889
|
+
* jsStringEscape('say "hi"\nbye') // 'say \\"hi\\"\\nbye'
|
|
1890
|
+
* ```
|
|
1891
|
+
*/
|
|
1892
|
+
function jsStringEscape(input) {
|
|
1893
|
+
return `${input}`.replace(/["'\\\n\r\u2028\u2029]/g, (character) => {
|
|
1894
|
+
switch (character) {
|
|
1895
|
+
case "\"":
|
|
1896
|
+
case "'":
|
|
1897
|
+
case "\\": return `\\${character}`;
|
|
1898
|
+
case "\n": return "\\n";
|
|
1899
|
+
case "\r": return "\\r";
|
|
1900
|
+
case "\u2028": return "\\u2028";
|
|
1901
|
+
case "\u2029": return "\\u2029";
|
|
1902
|
+
default: return "";
|
|
1903
|
+
}
|
|
1904
|
+
});
|
|
1905
|
+
}
|
|
1906
|
+
/**
|
|
1907
|
+
* Converts a pattern string into a `new RegExp(...)` constructor call or a regex literal string.
|
|
1908
|
+
* Inline flags expressed as a `^(?im)` prefix are extracted and applied to the resulting expression.
|
|
1909
|
+
* Pass `null` as the second argument to emit a `/pattern/flags` literal instead.
|
|
1910
|
+
*
|
|
1911
|
+
* @example
|
|
1912
|
+
* ```ts
|
|
1913
|
+
* toRegExpString('^(?im)foo') // 'new RegExp("^foo", "im")'
|
|
1914
|
+
* toRegExpString('^(?im)foo', null) // '/^foo/im'
|
|
1915
|
+
* ```
|
|
1916
|
+
*/
|
|
1917
|
+
function toRegExpString(text, func = "RegExp") {
|
|
1918
|
+
const raw = trimQuotes(text);
|
|
1919
|
+
const match = raw.match(/^\^(\(\?([igmsuy]+)\))/i);
|
|
1920
|
+
const replacementTarget = match?.[1] ?? "";
|
|
1921
|
+
const matchedFlags = match?.[2];
|
|
1922
|
+
const cleaned = raw.replace(/^\\?\//, "").replace(/\\?\/$/, "").replace(replacementTarget, "");
|
|
1923
|
+
const { source, flags } = new RegExp(cleaned, matchedFlags);
|
|
1924
|
+
if (func === null) return `/${source}/${flags}`;
|
|
1925
|
+
return `new ${func}(${JSON.stringify(source)}${flags ? `, ${JSON.stringify(flags)}` : ""})`;
|
|
1926
|
+
}
|
|
1927
|
+
/**
|
|
1928
|
+
* Renders a plain object as multi-line `key: value` source for embedding in generated code. Nested
|
|
1929
|
+
* objects recurse with fixed indentation, so the result drops straight into an object literal
|
|
1930
|
+
* without re-parsing.
|
|
1931
|
+
*
|
|
1932
|
+
* @example
|
|
1933
|
+
* ```ts
|
|
1934
|
+
* stringifyObject({ foo: 'bar', nested: { a: 1 } })
|
|
1935
|
+
* // 'foo: bar,\nnested: {\n a: 1\n }'
|
|
1936
|
+
* ```
|
|
1937
|
+
*/
|
|
1938
|
+
function stringifyObject(value) {
|
|
1939
|
+
return Object.entries(value).map(([key, val]) => {
|
|
1940
|
+
if (val !== null && typeof val === "object") return `${key}: {\n ${stringifyObject(val)}\n }`;
|
|
1941
|
+
return `${key}: ${val}`;
|
|
1942
|
+
}).filter(Boolean).join(",\n");
|
|
1943
|
+
}
|
|
1944
|
+
/**
|
|
1945
|
+
* Renders a dotted path or string array as an optional-chaining accessor expression rooted at
|
|
1946
|
+
* `accessor`. Returns `null` for an empty path.
|
|
1947
|
+
*
|
|
1948
|
+
* @example
|
|
1949
|
+
* ```ts
|
|
1950
|
+
* getNestedAccessor('pagination.next.id', 'lastPage')
|
|
1951
|
+
* // "lastPage?.['pagination']?.['next']?.['id']"
|
|
1952
|
+
* ```
|
|
1953
|
+
*/
|
|
1954
|
+
function getNestedAccessor(param, accessor) {
|
|
1955
|
+
const parts = Array.isArray(param) ? param : param.split(".");
|
|
1956
|
+
if (parts.length === 0 || parts.length === 1 && parts[0] === "") return null;
|
|
1957
|
+
return `${accessor}?.['${`${parts.join("']?.['")}']`}`;
|
|
1958
|
+
}
|
|
1959
|
+
/**
|
|
1960
|
+
* Builds a JSDoc comment block from an array of lines, returning `fallback` when there are no
|
|
1961
|
+
* comments so callers always get a usable string.
|
|
1962
|
+
*
|
|
1963
|
+
* @example
|
|
1964
|
+
* ```ts
|
|
1965
|
+
* buildJSDoc(['@type string', '@example hello'])
|
|
1966
|
+
* // '/**\n * @type string\n * @example hello\n *\/\n '
|
|
1967
|
+
* ```
|
|
1968
|
+
*/
|
|
1969
|
+
function buildJSDoc(comments, options = {}) {
|
|
1970
|
+
const { indent = " * ", suffix = "\n ", fallback = " " } = options;
|
|
1971
|
+
if (comments.length === 0) return fallback;
|
|
1972
|
+
return `/**\n${comments.map((c) => `${indent}${c}`).join("\n")}\n */${suffix}`;
|
|
1973
|
+
}
|
|
1974
|
+
/**
|
|
1975
|
+
* Indents every non-empty line of `text` by one indent level, leaving blank lines empty.
|
|
1976
|
+
*/
|
|
1977
|
+
function indentLines(text) {
|
|
1978
|
+
if (!text) return "";
|
|
1979
|
+
return text.split("\n").map((line) => line.trim() ? `${INDENT}${line}` : "").join("\n");
|
|
1980
|
+
}
|
|
1981
|
+
/**
|
|
1982
|
+
* Renders an object key, quoting it with single quotes only when it is not a valid identifier.
|
|
1983
|
+
* Reserved words and globals (`name`, `class`, …) are valid bare keys and stay unquoted.
|
|
1984
|
+
*
|
|
1985
|
+
* @example
|
|
1986
|
+
* ```ts
|
|
1987
|
+
* objectKey('name') // 'name'
|
|
1988
|
+
* objectKey('x-total') // "'x-total'"
|
|
1989
|
+
* ```
|
|
1990
|
+
*/
|
|
1991
|
+
function objectKey(name) {
|
|
1992
|
+
return isIdentifier(name) ? name : singleQuote(name);
|
|
1993
|
+
}
|
|
1994
|
+
/**
|
|
1995
|
+
* Assembles a multi-line object literal from already-rendered `entries`, indenting each entry one
|
|
1996
|
+
* level and closing the brace at column zero. Nested objects built the same way indent cumulatively,
|
|
1997
|
+
* so callers never re-parse the generated code. A trailing comma is added per entry to match the
|
|
1998
|
+
* formatter's multi-line style.
|
|
1999
|
+
*
|
|
2000
|
+
* @example
|
|
2001
|
+
* ```ts
|
|
2002
|
+
* buildObject(['id: z.number()', 'name: z.string()'])
|
|
2003
|
+
* // '{\n id: z.number(),\n name: z.string(),\n}'
|
|
2004
|
+
* ```
|
|
2005
|
+
*/
|
|
2006
|
+
function buildObject(entries) {
|
|
2007
|
+
if (entries.length === 0) return "{}";
|
|
2008
|
+
return `{\n${entries.map((entry) => `${indentLines(entry)},`).join("\n")}\n}`;
|
|
2009
|
+
}
|
|
2010
|
+
/**
|
|
2011
|
+
* Assembles a bracketed list (array by default) from already-rendered `items`. Keeps everything on
|
|
2012
|
+
* one line when no item spans multiple lines, and otherwise puts each item on its own line, indented
|
|
2013
|
+
* one level with a trailing comma and the closing bracket at column zero. Use it for `z.union([…])`,
|
|
2014
|
+
* `z.array([…])`, and similar member lists so objects inside them nest correctly.
|
|
2015
|
+
*
|
|
2016
|
+
* @example
|
|
2017
|
+
* ```ts
|
|
2018
|
+
* buildList(['z.string()', 'z.number()'])
|
|
2019
|
+
* // '[z.string(), z.number()]'
|
|
2020
|
+
* ```
|
|
2021
|
+
*/
|
|
2022
|
+
function buildList(items, brackets = ["[", "]"]) {
|
|
2023
|
+
const [open, close] = brackets;
|
|
2024
|
+
if (items.length === 0) return `${open}${close}`;
|
|
2025
|
+
if (!items.some((item) => item.includes("\n"))) return `${open}${items.join(", ")}${close}`;
|
|
2026
|
+
return `${open}\n${items.map((item) => `${indentLines(item)},`).join("\n")}\n${close}`;
|
|
2027
|
+
}
|
|
2028
|
+
/**
|
|
2029
|
+
* Returns the last path segment of a reference string.
|
|
2030
|
+
*
|
|
2031
|
+
* @example
|
|
2032
|
+
* ```ts
|
|
2033
|
+
* extractRefName('#/components/schemas/Pet') // 'Pet'
|
|
2034
|
+
* ```
|
|
2035
|
+
*/
|
|
2036
|
+
function extractRefName(ref) {
|
|
2037
|
+
return ref.split("/").at(-1) ?? ref;
|
|
2038
|
+
}
|
|
2039
|
+
/**
|
|
2040
|
+
* Builds a PascalCase child schema name by joining a parent name and property name.
|
|
2041
|
+
* Returns `null` when there is no parent to nest under.
|
|
2042
|
+
*
|
|
2043
|
+
* @example
|
|
2044
|
+
* ```ts
|
|
2045
|
+
* childName('Order', 'shipping_address') // 'OrderShippingAddress'
|
|
2046
|
+
* childName(undefined, 'params') // null
|
|
2047
|
+
* ```
|
|
2048
|
+
*/
|
|
2049
|
+
function childName(parentName, propName) {
|
|
2050
|
+
return parentName ? pascalCase([parentName, propName].join(" ")) : null;
|
|
2051
|
+
}
|
|
2052
|
+
/**
|
|
2053
|
+
* Builds a PascalCase enum name from the parent name, property name, and a suffix, skipping any
|
|
2054
|
+
* empty parts.
|
|
2055
|
+
*
|
|
2056
|
+
* @example
|
|
2057
|
+
* ```ts
|
|
2058
|
+
* enumPropName('Order', 'status', 'enum') // 'OrderStatusEnum'
|
|
2059
|
+
* ```
|
|
2060
|
+
*/
|
|
2061
|
+
function enumPropName(parentName, propName, enumSuffix) {
|
|
2062
|
+
return pascalCase([
|
|
2063
|
+
parentName,
|
|
2064
|
+
propName,
|
|
2065
|
+
enumSuffix
|
|
2066
|
+
].filter(Boolean).join(" "));
|
|
2067
|
+
}
|
|
2068
|
+
/**
|
|
2069
|
+
* Returns the discriminator key whose mapping value matches `ref`, or `null` when there is no match.
|
|
2070
|
+
*
|
|
2071
|
+
* @example
|
|
2072
|
+
* ```ts
|
|
2073
|
+
* findDiscriminator({ dog: '#/components/schemas/Dog' }, '#/components/schemas/Dog') // 'dog'
|
|
2074
|
+
* ```
|
|
2075
|
+
*/
|
|
2076
|
+
function findDiscriminator(mapping, ref) {
|
|
2077
|
+
if (!mapping || !ref) return null;
|
|
2078
|
+
return Object.entries(mapping).find(([, value]) => value === ref)?.[0] ?? null;
|
|
2079
|
+
}
|
|
2080
|
+
/**
|
|
2081
|
+
* Derives a {@link ParamGroupType} for a query or header group from the resolver.
|
|
2082
|
+
*
|
|
2083
|
+
* Returns `null` when there is no resolver, no params, or the group name equals the
|
|
2084
|
+
* individual param name (so there is no real group to emit).
|
|
2085
|
+
*/
|
|
2086
|
+
function resolveGroupType({ node, params, group, resolver }) {
|
|
2087
|
+
if (!resolver || !params.length) return null;
|
|
2088
|
+
const firstParam = params[0];
|
|
2089
|
+
const groupName = (group === "query" ? resolver.resolveQueryParamsName : resolver.resolveHeaderParamsName).call(resolver, node, firstParam);
|
|
2090
|
+
if (groupName === resolver.resolveParamName(node, firstParam)) return null;
|
|
2091
|
+
return {
|
|
2092
|
+
type: groupName,
|
|
2093
|
+
optional: params.every((p) => !p.required)
|
|
2094
|
+
};
|
|
2095
|
+
}
|
|
2096
|
+
//#endregion
|
|
2097
|
+
export { contentDef as $, collect as A, isValidVarName as At, createOperation as B, containsCircularRef as C, functionParametersDef as Ct, isStringType as D, isHttpOperationNode as Dt, findCircularSchemas as E, typeLiteralDef as Et, responseDef as F, httpMethods as Ft, inputDef as G, createRequestBody as H, createParameter as I, isScalarPrimitive as It, createSource as J, createExport as K, parameterDef as L, schemaTypes as Lt, transform as M, schemaDef as Mt, walk as N, defineNode as Nt, resolveParamType as O, narrowSchema as Ot, createResponse as P, syncOptionality as Pt, sourceDef as Q, createOutput as R, combineSources as S, functionParameterDef as St, createOperationParams as T, objectBindingPatternDef as Tt, requestBodyDef as U, operationDef as V, createInput as W, fileDef as X, exportDef as Y, importDef as Z, buildTypeLiteral as _, createFunctionParameter as _t, enumPropName as a, createBreak as at, combineExports as b, createObjectBindingPattern as bt, getNestedAccessor as c, createJsx as ct, resolveGroupType as d, functionDef as dt, createContent as et, stringify as f, jsxDef as ft, buildGroupParam as g, propertyDef as gt, trimQuotes as h, createProperty as ht, childName as i, createArrowFunction as it, collectLazy as j, createSchema as jt, syncSchemaRef as k, extractStringsFromNodes as kt, jsStringEscape as l, createText as lt, toRegExpString as m, typeDef as mt, buildList as n, breakDef as nt, extractRefName as o, createConst as ot, stringifyObject as p, textDef as pt, createImport as q, buildObject as r, constDef as rt, findDiscriminator as s, createFunction as st, buildJSDoc as t, arrowFunctionDef as tt, objectKey as u, createType as ut, caseParams as v, createFunctionParameters as vt, createDiscriminantNode as w, indexedAccessTypeDef as wt, combineImports as x, createTypeLiteral as xt, collectUsedSchemaNames as y, createIndexedAccessType as yt, outputDef as z };
|
|
2098
|
+
|
|
2099
|
+
//# sourceMappingURL=utils-DN4XLVqz.js.map
|