vite-plugin-dts 3.2.0 → 3.3.0

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
@@ -280,20 +280,21 @@ export interface PluginOptions {
280
280
  *
281
281
  * This allows you to transform the path or content
282
282
  *
283
- * The file will be skipped when the return value `false`
283
+ * The file will be skipped when the return value `false` or `Promise<false>`
284
284
  *
285
285
  * @default () => {}
286
286
  */
287
287
  beforeWriteFile?: (
288
288
  filePath: string,
289
289
  content: string
290
- ) =>
291
- | void
292
- | false
293
- | {
294
- filePath?: string,
295
- content?: string
296
- },
290
+ ) => MaybePromise<
291
+ | void
292
+ | false
293
+ | {
294
+ filePath?: string,
295
+ content?: string
296
+ }
297
+ >,
297
298
 
298
299
  /**
299
300
  * Hook called after all declaration files are written
package/README.zh-CN.md CHANGED
@@ -280,20 +280,21 @@ export interface PluginOptions {
280
280
  *
281
281
  * 可以在钩子里转换文件路径和文件内容
282
282
  *
283
- * 当返回 `false` 时会跳过该文件
283
+ * 当返回 `false` 或 `Promise<false>` 时会跳过该文件
284
284
  *
285
285
  * @default () => {}
286
286
  */
287
287
  beforeWriteFile?: (
288
288
  filePath: string,
289
289
  content: string
290
- ) =>
291
- | void
292
- | false
293
- | {
294
- filePath?: string,
295
- content?: string
296
- },
290
+ ) => MaybePromise<
291
+ | void
292
+ | false
293
+ | {
294
+ filePath?: string,
295
+ content?: string
296
+ }
297
+ >,
297
298
 
298
299
  /**
299
300
  * 在所有类型文件被写入后调用的钩子
package/dist/index.cjs CHANGED
@@ -11,17 +11,163 @@ const vueTsc = require('vue-tsc');
11
11
  const debug = require('debug');
12
12
  const kolorist = require('kolorist');
13
13
  const apiExtractor = require('@microsoft/api-extractor');
14
- const Collector_js = require('@microsoft/api-extractor/lib/collector/Collector.js');
15
- const MessageRouter_js = require('@microsoft/api-extractor/lib/collector/MessageRouter.js');
16
- const SourceMapper_js = require('@microsoft/api-extractor/lib/collector/SourceMapper.js');
17
- const DtsRollupGenerator_js = require('@microsoft/api-extractor/lib/generators/DtsRollupGenerator.js');
18
- const nodeCoreLibrary = require('@rushstack/node-core-library');
19
14
 
20
15
  function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
21
16
 
22
17
  const ts__default = /*#__PURE__*/_interopDefaultCompat(ts);
23
18
  const debug__default = /*#__PURE__*/_interopDefaultCompat(debug);
24
19
 
20
+ const windowsSlashRE = /\\+/g;
21
+ function slash(p) {
22
+ return p.replace(windowsSlashRE, "/");
23
+ }
24
+ function normalizePath(id) {
25
+ return node_path.posix.normalize(slash(id));
26
+ }
27
+ function resolve(...paths) {
28
+ return normalizePath(node_path.resolve(...paths));
29
+ }
30
+ function isNativeObj(value) {
31
+ return Object.prototype.toString.call(value) === "[object Object]";
32
+ }
33
+ function isRegExp(value) {
34
+ return Object.prototype.toString.call(value) === "[object RegExp]";
35
+ }
36
+ function isPromise(value) {
37
+ return !!value && (typeof value === "function" || typeof value === "object") && typeof value.then === "function";
38
+ }
39
+ async function wrapPromise(maybePromise) {
40
+ return isPromise(maybePromise) ? await maybePromise : maybePromise;
41
+ }
42
+ function ensureAbsolute(path, root) {
43
+ return normalizePath(path ? node_path.isAbsolute(path) ? path : resolve(root, path) : root);
44
+ }
45
+ function ensureArray(value) {
46
+ return Array.isArray(value) ? value : value ? [value] : [];
47
+ }
48
+ async function runParallel(maxConcurrency, source, iteratorFn) {
49
+ const ret = [];
50
+ const executing = [];
51
+ for (const item of source) {
52
+ const p = Promise.resolve().then(() => iteratorFn(item, source));
53
+ ret.push(p);
54
+ if (maxConcurrency <= source.length) {
55
+ const e = p.then(() => executing.splice(executing.indexOf(e), 1));
56
+ executing.push(e);
57
+ if (executing.length >= maxConcurrency) {
58
+ await Promise.race(executing);
59
+ }
60
+ }
61
+ }
62
+ return Promise.all(ret);
63
+ }
64
+ const speRE = /[\\/]/;
65
+ function queryPublicPath(paths) {
66
+ if (paths.length === 0) {
67
+ return "";
68
+ } else if (paths.length === 1) {
69
+ return node_path.dirname(paths[0]);
70
+ }
71
+ let publicPath = node_path.normalize(node_path.dirname(paths[0])) + node_path.sep;
72
+ let publicUnits = publicPath.split(speRE);
73
+ let index = publicUnits.length - 1;
74
+ for (const path of paths.slice(1)) {
75
+ if (!index) {
76
+ return publicPath;
77
+ }
78
+ const dirPath = node_path.normalize(node_path.dirname(path)) + node_path.sep;
79
+ if (dirPath.startsWith(publicPath)) {
80
+ continue;
81
+ }
82
+ const units = dirPath.split(speRE);
83
+ if (units.length < index) {
84
+ publicPath = dirPath;
85
+ publicUnits = units;
86
+ continue;
87
+ }
88
+ for (let i = 0; i <= index; ++i) {
89
+ if (publicUnits[i] !== units[i]) {
90
+ if (!i) {
91
+ return "";
92
+ }
93
+ index = i - 1;
94
+ publicUnits = publicUnits.slice(0, index + 1);
95
+ publicPath = publicUnits.join(node_path.sep) + node_path.sep;
96
+ break;
97
+ }
98
+ }
99
+ }
100
+ return publicPath.slice(0, -1);
101
+ }
102
+ function removeDirIfEmpty(dir) {
103
+ if (!node_fs.existsSync(dir)) {
104
+ return;
105
+ }
106
+ let onlyHasDir = true;
107
+ for (const file of node_fs.readdirSync(dir)) {
108
+ const abs = resolve(dir, file);
109
+ if (node_fs.lstatSync(abs).isDirectory()) {
110
+ if (!removeDirIfEmpty(abs)) {
111
+ onlyHasDir = false;
112
+ }
113
+ } else {
114
+ onlyHasDir = false;
115
+ }
116
+ }
117
+ if (onlyHasDir) {
118
+ node_fs.rmdirSync(dir);
119
+ }
120
+ return onlyHasDir;
121
+ }
122
+ const BASE64_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");
123
+ function base64Encode(number) {
124
+ if (number >= 0 && number < BASE64_ALPHABET.length) {
125
+ return BASE64_ALPHABET[number];
126
+ }
127
+ throw new TypeError("Base64 integer must be between 0 and 63: " + number);
128
+ }
129
+ const VLQ_BASE_SHIFT = 5;
130
+ const VLQ_BASE = 1 << VLQ_BASE_SHIFT;
131
+ const VLQ_BASE_MASK = VLQ_BASE - 1;
132
+ const VLQ_CONTINUATION_BIT = VLQ_BASE;
133
+ function toVLQSigned(number) {
134
+ return number < 0 ? (-number << 1) + 1 : (number << 1) + 0;
135
+ }
136
+ function base64VLQEncode(numbers) {
137
+ let encoded = "";
138
+ for (const number of numbers) {
139
+ let vlq = toVLQSigned(number);
140
+ let digit;
141
+ do {
142
+ digit = vlq & VLQ_BASE_MASK;
143
+ vlq >>>= VLQ_BASE_SHIFT;
144
+ if (vlq > 0) {
145
+ digit |= VLQ_CONTINUATION_BIT;
146
+ }
147
+ encoded += base64Encode(digit);
148
+ } while (vlq > 0);
149
+ }
150
+ return encoded;
151
+ }
152
+ const pkgPathCache = /* @__PURE__ */ new Map();
153
+ function tryGetPkgPath(beginPath) {
154
+ beginPath = normalizePath(beginPath);
155
+ if (pkgPathCache.has(beginPath)) {
156
+ return pkgPathCache.get(beginPath);
157
+ }
158
+ const pkgPath = resolve(beginPath, "package.json");
159
+ if (node_fs.existsSync(pkgPath)) {
160
+ pkgPathCache.set(beginPath, pkgPath);
161
+ return pkgPath;
162
+ }
163
+ const parentDir = normalizePath(node_path.dirname(beginPath));
164
+ if (!parentDir || parentDir === beginPath) {
165
+ pkgPathCache.set(beginPath, void 0);
166
+ return;
167
+ }
168
+ return tryGetPkgPath(parentDir);
169
+ }
170
+
25
171
  const dtsRE$1 = /\.d\.tsx?$/;
