bun-plugin-dtsx 0.9.8 → 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,149 @@
1
+ # bun-plugin-dtsx
2
+
3
+ A Bun Bundler plugin for automatic TypeScript declaration file generation using dtsx.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ bun add bun-plugin-dtsx -d
9
+ # or
10
+ npm install bun-plugin-dtsx --save-dev
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ ```typescript
16
+ // build.ts
17
+ import { dts } from 'bun-plugin-dtsx'
18
+
19
+ await Bun.build({
20
+ entrypoints: ['src/index.ts'],
21
+ outdir: 'dist',
22
+ plugins: [
23
+ dts({
24
+ // Options
25
+ }),
26
+ ],
27
+ })
28
+ ```
29
+
30
+ ## Options
31
+
32
+ | Option | Type | Default | Description |
33
+ |--------|------|---------|-------------|
34
+ | `trigger` | `'build' \| 'watch' \| 'both'` | `'build'` | When to generate declarations |
35
+ | `entryPointsOnly` | `boolean` | `true` | Only generate for entry points |
36
+ | `declarationDir` | `string` | Bun outdir | Output directory for declarations |
37
+ | `bundle` | `boolean` | `false` | Bundle all declarations into one file |
38
+ | `bundleOutput` | `string` | `'index.d.ts'` | Bundled output filename |
39
+ | `exclude` | `(string \| RegExp)[]` | `[]` | Patterns to exclude |
40
+ | `include` | `(string \| RegExp)[]` | `[]` | Patterns to include |
41
+ | `emitOnError` | `boolean` | `true` | Emit even with type errors |
42
+
43
+ ## Examples
44
+
45
+ ### Basic Usage
46
+
47
+ ```typescript
48
+ import { dts } from 'bun-plugin-dtsx'
49
+
50
+ await Bun.build({
51
+ entrypoints: ['src/index.ts'],
52
+ outdir: 'dist',
53
+ plugins: [dts()],
54
+ })
55
+ ```
56
+
57
+ ### With Bundled Declarations
58
+
59
+ ```typescript
60
+ import { dts } from 'bun-plugin-dtsx'
61
+
62
+ await Bun.build({
63
+ entrypoints: ['src/index.ts'],
64
+ outdir: 'dist',
65
+ plugins: [
66
+ dts({
67
+ bundle: true,
68
+ bundleOutput: 'types.d.ts',
69
+ }),
70
+ ],
71
+ })
72
+ ```
73
+
74
+ ### Multiple Entry Points
75
+
76
+ ```typescript
77
+ import { dts } from 'bun-plugin-dtsx'
78
+
79
+ await Bun.build({
80
+ entrypoints: ['src/index.ts', 'src/utils.ts'],
81
+ outdir: 'dist',
82
+ plugins: [
83
+ dts({
84
+ entryPointsOnly: true,
85
+ }),
86
+ ],
87
+ })
88
+ ```
89
+
90
+ ### With Callbacks
91
+
92
+ ```typescript
93
+ import { dts } from 'bun-plugin-dtsx'
94
+
95
+ await Bun.build({
96
+ entrypoints: ['src/index.ts'],
97
+ outdir: 'dist',
98
+ plugins: [
99
+ dts({
100
+ onStart: () => {
101
+ console.log('Starting declaration generation...')
102
+ },
103
+ onSuccess: (stats) => {
104
+ console.log(`Generated ${stats.totalFiles} files in ${stats.totalTime}ms`)
105
+ },
106
+ onError: (error) => {
107
+ console.error('Failed to generate declarations:', error.message)
108
+ },
109
+ }),
110
+ ],
111
+ })
112
+ ```
113
+
114
+ ### Filter Files
115
+
116
+ ```typescript
117
+ import { dts } from 'bun-plugin-dtsx'
118
+
119
+ await Bun.build({
120
+ entrypoints: ['src/index.ts'],
121
+ outdir: 'dist',
122
+ plugins: [
123
+ dts({
124
+ include: [/src\/lib/],
125
+ exclude: ['test', /\.spec\.ts$/],
126
+ }),
127
+ ],
128
+ })
129
+ ```
130
+
131
+ ### Custom Output Directory
132
+
133
+ ```typescript
134
+ import { dts } from 'bun-plugin-dtsx'
135
+
136
+ await Bun.build({
137
+ entrypoints: ['src/index.ts'],
138
+ outdir: 'dist',
139
+ plugins: [
140
+ dts({
141
+ declarationDir: 'types',
142
+ }),
143
+ ],
144
+ })
145
+ ```
146
+
147
+ ## License
148
+
149
+ MIT
package/dist/index.d.ts CHANGED
@@ -1,21 +1,110 @@
1
1
  import type { BunPlugin } from 'bun';
