@voidzero-dev/vite-plus-core 0.3.0 → 0.3.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.
Files changed (62) hide show
  1. package/dist/rolldown/cli.mjs +6 -6
  2. package/dist/rolldown/config.d.mts +1 -1
  3. package/dist/rolldown/config.mjs +2 -2
  4. package/dist/rolldown/experimental-index.d.mts +33 -4
  5. package/dist/rolldown/experimental-index.mjs +33 -8
  6. package/dist/rolldown/experimental-runtime-types.d.ts +2 -2
  7. package/dist/rolldown/experimental-runtime.d.ts +2 -2
  8. package/dist/rolldown/experimental-runtime.mjs +2 -2
  9. package/dist/rolldown/filter-index.d.mts +1 -1
  10. package/dist/rolldown/filter-index.mjs +1 -3
  11. package/dist/rolldown/index.d.mts +3 -3
  12. package/dist/rolldown/index.mjs +4 -4
  13. package/dist/rolldown/parallel-plugin-worker.mjs +2 -2
  14. package/dist/rolldown/parallel-plugin.d.mts +1 -1
  15. package/dist/rolldown/parse-ast-index.d.mts +1 -1
  16. package/dist/rolldown/parse-ast-index.mjs +1 -1
  17. package/dist/rolldown/plugins-index.d.mts +3 -3
  18. package/dist/rolldown/plugins-index.mjs +2 -2
  19. package/dist/rolldown/shared/{binding-Bvw14S3g.d.mts → binding-DZuNHVw4.d.mts} +19 -5
  20. package/dist/rolldown/shared/{binding-C__LJDBG.mjs → binding-DmImI4pj.mjs} +27 -27
  21. package/dist/rolldown/shared/{bindingify-input-options-V9YvAjrr.mjs → bindingify-input-options-BYClWKnj.mjs} +11 -9
  22. package/dist/rolldown/shared/{constructors-CRumnw21.d.mts → constructors-BM20b11r.d.mts} +2 -2
  23. package/dist/rolldown/shared/{constructors-DklcHr18.mjs → constructors-mRbcbLyX.mjs} +1 -1
  24. package/dist/rolldown/shared/{create-bundler-option-DbV2ud0B.mjs → create-bundler-option-CHTBktos.mjs} +47 -5
  25. package/dist/rolldown/shared/{define-config-DwTNhgWB.d.mts → define-config-DNX0WekP.d.mts} +36 -3
  26. package/dist/rolldown/shared/{error-NcRuXAVN.mjs → error-BP8lJHle.mjs} +1 -1
  27. package/dist/rolldown/shared/{load-config-Dd7jKGUy.mjs → load-config-Cx5fx_8Q.mjs} +1 -1
  28. package/dist/rolldown/shared/{normalize-string-or-regex-CFtim40S.mjs → normalize-string-or-regex-Dm69lpQ-.mjs} +1 -1
  29. package/dist/rolldown/shared/{parse-rvxTD36n.mjs → parse-8sr82jSR.mjs} +2 -2
  30. package/dist/rolldown/shared/{resolve-tsconfig-D2vSIIkR.mjs → resolve-tsconfig-BlNGaH3Y.mjs} +10 -6
  31. package/dist/rolldown/shared/{rolldown-Bblizyw1.mjs → rolldown-CaX_Wmqc.mjs} +5 -4
  32. package/dist/rolldown/shared/{transform--WSMLt1x.d.mts → transform-CVse9_mH.d.mts} +8 -4
  33. package/dist/rolldown/shared/{watch-DPvOlccK.mjs → watch-YKfJgIxz.mjs} +4 -4
  34. package/dist/rolldown/utils-index.d.mts +3 -3
  35. package/dist/rolldown/utils-index.mjs +5 -5
  36. package/dist/tsdown/{build-D_enfyvD-tOzhITac.js → build-JVmLFaZt-kqQJ2U7s.js} +1101 -687
  37. package/dist/tsdown/debug-CpC4hV25-tvH_Dsg5.js +247 -0
  38. package/dist/tsdown/{detect-DGhJGEqb-LL52mV6u.js → detect-Bg-d8iUV-KfbO7neP.js} +10 -12
  39. package/dist/tsdown/{dist-BsS7BOcb.js → dist-Cuw3Ngo4.js} +1226 -893
  40. package/dist/tsdown/index-types.d.ts +277 -355
  41. package/dist/tsdown/index.js +4 -4
  42. package/dist/tsdown/internal-D-JfB5uT.js +29 -0
  43. package/dist/tsdown/internal-lhH-5yya.js +62 -0
  44. package/dist/tsdown/{main-Bcv7jU2b.js → main-CyNcZUzu.js} +8 -214
  45. package/dist/tsdown/{resolver-cwLsPb2o-Bb9SDBm6.js → resolver-DE0_sy8o-ZQqHQjRu.js} +4 -4
  46. package/dist/tsdown/rolldown-runtime-B4iAMlE-.js +35 -0
  47. package/dist/tsdown/run.js +44 -8
  48. package/dist/tsdown/{src-JVSpR8xt.js → src-BWidcM5N.js} +1 -1
  49. package/dist/tsdown/{tsc-B8FD48Oc.js → tsc-ChjRhsoQ.js} +26 -20
  50. package/dist/tsdown/tsdown-css.js +17 -11
  51. package/dist/tsdown/tsdown-exe.js +16 -5
  52. package/dist/tsdown/version-CQ98ZBpL-Obdnv4J7.js +141 -0
  53. package/dist/vite/client/bundledDevClient.mjs +6 -6
  54. package/dist/vite/client/client.mjs +4 -4
  55. package/dist/vite/node/chunks/build.js +2 -2
  56. package/dist/vite/node/chunks/lib.js +2 -2
  57. package/dist/vite/node/chunks/node.js +42 -31
  58. package/dist/vite/node/module-runner.js +3 -3
  59. package/package.json +25 -25
  60. package/dist/tsdown/debug-CKcBYQLP-By_AQqN8.js +0 -157
  61. package/dist/tsdown/internal-DSmmwu4u.js +0 -3
  62. package/dist/tsdown/target-Bab3CUeB-8PBzMh3p.js +0 -582
@@ -1,6 +1,6 @@
1
- import { r as createDebug } from "./main-Bcv7jU2b.js";
2
- import { C as filename_to_dts, S as filename_js_to_dts, T as resolveTemplateFn, _ as RE_JSON, b as RE_TS, g as RE_JS, h as RE_DTS_MAP, m as RE_DTS, p as RE_CSS, v as RE_NODE_MODULES, w as replaceTemplateName, x as filename_dts_to, y as RE_ROLLDOWN_RUNTIME } from "./target-Bab3CUeB-8PBzMh3p.js";
3
- import { o as at, s as ee } from "./build-D_enfyvD-tOzhITac.js";
1
+ import { r as createDebug } from "./main-CyNcZUzu.js";
2
+ import { o as mt, s as te } from "./build-JVmLFaZt-kqQJ2U7s.js";
3
+ import { a as RE_JSON, c as RE_TS, d as filename_to_dts, f as replaceTemplateName, i as RE_JS, l as filename_dts_to, n as RE_DTS, o as RE_NODE_MODULES, p as resolveTemplateFn, r as RE_DTS_MAP, s as RE_ROLLDOWN_RUNTIME, t as RE_CSS, u as filename_js_to_dts } from "./internal-D-JfB5uT.js";
4
4
  import { createRequire } from "node:module";
5
5
  import process from "node:process";
6
6
  import { styleText } from "node:util";
@@ -11,10 +11,11 @@ import { access, mkdtemp, readFile, rm } from "node:fs/promises";
11
11
  import { importerId, include } from "@voidzero-dev/vite-plus-core/rolldown/filter";
12
12
  import { tmpdir } from "node:os";
13
13
  import { ResolverFactory, isolatedDeclarationSync } from "@voidzero-dev/vite-plus-core/rolldown/experimental";
14
- import { print } from "yuku-codegen";
14
+ import { generate } from "yuku-codegen";
15
15
  import { parse as parse$1 } from "yuku-parser";
16
- //#region ../../node_modules/.pnpm/rolldown-plugin-dts@0.27.13_@typescript+native-preview@7.0.0-dev.20260605.1_oxc-resolve_19173df252fb1b72b750fe1e656588b8/node_modules/rolldown-plugin-dts/dist/tsc-context.mjs
16
+ //#region ../../node_modules/.pnpm/rolldown-plugin-dts@0.28.5_@typescript+native-preview@7.0.0-dev.20260605.1_oxc-resolver_395c84c3f0e463da1bb9023138bdcb2e/node_modules/rolldown-plugin-dts/dist/tsc-context.mjs
17
17
  const debug$7 = createDebug("rolldown-plugin-dts:tsc-context");
