@kubb/plugin-ts 5.0.0-alpha.11 → 5.0.0-alpha.13

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-C8EHVKjc.js +663 -0
  2. package/dist/Type-C8EHVKjc.js.map +1 -0
  3. package/dist/Type-DrOq6-nh.cjs +680 -0
  4. package/dist/Type-DrOq6-nh.cjs.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 -9
  11. package/dist/components.js +2 -2
  12. package/dist/generators-CX3cSSdF.cjs +551 -0
  13. package/dist/generators-CX3cSSdF.cjs.map +1 -0
  14. package/dist/generators-dCqW0ECC.js +547 -0
  15. package/dist/generators-dCqW0ECC.js.map +1 -0
  16. package/dist/generators.cjs +2 -3
  17. package/dist/generators.d.ts +3 -503
  18. package/dist/generators.js +2 -2
  19. package/dist/index.cjs +135 -4
  20. package/dist/index.cjs.map +1 -0
  21. package/dist/index.d.ts +2 -41
  22. package/dist/index.js +134 -2
  23. package/dist/index.js.map +1 -0
  24. package/dist/resolvers-CH7hINyz.js +181 -0
  25. package/dist/resolvers-CH7hINyz.js.map +1 -0
  26. package/dist/resolvers-ebHaaCyw.cjs +191 -0
  27. package/dist/resolvers-ebHaaCyw.cjs.map +1 -0
  28. package/dist/resolvers.cjs +4 -0
  29. package/dist/resolvers.d.ts +51 -0
  30. package/dist/resolvers.js +2 -0
  31. package/dist/{types-mSXmB8WU.d.ts → types-BSRhtbGl.d.ts} +80 -57
  32. package/package.json +12 -5
  33. package/src/components/{v2/Enum.tsx → Enum.tsx} +27 -11
  34. package/src/components/Type.tsx +24 -141
  35. package/src/components/index.ts +1 -0
  36. package/src/generators/index.ts +0 -1
  37. package/src/generators/typeGenerator.tsx +204 -413
  38. package/src/generators/utils.ts +300 -0
  39. package/src/index.ts +0 -1
  40. package/src/plugin.ts +81 -126
  41. package/src/printer.ts +20 -6
  42. package/src/resolvers/index.ts +2 -0
  43. package/src/{resolverTs.ts → resolvers/resolverTs.ts} +26 -2
  44. package/src/resolvers/resolverTsLegacy.ts +85 -0
  45. package/src/types.ts +75 -52
  46. package/dist/components-CRu8IKY3.js +0 -729
  47. package/dist/components-CRu8IKY3.js.map +0 -1
  48. package/dist/components-DeNDKlzf.cjs +0 -982
  49. package/dist/components-DeNDKlzf.cjs.map +0 -1
  50. package/dist/plugin-CJ29AwE2.cjs +0 -1320
  51. package/dist/plugin-CJ29AwE2.cjs.map +0 -1
  52. package/dist/plugin-D60XNJSD.js +0 -1267
  53. package/dist/plugin-D60XNJSD.js.map +0 -1
  54. package/src/components/v2/Type.tsx +0 -59
  55. package/src/generators/v2/typeGenerator.tsx +0 -167
  56. package/src/generators/v2/utils.ts +0 -140
  57. package/src/parser.ts +0 -389
