vite-plugin-dts 4.0.0-beta.2 → 4.0.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.
Files changed (3) hide show
  1. package/dist/index.cjs +104 -32
  2. package/dist/index.mjs +103 -32
  3. package/package.json +1 -1
package/dist/index.cjs CHANGED
@@ -14,17 +14,19 @@ const pluginutils = require('@rollup/pluginutils');
14
14
  const debug = require('debug');
15
15
  const kolorist = require('kolorist');
16
16
  const apiExtractor = require('@microsoft/api-extractor');
17
+ const node_module = require('node:module');
17
18
  const localPkg = require('local-pkg');
18
19
  const compareVersions = require('compare-versions');
19
20
  const MagicString = require('magic-string');
20
21
 
22
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
21
23
  function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
22
24
 
23
25
  const ts__default = /*#__PURE__*/_interopDefaultCompat(ts);
24
26
  const debug__default = /*#__PURE__*/_interopDefaultCompat(debug);
25
27
  const MagicString__default = /*#__PURE__*/_interopDefaultCompat(MagicString);
26
28
 
27
- const createProgram = typescript.proxyCreateProgram(ts__default, ts__default.createProgram, (ts2, options) => {
29
+ const _createProgram = typescript.proxyCreateProgram(ts__default, ts__default.createProgram, (ts2, options) => {
28
30
  const { configFilePath } = options.options;
29
31
  const vueOptions = typeof configFilePath === "string" ? languageCore.createParsedCommandLine(ts2, ts2.sys, configFilePath.replace(/\\/g, "/")).vueOptions : languageCore.resolveVueCompilerOptions({});
30
32
  if (options.host) {
@@ -46,6 +48,34 @@ const createProgram = typescript.proxyCreateProgram(ts__default, ts__default.cre
46
48
  );
47
49
  return [vueLanguagePlugin];
48
50
  });
51
+ const createProgram = (options) => {
52
+ const program = _createProgram(options);
53
+ const emit = program.emit;
54
+ program.emit = (targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) => {
55
+ if (writeFile) {
56
+ return emit(
57
+ targetSourceFile,
58
+ (fileName, data, writeByteOrderMark, onError, sourceFiles) => {
59
+ if (fileName.endsWith(".d.ts")) {
60
+ data = vueTsc.removeEmitGlobalTypes(data);
61
+ }
62
+ return writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles);
63
+ },
64
+ cancellationToken,
65
+ emitOnlyDtsFiles,
66
+ customTransformers
67
+ );
68
+ }
69
+ return emit(
70
+ targetSourceFile,
71
+ writeFile,
72
+ cancellationToken,
73
+ emitOnlyDtsFiles,
74
+ customTransformers
75
+ );
76
+ };
77
+ return program;
78
+ };
49
79
 
50
80
  const windowsSlashRE = /\\+/g;
51
81
  function slash(p) {
@@ -170,6 +200,23 @@ function getTsConfig(tsConfigPath, readFileSync) {
170
200
  Object.assign(tsConfig.compilerOptions, baseConfig.compilerOptions);
171
201
  return tsConfig;
172
202
  }
203
+ function getTsLibFolder({ root, entryRoot }) {
204
+ let libFolder;
205
+ try {
206
+ libFolder = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))).resolve("typescript").replace(/node_modules\/typescript.*/, "node_modules/typescript");
207
+ } catch {
208
+ libFolder = resolve(root, "node_modules/typescript");
209
+ if (!node_fs.existsSync(libFolder)) {
210
+ if (root !== entryRoot) {
211
+ libFolder = resolve(entryRoot, "node_modules/typescript");
212
+ if (!node_fs.existsSync(libFolder))
213
+ libFolder = void 0;
214
+ }
215
+ libFolder = void 0;
216
+ }
217
+ }
218
+ return libFolder;
219
+ }
173
220
  const BASE64_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");
