@kubb/plugin-ts 5.0.0-alpha.22 → 5.0.0-alpha.23

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