@kubb/plugin-valibot 0.0.0-stage → 0.0.0
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/LICENSE +21 -0
- package/README.md +73 -2
- package/dist/index.cjs +2105 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +308 -0
- package/dist/index.d.ts +308 -0
- package/dist/index.js +2096 -0
- package/dist/index.js.map +1 -0
- package/docs/guides/coercion.md +52 -0
- package/docs/guides/customization.md +131 -0
- package/docs/guides/format-mappings.md +98 -0
- package/docs/guides/inferred-types.md +70 -0
- package/docs/options.md +215 -0
- package/docs/overview.md +70 -0
- package/kubb-extension.json +224 -0
- package/package.json +93 -3
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,2105 @@
|
|
|
1
|
+
Object.defineProperties(exports, {
|
|
2
|
+
__esModule: { value: true },
|
|
3
|
+
[Symbol.toStringTag]: { value: "Module" }
|
|
4
|
+
});
|
|
5
|
+
let _kubb_kit = require("@kubb/kit");
|
|
6
|
+
let _kubb_renderer_jsx = require("@kubb/renderer-jsx");
|
|
7
|
+
let _kubb_renderer_jsx_jsx_runtime = require("@kubb/renderer-jsx/jsx-runtime");
|
|
8
|
+
// ../../internals/utils/src/reserved.ts
|
|
9
|
+
/**
|
|
10
|
+
* JavaScript and Java reserved words.
|
|
11
|
+
* @link https://github.com/jonschlinkert/reserved/blob/master/index.js
|
|
12
|
+
*/
|
|
13
|
+
const reservedWords = /* @__PURE__ */ new Set([
|
|
14
|
+
"abstract",
|
|
15
|
+
"arguments",
|
|
16
|
+
"await",
|
|
17
|
+
"boolean",
|
|
18
|
+
"break",
|
|
19
|
+
"byte",
|
|
20
|
+
"case",
|
|
21
|
+
"catch",
|
|
22
|
+
"char",
|
|
23
|
+
"class",
|
|
24
|
+
"const",
|
|
25
|
+
"continue",
|
|
26
|
+
"debugger",
|
|
27
|
+
"default",
|
|
28
|
+
"delete",
|
|
29
|
+
"do",
|
|
30
|
+
"double",
|
|
31
|
+
"else",
|
|
32
|
+
"enum",
|
|
33
|
+
"eval",
|
|
34
|
+
"export",
|
|
35
|
+
"extends",
|
|
36
|
+
"false",
|
|
37
|
+
"final",
|
|
38
|
+
"finally",
|
|
39
|
+
"float",
|
|
40
|
+
"for",
|
|
41
|
+
"function",
|
|
42
|
+
"goto",
|
|
43
|
+
"if",
|
|
44
|
+
"implements",
|
|
45
|
+
"import",
|
|
46
|
+
"in",
|
|
47
|
+
"instanceof",
|
|
48
|
+
"int",
|
|
49
|
+
"interface",
|
|
50
|
+
"let",
|
|
51
|
+
"long",
|
|
52
|
+
"native",
|
|
53
|
+
"new",
|
|
54
|
+
"null",
|
|
55
|
+
"package",
|
|
56
|
+
"private",
|
|
57
|
+
"protected",
|
|
58
|
+
"public",
|
|
59
|
+
"return",
|
|
60
|
+
"short",
|
|
61
|
+
"static",
|
|
62
|
+
"super",
|
|
63
|
+
"switch",
|
|
64
|
+
"synchronized",
|
|
65
|
+
"this",
|
|
66
|
+
"throw",
|
|
67
|
+
"throws",
|
|
68
|
+
"transient",
|
|
69
|
+
"true",
|
|
70
|
+
"try",
|
|
71
|
+
"typeof",
|
|
72
|
+
"var",
|
|
73
|
+
"void",
|
|
74
|
+
"volatile",
|
|
75
|
+
"while",
|
|
76
|
+
"with",
|
|
77
|
+
"yield",
|
|
78
|
+
"Array",
|
|
79
|
+
"Date",
|
|
80
|
+
"hasOwnProperty",
|
|
81
|
+
"Infinity",
|
|
82
|
+
"isFinite",
|
|
83
|
+
"isNaN",
|
|
84
|
+
"isPrototypeOf",
|
|
85
|
+
"length",
|
|
86
|
+
"Math",
|
|
87
|
+
"name",
|
|
88
|
+
"NaN",
|
|
89
|
+
"Number",
|
|
90
|
+
"Object",
|
|
91
|
+
"prototype",
|
|
92
|
+
"String",
|
|
93
|
+
"toString",
|
|
94
|
+
"undefined",
|
|
95
|
+
"valueOf"
|
|
96
|
+
]);
|
|
97
|
+
/**
|
|
98
|
+
* Returns `true` when `name` is a syntactically valid JavaScript variable name.
|
|
99
|
+
*
|
|
100
|
+
* @example
|
|
101
|
+
* ```ts
|
|
102
|
+
* isValidVarName('status') // true
|
|
103
|
+
* isValidVarName('class') // false (reserved word)
|
|
104
|
+
* isValidVarName('42foo') // false (starts with digit)
|
|
105
|
+
* ```
|
|
106
|
+
*/
|
|
107
|
+
function isValidVarName(name) {
|
|
108
|
+
if (!name || reservedWords.has(name)) return false;
|
|
109
|
+
return isIdentifier(name);
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Returns `name` when it's a syntactically valid JavaScript variable name,
|
|
113
|
+
* otherwise prefixes it with `_` so the result is a valid identifier.
|
|
114
|
+
*
|
|
115
|
+
* Useful for sanitizing OpenAPI schema names or operation IDs that start with
|
|
116
|
+
* a digit (e.g. `409`, `504AccountCancel`) before using them as exported
|
|
117
|
+
* variable, type, or function names.
|
|
118
|
+
*
|
|
119
|
+
* @example
|
|
120
|
+
* ```ts
|
|
121
|
+
* ensureValidVarName('409') // '_409'
|
|
122
|
+
* ensureValidVarName('504AccountCancel') // '_504AccountCancel'
|
|
123
|
+
* ensureValidVarName('Pet') // 'Pet'
|
|
124
|
+
* ensureValidVarName('class') // '_class'
|
|
125
|
+
* ```
|
|
126
|
+
*/
|
|
127
|
+
function ensureValidVarName(name) {
|
|
128
|
+
if (!name || isValidVarName(name)) return name;
|
|
129
|
+
return `_${name}`;
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Returns `true` when `name` is syntactically a valid identifier, ignoring reserved words.
|
|
133
|
+
*
|
|
134
|
+
* Reserved words and globals (`class`, `name`, `Date`, …) are valid as bare object-literal keys
|
|
135
|
+
* even though they are not valid variable names, so use this (not {@link isValidVarName}) when
|
|
136
|
+
* deciding whether an object key needs quoting.
|
|
137
|
+
*
|
|
138
|
+
* @example
|
|
139
|
+
* ```ts
|
|
140
|
+
* isIdentifier('name') // true
|
|
141
|
+
* isIdentifier('x-total')// false
|
|
142
|
+
* ```
|
|
143
|
+
*/
|
|
144
|
+
function isIdentifier(name) {
|
|
145
|
+
return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name);
|
|
146
|
+
}
|
|
147
|
+
// ../../internals/utils/src/codegen.ts
|
|
148
|
+
/**
|
|
149
|
+
* Assembles a multi-line object literal from already-rendered `entries`, indenting each entry one
|
|
150
|
+
* level and closing the brace at column zero. Entries that are themselves multi-line objects indent
|
|
151
|
+
* cumulatively. Each entry ends with a trailing comma to match the formatter's multi-line style.
|
|
152
|
+
*
|
|
153
|
+
* @example
|
|
154
|
+
* ```ts
|
|
155
|
+
* buildObject(['id: z.number()', 'name: z.string()'])
|
|
156
|
+
* // '{\n id: z.number(),\n name: z.string(),\n}'
|
|
157
|
+
* ```
|
|
158
|
+
*/
|
|
159
|
+
function buildObject(entries) {
|
|
160
|
+
if (entries.length === 0) return "{}";
|
|
161
|
+
return `{\n${entries.map((entry) => `${_kubb_kit.text.indent({ text: entry })},`).join("\n")}\n}`;
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Assembles a bracketed list (array by default) from already-rendered `items`. Keeps everything on
|
|
165
|
+
* one line when no item spans multiple lines, and otherwise puts each item on its own line, indented
|
|
166
|
+
* one level with a trailing comma and the closing bracket at column zero. Used for member lists such
|
|
167
|
+
* as `z.union([…])` and `z.array([…])`.
|
|
168
|
+
*
|
|
169
|
+
* @example
|
|
170
|
+
* ```ts
|
|
171
|
+
* buildList(['z.string()', 'z.number()'])
|
|
172
|
+
* // '[z.string(), z.number()]'
|
|
173
|
+
* ```
|
|
174
|
+
*/
|
|
175
|
+
function buildList(items, brackets = ["[", "]"]) {
|
|
176
|
+
const [open, close] = brackets;
|
|
177
|
+
if (items.length === 0) return `${open}${close}`;
|
|
178
|
+
if (!items.some((item) => item.includes("\n"))) return `${open}${items.join(", ")}${close}`;
|
|
179
|
+
return `${open}\n${items.map((item) => `${_kubb_kit.text.indent({ text: item })},`).join("\n")}\n${close}`;
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* An object key, quoted only when it is not identifier-shaped. Reserved words such as `class` stay bare.
|
|
183
|
+
*
|
|
184
|
+
* @example
|
|
185
|
+
* ```ts
|
|
186
|
+
* objectKey('x-total') // "'x-total'"
|
|
187
|
+
* ```
|
|
188
|
+
*/
|
|
189
|
+
function objectKey(name) {
|
|
190
|
+
return isIdentifier(name) ? name : _kubb_kit.text.quote(name);
|
|
191
|
+
}
|
|
192
|
+
// ../../internals/utils/src/fs.ts
|
|
193
|
+
/**
|
|
194
|
+
* Builds a nested file path from a dotted name. Splits on dots that precede a letter
|
|
195
|
+
* (so version numbers embedded in operationIds like `v2025.0` stay intact), camelCases
|
|
196
|
+
* every earlier segment, applies `caseLast` to the final segment, and joins with `/`.
|
|
197
|
+
*
|
|
198
|
+
* Empty segments are dropped before joining. They arise when the name starts with a dot
|
|
199
|
+
* followed by a letter (e.g. `..Schema` splits into `['..', 'Schema']` and `'..'` cases to
|
|
200
|
+
* an empty string). Without this a leading `/` would form, which `path.resolve` reads as an
|
|
201
|
+
* absolute path, letting generated files escape the configured output directory.
|
|
202
|
+
*
|
|
203
|
+
* @example Nested path from a dotted name
|
|
204
|
+
* `toFilePath('pet.petId') // 'pet/petId'`
|
|
205
|
+
*
|
|
206
|
+
* @example PascalCase the final segment
|
|
207
|
+
* `toFilePath('pet.Pet', pascalCase) // 'pet/Pet'`
|
|
208
|
+
*
|
|
209
|
+
* @example Suffix applied to the final segment only
|
|
210
|
+
* `toFilePath('tag.tag', (part) => camelCase(part, { suffix: 'schema' })) // 'tag/tagSchema'`
|
|
211
|
+
*/
|
|
212
|
+
function toFilePath(name, caseLast = _kubb_kit.casing.camel) {
|
|
213
|
+
const parts = name.split(/\.(?=[a-zA-Z])/);
|
|
214
|
+
return parts.map((part, i) => i === parts.length - 1 ? caseLast(part) : _kubb_kit.casing.camel(part)).filter(Boolean).join("/");
|
|
215
|
+
}
|
|
216
|
+
// ../../internals/utils/src/strings.ts
|
|
217
|
+
const NEEDS_UNICODE = /(?<!\\)(?:\\\\)*\\[pPu]\{|[\u{10000}-\u{10FFFF}]/u;
|
|
218
|
+
const KEPT_ESCAPE = /[A-Za-z0-9^$\\.*+?()[\]{}|/]/;
|
|
219
|
+
/**
|
|
220
|
+
* Drops the backslash from escapes that the `u` flag rejects: an escaped punctuation character that is
|
|
221
|
+
* not a syntax character, and `\-` outside a class. Both match the same character without the backslash.
|
|
222
|
+
*/
|
|
223
|
+
function dropIdentityEscapes(pattern) {
|
|
224
|
+
let inClass = false;
|
|
225
|
+
return pattern.replace(/\\(.)|[[\]]/gs, (match, escaped) => {
|
|
226
|
+
if (escaped === void 0) {
|
|
227
|
+
inClass = match === "[";
|
|
228
|
+
return match;
|
|
229
|
+
}
|
|
230
|
+
return KEPT_ESCAPE.test(escaped) || escaped === "-" && inClass ? match : escaped;
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
/**
|
|
234
|
+
* Builds the `RegExp` for a pattern, adding the `u` flag when it uses `\p{...}`, `\P{...}` or `\u{...}`, or
|
|
235
|
+
* holds a character outside the BMP. A pattern that is not valid under `u` keeps the flags it came with.
|
|
236
|
+
*/
|
|
237
|
+
function toRegExp(pattern, flags) {
|
|
238
|
+
if (flags?.includes("u") || !NEEDS_UNICODE.test(pattern)) return new RegExp(pattern, flags);
|
|
239
|
+
try {
|
|
240
|
+
return new RegExp(dropIdentityEscapes(pattern), `${flags ?? ""}u`);
|
|
241
|
+
} catch {
|
|
242
|
+
return new RegExp(pattern, flags);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* Converts a pattern string into a `new RegExp(...)` constructor call or a regex literal string.
|
|
247
|
+
* Inline flags expressed as a `^(?im)` prefix are extracted and applied to the resulting expression.
|
|
248
|
+
* Pass `null` as the second argument to emit a `/pattern/flags` literal instead.
|
|
249
|
+
*
|
|
250
|
+
* @example
|
|
251
|
+
* ```ts
|
|
252
|
+
* toRegExpString('^(?im)foo') // 'new RegExp("^foo", "im")'
|
|
253
|
+
* toRegExpString('^(?im)foo', null) // '/^foo/im'
|
|
254
|
+
* ```
|
|
255
|
+
*/
|
|
256
|
+
function toRegExpString(pattern, func = "RegExp") {
|
|
257
|
+
const raw = _kubb_kit.text.unquote(pattern);
|
|
258
|
+
const match = raw.match(/^\^(\(\?([igmsuy]+)\))/i);
|
|
259
|
+
const replacementTarget = match?.[1] ?? "";
|
|
260
|
+
const matchedFlags = match?.[2];
|
|
261
|
+
const { source, flags } = toRegExp(raw.replace(/^\\?\//, "").replace(/\\?\/$/, "").replace(replacementTarget, ""), matchedFlags);
|
|
262
|
+
if (func === null) return `/${source}/${flags}`;
|
|
263
|
+
return `new ${func}(${JSON.stringify(source)}${flags ? `, ${JSON.stringify(flags)}` : ""})`;
|
|
264
|
+
}
|
|
265
|
+
/**
|
|
266
|
+
* Escapes an `@` at the start of a line, so a multi-line description can't start a new JSDoc tag.
|
|
267
|
+
* Editors render `\@` as `@` in hovers.
|
|
268
|
+
*
|
|
269
|
+
* @example
|
|
270
|
+
* ```ts
|
|
271
|
+
* jsDocEscape('intro\n@example value') // 'intro\n\\@example value'
|
|
272
|
+
* ```
|
|
273
|
+
*/
|
|
274
|
+
function jsDocEscape(input) {
|
|
275
|
+
return `${input}`.replace(/^(\s*)@/gm, "$1\\@");
|
|
276
|
+
}
|
|
277
|
+
// ../../internals/shared/src/operation.ts
|
|
278
|
+
/**
|
|
279
|
+
* Builds the `ResolverFileParams` every operation generator passes to
|
|
280
|
+
* `resolver.file`: a file named `name`, tagged by the operation's first
|
|
281
|
+
* tag (or `'default'`), at the operation's path. Centralizes the entry object
|
|
282
|
+
* that was repeated at dozens of call sites across the client and query plugins.
|
|
283
|
+
*
|
|
284
|
+
* @example
|
|
285
|
+
* ```ts
|
|
286
|
+
* resolver.file(operationFileEntry(node, node.operationId), { root, output, group })
|
|
287
|
+
* ```
|
|
288
|
+
*/
|
|
289
|
+
function operationFileEntry(node, name, extname = ".ts") {
|
|
290
|
+
return {
|
|
291
|
+
name,
|
|
292
|
+
extname,
|
|
293
|
+
tag: node.tags[0] ?? "default",
|
|
294
|
+
path: node.path
|
|
295
|
+
};
|
|
296
|
+
}
|
|
297
|
+
/**
|
|
298
|
+
* Resolves the file a schema-emitting plugin (`plugin-ts`, `plugin-zod`, `plugin-faker`) writes
|
|
299
|
+
* `node` to, cached in `ctx.memo` under the resolver's plugin name and the
|
|
300
|
+
* operation. The plugin itself and every plugin that imports from it call this, so they all get
|
|
301
|
+
* the same path.
|
|
302
|
+
*
|
|
303
|
+
* When that path matches the file of a component schema in `ctx.schemas`, ignoring case, the file name
|
|
304
|
+
* gets an `Operation` suffix: operation `point` goes to `PointOperation.ts` next to schema `Point.ts`.
|
|
305
|
+
* Otherwise the two merge into one file, or overwrite each other on a case-insensitive file system.
|
|
306
|
+
* Only the file name changes. The declarations keep their names.
|
|
307
|
+
*
|
|
308
|
+
* @example Resolve `plugin-ts`'s file for the current operation
|
|
309
|
+
* ```ts
|
|
310
|
+
* const fileTs = resolveOperationFile({ ctx, node, resolver: tsResolver, root, output })
|
|
311
|
+
* ```
|
|
312
|
+
*/
|
|
313
|
+
function resolveOperationFile(options) {
|
|
314
|
+
const { ctx, node, resolver, root, output } = options;
|
|
315
|
+
const { memo } = ctx;
|
|
316
|
+
const location = {
|
|
317
|
+
root,
|
|
318
|
+
output,
|
|
319
|
+
group: options.group ?? void 0
|
|
320
|
+
};
|
|
321
|
+
return memo(`${resolver.pluginName}:operationFile:${node.operationId}`, () => {
|
|
322
|
+
const schemaPaths = memo(`${resolver.pluginName}:schemaFilePaths`, () => new Set(ctx.schemas.flatMap((schema) => schema.name ? [resolver.file({
|
|
323
|
+
name: schema.name,
|
|
324
|
+
extname: ".ts",
|
|
325
|
+
...location
|
|
326
|
+
}).path.toLowerCase()] : [])));
|
|
327
|
+
let file = resolver.file({
|
|
328
|
+
...operationFileEntry(node, node.operationId),
|
|
329
|
+
...location
|
|
330
|
+
});
|
|
331
|
+
for (let name = `${node.operationId}Operation`; schemaPaths.has(file.path.toLowerCase()); name += "Operation") {
|
|
332
|
+
const next = resolver.file({
|
|
333
|
+
...operationFileEntry(node, name),
|
|
334
|
+
...location
|
|
335
|
+
});
|
|
336
|
+
if (next.path === file.path) break;
|
|
337
|
+
file = next;
|
|
338
|
+
}
|
|
339
|
+
return file;
|
|
340
|
+
});
|
|
341
|
+
}
|
|
342
|
+
/**
|
|
343
|
+
* How a content entry is framed as a stream: `'events'` for Server-Sent Events, `'lines'` for JSON Lines.
|
|
344
|
+
*/
|
|
345
|
+
function getStreamFraming(entry) {
|
|
346
|
+
if (_kubb_kit.ast.mediaType.getBase(entry) === "text/event-stream") return "events";
|
|
347
|
+
return entry.stream && _kubb_kit.ast.mediaType.isStream(entry) ? "lines" : void 0;
|
|
348
|
+
}
|
|
349
|
+
/**
|
|
350
|
+
* Parser for one response content entry.
|
|
351
|
+
*
|
|
352
|
+
* JSON stays unset so the runtime detects it. `text/event-stream` and JSON Lines are streams. A binary schema
|
|
353
|
+
* (`format: binary` / `contentMediaType`) is a blob even when the media type is not a well-known
|
|
354
|
+
* binary type. Other `text/*` is text, and `application/octet-stream`, `application/pdf`,
|
|
355
|
+
* `image/*`, `audio/*`, and `video/*` are blobs.
|
|
356
|
+
*/
|
|
357
|
+
function responseTypeForContent(entry) {
|
|
358
|
+
const baseType = _kubb_kit.ast.mediaType.getBase(entry);
|
|
359
|
+
if (!baseType) return void 0;
|
|
360
|
+
if (getStreamFraming(entry)) return "stream";
|
|
361
|
+
if (_kubb_kit.ast.mediaType.isJson(baseType)) return void 0;
|
|
362
|
+
if (entry.schema?.type === "blob") return "blob";
|
|
363
|
+
if (baseType.startsWith("text/")) return "text";
|
|
364
|
+
if (isBinaryContentType(baseType)) return "blob";
|
|
365
|
+
}
|
|
366
|
+
function isBinaryContentType(baseType) {
|
|
367
|
+
return baseType === "application/octet-stream" || baseType === "application/pdf" || /^(image|audio|video)\//.test(baseType);
|
|
368
|
+
}
|
|
369
|
+
/**
|
|
370
|
+
* Maps a content type to the PascalCase suffix used to name per-content-type variants
|
|
371
|
+
* (e.g. `application/json` → `Json`, `application/xml` → `Xml`, `multipart/form-data` → `FormData`).
|
|
372
|
+
*/
|
|
373
|
+
function getContentTypeSuffix(contentType) {
|
|
374
|
+
const baseType = contentType.split(";")[0].trim();
|
|
375
|
+
if (baseType === "application/json") return "Json";
|
|
376
|
+
if (baseType === "multipart/form-data") return "FormData";
|
|
377
|
+
if (baseType === "application/x-www-form-urlencoded") return "FormUrlEncoded";
|
|
378
|
+
const parts = (baseType.split("/").pop() ?? baseType).split(/[^a-zA-Z0-9]+/).filter(Boolean);
|
|
379
|
+
if (parts.length === 0) return "Unknown";
|
|
380
|
+
return parts.map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
|
|
381
|
+
}
|
|
382
|
+
/**
|
|
383
|
+
* Appends a content-type suffix to a base name, keeping a trailing `Data` segment last
|
|
384
|
+
* (e.g. `AddPetData` + `Json` → `AddPetJsonData`, `AddPetStatus200` + `Xml` → `AddPetStatus200Xml`).
|
|
385
|
+
*/
|
|
386
|
+
function getPerContentTypeName(baseName, suffix) {
|
|
387
|
+
if (baseName.endsWith("Data")) return suffix.endsWith("Data") ? baseName.slice(0, -4) + suffix : `${baseName.slice(0, -4)}${suffix}Data`;
|
|
388
|
+
return baseName + suffix;
|
|
389
|
+
}
|
|
390
|
+
/**
|
|
391
|
+
* Returns the entry with the schema of the value the client returns: `string` for a body read as text, such as `Pet` on
|
|
392
|
+
* `application/xml`, and `blob` for `image/*`, `audio/*`, `video/*`, PDF, and octet-stream. A binary schema elsewhere is a `Blob`
|
|
393
|
+
* only through `parseAs: 'blob'`, which needs every entry in `entries` binary. JSON, vendor (`application/vnd.*`), stream,
|
|
394
|
+
* schemaless, and wildcard entries keep their schema. `entries` is the response's full list of content types.
|
|
395
|
+
*/
|
|
396
|
+
function toResponseContent(entry, entries = [entry]) {
|
|
397
|
+
const { contentType, schema } = entry;
|
|
398
|
+
if (!schema || entry.stream) return entry;
|
|
399
|
+
const baseType = _kubb_kit.ast.mediaType.getBase(contentType);
|
|
400
|
+
const resolved = _kubb_kit.ast.ref.getSchema(schema);
|
|
401
|
+
if (isBinaryContentType(baseType)) return resolved.type === "blob" ? entry : {
|
|
402
|
+
...entry,
|
|
403
|
+
schema: _kubb_kit.ast.factory.createSchema({ type: "blob" }),
|
|
404
|
+
keysToOmit: null
|
|
405
|
+
};
|
|
406
|
+
const isPlainMediaType = Boolean(baseType) && !_kubb_kit.ast.mediaType.isJson(baseType) && !baseType.includes("*");
|
|
407
|
+
if (resolved.type === "blob") return isPlainMediaType && !entries.every((item) => item.schema?.type === "blob") ? {
|
|
408
|
+
...entry,
|
|
409
|
+
schema: _kubb_kit.ast.factory.createSchema({ type: "string" }),
|
|
410
|
+
keysToOmit: null
|
|
411
|
+
} : entry;
|
|
412
|
+
if (resolved.primitive === "string") return entry;
|
|
413
|
+
const responseType = responseTypeForContent(entry);
|
|
414
|
+
if (responseType !== "text" && (resolved.type === "unknown" || resolved.type === "any" || resolved.type === "void")) return entry;
|
|
415
|
+
const isVendorJson = /^[^/]+\/vnd\./.test(baseType) && !/(xml|yaml|yml|csv)$/.test(baseType);
|
|
416
|
+
return responseType === "text" || !responseType && isPlainMediaType && !isVendorJson ? {
|
|
417
|
+
...entry,
|
|
418
|
+
schema: _kubb_kit.ast.factory.createSchema({ type: "string" }),
|
|
419
|
+
keysToOmit: null
|
|
420
|
+
} : entry;
|
|
421
|
+
}
|
|
422
|
+
/**
|
|
423
|
+
* Resolves per-content-type variant names for a set of content entries, deduplicating suffix
|
|
424
|
+
* collisions with a numeric counter. Entries without a schema are skipped. The returned `suffix` is
|
|
425
|
+
* the final (possibly counter-augmented) value, so callers can derive parallel names in another
|
|
426
|
+
* namespace (e.g. plugin-faker deriving the matching plugin-ts type name).
|
|
427
|
+
*/
|
|
428
|
+
function resolveContentTypeVariants(entries, baseName) {
|
|
429
|
+
const usedNames = /* @__PURE__ */ new Set();
|
|
430
|
+
return entries.filter((entry) => entry.schema).map((entry) => {
|
|
431
|
+
const baseSuffix = getContentTypeSuffix(entry.contentType);
|
|
432
|
+
let suffix = baseSuffix;
|
|
433
|
+
let name = getPerContentTypeName(baseName, suffix);
|
|
434
|
+
let counter = 2;
|
|
435
|
+
while (usedNames.has(name)) {
|
|
436
|
+
suffix = `${baseSuffix}${counter++}`;
|
|
437
|
+
name = getPerContentTypeName(baseName, suffix);
|
|
438
|
+
}
|
|
439
|
+
usedNames.add(name);
|
|
440
|
+
return {
|
|
441
|
+
name,
|
|
442
|
+
suffix,
|
|
443
|
+
schema: entry.schema,
|
|
444
|
+
keysToOmit: entry.keysToOmit,
|
|
445
|
+
contentType: entry.contentType
|
|
446
|
+
};
|
|
447
|
+
});
|
|
448
|
+
}
|
|
449
|
+
/**
|
|
450
|
+
* Whether the operation declares more than one request media type with a schema, so a caller must pick one on `contentType`.
|
|
451
|
+
*/
|
|
452
|
+
function hasRequestContentTypeChoice(node) {
|
|
453
|
+
return (node.requestBody?.content ?? []).filter((entry) => entry.schema).length > 1;
|
|
454
|
+
}
|
|
455
|
+
/**
|
|
456
|
+
* Builds the combined `{ body, path, query, headers, cookies }` options object schema for an operation,
|
|
457
|
+
* referencing the already-resolved body and grouped param names. `cookies` appears only on an operation
|
|
458
|
+
* with a cookie parameter, and stays optional because a browser sends its cookies itself. Shared by `@kubb/plugin-ts`'s
|
|
459
|
+
* `Options` type and `@kubb/plugin-zod`'s inferred options schema, so both printers emit the same shape from the same inputs.
|
|
460
|
+
* `primitive: 'object'` is a no-op for the TS printer and tells the Zod printer to emit `z.object(…)` rather
|
|
461
|
+
* than a record.
|
|
462
|
+
*/
|
|
463
|
+
function buildOptionsSchema(node, resolver, { pairContentTypes = false } = {}) {
|
|
464
|
+
const { path, query, header, cookie } = _kubb_kit.ast.http.groupParameters(node);
|
|
465
|
+
const hasBody = Boolean(_kubb_kit.ast.http.requestBody.getSchema(node));
|
|
466
|
+
const createNever = () => _kubb_kit.ast.factory.createSchema({
|
|
467
|
+
type: "never",
|
|
468
|
+
primitive: void 0,
|
|
469
|
+
optional: true
|
|
470
|
+
});
|
|
471
|
+
const groups = [
|
|
472
|
+
{
|
|
473
|
+
name: "path",
|
|
474
|
+
params: path,
|
|
475
|
+
resolve: resolver.param.path
|
|
476
|
+
},
|
|
477
|
+
{
|
|
478
|
+
name: "query",
|
|
479
|
+
params: query,
|
|
480
|
+
resolve: resolver.param.query
|
|
481
|
+
},
|
|
482
|
+
{
|
|
483
|
+
name: "headers",
|
|
484
|
+
params: header,
|
|
485
|
+
resolve: resolver.param.headers
|
|
486
|
+
},
|
|
487
|
+
{
|
|
488
|
+
name: "cookies",
|
|
489
|
+
params: cookie,
|
|
490
|
+
resolve: resolver.param.cookies
|
|
491
|
+
}
|
|
492
|
+
];
|
|
493
|
+
const createOptions = (body, extra = []) => _kubb_kit.ast.factory.createSchema({
|
|
494
|
+
type: "object",
|
|
495
|
+
primitive: "object",
|
|
496
|
+
deprecated: node.deprecated,
|
|
497
|
+
properties: [
|
|
498
|
+
_kubb_kit.ast.factory.createProperty({
|
|
499
|
+
name: "body",
|
|
500
|
+
required: hasBody && node.requestBody?.required === true,
|
|
501
|
+
schema: body
|
|
502
|
+
}),
|
|
503
|
+
...groups.filter(({ name, params }) => name !== "cookies" || params.length > 0).map(({ name, params, resolve }) => {
|
|
504
|
+
const required = name !== "cookies" && params.some((param) => param.required);
|
|
505
|
+
return _kubb_kit.ast.factory.createProperty({
|
|
506
|
+
name,
|
|
507
|
+
required,
|
|
508
|
+
schema: params.length > 0 ? _kubb_kit.ast.factory.createSchema({
|
|
509
|
+
type: "ref",
|
|
510
|
+
name: resolve.call(resolver.param, node, params[0]),
|
|
511
|
+
optional: !required
|
|
512
|
+
}) : createNever()
|
|
513
|
+
});
|
|
514
|
+
}),
|
|
515
|
+
...extra
|
|
516
|
+
]
|
|
517
|
+
});
|
|
518
|
+
const variants = pairContentTypes && hasRequestContentTypeChoice(node) ? resolveContentTypeVariants(node.requestBody?.content ?? [], resolver.response.body(node)) : [];
|
|
519
|
+
if (variants.length < 2) return createOptions(hasBody ? _kubb_kit.ast.factory.createSchema({
|
|
520
|
+
type: "ref",
|
|
521
|
+
name: resolver.response.body(node)
|
|
522
|
+
}) : createNever());
|
|
523
|
+
return _kubb_kit.ast.factory.createSchema({
|
|
524
|
+
type: "union",
|
|
525
|
+
members: variants.map((variant, index) => {
|
|
526
|
+
const contentType = _kubb_kit.ast.factory.createSchema({
|
|
527
|
+
type: "enum",
|
|
528
|
+
enumValues: [variant.contentType]
|
|
529
|
+
});
|
|
530
|
+
return createOptions(_kubb_kit.ast.factory.createSchema({
|
|
531
|
+
type: "ref",
|
|
532
|
+
name: variant.name
|
|
533
|
+
}), [_kubb_kit.ast.factory.createProperty({
|
|
534
|
+
name: "contentType",
|
|
535
|
+
required: index > 0,
|
|
536
|
+
schema: _kubb_kit.ast.factory.createSchema({
|
|
537
|
+
type: "union",
|
|
538
|
+
members: [contentType, _kubb_kit.ast.factory.createSchema({
|
|
539
|
+
type: "object",
|
|
540
|
+
primitive: "object",
|
|
541
|
+
properties: [_kubb_kit.ast.factory.createProperty({
|
|
542
|
+
name: "request",
|
|
543
|
+
required: true,
|
|
544
|
+
schema: contentType
|
|
545
|
+
})]
|
|
546
|
+
})]
|
|
547
|
+
})
|
|
548
|
+
})]);
|
|
549
|
+
})
|
|
550
|
+
});
|
|
551
|
+
}
|
|
552
|
+
/**
|
|
553
|
+
* The schema a status occupies in the `<Name>Responses` record. A status that documents several
|
|
554
|
+
* content types becomes a `{ contentType; data }` union so the runtime can surface the negotiated type
|
|
555
|
+
* on `result.parsed`, while the standalone `<Name>StatusNNN` alias stays the plain body union that the
|
|
556
|
+
* query hooks and `result.data` use. With `streamData`, the stream variant of a 2xx status holds that schema, since the
|
|
557
|
+
* client returns its body unread.
|
|
558
|
+
*/
|
|
559
|
+
function buildResponseRecordEntry(node, res, resolver, streamData) {
|
|
560
|
+
const statusName = resolver.response.status(node, res.statusCode);
|
|
561
|
+
const variants = (res.content ?? []).filter((entry) => entry.schema);
|
|
562
|
+
if (variants.length <= 1) return _kubb_kit.ast.factory.createSchema({
|
|
563
|
+
type: "ref",
|
|
564
|
+
name: statusName
|
|
565
|
+
});
|
|
566
|
+
return _kubb_kit.ast.factory.createSchema({
|
|
567
|
+
type: "union",
|
|
568
|
+
members: resolveContentTypeVariants(variants, statusName).map((variant) => _kubb_kit.ast.factory.createSchema({
|
|
569
|
+
type: "object",
|
|
570
|
+
primitive: "object",
|
|
571
|
+
properties: [_kubb_kit.ast.factory.createProperty({
|
|
572
|
+
name: "contentType",
|
|
573
|
+
required: true,
|
|
574
|
+
schema: _kubb_kit.ast.factory.createSchema({
|
|
575
|
+
type: "enum",
|
|
576
|
+
enumValues: [_kubb_kit.ast.mediaType.getBase(variant)]
|
|
577
|
+
})
|
|
578
|
+
}), _kubb_kit.ast.factory.createProperty({
|
|
579
|
+
name: "data",
|
|
580
|
+
required: true,
|
|
581
|
+
schema: streamData && _kubb_kit.ast.http.status.isSuccess(res) && _kubb_kit.ast.mediaType.isStream(variant) ? streamData : _kubb_kit.ast.factory.createSchema({
|
|
582
|
+
type: "ref",
|
|
583
|
+
name: variant.name
|
|
584
|
+
})
|
|
585
|
+
})]
|
|
586
|
+
}))
|
|
587
|
+
});
|
|
588
|
+
}
|
|
589
|
+
/**
|
|
590
|
+
* Builds the per-status `<Name>Responses` record for an operation, referencing the already-resolved
|
|
591
|
+
* `<Name>StatusNNN` names. Shared by `@kubb/plugin-ts`'s `Responses` type and `@kubb/plugin-zod`'s
|
|
592
|
+
* inferred responses schema, so both emit the same shape from the same inputs.
|
|
593
|
+
*
|
|
594
|
+
* Always emits the keyed record, even when an operation declares no responses. An operation with no
|
|
595
|
+
* responses renders as an empty object, which keeps every consumer's import (for example the axios
|
|
596
|
+
* SDK's `RequestResult<XResponses>`) resolvable instead of pointing at a missing export.
|
|
597
|
+
*
|
|
598
|
+
* `streamData` is the type of a stream variant's `data`, such as a `ReadableStream<Uint8Array>` reference.
|
|
599
|
+
*/
|
|
600
|
+
function buildResponses(node, resolver, { streamData } = {}) {
|
|
601
|
+
return _kubb_kit.ast.factory.createSchema({
|
|
602
|
+
type: "object",
|
|
603
|
+
primitive: "object",
|
|
604
|
+
properties: node.responses.map((res) => _kubb_kit.ast.factory.createProperty({
|
|
605
|
+
name: String(res.statusCode),
|
|
606
|
+
required: true,
|
|
607
|
+
schema: buildResponseRecordEntry(node, res, resolver, streamData)
|
|
608
|
+
}))
|
|
609
|
+
});
|
|
610
|
+
}
|
|
611
|
+
/**
|
|
612
|
+
* One object schema for a list of parameters or response headers, with each schema inline.
|
|
613
|
+
*/
|
|
614
|
+
function buildParamsSchema(params) {
|
|
615
|
+
return _kubb_kit.ast.factory.createSchema({
|
|
616
|
+
type: "object",
|
|
617
|
+
primitive: "object",
|
|
618
|
+
properties: params.map((param) => _kubb_kit.ast.factory.createProperty({
|
|
619
|
+
name: param.name,
|
|
620
|
+
required: param.required,
|
|
621
|
+
schema: param.schema
|
|
622
|
+
}))
|
|
623
|
+
});
|
|
624
|
+
}
|
|
625
|
+
/**
|
|
626
|
+
* One object schema for the parameters of an operation, where each key points at the const of
|
|
627
|
+
* that parameter. The const already has its optional wrapper, so every key is required here.
|
|
628
|
+
*/
|
|
629
|
+
function buildParamRefsSchema({ node, params, resolver }) {
|
|
630
|
+
return _kubb_kit.ast.factory.createSchema({
|
|
631
|
+
type: "object",
|
|
632
|
+
primitive: "object",
|
|
633
|
+
properties: params.map((param) => _kubb_kit.ast.factory.createProperty({
|
|
634
|
+
name: param.name,
|
|
635
|
+
required: true,
|
|
636
|
+
schema: _kubb_kit.ast.factory.createSchema({
|
|
637
|
+
type: "ref",
|
|
638
|
+
name: resolver.param.name(node, param)
|
|
639
|
+
})
|
|
640
|
+
}))
|
|
641
|
+
});
|
|
642
|
+
}
|
|
643
|
+
/**
|
|
644
|
+
* The schemas a name with several content types needs: one per content type, then the union of
|
|
645
|
+
* them under `baseName`.
|
|
646
|
+
*/
|
|
647
|
+
function buildContentTypeEntries(entries, baseName, decorate = (schema) => schema) {
|
|
648
|
+
const variants = resolveContentTypeVariants(entries, baseName);
|
|
649
|
+
const union = _kubb_kit.ast.factory.createSchema({
|
|
650
|
+
type: "union",
|
|
651
|
+
members: variants.map((variant) => _kubb_kit.ast.factory.createSchema({
|
|
652
|
+
type: "ref",
|
|
653
|
+
name: variant.name
|
|
654
|
+
}))
|
|
655
|
+
});
|
|
656
|
+
return [...variants.map((variant) => ({
|
|
657
|
+
schema: decorate(variant.schema),
|
|
658
|
+
name: variant.name,
|
|
659
|
+
keysToOmit: variant.keysToOmit
|
|
660
|
+
})), {
|
|
661
|
+
schema: union,
|
|
662
|
+
name: baseName
|
|
663
|
+
}];
|
|
664
|
+
}
|
|
665
|
+
/**
|
|
666
|
+
* The schema behind a response or error name: a union of the per-status schemas. Returns `null`
|
|
667
|
+
* when a response is a `$ref` to a component whose name is already `name`, which would declare it twice.
|
|
668
|
+
*/
|
|
669
|
+
function buildResponseUnionSchema({ node, responses, name, resolver, fallbackUnknown }) {
|
|
670
|
+
if (new Set(_kubb_kit.ast.http.responses.getImportedNames(responses).map((refName) => resolver.name(refName))).has(name)) return null;
|
|
671
|
+
const members = responses.map((res) => _kubb_kit.ast.factory.createSchema({
|
|
672
|
+
type: "ref",
|
|
673
|
+
name: resolver.response.status(node, res.statusCode)
|
|
674
|
+
}));
|
|
675
|
+
if (members.length === 0) return fallbackUnknown ? _kubb_kit.ast.factory.createSchema({ type: "unknown" }) : null;
|
|
676
|
+
return members.length === 1 ? members[0] : _kubb_kit.ast.factory.createSchema({
|
|
677
|
+
type: "union",
|
|
678
|
+
members
|
|
679
|
+
});
|
|
680
|
+
}
|
|
681
|
+
// ../../internals/shared/src/adapter.ts
|
|
682
|
+
/**
|
|
683
|
+
* Narrows the generic `Adapter` from a generator context to the OpenAPI adapter,
|
|
684
|
+
* so OAS-only options (`dateType`, `enums`) and the parsed `document` are typed.
|
|
685
|
+
*
|
|
686
|
+
* Throws when a non-OAS adapter is configured, turning a silently wrong cast into a
|
|
687
|
+
* clear, actionable error at the point of use.
|
|
688
|
+
*
|
|
689
|
+
* @example
|
|
690
|
+
* ```ts
|
|
691
|
+
* const { dateType } = getOasAdapter(ctx.adapter).options
|
|
692
|
+
* ```
|
|
693
|
+
*/
|
|
694
|
+
function getOasAdapter(adapter) {
|
|
695
|
+
if (adapter.name !== "oas") throw new _kubb_kit.Diagnostics.Error({
|
|
696
|
+
code: _kubb_kit.Diagnostics.code.adapterRequired,
|
|
697
|
+
severity: "error",
|
|
698
|
+
message: `Expected the OpenAPI adapter (adapterOas), but received "${adapter.name}".`,
|
|
699
|
+
help: "Set `adapter: adapterOas()` in kubb.config.ts.",
|
|
700
|
+
location: { kind: "config" }
|
|
701
|
+
});
|
|
702
|
+
return adapter;
|
|
703
|
+
}
|
|
704
|
+
// ../../internals/shared/src/resolver.ts
|
|
705
|
+
/**
|
|
706
|
+
* Builds the allocation key for a declaration an operation owns. `scope` names which declaration
|
|
707
|
+
* it is, so two of them never share an allocation even when a custom resolver gives both the same
|
|
708
|
+
* name. Leave `scope` empty for the operation's own declaration.
|
|
709
|
+
*
|
|
710
|
+
* The key starts from the operation's input `pointer`, which macros keep, so a plugin whose macro
|
|
711
|
+
* rewrites the method or path still resolves another plugin's names for the same operation.
|
|
712
|
+
*
|
|
713
|
+
* @example
|
|
714
|
+
* ```ts
|
|
715
|
+
* resolver.resolveName({ key: operationKey(node, 'response', 'status', 404), name })
|
|
716
|
+
* ```
|
|
717
|
+
*/
|
|
718
|
+
function operationKey(node, ...scope) {
|
|
719
|
+
return [
|
|
720
|
+
"operation",
|
|
721
|
+
...node.pointer ? [node.pointer] : [node.method, node.path],
|
|
722
|
+
...scope.map(String)
|
|
723
|
+
];
|
|
724
|
+
}
|
|
725
|
+
/**
|
|
726
|
+
* Builds the shared `param` namespace. Spread the result into `createResolver`
|
|
727
|
+
* and override individual methods next to it when a plugin deviates.
|
|
728
|
+
*
|
|
729
|
+
* @example
|
|
730
|
+
* ```ts
|
|
731
|
+
* createResolver<PluginTs>({ param: createOperationParamResolver(), ... })
|
|
732
|
+
* ```
|
|
733
|
+
*/
|
|
734
|
+
function createOperationParamResolver() {
|
|
735
|
+
return {
|
|
736
|
+
name(node, param) {
|
|
737
|
+
const name = this.name(`${node.operationId} ${param.in} ${param.name}`);
|
|
738
|
+
return this.resolveName({
|
|
739
|
+
key: operationKey(node, "param", "name", param.in, param.name),
|
|
740
|
+
name
|
|
741
|
+
});
|
|
742
|
+
},
|
|
743
|
+
path(node) {
|
|
744
|
+
const name = this.name(`${node.operationId} Path`);
|
|
745
|
+
return this.resolveName({
|
|
746
|
+
key: operationKey(node, "param", "path"),
|
|
747
|
+
name
|
|
748
|
+
});
|
|
749
|
+
},
|
|
750
|
+
query(node) {
|
|
751
|
+
const name = this.name(`${node.operationId} Query`);
|
|
752
|
+
return this.resolveName({
|
|
753
|
+
key: operationKey(node, "param", "query"),
|
|
754
|
+
name
|
|
755
|
+
});
|
|
756
|
+
},
|
|
757
|
+
headers(node) {
|
|
758
|
+
const name = this.name(`${node.operationId} Headers`);
|
|
759
|
+
return this.resolveName({
|
|
760
|
+
key: operationKey(node, "param", "headers"),
|
|
761
|
+
name
|
|
762
|
+
});
|
|
763
|
+
},
|
|
764
|
+
cookies(node) {
|
|
765
|
+
const name = this.name(`${node.operationId} Cookies`);
|
|
766
|
+
return this.resolveName({
|
|
767
|
+
key: operationKey(node, "param", "cookies"),
|
|
768
|
+
name
|
|
769
|
+
});
|
|
770
|
+
}
|
|
771
|
+
};
|
|
772
|
+
}
|
|
773
|
+
/**
|
|
774
|
+
* Builds the shared `response` namespace. Spread the result into
|
|
775
|
+
* `createResolver` and add plugin-specific methods (`options`, `error`) next
|
|
776
|
+
* to it.
|
|
777
|
+
*
|
|
778
|
+
* @example
|
|
779
|
+
* ```ts
|
|
780
|
+
* createResolver<PluginTs>({ response: { ...createOperationResponseResolver(), options(node) {...} }, ... })
|
|
781
|
+
* ```
|
|
782
|
+
*/
|
|
783
|
+
function createOperationResponseResolver() {
|
|
784
|
+
return {
|
|
785
|
+
status(node, statusCode) {
|
|
786
|
+
const name = this.name(`${node.operationId} Status ${statusCode}`);
|
|
787
|
+
return this.resolveName({
|
|
788
|
+
key: operationKey(node, "response", "status", statusCode),
|
|
789
|
+
name
|
|
790
|
+
});
|
|
791
|
+
},
|
|
792
|
+
headers(node, statusCode) {
|
|
793
|
+
const name = this.name(`${node.operationId} Status ${statusCode} Headers`);
|
|
794
|
+
return this.resolveName({
|
|
795
|
+
key: operationKey(node, "response", "headers", statusCode),
|
|
796
|
+
name
|
|
797
|
+
});
|
|
798
|
+
},
|
|
799
|
+
body(node) {
|
|
800
|
+
const name = this.name(`${node.operationId} Body`);
|
|
801
|
+
return this.resolveName({
|
|
802
|
+
key: operationKey(node, "response", "body"),
|
|
803
|
+
name
|
|
804
|
+
});
|
|
805
|
+
},
|
|
806
|
+
responses(node) {
|
|
807
|
+
const name = this.name(`${node.operationId} Responses`);
|
|
808
|
+
return this.resolveName({
|
|
809
|
+
key: operationKey(node, "response", "responses"),
|
|
810
|
+
name
|
|
811
|
+
});
|
|
812
|
+
},
|
|
813
|
+
response(node) {
|
|
814
|
+
const name = this.name(`${node.operationId} Response`);
|
|
815
|
+
return this.resolveName({
|
|
816
|
+
key: operationKey(node, "response", "response"),
|
|
817
|
+
name
|
|
818
|
+
});
|
|
819
|
+
}
|
|
820
|
+
};
|
|
821
|
+
}
|
|
822
|
+
/**
|
|
823
|
+
* Builds a resolver `file` override whose base name runs every path segment
|
|
824
|
+
* through `toFilePath`, casing the final segment with `caseLast`.
|
|
825
|
+
*
|
|
826
|
+
* @example
|
|
827
|
+
* ```ts
|
|
828
|
+
* createResolver<PluginTs>({ file: createCasedFile(pascalCase), ... })
|
|
829
|
+
* ```
|
|
830
|
+
*/
|
|
831
|
+
function createCasedFile(caseLast) {
|
|
832
|
+
return { baseName({ name, extname }) {
|
|
833
|
+
return this.memo(`file:${name}\0${extname}`, () => `${toFilePath(name, caseLast)}${extname}`);
|
|
834
|
+
} };
|
|
835
|
+
}
|
|
836
|
+
/**
|
|
837
|
+
* Names of the schemas in a circular reference chain, computed once per build.
|
|
838
|
+
*/
|
|
839
|
+
function getCircularNames(ctx) {
|
|
840
|
+
return ctx.memo("circularNames:set", () => _kubb_kit.ast.graph.getCircularNames(ctx.schemas));
|
|
841
|
+
}
|
|
842
|
+
// ../../internals/shared/src/schema.ts
|
|
843
|
+
/**
|
|
844
|
+
* Whether the node is a plain inline object whose properties can merge into another object schema.
|
|
845
|
+
* Input checks, `additionalProperties`, `patternProperties`, `propertyNames`, and a nullable or
|
|
846
|
+
* optional wrapper rule it out.
|
|
847
|
+
*/
|
|
848
|
+
function isPlainInlineObject(node) {
|
|
849
|
+
if (node.type !== "object") return false;
|
|
850
|
+
if (hasInputChecks(node)) return false;
|
|
851
|
+
if (node.nullable || node.optional || node.nullish) return false;
|
|
852
|
+
const hasAdditionalProperties = node.additionalProperties !== void 0;
|
|
853
|
+
const hasPatternProperties = Boolean(node.patternProperties);
|
|
854
|
+
return !hasAdditionalProperties && !hasPatternProperties && !node.propertyNames;
|
|
855
|
+
}
|
|
856
|
+
/**
|
|
857
|
+
* Whether a node prints as a plain object schema, which other schemas can extend or discriminate on.
|
|
858
|
+
* Covers object nodes, a `$ref` that resolves to an object or is still unresolved, a union with one
|
|
859
|
+
* object member, and an object-composable `allOf`.
|
|
860
|
+
*
|
|
861
|
+
* A nullable or optional node, a node with input checks, and a ref into `cyclicSchemas` do not count.
|
|
862
|
+
*/
|
|
863
|
+
function isObjectSchemaNode(node, cyclicSchemas) {
|
|
864
|
+
if (node.nullable || node.optional || node.nullish) return false;
|
|
865
|
+
if (hasInputChecks(node)) return false;
|
|
866
|
+
if (node.type === "object") {
|
|
867
|
+
const hasProperties = Boolean(node.properties?.length);
|
|
868
|
+
const hasTypedAdditionalProperties = Boolean(node.additionalProperties && node.additionalProperties !== true);
|
|
869
|
+
const hasPatternProperties = Boolean(node.patternProperties);
|
|
870
|
+
return !(!hasProperties && (hasTypedAdditionalProperties || hasPatternProperties || node.propertyNames));
|
|
871
|
+
}
|
|
872
|
+
if (node.type === "ref") {
|
|
873
|
+
const refName = _kubb_kit.ast.ref.getName(node);
|
|
874
|
+
if (refName && cyclicSchemas?.has(refName)) return false;
|
|
875
|
+
const resolved = _kubb_kit.ast.ref.mergeSchema(node);
|
|
876
|
+
return resolved.type === "ref" || isObjectSchemaNode(resolved, cyclicSchemas);
|
|
877
|
+
}
|
|
878
|
+
if (node.type === "union") {
|
|
879
|
+
const members = node.members ?? [];
|
|
880
|
+
return members.length === 1 && isObjectSchemaNode(members[0], cyclicSchemas);
|
|
881
|
+
}
|
|
882
|
+
return isObjectComposableIntersection(node, cyclicSchemas);
|
|
883
|
+
}
|
|
884
|
+
/**
|
|
885
|
+
* Whether an `allOf` is an object base plus inline object members, so it can print as one object
|
|
886
|
+
* schema and not as an intersection.
|
|
887
|
+
*/
|
|
888
|
+
function isObjectComposableIntersection(node, cyclicSchemas) {
|
|
889
|
+
if (node.type !== "intersection") return false;
|
|
890
|
+
const [first, ...rest] = node.members ?? [];
|
|
891
|
+
return !!first && isObjectSchemaNode(first, cyclicSchemas) && rest.every(isPlainInlineObject);
|
|
892
|
+
}
|
|
893
|
+
/**
|
|
894
|
+
* Marks a property required in a later `allOf` member when an earlier member already requires it.
|
|
895
|
+
*/
|
|
896
|
+
function preserveRequiredProperties(members) {
|
|
897
|
+
const hasRequiredProperty = ({ node, propertyName, seen = /* @__PURE__ */ new Set() }) => {
|
|
898
|
+
if (seen.has(node)) return false;
|
|
899
|
+
seen.add(node);
|
|
900
|
+
const resolved = _kubb_kit.ast.ref.mergeSchema(node);
|
|
901
|
+
const composition = _kubb_kit.ast.schema.narrow(resolved, _kubb_kit.ast.schema.types.intersection) ?? _kubb_kit.ast.schema.narrow(resolved, _kubb_kit.ast.schema.types.union);
|
|
902
|
+
if (composition) {
|
|
903
|
+
if (composition.type === _kubb_kit.ast.schema.types.union && composition.members?.length !== 1) return false;
|
|
904
|
+
return composition.members?.some((child) => hasRequiredProperty({
|
|
905
|
+
node: child,
|
|
906
|
+
propertyName,
|
|
907
|
+
seen
|
|
908
|
+
})) ?? false;
|
|
909
|
+
}
|
|
910
|
+
return _kubb_kit.ast.schema.findProperties({
|
|
911
|
+
node: resolved,
|
|
912
|
+
propertyName
|
|
913
|
+
}).some((property) => property.required !== false && !property.schema.optional && !property.schema.nullish);
|
|
914
|
+
};
|
|
915
|
+
return members.map((member, index) => {
|
|
916
|
+
const object = _kubb_kit.ast.schema.narrow(member, _kubb_kit.ast.schema.types.object);
|
|
917
|
+
if (!object || index === 0) return member;
|
|
918
|
+
return {
|
|
919
|
+
...object,
|
|
920
|
+
properties: object.properties.map((property) => {
|
|
921
|
+
if (!members.slice(0, index).some((base) => hasRequiredProperty({
|
|
922
|
+
node: base,
|
|
923
|
+
propertyName: property.name
|
|
924
|
+
}))) return property;
|
|
925
|
+
return {
|
|
926
|
+
...property,
|
|
927
|
+
required: true,
|
|
928
|
+
schema: {
|
|
929
|
+
...property.schema,
|
|
930
|
+
optional: false,
|
|
931
|
+
nullish: false,
|
|
932
|
+
nullable: property.schema.nullable || property.schema.nullish
|
|
933
|
+
}
|
|
934
|
+
};
|
|
935
|
+
})
|
|
936
|
+
};
|
|
937
|
+
});
|
|
938
|
+
}
|
|
939
|
+
/**
|
|
940
|
+
* Format a default value as a code-level literal.
|
|
941
|
+
* Arrays and objects keep their contents as a JSON literal, primitives become their string
|
|
942
|
+
* representation, strings are quoted.
|
|
943
|
+
*/
|
|
944
|
+
function formatDefault(value) {
|
|
945
|
+
if (typeof value === "string") return _kubb_kit.text.quote(value);
|
|
946
|
+
if (typeof value === "object" && value !== null) return JSON.stringify(value);
|
|
947
|
+
return String(value ?? "");
|
|
948
|
+
}
|
|
949
|
+
/**
|
|
950
|
+
* Formats a default so the literal matches the type of the generated schema, or returns `null` when
|
|
951
|
+
* the default should be dropped.
|
|
952
|
+
*
|
|
953
|
+
* An OpenAPI `default` does not always agree with its schema: a `bigint` field (`format: int64`)
|
|
954
|
+
* carries a `number` default, and a spec may put `default: {}` on an `array`. Printed as they are,
|
|
955
|
+
* those do not typecheck, so a bigint default becomes a `BigInt(...)` literal and a non-array default
|
|
956
|
+
* on an array is dropped.
|
|
957
|
+
*/
|
|
958
|
+
function defaultLiteral(node, value) {
|
|
959
|
+
if (value === null) return null;
|
|
960
|
+
const resolved = node ? _kubb_kit.ast.ref.mergeSchema(node) : void 0;
|
|
961
|
+
if (resolved?.type === "blob") return null;
|
|
962
|
+
if (resolved && _kubb_kit.ast.schema.narrow(resolved, "bigint")) {
|
|
963
|
+
if (typeof value === "bigint" || typeof value === "number" && Number.isInteger(value)) return `BigInt('${BigInt(value)}')`;
|
|
964
|
+
return null;
|
|
965
|
+
}
|
|
966
|
+
if (resolved && _kubb_kit.ast.schema.narrow(resolved, "array")) return Array.isArray(value) ? JSON.stringify(value) : null;
|
|
967
|
+
const enumNode = resolved ? _kubb_kit.ast.schema.narrow(resolved, "enum") : void 0;
|
|
968
|
+
if (enumNode) {
|
|
969
|
+
const values = _kubb_kit.ast.schema.getLiterals(enumNode);
|
|
970
|
+
if (values.length) {
|
|
971
|
+
const match = values.find((member) => member === value || String(member) === String(value));
|
|
972
|
+
return match != null ? formatDefault(match) : null;
|
|
973
|
+
}
|
|
974
|
+
}
|
|
975
|
+
return formatDefault(value);
|
|
976
|
+
}
|
|
977
|
+
/**
|
|
978
|
+
* Digit pattern for a `type: 'string'` schema that carries an integer `format`, the way ProtoJSON
|
|
979
|
+
* encodes 64-bit integers. Returns `undefined` for every other format, and a `pattern` from the
|
|
980
|
+
* spec takes precedence over this fallback.
|
|
981
|
+
*
|
|
982
|
+
* @example
|
|
983
|
+
* ```ts
|
|
984
|
+
* integerFormatPattern('uint64') // '^\\d+$'
|
|
985
|
+
* ```
|
|
986
|
+
*/
|
|
987
|
+
function integerFormatPattern(format) {
|
|
988
|
+
if (format === "int32" || format === "int64") return "^-?\\d+$";
|
|
989
|
+
if (format === "uint64") return "^\\d+$";
|
|
990
|
+
}
|
|
991
|
+
/**
|
|
992
|
+
* Numeric bounds for a bigint: the inclusive, whole, safe bounds faker mocks against, and a whole, safe `multipleOf`.
|
|
993
|
+
*/
|
|
994
|
+
function bigintConstraints({ min, max, exclusive, multipleOf }) {
|
|
995
|
+
return {
|
|
996
|
+
..._kubb_kit.ast.schema.getNumberBounds({
|
|
997
|
+
min,
|
|
998
|
+
max,
|
|
999
|
+
exclusive,
|
|
1000
|
+
integer: true
|
|
1001
|
+
}),
|
|
1002
|
+
multipleOf: Number.isSafeInteger(multipleOf) ? multipleOf : void 0
|
|
1003
|
+
};
|
|
1004
|
+
}
|
|
1005
|
+
const integerFormatRanges = {
|
|
1006
|
+
integer: {
|
|
1007
|
+
int8: [-(2n ** 7n), 2n ** 7n - 1n],
|
|
1008
|
+
uint8: [0n, 2n ** 8n - 1n],
|
|
1009
|
+
int16: [-(2n ** 15n), 2n ** 15n - 1n],
|
|
1010
|
+
uint16: [0n, 2n ** 16n - 1n],
|
|
1011
|
+
int32: [-(2n ** 31n), 2n ** 31n - 1n],
|
|
1012
|
+
uint32: [0n, 2n ** 32n - 1n]
|
|
1013
|
+
},
|
|
1014
|
+
bigint: {
|
|
1015
|
+
int64: [-(2n ** 63n), 2n ** 63n - 1n],
|
|
1016
|
+
uint64: [0n, 2n ** 64n - 1n]
|
|
1017
|
+
}
|
|
1018
|
+
};
|
|
1019
|
+
/**
|
|
1020
|
+
* Adds the range of an integer `format` to a schema's limits. A bound from the spec stays when it
|
|
1021
|
+
* is at least as tight as the format's.
|
|
1022
|
+
*
|
|
1023
|
+
* @example
|
|
1024
|
+
* ```ts
|
|
1025
|
+
* withFormatRange({ format: 'int32', min: 0 }, 'integer') // { format: 'int32', min: 0, max: '2147483647' }
|
|
1026
|
+
* ```
|
|
1027
|
+
*/
|
|
1028
|
+
function withFormatRange(node, type) {
|
|
1029
|
+
const range = node.format ? integerFormatRanges[type][node.format] : void 0;
|
|
1030
|
+
if (!range) return node;
|
|
1031
|
+
const [min, max] = range;
|
|
1032
|
+
return {
|
|
1033
|
+
...node,
|
|
1034
|
+
min: node.min === void 0 || node.min < Number(min) ? String(min) : node.min,
|
|
1035
|
+
max: node.max === void 0 || node.max > Number(max) ? String(max) : node.max
|
|
1036
|
+
};
|
|
1037
|
+
}
|
|
1038
|
+
/**
|
|
1039
|
+
* Whether `propertyNames` needs its own check. A record schema checks its keys, but an object with
|
|
1040
|
+
* `properties` and a record keyed by `patternProperties` do not.
|
|
1041
|
+
*/
|
|
1042
|
+
function hasKeyCheck(node) {
|
|
1043
|
+
if (node.type !== "object" || !node.propertyNames) return false;
|
|
1044
|
+
const hasTypedAdditionalProperties = Boolean(node.additionalProperties && node.additionalProperties !== true);
|
|
1045
|
+
return node.properties.length > 0 || Boolean(node.patternProperties) && !hasTypedAdditionalProperties;
|
|
1046
|
+
}
|
|
1047
|
+
/**
|
|
1048
|
+
* Whether the node has checks that run on the raw input: `conditionals`, property counts, or a key check.
|
|
1049
|
+
*/
|
|
1050
|
+
function hasInputChecks(node) {
|
|
1051
|
+
return Boolean(node.conditionals?.length) || node.type === "object" && (node.min !== void 0 || node.max !== void 0) || hasKeyCheck(node);
|
|
1052
|
+
}
|
|
1053
|
+
/**
|
|
1054
|
+
* Marks an inline `oneOf` object strict, so a value with the keys of another member does not match it.
|
|
1055
|
+
*/
|
|
1056
|
+
function strictOneOfNode(node) {
|
|
1057
|
+
return node.type === "object" && node.additionalProperties === void 0 ? {
|
|
1058
|
+
...node,
|
|
1059
|
+
additionalProperties: false
|
|
1060
|
+
} : node;
|
|
1061
|
+
}
|
|
1062
|
+
/**
|
|
1063
|
+
* Whether the `coercion` option turns on conversion for a type.
|
|
1064
|
+
*/
|
|
1065
|
+
function shouldCoerce(coercion, type) {
|
|
1066
|
+
return coercion === true || typeof coercion === "object" && Boolean(coercion[type]);
|
|
1067
|
+
}
|
|
1068
|
+
/**
|
|
1069
|
+
* A numeric bound as source code. A bigint bound prints as `BigInt('…')`, which is exact and
|
|
1070
|
+
* compiles below ES2020, where a `1n` literal does not.
|
|
1071
|
+
*/
|
|
1072
|
+
function numericLiteral(value, isBigint) {
|
|
1073
|
+
return isBigint ? `BigInt('${value}')` : value;
|
|
1074
|
+
}
|
|
1075
|
+
/**
|
|
1076
|
+
* The JSDoc lines above a schema const: its description, and `@deprecated` when the spec says so.
|
|
1077
|
+
* A `$ref` const gets none, because the const it points to has them.
|
|
1078
|
+
*/
|
|
1079
|
+
function schemaComments(node) {
|
|
1080
|
+
if (node.type === _kubb_kit.ast.schema.types.ref) return [];
|
|
1081
|
+
return [node.description && jsDocEscape(node.description), node.deprecated && "@deprecated"].filter((comment) => Boolean(comment));
|
|
1082
|
+
}
|
|
1083
|
+
// src/components/Valibot.tsx
|
|
1084
|
+
function Valibot({ name, node, printer, inferTypeName, inferKind = "InferOutput", typeGuards, isName, assertName, cyclic, comments = [] }) {
|
|
1085
|
+
const output = printer.print(node);
|
|
1086
|
+
const printerImports = printer.drainImports();
|
|
1087
|
+
if (!output) return;
|
|
1088
|
+
const guardType = `v.InferInput<typeof ${name}>`;
|
|
1089
|
+
const shouldGenerateIs = isName && (typeof typeGuards === "object" ? typeGuards.is ?? true : Boolean(typeGuards));
|
|
1090
|
+
const shouldGenerateAssert = assertName && (typeof typeGuards === "object" ? typeGuards.assert ?? true : Boolean(typeGuards));
|
|
1091
|
+
return /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsxs)(_kubb_renderer_jsx_jsx_runtime.Fragment, { children: [
|
|
1092
|
+
printerImports.map((imp) => /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.File.Import, {
|
|
1093
|
+
name: imp.name,
|
|
1094
|
+
path: imp.path,
|
|
1095
|
+
root: imp.root,
|
|
1096
|
+
isTypeOnly: imp.isTypeOnly,
|
|
1097
|
+
isNameSpace: imp.isNameSpace
|
|
1098
|
+
}, [
|
|
1099
|
+
name,
|
|
1100
|
+
imp.path,
|
|
1101
|
+
imp.name
|
|
1102
|
+
].join("-"))),
|
|
1103
|
+
/* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.File.Source, {
|
|
1104
|
+
name,
|
|
1105
|
+
isExportable: true,
|
|
1106
|
+
isIndexable: true,
|
|
1107
|
+
children: /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.Const, {
|
|
1108
|
+
export: true,
|
|
1109
|
+
name,
|
|
1110
|
+
type: cyclic ? "v.GenericSchema" : void 0,
|
|
1111
|
+
JSDoc: comments.length ? { comments } : void 0,
|
|
1112
|
+
children: output
|
|
1113
|
+
})
|
|
1114
|
+
}),
|
|
1115
|
+
inferTypeName && /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.File.Source, {
|
|
1116
|
+
name: inferTypeName,
|
|
1117
|
+
isExportable: true,
|
|
1118
|
+
isIndexable: true,
|
|
1119
|
+
isTypeOnly: true,
|
|
1120
|
+
children: /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.Type, {
|
|
1121
|
+
export: true,
|
|
1122
|
+
name: inferTypeName,
|
|
1123
|
+
children: `v.${inferKind}<typeof ${name}>`
|
|
1124
|
+
})
|
|
1125
|
+
}),
|
|
1126
|
+
shouldGenerateIs && /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.File.Source, {
|
|
1127
|
+
name: isName,
|
|
1128
|
+
isExportable: true,
|
|
1129
|
+
isIndexable: true,
|
|
1130
|
+
children: /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.Const, {
|
|
1131
|
+
export: true,
|
|
1132
|
+
name: isName,
|
|
1133
|
+
JSDoc: { comments: [`Type guard for {@link ${name}}`] },
|
|
1134
|
+
children: `(data: unknown): data is ${guardType} => v.is(${name}, data)`
|
|
1135
|
+
})
|
|
1136
|
+
}),
|
|
1137
|
+
shouldGenerateAssert && /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.File.Source, {
|
|
1138
|
+
name: assertName,
|
|
1139
|
+
isExportable: true,
|
|
1140
|
+
isIndexable: true,
|
|
1141
|
+
children: /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.Function, {
|
|
1142
|
+
export: true,
|
|
1143
|
+
name: assertName,
|
|
1144
|
+
params: "data: unknown",
|
|
1145
|
+
returnType: `asserts data is ${guardType}`,
|
|
1146
|
+
JSDoc: { comments: [`Asserter for {@link ${name}}`, "@throws {v.ValiError} If data is invalid"] },
|
|
1147
|
+
children: `v.assert(${name}, data)`
|
|
1148
|
+
})
|
|
1149
|
+
})
|
|
1150
|
+
] });
|
|
1151
|
+
}
|
|
1152
|
+
// src/printers/printerValibot.ts
|
|
1153
|
+
const UNKNOWN = "v.unknown()";
|
|
1154
|
+
const NOT_OBJECT = "typeof value !== \"object\" || value === null || Array.isArray(value)";
|
|
1155
|
+
const stringFormatActions = /* @__PURE__ */ new Map([
|
|
1156
|
+
["byte", "v.base64()"],
|
|
1157
|
+
["base64", "v.base64()"],
|
|
1158
|
+
["ulid", "v.ulid()"]
|
|
1159
|
+
]);
|
|
1160
|
+
function pipe(base, actions) {
|
|
1161
|
+
const list = actions.filter(Boolean);
|
|
1162
|
+
return list.length ? `v.pipe(${[base, ...list].join(", ")})` : base;
|
|
1163
|
+
}
|
|
1164
|
+
function lengthActions({ min, max, pattern }, regexType) {
|
|
1165
|
+
return [
|
|
1166
|
+
min !== void 0 && `v.minLength(${min})`,
|
|
1167
|
+
max !== void 0 && `v.maxLength(${max})`,
|
|
1168
|
+
pattern !== void 0 && `v.regex(${toRegExpString(pattern, regexType === "constructor" ? "RegExp" : null)})`
|
|
1169
|
+
].filter((action) => Boolean(action));
|
|
1170
|
+
}
|
|
1171
|
+
function numberActions({ min, max, exclusive, multipleOf }, isBigint = false) {
|
|
1172
|
+
const literal = (value) => numericLiteral(value, isBigint);
|
|
1173
|
+
return [
|
|
1174
|
+
min !== void 0 && `v.minValue(${literal(min)})`,
|
|
1175
|
+
max !== void 0 && `v.maxValue(${literal(max)})`,
|
|
1176
|
+
exclusive?.min !== void 0 && `v.gtValue(${literal(exclusive.min)})`,
|
|
1177
|
+
exclusive?.max !== void 0 && `v.ltValue(${literal(exclusive.max)})`,
|
|
1178
|
+
multipleOf !== void 0 && `v.multipleOf(${literal(multipleOf)})`
|
|
1179
|
+
].filter((action) => Boolean(action));
|
|
1180
|
+
}
|
|
1181
|
+
function memberActions({ member, base, regexType }) {
|
|
1182
|
+
if (hasChecks(member)) return [];
|
|
1183
|
+
if (member.primitive === "string") return lengthActions(_kubb_kit.ast.schema.narrow(member, "string") ?? {}, regexType);
|
|
1184
|
+
if (member.primitive === "number" || member.primitive === "integer") {
|
|
1185
|
+
const numeric = _kubb_kit.ast.schema.narrow(member, "number") ?? _kubb_kit.ast.schema.narrow(member, "integer") ?? {};
|
|
1186
|
+
if (base.type === _kubb_kit.ast.schema.types.bigint) return numberActions(bigintConstraints(numeric), true);
|
|
1187
|
+
return [...member.primitive === "integer" && base.type !== _kubb_kit.ast.schema.types.integer ? ["v.integer()"] : [], ...numberActions(numeric)];
|
|
1188
|
+
}
|
|
1189
|
+
if (member.primitive === "array") {
|
|
1190
|
+
const array = _kubb_kit.ast.schema.narrow(member, "array");
|
|
1191
|
+
return array && !array.contains ? lengthActions({
|
|
1192
|
+
min: array.min,
|
|
1193
|
+
max: array.max
|
|
1194
|
+
}, regexType) : [];
|
|
1195
|
+
}
|
|
1196
|
+
return [];
|
|
1197
|
+
}
|
|
1198
|
+
function buildLiteral(value) {
|
|
1199
|
+
if (value === null) return "v.null()";
|
|
1200
|
+
if (Array.isArray(value)) return `v.strictTuple([${value.map((item) => buildLiteral(item)).join(", ")}])`;
|
|
1201
|
+
if (typeof value === "object") return `v.strictObject({${Object.entries(value).map(([name, item]) => `${JSON.stringify(name)}: ${buildLiteral(item)}`).join(", ")}})`;
|
|
1202
|
+
return `v.literal(${formatDefault(value)})`;
|
|
1203
|
+
}
|
|
1204
|
+
function buildEnum(values) {
|
|
1205
|
+
if (values.length === 1) return buildLiteral(values[0]);
|
|
1206
|
+
if (values.every((value) => typeof value === "string" || typeof value === "number")) return `v.picklist([${values.map((value) => formatDefault(value)).join(", ")}])`;
|
|
1207
|
+
return `v.union([${values.map((value) => buildLiteral(value)).join(", ")}])`;
|
|
1208
|
+
}
|
|
1209
|
+
function expectsDate(node, direction) {
|
|
1210
|
+
const resolved = _kubb_kit.ast.ref.mergeSchema(node);
|
|
1211
|
+
return direction === "encode" && (resolved.type === "date" || resolved.type === "time") && resolved.representation !== "string";
|
|
1212
|
+
}
|
|
1213
|
+
function hasPatternKeyCheck(node) {
|
|
1214
|
+
return node.type === "object" && node.additionalProperties === false && node.properties.length > 0 && Boolean(node.patternProperties);
|
|
1215
|
+
}
|
|
1216
|
+
function hasChecks(node) {
|
|
1217
|
+
return hasInputChecks(node) || hasPatternKeyCheck(node);
|
|
1218
|
+
}
|
|
1219
|
+
function countChecks(node) {
|
|
1220
|
+
const object = _kubb_kit.ast.schema.narrow(node, "object");
|
|
1221
|
+
return Number(object?.min !== void 0) + Number(object?.max !== void 0) + Number(hasKeyCheck(node)) + Number(hasPatternKeyCheck(node)) + (node.conditionals?.length ?? 0);
|
|
1222
|
+
}
|
|
1223
|
+
function applyModifiers({ value, schema, nullable, optional, nullish, defaultValue, title, description, examples, direction }) {
|
|
1224
|
+
const metadata = [
|
|
1225
|
+
title && `v.title(${_kubb_kit.text.quote(title)})`,
|
|
1226
|
+
description && `v.description(${_kubb_kit.text.quote(description)})`,
|
|
1227
|
+
examples?.length && `v.metadata({ examples: [${examples.map((example) => example === null ? "null" : formatDefault(example)).join(", ")}] })`
|
|
1228
|
+
].filter(Boolean);
|
|
1229
|
+
const described = metadata.length ? `v.pipe(${value}, ${metadata.join(", ")})` : value;
|
|
1230
|
+
const inner = nullable || nullish ? `v.nullable(${described})` : described;
|
|
1231
|
+
const literal = defaultValue !== void 0 && !expectsDate(schema, direction) ? defaultLiteral(schema, defaultValue) : null;
|
|
1232
|
+
if (literal !== null) return `v.optional(${inner}, ${literal})`;
|
|
1233
|
+
return optional || nullish ? `v.optional(${inner})` : inner;
|
|
1234
|
+
}
|
|
1235
|
+
function hasMetadata(node) {
|
|
1236
|
+
return node.type !== _kubb_kit.ast.schema.types.ref && Boolean(node.title || node.description || node.examples?.length);
|
|
1237
|
+
}
|
|
1238
|
+
function unwrapChain(node, direction) {
|
|
1239
|
+
const ref = _kubb_kit.ast.schema.narrow(node, "ref");
|
|
1240
|
+
if (!ref) return "";
|
|
1241
|
+
const target = ref.schema ?? ref;
|
|
1242
|
+
const meta = _kubb_kit.ast.ref.mergeSchema(target);
|
|
1243
|
+
const hasDefault = meta.default !== void 0 && !expectsDate(target, direction) && defaultLiteral(target, meta.default) !== null;
|
|
1244
|
+
const depth = Number(Boolean(meta.nullable || meta.nullish)) + Number(Boolean(meta.optional || meta.nullish || hasDefault));
|
|
1245
|
+
const inner = target !== ref && target.type === _kubb_kit.ast.schema.types.ref ? unwrapChain(target, direction) : "";
|
|
1246
|
+
return `${".wrapped".repeat(depth)}${inner}${hasMetadata(target) ? ".pipe[0]" : ""}`;
|
|
1247
|
+
}
|
|
1248
|
+
function objectEntries(ctx, properties) {
|
|
1249
|
+
return properties.map(({ name, schema, required }) => {
|
|
1250
|
+
const meta = _kubb_kit.ast.ref.mergeSchema(schema);
|
|
1251
|
+
const value = applyModifiers({
|
|
1252
|
+
value: ctx.transform(schema) ?? UNKNOWN,
|
|
1253
|
+
schema,
|
|
1254
|
+
nullable: meta.nullable,
|
|
1255
|
+
optional: schema.optional || required === false,
|
|
1256
|
+
nullish: schema.nullish,
|
|
1257
|
+
defaultValue: meta.default,
|
|
1258
|
+
title: schema.type === _kubb_kit.ast.schema.types.ref ? void 0 : schema.title,
|
|
1259
|
+
description: schema.type !== _kubb_kit.ast.schema.types.ref && meta.type === _kubb_kit.ast.schema.types.ref ? void 0 : meta.description,
|
|
1260
|
+
examples: meta.examples,
|
|
1261
|
+
direction: ctx.options.direction
|
|
1262
|
+
});
|
|
1263
|
+
return `${objectKey(name)}: ${value}`;
|
|
1264
|
+
});
|
|
1265
|
+
}
|
|
1266
|
+
function strictMember({ member, node, cyclicSchemas }) {
|
|
1267
|
+
if (node.type !== _kubb_kit.ast.schema.types.ref) return member;
|
|
1268
|
+
const refName = _kubb_kit.ast.ref.getName(node);
|
|
1269
|
+
if (refName && cyclicSchemas?.has(refName)) return member;
|
|
1270
|
+
const schema = _kubb_kit.ast.ref.mergeSchema(node);
|
|
1271
|
+
const isWrapped = schema.nullable || schema.optional || schema.nullish || schema.default !== void 0 || node.nullable || node.optional;
|
|
1272
|
+
return schema.type === _kubb_kit.ast.schema.types.object && (schema.additionalProperties === void 0 || schema.additionalProperties === false) && !schema.patternProperties && !schema.propertyNames && !hasChecks(schema) && !isWrapped ? `v.strictObject(${member}.entries)` : member;
|
|
1273
|
+
}
|
|
1274
|
+
function containsCheck(ctx, { schema, min = 1, max }) {
|
|
1275
|
+
if (min === 0 && max === void 0) return false;
|
|
1276
|
+
const bounds = [`count >= ${min}`, max !== void 0 && `count <= ${max}`].filter(Boolean).join(" && ");
|
|
1277
|
+
const message = max !== void 0 ? `Array must contain ${min} to ${max} matching items` : `Array must contain at least ${min} matching items`;
|
|
1278
|
+
return `v.check((items) => { const count = items.filter((item) => v.is(${ctx.transform(schema) ?? UNKNOWN}, item)).length; return ${bounds} }, ${JSON.stringify(message)})`;
|
|
1279
|
+
}
|
|
1280
|
+
function conditionExpression(ctx, schema) {
|
|
1281
|
+
if (!schema) return "true";
|
|
1282
|
+
const object = _kubb_kit.ast.schema.narrow(schema, _kubb_kit.ast.schema.types.object);
|
|
1283
|
+
const keyOnlyNames = object?.properties.filter((property) => property.required && property.schema.type === _kubb_kit.ast.schema.types.unknown).map((property) => property.name) ?? [];
|
|
1284
|
+
const restSchema = object ? {
|
|
1285
|
+
...object,
|
|
1286
|
+
properties: object.properties.filter((property) => !keyOnlyNames.includes(property.name))
|
|
1287
|
+
} : schema;
|
|
1288
|
+
const isOnlyKeys = keyOnlyNames.length > 0 && restSchema.type === "object" && restSchema.properties.length === 0 && restSchema.additionalProperties === void 0 && !restSchema.patternProperties && !restSchema.propertyNames && !hasChecks(restSchema);
|
|
1289
|
+
return [keyOnlyNames.length > 0 && `typeof value === "object" && value !== null && ${JSON.stringify(keyOnlyNames)}.every((key) => key in value)`, !isOnlyKeys && `v.is(${ctx.transform(restSchema) ?? UNKNOWN}, value)`].filter(Boolean).join(" && ");
|
|
1290
|
+
}
|
|
1291
|
+
function inputChecks(ctx, node) {
|
|
1292
|
+
const { min, max } = node.type === "object" ? node : {};
|
|
1293
|
+
const keySchema = hasKeyCheck(node) ? ctx.transform(node.propertyNames) : null;
|
|
1294
|
+
const patternKeys = hasPatternKeyCheck(node) ? `${JSON.stringify(node.properties.map((property) => property.name))}.includes(key) || ${Object.keys(node.patternProperties).map((pattern) => `${toRegExpString(pattern, ctx.options.regexType === "constructor" ? "RegExp" : null)}.test(key)`).join(" || ")}` : null;
|
|
1295
|
+
return [
|
|
1296
|
+
min !== void 0 && `v.check((value) => ${NOT_OBJECT} || Object.keys(value).length >= ${min}, "Object must have at least ${min} properties")`,
|
|
1297
|
+
max !== void 0 && `v.check((value) => ${NOT_OBJECT} || Object.keys(value).length <= ${max}, "Object must have at most ${max} properties")`,
|
|
1298
|
+
keySchema && `v.check((value) => ${NOT_OBJECT} || Object.keys(value).every((key) => v.is(${keySchema}, key)), "Object keys must match the property names schema")`,
|
|
1299
|
+
patternKeys && `v.check((value) => ${NOT_OBJECT} || Object.keys(value).every((key) => ${patternKeys}), "Object keys must be declared or match a pattern")`,
|
|
1300
|
+
...(node.conditionals ?? []).map((entry) => `v.check((value) => (${conditionExpression(ctx, entry.if)} ? ${conditionExpression(ctx, entry.then)} : ${conditionExpression(ctx, entry.else)}), "Value does not meet a conditional schema")`)
|
|
1301
|
+
].filter((check) => Boolean(check));
|
|
1302
|
+
}
|
|
1303
|
+
function withInputChecks(nodes, isSkipped) {
|
|
1304
|
+
const wrapHandler = (type) => {
|
|
1305
|
+
const handler = nodes[type];
|
|
1306
|
+
if (!handler) return [];
|
|
1307
|
+
const checkedHandler = function(node) {
|
|
1308
|
+
const output = handler.call(this, node);
|
|
1309
|
+
if (!output || isSkipped(node) || !hasChecks(node)) return output;
|
|
1310
|
+
return pipe(UNKNOWN, [...inputChecks(this, node), output]);
|
|
1311
|
+
};
|
|
1312
|
+
return [[type, checkedHandler]];
|
|
1313
|
+
};
|
|
1314
|
+
return Object.fromEntries(Object.values(_kubb_kit.ast.schema.types).flatMap(wrapHandler));
|
|
1315
|
+
}
|
|
1316
|
+
/**
|
|
1317
|
+
* The handlers that print differently per direction. `date` and `time` decode a wire string into a
|
|
1318
|
+
* `Date` on responses and encode it back on requests. Only `representation: 'date'` fields convert.
|
|
1319
|
+
* `time` has no date part, so it decodes onto `1970-01-01` and encodes back to `HH:mm:ssZ`, with milliseconds when it has them.
|
|
1320
|
+
*/
|
|
1321
|
+
const directionalNodes = {
|
|
1322
|
+
date(node) {
|
|
1323
|
+
if (node.representation !== "date") return "v.pipe(v.string(), v.isoDate())";
|
|
1324
|
+
if (this.options.direction === "encode") return node.format === "date" ? "v.pipe(v.date(), v.transform((value) => value.toISOString().slice(0, 10)))" : "v.pipe(v.date(), v.transform((value) => value.toISOString()))";
|
|
1325
|
+
if (shouldCoerce(this.options.coercion, "dates")) return "v.pipe(v.unknown(), v.toDate())";
|
|
1326
|
+
return node.format === "date" ? "v.pipe(v.string(), v.isoDate(), v.transform((value) => new Date(value)))" : "v.pipe(v.string(), v.isoTimestamp(), v.transform((value) => new Date(value)))";
|
|
1327
|
+
},
|
|
1328
|
+
time(node) {
|
|
1329
|
+
if (node.representation === "string") return "v.string()";
|
|
1330
|
+
if (this.options.direction === "encode") return "v.pipe(v.date(), v.transform((value) => value.toISOString().slice(11).replace(\".000Z\", \"Z\")))";
|
|
1331
|
+
return "v.pipe(v.string(), v.transform((value) => new Date(`1970-01-01T${value}${/(?:z|[+-]\\d{2}:\\d{2})$/i.test(value) ? \"\" : \"Z\"}`)), v.date())";
|
|
1332
|
+
}
|
|
1333
|
+
};
|
|
1334
|
+
function variesByDirection({ node, printerOptions }) {
|
|
1335
|
+
const handler = printerOptions.nodes?.[node.type] ?? directionalNodes[node.type];
|
|
1336
|
+
if (!handler) return false;
|
|
1337
|
+
const call = (direction) => {
|
|
1338
|
+
const context = {
|
|
1339
|
+
options: {
|
|
1340
|
+
...printerOptions,
|
|
1341
|
+
direction
|
|
1342
|
+
},
|
|
1343
|
+
transform: () => null,
|
|
1344
|
+
base: () => null,
|
|
1345
|
+
import: () => {}
|
|
1346
|
+
};
|
|
1347
|
+
return handler.call(context, node);
|
|
1348
|
+
};
|
|
1349
|
+
return call("decode") !== call("encode");
|
|
1350
|
+
}
|
|
1351
|
+
/**
|
|
1352
|
+
* Whether the schema contains a node that prints differently per direction, so it decodes on
|
|
1353
|
+
* responses and encodes on requests. Follows a `$ref` through its resolved schema.
|
|
1354
|
+
*/
|
|
1355
|
+
function containsDirectionalNode({ node, printerOptions }) {
|
|
1356
|
+
if (!node) return false;
|
|
1357
|
+
const { resolver, nodes, coercion, dateType } = printerOptions;
|
|
1358
|
+
const cache = resolver && !nodes ? resolver.memo(`valibotDirectionalNodes:${shouldCoerce(coercion, "dates")}:${dateType}`, () => /* @__PURE__ */ new WeakMap()) : void 0;
|
|
1359
|
+
return _kubb_kit.ast.schema.find(node, {
|
|
1360
|
+
predicate: (schema) => variesByDirection({
|
|
1361
|
+
node: schema,
|
|
1362
|
+
printerOptions
|
|
1363
|
+
}),
|
|
1364
|
+
followRefs: true,
|
|
1365
|
+
cache
|
|
1366
|
+
}) !== void 0;
|
|
1367
|
+
}
|
|
1368
|
+
/**
|
|
1369
|
+
* Names of the `$ref` schemas a request schema reads from their `${name}InputSchema` variant.
|
|
1370
|
+
*/
|
|
1371
|
+
function collectDirectionalRefNames({ node, printerOptions }) {
|
|
1372
|
+
return _kubb_kit.ast.node.collect(node, { schema: (n) => n.type === _kubb_kit.ast.schema.types.ref && n.ref && containsDirectionalNode({
|
|
1373
|
+
node: n,
|
|
1374
|
+
printerOptions
|
|
1375
|
+
}) ? _kubb_kit.ast.ref.getName(n) ?? void 0 : void 0 });
|
|
1376
|
+
}
|
|
1377
|
+
/**
|
|
1378
|
+
* Valibot v1 printer. Turns a `SchemaNode` into the code of a Valibot schema.
|
|
1379
|
+
*
|
|
1380
|
+
* @example
|
|
1381
|
+
* ```ts
|
|
1382
|
+
* const printer = printerValibot({})
|
|
1383
|
+
*
|
|
1384
|
+
* printer.print(ast.factory.createSchema({ type: 'string', min: 1 })) // 'v.pipe(v.string(), v.minLength(1))'
|
|
1385
|
+
* ```
|
|
1386
|
+
*/
|
|
1387
|
+
const printerValibot = (0, _kubb_kit.createPrinter)((options) => {
|
|
1388
|
+
const { cyclicSchemas } = options;
|
|
1389
|
+
const isObjectNode = (node) => {
|
|
1390
|
+
const resolved = _kubb_kit.ast.ref.mergeSchema(node);
|
|
1391
|
+
return isObjectSchemaNode(node, cyclicSchemas) && resolved.default === void 0 && !hasPatternKeyCheck(resolved);
|
|
1392
|
+
};
|
|
1393
|
+
let uncheckedNode = null;
|
|
1394
|
+
const unionsWithSiblings = /* @__PURE__ */ new WeakSet();
|
|
1395
|
+
const printNullable = (schema, output) => output && schema.nullable ? `v.nullable(${output})` : output;
|
|
1396
|
+
const formatString = (action, node) => pipe("v.string()", [action, ...lengthActions(node, options.regexType)]);
|
|
1397
|
+
const mergesToObject = (node) => {
|
|
1398
|
+
const [first, ...rest] = _kubb_kit.ast.schema.narrow(node, _kubb_kit.ast.schema.types.intersection)?.members ?? [];
|
|
1399
|
+
if (!first || rest.length === 0) return false;
|
|
1400
|
+
const baseObject = _kubb_kit.ast.schema.narrow(_kubb_kit.ast.ref.mergeSchema(first), _kubb_kit.ast.schema.types.object);
|
|
1401
|
+
return !(Boolean(baseObject?.patternProperties) || baseObject?.additionalProperties !== void 0 && typeof baseObject.additionalProperties !== "boolean") && isObjectNode(first) && isObjectComposableIntersection(node, cyclicSchemas);
|
|
1402
|
+
};
|
|
1403
|
+
const printsEntries = (node) => {
|
|
1404
|
+
const ref = _kubb_kit.ast.schema.narrow(node, _kubb_kit.ast.schema.types.ref);
|
|
1405
|
+
if (ref?.schema && ref.schema !== ref) return printsEntries(ref.schema);
|
|
1406
|
+
if (ref) return true;
|
|
1407
|
+
return node.type === _kubb_kit.ast.schema.types.object ? node.properties.length > 0 : mergesToObject(node);
|
|
1408
|
+
};
|
|
1409
|
+
function omitKeys({ node, transformed, keysToOmit }) {
|
|
1410
|
+
const target = _kubb_kit.ast.schema.narrow(node, "ref")?.schema ?? node;
|
|
1411
|
+
const keys = `[${keysToOmit.map((key) => _kubb_kit.text.quote(key)).join(", ")}]`;
|
|
1412
|
+
if (transformed.startsWith("v.lazy(")) return transformed;
|
|
1413
|
+
const base = `${transformed}${unwrapChain(node, this.options.direction)}`;
|
|
1414
|
+
if (!hasChecks(target)) return `v.omit(${base}, ${keys})`;
|
|
1415
|
+
if (node.type === _kubb_kit.ast.schema.types.ref) {
|
|
1416
|
+
const count = countChecks(target);
|
|
1417
|
+
const checks = Array.from({ length: count }, (_, index) => `${base}.pipe[${index + 1}]`);
|
|
1418
|
+
return pipe(UNKNOWN, [...checks, `v.omit(${base}.pipe[${count + 1}], ${keys})`]);
|
|
1419
|
+
}
|
|
1420
|
+
uncheckedNode = node;
|
|
1421
|
+
try {
|
|
1422
|
+
return pipe(UNKNOWN, [...inputChecks(this, node), `v.omit(${this.transform(node)}, ${keys})`]);
|
|
1423
|
+
} finally {
|
|
1424
|
+
uncheckedNode = null;
|
|
1425
|
+
}
|
|
1426
|
+
}
|
|
1427
|
+
return {
|
|
1428
|
+
name: "valibot",
|
|
1429
|
+
options,
|
|
1430
|
+
nodes: withInputChecks({
|
|
1431
|
+
any: () => "v.any()",
|
|
1432
|
+
unknown: () => UNKNOWN,
|
|
1433
|
+
void: () => "v.void()",
|
|
1434
|
+
never: () => "v.never()",
|
|
1435
|
+
boolean: () => "v.boolean()",
|
|
1436
|
+
null: () => "v.null()",
|
|
1437
|
+
blob: () => "v.blob()",
|
|
1438
|
+
ipv4: () => "v.pipe(v.string(), v.ipv4())",
|
|
1439
|
+
ipv6: () => "v.pipe(v.string(), v.ipv6())",
|
|
1440
|
+
string(node) {
|
|
1441
|
+
const coerce = shouldCoerce(this.options.coercion, "strings");
|
|
1442
|
+
const format = stringFormatActions.get(node.format) ?? (node.content?.encoding?.toLowerCase() === "base64" ? "v.base64()" : void 0);
|
|
1443
|
+
const pattern = node.pattern ?? integerFormatPattern(node.format);
|
|
1444
|
+
const actions = [
|
|
1445
|
+
coerce && "v.toString()",
|
|
1446
|
+
format,
|
|
1447
|
+
...lengthActions({
|
|
1448
|
+
...node,
|
|
1449
|
+
pattern
|
|
1450
|
+
}, this.options.regexType)
|
|
1451
|
+
];
|
|
1452
|
+
const contentNode = _kubb_kit.ast.schema.getEmbeddedJson(node);
|
|
1453
|
+
if (!contentNode) return pipe(coerce ? UNKNOWN : "v.string()", actions);
|
|
1454
|
+
const { direction } = this.options;
|
|
1455
|
+
this.options.direction = "decode";
|
|
1456
|
+
let content;
|
|
1457
|
+
try {
|
|
1458
|
+
content = this.transform(contentNode);
|
|
1459
|
+
} finally {
|
|
1460
|
+
this.options.direction = direction;
|
|
1461
|
+
}
|
|
1462
|
+
return pipe(coerce ? UNKNOWN : "v.string()", [...actions, content && `v.check((value) => { try { return v.is(${content}, JSON.parse(value)) } catch { return false } }, "String must hold JSON that matches its content schema")`]);
|
|
1463
|
+
},
|
|
1464
|
+
uuid: (node) => formatString("v.uuid()", node),
|
|
1465
|
+
email: (node) => formatString("v.email()", node),
|
|
1466
|
+
url: (node) => formatString("v.url()", node),
|
|
1467
|
+
number(node) {
|
|
1468
|
+
const coerce = shouldCoerce(this.options.coercion, "numbers");
|
|
1469
|
+
return pipe(coerce ? UNKNOWN : "v.number()", [coerce && "v.toNumber()", ...numberActions(node)]);
|
|
1470
|
+
},
|
|
1471
|
+
integer(node) {
|
|
1472
|
+
const coerce = shouldCoerce(this.options.coercion, "numbers");
|
|
1473
|
+
return pipe(coerce ? UNKNOWN : "v.number()", [
|
|
1474
|
+
coerce && "v.toNumber()",
|
|
1475
|
+
"v.integer()",
|
|
1476
|
+
...numberActions(withFormatRange(node, "integer"))
|
|
1477
|
+
]);
|
|
1478
|
+
},
|
|
1479
|
+
bigint(node) {
|
|
1480
|
+
return pipe("v.union([v.bigint(), v.number(), v.string()])", ["v.toBigint()", ...numberActions(withFormatRange({
|
|
1481
|
+
...bigintConstraints(node),
|
|
1482
|
+
format: node.format
|
|
1483
|
+
}, "bigint"), true)]);
|
|
1484
|
+
},
|
|
1485
|
+
...directionalNodes,
|
|
1486
|
+
datetime(node) {
|
|
1487
|
+
return node.local || this.options.dateType === "stringLocal" ? "v.string()" : "v.pipe(v.string(), v.isoTimestamp())";
|
|
1488
|
+
},
|
|
1489
|
+
enum(node) {
|
|
1490
|
+
return buildEnum(_kubb_kit.ast.schema.getLiterals(node).filter((value) => value !== null));
|
|
1491
|
+
},
|
|
1492
|
+
ref(node) {
|
|
1493
|
+
if (!node.name) return null;
|
|
1494
|
+
const refName = _kubb_kit.ast.ref.getName(node);
|
|
1495
|
+
if (!refName) return null;
|
|
1496
|
+
const useInputVariant = node.ref != null && this.options.direction === "encode" && containsDirectionalNode({
|
|
1497
|
+
node,
|
|
1498
|
+
printerOptions: this.options
|
|
1499
|
+
});
|
|
1500
|
+
const resolver = this.options.resolver;
|
|
1501
|
+
const resolvedName = node.ref ? (useInputVariant ? resolver?.schema.inputName(refName) : resolver?.name(refName)) ?? refName : node.name;
|
|
1502
|
+
return node.ref && cyclicSchemas?.has(refName) ? `v.lazy(() => ${resolvedName})` : resolvedName;
|
|
1503
|
+
},
|
|
1504
|
+
object(node) {
|
|
1505
|
+
const hasProperties = node.properties.length > 0;
|
|
1506
|
+
const patterns = node.patternProperties ? Object.entries(node.patternProperties) : [];
|
|
1507
|
+
const shape = buildObject(objectEntries(this, node.properties));
|
|
1508
|
+
const keySchema = node.propertyNames ? this.transform(node.propertyNames) : null;
|
|
1509
|
+
const isStrict = node.additionalProperties === false && patterns.length === 0;
|
|
1510
|
+
if (node.additionalProperties && node.additionalProperties !== true) {
|
|
1511
|
+
const rest = this.transform(node.additionalProperties);
|
|
1512
|
+
if (rest) return hasProperties ? `v.objectWithRest(${shape}, ${rest})` : `v.record(${keySchema ?? "v.string()"}, ${rest})`;
|
|
1513
|
+
}
|
|
1514
|
+
if (isStrict) return `v.strictObject(${shape})`;
|
|
1515
|
+
if (!hasProperties && patterns.length === 0 && keySchema) return `v.record(${keySchema}, ${UNKNOWN})`;
|
|
1516
|
+
if (node.additionalProperties === true) return `v.looseObject(${shape})`;
|
|
1517
|
+
if (patterns.length > 0) {
|
|
1518
|
+
const values = [...new Set(patterns.map(([, schema]) => printNullable(schema, this.transform(schema) ?? UNKNOWN)))];
|
|
1519
|
+
const value = values.length === 1 ? values[0] : `v.union(${buildList(values)})`;
|
|
1520
|
+
if (hasProperties) return `v.objectWithRest(${shape}, ${value})`;
|
|
1521
|
+
return `v.record(${pipe("v.string()", lengthActions({ pattern: patterns.length === 1 ? patterns[0][0] : patterns.map(([pattern]) => `(${pattern})`).join("|") }, this.options.regexType))}, ${value})`;
|
|
1522
|
+
}
|
|
1523
|
+
return `v.object(${shape})`;
|
|
1524
|
+
},
|
|
1525
|
+
array(node) {
|
|
1526
|
+
const items = (node.items ?? []).map((item) => printNullable(item, this.transform(item))).filter((item) => Boolean(item));
|
|
1527
|
+
return pipe(`v.array(${items.length > 1 ? `v.union(${buildList(items)})` : items[0] ?? UNKNOWN})`, [
|
|
1528
|
+
...lengthActions({
|
|
1529
|
+
min: node.min,
|
|
1530
|
+
max: node.max
|
|
1531
|
+
}, this.options.regexType),
|
|
1532
|
+
node.unique && "v.check((items) => new Set(items).size === items.length, \"Array entries must be unique\")",
|
|
1533
|
+
node.contains && containsCheck(this, node.contains)
|
|
1534
|
+
]);
|
|
1535
|
+
},
|
|
1536
|
+
tuple(node) {
|
|
1537
|
+
const items = buildList((node.items ?? []).map((item) => printNullable(item, this.transform(item))).filter((item) => Boolean(item)));
|
|
1538
|
+
const rest = node.rest ? this.transform(node.rest) : null;
|
|
1539
|
+
return pipe(rest ? `v.tupleWithRest(${items}, ${rest})` : `v.tuple(${items})`, [node.contains && containsCheck(this, node.contains)]);
|
|
1540
|
+
},
|
|
1541
|
+
union(node) {
|
|
1542
|
+
const nodeMembers = node.members ?? [];
|
|
1543
|
+
const { discriminatorPropertyName } = node;
|
|
1544
|
+
const isDiscriminated = !!discriminatorPropertyName && nodeMembers.every(isObjectNode);
|
|
1545
|
+
const isXor = node.strategy === "one" && !isDiscriminated && this.options.oneOfType === "xor";
|
|
1546
|
+
const isStrict = node.strategy === "one" && !isXor && !isDiscriminated && !unionsWithSiblings.has(node);
|
|
1547
|
+
const members = nodeMembers.map((member) => {
|
|
1548
|
+
const output = this.transform(isStrict ? strictOneOfNode(member) : member);
|
|
1549
|
+
return printNullable(member, output && isStrict ? strictMember({
|
|
1550
|
+
member: output,
|
|
1551
|
+
node: member,
|
|
1552
|
+
cyclicSchemas
|
|
1553
|
+
}) : output);
|
|
1554
|
+
}).filter((member) => Boolean(member));
|
|
1555
|
+
if (members.length === 0) return "";
|
|
1556
|
+
if (members.length === 1) return members[0];
|
|
1557
|
+
if (isDiscriminated) return `v.variant(${_kubb_kit.text.quote(discriminatorPropertyName)}, ${buildList(members)})`;
|
|
1558
|
+
const union = `v.union(${buildList(members)})`;
|
|
1559
|
+
return isXor ? `((schema) => v.pipe(v.unknown(), v.check((value) => schema.options.filter((member) => v.is(member, value)).length === 1, "Value must match exactly one schema"), schema))(${union})` : union;
|
|
1560
|
+
},
|
|
1561
|
+
intersection(node) {
|
|
1562
|
+
const members = node.members ?? [];
|
|
1563
|
+
const [first, ...rest] = members;
|
|
1564
|
+
if (!first) return "";
|
|
1565
|
+
const hasSiblingProperties = members.some((member) => member.type === _kubb_kit.ast.schema.types.object && member.properties.length > 0);
|
|
1566
|
+
const transform = (member) => {
|
|
1567
|
+
if (!hasSiblingProperties) return this.transform(member);
|
|
1568
|
+
unionsWithSiblings.add(member);
|
|
1569
|
+
try {
|
|
1570
|
+
return this.transform(member);
|
|
1571
|
+
} finally {
|
|
1572
|
+
unionsWithSiblings.delete(member);
|
|
1573
|
+
}
|
|
1574
|
+
};
|
|
1575
|
+
const firstBase = transform(first);
|
|
1576
|
+
if (!firstBase) return "";
|
|
1577
|
+
const base = _kubb_kit.ast.ref.mergeSchema(first);
|
|
1578
|
+
const baseObject = _kubb_kit.ast.schema.narrow(base, _kubb_kit.ast.schema.types.object);
|
|
1579
|
+
if (mergesToObject(node)) {
|
|
1580
|
+
const discriminator = _kubb_kit.ast.schema.narrow(first, _kubb_kit.ast.schema.types.union)?.discriminatorPropertyName;
|
|
1581
|
+
const properties = new Map(preserveRequiredProperties(members).slice(1).flatMap((member) => _kubb_kit.ast.schema.narrow(member, _kubb_kit.ast.schema.types.object)?.properties ?? []).filter((property) => property.name !== discriminator).map((property) => [property.name, property]));
|
|
1582
|
+
const additional = baseObject?.additionalProperties;
|
|
1583
|
+
return `${additional === true ? "v.looseObject" : additional === false ? "v.strictObject" : "v.object"}(${buildObject([`...${firstBase}.entries`, ...objectEntries(this, [...properties.values()])])})`;
|
|
1584
|
+
}
|
|
1585
|
+
const schemas = [firstBase];
|
|
1586
|
+
const actions = [];
|
|
1587
|
+
for (const member of rest) {
|
|
1588
|
+
const constraints = memberActions({
|
|
1589
|
+
member,
|
|
1590
|
+
base,
|
|
1591
|
+
regexType: this.options.regexType
|
|
1592
|
+
});
|
|
1593
|
+
const transformed = constraints.length ? null : transform(member);
|
|
1594
|
+
actions.push(...constraints);
|
|
1595
|
+
if (transformed) schemas.push(transformed);
|
|
1596
|
+
}
|
|
1597
|
+
return pipe(schemas.length > 1 ? `v.intersect(${buildList(schemas)})` : firstBase, actions);
|
|
1598
|
+
}
|
|
1599
|
+
}, (node) => node === uncheckedNode),
|
|
1600
|
+
overrides: options.nodes,
|
|
1601
|
+
print(node) {
|
|
1602
|
+
const transformed = this.transform(node);
|
|
1603
|
+
if (!transformed) return null;
|
|
1604
|
+
const { keysToOmit, direction } = this.options;
|
|
1605
|
+
const meta = _kubb_kit.ast.ref.mergeSchema(node);
|
|
1606
|
+
return applyModifiers({
|
|
1607
|
+
value: keysToOmit?.length && printsEntries(node) ? omitKeys.call(this, {
|
|
1608
|
+
node,
|
|
1609
|
+
transformed,
|
|
1610
|
+
keysToOmit
|
|
1611
|
+
}) : transformed,
|
|
1612
|
+
schema: node,
|
|
1613
|
+
nullable: meta.nullable,
|
|
1614
|
+
optional: meta.optional,
|
|
1615
|
+
nullish: meta.nullish,
|
|
1616
|
+
defaultValue: meta.default,
|
|
1617
|
+
title: hasMetadata(node) ? meta.title : void 0,
|
|
1618
|
+
description: hasMetadata(node) ? meta.description : void 0,
|
|
1619
|
+
examples: hasMetadata(node) ? meta.examples : void 0,
|
|
1620
|
+
direction
|
|
1621
|
+
});
|
|
1622
|
+
}
|
|
1623
|
+
};
|
|
1624
|
+
});
|
|
1625
|
+
// src/generators/valibotGenerator.tsx
|
|
1626
|
+
/**
|
|
1627
|
+
* The printer for one direction, built once per plugin per build. A `keysToOmit` list and a
|
|
1628
|
+
* `printer.nodes` override differ per node and have no string key, so they get a fresh printer.
|
|
1629
|
+
*/
|
|
1630
|
+
function getPrinter(resolver, options, direction) {
|
|
1631
|
+
const build = () => printerValibot({
|
|
1632
|
+
...options,
|
|
1633
|
+
direction
|
|
1634
|
+
});
|
|
1635
|
+
if (options.nodes || options.keysToOmit?.length) return build();
|
|
1636
|
+
return resolver.memo(`valibotPrinter:${[
|
|
1637
|
+
direction,
|
|
1638
|
+
JSON.stringify(options.coercion),
|
|
1639
|
+
options.regexType,
|
|
1640
|
+
options.oneOfType,
|
|
1641
|
+
options.dateType
|
|
1642
|
+
].join(":")}`, build);
|
|
1643
|
+
}
|
|
1644
|
+
const inferKinds = {
|
|
1645
|
+
encode: "InferInput",
|
|
1646
|
+
decode: "InferOutput"
|
|
1647
|
+
};
|
|
1648
|
+
/**
|
|
1649
|
+
* Built-in generator for `@kubb/plugin-valibot`. Emits one Valibot schema per schema in the spec,
|
|
1650
|
+
* plus the parameter, request, and response schemas of each operation.
|
|
1651
|
+
*/
|
|
1652
|
+
const valibotGenerator = (0, _kubb_kit.defineGenerator)({
|
|
1653
|
+
name: "valibot",
|
|
1654
|
+
renderer: _kubb_renderer_jsx.jsxRenderer,
|
|
1655
|
+
schema(node, ctx) {
|
|
1656
|
+
const { adapter, config, resolver, root } = ctx;
|
|
1657
|
+
const { output, regexType, oneOfType, coercion, inferred, typeGuards, importPath, group, printer } = ctx.options;
|
|
1658
|
+
if (!node.name) return;
|
|
1659
|
+
const cyclicSchemas = getCircularNames(ctx);
|
|
1660
|
+
const printerOptions = {
|
|
1661
|
+
regexType,
|
|
1662
|
+
oneOfType,
|
|
1663
|
+
coercion,
|
|
1664
|
+
dateType: getOasAdapter(adapter).options.dateType,
|
|
1665
|
+
resolver,
|
|
1666
|
+
cyclicSchemas,
|
|
1667
|
+
nodes: printer?.nodes
|
|
1668
|
+
};
|
|
1669
|
+
const hasDirectionalNode = containsDirectionalNode({
|
|
1670
|
+
node,
|
|
1671
|
+
printerOptions
|
|
1672
|
+
});
|
|
1673
|
+
const inputImports = hasDirectionalNode ? collectDirectionalRefNames({
|
|
1674
|
+
node,
|
|
1675
|
+
printerOptions
|
|
1676
|
+
}).map((schemaName) => ({
|
|
1677
|
+
name: [resolver.schema.inputName(schemaName)],
|
|
1678
|
+
path: resolver.file({
|
|
1679
|
+
name: schemaName,
|
|
1680
|
+
extname: ".ts",
|
|
1681
|
+
root,
|
|
1682
|
+
output,
|
|
1683
|
+
group: group ?? void 0
|
|
1684
|
+
}).path
|
|
1685
|
+
})) : [];
|
|
1686
|
+
const imports = [...new Map([...resolver.imports({
|
|
1687
|
+
node,
|
|
1688
|
+
root,
|
|
1689
|
+
output,
|
|
1690
|
+
group: group ?? void 0,
|
|
1691
|
+
checks: true
|
|
1692
|
+
}), ...inputImports].map((imp) => [`${Array.isArray(imp.name) ? imp.name.join(",") : imp.name}|${imp.path}`, imp])).values()];
|
|
1693
|
+
const inputName = resolver.schema.inputName(node.name);
|
|
1694
|
+
const meta = {
|
|
1695
|
+
name: resolver.name(node.name),
|
|
1696
|
+
file: resolver.file({
|
|
1697
|
+
name: node.name,
|
|
1698
|
+
extname: ".ts",
|
|
1699
|
+
root,
|
|
1700
|
+
output,
|
|
1701
|
+
group: group ?? void 0
|
|
1702
|
+
})
|
|
1703
|
+
};
|
|
1704
|
+
return /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsxs)(_kubb_renderer_jsx.File, {
|
|
1705
|
+
baseName: meta.file.baseName,
|
|
1706
|
+
path: meta.file.path,
|
|
1707
|
+
meta: meta.file.meta,
|
|
1708
|
+
banner: resolver.default.banner(ctx.meta, {
|
|
1709
|
+
output,
|
|
1710
|
+
config,
|
|
1711
|
+
file: {
|
|
1712
|
+
path: meta.file.path,
|
|
1713
|
+
baseName: meta.file.baseName
|
|
1714
|
+
}
|
|
1715
|
+
}),
|
|
1716
|
+
footer: resolver.default.footer(ctx.meta, {
|
|
1717
|
+
output,
|
|
1718
|
+
config,
|
|
1719
|
+
file: {
|
|
1720
|
+
path: meta.file.path,
|
|
1721
|
+
baseName: meta.file.baseName
|
|
1722
|
+
}
|
|
1723
|
+
}),
|
|
1724
|
+
children: [
|
|
1725
|
+
/* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.File.Import, {
|
|
1726
|
+
name: "v",
|
|
1727
|
+
path: importPath,
|
|
1728
|
+
isNameSpace: true
|
|
1729
|
+
}),
|
|
1730
|
+
imports.map((imp) => /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.File.Import, {
|
|
1731
|
+
root: meta.file.path,
|
|
1732
|
+
path: imp.path,
|
|
1733
|
+
name: imp.name
|
|
1734
|
+
}, [
|
|
1735
|
+
node.name,
|
|
1736
|
+
imp.path,
|
|
1737
|
+
imp.name
|
|
1738
|
+
].join("-"))),
|
|
1739
|
+
/* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(Valibot, {
|
|
1740
|
+
name: meta.name,
|
|
1741
|
+
node,
|
|
1742
|
+
printer: getPrinter(resolver, printerOptions, "decode"),
|
|
1743
|
+
inferTypeName: inferred ? resolver.schema.typeName(node.name) : null,
|
|
1744
|
+
typeGuards,
|
|
1745
|
+
isName: resolver.schema.isName(node.name),
|
|
1746
|
+
assertName: resolver.schema.assertName(node.name),
|
|
1747
|
+
cyclic: cyclicSchemas.has(node.name),
|
|
1748
|
+
comments: schemaComments(node)
|
|
1749
|
+
}),
|
|
1750
|
+
hasDirectionalNode && /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(Valibot, {
|
|
1751
|
+
name: inputName,
|
|
1752
|
+
node,
|
|
1753
|
+
printer: getPrinter(resolver, printerOptions, "encode"),
|
|
1754
|
+
inferTypeName: inferred ? resolver.schema.inputTypeName(node.name) : null,
|
|
1755
|
+
inferKind: "InferInput",
|
|
1756
|
+
typeGuards,
|
|
1757
|
+
isName: resolver.schema.isName(inputName),
|
|
1758
|
+
assertName: resolver.schema.assertName(inputName),
|
|
1759
|
+
cyclic: cyclicSchemas.has(node.name),
|
|
1760
|
+
comments: schemaComments(node)
|
|
1761
|
+
})
|
|
1762
|
+
]
|
|
1763
|
+
});
|
|
1764
|
+
},
|
|
1765
|
+
operation(node, ctx) {
|
|
1766
|
+
if (!_kubb_kit.ast.http.isOperation(node)) return null;
|
|
1767
|
+
const { adapter, config, resolver, root } = ctx;
|
|
1768
|
+
const { output, regexType, oneOfType, coercion, inferred, importPath, group, printer } = ctx.options;
|
|
1769
|
+
const dateType = getOasAdapter(adapter).options.dateType;
|
|
1770
|
+
const meta = { file: resolveOperationFile({
|
|
1771
|
+
ctx,
|
|
1772
|
+
node,
|
|
1773
|
+
resolver,
|
|
1774
|
+
root,
|
|
1775
|
+
output,
|
|
1776
|
+
group
|
|
1777
|
+
}) };
|
|
1778
|
+
const cyclicSchemas = getCircularNames(ctx);
|
|
1779
|
+
const printerOptions = {
|
|
1780
|
+
regexType,
|
|
1781
|
+
oneOfType,
|
|
1782
|
+
coercion,
|
|
1783
|
+
dateType,
|
|
1784
|
+
resolver,
|
|
1785
|
+
cyclicSchemas,
|
|
1786
|
+
nodes: printer?.nodes
|
|
1787
|
+
};
|
|
1788
|
+
function renderSchemaEntry({ schema, name, keysToOmit, direction = "decode" }) {
|
|
1789
|
+
if (!schema) return null;
|
|
1790
|
+
const refName = schema.type === "ref" ? _kubb_kit.ast.ref.getName(schema) : null;
|
|
1791
|
+
const target = schema.type === "ref" ? schema.schema : void 0;
|
|
1792
|
+
if (keysToOmit?.length && target && refName && cyclicSchemas.has(refName)) {
|
|
1793
|
+
const declaresKey = (node) => keysToOmit.some((propertyName) => _kubb_kit.ast.schema.findProperties({
|
|
1794
|
+
node,
|
|
1795
|
+
propertyName
|
|
1796
|
+
}).length > 0);
|
|
1797
|
+
const withoutKeys = (node, seen = /* @__PURE__ */ new Set()) => {
|
|
1798
|
+
if (node.type === "object") return {
|
|
1799
|
+
...node,
|
|
1800
|
+
properties: node.properties.filter((property) => !keysToOmit.includes(property.name))
|
|
1801
|
+
};
|
|
1802
|
+
if (node.type === "intersection") return {
|
|
1803
|
+
...node,
|
|
1804
|
+
members: (node.members ?? []).map((member) => withoutKeys(member, seen))
|
|
1805
|
+
};
|
|
1806
|
+
if (node.type !== "ref" || !node.schema || seen.has(node.schema) || !declaresKey(node.schema)) return node;
|
|
1807
|
+
return withoutKeys(node.schema, new Set(seen).add(node.schema));
|
|
1808
|
+
};
|
|
1809
|
+
const inline = withoutKeys(target);
|
|
1810
|
+
if (inline.type === "object" || inline.type === "intersection") return renderSchemaEntry({
|
|
1811
|
+
schema: inline,
|
|
1812
|
+
name,
|
|
1813
|
+
direction
|
|
1814
|
+
});
|
|
1815
|
+
}
|
|
1816
|
+
const inputRefNames = direction === "encode" ? new Set(collectDirectionalRefNames({
|
|
1817
|
+
node: schema,
|
|
1818
|
+
printerOptions
|
|
1819
|
+
})) : null;
|
|
1820
|
+
const imports = resolver.imports({
|
|
1821
|
+
node: schema,
|
|
1822
|
+
root,
|
|
1823
|
+
output,
|
|
1824
|
+
group: group ?? void 0,
|
|
1825
|
+
checks: true,
|
|
1826
|
+
name: (schemaName) => inputRefNames?.has(schemaName) ? resolver.schema.inputName(schemaName) : resolver.name(schemaName)
|
|
1827
|
+
});
|
|
1828
|
+
return /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsxs)(_kubb_renderer_jsx_jsx_runtime.Fragment, { children: [imports.map((imp) => /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.File.Import, {
|
|
1829
|
+
root: meta.file.path,
|
|
1830
|
+
path: imp.path,
|
|
1831
|
+
name: imp.name
|
|
1832
|
+
}, [
|
|
1833
|
+
name,
|
|
1834
|
+
imp.path,
|
|
1835
|
+
imp.name
|
|
1836
|
+
].join("-"))), /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(Valibot, {
|
|
1837
|
+
name,
|
|
1838
|
+
node: schema,
|
|
1839
|
+
printer: getPrinter(resolver, {
|
|
1840
|
+
...printerOptions,
|
|
1841
|
+
keysToOmit
|
|
1842
|
+
}, direction),
|
|
1843
|
+
inferTypeName: inferred ? resolver.schema.type(name) : null,
|
|
1844
|
+
inferKind: inferKinds[direction],
|
|
1845
|
+
comments: schemaComments(schema)
|
|
1846
|
+
})] });
|
|
1847
|
+
}
|
|
1848
|
+
const renderContentTypeVariants = (entries, baseName, direction) => /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx_jsx_runtime.Fragment, { children: buildContentTypeEntries(entries, baseName).map((entry) => renderSchemaEntry({
|
|
1849
|
+
...entry,
|
|
1850
|
+
direction
|
|
1851
|
+
})) });
|
|
1852
|
+
const renderResponseUnion = (responses, name, fallbackUnknown) => renderSchemaEntry({
|
|
1853
|
+
schema: buildResponseUnionSchema({
|
|
1854
|
+
node,
|
|
1855
|
+
responses,
|
|
1856
|
+
name,
|
|
1857
|
+
resolver,
|
|
1858
|
+
fallbackUnknown
|
|
1859
|
+
}),
|
|
1860
|
+
name
|
|
1861
|
+
});
|
|
1862
|
+
const paramSchemas = node.parameters.map((param) => renderSchemaEntry({
|
|
1863
|
+
schema: param.schema,
|
|
1864
|
+
name: resolver.param.name(node, param),
|
|
1865
|
+
direction: "encode"
|
|
1866
|
+
}));
|
|
1867
|
+
const responseSchemas = node.responses.map((res) => {
|
|
1868
|
+
const content = (res.content ?? []).map((entry, _, content) => toResponseContent(entry, content));
|
|
1869
|
+
const variants = content.filter((entry) => entry.schema);
|
|
1870
|
+
if (variants.length > 1) return renderContentTypeVariants(content, resolver.response.status(node, res.statusCode));
|
|
1871
|
+
const primary = variants[0] ?? content[0];
|
|
1872
|
+
return renderSchemaEntry({
|
|
1873
|
+
schema: primary?.schema ?? null,
|
|
1874
|
+
name: resolver.response.status(node, res.statusCode),
|
|
1875
|
+
keysToOmit: primary?.keysToOmit
|
|
1876
|
+
});
|
|
1877
|
+
});
|
|
1878
|
+
const responseHeaderSchemas = node.responses.map((res) => res.headers?.length ? renderSchemaEntry({
|
|
1879
|
+
schema: buildParamsSchema(res.headers),
|
|
1880
|
+
name: resolver.response.headers(node, res.statusCode)
|
|
1881
|
+
}) : null);
|
|
1882
|
+
const responsesWithSchema = node.responses.filter((res) => res.content?.some((entry) => entry.schema));
|
|
1883
|
+
const successResponsesWithSchema = responsesWithSchema.filter((res) => _kubb_kit.ast.http.status.isSuccess(res));
|
|
1884
|
+
const responseUnionSchema = responsesWithSchema.length > 0 ? renderResponseUnion(successResponsesWithSchema, resolver.response.response(node), true) : null;
|
|
1885
|
+
const errorResponsesWithSchema = responsesWithSchema.filter((res) => !_kubb_kit.ast.http.status.isSuccess(res));
|
|
1886
|
+
const errorUnionSchema = errorResponsesWithSchema.length > 0 ? renderResponseUnion(errorResponsesWithSchema, resolver.response.error(node), false) : null;
|
|
1887
|
+
const requestBodyContent = node.requestBody?.content ?? [];
|
|
1888
|
+
const requestSchema = (() => {
|
|
1889
|
+
if (requestBodyContent.length === 0) return null;
|
|
1890
|
+
if (requestBodyContent.length === 1) {
|
|
1891
|
+
const entry = requestBodyContent[0];
|
|
1892
|
+
if (!entry.schema) return null;
|
|
1893
|
+
return renderSchemaEntry({
|
|
1894
|
+
schema: entry.schema,
|
|
1895
|
+
name: resolver.response.body(node),
|
|
1896
|
+
keysToOmit: entry.keysToOmit,
|
|
1897
|
+
direction: "encode"
|
|
1898
|
+
});
|
|
1899
|
+
}
|
|
1900
|
+
return renderContentTypeVariants(requestBodyContent, resolver.response.body(node), "encode");
|
|
1901
|
+
})();
|
|
1902
|
+
const { path, query, header, cookie } = _kubb_kit.ast.http.groupParameters(node);
|
|
1903
|
+
const paramGroupSchemas = [
|
|
1904
|
+
{
|
|
1905
|
+
kind: "path",
|
|
1906
|
+
params: path
|
|
1907
|
+
},
|
|
1908
|
+
{
|
|
1909
|
+
kind: "query",
|
|
1910
|
+
params: query
|
|
1911
|
+
},
|
|
1912
|
+
{
|
|
1913
|
+
kind: "headers",
|
|
1914
|
+
params: header
|
|
1915
|
+
},
|
|
1916
|
+
{
|
|
1917
|
+
kind: "cookies",
|
|
1918
|
+
params: cookie
|
|
1919
|
+
}
|
|
1920
|
+
].filter(({ params }) => params.length > 0).map(({ kind, params }) => renderSchemaEntry({
|
|
1921
|
+
schema: buildParamRefsSchema({
|
|
1922
|
+
node,
|
|
1923
|
+
params,
|
|
1924
|
+
resolver
|
|
1925
|
+
}),
|
|
1926
|
+
name: resolver.param[kind](node, params[0]),
|
|
1927
|
+
direction: "encode"
|
|
1928
|
+
}));
|
|
1929
|
+
const optionsSchema = inferred ? renderSchemaEntry({
|
|
1930
|
+
schema: buildOptionsSchema(node, resolver),
|
|
1931
|
+
name: resolver.name(`${node.operationId} Options`),
|
|
1932
|
+
direction: "encode"
|
|
1933
|
+
}) : null;
|
|
1934
|
+
const responsesSchema = inferred ? renderSchemaEntry({
|
|
1935
|
+
schema: buildResponses(node, resolver),
|
|
1936
|
+
name: resolver.response.responses(node)
|
|
1937
|
+
}) : null;
|
|
1938
|
+
return /* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsxs)(_kubb_renderer_jsx.File, {
|
|
1939
|
+
baseName: meta.file.baseName,
|
|
1940
|
+
path: meta.file.path,
|
|
1941
|
+
meta: meta.file.meta,
|
|
1942
|
+
banner: resolver.default.banner(ctx.meta, {
|
|
1943
|
+
output,
|
|
1944
|
+
config,
|
|
1945
|
+
file: {
|
|
1946
|
+
path: meta.file.path,
|
|
1947
|
+
baseName: meta.file.baseName
|
|
1948
|
+
}
|
|
1949
|
+
}),
|
|
1950
|
+
footer: resolver.default.footer(ctx.meta, {
|
|
1951
|
+
output,
|
|
1952
|
+
config,
|
|
1953
|
+
file: {
|
|
1954
|
+
path: meta.file.path,
|
|
1955
|
+
baseName: meta.file.baseName
|
|
1956
|
+
}
|
|
1957
|
+
}),
|
|
1958
|
+
children: [
|
|
1959
|
+
/* @__PURE__ */ (0, _kubb_renderer_jsx_jsx_runtime.jsx)(_kubb_renderer_jsx.File.Import, {
|
|
1960
|
+
name: "v",
|
|
1961
|
+
path: importPath,
|
|
1962
|
+
isNameSpace: true
|
|
1963
|
+
}),
|
|
1964
|
+
paramSchemas,
|
|
1965
|
+
responseSchemas,
|
|
1966
|
+
responseHeaderSchemas,
|
|
1967
|
+
responseUnionSchema,
|
|
1968
|
+
errorUnionSchema,
|
|
1969
|
+
requestSchema,
|
|
1970
|
+
paramGroupSchemas,
|
|
1971
|
+
optionsSchema,
|
|
1972
|
+
responsesSchema
|
|
1973
|
+
]
|
|
1974
|
+
});
|
|
1975
|
+
}
|
|
1976
|
+
});
|
|
1977
|
+
// kubb-extension.json
|
|
1978
|
+
var compatibility = {
|
|
1979
|
+
"kubb": ">=5.19.0",
|
|
1980
|
+
"node": ">=22.22"
|
|
1981
|
+
};
|
|
1982
|
+
// package.json
|
|
1983
|
+
var version = "0.0.0";
|
|
1984
|
+
// src/resolvers/resolverValibot.ts
|
|
1985
|
+
/**
|
|
1986
|
+
* Default resolver for `@kubb/plugin-valibot`. Schema and file names are camelCase with a `Schema`
|
|
1987
|
+
* suffix, and inferred types are PascalCase.
|
|
1988
|
+
*
|
|
1989
|
+
* @example
|
|
1990
|
+
* ```ts
|
|
1991
|
+
* resolverValibot.name('list pets') // 'listPetsSchema'
|
|
1992
|
+
* resolverValibot.schema.typeName('pet') // 'PetSchemaType'
|
|
1993
|
+
* ```
|
|
1994
|
+
*/
|
|
1995
|
+
const resolverValibot = (0, _kubb_kit.createResolver)({
|
|
1996
|
+
pluginName: "plugin-valibot",
|
|
1997
|
+
name(name) {
|
|
1998
|
+
return this.memo(`name:${name}`, () => ensureValidVarName(_kubb_kit.casing.camel(name, { suffix: "schema" })));
|
|
1999
|
+
},
|
|
2000
|
+
file: createCasedFile((part) => _kubb_kit.casing.camel(part, { suffix: "schema" })),
|
|
2001
|
+
schema: {
|
|
2002
|
+
typeName(name) {
|
|
2003
|
+
return this.memo(`typeName:${name}`, () => ensureValidVarName(_kubb_kit.casing.pascal(name, { suffix: "schema type" })));
|
|
2004
|
+
},
|
|
2005
|
+
type(name) {
|
|
2006
|
+
return this.memo(`type:${name}`, () => ensureValidVarName(_kubb_kit.casing.pascal(name, { suffix: "type" })));
|
|
2007
|
+
},
|
|
2008
|
+
inputName(name) {
|
|
2009
|
+
return this.name(`${name} input`);
|
|
2010
|
+
},
|
|
2011
|
+
inputTypeName(name) {
|
|
2012
|
+
return this.schema.typeName(`${name} input`);
|
|
2013
|
+
},
|
|
2014
|
+
isName(name) {
|
|
2015
|
+
return ensureValidVarName(_kubb_kit.casing.camel(name, { prefix: "is" }));
|
|
2016
|
+
},
|
|
2017
|
+
assertName(name) {
|
|
2018
|
+
return ensureValidVarName(_kubb_kit.casing.camel(name, { prefix: "assert" }));
|
|
2019
|
+
}
|
|
2020
|
+
},
|
|
2021
|
+
param: createOperationParamResolver(),
|
|
2022
|
+
response: {
|
|
2023
|
+
...createOperationResponseResolver(),
|
|
2024
|
+
error(node) {
|
|
2025
|
+
const name = this.name(`${node.operationId} Error`);
|
|
2026
|
+
return this.resolveName({
|
|
2027
|
+
key: operationKey(node, "response", "error"),
|
|
2028
|
+
name
|
|
2029
|
+
});
|
|
2030
|
+
},
|
|
2031
|
+
options(node) {
|
|
2032
|
+
const name = this.schema.type(this.name(`${node.operationId} Options`));
|
|
2033
|
+
return this.resolveName({
|
|
2034
|
+
key: operationKey(node, "response", "options"),
|
|
2035
|
+
name
|
|
2036
|
+
});
|
|
2037
|
+
}
|
|
2038
|
+
}
|
|
2039
|
+
});
|
|
2040
|
+
// src/plugin.ts
|
|
2041
|
+
/**
|
|
2042
|
+
* Canonical plugin name for `@kubb/plugin-valibot`. Used for driver lookups and cross-plugin
|
|
2043
|
+
* dependency references.
|
|
2044
|
+
*/
|
|
2045
|
+
const pluginValibotName = "plugin-valibot";
|
|
2046
|
+
/**
|
|
2047
|
+
* Generates Valibot v1 schemas from an OpenAPI spec. Use them to validate API responses at
|
|
2048
|
+
* runtime, build form schemas, or pass them to any library that takes a Standard Schema.
|
|
2049
|
+
*
|
|
2050
|
+
* @example
|
|
2051
|
+
* ```ts
|
|
2052
|
+
* import { defineConfig } from 'kubb/config'
|
|
2053
|
+
* import { pluginValibot } from '@kubb/plugin-valibot'
|
|
2054
|
+
*
|
|
2055
|
+
* export default defineConfig({
|
|
2056
|
+
* input: './petStore.yaml',
|
|
2057
|
+
* output: { path: './src/gen' },
|
|
2058
|
+
* plugins: [
|
|
2059
|
+
* pluginValibot({
|
|
2060
|
+
* output: { path: './valibot' },
|
|
2061
|
+
* inferred: true,
|
|
2062
|
+
* }),
|
|
2063
|
+
* ],
|
|
2064
|
+
* })
|
|
2065
|
+
* ```
|
|
2066
|
+
*/
|
|
2067
|
+
const pluginValibot = (0, _kubb_kit.defineExtension)({
|
|
2068
|
+
kind: "plugin",
|
|
2069
|
+
meta: {
|
|
2070
|
+
name: pluginValibotName,
|
|
2071
|
+
version,
|
|
2072
|
+
compatibility
|
|
2073
|
+
},
|
|
2074
|
+
setup(options) {
|
|
2075
|
+
const { output = {
|
|
2076
|
+
path: "valibot",
|
|
2077
|
+
barrel: { type: "named" }
|
|
2078
|
+
}, group, exclude = [], include, override = [], importPath = "valibot", inferred = false, regexType = "literal", oneOfType = "union", coercion = false, typeGuards = false, printer, resolver: userResolver, macros: userMacros } = options;
|
|
2079
|
+
(0, _kubb_kit.setResolver)(userResolver ? _kubb_kit.Resolver.merge(resolverValibot, userResolver) : resolverValibot);
|
|
2080
|
+
if (userMacros?.length) (0, _kubb_kit.setMacros)(userMacros);
|
|
2081
|
+
(0, _kubb_kit.addGenerator)(valibotGenerator);
|
|
2082
|
+
return {
|
|
2083
|
+
output,
|
|
2084
|
+
exclude,
|
|
2085
|
+
include,
|
|
2086
|
+
override,
|
|
2087
|
+
group: group ?? null,
|
|
2088
|
+
importPath,
|
|
2089
|
+
inferred,
|
|
2090
|
+
regexType,
|
|
2091
|
+
oneOfType,
|
|
2092
|
+
coercion,
|
|
2093
|
+
typeGuards,
|
|
2094
|
+
printer
|
|
2095
|
+
};
|
|
2096
|
+
}
|
|
2097
|
+
});
|
|
2098
|
+
exports.default = pluginValibot;
|
|
2099
|
+
exports.pluginValibot = pluginValibot;
|
|
2100
|
+
exports.pluginValibotName = pluginValibotName;
|
|
2101
|
+
exports.printerValibot = printerValibot;
|
|
2102
|
+
exports.resolverValibot = resolverValibot;
|
|
2103
|
+
exports.valibotGenerator = valibotGenerator;
|
|
2104
|
+
|
|
2105
|
+
//# sourceMappingURL=index.cjs.map
|