@kubb/parser-ts 5.0.0-beta.9 → 5.0.0-beta.93

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,11 +1,30 @@
1
- import "./chunk--u3MIqq1.js";
1
+ import "./rolldown-runtime-C0LytTxp.js";
2
2
  import { defineParser } from "@kubb/core";
3
3
  import { normalize, relative } from "node:path";
4
4
  import ts from "typescript";
5
- //#region src/constants.ts
5
+ //#region ../../internals/utils/src/fs.ts
6
6
  /**
7
- * Matches the trailing `.<ext>` segment of a path (keeps segments like `foo.bar.ts`
8
- * intact by only trimming the last run of non-`/`/`.` characters).
7
+ * Strips the file extension from a path or file name.
8
+ * Only removes the last `.ext` segment when the dot is not part of a directory name.
9
+ *
10
+ * @example
11
+ * trimExtName('petStore.ts') // 'petStore'
12
+ * trimExtName('/src/models/pet.ts') // '/src/models/pet'
13
+ * trimExtName('/project.v2/gen/pet.ts') // '/project.v2/gen/pet'
14
+ * trimExtName('noExtension') // 'noExtension'
15
+ */
16
+ function trimExtName(text) {
17
+ const dotIndex = text.lastIndexOf(".");
18
+ if (dotIndex > 0 && !text.includes("/", dotIndex)) return text.slice(0, dotIndex);
19
+ return text;
20
+ }
21
+ /**
22
+ * Indentation unit prepended once per nesting level when pretty-printing.
23
+ */
24
+ const INDENT = " ".repeat(2);
25
+ /**
26
+ * Matches only the final `.<ext>` of a path, so a name like `foo.bar.ts` keeps
27
+ * `foo.bar` and loses just `.ts`.
9
28
  */
10
29
  const FILE_EXTENSION_PATTERN = /\.[^/.]+$/;
11
30
  /**
@@ -13,48 +32,35 @@ const FILE_EXTENSION_PATTERN = /\.[^/.]+$/;
13
32
  */
14
33
  const WINDOWS_PATH_SEPARATOR = /\\/g;
15
34
  /**
16
- * Matches `*\/` in free-form text so JSDoc bodies can neutralise premature
35
+ * Matches `*\/` in free-form text so JSDoc bodies can neutralize premature
17
36
  * comment terminators (`*\/` → `* /`).
18
37
  */
19
38
  const JSDOC_TERMINATOR_PATTERN = /\*\//g;
20
39
  /**
21
- * Matches carriage returns for normalising CRLF/CR line endings to LF.
40
+ * Matches carriage returns for normalizing CRLF/CR line endings to LF.
22
41
  */
23
42
  const CARRIAGE_RETURN_PATTERN = /\r/g;
24
43
  /**
25
- * Matches CRLF sequences used when normalising TypeScript printer output.
44
+ * Matches CRLF sequences used when normalizing TypeScript printer output.
26
45
  */
27
46
  const CRLF_PATTERN = /\r\n/g;
28
47
  /**
29
- * Matches an identifier that starts with a digit JavaScript disallows this
30
- * so the printer prefixes such names with `_`.
48
+ * Matches an identifier that starts with a digit. JavaScript disallows this,
49
+ * so the printer replaces the leading digit with `_`.
31
50
  */
32
51
  const LEADING_DIGIT_PATTERN = /^\d/;
33
52
  //#endregion
34
53
  //#region src/utils.ts
35
54
  const { factory } = ts;
36
55
  /**
37
- * Normalises a file-system path to POSIX separators and strips any leading `../` segment.
38
- */
39
- function slash(path) {
40
- return normalize(path).replaceAll(WINDOWS_PATH_SEPARATOR, "/").replace("../", "");
41
- }
42
- /**
43
56
  * Resolves `filePath` relative to `rootDir` and returns a POSIX-style path
44
57
  * prefixed with `./` when the target sits inside the root, or `../` when it escapes it.
45
58
  */
46
59
  function getRelativePath(rootDir, filePath) {
47
- const slashed = slash(relative(rootDir, filePath));
60
+ const slashed = normalize(relative(rootDir, filePath)).replaceAll(WINDOWS_PATH_SEPARATOR, "/").replace("../", "");
48
61
  return slashed.startsWith("../") ? slashed : `./${slashed}`;
49
62
  }
