vite-plugin-dts 1.0.4 → 1.1.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.js CHANGED
@@ -28,7 +28,7 @@ module.exports = dtsPlugin;
28
28
  dtsPlugin['default'] = dtsPlugin;
29
29
 
30
30
  // src/plugin.ts
31
- var import_path3 = require("path");
31
+ var import_path4 = require("path");
32
32
  var import_fs_extra = __toESM(require("fs-extra"));
33
33
  var import_os = __toESM(require("os"));
34
34
  var import_chalk = __toESM(require("chalk"));
@@ -44,6 +44,7 @@ var import_vite = require("vite");
44
44
 
45
45
  // src/utils.ts
46
46
  var import_path = require("path");
47
+ var import_fs = require("fs");
47
48
  function isNativeObj(value) {
48
49
  return Object.prototype.toString.call(value) === "[object Object]";
49
50
  }
@@ -146,6 +147,26 @@ function queryPublicPath(paths) {
146
147
  }
147
148
  return publicPath.slice(0, -1);
148
149
  }
150
+ function removeDirIfEmpty(dir) {
151
+ if (!(0, import_fs.existsSync)(dir)) {
152
+ return;
153
+ }
154
+ let onlyHasDir = true;
155
+ for (const file of (0, import_fs.readdirSync)(dir)) {
156
+ const abs = (0, import_path.resolve)(dir, file);
157
+ if ((0, import_fs.lstatSync)(abs).isDirectory()) {
158
+ if (!removeDirIfEmpty(abs)) {
159
+ onlyHasDir = false;
160
+ }
161
+ } else {
162
+ onlyHasDir = false;
163
+ }
164
+ }
165
+ if (onlyHasDir) {
166
+ (0, import_fs.rmdirSync)(dir);
167
+ }
168
+ return onlyHasDir;
169
+ }
149
170
 
150
171
  // src/transform.ts
151
172
  var globSuffixRE = /^((?:.*\.[^.]+)|(?:\*+))$/;