26
172
  function rollupDeclarationFiles({
27
173
  root,
@@ -34,8 +180,6 @@ function rollupDeclarationFiles({
34
180
  bundledPackages
35
181
  }) {
36
182
  const configObjectFullPath = node_path.resolve(root, "api-extractor.json");
37
- const packageJsonLookup = new nodeCoreLibrary.PackageJsonLookup();
38
- const packageJsonFullPath = packageJsonLookup.tryGetPackageJsonFilePathFor(configObjectFullPath);
39
183
  if (!dtsRE$1.test(fileName)) {
40
184
  fileName += ".d.ts";
41
185
  }
@@ -48,15 +192,11 @@ function rollupDeclarationFiles({
48
192
  tsconfigFilePath: configPath,
49
193
  overrideTsconfig: {
50
194
  $schema: "http://json.schemastore.org/tsconfig",
51
- compilerOptions: {
52
- ...compilerOptions,
53
- target: "ESNext"
54
- }
195
+ compilerOptions
55
196
  }
56
197
  },
57
198
  apiReport: {
58
- enabled: false,
59
- reportFileName: "<unscopedPackageName>.api.md"
199
+ enabled: false
60
200
  },
61
201
  docModel: {
62
202
  enabled: false
@@ -82,36 +222,15 @@ function rollupDeclarationFiles({
82
222
  }
83
223
  },
84
224
  configObjectFullPath,
85
- packageJsonFullPath
225
+ packageJsonFullPath: tryGetPkgPath(configObjectFullPath)
86
226
  });
87
- const compilerState = apiExtractor.CompilerState.create(extractorConfig, {
227
+ const result = apiExtractor.Extractor.invoke(extractorConfig, {
88
228
  localBuild: false,
89
229
  showVerboseMessages: false,
90
- typescriptCompilerFolder: libFolder ? node_path.resolve(libFolder) : void 0
91
- });
92
- const sourceMapper = new SourceMapper_js.SourceMapper();
93
- const messageRouter = new MessageRouter_js.MessageRouter({
94
- workingPackageFolder: root,
95
- messageCallback: void 0,
96
- messagesConfig: extractorConfig.messages,
97
- showVerboseMessages: false,
98
230
  showDiagnostics: false,
99
- tsdocConfiguration: extractorConfig.tsdocConfiguration,
100
- sourceMapper
101
- });
102
- const collector = new Collector_js.Collector({
103
- program: compilerState.program,
104
- messageRouter,
105
- extractorConfig,
106
- sourceMapper
231
+ typescriptCompilerFolder: libFolder ? node_path.resolve(libFolder) : void 0
107
232
  });
108
- collector.analyze();
109
- DtsRollupGenerator_js.DtsRollupGenerator.writeTypingsFile(
110
- collector,
111
- extractorConfig.publicTrimmedFilePath,
112
- DtsRollupGenerator_js.DtsRollupKind.PublicRelease,
113
- extractorConfig.newlineKind
114
- );
233
+ return result.succeeded;
115
234
  }
116
235
 
117
236
  const jsonRE = /\.json$/;
@@ -163,16 +282,36 @@ function VueResolver() {
163
282
  supports(id) {
164
283
  return vueRE.test(id);
165
284
  },
166
- transform({ id, program, service }) {
285
+ transform({ id, code, program, service }) {
167
286
  const sourceFile = program.getSourceFile(id) || program.getSourceFile(id + ".ts") || program.getSourceFile(id + ".js") || program.getSourceFile(id + ".tsx") || program.getSourceFile(id + ".jsx");
168
287
  if (!sourceFile)
169
288
  return [];
170
- return service.getEmitOutput(sourceFile.fileName, true).outputFiles.map((file) => {
289
+ const outputs = service.getEmitOutput(sourceFile.fileName, true).outputFiles.map((file) => {
171
290
  return {
172
291
  path: file.name,
173
292
  content: file.text
174
293
  };
175
294
  });
295
+ if (!program.getCompilerOptions().declarationMap)
296
+ return outputs;
297
+ const [beforeScript] = code.split(/\s*<script.*>/);
298
+ const beforeLines = beforeScript.split("\n").length;
299
+ for (const output of outputs) {
300
+ if (output.path.endsWith(".map")) {
301
+ try {
302
+ const sourceMap = JSON.parse(output.content);
303
+ sourceMap.sources = sourceMap.sources.map(
304
+ (source) => source.replace(/\.vue\.ts$/, ".vue")
305
+ );
306
+ if (beforeScript && beforeScript !== code && beforeLines) {
307
+ sourceMap.mappings = `${base64VLQEncode([0, 0, beforeLines, 0])};${sourceMap.mappings}`;
308
+ }
309
+ output.content = JSON.stringify(sourceMap);
310
+ } catch (e) {
311
+ }
312
+ }
313
+ }
314
+ return outputs;
176
315
  }
177
316
  };
178
317
  }
@@ -185,106 +324,6 @@ function parseResolvers(resolvers) {
185
324
  return Array.from(nameMap.values());
186
325
  }
187
326
 
188
- const windowsSlashRE = /\\+/g;
189
- function slash(p) {
190
- return p.replace(windowsSlashRE, "/");
191
- }
192
- function normalizePath(id) {
193
- return node_path.posix.normalize(slash(id));
194
- }
195
- function resolve(...paths) {
196
- return normalizePath(node_path.resolve(...paths));
197
- }
198
- function isNativeObj(value) {
199
- return Object.prototype.toString.call(value) === "[object Object]";
200
- }
201
- function isRegExp(value) {
202
- return Object.prototype.toString.call(value) === "[object RegExp]";
203
- }
204
- function isPromise(value) {
205
- return !!value && (typeof value === "function" || typeof value === "object") && typeof value.then === "function";
206
- }
207
- function ensureAbsolute(path, root) {
208
- return normalizePath(path ? node_path.isAbsolute(path) ? path : resolve(root, path) : root);
209
- }
210
- function ensureArray(value) {
211
- return Array.isArray(value) ? value : value ? [value] : [];
212
- }
213
- async function runParallel(maxConcurrency, source, iteratorFn) {
214
- const ret = [];
215
- const executing = [];
216
- for (const item of source) {
217
- const p = Promise.resolve().then(() => iteratorFn(item, source));
218
- ret.push(p);
219
- if (maxConcurrency <= source.length) {
220
- const e = p.then(() => executing.splice(executing.indexOf(e), 1));
221
- executing.push(e);
222
- if (executing.length >= maxConcurrency) {
223
- await Promise.race(executing);
224
- }
225
- }
226
- }
227
- return Promise.all(ret);
228
- }
229
- const speRE = /[\\/]/;
230
- function queryPublicPath(paths) {
231
- if (paths.length === 0) {
232
- return "";
233
- } else if (paths.length === 1) {
234
- return node_path.dirname(paths[0]);
235
- }
236
- let publicPath = node_path.normalize(node_path.dirname(paths[0])) + node_path.sep;
237
- let publicUnits = publicPath.split(speRE);
238
- let index = publicUnits.length - 1;
239
- for (const path of paths.slice(1)) {
240
- if (!index) {
241
- return publicPath;
242
- }
243
- const dirPath = node_path.normalize(node_path.dirname(path)) + node_path.sep;
244
- if (dirPath.startsWith(publicPath)) {
245
- continue;
246
- }
247
- const units = dirPath.split(speRE);
248
- if (units.length < index) {
249
- publicPath = dirPath;
250
- publicUnits = units;
251
- continue;
252
- }
253
- for (let i = 0; i <= index; ++i) {
254
- if (publicUnits[i] !== units[i]) {
255
- if (!i) {
256
- return "";
257
- }
258
- index = i - 1;
259
- publicUnits = publicUnits.slice(0, index + 1);
260
- publicPath = publicUnits.join(node_path.sep) + node_path.sep;
261
- break;
262
- }
263
- }
264
- }
265
- return publicPath.slice(0, -1);
266
- }
267
- function removeDirIfEmpty(dir) {
268
- if (!node_fs.existsSync(dir)) {
269
- return;
270
- }
271
- let onlyHasDir = true;
272
- for (const file of node_fs.readdirSync(dir)) {
273
- const abs = resolve(dir, file);
274
- if (node_fs.lstatSync(abs).isDirectory()) {
275
- if (!removeDirIfEmpty(abs)) {
276
- onlyHasDir = false;
277
- }
278
- } else {
279
- onlyHasDir = false;
280
- }
281
- }
282
- if (onlyHasDir) {
283
- node_fs.rmdirSync(dir);
284
- }
285
- return onlyHasDir;
286
- }
287
-
288
327
  const globSuffixRE = /^((?:.*\.[^.]+)|(?:\*+))$/;
289
328
  function normalizeGlob(path) {
290
329
  if (/[\\/]$/.test(path)) {
@@ -587,8 +626,7 @@ ${kolorist.cyan(
587
626
  logger.error(ts__default.formatDiagnostics(diagnostics, host));
588
627
  }
589
628
  if (typeof afterDiagnostic === "function") {
590
- const result = afterDiagnostic(diagnostics);
591
- isPromise(result) && await result;
629
+ await wrapPromise(afterDiagnostic(diagnostics));
592
630
  }
593
631
  rootNames.forEach((file) => {
594
632
  this.addWatchFile(file);
@@ -599,13 +637,14 @@ ${kolorist.cyan(
599
637
  },
600
638
  async transform(code, id) {
601
639
  let resolver;
602
- id = normalizePath(id).split("?")[0];
640
+ id = normalizePath(id);
603
641
  if (!host || !program || !filter(id) || !(resolver = resolvers.find((r) => r.supports(id))) && !tjsRE.test(id)) {
604
642
  return;
605
643
  }
606
644
  const startTime = Date.now();
607
645
  const outDir = outDirs[0];
608
646
  const service = program.__vue.languageService;
647
+ id = id.split("?")[0];
609
648
  rootFiles.delete(id);
610
649
  if (resolver) {
611
650
  const result = await resolver.transform({
@@ -640,11 +679,12 @@ ${kolorist.cyan(
640
679
  timeRecord += Date.now() - startTime;
641
680
  },
642
681
  watchChange(id) {
643
- id = normalizePath(id).split("?")[0];
682
+ id = normalizePath(id);
644
683
  if (!host || !program || !filter(id) || !resolvers.find((r) => r.supports(id)) && !tjsRE.test(id)) {
645
684
  return;
646
685
  }
647
- const sourceFile = host.getSourceFile(normalizePath(id), ts__default.ScriptTarget.ESNext);
686
+ id = id.split("?")[0];
687
+ const sourceFile = host.getSourceFile(id, ts__default.ScriptTarget.ESNext);
648
688
  if (sourceFile) {
649
689
  rootFiles.add(sourceFile.fileName);
650
690
  program.__vue.projectVersion++;
@@ -662,7 +702,16 @@ ${logPrefix} Start generate declaration files...`));
662
702
  const startTime = Date.now();
663
703
  const outDir = outDirs[0];
664
704
  const emittedFiles = /* @__PURE__ */ new Map();
665
- const writeOutput = async (path, content, outDir2) => {
705
+ const writeOutput = async (path, content, outDir2, record = true) => {
706
+ if (typeof beforeWriteFile === "function") {
707
+ const result = await wrapPromise(beforeWriteFile(path, content));
708
+ if (result === false)
709
+ return;
710
+ if (result) {
711
+ path = result.filePath || path;
712
+ content = result.content ?? content;
713
+ }
714
+ }
666
715
  path = normalizePath(path);
667
716
  const dir = normalizePath(node_path.dirname(path));
668
717
  if (strictOutput && !dir.startsWith(normalizePath(outDir2))) {
@@ -673,7 +722,7 @@ ${logPrefix} Start generate declaration files...`));
673
722
  await promises.mkdir(dir, { recursive: true });
674
723
  }
675
724
  await promises.writeFile(path, content, "utf-8");
676
- emittedFiles.set(path, content);
725
+ record && emittedFiles.set(path, content);
677
726
  };
678
727
  const service = program.__vue.languageService;
679
728
  const sourceFiles = program.getSourceFiles();
@@ -699,6 +748,7 @@ ${logPrefix} Start generate declaration files...`));
699
748
  Array.from(outputFiles.entries()),
700
749
  async ([path, content]) => {
701
750
  const isMapFile = path.endsWith(".map");
751
+ const baseDir = node_path.dirname(path);
702
752
  if (!isMapFile && content) {
703
753
  content = clearPureImport ? removePureImport(content) : content;
704
754
  content = transformAliasImport(path, content, aliases, aliasesExclude);
@@ -709,13 +759,15 @@ ${logPrefix} Start generate declaration files...`));
709
759
  node_path.relative(entryRoot, cleanVueFileName ? path.replace(".vue.d.ts", ".d.ts") : path)
710
760
  );
711
761
  content = cleanVueFileName ? content.replace(/['"](.+)\.vue['"]/g, '"$1"') : content;
712
- if (typeof beforeWriteFile === "function") {
713
- const result = beforeWriteFile(path, content);
714
- if (result === false)
715
- return;
716
- if (result && isNativeObj(result)) {
717
- path = result.filePath || path;
718
- content = result.content ?? content;
762
+ if (isMapFile) {
763
+ try {
764
+ const sourceMap = JSON.parse(content);
765
+ sourceMap.sources = sourceMap.sources.map((source) => {
766
+ return normalizePath(node_path.relative(node_path.dirname(path), resolve(baseDir, source)));
767
+ });
768
+ content = JSON.stringify(sourceMap);
769
+ } catch (e) {
770
+ logger.warn(`${logPrefix} ${kolorist.yellow("Processing source map fail:")} ${path}`);
719
771
  }
720
772
  }
721
773
  await writeOutput(path, content, outDir);
@@ -723,14 +775,18 @@ ${logPrefix} Start generate declaration files...`));
723
775
  );
724
776
  bundleDebug("write output");
725
777
  if (insertTypesEntry || rollupTypes) {
726
- const pkgPath = resolve(root, "package.json");
727
- const pkg = node_fs.existsSync(pkgPath) ? JSON.parse(await promises.readFile(pkgPath, "utf-8")) : {};
778
+ const pkgPath = tryGetPkgPath(root);
779
+ let pkg;
780
+ try {
781
+ pkg = pkgPath && node_fs.existsSync(pkgPath) ? JSON.parse(await promises.readFile(pkgPath, "utf-8")) : {};
782
+ } catch (e) {
783
+ }
728
784
  const entryNames = Object.keys(entries);
729
785
  const types = pkg.types || pkg.typings || pkg.publishConfig?.types || pkg.publishConfig?.typings || (pkg.exports?.["."] || pkg.exports?.["./"])?.types;
730
786
  const multiple = entryNames.length > 1;
731
787
  const typesPath = types ? resolve(root, types) : resolve(outDir, indexName);
732
788
  for (const name of entryNames) {
733
- let path = multiple ? resolve(outDir, `${name.replace(tsRE, "")}.d.ts`) : typesPath;
789
+ const path = multiple ? resolve(outDir, `${name.replace(tsRE, "")}.d.ts`) : typesPath;
734
790
  if (node_fs.existsSync(path))
735
791
  continue;
736
792
  const index = resolve(
@@ -750,15 +806,6 @@ export default ${libName}
750
806
  `;
751
807
  }
752
808
  }
753
- if (typeof beforeWriteFile === "function") {
754
- const result = beforeWriteFile(path, content);
755
- if (result === false)
756
- return;
757
- if (result && isNativeObj(result)) {
758
- path = result.filePath ?? path;
759
- content = result.content ?? content;
760
- }
761
- }
762
809
  await writeOutput(path, content, outDir);
763
810
  }
764
811
  bundleDebug("insert index");
@@ -818,15 +865,29 @@ export default ${libName}
818
865
  await runParallel(node_os.cpus().length, Array.from(emittedFiles), async ([wroteFile, content]) => {
819
866
  const relativePath = node_path.relative(outDir, wroteFile);
820
867
  await Promise.all(
821
- extraOutDirs.map(async (outDir2) => {
822
- await writeOutput(resolve(outDir2, relativePath), content, outDir2);
868
+ extraOutDirs.map(async (targetOutDir) => {
869
+ const path = resolve(targetOutDir, relativePath);
870
+ if (wroteFile.endsWith(".map")) {
871
+ const relativeOutDir = node_path.relative(outDir, targetOutDir);
872
+ if (relativeOutDir) {
873
+ try {
874
+ const sourceMap = JSON.parse(content);
875
+ sourceMap.sources = sourceMap.sources.map((source) => {
876
+ return normalizePath(node_path.relative(relativeOutDir, source));
877
+ });
878
+ content = JSON.stringify(sourceMap);
879
+ } catch (e) {
880
+ logger.warn(`${logPrefix} ${kolorist.yellow("Processing source map fail:")} ${path}`);
881
+ }
882
+ }
883
+ }
884
+ await writeOutput(path, content, targetOutDir, false);
823
885
  })
824
886
  );
825
887
  });
826
888
  }
827
889
  if (typeof afterBuild === "function") {
828
- const result = afterBuild();
829
- isPromise(result) && await result;
890
+ await wrapPromise(afterBuild());
830
891
  }
831
892
  bundleDebug("finish");
832
893
  logger.info(
package/dist/index.d.ts CHANGED
@@ -181,14 +181,14 @@ interface PluginOptions {
181
181
  *
182
182
  * This allows you to transform the path or content
183
183
  *
184
- * The file will be skipped when the return value `false`
184
+ * The file will be skipped when the return value `false` or `Promise<false>`
185
185
  *
186
186
  * @default () => {}
187
187
  */
188
- beforeWriteFile?: (filePath: string, content: string) => void | false | {
188
+ beforeWriteFile?: (filePath: string, content: string) => MaybePromise<void | false | {
189
189
  filePath?: string;
190
190
  content?: string;
191
- };
191
+ }>;
192
192
  /**
193
193
  * Hook called after all declaration files are written
194
194
  *
package/dist/index.mjs CHANGED
@@ -5,7 +5,7 @@ import __cjs_mod__ from 'module';
5
5
  const __filename = __cjs_url__.fileURLToPath(import.meta.url);
6
6
  const __dirname = __cjs_path__.dirname(__filename);
7
7
  const require = __cjs_mod__.createRequire(import.meta.url);
8
- import { resolve as resolve$1, relative, posix, isAbsolute, dirname, normalize, sep, basename } from 'node:path';
8
+ import { posix, resolve as resolve$1, isAbsolute, dirname, normalize, sep, relative, basename } from 'node:path';
9
9
  import { existsSync, readdirSync, lstatSync, rmdirSync } from 'node:fs';
10
10
  import { readFile, mkdir, writeFile, unlink } from 'node:fs/promises';
11
11
  import { cpus } from 'node:os';
@@ -15,12 +15,158 @@ import { createFilter } from '@rollup/pluginutils';
15
15
  import { createProgram } from 'vue-tsc';
16
16
  import debug from 'debug';
17
17
  import { cyan, yellow, green } from 'kolorist';
18
- import { ExtractorConfig, CompilerState } from '@microsoft/api-extractor';
19
- import { Collector } from '@microsoft/api-extractor/lib/collector/Collector.js';
20
- import { MessageRouter } from '@microsoft/api-extractor/lib/collector/MessageRouter.js';
21
- import { SourceMapper } from '@microsoft/api-extractor/lib/collector/SourceMapper.js';
22
- import { DtsRollupGenerator, DtsRollupKind } from '@microsoft/api-extractor/lib/generators/DtsRollupGenerator.js';
23
- import { PackageJsonLookup } from '@rushstack/node-core-library';
18
+ import { ExtractorConfig, Extractor } from '@microsoft/api-extractor';
19
+
20
+ const windowsSlashRE = /\\+/g;
21
+ function slash(p) {
22
+ return p.replace(windowsSlashRE, "/");
23
+ }
24
+ function normalizePath(id) {
25
+ return posix.normalize(slash(id));
26
+ }
27
+ function resolve(...paths) {
28
+ return normalizePath(resolve$1(...paths));
29
+ }
30
+ function isNativeObj(value) {
31
+ return Object.prototype.toString.call(value) === "[object Object]";
32
+ }
33
+ function isRegExp(value) {
34
+ return Object.prototype.toString.call(value) === "[object RegExp]";
35
+ }
36
+ function isPromise(value) {
37
+ return !!value && (typeof value === "function" || typeof value === "object") && typeof value.then === "function";
38
+ }
39
+ async function wrapPromise(maybePromise) {
40
+ return isPromise(maybePromise) ? await maybePromise : maybePromise;
41
+ }
42
+ function ensureAbsolute(path, root) {
43
+ return normalizePath(path ? isAbsolute(path) ? path : resolve(root, path) : root);
44
+ }
45
+ function ensureArray(value) {
46
+ return Array.isArray(value) ? value : value ? [value] : [];
47
+ }
48
+ async function runParallel(maxConcurrency, source, iteratorFn) {
49
+ const ret = [];
50
+ const executing = [];
51
+ for (const item of source) {
52
+ const p = Promise.resolve().then(() => iteratorFn(item, source));
53
+ ret.push(p);
54
+ if (maxConcurrency <= source.length) {
55
+ const e = p.then(() => executing.splice(executing.indexOf(e), 1));
56
+ executing.push(e);
57
+ if (executing.length >= maxConcurrency) {
58
+ await Promise.race(executing);
59
+ }
60
+ }
61
+ }
62
+ return Promise.all(ret);
63
+ }
64
+ const speRE = /[\\/]/;
65
+ function queryPublicPath(paths) {
66
+ if (paths.length === 0) {
67
+ return "";
68
+ } else if (paths.length === 1) {
69
+ return dirname(paths[0]);
70
+ }
71
+ let publicPath = normalize(dirname(paths[0])) + sep;
72
+ let publicUnits = publicPath.split(speRE);
73
+ let index = publicUnits.length - 1;
74
+ for (const path of paths.slice(1)) {
75
+ if (!index) {
76
+ return publicPath;
77
+ }
78
+ const dirPath = normalize(dirname(path)) + sep;
79
+ if (dirPath.startsWith(publicPath)) {
80
+ continue;
81
+ }
82
+ const units = dirPath.split(speRE);
83
+ if (units.length < index) {
84
+ publicPath = dirPath;
85
+ publicUnits = units;
86
+ continue;
87
+ }
88
+ for (let i = 0; i <= index; ++i) {
89
+ if (publicUnits[i] !== units[i]) {
90
+ if (!i) {
91
+ return "";
92
+ }
93
+ index = i - 1;
94
+ publicUnits = publicUnits.slice(0, index + 1);
95
+ publicPath = publicUnits.join(sep) + sep;
96
+ break;
97
+ }
98
+ }
99
+ }
100
+ return publicPath.slice(0, -1);
101
+ }
102
+ function removeDirIfEmpty(dir) {
103
+ if (!existsSync(dir)) {
104
+ return;
105
+ }
106
+ let onlyHasDir = true;
107
+ for (const file of readdirSync(dir)) {
108
+ const abs = resolve(dir, file);
109
+ if (lstatSync(abs).isDirectory()) {
110
+ if (!removeDirIfEmpty(abs)) {
111
+ onlyHasDir = false;
112
+ }
113
+ } else {
114
+ onlyHasDir = false;
115
+ }
116
+ }
117
+ if (onlyHasDir) {
118
+ rmdirSync(dir);
119
+ }
120
+ return onlyHasDir;
121
+ }
122
+ const BASE64_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");
123
+ function base64Encode(number) {
124
+ if (number >= 0 && number < BASE64_ALPHABET.length) {
125
+ return BASE64_ALPHABET[number];
126
+ }
127
+ throw new TypeError("Base64 integer must be between 0 and 63: " + number);
128
+ }
129
+ const VLQ_BASE_SHIFT = 5;
130
+ const VLQ_BASE = 1 << VLQ_BASE_SHIFT;
131
+ const VLQ_BASE_MASK = VLQ_BASE - 1;
132
+ const VLQ_CONTINUATION_BIT = VLQ_BASE;
133
+ function toVLQSigned(number) {
134
+ return number < 0 ? (-number << 1) + 1 : (number << 1) + 0;
135
+ }
136
+ function base64VLQEncode(numbers) {
137
+ let encoded = "";
138
+ for (const number of numbers) {
139
+ let vlq = toVLQSigned(number);
140
+ let digit;
141
+ do {
142
+ digit = vlq & VLQ_BASE_MASK;
143
+ vlq >>>= VLQ_BASE_SHIFT;
144
+ if (vlq > 0) {
145
+ digit |= VLQ_CONTINUATION_BIT;
146
+ }
147
+ encoded += base64Encode(digit);
148
+ } while (vlq > 0);
149
+ }
150
+ return encoded;
151
+ }
152
+ const pkgPathCache = /* @__PURE__ */ new Map();
153
+ function tryGetPkgPath(beginPath) {
154
+ beginPath = normalizePath(beginPath);
155
+ if (pkgPathCache.has(beginPath)) {
156
+ return pkgPathCache.get(beginPath);
157
+ }
158
+ const pkgPath = resolve(beginPath, "package.json");
159
+ if (existsSync(pkgPath)) {
160
+ pkgPathCache.set(beginPath, pkgPath);
161
+ return pkgPath;
162
+ }
163
+ const parentDir = normalizePath(dirname(beginPath));
164
+ if (!parentDir || parentDir === beginPath) {
165
+ pkgPathCache.set(beginPath, void 0);
166
+ return;
167
+ }
168
+ return tryGetPkgPath(parentDir);
169
+ }
24
170
 
25
171
  const dtsRE$1 = /\.d\.tsx?$/;
26
172
  function rollupDeclarationFiles({
@@ -34,8 +180,6 @@ function rollupDeclarationFiles({
34
180
  bundledPackages
35
181
  }) {
36
182
  const configObjectFullPath = resolve$1(root, "api-extractor.json");
37
- const packageJsonLookup = new PackageJsonLookup();
38
- const packageJsonFullPath = packageJsonLookup.tryGetPackageJsonFilePathFor(configObjectFullPath);
39
183
  if (!dtsRE$1.test(fileName)) {
40
184
  fileName += ".d.ts";
41
185
  }
@@ -48,15 +192,11 @@ function rollupDeclarationFiles({
48
192
  tsconfigFilePath: configPath,
49
193
  overrideTsconfig: {
50
194
  $schema: "http://json.schemastore.org/tsconfig",
51
- compilerOptions: {
52
- ...compilerOptions,
53
- target: "ESNext"
54
- }
195
+ compilerOptions
55
196
  }
56
197
  },
57
198
  apiReport: {
58
- enabled: false,
59
- reportFileName: "<unscopedPackageName>.api.md"
199
+ enabled: false
60
200
  },
61
201
  docModel: {
62
202
  enabled: false
@@ -82,36 +222,15 @@ function rollupDeclarationFiles({
82
222
  }
83
223
  },
84
224
  configObjectFullPath,
85
- packageJsonFullPath
225
+ packageJsonFullPath: tryGetPkgPath(configObjectFullPath)
86
226
  });
87
- const compilerState = CompilerState.create(extractorConfig, {
227
+ const result = Extractor.invoke(extractorConfig, {
88
228
  localBuild: false,
89
229
  showVerboseMessages: false,
90
- typescriptCompilerFolder: libFolder ? resolve$1(libFolder) : void 0
91
- });
92
- const sourceMapper = new SourceMapper();
93
- const messageRouter = new MessageRouter({
94
- workingPackageFolder: root,
95
- messageCallback: void 0,
96
- messagesConfig: extractorConfig.messages,
97
- showVerboseMessages: false,
98
230
  showDiagnostics: false,
99
- tsdocConfiguration: extractorConfig.tsdocConfiguration,
100
- sourceMapper
101
- });
102
- const collector = new Collector({
103
- program: compilerState.program,
104
- messageRouter,
105
- extractorConfig,
106
- sourceMapper
231
+ typescriptCompilerFolder: libFolder ? resolve$1(libFolder) : void 0
107
232
  });
108
- collector.analyze();
109
- DtsRollupGenerator.writeTypingsFile(
110
- collector,
111
- extractorConfig.publicTrimmedFilePath,
112
- DtsRollupKind.PublicRelease,
113
- extractorConfig.newlineKind
114
- );
233
+ return result.succeeded;
115
234
  }
116
235
 
117
236
  const jsonRE = /\.json$/;
@@ -163,16 +282,36 @@ function VueResolver() {
163
282
  supports(id) {
164
283
  return vueRE.test(id);
165
284
  },
166
- transform({ id, program, service }) {
285
+ transform({ id, code, program, service }) {
167
286
  const sourceFile = program.getSourceFile(id) || program.getSourceFile(id + ".ts") || program.getSourceFile(id + ".js") || program.getSourceFile(id + ".tsx") || program.getSourceFile(id + ".jsx");
168
287
  if (!sourceFile)
169
288
  return [];
170
- return service.getEmitOutput(sourceFile.fileName, true).outputFiles.map((file) => {
289
+ const outputs = service.getEmitOutput(sourceFile.fileName, true).outputFiles.map((file) => {
171
290
  return {
172
291
  path: file.name,
173
292
  content: file.text
174
293
  };
175
294
  });
295
+ if (!program.getCompilerOptions().declarationMap)
296
+ return outputs;
297
+ const [beforeScript] = code.split(/\s*<script.*>/);
298
+ const beforeLines = beforeScript.split("\n").length;
299
+ for (const output of outputs) {
300
+ if (output.path.endsWith(".map")) {
301
+ try {
302
+ const sourceMap = JSON.parse(output.content);
303
+ sourceMap.sources = sourceMap.sources.map(
304
+ (source) => source.replace(/\.vue\.ts$/, ".vue")
305
+ );
306
+ if (beforeScript && beforeScript !== code && beforeLines) {
307
+ sourceMap.mappings = `${base64VLQEncode([0, 0, beforeLines, 0])};${sourceMap.mappings}`;
308
+ }
309
+ output.content = JSON.stringify(sourceMap);
310
+ } catch (e) {
311
+ }
312
+ }
313
+ }
314
+ return outputs;
176
315
  }
177
316
  };
178
317
  }
@@ -185,106 +324,6 @@ function parseResolvers(resolvers) {
185
324
  return Array.from(nameMap.values());
186
325
  }
187
326
 
188
- const windowsSlashRE = /\\+/g;
189
- function slash(p) {
190
- return p.replace(windowsSlashRE, "/");
191
- }
192
- function normalizePath(id) {
193
- return posix.normalize(slash(id));
194
- }
195
- function resolve(...paths) {
196
- return normalizePath(resolve$1(...paths));
197
- }
198
- function isNativeObj(value) {
199
- return Object.prototype.toString.call(value) === "[object Object]";
200
- }
201
- function isRegExp(value) {
202
- return Object.prototype.toString.call(value) === "[object RegExp]";
203
- }
204
- function isPromise(value) {
205
- return !!value && (typeof value === "function" || typeof value === "object") && typeof value.then === "function";
206
- }
207
- function ensureAbsolute(path, root) {
208
- return normalizePath(path ? isAbsolute(path) ? path : resolve(root, path) : root);
209
- }
210
- function ensureArray(value) {
211
- return Array.isArray(value) ? value : value ? [value] : [];
212
- }
213
- async function runParallel(maxConcurrency, source, iteratorFn) {
214
- const ret = [];
215
- const executing = [];
216
- for (const item of source) {
217
- const p = Promise.resolve().then(() => iteratorFn(item, source));
218
- ret.push(p);
219
- if (maxConcurrency <= source.length) {
220
- const e = p.then(() => executing.splice(executing.indexOf(e), 1));
221
- executing.push(e);
222
- if (executing.length >= maxConcurrency) {
223
- await Promise.race(executing);
224
- }
225
- }
226
- }
227
- return Promise.all(ret);
228
- }
229
- const speRE = /[\\/]/;
230
- function queryPublicPath(paths) {
231
- if (paths.length === 0) {
232
- return "";
233
- } else if (paths.length === 1) {
234
- return dirname(paths[0]);
235
- }
236
- let publicPath = normalize(dirname(paths[0])) + sep;
237
- let publicUnits = publicPath.split(speRE);
238
- let index = publicUnits.length - 1;
239
- for (const path of paths.slice(1)) {
240
- if (!index) {
241
- return publicPath;
242
- }
243
- const dirPath = normalize(dirname(path)) + sep;
244
- if (dirPath.startsWith(publicPath)) {
245
- continue;
246
- }
247
- const units = dirPath.split(speRE);
248
- if (units.length < index) {
249
- publicPath = dirPath;
250
- publicUnits = units;
251
- continue;
252
- }
253
- for (let i = 0; i <= index; ++i) {
254
- if (publicUnits[i] !== units[i]) {
255
- if (!i) {
256
- return "";
257
- }
258
- index = i - 1;
259
- publicUnits = publicUnits.slice(0, index + 1);
260
- publicPath = publicUnits.join(sep) + sep;
261
- break;
262
- }
263
- }
264
- }
265
- return publicPath.slice(0, -1);
266
- }
267
- function removeDirIfEmpty(dir) {
268
- if (!existsSync(dir)) {
269
- return;
270
- }
271
- let onlyHasDir = true;
272
- for (const file of readdirSync(dir)) {
273
- const abs = resolve(dir, file);
274
- if (lstatSync(abs).isDirectory()) {
275
- if (!removeDirIfEmpty(abs)) {
276
- onlyHasDir = false;
277
- }
278
- } else {
279
- onlyHasDir = false;
280
- }
281
- }
282
- if (onlyHasDir) {
283
- rmdirSync(dir);
284
- }
285
- return onlyHasDir;
286
- }
287
-
288
327
  const globSuffixRE = /^((?:.*\.[^.]+)|(?:\*+))$/;
289
328
  function normalizeGlob(path) {
290
329
  if (/[\\/]$/.test(path)) {
@@ -587,8 +626,7 @@ ${cyan(
587
626
  logger.error(ts.formatDiagnostics(diagnostics, host));
588
627
  }
589
628
  if (typeof afterDiagnostic === "function") {
590
- const result = afterDiagnostic(diagnostics);
591
- isPromise(result) && await result;
629
+ await wrapPromise(afterDiagnostic(diagnostics));
592
630
  }
593
631
  rootNames.forEach((file) => {
594
632
  this.addWatchFile(file);
@@ -599,13 +637,14 @@ ${cyan(
599
637
  },
600
638
  async transform(code, id) {
601
639
  let resolver;
602
- id = normalizePath(id).split("?")[0];
640
+ id = normalizePath(id);
603
641
  if (!host || !program || !filter(id) || !(resolver = resolvers.find((r) => r.supports(id))) && !tjsRE.test(id)) {
604
642
  return;
605
643
  }
606
644
  const startTime = Date.now();
607
645
  const outDir = outDirs[0];
608
646
  const service = program.__vue.languageService;
647
+ id = id.split("?")[0];
609
648
  rootFiles.delete(id);
610
649
  if (resolver) {
611
650
  const result = await resolver.transform({
@@ -640,11 +679,12 @@ ${cyan(
640
679
  timeRecord += Date.now() - startTime;
641
680
  },
642
681
  watchChange(id) {
643
- id = normalizePath(id).split("?")[0];
682
+ id = normalizePath(id);
644
683
  if (!host || !program || !filter(id) || !resolvers.find((r) => r.supports(id)) && !tjsRE.test(id)) {
645
684
  return;
646
685
  }
647
- const sourceFile = host.getSourceFile(normalizePath(id), ts.ScriptTarget.ESNext);
686
+ id = id.split("?")[0];
687
+ const sourceFile = host.getSourceFile(id, ts.ScriptTarget.ESNext);
648
688
  if (sourceFile) {
649
689
  rootFiles.add(sourceFile.fileName);
650
690
  program.__vue.projectVersion++;
@@ -662,7 +702,16 @@ ${logPrefix} Start generate declaration files...`));
662
702
  const startTime = Date.now();
663
703
  const outDir = outDirs[0];
664
704
  const emittedFiles = /* @__PURE__ */ new Map();
665
- const writeOutput = async (path, content, outDir2) => {
705
+ const writeOutput = async (path, content, outDir2, record = true) => {
706
+ if (typeof beforeWriteFile === "function") {
707
+ const result = await wrapPromise(beforeWriteFile(path, content));
708
+ if (result === false)
709
+ return;
710
+ if (result) {
711
+ path = result.filePath || path;
712
+ content = result.content ?? content;
713
+ }
714
+ }
666
715
  path = normalizePath(path);
667
716
  const dir = normalizePath(dirname(path));
668
717
  if (strictOutput && !dir.startsWith(normalizePath(outDir2))) {
@@ -673,7 +722,7 @@ ${logPrefix} Start generate declaration files...`));
673
722
  await mkdir(dir, { recursive: true });
674
723
  }
675
724
  await writeFile(path, content, "utf-8");
676
- emittedFiles.set(path, content);
725
+ record && emittedFiles.set(path, content);
677
726
  };
678
727
  const service = program.__vue.languageService;
679
728
  const sourceFiles = program.getSourceFiles();
@@ -699,6 +748,7 @@ ${logPrefix} Start generate declaration files...`));
699
748
  Array.from(outputFiles.entries()),
700
749
  async ([path, content]) => {
701
750
  const isMapFile = path.endsWith(".map");
751
+ const baseDir = dirname(path);
702
752
  if (!isMapFile && content) {
703
753
  content = clearPureImport ? removePureImport(content) : content;
704
754
  content = transformAliasImport(path, content, aliases, aliasesExclude);
@@ -709,13 +759,15 @@ ${logPrefix} Start generate declaration files...`));
709
759
  relative(entryRoot, cleanVueFileName ? path.replace(".vue.d.ts", ".d.ts") : path)
710
760
  );
711
761
  content = cleanVueFileName ? content.replace(/['"](.+)\.vue['"]/g, '"$1"') : content;
712
- if (typeof beforeWriteFile === "function") {
713
- const result = beforeWriteFile(path, content);
714
- if (result === false)
715
- return;
716
- if (result && isNativeObj(result)) {
717
- path = result.filePath || path;
718
- content = result.content ?? content;
762
+ if (isMapFile) {
763
+ try {
764
+ const sourceMap = JSON.parse(content);
765
+ sourceMap.sources = sourceMap.sources.map((source) => {
766
+ return normalizePath(relative(dirname(path), resolve(baseDir, source)));
767
+ });
768
+ content = JSON.stringify(sourceMap);
769
+ } catch (e) {
770
+ logger.warn(`${logPrefix} ${yellow("Processing source map fail:")} ${path}`);
719
771
  }
720
772
  }
721
773
  await writeOutput(path, content, outDir);
@@ -723,14 +775,18 @@ ${logPrefix} Start generate declaration files...`));
723
775
  );
724
776
  bundleDebug("write output");
725
777
  if (insertTypesEntry || rollupTypes) {
726
- const pkgPath = resolve(root, "package.json");
727
- const pkg = existsSync(pkgPath) ? JSON.parse(await readFile(pkgPath, "utf-8")) : {};
778
+ const pkgPath = tryGetPkgPath(root);
779
+ let pkg;
780
+ try {
781
+ pkg = pkgPath && existsSync(pkgPath) ? JSON.parse(await readFile(pkgPath, "utf-8")) : {};
782
+ } catch (e) {
783
+ }
728
784
  const entryNames = Object.keys(entries);
729
785
  const types = pkg.types || pkg.typings || pkg.publishConfig?.types || pkg.publishConfig?.typings || (pkg.exports?.["."] || pkg.exports?.["./"])?.types;
730
786
  const multiple = entryNames.length > 1;
731
787
  const typesPath = types ? resolve(root, types) : resolve(outDir, indexName);
732
788
  for (const name of entryNames) {
733
- let path = multiple ? resolve(outDir, `${name.replace(tsRE, "")}.d.ts`) : typesPath;
789
+ const path = multiple ? resolve(outDir, `${name.replace(tsRE, "")}.d.ts`) : typesPath;
734
790
  if (existsSync(path))
735
791
  continue;
736
792
  const index = resolve(
@@ -750,15 +806,6 @@ export default ${libName}
750
806
  `;
751
807
  }
752
808
  }
753
- if (typeof beforeWriteFile === "function") {
754
- const result = beforeWriteFile(path, content);
755
- if (result === false)
756
- return;
757
- if (result && isNativeObj(result)) {
758
- path = result.filePath ?? path;
759
- content = result.content ?? content;
760
- }
761
- }
762
809
  await writeOutput(path, content, outDir);
763
810
  }
764
811
  bundleDebug("insert index");
@@ -818,15 +865,29 @@ export default ${libName}
818
865
  await runParallel(cpus().length, Array.from(emittedFiles), async ([wroteFile, content]) => {
819
866
  const relativePath = relative(outDir, wroteFile);
820
867
  await Promise.all(
821
- extraOutDirs.map(async (outDir2) => {
822
- await writeOutput(resolve(outDir2, relativePath), content, outDir2);
868
+ extraOutDirs.map(async (targetOutDir) => {
869
+ const path = resolve(targetOutDir, relativePath);
870
+ if (wroteFile.endsWith(".map")) {
871
+ const relativeOutDir = relative(outDir, targetOutDir);
872
+ if (relativeOutDir) {
873
+ try {
874
+ const sourceMap = JSON.parse(content);
875
+ sourceMap.sources = sourceMap.sources.map((source) => {
876
+ return normalizePath(relative(relativeOutDir, source));
877
+ });
878
+ content = JSON.stringify(sourceMap);
879
+ } catch (e) {
880
+ logger.warn(`${logPrefix} ${yellow("Processing source map fail:")} ${path}`);
881
+ }
882
+ }
883
+ }
884
+ await writeOutput(path, content, targetOutDir, false);
823
885
  })
824
886
  );
825
887
  });
826
888
  }
827
889
  if (typeof afterBuild === "function") {
828
- const result = afterBuild();
829
- isPromise(result) && await result;
890
+ await wrapPromise(afterBuild());
830
891
  }
831
892
  bundleDebug("finish");
832
893
  logger.info(
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vite-plugin-dts",
3
- "version": "3.2.0",
3
+ "version": "3.3.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "author": "qmhc",
@@ -55,7 +55,6 @@
55
55
  "dependencies": {
56
56
  "@microsoft/api-extractor": "^7.36.0",
57
57
  "@rollup/pluginutils": "^5.0.2",
58
- "@rushstack/node-core-library": "^3.59.4",
59
58
  "@vue/language-core": "^1.8.1",
60
59
  "debug": "^4.3.4",
61
60
  "kolorist": "^1.8.0",
@@ -96,10 +95,12 @@
96
95
  "vitest": "^0.32.2"
97
96
  },
98
97
  "peerDependencies": {
99
- "typescript": "*"
100
- },
101
- "optionalDependencies": {
102
- "rollup": "*",
98
+ "typescript": "*",
103
99
  "vite": "*"
100
+ },
101
+ "peerDependenciesMeta": {
102
+ "vite": {
103
+ "optional": true
104
+ }
104
105
  }
105
106
  }