rsbuild-plugin-dts 0.5.0 → 0.5.2

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 CHANGED
@@ -228,8 +228,8 @@ Whether to automatically redirect the file extension to import paths based on th
228
228
  import { foo } from './foo'; // source code of './src/bar.ts' ↓
229
229
  import { foo } from './foo.mjs'; // expected output of './dist/bar.d.mts'
230
230
 
231
- import { foo } from './foo.ts'; // source code of './src/utils/index.ts' ↓
232
- import { foo } from './foo.mjs'; // expected output './dist/utils/index.d.mts'
231
+ import { foo } from './foo.ts'; // source code of './src/bar.ts' ↓
232
+ import { foo } from './foo.mjs'; // expected output of './dist/bar.d.mts'
233
233
  ```
234
234
 
235
235
  - When set to `false`, the file extension will remain unchanged from the original import path in the rewritten import path of the output file (regardless of whether it is specified or specified as any value).
@@ -6,7 +6,7 @@ export type BundleOptions = {
6
6
  dtsExtension: string;
7
7
  banner?: string;
8
8
  footer?: string;
9
- dtsEntry: DtsEntry;
9
+ dtsEntry: DtsEntry[];
10
10
  tsconfigPath?: string;
11
11
  bundledPackages?: string[];
12
12
  };
@@ -4,37 +4,36 @@ import * as __WEBPACK_EXTERNAL_MODULE__rsbuild_core_1b356efc__ from "@rsbuild/co
4
4
  import * as __WEBPACK_EXTERNAL_MODULE_picocolors__ from "picocolors";
5
5
  import * as __WEBPACK_EXTERNAL_MODULE__utils_js_d88b7fe1__ from "./utils.js";
6
6
  async function bundleDts(options) {
7
- const { name, cwd, distPath, dtsExtension, banner, footer, dtsEntry = {
8
- name: 'index',
9
- path: 'index.d.ts'
10
- }, tsconfigPath = 'tsconfig.json', bundledPackages = [] } = options;
7
+ const { name, cwd, distPath, dtsExtension, banner, footer, dtsEntry, tsconfigPath = 'tsconfig.json', bundledPackages = [] } = options;
11
8
  try {
12
- const start = Date.now();
13
- const untrimmedFilePath = (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.join)(cwd, (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.relative)(cwd, distPath), `${dtsEntry.name}${dtsExtension}`);
14
- const mainEntryPointFilePath = dtsEntry.path.replace(/\?.*$/, '');
15
- const internalConfig = {
16
- mainEntryPointFilePath,
17
- bundledPackages,
18
- dtsRollup: {
19
- enabled: true,
20
- untrimmedFilePath
21
- },
22
- compiler: {
23
- tsconfigFilePath: tsconfigPath
24
- },
25
- projectFolder: cwd
26
- };
27
- const extractorConfig = __WEBPACK_EXTERNAL_MODULE__microsoft_api_extractor_99b102c2__.ExtractorConfig.prepare({
28
- configObject: internalConfig,
29
- configObjectFullPath: void 0,
30
- packageJsonFullPath: (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.join)(cwd, 'package.json')
31
- });
32
- const extractorResult = __WEBPACK_EXTERNAL_MODULE__microsoft_api_extractor_99b102c2__.Extractor.invoke(extractorConfig, {
33
- localBuild: true
34
- });
35
- if (!extractorResult.succeeded) throw new Error(`API Extractor error. ${__WEBPACK_EXTERNAL_MODULE_picocolors__["default"].gray(`(${name})`)}`);
36
- await (0, __WEBPACK_EXTERNAL_MODULE__utils_js_d88b7fe1__.addBannerAndFooter)(untrimmedFilePath, banner, footer);
37
- __WEBPACK_EXTERNAL_MODULE__rsbuild_core_1b356efc__.logger.info(`API Extractor bundle DTS succeeded: ${__WEBPACK_EXTERNAL_MODULE_picocolors__["default"].cyan(untrimmedFilePath)} in ${(0, __WEBPACK_EXTERNAL_MODULE__utils_js_d88b7fe1__.getTimeCost)(start)} ${__WEBPACK_EXTERNAL_MODULE_picocolors__["default"].gray(`(${name})`)}`);
9
+ await Promise.all(dtsEntry.map(async (entry)=>{
10
+ const start = Date.now();
11
+ const untrimmedFilePath = (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.join)(cwd, (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.relative)(cwd, distPath), `${entry.name}${dtsExtension}`);
12
+ const mainEntryPointFilePath = entry.path.replace(/\?.*$/, '');
13
+ const internalConfig = {
14
+ mainEntryPointFilePath,
15
+ bundledPackages,
16
+ dtsRollup: {
17
+ enabled: true,
18
+ untrimmedFilePath
19
+ },
20
+ compiler: {
21
+ tsconfigFilePath: tsconfigPath
22
+ },
23
+ projectFolder: cwd
24
+ };
25
+ const extractorConfig = __WEBPACK_EXTERNAL_MODULE__microsoft_api_extractor_99b102c2__.ExtractorConfig.prepare({
26
+ configObject: internalConfig,
27
+ configObjectFullPath: void 0,
28
+ packageJsonFullPath: (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.join)(cwd, 'package.json')
29
+ });
30
+ const extractorResult = __WEBPACK_EXTERNAL_MODULE__microsoft_api_extractor_99b102c2__.Extractor.invoke(extractorConfig, {
31
+ localBuild: true
32
+ });
33
+ if (!extractorResult.succeeded) throw new Error(`API Extractor error. ${__WEBPACK_EXTERNAL_MODULE_picocolors__["default"].gray(`(${name})`)}`);
34
+ await (0, __WEBPACK_EXTERNAL_MODULE__utils_js_d88b7fe1__.addBannerAndFooter)(untrimmedFilePath, banner, footer);
35
+ __WEBPACK_EXTERNAL_MODULE__rsbuild_core_1b356efc__.logger.info(`API Extractor bundle DTS succeeded: ${__WEBPACK_EXTERNAL_MODULE_picocolors__["default"].cyan(untrimmedFilePath)} in ${(0, __WEBPACK_EXTERNAL_MODULE__utils_js_d88b7fe1__.getTimeCost)(start)} ${__WEBPACK_EXTERNAL_MODULE_picocolors__["default"].gray(`(${name})`)}`);
36
+ }));
38
37
  } catch (e) {
39
38
  __WEBPACK_EXTERNAL_MODULE__rsbuild_core_1b356efc__.logger.error('API Extractor Error');
40
39
  throw new Error(`${e}`);
package/dist/dts.js CHANGED
@@ -68,13 +68,18 @@ async function generateDts(data) {
68
68
  }
69
69
  }
70
70
  const declarationDir = bundle ? (0, __WEBPACK_EXTERNAL_MODULE__utils_js_d88b7fe1__.ensureTempDeclarationDir)(cwd, name) : dtsEmitPath;
71
- const { name: entryName, path: entryPath } = dtsEntry;
72
- let entry = '';
73
- if (true === bundle && entryPath) {
71
+ let dtsEntries = [];
72
+ if (true === bundle) dtsEntries = dtsEntry.map((entryObj)=>{
73
+ const { name: entryName, path: entryPath } = entryObj;
74
+ if (!entryPath) return null;
74
75
  const entrySourcePath = (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.isAbsolute)(entryPath) ? entryPath : (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.join)(cwd, entryPath);
75
76
  const relativePath = (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.relative)(rootDir, (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.dirname)(entrySourcePath));
76
- entry = (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.join)(declarationDir, relativePath, (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.basename)(entrySourcePath)).replace(/\?.*$/, '').replace(/\.(js|mjs|jsx|ts|mts|tsx|cjs|cts|cjsx|ctsx|mjsx|mtsx)$/, '.d.ts');
77
- }
77
+ const newPath = (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.join)(declarationDir, relativePath, (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.basename)(entrySourcePath)).replace(/\?.*$/, '').replace(/\.(js|mjs|jsx|ts|mts|tsx|cjs|cts|cjsx|ctsx|mjsx|mtsx)$/, '.d.ts');
78
+ return {
79
+ name: entryName,
80
+ path: newPath
81
+ };
82
+ }).filter(Boolean);
78
83
  const bundleDtsIfNeeded = async ()=>{
79
84
  if (true === bundle) {
80
85
  const { bundleDts } = await import("./apiExtractor.js");
@@ -82,10 +87,7 @@ async function generateDts(data) {
82
87
  name,
83
88
  cwd,
84
89
  distPath: dtsEmitPath,
85
- dtsEntry: {
86
- name: entryName,
87
- path: entry
88
- },
90
+ dtsEntry: dtsEntries,
89
91
  tsconfigPath,
90
92
  dtsExtension,
91
93
  banner,
package/dist/index.d.ts CHANGED
@@ -27,7 +27,7 @@ export type DtsGenOptions = PluginDtsOptions & {
27
27
  name: string;
28
28
  cwd: string;
29
29
  isWatch: boolean;
30
- dtsEntry: DtsEntry;
30
+ dtsEntry: DtsEntry[];
31
31
  dtsEmitPath: string;
32
32
  build?: boolean;
33
33
  tsconfigPath: string;
package/dist/index.js CHANGED
@@ -32,10 +32,13 @@ const pluginDts = (options = {})=>({
32
32
  }
33
33
  const tsConfigResult = (0, __WEBPACK_EXTERNAL_MODULE__utils_js_d88b7fe1__.loadTsconfig)(tsconfigPath);
34
34
  const { options: rawCompilerOptions } = tsConfigResult;
35
- const dtsEmitPath = options.distPath ?? rawCompilerOptions.declarationDir ?? config.output?.distPath?.root;
35
+ const { declarationDir, outDir, composite, incremental } = rawCompilerOptions;
36
+ const dtsEmitPath = (0, __WEBPACK_EXTERNAL_MODULE__utils_js_d88b7fe1__.getDtsEmitPath)(options.distPath, declarationDir, config.output?.distPath?.root);
37
+ (0, __WEBPACK_EXTERNAL_MODULE__utils_js_d88b7fe1__.warnIfOutside)(cwd, declarationDir, 'declarationDir');
38
+ (0, __WEBPACK_EXTERNAL_MODULE__utils_js_d88b7fe1__.warnIfOutside)(cwd, outDir, 'outDir');
36
39
  if (false !== config.output.cleanDistPath) await (0, __WEBPACK_EXTERNAL_MODULE__utils_js_d88b7fe1__.cleanDtsFiles)(dtsEmitPath);
37
40
  if (options.bundle) await (0, __WEBPACK_EXTERNAL_MODULE__utils_js_d88b7fe1__.clearTempDeclarationDir)(cwd);
38
- if (rawCompilerOptions.composite || rawCompilerOptions.incremental || options.build) await (0, __WEBPACK_EXTERNAL_MODULE__utils_js_d88b7fe1__.cleanTsBuildInfoFile)(tsconfigPath, rawCompilerOptions);
41
+ if (composite || incremental || options.build) await (0, __WEBPACK_EXTERNAL_MODULE__utils_js_d88b7fe1__.cleanTsBuildInfoFile)(tsconfigPath, rawCompilerOptions);
39
42
  const jsExtension = (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.extname)(src_rslib_entry_filename);
40
43
  const childProcess = (0, __WEBPACK_EXTERNAL_MODULE_node_child_process_27f17141__.fork)((0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.join)(src_rslib_entry_dirname, `./dts${jsExtension}`), [], {
41
44
  stdio: 'inherit'
package/dist/utils.d.ts CHANGED
@@ -8,6 +8,7 @@ export declare const TEMP_FOLDER = ".rslib";
8
8
  export declare const TEMP_DTS_DIR: string;
9
9
  export declare function ensureTempDeclarationDir(cwd: string, name: string): string;
10
10
  export declare function pathExists(path: string): Promise<boolean>;
11
+ export declare function isDirectory(filePath: string): Promise<boolean>;
11
12
  export declare function emptyDir(dir: string): Promise<void>;
12
13
  export declare function clearTempDeclarationDir(cwd: string): Promise<void>;
13
14
  export declare function getFileLoc(diagnostic: ts.Diagnostic, configPath: string): string;
@@ -16,7 +17,9 @@ export declare function getTimeCost(start: number): string;
16
17
  export declare function addBannerAndFooter(dtsFile: string, banner?: string, footer?: string): Promise<void>;
17
18
  export declare function redirectDtsImports(dtsFile: string, dtsExtension: string, redirect: DtsRedirect, matchPath: MatchPath, outDir: string, rootDir: string): Promise<void>;
18
19
  export declare function processDtsFiles(bundle: boolean, dir: string, dtsExtension: string, redirect: DtsRedirect, tsconfigPath: string, rootDir: string, banner?: string, footer?: string): Promise<void>;
19
- export declare function processSourceEntry(bundle: boolean, entryConfig: NonNullable<RsbuildConfig['source']>['entry']): DtsEntry;
20
+ export declare function processSourceEntry(bundle: boolean, entryConfig: NonNullable<RsbuildConfig['source']>['entry']): DtsEntry[];
20
21
  export declare function calcLongestCommonPath(absPaths: string[]): Promise<string | null>;
21
22
  export declare function cleanDtsFiles(dir: string): Promise<void>;
22
23
  export declare function cleanTsBuildInfoFile(tsconfigPath: string, compilerOptions: ts.CompilerOptions): Promise<void>;
24
+ export declare function getDtsEmitPath(pathFromPlugin: string | undefined, declarationDir: string | undefined, distPath: string): string;
25
+ export declare function warnIfOutside(cwd: string, dir: string | undefined, label: string): void;
package/dist/utils.js CHANGED
@@ -44,6 +44,14 @@ function ensureTempDeclarationDir(cwd, name) {
44
44
  async function pathExists(path) {
45
45
  return __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].promises.access(path).then(()=>true).catch(()=>false);
46
46
  }
47
+ async function isDirectory(filePath) {
48
+ try {
49
+ const stat = await __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__["default"].stat(filePath);
50
+ return stat.isDirectory();
51
+ } catch {
52
+ return false;
53
+ }
54
+ }
47
55
  async function emptyDir(dir) {
48
56
  if (!await pathExists(dir)) return;
49
57
  try {
@@ -92,6 +100,12 @@ async function addBannerAndFooter(dtsFile, banner, footer) {
92
100
  if (footer && !content.trimEnd().endsWith(footer.trim())) code.append(`\n${footer}\n`);
93
101
  if (code.hasChanged()) await __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__["default"].writeFile(dtsFile, code.toString());
94
102
  }
103
+ async function addExtension(redirect, dtsFile, path, extension) {
104
+ if (!redirect.extension) return path;
105
+ let redirectPath = path;
106
+ if (await isDirectory((0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.join)((0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.dirname)(dtsFile), redirectPath))) redirectPath = `${redirectPath}/index`;
107
+ return `${redirectPath}${extension}`;
108
+ }
95
109
  async function redirectDtsImports(dtsFile, dtsExtension, redirect, matchPath, outDir, rootDir) {
96
110
  const content = await __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__["default"].readFile(dtsFile, 'utf-8');
97
111
  const code = new __WEBPACK_EXTERNAL_MODULE_magic_string_758c1a52__["default"](content);
@@ -137,7 +151,7 @@ async function redirectDtsImports(dtsFile, dtsExtension, redirect, matchPath, ou
137
151
  s: matchNode.range().start.index,
138
152
  e: matchNode.range().end.index
139
153
  }));
140
- const extensions = dtsExtension.replace(/\.d\.ts$/, '.js').replace(/\.d\.cts$/, '.cjs').replace(/\.d\.mts$/, '.mjs');
154
+ const extension = dtsExtension.replace(/\.d\.ts$/, '.js').replace(/\.d\.cts$/, '.cjs').replace(/\.d\.mts$/, '.mjs');
141
155
  for (const imp of matchModule){
142
156
  const { n: importPath, s: start, e: end } = imp;
143
157
  if (!!importPath) try {
@@ -167,15 +181,11 @@ async function redirectDtsImports(dtsFile, dtsExtension, redirect, matchPath, ou
167
181
  const ext = (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.extname)(redirectImportPath);
168
182
  if (ext) {
169
183
  if (JS_EXTENSIONS_PATTERN.test(redirectImportPath)) {
170
- if (redirect.extension) redirectImportPath = redirectImportPath.replace(/\.[^.]+$/, extensions);
184
+ if (redirect.extension) redirectImportPath = redirectImportPath.replace(/\.[^.]+$/, extension);
171
185
  }
172
186
  } else {
173
- if (absoluteImportPath && (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.normalize)(absoluteImportPath).startsWith((0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.normalize)(rootDir))) {
174
- if (redirect.extension) redirectImportPath = `${redirectImportPath}${extensions}`;
175
- }
176
- if (!absoluteImportPath && importPath.startsWith('.')) {
177
- if (redirect.extension) redirectImportPath = `${redirectImportPath}${extensions}`;
178
- }
187
+ if (absoluteImportPath && (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.normalize)(absoluteImportPath).startsWith((0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.normalize)(rootDir))) redirectImportPath = await addExtension(redirect, dtsFile, redirectImportPath, extension);
188
+ if (!absoluteImportPath && importPath.startsWith('.')) redirectImportPath = await addExtension(redirect, dtsFile, redirectImportPath, extension);
179
189
  }
180
190
  const normalizedRedirectImportPath = redirectImportPath.split(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].sep).join('/');
181
191
  code.overwrite(start, end, normalizedRedirectImportPath);
@@ -210,15 +220,12 @@ async function processDtsFiles(bundle, dir, dtsExtension, redirect, tsconfigPath
210
220
  }
211
221
  }
212
222
  function processSourceEntry(bundle, entryConfig) {
213
- if (!bundle) return {
214
- name: void 0,
215
- path: void 0
216
- };
217
- if (entryConfig && Object.values(entryConfig).every((val)=>'string' == typeof val)) return {
218
- name: Object.keys(entryConfig)[0],
219
- path: Object.values(entryConfig)[0]
220
- };
221
- throw new Error('@microsoft/api-extractor only support single entry of Record<string, string> type to bundle DTS, please check your entry config.');
223
+ if (!bundle) return [];
224
+ if (entryConfig && Object.values(entryConfig).every((val)=>'string' == typeof val)) return Object.entries(entryConfig).map(([name, path])=>({
225
+ name,
226
+ path
227
+ }));
228
+ throw new Error('@microsoft/api-extractor only support entry of Record<string, string> type to bundle DTS, please check your entry config.');
222
229
  }
223
230
  async function calcLongestCommonPath(absPaths) {
224
231
  if (0 === absPaths.length) return null;
@@ -260,4 +267,15 @@ async function cleanTsBuildInfoFile(tsconfigPath, compilerOptions) {
260
267
  force: true
261
268
  });
262
269
  }
263
- export { JS_EXTENSIONS_PATTERN, TEMP_DTS_DIR, TEMP_FOLDER, addBannerAndFooter, calcLongestCommonPath, cleanDtsFiles, cleanTsBuildInfoFile, clearTempDeclarationDir, emptyDir, ensureTempDeclarationDir, getFileLoc, getTimeCost, loadTsconfig, pathExists, prettyTime, processDtsFiles, processSourceEntry, redirectDtsImports };
270
+ function getDtsEmitPath(pathFromPlugin, declarationDir, distPath) {
271
+ return pathFromPlugin ?? declarationDir ?? distPath;
272
+ }
273
+ function warnIfOutside(cwd, dir, label) {
274
+ if (dir) {
275
+ const normalizedCwd = (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.normalize)(cwd);
276
+ const normalizedDir = (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.normalize)(dir);
277
+ const relDir = (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.relative)(normalizedCwd, normalizedDir);
278
+ if (relDir.startsWith('..')) __WEBPACK_EXTERNAL_MODULE__rsbuild_core_1b356efc__.logger.warn(`The resolved ${label} ${__WEBPACK_EXTERNAL_MODULE_picocolors__["default"].cyan(normalizedDir)} is outside the project root ${__WEBPACK_EXTERNAL_MODULE_picocolors__["default"].cyan(normalizedCwd)}, please check your tsconfig file.`);
279
+ }
280
+ }
281
+ export { JS_EXTENSIONS_PATTERN, TEMP_DTS_DIR, TEMP_FOLDER, addBannerAndFooter, calcLongestCommonPath, cleanDtsFiles, cleanTsBuildInfoFile, clearTempDeclarationDir, emptyDir, ensureTempDeclarationDir, getDtsEmitPath, getFileLoc, getTimeCost, isDirectory, loadTsconfig, pathExists, prettyTime, processDtsFiles, processSourceEntry, redirectDtsImports, warnIfOutside };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rsbuild-plugin-dts",
3
- "version": "0.5.0",
3
+ "version": "0.5.2",
4
4
  "description": "Rsbuild plugin that supports emitting declaration files for TypeScript.",
5
5
  "homepage": "https://lib.rsbuild.dev",
6
6
  "bugs": {
@@ -28,14 +28,14 @@
28
28
  "@ast-grep/napi": "^0.35.0",
29
29
  "magic-string": "^0.30.17",
30
30
  "picocolors": "1.1.1",
31
- "tinyglobby": "^0.2.11",
31
+ "tinyglobby": "^0.2.12",
32
32
  "tsconfig-paths": "^4.2.0"
33
33
  },
34
34
  "devDependencies": {
35
- "@microsoft/api-extractor": "^7.50.0",
36
- "@rsbuild/core": "~1.2.9",
35
+ "@microsoft/api-extractor": "^7.50.1",
36
+ "@rsbuild/core": "~1.2.10",
37
37
  "rsbuild-plugin-publint": "^0.3.0",
38
- "rslib": "npm:@rslib/core@0.4.1",
38
+ "rslib": "npm:@rslib/core@0.5.1",
39
39
  "typescript": "^5.7.3",
40
40
  "@rslib/tsconfig": "0.0.1"
41
41
  },
@@ -53,7 +53,7 @@
53
53
  }
54
54
  },
55
55
  "engines": {
56
- "node": ">=16.0.0"
56
+ "node": ">=16.7.0"
57
57
  },
58
58
  "publishConfig": {
59
59
  "access": "public",