@@ -291,33 +312,117 @@ const _sfc_main = ${classMatch[1]}`;
291
312
  content += "\nexport default _sfc_main\n";
292
313
  ext = scriptSetup.lang || "js";
293
314
  } else if (script && script.content) {
294
- content = script.content;
315
+ content = rewriteDefault(script.content, "_sfc_main");
316
+ content += "\nexport default _sfc_main\n";
295
317
  ext = script.lang || "js";
296
318
  }
297
319
  }
298
320
  return { content, ext };
299
321
  }
300
322
 
323
+ // src/rollup.ts
324
+ var import_path3 = require("path");
325
+ var import_api_extractor = require("@microsoft/api-extractor");
326
+ var import_Collector = require("@microsoft/api-extractor/lib/collector/Collector");
327
+ var import_MessageRouter = require("@microsoft/api-extractor/lib/collector/MessageRouter");
328
+ var import_DtsRollupGenerator = require("@microsoft/api-extractor/lib/generators/DtsRollupGenerator");
329
+ var import_node_core_library = require("@rushstack/node-core-library");
330
+ var dtsRE = /\.d\.tsx?$/;
331
+ function rollupDeclarationFiles({
332
+ root,
333
+ tsConfigPath,
334
+ outputDir,
335
+ entryPath,
336
+ fileName
337
+ }) {
338
+ const configObjectFullPath = (0, import_path3.resolve)(root, "api-extractor.json");
339
+ const packageJsonLookup = new import_node_core_library.PackageJsonLookup();
340
+ const packageJsonFullPath = packageJsonLookup.tryGetPackageJsonFilePathFor(configObjectFullPath);
341
+ if (!dtsRE.test(fileName)) {
342
+ fileName += ".d.ts";
343
+ }
344
+ const extractorConfig = import_api_extractor.ExtractorConfig.prepare({
345
+ configObject: {
346
+ projectFolder: root,
347
+ mainEntryPointFilePath: entryPath,
348
+ compiler: {
349
+ tsconfigFilePath: tsConfigPath
350
+ },
351
+ apiReport: {
352
+ enabled: false,
353
+ reportFileName: "<unscopedPackageName>.api.md"
354
+ },
355
+ docModel: {
356
+ enabled: false
357
+ },
358
+ dtsRollup: {
359
+ enabled: true,
360
+ publicTrimmedFilePath: (0, import_path3.resolve)(outputDir, fileName)
361
+ },
362
+ tsdocMetadata: {
363
+ enabled: false
364
+ },
365
+ messages: {
366
+ compilerMessageReporting: {
367
+ default: {
368
+ logLevel: "none"
369
+ }
370
+ },
371
+ extractorMessageReporting: {
372
+ default: {
373
+ logLevel: "none"
374
+ }
375
+ }
376
+ }
377
+ },
378
+ configObjectFullPath,
379
+ packageJsonFullPath
380
+ });
381
+ const compilerState = import_api_extractor.CompilerState.create(extractorConfig, {
382
+ localBuild: true,
383
+ showVerboseMessages: false
384
+ });
385
+ const messageRouter = new import_MessageRouter.MessageRouter({
386
+ workingPackageFolder: root,
387
+ messageCallback: void 0,
388
+ messagesConfig: extractorConfig.messages,
389
+ showVerboseMessages: false,
390
+ showDiagnostics: false,
391
+ tsdocConfiguration: extractorConfig.tsdocConfiguration
392
+ });
393
+ const collector = new import_Collector.Collector({
394
+ program: compilerState.program,
395
+ messageRouter,
396
+ extractorConfig
397
+ });
398
+ collector.analyze();
399
+ import_DtsRollupGenerator.DtsRollupGenerator.writeTypingsFile(collector, extractorConfig.publicTrimmedFilePath, import_DtsRollupGenerator.DtsRollupKind.PublicRelease, extractorConfig.newlineKind);
400
+ }
401
+
301
402
  // src/plugin.ts
302
403
  var noneExport = "export {};\n";
303
404
  var virtualPrefix = "\0";
304
405
  var vueRE = /\.vue$/;
305
406
  var tsRE = /\.tsx?$/;
306
407
  var jsRE = /\.jsx?$/;
307
- var dtsRE = /\.d\.tsx?$/;
408
+ var dtsRE2 = /\.d\.tsx?$/;
308
409
  var tjsRE = /\.(t|j)sx?$/;
309
410
  var watchExtensionRE = /\.(vue|(t|j)sx?)$/;
411
+ var fullRelativeRE = /^\.\.?\//;
412
+ var defaultIndex = "index.d.ts";
310
413
  var noop = () => {
311
414
  };
415
+ var logPrefix = import_chalk.default.cyan("[vite:dts]");
312
416
  var bundleDebug = (0, import_debug.debug)("vite-plugin-dts:bundle");
313
417
  function dtsPlugin(options = {}) {
314
- var _a;
418
+ var _a, _b;
315
419
  const {
316
420
  tsConfigFilePath = "tsconfig.json",
317
421
  cleanVueFileName = false,
318
422
  staticImport = false,
319
423
  clearPureImport = true,
320
424
  insertTypesEntry = false,
425
+ rollupTypes = false,
321
426
  noEmitOnError = false,
322
427
  skipDiagnostics = true,
323
428
  logDiagnostics = false,
@@ -328,7 +433,9 @@ function dtsPlugin(options = {}) {
328
433
  } = options;
329
434
  const compilerOptions = (_a = options.compilerOptions) != null ? _a : {};
330
435
  let root;
331
- let entryRoot;
436
+ let entryRoot = (_b = options.entryRoot) != null ? _b : "";
437
+ let libName;
438
+ let indexName;
332
439
  let aliases;
333
440
  let entries;
334
441
  let logger;
@@ -357,7 +464,7 @@ function dtsPlugin(options = {}) {
357
464
  }
358
465
  },
359
466
  configResolved(config) {
360
- var _a2, _b;
467
+ var _a2, _b2, _c;
361
468
  if (isBundle)
362
469
  return;
363
470
  logger = config.logger;
@@ -365,8 +472,17 @@ function dtsPlugin(options = {}) {
365
472
  logger.warn(import_chalk.default.yellow(`
