@kubb/parser-ts 5.0.0-beta.75 → 5.0.0-beta.8
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/README.md +112 -0
- package/dist/index.cjs +65 -60
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.js +65 -60
- package/dist/index.js.map +1 -1
- package/extension.yaml +100 -0
- package/package.json +5 -5
- package/src/parserTs.ts +5 -454
- package/src/utils.ts +459 -0
package/README.md
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
<div align="center">
|
|
2
|
+
<h1>@kubb/parser-ts</h1>
|
|
3
|
+
<a href="https://kubb.dev" target="_blank" rel="noopener noreferrer">
|
|
4
|
+
<img width="180" src="https://raw.githubusercontent.com/kubb-labs/kubb/main/assets/logo.png" alt="Kubb logo">
|
|
5
|
+
</a>
|
|
6
|
+
|
|
7
|
+
[![npm version][npm-version-src]][npm-version-href]
|
|
8
|
+
[![npm downloads][npm-downloads-src]][npm-downloads-href]
|
|
9
|
+
[![Coverage][coverage-src]][coverage-href]
|
|
10
|
+
[![License][license-src]][license-href]
|
|
11
|
+
[![Sponsors][sponsors-src]][sponsors-href]
|
|
12
|
+
|
|
13
|
+
<h4>
|
|
14
|
+
<a href="https://kubb.dev/" target="_blank">Documentation</a>
|
|
15
|
+
<span> · </span>
|
|
16
|
+
<a href="https://github.com/kubb-labs/kubb/issues/" target="_blank">Report Bug</a>
|
|
17
|
+
<span> · </span>
|
|
18
|
+
<a href="https://github.com/kubb-labs/kubb/issues/" target="_blank">Request Feature</a>
|
|
19
|
+
</h4>
|
|
20
|
+
</div>
|
|
21
|
+
|
|
22
|
+
TypeScript and TSX source file parser for Kubb. Converts AST nodes and raw TypeScript code into formatted source strings using the TypeScript compiler API.
|
|
23
|
+
|
|
24
|
+
## Installation
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
bun add @kubb/parser-ts
|
|
28
|
+
# or
|
|
29
|
+
pnpm add @kubb/parser-ts
|
|
30
|
+
# or
|
|
31
|
+
npm install @kubb/parser-ts
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Usage
|
|
35
|
+
|
|
36
|
+
```typescript
|
|
37
|
+
import { print, createImport, createExport } from '@kubb/parser-ts'
|
|
38
|
+
import ts from 'typescript'
|
|
39
|
+
|
|
40
|
+
// Print a TypeScript source file from compiler AST nodes
|
|
41
|
+
const source = print([
|
|
42
|
+
ts.factory.createVariableStatement(
|
|
43
|
+
[ts.factory.createModifier(ts.SyntaxKind.ExportKeyword)],
|
|
44
|
+
ts.factory.createVariableDeclarationList(
|
|
45
|
+
[ts.factory.createVariableDeclaration('hello', undefined, undefined, ts.factory.createStringLiteral('world'))],
|
|
46
|
+
ts.NodeFlags.Const,
|
|
47
|
+
),
|
|
48
|
+
),
|
|
49
|
+
])
|
|
50
|
+
// → export const hello = 'world'
|
|
51
|
+
|
|
52
|
+
// Create an import declaration
|
|
53
|
+
const importNode = createImport({ name: 'axios', path: 'axios' })
|
|
54
|
+
|
|
55
|
+
// Create an export declaration
|
|
56
|
+
const exportNode = createExport({ name: 'MyType', path: './types' })
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## API
|
|
60
|
+
|
|
61
|
+
### `print(nodes, options?)`
|
|
62
|
+
|
|
63
|
+
Converts an array of TypeScript compiler `Node` instances into a formatted source string. Returns the printed source code.
|
|
64
|
+
|
|
65
|
+
### `safePrint(nodes, options?)`
|
|
66
|
+
|
|
67
|
+
Same as `print` but catches formatting errors and returns the unformatted output as a fallback.
|
|
68
|
+
|
|
69
|
+
### `parserTs`
|
|
70
|
+
|
|
71
|
+
Parser instance for `.ts` files. Use with Kubb's file system to emit TypeScript source files.
|
|
72
|
+
|
|
73
|
+
### `parserTsx`
|
|
74
|
+
|
|
75
|
+
Parser instance for `.tsx` files. Use with Kubb's file system to emit TSX source files.
|
|
76
|
+
|
|
77
|
+
### `createImport(options)`
|
|
78
|
+
|
|
79
|
+
Factory helper that creates a TypeScript `ImportDeclaration` node.
|
|
80
|
+
|
|
81
|
+
### `createExport(options)`
|
|
82
|
+
|
|
83
|
+
Factory helper that creates a TypeScript `ExportDeclaration` node.
|
|
84
|
+
|
|
85
|
+
### `validateNodes(nodes)`
|
|
86
|
+
|
|
87
|
+
Validates an array of TypeScript AST nodes for correctness before printing.
|
|
88
|
+
|
|
89
|
+
## Supporting Kubb
|
|
90
|
+
|
|
91
|
+
Kubb is an open source project with its ongoing development made possible entirely by the support of Sponsors. If you would like to become a sponsor, please consider:
|
|
92
|
+
|
|
93
|
+
- [Become a Sponsor on GitHub](https://github.com/sponsors/stijnvanhulle)
|
|
94
|
+
|
|
95
|
+
<p align="center">
|
|
96
|
+
<a href="https://github.com/sponsors/stijnvanhulle">
|
|
97
|
+
<img src="https://raw.githubusercontent.com/stijnvanhulle/sponsors/main/sponsors.svg" alt="My sponsors" />
|
|
98
|
+
</a>
|
|
99
|
+
</p>
|
|
100
|
+
|
|
101
|
+
<!-- Badges -->
|
|
102
|
+
|
|
103
|
+
[npm-version-src]: https://img.shields.io/npm/v/@kubb/parser-ts?flat&colorA=18181B&colorB=f58517
|
|
104
|
+
[npm-version-href]: https://npmjs.com/package/@kubb/parser-ts
|
|
105
|
+
[npm-downloads-src]: https://img.shields.io/npm/dm/@kubb/parser-ts?flat&colorA=18181B&colorB=f58517
|
|
106
|
+
[npm-downloads-href]: https://npmjs.com/package/@kubb/parser-ts
|
|
107
|
+
[license-src]: https://img.shields.io/github/license/kubb-labs/kubb.svg?flat&colorA=18181B&colorB=f58517
|
|
108
|
+
[license-href]: https://github.com/kubb-labs/kubb/blob/main/LICENSE
|
|
109
|
+
[coverage-src]: https://img.shields.io/codecov/c/github/kubb-labs/kubb?style=flat&colorA=18181B&colorB=f58517
|
|
110
|
+
[coverage-href]: https://www.npmjs.com/package/@kubb/parser-ts
|
|
111
|
+
[sponsors-src]: https://img.shields.io/github/sponsors/stijnvanhulle?style=flat&colorA=18181B&colorB=f58517
|
|
112
|
+
[sponsors-href]: https://github.com/sponsors/stijnvanhulle/
|
package/dist/index.cjs
CHANGED
|
@@ -21,8 +21,8 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
21
21
|
enumerable: true
|
|
22
22
|
}) : target, mod));
|
|
23
23
|
//#endregion
|
|
24
|
-
let node_path = require("node:path");
|
|
25
24
|
let _kubb_core = require("@kubb/core");
|
|
25
|
+
let node_path = require("node:path");
|
|
26
26
|
let typescript = require("typescript");
|
|
27
27
|
typescript = __toESM(typescript, 1);
|
|
28
28
|
//#region src/constants.ts
|
|
@@ -54,8 +54,11 @@ const CRLF_PATTERN = /\r\n/g;
|
|
|
54
54
|
*/
|
|
55
55
|
const LEADING_DIGIT_PATTERN = /^\d/;
|
|
56
56
|
//#endregion
|
|
57
|
-
//#region src/
|
|
57
|
+
//#region src/utils.ts
|
|
58
58
|
const { factory } = typescript.default;
|
|
59
|
+
/**
|
|
60
|
+
* Normalises a file-system path to POSIX separators and strips any leading `../` segment.
|
|
61
|
+
*/
|
|
59
62
|
function slash(path) {
|
|
60
63
|
return (0, node_path.normalize)(path).replaceAll(WINDOWS_PATH_SEPARATOR, "/").replace("../", "");
|
|
61
64
|
}
|
|
@@ -85,6 +88,41 @@ function resolveOutputPath(path, options, rootAware) {
|
|
|
85
88
|
return rootAware ? trimExtName(path) : path;
|
|
86
89
|
}
|
|
87
90
|
/**
|
|
91
|
+
* Serializes the body / value content from a `nodes` array.
|
|
92
|
+
*
|
|
93
|
+
* Each element is either a raw string or a structured {@link CodeNode}
|
|
94
|
+
* (recursively converted via {@link printCodeNode}).
|
|
95
|
+
* Elements are joined with `\n`.
|
|
96
|
+
*/
|
|
97
|
+
function printNodes(nodes) {
|
|
98
|
+
if (!nodes || nodes.length === 0) return "";
|
|
99
|
+
return nodes.map(printCodeNode).join("\n");
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Indents every non-empty line of `text` by `spaces` spaces.
|
|
103
|
+
*/
|
|
104
|
+
function indentLines(text, spaces = 2) {
|
|
105
|
+
if (!text) return "";
|
|
106
|
+
const pad = " ".repeat(spaces);
|
|
107
|
+
return text.split("\n").map((line) => line.trim() ? `${pad}${line}` : "").join("\n");
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Renders the generic clause (`<T, U>`) shared by function and arrow-function nodes.
|
|
111
|
+
* Accepts either a raw string (rendered verbatim) or an array of type-parameter names.
|
|
112
|
+
*/
|
|
113
|
+
function formatGenerics(generics) {
|
|
114
|
+
if (!generics) return "";
|
|
115
|
+
return `<${Array.isArray(generics) ? generics.join(", ") : generics}>`;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Renders the return-type suffix (`: T` or `: Promise<T>` when `isAsync` is true).
|
|
119
|
+
* Returns an empty string when no return type is provided.
|
|
120
|
+
*/
|
|
121
|
+
function formatReturnType(returnType, isAsync) {
|
|
122
|
+
if (!returnType) return "";
|
|
123
|
+
return isAsync ? `: Promise<${returnType}>` : `: ${returnType}`;
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
88
126
|
* Validates TypeScript AST nodes before printing.
|
|
89
127
|
* Throws an error if any node has SyntaxKind.Unknown which would cause the
|
|
90
128
|
* TypeScript printer to crash.
|
|
@@ -114,29 +152,6 @@ function safePrint(...elements) {
|
|
|
114
152
|
validateNodes(...elements);
|
|
115
153
|
return print(...elements);
|
|
116
154
|
}
|
|
117
|
-
function createImport({ name, path, root, isTypeOnly = false, isNameSpace = false }) {
|
|
118
|
-
const resolvePath = root ? getRelativePath(root, path) : path;
|
|
119
|
-
if (!Array.isArray(name)) {
|
|
120
|
-
if (isNameSpace) return factory.createImportDeclaration(void 0, factory.createImportClause(isTypeOnly, void 0, factory.createNamespaceImport(factory.createIdentifier(name))), factory.createStringLiteral(resolvePath), void 0);
|
|
121
|
-
return factory.createImportDeclaration(void 0, factory.createImportClause(isTypeOnly, factory.createIdentifier(name), void 0), factory.createStringLiteral(resolvePath), void 0);
|
|
122
|
-
}
|
|
123
|
-
const specifiers = name.map((item) => {
|
|
124
|
-
if (typeof item === "object") {
|
|
125
|
-
const { propertyName, name: alias } = item;
|
|
126
|
-
return factory.createImportSpecifier(false, alias ? factory.createIdentifier(propertyName) : void 0, factory.createIdentifier(alias ?? propertyName));
|
|
127
|
-
}
|
|
128
|
-
return factory.createImportSpecifier(false, void 0, factory.createIdentifier(item));
|
|
129
|
-
});
|
|
130
|
-
return factory.createImportDeclaration(void 0, factory.createImportClause(isTypeOnly, void 0, factory.createNamedImports(specifiers)), factory.createStringLiteral(resolvePath), void 0);
|
|
131
|
-
}
|
|
132
|
-
function createExport({ path, asAlias, isTypeOnly = false, name }) {
|
|
133
|
-
if (name && !Array.isArray(name) && !asAlias) console.warn(`When using name as string, asAlias should be true: ${name}`);
|
|
134
|
-
if (!Array.isArray(name)) {
|
|
135
|
-
const parsedName = name && LEADING_DIGIT_PATTERN.test(name) ? `_${name.slice(1)}` : name;
|
|
136
|
-
return factory.createExportDeclaration(void 0, isTypeOnly, asAlias && parsedName ? factory.createNamespaceExport(factory.createIdentifier(parsedName)) : void 0, factory.createStringLiteral(path), void 0);
|
|
137
|
-
}
|
|
138
|
-
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);
|
|
139
|
-
}
|
|
140
155
|
/**
|
|
141
156
|
* Converts a {@link JSDocNode} to a JSDoc comment block string.
|
|
142
157
|
*
|
|
@@ -161,41 +176,6 @@ function printJSDoc(jsDoc) {
|
|
|
161
176
|
].join("\n");
|
|
162
177
|
}
|
|
163
178
|
/**
|
|
164
|
-
* Serializes the body / value content from a `nodes` array.
|
|
165
|
-
*
|
|
166
|
-
* Each element is either a raw string or a structured {@link CodeNode}
|
|
167
|
-
* (recursively converted via {@link printCodeNode}).
|
|
168
|
-
* Elements are joined with `\n`.
|
|
169
|
-
*/
|
|
170
|
-
function printNodes(nodes) {
|
|
171
|
-
if (!nodes || nodes.length === 0) return "";
|
|
172
|
-
return nodes.map(printCodeNode).join("\n");
|
|
173
|
-
}
|
|
174
|
-
/**
|
|
175
|
-
* Indents every non-empty line of `text` by `spaces` spaces.
|
|
176
|
-
*/
|
|
177
|
-
function indentLines(text, spaces = 2) {
|
|
178
|
-
if (!text) return "";
|
|
179
|
-
const pad = " ".repeat(spaces);
|
|
180
|
-
return text.split("\n").map((line) => line.trim() ? `${pad}${line}` : "").join("\n");
|
|
181
|
-
}
|
|
182
|
-
/**
|
|
183
|
-
* Renders the generic clause (`<T, U>`) shared by function and arrow-function nodes.
|
|
184
|
-
* Accepts either a raw string (rendered verbatim) or an array of type-parameter names.
|
|
185
|
-
*/
|
|
186
|
-
function formatGenerics(generics) {
|
|
187
|
-
if (!generics) return "";
|
|
188
|
-
return `<${Array.isArray(generics) ? generics.join(", ") : generics}>`;
|
|
189
|
-
}
|
|
190
|
-
/**
|
|
191
|
-
* Renders the return-type suffix (`: T` or `: Promise<T>` when `isAsync` is true).
|
|
192
|
-
* Returns an empty string when no return type is provided.
|
|
193
|
-
*/
|
|
194
|
-
function formatReturnType(returnType, isAsync) {
|
|
195
|
-
if (!returnType) return "";
|
|
196
|
-
return isAsync ? `: Promise<${returnType}>` : `: ${returnType}`;
|
|
197
|
-
}
|
|
198
|
-
/**
|
|
199
179
|
* Converts a {@link ConstNode} to a TypeScript `const` declaration string.
|
|
200
180
|
*
|
|
201
181
|
* Mirrors the `Const` component from `@kubb/renderer-jsx`.
|
|
@@ -358,6 +338,31 @@ function printSource(node) {
|
|
|
358
338
|
if (node.nodes && node.nodes.length > 0) return node.nodes.map(printCodeNode).join("\n");
|
|
359
339
|
return "";
|
|
360
340
|
}
|
|
341
|
+
function createImport({ name, path, root, isTypeOnly = false, isNameSpace = false }) {
|
|
342
|
+
const resolvePath = root ? getRelativePath(root, path) : path;
|
|
343
|
+
if (!Array.isArray(name)) {
|
|
344
|
+
if (isNameSpace) return factory.createImportDeclaration(void 0, factory.createImportClause(isTypeOnly, void 0, factory.createNamespaceImport(factory.createIdentifier(name))), factory.createStringLiteral(resolvePath), void 0);
|
|
345
|
+
return factory.createImportDeclaration(void 0, factory.createImportClause(isTypeOnly, factory.createIdentifier(name), void 0), factory.createStringLiteral(resolvePath), void 0);
|
|
346
|
+
}
|
|
347
|
+
const specifiers = name.map((item) => {
|
|
348
|
+
if (typeof item === "object") {
|
|
349
|
+
const { propertyName, name: alias } = item;
|
|
350
|
+
return factory.createImportSpecifier(false, alias ? factory.createIdentifier(propertyName) : void 0, factory.createIdentifier(alias ?? propertyName));
|
|
351
|
+
}
|
|
352
|
+
return factory.createImportSpecifier(false, void 0, factory.createIdentifier(item));
|
|
353
|
+
});
|
|
354
|
+
return factory.createImportDeclaration(void 0, factory.createImportClause(isTypeOnly, void 0, factory.createNamedImports(specifiers)), factory.createStringLiteral(resolvePath), void 0);
|
|
355
|
+
}
|
|
356
|
+
function createExport({ path, asAlias, isTypeOnly = false, name }) {
|
|
357
|
+
if (name && !Array.isArray(name) && !asAlias) console.warn(`When using name as string, asAlias should be true: ${name}`);
|
|
358
|
+
if (!Array.isArray(name)) {
|
|
359
|
+
const parsedName = name && LEADING_DIGIT_PATTERN.test(name) ? `_${name.slice(1)}` : name;
|
|
360
|
+
return factory.createExportDeclaration(void 0, isTypeOnly, asAlias && parsedName ? factory.createNamespaceExport(factory.createIdentifier(parsedName)) : void 0, factory.createStringLiteral(path), void 0);
|
|
361
|
+
}
|
|
362
|
+
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);
|
|
363
|
+
}
|
|
364
|
+
//#endregion
|
|
365
|
+
//#region src/parserTs.ts
|
|
361
366
|
/**
|
|
362
367
|
* Parser that converts `.ts` and `.js` files to strings using the TypeScript
|
|
363
368
|
* compiler. Handles import/export statement generation from file metadata.
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["ts"],"sources":["../src/constants.ts","../src/parserTs.ts","../src/parserTsx.ts"],"sourcesContent":["/**\n * Number of spaces used to indent a nested block when pretty-printing.\n */\nexport const INDENT_SIZE = 2 as const\n\n/**\n * Matches the trailing `.<ext>` segment of a path (keeps segments like `foo.bar.ts`\n * intact by only trimming the last run of non-`/`/`.` characters).\n */\nexport const FILE_EXTENSION_PATTERN = /\\.[^/.]+$/\n\n/**\n * Matches Windows-style backslash path separators.\n */\nexport const WINDOWS_PATH_SEPARATOR = /\\\\/g\n\n/**\n * Matches `*\\/` in free-form text so JSDoc bodies can neutralise premature\n * comment terminators (`*\\/` → `* /`).\n */\nexport const JSDOC_TERMINATOR_PATTERN = /\\*\\//g\n\n/**\n * Matches carriage returns for normalising CRLF/CR line endings to LF.\n */\nexport const CARRIAGE_RETURN_PATTERN = /\\r/g\n\n/**\n * Matches CRLF sequences used when normalising TypeScript printer output.\n */\nexport const CRLF_PATTERN = /\\r\\n/g\n\n/**\n * Matches an identifier that starts with a digit — JavaScript disallows this\n * so the printer prefixes such names with `_`.\n */\nexport const LEADING_DIGIT_PATTERN = /^\\d/\n\n/**\n * Relative path prefix used to detect traversal segments (`../`).\n */\nexport const PARENT_DIRECTORY_PREFIX = '../' as const\n\n/**\n * Relative path prefix used when resolving imports within the output root.\n */\nexport const CURRENT_DIRECTORY_PREFIX = './' as const\n","import { normalize, relative } from 'node:path'\nimport type { ArrowFunctionNode, CodeNode, ConstNode, FileNode, FunctionNode, JSDocNode, JsxNode, SourceNode, TextNode, TypeNode } from '@kubb/ast'\nimport type { Parser } from '@kubb/core'\nimport { defineParser } from '@kubb/core'\nimport ts from 'typescript'\nimport {\n CARRIAGE_RETURN_PATTERN,\n CRLF_PATTERN,\n CURRENT_DIRECTORY_PREFIX,\n FILE_EXTENSION_PATTERN,\n INDENT_SIZE,\n JSDOC_TERMINATOR_PATTERN,\n LEADING_DIGIT_PATTERN,\n PARENT_DIRECTORY_PREFIX,\n WINDOWS_PATH_SEPARATOR,\n} from './constants.ts'\n\nconst { factory } = ts\n\nfunction slash(path: string): string {\n return normalize(path).replaceAll(WINDOWS_PATH_SEPARATOR, '/').replace(PARENT_DIRECTORY_PREFIX, '')\n}\n\n/**\n * Resolves `filePath` relative to `rootDir` and returns a POSIX-style path\n * prefixed with `./` when the target sits inside the root, or `../` when it escapes it.\n */\nfunction getRelativePath(rootDir: string, filePath: string): string {\n const rel = relative(rootDir, filePath)\n const slashed = slash(rel)\n return slashed.startsWith(PARENT_DIRECTORY_PREFIX) ? slashed : `${CURRENT_DIRECTORY_PREFIX}${slashed}`\n}\n\n/**\n * Strips the trailing file extension (for example `.ts`) from a path.\n * Preserves intermediate dots like `foo.bar.ts` → `foo.bar`.\n */\nfunction trimExtName(text: string): string {\n return text.replace(FILE_EXTENSION_PATTERN, '')\n}\n\n/**\n * Rewrites an import/export path so its extension matches the caller-supplied\n * `options.extname`. When the source path has no extension the original is kept,\n * so virtual/module-only paths flow through unchanged.\n */\nfunction resolveOutputPath(path: string, options: { extname?: string } | undefined, rootAware: boolean): string {\n const hasExtname = FILE_EXTENSION_PATTERN.test(path)\n if (options?.extname && hasExtname) {\n return `${trimExtName(path)}${options.extname}`\n }\n return rootAware ? trimExtName(path) : path\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(CRLF_PATTERN, '\\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 && LEADING_DIGIT_PATTERN.test(name) ? `_${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(JSDOC_TERMINATOR_PATTERN, '* /').replace(CARRIAGE_RETURN_PATTERN, ''))\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 * Serializes 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> | undefined): string {\n if (!nodes || nodes.length === 0) return ''\n return nodes.map(printCodeNode).join('\\n')\n}\n\n/**\n * Indents every non-empty line of `text` by `spaces` spaces.\n */\nfunction indentLines(text: string, spaces: number = INDENT_SIZE): 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 * Renders the generic clause (`<T, U>`) shared by function and arrow-function nodes.\n * Accepts either a raw string (rendered verbatim) or an array of type-parameter names.\n */\nfunction formatGenerics(generics: FunctionNode['generics'] | ArrowFunctionNode['generics']): string {\n if (!generics) return ''\n return `<${Array.isArray(generics) ? generics.join(', ') : generics}>`\n}\n\n/**\n * Renders the return-type suffix (`: T` or `: Promise<T>` when `isAsync` is true).\n * Returns an empty string when no return type is provided.\n */\nfunction formatReturnType(returnType: string | undefined, isAsync: boolean | undefined): string {\n if (!returnType) return ''\n return isAsync ? `: Promise<${returnType}>` : `: ${returnType}`\n}\n\n/**\n * Converts a {@link ConstNode} to a TypeScript `const` declaration string.\n *\n * Mirrors the `Const` component from `@kubb/renderer-jsx`.\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/renderer-jsx`.\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/renderer-jsx`.\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 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(formatGenerics(generics))\n parts.push(`(${params ?? ''})`)\n parts.push(formatReturnType(returnType, isAsync))\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/renderer-jsx`.\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 const body = printNodes(nodes)\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(formatGenerics(generics))\n parts.push(`(${params ?? ''})`)\n parts.push(formatReturnType(returnType, isAsync))\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 'Break':\n return ''\n case 'Text':\n return (node as TextNode).value\n case 'Jsx':\n return (node as JsxNode).value\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 * Iterates `nodes` in DOM order, rendering each {@link CodeNode} via\n * {@link printCodeNode}.\n *\n * @example From nodes\n * ```ts\n * printSource({ kind: 'Source', nodes: [createConst({ name: 'x', nodes: [createText('1')] }), createText('x.toString()')] })\n * // 'const x = 1\\nx.toString()'\n * ```\n */\nexport function printSource(node: SourceNode): string {\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.trimEnd())\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 importNodes.push(\n createImport({\n name: item.name as string | Array<string | { propertyName: string; name?: string }>,\n path: resolveOutputPath(importPath, options, Boolean(item.root)),\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 exportNodes.push(\n createExport({\n name: item.name as string | Array<ts.Identifier | string> | undefined,\n path: resolveOutputPath(item.path, options, true),\n isTypeOnly: item.isTypeOnly,\n asAlias: item.asAlias,\n }),\n )\n }\n\n const parts = [file.banner, print(...importNodes, ...exportNodes), source, file.footer]\n .filter((segment): segment is string => Boolean(segment))\n .map((s) => s.trimEnd())\n return parts.join('\\n\\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AASA,MAAa,yBAAyB;;;;AAKtC,MAAa,yBAAyB;;;;;AAMtC,MAAa,2BAA2B;;;;AAKxC,MAAa,0BAA0B;;;;AAKvC,MAAa,eAAe;;;;;AAM5B,MAAa,wBAAwB;;;ACnBrC,MAAM,EAAE,YAAYA,WAAAA;AAEpB,SAAS,MAAM,MAAsB;AACnC,SAAA,GAAA,UAAA,WAAiB,KAAK,CAAC,WAAW,wBAAwB,IAAI,CAAC,QAAA,OAAiC,GAAG;;;;;;AAOrG,SAAS,gBAAgB,SAAiB,UAA0B;CAElE,MAAM,UAAU,OAAA,GAAA,UAAA,UADK,SAAS,SACL,CAAC;AAC1B,QAAO,QAAQ,WAAA,MAAmC,GAAG,UAAU,KAA8B;;;;;;AAO/F,SAAS,YAAY,MAAsB;AACzC,QAAO,KAAK,QAAQ,wBAAwB,GAAG;;;;;;;AAQjD,SAAS,kBAAkB,MAAc,SAA2C,WAA4B;CAC9G,MAAM,aAAa,uBAAuB,KAAK,KAAK;AACpD,KAAI,SAAS,WAAW,WACtB,QAAO,GAAG,YAAY,KAAK,GAAG,QAAQ;AAExC,QAAO,YAAY,YAAY,KAAK,GAAG;;;;;;;AAQzC,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,SAA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AK,SAAS;GAC/B,MAAM,YAAY,YAAY,KAAmB;AACjD,OAAI,UACF,aAAY,KAAK,UAAU,SAAS,CAAC;;EAGzC,MAAM,SAAS,YAAY,KAAK,OAAO;EAEvC,MAAM,cAA2C,EAAE;AACnD,OAAK,MAAM,QAAS,KAAkB,SAAS;GAC7C,MAAM,aAAa,KAAK,OAAO,gBAAgB,KAAK,MAAM,KAAK,KAAK,GAAG,KAAK;AAC5E,eAAY,KACV,aAAa;IACX,MAAM,KAAK;IACX,MAAM,kBAAkB,YAAY,SAAS,QAAQ,KAAK,KAAK,CAAC;IAChE,YAAY,KAAK;IACjB,aAAa,KAAK;IACnB,CAAC,CACH;;EAGH,MAAM,cAA2C,EAAE;AACnD,OAAK,MAAM,QAAS,KAAkB,QACpC,aAAY,KACV,aAAa;GACX,MAAM,KAAK;GACX,MAAM,kBAAkB,KAAK,MAAM,SAAS,KAAK;GACjD,YAAY,KAAK;GACjB,SAAS,KAAK;GACf,CAAC,CACH;AAMH,SAHc;GAAC,KAAK;GAAQ,MAAM,GAAG,aAAa,GAAG,YAAY;GAAE;GAAQ,KAAK;GAAO,CACpF,QAAQ,YAA+B,QAAQ,QAAQ,CAAC,CACxD,KAAK,MAAM,EAAE,SAAS,CACb,CAAC,KAAK,OAAO;;CAE5B,CAAC;;;;;;;;;;;;AC/eF,MAAa,aAAA,GAAA,WAAA,cAAiC;CAC5C,MAAM;CACN,UAAU,CAAC,QAAQ,OAAO;CAC1B,MAAM,MAAM,MAAM,UAAU,EAAE,SAAS,QAAQ,EAAE;AAC/C,SAAO,SAAS,MAAM,MAAM,QAAQ;;CAEvC,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["ts"],"sources":["../src/constants.ts","../src/utils.ts","../src/parserTs.ts","../src/parserTsx.ts"],"sourcesContent":["/**\n * Number of spaces used to indent a nested block when pretty-printing.\n */\nexport const INDENT_SIZE = 2 as const\n\n/**\n * Matches the trailing `.<ext>` segment of a path (keeps segments like `foo.bar.ts`\n * intact by only trimming the last run of non-`/`/`.` characters).\n */\nexport const FILE_EXTENSION_PATTERN = /\\.[^/.]+$/\n\n/**\n * Matches Windows-style backslash path separators.\n */\nexport const WINDOWS_PATH_SEPARATOR = /\\\\/g\n\n/**\n * Matches `*\\/` in free-form text so JSDoc bodies can neutralise premature\n * comment terminators (`*\\/` → `* /`).\n */\nexport const JSDOC_TERMINATOR_PATTERN = /\\*\\//g\n\n/**\n * Matches carriage returns for normalising CRLF/CR line endings to LF.\n */\nexport const CARRIAGE_RETURN_PATTERN = /\\r/g\n\n/**\n * Matches CRLF sequences used when normalising TypeScript printer output.\n */\nexport const CRLF_PATTERN = /\\r\\n/g\n\n/**\n * Matches an identifier that starts with a digit — JavaScript disallows this\n * so the printer prefixes such names with `_`.\n */\nexport const LEADING_DIGIT_PATTERN = /^\\d/\n\n/**\n * Relative path prefix used to detect traversal segments (`../`).\n */\nexport const PARENT_DIRECTORY_PREFIX = '../' as const\n\n/**\n * Relative path prefix used when resolving imports within the output root.\n */\nexport const CURRENT_DIRECTORY_PREFIX = './' as const\n","import { normalize, relative } from 'node:path'\nimport type { ArrowFunctionNode, CodeNode, ConstNode, FunctionNode, JSDocNode, JsxNode, SourceNode, TextNode, TypeNode } from '@kubb/ast'\nimport ts from 'typescript'\nimport {\n CARRIAGE_RETURN_PATTERN,\n CRLF_PATTERN,\n CURRENT_DIRECTORY_PREFIX,\n FILE_EXTENSION_PATTERN,\n INDENT_SIZE,\n JSDOC_TERMINATOR_PATTERN,\n LEADING_DIGIT_PATTERN,\n PARENT_DIRECTORY_PREFIX,\n WINDOWS_PATH_SEPARATOR,\n} from './constants.ts'\n\nconst { factory } = ts\n\n/**\n * Normalises a file-system path to POSIX separators and strips any leading `../` segment.\n */\nexport function slash(path: string): string {\n return normalize(path).replaceAll(WINDOWS_PATH_SEPARATOR, '/').replace(PARENT_DIRECTORY_PREFIX, '')\n}\n\n/**\n * Resolves `filePath` relative to `rootDir` and returns a POSIX-style path\n * prefixed with `./` when the target sits inside the root, or `../` when it escapes it.\n */\nexport function getRelativePath(rootDir: string, filePath: string): string {\n const rel = relative(rootDir, filePath)\n const slashed = slash(rel)\n return slashed.startsWith(PARENT_DIRECTORY_PREFIX) ? slashed : `${CURRENT_DIRECTORY_PREFIX}${slashed}`\n}\n\n/**\n * Strips the trailing file extension (for example `.ts`) from a path.\n * Preserves intermediate dots like `foo.bar.ts` → `foo.bar`.\n */\nexport function trimExtName(text: string): string {\n return text.replace(FILE_EXTENSION_PATTERN, '')\n}\n\n/**\n * Rewrites an import/export path so its extension matches the caller-supplied\n * `options.extname`. When the source path has no extension the original is kept,\n * so virtual/module-only paths flow through unchanged.\n */\nexport function resolveOutputPath(path: string, options: { extname?: string } | undefined, rootAware: boolean): string {\n const hasExtname = FILE_EXTENSION_PATTERN.test(path)\n if (options?.extname && hasExtname) {\n return `${trimExtName(path)}${options.extname}`\n }\n return rootAware ? trimExtName(path) : path\n}\n\n/**\n * Serializes 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 */\nexport function printNodes(nodes: Array<CodeNode> | undefined): string {\n if (!nodes || nodes.length === 0) return ''\n return nodes.map(printCodeNode).join('\\n')\n}\n\n/**\n * Indents every non-empty line of `text` by `spaces` spaces.\n */\nexport function indentLines(text: string, spaces: number = INDENT_SIZE): 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 * Renders the generic clause (`<T, U>`) shared by function and arrow-function nodes.\n * Accepts either a raw string (rendered verbatim) or an array of type-parameter names.\n */\nexport function formatGenerics(generics: FunctionNode['generics'] | ArrowFunctionNode['generics']): string {\n if (!generics) return ''\n return `<${Array.isArray(generics) ? generics.join(', ') : generics}>`\n}\n\n/**\n * Renders the return-type suffix (`: T` or `: Promise<T>` when `isAsync` is true).\n * Returns an empty string when no return type is provided.\n */\nexport function formatReturnType(returnType: string | undefined, isAsync: boolean | undefined): string {\n if (!returnType) return ''\n return isAsync ? `: Promise<${returnType}>` : `: ${returnType}`\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(CRLF_PATTERN, '\\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\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(JSDOC_TERMINATOR_PATTERN, '* /').replace(CARRIAGE_RETURN_PATTERN, ''))\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 * Converts a {@link ConstNode} to a TypeScript `const` declaration string.\n *\n * Mirrors the `Const` component from `@kubb/renderer-jsx`.\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/renderer-jsx`.\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/renderer-jsx`.\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 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(formatGenerics(generics))\n parts.push(`(${params ?? ''})`)\n parts.push(formatReturnType(returnType, isAsync))\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/renderer-jsx`.\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 const body = printNodes(nodes)\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(formatGenerics(generics))\n parts.push(`(${params ?? ''})`)\n parts.push(formatReturnType(returnType, isAsync))\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 'Break':\n return ''\n case 'Text':\n return (node as TextNode).value\n case 'Jsx':\n return (node as JsxNode).value\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 * Iterates `nodes` in DOM order, rendering each {@link CodeNode} via\n * {@link printCodeNode}.\n *\n * @example From nodes\n * ```ts\n * printSource({ kind: 'Source', nodes: [createConst({ name: 'x', nodes: [createText('1')] }), createText('x.toString()')] })\n * // 'const x = 1\\nx.toString()'\n * ```\n */\nexport function printSource(node: SourceNode): string {\n if (node.nodes && node.nodes.length > 0) {\n return node.nodes.map(printCodeNode).join('\\n')\n }\n return ''\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 && LEADING_DIGIT_PATTERN.test(name) ? `_${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","import type { FileNode, SourceNode } from '@kubb/ast'\nimport type { Parser } from '@kubb/core'\nimport { defineParser } from '@kubb/core'\nimport type * as ts from 'typescript'\nimport { createExport, createImport, getRelativePath, print, printSource, resolveOutputPath } from './utils.ts'\n\nexport { createExport, createImport, print, safePrint, validateNodes } from './utils.ts'\n\nexport { printArrowFunction, printCodeNode, printConst, printFunction, printJSDoc, printSource, printType } from './utils.ts'\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.trimEnd())\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 importNodes.push(\n createImport({\n name: item.name as string | Array<string | { propertyName: string; name?: string }>,\n path: resolveOutputPath(importPath, options, Boolean(item.root)),\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 exportNodes.push(\n createExport({\n name: item.name as string | Array<ts.Identifier | string> | undefined,\n path: resolveOutputPath(item.path, options, true),\n isTypeOnly: item.isTypeOnly,\n asAlias: item.asAlias,\n }),\n )\n }\n\n const parts = [file.banner, print(...importNodes, ...exportNodes), source, file.footer]\n .filter((segment): segment is string => Boolean(segment))\n .map((s) => s.trimEnd())\n return parts.join('\\n\\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AASA,MAAa,yBAAyB;;;;AAKtC,MAAa,yBAAyB;;;;;AAMtC,MAAa,2BAA2B;;;;AAKxC,MAAa,0BAA0B;;;;AAKvC,MAAa,eAAe;;;;;AAM5B,MAAa,wBAAwB;;;ACrBrC,MAAM,EAAE,YAAYA,WAAAA;;;;AAKpB,SAAgB,MAAM,MAAsB;CAC1C,QAAA,GAAA,UAAA,WAAiB,KAAK,CAAC,WAAW,wBAAwB,IAAI,CAAC,QAAA,OAAiC,GAAG;;;;;;AAOrG,SAAgB,gBAAgB,SAAiB,UAA0B;CAEzE,MAAM,UAAU,OAAA,GAAA,UAAA,UADK,SAAS,SACL,CAAC;CAC1B,OAAO,QAAQ,WAAA,MAAmC,GAAG,UAAU,KAA8B;;;;;;AAO/F,SAAgB,YAAY,MAAsB;CAChD,OAAO,KAAK,QAAQ,wBAAwB,GAAG;;;;;;;AAQjD,SAAgB,kBAAkB,MAAc,SAA2C,WAA4B;CACrH,MAAM,aAAa,uBAAuB,KAAK,KAAK;CACpD,IAAI,SAAS,WAAW,YACtB,OAAO,GAAG,YAAY,KAAK,GAAG,QAAQ;CAExC,OAAO,YAAY,YAAY,KAAK,GAAG;;;;;;;;;AAUzC,SAAgB,WAAW,OAA4C;CACrE,IAAI,CAAC,SAAS,MAAM,WAAW,GAAG,OAAO;CACzC,OAAO,MAAM,IAAI,cAAc,CAAC,KAAK,KAAK;;;;;AAM5C,SAAgB,YAAY,MAAc,SAAA,GAAsC;CAC9E,IAAI,CAAC,MAAM,OAAO;CAClB,MAAM,MAAM,IAAI,OAAO,OAAO;CAC9B,OAAO,KACJ,MAAM,KAAK,CAC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,YAAY,YAAY,KAAmB;GACjD,IAAI,WACF,YAAY,KAAK,UAAU,SAAS,CAAC;;EAGzC,MAAM,SAAS,YAAY,KAAK,OAAO;EAEvC,MAAM,cAA2C,EAAE;EACnD,KAAK,MAAM,QAAS,KAAkB,SAAS;GAC7C,MAAM,aAAa,KAAK,OAAO,gBAAgB,KAAK,MAAM,KAAK,KAAK,GAAG,KAAK;GAC5E,YAAY,KACV,aAAa;IACX,MAAM,KAAK;IACX,MAAM,kBAAkB,YAAY,SAAS,QAAQ,KAAK,KAAK,CAAC;IAChE,YAAY,KAAK;IACjB,aAAa,KAAK;IACnB,CAAC,CACH;;EAGH,MAAM,cAA2C,EAAE;EACnD,KAAK,MAAM,QAAS,KAAkB,SACpC,YAAY,KACV,aAAa;GACX,MAAM,KAAK;GACX,MAAM,kBAAkB,KAAK,MAAM,SAAS,KAAK;GACjD,YAAY,KAAK;GACjB,SAAS,KAAK;GACf,CAAC,CACH;EAMH,OAHc;GAAC,KAAK;GAAQ,MAAM,GAAG,aAAa,GAAG,YAAY;GAAE;GAAQ,KAAK;GAAO,CACpF,QAAQ,YAA+B,QAAQ,QAAQ,CAAC,CACxD,KAAK,MAAM,EAAE,SAAS,CACb,CAAC,KAAK,OAAO;;CAE5B,CAAC;;;;;;;;;;;;AC9CF,MAAa,aAAA,GAAA,WAAA,cAAiC;CAC5C,MAAM;CACN,UAAU,CAAC,QAAQ,OAAO;CAC1B,MAAM,MAAM,MAAM,UAAU,EAAE,SAAS,QAAQ,EAAE;EAC/C,OAAO,SAAS,MAAM,MAAM,QAAQ;;CAEvC,CAAC"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { t as __name } from "./chunk--u3MIqq1.js";
|
|
2
2
|
import { Parser } from "@kubb/core";
|
|
3
3
|
import ts from "typescript";
|
|
4
|
-
//#region src/
|
|
4
|
+
//#region src/utils.d.ts
|
|
5
5
|
/**
|
|
6
6
|
* Validates TypeScript AST nodes before printing.
|
|
7
7
|
* Throws an error if any node has SyntaxKind.Unknown which would cause the
|
|
@@ -43,6 +43,8 @@ declare function createExport({
|
|
|
43
43
|
isTypeOnly?: boolean;
|
|
44
44
|
name?: string | Array<ts.Identifier | string>;
|
|
45
45
|
}): ts.ExportDeclaration;
|
|
46
|
+
//#endregion
|
|
47
|
+
//#region src/parserTs.d.ts
|
|
46
48
|
/**
|
|
47
49
|
* Parser that converts `.ts` and `.js` files to strings using the TypeScript
|
|
48
50
|
* compiler. Handles import/export statement generation from file metadata.
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import "./chunk--u3MIqq1.js";
|
|
2
|
-
import { normalize, relative } from "node:path";
|
|
3
2
|
import { defineParser } from "@kubb/core";
|
|
3
|
+
import { normalize, relative } from "node:path";
|
|
4
4
|
import ts from "typescript";
|
|
5
5
|
//#region src/constants.ts
|
|
6
6
|
/**
|
|
@@ -31,8 +31,11 @@ const CRLF_PATTERN = /\r\n/g;
|
|
|
31
31
|
*/
|
|
32
32
|
const LEADING_DIGIT_PATTERN = /^\d/;
|
|
33
33
|
//#endregion
|
|
34
|
-
//#region src/
|
|
34
|
+
//#region src/utils.ts
|
|
35
35
|
const { factory } = ts;
|
|
36
|
+
/**
|
|
37
|
+
* Normalises a file-system path to POSIX separators and strips any leading `../` segment.
|
|
38
|
+
*/
|
|
36
39
|
function slash(path) {
|
|
37
40
|
return normalize(path).replaceAll(WINDOWS_PATH_SEPARATOR, "/").replace("../", "");
|
|
38
41
|
}
|
|
@@ -62,6 +65,41 @@ function resolveOutputPath(path, options, rootAware) {
|
|
|
62
65
|
return rootAware ? trimExtName(path) : path;
|
|
63
66
|
}
|
|
64
67
|
/**
|
|
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`.
|
|
73
|
+
*/
|
|
74
|
+
function printNodes(nodes) {
|
|
75
|
+
if (!nodes || nodes.length === 0) return "";
|
|
76
|
+
return nodes.map(printCodeNode).join("\n");
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Indents every non-empty line of `text` by `spaces` spaces.
|
|
80
|
+
*/
|
|
81
|
+
function indentLines(text, spaces = 2) {
|
|
82
|
+
if (!text) return "";
|
|
83
|
+
const pad = " ".repeat(spaces);
|
|
84
|
+
return text.split("\n").map((line) => line.trim() ? `${pad}${line}` : "").join("\n");
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Renders the generic clause (`<T, U>`) shared by function and arrow-function nodes.
|
|
88
|
+
* Accepts either a raw string (rendered verbatim) or an array of type-parameter names.
|
|
89
|
+
*/
|
|
90
|
+
function formatGenerics(generics) {
|
|
91
|
+
if (!generics) return "";
|
|
92
|
+
return `<${Array.isArray(generics) ? generics.join(", ") : generics}>`;
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Renders the return-type suffix (`: T` or `: Promise<T>` when `isAsync` is true).
|
|
96
|
+
* Returns an empty string when no return type is provided.
|
|
97
|
+
*/
|
|
98
|
+
function formatReturnType(returnType, isAsync) {
|
|
99
|
+
if (!returnType) return "";
|
|
100
|
+
return isAsync ? `: Promise<${returnType}>` : `: ${returnType}`;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
65
103
|
* Validates TypeScript AST nodes before printing.
|
|
66
104
|
* Throws an error if any node has SyntaxKind.Unknown which would cause the
|
|
67
105
|
* TypeScript printer to crash.
|
|
@@ -91,29 +129,6 @@ function safePrint(...elements) {
|
|
|
91
129
|
validateNodes(...elements);
|
|
92
130
|
return print(...elements);
|
|
93
131
|
}
|
|
94
|
-
function createImport({ name, path, root, isTypeOnly = false, isNameSpace = false }) {
|
|
95
|
-
const resolvePath = root ? getRelativePath(root, path) : path;
|
|
96
|
-
if (!Array.isArray(name)) {
|
|
97
|
-
if (isNameSpace) return factory.createImportDeclaration(void 0, factory.createImportClause(isTypeOnly, void 0, factory.createNamespaceImport(factory.createIdentifier(name))), factory.createStringLiteral(resolvePath), void 0);
|
|
98
|
-
return factory.createImportDeclaration(void 0, factory.createImportClause(isTypeOnly, factory.createIdentifier(name), void 0), factory.createStringLiteral(resolvePath), void 0);
|
|
99
|
-
}
|
|
100
|
-
const specifiers = name.map((item) => {
|
|
101
|
-
if (typeof item === "object") {
|
|
102
|
-
const { propertyName, name: alias } = item;
|
|
103
|
-
return factory.createImportSpecifier(false, alias ? factory.createIdentifier(propertyName) : void 0, factory.createIdentifier(alias ?? propertyName));
|
|
104
|
-
}
|
|
105
|
-
return factory.createImportSpecifier(false, void 0, factory.createIdentifier(item));
|
|
106
|
-
});
|
|
107
|
-
return factory.createImportDeclaration(void 0, factory.createImportClause(isTypeOnly, void 0, factory.createNamedImports(specifiers)), factory.createStringLiteral(resolvePath), void 0);
|
|
108
|
-
}
|
|
109
|
-
function createExport({ path, asAlias, isTypeOnly = false, name }) {
|
|
110
|
-
if (name && !Array.isArray(name) && !asAlias) console.warn(`When using name as string, asAlias should be true: ${name}`);
|
|
111
|
-
if (!Array.isArray(name)) {
|
|
112
|
-
const parsedName = name && LEADING_DIGIT_PATTERN.test(name) ? `_${name.slice(1)}` : name;
|
|
113
|
-
return factory.createExportDeclaration(void 0, isTypeOnly, asAlias && parsedName ? factory.createNamespaceExport(factory.createIdentifier(parsedName)) : void 0, factory.createStringLiteral(path), void 0);
|
|
114
|
-
}
|
|
115
|
-
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);
|
|
116
|
-
}
|
|
117
132
|
/**
|
|
118
133
|
* Converts a {@link JSDocNode} to a JSDoc comment block string.
|
|
119
134
|
*
|
|
@@ -138,41 +153,6 @@ function printJSDoc(jsDoc) {
|
|
|
138
153
|
].join("\n");
|
|
139
154
|
}
|
|
140
155
|
/**
|
|
141
|
-
* Serializes the body / value content from a `nodes` array.
|
|
142
|
-
*
|
|
143
|
-
* Each element is either a raw string or a structured {@link CodeNode}
|
|
144
|
-
* (recursively converted via {@link printCodeNode}).
|
|
145
|
-
* Elements are joined with `\n`.
|
|
146
|
-
*/
|
|
147
|
-
function printNodes(nodes) {
|
|
148
|
-
if (!nodes || nodes.length === 0) return "";
|
|
149
|
-
return nodes.map(printCodeNode).join("\n");
|
|
150
|
-
}
|
|
151
|
-
/**
|
|
152
|
-
* Indents every non-empty line of `text` by `spaces` spaces.
|
|
153
|
-
*/
|
|
154
|
-
function indentLines(text, spaces = 2) {
|
|
155
|
-
if (!text) return "";
|
|
156
|
-
const pad = " ".repeat(spaces);
|
|
157
|
-
return text.split("\n").map((line) => line.trim() ? `${pad}${line}` : "").join("\n");
|
|
158
|
-
}
|
|
159
|
-
/**
|
|
160
|
-
* Renders the generic clause (`<T, U>`) shared by function and arrow-function nodes.
|
|
161
|
-
* Accepts either a raw string (rendered verbatim) or an array of type-parameter names.
|
|
162
|
-
*/
|
|
163
|
-
function formatGenerics(generics) {
|
|
164
|
-
if (!generics) return "";
|
|
165
|
-
return `<${Array.isArray(generics) ? generics.join(", ") : generics}>`;
|
|
166
|
-
}
|
|
167
|
-
/**
|
|
168
|
-
* Renders the return-type suffix (`: T` or `: Promise<T>` when `isAsync` is true).
|
|
169
|
-
* Returns an empty string when no return type is provided.
|
|
170
|
-
*/
|
|
171
|
-
function formatReturnType(returnType, isAsync) {
|
|
172
|
-
if (!returnType) return "";
|
|
173
|
-
return isAsync ? `: Promise<${returnType}>` : `: ${returnType}`;
|
|
174
|
-
}
|
|
175
|
-
/**
|
|
176
156
|
* Converts a {@link ConstNode} to a TypeScript `const` declaration string.
|
|
177
157
|
*
|
|
178
158
|
* Mirrors the `Const` component from `@kubb/renderer-jsx`.
|
|
@@ -335,6 +315,31 @@ function printSource(node) {
|
|
|
335
315
|
if (node.nodes && node.nodes.length > 0) return node.nodes.map(printCodeNode).join("\n");
|
|
336
316
|
return "";
|
|
337
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);
|
|
323
|
+
}
|
|
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);
|
|
332
|
+
}
|
|
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}`);
|
|
335
|
+
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);
|
|
338
|
+
}
|
|
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);
|
|
340
|
+
}
|
|
341
|
+
//#endregion
|
|
342
|
+
//#region src/parserTs.ts
|
|
338
343
|
/**
|
|
339
344
|
* Parser that converts `.ts` and `.js` files to strings using the TypeScript
|
|
340
345
|
* compiler. Handles import/export statement generation from file metadata.
|