esbuild-plugin-dtsx 0.9.10

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.md ADDED
@@ -0,0 +1,21 @@
1
+ # MIT License
2
+
3
+ Copyright (c) 2024 Open Web Foundation
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:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
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.
package/README.md ADDED
@@ -0,0 +1,152 @@
1
+ # esbuild-plugin-dtsx
2
+
3
+ An esbuild plugin for automatic TypeScript declaration file generation using dtsx.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ bun add esbuild-plugin-dtsx -d
9
+ # or
10
+ npm install esbuild-plugin-dtsx --save-dev
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ ```typescript
16
+ import { build } from 'esbuild'
17
+ import { dtsx } from 'esbuild-plugin-dtsx'
18
+
19
+ await build({
20
+ entryPoints: ['src/index.ts'],
21
+ outdir: 'dist',
22
+ bundle: true,
23
+ format: 'esm',
24
+ plugins: [
25
+ dtsx({
26
+ // Options
27
+ }),
28
+ ],
29
+ })
30
+ ```
31
+
32
+ ## Options
33
+
34
+ | Option | Type | Default | Description |
35
+ |--------|------|---------|-------------|
36
+ | `trigger` | `'build' \| 'watch' \| 'both'` | `'build'` | When to generate declarations |
37
+ | `entryPointsOnly` | `boolean` | `true` | Only generate for entry points |
38
+ | `declarationDir` | `string` | esbuild outdir | Output directory for declarations |
39
+ | `bundle` | `boolean` | `false` | Bundle all declarations into one file |
40
+ | `bundleOutput` | `string` | `'index.d.ts'` | Bundled output filename |
41
+ | `exclude` | `(string \| RegExp)[]` | `[]` | Patterns to exclude |
42
+ | `include` | `(string \| RegExp)[]` | `[]` | Patterns to include |
43
+ | `emitOnError` | `boolean` | `true` | Emit even with type errors |
44
+
45
+ ## Examples
46
+
47
+ ### Basic Usage
48
+
49
+ ```typescript
50
+ import { build } from 'esbuild'
51
+ import { dtsx } from 'esbuild-plugin-dtsx'
52
+
53
+ await build({
54
+ entryPoints: ['src/index.ts'],
55
+ outdir: 'dist',
56
+ plugins: [dtsx()],
57
+ })
58
+ ```
59
+
60
+ ### With Bundled Declarations
61
+
62
+ ```typescript
63
+ import { build } from 'esbuild'
64
+ import { dtsx } from 'esbuild-plugin-dtsx'
65
+
66
+ await build({
67
+ entryPoints: ['src/index.ts'],
68
+ outdir: 'dist',
69
+ plugins: [
70
+ dtsx({
71
+ bundle: true,
72
+ bundleOutput: 'types.d.ts',
73
+ }),
74
+ ],
75
+ })
76
+ ```
77
+
78
+ ### Watch Mode
79
+
80
+ ```typescript
81
+ import { context } from 'esbuild'
82
+ import { dtsx } from 'esbuild-plugin-dtsx'
83
+
84
+ const ctx = await context({
85
+ entryPoints: ['src/index.ts'],
86
+ outdir: 'dist',
87
+ plugins: [
88
+ dtsx({
89
+ trigger: 'both', // Generate on initial build and rebuilds
90
+ }),
91
+ ],
92
+ })
93
+
94
+ await ctx.watch()
95
+ ```
96
+
97
+ ### With Callbacks
98
+
99
+ ```typescript
100
+ import { build } from 'esbuild'
101
+ import { dtsx } from 'esbuild-plugin-dtsx'
102
+
103
+ await build({
104
+ entryPoints: ['src/index.ts'],
105
+ outdir: 'dist',
106
+ plugins: [
107
+ dtsx({
108
+ onStart: () => {
109
+ console.log('Starting declaration generation...')
110
+ },
111
+ onSuccess: (stats) => {
112
+ console.log(`Generated ${stats.totalFiles} files in ${stats.totalTime}ms`)
113
+ },
114
+ onError: (error) => {
115
+ console.error('Failed to generate declarations:', error.message)
116
+ },
117
+ }),
118
+ ],
119
+ })
120
+ ```
121
+
122
+ ## Additional Plugins
123
+
124
+ ### Type Checking Only
125
+
126
+ ```typescript
127
+ import { dtsxCheck } from 'esbuild-plugin-dtsx'
128
+
129
+ await build({
130
+ plugins: [dtsxCheck()],
131
+ })
132
+ ```
133
+
134
+ ### Watch for Declaration Changes
135
+
136
+ ```typescript
137
+ import { dtsxWatch } from 'esbuild-plugin-dtsx'
138
+
139
+ await build({
140
+ plugins: [
141
+ dtsxWatch({
142
+ onDeclarationChange: (file) => {
143
+ console.log(`Declaration changed: ${file}`)
144
+ },
145
+ }),
146
+ ],
147
+ })
148
+ ```
149
+
150
+ ## License
151
+
152
+ MIT
@@ -0,0 +1,40 @@
1
+ import type { DtsGenerationOption, GenerationStats } from '@stacksjs/dtsx';
2
+ import type { Plugin } from 'esbuild';
3
+ // Re-export types
4
+ export type { DtsGenerationOption, GenerationStats };
5
+ /**
6
+ * Create esbuild plugin for dtsx
7
+ */
8
+ export declare function dtsx(options?: DtsxEsbuildOptions): Plugin;
9
+ /**
10
+ * Create a minimal plugin that only validates types
11
+ */
12
+ export declare function dtsxCheck(): Plugin;
13
+ /**
14
+ * Create a plugin that watches for .d.ts changes
15
+ */
16
+ export declare function dtsxWatch(options?: {
17
+ onDeclarationChange?: (file: string) => void
18
+ }): Plugin;
19
+ /**
20
+ * Plugin configuration options
21
+ */
22
+ export declare interface DtsxEsbuildOptions extends Omit<Partial<DtsGenerationOption>, 'exclude' | 'include'> {
23
+ trigger?: 'build' | 'watch' | 'both'
24
+ entryPointsOnly?: boolean
25
+ declarationDir?: string
26
+ bundle?: boolean
27
+ bundleOutput?: string
28
+ sourceMaps?: boolean
29
+ exclude?: (string | RegExp)[]
30
+ include?: (string | RegExp)[]
31
+ emitOnError?: boolean
32
+ declarationMap?: boolean
33
+ paths?: Record<string, string[]>
34
+ baseUrl?: string
35
+ onSuccess?: (stats: GenerationStats) => void | Promise<void>
36
+ onError?: (error: Error) => void | Promise<void>
37
+ onStart?: () => void | Promise<void>
38
+ onProgress?: (current: number, total: number, file: string) => void
39
+ }
40
+ export default dtsx;
package/dist/index.js ADDED
@@ -0,0 +1,251 @@
1
+ // src/index.ts
2
+ import { generate } from "@stacksjs/dtsx";
3
+ import { resolve, dirname, relative, join } from "node:path";
4
+ import { existsSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";
5
+ function dtsx(options = {}) {
6
+ const {
7
+ trigger = "build",
8
+ entryPointsOnly = true,
9
+ declarationDir,
10
+ bundle: bundleDeclarations = false,
11
+ bundleOutput = "index.d.ts",
12
+ sourceMaps = false,
13
+ exclude = [],
14
+ include = [],
15
+ emitOnError = true,
16
+ declarationMap = false,
17
+ paths,
18
+ baseUrl,
19
+ onSuccess,
20
+ onError,
21
+ onStart,
22
+ onProgress,
23
+ ...dtsOptions
24
+ } = options;
25
+ const state = {
26
+ buildOptions: null,
27
+ isWatchMode: false,
28
+ generatedFiles: /* @__PURE__ */ new Set(),
29
+ errors: []
30
+ };
31
+ return {
32
+ name: "dtsx",
33
+ setup(build) {
34
+ state.buildOptions = build.initialOptions;
35
+ state.isWatchMode = !!build.initialOptions.watch;
36
+ const shouldRun = trigger === "both" || trigger === "build" && !state.isWatchMode || trigger === "watch" && state.isWatchMode;
37
+ if (!shouldRun) {
38
+ return;
39
+ }
40
+ build.onEnd(async (result) => {
41
+ if (result.errors.length > 0 && !emitOnError) {
42
+ console.log("[dtsx] Skipping declaration generation due to build errors");
43
+ return;
44
+ }
45
+ try {
46
+ await onStart?.();
47
+ const config = normalizeConfig(
48
+ dtsOptions,
49
+ state.buildOptions,
50
+ declarationDir
51
+ );
52
+ let filesToProcess = [];
53
+ if (entryPointsOnly) {
54
+ filesToProcess = getEntryPoints(state.buildOptions);
55
+ } else {
56
+ filesToProcess = getTypeScriptFiles(result, state.buildOptions);
57
+ }
58
+ filesToProcess = filterFiles(filesToProcess, include, exclude);
59
+ if (filesToProcess.length === 0) {
60
+ console.log("[dtsx] No files to process");
61
+ return;
62
+ }
63
+ console.log(`[dtsx] Generating declarations for ${filesToProcess.length} file(s)...`);
64
+ const stats = await generate({
65
+ ...config,
66
+ entrypoints: filesToProcess.map((f) => relative(config.cwd || process.cwd(), f))
67
+ });
68
+ state.generatedFiles = /* @__PURE__ */ new Set();
69
+ if (bundleDeclarations && state.generatedFiles.size > 0) {
70
+ await bundleDeclarationsFiles(
71
+ Array.from(state.generatedFiles),
72
+ join(config.outdir || "dist", bundleOutput)
73
+ );
74
+ }
75
+ await onSuccess?.(stats);
76
+ console.log(`[dtsx] Generated ${state.generatedFiles.size} declaration file(s)`);
77
+ } catch (error) {
78
+ const err = error instanceof Error ? error : new Error(String(error));
79
+ state.errors.push(err);
80
+ if (onError) {
81
+ await onError(err);
82
+ } else {
83
+ console.error("[dtsx] Error generating declarations:", err.message);
84
+ }
85
+ }
86
+ });
87
+ }
88
+ };
89
+ }
90
+ function normalizeConfig(options, buildOptions, declarationDir) {
91
+ const outdir = declarationDir || buildOptions.outdir || "dist";
92
+ const cwd = options.cwd || process.cwd();
93
+ let tsconfigPath = options.tsconfigPath;
94
+ if (!tsconfigPath) {
95
+ const defaultPaths = ["tsconfig.json", "tsconfig.build.json"];
96
+ for (const p of defaultPaths) {
97
+ if (existsSync(resolve(cwd, p))) {
98
+ tsconfigPath = p;
99
+ break;
100
+ }
101
+ }
102
+ }
103
+ return {
104
+ cwd,
105
+ root: options.root || "./src",
106
+ outdir,
107
+ tsconfigPath,
108
+ clean: options.clean ?? false,
109
+ keepComments: options.keepComments ?? true,
110
+ ...options
111
+ };
112
+ }
113
+ function getEntryPoints(options) {
114
+ const entryPoints = options.entryPoints;
115
+ if (!entryPoints) {
116
+ return [];
117
+ }
118
+ if (Array.isArray(entryPoints)) {
119
+ return entryPoints.filter((e) => typeof e === "string");
120
+ }
121
+ if (typeof entryPoints === "object") {
122
+ return Object.values(entryPoints);
123
+ }
124
+ return [];
125
+ }
126
+ function getTypeScriptFiles(result, options) {
127
+ const files = [];
128
+ if (result.metafile) {
129
+ for (const input of Object.keys(result.metafile.inputs)) {
130
+ if (input.endsWith(".ts") || input.endsWith(".tsx")) {
131
+ if (!input.endsWith(".d.ts")) {
132
+ files.push(resolve(input));
133
+ }
134
+ }
135
+ }
136
+ }
137
+ if (files.length === 0) {
138
+ files.push(...getEntryPoints(options));
139
+ }
140
+ return files;
141
+ }
142
+ function filterFiles(files, include, exclude) {
143
+ return files.filter((file) => {
144
+ for (const pattern of exclude) {
145
+ if (typeof pattern === "string") {
146
+ if (file.includes(pattern)) return false;
147
+ } else if (pattern.test(file)) {
148
+ return false;
149
+ }
150
+ }
151
+ if (include.length > 0) {
152
+ for (const pattern of include) {
153
+ if (typeof pattern === "string") {
154
+ if (file.includes(pattern)) return true;
155
+ } else if (pattern.test(file)) {
156
+ return true;
157
+ }
158
+ }
159
+ return false;
160
+ }
161
+ return true;
162
+ });
163
+ }
164
+ async function bundleDeclarationsFiles(files, outputPath) {
165
+ const contents = [
166
+ "/**",
167
+ " * Bundled TypeScript declarations",
168
+ ` * Generated by dtsx esbuild plugin`,
169
+ " */",
170
+ ""
171
+ ];
172
+ const imports = /* @__PURE__ */ new Map();
173
+ const declarations = [];
174
+ for (const file of files) {
175
+ if (!existsSync(file)) continue;
176
+ const content = readFileSync(file, "utf-8");
177
+ const lines = content.split("\n");
178
+ for (const line of lines) {
179
+ const trimmed = line.trim();
180
+ if (trimmed.startsWith("import ")) {
181
+ const match = trimmed.match(/from\s+['"]([^'"]+)['"]/);
182
+ if (match && !match[1].startsWith(".")) {
183
+ if (!imports.has(match[1])) {
184
+ imports.set(match[1], /* @__PURE__ */ new Set());
185
+ }
186
+ const specMatch = trimmed.match(/\{([^}]+)\}/);
187
+ if (specMatch) {
188
+ specMatch[1].split(",").forEach((s) => {
189
+ imports.get(match[1]).add(s.trim());
190
+ });
191
+ }
192
+ }
193
+ continue;
194
+ }
195
+ if (trimmed.startsWith("import ") || trimmed === "") continue;
196
+ declarations.push(line);
197
+ }
198
+ }
199
+ for (const [source, specifiers] of imports) {
200
+ if (specifiers.size > 0) {
201
+ contents.push(`import { ${Array.from(specifiers).join(", ")} } from '${source}';`);
202
+ }
203
+ }
204
+ if (imports.size > 0) {
205
+ contents.push("");
206
+ }
207
+ contents.push(...declarations);
208
+ const outDir = dirname(outputPath);
209
+ if (!existsSync(outDir)) {
210
+ mkdirSync(outDir, { recursive: true });
211
+ }
212
+ writeFileSync(outputPath, contents.join("\n"));
213
+ console.log(`[dtsx] Bundled declarations to ${outputPath}`);
214
+ }
215
+ function dtsxCheck() {
216
+ return {
217
+ name: "dtsx-check",
218
+ setup(build) {
219
+ build.onEnd(async (result) => {
220
+ if (result.errors.length === 0) {
221
+ console.log("[dtsx-check] Build passed type checking");
222
+ }
223
+ });
224
+ }
225
+ };
226
+ }
227
+ function dtsxWatch(options = {}) {
228
+ return {
229
+ name: "dtsx-watch",
230
+ setup(build) {
231
+ const { onDeclarationChange } = options;
232
+ build.onResolve({ filter: /\.d\.ts$/ }, (args) => {
233
+ return {
234
+ path: args.path,
235
+ watchFiles: [args.path]
236
+ };
237
+ });
238
+ build.onLoad({ filter: /\.d\.ts$/ }, (args) => {
239
+ onDeclarationChange?.(args.path);
240
+ return null;
241
+ });
242
+ }
243
+ };
244
+ }
245
+ var index_default = dtsx;
246
+ export {
247
+ index_default as default,
248
+ dtsx,
249
+ dtsxCheck,
250
+ dtsxWatch
251
+ };
package/package.json ADDED
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "esbuild-plugin-dtsx",
3
+ "type": "module",
4
+ "version": "0.9.10",
5
+ "description": "An esbuild plugin that auto generates your DTS types extremely fast.",
6
+ "author": "Chris Breuer <chris@ow3.org>",
7
+ "license": "MIT",
8
+ "homepage": "https://github.com/stacksjs/dtsx/tree/main/packages/esbuild-plugin#readme",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/stacksjs/dtsx.git"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/stacksjs/dtsx/issues"
15
+ },
16
+ "keywords": [
17
+ "dts",
18
+ "dtsx",
19
+ "emit",
20
+ "generation",
21
+ "typescript",
22
+ "types",
23
+ "auto",
24
+ "stacks",
25
+ "esbuild",
26
+ "plugin",
27
+ "package"
28
+ ],
29
+ "exports": {
30
+ ".": {
31
+ "types": "./dist/index.d.ts",
32
+ "import": "./dist/index.js"
33
+ },
34
+ "./*": {
35
+ "import": "./dist/*"
36
+ }
37
+ },
38
+ "module": "./dist/index.js",
39
+ "types": "./dist/index.d.ts",
40
+ "files": [
41
+ "LICENSE.md",
42
+ "README.md",
43
+ "dist"
44
+ ],
45
+ "scripts": {
46
+ "build": "bun build.ts",
47
+ "prepublishOnly": "bun run build",
48
+ "test": "bun test",
49
+ "typecheck": "bun tsc --noEmit"
50
+ },
51
+ "dependencies": {
52
+ "@stacksjs/dtsx": "0.9.10"
53
+ },
54
+ "peerDependencies": {
55
+ "esbuild": ">=0.27.3"
56
+ }
57
+ }