366
473
  ${import_chalk.default.cyan("[vite:dts]")} You building not a library that may not need to generate declaration files.
367
474
  `));
475
+ libName = "_default";
476
+ indexName = defaultIndex;
477
+ } else {
478
+ const filename = (_a2 = config.build.lib.fileName) != null ? _a2 : defaultIndex;
479
+ libName = config.build.lib.name || "_default";
480
+ indexName = typeof filename === "string" ? filename : filename("es");
481
+ if (!dtsRE2.test(indexName)) {
482
+ indexName = `${tjsRE.test(indexName) ? indexName.replace(tjsRE, "") : indexName}.d.ts`;
483
+ }
368
484
  }
369
- root = ensureAbsolute((_a2 = options.root) != null ? _a2 : "", config.root);
485
+ root = ensureAbsolute((_b2 = options.root) != null ? _b2 : "", config.root);
370
486
  tsConfigPath = ensureAbsolute(tsConfigFilePath, root);
371
487
  outputDir = options.outputDir ? ensureAbsolute(options.outputDir, root) : ensureAbsolute(config.build.outDir, root);
372
488
  if (!outputDir) {
@@ -390,10 +506,10 @@ ${import_chalk.default.cyan("[vite:dts]")} Can not resolve declaration directory
390
506
  tsConfigFilePath: tsConfigPath,
391
507
  skipAddingFilesFromTsConfig: true
392
508
  });
393
- allowJs = (_b = project.getCompilerOptions().allowJs) != null ? _b : false;
509
+ allowJs = (_c = project.getCompilerOptions().allowJs) != null ? _c : false;
394
510
  },
395
511
  buildStart(inputOptions) {
396
- if (insertTypesEntry) {
512
+ if (!isBundle && (insertTypesEntry || rollupTypes)) {
397
513
  entries = Array.isArray(inputOptions.input) ? inputOptions.input : Object.values(inputOptions.input);
398
514
  }
399
515
  },
@@ -423,17 +539,17 @@ ${import_chalk.default.cyan("[vite:dts]")} Can not resolve declaration directory
423
539
  }
424
540
  },
425
541
  async closeBundle() {
426
- var _a2, _b, _c, _d, _e, _f;
542
+ var _a2, _b2, _c, _d, _e, _f;
427
543
  if (!outputDir || !project || isBundle)
428
544
  return;
429
545
  logger.info(import_chalk.default.green(`
430
- ${import_chalk.default.cyan("[vite:dts]")} Start generate declaration files...`));
546
+ ${logPrefix} Start generate declaration files...`));
431
547
  bundleDebug("start");
432
548
  isBundle = true;
433
549
  sourceDtsFiles.clear();
434
550
  const startTime = Date.now();
435
551
  const tsConfig = (_a2 = (0, import_typescript.readConfigFile)(tsConfigPath, project.getFileSystem().readFileSync).config) != null ? _a2 : {};
436
- const include = (_c = (_b = options.include) != null ? _b : tsConfig.include) != null ? _c : "**/*";
552
+ const include = (_c = (_b2 = options.include) != null ? _b2 : tsConfig.include) != null ? _c : "**/*";
437
553
  const exclude = (_d = options.exclude) != null ? _d : tsConfig.exclude;
438
554
  bundleDebug("read config");
439
555
  const includedFileSet = /* @__PURE__ */ new Set();
