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