vite-plugin-dts 2.3.0 → 3.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,19 +1,15 @@
1
1
  'use strict';
2
2
 
3
3
  const node_path = require('node:path');
4
- const fs = require('fs-extra');
5
- const os = require('os');
6
- const kolorist = require('kolorist');
7
- const glob = require('fast-glob');
8
- const debug = require('debug');
9
- const tsMorph = require('ts-morph');
10
- const vite = require('vite');
11
- const pluginutils = require('@rollup/pluginutils');
12
4
  const node_fs = require('node:fs');
13
- const typescript = require('typescript');
14
- const node_module = require('node:module');
15
- const parser = require('@babel/parser');
16
- const MagicString = require('magic-string');
5
+ const promises = require('node:fs/promises');
6
+ const node_os = require('node:os');
7
+ const ts = require('typescript');
8
+ const pluginutils = require('@rollup/pluginutils');
9
+ const languageCore = require('@vue/language-core');
10
+ const vueTsc = require('vue-tsc');
11
+ const debug = require('debug');
12
+ const kolorist = require('kolorist');
17
13
  const apiExtractor = require('@microsoft/api-extractor');
18
14
  const Collector_js = require('@microsoft/api-extractor/lib/collector/Collector.js');
19
15
  const MessageRouter_js = require('@microsoft/api-extractor/lib/collector/MessageRouter.js');