@@ -444,7 +560,7 @@ ${import_chalk.default.cyan("[vite:dts]")} Start generate declaration files...`)
444
560
  ignore: ensureArray(exclude != null ? exclude : ["node_modules/**"]).map(normalizeGlob)
445
561
  });
446
562
  files.forEach((file) => {
447
- if (dtsRE.test(file)) {
563
+ if (dtsRE2.test(file)) {
448
564
  if (!copyDtsFiles) {
449
565
  return;
450
566
  }
@@ -475,21 +591,23 @@ ${import_chalk.default.cyan("[vite:dts]")} Start generate declaration files...`)
475
591
  }
476
592
  bundleDebug("diagnostics");
477
593
  }
594
+ const dtsOutputFiles = Array.from(sourceDtsFiles).map((sourceFile) => ({
595
+ path: sourceFile.getFilePath(),
596
+ content: sourceFile.getFullText()
597
+ }));
478
598
  const service = project.getLanguageService();
479
599
  const outputFiles = project.getSourceFiles().map((sourceFile) => service.getEmitOutput(sourceFile, true).getOutputFiles().map((outputFile) => ({
480
600
  path: outputFile.getFilePath(),
481
601
  content: outputFile.getText()
482
- }))).flat().concat(Array.from(sourceDtsFiles).map((sourceFile) => ({
483
- path: sourceFile.getFilePath(),
484
- content: sourceFile.getFullText()
485
- })));
602
+ }))).flat().concat(dtsOutputFiles);
603
+ bundleDebug("emit");
486
604
  if (!entryRoot) {
487
605
  entryRoot = queryPublicPath(outputFiles.map((file) => file.path));
488
606
  }
489
607
  entryRoot = ensureAbsolute(entryRoot, root);
490
- bundleDebug("emit");
608
+ const wroteFiles = /* @__PURE__ */ new Set();
491
609
  await runParallel(import_os.default.cpus().length, outputFiles, async (outputFile) => {
492
- var _a3, _b2;
610
+ var _a3, _b3;
493
611
  let filePath = outputFile.path;
494
612
  let content = outputFile.content;
495
613
  const isMapFile = filePath.endsWith(".map");
@@ -499,31 +617,34 @@ ${import_chalk.default.cyan("[vite:dts]")} Start generate declaration files...`)
499
617
  if (!isMapFile && content && content !== noneExport) {
500
618
  content = clearPureImport ? removePureImport(content) : content;
501
619
  content = transformAliasImport(filePath, content, aliases);
502
- content = staticImport ? transformDynamicImport(content) : content;
620
+ content = staticImport || rollupTypes ? transformDynamicImport(content) : content;
503
621
  }
504
- filePath = (0, import_path3.resolve)(outputDir, (0, import_path3.relative)(entryRoot, cleanVueFileName ? filePath.replace(".vue.d.ts", ".d.ts") : filePath));
622
+ filePath = (0, import_path4.resolve)(outputDir, (0, import_path4.relative)(entryRoot, cleanVueFileName ? filePath.replace(".vue.d.ts", ".d.ts") : filePath));
505
623
  if (typeof beforeWriteFile === "function") {
506
624
  const result = beforeWriteFile(filePath, content);
507
625
  if (result && isNativeObj(result)) {
508
626
  filePath = (_a3 = result.filePath) != null ? _a3 : filePath;
509
- content = (_b2 = result.content) != null ? _b2 : content;
627
+ content = (_b3 = result.content) != null ? _b3 : content;
510
628
  }
511
629
  }
512
- await import_fs_extra.default.mkdir((0, import_path3.dirname)(filePath), { recursive: true });
630
+ await import_fs_extra.default.mkdir((0, import_path4.dirname)(filePath), { recursive: true });
513
631
  await import_fs_extra.default.writeFile(filePath, cleanVueFileName ? content.replace(/['"](.+)\.vue['"]/g, '"$1"') : content, "utf8");
632
+ wroteFiles.add((0, import_vite2.normalizePath)(filePath));
514
633
  });
515
634
  bundleDebug("output");
516
- if (insertTypesEntry) {
517
- const pkgPath = (0, import_path3.resolve)(root, "package.json");
635
+ if (insertTypesEntry || rollupTypes) {
636
+ const pkgPath = (0, import_path4.resolve)(root, "package.json");
518
637
  const pkg = import_fs_extra.default.existsSync(pkgPath) ? JSON.parse(await import_fs_extra.default.readFile(pkgPath, "utf-8")) : {};
519
- let typesPath = pkg.types ? (0, import_path3.resolve)(root, pkg.types) : (0, import_path3.resolve)(outputDir, "index.d.ts");
638
+ let typesPath = pkg.types ? (0, import_path4.resolve)(root, pkg.types) : (0, import_path4.resolve)(outputDir, indexName);
520
639
  if (!import_fs_extra.default.existsSync(typesPath)) {
521
- let content = entries.map((entry) => {
522
- let filePath = (0, import_vite2.normalizePath)((0, import_path3.relative)((0, import_path3.dirname)(typesPath), (0, import_path3.resolve)(outputDir, (0, import_path3.relative)(entryRoot, entry))));
523
- filePath = filePath.replace(tsRE, "");
524
- filePath = /^\.\.?\//.test(filePath) ? filePath : `./${filePath}`;
525
- return `export * from '${filePath}'`;
526
- }).join("\n") + "\n";
640
+ const entry = entries[0];
641
+ let filePath = (0, import_vite2.normalizePath)((0, import_path4.relative)((0, import_path4.dirname)(typesPath), (0, import_path4.resolve)(outputDir, (0, import_path4.relative)(entryRoot, entry))));
642
+ filePath = filePath.replace(tsRE, "");
643
+ filePath = fullRelativeRE.test(filePath) ? filePath : `./${filePath}`;
644
+ let content = `import ${libName} from '${filePath}'
645
+ export default ${libName}
646
+ export * from '${filePath}'
647
+ `;
527
648
  if (typeof beforeWriteFile === "function") {
528
649
  const result = beforeWriteFile(typesPath, content);
529
650
  if (result && isNativeObj(result)) {
@@ -534,13 +655,32 @@ ${import_chalk.default.cyan("[vite:dts]")} Start generate declaration files...`)
534
655
  await import_fs_extra.default.writeFile(typesPath, content, "utf-8");
535
656
  }
