rsbuild-plugin-dts 0.0.15 → 0.0.17

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
@@ -4,7 +4,7 @@
4
4
 
5
5
  # Rslib
6
6
 
7
- Rslib is a library build tool powered by [Rsbuild](https://rsbuild.dev). It allows library developers to leverage the knowledge and ecosystem of webpack and Rspack.
7
+ Rslib is a library development tool powered by [Rsbuild](https://rsbuild.dev). It allows library developers to leverage the knowledge and ecosystem of webpack and Rspack.
8
8
 
9
9
  ## Documentation
10
10
 
package/dist/dts.js CHANGED
@@ -56,7 +56,7 @@ const calcBundledPackages = (options)=>{
56
56
  return Array.from(new Set(bundledPackages));
57
57
  };
58
58
  async function generateDts(data) {
59
- const { bundle, distPath, dtsEntry, tsconfigPath, name, cwd, isWatch, dtsExtension = '.d.ts', autoExternal = true, userExternals, banner, footer } = data;
59
+ const { bundle, distPath, dtsEntry, tsconfigPath, name, cwd, build, isWatch, dtsExtension = '.d.ts', autoExternal = true, userExternals, banner, footer } = data;
60
60
  __WEBPACK_EXTERNAL_MODULE__rsbuild_core__.logger.start(`Generating DTS... ${__WEBPACK_EXTERNAL_MODULE_picocolors__["default"].gray(`(${name})`)}`);
61
61
  const configPath = __WEBPACK_EXTERNAL_MODULE_typescript__["default"].findConfigFile(cwd, __WEBPACK_EXTERNAL_MODULE_typescript__["default"].sys.fileExists, tsconfigPath);
62
62
  if (!configPath) {
@@ -64,8 +64,20 @@ async function generateDts(data) {
64
64
  throw new Error();
65
65
  }
66
66
  const { options: rawCompilerOptions, fileNames } = (0, __WEBPACK_EXTERNAL_MODULE__utils_js__.loadTsconfig)(configPath);
67
- const rootDir = rawCompilerOptions.rootDir ?? await (0, __WEBPACK_EXTERNAL_MODULE__utils_js__.calcLongestCommonPath)(fileNames) ?? (0, __WEBPACK_EXTERNAL_MODULE_node_path__.dirname)(configPath);
67
+ // The longest common path of all non-declaration input files.
68
+ // If composite is set, the default is instead the directory containing the tsconfig.json file.
69
+ // see https://www.typescriptlang.org/tsconfig/#rootDir
70
+ const rootDir = rawCompilerOptions.rootDir ?? (rawCompilerOptions.composite ? (0, __WEBPACK_EXTERNAL_MODULE_node_path__.dirname)(configPath) : await (0, __WEBPACK_EXTERNAL_MODULE__utils_js__.calcLongestCommonPath)(fileNames.filter((fileName)=>!/\.d\.(ts|mts|cts)$/.test(fileName)))) ?? (0, __WEBPACK_EXTERNAL_MODULE_node_path__.dirname)(configPath);
68
71
  const outDir = distPath ? distPath : rawCompilerOptions.declarationDir || './dist';
72
+ if (build) {
73
+ // do not allow to use bundle DTS when 'build: true' since temp declarationDir should be set by user in tsconfig
74
+ if (bundle) throw Error('Can not set "dts.bundle: true" when "dts.build: true"');
75
+ // can not set '--declarationDir' or '--outDir' when 'build: true'.
76
+ if ((!rawCompilerOptions.outDir || (0, __WEBPACK_EXTERNAL_MODULE_node_path__.normalize)(rawCompilerOptions.outDir) !== (0, __WEBPACK_EXTERNAL_MODULE_node_path__.normalize)((0, __WEBPACK_EXTERNAL_MODULE_node_path__.resolve)((0, __WEBPACK_EXTERNAL_MODULE_node_path__.dirname)(configPath), outDir))) && (!rawCompilerOptions.declarationDir || (0, __WEBPACK_EXTERNAL_MODULE_node_path__.normalize)(rawCompilerOptions.declarationDir) !== (0, __WEBPACK_EXTERNAL_MODULE_node_path__.normalize)((0, __WEBPACK_EXTERNAL_MODULE_node_path__.resolve)((0, __WEBPACK_EXTERNAL_MODULE_node_path__.dirname)(configPath), outDir)))) {
77
+ const info = rawCompilerOptions.outDir && !rawCompilerOptions.declarationDir ? 'outDir' : 'declarationDir';
78
+ throw Error(`Please set ${info}: "${outDir}" in ${__WEBPACK_EXTERNAL_MODULE_picocolors__["default"].underline(configPath)} to keep it same as "dts.distPath" or "output.distPath" field in lib config.`);
79
+ }
80
+ }
69
81
  const getDeclarationDir = (bundle, distPath)=>{
70
82
  if (bundle) return (0, __WEBPACK_EXTERNAL_MODULE__utils_js__.ensureTempDeclarationDir)(cwd);
71
83
  return distPath ? distPath : rawCompilerOptions.declarationDir ?? './dist';
@@ -112,7 +124,7 @@ async function generateDts(data) {
112
124
  dtsExtension,
113
125
  banner,
114
126
  footer
115
- }, onComplete, bundle, isWatch);
127
+ }, onComplete, bundle, isWatch, build);
116
128
  if (!isWatch) await bundleDtsIfNeeded();
117
129
  }
118
130
  process.on('message', async (data)=>{
package/dist/index.d.ts CHANGED
@@ -2,6 +2,7 @@ import { type RsbuildConfig, type RsbuildPlugin } from '@rsbuild/core';
2
2
  export type PluginDtsOptions = {
3
3
  bundle?: boolean;
4
4
  distPath?: string;
5
+ build?: boolean;
5
6
  abortOnError?: boolean;
6
7
  dtsExtension?: string;
7
8
  autoExternal?: boolean | {
@@ -21,6 +22,7 @@ export type DtsGenOptions = PluginDtsOptions & {
21
22
  cwd: string;
22
23
  isWatch: boolean;
23
24
  dtsEntry: DtsEntry;
25
+ build?: boolean;
24
26
  tsconfigPath?: string;
25
27
  userExternals?: NonNullable<RsbuildConfig['output']>['externals'];
26
28
  };
package/dist/index.js CHANGED
@@ -8,13 +8,13 @@ const src_dirname = (0, __WEBPACK_EXTERNAL_MODULE_node_path__.dirname)(src_filen
8
8
  const PLUGIN_DTS_NAME = 'rsbuild:dts';
9
9
  // use ts compiler API to generate bundleless dts
10
10
  // use ts compiler API and api-extractor to generate dts bundle
11
- // TODO: support incremental build, to build one or more projects and their dependencies
12
11
  // TODO: deal alias in dts
13
12
  const pluginDts = (options)=>({
14
13
  name: PLUGIN_DTS_NAME,
15
14
  setup (api) {
16
15
  options.bundle = options.bundle ?? false;
17
16
  options.abortOnError = options.abortOnError ?? true;
17
+ options.build = options.build ?? false;
18
18
  const dtsPromises = [];
19
19
  let promisesResult = [];
20
20
  api.onBeforeEnvironmentCompile(({ isWatch, isFirstCompile, environment })=>{
package/dist/tsc.d.ts CHANGED
@@ -7,4 +7,4 @@ export type EmitDtsOptions = {
7
7
  banner?: string;
8
8
  footer?: string;
9
9
  };
10
- export declare function emitDts(options: EmitDtsOptions, onComplete: (isSuccess: boolean) => void, bundle?: boolean, isWatch?: boolean): Promise<void>;
10
+ export declare function emitDts(options: EmitDtsOptions, onComplete: (isSuccess: boolean) => void, bundle?: boolean, isWatch?: boolean, build?: boolean): Promise<void>;
package/dist/tsc.js CHANGED
@@ -2,7 +2,7 @@ import * as __WEBPACK_EXTERNAL_MODULE__rsbuild_core__ from "@rsbuild/core";
2
2
  import * as __WEBPACK_EXTERNAL_MODULE_picocolors__ from "picocolors";
3
3
  import * as __WEBPACK_EXTERNAL_MODULE_typescript__ from "typescript";
4
4
  import * as __WEBPACK_EXTERNAL_MODULE__utils_js__ from "./utils.js";
5
- async function emitDts(options, onComplete, bundle = false, isWatch = false) {
5
+ async function emitDts(options, onComplete, bundle = false, isWatch = false, build = false) {
6
6
  const start = Date.now();
7
7
  const { configPath, declarationDir, name, dtsExtension, banner, footer } = options;
8
8
  const configFileParseResult = (0, __WEBPACK_EXTERNAL_MODULE__utils_js__.loadTsconfig)(configPath);
@@ -14,63 +14,95 @@ async function emitDts(options, onComplete, bundle = false, isWatch = false) {
14
14
  declarationDir,
15
15
  emitDeclarationOnly: true
16
16
  };
17
+ const createProgram = __WEBPACK_EXTERNAL_MODULE_typescript__["default"].createSemanticDiagnosticsBuilderProgram;
18
+ const formatHost = {
19
+ getCanonicalFileName: (path)=>path,
20
+ getCurrentDirectory: __WEBPACK_EXTERNAL_MODULE_typescript__["default"].sys.getCurrentDirectory,
21
+ getNewLine: ()=>__WEBPACK_EXTERNAL_MODULE_typescript__["default"].sys.newLine
22
+ };
23
+ const reportDiagnostic = (diagnostic)=>{
24
+ const fileLoc = (0, __WEBPACK_EXTERNAL_MODULE__utils_js__.getFileLoc)(diagnostic, configPath);
25
+ __WEBPACK_EXTERNAL_MODULE__rsbuild_core__.logger.error(`${fileLoc} - ${__WEBPACK_EXTERNAL_MODULE_picocolors__["default"].red('error')} ${__WEBPACK_EXTERNAL_MODULE_picocolors__["default"].gray(`TS${diagnostic.code}:`)}`, __WEBPACK_EXTERNAL_MODULE_typescript__["default"].flattenDiagnosticMessageText(diagnostic.messageText, formatHost.getNewLine()));
26
+ };
27
+ const reportWatchStatusChanged = async (diagnostic, _newLine, _options, errorCount)=>{
28
+ const message = `${__WEBPACK_EXTERNAL_MODULE_typescript__["default"].flattenDiagnosticMessageText(diagnostic.messageText, formatHost.getNewLine())} ${__WEBPACK_EXTERNAL_MODULE_picocolors__["default"].gray(`(${name})`)}`;
29
+ // 6031: File change detected. Starting incremental compilation...
30
+ // 6032: Starting compilation in watch mode...
31
+ if (6031 === diagnostic.code || 6032 === diagnostic.code) __WEBPACK_EXTERNAL_MODULE__rsbuild_core__.logger.info(message);
32
+ // 6194: 0 errors or 2+ errors!
33
+ if (6194 === diagnostic.code) {
34
+ if (0 !== errorCount && errorCount) __WEBPACK_EXTERNAL_MODULE__rsbuild_core__.logger.error(message);
35
+ else {
36
+ __WEBPACK_EXTERNAL_MODULE__rsbuild_core__.logger.info(message);
37
+ onComplete(true);
38
+ }
39
+ await (0, __WEBPACK_EXTERNAL_MODULE__utils_js__.processDtsFiles)(bundle, declarationDir, dtsExtension, banner, footer);
40
+ }
41
+ // 6193: 1 error
42
+ if (6193 === diagnostic.code) {
43
+ __WEBPACK_EXTERNAL_MODULE__rsbuild_core__.logger.error(message);
44
+ await (0, __WEBPACK_EXTERNAL_MODULE__utils_js__.processDtsFiles)(bundle, declarationDir, dtsExtension, banner, footer);
45
+ }
46
+ };
47
+ const system = {
48
+ ...__WEBPACK_EXTERNAL_MODULE_typescript__["default"].sys
49
+ };
17
50
  if (isWatch) {
18
- const createProgram = __WEBPACK_EXTERNAL_MODULE_typescript__["default"].createSemanticDiagnosticsBuilderProgram;
19
- const formatHost = {
20
- getCanonicalFileName: (path)=>path,
21
- getCurrentDirectory: __WEBPACK_EXTERNAL_MODULE_typescript__["default"].sys.getCurrentDirectory,
22
- getNewLine: ()=>__WEBPACK_EXTERNAL_MODULE_typescript__["default"].sys.newLine
23
- };
24
- const reportDiagnostic = (diagnostic)=>{
25
- const fileLoc = (0, __WEBPACK_EXTERNAL_MODULE__utils_js__.getFileLoc)(diagnostic, configPath);
26
- __WEBPACK_EXTERNAL_MODULE__rsbuild_core__.logger.error(`${fileLoc} - ${__WEBPACK_EXTERNAL_MODULE_picocolors__["default"].red('error')} ${__WEBPACK_EXTERNAL_MODULE_picocolors__["default"].gray(`TS${diagnostic.code}:`)}`, __WEBPACK_EXTERNAL_MODULE_typescript__["default"].flattenDiagnosticMessageText(diagnostic.messageText, formatHost.getNewLine()));
27
- };
28
- const reportWatchStatusChanged = async (diagnostic, _newLine, _options, errorCount)=>{
29
- const message = `${__WEBPACK_EXTERNAL_MODULE_typescript__["default"].flattenDiagnosticMessageText(diagnostic.messageText, formatHost.getNewLine())} ${__WEBPACK_EXTERNAL_MODULE_picocolors__["default"].gray(`(${name})`)}`;
30
- // 6031: File change detected. Starting incremental compilation...
31
- // 6032: Starting compilation in watch mode...
32
- if (6031 === diagnostic.code || 6032 === diagnostic.code) __WEBPACK_EXTERNAL_MODULE__rsbuild_core__.logger.info(message);
33
- // 6194: 0 errors or 2+ errors!
34
- if (6194 === diagnostic.code) {
35
- if (0 === errorCount) {
36
- __WEBPACK_EXTERNAL_MODULE__rsbuild_core__.logger.info(message);
37
- onComplete(true);
38
- } else __WEBPACK_EXTERNAL_MODULE__rsbuild_core__.logger.error(message);
39
- await (0, __WEBPACK_EXTERNAL_MODULE__utils_js__.processDtsFiles)(bundle, declarationDir, dtsExtension, banner, footer);
51
+ // watch mode
52
+ if (build) {
53
+ // incremental build with project references
54
+ const host = __WEBPACK_EXTERNAL_MODULE_typescript__["default"].createSolutionBuilderWithWatchHost(system, createProgram, reportDiagnostic, void 0, reportWatchStatusChanged);
55
+ const solutionBuilder = __WEBPACK_EXTERNAL_MODULE_typescript__["default"].createSolutionBuilderWithWatch(host, [
56
+ configPath
57
+ ], compilerOptions, {
58
+ watch: true
59
+ });
60
+ solutionBuilder.build();
61
+ } else {
62
+ const host = __WEBPACK_EXTERNAL_MODULE_typescript__["default"].createWatchCompilerHost(configPath, compilerOptions, system, createProgram, reportDiagnostic, reportWatchStatusChanged);
63
+ __WEBPACK_EXTERNAL_MODULE_typescript__["default"].createWatchProgram(host);
64
+ }
65
+ } else {
66
+ // build mode
67
+ if (build) {
68
+ // incremental build with project references
69
+ let errorNumber = 0;
70
+ const reportErrorSummary = (errorCount)=>{
71
+ errorNumber = errorCount;
72
+ };
73
+ const host = __WEBPACK_EXTERNAL_MODULE_typescript__["default"].createSolutionBuilderHost(system, createProgram, reportDiagnostic, void 0, reportErrorSummary);
74
+ const solutionBuilder = __WEBPACK_EXTERNAL_MODULE_typescript__["default"].createSolutionBuilder(host, [
75
+ configPath
76
+ ], compilerOptions);
77
+ solutionBuilder.build();
78
+ await (0, __WEBPACK_EXTERNAL_MODULE__utils_js__.processDtsFiles)(bundle, declarationDir, dtsExtension, banner, footer);
79
+ if (errorNumber > 0) {
80
+ __WEBPACK_EXTERNAL_MODULE__rsbuild_core__.logger.error(`Failed to emit declaration files. ${__WEBPACK_EXTERNAL_MODULE_picocolors__["default"].gray(`(${name})`)}`);
81
+ throw new Error('DTS generation failed');
40
82
  }
41
- // 6193: 1 error
42
- if (6193 === diagnostic.code) {
43
- __WEBPACK_EXTERNAL_MODULE__rsbuild_core__.logger.error(message);
44
- await (0, __WEBPACK_EXTERNAL_MODULE__utils_js__.processDtsFiles)(bundle, declarationDir, dtsExtension, banner, footer);
83
+ } else {
84
+ const host = __WEBPACK_EXTERNAL_MODULE_typescript__["default"].createCompilerHost(compilerOptions);
85
+ const program = __WEBPACK_EXTERNAL_MODULE_typescript__["default"].createProgram({
86
+ rootNames: fileNames,
87
+ options: compilerOptions,
88
+ projectReferences,
89
+ host,
90
+ configFileParsingDiagnostics: __WEBPACK_EXTERNAL_MODULE_typescript__["default"].getConfigFileParsingDiagnostics(configFileParseResult)
91
+ });
92
+ const emitResult = program.emit();
93
+ const allDiagnostics = __WEBPACK_EXTERNAL_MODULE_typescript__["default"].getPreEmitDiagnostics(program).concat(emitResult.diagnostics);
94
+ const diagnosticMessages = [];
95
+ for (const diagnostic of allDiagnostics){
96
+ const fileLoc = (0, __WEBPACK_EXTERNAL_MODULE__utils_js__.getFileLoc)(diagnostic, configPath);
97
+ const message = `${fileLoc} - ${__WEBPACK_EXTERNAL_MODULE_picocolors__["default"].red('error')} ${__WEBPACK_EXTERNAL_MODULE_picocolors__["default"].gray(`TS${diagnostic.code}:`)} ${__WEBPACK_EXTERNAL_MODULE_typescript__["default"].flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine())}`;
98
+ diagnosticMessages.push(message);
99
+ }
100
+ await (0, __WEBPACK_EXTERNAL_MODULE__utils_js__.processDtsFiles)(bundle, declarationDir, dtsExtension, banner, footer);
101
+ if (diagnosticMessages.length) {
102
+ __WEBPACK_EXTERNAL_MODULE__rsbuild_core__.logger.error(`Failed to emit declaration files. ${__WEBPACK_EXTERNAL_MODULE_picocolors__["default"].gray(`(${name})`)}`);
103
+ for (const message of diagnosticMessages)__WEBPACK_EXTERNAL_MODULE__rsbuild_core__.logger.error(message);
104
+ throw new Error('DTS generation failed');
45
105
  }
46
- };
47
- const system = {
48
- ...__WEBPACK_EXTERNAL_MODULE_typescript__["default"].sys
49
- };
50
- const host = __WEBPACK_EXTERNAL_MODULE_typescript__["default"].createWatchCompilerHost(configPath, compilerOptions, system, createProgram, reportDiagnostic, reportWatchStatusChanged);
51
- __WEBPACK_EXTERNAL_MODULE_typescript__["default"].createWatchProgram(host);
52
- } else {
53
- const host = __WEBPACK_EXTERNAL_MODULE_typescript__["default"].createCompilerHost(compilerOptions);
54
- const program = __WEBPACK_EXTERNAL_MODULE_typescript__["default"].createProgram({
55
- rootNames: fileNames,
56
- options: compilerOptions,
57
- projectReferences,
58
- host,
59
- configFileParsingDiagnostics: __WEBPACK_EXTERNAL_MODULE_typescript__["default"].getConfigFileParsingDiagnostics(configFileParseResult)
60
- });
61
- const emitResult = program.emit();
62
- const allDiagnostics = __WEBPACK_EXTERNAL_MODULE_typescript__["default"].getPreEmitDiagnostics(program).concat(emitResult.diagnostics);
63
- const diagnosticMessages = [];
64
- for (const diagnostic of allDiagnostics){
65
- const fileLoc = (0, __WEBPACK_EXTERNAL_MODULE__utils_js__.getFileLoc)(diagnostic, configPath);
66
- const message = `${fileLoc} - ${__WEBPACK_EXTERNAL_MODULE_picocolors__["default"].red('error')} ${__WEBPACK_EXTERNAL_MODULE_picocolors__["default"].gray(`TS${diagnostic.code}:`)} ${__WEBPACK_EXTERNAL_MODULE_typescript__["default"].flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine())}`;
67
- diagnosticMessages.push(message);
68
- }
69
- await (0, __WEBPACK_EXTERNAL_MODULE__utils_js__.processDtsFiles)(bundle, declarationDir, dtsExtension, banner, footer);
70
- if (diagnosticMessages.length) {
71
- __WEBPACK_EXTERNAL_MODULE__rsbuild_core__.logger.error(`Failed to emit declaration files. ${__WEBPACK_EXTERNAL_MODULE_picocolors__["default"].gray(`(${name})`)}`);
72
- for (const message of diagnosticMessages)__WEBPACK_EXTERNAL_MODULE__rsbuild_core__.logger.error(message);
73
- throw new Error('DTS generation failed');
74
106
  }
75
107
  __WEBPACK_EXTERNAL_MODULE__rsbuild_core__.logger.ready(`DTS generated in ${(0, __WEBPACK_EXTERNAL_MODULE__utils_js__.getTimeCost)(start)} ${__WEBPACK_EXTERNAL_MODULE_picocolors__["default"].gray(`(${name})`)}`);
76
108
  }
package/dist/utils.js CHANGED
@@ -55,9 +55,9 @@ async function addBannerAndFooter(file, banner, footer) {
55
55
  if (!banner && !footer) return;
56
56
  const content = await __WEBPACK_EXTERNAL_MODULE_node_fs_promises__["default"].readFile(file, 'utf-8');
57
57
  const code = new __WEBPACK_EXTERNAL_MODULE_magic_string__["default"](content);
58
- banner && code.prepend(`${banner}\n`);
59
- footer && code.append(`\n${footer}\n`);
60
- await __WEBPACK_EXTERNAL_MODULE_node_fs_promises__["default"].writeFile(file, code.toString());
58
+ if (banner && !content.trimStart().startsWith(banner.trim())) code.prepend(`${banner}\n`);
59
+ if (footer && !content.trimEnd().endsWith(footer.trim())) code.append(`\n${footer}\n`);
60
+ if (code.hasChanged()) await __WEBPACK_EXTERNAL_MODULE_node_fs_promises__["default"].writeFile(file, code.toString());
61
61
  }
62
62
  async function processDtsFiles(bundle, dir, dtsExtension, banner, footer) {
63
63
  if (bundle) return;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rsbuild-plugin-dts",
3
- "version": "0.0.15",
3
+ "version": "0.0.17",
4
4
  "description": "Rsbuild plugin that supports emitting declaration files for TypeScript.",
5
5
  "homepage": "https://lib.rsbuild.dev",
6
6
  "bugs": {
@@ -31,8 +31,8 @@
31
31
  },
32
32
  "devDependencies": {
33
33
  "@microsoft/api-extractor": "^7.47.11",
34
- "@rsbuild/core": "~1.0.18",
35
- "rslib": "npm:@rslib/core@0.0.14",
34
+ "@rsbuild/core": "~1.1.0",
35
+ "rslib": "npm:@rslib/core@0.0.16",
36
36
  "typescript": "^5.6.3",
37
37
  "@rslib/tsconfig": "0.0.1"
38
38
  },