@@ -21,6 +17,110 @@ const SourceMapper_js = require('@microsoft/api-extractor/lib/collector/SourceMa
21
17
  const DtsRollupGenerator_js = require('@microsoft/api-extractor/lib/generators/DtsRollupGenerator.js');
22
18
  const nodeCoreLibrary = require('@rushstack/node-core-library');
23
19
 
20
+ function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
21
+
22
+ const ts__default = /*#__PURE__*/_interopDefaultCompat(ts);
23
+ const debug__default = /*#__PURE__*/_interopDefaultCompat(debug);
24
+
25
+ const dtsRE$1 = /\.d\.tsx?$/;
26
+ function rollupDeclarationFiles({
27
+ root,
28
+ compilerOptions,
29
+ outDir,
30
+ entryPath,
31
+ fileName,
32
+ libFolder,
33
+ bundledPackages
34
+ }) {
35
+ const configObjectFullPath = node_path.resolve(root, "api-extractor.json");
36
+ const packageJsonLookup = new nodeCoreLibrary.PackageJsonLookup();
37
+ const packageJsonFullPath = packageJsonLookup.tryGetPackageJsonFilePathFor(configObjectFullPath);
38
+ if (!dtsRE$1.test(fileName)) {
39
+ fileName += ".d.ts";
40
+ }
41
+ const extractorConfig = apiExtractor.ExtractorConfig.prepare({
42
+ configObject: {
43
+ projectFolder: root,
44
+ mainEntryPointFilePath: entryPath,
45
+ bundledPackages,
46
+ compiler: {
47
+ // tsconfigFilePath: tsConfigPath,
48
+ overrideTsconfig: {
49
+ $schema: "http://json.schemastore.org/tsconfig",
50
+ compilerOptions: {
51
+ ...compilerOptions,
52
+ target: "ESNext"
53
+ }
54
+ }
55
+ },
56
+ apiReport: {
57
+ enabled: false,
58
+ reportFileName: "<unscopedPackageName>.api.md"
59
+ },
60
+ docModel: {
61
+ enabled: false
62
+ },
63
+ dtsRollup: {
64
+ enabled: true,
65
+ publicTrimmedFilePath: node_path.resolve(outDir, fileName)
66
+ },
67
+ tsdocMetadata: {
68
+ enabled: false
69
+ },
70
+ messages: {
71
+ compilerMessageReporting: {
72
+ default: {
73
+ logLevel: "none"
74
+ }
75
+ },
76
+ extractorMessageReporting: {
77
+ default: {
78
+ logLevel: "none"
79
+ }
80
+ }
81
+ }
82
+ },
83
+ configObjectFullPath,
84
+ packageJsonFullPath
85
+ });
86
+ const compilerState = apiExtractor.CompilerState.create(extractorConfig, {
87
+ localBuild: false,
88
+ showVerboseMessages: false,
89
+ typescriptCompilerFolder: libFolder ? node_path.resolve(libFolder, "..") : void 0
90
+ });
91
+ const sourceMapper = new SourceMapper_js.SourceMapper();
92
+ const messageRouter = new MessageRouter_js.MessageRouter({
93
+ workingPackageFolder: root,
94
+ messageCallback: void 0,
95
+ messagesConfig: extractorConfig.messages,
96
+ showVerboseMessages: false,
97
+ showDiagnostics: false,
98
+ tsdocConfiguration: extractorConfig.tsdocConfiguration,
99
+ sourceMapper
100
+ });
101
+ const collector = new Collector_js.Collector({
102
+ program: compilerState.program,
103
+ messageRouter,
104
+ extractorConfig,
105
+ sourceMapper
106
+ });
107
+ collector.analyze();
108
+ DtsRollupGenerator_js.DtsRollupGenerator.writeTypingsFile(
109
+ collector,
110
+ extractorConfig.publicTrimmedFilePath,
111
+ DtsRollupGenerator_js.DtsRollupKind.PublicRelease,
112
+ extractorConfig.newlineKind
113
+ );
114
+ }
115
+
116
+ const windowsSlashRE = /\\/g;
117
+ function slash(p) {
118
+ return p.replace(windowsSlashRE, "/");
119
+ }
120
+ const isWindows = node_os.platform() === "win32";
121
+ function normalizePath(id) {
122
+ return node_path.posix.normalize(isWindows ? slash(id) : id);
123
+ }
24
124
  function isNativeObj(value) {
25
125
  return Object.prototype.toString.call(value) === "[object Object]";
26
126
  }
@@ -30,39 +130,6 @@ function isRegExp(value) {
30
130
  function isPromise(value) {
31
131
  return !!value && typeof value.then === "function" && typeof value.catch === "function";
32
132
  }
33
- function mergeObjects(sourceObj, targetObj) {
34
- const loop = [
35
- {
36
- source: sourceObj,
37
- target: targetObj
38
- }
39
- ];
40
- while (loop.length) {
41
- const { source, target } = loop.pop();
42
- Object.keys(target).forEach((key) => {
43
- if (isNativeObj(target[key])) {
44
- if (!isNativeObj(source[key])) {
45
- source[key] = {};
46
- }
47
- loop.push({
48
- source: source[key],
49
- target: target[key]
50
- });
51
- } else if (Array.isArray(target[key])) {
52
- if (!Array.isArray(source[key])) {
53
- source[key] = [];
54
- }
55
- loop.push({
56
- source: source[key],
57
- target: target[key]
58
- });
59
- } else {
60
- source[key] = target[key];
61
- }
62
- });
63
- }
64
- return sourceObj;
65
- }
66
133
  function ensureAbsolute(path, root) {
67
134
  return path ? node_path.isAbsolute(path) ? path : node_path.resolve(root, path) : root;
68
135
  }
@@ -143,25 +210,6 @@ function removeDirIfEmpty(dir) {
143
210
  }
144
211
  return onlyHasDir;
145
212
  }
146
- function getTsConfig(tsConfigPath, readFileSync) {
147
- const tsConfig = {
148
- compilerOptions: {},
149
- ...typescript.readConfigFile(tsConfigPath, readFileSync).config ?? {}
150
- };
151
- if (tsConfig.extends) {
152
- ensureArray(tsConfig.extends).forEach((configPath) => {
153
- const config = getTsConfig(ensureAbsolute(configPath, node_path.dirname(tsConfigPath)), readFileSync);
154
- Object.assign(tsConfig.compilerOptions, config.compilerOptions);
155
- if (!tsConfig.include) {
156
- tsConfig.include = config.include;
157
- }
158
- if (!tsConfig.exclude) {
159
- tsConfig.exclude = config.exclude;
160
- }
161
- });
162
- }
163
- return tsConfig;
164
- }
165
213
 
166
214
  const globSuffixRE = /^((?:.*\.[^.]+)|(?:\*+))$/;
167
215
  function normalizeGlob(path) {
@@ -234,7 +282,7 @@ function transformAliasImport(filePath, content, aliases, exclude = []) {
234
282
  if (exclude.some((e) => isRegExp(e) ? e.test(matchResult[1]) : String(e) === matchResult[1])) {
235
283
  return str;
236
284
  }
237
- const truthPath = node_path.isAbsolute(matchedAlias.replacement) ? vite.normalizePath(node_path.relative(node_path.dirname(filePath), matchedAlias.replacement)) : vite.normalizePath(matchedAlias.replacement);
285
+ const truthPath = node_path.isAbsolute(matchedAlias.replacement) ? normalizePath(node_path.relative(node_path.dirname(filePath), matchedAlias.replacement)) : normalizePath(matchedAlias.replacement);
238
286
  return str.replace(
239
287
  isDynamic ? simpleDynamicImportRE : simpleStaticImportRE,
240
288
  `$1'${matchResult[1].replace(
@@ -251,456 +299,72 @@ const pureImportRE = /import\s?['"][^;\n]+?['"];?\n?/g;
251
299
  function removePureImport(content) {
252
300
  return content.replace(pureImportRE, "");
253
301
  }
254
- const setupFunctionRE = /function setup\([\s\S]+\)\s+?\{[\s\S]+return __returned__\n\}/;
255
- function transferSetupPosition(content) {
256
- const match = content.match(setupFunctionRE);
257
- if (match) {
258
- const setupFunction = match[0];
259
- return content.replace(setupFunction, "").replace("setup})", setupFunction.slice("function ".length) + "\n\r})");
260
- }
261
- return content;
262
- }
263
-
264
- const noScriptContent = "import { defineComponent } from 'vue'\nexport default defineComponent({})";
265
- const _require = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (document.currentScript && document.currentScript.src || new URL('index.cjs', document.baseURI).href)));
266
- let index = 1;
267
- let compileRoot = null;
268
- let compiler;
269
- let vue;
270
- function requireCompiler() {
271
- if (!compiler) {
272
- if (compileRoot) {
273
- try {
274
- compiler = _require(_require.resolve("vue/compiler-sfc", { paths: [compileRoot] }));
275
- } catch (e) {
276
- try {
277
- compiler = _require(_require.resolve("@vue/compiler-sfc", { paths: [compileRoot] }));
278
- } catch (e2) {
279
- }
280
- }
281
- }
282
- if (!compiler) {
283
- try {
284
- compiler = _require("vue/compiler-sfc");
285
- } catch (e) {
286
- try {
287
- compiler = _require("@vue/compiler-sfc");
288
- } catch (e2) {
289
- throw new Error("@vue/compiler-sfc is not present in the dependency tree.\n");
290
- }
291
- }
292
- }
293
- }
294
- return compiler;
295
- }
296
- function isVue3() {
297
- if (!vue) {
298
- if (compileRoot) {
299
- try {
300
- vue = _require(_require.resolve("vue", { paths: [compileRoot] }));
301
- } catch (e) {
302
- }
303
- }
304
- if (!vue) {
305
- try {
306
- vue = _require("vue");
307
- } catch (e) {
308
- throw new Error("vue is not present in the dependency tree.\n");
309
- }
310
- }
311
- }
312
- return vue.version.startsWith("3");
313
- }
314
- function setCompileRoot(root) {
315
- if (root && root !== compileRoot) {
316
- compileRoot = root;
317
- compiler = null;
318
- }
319
- }
320
- function parseCode(code) {
321
- const { parse: parseVueCode } = requireCompiler();
322
- let descriptor;
323
- if (isVue3()) {
324
- descriptor = parseVueCode(code).descriptor;
325
- } else {
326
- descriptor = parseVueCode({ source: code });
327
- }
328
- return descriptor;
329
- }
330
- function transformJsToTs(script) {
331
- if (!script)
332
- return script;
333
- const lang = !script.lang || script.lang === "js" ? "ts" : script.lang === "jsx" ? "tsx" : script.lang;
334
- return { ...script, lang };
335
- }
336
- function preprocessVueCode(code, setupScript) {
337
- const plugins = ["typescript", "decorators-legacy", "jsx"];
338
- const scriptAst = parser.parse(code, { sourceType: "module", plugins }).program.body;
339
- const source = new MagicString(code);
340
- let propsTypeName;
341
- let propsTypeLiteral;
342
- if (setupScript) {
343
- let processDefineProps = function(node) {
344
- if (node.type === "CallExpression" && node.callee.type === "Identifier") {
345
- if (node.callee.name === "defineProps") {
346
- defineProps = node;
347
- return true;
348
- } else if (node.callee.name === "withDefaults") {
349
- const propsDef = node.arguments[0];
350
- if (propsDef.type === "CallExpression" && propsDef.callee.type === "Identifier" && propsDef.callee.name === "defineProps") {
351
- defineProps = propsDef;
352
- return true;
353
- }
354
- }
355
- }
356
- return false;
357
- };
358
- const setupAst = parser.parse(setupScript.content, { sourceType: "module", plugins }).program.body;
359
- let defineProps;
360
- for (const node of setupAst) {
361
- if (node.type === "ExpressionStatement") {
362
- processDefineProps(node.expression);
363
- } else if (node.type === "VariableDeclaration" && !node.declare) {
364
- for (const decl of node.declarations) {
365
- if (decl.init && processDefineProps(decl.init)) {
366
- break;
367
- }
368
- }
369
- }
370
- if (defineProps) {
371
- const type = defineProps.typeParameters?.params[0];
372
- if (type && type.type === "TSTypeReference" && type.typeName.type === "Identifier") {
373
- propsTypeName = type.typeName.name;
374
- } else if (type?.type === "TSTypeLiteral") {
375
- propsTypeName = "__DTS_Props__";
376
- propsTypeLiteral = setupScript.content.substring(type.start, type.end);
377
- }
378
- break;
379
- }
380
- }
381
- }
382
- const declRecord = /* @__PURE__ */ new Map();
383
- let defaultExport;
384
- let options;
385
- for (const node of scriptAst) {
386
- if (node.type === "VariableDeclaration") {
387
- for (const decl of node.declarations) {
388
- if (decl.id.type === "Identifier" && decl.init) {
389
- let properties;
390
- if (decl.init.type === "ObjectExpression") {
391
- properties = decl.init.properties;
392
- } else if (decl.init.type === "CallExpression" && decl.init.arguments[0]?.type === "ObjectExpression") {
393
- properties = decl.init.arguments[0].properties;
394
- }
395
- if (!properties)
396
- continue;
397
- if (defaultExport && decl.id.name === defaultExport) {
398
- options = properties;
399
- break;
400
- } else {
401
- declRecord.set(decl.id.name, properties);
402
- }
403
- }
404
- }
405
- }
406
- if (node.type === "ExportDefaultDeclaration") {
407
- if (node.declaration.type === "ObjectExpression") {
408
- options = node.declaration.properties;
409
- } else if (node.declaration.type === "CallExpression" && node.declaration.arguments[0]?.type === "ObjectExpression") {
410
- options = node.declaration.arguments[0].properties;
411
- } else if (node.declaration.type === "Identifier") {
412
- if (declRecord.has(node.declaration.name)) {
413
- options = declRecord.get(node.declaration.name);
414
- } else {
415
- defaultExport = node.declaration.name;
416
- }
417
- }
418
- }
419
- if (options) {
420
- for (const option of options) {
421
- if (propsTypeName && option.type === "ObjectProperty" && option.key.type === "Identifier" && option.key.name === "props" && option.value.type === "ObjectExpression") {
422
- for (const prop of option.value.properties) {
423
- if (prop.type === "ObjectProperty" && prop.key.type === "Identifier") {
424
- if (prop.value.type === "ObjectExpression") {
425
- for (const propDef of prop.value.properties) {
426
- if (propDef.type === "ObjectProperty" && propDef.key.type === "Identifier" && propDef.key.name === "type") {
427
- source.prependLeft(
428
- propDef.end,
429
- ` as unknown as __PropType<${propsTypeName}['${prop.key.name}']>`
430
- );
431
- }
432
- }
433
- } else {
434
- source.prependLeft(
435
- prop.end,
436
- ` as unknown as __PropType<${propsTypeName}['${prop.key.name}']>`
437
- );
438
- }
439
- }
440
- }
441
- }
442
- if (option.type === "ObjectProperty" && option.key.type === "Identifier" && option.key.name === "components") {
443
- source.overwrite(option.value.start, option.value.end, "undefined");
444
- }
445
- if (option.type === "ObjectMethod" && option.key.type === "Identifier" && option.key.name === "setup") {
446
- let exposed;
447
- let returned;
448
- for (const node2 of option.body.body) {
449
- if (!exposed && node2.type === "ExpressionStatement" && node2.expression.type === "CallExpression" && node2.expression.callee.type === "Identifier" && node2.expression.callee.name === "expose") {
450
- exposed = node2.expression.arguments[0];
451
- continue;
452
- }
453
- if (node2.type === "ReturnStatement") {
454
- returned = node2;
455
- break;
456
- }
457
- }
458
- const newReturned = exposed && exposed.type === "ObjectExpression" ? `return ${code.substring(exposed.start, exposed.end)}` : setupScript ? "return {}" : "";
459
- if (newReturned) {
460
- if (returned) {
461
- source.overwrite(returned.start, returned.end, newReturned);
462
- } else if (option.body.body.length) {
463
- source.appendRight(option.body.body.at(-1).end, `
464
- ${newReturned}
465
- `);
466
- }
467
- }
468
- }
469
- }
470
- break;
471
- }
472
- }
473
- if (propsTypeName) {
474
- if (propsTypeLiteral) {
475
- source.prepend(`
476
- type ${propsTypeName} = ${propsTypeLiteral}
477
-
478
- `);
479
- }
480
- source.prepend("import type { PropType as __PropType } from 'vue'\n");
481
- }
482
- return source.toString();
483
- }
484
- function compileVueCode(code) {
485
- const { compileScript, rewriteDefault } = requireCompiler();
486
- const descriptor = parseCode(code);
487
- const { script, scriptSetup } = descriptor;
488
- let error;
489
- let content;
490
- let ext = "js";
491
- if (script || scriptSetup) {
492
- const compiled = compileScript(
493
- {
494
- ...descriptor,
495
- script: transformJsToTs(script),
496
- scriptSetup: transformJsToTs(scriptSetup),
497
- cssVars: []
498
- },
499
- { id: `${index++}` }
500
- );
501
- try {
502
- content = preprocessVueCode(compiled.content, scriptSetup);
503
- } catch (e) {
504
- error = e;
505
- content = compiled.content;
506
- }
507
- content = rewriteDefault(content, "_sfc_main", ["typescript", "decorators-legacy"]);
508
- if (scriptSetup) {
509
- content = transferSetupPosition(content);
510
- ext = scriptSetup.lang || "js";
511
- } else if (script && script.content) {
512
- ext = script.lang || "js";
513
- }
514
- content += "\nexport default _sfc_main\n";
515
- } else {
516
- content = noScriptContent;
517
- ext = "ts";
518
- }
519
- return { error, content, ext };
520
- }
521
-
522
- const dtsRE$1 = /\.d\.tsx?$/;
523
- function rollupDeclarationFiles({
524
- root,
525
- compilerOptions,
526
- outputDir,
527
- entryPath,
528
- fileName,
529
- libFolder,
530
- bundledPackages
531
- }) {
532
- const configObjectFullPath = node_path.resolve(root, "api-extractor.json");
533
- const packageJsonLookup = new nodeCoreLibrary.PackageJsonLookup();
534
- const packageJsonFullPath = packageJsonLookup.tryGetPackageJsonFilePathFor(configObjectFullPath);
535
- if (!dtsRE$1.test(fileName)) {
536
- fileName += ".d.ts";
537
- }
538
- const extractorConfig = apiExtractor.ExtractorConfig.prepare({
539
- configObject: {
540
- projectFolder: root,
541
- mainEntryPointFilePath: entryPath,
542
- bundledPackages,
543
- compiler: {
544
- overrideTsconfig: {
545
- $schema: "http://json.schemastore.org/tsconfig",
546
- compilerOptions
547
- }
548
- },
549
- apiReport: {
550
- enabled: false,
551
- reportFileName: "<unscopedPackageName>.api.md"
552
- },
553
- docModel: {
554
- enabled: false
555
- },
556
- dtsRollup: {
557
- enabled: true,
558
- publicTrimmedFilePath: node_path.resolve(outputDir, fileName)
559
- },
560
- tsdocMetadata: {
561
- enabled: false
562
- },
563
- messages: {
564
- compilerMessageReporting: {
565
- default: {
566
- logLevel: "none"
567
- }
568
- },
569
- extractorMessageReporting: {
570
- default: {
571
- logLevel: "none"
572
- }
573
- }
574
- }
575
- },
576
- configObjectFullPath,
577
- packageJsonFullPath
578
- });
579
- const compilerState = apiExtractor.CompilerState.create(extractorConfig, {
580
- localBuild: false,
581
- showVerboseMessages: false,
582
- typescriptCompilerFolder: libFolder ? node_path.resolve(libFolder, "..") : void 0
583
- });
584
- const sourceMapper = new SourceMapper_js.SourceMapper();
585
- const messageRouter = new MessageRouter_js.MessageRouter({
586
- workingPackageFolder: root,
587
- messageCallback: void 0,
588
- messagesConfig: extractorConfig.messages,
589
- showVerboseMessages: false,
590
- showDiagnostics: false,
591
- tsdocConfiguration: extractorConfig.tsdocConfiguration,
592
- sourceMapper
593
- });
594
- const collector = new Collector_js.Collector({
595
- program: compilerState.program,
596
- messageRouter,
597
- extractorConfig,
598
- sourceMapper
599
- });
600
- collector.analyze();
601
- DtsRollupGenerator_js.DtsRollupGenerator.writeTypingsFile(
602
- collector,
603
- extractorConfig.publicTrimmedFilePath,
604
- DtsRollupGenerator_js.DtsRollupKind.PublicRelease,
605
- extractorConfig.newlineKind
606
- );
607
- }
608
302
 
609
- const noneExport = "export {};\n";
610
303
  const vueRE = /\.vue$/;
611
- const svelteRE = /\.svelte$/;
612
304
  const tsRE = /\.(m|c)?tsx?$/;
613
- const jsRE = /\.(m|c)?jsx?$/;
614
305
  const dtsRE = /\.d\.(m|c)?tsx?$/;
615
306
  const tjsRE = /\.(m|c)?(t|j)sx?$/;
616
307
  const mtjsRE = /\.m(t|j)sx?$/;
617
308
  const ctjsRE = /\.c(t|j)sx?$/;
618
- const watchExtensionRE = /\.(vue|(m|c)?(t|j)sx?)$/;
619
309
  const fullRelativeRE = /^\.\.?\//;
310
+ const watchExtensionRE = /\.(vue|(m|c)?(t|j)sx?)$/;
620
311
  const defaultIndex = "index.d.ts";
312
+ const logPrefix = kolorist.cyan("[vite:dts]");
313
+ const bundleDebug = debug__default("vite-plugin-dts:bundle");
314
+ const fixedCompilerOptions = {
315
+ noEmit: false,
316
+ declaration: true,
317
+ emitDeclarationOnly: true,
318
+ noUnusedParameters: false,
319
+ checkJs: false,
320
+ skipLibCheck: true,
321
+ preserveSymlinks: false,
322
+ noEmitOnError: void 0,
323
+ target: ts__default.ScriptTarget.ESNext
324
+ };
621
325
  const noop = () => {
622
326
  };
623
327
  const extPrefix = (file) => mtjsRE.test(file) ? "m" : ctjsRE.test(file) ? "c" : "";
624
- const resolve = (...paths) => vite.normalizePath(node_path.resolve(...paths));
625
- const logPrefix = kolorist.cyan("[vite:dts]");
626
- const bundleDebug = debug("vite-plugin-dts:bundle");
328
+ const resolve = (...paths) => normalizePath(node_path.resolve(...paths));
627
329
  function dtsPlugin(options = {}) {
628
330
  const {
629
- tsConfigFilePath = "tsconfig.json",
630
- aliasesExclude = [],
631
- cleanVueFileName = false,
331
+ tsconfigPath,
632
332
  staticImport = false,
633
333
  clearPureImport = true,
334
+ cleanVueFileName = false,
634
335
  insertTypesEntry = false,
635
336
  rollupTypes = false,
636
337
  bundledPackages = [],
637
- noEmitOnError = false,
638
- skipDiagnostics = false,
338
+ aliasesExclude = [],
339
+ logLevel,
639
340
  copyDtsFiles = false,
640
- logLevel = void 0,
641
341
  afterDiagnostic = noop,
642
342
  beforeWriteFile = noop,
643
343
  afterBuild = noop
644
344
  } = options;
645
- let compilerOptions = options.compilerOptions ?? {};
646
- let root;
345
+ let root = ensureAbsolute(options.root ?? "", process.cwd());
647
346
  let entryRoot = options.entryRoot ?? "";
648
- let libName;
649
- let indexName;
650
- let aliases;
347
+ let compilerOptions;
348
+ let rawCompilerOptions;
349
+ let outDirs;
651
350
  let entries;
652
- let logger;
653
- let project;
654
- let tsConfigPath;
655
- let outputDirs;
656
- let isBundle = false;
657
351
  let include;
658
352
  let exclude;
353
+ let aliases;
354
+ let libName;
355
+ let indexName;
356
+ let logger;
357
+ let host;
358
+ let program;
659
359
  let filter;
660
- let libFolderPath = options.libFolderPath;
661
- const sourceDtsFiles = /* @__PURE__ */ new Set();
662
- const includedFiles = /* @__PURE__ */ new Set();
663
- const emittedFiles = /* @__PURE__ */ new Map();
664
- let hasJsVue = false;
665
- let allowJs = false;
666
- let transformError = false;
667
- async function internalTransform(id) {
668
- if (!project || !filter(id)) {
669
- return;
670
- }
671
- if (vueRE.test(id)) {
672
- const { error, content, ext } = compileVueCode(await fs.readFile(id, "utf-8"));
673
- if (!transformError && error) {
674
- logger.error(
675
- kolorist.red(
676
- `
677
- ${kolorist.cyan(
678
- "[vite:dts]"
679
- )} A error occurred when transform code, maybe there are some inertnal bugs.
680
- `
681
- )
682
- );
683
- transformError = true;
684
- }
685
- if (content) {
686
- if (ext === "js" || ext === "jsx")
687
- hasJsVue = true;
688
- project.createSourceFile(`${id}.${ext || "js"}`, content, { overwrite: true });
689
- }
690
- } else if (!id.includes(".vue?vue") && (tsRE.test(id) || allowJs && jsRE.test(id))) {
691
- project.createSourceFile(id, await fs.readFile(id, "utf-8"), { overwrite: true });
692
- } else if (svelteRE.test(id)) {
693
- const content = "export { SvelteComponentTyped as default } from 'svelte/internal';";
694
- project.createSourceFile(`${id}.ts`, content, { overwrite: true });
695
- }
696
- }
360
+ let bundled = false;
361
+ const rootFiles = /* @__PURE__ */ new Set();
362
+ const outputFiles = /* @__PURE__ */ new Map();
697
363
  return {
698
364
  name: "vite:dts",
699
365
  apply: "build",
700
366
  enforce: "pre",
701
367
  config(config) {
702
- if (isBundle)
703
- return;
704
368
  const aliasOptions = config?.resolve?.alias ?? [];
705
369
  if (isNativeObj(aliasOptions)) {
706
370
  aliases = Object.entries(aliasOptions).map(([key, value]) => {
@@ -717,23 +381,19 @@ ${kolorist.cyan(
717
381
  );
718
382
  }
719
383
  },
720
- configResolved(config) {
721
- if (isBundle)
722
- return;
723
- logger = logLevel ? vite.createLogger(logLevel, { allowClearScreen: config.clearScreen }) : config.logger;
724
- if (!config.build.lib) {
725
- logger.warn(
726
- kolorist.yellow(
727
- `
728
- ${kolorist.cyan(
729
- "[vite:dts]"
730
- )} You are building a library that may not need to generate declaration files.
731
- `
732
- )
733
- );
734
- libName = "_default";
735
- indexName = defaultIndex;
736
- } else {
384
+ async configResolved(config) {
385
+ logger = logLevel ? (await import('vite')).createLogger(logLevel, { allowClearScreen: config.clearScreen }) : config.logger;
386
+ root = ensureAbsolute(options.root ?? "", config.root);
387
+ if (config.build.lib) {
388
+ const input = typeof config.build.lib.entry === "string" ? [config.build.lib.entry] : config.build.lib.entry;
389
+ if (Array.isArray(input)) {
390
+ entries = input.reduce((prev, current) => {
391
+ prev[node_path.basename(current)] = current;
392
+ return prev;
393
+ }, {});
394
+ } else {
395
+ entries = { ...input };
396
+ }
737
397
  const filename = config.build.lib.fileName ?? defaultIndex;
738
398
  const entry = typeof config.build.lib.entry === "string" ? config.build.lib.entry : Object.values(config.build.lib.entry)[0];
739
399
  libName = config.build.lib.name || "_default";
@@ -741,199 +401,201 @@ ${kolorist.cyan(
741
401
  if (!dtsRE.test(indexName)) {
742
402
  indexName = `${indexName.replace(tjsRE, "")}.d.${extPrefix(indexName)}ts`;
743
403
  }
744
- }
745
- root = ensureAbsolute(options.root ?? "", config.root);
746
- tsConfigPath = ensureAbsolute(tsConfigFilePath, root);
747
- libFolderPath = libFolderPath && ensureAbsolute(libFolderPath, root);
748
- outputDirs = options.outputDir ? ensureArray(options.outputDir).map((d) => ensureAbsolute(d, root)) : [ensureAbsolute(config.build.outDir, root)];
749
- if (!outputDirs[0]) {
750
- logger.error(
751
- kolorist.red(
404
+ } else {
405
+ logger.warn(
406
+ kolorist.yellow(
752
407
  `
753
408
  ${kolorist.cyan(
754
409
  "[vite:dts]"
755
- )} Can not resolve declaration directory. Please check your vite config and plugin options.
410
+ )} You are building a library that may not need to generate declaration files.
756
411
  `
757
412
  )
758
413
  );
759
- return;
414
+ libName = "_default";
415
+ indexName = defaultIndex;
760
416
  }
761
- setCompileRoot(root);
762
- project = new tsMorph.Project({
763
- compilerOptions: mergeObjects(compilerOptions, {
764
- rootDir: compilerOptions.rootDir || root,
765
- noEmitOnError,
766
- outDir: outputDirs[0],
767
- declarationDir: void 0,
768
- noUnusedParameters: false,
769
- declaration: true,
770
- noEmit: false,
771
- emitDeclarationOnly: true,
772
- composite: false
773
- }),
774
- tsConfigFilePath: tsConfigPath,
775
- skipAddingFilesFromTsConfig: true,
776
- libFolderPath
777
- });
778
- allowJs = project.getCompilerOptions().allowJs ?? false;
779
- const tsConfig = getTsConfig(tsConfigPath, project.getFileSystem().readFileSync);
780
- include = ensureArray(options.include ?? tsConfig.include ?? "**/*").map(normalizeGlob);
781
- exclude = ensureArray(options.exclude ?? tsConfig.exclude ?? "node_modules/**").map(
782
- normalizeGlob
783
- );
784
- filter = pluginutils.createFilter(include, exclude, { resolve: root });
785
- compilerOptions = tsConfig.compilerOptions;
417
+ if (!options.outDir) {
418
+ outDirs = [ensureAbsolute(config.build.outDir, root)];
419
+ }
420
+ bundleDebug("parse vite config");
786
421
  },
787
- async buildStart(inputOptions) {
788
- if (Array.isArray(inputOptions.input)) {
789
- entries = inputOptions.input.reduce((prev, current) => {
422
+ options(options2) {
423
+ if (entries)
424
+ return;
425
+ const input = typeof options2.input === "string" ? [options2.input] : options2.input;
426
+ if (Array.isArray(input)) {
427
+ entries = input.reduce((prev, current) => {
790
428
  prev[node_path.basename(current)] = current;
791
429
  return prev;
792
430
  }, {});
793
431
  } else {
794
- entries = { ...inputOptions.input };
432
+ entries = { ...input };
795
433
  }
796
- bundleDebug("parse entries");
797
- sourceDtsFiles.clear();
798
- includedFiles.clear();
799
- if (project && include && include.length) {
800
- const files = await glob(include, {
801
- cwd: root,
802
- absolute: true,
803
- ignore: exclude
804
- });
805
- for (const file of files) {
806
- this.addWatchFile(file);
807
- if (dtsRE.test(file)) {
808
- sourceDtsFiles.add(project.addSourceFileAtPath(file));
809
- if (!copyDtsFiles) {
810
- continue;
811
- }
812
- includedFiles.add(file);
813
- continue;
814
- }
815
- includedFiles.add(`${file.replace(tjsRE, "")}.d.${extPrefix(file)}ts`);
816
- }
817
- if (hasJsVue) {
818
- if (!allowJs) {
819
- logger.warn(
820
- kolorist.yellow(
821
- `${kolorist.cyan(
822
- "[vite:dts]"
823
- )} Some js files are referenced, but you may not enable the 'allowJs' option.`
824
- )
825
- );
826
- }
827
- project.compilerOptions.set({ allowJs: true });
434
+ logger = logger || console;
435
+ libName = "_default";
436
+ indexName = defaultIndex;
437
+ bundleDebug("parse options");
438
+ },
439
+ async buildStart() {
440
+ if (program)
441
+ return;
442
+ bundleDebug("begin buildStart");
443
+ const configPath = tsconfigPath ? ensureAbsolute(tsconfigPath, root) : ts__default.findConfigFile(root, ts__default.sys.fileExists);
444
+ const content = configPath ? languageCore.createParsedCommandLine(ts__default, ts__default.sys, configPath) : void 0;
445
+ const config = content ? {
446
+ include: content.raw.include,
447
+ exclude: content.raw.exclude,
448
+ raw: content.raw,
449
+ options: {
450
+ ...content.options,
451
+ ...options.compilerOptions || {},
452
+ ...fixedCompilerOptions
828
453
  }
829
- bundleDebug("collect files");
454
+ } : { options: { ...options.compilerOptions || {}, ...fixedCompilerOptions } };
455
+ if (!outDirs) {
456
+ outDirs = options.outDir ? ensureArray(options.outDir).map((d) => ensureAbsolute(d, root)) : [ensureAbsolute(config.raw?.compilerOptions?.outDir || "dist", root)];
457
+ }
458
+ include = ensureArray(options.include ?? config.include ?? "**/*").map(normalizeGlob);
459
+ exclude = ensureArray(options.exclude ?? config.exclude ?? "node_modules/**").map(
460
+ normalizeGlob
461
+ );
462
+ compilerOptions = { ...config.options, outDir: outDirs[0] };
463
+ rawCompilerOptions = config.raw?.compilerOptions || {};
464
+ filter = pluginutils.createFilter(include, exclude, { resolve: root });
465
+ const rootNames = Object.values(entries).concat(content?.fileNames.filter(filter) || []).map(normalizePath);
466
+ host = ts__default.createCompilerHost(compilerOptions, true);
467
+ program = vueTsc.createProgram({ host, rootNames, options: compilerOptions });
468
+ libName = libName || "_default";
469
+ indexName = indexName || defaultIndex;
470
+ const diagnostics = program.getDeclarationDiagnostics();
471
+ if (diagnostics?.length) {
472
+ logger.error(ts__default.formatDiagnostics(diagnostics, host));
830
473
  }
474
+ if (typeof afterDiagnostic === "function") {
475
+ const result = afterDiagnostic(diagnostics);
476
+ isPromise(result) && await result;
477
+ }
478
+ rootNames.forEach((file) => {
479
+ this.addWatchFile(file);
480
+ rootFiles.add(file);
481
+ });
482
+ bundleDebug("create ts program");
831
483
  },
832
- async transform(_, id) {
833
- await internalTransform(id);
834
- return null;
484
+ transform(_, id) {
485
+ if (!program || !filter(id) || id.includes(".vue?vue") || !tsRE.test(id) && !vueRE.test(id)) {
486
+ return;
487
+ }
488
+ id = normalizePath(id);
489
+ rootFiles.delete(id);
490
+ let sourceFile = program.getSourceFile(normalizePath(id));
491
+ if (!sourceFile && vueRE.test(id)) {
492
+ sourceFile = program.getSourceFile(id + ".ts") || program.getSourceFile(id + ".js") || program.getSourceFile(id + ".tsx") || program.getSourceFile(id + ".jsx");
493
+ }
494
+ if (!sourceFile)
495
+ return;
496
+ const outDir = outDirs[0];
497
+ const service = program.__vue.languageService;
498
+ for (const outputFile of service.getEmitOutput(sourceFile.fileName, true).outputFiles) {
499
+ outputFiles.set(resolve(root, node_path.relative(outDir, outputFile.name)), outputFile.text);
500
+ }
501
+ const dtsId = id.replace(tjsRE, ".d.ts");
502
+ const dtsSourceFile = program.getSourceFile(dtsId);
503
+ dtsSourceFile && filter(dtsSourceFile.fileName) && outputFiles.set(dtsSourceFile.fileName, dtsSourceFile.getFullText());
835
504
  },
836
- async watchChange(id) {
837
- if (watchExtensionRE.test(id)) {
838
- isBundle = false;
839
- if (project) {
840
- const sourceFile = project.getSourceFile(vite.normalizePath(id));
841
- sourceFile && project.removeSourceFile(sourceFile);
842
- await internalTransform(id);
505
+ watchChange(id) {
506
+ if (host && program && watchExtensionRE.test(id)) {
507
+ const sourceFile = host.getSourceFile(normalizePath(id), ts__default.ScriptTarget.ESNext);
508
+ if (sourceFile && filter(sourceFile.fileName)) {
509
+ !vueRE.test(id) && rootFiles.add(sourceFile.fileName);
510
+ program.__vue.projectVersion++;
511
+ bundled = false;
843
512
  }
844
513
  }
845
514
  },
846
- async closeBundle() {
847
- if (!outputDirs || !project || isBundle)
515
+ async writeBundle() {
516
+ if (!program || bundled)
848
517
  return;
518
+ bundled = true;
519
+ bundleDebug("begin writeBundle");
849
520
  logger.info(kolorist.green(`
850
521
  ${logPrefix} Start generate declaration files...`));
851
- bundleDebug("start");
852
- isBundle = true;
853
- emittedFiles.clear();
854
522
  const startTime = Date.now();
855
- project.resolveSourceFileDependencies();
856
- bundleDebug("resolve");
857
- if (!skipDiagnostics) {
858
- const diagnostics = project.getPreEmitDiagnostics();
859
- if (diagnostics?.length) {
860
- logger.warn(project.formatDiagnosticsWithColorAndContext(diagnostics));
523
+ const outDir = outDirs[0];
524
+ const emittedFiles = /* @__PURE__ */ new Map();
525
+ const service = program.__vue.languageService;
526
+ const sourceFiles = program.getSourceFiles();
527
+ for (const sourceFile of sourceFiles) {
528
+ if (!filter(sourceFile.fileName))
529
+ continue;
530
+ if (copyDtsFiles && dtsRE.test(sourceFile.fileName)) {
531
+ outputFiles.set(sourceFile.fileName, sourceFile.getFullText());
861
532
  }
862
- if (typeof afterDiagnostic === "function") {
863
- const result = afterDiagnostic(diagnostics);
864
- isPromise(result) && await result;
533
+ if (rootFiles.has(sourceFile.fileName)) {
534
+ for (const outputFile of service.getEmitOutput(sourceFile.fileName, true).outputFiles) {
535
+ outputFiles.set(resolve(root, node_path.relative(outDir, outputFile.name)), outputFile.text);
536
+ }
537
+ rootFiles.delete(sourceFile.fileName);
865
538
  }
866
- bundleDebug("diagnostics");
867
539
  }
868
- const outputDir = outputDirs[0];
869
- const dtsOutputFiles = Array.from(sourceDtsFiles).map((sourceFile) => ({
870
- path: sourceFile.getFilePath(),
871
- content: sourceFile.getFullText()
872
- }));
873
- const service = project.getLanguageService();
874
- const outputFiles = project.getSourceFiles().map(
875
- (sourceFile) => service.getEmitOutput(sourceFile, true).getOutputFiles().map((outputFile) => ({
876
- path: resolve(root, node_path.relative(outputDir, outputFile.compilerObject.name)),
877
- content: outputFile.getText()
878
- }))
879
- ).flat().concat(dtsOutputFiles);
880
- bundleDebug("emit");
881
- entryRoot = entryRoot || queryPublicPath(outputFiles.map((file) => file.path));
540
+ bundleDebug("emit output patch");
541
+ entryRoot = entryRoot || queryPublicPath(Array.from(outputFiles.keys()));
882
542
  entryRoot = ensureAbsolute(entryRoot, root);
883
- await runParallel(os.cpus().length, outputFiles, async (outputFile) => {
884
- let filePath = outputFile.path;
885
- let content = outputFile.content;
886
- const isMapFile = filePath.endsWith(".map");
887
- if (!includedFiles.has(isMapFile ? filePath.slice(0, -4) : filePath) || clearPureImport && content === noneExport) {
888
- return;
889
- }
890
- if (!isMapFile && content && content !== noneExport) {
891
- content = clearPureImport ? removePureImport(content) : content;
892
- content = transformAliasImport(filePath, content, aliases, aliasesExclude);
893
- content = staticImport || rollupTypes ? transformDynamicImport(content) : content;
894
- }
895
- filePath = resolve(
896
- outputDir,
897
- node_path.relative(entryRoot, cleanVueFileName ? filePath.replace(".vue.d.ts", ".d.ts") : filePath)
898
- );
899
- content = cleanVueFileName ? content.replace(/['"](.+)\.vue['"]/g, '"$1"') : content;
900
- if (typeof beforeWriteFile === "function") {
901
- const result = beforeWriteFile(filePath, content);
902
- if (result === false)
903
- return;
904
- if (result && isNativeObj(result)) {
905
- filePath = result.filePath || filePath;
906
- content = result.content ?? content;
543
+ await runParallel(
544
+ node_os.cpus().length,
545
+ Array.from(outputFiles.entries()),
546
+ async ([path, content]) => {
547
+ const isMapFile = path.endsWith(".map");
548
+ if (!isMapFile && content) {
549
+ content = clearPureImport ? removePureImport(content) : content;
550
+ content = transformAliasImport(path, content, aliases, aliasesExclude);
551
+ content = staticImport || rollupTypes ? transformDynamicImport(content) : content;
552
+ }
553
+ path = resolve(
554
+ outDir,
555
+ node_path.relative(entryRoot, cleanVueFileName ? path.replace(".vue.d.ts", ".d.ts") : path)
556
+ );
557
+ content = cleanVueFileName ? content.replace(/['"](.+)\.vue['"]/g, '"$1"') : content;
558
+ if (typeof beforeWriteFile === "function") {
559
+ const result = beforeWriteFile(path, content);
560
+ if (result === false)
561
+ return;
562
+ if (result && isNativeObj(result)) {
563
+ path = result.filePath || path;
564
+ content = result.content ?? content;
565
+ }
566
+ }
567
+ path = normalizePath(path);
568
+ const dir = node_path.dirname(path);
569
+ if (!node_fs.existsSync(dir)) {
570
+ await promises.mkdir(dir, { recursive: true });
907
571
  }
572
+ await promises.writeFile(path, content, "utf-8");
573
+ emittedFiles.set(path, content);
908
574
  }
909
- filePath = vite.normalizePath(filePath);
910
- await fs.mkdir(node_path.dirname(filePath), { recursive: true });
911
- await fs.writeFile(filePath, content, "utf-8");
912
- emittedFiles.set(filePath, content);
913
- });
914
- bundleDebug("output");
575
+ );
576
+ bundleDebug("write output");
915
577
  if (insertTypesEntry || rollupTypes) {
916
578
  const pkgPath = resolve(root, "package.json");
917
- const pkg = fs.existsSync(pkgPath) ? JSON.parse(await fs.readFile(pkgPath, "utf-8")) : {};
579
+ const pkg = node_fs.existsSync(pkgPath) ? JSON.parse(await promises.readFile(pkgPath, "utf-8")) : {};
918
580
  const entryNames = Object.keys(entries);
919
581
  const types = pkg.types || pkg.typings || pkg.publishConfig?.types || pkg.publishConfig?.typings || (pkg.exports?.["."] || pkg.exports?.["./"])?.types;
920
582
  const multiple = entryNames.length > 1;
921
- const typesPath = types ? resolve(root, types) : resolve(outputDir, indexName);
583
+ const typesPath = types ? resolve(root, types) : resolve(outDir, indexName);
922
584
  for (const name of entryNames) {
923
- let filePath = multiple ? resolve(outputDir, `${name.replace(tsRE, "")}.d.ts`) : typesPath;
924
- if (fs.existsSync(filePath))
585
+ let path = multiple ? resolve(outDir, `${name.replace(tsRE, "")}.d.ts`) : typesPath;
586
+ if (node_fs.existsSync(path))
925
587
  continue;
926
588
  const index = resolve(
927
- outputDir,
589
+ outDir,
928
590
  node_path.relative(entryRoot, `${entries[name].replace(tsRE, "")}.d.ts`)
929
591
  );
930
- let fromPath = vite.normalizePath(node_path.relative(node_path.dirname(filePath), index));
592
+ let fromPath = normalizePath(node_path.relative(node_path.dirname(path), index));
931
593
  fromPath = fromPath.replace(dtsRE, "");
932
594
  fromPath = fullRelativeRE.test(fromPath) ? fromPath : `./${fromPath}`;
933
595
  let content = `export * from '${fromPath}'
934
596
  `;
935
- if (fs.existsSync(index)) {
936
- const entryCodes = await fs.readFile(index, "utf-8");
597
+ if (node_fs.existsSync(index)) {
598
+ const entryCodes = await promises.readFile(index, "utf-8");
937
599
  if (entryCodes.includes("export default")) {
938
600
  content += `import ${libName} from '${fromPath}'
939
601
  export default ${libName}
@@ -942,32 +604,41 @@ export default ${libName}
942
604
  }
943
605
  let result;
944
606
  if (typeof beforeWriteFile === "function") {
945
- result = beforeWriteFile(filePath, content);
607
+ result = beforeWriteFile(path, content);
946
608
  if (result && isNativeObj(result)) {
947
- filePath = result.filePath ?? filePath;
609
+ path = result.filePath ?? path;
948
610
  content = result.content ?? content;
949
611
  }
950
612
  }
951
- filePath = vite.normalizePath(filePath);
613
+ path = normalizePath(path);
952
614
  if (result !== false) {
953
- await fs.writeFile(filePath, content, "utf-8");
954
- emittedFiles.set(filePath, content);
615
+ await promises.writeFile(path, content, "utf-8");
616
+ emittedFiles.set(path, content);
955
617
  }
956
618
  }