536
657
  bundleDebug("insert index");
658
+ if (rollupTypes) {
659
+ logger.info(import_chalk.default.green(`${logPrefix} Start rollup declaration files...`));
660
+ rollupDeclarationFiles({
661
+ root,
662
+ tsConfigPath,
663
+ outputDir,
664
+ entryPath: typesPath,
665
+ fileName: (0, import_path4.basename)(typesPath)
666
+ });
667
+ wroteFiles.delete((0, import_vite2.normalizePath)(typesPath));
668
+ await runParallel(import_os.default.cpus().length, Array.from(wroteFiles), (f) => import_fs_extra.default.unlink(f));
669
+ removeDirIfEmpty(outputDir);
670
+ if (copyDtsFiles) {
671
+ await runParallel(import_os.default.cpus().length, dtsOutputFiles, async ({ path, content }) => {
672
+ await import_fs_extra.default.writeFile((0, import_path4.resolve)(outputDir, (0, import_path4.basename)(path)), content, "utf8");
673
+ });
674
+ }
675
+ bundleDebug("rollup");
676
+ }
537
677
  }
538
678
  if (typeof afterBuild === "function") {
539
679
  const result = afterBuild();
540
680
  isPromise(result) && await result;
541
681
  }
542
682
  bundleDebug("finish");
543
- logger.info(import_chalk.default.green(`${import_chalk.default.cyan("[vite:dts]")} Declaration files built in ${Date.now() - startTime}ms.
683
+ logger.info(import_chalk.default.green(`${logPrefix} Declaration files built in ${Date.now() - startTime}ms.
544
684
  `));
545
685
  }
546
686
  };