50
63
  /**
51
- * Strips the trailing file extension (for example `.ts`) from a path.
52
- * Preserves intermediate dots like `foo.bar.ts` → `foo.bar`.
53
- */
54
- function trimExtName(text) {
55
- return text.replace(FILE_EXTENSION_PATTERN, "");
56
- }
57
- /**
58
64
  * Rewrites an import/export path so its extension matches the caller-supplied
59
65
  * `options.extname`. When the source path has no extension the original is kept,
60
66
  * so virtual/module-only paths flow through unchanged.
@@ -65,25 +71,64 @@ function resolveOutputPath(path, options, rootAware) {
65
71
  return rootAware ? trimExtName(path) : path;
66
72
  }
67
73
  /**
68
- * Serializes the body / value content from a `nodes` array.
69
- *
70
- * Each element is either a raw string or a structured {@link CodeNode}
71
- * (recursively converted via {@link printCodeNode}).
72
- * Elements are joined with `\n`.
74
+ * Serializes a `nodes` array into source text. Each entry is rendered via {@link printCodeNode}
75
+ * and joined with a single newline. A `Break` node (`<br/>`) inserts one blank line between
76
+ * statements. Consecutive breaks, and breaks at the very start or end, are folded into the
77
+ * separator, so a double `<br/>` never emits more than one blank line.
73
78
  */
74
79
  function printNodes(nodes) {
75
80
  if (!nodes || nodes.length === 0) return "";
76
- return nodes.map(printCodeNode).join("\n");
81
+ let result = "";
82
+ let hasContent = false;
83
+ let pendingBreak = false;
84
+ for (const node of nodes) {
85
+ if (node.kind === "Break") {
86
+ if (hasContent) pendingBreak = true;
87
+ continue;
88
+ }
89
+ const text = printCodeNode(node);
90
+ if (!text) continue;
91
+ if (hasContent) result += pendingBreak ? "\n\n" : "\n";
92
+ result += text;
93
+ hasContent = true;
94
+ pendingBreak = false;
95
+ }
96
+ return result;
77
97
  }
78
98
  /**
79
- * Indents every non-empty line of `text` by `spaces` spaces.
99
+ * Indents every non-empty line of `text` by one indent unit. Pass a number to repeat
100
+ * {@link INDENT_CHAR} that many times, or a string to use as the indent verbatim.
80
101
  */
