@kubb/plugin-ts 5.0.0-alpha.2 → 5.0.0-alpha.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/dist/Type-B70QnSzH.cjs +688 -0
  2. package/dist/Type-B70QnSzH.cjs.map +1 -0
  3. package/dist/Type-CMC7L-38.js +671 -0
  4. package/dist/Type-CMC7L-38.js.map +1 -0
  5. package/dist/casing-Cp-jbC_k.js +84 -0
  6. package/dist/casing-Cp-jbC_k.js.map +1 -0
  7. package/dist/casing-D2uQKLWS.cjs +144 -0
  8. package/dist/casing-D2uQKLWS.cjs.map +1 -0
  9. package/dist/components.cjs +3 -2
  10. package/dist/components.d.ts +41 -11
  11. package/dist/components.js +2 -2
  12. package/dist/generators-BFkr7ecU.js +556 -0
  13. package/dist/generators-BFkr7ecU.js.map +1 -0
  14. package/dist/generators-xHWQCNd9.cjs +560 -0
  15. package/dist/generators-xHWQCNd9.cjs.map +1 -0
  16. package/dist/generators.cjs +2 -2
  17. package/dist/generators.d.ts +3 -491
  18. package/dist/generators.js +1 -1
  19. package/dist/index.cjs +146 -3
  20. package/dist/index.cjs.map +1 -0
  21. package/dist/index.d.ts +2 -2
  22. package/dist/index.js +145 -1
  23. package/dist/index.js.map +1 -0
  24. package/dist/resolvers-DsKabI0F.js +184 -0
  25. package/dist/resolvers-DsKabI0F.js.map +1 -0
  26. package/dist/resolvers-YIpeP5YD.cjs +194 -0
  27. package/dist/resolvers-YIpeP5YD.cjs.map +1 -0
  28. package/dist/resolvers.cjs +4 -0
  29. package/dist/resolvers.d.ts +52 -0
  30. package/dist/resolvers.js +2 -0
  31. package/dist/types-zqLMbIqZ.d.ts +340 -0
  32. package/package.json +15 -8
  33. package/src/components/Enum.tsx +83 -0
  34. package/src/components/Type.tsx +25 -144
  35. package/src/components/index.ts +1 -0
  36. package/src/constants.ts +29 -0
  37. package/src/factory.ts +14 -16
  38. package/src/generators/typeGenerator.tsx +221 -414
  39. package/src/generators/utils.ts +308 -0
  40. package/src/index.ts +1 -1
  41. package/src/plugin.ts +74 -87
  42. package/src/presets.ts +23 -0
  43. package/src/printer.ts +256 -92
  44. package/src/resolvers/index.ts +2 -0
  45. package/src/resolvers/resolverTs.ts +104 -0
  46. package/src/resolvers/resolverTsLegacy.ts +87 -0
  47. package/src/types.ts +234 -63
  48. package/dist/components-9wydyqUx.cjs +0 -848
  49. package/dist/components-9wydyqUx.cjs.map +0 -1
  50. package/dist/components-LmqJfxMv.js +0 -721
  51. package/dist/components-LmqJfxMv.js.map +0 -1
  52. package/dist/plugin-CNkzbtpl.cjs +0 -508
  53. package/dist/plugin-CNkzbtpl.cjs.map +0 -1
  54. package/dist/plugin-DoLrDl9P.js +0 -476
  55. package/dist/plugin-DoLrDl9P.js.map +0 -1
  56. package/dist/types-BpeKGgCn.d.ts +0 -170
  57. package/src/parser.ts +0 -396
