vite-plugin-dts 3.9.1 → 4.0.0-beta.1

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
@@ -7,12 +7,15 @@ const node_fs = require('node:fs');
7
7
  const promises = require('node:fs/promises');
8
8
  const node_os = require('node:os');
9
9
  const languageCore = require('@vue/language-core');
10
+ const typescript = require('@volar/typescript');
10
11
  const ts = require('typescript');
11
12
  const pluginutils = require('@rollup/pluginutils');
12
13
  const vueTsc = require('vue-tsc');
13
14
  const debug = require('debug');
14
15
  const kolorist = require('kolorist');
15
16
  const apiExtractor = require('@microsoft/api-extractor');
17
+ const localPkg = require('local-pkg');
18
+ const compareVersions = require('compare-versions');
16
19
  const MagicString = require('magic-string');
17
20
 
18
21
  function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
@@ -124,9 +127,10 @@ function removeDirIfEmpty(dir) {
124
127
  return onlyHasDir;
125
128
  }
126
129
  function getTsConfig(tsConfigPath, readFileSync) {
130
+ const baseConfig = ts__default.readConfigFile(tsConfigPath, readFileSync).config ?? {};
127
131
  const tsConfig = {
128
- compilerOptions: {},
129
- ...ts__default.readConfigFile(tsConfigPath, readFileSync).config ?? {}
132
+ ...baseConfig,
133
+ compilerOptions: {}
130
134
  };
131
135
  if (tsConfig.extends) {
132
136
  ensureArray(tsConfig.extends).forEach((configPath) => {
@@ -140,6 +144,7 @@ function getTsConfig(tsConfigPath, readFileSync) {
140
144
  }
141
145
  });
142
146
  }
147
+ Object.assign(tsConfig.compilerOptions, baseConfig.compilerOptions);
143
148
  return tsConfig;
144
149
  }
145
150
  const BASE64_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");
@@ -203,7 +208,7 @@ function findTypesPath(...pkgs) {
203
208
  for (const pkg of pkgs) {
204
209
  if (typeof pkg !== "object")
205
210
  continue;
206
- path = pkg.types || pkg.typings || pkg.exports?.["."]?.types || pkg.exports?.["./"]?.types;
211
+ path = pkg.types || pkg.typings || pkg.exports?.types || pkg.exports?.["."]?.types || pkg.exports?.["./"]?.types;
207
212
  if (path)
208
213
  return path;
209
214
  }
@@ -244,8 +249,27 @@ function editSourceMapDir(content, fromDir, toDir) {
244
249
  }
245
250
  return true;
246
251
  }
252
+ const regexpSymbolRE = /([$.\\+?()[\]!<=|{}^,])/g;
253
+ const asteriskRE = /[*]+/g;
254
+ function parseTsAliases(basePath, paths) {
255
+ const result = [];
256
+ for (const [pathWithAsterisk, replacements] of Object.entries(paths)) {
257
+ const find = new RegExp(
258
+ `^${pathWithAsterisk.replace(regexpSymbolRE, "\\$1").replace(asteriskRE, "([^\\/]+)")}$`
259
+ );
260
+ let index = 1;
261
+ result.push({
262
+ find,
263
+ replacement: ensureAbsolute(
264
+ replacements[0].replace(asteriskRE, () => `$${index++}`),
265
+ basePath
266
+ )
267
+ });
268
+ }
269
+ return result;
270
+ }
247
271
 