174
221
  function base64Encode(number) {
175
222
  if (number >= 0 && number < BASE64_ALPHABET.length) {
@@ -308,6 +355,9 @@ function rollupDeclarationFiles({
308
355
  if (!dtsRE$1.test(fileName)) {
309
356
  fileName += ".d.ts";
310
357
  }
358
+ if (/preserve/i.test(compilerOptions.module)) {
359
+ compilerOptions = { ...compilerOptions, module: "ESNext" };
360
+ }
311
361
  const extractorConfig = apiExtractor.ExtractorConfig.prepare({
312
362
  configObject: {
313
363
  ...rollupConfig,
@@ -433,7 +483,7 @@ function VueResolver() {
433
483
  program.emit(
434
484
  sourceFile,
435
485
  (path, content) => {
436
- outputs.push({ path, content });
486
+ outputs.push({ path, content: vueTsc.removeEmitGlobalTypes(content) });
437
487
  },
438
488
  void 0,
439
489
  true
@@ -524,10 +574,12 @@ function transformCode(options) {
524
574
  return options.cleanVueFileName ? name.replace(/\.vue$/, "") : name;
525
575
  };
526
576
  let indexCount = 0;
577
+ let importCount = 0;
527
578
  walkSourceFile(ast, (node, parent) => {
528
579
  if (ts__default.isImportDeclaration(node)) {
529
580
  if (!node.importClause) {
530
581
  options.clearPureImport && s.remove(node.pos, node.end);
582
+ ++importCount;
531
583
  } else if (ts__default.isStringLiteral(node.moduleSpecifier) && (node.importClause.name || node.importClause.namedBindings && ts__default.isNamedImports(node.importClause.namedBindings))) {
532
584
  const libName = toLibName(node.moduleSpecifier.text);
533
585
  const importSet = importMap.get(libName) ?? importMap.set(libName, /* @__PURE__ */ new Set()).get(libName);
@@ -546,6 +598,7 @@ function transformCode(options) {
546
598
  });
547
599
  }
548
600
  s.remove(node.pos, node.end);
601
+ ++importCount;
549
602
  }
550
603
  return false;
551
604
  }
@@ -601,10 +654,11 @@ function transformCode(options) {
601
654
  prependImports += `import { ${Array.from(importSet).join(", ")} } from '${libName}';
602
655
  `;
603
656
  });
604
- s.prepend(prependImports);
657
+ s.trimStart("\n").prepend(prependImports);
605
658
  return {
606
659
  content: s.toString(),
607
- declareModules
660
+ declareModules,
661
+ diffLineCount: importMap.size && importCount < importMap.size ? importMap.size - importCount : null
608
662
  };
609
663
  }
610
664
  function hasNamedExport(content) {
@@ -1023,13 +1077,28 @@ ${logPrefix} Start generate declaration files...`));
1023
1077
  }
1024
1078
  bundleDebug("emit output patch");
1025
1079
  const currentDir = host.getCurrentDirectory();
1080
+ const declarationFiles = /* @__PURE__ */ new Map();
1081
+ const mapFiles = /* @__PURE__ */ new Map();
1082
+ const prependMappings = /* @__PURE__ */ new Map();
1083
+ for (const [filePath, content] of outputFiles.entries()) {
1084
+ if (filePath.endsWith(".map")) {
1085
+ mapFiles.set(filePath, content);
1086
+ } else {
1087
+ declarationFiles.set(filePath, content);
1088
+ }
1089
+ }
1026
1090
  await runParallel(
1027
1091
  node_os.cpus().length,
1028
- Array.from(outputFiles.entries()),
1092
+ Array.from(declarationFiles.entries()),
1029
1093
  async ([filePath, content]) => {
1030
- const isMapFile = filePath.endsWith(".map");
1031
- const baseDir = node_path.dirname(filePath);
1032
- if (!isMapFile && content) {
1094
+ const newFilePath = resolve(
1095
+ outDir,
1096
+ node_path.relative(
1097
+ entryRoot,
1098
+ cleanVueFileName ? filePath.replace(".vue.d.ts", ".d.ts") : filePath
1099
+ )
1100
+ );
1101
+ if (content) {
1033
1102
  const result = transformCode({
1034
1103
  filePath,
1035
1104
  content,
@@ -1041,7 +1110,18 @@ ${logPrefix} Start generate declaration files...`));
1041
1110
  });
1042
1111
  content = result.content;
1043
1112
  declareModules.push(...result.declareModules);
1113
+ if (result.diffLineCount) {
1114
+ prependMappings.set(`${newFilePath}.map`, ";".repeat(result.diffLineCount));
1115
+ }
1044
1116
  }
1117
+ await writeOutput(newFilePath, content, outDir);
1118
+ }
1119
+ );
1120
+ await runParallel(
1121
+ node_os.cpus().length,
1122
+ Array.from(mapFiles.entries()),
1123
+ async ([filePath, content]) => {
1124
+ const baseDir = node_path.dirname(filePath);
1045
1125
  filePath = resolve(
1046
1126
  outDir,
1047
1127
  node_path.relative(
@@ -1049,21 +1129,22 @@ ${logPrefix} Start generate declaration files...`));
1049
1129
  cleanVueFileName ? filePath.replace(".vue.d.ts", ".d.ts") : filePath
1050
1130
  )
1051
1131
  );
1052
- if (isMapFile) {
1053
- try {
1054
- const sourceMap = JSON.parse(content);
1055
- sourceMap.sources = sourceMap.sources.map((source) => {
1056
- return normalizePath(
1057
- node_path.relative(
1058
- node_path.dirname(filePath),
1059
- resolve(currentDir, node_path.relative(publicRoot, baseDir), source)
1060
- )
1061
- );
1062
- });
1063
- content = JSON.stringify(sourceMap);
1064
- } catch (e) {
1065
- logger.warn(`${logPrefix} ${kolorist.yellow("Processing source map fail:")} ${filePath}`);
1132
+ try {
1133
+ const sourceMap = JSON.parse(content);
1134
+ sourceMap.sources = sourceMap.sources.map((source) => {
1135
+ return normalizePath(
1136
+ node_path.relative(
1137
+ node_path.dirname(filePath),
1138
+ resolve(currentDir, node_path.relative(publicRoot, baseDir), source)
1139
+ )
1140
+ );
1141
+ });
1142
+ if (prependMappings.has(filePath)) {
1143
+ sourceMap.mappings = `${prependMappings.get(filePath)}${sourceMap.mappings}`;
1066
1144
  }
1145
+ content = JSON.stringify(sourceMap);
1146
+ } catch (e) {
1147
+ logger.warn(`${logPrefix} ${kolorist.yellow("Processing source map fail:")} ${filePath}`);
1067
1148
  }
1068
1149
  await writeOutput(filePath, content, outDir);
1069
1150
  }
@@ -1117,15 +1198,6 @@ export default ${libName}
1117
1198
  bundleDebug("insert index");
1118
1199
  if (rollupTypes) {
1119
1200
  logger.info(kolorist.green(`${logPrefix} Start rollup declaration files...`));
1120
- let libFolder = resolve(root, "node_modules/typescript");
1121
- if (!node_fs.existsSync(libFolder)) {
1122
- if (root !== entryRoot) {
1123
- libFolder = resolve(entryRoot, "node_modules/typescript");
1124
- if (!node_fs.existsSync(libFolder))
1125
- libFolder = void 0;
1126
- }
1127
- libFolder = void 0;
1128
- }
1129
1201
  const rollupFiles = /* @__PURE__ */ new Set();
1130
1202
  const compilerOptions2 = configPath ? getTsConfig(configPath, host.readFile).compilerOptions : rawCompilerOptions;
1131
1203
  const rollup = async (path) => {
@@ -1136,7 +1208,7 @@ export default ${libName}
1136
1208
  outDir,
1137
1209
  entryPath: path,
1138
1210
  fileName: node_path.basename(path),
1139
- libFolder,
1211
+ libFolder: getTsLibFolder({ root, entryRoot }),
1140
1212
  rollupConfig,
1141
1213
  rollupOptions
1142
1214
  });
package/dist/index.mjs CHANGED
@@ -17,11 +17,12 @@ import { createFilter } from '@rollup/pluginutils';
17
17
  import debug from 'debug';
18
18
  import { cyan, yellow, green } from 'kolorist';
19
19
  import { ExtractorConfig, Extractor } from '@microsoft/api-extractor';
20
+ import { createRequire } from 'node:module';
20
21
  import { getPackageInfoSync, resolveModule } from 'local-pkg';
21
22
  import { compare } from 'compare-versions';
22
23
  import MagicString from 'magic-string';
23
24
 
24
- const createProgram = proxyCreateProgram(ts, ts.createProgram, (ts2, options) => {
25
+ const _createProgram = proxyCreateProgram(ts, ts.createProgram, (ts2, options) => {
25
26
  const { configFilePath } = options.options;
26
27
  const vueOptions = typeof configFilePath === "string" ? createParsedCommandLine(ts2, ts2.sys, configFilePath.replace(/\\/g, "/")).vueOptions : resolveVueCompilerOptions({});
27
28
  if (options.host) {
@@ -43,6 +44,34 @@ const createProgram = proxyCreateProgram(ts, ts.createProgram, (ts2, options) =>
43
44
  );
44
45
  return [vueLanguagePlugin];
45
46
  });
47
+ const createProgram = (options) => {
48
+ const program = _createProgram(options);
49
+ const emit = program.emit;
50
+ program.emit = (targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) => {
51
+ if (writeFile) {
52
+ return emit(
53
+ targetSourceFile,
54
+ (fileName, data, writeByteOrderMark, onError, sourceFiles) => {
55
+ if (fileName.endsWith(".d.ts")) {
56
+ data = removeEmitGlobalTypes(data);
57
+ }
58
+ return writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles);
59
+ },
60
+ cancellationToken,
61
+ emitOnlyDtsFiles,
62
+ customTransformers
63
+ );
64
+ }
65
+ return emit(
66
+ targetSourceFile,
67
+ writeFile,
68
+ cancellationToken,
69
+ emitOnlyDtsFiles,
70
+ customTransformers
71
+ );
72
+ };
73
+ return program;
74
+ };
46
75
 
47
76
  const windowsSlashRE = /\\+/g;
48
77
  function slash(p) {
@@ -167,6 +196,23 @@ function getTsConfig(tsConfigPath, readFileSync) {
167
196
  Object.assign(tsConfig.compilerOptions, baseConfig.compilerOptions);
168
197
  return tsConfig;
169
198
  }
199
+ function getTsLibFolder({ root, entryRoot }) {
200
+ let libFolder;
201
+ try {
202
+ libFolder = createRequire(import.meta.url).resolve("typescript").replace(/node_modules\/typescript.*/, "node_modules/typescript");
203
+ } catch {
204
+ libFolder = resolve(root, "node_modules/typescript");
205
+ if (!existsSync(libFolder)) {
206
+ if (root !== entryRoot) {
207
+ libFolder = resolve(entryRoot, "node_modules/typescript");
208
+ if (!existsSync(libFolder))
209
+ libFolder = void 0;
210
+ }
211
+ libFolder = void 0;
212
+ }
213
+ }
214
+ return libFolder;
215
+ }
170
216
  const BASE64_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");
171
217
  function base64Encode(number) {
172
218
  if (number >= 0 && number < BASE64_ALPHABET.length) {
@@ -305,6 +351,9 @@ function rollupDeclarationFiles({
305
351
  if (!dtsRE$1.test(fileName)) {
306
352
  fileName += ".d.ts";
307
353
  }
354
+ if (/preserve/i.test(compilerOptions.module)) {
355
+ compilerOptions = { ...compilerOptions, module: "ESNext" };
356
+ }
308
357
  const extractorConfig = ExtractorConfig.prepare({
309
358
  configObject: {
310
359
  ...rollupConfig,
@@ -430,7 +479,7 @@ function VueResolver() {
430
479
  program.emit(
431
480
  sourceFile,
432
481
  (path, content) => {
433
- outputs.push({ path, content });
482
+ outputs.push({ path, content: removeEmitGlobalTypes(content) });
434
483
  },
435
484
  void 0,
436
485
  true
@@ -521,10 +570,12 @@ function transformCode(options) {
521
570
  return options.cleanVueFileName ? name.replace(/\.vue$/, "") : name;
522
571
  };
523
572
  let indexCount = 0;
573
+ let importCount = 0;
524
574
  walkSourceFile(ast, (node, parent) => {
525
575
  if (ts.isImportDeclaration(node)) {
526
576
  if (!node.importClause) {
527
577
  options.clearPureImport && s.remove(node.pos, node.end);
578
+ ++importCount;
528
579
  } else if (ts.isStringLiteral(node.moduleSpecifier) && (node.importClause.name || node.importClause.namedBindings && ts.isNamedImports(node.importClause.namedBindings))) {
529
580
  const libName = toLibName(node.moduleSpecifier.text);
530
581
  const importSet = importMap.get(libName) ?? importMap.set(libName, /* @__PURE__ */ new Set()).get(libName);
@@ -543,6 +594,7 @@ function transformCode(options) {
543
594
  });
544
595
  }
545
596
  s.remove(node.pos, node.end);
597
+ ++importCount;
546
598
  }
547
599
  return false;
548
600
  }
@@ -598,10 +650,11 @@ function transformCode(options) {
598
650
  prependImports += `import { ${Array.from(importSet).join(", ")} } from '${libName}';
599
651
  `;
600
652
  });
601
- s.prepend(prependImports);
653
+ s.trimStart("\n").prepend(prependImports);
602
654
  return {
603
655
  content: s.toString(),
604
- declareModules
656
+ declareModules,
657
+ diffLineCount: importMap.size && importCount < importMap.size ? importMap.size - importCount : null
605
658
  };
606
659
  }
607
660
  function hasNamedExport(content) {
@@ -1020,13 +1073,28 @@ ${logPrefix} Start generate declaration files...`));
1020
1073
  }
1021
1074
  bundleDebug("emit output patch");
1022
1075
  const currentDir = host.getCurrentDirectory();
1076
+ const declarationFiles = /* @__PURE__ */ new Map();
1077
+ const mapFiles = /* @__PURE__ */ new Map();
1078
+ const prependMappings = /* @__PURE__ */ new Map();
1079
+ for (const [filePath, content] of outputFiles.entries()) {
1080
+ if (filePath.endsWith(".map")) {
1081
+ mapFiles.set(filePath, content);
1082
+ } else {
1083
+ declarationFiles.set(filePath, content);
1084
+ }
1085
+ }
1023
1086
  await runParallel(
1024
1087
  cpus().length,
1025
- Array.from(outputFiles.entries()),
1088
+ Array.from(declarationFiles.entries()),
1026
1089
  async ([filePath, content]) => {
1027
- const isMapFile = filePath.endsWith(".map");
1028
- const baseDir = dirname(filePath);
1029
- if (!isMapFile && content) {
1090
+ const newFilePath = resolve(
1091
+ outDir,
1092
+ relative(
1093
+ entryRoot,
1094
+ cleanVueFileName ? filePath.replace(".vue.d.ts", ".d.ts") : filePath
1095
+ )
1096
+ );
1097
+ if (content) {
1030
1098
  const result = transformCode({
1031
1099
  filePath,
1032
1100
  content,
@@ -1038,7 +1106,18 @@ ${logPrefix} Start generate declaration files...`));
1038
1106
  });
1039
1107
  content = result.content;
1040
1108
  declareModules.push(...result.declareModules);
1109
+ if (result.diffLineCount) {
1110
+ prependMappings.set(`${newFilePath}.map`, ";".repeat(result.diffLineCount));
1111
+ }
1041
1112
  }
1113
+ await writeOutput(newFilePath, content, outDir);
1114
+ }
1115
+ );
1116
+ await runParallel(
1117
+ cpus().length,
1118
+ Array.from(mapFiles.entries()),
1119
+ async ([filePath, content]) => {
1120
+ const baseDir = dirname(filePath);
1042
1121
  filePath = resolve(
1043
1122
  outDir,
1044
1123
  relative(
@@ -1046,21 +1125,22 @@ ${logPrefix} Start generate declaration files...`));
1046
1125
  cleanVueFileName ? filePath.replace(".vue.d.ts", ".d.ts") : filePath
1047
1126
  )
1048
1127
  );
1049
- if (isMapFile) {
1050
- try {
1051
- const sourceMap = JSON.parse(content);
1052
- sourceMap.sources = sourceMap.sources.map((source) => {
1053
- return normalizePath(
1054
- relative(
1055
- dirname(filePath),
1056
- resolve(currentDir, relative(publicRoot, baseDir), source)
1057
- )
1058
- );
1059
- });
1060
- content = JSON.stringify(sourceMap);
1061
- } catch (e) {
1062
- logger.warn(`${logPrefix} ${yellow("Processing source map fail:")} ${filePath}`);
1128
+ try {
1129
+ const sourceMap = JSON.parse(content);
1130
+ sourceMap.sources = sourceMap.sources.map((source) => {
1131
+ return normalizePath(
1132
+ relative(
1133
+ dirname(filePath),
1134
+ resolve(currentDir, relative(publicRoot, baseDir), source)
1135
+ )
1136
+ );
1137
+ });
1138
+ if (prependMappings.has(filePath)) {
1139
+ sourceMap.mappings = `${prependMappings.get(filePath)}${sourceMap.mappings}`;
1063
1140
  }
1141
+ content = JSON.stringify(sourceMap);
1142
+ } catch (e) {
1143
+ logger.warn(`${logPrefix} ${yellow("Processing source map fail:")} ${filePath}`);
1064
1144
  }
1065
1145
  await writeOutput(filePath, content, outDir);
1066
1146
  }
@@ -1114,15 +1194,6 @@ export default ${libName}
1114
1194
  bundleDebug("insert index");
1115
1195
  if (rollupTypes) {
1116
1196
  logger.info(green(`${logPrefix} Start rollup declaration files...`));
1117
- let libFolder = resolve(root, "node_modules/typescript");
1118
- if (!existsSync(libFolder)) {
1119
- if (root !== entryRoot) {
1120
- libFolder = resolve(entryRoot, "node_modules/typescript");
1121
- if (!existsSync(libFolder))
1122
- libFolder = void 0;
1123
- }
1124
- libFolder = void 0;
1125
- }
1126
1197
  const rollupFiles = /* @__PURE__ */ new Set();
1127
1198
  const compilerOptions2 = configPath ? getTsConfig(configPath, host.readFile).compilerOptions : rawCompilerOptions;
1128
1199
  const rollup = async (path) => {
@@ -1133,7 +1204,7 @@ export default ${libName}
1133
1204
  outDir,
1134
1205
  entryPath: path,
1135
1206
  fileName: basename(path),
1136
- libFolder,
1207
+ libFolder: getTsLibFolder({ root, entryRoot }),
1137
1208
  rollupConfig,
1138
1209
  rollupOptions
1139
1210
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vite-plugin-dts",
3
- "version": "4.0.0-beta.2",
3
+ "version": "4.0.0",
4
4
  "type": "module",
5
5
  "packageManager": "pnpm@8.3.0",
6
6
  "license": "MIT",