@kubb/parser-ts 4.1.4 → 5.0.0-alpha.32

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/LICENSE CHANGED
@@ -1,21 +1,14 @@
1
- MIT License
1
+ Copyright (c) 2026 Stijn Van Hulle
2
2
 
3
- Copyright (c) 2025 Stijn Van Hulle
3
+ This repository contains software under two licenses:
4
4
 
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
5
+ 1. Most of the code in this repository is licensed under the
6
+ MIT License see licenses/LICENSE-MIT for the full license text.
11
7
 
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
8
+ 2. The following components are licensed under the
9
+ GNU Affero General Public License v3.0 or later (AGPL-3.0-or-later)
10
+ — see licenses/LICENSE-AGPL-3.0 for the full license text:
14
11
 
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
12
+ - packages/agent (published as @kubb/agent)
13
+
14
+ Each package's own LICENSE file or package.json specifies its applicable license.
@@ -0,0 +1,8 @@
1
+ //#region \0rolldown/runtime.js
2
+ var __defProp = Object.defineProperty;
3
+ var __name = (target, value) => __defProp(target, "name", {
4
+ value,
5
+ configurable: true
6
+ });
7
+ //#endregion
8
+ export { __name as t };
package/dist/index.cjs CHANGED
@@ -1,70 +1,379 @@
1
- const require_factory = require('./factory-BNDICAoK.cjs');
2
- let typescript = require("typescript");
3
- typescript = require_factory.__toESM(typescript);
4
- let prettier = require("prettier");
5
- prettier = require_factory.__toESM(prettier);
6
- let prettier_plugins_typescript = require("prettier/plugins/typescript");
7
- prettier_plugins_typescript = require_factory.__toESM(prettier_plugins_typescript);
8
-
9
- //#region src/format.ts
10
- const formatOptions = {
11
- tabWidth: 2,
12
- printWidth: 160,
13
- parser: "typescript",
14
- singleQuote: true,
15
- semi: false,
16
- bracketSameLine: false,
17
- endOfLine: "auto",
18
- plugins: [prettier_plugins_typescript.default]
19
- };
20
- function format(source) {
21
- if (!source) return Promise.resolve("");
22
- try {
23
- return (0, prettier.format)(source, formatOptions);
24
- } catch (_e) {
25
- return Promise.resolve(source);
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region \0rolldown/runtime.js
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
+ key = keys[i];
12
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
13
+ get: ((k) => from[k]).bind(null, key),
14
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
15
+ });
26
16
  }
27
- }
28
-
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
20
+ value: mod,
21
+ enumerable: true
22
+ }) : target, mod));
29
23
  //#endregion
30
- //#region src/print.ts
24
+ let node_path = require("node:path");
25
+ let _kubb_core = require("@kubb/core");
26
+ let typescript = require("typescript");
27
+ typescript = __toESM(typescript);
28
+ //#region src/parserTs.ts
31
29
  const { factory } = typescript.default;
30
+ function slash(path) {
31
+ return (0, node_path.normalize)(path).replaceAll(/\\/g, "/").replace("../", "");
32
+ }
33
+ function getRelativePath(rootDir, filePath) {
34
+ const slashed = slash((0, node_path.relative)(rootDir, filePath));
35
+ return slashed.startsWith("../") ? slashed : `./${slashed}`;
36
+ }
37
+ function trimExtName(text) {
38
+ return text.replace(/\.[^/.]+$/, "");
39
+ }
32
40
  /**
33
- * Escaped new lines in code with block comments so they can be restored by {@link restoreNewLines}
34
- */
35
- const escapeNewLines = (code) => code.replace(/\n\n/g, "\n/* :newline: */");
36
- /**
37
- * Reverses {@link escapeNewLines} and restores new lines
41
+ * Validates TypeScript AST nodes before printing.
42
+ * Throws an error if any node has SyntaxKind.Unknown which would cause the
43
+ * TypeScript printer to crash.
38
44
  */