@@ -0,0 +1,688 @@
1
+ const require_casing = require("./casing-D2uQKLWS.cjs");
2
+ let _kubb_ast = require("@kubb/ast");
3
+ let _kubb_core = require("@kubb/core");
4
+ let _kubb_react_fabric = require("@kubb/react-fabric");
5
+ let _kubb_fabric_core_parsers_typescript = require("@kubb/fabric-core/parsers/typescript");
6
+ let remeda = require("remeda");
7
+ let typescript = require("typescript");
8
+ typescript = require_casing.__toESM(typescript);
9
+ let _kubb_react_fabric_jsx_runtime = require("@kubb/react-fabric/jsx-runtime");
10
+ //#region ../../internals/utils/src/string.ts
11
+ /**
12
+ * Strips a single matching pair of `"..."`, `'...'`, or `` `...` `` from both ends of `text`.
13
+ * Returns the string unchanged when no balanced quote pair is found.
14
+ *
15
+ * @example
16
+ * trimQuotes('"hello"') // 'hello'
17
+ * trimQuotes('hello') // 'hello'
18
+ */
19
+ function trimQuotes(text) {
20
+ if (text.length >= 2) {
21
+ const first = text[0];
22
+ const last = text[text.length - 1];
23
+ if (first === "\"" && last === "\"" || first === "'" && last === "'" || first === "`" && last === "`") return text.slice(1, -1);
24
+ }
25
+ return text;
26
+ }
27
+ /**
28
+ * Escapes characters that are not allowed inside JS string literals.
29
+ * Handles quotes, backslashes, and Unicode line terminators (U+2028 / U+2029).
30
+ *
31
+ * @see http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.4
32
+ *
33
+ * @example
34
+ * ```ts
35
+ * jsStringEscape('say "hi"\nbye') // 'say \\"hi\\"\\nbye'
36
+ * ```
37
+ */
38
+ function jsStringEscape(input) {
39
+ return `${input}`.replace(/["'\\\n\r\u2028\u2029]/g, (character) => {
40
+ switch (character) {
41
+ case "\"":
42
+ case "'":
43
+ case "\\": return `\\${character}`;
44
+ case "\n": return "\\n";
45
+ case "\r": return "\\r";
46
+ case "\u2028": return "\\u2028";
47
+ case "\u2029": return "\\u2029";
48
+ default: return "";
49
+ }
50
+ });
51
+ }
52
+ //#endregion
53
+ //#region ../../internals/utils/src/object.ts
54
+ /**
55
+ * Serializes a primitive value to a JSON string literal, stripping any surrounding quote characters first.
56
+ *
57
+ * @example
58
+ * stringify('hello') // '"hello"'
59
+ * stringify('"hello"') // '"hello"'
60
+ */
61
+ function stringify(value) {
62
+ if (value === void 0 || value === null) return "\"\"";
63
+ return JSON.stringify(trimQuotes(value.toString()));
64
+ }
65
+ //#endregion
66
+ //#region src/constants.ts
67
+ /**
68
+ * `optionalType` values that cause a property's type to include `| undefined`.
69
+ */
70
+ const OPTIONAL_ADDS_UNDEFINED = new Set(["undefined", "questionTokenAndUndefined"]);
71
+ /**
72
+ * `optionalType` values that render the property key with a `?` token.
73
+ */
74
+ const OPTIONAL_ADDS_QUESTION_TOKEN = new Set(["questionToken", "questionTokenAndUndefined"]);
75
+ /**
76
+ * `enumType` values that append a `Key` suffix to the generated enum type alias.
77
+ */
78
+ const ENUM_TYPES_WITH_KEY_SUFFIX = new Set(["asConst", "asPascalConst"]);
79
+ /**
80
+ * `enumType` values that require a runtime value declaration (object, enum, or literal).
81
+ */
82
+ const ENUM_TYPES_WITH_RUNTIME_VALUE = new Set([
83
+ "enum",
84
+ "asConst",
85
+ "asPascalConst",
86
+ "constEnum",
87
+ "literal",
88
+ void 0
89
+ ]);
90
+ /**
91
+ * `enumType` values whose type declaration is type-only (no runtime value emitted for the type alias).
92
+ */
93
+ const ENUM_TYPES_WITH_TYPE_ONLY = new Set([
94
+ "asConst",
95
+ "asPascalConst",
96
+ "literal",
97
+ void 0
98
+ ]);
99
+ //#endregion
100
+ //#region src/factory.ts
101
+ const { SyntaxKind, factory } = typescript.default;
102
+ const modifiers = {
103
+ async: factory.createModifier(typescript.default.SyntaxKind.AsyncKeyword),
104
+ export: factory.createModifier(typescript.default.SyntaxKind.ExportKeyword),
105
+ const: factory.createModifier(typescript.default.SyntaxKind.ConstKeyword),
106
+ static: factory.createModifier(typescript.default.SyntaxKind.StaticKeyword)
107
+ };
108
+ const syntaxKind = {
109
+ union: SyntaxKind.UnionType,
110
+ literalType: SyntaxKind.LiteralType,
111
+ stringLiteral: SyntaxKind.StringLiteral
112
+ };
113
+ function isValidIdentifier(str) {
114
+ if (!str.length || str.trim() !== str) return false;
115
+ const node = typescript.default.parseIsolatedEntityName(str, typescript.default.ScriptTarget.Latest);
116
+ return !!node && node.kind === typescript.default.SyntaxKind.Identifier && typescript.default.identifierToKeywordKind(node.kind) === void 0;
117
+ }
118
+ function propertyName(name) {
119
+ if (typeof name === "string") return isValidIdentifier(name) ? factory.createIdentifier(name) : factory.createStringLiteral(name);
120
+ return name;
121
+ }
122
+ const questionToken = factory.createToken(typescript.default.SyntaxKind.QuestionToken);
123
+ function createQuestionToken(token) {
124
+ if (!token) return;
125
+ if (token === true) return questionToken;
126
+ return token;
127
+ }
128
+ function createIntersectionDeclaration({ nodes, withParentheses }) {
129
+ if (!nodes.length) return null;
130
+ if (nodes.length === 1) return nodes[0] || null;
131
+ const node = factory.createIntersectionTypeNode(nodes);
132
+ if (withParentheses) return factory.createParenthesizedType(node);
133
+ return node;
134
+ }
135
+ function createArrayDeclaration({ nodes, arrayType = "array" }) {
136
+ if (!nodes.length) return factory.createTupleTypeNode([]);
137
+ if (nodes.length === 1) {
138
+ const node = nodes[0];
139
+ if (!node) return null;
140
+ if (arrayType === "generic") return factory.createTypeReferenceNode(factory.createIdentifier("Array"), [node]);
141
+ return factory.createArrayTypeNode(node);
142
+ }
143
+ const unionType = factory.createUnionTypeNode(nodes);
144
+ if (arrayType === "generic") return factory.createTypeReferenceNode(factory.createIdentifier("Array"), [unionType]);
145
+ return factory.createArrayTypeNode(factory.createParenthesizedType(unionType));
146
+ }
147
+ /**
148
+ * Minimum nodes length of 2
149
+ * @example `string | number`
150
+ */
151
+ function createUnionDeclaration({ nodes, withParentheses }) {
152
+ if (!nodes.length) return keywordTypeNodes.any;
153
+ if (nodes.length === 1) return nodes[0];
154
+ const node = factory.createUnionTypeNode(nodes);
155
+ if (withParentheses) return factory.createParenthesizedType(node);
156
+ return node;
157
+ }
158
+ function createPropertySignature({ readOnly, modifiers = [], name, questionToken, type }) {
159
+ return factory.createPropertySignature([...modifiers, readOnly ? factory.createToken(typescript.default.SyntaxKind.ReadonlyKeyword) : void 0].filter(Boolean), propertyName(name), createQuestionToken(questionToken), type);
160
+ }
161
+ function createParameterSignature(name, { modifiers, dotDotDotToken, questionToken, type, initializer }) {
162
+ return factory.createParameterDeclaration(modifiers, dotDotDotToken, name, createQuestionToken(questionToken), type, initializer);
163
+ }
164
+ /**
165
+ * @link https://github.com/microsoft/TypeScript/issues/44151
166
+ */
167
+ function appendJSDocToNode({ node, comments }) {
168
+ const filteredComments = comments.filter(Boolean);
169
+ if (!filteredComments.length) return node;
170
+ const text = filteredComments.reduce((acc = "", comment = "") => {
171
+ return `${acc}\n * ${comment.replaceAll("*/", "*\\/")}`;
172
+ }, "*");
173
+ return typescript.default.addSyntheticLeadingComment(node, typescript.default.SyntaxKind.MultiLineCommentTrivia, `${text || "*"}\n`, true);
174
+ }
175
+ function createIndexSignature(type, { modifiers, indexName = "key", indexType = factory.createKeywordTypeNode(typescript.default.SyntaxKind.StringKeyword) } = {}) {
176
+ return factory.createIndexSignature(modifiers, [createParameterSignature(indexName, { type: indexType })], type);
177
+ }
178
+ function createTypeAliasDeclaration({ modifiers, name, typeParameters, type }) {
179
+ return factory.createTypeAliasDeclaration(modifiers, name, typeParameters, type);
180
+ }
181
+ function createInterfaceDeclaration({ modifiers, name, typeParameters, members }) {
182
+ return factory.createInterfaceDeclaration(modifiers, name, typeParameters, void 0, members);
183
+ }
184
+ function createTypeDeclaration({ syntax, isExportable, comments, name, type }) {
185
+ if (syntax === "interface" && "members" in type) return appendJSDocToNode({
186
+ node: createInterfaceDeclaration({
187
+ members: type.members,
188
+ modifiers: isExportable ? [modifiers.export] : [],
189
+ name,
190
+ typeParameters: void 0
191
+ }),
192
+ comments
193
+ });
194
+ return appendJSDocToNode({
195
+ node: createTypeAliasDeclaration({
196
+ type,
197
+ modifiers: isExportable ? [modifiers.export] : [],
198
+ name,
199
+ typeParameters: void 0
200
+ }),
201
+ comments
202
+ });
203
+ }
204
+ /**
205
+ * Apply casing transformation to enum keys
206
+ */
207
+ function applyEnumKeyCasing(key, casing = "none") {
208
+ if (casing === "none") return key;
209
+ if (casing === "screamingSnakeCase") return require_casing.screamingSnakeCase(key);
210
+ if (casing === "snakeCase") return require_casing.snakeCase(key);
211
+ if (casing === "pascalCase") return require_casing.pascalCase(key);
212
+ if (casing === "camelCase") return require_casing.camelCase(key);
213
+ return key;
214
+ }
215
+ function createEnumDeclaration({ type = "enum", name, typeName, enums, enumKeyCasing = "none" }) {
216
+ if (type === "literal" || type === "inlineLiteral") return [void 0, factory.createTypeAliasDeclaration([factory.createToken(typescript.default.SyntaxKind.ExportKeyword)], factory.createIdentifier(typeName), void 0, factory.createUnionTypeNode(enums.map(([_key, value]) => {
217
+ if ((0, remeda.isNumber)(value)) {
218
+ if (value < 0) return factory.createLiteralTypeNode(factory.createPrefixUnaryExpression(typescript.default.SyntaxKind.MinusToken, factory.createNumericLiteral(Math.abs(value))));
219
+ return factory.createLiteralTypeNode(factory.createNumericLiteral(value?.toString()));
220
+ }
221
+ if (typeof value === "boolean") return factory.createLiteralTypeNode(value ? factory.createTrue() : factory.createFalse());
222
+ if (value) return factory.createLiteralTypeNode(factory.createStringLiteral(value.toString()));
223
+ }).filter(Boolean)))];
224
+ if (type === "enum" || type === "constEnum") return [void 0, factory.createEnumDeclaration([factory.createToken(typescript.default.SyntaxKind.ExportKeyword), type === "constEnum" ? factory.createToken(typescript.default.SyntaxKind.ConstKeyword) : void 0].filter(Boolean), factory.createIdentifier(typeName), enums.map(([key, value]) => {
225
+ let initializer = factory.createStringLiteral(value?.toString());
226
+ if (Number.parseInt(value.toString(), 10) === value && (0, remeda.isNumber)(Number.parseInt(value.toString(), 10))) if (value < 0) initializer = factory.createPrefixUnaryExpression(typescript.default.SyntaxKind.MinusToken, factory.createNumericLiteral(Math.abs(value)));
227
+ else initializer = factory.createNumericLiteral(value);
228
+ if (typeof value === "boolean") initializer = value ? factory.createTrue() : factory.createFalse();
229
+ if ((0, remeda.isNumber)(Number.parseInt(key.toString(), 10))) {
230
+ const casingKey = applyEnumKeyCasing(`${typeName}_${key}`, enumKeyCasing);
231
+ return factory.createEnumMember(propertyName(casingKey), initializer);
232
+ }
233
+ if (key) {
234
+ const casingKey = applyEnumKeyCasing(key.toString(), enumKeyCasing);
235
+ return factory.createEnumMember(propertyName(casingKey), initializer);
236
+ }
237
+ }).filter(Boolean))];
238
+ const identifierName = name;
239
+ if (enums.length === 0) return [void 0, factory.createTypeAliasDeclaration([factory.createToken(typescript.default.SyntaxKind.ExportKeyword)], factory.createIdentifier(typeName), void 0, factory.createKeywordTypeNode(typescript.default.SyntaxKind.NeverKeyword))];
240
+ return [factory.createVariableStatement([factory.createToken(typescript.default.SyntaxKind.ExportKeyword)], factory.createVariableDeclarationList([factory.createVariableDeclaration(factory.createIdentifier(identifierName), void 0, void 0, factory.createAsExpression(factory.createObjectLiteralExpression(enums.map(([key, value]) => {
241
+ let initializer = factory.createStringLiteral(value?.toString());
242
+ if ((0, remeda.isNumber)(value)) if (value < 0) initializer = factory.createPrefixUnaryExpression(typescript.default.SyntaxKind.MinusToken, factory.createNumericLiteral(Math.abs(value)));
243
+ else initializer = factory.createNumericLiteral(value);
244
+ if (typeof value === "boolean") initializer = value ? factory.createTrue() : factory.createFalse();
245
+ if (key) {
246
+ const casingKey = applyEnumKeyCasing(key.toString(), enumKeyCasing);
247
+ return factory.createPropertyAssignment(propertyName(casingKey), initializer);
248
+ }
249
+ }).filter(Boolean), true), factory.createTypeReferenceNode(factory.createIdentifier("const"), void 0)))], typescript.default.NodeFlags.Const)), factory.createTypeAliasDeclaration([factory.createToken(typescript.default.SyntaxKind.ExportKeyword)], factory.createIdentifier(typeName), void 0, factory.createIndexedAccessTypeNode(factory.createParenthesizedType(factory.createTypeQueryNode(factory.createIdentifier(identifierName), void 0)), factory.createTypeOperatorNode(typescript.default.SyntaxKind.KeyOfKeyword, factory.createTypeQueryNode(factory.createIdentifier(identifierName), void 0))))];
250
+ }
251
+ function createOmitDeclaration({ keys, type, nonNullable }) {
252
+ const node = nonNullable ? factory.createTypeReferenceNode(factory.createIdentifier("NonNullable"), [type]) : type;
253
+ if (Array.isArray(keys)) return factory.createTypeReferenceNode(factory.createIdentifier("Omit"), [node, factory.createUnionTypeNode(keys.map((key) => {
254
+ return factory.createLiteralTypeNode(factory.createStringLiteral(key));
255
+ }))]);
256
+ return factory.createTypeReferenceNode(factory.createIdentifier("Omit"), [node, factory.createLiteralTypeNode(factory.createStringLiteral(keys))]);
257
+ }
258
+ const keywordTypeNodes = {
259
+ any: factory.createKeywordTypeNode(typescript.default.SyntaxKind.AnyKeyword),
260
+ unknown: factory.createKeywordTypeNode(typescript.default.SyntaxKind.UnknownKeyword),
261
+ void: factory.createKeywordTypeNode(typescript.default.SyntaxKind.VoidKeyword),
262
+ number: factory.createKeywordTypeNode(typescript.default.SyntaxKind.NumberKeyword),
263
+ integer: factory.createKeywordTypeNode(typescript.default.SyntaxKind.NumberKeyword),
264
+ bigint: factory.createKeywordTypeNode(typescript.default.SyntaxKind.BigIntKeyword),
265
+ object: factory.createKeywordTypeNode(typescript.default.SyntaxKind.ObjectKeyword),
266
+ string: factory.createKeywordTypeNode(typescript.default.SyntaxKind.StringKeyword),
267
+ boolean: factory.createKeywordTypeNode(typescript.default.SyntaxKind.BooleanKeyword),
268
+ undefined: factory.createKeywordTypeNode(typescript.default.SyntaxKind.UndefinedKeyword),
269
+ null: factory.createLiteralTypeNode(factory.createToken(typescript.default.SyntaxKind.NullKeyword)),
270
+ never: factory.createKeywordTypeNode(typescript.default.SyntaxKind.NeverKeyword)
271
+ };
272
+ /**
273
+ * Converts a path like '/pet/{petId}/uploadImage' to a template literal type
274
+ * like `/pet/${string}/uploadImage`
275
+ */
276
+ /**
277
+ * Converts an OAS-style path (e.g. `/pets/{petId}`) or an Express-style path
278
+ * (e.g. `/pets/:petId`) to a TypeScript template literal type
279
+ * like `` `/pets/${string}` ``.
280
+ */
281
+ function createUrlTemplateType(path) {
282
+ const normalized = path.replace(/:([^/]+)/g, "{$1}");
283
+ if (!normalized.includes("{")) return factory.createLiteralTypeNode(factory.createStringLiteral(normalized));
284
+ const segments = normalized.split(/(\{[^}]+\})/);
285
+ const parts = [];
286
+ const parameterIndices = [];
287
+ segments.forEach((segment) => {
288
+ if (segment.startsWith("{") && segment.endsWith("}")) {
289
+ parameterIndices.push(parts.length);
290
+ parts.push(segment);
291
+ } else if (segment) parts.push(segment);
292
+ });
293
+ const head = typescript.default.factory.createTemplateHead(parts[0] || "");
294
+ const templateSpans = [];
295
+ parameterIndices.forEach((paramIndex, i) => {
296
+ const isLast = i === parameterIndices.length - 1;
297
+ const nextPart = parts[paramIndex + 1] || "";
298
+ const literal = isLast ? typescript.default.factory.createTemplateTail(nextPart) : typescript.default.factory.createTemplateMiddle(nextPart);
299
+ templateSpans.push(typescript.default.factory.createTemplateLiteralTypeSpan(keywordTypeNodes.string, literal));
300
+ });
301
+ return typescript.default.factory.createTemplateLiteralType(head, templateSpans);
302
+ }
303
+ const createTypeLiteralNode = factory.createTypeLiteralNode;
304
+ const createTypeReferenceNode = factory.createTypeReferenceNode;
305
+ const createNumericLiteral = factory.createNumericLiteral;
306
+ const createStringLiteral = factory.createStringLiteral;
307
+ const createArrayTypeNode = factory.createArrayTypeNode;
308
+ factory.createParenthesizedType;
309
+ const createLiteralTypeNode = factory.createLiteralTypeNode;
310
+ factory.createNull;
311
+ const createIdentifier = factory.createIdentifier;
312
+ const createOptionalTypeNode = factory.createOptionalTypeNode;
313
+ const createTupleTypeNode = factory.createTupleTypeNode;
314
+ const createRestTypeNode = factory.createRestTypeNode;
315
+ const createTrue = factory.createTrue;
316
+ const createFalse = factory.createFalse;
317
+ factory.createIndexedAccessTypeNode;
318
+ factory.createTypeOperatorNode;
319
+ const createPrefixUnaryExpression = factory.createPrefixUnaryExpression;
320
+ //#endregion
321
+ //#region src/printer.ts
322
+ /**
323
+ * Converts a primitive const value to a TypeScript literal type node.
324
+ * Handles negative numbers via a prefix unary expression.
325
+ */
326
+ function constToTypeNode(value, format) {
327
+ if (format === "boolean") return createLiteralTypeNode(value === true ? createTrue() : createFalse());
328
+ if (format === "number" && typeof value === "number") {
329
+ if (value < 0) return createLiteralTypeNode(createPrefixUnaryExpression(SyntaxKind.MinusToken, createNumericLiteral(Math.abs(value))));
330
+ return createLiteralTypeNode(createNumericLiteral(value));
331
+ }
332
+ return createLiteralTypeNode(createStringLiteral(String(value)));
333
+ }
334
+ /**
335
+ * Returns a `Date` reference type node when `representation` is `'date'`, otherwise falls back to `string`.
336
+ */
337
+ function dateOrStringNode(node) {
338
+ return node.representation === "date" ? createTypeReferenceNode(createIdentifier("Date")) : keywordTypeNodes.string;
339
+ }
340
+ /**
341
+ * Maps an array of `SchemaNode`s through the printer, filtering out `null` and `undefined` results.
342
+ */
343
+ function buildMemberNodes(members, print) {
344
+ return (members ?? []).map(print).filter(Boolean);
345
+ }
346
+ /**
347
+ * Builds a TypeScript tuple type node from an array schema's `items`,
348
+ * applying min/max slice and optional/rest element rules.
349
+ */
350
+ function buildTupleNode(node, print) {
351
+ let items = (node.items ?? []).map(print).filter(Boolean);
352
+ const restNode = node.rest ? print(node.rest) ?? void 0 : void 0;
353
+ const { min, max } = node;
354
+ if (max !== void 0) {
355
+ items = items.slice(0, max);
356
+ if (items.length < max && restNode) items = [...items, ...Array(max - items.length).fill(restNode)];
357
+ }
358
+ if (min !== void 0) items = items.map((item, i) => i >= min ? createOptionalTypeNode(item) : item);
359
+ if (max === void 0 && restNode) items.push(createRestTypeNode(createArrayTypeNode(restNode)));
360
+ return createTupleTypeNode(items);
361
+ }
362
+ /**
363
+ * Applies `nullable` and optional/nullish `| undefined` union modifiers to a property's resolved base type.
364
+ */
365
+ function buildPropertyType(schema, baseType, optionalType) {
366
+ const addsUndefined = OPTIONAL_ADDS_UNDEFINED.has(optionalType);
367
+ let type = baseType;
368
+ if (schema.nullable) type = createUnionDeclaration({ nodes: [type, keywordTypeNodes.null] });
369
+ if ((schema.nullish || schema.optional) && addsUndefined) type = createUnionDeclaration({ nodes: [type, keywordTypeNodes.undefined] });
370
+ return type;
371
+ }
372
+ /**
373
+ * Collects JSDoc annotation strings (description, deprecated, min/max, pattern, default, example, type) for a schema node.
374
+ */
375
+ function buildPropertyJSDocComments(schema) {
376
+ const isArray = schema.type === "array";
377
+ return [
378
+ "description" in schema && schema.description ? `@description ${jsStringEscape(schema.description)}` : void 0,
379
+ "deprecated" in schema && schema.deprecated ? "@deprecated" : void 0,
380
+ !isArray && "min" in schema && schema.min !== void 0 ? `@minLength ${schema.min}` : void 0,
381
+ !isArray && "max" in schema && schema.max !== void 0 ? `@maxLength ${schema.max}` : void 0,
382
+ "pattern" in schema && schema.pattern ? `@pattern ${schema.pattern}` : void 0,
383
+ "default" in schema && schema.default !== void 0 ? `@default ${"primitive" in schema && schema.primitive === "string" ? stringify(schema.default) : schema.default}` : void 0,
384
+ "example" in schema && schema.example !== void 0 ? `@example ${schema.example}` : void 0,
385
+ "primitive" in schema && schema.primitive ? [`@type ${schema.primitive || "unknown"}`, "optional" in schema && schema.optional ? " | undefined" : void 0].filter(Boolean).join("") : void 0
386
+ ];
387
+ }
388
+ /**
389
+ * Creates TypeScript index signatures for `additionalProperties` and `patternProperties` on an object schema node.
390
+ */
391
+ function buildIndexSignatures(node, propertyCount, print) {
392
+ const elements = [];
393
+ if (node.additionalProperties && node.additionalProperties !== true) {
394
+ const additionalType = print(node.additionalProperties) ?? keywordTypeNodes.unknown;
395
+ elements.push(createIndexSignature(propertyCount > 0 ? keywordTypeNodes.unknown : additionalType));
396
+ } else if (node.additionalProperties === true) elements.push(createIndexSignature(keywordTypeNodes.unknown));
397
+ if (node.patternProperties) {
398
+ const first = Object.values(node.patternProperties)[0];
399
+ if (first) {
400
+ let patternType = print(first) ?? keywordTypeNodes.unknown;
401
+ if (first.nullable) patternType = createUnionDeclaration({ nodes: [patternType, keywordTypeNodes.null] });
402
+ elements.push(createIndexSignature(patternType));
403
+ }
404
+ }
405
+ return elements;
406
+ }
407
+ /**
408
+ * TypeScript type printer built with `definePrinter`.
409
+ *
410
+ * Converts a `SchemaNode` AST node into a TypeScript AST node:
411
+ * - **`printer.print(node)`** — when `options.typeName` is set, returns a full
412
+ * `type Name = …` or `interface Name { … }` declaration (`ts.Node`).
413
+ * Without `typeName`, returns the raw `ts.TypeNode` for the schema.
414
+ *
415
+ * Dispatches on `node.type` to the appropriate handler in `nodes`. Options are closed
416
+ * over per printer instance, so each call to `printerTs(options)` produces an independent printer.
417
+ *
418
+ * @example Raw type node (no `typeName`)
419
+ * ```ts
420
+ * const printer = printerTs({ optionalType: 'questionToken', arrayType: 'array', enumType: 'inlineLiteral' })
421
+ * const typeNode = printer.print(schemaNode) // ts.TypeNode
422
+ * ```
423
+ *
424
+ * @example Full declaration (with `typeName`)
425
+ * ```ts
426
+ * const printer = printerTs({ optionalType: 'questionToken', arrayType: 'array', enumType: 'inlineLiteral', typeName: 'MyType' })
427
+ * const declaration = printer.print(schemaNode) // ts.TypeAliasDeclaration | ts.InterfaceDeclaration
428
+ * ```
429
+ */
430
+ const printerTs = (0, _kubb_core.definePrinter)((options) => {
431
+ const addsUndefined = OPTIONAL_ADDS_UNDEFINED.has(options.optionalType);
432
+ return {
433
+ name: "typescript",
434
+ options,
435
+ nodes: {
436
+ any: () => keywordTypeNodes.any,
437
+ unknown: () => keywordTypeNodes.unknown,
438
+ void: () => keywordTypeNodes.void,
439
+ never: () => keywordTypeNodes.never,
440
+ boolean: () => keywordTypeNodes.boolean,
441
+ null: () => keywordTypeNodes.null,
442
+ blob: () => createTypeReferenceNode("Blob", []),
443
+ string: () => keywordTypeNodes.string,
444
+ uuid: () => keywordTypeNodes.string,
445
+ email: () => keywordTypeNodes.string,
446
+ url: (node) => {
447
+ if (node.path) return createUrlTemplateType(node.path);
448
+ return keywordTypeNodes.string;
449
+ },
450
+ datetime: () => keywordTypeNodes.string,
451
+ number: () => keywordTypeNodes.number,
452
+ integer: () => keywordTypeNodes.number,
453
+ bigint: () => keywordTypeNodes.bigint,
454
+ date: dateOrStringNode,
455
+ time: dateOrStringNode,
456
+ ref(node) {
457
+ if (!node.name) return;
458
+ const refName = node.ref ? node.ref.split("/").at(-1) ?? node.name : node.name;
459
+ return createTypeReferenceNode(node.ref ? this.options.resolver.default(refName, "type") : refName, void 0);
460
+ },
461
+ enum(node) {
462
+ const values = node.namedEnumValues?.map((v) => v.value) ?? node.enumValues ?? [];
463
+ if (this.options.enumType === "inlineLiteral" || !node.name) return createUnionDeclaration({
464
+ withParentheses: true,
465
+ nodes: values.filter((v) => v !== null).map((value) => constToTypeNode(value, typeof value)).filter(Boolean)
466
+ }) ?? void 0;
467
+ const resolvedName = this.options.resolver.default(node.name, "type");
468
+ return createTypeReferenceNode(ENUM_TYPES_WITH_KEY_SUFFIX.has(this.options.enumType) ? `${resolvedName}Key` : resolvedName, void 0);
469
+ },
470
+ union(node) {
471
+ const members = node.members ?? [];
472
+ const hasStringLiteral = members.some((m) => {
473
+ return (0, _kubb_ast.narrowSchema)(m, _kubb_ast.schemaTypes.enum)?.primitive === "string";
474
+ });
475
+ const hasPlainString = members.some((m) => (0, _kubb_ast.isStringType)(m));
476
+ if (hasStringLiteral && hasPlainString) return createUnionDeclaration({
477
+ withParentheses: true,
478
+ nodes: members.map((m) => {
479
+ if ((0, _kubb_ast.isStringType)(m)) return createIntersectionDeclaration({
480
+ nodes: [keywordTypeNodes.string, createTypeLiteralNode([])],
481
+ withParentheses: true
482
+ });
483
+ return this.print(m);
484
+ }).filter(Boolean)
485
+ }) ?? void 0;
486
+ return createUnionDeclaration({
487
+ withParentheses: true,
488
+ nodes: buildMemberNodes(members, this.print)
489
+ }) ?? void 0;
490
+ },
491
+ intersection(node) {
492
+ return createIntersectionDeclaration({
493
+ withParentheses: true,
494
+ nodes: buildMemberNodes(node.members, this.print)
495
+ }) ?? void 0;
496
+ },
497
+ array(node) {
498
+ return createArrayDeclaration({
499
+ nodes: (node.items ?? []).map((item) => this.print(item)).filter(Boolean),
500
+ arrayType: this.options.arrayType
501
+ }) ?? void 0;
502
+ },
503
+ tuple(node) {
504
+ return buildTupleNode(node, this.print);
505
+ },
506
+ object(node) {
507
+ const { print, options } = this;
508
+ const addsQuestionToken = OPTIONAL_ADDS_QUESTION_TOKEN.has(options.optionalType);
509
+ const propertyNodes = node.properties.map((prop) => {
510
+ const baseType = print(prop.schema) ?? keywordTypeNodes.unknown;
511
+ const type = buildPropertyType(prop.schema, baseType, options.optionalType);
512
+ return appendJSDocToNode({
513
+ node: createPropertySignature({
514
+ questionToken: prop.schema.optional || prop.schema.nullish ? addsQuestionToken : false,
515
+ name: prop.name,
516
+ type,
517
+ readOnly: prop.schema.readOnly
518
+ }),
519
+ comments: buildPropertyJSDocComments(prop.schema)
520
+ });
521
+ });
522
+ const allElements = [...propertyNodes, ...buildIndexSignatures(node, propertyNodes.length, print)];
523
+ if (!allElements.length) return keywordTypeNodes.object;
524
+ return createTypeLiteralNode(allElements);
525
+ }
526
+ },
527
+ print(node) {
528
+ let type = this.print(node);
529
+ if (!type) return;
530
+ if (node.nullable) type = createUnionDeclaration({ nodes: [type, keywordTypeNodes.null] });
531
+ if ((node.nullish || node.optional) && addsUndefined) type = createUnionDeclaration({ nodes: [type, keywordTypeNodes.undefined] });
532
+ const { typeName, syntaxType = "type", description, keysToOmit } = this.options;
533
+ if (!typeName) return type;
534
+ const useTypeGeneration = syntaxType === "type" || type.kind === syntaxKind.union || !!keysToOmit?.length;
535
+ return createTypeDeclaration({
536
+ name: typeName,
537
+ isExportable: true,
538
+ type: keysToOmit?.length ? createOmitDeclaration({
539
+ keys: keysToOmit,
540
+ type,
541
+ nonNullable: true
542
+ }) : type,
543
+ syntax: useTypeGeneration ? "type" : "interface",
544
+ comments: [
545
+ node?.title ? jsStringEscape(node.title) : void 0,
546
+ description ? `@description ${jsStringEscape(description)}` : void 0,
547
+ node?.deprecated ? "@deprecated" : void 0,
548
+ node && "min" in node && node.min !== void 0 ? `@minLength ${node.min}` : void 0,
549
+ node && "max" in node && node.max !== void 0 ? `@maxLength ${node.max}` : void 0,
550
+ node && "pattern" in node && node.pattern ? `@pattern ${node.pattern}` : void 0,
551
+ node?.default ? `@default ${node.default}` : void 0,
552
+ node?.example ? `@example ${node.example}` : void 0
553
+ ]
554
+ });
555
+ }
556
+ };
557
+ });
558
+ //#endregion
559
+ //#region src/components/Enum.tsx
560
+ /**
561
+ * Resolves the runtime identifier name and the TypeScript type name for an enum schema node.
562
+ *
563
+ * The raw `node.name` may be a YAML key such as `"enumNames.Type"` which is not a
564
+ * valid TypeScript identifier. The resolver normalizes it; for inline enum
565
+ * properties the adapter already emits a PascalCase+suffix name so resolution is typically a no-op.
566
+ */
567
+ function getEnumNames({ node, enumType, resolver }) {
568
+ const resolved = resolver.default(node.name, "type");
569
+ return {
570
+ enumName: enumType === "asPascalConst" ? resolved : require_casing.camelCase(node.name),
571
+ typeName: ENUM_TYPES_WITH_KEY_SUFFIX.has(enumType) ? `${resolved}Key` : resolved,
572
+ refName: resolved
573
+ };
574
+ }
575
+ /**
576
+ * Renders the enum declaration(s) for a single named `EnumSchemaNode`.
577
+ *
578
+ * Depending on `enumType` this may emit:
579
+ * - A runtime object (`asConst` / `asPascalConst`) plus a `typeof` type alias
580
+ * - A `const enum` or plain `enum` declaration (`constEnum` / `enum`)
581
+ * - A union literal type alias (`literal`)
582
+ *
583
+ * The emitted `File.Source` nodes carry the resolved names so that the barrel
584
+ * index picks up the correct export identifiers.
585
+ */
586
+ function Enum({ node, enumType, enumKeyCasing, resolver }) {
587
+ const { enumName, typeName, refName } = getEnumNames({
588
+ node,
589
+ enumType,
590
+ resolver
591
+ });
592
+ const [nameNode, typeNode] = createEnumDeclaration({
593
+ name: enumName,
594
+ typeName,
595
+ enums: node.namedEnumValues?.map((v) => [trimQuotes(v.name.toString()), v.value]) ?? node.enumValues?.filter((v) => v !== null && v !== void 0).map((v) => [trimQuotes(v.toString()), v]) ?? [],
596
+ type: enumType,
597
+ enumKeyCasing
598
+ });
599
+ const needsRefAlias = ENUM_TYPES_WITH_KEY_SUFFIX.has(enumType) && refName !== typeName;
600
+ return /* @__PURE__ */ (0, _kubb_react_fabric_jsx_runtime.jsxs)(_kubb_react_fabric_jsx_runtime.Fragment, { children: [
601
+ nameNode && /* @__PURE__ */ (0, _kubb_react_fabric_jsx_runtime.jsx)(_kubb_react_fabric.File.Source, {
602
+ name: enumName,
603
+ isExportable: true,
604
+ isIndexable: true,
605
+ isTypeOnly: false,
606
+ children: (0, _kubb_fabric_core_parsers_typescript.safePrint)(nameNode)
607
+ }),
608
+ /* @__PURE__ */ (0, _kubb_react_fabric_jsx_runtime.jsx)(_kubb_react_fabric.File.Source, {
609
+ name: typeName,
610
+ isIndexable: true,
611
+ isExportable: ENUM_TYPES_WITH_RUNTIME_VALUE.has(enumType),
612
+ isTypeOnly: ENUM_TYPES_WITH_TYPE_ONLY.has(enumType),
613
+ children: (0, _kubb_fabric_core_parsers_typescript.safePrint)(typeNode)
614
+ }),
615
+ needsRefAlias && /* @__PURE__ */ (0, _kubb_react_fabric_jsx_runtime.jsx)(_kubb_react_fabric.File.Source, {
616
+ name: refName,
617
+ isExportable: true,
618
+ isIndexable: true,
619
+ isTypeOnly: true,
620
+ children: `export type ${refName} = ${typeName}`
621
+ })
622
+ ] });
623
+ }
624
+ //#endregion
625
+ //#region src/components/Type.tsx
626
+ function Type({ name, typedName, node, keysToOmit, optionalType, arrayType, syntaxType, enumType, enumKeyCasing, description, resolver }) {
627
+ const resolvedDescription = description || node?.description;
628
+ const enumSchemaNodes = (0, _kubb_ast.collect)(node, { schema(n) {
629
+ const enumNode = (0, _kubb_ast.narrowSchema)(n, _kubb_ast.schemaTypes.enum);
630
+ if (enumNode?.name) return enumNode;
631
+ } });
632
+ const typeNode = printerTs({
633
+ optionalType,
634
+ arrayType,
635
+ enumType,
636
+ typeName: name,
637
+ syntaxType,
638
+ description: resolvedDescription,
639
+ keysToOmit,
640
+ resolver
641
+ }).print(node);
642
+ if (!typeNode) return;
643
+ const enums = [...new Map(enumSchemaNodes.map((n) => [n.name, n])).values()].map((node) => {
644
+ return {
645
+ node,
646
+ ...getEnumNames({
647
+ node,
648
+ enumType,
649
+ resolver
650
+ })
651
+ };
652
+ });
653
+ const shouldExportEnums = enumType !== "inlineLiteral";
654
+ const shouldExportType = enumType === "inlineLiteral" || enums.every((item) => item.typeName !== name);
655
+ return /* @__PURE__ */ (0, _kubb_react_fabric_jsx_runtime.jsxs)(_kubb_react_fabric_jsx_runtime.Fragment, { children: [shouldExportEnums && enums.map(({ node }) => /* @__PURE__ */ (0, _kubb_react_fabric_jsx_runtime.jsx)(Enum, {
656
+ node,
657
+ enumType,
658
+ enumKeyCasing,
659
+ resolver
660
+ })), shouldExportType && /* @__PURE__ */ (0, _kubb_react_fabric_jsx_runtime.jsx)(_kubb_react_fabric.File.Source, {
661
+ name: typedName,
662
+ isTypeOnly: true,
663
+ isExportable: true,
664
+ isIndexable: true,
665
+ children: (0, _kubb_fabric_core_parsers_typescript.safePrint)(typeNode)
666
+ })] });
667
+ }
668
+ //#endregion
669
+ Object.defineProperty(exports, "ENUM_TYPES_WITH_KEY_SUFFIX", {
670
+ enumerable: true,
671
+ get: function() {
672
+ return ENUM_TYPES_WITH_KEY_SUFFIX;
673
+ }
674
+ });
675
+ Object.defineProperty(exports, "Enum", {
676
+ enumerable: true,
677
+ get: function() {
678
+ return Enum;
679
+ }
680
+ });
681
+ Object.defineProperty(exports, "Type", {
682
+ enumerable: true,
683
+ get: function() {
684
+ return Type;
685
+ }
686
+ });
687
+
688
+ //# sourceMappingURL=Type-B70QnSzH.cjs.map