248
- const dtsRE$1 = /\.d\.tsx?$/;
272
+ const dtsRE$1 = /\.d\.(m|c)?tsx?$/;
249
273
  function rollupDeclarationFiles({
250
274
  root,
251
275
  configPath,
@@ -341,6 +365,17 @@ export default _default;
341
365
  }
342
366
 
343
367
  const svelteRE = /\.svelte$/;
368
+ let lowerVersion;
369
+ function querySvelteVersion() {
370
+ if (typeof lowerVersion === "boolean")
371
+ return;
372
+ try {
373
+ const version = localPkg.getPackageInfoSync("svelte")?.version ?? localPkg.getPackageInfoSync("svelte", { paths: [localPkg.resolveModule("svelte") || process.cwd()] })?.version;
374
+ lowerVersion = version ? compareVersions.compare(version, "4.0.0", "<") : false;
375
+ } catch {
376
+ lowerVersion = false;
377
+ }
378
+ }
344
379
  function SvelteResolver() {
345
380
  return {
346
381
  name: "svelte",
@@ -348,10 +383,12 @@ function SvelteResolver() {
348
383
  return svelteRE.test(id);
349
384
  },
350
385
  transform({ id, root }) {
386
+ querySvelteVersion();
351
387
  return [
352
388
  {
353
389
  path: node_path.relative(root, `${id}.d.ts`),
354
- content: "export { SvelteComponentTyped as default } from 'svelte';\n"
390
+ content: `export { ${lowerVersion ? "SvelteComponentTyped" : "SvelteComponent"} as default } from 'svelte';
391
+ `
355
392
  }
356
393
  ];
357
394
  }
@@ -365,16 +402,19 @@ function VueResolver() {
365
402
  supports(id) {
366
403
  return vueRE.test(id);
367
404
  },
368
- transform({ id, code, program, service }) {
405
+ transform({ id, code, program }) {
369
406
  const sourceFile = program.getSourceFile(id) || program.getSourceFile(id + ".ts") || program.getSourceFile(id + ".js") || program.getSourceFile(id + ".tsx") || program.getSourceFile(id + ".jsx");
370
407
  if (!sourceFile)
371
408
  return [];
372
- const outputs = service.getEmitOutput(sourceFile.fileName, true).outputFiles.map((file) => {
373
- return {
374
- path: file.name,
375
- content: file.text
376
- };
377
- });
409
+ const outputs = [];
410
+ program.emit(
411
+ sourceFile,
412
+ (path, content) => {
413
+ outputs.push({ path, content });
414
+ },
415
+ void 0,
416
+ true
417
+ );
378
418
  if (!program.getCompilerOptions().declarationMap)
379
419
  return outputs;
380
420
  const [beforeScript] = code.split(/\s*<script.*>/);
@@ -570,6 +610,26 @@ function hasExportDefault(content) {
570
610
  return has;
571
611
  }
572
612
 
613
+ const createProgram = typescript.proxyCreateProgram(ts__default, ts__default.createProgram, (ts2, options) => {
614
+ const { configFilePath } = options.options;
615
+ const vueOptions = typeof configFilePath === "string" ? languageCore.createParsedCommandLine(ts2, ts2.sys, configFilePath.replace(/\\/g, "/")).vueOptions : languageCore.resolveVueCompilerOptions({});
616
+ if (options.host) {
617
+ const writeFile2 = options.host.writeFile.bind(options.host);
618
+ options.host.writeFile = (fileName, contents, ...args) => {
619
+ return writeFile2(fileName, vueTsc.removeEmitGlobalTypes(contents), ...args);
620
+ };
621
+ }
622
+ const vueLanguagePlugin = languageCore.createVueLanguagePlugin(
623
+ ts2,
624
+ (id) => id,
625
+ options.host?.useCaseSensitiveFileNames?.() ?? false,
626
+ () => "",
627
+ () => options.rootNames.map((rootName) => rootName.replace(/\\/g, "/")),
628
+ options.options,
629
+ vueOptions
630
+ );
631
+ return [vueLanguagePlugin];
632
+ });
573
633
  const jsRE = /\.(m|c)?jsx?$/;
574
634
  const tsRE = /\.(m|c)?tsx?$/;
575
635
  const dtsRE = /\.d\.(m|c)?tsx?$/;
@@ -596,8 +656,6 @@ const noop = () => {
596
656
  };
597
657
  const extPrefix = (file) => mtjsRE.test(file) ? "m" : ctjsRE.test(file) ? "c" : "";
598
658
  const tsToDts = (path) => `${path.replace(tsRE, "")}.d.ts`;
599
- const regexpSymbolRE = /([$.\\+?()[\]!<=|{}^,])/g;
600
- const asteriskRE = /[*]+/g;
601
659
  function dtsPlugin(options = {}) {
602
660
  const {
603
661
  tsconfigPath,
@@ -635,6 +693,7 @@ function dtsPlugin(options = {}) {
635
693
  let host;
636
694
  let program;
637
695
  let filter;
696
+ let rebuildProgram;
638
697
  let bundled = false;
639
698
  let timeRecord = 0;
640
699
  const resolvers = parseResolvers([
@@ -645,6 +704,9 @@ function dtsPlugin(options = {}) {
645
704
  ]);
646
705
  const rootFiles = /* @__PURE__ */ new Set();
647
706
  const outputFiles = /* @__PURE__ */ new Map();
707
+ const setOutputFile = (path, content) => {
708
+ outputFiles.set(path, content);
709
+ };
648
710
  const rollupConfig = { ...options.rollupConfig || {} };
649
711
  rollupConfig.bundledPackages = rollupConfig.bundledPackages || options.bundledPackages || [];
650
712
  const cleanPath = (path) => {
@@ -758,20 +820,9 @@ ${logPrefix} ${kolorist.yellow(
758
820
  }
759
821
  const { baseUrl, paths } = compilerOptions;
760
822
  if (pathsToAliases && baseUrl && paths) {
761
- const basePath = ensureAbsolute(baseUrl, configPath ? node_path.dirname(configPath) : root);
762
- for (const [pathWithAsterisk, replacements] of Object.entries(paths)) {
763
- const find = new RegExp(
764
- `^${pathWithAsterisk.replace(regexpSymbolRE, "\\$1").replace(asteriskRE, "(.+)")}$`
765
- );
766
- let index = 1;
767
- aliases.push({
768
- find,
769
- replacement: ensureAbsolute(
770
- replacements[0].replace(asteriskRE, () => `$${index++}`),
771
- basePath
772
- )
773
- });
774
- }
823
+ aliases.push(
824
+ ...parseTsAliases(ensureAbsolute(baseUrl, configPath ? node_path.dirname(configPath) : root), paths)
825
+ );
775
826
  }
776
827
  const computeGlobs = (rootGlobs, tsGlobs, defaultGlob) => {
777
828
  if (rootGlobs?.length) {
@@ -781,7 +832,11 @@ ${logPrefix} ${kolorist.yellow(
781
832
  (glob) => normalizeGlob(ensureAbsolute(glob, configPath ? node_path.dirname(configPath) : root))
782
833
  );
783
834
  };
784
- include = computeGlobs(options.include, content?.raw.include, "**/*");
835
+ include = computeGlobs(
836
+ options.include,
837
+ [...ensureArray(content?.raw.include ?? []), ...ensureArray(content?.raw.files ?? [])],
838
+ "**/*"
839
+ );
785
840
  exclude = computeGlobs(options.exclude, content?.raw.exclude, "node_modules/**");
786
841
  filter = pluginutils.createFilter(include, exclude);
787
842
  const rootNames = [
@@ -790,11 +845,12 @@ ${logPrefix} ${kolorist.yellow(
790
845
  )
791
846
  ];
792
847
  host = ts__default.createCompilerHost(compilerOptions);
793
- program = vueTsc.createProgram({
848
+ program = (rebuildProgram = () => createProgram({
794
849
  host,
795
850
  rootNames,
796
- options: compilerOptions
797
- });
851
+ options: compilerOptions,
852
+ projectReferences: content?.projectReferences
853
+ }))();
798
854
  libName = toCapitalCase(libName || "_default");
799
855
  indexName = indexName || defaultIndex;
800
856
  const maybeEmitted = (sourceFile) => {
@@ -832,7 +888,6 @@ ${logPrefix} ${kolorist.yellow(
832
888
  }
833
889
  const startTime = Date.now();
834
890
  const outDir = outDirs[0];
835
- const service = program.__vue.languageService;
836
891
  id = id.split("?")[0];
837
892
  rootFiles.delete(id);
838
893
  if (resolver) {
@@ -842,11 +897,10 @@ ${logPrefix} ${kolorist.yellow(
842
897
  root: publicRoot,
843
898
  outDir,
844
899
  host,
845
- program,
846
- service
900
+ program
847
901
  });
848
902
  for (const { path, content } of result) {
849
- outputFiles.set(
903
+ setOutputFile(
850
904
  resolve(publicRoot, node_path.relative(outDir, ensureAbsolute(path, outDir))),
851
905
  content
852
906
  );
@@ -854,17 +908,22 @@ ${logPrefix} ${kolorist.yellow(
854
908
  } else {
855
909
  const sourceFile = program.getSourceFile(id);
856
910
  if (sourceFile) {
857
- for (const outputFile of service.getEmitOutput(sourceFile.fileName, true).outputFiles) {
858
- outputFiles.set(
859
- resolve(publicRoot, node_path.relative(outDir, ensureAbsolute(outputFile.name, outDir))),
860
- outputFile.text
861
- );
862
- }
911
+ program.emit(
912
+ sourceFile,
913
+ (name, text) => {
914
+ setOutputFile(
915
+ resolve(publicRoot, node_path.relative(outDir, ensureAbsolute(name, outDir))),
916
+ text
917
+ );
918
+ },
919
+ void 0,
920
+ true
921
+ );
863
922
  }
864
923
  }
865
924
  const dtsId = id.replace(tjsRE, "") + ".d.ts";
866
925
  const dtsSourceFile = program.getSourceFile(dtsId);
867
- dtsSourceFile && filter(dtsSourceFile.fileName) && outputFiles.set(normalizePath(dtsSourceFile.fileName), dtsSourceFile.getFullText());
926
+ dtsSourceFile && filter(dtsSourceFile.fileName) && setOutputFile(normalizePath(dtsSourceFile.fileName), dtsSourceFile.getFullText());
868
927
  timeRecord += Date.now() - startTime;
869
928
  },
870
929
  watchChange(id) {
@@ -876,9 +935,9 @@ ${logPrefix} ${kolorist.yellow(
876
935
  const sourceFile = host.getSourceFile(id, ts__default.ScriptTarget.ESNext);
877
936
  if (sourceFile) {
878
937
  rootFiles.add(sourceFile.fileName);
879
- program.__vue.projectVersion++;
880
938
  bundled = false;
881
939
  timeRecord = 0;
940
+ program = rebuildProgram();
882
941
  }
883
942
  },
884
943
  async writeBundle() {
@@ -914,21 +973,25 @@ ${logPrefix} Start generate declaration files...`));
914
973
  await promises.writeFile(path, content, "utf-8");
915
974
  record && emittedFiles.set(path, content);
916
975
  };
917
- const service = program.__vue.languageService;
918
976
  const sourceFiles = program.getSourceFiles();
919
977
  for (const sourceFile of sourceFiles) {
920
978
  if (!filter(sourceFile.fileName))
921
979
  continue;
922
980
  if (copyDtsFiles && dtsRE.test(sourceFile.fileName)) {
923
- outputFiles.set(normalizePath(sourceFile.fileName), sourceFile.getFullText());
981
+ setOutputFile(normalizePath(sourceFile.fileName), sourceFile.getFullText());
924
982
  }
925
983
  if (rootFiles.has(sourceFile.fileName)) {
926
- for (const outputFile of service.getEmitOutput(sourceFile.fileName, true).outputFiles) {
927
- outputFiles.set(
928
- resolve(publicRoot, node_path.relative(outDir, ensureAbsolute(outputFile.name, outDir))),
929
- outputFile.text
930
- );
931
- }
984
+ program.emit(
985
+ sourceFile,
986
+ (name, text) => {
987
+ setOutputFile(
988
+ resolve(publicRoot, node_path.relative(outDir, ensureAbsolute(name, outDir))),
989
+ text
990
+ );
991
+ },
992
+ void 0,
993
+ true
994
+ );
932
995
  rootFiles.delete(sourceFile.fileName);
933
996
  }
934
997
  }
package/dist/index.d.cts CHANGED
@@ -28,7 +28,6 @@ interface Resolver {
28
28
  outDir: string;
29
29
  host: ts.CompilerHost;
30
30
  program: ts.Program;
31
- service: ts.LanguageService;
32
31
  }) => MaybePromise<{
33
32
  path: string;
34
33
  content: string;
package/dist/index.d.mts CHANGED
@@ -28,7 +28,6 @@ interface Resolver {
28
28
  outDir: string;
29
29
  host: ts.CompilerHost;
30
30
  program: ts.Program;
31
- service: ts.LanguageService;
32
31
  }) => MaybePromise<{
33
32
  path: string;
34
33
  content: string;
package/dist/index.d.ts CHANGED
@@ -28,7 +28,6 @@ interface Resolver {
28
28
  outDir: string;
29
29
  host: ts.CompilerHost;
30
30
  program: ts.Program;
31
- service: ts.LanguageService;
32
31
  }) => MaybePromise<{
33
32
  path: string;
34
33
  content: string;