rsbuild-plugin-dts 0.0.3 → 0.0.5

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.
@@ -4,6 +4,8 @@ export type BundleOptions = {
4
4
  cwd: string;
5
5
  outDir: string;
6
6
  dtsExtension: string;
7
+ banner?: string;
8
+ footer?: string;
7
9
  dtsEntry: DtsEntry;
8
10
  tsconfigPath?: string;
9
11
  bundledPackages?: string[];
@@ -3,41 +3,19 @@ import * as __WEBPACK_EXTERNAL_MODULE__microsoft_api_extractor__ from "@microsof
3
3
  import * as __WEBPACK_EXTERNAL_MODULE__rsbuild_core__ from "@rsbuild/core";
4
4
  import * as __WEBPACK_EXTERNAL_MODULE_picocolors__ from "picocolors";
5
5
  import * as __WEBPACK_EXTERNAL_MODULE__utils_js__ from "./utils.js";
6
-
7
- ;// CONCATENATED MODULE: external "node:path"
8
-
9
6
  var external_node_path_namespaceObject = __WEBPACK_EXTERNAL_MODULE_node_path__;
10
-
11
- ;// CONCATENATED MODULE: external "@microsoft/api-extractor"
12
-
13
7
  var api_extractor_namespaceObject = __WEBPACK_EXTERNAL_MODULE__microsoft_api_extractor__;
14
-
15
- ;// CONCATENATED MODULE: external "@rsbuild/core"
16
-
17
8
  var core_namespaceObject = __WEBPACK_EXTERNAL_MODULE__rsbuild_core__;
18
-
19
- ;// CONCATENATED MODULE: external "picocolors"
20
-
21
9
  var external_picocolors_namespaceObject = __WEBPACK_EXTERNAL_MODULE_picocolors__;
22
-
23
- ;// CONCATENATED MODULE: external "./utils.js"
24
-
25
10
  var external_utils_js_namespaceObject = __WEBPACK_EXTERNAL_MODULE__utils_js__;
26
-
27
- ;// CONCATENATED MODULE: ./src/apiExtractor.ts
28
-
29
-
30
-
31
-
32
-
33
11
  async function bundleDts(options) {
34
- const { name, cwd, outDir, dtsExtension, dtsEntry = {
12
+ const { name, cwd, outDir, dtsExtension, banner, footer, dtsEntry = {
35
13
  name: 'index',
36
14
  path: 'index.d.ts'
37
15
  }, tsconfigPath = 'tsconfig.json', bundledPackages = [] } = options;
38
16
  try {
39
17
  const start = Date.now();
40
- const untrimmedFilePath = (0,external_node_path_namespaceObject.join)(cwd, (0,external_node_path_namespaceObject.relative)(cwd, outDir), `${dtsEntry.name}${dtsExtension}`);
18
+ const untrimmedFilePath = (0, external_node_path_namespaceObject.join)(cwd, (0, external_node_path_namespaceObject.relative)(cwd, outDir), `${dtsEntry.name}${dtsExtension}`);
41
19
  const mainEntryPointFilePath = dtsEntry.path;
42
20
  const internalConfig = {
43
21
  mainEntryPointFilePath,
@@ -47,26 +25,24 @@ async function bundleDts(options) {
47
25
  untrimmedFilePath
48
26
  },
49
27
  compiler: {
50
- tsconfigFilePath: tsconfigPath.includes(cwd) ? tsconfigPath : (0,external_node_path_namespaceObject.join)(cwd, tsconfigPath)
28
+ tsconfigFilePath: tsconfigPath.includes(cwd) ? tsconfigPath : (0, external_node_path_namespaceObject.join)(cwd, tsconfigPath)
51
29
  },
52
30
  projectFolder: cwd
53
31
  };
54
32
  const extractorConfig = api_extractor_namespaceObject.ExtractorConfig.prepare({
55
33
  configObject: internalConfig,
56
- configObjectFullPath: undefined,
57
- packageJsonFullPath: (0,external_node_path_namespaceObject.join)(cwd, 'package.json')
34
+ configObjectFullPath: void 0,
35
+ packageJsonFullPath: (0, external_node_path_namespaceObject.join)(cwd, 'package.json')
58
36
  });
59
37
  const extractorResult = api_extractor_namespaceObject.Extractor.invoke(extractorConfig, {
60
38
  localBuild: true
61
39
  });
62
- if (!extractorResult.succeeded) {
63
- throw new Error(`API Extractor error. ${external_picocolors_namespaceObject["default"].gray(`(${name})`)}`);
64
- }
65
- core_namespaceObject.logger.info(`API Extractor bundle DTS succeeded: ${external_picocolors_namespaceObject["default"].cyan(untrimmedFilePath)} in ${(0,external_utils_js_namespaceObject.getTimeCost)(start)} ${external_picocolors_namespaceObject["default"].gray(`(${name})`)}`);
40
+ if (!extractorResult.succeeded) throw new Error(`API Extractor error. ${external_picocolors_namespaceObject["default"].gray(`(${name})`)}`);
41
+ await (0, external_utils_js_namespaceObject.addBannerAndFooter)(untrimmedFilePath, banner, footer);
42
+ core_namespaceObject.logger.info(`API Extractor bundle DTS succeeded: ${external_picocolors_namespaceObject["default"].cyan(untrimmedFilePath)} in ${(0, external_utils_js_namespaceObject.getTimeCost)(start)} ${external_picocolors_namespaceObject["default"].gray(`(${name})`)}`);
66
43
  } catch (e) {
67
44
  core_namespaceObject.logger.error('API Extractor Error');
68
45
  throw new Error(`${e}`);
69
46
  }
70
47
  }
71
-
72
48
  export { bundleDts };
package/dist/dts.js CHANGED
@@ -5,82 +5,41 @@ import * as __WEBPACK_EXTERNAL_MODULE_picocolors__ from "picocolors";
5
5
  import * as __WEBPACK_EXTERNAL_MODULE_typescript__ from "typescript";
6
6
  import * as __WEBPACK_EXTERNAL_MODULE__tsc_js__ from "./tsc.js";
7
7
  import * as __WEBPACK_EXTERNAL_MODULE__utils_js__ from "./utils.js";
8
- var __webpack_modules__ = ({
9
- "./apiExtractor": (function (module) {
10
- module.exports = import("./apiExtractor.js");
11
-
12
- }),
13
-
14
- });
15
- /************************************************************************/
16
- // The module cache
8
+ var __webpack_modules__ = {
9
+ "./apiExtractor": function(module) {
10
+ module.exports = import("./apiExtractor.js");
11
+ }
12
+ };
13
+ /************************************************************************/ // The module cache
17
14
  var __webpack_module_cache__ = {};
18
-
19
15
  // The require function
20
16
  function __webpack_require__(moduleId) {
21
-
22
- // Check if module is in cache
23
- var cachedModule = __webpack_module_cache__[moduleId];
24
- if (cachedModule !== undefined) {
25
- return cachedModule.exports;
26
- }
27
- // Create a new module (and put it into the cache)
28
- var module = (__webpack_module_cache__[moduleId] = {
29
- exports: {}
30
- });
31
- // Execute the module function
32
- __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
33
-
34
- // Return the exports of the module
35
- return module.exports;
36
-
37
- }
38
-
39
- /************************************************************************/
40
-
41
- ;// CONCATENATED MODULE: external "node:fs"
42
-
17
+ // Check if module is in cache
18
+ var cachedModule = __webpack_module_cache__[moduleId];
19
+ if (void 0 !== cachedModule) return cachedModule.exports;
20
+ // Create a new module (and put it into the cache)
21
+ var module = __webpack_module_cache__[moduleId] = {
22
+ exports: {}
23
+ };
24
+ // Execute the module function
25
+ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
26
+ // Return the exports of the module
27
+ return module.exports;
28
+ } /************************************************************************/
43
29
  var external_node_fs_namespaceObject = __WEBPACK_EXTERNAL_MODULE_node_fs__;
44
-
45
- ;// CONCATENATED MODULE: external "node:path"
46
-
47
30
  var external_node_path_namespaceObject = __WEBPACK_EXTERNAL_MODULE_node_path__;
48
-
49
- ;// CONCATENATED MODULE: external "@rsbuild/core"
50
-
51
31
  var core_namespaceObject = __WEBPACK_EXTERNAL_MODULE__rsbuild_core__;
52
-
53
- ;// CONCATENATED MODULE: external "picocolors"
54
-
55
32
  var external_picocolors_namespaceObject = __WEBPACK_EXTERNAL_MODULE_picocolors__;
56
-
57
- ;// CONCATENATED MODULE: external "typescript"
58
-
59
33
  var external_typescript_namespaceObject = __WEBPACK_EXTERNAL_MODULE_typescript__;
60
-
61
- ;// CONCATENATED MODULE: external "./tsc.js"
62
-
63
34
  var external_tsc_js_namespaceObject = __WEBPACK_EXTERNAL_MODULE__tsc_js__;
64
-
65
- ;// CONCATENATED MODULE: external "./utils.js"
66
-
67
35
  var external_utils_js_namespaceObject = __WEBPACK_EXTERNAL_MODULE__utils_js__;
68
-
69
- ;// CONCATENATED MODULE: ./src/dts.ts
70
-
71
-
72
-
73
-
74
-
75
-
76
-
77
- const isObject = (obj)=>Object.prototype.toString.call(obj) === '[object Object]';
36
+ const isObject = (obj)=>'[object Object]' === Object.prototype.toString.call(obj);
78
37
  // use !externals
79
38
  const calcBundledPackages = (options)=>{
80
39
  const { autoExternal, cwd, userExternals } = options;
81
40
  let pkgJson;
82
41
  try {
83
- const content = external_node_fs_namespaceObject["default"].readFileSync((0,external_node_path_namespaceObject.join)(cwd, 'package.json'), 'utf-8');
42
+ const content = external_node_fs_namespaceObject["default"].readFileSync((0, external_node_path_namespaceObject.join)(cwd, 'package.json'), 'utf-8');
84
43
  pkgJson = JSON.parse(content);
85
44
  } catch (err) {
86
45
  core_namespaceObject.logger.warn('The type of third-party packages will not be bundled due to read package.json failed');
@@ -90,7 +49,7 @@ const calcBundledPackages = (options)=>{
90
49
  dependencies: true,
91
50
  peerDependencies: true,
92
51
  devDependencies: false,
93
- ...autoExternal === true ? {} : autoExternal
52
+ ...true === autoExternal ? {} : autoExternal
94
53
  } : {
95
54
  dependencies: false,
96
55
  peerDependencies: false,
@@ -99,20 +58,12 @@ const calcBundledPackages = (options)=>{
99
58
  // User externals should not bundled
100
59
  // Only handle the case where the externals type is string / (string | RegExp)[] / plain object, function type is too complex.
101
60
  const getUserExternalsKeys = (value)=>{
102
- if (!value) {
103
- return [];
104
- }
105
- if (typeof value === 'string' || value instanceof RegExp) {
106
- return [
107
- value
108
- ];
109
- }
110
- if (Array.isArray(value)) {
111
- return value.flatMap((v)=>getUserExternalsKeys(v));
112
- }
113
- if (isObject(userExternals)) {
114
- return Object.keys(userExternals);
115
- }
61
+ if (!value) return [];
62
+ if ('string' == typeof value || value instanceof RegExp) return [
63
+ value
64
+ ];
65
+ if (Array.isArray(value)) return value.flatMap((v)=>getUserExternalsKeys(v));
66
+ if (isObject(userExternals)) return Object.keys(userExternals);
116
67
  return [];
117
68
  };
118
69
  const externals = getUserExternalsKeys(userExternals);
@@ -124,43 +75,39 @@ const calcBundledPackages = (options)=>{
124
75
  ]){
125
76
  const deps = pkgJson[type] && Object.keys(pkgJson[type]);
126
77
  if (deps) {
127
- if (externalOptions[type]) {
128
- externals.push(...deps);
129
- }
78
+ if (externalOptions[type]) externals.push(...deps);
130
79
  allDeps.push(...deps);
131
80
  }
132
81
  }
133
- const bundledPackages = allDeps.filter((d)=>!externals.some((e)=>typeof e === 'string' ? d === e : e.test(d)));
82
+ const bundledPackages = allDeps.filter((d)=>!externals.some((e)=>'string' == typeof e ? d === e : e.test(d)));
134
83
  return Array.from(new Set(bundledPackages));
135
84
  };
136
85
  async function generateDts(data) {
137
- const { bundle, distPath, dtsEntry, tsconfigPath, name, cwd, isWatch, dtsExtension = '.d.ts', autoExternal = true, userExternals } = data;
86
+ const { bundle, distPath, dtsEntry, tsconfigPath, name, cwd, isWatch, dtsExtension = '.d.ts', autoExternal = true, userExternals, banner, footer } = data;
138
87
  core_namespaceObject.logger.start(`Generating DTS... ${external_picocolors_namespaceObject["default"].gray(`(${name})`)}`);
139
88
  const configPath = external_typescript_namespaceObject["default"].findConfigFile(cwd, external_typescript_namespaceObject["default"].sys.fileExists, tsconfigPath);
140
89
  if (!configPath) {
141
90
  core_namespaceObject.logger.error(`tsconfig.json not found in ${cwd}`);
142
91
  throw new Error();
143
92
  }
144
- const { options: rawCompilerOptions, fileNames } = (0,external_utils_js_namespaceObject.loadTsconfig)(configPath);
145
- const rootDir = rawCompilerOptions.rootDir ?? await (0,external_utils_js_namespaceObject.calcLongestCommonPath)(fileNames) ?? (0,external_node_path_namespaceObject.dirname)(configPath);
93
+ const { options: rawCompilerOptions, fileNames } = (0, external_utils_js_namespaceObject.loadTsconfig)(configPath);
94
+ const rootDir = rawCompilerOptions.rootDir ?? await (0, external_utils_js_namespaceObject.calcLongestCommonPath)(fileNames) ?? (0, external_node_path_namespaceObject.dirname)(configPath);
146
95
  const outDir = distPath ? distPath : rawCompilerOptions.declarationDir || './dist';
147
96
  const getDeclarationDir = (bundle, distPath)=>{
148
- if (bundle) {
149
- return (0,external_utils_js_namespaceObject.ensureTempDeclarationDir)(cwd);
150
- }
97
+ if (bundle) return (0, external_utils_js_namespaceObject.ensureTempDeclarationDir)(cwd);
151
98
  return distPath ? distPath : rawCompilerOptions.declarationDir ?? './dist';
152
99
  };
153
100
  const declarationDir = getDeclarationDir(bundle, distPath);
154
101
  const { name: entryName, path: entryPath } = dtsEntry;
155
102
  let entry = '';
156
- if (bundle === true && entryPath) {
157
- const entrySourcePath = (0,external_node_path_namespaceObject.isAbsolute)(entryPath) ? entryPath : (0,external_node_path_namespaceObject.join)(cwd, entryPath);
158
- const relativePath = (0,external_node_path_namespaceObject.relative)(rootDir, (0,external_node_path_namespaceObject.dirname)(entrySourcePath));
159
- entry = (0,external_node_path_namespaceObject.join)(declarationDir, relativePath, (0,external_node_path_namespaceObject.basename)(entrySourcePath)).replace(/\.(js|mjs|jsx|ts|mts|tsx|cjs|cts|cjsx|ctsx|mjsx|mtsx)$/, '.d.ts');
103
+ if (true === bundle && entryPath) {
104
+ const entrySourcePath = (0, external_node_path_namespaceObject.isAbsolute)(entryPath) ? entryPath : (0, external_node_path_namespaceObject.join)(cwd, entryPath);
105
+ const relativePath = (0, external_node_path_namespaceObject.relative)(rootDir, (0, external_node_path_namespaceObject.dirname)(entrySourcePath));
106
+ entry = (0, external_node_path_namespaceObject.join)(declarationDir, relativePath, (0, external_node_path_namespaceObject.basename)(entrySourcePath)).replace(/\.(js|mjs|jsx|ts|mts|tsx|cjs|cts|cjsx|ctsx|mjsx|mtsx)$/, '.d.ts');
160
107
  }
161
108
  const bundleDtsIfNeeded = async ()=>{
162
- if (bundle === true) {
163
- const { bundleDts } = await Promise.resolve(/* import() */ ).then(__webpack_require__.bind(__webpack_require__, "./apiExtractor"));
109
+ if (true === bundle) {
110
+ const { bundleDts } = await Promise.resolve().then(__webpack_require__.bind(__webpack_require__, "./apiExtractor"));
164
111
  await bundleDts({
165
112
  name,
166
113
  cwd,
@@ -171,6 +118,8 @@ async function generateDts(data) {
171
118
  },
172
119
  tsconfigPath,
173
120
  dtsExtension,
121
+ banner,
122
+ footer,
174
123
  bundledPackages: calcBundledPackages({
175
124
  autoExternal,
176
125
  cwd,
@@ -180,25 +129,21 @@ async function generateDts(data) {
180
129
  }
181
130
  };
182
131
  const onComplete = async (isSuccess)=>{
183
- if (isSuccess) {
184
- await bundleDtsIfNeeded();
185
- }
132
+ if (isSuccess) await bundleDtsIfNeeded();
186
133
  };
187
- await (0,external_tsc_js_namespaceObject.emitDts)({
134
+ await (0, external_tsc_js_namespaceObject.emitDts)({
188
135
  name,
189
136
  cwd,
190
137
  configPath,
191
138
  declarationDir,
192
- dtsExtension
139
+ dtsExtension,
140
+ banner,
141
+ footer
193
142
  }, onComplete, bundle, isWatch);
194
- if (!isWatch) {
195
- await bundleDtsIfNeeded();
196
- }
143
+ if (!isWatch) await bundleDtsIfNeeded();
197
144
  }
198
145
  process.on('message', async (data)=>{
199
- if (!data.cwd) {
200
- return;
201
- }
146
+ if (!data.cwd) return;
202
147
  try {
203
148
  await generateDts(data);
204
149
  } catch (e) {
@@ -207,9 +152,6 @@ process.on('message', async (data)=>{
207
152
  process.exit(1);
208
153
  }
209
154
  process.send('success');
210
- if (!data.isWatch) {
211
- process.exit();
212
- }
155
+ if (!data.isWatch) process.exit();
213
156
  });
214
-
215
157
  export { calcBundledPackages, generateDts };
package/dist/index.d.ts CHANGED
@@ -9,6 +9,8 @@ export type PluginDtsOptions = {
9
9
  devDependencies?: boolean;
10
10
  peerDependencies?: boolean;
11
11
  };
12
+ banner?: string;
13
+ footer?: string;
12
14
  };
13
15
  export type DtsEntry = {
14
16
  name?: string;
package/dist/index.js CHANGED
@@ -1,33 +1,15 @@
1
- import {fileURLToPath as __webpack_fileURLToPath__} from "url";
2
- import {dirname as __webpack_dirname__} from "path";
1
+ import { fileURLToPath as __webpack_fileURLToPath__ } from "url";
2
+ import { dirname as __webpack_dirname__ } from "path";
3
3
  import * as __WEBPACK_EXTERNAL_MODULE_node_child_process__ from "node:child_process";
4
4
  import * as __WEBPACK_EXTERNAL_MODULE_node_path__ from "node:path";
5
5
  import * as __WEBPACK_EXTERNAL_MODULE__rsbuild_core__ from "@rsbuild/core";
6
6
  import * as __WEBPACK_EXTERNAL_MODULE__utils_js__ from "./utils.js";
7
-
8
- ;// CONCATENATED MODULE: external "node:child_process"
9
-
10
7
  var external_node_child_process_namespaceObject = __WEBPACK_EXTERNAL_MODULE_node_child_process__;
11
-
12
- ;// CONCATENATED MODULE: external "node:path"
13
-
14
8
  var external_node_path_namespaceObject = __WEBPACK_EXTERNAL_MODULE_node_path__;
15
-
16
- ;// CONCATENATED MODULE: external "@rsbuild/core"
17
-
18
9
  var core_namespaceObject = __WEBPACK_EXTERNAL_MODULE__rsbuild_core__;
19
-
20
- ;// CONCATENATED MODULE: external "./utils.js"
21
-
22
10
  var external_utils_js_namespaceObject = __WEBPACK_EXTERNAL_MODULE__utils_js__;
23
-
24
- ;// CONCATENATED MODULE: ./src/index.ts
25
11
  var src_filename = __webpack_fileURLToPath__(import.meta.url);
26
12
  var src_dirname = __webpack_dirname__(__webpack_fileURLToPath__(import.meta.url));
27
-
28
-
29
-
30
-
31
13
  const PLUGIN_DTS_NAME = 'rsbuild:dts';
32
14
  // use ts compiler API to generate bundleless dts
33
15
  // use ts compiler API and api-extractor to generate dts bundle
@@ -41,18 +23,16 @@ const pluginDts = (options)=>({
41
23
  const dtsPromises = [];
42
24
  let promisesResult = [];
43
25
  api.onBeforeEnvironmentCompile(({ isWatch, isFirstCompile, environment })=>{
44
- if (!isFirstCompile) {
45
- return;
46
- }
26
+ if (!isFirstCompile) return;
47
27
  const { config } = environment;
48
28
  options.distPath = options.distPath ?? config.output?.distPath?.root;
49
- const jsExtension = (0,external_node_path_namespaceObject.extname)(src_filename);
50
- const childProcess = (0,external_node_child_process_namespaceObject.fork)((0,external_node_path_namespaceObject.join)(src_dirname, `./dts${jsExtension}`), [], {
29
+ const jsExtension = (0, external_node_path_namespaceObject.extname)(src_filename);
30
+ const childProcess = (0, external_node_child_process_namespaceObject.fork)((0, external_node_path_namespaceObject.join)(src_dirname, `./dts${jsExtension}`), [], {
51
31
  stdio: 'inherit'
52
32
  });
53
33
  // TODO: @microsoft/api-extractor only support single entry to bundle DTS
54
34
  // use first element of Record<string, string> type entry config
55
- const dtsEntry = (0,external_utils_js_namespaceObject.processSourceEntry)(options.bundle, config.source?.entry);
35
+ const dtsEntry = (0, external_utils_js_namespaceObject.processSourceEntry)(options.bundle, config.source?.entry);
56
36
  const dtsGenOptions = {
57
37
  ...options,
58
38
  dtsEntry,
@@ -65,43 +45,31 @@ const pluginDts = (options)=>({
65
45
  childProcess.send(dtsGenOptions);
66
46
  dtsPromises.push(new Promise((resolve)=>{
67
47
  childProcess.on('message', (message)=>{
68
- if (message === 'success') {
69
- resolve({
70
- status: 'success'
71
- });
72
- } else if (message === 'error') {
73
- resolve({
74
- status: 'error',
75
- errorMessage: `Error occurred in ${environment.name} DTS generation`
76
- });
77
- }
48
+ if ('success' === message) resolve({
49
+ status: 'success'
50
+ });
51
+ else if ('error' === message) resolve({
52
+ status: 'error',
53
+ errorMessage: `Error occurred in ${environment.name} DTS generation`
54
+ });
78
55
  });
79
56
  }));
80
57
  });
81
58
  api.onAfterBuild(async ({ isFirstCompile })=>{
82
- if (!isFirstCompile) {
83
- return;
84
- }
59
+ if (!isFirstCompile) return;
85
60
  promisesResult = await Promise.all(dtsPromises);
86
61
  });
87
62
  api.onAfterBuild({
88
63
  handler: ({ isFirstCompile })=>{
89
- if (!isFirstCompile) {
90
- return;
91
- }
92
- for (const result of promisesResult){
93
- if (result.status === 'error') {
94
- if (options.abortOnError) {
95
- throw new Error(result.errorMessage);
96
- }
97
- result.errorMessage && core_namespaceObject.logger.error(result.errorMessage);
98
- core_namespaceObject.logger.warn('With the `abortOnError` configuration currently turned off, type errors do not cause build failures, but they do not guarantee proper type file output.');
99
- }
64
+ if (!isFirstCompile) return;
65
+ for (const result of promisesResult)if ('error' === result.status) {
66
+ if (options.abortOnError) throw new Error(result.errorMessage);
67
+ result.errorMessage && core_namespaceObject.logger.error(result.errorMessage);
68
+ core_namespaceObject.logger.warn('With the `abortOnError` configuration currently turned off, type errors do not cause build failures, but they do not guarantee proper type file output.');
100
69
  }
101
70
  },
102
71
  order: 'post'
103
72
  });
104
73
  }
105
74
  });
106
-
107
75
  export { PLUGIN_DTS_NAME, pluginDts };
package/dist/tsc.d.ts CHANGED
@@ -4,5 +4,7 @@ export type EmitDtsOptions = {
4
4
  configPath: string;
5
5
  declarationDir: string;
6
6
  dtsExtension: string;
7
+ banner?: string;
8
+ footer?: string;
7
9
  };
8
10
  export declare function emitDts(options: EmitDtsOptions, onComplete: (isSuccess: boolean) => void, bundle?: boolean, isWatch?: boolean): Promise<void>;
package/dist/tsc.js CHANGED
@@ -2,32 +2,14 @@ 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
-
6
- ;// CONCATENATED MODULE: external "@rsbuild/core"
7
-
8
5
  var core_namespaceObject = __WEBPACK_EXTERNAL_MODULE__rsbuild_core__;
9
-
10
- ;// CONCATENATED MODULE: external "picocolors"
11
-
12
6
  var external_picocolors_namespaceObject = __WEBPACK_EXTERNAL_MODULE_picocolors__;
13
-
14
- ;// CONCATENATED MODULE: external "typescript"
15
-
16
7
  var external_typescript_namespaceObject = __WEBPACK_EXTERNAL_MODULE_typescript__;
17
-
18
- ;// CONCATENATED MODULE: external "./utils.js"
19
-
20
8
  var external_utils_js_namespaceObject = __WEBPACK_EXTERNAL_MODULE__utils_js__;
21
-
22
- ;// CONCATENATED MODULE: ./src/tsc.ts
23
-
24
-
25
-
26
-
27
9
  async function emitDts(options, onComplete, bundle = false, isWatch = false) {
28
10
  const start = Date.now();
29
- const { configPath, declarationDir, name, dtsExtension } = options;
30
- const { options: rawCompilerOptions, fileNames } = (0,external_utils_js_namespaceObject.loadTsconfig)(configPath);
11
+ const { configPath, declarationDir, name, dtsExtension, banner, footer } = options;
12
+ const { options: rawCompilerOptions, fileNames } = (0, external_utils_js_namespaceObject.loadTsconfig)(configPath);
31
13
  const compilerOptions = {
32
14
  ...rawCompilerOptions,
33
15
  noEmit: false,
@@ -35,27 +17,7 @@ async function emitDts(options, onComplete, bundle = false, isWatch = false) {
35
17
  declarationDir,
36
18
  emitDeclarationOnly: true
37
19
  };
38
- if (!isWatch) {
39
- const host = external_typescript_namespaceObject["default"].createCompilerHost(compilerOptions);
40
- const program = external_typescript_namespaceObject["default"].createProgram(fileNames, compilerOptions, host);
41
- const emitResult = program.emit();
42
- const allDiagnostics = external_typescript_namespaceObject["default"].getPreEmitDiagnostics(program).concat(emitResult.diagnostics);
43
- const diagnosticMessages = [];
44
- for (const diagnostic of allDiagnostics){
45
- const fileLoc = (0,external_utils_js_namespaceObject.getFileLoc)(diagnostic);
46
- const message = `${fileLoc} - ${external_picocolors_namespaceObject["default"].red('error')} ${external_picocolors_namespaceObject["default"].gray(`TS${diagnostic.code}:`)} ${external_typescript_namespaceObject["default"].flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine())}`;
47
- diagnosticMessages.push(message);
48
- }
49
- await (0,external_utils_js_namespaceObject.processDtsFiles)(bundle, declarationDir, dtsExtension);
50
- if (diagnosticMessages.length) {
51
- core_namespaceObject.logger.error(`Failed to emit declaration files. ${external_picocolors_namespaceObject["default"].gray(`(${name})`)}`);
52
- for (const message of diagnosticMessages){
53
- core_namespaceObject.logger.error(message);
54
- }
55
- throw new Error('DTS generation failed');
56
- }
57
- core_namespaceObject.logger.ready(`DTS generated in ${(0,external_utils_js_namespaceObject.getTimeCost)(start)} ${external_picocolors_namespaceObject["default"].gray(`(${name})`)}`);
58
- } else {
20
+ if (isWatch) {
59
21
  const createProgram = external_typescript_namespaceObject["default"].createSemanticDiagnosticsBuilderProgram;
60
22
  const formatHost = {
61
23
  getCanonicalFileName: (path)=>path,
@@ -63,30 +25,26 @@ async function emitDts(options, onComplete, bundle = false, isWatch = false) {
63
25
  getNewLine: ()=>external_typescript_namespaceObject["default"].sys.newLine
64
26
  };
65
27
  const reportDiagnostic = (diagnostic)=>{
66
- const fileLoc = (0,external_utils_js_namespaceObject.getFileLoc)(diagnostic);
28
+ const fileLoc = (0, external_utils_js_namespaceObject.getFileLoc)(diagnostic);
67
29
  core_namespaceObject.logger.error(`${fileLoc} - ${external_picocolors_namespaceObject["default"].red('error')} ${external_picocolors_namespaceObject["default"].gray(`TS${diagnostic.code}:`)}`, external_typescript_namespaceObject["default"].flattenDiagnosticMessageText(diagnostic.messageText, formatHost.getNewLine()));
68
30
  };
69
31
  const reportWatchStatusChanged = async (diagnostic, _newLine, _options, errorCount)=>{
70
32
  const message = `${external_typescript_namespaceObject["default"].flattenDiagnosticMessageText(diagnostic.messageText, formatHost.getNewLine())} ${external_picocolors_namespaceObject["default"].gray(`(${name})`)}`;
71
33
  // 6031: File change detected. Starting incremental compilation...
72
34
  // 6032: Starting compilation in watch mode...
73
- if (diagnostic.code === 6031 || diagnostic.code === 6032) {
74
- core_namespaceObject.logger.info(message);
75
- }
35
+ if (6031 === diagnostic.code || 6032 === diagnostic.code) core_namespaceObject.logger.info(message);
76
36
  // 6194: 0 errors or 2+ errors!
77
- if (diagnostic.code === 6194) {
78
- if (errorCount === 0) {
37
+ if (6194 === diagnostic.code) {
38
+ if (0 === errorCount) {
79
39
  core_namespaceObject.logger.info(message);
80
40
  onComplete(true);
81
- } else {
82
- core_namespaceObject.logger.error(message);
83
- }
84
- await (0,external_utils_js_namespaceObject.processDtsFiles)(bundle, declarationDir, dtsExtension);
41
+ } else core_namespaceObject.logger.error(message);
42
+ await (0, external_utils_js_namespaceObject.processDtsFiles)(bundle, declarationDir, dtsExtension, banner, footer);
85
43
  }
86
44
  // 6193: 1 error
87
- if (diagnostic.code === 6193) {
45
+ if (6193 === diagnostic.code) {
88
46
  core_namespaceObject.logger.error(message);
89
- await (0,external_utils_js_namespaceObject.processDtsFiles)(bundle, declarationDir, dtsExtension);
47
+ await (0, external_utils_js_namespaceObject.processDtsFiles)(bundle, declarationDir, dtsExtension, banner, footer);
90
48
  }
91
49
  };
92
50
  const system = {
@@ -94,7 +52,24 @@ async function emitDts(options, onComplete, bundle = false, isWatch = false) {
94
52
  };
95
53
  const host = external_typescript_namespaceObject["default"].createWatchCompilerHost(configPath, compilerOptions, system, createProgram, reportDiagnostic, reportWatchStatusChanged);
96
54
  external_typescript_namespaceObject["default"].createWatchProgram(host);
55
+ } else {
56
+ const host = external_typescript_namespaceObject["default"].createCompilerHost(compilerOptions);
57
+ const program = external_typescript_namespaceObject["default"].createProgram(fileNames, compilerOptions, host);
58
+ const emitResult = program.emit();
59
+ const allDiagnostics = external_typescript_namespaceObject["default"].getPreEmitDiagnostics(program).concat(emitResult.diagnostics);
60
+ const diagnosticMessages = [];
61
+ for (const diagnostic of allDiagnostics){
62
+ const fileLoc = (0, external_utils_js_namespaceObject.getFileLoc)(diagnostic);
63
+ const message = `${fileLoc} - ${external_picocolors_namespaceObject["default"].red('error')} ${external_picocolors_namespaceObject["default"].gray(`TS${diagnostic.code}:`)} ${external_typescript_namespaceObject["default"].flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine())}`;
64
+ diagnosticMessages.push(message);
65
+ }
66
+ await (0, external_utils_js_namespaceObject.processDtsFiles)(bundle, declarationDir, dtsExtension, banner, footer);
67
+ if (diagnosticMessages.length) {
68
+ core_namespaceObject.logger.error(`Failed to emit declaration files. ${external_picocolors_namespaceObject["default"].gray(`(${name})`)}`);
69
+ for (const message of diagnosticMessages)core_namespaceObject.logger.error(message);
70
+ throw new Error('DTS generation failed');
71
+ }
72
+ core_namespaceObject.logger.ready(`DTS generated in ${(0, external_utils_js_namespaceObject.getTimeCost)(start)} ${external_picocolors_namespaceObject["default"].gray(`(${name})`)}`);
97
73
  }
98
74
  }
99
-
100
75
  export { emitDts };
package/dist/utils.d.ts CHANGED
@@ -8,6 +8,7 @@ export declare function ensureTempDeclarationDir(cwd: string): string;
8
8
  export declare function getFileLoc(diagnostic: ts.Diagnostic): string;
9
9
  export declare const prettyTime: (seconds: number) => string;
10
10
  export declare function getTimeCost(start: number): string;
11
- export declare function processDtsFiles(bundle: boolean, dir: string, dtsExtension: string): Promise<void>;
11
+ export declare function addBannerAndFooter(file: string, banner?: string, footer?: string): Promise<void>;
12
+ export declare function processDtsFiles(bundle: boolean, dir: string, dtsExtension: string, banner?: string, footer?: string): Promise<void>;
12
13
  export declare function processSourceEntry(bundle: boolean, entryConfig: NonNullable<RsbuildConfig['source']>['entry']): DtsEntry;
13
14
  export declare function calcLongestCommonPath(absPaths: string[]): Promise<string | null>;
package/dist/utils.js CHANGED
@@ -4,50 +4,18 @@ import * as __WEBPACK_EXTERNAL_MODULE_node_os__ from "node:os";
4
4
  import * as __WEBPACK_EXTERNAL_MODULE_node_path__ from "node:path";
5
5
  import * as __WEBPACK_EXTERNAL_MODULE__rsbuild_core__ from "@rsbuild/core";
6
6
  import * as __WEBPACK_EXTERNAL_MODULE_fast_glob__ from "fast-glob";
7
+ import * as __WEBPACK_EXTERNAL_MODULE_magic_string__ from "magic-string";
7
8
  import * as __WEBPACK_EXTERNAL_MODULE_picocolors__ from "picocolors";
8
9
  import * as __WEBPACK_EXTERNAL_MODULE_typescript__ from "typescript";
9
-
10
- ;// CONCATENATED MODULE: external "node:fs"
11
-
12
10
  var external_node_fs_namespaceObject = __WEBPACK_EXTERNAL_MODULE_node_fs__;
13
-
14
- ;// CONCATENATED MODULE: external "node:fs/promises"
15
-
16
11
  var promises_namespaceObject = __WEBPACK_EXTERNAL_MODULE_node_fs_promises__;
17
-
18
- ;// CONCATENATED MODULE: external "node:os"
19
-
20
12
  var external_node_os_namespaceObject = __WEBPACK_EXTERNAL_MODULE_node_os__;
21
-
22
- ;// CONCATENATED MODULE: external "node:path"
23
-
24
13
  var external_node_path_namespaceObject = __WEBPACK_EXTERNAL_MODULE_node_path__;
25
-
26
- ;// CONCATENATED MODULE: external "@rsbuild/core"
27
-
28
14
  var core_namespaceObject = __WEBPACK_EXTERNAL_MODULE__rsbuild_core__;
29
-
30
- ;// CONCATENATED MODULE: external "fast-glob"
31
-
32
15
  var external_fast_glob_namespaceObject = __WEBPACK_EXTERNAL_MODULE_fast_glob__;
33
-
34
- ;// CONCATENATED MODULE: external "picocolors"
35
-
16
+ var external_magic_string_namespaceObject = __WEBPACK_EXTERNAL_MODULE_magic_string__;
36
17
  var external_picocolors_namespaceObject = __WEBPACK_EXTERNAL_MODULE_picocolors__;
37
-
38
- ;// CONCATENATED MODULE: external "typescript"
39
-
40
18
  var external_typescript_namespaceObject = __WEBPACK_EXTERNAL_MODULE_typescript__;
41
-
42
- ;// CONCATENATED MODULE: ./src/utils.ts
43
-
44
-
45
-
46
-
47
-
48
-
49
-
50
-
51
19
  const { convertPathToPattern } = external_fast_glob_namespaceObject["default"];
52
20
  function loadTsconfig(tsconfigPath) {
53
21
  const configFile = external_typescript_namespaceObject["default"].readConfigFile(tsconfigPath, external_typescript_namespaceObject["default"].sys.readFile);
@@ -58,9 +26,7 @@ const TEMP_FOLDER = '.rslib';
58
26
  const TEMP_DTS_DIR = `${TEMP_FOLDER}/declarations`;
59
27
  function ensureTempDeclarationDir(cwd) {
60
28
  const dirPath = external_node_path_namespaceObject["default"].join(cwd, TEMP_DTS_DIR);
61
- if (external_node_fs_namespaceObject["default"].existsSync(dirPath)) {
62
- return dirPath;
63
- }
29
+ if (external_node_fs_namespaceObject["default"].existsSync(dirPath)) return dirPath;
64
30
  external_node_fs_namespaceObject["default"].mkdirSync(dirPath, {
65
31
  recursive: true
66
32
  });
@@ -81,58 +47,53 @@ const prettyTime = (seconds)=>{
81
47
  const digits = seconds >= 0.01 ? 2 : 3;
82
48
  return `${format(seconds.toFixed(digits))} s`;
83
49
  }
84
- if (seconds < 60) {
85
- return `${format(seconds.toFixed(1))} s`;
86
- }
50
+ if (seconds < 60) return `${format(seconds.toFixed(1))} s`;
87
51
  const minutes = seconds / 60;
88
52
  return `${format(minutes.toFixed(2))} m`;
89
53
  };
90
54
  // fast-glob only accepts posix path
91
55
  // https://github.com/mrmlnc/fast-glob#convertpathtopatternpath
92
56
  const convertPath = (path)=>{
93
- if ((0,external_node_os_namespaceObject.platform)() === 'win32') {
94
- return convertPathToPattern(path);
95
- }
57
+ if ('win32' === (0, external_node_os_namespaceObject.platform)()) return convertPathToPattern(path);
96
58
  return path;
97
59
  };
98
60
  function getTimeCost(start) {
99
61
  const second = (Date.now() - start) / 1000;
100
62
  return prettyTime(second);
101
63
  }
102
- async function processDtsFiles(bundle, dir, dtsExtension) {
103
- if (bundle) {
104
- return;
105
- }
106
- const dtsFiles = await (0,external_fast_glob_namespaceObject["default"])(convertPath((0,external_node_path_namespaceObject.join)(dir, '/**/*.d.ts')));
107
- for (const file of dtsFiles){
108
- try {
109
- const newFile = file.replace('.d.ts', dtsExtension);
110
- external_node_fs_namespaceObject["default"].renameSync(file, newFile);
111
- } catch (error) {
112
- core_namespaceObject.logger.error(`Error renaming DTS file ${file}: ${error}`);
113
- }
64
+ async function addBannerAndFooter(file, banner, footer) {
65
+ if (!banner && !footer) return;
66
+ const content = await promises_namespaceObject["default"].readFile(file, 'utf-8');
67
+ const code = new external_magic_string_namespaceObject["default"](content);
68
+ banner && code.prepend(`${banner}\n`);
69
+ footer && code.append(`\n${footer}\n`);
70
+ await promises_namespaceObject["default"].writeFile(file, code.toString());
71
+ }
72
+ async function processDtsFiles(bundle, dir, dtsExtension, banner, footer) {
73
+ if (bundle) return;
74
+ const dtsFiles = await (0, external_fast_glob_namespaceObject["default"])(convertPath((0, external_node_path_namespaceObject.join)(dir, '/**/*.d.ts')));
75
+ for (const file of dtsFiles)try {
76
+ await addBannerAndFooter(file, banner, footer);
77
+ const newFile = file.replace('.d.ts', dtsExtension);
78
+ external_node_fs_namespaceObject["default"].renameSync(file, newFile);
79
+ } catch (error) {
80
+ core_namespaceObject.logger.error(`Error renaming DTS file ${file}: ${error}`);
114
81
  }
115
82
  }
116
83
  function processSourceEntry(bundle, entryConfig) {
117
- if (!bundle) {
118
- return {
119
- name: undefined,
120
- path: undefined
121
- };
122
- }
123
- if (entryConfig && Object.values(entryConfig).every((val)=>typeof val === 'string')) {
124
- return {
125
- name: Object.keys(entryConfig)[0],
126
- path: Object.values(entryConfig)[0]
127
- };
128
- }
84
+ if (!bundle) return {
85
+ name: void 0,
86
+ path: void 0
87
+ };
88
+ if (entryConfig && Object.values(entryConfig).every((val)=>'string' == typeof val)) return {
89
+ name: Object.keys(entryConfig)[0],
90
+ path: Object.values(entryConfig)[0]
91
+ };
129
92
  throw new Error('@microsoft/api-extractor only support single entry of Record<string, string> type to bundle DTS, please check your entry config.');
130
93
  }
131
94
  // same as @rslib/core, we should extract into a single published package to share
132
95
  async function calcLongestCommonPath(absPaths) {
133
- if (absPaths.length === 0) {
134
- return null;
135
- }
96
+ if (0 === absPaths.length) return null;
136
97
  // we support two cases
137
98
  // 1. /packages-a/src/index.ts
138
99
  // 2. D:/packages-a/src/index.ts
@@ -143,17 +104,12 @@ async function calcLongestCommonPath(absPaths) {
143
104
  const currentPath = splitPaths[i];
144
105
  const minLength = Math.min(lcaFragments.length, currentPath.length);
145
106
  let j = 0;
146
- while(j < minLength && lcaFragments[j] === currentPath[j]){
147
- j++;
148
- }
107
+ while(j < minLength && lcaFragments[j] === currentPath[j])j++;
149
108
  lcaFragments = lcaFragments.slice(0, j);
150
109
  }
151
110
  let lca = lcaFragments.length > 0 ? lcaFragments.join(sep) : sep;
152
111
  const stats = await promises_namespaceObject["default"].stat(lca);
153
- if (stats?.isFile()) {
154
- lca = external_node_path_namespaceObject["default"].dirname(lca);
155
- }
112
+ if (stats?.isFile()) lca = external_node_path_namespaceObject["default"].dirname(lca);
156
113
  return lca;
157
114
  }
158
-
159
- export { TEMP_DTS_DIR, TEMP_FOLDER, calcLongestCommonPath, ensureTempDeclarationDir, getFileLoc, getTimeCost, loadTsconfig, prettyTime, processDtsFiles, processSourceEntry };
115
+ export { TEMP_DTS_DIR, TEMP_FOLDER, addBannerAndFooter, calcLongestCommonPath, ensureTempDeclarationDir, getFileLoc, getTimeCost, loadTsconfig, prettyTime, processDtsFiles, processSourceEntry };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rsbuild-plugin-dts",
3
- "version": "0.0.3",
3
+ "version": "0.0.5",
4
4
  "description": "Dts plugin for Rsbuild",
5
5
  "homepage": "https://rslib.dev",
6
6
  "bugs": {
@@ -26,12 +26,13 @@
26
26
  ],
27
27
  "dependencies": {
28
28
  "fast-glob": "^3.3.2",
29
- "picocolors": "1.0.1"
29
+ "magic-string": "^0.30.11",
30
+ "picocolors": "1.1.0"
30
31
  },
31
32
  "devDependencies": {
32
- "@microsoft/api-extractor": "^7.47.5",
33
- "@rsbuild/core": "1.0.1-beta.16",
34
- "rslib": "npm:@rslib/core@0.0.2",
33
+ "@microsoft/api-extractor": "^7.47.7",
34
+ "@rsbuild/core": "1.0.1-rc.4",
35
+ "rslib": "npm:@rslib/core@0.0.4",
35
36
  "typescript": "^5.5.4",
36
37
  "@rslib/tsconfig": "0.0.1"
37
38
  },