957
619
  bundleDebug("insert index");
958
620
  if (rollupTypes) {
959
621
  logger.info(kolorist.green(`${logPrefix} Start rollup declaration files...`));
622
+ let libFolder = resolve(root, "node_modules/typescript");
623
+ if (!node_fs.existsSync(libFolder)) {
624
+ if (root !== entryRoot) {
625
+ libFolder = resolve(entryRoot, "node_modules/typescript");
626
+ if (!node_fs.existsSync(libFolder))
627
+ libFolder = void 0;
628
+ }
629
+ libFolder = void 0;
630
+ }
960
631
  const rollupFiles = /* @__PURE__ */ new Set();
961
632
  if (multiple) {
962
633
  for (const name of entryNames) {
963
- const path = resolve(outputDir, `${name.replace(tsRE, "")}.d.ts`);
634
+ const path = resolve(outDir, `${name.replace(tsRE, "")}.d.ts`);
964
635
  rollupDeclarationFiles({
965
636
  root,
966
- compilerOptions,
967
- outputDir,
637
+ compilerOptions: rawCompilerOptions,
638
+ outDir,
968
639
  entryPath: path,
969
640
  fileName: node_path.basename(path),
970
- libFolder: libFolderPath,
641
+ libFolder,
971
642
  bundledPackages
972
643
  });
973
644
  emittedFiles.delete(path);
@@ -976,41 +647,40 @@ export default ${libName}
976
647
  } else {
977
648
  rollupDeclarationFiles({
978
649
  root,
979
- compilerOptions,
980
- outputDir,
650
+ compilerOptions: rawCompilerOptions,
651
+ outDir,
981
652
  entryPath: typesPath,
982
653
  fileName: node_path.basename(typesPath),
983
- libFolder: libFolderPath,
654
+ libFolder,
984
655
  bundledPackages
985
656
  });
986
657
  emittedFiles.delete(typesPath);
987
658
  rollupFiles.add(typesPath);
988
659
  }
989
- await runParallel(os.cpus().length, Array.from(emittedFiles.keys()), (f) => fs.unlink(f));
990
- removeDirIfEmpty(outputDir);
660
+ await runParallel(node_os.cpus().length, Array.from(emittedFiles.keys()), (f) => promises.unlink(f));
661
+ removeDirIfEmpty(outDir);
991
662
  emittedFiles.clear();
992
663
  for (const file of rollupFiles) {
993
- emittedFiles.set(file, await fs.readFile(file, "utf-8"));
664
+ emittedFiles.set(file, await promises.readFile(file, "utf-8"));
994
665
  }
995
- bundleDebug("rollup");
666
+ bundleDebug("rollup output");
996
667
  }
997
668
  }