2
- import type { DtsGenerationOption } from '@stacksjs/dtsx';
3
- export type { DtsGenerationOption };
2
+ import type { DtsGenerationOption, GenerationStats } from '@stacksjs/dtsx';
3
+ export type { DtsGenerationOption, GenerationStats };
4
4
  /**
5
5
  * Creates a Bun plugin for generating TypeScript declaration files
6
6
  * @param options - Configuration options for DTS generation
7
7
  * @returns BunPlugin instance
8
8
  */
9
9
  export declare function dts(options?: PluginConfig): BunPlugin;
10
+ /**
11
+ * Create a watch mode plugin that regenerates on file changes
12
+ */
13
+ export declare function dtsWatch(options?: PluginConfig): BunPlugin;
14
+ /**
15
+ * Create a plugin that only validates types without generating
16
+ */
17
+ export declare function dtsCheck(options: Omit<PluginConfig, 'outdir'>): BunPlugin;
18
+ /**
19
+ * Clear the incremental cache
20
+ */
21
+ export declare function clearCache(cacheDir?: string): void;
22
+ /**
23
+ * Error codes for categorizing plugin errors
24
+ */
25
+ export declare const PluginErrorCodes: {
26
+ CONFIG_ERROR: 'CONFIG_ERROR';
27
+ GENERATION_ERROR: 'GENERATION_ERROR';
28
+ FILE_ERROR: 'FILE_ERROR';
29
+ CACHE_ERROR: 'CACHE_ERROR';
30
+ TIMEOUT_ERROR: 'TIMEOUT_ERROR'
31
+ };
32
+ /**
33
+ * Build event payload
34
+ */
35
+ export declare interface BuildEvent {
36
+ type: BuildEventType
37
+ timestamp: number
38
+ data: BuildEventData
39
+ }
40
+ /**
41
+ * Incremental cache entry
42
+ */
43
+ declare interface CacheEntry {
44
+ hash: string
45
+ outputFile: string
46
+ timestamp: number
47
+ }
10
48
  /**
11
49
  * Configuration interface extending DtsGenerationOption with build-specific properties
12
50
  */