18
+ /** Creates an empty, isolated TypeScript compiler context. */
18
19
  function createContext() {
19
20
  return {
20
21
  programs: [],
@@ -22,33 +23,106 @@ function createContext() {
22
23
  projects: /* @__PURE__ */ new Map()
23
24
  };
24
25
  }
26
+ /**
27
+ * Removes a file and any dependent compiler state from a context.
28
+ *
29
+ * @param context - Context to invalidate.
30
+ * @param file - File path to remove. Relative paths resolve from the process
31
+ * working directory.
32
+ */
25
33
  function invalidateContextFile(context, file) {
26
34
  file = path.resolve(file).replaceAll("\\", "/");
27
35
  debug$7(`invalidating context file: ${file}`);
28
36
  context.files.delete(file);
29
37
  context.programs = context.programs.filter((program) => {
30
- return !program.getSourceFiles().some((sourceFile) => sourceFile.fileName === file);
38
+ return program.getSourceFiles().every((sourceFile) => sourceFile.fileName !== file);
31
39
  });
32
40
  context.projects.clear();
33
41
  }
42
+ /** Shared compiler context used when no explicit context is provided. */
34
43
  const globalContext = createContext();
35
44
  //#endregion
36
- //#region ../../node_modules/.pnpm/rolldown-plugin-dts@0.27.13_@typescript+native-preview@7.0.0-dev.20260605.1_oxc-resolve_19173df252fb1b72b750fe1e656588b8/node_modules/rolldown-plugin-dts/dist/load-tsc-BKULZsrs.mjs
37
- const require$2 = createRequire(import.meta.url);
38
- const debug$6 = createDebug("rolldown-plugin-dts:load-tsc");
45
+ //#region ../../node_modules/.pnpm/rolldown-plugin-dts@0.28.5_@typescript+native-preview@7.0.0-dev.20260605.1_oxc-resolver_395c84c3f0e463da1bb9023138bdcb2e/node_modules/rolldown-plugin-dts/dist/require-BbBF8Ii0.mjs
46
+ const require = createRequire(import.meta.url);
47
+ const debug$6 = createDebug("rolldown-plugin-dts:utils");
48
+ function tryRequire(moduleName) {
49
+ try {
50
+ return require(moduleName);
51
+ } catch {}
52
+ }
53
+ function tryResolve(id) {
54
+ try {
55
+ return require.resolve(id);
56
+ } catch {}
57
+ }
39
58
  let _ts;
40
- function requireTS(message = "") {
59
+ function isTS70Installed() {
60
+ return tryRequire("typescript/package.json")?.version.slice(0, 3) === "7.0";
61
+ }
62
+ function requireTSApi(mode = "tsc", message = ".") {
41
63
  if (_ts) return _ts;
64
+ if (isTS70Installed()) throw new Error(`TypeScript 7.0 is not supported when using ${mode}. Please use TypeScript 6.0 or below${message}`);
65
+ let ts;
42
66
  try {
43
- _ts = require$2("typescript");
44
- if (debug$6.enabled) debug$6(`loaded TypeScript version ${_ts.version} from ${require$2.resolve("typescript")}`);
45
- return _ts;
67
+ ts = require("typescript");
46
68
  } catch (cause) {
47
- throw new Error(`TypeScript is not installed. You should install \`typescript\` package. ${message}`, { cause });
69
+ throw new Error(`TypeScript is not installed. Please install the \`typescript\` package (v7.0 is not yet supported)${message}`, { cause });
48
70
  }
71
+ if (debug$6.enabled) debug$6(`Loaded TypeScript version ${ts.version} from ${require.resolve("typescript")}`);
72
+ return _ts = ts;
49
73
  }
50
74
  //#endregion
51
- //#region ../../node_modules/.pnpm/yuku-ast@0.7.0/node_modules/yuku-ast/dist/index.js
75
+ //#region ../../node_modules/.pnpm/rolldown-plugin-dts@0.28.5_@typescript+native-preview@7.0.0-dev.20260605.1_oxc-resolver_395c84c3f0e463da1bb9023138bdcb2e/node_modules/rolldown-plugin-dts/dist/custom-language-BR14iqr3.mjs
76
+ var LanguageContext = class {
77
+ languages;
78
+ patterns;
79
+ constructor(languages) {
80
+ this.languages = languages;
81
+ this.patterns = languages.flatMap((language) => language.extensionPatterns);
82
+ }
83
+ isCustomLanguageFile(id) {
84
+ return this.patterns.some((pattern) => pattern.test(id));
85
+ }
86
+ isUsingVolar() {
87
+ return this.languages.some((language) => language.volarTypeScript || language.createVolarPlugins);
88
+ }
89
+ getExtraFileExtensions() {
90
+ if (!this.languages.length) return;
91
+ return this.languages.flatMap((language) => language.tsFileExtensionInfos || []);
92
+ }
93
+ /** @internal */
94
+ getCreateProgram(ts) {
95
+ if (!this.languages.length) return ts.createProgram;
96
+ const volarTypeScript = this.languages.find((language) => language.volarTypeScript)?.volarTypeScript;
97
+ if (!volarTypeScript) return ts.createProgram;
98
+ const { proxyCreateProgram } = volarTypeScript;
99
+ return proxyCreateProgram(ts, ts.createProgram, (ts, options) => {
100
+ const setups = [];
101
+ const plugins = [];
102
+ for (const language of this.languages) {
103
+ if (!language.createVolarPlugins) continue;
104
+ const result = language.createVolarPlugins(ts, options);
105
+ if (Array.isArray(result)) plugins.push(...result);
106
+ else {
107
+ if (result.setup) setups.push(result.setup);
108
+ plugins.push(...result.languagePlugins);
109
+ }
110
+ }
111
+ return {
112
+ setup: setups.length ? (language) => {
113
+ for (const setup of setups) setup(language);
114
+ } : void 0,
115
+ languagePlugins: plugins
116
+ };
117
+ });
118
+ }
119
+ toTsFilename(id) {
120
+ for (const language of this.languages) if (language.toTsFilename && language.extensionPatterns.some((pattern) => pattern.test(id))) return language.toTsFilename(id);
121
+ return id;
122
+ }
123
+ };
124
+ //#endregion
125
+ //#region ../../node_modules/.pnpm/yuku-ast@0.9.3/node_modules/yuku-ast/dist/aliases.js
52
126
  const ALIAS_GROUPS = {
53
127
  Expression: [
54
128
  "Identifier",
@@ -214,6 +288,8 @@ const ALIAS_GROUPS = {
214
288
  ]
215
289
  };
216
290
  Object.keys(ALIAS_GROUPS);
291
+ //#endregion
292
+ //#region ../../node_modules/.pnpm/yuku-ast@0.9.3/node_modules/yuku-ast/dist/generated.js
217
293
  const KEYS = Object.create(null);
218
294
  function ck(type, keys) {
219
295
  const prev = KEYS[type];
@@ -780,6 +856,8 @@ const NODE_TYPES = [.../* @__PURE__ */ new Set([
780
856
  "JSXSpreadChild",
781
857
  "Hashbang"
782
858
  ])];
859
+ //#endregion
860
+ //#region ../../node_modules/.pnpm/yuku-ast@0.9.3/node_modules/yuku-ast/dist/builders.js
783
861
  /**
784
862
  * One constructor per node type, its fields derived from the node type
785
863
  * itself. `start` and `end` default to 0, which `ctx.replace` treats
@@ -795,6 +873,8 @@ const b = Object.fromEntries(NODE_TYPES.map((type) => [type, (fields) => ({
795
873
  end: 0,
796
874
  ...fields
797
875
  })]));
876
+ //#endregion
877
+ //#region ../../node_modules/.pnpm/yuku-ast@0.9.3/node_modules/yuku-ast/dist/context.js
798
878
  /**
799
879
  * The walk context: one reused object exposing the current position and
800
880
  * the tree mutation operations. Valid only during the visit that
@@ -879,6 +959,8 @@ var WalkContext = class {
879
959
  this._list.splice(this._frame.i + offset, 0, node);
880
960
  }
881
961
  };
962
+ //#endregion
963
+ //#region ../../node_modules/.pnpm/yuku-ast@0.9.3/node_modules/yuku-ast/dist/identifier.js
882
964
  const IDENTIFIER_NAME = /^[$_\p{ID_Start}][$\u200C\u200D\p{ID_Continue}]*$/u;
883
965
  /**
884
966
  * True if `name` is a valid ECMAScript `IdentifierName`, the grammar an
@@ -889,6 +971,8 @@ const IDENTIFIER_NAME = /^[$_\p{ID_Start}][$\u200C\u200D\p{ID_Continue}]*$/u;
889
971
  function isIdentifierName(name) {
890
972
  return IDENTIFIER_NAME.test(name);
891
973
  }
974
+ //#endregion
975
+ //#region ../../node_modules/.pnpm/yuku-ast@0.9.3/node_modules/yuku-ast/dist/is.js
892
976
  function aliasGuard(name) {
893
977
  const set = new Set(ALIAS_GROUPS[name]);
894
978
  return (node) => node != null && set.has(node.type);
@@ -905,7 +989,9 @@ function aliasGuard(name) {
905
989
  */
906
990
  const is = {
907
991
  ...Object.fromEntries(NODE_TYPES.map((type) => [type, (node) => node != null && node.type === type])),
992
+ /** True when `node.type` is one of `types`, narrowing to that union. */
908
993
  oneOf: (node, types) => node != null && types.some((type) => type === node.type),
994
+ /** An `Identifier`, optionally with the exact `name`. */
909
995
  Identifier: (node, name) => node?.type === "Identifier" && (name === void 0 || node.name === name),
910
996
  Expression: aliasGuard("Expression"),
911
997
  Statement: aliasGuard("Statement"),
@@ -929,19 +1015,21 @@ const is = {
929
1015
  PrivateFieldExpression: (node) => node?.type === "MemberExpression" && node.property.type === "PrivateIdentifier",
930
1016
  Directive: (node) => node?.type === "ExpressionStatement" && node.directive != null
931
1017
  };
1018
+ //#endregion
1019
+ //#region ../../node_modules/.pnpm/yuku-ast@0.9.3/node_modules/yuku-ast/dist/walk.js
932
1020
  function createDispatch(visitors) {
933
1021
  let enter = null;
934
1022
  let leave = null;
935
- const concrete$1 = /* @__PURE__ */ new Map();
1023
+ const concrete = /* @__PURE__ */ new Map();
936
1024
  const add = (type, handler) => {
937
1025
  const hooks = typeof handler === "function" ? { enter: handler } : handler;
938
- let entry = concrete$1.get(type);
1026
+ let entry = concrete.get(type);
939
1027
  if (entry === void 0) {
940
1028
  entry = {
941
1029
  enter: [],
942
1030
  leave: []
943
1031
  };
944
- concrete$1.set(type, entry);
1032
+ concrete.set(type, entry);
945
1033
  }
946
1034
  if (hooks.enter) entry.enter.push(hooks.enter);
947
1035
  if (hooks.leave) entry.leave.unshift(hooks.leave);
@@ -959,7 +1047,7 @@ function createDispatch(visitors) {
959
1047
  return {
960
1048
  enter,
961
1049
  leave,
962
- typed: (type) => concrete$1.get(type)
1050
+ typed: (type) => concrete.get(type)
963
1051
  };
964
1052
  }
965
1053
  /**
@@ -1118,6 +1206,8 @@ async function _walkAsync(root, visitors, state, ctx) {
1118
1206
  return true;
1119
1207
  })(root, null, null, null);
1120
1208
  }
1209
+ //#endregion
1210
+ //#region ../../node_modules/.pnpm/yuku-ast@0.9.3/node_modules/yuku-ast/dist/utils.js
1121
1211
  function nameOf(node) {
1122
1212
  if (node == null) return null;
1123
1213
  if (node.type === "Identifier") return node.name;
@@ -1237,7 +1327,7 @@ function ensureValue(value) {
1237
1327
  return value && ALLOW_EXTENSIONS.has(extname(value)) ? value.replaceAll("\\", "/") : null;
1238
1328
  }
1239
1329
  //#endregion
1240
- //#region ../../node_modules/.pnpm/rolldown-plugin-dts@0.27.13_@typescript+native-preview@7.0.0-dev.20260605.1_oxc-resolve_19173df252fb1b72b750fe1e656588b8/node_modules/rolldown-plugin-dts/dist/index.mjs
1330
+ //#region ../../node_modules/.pnpm/rolldown-plugin-dts@0.28.5_@typescript+native-preview@7.0.0-dev.20260605.1_oxc-resolver_395c84c3f0e463da1bb9023138bdcb2e/node_modules/rolldown-plugin-dts/dist/index.mjs
1241
1331
  function createDtsInputPlugin({ sideEffects }) {
1242
1332
  return {
1243
1333
  name: "rolldown-plugin-dts:dts-input",
@@ -1270,40 +1360,234 @@ function createDtsInputPlugin({ sideEffects }) {
1270
1360
  }
1271
1361
  };
1272
1362
  }
1273
- const require$1 = createRequire(import.meta.url);
1274
- const debug$5 = createDebug("rolldown-plugin-dts:tsgo");
1275
- function isTS70Installed() {
1276
- try {
1277
- const { versionMajorMinor } = require$1("typescript");
1278
- return versionMajorMinor === "7.0";
1279
- } catch {}
1280
- return false;
1363
+ var OxcGenerator = class {
1364
+ options;
1365
+ languageContext;
1366
+ constructor(options, languageContext) {
1367
+ this.options = options;
1368
+ this.languageContext = languageContext;
1369
+ }
1370
+ emit(code, fileName) {
1371
+ const result = isolatedDeclarationSync(this.languageContext.toTsFilename(fileName), code, this.options);
1372
+ if (result.errors.length) {
1373
+ const [error] = result.errors;
1374
+ return { error: {
1375
+ message: error.message,
1376
+ frame: error.codeframe || void 0
1377
+ } };
1378
+ }
1379
+ let map;
1380
+ if (result.map) {
1381
+ map = result.map;
1382
+ map.sources = [fileName];
1383
+ map.sourcesContent = void 0;
1384
+ }
1385
+ return {
1386
+ code: result.code,
1387
+ map
1388
+ };
1389
+ }
1390
+ };
1391
+ const WORKER_URL = "./tsc-worker.mjs";
1392
+ var TscGenerator = class {
1393
+ options;
1394
+ parallel;
1395
+ newContext;
1396
+ getEntries;
1397
+ worker;
1398
+ tscModule;
1399
+ context;
1400
+ constructor({ parallel, newContext, getEntries, ...options }) {
1401
+ this.options = options;
1402
+ this.parallel = parallel;
1403
+ this.newContext = newContext;
1404
+ this.getEntries = getEntries;
1405
+ }
1406
+ async init() {
1407
+ if (this.parallel) {
1408
+ this.worker = createTscWorker();
1409
+ return;
1410
+ }
1411
+ this.tscModule = await import("./tsc-ChjRhsoQ.js");
1412
+ if (this.newContext) this.context = createContext();
1413
+ }
1414
+ async emit(_code, fileName) {
1415
+ const options = {
1416
+ ...this.options,
1417
+ entries: this.getEntries(),
1418
+ id: fileName,
1419
+ context: this.context
1420
+ };
1421
+ let result;
1422
+ if (this.parallel) {
1423
+ if (!this.worker) throw new Error("TscGenerator has not been initialized.");
1424
+ result = await this.worker.emit(options);
1425
+ } else {
1426
+ if (!this.tscModule) throw new Error("TscGenerator has not been initialized.");
1427
+ result = this.tscModule.tscEmit(options);
1428
+ }
1429
+ if (result.code && RE_JSON.test(fileName)) result.code = patchJsonDts(result.code);
1430
+ return result;
1431
+ }
1432
+ dispose() {
1433
+ this.worker?.kill();
1434
+ this.worker = void 0;
1435
+ this.tscModule = void 0;
1436
+ if (this.newContext) this.context = void 0;
1437
+ }
1438
+ invalidate(fileName) {
1439
+ if (this.parallel) return;
1440
+ if (this.newContext) {
1441
+ if (this.context) invalidateContextFile(this.context, fileName);
1442
+ } else invalidateContextFile(globalContext, fileName);
1443
+ }
1444
+ };
1445
+ function createTscWorker() {
1446
+ const childProcess = fork(new URL(WORKER_URL, import.meta.url), {
1447
+ stdio: "inherit",
1448
+ serialization: "advanced"
1449
+ });
1450
+ const pending = /* @__PURE__ */ new Map();
1451
+ let nextId = 0;
1452
+ childProcess.on("message", (response) => {
1453
+ const handler = pending.get(response.id);
1454
+ if (!handler) return;
1455
+ pending.delete(response.id);
1456
+ if (response.error) handler.reject(response.error);
1457
+ else handler.resolve(response.result);
1458
+ });
1459
+ childProcess.on("exit", (code) => {
1460
+ for (const handler of pending.values()) handler.reject(/* @__PURE__ */ new Error(`tsc worker exited with code ${code}`));
1461
+ pending.clear();
1462
+ });
1463
+ return {
1464
+ emit: (options) => new Promise((resolve, reject) => {
1465
+ const id = nextId++;
1466
+ pending.set(id, {
1467
+ resolve,
1468
+ reject
1469
+ });
1470
+ childProcess.send({
1471
+ id,
1472
+ options
1473
+ });
1474
+ }),
1475
+ kill: () => childProcess.kill()
1476
+ };
1477
+ }
1478
+ function patchJsonDts(code) {
1479
+ if (code.includes("declare const _exports")) {
1480
+ if (code.includes("declare const _exports: {") && !code.includes("\n}[];")) {
1481
+ const exports = collectJsonExports(code);
1482
+ let index = 0;
1483
+ code += exports.map((exported) => {
1484
+ const valid = `_${exported.replaceAll(/[^\w$]/g, "_")}${index++}`;
1485
+ const jsonKey = JSON.stringify(exported);
1486
+ return `declare let ${valid}: typeof _exports[${jsonKey}]\nexport { ${valid} as ${jsonKey} }`;
1487
+ }).join("\n");
1488
+ }
1489
+ return code;
1490
+ }
1491
+ const exportMap = collectJsonExportMap(code);
1492
+ code += `
1493
+ declare namespace __json_default_export {
1494
+ export { ${Array.from(exportMap.entries(), ([exported, local]) => exported === local ? exported : `${local} as ${exported}`).join(", ")} }
1495
+ }
1496
+ export { __json_default_export as default }`;
1497
+ return code;
1498
+ }
1499
+ function collectJsonExportMap(code) {
1500
+ const exportMap = /* @__PURE__ */ new Map();
1501
+ const { program } = parse$1(code, {
1502
+ sourceType: "module",
1503
+ lang: "dts"
1504
+ });
1505
+ for (const decl of program.body) if (decl.type === "ExportNamedDeclaration") {
1506
+ if (decl.declaration) {
1507
+ if (decl.declaration.type === "VariableDeclaration") {
1508
+ for (const vdecl of decl.declaration.declarations) if (vdecl.id.type === "Identifier") exportMap.set(vdecl.id.name, vdecl.id.name);
1509
+ } else if (decl.declaration.type === "TSModuleDeclaration" && decl.declaration.id.type === "Identifier") exportMap.set(decl.declaration.id.name, decl.declaration.id.name);
1510
+ } else if (decl.specifiers.length) {
1511
+ for (const spec of decl.specifiers) if (spec.type === "ExportSpecifier" && spec.exported.type === "Identifier") exportMap.set(spec.exported.name, spec.local.type === "Identifier" ? spec.local.name : spec.exported.name);
1512
+ }
1513
+ }
1514
+ return exportMap;
1515
+ }
1516
+ /** `declare const _exports` mode */
1517
+ function collectJsonExports(code) {
1518
+ const exports = [];
1519
+ const { program } = parse$1(code, {
1520
+ sourceType: "module",
1521
+ lang: "dts"
1522
+ });
1523
+ const members = program.body[0].declarations[0].id.typeAnnotation.typeAnnotation.members;
1524
+ for (const member of members) if (member.key.type === "Identifier") exports.push(member.key.name);
1525
+ else if (is.StringLiteral(member.key)) exports.push(member.key.value);
1526
+ return exports;
1281
1527
  }
1528
+ const debug$5 = createDebug("rolldown-plugin-dts:tsgo");
1282
1529
  const spawnAsync = (...args) => new Promise((resolve, reject) => {
1283
1530
  const child = spawn(...args);
1284
- child.on("close", () => resolve());
1531
+ child.on("close", (code, signal) => {
1532
+ if (code === 0) resolve();
1533
+ else if (signal) reject(/* @__PURE__ */ new Error(`tsgo process terminated by signal ${signal}`));
1534
+ else reject(/* @__PURE__ */ new Error(`tsgo process exited with code ${code}`));
1535
+ });
1285
1536
  child.on("error", (error) => reject(error));
1286
1537
  });
1287
1538
  let tsgoPathCache;
1288
- async function getTsgoPathFromNodeModules(logger) {
1539
+ function resolveTsgoPath(logger) {
1289
1540
  if (tsgoPathCache) return tsgoPathCache;
1290
1541
  const pkgName = isTS70Installed() ? "typescript" : "@typescript/native-preview";
1291
- const tsgoPkg = import.meta.resolve(`${pkgName}/package.json`);
1292
- const { default: { version } } = await import(tsgoPkg, { with: { type: "json" } });
1542
+ const pkgJsonPath = tryResolve(`${pkgName}/package.json`);
1543
+ if (!pkgJsonPath) throw new Error("TypeScript Go is not installed. Please install the `typescript@7.0` or `@typescript/native-preview` package to use the `tsgo` generator.");
1544
+ const { version } = require(pkgJsonPath);
1293
1545
  logger.info(`Emit types with ${styleText("underline", `${pkgName}@${version}`)}`);
1294
- const { default: getExePath } = await import(new URL("lib/getExePath.js", tsgoPkg).href);
1295
- return tsgoPathCache = getExePath();
1296
- }
1297
- async function runTsgo(logger, rootDir, tsconfig, sourcemap, tsgoPath) {
1298
- debug$5("[tsgo] rootDir", rootDir);
1299
- let tsgo;
1300
- if (tsgoPath) {
1301
- tsgo = tsgoPath;
1302
- debug$5("[tsgo] using custom path", tsgo);
1303
- } else {
1304
- tsgo = await getTsgoPathFromNodeModules(logger);
1305
- debug$5("[tsgo] using tsgo from node_modules", tsgo);
1546
+ const getExePath = require(path.join(path.dirname(pkgJsonPath), "lib/getExePath.js"));
1547
+ return tsgoPathCache = (typeof getExePath === "function" ? getExePath : getExePath.default)();
1548
+ }
1549
+ var TsgoGenerator = class {
1550
+ options;
1551
+ context;
1552
+ constructor(options) {
1553
+ this.options = options;
1554
+ }
1555
+ async init() {
1556
+ const { tsgoPath, rootDir, tsconfig, sourcemap } = this.options;
1557
+ this.context = await runTsgo(tsgoPath, rootDir, tsconfig, sourcemap);
1558
+ }
1559
+ async emit(_code, fileName) {
1560
+ const { rootDir, languageContext } = this.options;
1561
+ if (languageContext.isCustomLanguageFile(fileName)) return { error: `tsgo does not support ${path.extname(fileName)} files.` };
1562
+ if (!this.context) throw new Error("TsgoGenerator has not been initialized.");
1563
+ const dtsPath = path.resolve(this.context.path, path.relative(path.resolve(rootDir), filename_to_dts(fileName, languageContext)));
1564
+ if (!existsSync(dtsPath)) {
1565
+ debug$5("[tsgo]", dtsPath, "is missing");
1566
+ return { error: `tsgo did not generate dts file for ${fileName}, please check your tsconfig.` };
1567
+ }
1568
+ const code = await readFile(dtsPath, "utf8");
1569
+ let map;
1570
+ const mapPath = `${dtsPath}.map`;
1571
+ if (existsSync(mapPath)) {
1572
+ const mapRaw = await readFile(mapPath, "utf8");
1573
+ map = {
1574
+ ...JSON.parse(mapRaw),
1575
+ sources: [fileName]
1576
+ };
1577
+ }
1578
+ return {
1579
+ code,
1580
+ map
1581
+ };
1582
+ }
1583
+ async dispose() {
1584
+ await this.context?.dispose();
1585
+ this.context = void 0;
1306
1586
  }
1587
+ };
1588
+ async function runTsgo(tsgoPath, rootDir, tsconfig, sourcemap) {
1589
+ debug$5("[tsgo] rootDir", rootDir);
1590
+ debug$5("[tsgo] using tsgo binary", tsgoPath);
1307
1591
  const tsgoDist = await mkdtemp(path.join(tmpdir(), "rolldown-plugin-dts-"));
1308
1592
  debug$5("[tsgo] tsgoDist", tsgoDist);
1309
1593
  const args = [
@@ -1321,7 +1605,7 @@ async function runTsgo(logger, rootDir, tsconfig, sourcemap, tsgoPath) {
1321
1605
  ...sourcemap ? ["--declarationMap"] : []
1322
1606
  ];
1323
1607
  debug$5("[tsgo] args %o", args);
1324
- await spawnAsync(tsgo, args, { stdio: "inherit" });
1608
+ await spawnAsync(tsgoPath, args, { stdio: "inherit" });
1325
1609
  return {
1326
1610
  path: tsgoDist,
1327
1611
  async dispose() {
@@ -1336,13 +1620,35 @@ async function runTsgo(logger, rootDir, tsconfig, sourcemap, tsgoPath) {
1336
1620
  }
1337
1621
  };
1338
1622
  }
1623
+ function createGenerator({ generator, tsconfig, tsconfigRaw, build, incremental, cwd, oxc, languageContext, parallel, tsgo, newContext, sourcemap }, getEntries) {
1624
+ if (generator === "oxc") return new OxcGenerator(oxc, languageContext);
1625
+ if (generator === "tsgo") return new TsgoGenerator({
1626
+ tsgoPath: tsgo.path,
1627
+ rootDir: tsconfig ? path.dirname(tsconfig) : cwd,
1628
+ tsconfig,
1629
+ sourcemap,
1630
+ languageContext
1631
+ });
1632
+ return new TscGenerator({
1633
+ tsconfig,
1634
+ tsconfigRaw,
1635
+ build,
1636
+ incremental,
1637
+ cwd,
1638
+ sourcemap,
1639
+ languageContext,
1640
+ parallel,
1641
+ newContext,
1642
+ getEntries
1643
+ });
1644
+ }
1339
1645
  const debug$4 = createDebug("rolldown-plugin-dts:generate");
1340
- const WORKER_URL = "./tsc-worker.mjs";
1341
1646
  const EMPTY_STUB = `export {}`;
1342
- function createGeneratePlugin({ generator, entry, tsconfig, tsconfigRaw, build, incremental, cwd, oxc, emitDtsOnly, volarContext, parallel, eager, tsgo, newContext, emitJs, sourcemap, logger }) {
1647
+ function createGeneratePlugin(options) {
1648
+ const { entry, cwd, emitDtsOnly, languageContext, eager, emitJs } = options;
1343
1649
  const entryIncludes = entry?.filter((p) => p[0] !== "!");
1344
1650
  const entryIgnores = entry?.filter((p) => p[0] === "!").map((p) => p.slice(1));
1345
- const entryMatcher = entry ? (file) => entryIncludes.some((p) => path.matchesGlob(file, p)) && !entryIgnores.some((p) => path.matchesGlob(file, p)) : void 0;
1651
+ const entryMatcher = entry ? (file) => entryIncludes.some((p) => path.matchesGlob(file, p)) && entryIgnores.every((p) => !path.matchesGlob(file, p)) : void 0;
1346
1652
  const dtsMap = /* @__PURE__ */ new Map();
1347
1653
  /**
1348
1654
  * A map of input id to output file name
@@ -1354,20 +1660,11 @@ function createGeneratePlugin({ generator, entry, tsconfig, tsconfigRaw, build,
1354
1660
  * ])
1355
1661
  */
1356
1662
  const inputAliasMap = /* @__PURE__ */ new Map();
1357
- let tscWorker;
1358
- let tscModule;
1359
- let tscContext;
1360
- let tsgoContext;
1361
- const rootDir = tsconfig ? path.dirname(tsconfig) : cwd;
1663
+ const declarationGenerator = createGenerator(options, () => eager ? void 0 : Array.from(dtsMap.values()).filter((module) => module.isEntry).map((module) => module.id));
1362
1664
  return {
1363
1665
  name: "rolldown-plugin-dts:generate",
1364
1666
  async buildStart(options) {
1365
- if (generator === "tsgo") tsgoContext = await runTsgo(logger, rootDir, tsconfig, sourcemap, tsgo.path);
1366
- else if (generator === "tsc") if (parallel) tscWorker = createTscWorker();
1367
- else {
1368
- tscModule = await import("./tsc-B8FD48Oc.js");
1369
- if (newContext) tscContext = createContext();
1370
- }
1667
+ await declarationGenerator.init?.();
1371
1668
  if (!Array.isArray(options.input)) for (const [name, id] of Object.entries(options.input)) {
1372
1669
  debug$4("resolving input alias %s -> %s", name, id);
1373
1670
  let resolved = await this.resolve(id);
@@ -1392,10 +1689,9 @@ function createGeneratePlugin({ generator, entry, tsconfig, tsconfigRaw, build,
1392
1689
  };
1393
1690
  },
1394
1691
  resolveId(id) {
1395
- if (dtsMap.has(id)) {
1396
- debug$4("resolve dts id %s", id);
1397
- return { id };
1398
- }
1692
+ if (!dtsMap.has(id)) return;
1693
+ debug$4("resolve dts id %s", id);
1694
+ return { id };
1399
1695
  },
1400
1696
  transform: {
1401
1697
  order: "pre",
@@ -1404,7 +1700,7 @@ function createGeneratePlugin({ generator, entry, tsconfig, tsconfigRaw, build,
1404
1700
  RE_JS,
1405
1701
  RE_TS,
1406
1702
  RE_JSON,
1407
- ...volarContext.patterns
1703
+ ...languageContext.patterns
1408
1704
  ],
1409
1705
  exclude: [
1410
1706
  RE_DTS,
@@ -1417,7 +1713,7 @@ function createGeneratePlugin({ generator, entry, tsconfig, tsconfigRaw, build,
1417
1713
  if (!jsFile || emitJs) {
1418
1714
  const mod = this.getModuleInfo(id);
1419
1715
  const isEntry = entryMatcher ? entryMatcher(path.relative(cwd, id)) : !!mod?.isEntry;
1420
- const dtsId = filename_to_dts(id, volarContext);
1716
+ const dtsId = filename_to_dts(id, languageContext);
1421
1717
  dtsMap.set(dtsId, {
1422
1718
  code,
1423
1719
  id,
@@ -1453,80 +1749,12 @@ function createGeneratePlugin({ generator, entry, tsconfig, tsconfigRaw, build,
1453
1749
  debug$4("dts file already exists for %s, skipping generation", id);
1454
1750
  return;
1455
1751
  }
1456
- let dtsCode;
1457
- let map;
1458
1752
  debug$4("generate dts %s from %s", dtsId, id);
1459
- if (generator === "tsgo") {
1460
- if (volarContext.isVolarFile(id)) throw new Error(`tsgo does not support .${path.extname(id)} file.`);
1461
- const dtsPath = path.resolve(tsgoContext.path, path.relative(path.resolve(rootDir), filename_to_dts(id, volarContext)));
1462
- if (!existsSync(dtsPath)) {
1463
- debug$4("[tsgo]", dtsPath, "is missing");
1464
- throw new Error(`tsgo did not generate dts file for ${id}, please check your tsconfig.`);
1465
- }
1466
- dtsCode = await readFile(dtsPath, "utf8");
1467
- const mapPath = `${dtsPath}.map`;
1468
- if (existsSync(mapPath)) {
1469
- const mapRaw = await readFile(mapPath, "utf8");
1470
- map = {
1471
- ...JSON.parse(mapRaw),
1472
- sources: [id]
1473
- };
1474
- }
1475
- } else if (generator === "oxc" && !volarContext.isVolarFile(id)) {
1476
- const result = isolatedDeclarationSync(id, code, oxc);
1477
- if (result.errors.length) {
1478
- const [error] = result.errors;
1479
- return this.error({
1480
- message: error.message,
1481
- frame: error.codeframe || void 0
1482
- });
1483
- }
1484
- dtsCode = result.code;
1485
- if (result.map) {
1486
- map = result.map;
1487
- map.sourcesContent = void 0;
1488
- }
1489
- } else {
1490
- const options = {
1491
- tsconfig,
1492
- tsconfigRaw,
1493
- build,
1494
- incremental,
1495
- cwd,
1496
- entries: eager ? void 0 : Array.from(dtsMap.values()).filter((v) => v.isEntry).map((v) => v.id),
1497
- id,
1498
- sourcemap,
1499
- volarContext,
1500
- context: tscContext
1501
- };
1502
- let result;
1503
- if (parallel) result = await tscWorker.emit(options);
1504
- else result = tscModule.tscEmit(options);
1505
- if (result.error) return this.error(result.error);
1506
- dtsCode = result.code;
1507
- map = result.map;
1508
- if (dtsCode && RE_JSON.test(id)) if (dtsCode.includes("declare const _exports")) {
1509
- if (dtsCode.includes("declare const _exports: {") && !dtsCode.includes("\n}[];")) {
1510
- const exports = collectJsonExports(dtsCode);
1511
- let i = 0;
1512
- dtsCode += exports.map((e) => {
1513
- const valid = `_${e.replaceAll(/[^\w$]/g, "_")}${i++}`;
1514
- const jsonKey = JSON.stringify(e);
1515
- return `declare let ${valid}: typeof _exports[${jsonKey}]\nexport { ${valid} as ${jsonKey} }`;
1516
- }).join("\n");
1517
- }
1518
- } else {
1519
- const exportMap = collectJsonExportMap(dtsCode);
1520
- dtsCode += `
1521
- declare namespace __json_default_export {
1522
- export { ${Array.from(exportMap.entries()).map(([exported, local]) => exported === local ? exported : `${local} as ${exported}`).join(", ")} }
1523
- }
1524
- export { __json_default_export as default }`;
1525
- }
1526
- }
1753
+ const result = await declarationGenerator.emit(code, id);
1754
+ if (result.error) return this.error(result.error);
1527
1755
  return {
1528
- code: dtsCode || "",
1529
- map
1756
+ code: result.code || "",
1757
+ map: result.map
1530
1758
  };
1531
1759
  }
1532
1760
  },
@@ -1534,370 +1762,239 @@ export { __json_default_export as default }`;
1534
1762
  for (const fileName of Object.keys(bundle)) if (bundle[fileName].type === "chunk" && !RE_DTS.test(fileName) && !RE_DTS_MAP.test(fileName)) delete bundle[fileName];
1535
1763
  } : void 0,
1536
1764
  async buildEnd() {
1537
- tscWorker?.kill();
1538
- tscWorker = void 0;
1539
- await tsgoContext?.dispose();
1540
- tsgoContext = void 0;
1541
- if (newContext) tscContext = void 0;
1765
+ await declarationGenerator.dispose?.();
1542
1766
  },
1543
1767
  watchChange(id) {
1544
- if (tscModule) invalidateContextFile(tscContext || globalContext, id);
1768
+ declarationGenerator.invalidate?.(id);
1545
1769
  }
1546
1770
  };
1547
1771
  }
1548
- function createTscWorker() {
1549
- const childProcess = fork(new URL(WORKER_URL, import.meta.url), {
1550
- stdio: "inherit",
1551
- serialization: "advanced"
1552
- });
1553
- const pending = /* @__PURE__ */ new Map();
1554
- let nextId = 0;
1555
- childProcess.on("message", (response) => {
1556
- const handler = pending.get(response.id);
1557
- if (!handler) return;
1558
- pending.delete(response.id);
1559
- if (response.error) handler.reject(response.error);
1560
- else handler.resolve(response.result);
1561
- });
1562
- childProcess.on("exit", (code) => {
1563
- for (const handler of pending.values()) handler.reject(/* @__PURE__ */ new Error(`tsc worker exited with code ${code}`));
1564
- pending.clear();
1565
- });
1566
- return {
1567
- emit: (options) => new Promise((resolve, reject) => {
1568
- const id = nextId++;
1569
- pending.set(id, {
1570
- resolve,
1571
- reject
1572
- });
1573
- childProcess.send({
1574
- id,
1575
- options
1576
- });
1577
- }),
1578
- kill: () => childProcess.kill()
1579
- };
1772
+ function isThisExpression(node) {
1773
+ return is.Identifier(node, "this") || node.type === "ThisExpression" || node.type === "MemberExpression" && isThisExpression(node.object);
1580
1774
  }
1581
- function collectJsonExportMap(code) {
1582
- const exportMap = /* @__PURE__ */ new Map();
1583
- const { program } = parse$1(code, {
1584
- sourceType: "module",
1585
- lang: "dts"
1586
- });
1587
- for (const decl of program.body) if (decl.type === "ExportNamedDeclaration") {
1588
- if (decl.declaration) {
1589
- if (decl.declaration.type === "VariableDeclaration") {
1590
- for (const vdecl of decl.declaration.declarations) if (vdecl.id.type === "Identifier") exportMap.set(vdecl.id.name, vdecl.id.name);
1591
- } else if (decl.declaration.type === "TSModuleDeclaration" && decl.declaration.id.type === "Identifier") exportMap.set(decl.declaration.id.name, decl.declaration.id.name);
1592
- } else if (decl.specifiers.length) {
1593
- for (const spec of decl.specifiers) if (spec.type === "ExportSpecifier" && spec.exported.type === "Identifier") exportMap.set(spec.exported.name, spec.local.type === "Identifier" ? spec.local.name : spec.exported.name);
1594
- }
1595
- }
1596
- return exportMap;
1775
+ function isInfer(node) {
1776
+ return is.Identifier(node, "infer");
1597
1777
  }
1598
- /** `declare const _exports` mode */
1599
- function collectJsonExports(code) {
1600
- const exports = [];
1601
- const { program } = parse$1(code, {
1602
- sourceType: "module",
1603
- lang: "dts"
1778
+ function TSEntityNameToRuntime(node) {
1779
+ if (node.type === "Identifier" || node.type === "ThisExpression") return node;
1780
+ const left = TSEntityNameToRuntime(node.left);
1781
+ return Object.assign(node, {
1782
+ type: "MemberExpression",
1783
+ object: left,
1784
+ property: node.right,
1785
+ computed: false
1604
1786
  });
1605
- const members = program.body[0].declarations[0].id.typeAnnotation.typeAnnotation.members;
1606
- for (const member of members) if (member.key.type === "Identifier") exports.push(member.key.name);
1607
- else if (is.StringLiteral(member.key)) exports.push(member.key.value);
1608
- return exports;
1609
1787
  }
1610
- function createFakeJsPlugin({ sourcemap, cjsDefault, sideEffects }) {
1611
- let declarationIdx = 0;
1612
- const declarationMap = /* @__PURE__ */ new Map();
1613
- const commentsMap = /* @__PURE__ */ new Map();
1614
- const moduleExportsMap = /* @__PURE__ */ new Map();
1615
- const warnedCjsDtsInputs = /* @__PURE__ */ new Set();
1616
- return {
1617
- name: "rolldown-plugin-dts:fake-js",
1618
- outputOptions(options) {
1619
- if (options.format === "cjs" || options.format === "commonjs") throw new Error("[rolldown-plugin-dts] Cannot bundle dts files with `cjs` format.");
1620
- const { chunkFileNames, entryFileNames } = options;
1621
- return {
1622
- ...options,
1623
- sourcemap: options.sourcemap || sourcemap,
1624
- chunkFileNames(chunk) {
1625
- const nameTemplate = resolveTemplateFn(chunk.isEntry ? entryFileNames || "[name].js" : chunkFileNames || "[name]-[hash].js", chunk);
1626
- if (chunk.name.endsWith(".d")) {
1627
- const renderedNameWithoutD = filename_js_to_dts(replaceTemplateName(nameTemplate, chunk.name.slice(0, -2)));
1628
- if (RE_DTS.test(renderedNameWithoutD)) return renderedNameWithoutD;
1629
- const renderedName = filename_js_to_dts(replaceTemplateName(nameTemplate, chunk.name));
1630
- if (RE_DTS.test(renderedName)) return renderedName;
1788
+ function getIdFromTSEntityName(node) {
1789
+ if (node.type === "Identifier" || node.type === "ThisExpression") return node;
1790
+ return getIdFromTSEntityName(node.left);
1791
+ }
1792
+ function isReferenceId(node) {
1793
+ return is.oneOf(node, ["Identifier", "MemberExpression"]);
1794
+ }
1795
+ function isHelperImport(node) {
1796
+ return node.type === "ImportDeclaration" && node.specifiers.length > 0 && node.specifiers.every((spec) => spec.type === "ImportSpecifier" && spec.imported.type === "Identifier" && ["__exportAll", "__reExport"].includes(spec.local.name));
1797
+ }
1798
+ const REFERENCE_RE = /\/\s*<reference\s+(?:path|types)=/;
1799
+ function collectReferenceDirectives(comment, negative = false) {
1800
+ return comment.filter((c) => REFERENCE_RE.test(c.value) !== negative);
1801
+ }
1802
+ const SOURCE_MAP_PRAGMA_RE = /^#\s*source(?:Mapping)?URL=/;
1803
+ function isSourceMapPragma(comment) {
1804
+ return SOURCE_MAP_PRAGMA_RE.test(comment.value);
1805
+ }
1806
+ function isCjsDtsInputSyntax(node) {
1807
+ return node.type === "TSExportAssignment" || node.type === "TSImportEqualsDeclaration" && node.moduleReference.type === "TSExternalModuleReference";
1808
+ }
1809
+ function overwriteNode(node, newNode) {
1810
+ for (const key of Object.keys(node)) Reflect.deleteProperty(node, key);
1811
+ Object.assign(node, newNode);
1812
+ return node;
1813
+ }
1814
+ /**
1815
+ * Region markers and alike, the comments worth keeping when their node is
1816
+ * replaced or dropped
1817
+ */
1818
+ function pragmaComments(node) {
1819
+ return node.comments?.filter((comment) => comment.position === "before" && comment.value.startsWith("#") && !isSourceMapPragma(comment)) || [];
1820
+ }
1821
+ function inheritNodeComments(oldNode, newNode) {
1822
+ newNode.comments ||= [];
1823
+ newNode.comments.unshift(...pragmaComments(oldNode));
1824
+ newNode.comments = newNode.comments.filter((comment) => !REFERENCE_RE.test(comment.value) && !isSourceMapPragma(comment));
1825
+ return newNode;
1826
+ }
1827
+ function getIdentifierIndex(identifierMap, name) {
1828
+ if (name in identifierMap) return ++identifierMap[name];
1829
+ return identifierMap[name] = 0;
1830
+ }
1831
+ /**
1832
+ * Collects all TSTypeParameter nodes from the given node and groups them by
1833
+ * their name. One name can associate with one or more type parameters. These
1834
+ * names will be used as the parameter name in the generated JavaScript
1835
+ * dependency function.
1836
+ */
1837
+ function collectParams(node) {
1838
+ const typeParams = [];
1839
+ walk(node, { leave(node) {
1840
+ if ("typeParameters" in node && node.typeParameters?.type === "TSTypeParameterDeclaration") typeParams.push(...node.typeParameters.params.map(({ name }) => name));
1841
+ } });
1842
+ const paramMap = /* @__PURE__ */ new Map();
1843
+ for (const typeParam of typeParams) {
1844
+ const name = typeParam.name;
1845
+ const group = paramMap.get(name);
1846
+ if (group) group.push(typeParam);
1847
+ else paramMap.set(name, [typeParam]);
1848
+ }
1849
+ return Array.from(paramMap, ([name, typeParams]) => ({
1850
+ name,
1851
+ typeParams
1852
+ }));
1853
+ }
1854
+ async function collectDependencies(context, node, importer, namespaceStmts, children, identifierMap) {
1855
+ const deps = /* @__PURE__ */ new Set();
1856
+ const seen = /* @__PURE__ */ new Set();
1857
+ const preserveImportTypeCache = /* @__PURE__ */ new Map();
1858
+ const inferredStack = [];
1859
+ let currentInferred = /* @__PURE__ */ new Set();
1860
+ function isInferred(node) {
1861
+ return node.type === "Identifier" && currentInferred.has(node.name);
1862
+ }
1863
+ await walkAsync(node, {
1864
+ enter(node) {
1865
+ if (node.type !== "TSConditionalType") return;
1866
+ const inferred = collectInferredNames(node.extendsType);
1867
+ inferredStack.push(inferred);
1868
+ },
1869
+ async leave(node, path) {
1870
+ const { parent } = path;
1871
+ if (node.type === "TSConditionalType") inferredStack.pop();
1872
+ else if (parent?.type === "TSConditionalType") {
1873
+ const trueBranch = parent.trueType === node;
1874
+ currentInferred = new Set((trueBranch ? inferredStack : inferredStack.slice(0, -1)).flat());
1875
+ } else currentInferred = /* @__PURE__ */ new Set();
1876
+ if (node.type === "ExportNamedDeclaration") {
1877
+ for (const specifier of node.specifiers) if (specifier.type === "ExportSpecifier") addDependency(specifier.local);
1878
+ } else if (node.type === "TSInterfaceDeclaration" && node.extends) for (const heritage of node.extends || []) addDependency(heritage.expression);
1879
+ else if (node.type === "ClassDeclaration") {
1880
+ if (node.superClass) addDependency(node.superClass);
1881
+ if (node.implements) for (const implement of node.implements) addDependency(implement.expression);
1882
+ } else if (is.oneOf(node, [
1883
+ "Property",
1884
+ "PropertyDefinition",
1885
+ "TSAbstractPropertyDefinition",
1886
+ "MethodDefinition",
1887
+ "TSAbstractMethodDefinition",
1888
+ "TSPropertySignature",
1889
+ "TSMethodSignature"
1890
+ ])) {
1891
+ if (node.computed && isReferenceId(node.key)) addDependency(node.key);
1892
+ if ("value" in node && isReferenceId(node.value)) addDependency(node.value);
1893
+ } else switch (node.type) {
1894
+ case "TSTypeReference":
1895
+ addDependency(TSEntityNameToRuntime(node.typeName));
1896
+ break;
1897
+ case "TSQualifiedName":
1898
+ addDependency(getIdFromTSEntityName(node.left));
1899
+ break;
1900
+ case "TSTypeQuery":
1901
+ if (seen.has(node.exprName)) return;
1902
+ if (node.exprName.type === "TSImportType") break;
1903
+ addDependency(TSEntityNameToRuntime(node.exprName));
1904
+ break;
1905
+ case "TSImportType": {
1906
+ seen.add(node);
1907
+ const { source, qualifier } = node;
1908
+ const resolved = await context.resolve(source.value, importer);
1909
+ if (!resolved || !!resolved.external) {
1910
+ preserveImportTypeCache.set(source.value, true);
1911
+ break;
1631
1912
  }
1632
- return nameTemplate;
1913
+ const dep = importNamespace(node, qualifier, source, namespaceStmts, identifierMap);
1914
+ if (dep) addDependency(dep);
1915
+ break;
1633
1916
  }
1634
- };
1635
- },
1636
- transform: {
1637
- filter: { id: RE_DTS },
1638
- handler: transform
1639
- },
1640
- renderChunk,
1641
- generateBundle(options, bundle) {
1642
- for (const chunk of Object.values(bundle)) {
1643
- if (!RE_DTS_MAP.test(chunk.fileName)) continue;
1644
- if (sourcemap) {
1645
- if (chunk.type === "chunk" || typeof chunk.source !== "string") continue;
1646
- const map = JSON.parse(chunk.source);
1647
- map.sourcesContent = void 0;
1648
- chunk.source = JSON.stringify(map);
1649
- } else delete bundle[chunk.fileName];
1650
- }
1651
- }
1652
- };
1653
- async function transform(code, id) {
1654
- let file;
1655
- try {
1656
- file = parse$1(code, {
1657
- lang: "dts",
1658
- sourceType: "module",
1659
- attachComments: true
1660
- });
1661
- } catch (error) {
1662
- throw new Error(`Failed to parse ${id}. This may be caused by a syntax error in the declaration file or a bug in the plugin. Please report this issue to https://github.com/sxzz/rolldown-plugin-dts\n${error}`, { cause: error });
1663
- }
1664
- const { program } = file;
1665
- moduleExportsMap.set(id, await collectModuleExports(this, program.body, id));
1666
- const identifierMap = Object.create(null);
1667
- if (!warnedCjsDtsInputs.has(id) && program.body.some(isCjsDtsInputSyntax)) {
1668
- warnedCjsDtsInputs.add(id);
1669
- this.warn(`${id} uses CommonJS dts syntax. ${RE_NODE_MODULES.test(id) ? `CommonJS dts modules cannot be bundled by rolldown-plugin-dts. Please mark this module as external in your Rolldown config.` : `rolldown-plugin-dts does not support bundling CommonJS dts input.`}`);
1670
- }
1671
- const directives = collectReferenceDirectives(file.comments);
1672
- if (directives.length) commentsMap.set(id, directives);
1673
- const appendStmts = [];
1674
- const namespaceStmts = /* @__PURE__ */ new Map();
1675
- for (const [i, stmt] of program.body.entries()) {
1676
- const setStmt = (stmt) => program.body[i] = stmt;
1677
- if (rewriteImportExport(stmt, setStmt)) continue;
1678
- const sideEffect = stmt.type === "TSModuleDeclaration" && stmt.kind !== "namespace";
1679
- if (sideEffect && stmt.type === "TSModuleDeclaration" && is.StringLiteral(stmt.id) && stmt.id.value[0] === ".") this.warn(`\`declare module ${JSON.stringify(stmt.id.value)}\` will be kept as-is in the output. Relative module declaration may cause unexpected issues. Found in ${id}.`);
1680
- const isDefaultExport = stmt.type === "ExportDefaultDeclaration";
1681
- const isExportDecl = is.oneOf(stmt, ["ExportNamedDeclaration", "ExportDefaultDeclaration"]) && !!stmt.declaration;
1682
- const decl = isExportDecl ? stmt.declaration : stmt;
1683
- const setDecl = isExportDecl ? (decl) => stmt.declaration = decl : setStmt;
1684
- if (decl.type !== "TSDeclareFunction" && !is.Declaration(decl)) continue;
1685
- if (is.oneOf(decl, [
1686
- "TSEnumDeclaration",
1687
- "ClassDeclaration",
1688
- "FunctionDeclaration",
1689
- "TSDeclareFunction",
1690
- "TSModuleDeclaration",
1691
- "VariableDeclaration"
1692
- ])) decl.declare = true;
1693
- const bindings = [];
1694
- if (decl.type === "VariableDeclaration") bindings.push(...decl.declarations.map((decl) => decl.id));
1695
- else if ("id" in decl && decl.id) {
1696
- let binding = decl.id;
1697
- if (binding.type === "TSQualifiedName") binding = getIdFromTSEntityName(binding);
1698
- if (sideEffect) binding = b.Identifier({ name: `_${getIdentifierIndex(identifierMap, "")}` });
1699
- if (binding.type !== "Identifier") throw new Error(`Unexpected ${binding.type} declaration id`);
1700
- bindings.push(binding);
1701
- } else {
1702
- const binding = b.Identifier({ name: "export_default" });
1703
- bindings.push(binding);
1704
- decl.id = binding;
1705
1917
  }
1706
- const params = collectParams(decl);
1707
- const childrenSet = /* @__PURE__ */ new Set();
1708
- const deps = await collectDependencies(this, decl, id, namespaceStmts, childrenSet, identifierMap);
1709
- const children = Array.from(childrenSet).filter((child) => bindings.every((b) => child !== b));
1710
- if (decl !== stmt) decl.comments = stmt.comments;
1711
- const declarationId = registerDeclaration({
1712
- decl,
1713
- deps,
1714
- bindings,
1715
- params,
1716
- children
1717
- });
1718
- const declarationIdNode = b.Literal({
1719
- value: declarationId,
1720
- raw: String(declarationId)
1721
- });
1722
- const depsBody = b.ArrayExpression({ elements: deps });
1723
- const depsNode = b.ArrowFunctionExpression({
1724
- id: null,
1725
- generator: false,
1726
- async: false,
1727
- params: params.map(({ name }) => b.Identifier({ name })),
1728
- body: depsBody,
1729
- expression: true
1730
- });
1731
- const childrenNode = b.ArrayExpression({ elements: children.map((node) => b.Literal({
1732
- value: "",
1733
- raw: "\"\"",
1734
- start: node.start,
1735
- end: node.end
1736
- })) });
1737
- const sideEffectNode = sideEffect && b.CallExpression({
1738
- callee: b.Identifier({ name: "sideEffect" }),
1739
- arguments: [bindings[0]],
1740
- optional: false
1741
- });
1742
- const runtimeArrayNode = runtimeBindingArrayExpression([
1743
- declarationIdNode,
1744
- depsNode,
1745
- childrenNode,
1746
- ...sideEffectNode ? [sideEffectNode] : []
1747
- ]);
1748
- const runtimeAssignment = b.VariableDeclaration({
1749
- kind: "var",
1750
- declarations: [b.VariableDeclarator({
1751
- id: b.ArrayPattern({ elements: bindings.map((binding) => ({
1752
- ...binding,
1753
- typeAnnotation: null
1754
- })) }),
1755
- init: runtimeArrayNode
1756
- })]
1757
- });
1758
- if (isDefaultExport) {
1759
- appendStmts.push(b.ExportNamedDeclaration({
1760
- declaration: null,
1761
- specifiers: [b.ExportSpecifier({
1762
- local: bindings[0],
1763
- exported: b.Identifier({ name: "default" })
1764
- })],
1765
- source: null,
1766
- attributes: []
1767
- }));
1768
- setStmt(runtimeAssignment);
1769
- } else setDecl(runtimeAssignment);
1770
- }
1771
- if (sideEffects) appendStmts.push(b.ExpressionStatement({ expression: b.CallExpression({
1772
- callee: b.Identifier({ name: "sideEffect" }),
1773
- arguments: [],
1774
- optional: false
1775
- }) }));
1776
- program.body = [
1777
- ...Array.from(namespaceStmts.values()).map(({ stmt }) => stmt),
1778
- ...program.body,
1779
- ...appendStmts
1780
- ];
1781
- const result = print(program, {
1782
- comments: false,
1783
- ...sourcemap && { sourceMaps: {
1784
- source: code,
1785
- sourceFileName: id
1786
- } }
1787
- });
1788
- return {
1789
- code: result.code,
1790
- map: result.map ?? null
1791
- };
1792
- }
1793
- function renderChunk(code, chunk) {
1794
- if (!RE_DTS.test(chunk.fileName)) return;
1795
- const exportInfo = collectChunkExportInfo(chunk, moduleExportsMap);
1796
- let file;
1797
- try {
1798
- file = parse$1(code, {
1799
- lang: "ts",
1800
- sourceType: "module",
1801
- attachComments: true
1802
- });
1803
- } catch (error) {
1804
- throw new Error(`Failed to parse generated code for chunk ${chunk.fileName}. This may be caused by a bug in the plugin. Please report this issue to https://github.com/sxzz/rolldown-plugin-dts\n${error}`, { cause: error });
1805
- }
1806
- const { program } = file;
1807
- program.body = patchTsNamespace(program.body);
1808
- program.body = patchReExport(program.body);
1809
- program.body = program.body.map((node) => {
1810
- if (isHelperImport(node)) return null;
1811
- if (node.type === "ExpressionStatement") return null;
1812
- const newNode = patchImportExport(node, exportInfo, cjsDefault);
1813
- if (newNode || newNode === false) return newNode;
1814
- if (node.type !== "VariableDeclaration") return node;
1815
- if (!isRuntimeBindingVariableDeclaration(node)) return null;
1816
- const decl = node.declarations[0];
1817
- const [declarationIdNode, depsFn, children] = decl.init.elements;
1818
- const declarationId = declarationIdNode.value;
1819
- const declaration = getDeclaration(declarationId);
1820
- if (sourcemap) walk(declaration.decl, { enter(node) {
1821
- node.start = void 0;
1822
- node.end = void 0;
1823
- } });
1824
- for (const [i, id] of decl.id.elements.entries()) {
1825
- const transformedBinding = {
1826
- ...id,
1827
- typeAnnotation: declaration.bindings[i].typeAnnotation
1828
- };
1829
- overwriteNode(declaration.bindings[i], transformedBinding);
1830
- }
1831
- if (sourcemap) for (const [i, child] of children.elements.entries()) Object.assign(declaration.children[i], {
1832
- start: child.start,
1833
- end: child.end
1834
- });
1835
- const transformedParams = depsFn.params;
1836
- for (const [i, transformedParam] of transformedParams.entries()) {
1837
- const transformedName = transformedParam.name;
1838
- for (const originalTypeParam of declaration.params[i].typeParams) originalTypeParam.name = transformedName;
1839
- }
1840
- const transformedDeps = depsFn.body.elements;
1841
- for (const [i, originalDep] of declaration.deps.entries()) {
1842
- let transformedDep = transformedDeps[i];
1843
- if (transformedDep.type === "UnaryExpression" && transformedDep.operator === "void") {
1844
- const undefinedDep = b.Identifier({ name: "undefined" });
1845
- undefinedDep.start = transformedDep.start;
1846
- undefinedDep.end = transformedDep.end;
1847
- transformedDep = undefinedDep;
1848
- } else if (isInfer(transformedDep)) transformedDep.name = "__Infer";
1849
- if (originalDep.replace) originalDep.replace(transformedDep);
1850
- else Object.assign(originalDep, transformedDep);
1851
- }
1852
- return inheritNodeComments(node, declaration.decl);
1853
- }).filter((node) => !!node);
1854
- if (program.body.length === 0) return {
1855
- code: EMPTY_STUB,
1856
- map: null
1857
- };
1858
- const comments = /* @__PURE__ */ new Set();
1859
- const commentsValue = /* @__PURE__ */ new Set();
1860
- for (const id of chunk.moduleIds) {
1861
- const preserveComments = commentsMap.get(id);
1862
- if (preserveComments) {
1863
- preserveComments.forEach((c) => {
1864
- const id = c.type + c.value;
1865
- if (commentsValue.has(id)) return;
1866
- commentsValue.add(id);
1867
- comments.add(c);
1868
- });
1869
- commentsMap.delete(id);
1870
- }
1871
- }
1872
- if (comments.size) {
1873
- program.body[0].comments ||= [];
1874
- program.body[0].comments.unshift(...Array.from(comments, (c) => ({
1875
- type: c.type,
1876
- value: c.value,
1877
- position: "before",
1878
- sameLine: false
1879
- })));
1918
+ if (parent && !deps.has(node) && isChildSymbol(node, parent)) children.add(node);
1880
1919
  }
1881
- const result = print(program, {
1882
- comments: true,
1883
- ...sourcemap && { sourceMaps: {
1884
- source: code,
1885
- sourceFileName: chunk.fileName
1886
- } }
1887
- });
1888
- return {
1889
- code: result.code,
1890
- map: result.map ?? null
1891
- };
1892
- }
1893
- function registerDeclaration(info) {
1894
- const declarationId = declarationIdx++;
1895
- declarationMap.set(declarationId, info);
1896
- return declarationId;
1920
+ });
1921
+ return Array.from(deps);
1922
+ function addDependency(node) {
1923
+ if (isThisExpression(node) || isInferred(node)) return;
1924
+ deps.add(node);
1897
1925
  }
1898
- function getDeclaration(declarationId) {
1899
- return declarationMap.get(declarationId);
1926
+ }
1927
+ function importNamespace(node, imported, source, namespaceStmts, identifierMap) {
1928
+ const sourceText = source.value.replaceAll(/\W/g, "_");
1929
+ const localName = `_$${isIdentifierName(source.value) ? source.value : `${sourceText}${getIdentifierIndex(identifierMap, sourceText)}`}`;
1930
+ let local = b.Identifier({ name: localName });
1931
+ if (namespaceStmts.has(source.value)) local = namespaceStmts.get(source.value).local;
1932
+ else namespaceStmts.set(source.value, {
1933
+ stmt: b.ImportDeclaration({
1934
+ specifiers: [b.ImportNamespaceSpecifier({ local })],
1935
+ source,
1936
+ phase: null,
1937
+ attributes: []
1938
+ }),
1939
+ local
1940
+ });
1941
+ if (imported) {
1942
+ const importedLeft = getIdFromTSEntityName(imported);
1943
+ if (imported.type === "ThisExpression" || importedLeft.type === "ThisExpression") throw new Error("Cannot import `this` from module.");
1944
+ overwriteNode(importedLeft, b.TSQualifiedName({
1945
+ left: local,
1946
+ right: { ...importedLeft }
1947
+ }));
1948
+ local = imported;
1900
1949
  }
1950
+ let replacement = node;
1951
+ if (node.typeArguments) {
1952
+ overwriteNode(node, b.TSTypeReference({
1953
+ typeName: local,
1954
+ typeArguments: node.typeArguments
1955
+ }));
1956
+ replacement = local;
1957
+ } else overwriteNode(node, local);
1958
+ return {
1959
+ ...TSEntityNameToRuntime(local),
1960
+ replace(newNode) {
1961
+ overwriteNode(replacement, newNode);
1962
+ }
1963
+ };
1964
+ }
1965
+ function isChildSymbol(node, parent) {
1966
+ if (node.type === "Identifier") return true;
1967
+ if (is.oneOf(parent, ["TSPropertySignature", "TSMethodSignature"]) && parent.key === node) return true;
1968
+ return false;
1969
+ }
1970
+ function collectInferredNames(node) {
1971
+ const inferred = [];
1972
+ walk(node, { enter(node) {
1973
+ if (node.type === "TSInferType" && node.typeParameter) inferred.push(node.typeParameter.name.name);
1974
+ } });
1975
+ return inferred;
1976
+ }
1977
+ /**
1978
+ * Check if the given node is a {@link RuntimeBindingVariableDeclration}
1979
+ */
1980
+ function isRuntimeBindingVariableDeclaration(node) {
1981
+ return node?.type === "VariableDeclaration" && node.declarations.length === 1 && node.declarations[0].type === "VariableDeclarator" && node.declarations[0].id.type === "ArrayPattern" && isRuntimeBindingArrayExpression(node.declarations[0].init);
1982
+ }
1983
+ /**
1984
+ * Check if the given node is a {@link RuntimeBindingArrayExpression}
1985
+ */
1986
+ function isRuntimeBindingArrayExpression(node) {
1987
+ return node?.type === "ArrayExpression" && isRuntimeBindingArrayElements(node.elements);
1988
+ }
1989
+ /**
1990
+ * Check if the given array is a {@link RuntimeBindingArrayElements}
1991
+ */
1992
+ function isRuntimeBindingArrayElements(elements) {
1993
+ const [declarationId, deps, children, effect] = elements;
1994
+ return is.NumericLiteral(declarationId) && deps?.type === "ArrowFunctionExpression" && children?.type === "ArrayExpression" && (!effect || effect.type === "CallExpression");
1995
+ }
1996
+ function runtimeBindingArrayExpression(elements) {
1997
+ return b.ArrayExpression({ elements: [...elements] });
1901
1998
  }
1902
1999
  async function collectModuleExports(context, nodes, id) {
1903
2000
  const info = {
@@ -1981,7 +2078,21 @@ async function resolveExportSource(context, source, importer) {
1981
2078
  if (!resolved || resolved.external) return;
1982
2079
  return resolved.id;
1983
2080
  }
1984
- function collectChunkExportInfo(chunk, moduleExportsMap) {
2081
+ /**
2082
+ * Resolves what the chunk exports and how each export is emitted: which names
2083
+ * are type only, and which declarations get their `export` keyword back.
2084
+ */
2085
+ function planChunkExports(chunk, moduleExportsMap, nodes, getDeclaration, cjsDefault) {
2086
+ const { typeOnlyNames, typeOnlyExportAllSources, inlineNames } = collectChunkExports(chunk, moduleExportsMap);
2087
+ const { kinds, allowExportAssignment } = planInlineExports(nodes, inlineNames, getDeclaration, cjsDefault);
2088
+ return {
2089
+ typeOnlyNames,
2090
+ typeOnlyExportAllSources,
2091
+ inlineKinds: kinds,
2092
+ allowExportAssignment
2093
+ };
2094
+ }
2095
+ function collectChunkExports(chunk, moduleExportsMap) {
1985
2096
  const exportsByModule = resolveAllModuleExports(moduleExportsMap);
1986
2097
  const roots = chunk.facadeModuleId && moduleExportsMap.has(chunk.facadeModuleId) ? [chunk.facadeModuleId] : chunk.moduleIds;
1987
2098
  const mergedExports = /* @__PURE__ */ new Map();
@@ -1997,10 +2108,13 @@ function collectChunkExportInfo(chunk, moduleExportsMap) {
1997
2108
  }
1998
2109
  }
1999
2110
  const typeOnlyNames = /* @__PURE__ */ new Set();
2111
+ const inlineNames = /* @__PURE__ */ new Set();
2000
2112
  for (const [name, typeOnly] of mergedExports) if (typeOnly) typeOnlyNames.add(name);
2113
+ else inlineNames.add(name);
2001
2114
  return {
2002
2115
  typeOnlyNames,
2003
- typeOnlyExportAllSources
2116
+ typeOnlyExportAllSources,
2117
+ inlineNames
2004
2118
  };
2005
2119
  }
2006
2120
  function resolveAllModuleExports(moduleExportsMap) {
@@ -2038,377 +2152,636 @@ function setExportTypeOnly(exports, name, typeOnly) {
2038
2152
  return false;
2039
2153
  }
2040
2154
  /**
2041
- * Collects all TSTypeParameter nodes from the given node and groups them by
2042
- * their name. One name can associate with one or more type parameters. These
2043
- * names will be used as the parameter name in the generated JavaScript
2044
- * dependency function.
2155
+ * Collects the `export { local as exported }` statements of a chunk, i.e. the
2156
+ * exports that could be attached back to their declaration. Re-exports
2157
+ * (`export { x } from '...'`) are not local and therefore skipped.
2045
2158
  */
2046
- function collectParams(node) {
2047
- const typeParams = [];
2048
- walk(node, { leave(node) {
2049
- if ("typeParameters" in node && node.typeParameters?.type === "TSTypeParameterDeclaration") typeParams.push(...node.typeParameters.params.map(({ name }) => name));
2050
- } });
2051
- const paramMap = /* @__PURE__ */ new Map();
2052
- for (const typeParam of typeParams) {
2053
- const name = typeParam.name;
2054
- const group = paramMap.get(name);
2055
- if (group) group.push(typeParam);
2056
- else paramMap.set(name, [typeParam]);
2159
+ function getLocalExportsMap(nodes) {
2160
+ const exportsMap = /* @__PURE__ */ new Map();
2161
+ for (const node of nodes) {
2162
+ if (node.type !== "ExportNamedDeclaration" || node.declaration || node.source) continue;
2163
+ for (const specifier of node.specifiers) {
2164
+ if (specifier.type !== "ExportSpecifier") continue;
2165
+ exportsMap.set(nameOf(specifier.exported), {
2166
+ local: nameOf(specifier.local),
2167
+ typeOnly: node.exportKind === "type" || specifier.exportKind === "type",
2168
+ specifier
2169
+ });
2170
+ }
2057
2171
  }
2058
- return Array.from(paramMap.entries()).map(([name, typeParams]) => ({
2059
- name,
2060
- typeParams
2061
- }));
2172
+ return exportsMap;
2062
2173
  }
2063
- async function collectDependencies(context, node, importer, namespaceStmts, children, identifierMap) {
2064
- const deps = /* @__PURE__ */ new Set();
2065
- const seen = /* @__PURE__ */ new Set();
2066
- const preserveImportTypeCache = /* @__PURE__ */ new Map();
2067
- const inferredStack = [];
2068
- let currentInferred = /* @__PURE__ */ new Set();
2069
- function isInferred(node) {
2070
- return node.type === "Identifier" && currentInferred.has(node.name);
2174
+ /**
2175
+ * Decides which declarations get their `export` keyword back, so that a
2176
+ * declaration written as `export declare const x` is emitted as
2177
+ * `export declare const x` instead of `declare const x` + `export { x }`.
2178
+ *
2179
+ * A declaration qualifies only if it was exported inline in its own source
2180
+ * file, the chunk exports it as a value under its own name, and every
2181
+ * declaration it merges with qualifies as well. The specifiers of the
2182
+ * re-attached exports are removed here, before `patchImportExport` runs, so
2183
+ * that both stay in sync.
2184
+ */
2185
+ function planInlineExports(nodes, inlineNames, getDeclaration, cjsDefault) {
2186
+ const exportsMap = getLocalExportsMap(nodes);
2187
+ const allowExportAssignment = hasOnlyDefaultExport(nodes);
2188
+ const kinds = /* @__PURE__ */ new Map();
2189
+ const removed = /* @__PURE__ */ new Set();
2190
+ const declNames = /* @__PURE__ */ new Map();
2191
+ const nameDecls = /* @__PURE__ */ new Map();
2192
+ for (const node of nodes) {
2193
+ if (!isRuntimeBindingVariableDeclaration(node)) continue;
2194
+ const { id, init } = node.declarations[0];
2195
+ const declarationId = init.elements[0].value;
2196
+ const names = id.elements.map(({ name }) => name);
2197
+ declNames.set(declarationId, names);
2198
+ for (const name of names) {
2199
+ const decls = nameDecls.get(name);
2200
+ if (decls) decls.push(declarationId);
2201
+ else nameDecls.set(name, [declarationId]);
2202
+ }
2071
2203
  }
2072
- await walkAsync(node, {
2073
- enter(node) {
2074
- if (node.type === "TSConditionalType") {
2075
- const inferred = collectInferredNames(node.extendsType);
2076
- inferredStack.push(inferred);
2077
- }
2078
- },
2079
- async leave(node, path) {
2080
- const { parent } = path;
2081
- if (node.type === "TSConditionalType") inferredStack.pop();
2082
- else if (parent?.type === "TSConditionalType") {
2083
- const trueBranch = parent.trueType === node;
2084
- currentInferred = new Set((trueBranch ? inferredStack : inferredStack.slice(0, -1)).flat());
2085
- } else currentInferred = /* @__PURE__ */ new Set();
2086
- if (node.type === "ExportNamedDeclaration") {
2087
- for (const specifier of node.specifiers) if (specifier.type === "ExportSpecifier") addDependency(specifier.local);
2088
- } else if (node.type === "TSInterfaceDeclaration" && node.extends) for (const heritage of node.extends || []) addDependency(heritage.expression);
2089
- else if (node.type === "ClassDeclaration") {
2090
- if (node.superClass) addDependency(node.superClass);
2091
- if (node.implements) for (const implement of node.implements) addDependency(implement.expression);
2092
- } else if (is.oneOf(node, [
2093
- "Property",
2094
- "PropertyDefinition",
2095
- "TSAbstractPropertyDefinition",
2096
- "MethodDefinition",
2097
- "TSAbstractMethodDefinition",
2098
- "TSPropertySignature",
2099
- "TSMethodSignature"
2100
- ])) {
2101
- if (node.computed && isReferenceId(node.key)) addDependency(node.key);
2102
- if ("value" in node && isReferenceId(node.value)) addDependency(node.value);
2103
- } else switch (node.type) {
2104
- case "TSTypeReference":
2105
- addDependency(TSEntityNameToRuntime(node.typeName));
2106
- break;
2107
- case "TSTypeQuery":
2108
- if (seen.has(node.exprName)) return;
2109
- if (node.exprName.type === "TSImportType") break;
2110
- addDependency(TSEntityNameToRuntime(node.exprName));
2111
- break;
2112
- case "TSImportType": {
2113
- seen.add(node);
2114
- const { source, qualifier } = node;
2115
- const resolved = await context.resolve(source.value, importer);
2116
- if (!resolved || !!resolved.external) {
2117
- preserveImportTypeCache.set(source.value, true);
2118
- break;
2119
- }
2120
- const dep = importNamespace(node, qualifier, source, namespaceStmts, identifierMap);
2121
- if (dep) addDependency(dep);
2122
- break;
2123
- }
2124
- }
2125
- if (parent && !deps.has(node) && isChildSymbol(node, parent)) children.add(node);
2204
+ const named = /* @__PURE__ */ new Set();
2205
+ for (const [declarationId, names] of declNames) {
2206
+ if (getDeclaration(declarationId).exportType !== "named") continue;
2207
+ if (names.every(isInlinableName)) named.add(declarationId);
2208
+ }
2209
+ let changed = true;
2210
+ while (changed) {
2211
+ changed = false;
2212
+ for (const declarationId of named) if (!declNames.get(declarationId).every((name) => nameDecls.get(name).every((id) => named.has(id)))) {
2213
+ named.delete(declarationId);
2214
+ changed = true;
2126
2215
  }
2127
- });
2128
- return Array.from(deps);
2129
- function addDependency(node) {
2130
- if (isThisExpression(node) || isInferred(node)) return;
2131
- deps.add(node);
2132
2216
  }
2133
- }
2134
- function importNamespace(node, imported, source, namespaceStmts, identifierMap) {
2135
- const sourceText = source.value.replaceAll(/\W/g, "_");
2136
- const localName = `_$${isIdentifierName(source.value) ? source.value : `${sourceText}${getIdentifierIndex(identifierMap, sourceText)}`}`;
2137
- let local = b.Identifier({ name: localName });
2138
- if (namespaceStmts.has(source.value)) local = namespaceStmts.get(source.value).local;
2139
- else namespaceStmts.set(source.value, {
2140
- stmt: b.ImportDeclaration({
2141
- specifiers: [b.ImportNamespaceSpecifier({ local })],
2142
- source,
2143
- phase: null,
2144
- attributes: []
2145
- }),
2146
- local
2147
- });
2148
- if (imported) {
2149
- const importedLeft = getIdFromTSEntityName(imported);
2150
- if (imported.type === "ThisExpression" || importedLeft.type === "ThisExpression") throw new Error("Cannot import `this` from module.");
2151
- overwriteNode(importedLeft, b.TSQualifiedName({
2152
- left: local,
2153
- right: { ...importedLeft }
2154
- }));
2155
- local = imported;
2217
+ for (const declarationId of named) {
2218
+ kinds.set(declarationId, "named");
2219
+ for (const name of declNames.get(declarationId)) removed.add(exportsMap.get(name).specifier);
2220
+ }
2221
+ const defaultExport = exportsMap.get("default");
2222
+ if (defaultExport && !defaultExport.typeOnly && inlineNames.has("default") && (!cjsDefault || !allowExportAssignment)) for (const [declarationId, names] of declNames) {
2223
+ const declaration = getDeclaration(declarationId);
2224
+ if (declaration.exportType !== "default" || names.length !== 1 || names[0] !== defaultExport.local || nameDecls.get(names[0]).length !== 1 || !isInlinableDefaultDeclaration(declaration.decl)) continue;
2225
+ kinds.set(declarationId, "default");
2226
+ removed.add(defaultExport.specifier);
2227
+ break;
2228
+ }
2229
+ if (removed.size) for (const node of nodes) {
2230
+ if (node.type !== "ExportNamedDeclaration") continue;
2231
+ node.specifiers = node.specifiers.filter((specifier) => !removed.has(specifier));
2156
2232
  }
2157
- let replacement = node;
2158
- if (node.typeArguments) {
2159
- overwriteNode(node, b.TSTypeReference({
2160
- typeName: local,
2161
- typeArguments: node.typeArguments
2162
- }));
2163
- replacement = local;
2164
- } else overwriteNode(node, local);
2165
2233
  return {
2166
- ...TSEntityNameToRuntime(local),
2167
- replace(newNode) {
2168
- overwriteNode(replacement, newNode);
2169
- }
2234
+ kinds,
2235
+ allowExportAssignment
2170
2236
  };
2237
+ function isInlinableName(name) {
2238
+ if (!inlineNames.has(name)) return false;
2239
+ const exported = exportsMap.get(name);
2240
+ return !!exported && exported.local === name && !exported.typeOnly;
2241
+ }
2171
2242
  }
2172
- function isChildSymbol(node, parent) {
2173
- if (node.type === "Identifier") return true;
2174
- if (is.oneOf(parent, ["TSPropertySignature", "TSMethodSignature"]) && parent.key === node) return true;
2175
- return false;
2176
- }
2177
- function collectInferredNames(node) {
2178
- const inferred = [];
2179
- walk(node, { enter(node) {
2180
- if (node.type === "TSInferType" && node.typeParameter) inferred.push(node.typeParameter.name.name);
2181
- } });
2182
- return inferred;
2183
- }
2184
- const REFERENCE_RE = /\/\s*<reference\s+(?:path|types)=/;
2185
- function collectReferenceDirectives(comment, negative = false) {
2186
- return comment.filter((c) => REFERENCE_RE.test(c.value) !== negative);
2187
- }
2188
- const SOURCE_MAP_PRAGMA_RE = /^#\s*source(?:Mapping)?URL=/;
2189
- function isSourceMapPragma(comment) {
2190
- return SOURCE_MAP_PRAGMA_RE.test(comment.value);
2243
+ /** Whether `default` is the only name the chunk exports */
2244
+ function hasOnlyDefaultExport(nodes) {
2245
+ let hasDefault = false;
2246
+ for (const node of nodes) {
2247
+ if (node.type === "ExportAllDeclaration") return false;
2248
+ if (node.type === "ExportDefaultDeclaration") {
2249
+ hasDefault = true;
2250
+ continue;
2251
+ }
2252
+ if (node.type !== "ExportNamedDeclaration") continue;
2253
+ if (node.declaration) return false;
2254
+ for (const specifier of node.specifiers) {
2255
+ if (nameOf(specifier.exported) !== "default") return false;
2256
+ hasDefault = true;
2257
+ }
2258
+ }
2259
+ return hasDefault;
2191
2260
  }
2192
- function isCjsDtsInputSyntax(node) {
2193
- return node.type === "TSExportAssignment" || node.type === "TSImportEqualsDeclaration" && node.moduleReference.type === "TSExternalModuleReference";
2261
+ /** `export default` only accepts a class, function or interface declaration */
2262
+ function isInlinableDefaultDeclaration(node) {
2263
+ return is.oneOf(node, [
2264
+ "ClassDeclaration",
2265
+ "FunctionDeclaration",
2266
+ "TSDeclareFunction",
2267
+ "TSInterfaceDeclaration"
2268
+ ]);
2269
+ }
2270
+ function inlineExportDeclaration(decl, kind) {
2271
+ if (kind === "default" && "declare" in decl) decl.declare = false;
2272
+ const exported = kind === "default" ? b.ExportDefaultDeclaration({ declaration: decl }) : b.ExportNamedDeclaration({
2273
+ declaration: decl,
2274
+ specifiers: [],
2275
+ source: null,
2276
+ attributes: []
2277
+ });
2278
+ exported.comments = decl.comments;
2279
+ decl.comments = void 0;
2280
+ return exported;
2194
2281
  }
2195
2282
  /**
2196
- * Check if the given node is a {@link RuntimeBindingVariableDeclration}
2283
+ * patch `.d.ts` suffix in import source to `.js`
2197
2284
  */
2198
- function isRuntimeBindingVariableDeclaration(node) {
2199
- return node?.type === "VariableDeclaration" && node.declarations.length === 1 && node.declarations[0].type === "VariableDeclarator" && node.declarations[0].id.type === "ArrayPattern" && isRuntimeBindingArrayExpression(node.declarations[0].init);
2285
+ function patchImportExport(node, exportPlan, cjsDefault) {
2286
+ if (node.type === "ExportNamedDeclaration" && !node.declaration && !node.source && !node.specifiers.length && !node.attributes?.length) return false;
2287
+ if (node.type === "ImportDeclaration" && node.specifiers.length) {
2288
+ for (const specifier of node.specifiers) if (isInfer(specifier.local)) specifier.local.name = "__Infer";
2289
+ }
2290
+ if (is.oneOf(node, [
2291
+ "ImportDeclaration",
2292
+ "ExportAllDeclaration",
2293
+ "ExportNamedDeclaration"
2294
+ ])) {
2295
+ if (node.type === "ExportAllDeclaration" && node.source && exportPlan.typeOnlyExportAllSources.has(node.source.value)) node.exportKind = "type";
2296
+ if (node.type === "ExportNamedDeclaration" && exportPlan.typeOnlyNames.size) {
2297
+ for (const spec of node.specifiers) {
2298
+ const name = nameOf(spec.exported);
2299
+ if (exportPlan.typeOnlyNames.has(name)) {
2300
+ if (spec.type === "ExportSpecifier") spec.exportKind = "type";
2301
+ else node.exportKind = "type";
2302
+ }
2303
+ }
2304
+ normalizeTypeOnlyExport(node);
2305
+ }
2306
+ if (node.source?.value && RE_DTS.test(node.source.value)) {
2307
+ node.source.value = filename_dts_to(node.source.value, "js");
2308
+ return node;
2309
+ }
2310
+ if (cjsDefault && exportPlan.allowExportAssignment && node.type === "ExportNamedDeclaration" && !node.source && node.specifiers.length === 1 && node.specifiers[0].type === "ExportSpecifier" && nameOf(node.specifiers[0].exported) === "default") {
2311
+ const defaultExport = node.specifiers[0];
2312
+ return b.TSExportAssignment({ expression: defaultExport.local });
2313
+ }
2314
+ }
2200
2315
  }
2201
- /**
2202
- * Check if the given node is a {@link RuntimeBindingArrayExpression}
2203
- */
2204
- function isRuntimeBindingArrayExpression(node) {
2205
- return node?.type === "ArrayExpression" && isRuntimeBindingArrayElements(node.elements);
2316
+ function normalizeTypeOnlyExport(node) {
2317
+ if (node.declaration || !node.specifiers.length) return;
2318
+ for (const specifier of node.specifiers) if (specifier.type !== "ExportSpecifier" || specifier.exportKind !== "type") return;
2319
+ node.exportKind = "type";
2320
+ for (const specifier of node.specifiers) if (specifier.type === "ExportSpecifier") specifier.exportKind = "value";
2206
2321
  }
2207
2322
  /**
2208
- * Check if the given array is a {@link RuntimeBindingArrayElements}
2323
+ * Handle `__exportAll` call
2209
2324
  */
2210
- function isRuntimeBindingArrayElements(elements) {
2211
- const [declarationId, deps, children, effect] = elements;
2212
- return is.NumericLiteral(declarationId) && deps?.type === "ArrowFunctionExpression" && children?.type === "ArrayExpression" && (!effect || effect.type === "CallExpression");
2213
- }
2214
- function runtimeBindingArrayExpression(elements) {
2215
- return b.ArrayExpression({ elements: [...elements] });
2216
- }
2217
- function isThisExpression(node) {
2218
- return is.Identifier(node, "this") || node.type === "ThisExpression" || node.type === "MemberExpression" && isThisExpression(node.object);
2219
- }
2220
- function isInfer(node) {
2221
- return is.Identifier(node, "infer");
2222
- }
2223
- function TSEntityNameToRuntime(node) {
2224
- if (node.type === "Identifier" || node.type === "ThisExpression") return node;
2225
- const left = TSEntityNameToRuntime(node.left);
2226
- return Object.assign(node, {
2227
- type: "MemberExpression",
2228
- object: left,
2229
- property: node.right,
2230
- computed: false
2231
- });
2232
- }
2233
- function getIdFromTSEntityName(node) {
2234
- if (node.type === "Identifier" || node.type === "ThisExpression") return node;
2235
- return getIdFromTSEntityName(node.left);
2236
- }
2237
- function isReferenceId(node) {
2238
- return is.oneOf(node, ["Identifier", "MemberExpression"]);
2325
+ function patchTsNamespace(nodes) {
2326
+ const removed = /* @__PURE__ */ new Set();
2327
+ for (const [i, node] of nodes.entries()) {
2328
+ const result = getExportAllNamespace(node);
2329
+ if (!result) continue;
2330
+ const [binding, exports] = result;
2331
+ if (!exports.properties.length) continue;
2332
+ const namespaceExport = b.ExportNamedDeclaration({
2333
+ declaration: null,
2334
+ specifiers: exports.properties.filter((property) => property.type === "Property").map((property) => {
2335
+ const local = property.value.body;
2336
+ const exported = property.key;
2337
+ return b.ExportSpecifier({
2338
+ local,
2339
+ exported
2340
+ });
2341
+ }),
2342
+ source: null,
2343
+ attributes: []
2344
+ });
2345
+ nodes[i] = b.TSModuleDeclaration({
2346
+ id: binding,
2347
+ body: b.TSModuleBlock({ body: [namespaceExport] }),
2348
+ kind: "namespace",
2349
+ declare: true,
2350
+ global: false
2351
+ });
2352
+ }
2353
+ return nodes.filter((node) => !removed.has(node));
2239
2354
  }
2240
- function isHelperImport(node) {
2241
- return node.type === "ImportDeclaration" && node.specifiers.length && node.specifiers.every((spec) => spec.type === "ImportSpecifier" && spec.imported.type === "Identifier" && ["__exportAll", "__reExport"].includes(spec.local.name));
2355
+ function getExportAllNamespace(node) {
2356
+ if (node.type !== "VariableDeclaration" || node.declarations.length !== 1 || node.declarations[0].id.type !== "Identifier" || node.declarations[0].init?.type !== "CallExpression" || node.declarations[0].init.callee.type !== "Identifier" || node.declarations[0].init.callee.name !== "__exportAll" || node.declarations[0].init.arguments.length !== 1 || node.declarations[0].init.arguments[0].type !== "ObjectExpression") return false;
2357
+ return [node.declarations[0].id, node.declarations[0].init.arguments[0]];
2242
2358
  }
2243
2359
  /**
2244
- * patch `.d.ts` suffix in import source to `.js`
2360
+ * Handle `__reExport` call
2245
2361
  */
2246
- function patchImportExport(node, exportInfo, cjsDefault) {
2247
- if (node.type === "ExportNamedDeclaration" && !node.declaration && !node.source && !node.specifiers.length && !node.attributes?.length) return false;
2248
- if (node.type === "ImportDeclaration" && node.specifiers.length) {
2249
- for (const specifier of node.specifiers) if (isInfer(specifier.local)) specifier.local.name = "__Infer";
2362
+ function patchReExport(nodes) {
2363
+ const exportsNames = /* @__PURE__ */ new Map();
2364
+ for (const [i, node] of nodes.entries()) if (node.type === "ImportDeclaration" && node.specifiers.length === 1 && node.specifiers[0].type === "ImportSpecifier" && node.specifiers[0].local.type === "Identifier" && node.specifiers[0].local.name.endsWith("_exports")) exportsNames.set(node.specifiers[0].local.name, node.specifiers[0].local.name);
2365
+ else if (node.type === "ExpressionStatement" && node.expression.type === "CallExpression" && is.Identifier(node.expression.callee, "__reExport")) {
2366
+ const args = node.expression.arguments;
2367
+ exportsNames.set(args[0].name, args[1].name);
2368
+ } else if (node.type === "VariableDeclaration" && node.declarations.length === 1 && node.declarations[0].init?.type === "MemberExpression" && node.declarations[0].init.object.type === "Identifier" && exportsNames.has(node.declarations[0].init.object.name)) nodes[i] = b.TSTypeAliasDeclaration({
2369
+ id: b.Identifier({ name: node.declarations[0].id.name }),
2370
+ typeParameters: null,
2371
+ typeAnnotation: b.TSTypeReference({
2372
+ typeName: b.TSQualifiedName({
2373
+ left: b.Identifier({ name: exportsNames.get(node.declarations[0].init.object.name) }),
2374
+ right: b.Identifier({ name: node.declarations[0].init.property.name })
2375
+ }),
2376
+ typeArguments: null
2377
+ }),
2378
+ declare: false
2379
+ });
2380
+ else if (node.type === "ExportNamedDeclaration" && node.specifiers.length === 1 && node.specifiers[0].type === "ExportSpecifier" && node.specifiers[0].local.type === "Identifier" && exportsNames.has(node.specifiers[0].local.name)) node.specifiers[0].local.name = exportsNames.get(node.specifiers[0].local.name);
2381
+ return nodes;
2382
+ }
2383
+ function rewriteImportExport(node, set, appendStmts) {
2384
+ if (node.type === "ImportDeclaration" || node.type === "ExportNamedDeclaration" && !node.declaration) {
2385
+ for (const specifier of node.specifiers) if (specifier.type === "ImportSpecifier") specifier.importKind = "value";
2386
+ else if (specifier.type === "ExportSpecifier") specifier.exportKind = "value";
2387
+ if (node.type === "ImportDeclaration") node.importKind = "value";
2388
+ else if (node.type === "ExportNamedDeclaration") node.exportKind = "value";
2389
+ return true;
2390
+ } else if (node.type === "ExportAllDeclaration") {
2391
+ node.exportKind = "value";
2392
+ return true;
2393
+ } else if (node.type === "TSImportEqualsDeclaration" || node.type === "ExportNamedDeclaration" && node.declaration?.type === "TSImportEqualsDeclaration") {
2394
+ const decl = node.type === "ExportNamedDeclaration" ? node.declaration : node;
2395
+ if (decl.moduleReference.type === "TSExternalModuleReference") {
2396
+ set(b.ImportDeclaration({
2397
+ specifiers: [b.ImportNamespaceSpecifier({ local: decl.id })],
2398
+ source: decl.moduleReference.expression,
2399
+ phase: null,
2400
+ attributes: []
2401
+ }));
2402
+ if (node.type === "ExportNamedDeclaration") appendStmts.push(b.ExportNamedDeclaration({
2403
+ declaration: null,
2404
+ specifiers: [b.ExportSpecifier({
2405
+ local: decl.id,
2406
+ exported: decl.id
2407
+ })],
2408
+ source: null,
2409
+ attributes: []
2410
+ }));
2411
+ return true;
2412
+ }
2413
+ } else if (node.type === "TSExportAssignment" && node.expression.type === "Identifier") {
2414
+ set(b.ExportNamedDeclaration({
2415
+ declaration: null,
2416
+ specifiers: [b.ExportSpecifier({
2417
+ local: node.expression,
2418
+ exported: b.Identifier({ name: "default" })
2419
+ })],
2420
+ source: null,
2421
+ attributes: []
2422
+ }));
2423
+ return true;
2424
+ } else if (node.type === "ExportDefaultDeclaration" && node.declaration.type === "Identifier") {
2425
+ set(b.ExportNamedDeclaration({
2426
+ declaration: null,
2427
+ specifiers: [b.ExportSpecifier({
2428
+ local: node.declaration,
2429
+ exported: b.Identifier({ name: "default" })
2430
+ })],
2431
+ source: null,
2432
+ attributes: []
2433
+ }));
2434
+ return true;
2250
2435
  }
2251
- if (is.oneOf(node, [
2252
- "ImportDeclaration",
2253
- "ExportAllDeclaration",
2254
- "ExportNamedDeclaration"
2255
- ])) {
2256
- if (node.type === "ExportAllDeclaration" && node.source && exportInfo.typeOnlyExportAllSources.has(node.source.value)) node.exportKind = "type";
2257
- if (node.type === "ExportNamedDeclaration" && exportInfo.typeOnlyNames.size) {
2258
- for (const spec of node.specifiers) {
2259
- const name = nameOf(spec.exported);
2260
- if (exportInfo.typeOnlyNames.has(name)) if (spec.type === "ExportSpecifier") spec.exportKind = "type";
2261
- else node.exportKind = "type";
2436
+ return false;
2437
+ }
2438
+ function createFakeJsPlugin({ sourcemap, cjsDefault, sideEffects }) {
2439
+ let declarationIdx = 0;
2440
+ const declarationMap = /* @__PURE__ */ new Map();
2441
+ const commentsMap = /* @__PURE__ */ new Map();
2442
+ const moduleExportsMap = /* @__PURE__ */ new Map();
2443
+ const warnedCjsDtsInputs = /* @__PURE__ */ new Set();
2444
+ return {
2445
+ name: "rolldown-plugin-dts:fake-js",
2446
+ outputOptions(options) {
2447
+ if (options.format === "cjs" || options.format === "commonjs") throw new Error("[rolldown-plugin-dts] Cannot bundle dts files with `cjs` format.");
2448
+ const { chunkFileNames, entryFileNames } = options;
2449
+ return {
2450
+ ...options,
2451
+ sourcemap: options.sourcemap || sourcemap,
2452
+ chunkFileNames(chunk) {
2453
+ const nameTemplate = resolveTemplateFn(chunk.isEntry ? entryFileNames || "[name].js" : chunkFileNames || "[name]-[hash].js", chunk);
2454
+ if (chunk.name.endsWith(".d")) {
2455
+ const renderedNameWithoutD = filename_js_to_dts(replaceTemplateName(nameTemplate, chunk.name.slice(0, -2)));
2456
+ if (RE_DTS.test(renderedNameWithoutD)) return renderedNameWithoutD;
2457
+ const renderedName = filename_js_to_dts(replaceTemplateName(nameTemplate, chunk.name));
2458
+ if (RE_DTS.test(renderedName)) return renderedName;
2459
+ }
2460
+ return nameTemplate;
2461
+ }
2462
+ };
2463
+ },
2464
+ transform: {
2465
+ filter: { id: RE_DTS },
2466
+ handler: transform
2467
+ },
2468
+ renderChunk,
2469
+ generateBundle(options, bundle) {
2470
+ for (const chunk of Object.values(bundle)) {
2471
+ if (!RE_DTS_MAP.test(chunk.fileName)) continue;
2472
+ if (sourcemap) {
2473
+ if (chunk.type === "chunk" || typeof chunk.source !== "string") continue;
2474
+ const map = JSON.parse(chunk.source);
2475
+ map.sourcesContent = void 0;
2476
+ chunk.source = JSON.stringify(map);
2477
+ } else delete bundle[chunk.fileName];
2262
2478
  }
2263
- normalizeTypeOnlyExport(node);
2264
2479
  }
2265
- if (node.source?.value && RE_DTS.test(node.source.value)) {
2266
- node.source.value = filename_dts_to(node.source.value, "js");
2267
- return node;
2480
+ };
2481
+ async function transform(code, id) {
2482
+ let file;
2483
+ try {
2484
+ file = parse$1(code, {
2485
+ lang: "dts",
2486
+ sourceType: "module",
2487
+ attachComments: true
2488
+ });
2489
+ } catch (error) {
2490
+ throw new Error(`Failed to parse ${id}. This may be caused by a syntax error in the declaration file or a bug in the plugin. Please report this issue to https://github.com/sxzz/rolldown-plugin-dts\n${error}`, { cause: error });
2491
+ }
2492
+ const { program } = file;
2493
+ moduleExportsMap.set(id, await collectModuleExports(this, program.body, id));
2494
+ const identifierMap = Object.create(null);
2495
+ if (!warnedCjsDtsInputs.has(id) && program.body.some(isCjsDtsInputSyntax)) {
2496
+ warnedCjsDtsInputs.add(id);
2497
+ this.warn(`${id} uses CommonJS dts syntax. ${RE_NODE_MODULES.test(id) ? `CommonJS dts modules cannot be bundled by rolldown-plugin-dts. Please mark this module as external in your Rolldown config.` : `rolldown-plugin-dts does not support bundling CommonJS dts input.`}`);
2498
+ }
2499
+ const directives = collectReferenceDirectives(file.comments);
2500
+ if (directives.length) commentsMap.set(id, directives);
2501
+ const appendStmts = [];
2502
+ const namespaceStmts = /* @__PURE__ */ new Map();
2503
+ for (const [i, stmt] of program.body.entries()) {
2504
+ const setStmt = (stmt) => program.body[i] = stmt;
2505
+ if (rewriteImportExport(stmt, setStmt, appendStmts)) continue;
2506
+ const sideEffect = stmt.type === "TSModuleDeclaration" && stmt.kind !== "namespace";
2507
+ if (sideEffect && stmt.type === "TSModuleDeclaration" && is.StringLiteral(stmt.id) && stmt.id.value[0] === ".") this.warn(`\`declare module ${JSON.stringify(stmt.id.value)}\` will be kept as-is in the output. Relative module declaration may cause unexpected issues. Found in ${id}.`);
2508
+ const isDefaultExport = stmt.type === "ExportDefaultDeclaration";
2509
+ const isExportDecl = is.oneOf(stmt, ["ExportNamedDeclaration", "ExportDefaultDeclaration"]) && !!stmt.declaration;
2510
+ const decl = isExportDecl ? stmt.declaration : stmt;
2511
+ const setDecl = isExportDecl ? (decl) => stmt.declaration = decl : setStmt;
2512
+ if (decl.type !== "TSDeclareFunction" && !is.Declaration(decl)) continue;
2513
+ if (is.oneOf(decl, [
2514
+ "TSEnumDeclaration",
2515
+ "ClassDeclaration",
2516
+ "FunctionDeclaration",
2517
+ "TSDeclareFunction",
2518
+ "TSModuleDeclaration",
2519
+ "VariableDeclaration"
2520
+ ])) decl.declare = true;
2521
+ const bindings = [];
2522
+ if (decl.type === "VariableDeclaration") bindings.push(...decl.declarations.map((decl) => decl.id));
2523
+ else if ("id" in decl && decl.id) {
2524
+ let binding = decl.id;
2525
+ if (binding.type === "TSQualifiedName") binding = getIdFromTSEntityName(binding);
2526
+ if (sideEffect) binding = b.Identifier({ name: `_${getIdentifierIndex(identifierMap, "")}` });
2527
+ if (binding.type !== "Identifier") throw new Error(`Unexpected ${binding.type} declaration id`);
2528
+ bindings.push(binding);
2529
+ } else {
2530
+ const binding = b.Identifier({ name: "export_default" });
2531
+ bindings.push(binding);
2532
+ decl.id = binding;
2533
+ }
2534
+ const params = collectParams(decl);
2535
+ const childrenSet = /* @__PURE__ */ new Set();
2536
+ const deps = await collectDependencies(this, decl, id, namespaceStmts, childrenSet, identifierMap);
2537
+ const children = Array.from(childrenSet).filter((child) => bindings.every((b) => child !== b));
2538
+ if (decl !== stmt) decl.comments = stmt.comments;
2539
+ const declarationId = registerDeclaration({
2540
+ decl,
2541
+ deps,
2542
+ bindings,
2543
+ params,
2544
+ children,
2545
+ exportType: isDefaultExport ? "default" : isExportDecl ? "named" : void 0,
2546
+ comments: decl.comments && [...decl.comments]
2547
+ });
2548
+ const declarationIdNode = b.Literal({
2549
+ value: declarationId,
2550
+ raw: String(declarationId)
2551
+ });
2552
+ const depsBody = b.ArrayExpression({ elements: deps });
2553
+ const depsNode = b.ArrowFunctionExpression({
2554
+ id: null,
2555
+ generator: false,
2556
+ async: false,
2557
+ params: params.map(({ name }) => b.Identifier({ name })),
2558
+ body: depsBody,
2559
+ expression: true
2560
+ });
2561
+ const childrenNode = b.ArrayExpression({ elements: children.map((node) => b.Literal({
2562
+ value: "",
2563
+ raw: "\"\"",
2564
+ start: node.start,
2565
+ end: node.end
2566
+ })) });
2567
+ const sideEffectNode = sideEffect && b.CallExpression({
2568
+ callee: b.Identifier({ name: "sideEffect" }),
2569
+ arguments: [bindings[0]],
2570
+ optional: false
2571
+ });
2572
+ const runtimeArrayNode = runtimeBindingArrayExpression([
2573
+ declarationIdNode,
2574
+ depsNode,
2575
+ childrenNode,
2576
+ ...sideEffectNode ? [sideEffectNode] : []
2577
+ ]);
2578
+ const runtimeAssignment = b.VariableDeclaration({
2579
+ kind: "var",
2580
+ declarations: [b.VariableDeclarator({
2581
+ id: b.ArrayPattern({ elements: bindings.map((binding) => ({
2582
+ ...binding,
2583
+ typeAnnotation: null
2584
+ })) }),
2585
+ init: runtimeArrayNode
2586
+ })]
2587
+ });
2588
+ if (isDefaultExport) {
2589
+ appendStmts.push(b.ExportNamedDeclaration({
2590
+ declaration: null,
2591
+ specifiers: [b.ExportSpecifier({
2592
+ local: bindings[0],
2593
+ exported: b.Identifier({ name: "default" })
2594
+ })],
2595
+ source: null,
2596
+ attributes: []
2597
+ }));
2598
+ setStmt(runtimeAssignment);
2599
+ } else setDecl(runtimeAssignment);
2600
+ }
2601
+ if (sideEffects) appendStmts.push(b.ExpressionStatement({ expression: b.CallExpression({
2602
+ callee: b.Identifier({ name: "sideEffect" }),
2603
+ arguments: [],
2604
+ optional: false
2605
+ }) }));
2606
+ program.body = [
2607
+ ...Array.from(namespaceStmts.values(), ({ stmt }) => stmt),
2608
+ ...program.body,
2609
+ ...appendStmts
2610
+ ];
2611
+ const result = generate(program, {
2612
+ comments: false,
2613
+ ...sourcemap && { sourceMaps: {
2614
+ source: code,
2615
+ sourceFileName: id
2616
+ } }
2617
+ });
2618
+ return {
2619
+ code: result.code,
2620
+ map: result.map ?? null
2621
+ };
2622
+ }
2623
+ function renderChunk(code, chunk) {
2624
+ if (!RE_DTS.test(chunk.fileName)) return;
2625
+ let file;
2626
+ try {
2627
+ file = parse$1(code, {
2628
+ lang: "ts",
2629
+ sourceType: "module",
2630
+ attachComments: true
2631
+ });
2632
+ } catch (error) {
2633
+ throw new Error(`Failed to parse generated code for chunk ${chunk.fileName}. This may be caused by a bug in the plugin. Please report this issue to https://github.com/sxzz/rolldown-plugin-dts\n${error}`, { cause: error });
2634
+ }
2635
+ const { program } = file;
2636
+ program.body = patchTsNamespace(program.body);
2637
+ program.body = patchReExport(program.body);
2638
+ const exportPlan = planChunkExports(chunk, moduleExportsMap, program.body, getDeclaration, cjsDefault);
2639
+ function renderStatement(node) {
2640
+ if (isHelperImport(node)) return null;
2641
+ if (node.type === "ExpressionStatement") return null;
2642
+ const newNode = patchImportExport(node, exportPlan, cjsDefault);
2643
+ if (newNode || newNode === false) return newNode;
2644
+ if (node.type !== "VariableDeclaration") return node;
2645
+ if (!isRuntimeBindingVariableDeclaration(node)) return null;
2646
+ const decl = node.declarations[0];
2647
+ const [declarationIdNode, depsFn, children] = decl.init.elements;
2648
+ const declarationId = declarationIdNode.value;
2649
+ const declaration = getDeclaration(declarationId);
2650
+ declaration.decl.comments = declaration.comments && [...declaration.comments];
2651
+ if (sourcemap) walk(declaration.decl, { enter(node) {
2652
+ node.start = void 0;
2653
+ node.end = void 0;
2654
+ } });
2655
+ for (const [i, id] of decl.id.elements.entries()) {
2656
+ const transformedBinding = {
2657
+ ...id,
2658
+ typeAnnotation: declaration.bindings[i].typeAnnotation
2659
+ };
2660
+ overwriteNode(declaration.bindings[i], transformedBinding);
2661
+ }
2662
+ if (sourcemap) for (const [i, child] of children.elements.entries()) Object.assign(declaration.children[i], {
2663
+ start: child.start,
2664
+ end: child.end
2665
+ });
2666
+ const transformedParams = depsFn.params;
2667
+ for (const [i, transformedParam] of transformedParams.entries()) {
2668
+ const transformedName = transformedParam.name;
2669
+ for (const originalTypeParam of declaration.params[i].typeParams) originalTypeParam.name = transformedName;
2670
+ }
2671
+ const transformedDeps = depsFn.body.elements;
2672
+ for (const [i, originalDep] of declaration.deps.entries()) {
2673
+ let transformedDep = transformedDeps[i];
2674
+ if (transformedDep.type === "UnaryExpression" && transformedDep.operator === "void") {
2675
+ const undefinedDep = b.Identifier({ name: "undefined" });
2676
+ undefinedDep.start = transformedDep.start;
2677
+ undefinedDep.end = transformedDep.end;
2678
+ transformedDep = undefinedDep;
2679
+ } else if (isInfer(transformedDep)) transformedDep.name = "__Infer";
2680
+ if (originalDep.replace) originalDep.replace(transformedDep);
2681
+ else Object.assign(originalDep, transformedDep);
2682
+ }
2683
+ const kind = exportPlan.inlineKinds.get(declarationId);
2684
+ return inheritNodeComments(node, kind ? inlineExportDeclaration(declaration.decl, kind) : declaration.decl);
2268
2685
  }
2269
- if (cjsDefault && node.type === "ExportNamedDeclaration" && !node.source && node.specifiers.length === 1 && node.specifiers[0].type === "ExportSpecifier" && nameOf(node.specifiers[0].exported) === "default") {
2270
- const defaultExport = node.specifiers[0];
2271
- return b.TSExportAssignment({ expression: defaultExport.local });
2686
+ const body = [];
2687
+ let danglingComments = [];
2688
+ for (const node of program.body) {
2689
+ const rendered = renderStatement(node);
2690
+ if (rendered === false) {
2691
+ danglingComments.push(...pragmaComments(node));
2692
+ continue;
2693
+ }
2694
+ if (!rendered) continue;
2695
+ if (danglingComments.length) {
2696
+ rendered.comments = [...danglingComments, ...rendered.comments || []];
2697
+ danglingComments = [];
2698
+ }
2699
+ body.push(rendered);
2272
2700
  }
2273
- }
2274
- }
2275
- function normalizeTypeOnlyExport(node) {
2276
- if (node.declaration || !node.specifiers.length) return;
2277
- for (const specifier of node.specifiers) if (specifier.type !== "ExportSpecifier" || specifier.exportKind !== "type") return;
2278
- node.exportKind = "type";
2279
- for (const specifier of node.specifiers) if (specifier.type === "ExportSpecifier") specifier.exportKind = "value";
2280
- }
2281
- /**
2282
- * Handle `__exportAll` call
2283
- */
2284
- function patchTsNamespace(nodes) {
2285
- const removed = /* @__PURE__ */ new Set();
2286
- for (const [i, node] of nodes.entries()) {
2287
- const result = getExportAllNamespace(node);
2288
- if (!result) continue;
2289
- const [binding, exports] = result;
2290
- if (!exports.properties.length) continue;
2291
- const namespaceExport = b.ExportNamedDeclaration({
2701
+ const lastNode = body.at(-1);
2702
+ if (danglingComments.length && lastNode) lastNode.comments = [...lastNode.comments || [], ...danglingComments.map((comment) => ({
2703
+ ...comment,
2704
+ position: "after",
2705
+ sameLine: false
2706
+ }))];
2707
+ program.body = body;
2708
+ if (program.body.length === 0) return {
2709
+ code: EMPTY_STUB,
2710
+ map: null
2711
+ };
2712
+ if (!program.body.some(isModuleStatement)) program.body.push(b.ExportNamedDeclaration({
2292
2713
  declaration: null,
2293
- specifiers: exports.properties.filter((property) => property.type === "Property").map((property) => {
2294
- const local = property.value.body;
2295
- const exported = property.key;
2296
- return b.ExportSpecifier({
2297
- local,
2298
- exported
2299
- });
2300
- }),
2714
+ specifiers: [],
2301
2715
  source: null,
2302
2716
  attributes: []
2717
+ }));
2718
+ const comments = /* @__PURE__ */ new Set();
2719
+ const commentsValue = /* @__PURE__ */ new Set();
2720
+ for (const id of chunk.moduleIds) {
2721
+ const preserveComments = commentsMap.get(id);
2722
+ if (preserveComments) {
2723
+ preserveComments.forEach((c) => {
2724
+ const id = c.type + c.value;
2725
+ if (commentsValue.has(id)) return;
2726
+ commentsValue.add(id);
2727
+ comments.add(c);
2728
+ });
2729
+ commentsMap.delete(id);
2730
+ }
2731
+ }
2732
+ if (comments.size) {
2733
+ program.body[0].comments ||= [];
2734
+ program.body[0].comments.unshift(...Array.from(comments, (c) => ({
2735
+ type: c.type,
2736
+ value: c.value,
2737
+ position: "before",
2738
+ sameLine: false
2739
+ })));
2740
+ }
2741
+ const result = generate(program, {
2742
+ comments: true,
2743
+ ...sourcemap && { sourceMaps: {
2744
+ source: code,
2745
+ sourceFileName: chunk.fileName
2746
+ } }
2303
2747
  });
2304
- nodes[i] = b.TSModuleDeclaration({
2305
- id: binding,
2306
- body: b.TSModuleBlock({ body: [namespaceExport] }),
2307
- kind: "namespace",
2308
- declare: true,
2309
- global: false
2310
- });
2748
+ return {
2749
+ code: result.code.trimEnd(),
2750
+ map: result.map ?? null
2751
+ };
2311
2752
  }
2312
- return nodes.filter((node) => !removed.has(node));
2313
- }
2314
- function getExportAllNamespace(node) {
2315
- if (node.type !== "VariableDeclaration" || node.declarations.length !== 1 || node.declarations[0].id.type !== "Identifier" || node.declarations[0].init?.type !== "CallExpression" || node.declarations[0].init.callee.type !== "Identifier" || node.declarations[0].init.callee.name !== "__exportAll" || node.declarations[0].init.arguments.length !== 1 || node.declarations[0].init.arguments[0].type !== "ObjectExpression") return false;
2316
- return [node.declarations[0].id, node.declarations[0].init.arguments[0]];
2317
- }
2318
- /**
2319
- * Handle `__reExport` call
2320
- */
2321
- function patchReExport(nodes) {
2322
- const exportsNames = /* @__PURE__ */ new Map();
2323
- for (const [i, node] of nodes.entries()) if (node.type === "ImportDeclaration" && node.specifiers.length === 1 && node.specifiers[0].type === "ImportSpecifier" && node.specifiers[0].local.type === "Identifier" && node.specifiers[0].local.name.endsWith("_exports")) exportsNames.set(node.specifiers[0].local.name, node.specifiers[0].local.name);
2324
- else if (node.type === "ExpressionStatement" && node.expression.type === "CallExpression" && is.Identifier(node.expression.callee, "__reExport")) {
2325
- const args = node.expression.arguments;
2326
- exportsNames.set(args[0].name, args[1].name);
2327
- } else if (node.type === "VariableDeclaration" && node.declarations.length === 1 && node.declarations[0].init?.type === "MemberExpression" && node.declarations[0].init.object.type === "Identifier" && exportsNames.has(node.declarations[0].init.object.name)) nodes[i] = b.TSTypeAliasDeclaration({
2328
- id: b.Identifier({ name: node.declarations[0].id.name }),
2329
- typeParameters: null,
2330
- typeAnnotation: b.TSTypeReference({
2331
- typeName: b.TSQualifiedName({
2332
- left: b.Identifier({ name: exportsNames.get(node.declarations[0].init.object.name) }),
2333
- right: b.Identifier({ name: node.declarations[0].init.property.name })
2334
- }),
2335
- typeArguments: null
2336
- }),
2337
- declare: false
2338
- });
2339
- else if (node.type === "ExportNamedDeclaration" && node.specifiers.length === 1 && node.specifiers[0].type === "ExportSpecifier" && node.specifiers[0].local.type === "Identifier" && exportsNames.has(node.specifiers[0].local.name)) node.specifiers[0].local.name = exportsNames.get(node.specifiers[0].local.name);
2340
- return nodes;
2341
- }
2342
- function rewriteImportExport(node, set) {
2343
- if (node.type === "ImportDeclaration" || node.type === "ExportNamedDeclaration" && !node.declaration) {
2344
- for (const specifier of node.specifiers) if (specifier.type === "ImportSpecifier") specifier.importKind = "value";
2345
- else if (specifier.type === "ExportSpecifier") specifier.exportKind = "value";
2346
- if (node.type === "ImportDeclaration") node.importKind = "value";
2347
- else if (node.type === "ExportNamedDeclaration") node.exportKind = "value";
2348
- return true;
2349
- } else if (node.type === "ExportAllDeclaration") {
2350
- node.exportKind = "value";
2351
- return true;
2352
- } else if (node.type === "TSImportEqualsDeclaration") {
2353
- if (node.moduleReference.type === "TSExternalModuleReference") set(b.ImportDeclaration({
2354
- specifiers: [b.ImportDefaultSpecifier({ local: node.id })],
2355
- source: node.moduleReference.expression,
2356
- phase: null,
2357
- attributes: []
2358
- }));
2359
- return true;
2360
- } else if (node.type === "TSExportAssignment" && node.expression.type === "Identifier") {
2361
- set(b.ExportNamedDeclaration({
2362
- declaration: null,
2363
- specifiers: [b.ExportSpecifier({
2364
- local: node.expression,
2365
- exported: b.Identifier({ name: "default" })
2366
- })],
2367
- source: null,
2368
- attributes: []
2369
- }));
2370
- return true;
2371
- } else if (node.type === "ExportDefaultDeclaration" && node.declaration.type === "Identifier") {
2372
- set(b.ExportNamedDeclaration({
2373
- declaration: null,
2374
- specifiers: [b.ExportSpecifier({
2375
- local: node.declaration,
2376
- exported: b.Identifier({ name: "default" })
2377
- })],
2378
- source: null,
2379
- attributes: []
2380
- }));
2381
- return true;
2753
+ function registerDeclaration(info) {
2754
+ const declarationId = declarationIdx++;
2755
+ declarationMap.set(declarationId, info);
2756
+ return declarationId;
2757
+ }
2758
+ function getDeclaration(declarationId) {
2759
+ return declarationMap.get(declarationId);
2382
2760
  }
2383
- return false;
2384
- }
2385
- function overwriteNode(node, newNode) {
2386
- for (const key of Object.keys(node)) Reflect.deleteProperty(node, key);
2387
- Object.assign(node, newNode);
2388
- return node;
2389
- }
2390
- function inheritNodeComments(oldNode, newNode) {
2391
- newNode.comments ||= [];
2392
- const pragmas = oldNode.comments?.filter((comment) => comment.position === "before" && comment.value.startsWith("#") && !isSourceMapPragma(comment));
2393
- if (pragmas) newNode.comments.unshift(...pragmas);
2394
- newNode.comments = newNode.comments.filter((comment) => !REFERENCE_RE.test(comment.value) && !isSourceMapPragma(comment));
2395
- return newNode;
2396
2761
  }
2397
- function getIdentifierIndex(identifierMap, name) {
2398
- if (name in identifierMap) return ++identifierMap[name];
2399
- return identifierMap[name] = 0;
2762
+ function isModuleStatement(node) {
2763
+ return is.oneOf(node, [
2764
+ "ImportDeclaration",
2765
+ "ExportAllDeclaration",
2766
+ "ExportDefaultDeclaration",
2767
+ "ExportNamedDeclaration",
2768
+ "TSExportAssignment"
2769
+ ]) || node.type === "TSImportEqualsDeclaration" && node.moduleReference.type === "TSExternalModuleReference";
2400
2770
  }
2401
- const require = createRequire(import.meta.url);
2402
2771
  const debug$3 = createDebug("rolldown-plugin-dts:vue");
2403
2772
  const RE_VUE = /\.vue$/;
2404
- function getVueVolarPlugin() {
2405
- const ts = requireTS(`Vue support requires TypeScript to be installed. Please install \`typescript\` package.`);
2773
+ function createVueLanguage(userOptions = {}) {
2774
+ requireTSApi("Vue");
2406
2775
  const [volarTypeScript, vue] = loadVueLanguageTools();
2407
2776
  const getLanguagePlugin = (ts, options) => {
2408
2777
  const $rootDir = options.options.$rootDir;
2409
2778
  const $configRaw = options.options.$configRaw;
2410
2779
  const resolver = new vue.CompilerOptionsResolver(ts, ts.sys.readFile);
2411
- resolver.addConfig($configRaw?.vueCompilerOptions ?? {}, $rootDir);
2780
+ const rawOptions = {
2781
+ ...$configRaw?.vueCompilerOptions,
2782
+ ...userOptions?.vueCompilerOptions
2783
+ };
2784
+ resolver.addConfig(rawOptions, $rootDir);
2412
2785
  const vueOptions = resolver.build();
2413
2786
  return vue.createVueLanguagePlugin(ts, options.options, vueOptions, (id) => id);
2414
2787
  };
@@ -2417,10 +2790,10 @@ function getVueVolarPlugin() {
2417
2790
  tsFileExtensionInfos: [{
2418
2791
  extension: "vue",
2419
2792
  isMixedContent: true,
2420
- scriptKind: ts.ScriptKind.Deferred
2793
+ scriptKind: 7
2421
2794
  }],
2422
2795
  volarTypeScript,
2423
- create(ts, options) {
2796
+ createVolarPlugins(ts, options) {
2424
2797
  return [getLanguagePlugin(ts, options)];
2425
2798
  },
2426
2799
  toTsFilename(id) {
@@ -2435,64 +2808,20 @@ function loadVueLanguageTools() {
2435
2808
  return [require(require.resolve("@volar/typescript", { paths: [vueTscPath] })), require(require.resolve("@vue/language-core", { paths: [vueTscPath] }))];
2436
2809
  } catch (cause) {
2437
2810
  debug$3("vue language tools not found", cause);
2438
- throw new Error("Failed to load vue language tools. Please manually install vue-tsc.", { cause });
2811
+ throw new Error("Failed to load Vue language tools. Please install `vue-tsc` manually.", { cause });
2439
2812
  }
2440
2813
  }
2441
- var VolarContext = class {
2442
- plugins;
2443
- patterns;
2444
- constructor(plugins) {
2445
- this.plugins = plugins;
2446
- this.patterns = plugins.flatMap((plugin) => plugin.extensionPatterns);
2447
- }
2448
- isVolarFile(id) {
2449
- return this.patterns.some((pattern) => pattern.test(id));
2450
- }
2451
- getExtraFileExtensions() {
2452
- if (!this.plugins.length) return;
2453
- return this.plugins.flatMap((plugin) => plugin.tsFileExtensionInfos || []);
2454
- }
2455
- getCreateProgram(ts) {
2456
- if (!this.plugins.length) return ts.createProgram;
2457
- const volarTypeScript = this.plugins.find((plugin) => plugin.volarTypeScript)?.volarTypeScript;
2458
- if (!volarTypeScript) return ts.createProgram;
2459
- const { proxyCreateProgram } = volarTypeScript;
2460
- return proxyCreateProgram(ts, ts.createProgram, (ts, options) => {
2461
- const setups = [];
2462
- const plugins = [];
2463
- for (const plugin of this.plugins) {
2464
- if (!plugin.create) continue;
2465
- const result = plugin.create(ts, options);
2466
- if (Array.isArray(result)) plugins.push(...result);
2467
- else {
2468
- if (result.setup) setups.push(result.setup);
2469
- plugins.push(...result.languagePlugins);
2470
- }
2471
- }
2472
- return {
2473
- setup: setups.length ? (language) => {
2474
- for (const setup of setups) setup(language);
2475
- } : void 0,
2476
- languagePlugins: plugins
2477
- };
2478
- });
2479
- }
2480
- toTsFilename(id) {
2481
- for (const plugin of this.plugins) if (plugin.toTsFilename && plugin.extensionPatterns.some((pattern) => pattern.test(id))) return plugin.toTsFilename(id);
2482
- return id;
2483
- }
2484
- };
2485
2814
  const debug$2 = createDebug("rolldown-plugin-dts:options");
2486
2815
  let warnedTsgo = false;
2487
- function resolveOptions({ generator, entry, cwd = process.cwd(), dtsInput = false, emitDtsOnly = false, tsconfig, tsconfigRaw: overriddenTsconfigRaw = {}, compilerOptions = {}, sourcemap, resolver = "oxc", cjsDefault = false, sideEffects = false, logger = console, volarPlugins, build = false, incremental = false, vue = false, parallel = false, eager = false, newContext = false, emitJs, oxc, tsgo }) {
2816
+ function resolveOptions({ generator, entry, cwd = process.cwd(), dtsInput = false, emitDtsOnly = false, tsconfig, tsconfigRaw: overriddenTsconfigRaw = {}, compilerOptions = {}, sourcemap, resolver = "oxc", cjsDefault = false, sideEffects = false, logger = console, customLanguages, build = false, incremental = false, vue = false, parallel = false, eager = false, newContext = false, emitJs, oxc, tsgo }) {
2488
2817
  let resolvedTsconfig;
2489
2818
  if (tsconfig === true || tsconfig == null) {
2490
- const { config, path } = at(cwd) || {};
2819
+ const { config, path } = mt(cwd) || {};
2491
2820
  tsconfig = path;
2492
2821
  resolvedTsconfig = config;
2493
2822
  } else if (typeof tsconfig === "string") {
2494
2823
  tsconfig = path.resolve(cwd || process.cwd(), tsconfig);
2495
- resolvedTsconfig = ee(tsconfig).config;
2824
+ resolvedTsconfig = te(tsconfig).config;
2496
2825
  } else tsconfig = void 0;
2497
2826
  compilerOptions = {
2498
2827
  ...resolvedTsconfig?.compilerOptions,
@@ -2506,32 +2835,36 @@ function resolveOptions({ generator, entry, cwd = process.cwd(), dtsInput = fals
2506
2835
  ...overriddenTsconfigRaw,
2507
2836
  compilerOptions
2508
2837
  };
2509
- volarPlugins ||= [];
2510
- if (vue) volarPlugins.push(getVueVolarPlugin());
2511
- if (volarPlugins.length) {
2512
- if (isTS70Installed()) throw new Error("TypeScript 7.0 does not yet have a stable API and is experimental. The `vue` and `volarPlugins` options are not yet supported with TypeScript 7.0.");
2513
- if (generator && generator !== "tsc") logger.warn("The `vue` and `volarPlugins` options are enabled, which requires the `tsc` generator. The `generator` option is ignored.");
2514
- generator = "tsc";
2515
- }
2516
- const volarContext = new VolarContext(volarPlugins);
2517
- if (!generator) if (tsgo) generator = "tsgo";
2518
- else if (oxc || compilerOptions?.isolatedDeclarations) generator = "oxc";
2519
- else if (isTS70Installed()) generator = "tsgo";
2520
- else generator = "tsc";
2521
- if (generator === "tsc") requireTS("Or enable `isolatedDeclarations` in your `tsconfig.json` to use Oxc instead.");
2838
+ customLanguages ||= [];
2839
+ if (vue) customLanguages.push(createVueLanguage(typeof vue === "object" ? vue : {}));
2840
+ const languageContext = new LanguageContext(customLanguages);
2841
+ if (customLanguages.length) {
2842
+ if (languageContext.isUsingVolar()) {
2843
+ requireTSApi("custom languages", ". Custom languages (including the `vue` option) require the TypeScript API.");
2844
+ if (generator && generator !== "tsc") throw new Error("Volar-based custom languages (including the `vue` option) require the `tsc` generator.");
2845
+ generator = "tsc";
2846
+ } else if (generator === "tsgo") throw new Error("The `tsgo` generator does not support custom languages.");
2847
+ }
2848
+ if (!generator) {
2849
+ if (compilerOptions.isolatedDeclarations) generator = "oxc";
2850
+ else if (isTS70Installed()) {
2851
+ if (customLanguages.length) throw new Error("TypeScript 7.0 is installed, but the `tsgo` generator does not support custom languages. Enable `isolatedDeclarations` or set `generator: 'oxc'` to use Oxc instead, or install TypeScript 6.0 or below.");
2852
+ generator = "tsgo";
2853
+ } else generator = "tsc";
2854
+ }
2855
+ oxc ||= {};
2856
+ tsgo ||= {};
2857
+ if (generator === "tsc") requireTSApi("tsc", ", or enable `isolatedDeclarations` in your `tsconfig.json` to use Oxc instead.");
2522
2858
  else if (generator === "tsgo") {
2523
- if (!tsconfig) throw new Error("tsgo generator requires a tsconfig file to be specified.");
2859
+ if (!tsconfig) throw new Error("The `tsgo` generator requires a tsconfig file to be specified.");
2524
2860
  if (!warnedTsgo) {
2525
2861
  warnedTsgo = true;
2526
2862
  logger.warn("TypeScript 7.0 does not yet have a stable API and is experimental. Some options will be unavailable.");
2527
2863
  }
2864
+ tsgo.path ??= resolveTsgoPath(logger);
2528
2865
  }
2529
- if (oxc === true || !oxc) oxc = {};
2530
- if (oxc) {
2531
- oxc.stripInternal ??= !!compilerOptions?.stripInternal;
2532
- oxc.sourcemap = !!compilerOptions.declarationMap;
2533
- }
2534
- if (tsgo === true || !tsgo) tsgo = {};
2866
+ oxc.stripInternal ??= !!compilerOptions.stripInternal;
2867
+ oxc.sourcemap = !!compilerOptions.declarationMap;
2535
2868
  emitJs ??= !!(compilerOptions.checkJs || compilerOptions.allowJs);
2536
2869
  const resolved = {
2537
2870
  generator,
@@ -2551,7 +2884,7 @@ function resolveOptions({ generator, entry, cwd = process.cwd(), dtsInput = fals
2551
2884
  eager,
2552
2885
  newContext,
2553
2886
  emitJs,
2554
- volarContext,
2887
+ languageContext,
2555
2888
  oxc,
2556
2889
  tsgo,
2557
2890
  logger
@@ -2560,9 +2893,9 @@ function resolveOptions({ generator, entry, cwd = process.cwd(), dtsInput = fals
2560
2893
  return resolved;
2561
2894
  }
2562
2895
  const debug$1 = createDebug("rolldown-plugin-dts:resolver");
2563
- function createDtsResolvePlugin({ cwd, tsconfig, tsconfigRaw, resolver, sideEffects, volarContext }) {
2896
+ function createDtsResolvePlugin({ cwd, tsconfig, tsconfigRaw, resolver, sideEffects, languageContext }) {
2564
2897
  function isSourceFile(id) {
2565
- return RE_TS.test(id) || RE_JSON.test(id) || volarContext.isVolarFile(id);
2898
+ return RE_TS.test(id) || RE_JSON.test(id) || languageContext.isCustomLanguageFile(id);
2566
2899
  }
2567
2900
  const baseDtsResolver = createResolver({
2568
2901
  tsconfig,
@@ -2609,7 +2942,7 @@ function createDtsResolvePlugin({ cwd, tsconfig, tsconfigRaw, resolver, sideEffe
2609
2942
  debug$1("Resolving dts import to source file:", id);
2610
2943
  await this.load({ id: dtsResolution });
2611
2944
  return {
2612
- id: filename_to_dts(dtsResolution, volarContext),
2945
+ id: filename_to_dts(dtsResolution, languageContext),
2613
2946
  moduleSideEffects
2614
2947
  };
2615
2948
  }
@@ -2619,7 +2952,7 @@ function createDtsResolvePlugin({ cwd, tsconfig, tsconfigRaw, resolver, sideEffe
2619
2952
  async function resolveDtsPath(id, importer, rolldownResolution) {
2620
2953
  let dtsPath;
2621
2954
  if (resolver === "tsc") {
2622
- const { tscResolve } = await import("./resolver-cwLsPb2o-Bb9SDBm6.js");
2955
+ const { tscResolve } = await import("./resolver-DE0_sy8o-ZQqHQjRu.js");
2623
2956
  dtsPath = tscResolve(id, importer, cwd, tsconfig, tsconfigRaw);
2624
2957
  } else dtsPath = baseDtsResolver(id, importer);
2625
2958
  debug$1("Using %s for dts import: %O -> %O", resolver, id, dtsPath);
@@ -2646,4 +2979,4 @@ function dts(options = {}) {
2646
2979
  return plugins;
2647
2980
  }
2648
2981
  //#endregion
2649
- export { dts, globalContext as n, requireTS as t };
2982
+ export { dts, globalContext as n, requireTSApi as t };