@@ -1,729 +0,0 @@
1
- import "./chunk--u3MIqq1.js";
2
- import { SchemaGenerator, createParser, isKeyword, schemaKeywords } from "@kubb/plugin-oas";
3
- import { safePrint } from "@kubb/fabric-core/parsers/typescript";
4
- import { File } from "@kubb/react-fabric";
5
- import ts from "typescript";
6
- import { isNumber } from "remeda";
7
- import { Fragment, jsx, jsxs } from "@kubb/react-fabric/jsx-runtime";
8
- //#region ../../internals/utils/src/casing.ts
9
- /**
10
- * Shared implementation for camelCase and PascalCase conversion.
11
- * Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)
12
- * and capitalizes each word according to `pascal`.
13
- *
14
- * When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.
15
- */
16
- function toCamelOrPascal(text, pascal) {
17
- return text.trim().replace(/([a-z\d])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").replace(/(\d)([a-z])/g, "$1 $2").split(/[\s\-_./\\:]+/).filter(Boolean).map((word, i) => {
18
- if (word.length > 1 && word === word.toUpperCase()) return word;
19
- if (i === 0 && !pascal) return word.charAt(0).toLowerCase() + word.slice(1);
20
- return word.charAt(0).toUpperCase() + word.slice(1);
21
- }).join("").replace(/[^a-zA-Z0-9]/g, "");
22
- }
23
- /**
24
- * Splits `text` on `.` and applies `transformPart` to each segment.
25
- * The last segment receives `isLast = true`, all earlier segments receive `false`.
26
- * Segments are joined with `/` to form a file path.
27
- */
28
- function applyToFileParts(text, transformPart) {
29
- const parts = text.split(".");
30
- return parts.map((part, i) => transformPart(part, i === parts.length - 1)).join("/");
31
- }
32
- /**
33
- * Converts `text` to camelCase.
34
- * When `isFile` is `true`, dot-separated segments are each cased independently and joined with `/`.
35
- *
36
- * @example
37
- * camelCase('hello-world') // 'helloWorld'
38
- * camelCase('pet.petId', { isFile: true }) // 'pet/petId'
39
- */
40
- function camelCase(text, { isFile, prefix = "", suffix = "" } = {}) {
41
- if (isFile) return applyToFileParts(text, (part, isLast) => camelCase(part, isLast ? {
42
- prefix,
43
- suffix
44
- } : {}));
45
- return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false);
46
- }
47
- /**
48
- * Converts `text` to PascalCase.
49
- * When `isFile` is `true`, the last dot-separated segment is PascalCased and earlier segments are camelCased.
50
- *
51
- * @example
52
- * pascalCase('hello-world') // 'HelloWorld'
53
- * pascalCase('pet.petId', { isFile: true }) // 'pet/PetId'
54
- */
55
- function pascalCase(text, { isFile, prefix = "", suffix = "" } = {}) {
56
- if (isFile) return applyToFileParts(text, (part, isLast) => isLast ? pascalCase(part, {
57
- prefix,
58
- suffix
59
- }) : camelCase(part));
60
- return toCamelOrPascal(`${prefix} ${text} ${suffix}`, true);
61
- }
62
- /**
63
- * Converts `text` to snake_case.
64
- *
65
- * @example
66
- * snakeCase('helloWorld') // 'hello_world'
67
- * snakeCase('Hello-World') // 'hello_world'
68
- */
69
- function snakeCase(text, { prefix = "", suffix = "" } = {}) {
70
- return `${prefix} ${text} ${suffix}`.trim().replace(/([a-z])([A-Z])/g, "$1_$2").replace(/[\s\-.]+/g, "_").replace(/[^a-zA-Z0-9_]/g, "").toLowerCase().split("_").filter(Boolean).join("_");
71
- }
72
- /**
73
- * Converts `text` to SCREAMING_SNAKE_CASE.
74
- *
75
- * @example
76
- * screamingSnakeCase('helloWorld') // 'HELLO_WORLD'
77
- */
78
- function screamingSnakeCase(text, { prefix = "", suffix = "" } = {}) {
79
- return snakeCase(text, {
80
- prefix,
81
- suffix
82
- }).toUpperCase();
83
- }
84
- //#endregion
85
- //#region ../../internals/utils/src/string.ts
86
- /**
87
- * Strips a single matching pair of `"..."`, `'...'`, or `` `...` `` from both ends of `text`.
88
- * Returns the string unchanged when no balanced quote pair is found.
89
- *
90
- * @example
91
- * trimQuotes('"hello"') // 'hello'
92
- * trimQuotes('hello') // 'hello'
93
- */
94
- function trimQuotes(text) {
95
- if (text.length >= 2) {
96
- const first = text[0];
97
- const last = text[text.length - 1];
98
- if (first === "\"" && last === "\"" || first === "'" && last === "'" || first === "`" && last === "`") return text.slice(1, -1);
99
- }
100
- return text;
101
- }
102
- /**
103
- * Escapes characters that are not allowed inside JS string literals.
104
- * Handles quotes, backslashes, and Unicode line terminators (U+2028 / U+2029).
105
- *
106
- * @see http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.4
107
- */
108
- function jsStringEscape(input) {
109
- return `${input}`.replace(/["'\\\n\r\u2028\u2029]/g, (character) => {
110
- switch (character) {
111
- case "\"":
112
- case "'":
113
- case "\\": return `\\${character}`;
114
- case "\n": return "\\n";
115
- case "\r": return "\\r";
116
- case "\u2028": return "\\u2028";
117
- case "\u2029": return "\\u2029";
118
- default: return "";
119
- }
120
- });
121
- }
122
- //#endregion
123
- //#region src/factory.ts
124
- const { SyntaxKind, factory } = ts;
125
- const modifiers = {
126
- async: factory.createModifier(ts.SyntaxKind.AsyncKeyword),
127
- export: factory.createModifier(ts.SyntaxKind.ExportKeyword),
128
- const: factory.createModifier(ts.SyntaxKind.ConstKeyword),
129
- static: factory.createModifier(ts.SyntaxKind.StaticKeyword)
130
- };
131
- const syntaxKind = {
132
- union: SyntaxKind.UnionType,
133
- literalType: SyntaxKind.LiteralType,
134
- stringLiteral: SyntaxKind.StringLiteral
135
- };
136
- function getUnknownType(unknownType) {
137
- if (unknownType === "any") return keywordTypeNodes.any;
138
- if (unknownType === "void") return keywordTypeNodes.void;
139
- return keywordTypeNodes.unknown;
140
- }
141
- function isValidIdentifier(str) {
142
- if (!str.length || str.trim() !== str) return false;
143
- const node = ts.parseIsolatedEntityName(str, ts.ScriptTarget.Latest);
144
- return !!node && node.kind === ts.SyntaxKind.Identifier && ts.identifierToKeywordKind(node.kind) === void 0;
145
- }
146
- function propertyName(name) {
147
- if (typeof name === "string") return isValidIdentifier(name) ? factory.createIdentifier(name) : factory.createStringLiteral(name);
148
- return name;
149
- }
150
- const questionToken = factory.createToken(ts.SyntaxKind.QuestionToken);
151
- function createQuestionToken(token) {
152
- if (!token) return;
153
- if (token === true) return questionToken;
154
- return token;
155
- }
156
- function createIntersectionDeclaration({ nodes, withParentheses }) {
157
- if (!nodes.length) return null;
158
- if (nodes.length === 1) return nodes[0] || null;
159
- const node = factory.createIntersectionTypeNode(nodes);
160
- if (withParentheses) return factory.createParenthesizedType(node);
161
- return node;
162
- }
163
- function createArrayDeclaration({ nodes, arrayType = "array" }) {
164
- if (!nodes.length) return factory.createTupleTypeNode([]);
165
- if (nodes.length === 1) {
166
- const node = nodes[0];
167
- if (!node) return null;
168
- if (arrayType === "generic") return factory.createTypeReferenceNode(factory.createIdentifier("Array"), [node]);
169
- return factory.createArrayTypeNode(node);
170
- }
171
- const unionType = factory.createUnionTypeNode(nodes);
172
- if (arrayType === "generic") return factory.createTypeReferenceNode(factory.createIdentifier("Array"), [unionType]);
173
- return factory.createArrayTypeNode(factory.createParenthesizedType(unionType));
174
- }
175
- /**
176
- * Minimum nodes length of 2
177
- * @example `string | number`
178
- */
179
- function createUnionDeclaration({ nodes, withParentheses }) {
180
- if (!nodes.length) return keywordTypeNodes.any;
181
- if (nodes.length === 1) return nodes[0];
182
- const node = factory.createUnionTypeNode(nodes);
183
- if (withParentheses) return factory.createParenthesizedType(node);
184
- return node;
185
- }
186
- function createPropertySignature({ readOnly, modifiers = [], name, questionToken, type }) {
187
- return factory.createPropertySignature([...modifiers, readOnly ? factory.createToken(ts.SyntaxKind.ReadonlyKeyword) : void 0].filter(Boolean), propertyName(name), createQuestionToken(questionToken), type);
188
- }
189
- function createParameterSignature(name, { modifiers, dotDotDotToken, questionToken, type, initializer }) {
190
- return factory.createParameterDeclaration(modifiers, dotDotDotToken, name, createQuestionToken(questionToken), type, initializer);
191
- }
192
- /**
193
- * @link https://github.com/microsoft/TypeScript/issues/44151
194
- */
195
- function appendJSDocToNode({ node, comments }) {
196
- const filteredComments = comments.filter(Boolean);
197
- if (!filteredComments.length) return node;
198
- const text = filteredComments.reduce((acc = "", comment = "") => {
199
- return `${acc}\n * ${comment.replaceAll("*/", "*\\/")}`;
200
- }, "*");
201
- return ts.addSyntheticLeadingComment(node, ts.SyntaxKind.MultiLineCommentTrivia, `${text || "*"}\n`, true);
202
- }
203
- function createIndexSignature(type, { modifiers, indexName = "key", indexType = factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword) } = {}) {
204
- return factory.createIndexSignature(modifiers, [createParameterSignature(indexName, { type: indexType })], type);
205
- }
206
- function createTypeAliasDeclaration({ modifiers, name, typeParameters, type }) {
207
- return factory.createTypeAliasDeclaration(modifiers, name, typeParameters, type);
208
- }
209
- function createInterfaceDeclaration({ modifiers, name, typeParameters, members }) {
210
- return factory.createInterfaceDeclaration(modifiers, name, typeParameters, void 0, members);
211
- }
212
- function createTypeDeclaration({ syntax, isExportable, comments, name, type }) {
213
- if (syntax === "interface" && "members" in type) return appendJSDocToNode({
214
- node: createInterfaceDeclaration({
215
- members: type.members,
216
- modifiers: isExportable ? [modifiers.export] : [],
217
- name,
218
- typeParameters: void 0
219
- }),
220
- comments
221
- });
222
- return appendJSDocToNode({
223
- node: createTypeAliasDeclaration({
224
- type,
225
- modifiers: isExportable ? [modifiers.export] : [],
226
- name,
227
- typeParameters: void 0
228
- }),
229
- comments
230
- });
231
- }
232
- /**
233
- * Apply casing transformation to enum keys
234
- */
235
- function applyEnumKeyCasing(key, casing = "none") {
236
- if (casing === "none") return key;
237
- if (casing === "screamingSnakeCase") return screamingSnakeCase(key);
238
- if (casing === "snakeCase") return snakeCase(key);
239
- if (casing === "pascalCase") return pascalCase(key);
240
- if (casing === "camelCase") return camelCase(key);
241
- return key;
242
- }
243
- function createEnumDeclaration({ type = "enum", name, typeName, enums, enumKeyCasing = "none" }) {
244
- if (type === "literal" || type === "inlineLiteral") return [void 0, factory.createTypeAliasDeclaration([factory.createToken(ts.SyntaxKind.ExportKeyword)], factory.createIdentifier(typeName), void 0, factory.createUnionTypeNode(enums.map(([_key, value]) => {
245
- if (isNumber(value)) {
246
- if (value < 0) return factory.createLiteralTypeNode(factory.createPrefixUnaryExpression(ts.SyntaxKind.MinusToken, factory.createNumericLiteral(Math.abs(value))));
247
- return factory.createLiteralTypeNode(factory.createNumericLiteral(value?.toString()));
248
- }
249
- if (typeof value === "boolean") return factory.createLiteralTypeNode(value ? factory.createTrue() : factory.createFalse());
250
- if (value) return factory.createLiteralTypeNode(factory.createStringLiteral(value.toString()));
251
- }).filter(Boolean)))];
252
- if (type === "enum" || type === "constEnum") return [void 0, factory.createEnumDeclaration([factory.createToken(ts.SyntaxKind.ExportKeyword), type === "constEnum" ? factory.createToken(ts.SyntaxKind.ConstKeyword) : void 0].filter(Boolean), factory.createIdentifier(typeName), enums.map(([key, value]) => {
253
- let initializer = factory.createStringLiteral(value?.toString());
254
- if (Number.parseInt(value.toString(), 10) === value && isNumber(Number.parseInt(value.toString(), 10))) if (value < 0) initializer = factory.createPrefixUnaryExpression(ts.SyntaxKind.MinusToken, factory.createNumericLiteral(Math.abs(value)));
255
- else initializer = factory.createNumericLiteral(value);
256
- if (typeof value === "boolean") initializer = value ? factory.createTrue() : factory.createFalse();
257
- if (isNumber(Number.parseInt(key.toString(), 10))) {
258
- const casingKey = applyEnumKeyCasing(`${typeName}_${key}`, enumKeyCasing);
259
- return factory.createEnumMember(propertyName(casingKey), initializer);
260
- }
261
- if (key) {
262
- const casingKey = applyEnumKeyCasing(key.toString(), enumKeyCasing);
263
- return factory.createEnumMember(propertyName(casingKey), initializer);
264
- }
265
- }).filter(Boolean))];
266
- const identifierName = name;
267
- if (enums.length === 0) return [void 0, factory.createTypeAliasDeclaration([factory.createToken(ts.SyntaxKind.ExportKeyword)], factory.createIdentifier(typeName), void 0, factory.createKeywordTypeNode(ts.SyntaxKind.NeverKeyword))];
268
- return [factory.createVariableStatement([factory.createToken(ts.SyntaxKind.ExportKeyword)], factory.createVariableDeclarationList([factory.createVariableDeclaration(factory.createIdentifier(identifierName), void 0, void 0, factory.createAsExpression(factory.createObjectLiteralExpression(enums.map(([key, value]) => {
269
- let initializer = factory.createStringLiteral(value?.toString());
270
- if (isNumber(value)) if (value < 0) initializer = factory.createPrefixUnaryExpression(ts.SyntaxKind.MinusToken, factory.createNumericLiteral(Math.abs(value)));
271
- else initializer = factory.createNumericLiteral(value);
272
- if (typeof value === "boolean") initializer = value ? factory.createTrue() : factory.createFalse();
273
- if (key) {
274
- const casingKey = applyEnumKeyCasing(key.toString(), enumKeyCasing);
275
- return factory.createPropertyAssignment(propertyName(casingKey), initializer);
276
- }
277
- }).filter(Boolean), true), factory.createTypeReferenceNode(factory.createIdentifier("const"), void 0)))], ts.NodeFlags.Const)), factory.createTypeAliasDeclaration([factory.createToken(ts.SyntaxKind.ExportKeyword)], factory.createIdentifier(typeName), void 0, factory.createIndexedAccessTypeNode(factory.createParenthesizedType(factory.createTypeQueryNode(factory.createIdentifier(identifierName), void 0)), factory.createTypeOperatorNode(ts.SyntaxKind.KeyOfKeyword, factory.createTypeQueryNode(factory.createIdentifier(identifierName), void 0))))];
278
- }
279
- function createOmitDeclaration({ keys, type, nonNullable }) {
280
- const node = nonNullable ? factory.createTypeReferenceNode(factory.createIdentifier("NonNullable"), [type]) : type;
281
- if (Array.isArray(keys)) return factory.createTypeReferenceNode(factory.createIdentifier("Omit"), [node, factory.createUnionTypeNode(keys.map((key) => {
282
- return factory.createLiteralTypeNode(factory.createStringLiteral(key));
283
- }))]);
284
- return factory.createTypeReferenceNode(factory.createIdentifier("Omit"), [node, factory.createLiteralTypeNode(factory.createStringLiteral(keys))]);
285
- }
286
- const keywordTypeNodes = {
287
- any: factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword),
288
- unknown: factory.createKeywordTypeNode(ts.SyntaxKind.UnknownKeyword),
289
- void: factory.createKeywordTypeNode(ts.SyntaxKind.VoidKeyword),
290
- number: factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword),
291
- integer: factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword),
292
- bigint: factory.createKeywordTypeNode(ts.SyntaxKind.BigIntKeyword),
293
- object: factory.createKeywordTypeNode(ts.SyntaxKind.ObjectKeyword),
294
- string: factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword),
295
- boolean: factory.createKeywordTypeNode(ts.SyntaxKind.BooleanKeyword),
296
- undefined: factory.createKeywordTypeNode(ts.SyntaxKind.UndefinedKeyword),
297
- null: factory.createLiteralTypeNode(factory.createToken(ts.SyntaxKind.NullKeyword)),
298
- never: factory.createKeywordTypeNode(ts.SyntaxKind.NeverKeyword)
299
- };
300
- /**
301
- * Converts a path like '/pet/{petId}/uploadImage' to a template literal type
302
- * like `/pet/${string}/uploadImage`
303
- */
304
- /**
305
- * Converts an OAS-style path (e.g. `/pets/{petId}`) or an Express-style path
306
- * (e.g. `/pets/:petId`) to a TypeScript template literal type
307
- * like `` `/pets/${string}` ``.
308
- */
309
- function createUrlTemplateType(path) {
310
- const normalized = path.replace(/:([^/]+)/g, "{$1}");
311
- if (!normalized.includes("{")) return factory.createLiteralTypeNode(factory.createStringLiteral(normalized));
312
- const segments = normalized.split(/(\{[^}]+\})/);
313
- const parts = [];
314
- const parameterIndices = [];
315
- segments.forEach((segment) => {
316
- if (segment.startsWith("{") && segment.endsWith("}")) {
317
- parameterIndices.push(parts.length);
318
- parts.push(segment);
319
- } else if (segment) parts.push(segment);
320
- });
321
- const head = ts.factory.createTemplateHead(parts[0] || "");
322
- const templateSpans = [];
323
- parameterIndices.forEach((paramIndex, i) => {
324
- const isLast = i === parameterIndices.length - 1;
325
- const nextPart = parts[paramIndex + 1] || "";
326
- const literal = isLast ? ts.factory.createTemplateTail(nextPart) : ts.factory.createTemplateMiddle(nextPart);
327
- templateSpans.push(ts.factory.createTemplateLiteralTypeSpan(keywordTypeNodes.string, literal));
328
- });
329
- return ts.factory.createTemplateLiteralType(head, templateSpans);
330
- }
331
- const createTypeLiteralNode = factory.createTypeLiteralNode;
332
- const createTypeReferenceNode = factory.createTypeReferenceNode;
333
- const createNumericLiteral = factory.createNumericLiteral;
334
- const createStringLiteral = factory.createStringLiteral;
335
- const createArrayTypeNode = factory.createArrayTypeNode;
336
- factory.createParenthesizedType;
337
- const createLiteralTypeNode = factory.createLiteralTypeNode;
338
- factory.createNull;
339
- const createIdentifier = factory.createIdentifier;
340
- const createOptionalTypeNode = factory.createOptionalTypeNode;
341
- const createTupleTypeNode = factory.createTupleTypeNode;
342
- const createRestTypeNode = factory.createRestTypeNode;
343
- const createTrue = factory.createTrue;
344
- const createFalse = factory.createFalse;
345
- const createIndexedAccessTypeNode = factory.createIndexedAccessTypeNode;
346
- const createTypeOperatorNode = factory.createTypeOperatorNode;
347
- const createPrefixUnaryExpression = factory.createPrefixUnaryExpression;
348
- //#endregion
349
- //#region src/parser.ts
350
- const typeKeywordMapper = {
351
- any: () => keywordTypeNodes.any,
352
- unknown: () => keywordTypeNodes.unknown,
353
- void: () => keywordTypeNodes.void,
354
- number: () => keywordTypeNodes.number,
355
- integer: () => keywordTypeNodes.number,
356
- bigint: () => keywordTypeNodes.bigint,
357
- object: (nodes) => {
358
- if (!nodes || !nodes.length) return keywordTypeNodes.object;
359
- return createTypeLiteralNode(nodes);
360
- },
361
- string: () => keywordTypeNodes.string,
362
- boolean: () => keywordTypeNodes.boolean,
363
- undefined: () => keywordTypeNodes.undefined,
364
- nullable: void 0,
365
- null: () => keywordTypeNodes.null,
366
- nullish: void 0,
367
- array: (nodes, arrayType) => {
368
- if (!nodes) return;
369
- return createArrayDeclaration({
370
- nodes,
371
- arrayType
372
- });
373
- },
374
- tuple: (nodes, rest, min, max) => {
375
- if (!nodes) return;
376
- if (max) {
377
- nodes = nodes.slice(0, max);
378
- if (nodes.length < max && rest) nodes = [...nodes, ...Array(max - nodes.length).fill(rest)];
379
- }
380
- if (min) nodes = nodes.map((node, index) => index >= min ? createOptionalTypeNode(node) : node);
381
- if (typeof max === "undefined" && rest) nodes.push(createRestTypeNode(createArrayTypeNode(rest)));
382
- return createTupleTypeNode(nodes);
383
- },
384
- enum: (name) => {
385
- if (!name) return;
386
- return createTypeReferenceNode(name, void 0);
387
- },
388
- union: (nodes) => {
389
- if (!nodes) return;
390
- return createUnionDeclaration({
391
- withParentheses: true,
392
- nodes
393
- });
394
- },
395
- const: (name, format) => {
396
- if (name === null || name === void 0 || name === "") return;
397
- if (format === "boolean") {
398
- if (name === true) return createLiteralTypeNode(createTrue());
399
- return createLiteralTypeNode(createFalse());
400
- }
401
- if (format === "number" && typeof name === "number") return createLiteralTypeNode(createNumericLiteral(name));
402
- return createLiteralTypeNode(createStringLiteral(name.toString()));
403
- },
404
- datetime: () => keywordTypeNodes.string,
405
- date: (type = "string") => type === "string" ? keywordTypeNodes.string : createTypeReferenceNode(createIdentifier("Date")),
406
- time: (type = "string") => type === "string" ? keywordTypeNodes.string : createTypeReferenceNode(createIdentifier("Date")),
407
- uuid: () => keywordTypeNodes.string,
408
- url: () => keywordTypeNodes.string,
409
- default: void 0,
410
- and: (nodes) => {
411
- if (!nodes) return;
412
- return createIntersectionDeclaration({
413
- withParentheses: true,
414
- nodes
415
- });
416
- },
417
- describe: void 0,
418
- min: void 0,
419
- max: void 0,
420
- optional: void 0,
421
- matches: () => keywordTypeNodes.string,
422
- email: () => keywordTypeNodes.string,
423
- firstName: void 0,
424
- lastName: void 0,
425
- password: void 0,
426
- phone: void 0,
427
- readOnly: void 0,
428
- writeOnly: void 0,
429
- ref: (propertyName) => {
430
- if (!propertyName) return;
431
- return createTypeReferenceNode(propertyName, void 0);
432
- },
433
- blob: () => createTypeReferenceNode("Blob", []),
434
- deprecated: void 0,
435
- example: void 0,
436
- schema: void 0,
437
- catchall: void 0,
438
- name: void 0,
439
- interface: void 0,
440
- exclusiveMaximum: void 0,
441
- exclusiveMinimum: void 0
442
- };
443
- /**
444
- * Recursively parses a schema tree node into a corresponding TypeScript AST node.
445
- *
446
- * Maps OpenAPI schema keywords to TypeScript AST nodes using the `typeKeywordMapper`, handling complex types such as unions, intersections, arrays, tuples (with optional/rest elements and length constraints), enums, constants, references, and objects with property modifiers and documentation annotations.
447
- *
448
- * @param current - The schema node to parse.
449
- * @param siblings - Sibling schema nodes, used for context in certain mappings.
450
- * @param name - The name of the schema or property being parsed.
451
- * @param options - Parsing options controlling output style, property handling.
452
- * @returns The generated TypeScript AST node, or `undefined` if the schema keyword is not mapped.
453
- */
454
- const parse = createParser({
455
- mapper: typeKeywordMapper,
456
- handlers: {
457
- union(tree, options) {
458
- const { current, schema, name } = tree;
459
- return typeKeywordMapper.union(current.args.map((it) => this.parse({
460
- schema,
461
- parent: current,
462
- name,
463
- current: it,
464
- siblings: []
465
- }, options)).filter(Boolean));
466
- },
467
- and(tree, options) {
468
- const { current, schema, name } = tree;
469
- return typeKeywordMapper.and(current.args.map((it) => this.parse({
470
- schema,
471
- parent: current,
472
- name,
473
- current: it,
474
- siblings: []
475
- }, options)).filter(Boolean));
476
- },
477
- array(tree, options) {
478
- const { current, schema, name } = tree;
479
- return typeKeywordMapper.array(current.args.items.map((it) => this.parse({
480
- schema,
481
- parent: current,
482
- name,
483
- current: it,
484
- siblings: []
485
- }, options)).filter(Boolean), options.arrayType);
486
- },
487
- enum(tree, options) {
488
- const { current } = tree;
489
- if (options.enumType === "inlineLiteral") {
490
- const enumValues = current.args.items.map((item) => item.value).filter((value) => value !== void 0 && value !== null).map((value) => {
491
- const format = typeof value === "number" ? "number" : typeof value === "boolean" ? "boolean" : "string";
492
- return typeKeywordMapper.const(value, format);
493
- }).filter(Boolean);
494
- return typeKeywordMapper.union(enumValues);
495
- }
496
- return typeKeywordMapper.enum(["asConst", "asPascalConst"].includes(options.enumType) ? `${current.args.typeName}Key` : current.args.typeName);
497
- },
498
- ref(tree, _options) {
499
- const { current } = tree;
500
- return typeKeywordMapper.ref(current.args.name);
501
- },
502
- blob() {
503
- return typeKeywordMapper.blob();
504
- },
505
- tuple(tree, options) {
506
- const { current, schema, name } = tree;
507
- return typeKeywordMapper.tuple(current.args.items.map((it) => this.parse({
508
- schema,
509
- parent: current,
510
- name,
511
- current: it,
512
- siblings: []
513
- }, options)).filter(Boolean), current.args.rest && (this.parse({
514
- schema,
515
- parent: current,
516
- name,
517
- current: current.args.rest,
518
- siblings: []
519
- }, options) ?? void 0), current.args.min, current.args.max);
520
- },
521
- const(tree, _options) {
522
- const { current } = tree;
523
- return typeKeywordMapper.const(current.args.name, current.args.format);
524
- },
525
- object(tree, options) {
526
- const { current, schema, name } = tree;
527
- const properties = Object.entries(current.args?.properties || {}).filter((item) => {
528
- const schemas = item[1];
529
- return schemas && typeof schemas.map === "function";
530
- }).map(([name, schemas]) => {
531
- const mappedName = schemas.find((schema) => schema.keyword === schemaKeywords.name)?.args || name;
532
- const isNullish = schemas.some((schema) => schema.keyword === schemaKeywords.nullish);
533
- const isNullable = schemas.some((schema) => schema.keyword === schemaKeywords.nullable);
534
- const isOptional = schemas.some((schema) => schema.keyword === schemaKeywords.optional);
535
- const isReadonly = schemas.some((schema) => schema.keyword === schemaKeywords.readOnly);
536
- const describeSchema = schemas.find((schema) => schema.keyword === schemaKeywords.describe);
537
- const deprecatedSchema = schemas.find((schema) => schema.keyword === schemaKeywords.deprecated);
538
- const defaultSchema = schemas.find((schema) => schema.keyword === schemaKeywords.default);
539
- const exampleSchema = schemas.find((schema) => schema.keyword === schemaKeywords.example);
540
- const schemaSchema = schemas.find((schema) => schema.keyword === schemaKeywords.schema);
541
- const minSchema = schemas.find((schema) => schema.keyword === schemaKeywords.min);
542
- const maxSchema = schemas.find((schema) => schema.keyword === schemaKeywords.max);
543
- const matchesSchema = schemas.find((schema) => schema.keyword === schemaKeywords.matches);
544
- let type = schemas.map((it) => this.parse({
545
- schema,
546
- parent: current,
547
- name,
548
- current: it,
549
- siblings: schemas
550
- }, options)).filter(Boolean)[0];
551
- if (isNullable) type = createUnionDeclaration({ nodes: [type, keywordTypeNodes.null] });
552
- if (isNullish && ["undefined", "questionTokenAndUndefined"].includes(options.optionalType)) type = createUnionDeclaration({ nodes: [type, keywordTypeNodes.undefined] });
553
- if (isOptional && ["undefined", "questionTokenAndUndefined"].includes(options.optionalType)) type = createUnionDeclaration({ nodes: [type, keywordTypeNodes.undefined] });
554
- return appendJSDocToNode({
555
- node: createPropertySignature({
556
- questionToken: isOptional || isNullish ? ["questionToken", "questionTokenAndUndefined"].includes(options.optionalType) : false,
557
- name: mappedName,
558
- type,
559
- readOnly: isReadonly
560
- }),
561
- comments: [
562
- describeSchema ? `@description ${jsStringEscape(describeSchema.args)}` : void 0,
563
- deprecatedSchema ? "@deprecated" : void 0,
564
- minSchema ? `@minLength ${minSchema.args}` : void 0,
565
- maxSchema ? `@maxLength ${maxSchema.args}` : void 0,
566
- matchesSchema ? `@pattern ${matchesSchema.args}` : void 0,
567
- defaultSchema ? `@default ${defaultSchema.args}` : void 0,
568
- exampleSchema ? `@example ${exampleSchema.args}` : void 0,
569
- schemaSchema?.args?.type || schemaSchema?.args?.format ? [`@type ${schemaSchema?.args?.type || "unknown"}${!isOptional ? "" : " | undefined"}`, schemaSchema?.args?.format].filter(Boolean).join(", ") : void 0
570
- ].filter(Boolean)
571
- });
572
- });
573
- let additionalProperties;
574
- if (current.args?.additionalProperties?.length) {
575
- let additionalPropertiesType = current.args.additionalProperties.map((it) => this.parse({
576
- schema,
577
- parent: current,
578
- name,
579
- current: it,
580
- siblings: []
581
- }, options)).filter(Boolean).at(0);
582
- if (current.args?.additionalProperties.some((schema) => isKeyword(schema, schemaKeywords.nullable))) additionalPropertiesType = createUnionDeclaration({ nodes: [additionalPropertiesType, keywordTypeNodes.null] });
583
- additionalProperties = createIndexSignature(properties.length > 0 ? keywordTypeNodes.unknown : additionalPropertiesType);
584
- }
585
- let patternProperties;
586
- if (current.args?.patternProperties) {
587
- const allPatternSchemas = Object.values(current.args.patternProperties).flat();
588
- if (allPatternSchemas.length > 0) {
589
- patternProperties = allPatternSchemas.map((it) => this.parse({
590
- schema,
591
- parent: current,
592
- name,
593
- current: it,
594
- siblings: []
595
- }, options)).filter(Boolean).at(0);
596
- if (allPatternSchemas.some((schema) => isKeyword(schema, schemaKeywords.nullable))) patternProperties = createUnionDeclaration({ nodes: [patternProperties, keywordTypeNodes.null] });
597
- patternProperties = createIndexSignature(patternProperties);
598
- }
599
- }
600
- return typeKeywordMapper.object([
601
- ...properties,
602
- additionalProperties,
603
- patternProperties
604
- ].filter(Boolean));
605
- },
606
- datetime() {
607
- return typeKeywordMapper.datetime();
608
- },
609
- date(tree) {
610
- const { current } = tree;
611
- return typeKeywordMapper.date(current.args.type);
612
- },
613
- time(tree) {
614
- const { current } = tree;
615
- return typeKeywordMapper.time(current.args.type);
616
- }
617
- }
618
- });
619
- //#endregion
620
- //#region src/components/Type.tsx
621
- function Type({ name, typedName, tree, keysToOmit, schema, optionalType, arrayType, syntaxType, enumType, enumKeyCasing, description }) {
622
- const typeNodes = [];
623
- if (!tree.length) return "";
624
- const schemaFromTree = tree.find((item) => item.keyword === schemaKeywords.schema);
625
- const enumSchemas = SchemaGenerator.deepSearch(tree, schemaKeywords.enum);
626
- let type = tree.map((current, _index, siblings) => parse({
627
- name,
628
- schema,
629
- parent: void 0,
630
- current,
631
- siblings
632
- }, {
633
- optionalType,
634
- arrayType,
635
- enumType
636
- })).filter(Boolean).at(0) || typeKeywordMapper.undefined();
637
- if (["asConst", "asPascalConst"].includes(enumType) && enumSchemas.length > 0) {
638
- const isDirectEnum = schema.type === "array" && schema.items !== void 0;
639
- const isEnumOnly = "enum" in schema && schema.enum;
640
- if (isDirectEnum || isEnumOnly) {
641
- type = createTypeReferenceNode(`${enumSchemas[0].args.typeName}Key`);
642
- if (schema.type === "array") if (arrayType === "generic") type = createTypeReferenceNode(createIdentifier("Array"), [type]);
643
- else type = createArrayTypeNode(type);
644
- }
645
- }
646
- if (schemaFromTree && isKeyword(schemaFromTree, schemaKeywords.schema)) {
647
- const isNullish = tree.some((item) => item.keyword === schemaKeywords.nullish);
648
- const isNullable = tree.some((item) => item.keyword === schemaKeywords.nullable);
649
- const isOptional = tree.some((item) => item.keyword === schemaKeywords.optional);
650
- if (isNullable) type = createUnionDeclaration({ nodes: [type, keywordTypeNodes.null] });
651
- if (isNullish && ["undefined", "questionTokenAndUndefined"].includes(optionalType)) type = createUnionDeclaration({ nodes: [type, keywordTypeNodes.undefined] });
652
- if (isOptional && ["undefined", "questionTokenAndUndefined"].includes(optionalType)) type = createUnionDeclaration({ nodes: [type, keywordTypeNodes.undefined] });
653
- }
654
- const useTypeGeneration = syntaxType === "type" || [syntaxKind.union].includes(type.kind) || !!keysToOmit?.length;
655
- typeNodes.push(createTypeDeclaration({
656
- name,
657
- isExportable: true,
658
- type: keysToOmit?.length ? createOmitDeclaration({
659
- keys: keysToOmit,
660
- type,
661
- nonNullable: true
662
- }) : type,
663
- syntax: useTypeGeneration ? "type" : "interface",
664
- comments: [
665
- schema.title ? `${jsStringEscape(schema.title)}` : void 0,
666
- description ? `@description ${jsStringEscape(description)}` : void 0,
667
- schema.deprecated ? "@deprecated" : void 0,
668
- schema.minLength ? `@minLength ${schema.minLength}` : void 0,
669
- schema.maxLength ? `@maxLength ${schema.maxLength}` : void 0,
670
- schema.pattern ? `@pattern ${schema.pattern}` : void 0,
671
- schema.default ? `@default ${schema.default}` : void 0,
672
- schema.example ? `@example ${schema.example}` : void 0
673
- ]
674
- }));
675
- const enums = [...new Set(enumSchemas)].map((enumSchema) => {
676
- const name = enumType === "asPascalConst" ? pascalCase(enumSchema.args.name) : camelCase(enumSchema.args.name);
677
- const typeName = ["asConst", "asPascalConst"].includes(enumType) ? `${enumSchema.args.typeName}Key` : enumSchema.args.typeName;
678
- const [nameNode, typeNode] = createEnumDeclaration({
679
- name,
680
- typeName,
681
- enums: enumSchema.args.items.map((item) => item.value === void 0 ? void 0 : [trimQuotes(item.name?.toString()), item.value]).filter(Boolean),
682
- type: enumType,
683
- enumKeyCasing
684
- });
685
- return {
686
- nameNode,
687
- typeNode,
688
- name,
689
- typeName
690
- };
691
- });
692
- const shouldExportEnums = enumType !== "inlineLiteral";
693
- const shouldExportType = enumType === "inlineLiteral" || enums.every((item) => item.typeName !== name);
694
- return /* @__PURE__ */ jsxs(Fragment, { children: [shouldExportEnums && enums.map(({ name, nameNode, typeName, typeNode }) => /* @__PURE__ */ jsxs(Fragment, { children: [nameNode && /* @__PURE__ */ jsx(File.Source, {
695
- name,
696
- isExportable: true,
697
- isIndexable: true,
698
- isTypeOnly: false,
699
- children: safePrint(nameNode)
700
- }), /* @__PURE__ */ jsx(File.Source, {
701
- name: typeName,
702
- isIndexable: true,
703
- isExportable: [
704
- "enum",
705
- "asConst",
706
- "asPascalConst",
707
- "constEnum",
708
- "literal",
709
- void 0
710
- ].includes(enumType),
711
- isTypeOnly: [
712
- "asConst",
713
- "asPascalConst",
714
- "literal",
715
- void 0
716
- ].includes(enumType),
717
- children: safePrint(typeNode)
718
- })] })), shouldExportType && /* @__PURE__ */ jsx(File.Source, {
719
- name: typedName,
720
- isTypeOnly: true,
721
- isExportable: true,
722
- isIndexable: true,
723
- children: safePrint(...typeNodes)
724
- })] });
725
- }
726
- //#endregion
727
- export { keywordTypeNodes as A, createTypeDeclaration as C, createUnionDeclaration as D, createTypeReferenceNode as E, camelCase as F, pascalCase as I, syntaxKind as M, jsStringEscape as N, createUrlTemplateType as O, trimQuotes as P, createTypeAliasDeclaration as S, createTypeOperatorNode as T, createPropertySignature as _, createArrayTypeNode as a, createTrue as b, createIdentifier as c, createIntersectionDeclaration as d, createLiteralTypeNode as f, createPrefixUnaryExpression as g, createOptionalTypeNode as h, createArrayDeclaration as i, modifiers as j, getUnknownType as k, createIndexSignature as l, createOmitDeclaration as m, SyntaxKind as n, createEnumDeclaration as o, createNumericLiteral as p, appendJSDocToNode as r, createFalse as s, Type as t, createIndexedAccessTypeNode as u, createRestTypeNode as v, createTypeLiteralNode as w, createTupleTypeNode as x, createStringLiteral as y };
728
-
729
- //# sourceMappingURL=components-CRu8IKY3.js.map