39
- const restoreNewLines = (code) => code.replace(/\/\* :newline: \*\//g, "\n");
45
+ function validateNodes(...nodes) {
46
+ for (const node of nodes) {
47
+ if (!node) throw new Error("Attempted to print undefined or null TypeScript node");
48
+ if (node.kind === typescript.default.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)}`);
49
+ }
50
+ }
40
51
  /**
41
- * Convert AST TypeScript/TSX nodes to a string based on the TypeScript printer.
42
- * Ensures consistent output across environments.
43
- * Also works as a formatter when `source` is provided without `elements`.
52
+ * Converts TypeScript/TSX AST nodes to a string using the TypeScript printer.
44
53
  */
45
- function print(elements = [], { source = "", baseName = "print.tsx", scriptKind = typescript.default.ScriptKind.TSX } = {}) {
46
- const sourceFile = typescript.default.createSourceFile(baseName, escapeNewLines(source), typescript.default.ScriptTarget.ES2022, true, scriptKind);
47
- const printer = typescript.default.createPrinter({
54
+ function print(...elements) {
55
+ const sourceFile = typescript.default.createSourceFile("print.tsx", "", typescript.default.ScriptTarget.ES2022, true, typescript.default.ScriptKind.TSX);
56
+ return typescript.default.createPrinter({
48
57
  omitTrailingSemicolon: true,
49
58
  newLine: typescript.default.NewLineKind.LineFeed,
50
59
  removeComments: false,
51
60
  noEmitHelpers: true
61
+ }).printList(typescript.default.ListFormat.MultiLine, factory.createNodeArray(elements.filter(Boolean)), sourceFile).replace(/\r\n/g, "\n");
62
+ }
63
+ /**
64
+ * Like `print` but validates nodes first to surface issues early.
65
+ */
66
+ function safePrint(...elements) {
67
+ validateNodes(...elements);
68
+ return print(...elements);
69
+ }
70
+ function createImport({ name, path, root, isTypeOnly = false, isNameSpace = false }) {
71
+ const resolvePath = root ? getRelativePath(root, path) : path;
72
+ if (!Array.isArray(name)) {
73
+ if (isNameSpace) return factory.createImportDeclaration(void 0, factory.createImportClause(isTypeOnly, void 0, factory.createNamespaceImport(factory.createIdentifier(name))), factory.createStringLiteral(resolvePath), void 0);
74
+ return factory.createImportDeclaration(void 0, factory.createImportClause(isTypeOnly, factory.createIdentifier(name), void 0), factory.createStringLiteral(resolvePath), void 0);
75
+ }
76
+ const specifiers = name.map((item) => {
77
+ if (typeof item === "object") {
78
+ const { propertyName, name: alias } = item;
79
+ return factory.createImportSpecifier(false, alias ? factory.createIdentifier(propertyName) : void 0, factory.createIdentifier(alias ?? propertyName));
80
+ }
81
+ return factory.createImportSpecifier(false, void 0, factory.createIdentifier(item));
52
82
  });
53
- let output;
54
- if (elements.length > 0) {
55
- const nodes = elements.filter(Boolean).sort((a, b) => (a.pos ?? 0) - (b.pos ?? 0));
56
- output = printer.printList(typescript.default.ListFormat.MultiLine, factory.createNodeArray(nodes), sourceFile);
57
- } else output = printer.printFile(sourceFile);
58
- return restoreNewLines(output).replace(/\r\n/g, "\n");
83
+ return factory.createImportDeclaration(void 0, factory.createImportClause(isTypeOnly, void 0, factory.createNamedImports(specifiers)), factory.createStringLiteral(resolvePath), void 0);
59
84
  }
60
-
85
+ function createExport({ path, asAlias, isTypeOnly = false, name }) {
86
+ if (name && !Array.isArray(name) && !asAlias) console.warn(`When using name as string, asAlias should be true: ${name}`);
87
+ if (!Array.isArray(name)) {
88
+ const parsedName = name?.match(/^\d/) ? `_${name?.slice(1)}` : name;
89
+ return factory.createExportDeclaration(void 0, isTypeOnly, asAlias && parsedName ? factory.createNamespaceExport(factory.createIdentifier(parsedName)) : void 0, factory.createStringLiteral(path), void 0);
90
+ }
91
+ 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);
92
+ }
93
+ /**
94
+ * Converts a {@link JSDocNode} to a JSDoc comment block string.
95
+ *
96
+ * @example
97
+ * ```ts
98
+ * printJSDoc({ comments: ['@description A pet', '@deprecated'] })
99
+ * // /**
100
+ * // * @description A pet
101
+ * // * @deprecated
102
+ * // *\/
103
+ * ```
104
+ */
105
+ function printJSDoc(jsDoc) {
106
+ const comments = (jsDoc.comments ?? []).filter((c) => c != null);
107
+ if (comments.length === 0) return "";
108
+ const lines = comments.flatMap((c) => c.split(/\r?\n/)).map((l) => l.replace(/\*\//g, "* /").replace(/\r/g, "")).filter((l) => l.trim().length > 0);
109
+ if (lines.length === 0) return "";
110
+ return [
111
+ "/**",
112
+ ...lines.map((l) => ` * ${l}`),
113
+ " */"
114
+ ].join("\n");
115
+ }
116
+ /**
117
+ * Serialises the body / value content from a `nodes` array.
118
+ *
119
+ * Each element is either a raw string or a structured {@link CodeNode}
120
+ * (recursively converted via {@link printCodeNode}).
121
+ * Elements are joined with `\n`.
122
+ */
123
+ function printNodes(nodes) {
124
+ if (!nodes || nodes.length === 0) return "";
125
+ return nodes.map((n) => typeof n === "string" ? n : printCodeNode(n)).join("\n");
126
+ }
127
+ /**
128
+ * Indents every non-empty line of `text` by `spaces` spaces.
129
+ */
130
+ function indentLines(text, spaces = 2) {
131
+ if (!text) return "";
132
+ const pad = " ".repeat(spaces);
133
+ return text.split("\n").map((line) => line.trim() ? `${pad}${line}` : "").join("\n");
134
+ }
135
+ /**
136
+ * Converts a {@link ConstNode} to a TypeScript `const` declaration string.
137
+ *
138
+ * Mirrors the `Const` component from `@kubb/react-fabric`.
139
+ *
140
+ * @example
141
+ * ```ts
142
+ * printConst(createConst({ name: 'pet', export: true, nodes: ['{}'] }))
143
+ * // 'export const pet = {}'
144
+ * ```
145
+ *
146
+ * @example With type and `as const`
147
+ * ```ts
148
+ * printConst(createConst({ name: 'pets', export: true, type: 'Pet[]', asConst: true, nodes: ['[]'] }))
149
+ * // 'export const pets: Pet[] = [] as const'
150
+ * ```
151
+ */
152
+ function printConst(node) {
153
+ const { name, export: canExport, type, JSDoc, asConst, nodes } = node;
154
+ const jsDocStr = JSDoc ? printJSDoc(JSDoc) : "";
155
+ const body = printNodes(nodes);
156
+ const parts = [];
157
+ if (canExport) parts.push("export ");
158
+ parts.push("const ");
159
+ parts.push(name);
160
+ if (type) parts.push(`: ${type}`);
161
+ parts.push(" = ");
162
+ parts.push(body);
163
+ if (asConst) parts.push(" as const");
164
+ return [jsDocStr, parts.join("")].filter(Boolean).join("\n");
165
+ }
166
+ /**
167
+ * Converts a {@link TypeNode} to a TypeScript `type` alias declaration string.
168
+ *
169
+ * Mirrors the `Type` component from `@kubb/react-fabric`.
170
+ *
171
+ * @example
172
+ * ```ts
173
+ * printType(createType({ name: 'Pet', export: true, nodes: ['{ id: number }'] }))
174
+ * // 'export type Pet = { id: number }'
175
+ * ```
176
+ */
177
+ function printType(node) {
178
+ const { name, export: canExport, JSDoc, nodes } = node;
179
+ const jsDocStr = JSDoc ? printJSDoc(JSDoc) : "";
180
+ const body = printNodes(nodes);
181
+ const parts = [];
182
+ if (canExport) parts.push("export ");
183
+ parts.push("type ");
184
+ parts.push(name);
185
+ parts.push(" = ");
186
+ parts.push(body);
187
+ return [jsDocStr, parts.join("")].filter(Boolean).join("\n");
188
+ }
189
+ /**
190
+ * Converts a {@link FunctionNode} to a TypeScript `function` declaration string.
191
+ *
192
+ * Mirrors the `Function` component from `@kubb/react-fabric`.
193
+ *
194
+ * @example
195
+ * ```ts
196
+ * printFunction(createFunction({ name: 'getPet', export: true, params: 'id: string', returnType: 'Pet', nodes: ['return fetch(id)'] }))
197
+ * // 'export function getPet(id: string): Pet {\n return fetch(id)\n}'
198
+ * ```
199
+ *
200
+ * @example Async with generics
201
+ * ```ts
202
+ * printFunction(createFunction({ name: 'fetchPet', export: true, async: true, generics: ['T'], params: 'id: string', returnType: 'T' }))
203
+ * // 'export async function fetchPet<T>(id: string): Promise<T> {\n}'
204
+ * ```
205
+ */
206
+ function printFunction(node) {
207
+ const { name, default: isDefault, export: canExport, async: isAsync, generics, params, returnType, JSDoc, nodes } = node;
208
+ const jsDocStr = JSDoc ? printJSDoc(JSDoc) : "";
209
+ const genericsStr = generics ? `<${Array.isArray(generics) ? generics.join(", ") : generics}>` : "";
210
+ const returnTypeStr = returnType ? isAsync ? `: Promise<${returnType}>` : `: ${returnType}` : "";
211
+ const body = printNodes(nodes);
212
+ const indented = body ? indentLines(body) : "";
213
+ const parts = [];
214
+ if (canExport) parts.push("export ");
215
+ if (isDefault) parts.push("default ");
216
+ if (isAsync) parts.push("async ");
217
+ parts.push("function ");
218
+ parts.push(name);
219
+ parts.push(genericsStr);
220
+ parts.push(`(${params ?? ""})`);
221
+ parts.push(returnTypeStr);
222
+ parts.push(" {");
223
+ if (indented) parts.push(`\n${indented}\n`);
224
+ parts.push("}");
225
+ return [jsDocStr, parts.join("")].filter(Boolean).join("\n");
226
+ }
227
+ /**
228
+ * Converts an {@link ArrowFunctionNode} to a TypeScript arrow function declaration string.
229
+ *
230
+ * Mirrors the `Function.Arrow` component from `@kubb/react-fabric`.
231
+ *
232
+ * @example Multi-line arrow function
233
+ * ```ts
234
+ * printArrowFunction(createArrowFunction({ name: 'getPet', export: true, params: 'id: string', nodes: ['return fetch(id)'] }))
235
+ * // 'export const getPet = (id: string) => {\n return fetch(id)\n}'
236
+ * ```
237
+ *
238
+ * @example Single-line arrow function
239
+ * ```ts
240
+ * printArrowFunction(createArrowFunction({ name: 'double', params: 'n: number', singleLine: true, nodes: ['n * 2'] }))
241
+ * // 'const double = (n: number) => n * 2'
242
+ * ```
243
+ */
244
+ function printArrowFunction(node) {
245
+ const { name, default: isDefault, export: canExport, async: isAsync, generics, params, returnType, JSDoc, nodes, singleLine } = node;
246
+ const jsDocStr = JSDoc ? printJSDoc(JSDoc) : "";
247
+ const genericsStr = generics ? `<${Array.isArray(generics) ? generics.join(", ") : generics}>` : "";
248
+ const returnTypeStr = returnType ? isAsync ? `: Promise<${returnType}>` : `: ${returnType}` : "";
249
+ const body = printNodes(nodes);
250
+ const arrowBody = singleLine ? ` => ${body}` : body ? ` => {\n${indentLines(body)}\n}` : " => {}";
251
+ const parts = [];
252
+ if (canExport) parts.push("export ");
253
+ if (isDefault) parts.push("default ");
254
+ parts.push("const ");
255
+ parts.push(name);
256
+ parts.push(" = ");
257
+ if (isAsync) parts.push("async ");
258
+ parts.push(genericsStr);
259
+ parts.push(`(${params ?? ""})`);
260
+ parts.push(returnTypeStr);
261
+ parts.push(arrowBody);
262
+ return [jsDocStr, parts.join("")].filter(Boolean).join("\n");
263
+ }
264
+ /**
265
+ * Converts a {@link CodeNode} to its TypeScript string representation.
266
+ *
267
+ * Dispatches to the appropriate printer based on the node's `kind`.
268
+ *
269
+ * @example
270
+ * ```ts
271
+ * printCodeNode(createConst({ name: 'x', nodes: ['1'] }))
272
+ * // 'const x = 1'
273
+ * ```
274
+ */
275
+ function printCodeNode(node) {
276
+ switch (node.kind) {
277
+ case "Const": return printConst(node);
278
+ case "Type": return printType(node);
279
+ case "Function": return printFunction(node);
280
+ case "ArrowFunction": return printArrowFunction(node);
281
+ }
282
+ }
283
+ /**
284
+ * Converts a {@link SourceNode} to its TypeScript string representation.
285
+ *
286
+ * Uses `value` if present; otherwise converts the structured `nodes` array
287
+ * via {@link printCodeNode}.
288
+ *
289
+ * @example From value
290
+ * ```ts
291
+ * printSource({ kind: 'Source', value: 'const x = 1' })
292
+ * // 'const x = 1'
293
+ * ```
294
+ *
295
+ * @example From nodes
296
+ * ```ts
297
+ * printSource({ kind: 'Source', nodes: [createConst({ name: 'x', nodes: ['1'] })] })
298
+ * // 'const x = 1'
299
+ * ```
300
+ */
301
+ function printSource(node) {
302
+ if (node.value) return node.value;
303
+ if (node.nodes && node.nodes.length > 0) return node.nodes.map(printCodeNode).join("\n");
304
+ return "";
305
+ }
306
+ /**
307
+ * Parser that converts `.ts` and `.js` files to strings using the TypeScript
308
+ * compiler. Handles import/export statement generation from file metadata.
309
+ *
310
+ * @default Used automatically when no `parsers` option is set in `defineConfig`.
311
+ */
312
+ const parserTs = (0, _kubb_core.defineParser)({
313
+ name: "typescript",
314
+ extNames: [".ts", ".js"],
315
+ async parse(file, options = { extname: ".ts" }) {
316
+ const sourceParts = [];
317
+ for (const item of file.sources) {
318
+ const sourceStr = printSource(item);
319
+ if (sourceStr) sourceParts.push(sourceStr);
320
+ }
321
+ const source = sourceParts.join("\n\n");
322
+ const importNodes = [];
323
+ for (const item of file.imports) {
324
+ const importPath = item.root ? getRelativePath(item.root, item.path) : item.path;
325
+ const hasExtname = !!/\.[^/.]+$/.exec(importPath);
326
+ importNodes.push(createImport({
327
+ name: item.name,
328
+ path: options?.extname && hasExtname ? `${trimExtName(importPath)}${options.extname}` : item.root ? trimExtName(importPath) : importPath,
329
+ isTypeOnly: item.isTypeOnly,
330
+ isNameSpace: item.isNameSpace
331
+ }));
332
+ }
333
+ const exportNodes = [];
334
+ for (const item of file.exports) {
335
+ const exportPath = item.path;
336
+ const hasExtname = !!/\.[^/.]+$/.exec(exportPath);
337
+ exportNodes.push(createExport({
338
+ name: item.name,
339
+ path: options?.extname && hasExtname ? `${trimExtName(item.path)}${options.extname}` : trimExtName(item.path),
340
+ isTypeOnly: item.isTypeOnly,
341
+ asAlias: item.asAlias
342
+ }));
343
+ }
344
+ return [
345
+ file.banner,
346
+ print(...importNodes, ...exportNodes),
347
+ source,
348
+ file.footer
349
+ ].filter((segment) => segment != null).join("\n");
350
+ }
351
+ });
61
352
  //#endregion
62
- Object.defineProperty(exports, 'factory', {
63
- enumerable: true,
64
- get: function () {
65
- return require_factory.factory_exports;
66
- }
353
+ //#region src/parserTsx.ts
354
+ /**
355
+ * Parser that converts `.tsx` and `.jsx` files to strings.
356
+ * Delegates to `typescriptParser` since the TypeScript compiler natively
357
+ * supports JSX/TSX syntax via `ScriptKind.TSX`.
358
+ *
359
+ * Add this parser to the `parsers` option in `defineConfig` when generating `.tsx`/`.jsx` files.
360
+ *
361
+ * @default extname '.tsx'
362
+ */
363
+ const parserTsx = (0, _kubb_core.defineParser)({
364
+ name: "tsx",
365
+ extNames: [".tsx", ".jsx"],
366
+ async parse(file, options = { extname: ".tsx" }) {
367
+ return parserTs.parse(file, options);
368
+ }
67
369
  });
68
- exports.format = format;
370
+ //#endregion
371
+ exports.createExport = createExport;
372
+ exports.createImport = createImport;
373
+ exports.parserTs = parserTs;
374
+ exports.parserTsx = parserTsx;
69
375
  exports.print = print;
376
+ exports.safePrint = safePrint;
377
+ exports.validateNodes = validateNodes;
378
+
70
379
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["formatOptions: Options","pluginTypescript","ts","output: string"],"sources":["../src/format.ts","../src/print.ts"],"sourcesContent":["import type { Options } from 'prettier'\nimport { format as prettierFormat } from 'prettier'\nimport pluginTypescript from 'prettier/plugins/typescript'\n\nconst formatOptions: Options = {\n tabWidth: 2,\n printWidth: 160,\n parser: 'typescript',\n singleQuote: true,\n semi: false,\n bracketSameLine: false,\n endOfLine: 'auto',\n plugins: [pluginTypescript],\n}\nexport function format(source?: string): Promise<string> {\n if (!source) {\n return Promise.resolve('')\n }\n\n try {\n return prettierFormat(source, formatOptions)\n } catch (_e) {\n return Promise.resolve(source)\n }\n}\n","import ts from 'typescript'\n\nconst { factory } = ts\n\nexport type PrintOptions = {\n source?: string\n baseName?: string\n scriptKind?: ts.ScriptKind\n}\n\n/**\n * Escaped new lines in code with block comments so they can be restored by {@link restoreNewLines}\n */\nconst escapeNewLines = (code: string) => code.replace(/\\n\\n/g, '\\n/* :newline: */')\n\n/**\n * Reverses {@link escapeNewLines} and restores new lines\n */\nconst restoreNewLines = (code: string) => code.replace(/\\/\\* :newline: \\*\\//g, '\\n')\n\n/**\n * Convert AST TypeScript/TSX nodes to a string based on the TypeScript printer.\n * Ensures consistent output across environments.\n * Also works as a formatter when `source` is provided without `elements`.\n */\nexport function print(elements: Array<ts.Node> = [], { source = '', baseName = 'print.tsx', scriptKind = ts.ScriptKind.TSX }: PrintOptions = {}): string {\n const sourceFile = ts.createSourceFile(baseName, escapeNewLines(source), ts.ScriptTarget.ES2022, true, scriptKind)\n\n const printer = ts.createPrinter({\n omitTrailingSemicolon: true,\n newLine: ts.NewLineKind.LineFeed,\n removeComments: false,\n noEmitHelpers: true,\n })\n\n let output: string\n\n if (elements.length > 0) {\n // Print only provided nodes\n const nodes = elements.filter(Boolean).sort((a, b) => (a.pos ?? 0) - (b.pos ?? 0))\n output = printer.printList(ts.ListFormat.MultiLine, factory.createNodeArray(nodes), sourceFile)\n } else {\n // Format the whole file\n output = printer.printFile(sourceFile)\n }\n\n return restoreNewLines(output).replace(/\\r\\n/g, '\\n')\n}\n"],"mappings":";;;;;;;;;AAIA,MAAMA,gBAAyB;CAC7B,UAAU;CACV,YAAY;CACZ,QAAQ;CACR,aAAa;CACb,MAAM;CACN,iBAAiB;CACjB,WAAW;CACX,SAAS,CAACC,oCAAiB;CAC5B;AACD,SAAgB,OAAO,QAAkC;AACvD,KAAI,CAAC,OACH,QAAO,QAAQ,QAAQ,GAAG;AAG5B,KAAI;AACF,8BAAsB,QAAQ,cAAc;UACrC,IAAI;AACX,SAAO,QAAQ,QAAQ,OAAO;;;;;;ACpBlC,MAAM,EAAE,YAAYC;;;;AAWpB,MAAM,kBAAkB,SAAiB,KAAK,QAAQ,SAAS,oBAAoB;;;;AAKnF,MAAM,mBAAmB,SAAiB,KAAK,QAAQ,wBAAwB,KAAK;;;;;;AAOpF,SAAgB,MAAM,WAA2B,EAAE,EAAE,EAAE,SAAS,IAAI,WAAW,aAAa,aAAaA,mBAAG,WAAW,QAAsB,EAAE,EAAU;CACvJ,MAAM,aAAaA,mBAAG,iBAAiB,UAAU,eAAe,OAAO,EAAEA,mBAAG,aAAa,QAAQ,MAAM,WAAW;CAElH,MAAM,UAAUA,mBAAG,cAAc;EAC/B,uBAAuB;EACvB,SAASA,mBAAG,YAAY;EACxB,gBAAgB;EAChB,eAAe;EAChB,CAAC;CAEF,IAAIC;AAEJ,KAAI,SAAS,SAAS,GAAG;EAEvB,MAAM,QAAQ,SAAS,OAAO,QAAQ,CAAC,MAAM,GAAG,OAAO,EAAE,OAAO,MAAM,EAAE,OAAO,GAAG;AAClF,WAAS,QAAQ,UAAUD,mBAAG,WAAW,WAAW,QAAQ,gBAAgB,MAAM,EAAE,WAAW;OAG/F,UAAS,QAAQ,UAAU,WAAW;AAGxC,QAAO,gBAAgB,OAAO,CAAC,QAAQ,SAAS,KAAK"}
1
+ {"version":3,"file":"index.cjs","names":["ts"],"sources":["../src/parserTs.ts","../src/parserTsx.ts"],"sourcesContent":["import { normalize, relative } from 'node:path'\nimport type { ArrowFunctionNode, CodeNode, ConstNode, FileNode, FunctionNode, JSDocNode, SourceNode, TypeNode } from '@kubb/ast/types'\nimport type { Parser } from '@kubb/core'\nimport { defineParser } from '@kubb/core'\nimport ts from 'typescript'\n\nconst { factory } = ts\n\nfunction slash(path: string): string {\n return normalize(path).replaceAll(/\\\\/g, '/').replace('../', '')\n}\n\nfunction getRelativePath(rootDir: string, filePath: string): string {\n const rel = relative(rootDir, filePath)\n const slashed = slash(rel)\n return slashed.startsWith('../') ? slashed : `./${slashed}`\n}\n\nfunction trimExtName(text: string): string {\n return text.replace(/\\.[^/.]+$/, '')\n}\n\n/**\n * Validates TypeScript AST nodes before printing.\n * Throws an error if any node has SyntaxKind.Unknown which would cause the\n * TypeScript printer to crash.\n */\nexport function validateNodes(...nodes: ts.Node[]): void {\n for (const node of nodes) {\n if (!node) {\n throw new Error('Attempted to print undefined or null TypeScript node')\n }\n if (node.kind === ts.SyntaxKind.Unknown) {\n throw new Error(\n 'Invalid TypeScript AST node detected with SyntaxKind.Unknown. ' +\n 'This typically indicates a schema pattern that could not be properly converted to TypeScript. ' +\n `Node: ${JSON.stringify(node, null, 2)}`,\n )\n }\n }\n}\n\n/**\n * Converts TypeScript/TSX AST nodes to a string using the TypeScript printer.\n */\nexport function print(...elements: Array<ts.Node>): string {\n const sourceFile = ts.createSourceFile('print.tsx', '', ts.ScriptTarget.ES2022, true, ts.ScriptKind.TSX)\n\n const printer = ts.createPrinter({\n omitTrailingSemicolon: true,\n newLine: ts.NewLineKind.LineFeed,\n removeComments: false,\n noEmitHelpers: true,\n })\n\n const output = printer.printList(ts.ListFormat.MultiLine, factory.createNodeArray(elements.filter(Boolean)), sourceFile)\n\n return output.replace(/\\r\\n/g, '\\n')\n}\n\n/**\n * Like `print` but validates nodes first to surface issues early.\n */\nexport function safePrint(...elements: Array<ts.Node>): string {\n validateNodes(...elements)\n return print(...elements)\n}\n\nexport function createImport({\n name,\n path,\n root,\n isTypeOnly = false,\n isNameSpace = false,\n}: {\n name: string | Array<string | { propertyName: string; name?: string }>\n path: string\n root?: string\n /** @default false */\n isTypeOnly?: boolean\n /** @default false */\n isNameSpace?: boolean\n}): ts.ImportDeclaration {\n const resolvePath = root ? getRelativePath(root, path) : path\n\n if (!Array.isArray(name)) {\n if (isNameSpace) {\n return factory.createImportDeclaration(\n undefined,\n factory.createImportClause(isTypeOnly, undefined, factory.createNamespaceImport(factory.createIdentifier(name))),\n factory.createStringLiteral(resolvePath),\n undefined,\n )\n }\n\n return factory.createImportDeclaration(\n undefined,\n factory.createImportClause(isTypeOnly, factory.createIdentifier(name), undefined),\n factory.createStringLiteral(resolvePath),\n undefined,\n )\n }\n\n const specifiers = name.map((item) => {\n if (typeof item === 'object') {\n const { propertyName, name: alias } = item\n return factory.createImportSpecifier(false, alias ? factory.createIdentifier(propertyName) : undefined, factory.createIdentifier(alias ?? propertyName))\n }\n return factory.createImportSpecifier(false, undefined, factory.createIdentifier(item))\n })\n\n return factory.createImportDeclaration(\n undefined,\n factory.createImportClause(isTypeOnly, undefined, factory.createNamedImports(specifiers)),\n factory.createStringLiteral(resolvePath),\n undefined,\n )\n}\n\nexport function createExport({\n path,\n asAlias,\n isTypeOnly = false,\n name,\n}: {\n path: string\n /** @default false */\n asAlias?: boolean\n /** @default false */\n isTypeOnly?: boolean\n name?: string | Array<ts.Identifier | string>\n}): ts.ExportDeclaration {\n if (name && !Array.isArray(name) && !asAlias) {\n console.warn(`When using name as string, asAlias should be true: ${name}`)\n }\n\n if (!Array.isArray(name)) {\n const parsedName = name?.match(/^\\d/) ? `_${name?.slice(1)}` : name\n\n return factory.createExportDeclaration(\n undefined,\n isTypeOnly,\n asAlias && parsedName ? factory.createNamespaceExport(factory.createIdentifier(parsedName)) : undefined,\n factory.createStringLiteral(path),\n undefined,\n )\n }\n\n return factory.createExportDeclaration(\n undefined,\n isTypeOnly,\n factory.createNamedExports(\n name.map((propertyName) =>\n factory.createExportSpecifier(false, undefined, typeof propertyName === 'string' ? factory.createIdentifier(propertyName) : propertyName),\n ),\n ),\n factory.createStringLiteral(path),\n undefined,\n )\n}\n\n/**\n * Converts a {@link JSDocNode} to a JSDoc comment block string.\n *\n * @example\n * ```ts\n * printJSDoc({ comments: ['@description A pet', '@deprecated'] })\n * // /**\n * // * @description A pet\n * // * @deprecated\n * // *\\/\n * ```\n */\nexport function printJSDoc(jsDoc: JSDocNode): string {\n const comments = (jsDoc.comments ?? []).filter((c) => c != null)\n if (comments.length === 0) return ''\n\n const lines = comments\n .flatMap((c) => c.split(/\\r?\\n/))\n .map((l) => l.replace(/\\*\\//g, '* /').replace(/\\r/g, ''))\n .filter((l) => l.trim().length > 0)\n\n if (lines.length === 0) return ''\n\n return ['/**', ...lines.map((l) => ` * ${l}`), ' */'].join('\\n')\n}\n\n/**\n * Serialises the body / value content from a `nodes` array.\n *\n * Each element is either a raw string or a structured {@link CodeNode}\n * (recursively converted via {@link printCodeNode}).\n * Elements are joined with `\\n`.\n */\nfunction printNodes(nodes: Array<CodeNode | string> | undefined): string {\n if (!nodes || nodes.length === 0) return ''\n return nodes.map((n) => (typeof n === 'string' ? n : printCodeNode(n))).join('\\n')\n}\n\n/**\n * Indents every non-empty line of `text` by `spaces` spaces.\n */\nfunction indentLines(text: string, spaces = 2): string {\n if (!text) return ''\n const pad = ' '.repeat(spaces)\n return text\n .split('\\n')\n .map((line) => (line.trim() ? `${pad}${line}` : ''))\n .join('\\n')\n}\n\n/**\n * Converts a {@link ConstNode} to a TypeScript `const` declaration string.\n *\n * Mirrors the `Const` component from `@kubb/react-fabric`.\n *\n * @example\n * ```ts\n * printConst(createConst({ name: 'pet', export: true, nodes: ['{}'] }))\n * // 'export const pet = {}'\n * ```\n *\n * @example With type and `as const`\n * ```ts\n * printConst(createConst({ name: 'pets', export: true, type: 'Pet[]', asConst: true, nodes: ['[]'] }))\n * // 'export const pets: Pet[] = [] as const'\n * ```\n */\nexport function printConst(node: ConstNode): string {\n const { name, export: canExport, type, JSDoc, asConst, nodes } = node\n\n const jsDocStr = JSDoc ? printJSDoc(JSDoc) : ''\n const body = printNodes(nodes)\n\n const parts: string[] = []\n if (canExport) parts.push('export ')\n parts.push('const ')\n parts.push(name)\n if (type) {\n parts.push(`: ${type}`)\n }\n parts.push(' = ')\n parts.push(body)\n if (asConst) parts.push(' as const')\n\n const declaration = parts.join('')\n return [jsDocStr, declaration].filter(Boolean).join('\\n')\n}\n\n/**\n * Converts a {@link TypeNode} to a TypeScript `type` alias declaration string.\n *\n * Mirrors the `Type` component from `@kubb/react-fabric`.\n *\n * @example\n * ```ts\n * printType(createType({ name: 'Pet', export: true, nodes: ['{ id: number }'] }))\n * // 'export type Pet = { id: number }'\n * ```\n */\nexport function printType(node: TypeNode): string {\n const { name, export: canExport, JSDoc, nodes } = node\n\n const jsDocStr = JSDoc ? printJSDoc(JSDoc) : ''\n const body = printNodes(nodes)\n\n const parts: string[] = []\n if (canExport) parts.push('export ')\n parts.push('type ')\n parts.push(name)\n parts.push(' = ')\n parts.push(body)\n\n const declaration = parts.join('')\n return [jsDocStr, declaration].filter(Boolean).join('\\n')\n}\n\n/**\n * Converts a {@link FunctionNode} to a TypeScript `function` declaration string.\n *\n * Mirrors the `Function` component from `@kubb/react-fabric`.\n *\n * @example\n * ```ts\n * printFunction(createFunction({ name: 'getPet', export: true, params: 'id: string', returnType: 'Pet', nodes: ['return fetch(id)'] }))\n * // 'export function getPet(id: string): Pet {\\n return fetch(id)\\n}'\n * ```\n *\n * @example Async with generics\n * ```ts\n * printFunction(createFunction({ name: 'fetchPet', export: true, async: true, generics: ['T'], params: 'id: string', returnType: 'T' }))\n * // 'export async function fetchPet<T>(id: string): Promise<T> {\\n}'\n * ```\n */\nexport function printFunction(node: FunctionNode): string {\n const { name, default: isDefault, export: canExport, async: isAsync, generics, params, returnType, JSDoc, nodes } = node\n\n const jsDocStr = JSDoc ? printJSDoc(JSDoc) : ''\n\n const genericsStr = generics ? `<${Array.isArray(generics) ? generics.join(', ') : generics}>` : ''\n\n const returnTypeStr = returnType ? (isAsync ? `: Promise<${returnType}>` : `: ${returnType}`) : ''\n\n const body = printNodes(nodes)\n const indented = body ? indentLines(body) : ''\n\n const parts: string[] = []\n if (canExport) parts.push('export ')\n if (isDefault) parts.push('default ')\n if (isAsync) parts.push('async ')\n parts.push('function ')\n parts.push(name)\n parts.push(genericsStr)\n parts.push(`(${params ?? ''})`)\n parts.push(returnTypeStr)\n parts.push(' {')\n if (indented) {\n parts.push(`\\n${indented}\\n`)\n }\n parts.push('}')\n\n const declaration = parts.join('')\n return [jsDocStr, declaration].filter(Boolean).join('\\n')\n}\n\n/**\n * Converts an {@link ArrowFunctionNode} to a TypeScript arrow function declaration string.\n *\n * Mirrors the `Function.Arrow` component from `@kubb/react-fabric`.\n *\n * @example Multi-line arrow function\n * ```ts\n * printArrowFunction(createArrowFunction({ name: 'getPet', export: true, params: 'id: string', nodes: ['return fetch(id)'] }))\n * // 'export const getPet = (id: string) => {\\n return fetch(id)\\n}'\n * ```\n *\n * @example Single-line arrow function\n * ```ts\n * printArrowFunction(createArrowFunction({ name: 'double', params: 'n: number', singleLine: true, nodes: ['n * 2'] }))\n * // 'const double = (n: number) => n * 2'\n * ```\n */\nexport function printArrowFunction(node: ArrowFunctionNode): string {\n const { name, default: isDefault, export: canExport, async: isAsync, generics, params, returnType, JSDoc, nodes, singleLine } = node\n\n const jsDocStr = JSDoc ? printJSDoc(JSDoc) : ''\n\n const genericsStr = generics ? `<${Array.isArray(generics) ? generics.join(', ') : generics}>` : ''\n\n const returnTypeStr = returnType ? (isAsync ? `: Promise<${returnType}>` : `: ${returnType}`) : ''\n\n const body = printNodes(nodes)\n\n const arrowBody = singleLine ? ` => ${body}` : body ? ` => {\\n${indentLines(body)}\\n}` : ' => {}'\n\n const parts: string[] = []\n if (canExport) parts.push('export ')\n if (isDefault) parts.push('default ')\n parts.push('const ')\n parts.push(name)\n parts.push(' = ')\n if (isAsync) parts.push('async ')\n parts.push(genericsStr)\n parts.push(`(${params ?? ''})`)\n parts.push(returnTypeStr)\n parts.push(arrowBody)\n\n const declaration = parts.join('')\n return [jsDocStr, declaration].filter(Boolean).join('\\n')\n}\n\n/**\n * Converts a {@link CodeNode} to its TypeScript string representation.\n *\n * Dispatches to the appropriate printer based on the node's `kind`.\n *\n * @example\n * ```ts\n * printCodeNode(createConst({ name: 'x', nodes: ['1'] }))\n * // 'const x = 1'\n * ```\n */\nexport function printCodeNode(node: CodeNode): string {\n switch (node.kind) {\n case 'Const':\n return printConst(node)\n case 'Type':\n return printType(node)\n case 'Function':\n return printFunction(node)\n case 'ArrowFunction':\n return printArrowFunction(node)\n }\n}\n\n/**\n * Converts a {@link SourceNode} to its TypeScript string representation.\n *\n * Uses `value` if present; otherwise converts the structured `nodes` array\n * via {@link printCodeNode}.\n *\n * @example From value\n * ```ts\n * printSource({ kind: 'Source', value: 'const x = 1' })\n * // 'const x = 1'\n * ```\n *\n * @example From nodes\n * ```ts\n * printSource({ kind: 'Source', nodes: [createConst({ name: 'x', nodes: ['1'] })] })\n * // 'const x = 1'\n * ```\n */\nexport function printSource(node: SourceNode): string {\n if (node.value) return node.value\n if (node.nodes && node.nodes.length > 0) {\n return node.nodes.map(printCodeNode).join('\\n')\n }\n return ''\n}\n\n/**\n * Parser that converts `.ts` and `.js` files to strings using the TypeScript\n * compiler. Handles import/export statement generation from file metadata.\n *\n * @default Used automatically when no `parsers` option is set in `defineConfig`.\n */\nexport const parserTs: Parser = defineParser({\n name: 'typescript',\n extNames: ['.ts', '.js'],\n async parse(file, options = { extname: '.ts' }) {\n const sourceParts: Array<string> = []\n for (const item of file.sources) {\n const sourceStr = printSource(item as SourceNode)\n if (sourceStr) {\n sourceParts.push(sourceStr)\n }\n }\n const source = sourceParts.join('\\n\\n')\n\n const importNodes: Array<ts.ImportDeclaration> = []\n for (const item of (file as FileNode).imports) {\n const importPath = item.root ? getRelativePath(item.root, item.path) : item.path\n const hasExtname = !!/\\.[^/.]+$/.exec(importPath)\n\n importNodes.push(\n createImport({\n name: item.name as string | Array<string | { propertyName: string; name?: string }>,\n path: options?.extname && hasExtname ? `${trimExtName(importPath)}${options.extname}` : item.root ? trimExtName(importPath) : importPath,\n isTypeOnly: item.isTypeOnly,\n isNameSpace: item.isNameSpace,\n }),\n )\n }\n\n const exportNodes: Array<ts.ExportDeclaration> = []\n for (const item of (file as FileNode).exports) {\n const exportPath = item.path\n const hasExtname = !!/\\.[^/.]+$/.exec(exportPath)\n\n exportNodes.push(\n createExport({\n name: item.name as string | Array<ts.Identifier | string> | undefined,\n path: options?.extname && hasExtname ? `${trimExtName(item.path)}${options.extname}` : trimExtName(item.path),\n isTypeOnly: item.isTypeOnly,\n asAlias: item.asAlias,\n }),\n )\n }\n\n const parts = [file.banner, print(...importNodes, ...exportNodes), source, file.footer].filter((segment): segment is string => segment != null)\n return parts.join('\\n')\n },\n})\n","import type { Parser } from '@kubb/core'\nimport { defineParser } from '@kubb/core'\nimport { parserTs } from './parserTs.ts'\n\n/**\n * Parser that converts `.tsx` and `.jsx` files to strings.\n * Delegates to `typescriptParser` since the TypeScript compiler natively\n * supports JSX/TSX syntax via `ScriptKind.TSX`.\n *\n * Add this parser to the `parsers` option in `defineConfig` when generating `.tsx`/`.jsx` files.\n *\n * @default extname '.tsx'\n */\nexport const parserTsx: Parser = defineParser({\n name: 'tsx',\n extNames: ['.tsx', '.jsx'],\n async parse(file, options = { extname: '.tsx' }) {\n return parserTs.parse(file, options)\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA,MAAM,EAAE,YAAYA,WAAAA;AAEpB,SAAS,MAAM,MAAsB;AACnC,SAAA,GAAA,UAAA,WAAiB,KAAK,CAAC,WAAW,OAAO,IAAI,CAAC,QAAQ,OAAO,GAAG;;AAGlE,SAAS,gBAAgB,SAAiB,UAA0B;CAElE,MAAM,UAAU,OAAA,GAAA,UAAA,UADK,SAAS,SAAS,CACb;AAC1B,QAAO,QAAQ,WAAW,MAAM,GAAG,UAAU,KAAK;;AAGpD,SAAS,YAAY,MAAsB;AACzC,QAAO,KAAK,QAAQ,aAAa,GAAG;;;;;;;AAQtC,SAAgB,cAAc,GAAG,OAAwB;AACvD,MAAK,MAAM,QAAQ,OAAO;AACxB,MAAI,CAAC,KACH,OAAM,IAAI,MAAM,uDAAuD;AAEzE,MAAI,KAAK,SAASA,WAAAA,QAAG,WAAW,QAC9B,OAAM,IAAI,MACR,qKAEW,KAAK,UAAU,MAAM,MAAM,EAAE,GACzC;;;;;;AAQP,SAAgB,MAAM,GAAG,UAA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./chunk--u3MIqq1.js";
2
+ import { Parser } from "@kubb/core";
2
3
  import ts from "typescript";
3
-
4
- //#region src/format.d.ts
5
- declare function format(source?: string): Promise<string>;
4
+ //#region src/parserTs.d.ts
5
+ /**
6
+ * Validates TypeScript AST nodes before printing.
7
+ * Throws an error if any node has SyntaxKind.Unknown which would cause the
8
+ * TypeScript printer to crash.
9
+ */
10
+ declare function validateNodes(...nodes: ts.Node[]): void;
11
+ /**
12
+ * Converts TypeScript/TSX AST nodes to a string using the TypeScript printer.
13
+ */
14
+ declare function print(...elements: Array<ts.Node>): string;
15
+ /**
16
+ * Like `print` but validates nodes first to surface issues early.
17
+ */
18
+ declare function safePrint(...elements: Array<ts.Node>): string;
19
+ declare function createImport({
20
+ name,
21
+ path,
22
+ root,
23
+ isTypeOnly,
24
+ isNameSpace
25
+ }: {
26
+ name: string | Array<string | {
27
+ propertyName: string;
28
+ name?: string;
29
+ }>;
30
+ path: string;
31
+ root?: string; /** @default false */
32
+ isTypeOnly?: boolean; /** @default false */
33
+ isNameSpace?: boolean;
34
+ }): ts.ImportDeclaration;
35
+ declare function createExport({
36
+ path,
37
+ asAlias,
38
+ isTypeOnly,
39
+ name
40
+ }: {
41
+ path: string; /** @default false */
42
+ asAlias?: boolean; /** @default false */
43
+ isTypeOnly?: boolean;
44
+ name?: string | Array<ts.Identifier | string>;
45
+ }): ts.ExportDeclaration;
46
+ /**
47
+ * Parser that converts `.ts` and `.js` files to strings using the TypeScript
48
+ * compiler. Handles import/export statement generation from file metadata.
49
+ *
50
+ * @default Used automatically when no `parsers` option is set in `defineConfig`.
51
+ */
52
+ declare const parserTs: Parser;
6
53
  //#endregion
7
- //#region src/print.d.ts
8
- type PrintOptions = {
9
- source?: string;
10
- baseName?: string;
11
- scriptKind?: ts.ScriptKind;
12
- };
54
+ //#region src/parserTsx.d.ts
13
55
  /**
14
- * Convert AST TypeScript/TSX nodes to a string based on the TypeScript printer.
15
- * Ensures consistent output across environments.
16
- * Also works as a formatter when `source` is provided without `elements`.
56
+ * Parser that converts `.tsx` and `.jsx` files to strings.
57
+ * Delegates to `typescriptParser` since the TypeScript compiler natively
58
+ * supports JSX/TSX syntax via `ScriptKind.TSX`.
59
+ *
60
+ * Add this parser to the `parsers` option in `defineConfig` when generating `.tsx`/`.jsx` files.
61
+ *
62
+ * @default extname '.tsx'
17
63
  */
18
- declare function print(elements?: Array<ts.Node>, {
19
- source,
20
- baseName,
21
- scriptKind
22
- }?: PrintOptions): string;
64
+ declare const parserTsx: Parser;
23
65
  //#endregion
24
- export { factory_d_exports as factory, format, print };
66
+ export { createExport, createImport, parserTs, parserTsx, print, safePrint, validateNodes };
25
67
  //# sourceMappingURL=index.d.ts.map