13
- declare interface PluginConfig extends DtsGenerationOption {
51
+ export declare interface PluginConfig extends DtsGenerationOption {
14
52
  build?: {
15
53
  config: {
16
54
  root?: string
17
55
  outdir?: string
18
56
  }
19
57
  }
58
+ onSuccess?: (stats: GenerationStats) => void | Promise<void>
59
+ onError?: (error: DtsxPluginError) => void | Promise<void>
60
+ failOnError?: boolean
61
+ incremental?: boolean
62
+ cacheDir?: string
63
+ on?: Partial<Record<BuildEventType, BuildEventListener>>
64
+ timeout?: number
65
+ continueOnError?: boolean
66
+ verbose?: boolean
67
+ }
68
+ export type PluginErrorCode = typeof PluginErrorCodes[keyof typeof PluginErrorCodes];
69
+ /**
70
+ * Build event types
71
+ */
72
+ export type BuildEventType = 'start' | 'progress' | 'file' | 'complete' | 'error';
73
+ export type BuildEventData = | { type: 'start', files: string[], config: DtsGenerationOption }
74
+ | { type: 'progress', processed: number, total: number, currentFile: string }
75
+ | { type: 'file', file: string, outputFile: string, duration: number, cached: boolean }
76
+ | { type: 'complete', stats: GenerationStats, duration: number, fromCache: number }
77
+ | { type: 'error', error: DtsxPluginError, file?: string }
78
+ /**
79
+ * Event listener function
80
+ */
81
+ export type BuildEventListener = (_event: BuildEvent) => void | Promise<void>;
82
+ /**
83
+ * Custom error class for bun-plugin-dtsx
84
+ */
85
+ export declare class DtsxPluginError extends Error {
86
+ readonly code: PluginErrorCode;
87
+ readonly context?: Record<string, unknown>;
88
+ readonly cause?: Error;
89
+ constructor(message: string, code: PluginErrorCode, context?: Record<string, unknown>, cause?: Error);
90
+ toJSON(): Record<string, unknown>;
91
+ }
92
+ /**
93
+ * Event emitter for build events
94
+ */
95
+ declare class BuildEventEmitter {
96
+ on(type: BuildEventType, listener: BuildEventListener): void;
97
+ emit(type: BuildEventType, data: BuildEventData): Promise<void>;
98
+ }
99
+ /**
100
+ * Incremental cache manager
101
+ */
102
+ declare class IncrementalCache {
103
+ constructor(cacheDir: string, configHash: string);
104
+ save(): void;
105
+ getEntry(filePath: string): CacheEntry | undefined;
106
+ setEntry(filePath: string, entry: CacheEntry): void;
107
+ isValid(filePath: string, currentHash: string): boolean;
108
+ clear(): void;
20
109
  }
21
- export default dts;
110
+ export default dts;
package/dist/index.js CHANGED
@@ -1,24 +1,245 @@
1
1
  // @bun
2
+ var __require = import.meta.require;
3
+
2
4
  // src/index.ts
5
+ import { createHash } from "crypto";
6
+ import { existsSync, readFileSync, writeFileSync } from "fs";
7
+ import { join, resolve } from "path";
3
8
  import process from "process";
4
9
  import { generate } from "@stacksjs/dtsx";
5
- function dts(options = {
6
- root: "./src",
7
- outdir: "./dist"
8
- }) {
10
+ var PluginErrorCodes = {
11
+ CONFIG_ERROR: "CONFIG_ERROR",
12
+ GENERATION_ERROR: "GENERATION_ERROR",
13
+ FILE_ERROR: "FILE_ERROR",
14
+ CACHE_ERROR: "CACHE_ERROR",
15
+ TIMEOUT_ERROR: "TIMEOUT_ERROR"
16
+ };
17
+
18
+ class DtsxPluginError extends Error {
19
+ code;
20
+ context;
21
+ cause;
22
+ constructor(message, code, context, cause) {
23
+ super(message);
24
+ this.name = "DtsxPluginError";
25
+ this.code = code;
26
+ this.context = context;
27
+ this.cause = cause;
28
+ if (Error.captureStackTrace) {
29
+ Error.captureStackTrace(this, this.constructor);
30
+ }
31
+ }
32
+ toJSON() {
33
+ return {
34
+ name: this.name,
35
+ code: this.code,
36
+ message: this.message,
37
+ context: this.context,
38
+ stack: this.stack
39
+ };
40
+ }
41
+ }
42
+
43
+ class BuildEventEmitter {
44
+ listeners = new Map;
45
+ on(type, listener) {
46
+ const existing = this.listeners.get(type) || [];
47
+ existing.push(listener);
48
+ this.listeners.set(type, existing);
49
+ }
50
+ async emit(type, data) {
51
+ const event = {
52
+ type,
53
+ timestamp: Date.now(),
54
+ data
55
+ };
56
+ const listeners = this.listeners.get(type) || [];
57
+ for (const listener of listeners) {
58
+ await listener(event);
59
+ }
60
+ }
61
+ }
62
+
63
+ class IncrementalCache {
64
+ manifest;
65
+ cacheDir;
66
+ manifestPath;
67
+ constructor(cacheDir, configHash) {
68
+ this.cacheDir = cacheDir;
69
+ this.manifestPath = join(cacheDir, "manifest.json");
70
+ this.manifest = this.loadManifest(configHash);
71
+ }
72
+ loadManifest(configHash) {
73
+ try {
74
+ if (existsSync(this.manifestPath)) {
75
+ const data = JSON.parse(readFileSync(this.manifestPath, "utf-8"));
76
+ if (data.configHash === configHash && data.version === "1.0") {
77
+ return data;
78
+ }
79
+ }
80
+ } catch {}
81
+ return {
82
+ version: "1.0",
83
+ configHash,
84
+ entries: {}
85
+ };
86
+ }
87
+ save() {
88
+ try {
89
+ const { mkdirSync } = __require("fs");
90
+ mkdirSync(this.cacheDir, { recursive: true });
91
+ writeFileSync(this.manifestPath, JSON.stringify(this.manifest, null, 2));
92
+ } catch {}
93
+ }
94
+ getEntry(filePath) {
95
+ return this.manifest.entries[filePath];
96
+ }
97
+ setEntry(filePath, entry) {
98
+ this.manifest.entries[filePath] = entry;
99
+ }
100
+ isValid(filePath, currentHash) {
101
+ const entry = this.getEntry(filePath);
102
+ return entry?.hash === currentHash;
103
+ }
104
+ clear() {
105
+ this.manifest.entries = {};
106
+ this.save();
107
+ }
108
+ }
109
+ function computeConfigHash(config) {
110
+ const relevantConfig = {
111
+ root: config.root,
112
+ outdir: config.outdir,
113
+ entrypoints: config.entrypoints,
114
+ clean: config.clean,
115
+ tsconfigPath: config.tsconfigPath
116
+ };
117
+ return createHash("md5").update(JSON.stringify(relevantConfig)).digest("hex");
118
+ }
119
+ function dts(options = {}) {
120
+ const {
121
+ onSuccess,
122
+ onError,
123
+ failOnError = true,
124
+ incremental = false,
125
+ cacheDir = ".dtsx-cache",
126
+ on,
127
+ timeout = 60000,
128
+ continueOnError = false,
129
+ verbose = false,
130
+ ...dtsOptions
131
+ } = options;
132
+ const emitter = new BuildEventEmitter;
133
+ if (on) {
134
+ for (const [type, listener] of Object.entries(on)) {
135
+ if (listener) {
136
+ emitter.on(type, listener);
137
+ }
138
+ }
139
+ }
9
140
  return {
10
141
  name: "bun-plugin-dtsx",
11
142
  async setup(build) {
12
- const config = normalizeConfig(options, build);
13
- await generate(config);
143
+ const startTime = Date.now();
144
+ let cache = null;
145
+ const fromCache = 0;
146
+ try {
147
+ const config = normalizeConfig(dtsOptions, build);
148
+ const configHash = computeConfigHash(config);
149
+ if (incremental) {
150
+ cache = new IncrementalCache(resolve(cacheDir), configHash);
151
+ }
152
+ await emitter.emit("start", {
153
+ type: "start",
154
+ files: config.entrypoints || [],
155
+ config
156
+ });
157
+ if (verbose) {
158
+ console.log("[bun-plugin-dtsx] Starting declaration generation...");
159
+ if (incremental) {
160
+ console.log("[bun-plugin-dtsx] Incremental mode enabled");
161
+ }
162
+ }
163
+ const generateWithTimeout = async () => {
164
+ return new Promise((resolvePromise, rejectPromise) => {
165
+ const timeoutId = setTimeout(() => {
166
+ rejectPromise(new DtsxPluginError(`Generation timed out after ${timeout}ms`, "TIMEOUT_ERROR", { timeout }));
167
+ }, timeout);
168
+ generate(config).then((stats2) => {
169
+ clearTimeout(timeoutId);
170
+ resolvePromise(stats2);
171
+ }).catch((err) => {
172
+ clearTimeout(timeoutId);
173
+ rejectPromise(err);
174
+ });
175
+ });
176
+ };
177
+ const stats = await generateWithTimeout();
178
+ const duration = Date.now() - startTime;
179
+ if (cache) {
180
+ cache.save();
181
+ }
182
+ await emitter.emit("complete", {
183
+ type: "complete",
184
+ stats,
185
+ duration,
186
+ fromCache
187
+ });
188
+ if (verbose) {
189
+ console.log(`[bun-plugin-dtsx] Generation complete in ${duration}ms`);
190
+ if (fromCache > 0) {
191
+ console.log(`[bun-plugin-dtsx] ${fromCache} files served from cache`);
192
+ }
193
+ }
194
+ if (onSuccess) {
195
+ await onSuccess(stats);
196
+ }
197
+ } catch (error) {
198
+ const pluginError = wrapError(error);
199
+ await emitter.emit("error", {
200
+ type: "error",
201
+ error: pluginError
202
+ });
203
+ if (onError) {
204
+ await onError(pluginError);
205
+ } else {
206
+ console.error("[bun-plugin-dtsx] Error generating declarations:");
207
+ console.error(` Code: ${pluginError.code}`);
208
+ console.error(` Message: ${pluginError.message}`);
209
+ if (pluginError.context) {
210
+ console.error(` Context: ${JSON.stringify(pluginError.context)}`);
211
+ }
212
+ if (verbose && pluginError.stack) {
213
+ console.error(` Stack: ${pluginError.stack}`);
214
+ }
215
+ }
216
+ if (failOnError && !continueOnError) {
217
+ throw pluginError;
218
+ }
219
+ }
14
220
  }
15
221
  };
16
222
  }
223
+ function wrapError(error) {
224
+ if (error instanceof DtsxPluginError) {
225
+ return error;
226
+ }
227
+ if (error instanceof Error) {
228
+ let code = "GENERATION_ERROR";
229
+ if (error.message.includes("config") || error.message.includes("Config")) {
230
+ code = "CONFIG_ERROR";
231
+ } else if (error.message.includes("file") || error.message.includes("File") || error.message.includes("ENOENT")) {
232
+ code = "FILE_ERROR";
233
+ }
234
+ return new DtsxPluginError(error.message, code, { originalError: error.name }, error);
235
+ }
236
+ return new DtsxPluginError(String(error), "GENERATION_ERROR");
237
+ }
17
238
  function normalizeConfig(options, build) {
18
- const root = options.root || build?.config.root;
19
- const outdir = options.outdir || build?.config.outdir;
239
+ const root = options.root || options.build?.config.root || build?.config.root || "./src";
240
+ const outdir = options.outdir || options.build?.config.outdir || build?.config.outdir || "./dist";
20
241
  if (!root) {
21
- throw new Error("[bun-plugin-dtsx] Root directory is required");
242
+ throw new DtsxPluginError("Root directory is required", "CONFIG_ERROR", { providedRoot: root });
22
243
  }
23
244
  return {
24
245
  ...options,
@@ -30,8 +251,43 @@ function normalizeConfig(options, build) {
30
251
  tsconfigPath: options.tsconfigPath
31
252
  };
32
253
  }
254
+ function dtsWatch(options = {}) {
255
+ return dts({
256
+ ...options,
257
+ incremental: true,
258
+ verbose: options.verbose ?? true
259
+ });
260
+ }
261
+ function dtsCheck(options) {
262
+ return {
263
+ name: "bun-plugin-dtsx-check",
264
+ async setup(build) {
265
+ const config = normalizeConfig({ ...options, outdir: "" }, build);
266
+ try {
267
+ await generate({ ...config, clean: false });
268
+ } catch (error) {
269
+ const pluginError = wrapError(error);
270
+ if (options.onError) {
271
+ await options.onError(pluginError);
272
+ }
273
+ if (options.failOnError !== false) {
274
+ throw pluginError;
275
+ }
276
+ }
277
+ }
278
+ };
279
+ }
280
+ function clearCache(cacheDir = ".dtsx-cache") {
281
+ const cache = new IncrementalCache(resolve(cacheDir), "");
282
+ cache.clear();
283
+ }
33
284
  var src_default = dts;
34
285
  export {
286
+ dtsWatch,
287
+ dtsCheck,
35
288
  dts,
36
- src_default as default
289
+ src_default as default,
290
+ clearCache,
291
+ PluginErrorCodes,
292
+ DtsxPluginError
37
293
  };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "bun-plugin-dtsx",
3
3
  "type": "module",
4
- "version": "0.9.8",
4
+ "version": "0.9.10",
5
5
  "description": "A Bun Bundler plugin that auto generates your DTS types extremely fast.",
6
6
  "author": "Chris Breuer <chris@ow3.org>",
7
7
  "license": "MIT",
@@ -49,6 +49,6 @@
49
49
  "typecheck": "bun tsc --noEmit"
50
50
  },
51
51
  "dependencies": {
52
- "@stacksjs/dtsx": "0.9.7"
52
+ "@stacksjs/dtsx": "0.9.10"
53
53
  }
54
54
  }