998
- if (outputDirs.length > 1) {
999
- const dirs = outputDirs.slice(1);
1000
- await runParallel(
1001
- os.cpus().length,
1002
- Array.from(emittedFiles),
1003
- async ([wroteFile, content]) => {
1004
- const relativePath = node_path.relative(outputDir, wroteFile);
1005
- await Promise.all(
1006
- dirs.map(async (dir) => {
1007
- const filePath = resolve(dir, relativePath);
1008
- await fs.mkdir(node_path.dirname(filePath), { recursive: true });
1009
- await fs.writeFile(filePath, content, "utf-8");
1010
- })
1011
- );
1012
- }
1013
- );
669
+ if (outDirs.length > 1) {
670
+ const dirs = outDirs.slice(1);
671
+ await runParallel(node_os.cpus().length, Array.from(emittedFiles), async ([wroteFile, content]) => {
672
+ const relativePath = node_path.relative(outDir, wroteFile);
673
+ await Promise.all(
674
+ dirs.map(async (dir) => {
675
+ const path = resolve(dir, relativePath);
676
+ const dirPath = node_path.dirname(path);
677
+ if (!node_fs.existsSync(dirPath)) {
678
+ await promises.mkdir(dirPath, { recursive: true });
679
+ }
680
+ await promises.writeFile(path, content, "utf-8");
681
+ })
682
+ );
683
+ });
1014
684
  }
1015
685
  if (typeof afterBuild === "function") {
1016
686
  const result = afterBuild();