81
- function indentLines(text, spaces = 2) {
102
+ function indentLines(text, indent = INDENT) {
82
103
  if (!text) return "";
83
- const pad = " ".repeat(spaces);
104
+ const pad = typeof indent === "string" ? indent : " ".repeat(indent);
84
105
  return text.split("\n").map((line) => line.trim() ? `${pad}${line}` : "").join("\n");
85
106
  }
86
107
  /**
108
+ * Removes the common leading whitespace shared by every non-blank line and trims
109
+ * surrounding blank lines, so multi-line content authored inside an indented template
110
+ * literal lines up at a column-zero baseline. Leading whitespace is counted by
111
+ * character, so N tabs and N spaces are treated as the same depth.
112
+ *
113
+ * @example
114
+ * ```ts
115
+ * dedent('\n foo\n bar\n ')
116
+ * // 'foo\n bar'
117
+ * ```
118
+ */
119
+ function dedent(text) {
120
+ if (!text) return "";
121
+ const lines = text.split("\n");
122
+ const isBlank = (line) => line.trim() === "";
123
+ const start = lines.findIndex((line) => !isBlank(line));
124
+ if (start === -1) return "";
125
+ const end = lines.findLastIndex((line) => !isBlank(line));
126
+ const trimmed = lines.slice(start, end + 1);
127
+ const indents = trimmed.filter((line) => !isBlank(line)).map((line) => line.match(/^\s*/)?.[0].length ?? 0);
128
+ const min = indents.length ? Math.min(...indents) : 0;
129
+ return trimmed.map((line) => isBlank(line) ? "" : line.slice(min)).join("\n");
130
+ }
131
+ /**
87
132
  * Renders the generic clause (`<T, U>`) shared by function and arrow-function nodes.
88
133
  * Accepts either a raw string (rendered verbatim) or an array of type-parameter names.
89
134
  */
@@ -100,34 +145,28 @@ function formatReturnType(returnType, isAsync) {
100
145
  return isAsync ? `: Promise<${returnType}>` : `: ${returnType}`;
101
146
  }
102
147
  /**
103
- * Validates TypeScript AST nodes before printing.
104
- * Throws an error if any node has SyntaxKind.Unknown which would cause the
105
- * TypeScript printer to crash.
148
+ * Module-scoped TypeScript printer instance. A printer does not mutate the source file, so one
149
+ * instance is reused across every `print()` call instead of constructing a new printer each time.
106
150
  */
107
- function validateNodes(...nodes) {
108
- for (const node of nodes) {
109
- if (!node) throw new Error("Attempted to print undefined or null TypeScript node");
110
- if (node.kind === ts.SyntaxKind.Unknown) throw new Error(`Invalid TypeScript AST node detected with SyntaxKind.Unknown. This typically indicates a schema pattern that could not be properly converted to TypeScript. Node: ${JSON.stringify(node, null, 2)}`);
111
- }
112
- }
151
+ const TS_PRINTER = ts.createPrinter({
152
+ omitTrailingSemicolon: true,
153
+ newLine: ts.NewLineKind.LineFeed,
154
+ removeComments: false,
155
+ noEmitHelpers: true
156
+ });
113
157
  /**
114
- * Converts TypeScript/TSX AST nodes to a string using the TypeScript printer.
158
+ * Module-scoped source file used as the print target. `printList` only reads the source
159
+ * file's compiler options / language version. It never mutates it.
115
160
  */
116
- function print(...elements) {
117
- const sourceFile = ts.createSourceFile("print.tsx", "", ts.ScriptTarget.ES2022, true, ts.ScriptKind.TSX);
118
- return ts.createPrinter({
119
- omitTrailingSemicolon: true,
120
- newLine: ts.NewLineKind.LineFeed,
121
- removeComments: false,
122
- noEmitHelpers: true
123
- }).printList(ts.ListFormat.MultiLine, factory.createNodeArray(elements.filter(Boolean)), sourceFile).replace(CRLF_PATTERN, "\n");
124
- }
161
+ const PRINT_SOURCE_FILE = ts.createSourceFile("print.tsx", "", ts.ScriptTarget.ES2022, true, ts.ScriptKind.TSX);
162
+ TS_PRINTER.printList(ts.ListFormat.MultiLine, factory.createNodeArray([]), PRINT_SOURCE_FILE);
125
163
  /**
126
- * Like `print` but validates nodes first to surface issues early.
164
+ * Converts TypeScript/TSX AST nodes to a string using the TypeScript printer.
127
165
  */
128
- function safePrint(...elements) {
129
- validateNodes(...elements);
130
- return print(...elements);
166
+ function print(...elements) {
167
+ const filtered = elements.filter(Boolean);
168
+ if (filtered.length === 0) return "";
169
+ return TS_PRINTER.printList(ts.ListFormat.MultiLine, factory.createNodeArray(filtered), PRINT_SOURCE_FILE).replace(CRLF_PATTERN, "\n");
131
170
  }
132
171
  /**
133
172
  * Converts a {@link JSDocNode} to a JSDoc comment block string.
@@ -159,13 +198,13 @@ function printJSDoc(jsDoc) {
159
198
  *
160
199
  * @example
161
200
  * ```ts
162
- * printConst(createConst({ name: 'pet', export: true, nodes: ['{}'] }))
201
+ * printConst(factory.createConst({ name: 'pet', export: true, nodes: ['{}'] }))
163
202
  * // 'export const pet = {}'
164
203
  * ```
165
204
  *
166
205
  * @example With type and `as const`
167
206
  * ```ts
168
- * printConst(createConst({ name: 'pets', export: true, type: 'Pet[]', asConst: true, nodes: ['[]'] }))
207
+ * printConst(factory.createConst({ name: 'pets', export: true, type: 'Pet[]', asConst: true, nodes: ['[]'] }))
169
208
  * // 'export const pets: Pet[] = [] as const'
170
209
  * ```
171
210
  */
@@ -190,7 +229,7 @@ function printConst(node) {
190
229
  *
191
230
  * @example
192
231
  * ```ts
193
- * printType(createType({ name: 'Pet', export: true, nodes: ['{ id: number }'] }))
232
+ * printType(factory.createType({ name: 'Pet', export: true, nodes: ['{ id: number }'] }))
194
233
  * // 'export type Pet = { id: number }'
195
234
  * ```
196
235
  */
@@ -213,13 +252,13 @@ function printType(node) {
213
252
  *
214
253
  * @example
215
254
  * ```ts
216
- * printFunction(createFunction({ name: 'getPet', export: true, params: 'id: string', returnType: 'Pet', nodes: ['return fetch(id)'] }))
255
+ * printFunction(factory.createFunction({ name: 'getPet', export: true, params: 'id: string', returnType: 'Pet', nodes: ['return fetch(id)'] }))
217
256
  * // 'export function getPet(id: string): Pet {\n return fetch(id)\n}'
218
257
  * ```
219
258
  *
220
259
  * @example Async with generics
221
260
  * ```ts
222
- * printFunction(createFunction({ name: 'fetchPet', export: true, async: true, generics: ['T'], params: 'id: string', returnType: 'T' }))
261
+ * printFunction(factory.createFunction({ name: 'fetchPet', export: true, async: true, generics: ['T'], params: 'id: string', returnType: 'T' }))
223
262
  * // 'export async function fetchPet<T>(id: string): Promise<T> {\n}'
224
263
  * ```
225
264
  */
@@ -249,13 +288,13 @@ function printFunction(node) {
249
288
  *
250
289
  * @example Multi-line arrow function
251
290
  * ```ts
252
- * printArrowFunction(createArrowFunction({ name: 'getPet', export: true, params: 'id: string', nodes: ['return fetch(id)'] }))
291
+ * printArrowFunction(factory.createArrowFunction({ name: 'getPet', export: true, params: 'id: string', nodes: ['return fetch(id)'] }))
253
292
  * // 'export const getPet = (id: string) => {\n return fetch(id)\n}'
254
293
  * ```
255
294
  *
256
295
  * @example Single-line arrow function
257
296
  * ```ts
258
- * printArrowFunction(createArrowFunction({ name: 'double', params: 'n: number', singleLine: true, nodes: ['n * 2'] }))
297
+ * printArrowFunction(factory.createArrowFunction({ name: 'double', params: 'n: number', singleLine: true, nodes: ['n * 2'] }))
259
298
  * // 'const double = (n: number) => n * 2'
260
299
  * ```
261
300
  */
@@ -284,20 +323,19 @@ function printArrowFunction(node) {
284
323
  *
285
324
  * @example
286
325
  * ```ts
287
- * printCodeNode(createConst({ name: 'x', nodes: ['1'] }))
326
+ * printCodeNode(factory.createConst({ name: 'x', nodes: ['1'] }))
288
327
  * // 'const x = 1'
289
328
  * ```
290
329
  */
291
330
  function printCodeNode(node) {
292
- switch (node.kind) {
293
- case "Break": return "";
294
- case "Text": return node.value;
295
- case "Jsx": return node.value;
296
- case "Const": return printConst(node);
297
- case "Type": return printType(node);
298
- case "Function": return printFunction(node);
299
- case "ArrowFunction": return printArrowFunction(node);
300
- }
331
+ if (node.kind === "Break") return "";
332
+ if (node.kind === "Text") return dedent(node.value);
333
+ if (node.kind === "Jsx") return dedent(node.value);
334
+ if (node.kind === "Const") return printConst(node);
335
+ if (node.kind === "Type") return printType(node);
336
+ if (node.kind === "Function") return printFunction(node);
337
+ if (node.kind === "ArrowFunction") return printArrowFunction(node);
338
+ return "";
301
339
  }
302
340
  /**
303
341
  * Converts a {@link SourceNode} to its TypeScript string representation.
@@ -305,101 +343,183 @@ function printCodeNode(node) {
305
343
  * Iterates `nodes` in DOM order, rendering each {@link CodeNode} via
306
344
  * {@link printCodeNode}.
307
345
  *
346
+ * Top-level declarations are separated by a blank line so the source reads
347
+ * cleanly without an external formatter.
348
+ *
308
349
  * @example From nodes
309
350
  * ```ts
310
- * printSource({ kind: 'Source', nodes: [createConst({ name: 'x', nodes: [createText('1')] }), createText('x.toString()')] })
311
- * // 'const x = 1\nx.toString()'
351
+ * printSource({ kind: 'Source', nodes: [factory.createConst({ name: 'x', nodes: [factory.createText('1')] }), factory.createText('x.toString()')] })
352
+ * // 'const x = 1\n\nx.toString()'
312
353
  * ```
313
354
  */
314
355
  function printSource(node) {
315
- if (node.nodes && node.nodes.length > 0) return node.nodes.map(printCodeNode).join("\n");
316
- return "";
317
- }
318
- function createImport({ name, path, root, isTypeOnly = false, isNameSpace = false }) {
319
- const resolvePath = root ? getRelativePath(root, path) : path;
320
- if (!Array.isArray(name)) {
321
- if (isNameSpace) return factory.createImportDeclaration(void 0, factory.createImportClause(isTypeOnly, void 0, factory.createNamespaceImport(factory.createIdentifier(name))), factory.createStringLiteral(resolvePath), void 0);
322
- return factory.createImportDeclaration(void 0, factory.createImportClause(isTypeOnly, factory.createIdentifier(name), void 0), factory.createStringLiteral(resolvePath), void 0);
356
+ const nodes = node.nodes;
357
+ if (!nodes || nodes.length === 0) return "";
358
+ let result = "";
359
+ for (const child of nodes) {
360
+ const text = printCodeNode(child);
361
+ if (!text) continue;
362
+ result = result ? `${result}\n\n${text}` : text;
323
363
  }
324
- const specifiers = name.map((item) => {
325
- if (typeof item === "object") {
326
- const { propertyName, name: alias } = item;
327
- return factory.createImportSpecifier(false, alias ? factory.createIdentifier(propertyName) : void 0, factory.createIdentifier(alias ?? propertyName));
328
- }
329
- return factory.createImportSpecifier(false, void 0, factory.createIdentifier(item));
330
- });
331
- return factory.createImportDeclaration(void 0, factory.createImportClause(isTypeOnly, void 0, factory.createNamedImports(specifiers)), factory.createStringLiteral(resolvePath), void 0);
364
+ return result;
365
+ }
366
+ /**
367
+ * Wraps a module specifier in single quotes, escaping any embedded backslash or quote so the emitted
368
+ * statement stays valid even for unusual paths.
369
+ */
370
+ function quoteModulePath(path) {
371
+ return `'${path.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
332
372
  }
333
- function createExport({ path, asAlias, isTypeOnly = false, name }) {
334
- if (name && !Array.isArray(name) && !asAlias) console.warn(`When using name as string, asAlias should be true: ${name}`);
373
+ /**
374
+ * Renders an import declaration string in the repo style (single quotes, no semicolons), covering
375
+ * default, namespace (`* as`), and named imports with `{ a as b }` aliases, each optionally
376
+ * `type`-only. `path` is used verbatim, so resolve it first.
377
+ *
378
+ * @example
379
+ * ```ts
380
+ * printImport({ name: ['z'], path: './zod.ts' })
381
+ * // "import { z } from './zod.ts'"
382
+ * ```
383
+ */
384
+ function printImport({ name, path, isTypeOnly = false, isNameSpace = false }) {
385
+ const typePrefix = isTypeOnly ? "type " : "";
386
+ const from = quoteModulePath(path);
335
387
  if (!Array.isArray(name)) {
336
- const parsedName = name && LEADING_DIGIT_PATTERN.test(name) ? `_${name.slice(1)}` : name;
337
- return factory.createExportDeclaration(void 0, isTypeOnly, asAlias && parsedName ? factory.createNamespaceExport(factory.createIdentifier(parsedName)) : void 0, factory.createStringLiteral(path), void 0);
388
+ if (isNameSpace) return `import ${typePrefix}* as ${name} from ${from}`;
389
+ return `import ${typePrefix}${name} from ${from}`;
338
390
  }
339
- return factory.createExportDeclaration(void 0, isTypeOnly, factory.createNamedExports(name.map((propertyName) => factory.createExportSpecifier(false, void 0, typeof propertyName === "string" ? factory.createIdentifier(propertyName) : propertyName))), factory.createStringLiteral(path), void 0);
391
+ return `import ${typePrefix}{ ${name.map((item) => {
392
+ if (typeof item === "object") return item.name ? `${item.propertyName} as ${item.name}` : item.propertyName;
393
+ return item;
394
+ }).join(", ")} } from ${from}`;
395
+ }
396
+ /**
397
+ * Renders an export declaration string in the repo style (single quotes, no semicolons), covering
398
+ * named re-exports, namespace alias (`* as name`), and wildcard, each optionally `type`-only.
399
+ * `path` is used verbatim, so resolve it first.
400
+ *
401
+ * @example
402
+ * ```ts
403
+ * printExport({ name: ['Pet', 'Order'], path: './models.ts' })
404
+ * // "export { Pet, Order } from './models.ts'"
405
+ * ```
406
+ */
407
+ function printExport({ path, name, isTypeOnly = false, asAlias = false }) {
408
+ const typePrefix = isTypeOnly ? "type " : "";
409
+ const from = quoteModulePath(path);
410
+ if (Array.isArray(name)) return `export ${typePrefix}{ ${name.map((item) => typeof item === "string" ? item : item.text).join(", ")} } from ${from}`;
411
+ if (asAlias && name) return `export ${typePrefix}* as ${LEADING_DIGIT_PATTERN.test(name) ? `_${name.slice(1)}` : name} from ${from}`;
412
+ if (name) console.warn(`When using name as string, asAlias should be true: ${name}`);
413
+ return `export ${typePrefix}* from ${from}`;
340
414
  }
341
415
  //#endregion
342
416
  //#region src/parserTs.ts
417
+ const DEFAULT_EXTENSION = { ".ts": "" };
343
418
  /**
344
- * Parser that converts `.ts` and `.js` files to strings using the TypeScript
345
- * compiler. Handles import/export statement generation from file metadata.
419
+ * Default Kubb parser for `.ts` and `.js` files. Takes the universal AST
420
+ * produced by an adapter and prints it as TypeScript source using the official
421
+ * TypeScript compiler. Imports and exports are rewritten based on each file's
422
+ * metadata and the `extension` option.
423
+ *
424
+ * Used automatically when no `parsers` option is set on `defineConfig`. Use
425
+ * `parserTsx` instead for React projects that emit JSX.
426
+ *
427
+ * @example
428
+ * ```ts
429
+ * import { defineConfig } from 'kubb'
430
+ * import { adapterOas } from '@kubb/adapter-oas'
431
+ * import { parserTs } from '@kubb/parser-ts'
346
432
  *
347
- * @default Used automatically when no `parsers` option is set in `defineConfig`.
433
+ * export default defineConfig({
434
+ * input: './petStore.yaml',
435
+ * output: { path: './src/gen' },
436
+ * adapter: adapterOas(),
437
+ * parsers: [parserTs()],
438
+ * plugins: [],
439
+ * })
440
+ * ```
348
441
  */
349
- const parserTs = defineParser({
350
- name: "typescript",
351
- extNames: [".ts", ".js"],
352
- async parse(file, options = { extname: ".ts" }) {
353
- const sourceParts = [];
354
- for (const item of file.sources) {
355
- const sourceStr = printSource(item);
356
- if (sourceStr) sourceParts.push(sourceStr.trimEnd());
357
- }
358
- const source = sourceParts.join("\n\n");
359
- const importNodes = [];
360
- for (const item of file.imports) {
361
- const importPath = item.root ? getRelativePath(item.root, item.path) : item.path;
362
- importNodes.push(createImport({
442
+ const parserTs = defineParser(({ extension = DEFAULT_EXTENSION } = {}) => {
443
+ return {
444
+ name: "typescript",
445
+ extNames: [".ts", ".js"],
446
+ print(...nodes) {
447
+ return print(...nodes);
448
+ },
449
+ parse(file) {
450
+ const extname = extension[file.extname] || void 0;
451
+ const sourceParts = [];
452
+ for (const item of file.sources) {
453
+ const sourceStr = printSource(item);
454
+ if (sourceStr) sourceParts.push(sourceStr.trimEnd());
455
+ }
456
+ const source = sourceParts.join("\n\n");
457
+ const importLines = [];
458
+ for (const item of file.imports) {
459
+ const importPath = item.root ? getRelativePath(item.root, item.path) : item.path;
460
+ importLines.push(printImport({
461
+ name: item.name,
462
+ path: resolveOutputPath(importPath, { extname }, Boolean(item.root)),
463
+ isTypeOnly: item.isTypeOnly,
464
+ isNameSpace: item.isNameSpace
465
+ }));
466
+ }
467
+ const exportLines = [];
468
+ for (const item of file.exports) exportLines.push(printExport({
363
469
  name: item.name,
364
- path: resolveOutputPath(importPath, options, Boolean(item.root)),
470
+ path: resolveOutputPath(item.path, { extname }, true),
365
471
  isTypeOnly: item.isTypeOnly,
366
- isNameSpace: item.isNameSpace
472
+ asAlias: item.asAlias
367
473
  }));
474
+ const importExportBlock = [...importLines, ...exportLines].join("\n");
475
+ return [
476
+ file.banner,
477
+ importExportBlock,
478
+ source,
479
+ file.footer
480
+ ].filter((segment) => Boolean(segment)).map((s) => s.trimEnd()).join("\n\n");
368
481
  }
369
- const exportNodes = [];
370
- for (const item of file.exports) exportNodes.push(createExport({
371
- name: item.name,
372
- path: resolveOutputPath(item.path, options, true),
373
- isTypeOnly: item.isTypeOnly,
374
- asAlias: item.asAlias
375
- }));
376
- return [
377
- file.banner,
378
- print(...importNodes, ...exportNodes),
379
- source,
380
- file.footer
381
- ].filter((segment) => Boolean(segment)).map((s) => s.trimEnd()).join("\n\n");
382
- }
482
+ };
383
483
  });
384
484
  //#endregion
385
485
  //#region src/parserTsx.ts
386
486
  /**
387
- * Parser that converts `.tsx` and `.jsx` files to strings.
388
- * Delegates to `typescriptParser` since the TypeScript compiler natively
389
- * supports JSX/TSX syntax via `ScriptKind.TSX`.
487
+ * Kubb parser for `.tsx` and `.jsx` files. Delegates to `parserTs` because the
488
+ * TypeScript compiler handles JSX natively via `ScriptKind.TSX`, so it shares the
489
+ * same `extension` option.
390
490
  *
391
- * Add this parser to the `parsers` option in `defineConfig` when generating `.tsx`/`.jsx` files.
491
+ * Add to the `parsers` array on `defineConfig` when generating components for
492
+ * React (or any framework that emits JSX).
392
493
  *
393
- * @default extname '.tsx'
494
+ * @example
495
+ * ```ts
496
+ * import { defineConfig } from 'kubb'
497
+ * import { adapterOas } from '@kubb/adapter-oas'
498
+ * import { parserTsx } from '@kubb/parser-ts'
499
+ *
500
+ * export default defineConfig({
501
+ * input: './petStore.yaml',
502
+ * output: { path: './src/gen' },
503
+ * adapter: adapterOas(),
504
+ * parsers: [parserTsx()],
505
+ * plugins: [],
506
+ * })
507
+ * ```
394
508
  */
395
- const parserTsx = defineParser({
396
- name: "tsx",
397
- extNames: [".tsx", ".jsx"],
398
- async parse(file, options = { extname: ".tsx" }) {
399
- return parserTs.parse(file, options);
400
- }
509
+ const parserTsx = defineParser((options = {}) => {
510
+ const parser = parserTs(options);
511
+ return {
512
+ name: "tsx",
513
+ extNames: [".tsx", ".jsx"],
514
+ print(...nodes) {
515
+ return print(...nodes);
516
+ },
517
+ parse(file) {
518
+ return parser.parse(file);
519
+ }
520
+ };
401
521
  });
402
522
  //#endregion
403
- export { createExport, createImport, parserTs, parserTsx, print, safePrint, validateNodes };
523
+ export { parserTs, parserTsx };
404
524
 
405
525
  //# sourceMappingURL=index.js.map