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

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 (76) hide show
  1. package/dist/Type-B6fo0gSk.js +120 -0
  2. package/dist/Type-B6fo0gSk.js.map +1 -0
  3. package/dist/Type-oFwUfkZv.cjs +131 -0
  4. package/dist/Type-oFwUfkZv.cjs.map +1 -0
  5. package/dist/builderTs-Cd3juc2G.cjs +120 -0
  6. package/dist/builderTs-Cd3juc2G.cjs.map +1 -0
  7. package/dist/builderTs-DausqHpc.js +116 -0
  8. package/dist/builderTs-DausqHpc.js.map +1 -0
  9. package/dist/builders.cjs +3 -0
  10. package/dist/builders.d.ts +8 -0
  11. package/dist/builders.js +2 -0
  12. package/dist/casing-BJHFg-zZ.js +84 -0
  13. package/dist/casing-BJHFg-zZ.js.map +1 -0
  14. package/dist/casing-DHfdqpLi.cjs +107 -0
  15. package/dist/casing-DHfdqpLi.cjs.map +1 -0
  16. package/dist/chunk-ByKO4r7w.cjs +38 -0
  17. package/dist/components.cjs +3 -2
  18. package/dist/components.d.ts +40 -11
  19. package/dist/components.js +2 -2
  20. package/dist/generators-ByK18qUn.js +551 -0
  21. package/dist/generators-ByK18qUn.js.map +1 -0
  22. package/dist/generators-aSsiTfUO.cjs +563 -0
  23. package/dist/generators-aSsiTfUO.cjs.map +1 -0
  24. package/dist/generators.cjs +3 -2
  25. package/dist/generators.d.ts +7 -492
  26. package/dist/generators.js +2 -2
  27. package/dist/index.cjs +148 -3
  28. package/dist/index.cjs.map +1 -0
  29. package/dist/index.d.ts +1 -1
  30. package/dist/index.js +146 -1
  31. package/dist/index.js.map +1 -0
  32. package/dist/printerTs-BgZucv4T.js +559 -0
  33. package/dist/printerTs-BgZucv4T.js.map +1 -0
  34. package/dist/printerTs-CFXc_LpP.cjs +595 -0
  35. package/dist/printerTs-CFXc_LpP.cjs.map +1 -0
  36. package/dist/printers.cjs +3 -0
  37. package/dist/printers.d.ts +75 -0
  38. package/dist/printers.js +2 -0
  39. package/dist/resolverTsLegacy-DLl854-P.js +185 -0
  40. package/dist/resolverTsLegacy-DLl854-P.js.map +1 -0
  41. package/dist/resolverTsLegacy-sJ16Iqrl.cjs +196 -0
  42. package/dist/resolverTsLegacy-sJ16Iqrl.cjs.map +1 -0
  43. package/dist/resolvers.cjs +4 -0
  44. package/dist/resolvers.d.ts +52 -0
  45. package/dist/resolvers.js +2 -0
  46. package/dist/types-BcyuFDn9.d.ts +344 -0
  47. package/package.json +27 -8
  48. package/src/builders/builderTs.ts +92 -0
  49. package/src/builders/index.ts +1 -0
  50. package/src/components/Enum.tsx +83 -0
  51. package/src/components/Type.tsx +24 -145
  52. package/src/components/index.ts +1 -0
  53. package/src/constants.ts +29 -0
  54. package/src/factory.ts +14 -48
  55. package/src/generators/index.ts +1 -0
  56. package/src/generators/typeGenerator.tsx +119 -403
  57. package/src/generators/typeGeneratorLegacy.tsx +345 -0
  58. package/src/plugin.ts +80 -122
  59. package/src/presets.ts +26 -0
  60. package/src/printers/index.ts +1 -0
  61. package/src/printers/printerTs.ts +389 -0
  62. package/src/resolvers/index.ts +2 -0
  63. package/src/resolvers/resolverTs.ts +107 -0
  64. package/src/resolvers/resolverTsLegacy.ts +87 -0
  65. package/src/types.ts +261 -72
  66. package/dist/components-9wydyqUx.cjs +0 -848
  67. package/dist/components-9wydyqUx.cjs.map +0 -1
  68. package/dist/components-LmqJfxMv.js +0 -721
  69. package/dist/components-LmqJfxMv.js.map +0 -1
  70. package/dist/plugin-CNkzbtpl.cjs +0 -508
  71. package/dist/plugin-CNkzbtpl.cjs.map +0 -1
  72. package/dist/plugin-DoLrDl9P.js +0 -476
  73. package/dist/plugin-DoLrDl9P.js.map +0 -1
  74. package/dist/types-BpeKGgCn.d.ts +0 -170
  75. package/src/parser.ts +0 -396
  76. package/src/printer.ts +0 -221
@@ -1,721 +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 = { union: SyntaxKind.UnionType };
132
- function getUnknownType(unknownType) {
133
- if (unknownType === "any") return keywordTypeNodes.any;
134
- if (unknownType === "void") return keywordTypeNodes.void;
135
- return keywordTypeNodes.unknown;
136
- }
137
- function isValidIdentifier(str) {
138
- if (!str.length || str.trim() !== str) return false;
139
- const node = ts.parseIsolatedEntityName(str, ts.ScriptTarget.Latest);
140
- return !!node && node.kind === ts.SyntaxKind.Identifier && ts.identifierToKeywordKind(node.kind) === void 0;
141
- }
142
- function propertyName(name) {
143
- if (typeof name === "string") return isValidIdentifier(name) ? factory.createIdentifier(name) : factory.createStringLiteral(name);
144
- return name;
145
- }
146
- const questionToken = factory.createToken(ts.SyntaxKind.QuestionToken);
147
- function createQuestionToken(token) {
148
- if (!token) return;
149
- if (token === true) return questionToken;
150
- return token;
151
- }
152
- function createIntersectionDeclaration({ nodes, withParentheses }) {
153
- if (!nodes.length) return null;
154
- if (nodes.length === 1) return nodes[0] || null;
155
- const node = factory.createIntersectionTypeNode(nodes);
156
- if (withParentheses) return factory.createParenthesizedType(node);
157
- return node;
158
- }
159
- function createArrayDeclaration({ nodes, arrayType = "array" }) {
160
- if (!nodes.length) return factory.createTupleTypeNode([]);
161
- if (nodes.length === 1) {
162
- const node = nodes[0];
163
- if (!node) return null;
164
- if (arrayType === "generic") return factory.createTypeReferenceNode(factory.createIdentifier("Array"), [node]);
165
- return factory.createArrayTypeNode(node);
166
- }
167
- const unionType = factory.createUnionTypeNode(nodes);
168
- if (arrayType === "generic") return factory.createTypeReferenceNode(factory.createIdentifier("Array"), [unionType]);
169
- return factory.createArrayTypeNode(factory.createParenthesizedType(unionType));
170
- }
171
- /**
172
- * Minimum nodes length of 2
173
- * @example `string | number`
174
- */
175
- function createUnionDeclaration({ nodes, withParentheses }) {
176
- if (!nodes.length) return keywordTypeNodes.any;
177
- if (nodes.length === 1) return nodes[0];
178
- const node = factory.createUnionTypeNode(nodes);
179
- if (withParentheses) return factory.createParenthesizedType(node);
180
- return node;
181
- }
182
- function createPropertySignature({ readOnly, modifiers = [], name, questionToken, type }) {
183
- return factory.createPropertySignature([...modifiers, readOnly ? factory.createToken(ts.SyntaxKind.ReadonlyKeyword) : void 0].filter(Boolean), propertyName(name), createQuestionToken(questionToken), type);
184
- }
185
- function createParameterSignature(name, { modifiers, dotDotDotToken, questionToken, type, initializer }) {
186
- return factory.createParameterDeclaration(modifiers, dotDotDotToken, name, createQuestionToken(questionToken), type, initializer);
187
- }
188
- /**
189
- * @link https://github.com/microsoft/TypeScript/issues/44151
190
- */
191
- function appendJSDocToNode({ node, comments }) {
192
- const filteredComments = comments.filter(Boolean);
193
- if (!filteredComments.length) return node;
194
- const text = filteredComments.reduce((acc = "", comment = "") => {
195
- return `${acc}\n * ${comment.replaceAll("*/", "*\\/")}`;
196
- }, "*");
197
- return ts.addSyntheticLeadingComment(node, ts.SyntaxKind.MultiLineCommentTrivia, `${text || "*"}\n`, true);
198
- }
199
- function createIndexSignature(type, { modifiers, indexName = "key", indexType = factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword) } = {}) {
200
- return factory.createIndexSignature(modifiers, [createParameterSignature(indexName, { type: indexType })], type);
201
- }
202
- function createTypeAliasDeclaration({ modifiers, name, typeParameters, type }) {
203
- return factory.createTypeAliasDeclaration(modifiers, name, typeParameters, type);
204
- }
205
- function createInterfaceDeclaration({ modifiers, name, typeParameters, members }) {
206
- return factory.createInterfaceDeclaration(modifiers, name, typeParameters, void 0, members);
207
- }
208
- function createTypeDeclaration({ syntax, isExportable, comments, name, type }) {
209
- if (syntax === "interface" && "members" in type) return appendJSDocToNode({
210
- node: createInterfaceDeclaration({
211
- members: type.members,
212
- modifiers: isExportable ? [modifiers.export] : [],
213
- name,
214
- typeParameters: void 0
215
- }),
216
- comments
217
- });
218
- return appendJSDocToNode({
219
- node: createTypeAliasDeclaration({
220
- type,
221
- modifiers: isExportable ? [modifiers.export] : [],
222
- name,
223
- typeParameters: void 0
224
- }),
225
- comments
226
- });
227
- }
228
- /**
229
- * Apply casing transformation to enum keys
230
- */
231
- function applyEnumKeyCasing(key, casing = "none") {
232
- if (casing === "none") return key;
233
- if (casing === "screamingSnakeCase") return screamingSnakeCase(key);
234
- if (casing === "snakeCase") return snakeCase(key);
235
- if (casing === "pascalCase") return pascalCase(key);
236
- if (casing === "camelCase") return camelCase(key);
237
- return key;
238
- }
239
- function createEnumDeclaration({ type = "enum", name, typeName, enums, enumKeyCasing = "none" }) {
240
- 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]) => {
241
- if (isNumber(value)) {
242
- if (value < 0) return factory.createLiteralTypeNode(factory.createPrefixUnaryExpression(ts.SyntaxKind.MinusToken, factory.createNumericLiteral(Math.abs(value))));
243
- return factory.createLiteralTypeNode(factory.createNumericLiteral(value?.toString()));
244
- }
245
- if (typeof value === "boolean") return factory.createLiteralTypeNode(value ? factory.createTrue() : factory.createFalse());
246
- if (value) return factory.createLiteralTypeNode(factory.createStringLiteral(value.toString()));
247
- }).filter(Boolean)))];
248
- 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]) => {
249
- let initializer = factory.createStringLiteral(value?.toString());
250
- 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)));
251
- else initializer = factory.createNumericLiteral(value);
252
- if (typeof value === "boolean") initializer = value ? factory.createTrue() : factory.createFalse();
253
- if (isNumber(Number.parseInt(key.toString(), 10))) {
254
- const casingKey = applyEnumKeyCasing(`${typeName}_${key}`, enumKeyCasing);
255
- return factory.createEnumMember(propertyName(casingKey), initializer);
256
- }
257
- if (key) {
258
- const casingKey = applyEnumKeyCasing(key.toString(), enumKeyCasing);
259
- return factory.createEnumMember(propertyName(casingKey), initializer);
260
- }
261
- }).filter(Boolean))];
262
- const identifierName = name;
263
- if (enums.length === 0) return [void 0, factory.createTypeAliasDeclaration([factory.createToken(ts.SyntaxKind.ExportKeyword)], factory.createIdentifier(typeName), void 0, factory.createKeywordTypeNode(ts.SyntaxKind.NeverKeyword))];
264
- 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]) => {
265
- let initializer = factory.createStringLiteral(value?.toString());
266
- if (isNumber(value)) if (value < 0) initializer = factory.createPrefixUnaryExpression(ts.SyntaxKind.MinusToken, factory.createNumericLiteral(Math.abs(value)));
267
- else initializer = factory.createNumericLiteral(value);
268
- if (typeof value === "boolean") initializer = value ? factory.createTrue() : factory.createFalse();
269
- if (key) {
270
- const casingKey = applyEnumKeyCasing(key.toString(), enumKeyCasing);
271
- return factory.createPropertyAssignment(propertyName(casingKey), initializer);
272
- }
273
- }).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))))];
274
- }
275
- function createOmitDeclaration({ keys, type, nonNullable }) {
276
- const node = nonNullable ? factory.createTypeReferenceNode(factory.createIdentifier("NonNullable"), [type]) : type;
277
- if (Array.isArray(keys)) return factory.createTypeReferenceNode(factory.createIdentifier("Omit"), [node, factory.createUnionTypeNode(keys.map((key) => {
278
- return factory.createLiteralTypeNode(factory.createStringLiteral(key));
279
- }))]);
280
- return factory.createTypeReferenceNode(factory.createIdentifier("Omit"), [node, factory.createLiteralTypeNode(factory.createStringLiteral(keys))]);
281
- }
282
- const keywordTypeNodes = {
283
- any: factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword),
284
- unknown: factory.createKeywordTypeNode(ts.SyntaxKind.UnknownKeyword),
285
- void: factory.createKeywordTypeNode(ts.SyntaxKind.VoidKeyword),
286
- number: factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword),
287
- integer: factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword),
288
- bigint: factory.createKeywordTypeNode(ts.SyntaxKind.BigIntKeyword),
289
- object: factory.createKeywordTypeNode(ts.SyntaxKind.ObjectKeyword),
290
- string: factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword),
291
- boolean: factory.createKeywordTypeNode(ts.SyntaxKind.BooleanKeyword),
292
- undefined: factory.createKeywordTypeNode(ts.SyntaxKind.UndefinedKeyword),
293
- null: factory.createLiteralTypeNode(factory.createToken(ts.SyntaxKind.NullKeyword)),
294
- never: factory.createKeywordTypeNode(ts.SyntaxKind.NeverKeyword)
295
- };
296
- /**
297
- * Converts a path like '/pet/{petId}/uploadImage' to a template literal type
298
- * like `/pet/${string}/uploadImage`
299
- */
300
- function createUrlTemplateType(path) {
301
- if (!path.includes("{")) return factory.createLiteralTypeNode(factory.createStringLiteral(path));
302
- const segments = path.split(/(\{[^}]+\})/);
303
- const parts = [];
304
- const parameterIndices = [];
305
- segments.forEach((segment) => {
306
- if (segment.startsWith("{") && segment.endsWith("}")) {
307
- parameterIndices.push(parts.length);
308
- parts.push(segment);
309
- } else if (segment) parts.push(segment);
310
- });
311
- const head = ts.factory.createTemplateHead(parts[0] || "");
312
- const templateSpans = [];
313
- parameterIndices.forEach((paramIndex, i) => {
314
- const isLast = i === parameterIndices.length - 1;
315
- const nextPart = parts[paramIndex + 1] || "";
316
- const literal = isLast ? ts.factory.createTemplateTail(nextPart) : ts.factory.createTemplateMiddle(nextPart);
317
- templateSpans.push(ts.factory.createTemplateLiteralTypeSpan(keywordTypeNodes.string, literal));
318
- });
319
- return ts.factory.createTemplateLiteralType(head, templateSpans);
320
- }
321
- const createTypeLiteralNode = factory.createTypeLiteralNode;
322
- const createTypeReferenceNode = factory.createTypeReferenceNode;
323
- const createNumericLiteral = factory.createNumericLiteral;
324
- const createStringLiteral = factory.createStringLiteral;
325
- const createArrayTypeNode = factory.createArrayTypeNode;
326
- factory.createParenthesizedType;
327
- const createLiteralTypeNode = factory.createLiteralTypeNode;
328
- factory.createNull;
329
- const createIdentifier = factory.createIdentifier;
330
- const createOptionalTypeNode = factory.createOptionalTypeNode;
331
- const createTupleTypeNode = factory.createTupleTypeNode;
332
- const createRestTypeNode = factory.createRestTypeNode;
333
- const createTrue = factory.createTrue;
334
- const createFalse = factory.createFalse;
335
- const createIndexedAccessTypeNode = factory.createIndexedAccessTypeNode;
336
- const createTypeOperatorNode = factory.createTypeOperatorNode;
337
- factory.createPrefixUnaryExpression;
338
- //#endregion
339
- //#region src/parser.ts
340
- const typeKeywordMapper = {
341
- any: () => keywordTypeNodes.any,
342
- unknown: () => keywordTypeNodes.unknown,
343
- void: () => keywordTypeNodes.void,
344
- number: () => keywordTypeNodes.number,
345
- integer: () => keywordTypeNodes.number,
346
- bigint: () => keywordTypeNodes.bigint,
347
- object: (nodes) => {
348
- if (!nodes || !nodes.length) return keywordTypeNodes.object;
349
- return createTypeLiteralNode(nodes);
350
- },
351
- string: () => keywordTypeNodes.string,
352
- boolean: () => keywordTypeNodes.boolean,
353
- undefined: () => keywordTypeNodes.undefined,
354
- nullable: void 0,
355
- null: () => keywordTypeNodes.null,
356
- nullish: void 0,
357
- array: (nodes, arrayType) => {
358
- if (!nodes) return;
359
- return createArrayDeclaration({
360
- nodes,
361
- arrayType
362
- });
363
- },
364
- tuple: (nodes, rest, min, max) => {
365
- if (!nodes) return;
366
- if (max) {
367
- nodes = nodes.slice(0, max);
368
- if (nodes.length < max && rest) nodes = [...nodes, ...Array(max - nodes.length).fill(rest)];
369
- }
370
- if (min) nodes = nodes.map((node, index) => index >= min ? createOptionalTypeNode(node) : node);
371
- if (typeof max === "undefined" && rest) nodes.push(createRestTypeNode(createArrayTypeNode(rest)));
372
- return createTupleTypeNode(nodes);
373
- },
374
- enum: (name) => {
375
- if (!name) return;
376
- return createTypeReferenceNode(name, void 0);
377
- },
378
- union: (nodes) => {
379
- if (!nodes) return;
380
- return createUnionDeclaration({
381
- withParentheses: true,
382
- nodes
383
- });
384
- },
385
- const: (name, format) => {
386
- if (name === null || name === void 0 || name === "") return;
387
- if (format === "boolean") {
388
- if (name === true) return createLiteralTypeNode(createTrue());
389
- return createLiteralTypeNode(createFalse());
390
- }
391
- if (format === "number" && typeof name === "number") return createLiteralTypeNode(createNumericLiteral(name));
392
- return createLiteralTypeNode(createStringLiteral(name.toString()));
393
- },
394
- datetime: () => keywordTypeNodes.string,
395
- date: (type = "string") => type === "string" ? keywordTypeNodes.string : createTypeReferenceNode(createIdentifier("Date")),
396
- time: (type = "string") => type === "string" ? keywordTypeNodes.string : createTypeReferenceNode(createIdentifier("Date")),
397
- uuid: () => keywordTypeNodes.string,
398
- url: () => keywordTypeNodes.string,
399
- default: void 0,
400
- and: (nodes) => {
401
- if (!nodes) return;
402
- return createIntersectionDeclaration({
403
- withParentheses: true,
404
- nodes
405
- });
406
- },
407
- describe: void 0,
408
- min: void 0,
409
- max: void 0,
410
- optional: void 0,
411
- matches: () => keywordTypeNodes.string,
412
- email: () => keywordTypeNodes.string,
413
- firstName: void 0,
414
- lastName: void 0,
415
- password: void 0,
416
- phone: void 0,
417
- readOnly: void 0,
418
- writeOnly: void 0,
419
- ref: (propertyName) => {
420
- if (!propertyName) return;
421
- return createTypeReferenceNode(propertyName, void 0);
422
- },
423
- blob: () => createTypeReferenceNode("Blob", []),
424
- deprecated: void 0,
425
- example: void 0,
426
- schema: void 0,
427
- catchall: void 0,
428
- name: void 0,
429
- interface: void 0,
430
- exclusiveMaximum: void 0,
431
- exclusiveMinimum: void 0
432
- };
433
- /**
434
- * Recursively parses a schema tree node into a corresponding TypeScript AST node.
435
- *
436
- * 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.
437
- *
438
- * @param current - The schema node to parse.
439
- * @param siblings - Sibling schema nodes, used for context in certain mappings.
440
- * @param name - The name of the schema or property being parsed.
441
- * @param options - Parsing options controlling output style, property handling, and custom mappers.
442
- * @returns The generated TypeScript AST node, or `undefined` if the schema keyword is not mapped.
443
- */
444
- const parse = createParser({
445
- mapper: typeKeywordMapper,
446
- handlers: {
447
- union(tree, options) {
448
- const { current, schema, name } = tree;
449
- return typeKeywordMapper.union(current.args.map((it) => this.parse({
450
- schema,
451
- parent: current,
452
- name,
453
- current: it,
454
- siblings: []
455
- }, options)).filter(Boolean));
456
- },
457
- and(tree, options) {
458
- const { current, schema, name } = tree;
459
- return typeKeywordMapper.and(current.args.map((it) => this.parse({
460
- schema,
461
- parent: current,
462
- name,
463
- current: it,
464
- siblings: []
465
- }, options)).filter(Boolean));
466
- },
467
- array(tree, options) {
468
- const { current, schema, name } = tree;
469
- return typeKeywordMapper.array(current.args.items.map((it) => this.parse({
470
- schema,
471
- parent: current,
472
- name,
473
- current: it,
474
- siblings: []
475
- }, options)).filter(Boolean), options.arrayType);
476
- },
477
- enum(tree, options) {
478
- const { current } = tree;
479
- if (options.enumType === "inlineLiteral") {
480
- const enumValues = current.args.items.map((item) => item.value).filter((value) => value !== void 0 && value !== null).map((value) => {
481
- const format = typeof value === "number" ? "number" : typeof value === "boolean" ? "boolean" : "string";
482
- return typeKeywordMapper.const(value, format);
483
- }).filter(Boolean);
484
- return typeKeywordMapper.union(enumValues);
485
- }
486
- return typeKeywordMapper.enum(["asConst", "asPascalConst"].includes(options.enumType) ? `${current.args.typeName}Key` : current.args.typeName);
487
- },
488
- ref(tree, _options) {
489
- const { current } = tree;
490
- return typeKeywordMapper.ref(current.args.name);
491
- },
492
- blob() {
493
- return typeKeywordMapper.blob();
494
- },
495
- tuple(tree, options) {
496
- const { current, schema, name } = tree;
497
- return typeKeywordMapper.tuple(current.args.items.map((it) => this.parse({
498
- schema,
499
- parent: current,
500
- name,
501
- current: it,
502
- siblings: []
503
- }, options)).filter(Boolean), current.args.rest && (this.parse({
504
- schema,
505
- parent: current,
506
- name,
507
- current: current.args.rest,
508
- siblings: []
509
- }, options) ?? void 0), current.args.min, current.args.max);
510
- },
511
- const(tree, _options) {
512
- const { current } = tree;
513
- return typeKeywordMapper.const(current.args.name, current.args.format);
514
- },
515
- object(tree, options) {
516
- const { current, schema, name } = tree;
517
- const properties = Object.entries(current.args?.properties || {}).filter((item) => {
518
- const schemas = item[1];
519
- return schemas && typeof schemas.map === "function";
520
- }).map(([name, schemas]) => {
521
- const mappedName = schemas.find((schema) => schema.keyword === schemaKeywords.name)?.args || name;
522
- if (options.mapper && Object.hasOwn(options.mapper, mappedName)) return options.mapper[mappedName];
523
- const isNullish = schemas.some((schema) => schema.keyword === schemaKeywords.nullish);
524
- const isNullable = schemas.some((schema) => schema.keyword === schemaKeywords.nullable);
525
- const isOptional = schemas.some((schema) => schema.keyword === schemaKeywords.optional);
526
- const isReadonly = schemas.some((schema) => schema.keyword === schemaKeywords.readOnly);
527
- const describeSchema = schemas.find((schema) => schema.keyword === schemaKeywords.describe);
528
- const deprecatedSchema = schemas.find((schema) => schema.keyword === schemaKeywords.deprecated);
529
- const defaultSchema = schemas.find((schema) => schema.keyword === schemaKeywords.default);
530
- const exampleSchema = schemas.find((schema) => schema.keyword === schemaKeywords.example);
531
- const schemaSchema = schemas.find((schema) => schema.keyword === schemaKeywords.schema);
532
- const minSchema = schemas.find((schema) => schema.keyword === schemaKeywords.min);
533
- const maxSchema = schemas.find((schema) => schema.keyword === schemaKeywords.max);
534
- const matchesSchema = schemas.find((schema) => schema.keyword === schemaKeywords.matches);
535
- let type = schemas.map((it) => this.parse({
536
- schema,
537
- parent: current,
538
- name,
539
- current: it,
540
- siblings: schemas
541
- }, options)).filter(Boolean)[0];
542
- if (isNullable) type = createUnionDeclaration({ nodes: [type, keywordTypeNodes.null] });
543
- if (isNullish && ["undefined", "questionTokenAndUndefined"].includes(options.optionalType)) type = createUnionDeclaration({ nodes: [type, keywordTypeNodes.undefined] });
544
- if (isOptional && ["undefined", "questionTokenAndUndefined"].includes(options.optionalType)) type = createUnionDeclaration({ nodes: [type, keywordTypeNodes.undefined] });
545
- return appendJSDocToNode({
546
- node: createPropertySignature({
547
- questionToken: isOptional || isNullish ? ["questionToken", "questionTokenAndUndefined"].includes(options.optionalType) : false,
548
- name: mappedName,
549
- type,
550
- readOnly: isReadonly
551
- }),
552
- comments: [
553
- describeSchema ? `@description ${jsStringEscape(describeSchema.args)}` : void 0,
554
- deprecatedSchema ? "@deprecated" : void 0,
555
- minSchema ? `@minLength ${minSchema.args}` : void 0,
556
- maxSchema ? `@maxLength ${maxSchema.args}` : void 0,
557
- matchesSchema ? `@pattern ${matchesSchema.args}` : void 0,
558
- defaultSchema ? `@default ${defaultSchema.args}` : void 0,
559
- exampleSchema ? `@example ${exampleSchema.args}` : void 0,
560
- schemaSchema?.args?.type || schemaSchema?.args?.format ? [`@type ${schemaSchema?.args?.type || "unknown"}${!isOptional ? "" : " | undefined"}`, schemaSchema?.args?.format].filter(Boolean).join(", ") : void 0
561
- ].filter(Boolean)
562
- });
563
- });
564
- let additionalProperties;
565
- if (current.args?.additionalProperties?.length) {
566
- let additionalPropertiesType = current.args.additionalProperties.map((it) => this.parse({
567
- schema,
568
- parent: current,
569
- name,
570
- current: it,
571
- siblings: []
572
- }, options)).filter(Boolean).at(0);
573
- if (current.args?.additionalProperties.some((schema) => isKeyword(schema, schemaKeywords.nullable))) additionalPropertiesType = createUnionDeclaration({ nodes: [additionalPropertiesType, keywordTypeNodes.null] });
574
- additionalProperties = createIndexSignature(properties.length > 0 ? keywordTypeNodes.unknown : additionalPropertiesType);
575
- }
576
- let patternProperties;
577
- if (current.args?.patternProperties) {
578
- const allPatternSchemas = Object.values(current.args.patternProperties).flat();
579
- if (allPatternSchemas.length > 0) {
580
- patternProperties = allPatternSchemas.map((it) => this.parse({
581
- schema,
582
- parent: current,
583
- name,
584
- current: it,
585
- siblings: []
586
- }, options)).filter(Boolean).at(0);
587
- if (allPatternSchemas.some((schema) => isKeyword(schema, schemaKeywords.nullable))) patternProperties = createUnionDeclaration({ nodes: [patternProperties, keywordTypeNodes.null] });
588
- patternProperties = createIndexSignature(patternProperties);
589
- }
590
- }
591
- return typeKeywordMapper.object([
592
- ...properties,
593
- additionalProperties,
594
- patternProperties
595
- ].filter(Boolean));
596
- },
597
- datetime() {
598
- return typeKeywordMapper.datetime();
599
- },
600
- date(tree) {
601
- const { current } = tree;
602
- return typeKeywordMapper.date(current.args.type);
603
- },
604
- time(tree) {
605
- const { current } = tree;
606
- return typeKeywordMapper.time(current.args.type);
607
- }
608
- }
609
- });
610
- //#endregion
611
- //#region src/components/Type.tsx
612
- function Type({ name, typedName, tree, keysToOmit, schema, optionalType, arrayType, syntaxType, enumType, enumKeyCasing, mapper, description }) {
613
- const typeNodes = [];
614
- if (!tree.length) return "";
615
- const schemaFromTree = tree.find((item) => item.keyword === schemaKeywords.schema);
616
- const enumSchemas = SchemaGenerator.deepSearch(tree, schemaKeywords.enum);
617
- let type = tree.map((current, _index, siblings) => parse({
618
- name,
619
- schema,
620
- parent: void 0,
621
- current,
622
- siblings
623
- }, {
624
- optionalType,
625
- arrayType,
626
- enumType,
627
- mapper
628
- })).filter(Boolean).at(0) || typeKeywordMapper.undefined();
629
- if (["asConst", "asPascalConst"].includes(enumType) && enumSchemas.length > 0) {
630
- const isDirectEnum = schema.type === "array" && schema.items !== void 0;
631
- const isEnumOnly = "enum" in schema && schema.enum;
632
- if (isDirectEnum || isEnumOnly) {
633
- type = createTypeReferenceNode(`${enumSchemas[0].args.typeName}Key`);
634
- if (schema.type === "array") if (arrayType === "generic") type = createTypeReferenceNode(createIdentifier("Array"), [type]);
635
- else type = createArrayTypeNode(type);
636
- }
637
- }
638
- if (schemaFromTree && isKeyword(schemaFromTree, schemaKeywords.schema)) {
639
- const isNullish = tree.some((item) => item.keyword === schemaKeywords.nullish);
640
- const isNullable = tree.some((item) => item.keyword === schemaKeywords.nullable);
641
- const isOptional = tree.some((item) => item.keyword === schemaKeywords.optional);
642
- if (isNullable) type = createUnionDeclaration({ nodes: [type, keywordTypeNodes.null] });
643
- if (isNullish && ["undefined", "questionTokenAndUndefined"].includes(optionalType)) type = createUnionDeclaration({ nodes: [type, keywordTypeNodes.undefined] });
644
- if (isOptional && ["undefined", "questionTokenAndUndefined"].includes(optionalType)) type = createUnionDeclaration({ nodes: [type, keywordTypeNodes.undefined] });
645
- }
646
- const useTypeGeneration = syntaxType === "type" || [syntaxKind.union].includes(type.kind) || !!keysToOmit?.length;
647
- typeNodes.push(createTypeDeclaration({
648
- name,
649
- isExportable: true,
650
- type: keysToOmit?.length ? createOmitDeclaration({
651
- keys: keysToOmit,
652
- type,
653
- nonNullable: true
654
- }) : type,
655
- syntax: useTypeGeneration ? "type" : "interface",
656
- comments: [
657
- schema.title ? `${jsStringEscape(schema.title)}` : void 0,
658
- description ? `@description ${jsStringEscape(description)}` : void 0,
659
- schema.deprecated ? "@deprecated" : void 0,
660
- schema.minLength ? `@minLength ${schema.minLength}` : void 0,
661
- schema.maxLength ? `@maxLength ${schema.maxLength}` : void 0,
662
- schema.pattern ? `@pattern ${schema.pattern}` : void 0,
663
- schema.default ? `@default ${schema.default}` : void 0,
664
- schema.example ? `@example ${schema.example}` : void 0
665
- ]
666
- }));
667
- const enums = [...new Set(enumSchemas)].map((enumSchema) => {
668
- const name = enumType === "asPascalConst" ? pascalCase(enumSchema.args.name) : camelCase(enumSchema.args.name);
669
- const typeName = ["asConst", "asPascalConst"].includes(enumType) ? `${enumSchema.args.typeName}Key` : enumSchema.args.typeName;
670
- const [nameNode, typeNode] = createEnumDeclaration({
671
- name,
672
- typeName,
673
- enums: enumSchema.args.items.map((item) => item.value === void 0 ? void 0 : [trimQuotes(item.name?.toString()), item.value]).filter(Boolean),
674
- type: enumType,
675
- enumKeyCasing
676
- });
677
- return {
678
- nameNode,
679
- typeNode,
680
- name,
681
- typeName
682
- };
683
- });
684
- const shouldExportEnums = enumType !== "inlineLiteral";
685
- const shouldExportType = enumType === "inlineLiteral" || enums.every((item) => item.typeName !== name);
686
- return /* @__PURE__ */ jsxs(Fragment, { children: [shouldExportEnums && enums.map(({ name, nameNode, typeName, typeNode }) => /* @__PURE__ */ jsxs(Fragment, { children: [nameNode && /* @__PURE__ */ jsx(File.Source, {
687
- name,
688
- isExportable: true,
689
- isIndexable: true,
690
- isTypeOnly: false,
691
- children: safePrint(nameNode)
692
- }), /* @__PURE__ */ jsx(File.Source, {
693
- name: typeName,
694
- isIndexable: true,
695
- isExportable: [
696
- "enum",
697
- "asConst",
698
- "asPascalConst",
699
- "constEnum",
700
- "literal",
701
- void 0
702
- ].includes(enumType),
703
- isTypeOnly: [
704
- "asConst",
705
- "asPascalConst",
706
- "literal",
707
- void 0
708
- ].includes(enumType),
709
- children: safePrint(typeNode)
710
- })] })), shouldExportType && /* @__PURE__ */ jsx(File.Source, {
711
- name: typedName,
712
- isTypeOnly: true,
713
- isExportable: true,
714
- isIndexable: true,
715
- children: safePrint(...typeNodes)
716
- })] });
717
- }
718
- //#endregion
719
- export { createTypeAliasDeclaration as a, createTypeReferenceNode as c, getUnknownType as d, keywordTypeNodes as f, pascalCase as h, createPropertySignature as i, createUnionDeclaration as l, camelCase as m, createIdentifier as n, createTypeLiteralNode as o, modifiers as p, createIndexedAccessTypeNode as r, createTypeOperatorNode as s, Type as t, createUrlTemplateType as u };
720
-
721
- //# sourceMappingURL=components-LmqJfxMv.js.map