@voidzero-dev/vite-plus-core 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/LICENSE +36 -177
  2. package/dist/rolldown/cli.mjs +33 -29
  3. package/dist/rolldown/config.d.mts +3 -3
  4. package/dist/rolldown/config.mjs +2 -2
  5. package/dist/rolldown/experimental-index.d.mts +29 -29
  6. package/dist/rolldown/experimental-index.mjs +8 -8
  7. package/dist/rolldown/experimental-runtime-types.d.ts +39 -7
  8. package/dist/rolldown/experimental-runtime.d.ts +39 -7
  9. package/dist/rolldown/experimental-runtime.mjs +284 -255
  10. package/dist/rolldown/filter-index.d.mts +1 -1
  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 +3 -3
  15. package/dist/rolldown/parse-ast-index.d.mts +6 -7
  16. package/dist/rolldown/parse-ast-index.mjs +1 -1
  17. package/dist/rolldown/plugins-index.d.mts +5 -5
  18. package/dist/rolldown/plugins-index.mjs +2 -2
  19. package/dist/rolldown/shared/{binding-BY0qR5iS.mjs → binding-DlR5d34p.mjs} +27 -28
  20. package/dist/rolldown/shared/{binding-BTa6BPQe.d.mts → binding-tzp6Hc_3.d.mts} +1 -1
  21. package/dist/rolldown/shared/{bindingify-input-options-B8JHmN6_.mjs → bindingify-input-options-DhjlrWZE.mjs} +203 -20
  22. package/dist/rolldown/shared/{constructors-xEvVj3lN.mjs → constructors-B2hkJoIA.mjs} +1 -1
  23. package/dist/rolldown/shared/{constructors-DuOq7MqW.d.mts → constructors-Dw9H1IvX.d.mts} +2 -2
  24. package/dist/rolldown/shared/{create-bundler-option-COco-7P6.mjs → create-bundler-option-1AEe_J0o.mjs} +36 -10
  25. package/dist/rolldown/shared/{define-config-C7HCoqY8.d.mts → define-config-CGhm2DU-.d.mts} +94 -5
  26. package/dist/rolldown/shared/{error-C7pxws0W.mjs → error-Dsqzw0Oa.mjs} +2 -1
  27. package/dist/rolldown/shared/{load-config-DkUBnDsI.mjs → load-config-bvw8z7Ft.mjs} +2 -2
  28. package/dist/rolldown/shared/{normalize-string-or-regex-F14uvr6D.mjs → normalize-string-or-regex-B7Gsiuz7.mjs} +1 -1
  29. package/dist/rolldown/shared/{parse-BWeE7Vr9.mjs → parse-BCSSrLHf.mjs} +2 -2
  30. package/dist/rolldown/shared/{resolve-tsconfig-DHwpIs5e.mjs → resolve-tsconfig-DyR2RUTm.mjs} +2 -2
  31. package/dist/rolldown/shared/{rolldown-Bue0gNT5.mjs → rolldown-C8QomUuX.mjs} +4 -4
  32. package/dist/rolldown/shared/{transform-DK_nCt9j.d.mts → transform-D4RDjIPI.d.mts} +1 -1
  33. package/dist/rolldown/shared/{watch-RXhXN1aG.mjs → watch-CPI70Lkn.mjs} +4 -4
  34. package/dist/rolldown/utils-index.d.mts +5 -5
  35. package/dist/rolldown/utils-index.mjs +5 -5
  36. package/dist/tsdown/{build-JVmLFaZt-DRlLhpV3.js → build-KEepWO_k-BOsPZ2cH.js} +26 -25
  37. package/dist/tsdown/{debug-CpC4hV25-C-OYr2iI.js → debug-DKTolR2K-BMJOFfj2.js} +4 -5
  38. package/dist/tsdown/{detect-Bg-d8iUV-Du8LljhG.js → detect-DHDepxVX-CpWW52Jd.js} +38 -34
  39. package/dist/tsdown/dist-BebyOHRu.js +6224 -0
  40. package/dist/tsdown/index-types.d.ts +216 -216
  41. package/dist/tsdown/index.js +4 -4
  42. package/dist/tsdown/{main-CyNcZUzu.js → main-Du9xCnhX.js} +105 -19
  43. package/dist/tsdown/npm_entry_picomatch.cjs +36 -25
  44. package/dist/tsdown/{resolver-DE0_sy8o-Bi3xbRxi.js → resolver-DE0_sy8o-DNoi-dFQ.js} +3 -2
  45. package/dist/tsdown/run.js +28 -26
  46. package/dist/tsdown/{src-pN7Bl6zo.js → src-CBWRkeF5.js} +4 -4
  47. package/dist/tsdown/{target-DgdLrXba-DpO9JXxB.js → target-HZbF5Cux-Cmv1LI5D.js} +175 -9
  48. package/dist/tsdown/{tsc-BLb4pSBY.js → tsc-YwU2b8yT.js} +4 -4
  49. package/dist/tsdown/tsdown-css.js +4 -4
  50. package/dist/tsdown/tsdown-exe.js +5 -43
  51. package/dist/vite/client/bundledDevClient.mjs +109 -345
  52. package/dist/vite/client/client.mjs +80 -28
  53. package/dist/vite/node/chunks/build.js +19 -19
  54. package/dist/vite/node/chunks/node.js +5210 -4942
  55. package/dist/vite/node/chunks/postcss-import.js +10 -10
  56. package/dist/vite/node/cli.js +24 -21
  57. package/dist/vite/node/index.d.ts +5 -2
  58. package/dist/vite/node/index.js +1 -2
  59. package/dist/vite/node/internal.js +1 -2
  60. package/dist/vite/node/module-runner.d.ts +1 -0
  61. package/dist/vite/node/module-runner.js +32 -27
  62. package/package.json +46 -30
  63. package/dist/rolldown/experimental-default-runtime.mjs +0 -116
  64. package/dist/rolldown/experimental-runtime-base.mjs +0 -95
  65. package/dist/tsdown/dist-VDcV1Qyy.js +0 -2952
  66. package/dist/tsdown/require-BbBF8Ii0-BDaWJgzA.js +0 -320
  67. package/dist/tsdown/style-DiMP8pYv-DIC5PXeH.js +0 -88
  68. package/dist/tsdown/version-CQ98ZBpL-D6GAHapk.js +0 -169
@@ -1,2952 +0,0 @@
1
- import { C as RE_ROLLDOWN_RUNTIME, D as filename_to_dts, E as filename_js_to_dts, O as replaceTemplateName, S as RE_NODE_MODULES, T as filename_dts_to, _ as RE_CSS, b as RE_JS, k as resolveTemplateFn, v as RE_DTS, w as RE_TS, x as RE_JSON, y as RE_DTS_MAP } from "./version-CQ98ZBpL-D6GAHapk.js";
2
- import { o as mt, s as te } from "./build-JVmLFaZt-DRlLhpV3.js";
3
- import { a as createDebug, i as tryResolve, n as require, r as requireTSApi, t as isTS70Installed } from "./require-BbBF8Ii0-BDaWJgzA.js";
4
- import { createRequire } from "node:module";
5
- import process from "node:process";
6
- import { styleText } from "node:util";
7
- import { fork, spawn } from "node:child_process";
8
- import path, { dirname, extname } from "node:path";
9
- import { existsSync } from "node:fs";
10
- import { access, mkdtemp, readFile, rm } from "node:fs/promises";
11
- import { importerId, include } from "@voidzero-dev/vite-plus-core/rolldown/filter";
12
- import { tmpdir } from "node:os";
13
- import { ResolverFactory, isolatedDeclarationSync } from "@voidzero-dev/vite-plus-core/rolldown/experimental";
14
- import { generate } from "yuku-codegen";
15
- import { parse as parse$1 } from "yuku-parser";
16
- //#region ../../node_modules/.pnpm/rolldown-plugin-dts@0.28.6_@typescript+native-preview@7.0.0-dev.20260605.1_oxc-resolver_d7b1f0f9db662f38e672c8f14bf9ba00/node_modules/rolldown-plugin-dts/dist/tsc-context.mjs
17
- const debug$6 = createDebug("rolldown-plugin-dts:tsc-context");
18
- /** Creates an empty, isolated TypeScript compiler context. */
19
- function createContext() {
20
- return {
21
- programs: [],
22
- files: /* @__PURE__ */ new Map(),
23
- projects: /* @__PURE__ */ new Map()
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
- */
33
- function invalidateContextFile(context, file) {
34
- file = path.resolve(file).replaceAll("\\", "/");
35
- debug$6(`invalidating context file: ${file}`);
36
- context.files.delete(file);
37
- context.programs = context.programs.filter((program) => {
38
- return program.getSourceFiles().every((sourceFile) => sourceFile.fileName !== file);
39
- });
40
- context.projects.clear();
41
- }
42
- /** Shared compiler context used when no explicit context is provided. */
43
- const globalContext = createContext();
44
- //#endregion
45
- //#region ../../node_modules/.pnpm/rolldown-plugin-dts@0.28.6_@typescript+native-preview@7.0.0-dev.20260605.1_oxc-resolver_d7b1f0f9db662f38e672c8f14bf9ba00/node_modules/rolldown-plugin-dts/dist/custom-language-BR14iqr3.mjs
46
- var LanguageContext = class {
47
- languages;
48
- patterns;
49
- constructor(languages) {
50
- this.languages = languages;
51
- this.patterns = languages.flatMap((language) => language.extensionPatterns);
52
- }
53
- isCustomLanguageFile(id) {
54
- return this.patterns.some((pattern) => pattern.test(id));
55
- }
56
- isUsingVolar() {
57
- return this.languages.some((language) => language.volarTypeScript || language.createVolarPlugins);
58
- }
59
- getExtraFileExtensions() {
60
- if (!this.languages.length) return;
61
- return this.languages.flatMap((language) => language.tsFileExtensionInfos || []);
62
- }
63
- /** @internal */
64
- getCreateProgram(ts) {
65
- if (!this.languages.length) return ts.createProgram;
66
- const volarTypeScript = this.languages.find((language) => language.volarTypeScript)?.volarTypeScript;
67
- if (!volarTypeScript) return ts.createProgram;
68
- const { proxyCreateProgram } = volarTypeScript;
69
- return proxyCreateProgram(ts, ts.createProgram, (ts, options) => {
70
- const setups = [];
71
- const plugins = [];
72
- for (const language of this.languages) {
73
- if (!language.createVolarPlugins) continue;
74
- const result = language.createVolarPlugins(ts, options);
75
- if (Array.isArray(result)) plugins.push(...result);
76
- else {
77
- if (result.setup) setups.push(result.setup);
78
- plugins.push(...result.languagePlugins);
79
- }
80
- }
81
- return {
82
- setup: setups.length ? (language) => {
83
- for (const setup of setups) setup(language);
84
- } : void 0,
85
- languagePlugins: plugins
86
- };
87
- });
88
- }
89
- toTsFilename(id) {
90
- for (const language of this.languages) if (language.toTsFilename && language.extensionPatterns.some((pattern) => pattern.test(id))) return language.toTsFilename(id);
91
- return id;
92
- }
93
- };
94
- //#endregion
95
- //#region ../../node_modules/.pnpm/yuku-ast@0.10.2/node_modules/yuku-ast/dist/aliases.js
96
- const ALIAS_GROUPS = {
97
- Expression: [
98
- "Identifier",
99
- "Literal",
100
- "ThisExpression",
101
- "Super",
102
- "ArrayExpression",
103
- "ObjectExpression",
104
- "FunctionExpression",
105
- "ArrowFunctionExpression",
106
- "ClassExpression",
107
- "TaggedTemplateExpression",
108
- "TemplateLiteral",
109
- "MemberExpression",
110
- "CallExpression",
111
- "NewExpression",
112
- "ChainExpression",
113
- "SequenceExpression",
114
- "ParenthesizedExpression",
115
- "BinaryExpression",
116
- "LogicalExpression",
117
- "ConditionalExpression",
118
- "UnaryExpression",
119
- "UpdateExpression",
120
- "AssignmentExpression",
121
- "YieldExpression",
122
- "AwaitExpression",
123
- "ImportExpression",
124
- "MetaProperty",
125
- "TSAsExpression",
126
- "TSSatisfiesExpression",
127
- "TSTypeAssertion",
128
- "TSNonNullExpression",
129
- "TSInstantiationExpression",
130
- "JSXElement",
131
- "JSXFragment"
132
- ],
133
- Statement: [
134
- "ExpressionStatement",
135
- "BlockStatement",
136
- "EmptyStatement",
137
- "DebuggerStatement",
138
- "ReturnStatement",
139
- "LabeledStatement",
140
- "BreakStatement",
141
- "ContinueStatement",
142
- "IfStatement",
143
- "SwitchStatement",
144
- "ThrowStatement",
145
- "TryStatement",
146
- "WhileStatement",
147
- "DoWhileStatement",
148
- "ForStatement",
149
- "ForInStatement",
150
- "ForOfStatement",
151
- "WithStatement",
152
- "FunctionDeclaration",
153
- "ClassDeclaration",
154
- "VariableDeclaration",
155
- "TSDeclareFunction",
156
- "TSTypeAliasDeclaration",
157
- "TSInterfaceDeclaration",
158
- "TSEnumDeclaration",
159
- "TSModuleDeclaration",
160
- "TSImportEqualsDeclaration"
161
- ],
162
- Declaration: [
163
- "FunctionDeclaration",
164
- "ClassDeclaration",
165
- "VariableDeclaration",
166
- "TSDeclareFunction",
167
- "TSTypeAliasDeclaration",
168
- "TSInterfaceDeclaration",
169
- "TSEnumDeclaration",
170
- "TSModuleDeclaration",
171
- "TSImportEqualsDeclaration"
172
- ],
173
- ModuleDeclaration: [
174
- "ImportDeclaration",
175
- "ExportNamedDeclaration",
176
- "ExportDefaultDeclaration",
177
- "ExportAllDeclaration",
178
- "TSExportAssignment",
179
- "TSNamespaceExportDeclaration"
180
- ],
181
- Function: [
182
- "FunctionDeclaration",
183
- "FunctionExpression",
184
- "TSDeclareFunction",
185
- "TSEmptyBodyFunctionExpression",
186
- "ArrowFunctionExpression"
187
- ],
188
- Class: ["ClassDeclaration", "ClassExpression"],
189
- Method: ["MethodDefinition", "TSAbstractMethodDefinition"],
190
- Loop: [
191
- "DoWhileStatement",
192
- "ForInStatement",
193
- "ForOfStatement",
194
- "ForStatement",
195
- "WhileStatement"
196
- ],
197
- Pattern: [
198
- "ArrayPattern",
199
- "ObjectPattern",
200
- "AssignmentPattern",
201
- "RestElement"
202
- ],
203
- JSX: [
204
- "JSXAttribute",
205
- "JSXClosingElement",
206
- "JSXClosingFragment",
207
- "JSXElement",
208
- "JSXEmptyExpression",
209
- "JSXExpressionContainer",
210
- "JSXFragment",
211
- "JSXIdentifier",
212
- "JSXMemberExpression",
213
- "JSXNamespacedName",
214
- "JSXOpeningElement",
215
- "JSXOpeningFragment",
216
- "JSXSpreadAttribute",
217
- "JSXSpreadChild",
218
- "JSXText"
219
- ],
220
- TSType: [
221
- "TSAnyKeyword",
222
- "TSUnknownKeyword",
223
- "TSNeverKeyword",
224
- "TSVoidKeyword",
225
- "TSNullKeyword",
226
- "TSUndefinedKeyword",
227
- "TSStringKeyword",
228
- "TSNumberKeyword",
229
- "TSBigIntKeyword",
230
- "TSBooleanKeyword",
231
- "TSSymbolKeyword",
232
- "TSObjectKeyword",
233
- "TSIntrinsicKeyword",
234
- "TSThisType",
235
- "TSTypeReference",
236
- "TSTypeQuery",
237
- "TSImportType",
238
- "TSLiteralType",
239
- "TSTemplateLiteralType",
240
- "TSArrayType",
241
- "TSIndexedAccessType",
242
- "TSTupleType",
243
- "TSNamedTupleMember",
244
- "TSJSDocNullableType",
245
- "TSJSDocNonNullableType",
246
- "TSJSDocUnknownType",
247
- "TSUnionType",
248
- "TSIntersectionType",
249
- "TSConditionalType",
250
- "TSInferType",
251
- "TSTypeOperator",
252
- "TSParenthesizedType",
253
- "TSFunctionType",
254
- "TSConstructorType",
255
- "TSTypePredicate",
256
- "TSTypeLiteral",
257
- "TSMappedType"
258
- ]
259
- };
260
- Object.keys(ALIAS_GROUPS);
261
- //#endregion
262
- //#region ../../node_modules/.pnpm/yuku-ast@0.10.2/node_modules/yuku-ast/dist/generated.js
263
- const KEYS = Object.create(null);
264
- function ck(type, keys) {
265
- const prev = KEYS[type];
266
- if (prev === void 0) KEYS[type] = keys;
267
- else for (const k of keys) if (!prev.includes(k)) prev.push(k);
268
- }
269
- ck("SequenceExpression", ["expressions"]);
270
- ck("ParenthesizedExpression", ["expression"]);
271
- ck("ArrowFunctionExpression", [
272
- "typeParameters",
273
- "params",
274
- "returnType",
275
- "body"
276
- ]);
277
- ck("FunctionDeclaration", [
278
- "id",
279
- "typeParameters",
280
- "params",
281
- "returnType",
282
- "body"
283
- ]);
284
- ck("FunctionExpression", [
285
- "id",
286
- "typeParameters",
287
- "params",
288
- "returnType",
289
- "body"
290
- ]);
291
- ck("TSDeclareFunction", [
292
- "id",
293
- "typeParameters",
294
- "params",
295
- "returnType",
296
- "body"
297
- ]);
298
- ck("TSEmptyBodyFunctionExpression", [
299
- "id",
300
- "typeParameters",
301
- "params",
302
- "returnType",
303
- "body"
304
- ]);
305
- ck("BlockStatement", ["body"]);
306
- ck("BlockStatement", ["body"]);
307
- ck("BinaryExpression", ["left", "right"]);
308
- ck("LogicalExpression", ["left", "right"]);
309
- ck("ConditionalExpression", [
310
- "test",
311
- "consequent",
312
- "alternate"
313
- ]);
314
- ck("UnaryExpression", ["argument"]);
315
- ck("UpdateExpression", ["argument"]);
316
- ck("AssignmentExpression", ["left", "right"]);
317
- ck("ArrayExpression", ["elements"]);
318
- ck("ObjectExpression", ["properties"]);
319
- ck("SpreadElement", ["argument"]);
320
- ck("Property", ["key", "value"]);
321
- ck("MemberExpression", ["object", "property"]);
322
- ck("CallExpression", [
323
- "callee",
324
- "typeArguments",
325
- "arguments"
326
- ]);
327
- ck("ChainExpression", ["expression"]);
328
- ck("TaggedTemplateExpression", [
329
- "tag",
330
- "typeArguments",
331
- "quasi"
332
- ]);
333
- ck("NewExpression", [
334
- "callee",
335
- "typeArguments",
336
- "arguments"
337
- ]);
338
- ck("AwaitExpression", ["argument"]);
339
- ck("YieldExpression", ["argument"]);
340
- ck("MetaProperty", ["meta", "property"]);
341
- ck("Decorator", ["expression"]);
342
- ck("ClassDeclaration", [
343
- "decorators",
344
- "id",
345
- "typeParameters",
346
- "superClass",
347
- "superTypeArguments",
348
- "implements",
349
- "body"
350
- ]);
351
- ck("ClassExpression", [
352
- "decorators",
353
- "id",
354
- "typeParameters",
355
- "superClass",
356
- "superTypeArguments",
357
- "implements",
358
- "body"
359
- ]);
360
- ck("ClassBody", ["body"]);
361
- ck("MethodDefinition", [
362
- "decorators",
363
- "key",
364
- "value"
365
- ]);
366
- ck("TSAbstractMethodDefinition", [
367
- "decorators",
368
- "key",
369
- "value"
370
- ]);
371
- ck("PropertyDefinition", [
372
- "decorators",
373
- "key",
374
- "typeAnnotation",
375
- "value"
376
- ]);
377
- ck("AccessorProperty", [
378
- "decorators",
379
- "key",
380
- "typeAnnotation",
381
- "value"
382
- ]);
383
- ck("TSAbstractPropertyDefinition", [
384
- "decorators",
385
- "key",
386
- "typeAnnotation",
387
- "value"
388
- ]);
389
- ck("TSAbstractAccessorProperty", [
390
- "decorators",
391
- "key",
392
- "typeAnnotation",
393
- "value"
394
- ]);
395
- ck("StaticBlock", ["body"]);
396
- ck("Super", []);
397
- ck("Literal", []);
398
- ck("Literal", []);
399
- ck("Literal", []);
400
- ck("Literal", []);
401
- ck("Literal", []);
402
- ck("ThisExpression", []);
403
- ck("Literal", []);
404
- ck("TemplateLiteral", ["quasis", "expressions"]);
405
- ck("TemplateElement", []);
406
- ck("Identifier", []);
407
- ck("PrivateIdentifier", []);
408
- ck("Identifier", ["decorators", "typeAnnotation"]);
409
- ck("Identifier", []);
410
- ck("Identifier", []);
411
- ck("ExpressionStatement", ["expression"]);
412
- ck("IfStatement", [
413
- "test",
414
- "consequent",
415
- "alternate"
416
- ]);
417
- ck("SwitchStatement", ["discriminant", "cases"]);
418
- ck("SwitchCase", ["test", "consequent"]);
419
- ck("ForStatement", [
420
- "init",
421
- "test",
422
- "update",
423
- "body"
424
- ]);
425
- ck("ForInStatement", [
426
- "left",
427
- "right",
428
- "body"
429
- ]);
430
- ck("ForOfStatement", [
431
- "left",
432
- "right",
433
- "body"
434
- ]);
435
- ck("WhileStatement", ["test", "body"]);
436
- ck("DoWhileStatement", ["body", "test"]);
437
- ck("BreakStatement", ["label"]);
438
- ck("ContinueStatement", ["label"]);
439
- ck("LabeledStatement", ["label", "body"]);
440
- ck("WithStatement", ["object", "body"]);
441
- ck("ReturnStatement", ["argument"]);
442
- ck("ThrowStatement", ["argument"]);
443
- ck("TryStatement", [
444
- "block",
445
- "handler",
446
- "finalizer"
447
- ]);
448
- ck("CatchClause", ["param", "body"]);
449
- ck("DebuggerStatement", []);
450
- ck("EmptyStatement", []);
451
- ck("VariableDeclaration", ["declarations"]);
452
- ck("VariableDeclarator", ["id", "init"]);
453
- ck("ExpressionStatement", ["expression"]);
454
- ck("AssignmentPattern", [
455
- "decorators",
456
- "left",
457
- "typeAnnotation",
458
- "right"
459
- ]);
460
- ck("RestElement", [
461
- "decorators",
462
- "argument",
463
- "typeAnnotation"
464
- ]);
465
- ck("ArrayPattern", [
466
- "decorators",
467
- "elements",
468
- "typeAnnotation"
469
- ]);
470
- ck("ObjectPattern", [
471
- "decorators",
472
- "properties",
473
- "typeAnnotation"
474
- ]);
475
- ck("Property", ["key", "value"]);
476
- ck("Program", ["hashbang", "body"]);
477
- ck("ImportExpression", ["source", "options"]);
478
- ck("ImportDeclaration", [
479
- "specifiers",
480
- "source",
481
- "attributes"
482
- ]);
483
- ck("ImportSpecifier", ["imported", "local"]);
484
- ck("ImportDefaultSpecifier", ["local"]);
485
- ck("ImportNamespaceSpecifier", ["local"]);
486
- ck("ImportAttribute", ["key", "value"]);
487
- ck("ExportNamedDeclaration", [
488
- "declaration",
489
- "specifiers",
490
- "source",
491
- "attributes"
492
- ]);
493
- ck("ExportDefaultDeclaration", ["declaration"]);
494
- ck("ExportAllDeclaration", [
495
- "exported",
496
- "source",
497
- "attributes"
498
- ]);
499
- ck("ExportSpecifier", ["local", "exported"]);
500
- ck("TSTypeAnnotation", ["typeAnnotation"]);
501
- ck("TSAnyKeyword", []);
502
- ck("TSUnknownKeyword", []);
503
- ck("TSNeverKeyword", []);
504
- ck("TSVoidKeyword", []);
505
- ck("TSNullKeyword", []);
506
- ck("TSUndefinedKeyword", []);
507
- ck("TSStringKeyword", []);
508
- ck("TSNumberKeyword", []);
509
- ck("TSBigIntKeyword", []);
510
- ck("TSBooleanKeyword", []);
511
- ck("TSSymbolKeyword", []);
512
- ck("TSObjectKeyword", []);
513
- ck("TSIntrinsicKeyword", []);
514
- ck("TSThisType", []);
515
- ck("TSTypeReference", ["typeName", "typeArguments"]);
516
- ck("TSQualifiedName", ["left", "right"]);
517
- ck("TSTypeQuery", ["exprName", "typeArguments"]);
518
- ck("TSImportType", [
519
- "source",
520
- "options",
521
- "qualifier",
522
- "typeArguments"
523
- ]);
524
- ck("TSTypeParameter", [
525
- "name",
526
- "constraint",
527
- "default"
528
- ]);
529
- ck("TSTypeParameterDeclaration", ["params"]);
530
- ck("TSTypeParameterInstantiation", ["params"]);
531
- ck("TSLiteralType", ["literal"]);
532
- ck("TSTemplateLiteralType", ["quasis", "types"]);
533
- ck("TSArrayType", ["elementType"]);
534
- ck("TSIndexedAccessType", ["objectType", "indexType"]);
535
- ck("TSTupleType", ["elementTypes"]);
536
- ck("TSNamedTupleMember", ["label", "elementType"]);
537
- ck("TSOptionalType", ["typeAnnotation"]);
538
- ck("TSRestType", ["typeAnnotation"]);
539
- ck("TSJSDocNullableType", ["typeAnnotation"]);
540
- ck("TSJSDocNonNullableType", ["typeAnnotation"]);
541
- ck("TSJSDocUnknownType", []);
542
- ck("TSUnionType", ["types"]);
543
- ck("TSIntersectionType", ["types"]);
544
- ck("TSConditionalType", [
545
- "checkType",
546
- "extendsType",
547
- "trueType",
548
- "falseType"
549
- ]);
550
- ck("TSInferType", ["typeParameter"]);
551
- ck("TSTypeOperator", ["typeAnnotation"]);
552
- ck("TSParenthesizedType", ["typeAnnotation"]);
553
- ck("TSFunctionType", [
554
- "typeParameters",
555
- "params",
556
- "returnType"
557
- ]);
558
- ck("TSConstructorType", [
559
- "typeParameters",
560
- "params",
561
- "returnType"
562
- ]);
563
- ck("TSTypePredicate", ["parameterName", "typeAnnotation"]);
564
- ck("TSTypeLiteral", ["members"]);
565
- ck("TSMappedType", [
566
- "key",
567
- "constraint",
568
- "nameType",
569
- "typeAnnotation"
570
- ]);
571
- ck("TSPropertySignature", ["key", "typeAnnotation"]);
572
- ck("TSMethodSignature", [
573
- "key",
574
- "typeParameters",
575
- "params",
576
- "returnType"
577
- ]);
578
- ck("TSCallSignatureDeclaration", [
579
- "typeParameters",
580
- "params",
581
- "returnType"
582
- ]);
583
- ck("TSConstructSignatureDeclaration", [
584
- "typeParameters",
585
- "params",
586
- "returnType"
587
- ]);
588
- ck("TSIndexSignature", ["parameters", "typeAnnotation"]);
589
- ck("TSTypeAliasDeclaration", [
590
- "id",
591
- "typeParameters",
592
- "typeAnnotation"
593
- ]);
594
- ck("TSInterfaceDeclaration", [
595
- "id",
596
- "typeParameters",
597
- "extends",
598
- "body"
599
- ]);
600
- ck("TSInterfaceBody", ["body"]);
601
- ck("TSInterfaceHeritage", ["expression", "typeArguments"]);
602
- ck("TSClassImplements", ["expression", "typeArguments"]);
603
- ck("TSEnumDeclaration", ["id", "body"]);
604
- ck("TSEnumBody", ["members"]);
605
- ck("TSEnumMember", ["id", "initializer"]);
606
- ck("TSModuleDeclaration", ["id", "body"]);
607
- ck("TSModuleBlock", ["body"]);
608
- ck("TSModuleDeclaration", ["id", "body"]);
609
- ck("TSParameterProperty", ["decorators", "parameter"]);
610
- ck("Identifier", ["typeAnnotation"]);
611
- ck("TSAsExpression", ["expression", "typeAnnotation"]);
612
- ck("TSSatisfiesExpression", ["expression", "typeAnnotation"]);
613
- ck("TSTypeAssertion", ["typeAnnotation", "expression"]);
614
- ck("TSNonNullExpression", ["expression"]);
615
- ck("TSInstantiationExpression", ["expression", "typeArguments"]);
616
- ck("TSExportAssignment", ["expression"]);
617
- ck("TSNamespaceExportDeclaration", ["id"]);
618
- ck("TSImportEqualsDeclaration", ["id", "moduleReference"]);
619
- ck("TSExternalModuleReference", ["expression"]);
620
- ck("JSXElement", [
621
- "openingElement",
622
- "children",
623
- "closingElement"
624
- ]);
625
- ck("JSXOpeningElement", [
626
- "name",
627
- "typeArguments",
628
- "attributes"
629
- ]);
630
- ck("JSXClosingElement", ["name"]);
631
- ck("JSXFragment", [
632
- "openingFragment",
633
- "children",
634
- "closingFragment"
635
- ]);
636
- ck("JSXOpeningFragment", []);
637
- ck("JSXClosingFragment", []);
638
- ck("JSXIdentifier", []);
639
- ck("JSXNamespacedName", ["namespace", "name"]);
640
- ck("JSXMemberExpression", ["object", "property"]);
641
- ck("JSXAttribute", ["name", "value"]);
642
- ck("JSXSpreadAttribute", ["argument"]);
643
- ck("JSXExpressionContainer", ["expression"]);
644
- ck("JSXEmptyExpression", []);
645
- ck("JSXText", []);
646
- ck("JSXSpreadChild", ["expression"]);
647
- ck("Hashbang", []);
648
- const CHILD_KEYS = KEYS;
649
- const NODE_TYPES = [.../* @__PURE__ */ new Set([
650
- "SequenceExpression",
651
- "ParenthesizedExpression",
652
- "ArrowFunctionExpression",
653
- "FunctionDeclaration",
654
- "FunctionExpression",
655
- "TSDeclareFunction",
656
- "TSEmptyBodyFunctionExpression",
657
- "BlockStatement",
658
- "BlockStatement",
659
- "BinaryExpression",
660
- "LogicalExpression",
661
- "ConditionalExpression",
662
- "UnaryExpression",
663
- "UpdateExpression",
664
- "AssignmentExpression",
665
- "ArrayExpression",
666
- "ObjectExpression",
667
- "SpreadElement",
668
- "Property",
669
- "MemberExpression",
670
- "CallExpression",
671
- "ChainExpression",
672
- "TaggedTemplateExpression",
673
- "NewExpression",
674
- "AwaitExpression",
675
- "YieldExpression",
676
- "MetaProperty",
677
- "Decorator",
678
- "ClassDeclaration",
679
- "ClassExpression",
680
- "ClassBody",
681
- "MethodDefinition",
682
- "TSAbstractMethodDefinition",
683
- "PropertyDefinition",
684
- "AccessorProperty",
685
- "TSAbstractPropertyDefinition",
686
- "TSAbstractAccessorProperty",
687
- "StaticBlock",
688
- "Super",
689
- "Literal",
690
- "Literal",
691
- "Literal",
692
- "Literal",
693
- "Literal",
694
- "ThisExpression",
695
- "Literal",
696
- "TemplateLiteral",
697
- "TemplateElement",
698
- "Identifier",
699
- "PrivateIdentifier",
700
- "Identifier",
701
- "Identifier",
702
- "Identifier",
703
- "ExpressionStatement",
704
- "IfStatement",
705
- "SwitchStatement",
706
- "SwitchCase",
707
- "ForStatement",
708
- "ForInStatement",
709
- "ForOfStatement",
710
- "WhileStatement",
711
- "DoWhileStatement",
712
- "BreakStatement",
713
- "ContinueStatement",
714
- "LabeledStatement",
715
- "WithStatement",
716
- "ReturnStatement",
717
- "ThrowStatement",
718
- "TryStatement",
719
- "CatchClause",
720
- "DebuggerStatement",
721
- "EmptyStatement",
722
- "VariableDeclaration",
723
- "VariableDeclarator",
724
- "ExpressionStatement",
725
- "AssignmentPattern",
726
- "RestElement",
727
- "ArrayPattern",
728
- "ObjectPattern",
729
- "Property",
730
- "Program",
731
- "ImportExpression",
732
- "ImportDeclaration",
733
- "ImportSpecifier",
734
- "ImportDefaultSpecifier",
735
- "ImportNamespaceSpecifier",
736
- "ImportAttribute",
737
- "ExportNamedDeclaration",
738
- "ExportDefaultDeclaration",
739
- "ExportAllDeclaration",
740
- "ExportSpecifier",
741
- "TSTypeAnnotation",
742
- "TSAnyKeyword",
743
- "TSUnknownKeyword",
744
- "TSNeverKeyword",
745
- "TSVoidKeyword",
746
- "TSNullKeyword",
747
- "TSUndefinedKeyword",
748
- "TSStringKeyword",
749
- "TSNumberKeyword",
750
- "TSBigIntKeyword",
751
- "TSBooleanKeyword",
752
- "TSSymbolKeyword",
753
- "TSObjectKeyword",
754
- "TSIntrinsicKeyword",
755
- "TSThisType",
756
- "TSTypeReference",
757
- "TSQualifiedName",
758
- "TSTypeQuery",
759
- "TSImportType",
760
- "TSTypeParameter",
761
- "TSTypeParameterDeclaration",
762
- "TSTypeParameterInstantiation",
763
- "TSLiteralType",
764
- "TSTemplateLiteralType",
765
- "TSArrayType",
766
- "TSIndexedAccessType",
767
- "TSTupleType",
768
- "TSNamedTupleMember",
769
- "TSOptionalType",
770
- "TSRestType",
771
- "TSJSDocNullableType",
772
- "TSJSDocNonNullableType",
773
- "TSJSDocUnknownType",
774
- "TSUnionType",
775
- "TSIntersectionType",
776
- "TSConditionalType",
777
- "TSInferType",
778
- "TSTypeOperator",
779
- "TSParenthesizedType",
780
- "TSFunctionType",
781
- "TSConstructorType",
782
- "TSTypePredicate",
783
- "TSTypeLiteral",
784
- "TSMappedType",
785
- "TSPropertySignature",
786
- "TSMethodSignature",
787
- "TSCallSignatureDeclaration",
788
- "TSConstructSignatureDeclaration",
789
- "TSIndexSignature",
790
- "TSTypeAliasDeclaration",
791
- "TSInterfaceDeclaration",
792
- "TSInterfaceBody",
793
- "TSInterfaceHeritage",
794
- "TSClassImplements",
795
- "TSEnumDeclaration",
796
- "TSEnumBody",
797
- "TSEnumMember",
798
- "TSModuleDeclaration",
799
- "TSModuleBlock",
800
- "TSModuleDeclaration",
801
- "TSParameterProperty",
802
- "Identifier",
803
- "TSAsExpression",
804
- "TSSatisfiesExpression",
805
- "TSTypeAssertion",
806
- "TSNonNullExpression",
807
- "TSInstantiationExpression",
808
- "TSExportAssignment",
809
- "TSNamespaceExportDeclaration",
810
- "TSImportEqualsDeclaration",
811
- "TSExternalModuleReference",
812
- "JSXElement",
813
- "JSXOpeningElement",
814
- "JSXClosingElement",
815
- "JSXFragment",
816
- "JSXOpeningFragment",
817
- "JSXClosingFragment",
818
- "JSXIdentifier",
819
- "JSXNamespacedName",
820
- "JSXMemberExpression",
821
- "JSXAttribute",
822
- "JSXSpreadAttribute",
823
- "JSXExpressionContainer",
824
- "JSXEmptyExpression",
825
- "JSXText",
826
- "JSXSpreadChild",
827
- "Hashbang"
828
- ])];
829
- //#endregion
830
- //#region ../../node_modules/.pnpm/yuku-ast@0.10.2/node_modules/yuku-ast/dist/builders.js
831
- /**
832
- * One constructor per node type, its fields derived from the node type
833
- * itself. `start` and `end` default to 0, which `ctx.replace` treats
834
- * as span-less and fills from the replaced node.
835
- *
836
- * @example
837
- * b.Identifier({ name: "x" })
838
- * b.ExpressionStatement({ expression: b.Identifier({ name: "x" }) })
839
- */
840
- const b = Object.fromEntries(NODE_TYPES.map((type) => [type, (fields) => ({
841
- type,
842
- start: 0,
843
- end: 0,
844
- ...fields
845
- })]));
846
- //#endregion
847
- //#region ../../node_modules/.pnpm/yuku-ast@0.10.2/node_modules/yuku-ast/dist/context.js
848
- /**
849
- * The walk context: one reused object exposing the current position and
850
- * the tree mutation operations. Valid only during the visit that
851
- * receives it, do not store it. Underscore members are engine state.
852
- */
853
- var WalkContext = class {
854
- _ancestors = [];
855
- _node = null;
856
- _key = null;
857
- _list = null;
858
- _frame = null;
859
- _skip = false;
860
- _stopped = false;
861
- _removed = false;
862
- _replacement = null;
863
- /** State threaded through the walk, the third `walk` argument. */
864
- state;
865
- /** The node being visited. */
866
- get node() {
867
- return this._node;
868
- }
869
- /** The node holding {@link node}, or null at the walk root. */
870
- get parent() {
871
- const a = this._ancestors;
872
- return a.length === 0 ? null : a[a.length - 1];
873
- }
874
- /** The field on {@link parent} holding {@link node}, or null at the root. */
875
- get key() {
876
- return this._key;
877
- }
878
- /** Index within an array field, or null in a plain field. */
879
- get index() {
880
- return this._list === null ? null : this._frame.i;
881
- }
882
- /** Ancestors from the walk root down to {@link parent}. */
883
- ancestors() {
884
- return [...this._ancestors];
885
- }
886
- /** Do not descend into the current node's children. */
887
- skip() {
888
- this._skip = true;
889
- }
890
- /** Stop the walk entirely. */
891
- stop() {
892
- this._stopped = true;
893
- }
894
- /**
895
- * Replace the current node. The walk continues into the replacement's
896
- * children and `leave` fires for the replacement's type. A synthetic
897
- * node with `start === 0 && end === 0` inherits the original span,
898
- * for source maps. Throws at the walk root.
899
- */
900
- replace(node) {
901
- if (node === null || typeof node !== "object" || typeof node.type !== "string") throw new TypeError("replace: expected an AST node");
902
- if (this.parent === null) throw new TypeError("replace: cannot replace the walk root");
903
- if (node.start === 0 && node.end === 0) {
904
- node.start = this.node.start;
905
- node.end = this.node.end;
906
- }
907
- this._replacement = node;
908
- }
909
- /**
910
- * Remove the current node from its parent: spliced from array fields,
911
- * nulled in plain fields. Children are not walked and `leave` does
912
- * not fire. Throws at the walk root.
913
- */
914
- remove() {
915
- if (this.parent === null) throw new TypeError("remove: cannot remove the walk root");
916
- this._removed = true;
917
- }
918
- /** Insert a sibling before the current node, not visited. Array fields only. */
919
- insertBefore(node) {
920
- this.#insert(node, 0);
921
- this._frame.i++;
922
- }
923
- /** Insert a sibling after the current node, visited by the walk. Array fields only. */
924
- insertAfter(node) {
925
- this.#insert(node, 1);
926
- }
927
- #insert(node, offset) {
928
- if (this._list === null) throw new TypeError("insertBefore/insertAfter require a node in an array field");
929
- this._list.splice(this._frame.i + offset, 0, node);
930
- }
931
- };
932
- //#endregion
933
- //#region ../../node_modules/.pnpm/yuku-ast@0.10.2/node_modules/yuku-ast/dist/identifier.js
934
- const IDENTIFIER_NAME = /^[$_\p{ID_Start}][$\u200C\u200D\p{ID_Continue}]*$/u;
935
- /**
936
- * True if `name` is a valid ECMAScript `IdentifierName`, the grammar an
937
- * identifier token must satisfy. Validates a raw string, not a node.
938
- * Reserved words are syntactically identifier names, so
939
- * `isIdentifierName("class")` is true, see {@link isValidIdentifier}.
940
- */
941
- function isIdentifierName(name) {
942
- return IDENTIFIER_NAME.test(name);
943
- }
944
- //#endregion
945
- //#region ../../node_modules/.pnpm/yuku-ast@0.10.2/node_modules/yuku-ast/dist/is.js
946
- function aliasGuard(name) {
947
- const set = new Set(ALIAS_GROUPS[name]);
948
- return (node) => node != null && set.has(node.type);
949
- }
950
- /**
951
- * Type guards, one per concrete node `type` plus alias and shape
952
- * guards. Every guard accepts `null` and `undefined` and narrows.
953
- *
954
- * @example
955
- * is.CallExpression(node)
956
- * is.Identifier(node, "require")
957
- * is.Expression(node)
958
- * is.StringLiteral(node)
959
- */
960
- const is = {
961
- ...Object.fromEntries(NODE_TYPES.map((type) => [type, (node) => node != null && node.type === type])),
962
- /** True when `node.type` is one of `types`, narrowing to that union. */
963
- oneOf: (node, types) => node != null && types.some((type) => type === node.type),
964
- /** An `Identifier`, optionally with the exact `name`. */
965
- Identifier: (node, name) => node?.type === "Identifier" && (name === void 0 || node.name === name),
966
- Expression: aliasGuard("Expression"),
967
- Statement: aliasGuard("Statement"),
968
- Declaration: aliasGuard("Declaration"),
969
- ModuleDeclaration: aliasGuard("ModuleDeclaration"),
970
- Function: aliasGuard("Function"),
971
- Class: aliasGuard("Class"),
972
- Method: aliasGuard("Method"),
973
- Loop: aliasGuard("Loop"),
974
- Pattern: aliasGuard("Pattern"),
975
- JSX: aliasGuard("JSX"),
976
- TSType: aliasGuard("TSType"),
977
- StringLiteral: (node) => node?.type === "Literal" && typeof node.value === "string",
978
- NumericLiteral: (node) => node?.type === "Literal" && typeof node.value === "number",
979
- BooleanLiteral: (node) => node?.type === "Literal" && typeof node.value === "boolean",
980
- NullLiteral: (node) => node?.type === "Literal" && node.raw === "null",
981
- BigIntLiteral: (node) => node?.type === "Literal" && "bigint" in node,
982
- RegExpLiteral: (node) => node?.type === "Literal" && "regex" in node,
983
- ComputedMemberExpression: (node) => node?.type === "MemberExpression" && node.computed,
984
- StaticMemberExpression: (node) => node?.type === "MemberExpression" && !node.computed && node.property.type === "Identifier",
985
- PrivateFieldExpression: (node) => node?.type === "MemberExpression" && node.property.type === "PrivateIdentifier",
986
- Directive: (node) => node?.type === "ExpressionStatement" && node.directive != null
987
- };
988
- //#endregion
989
- //#region ../../node_modules/.pnpm/yuku-ast@0.10.2/node_modules/yuku-ast/dist/walk.js
990
- function createDispatch(visitors) {
991
- let enter = null;
992
- let leave = null;
993
- const concrete = /* @__PURE__ */ new Map();
994
- const add = (type, handler) => {
995
- const hooks = typeof handler === "function" ? { enter: handler } : handler;
996
- let entry = concrete.get(type);
997
- if (entry === void 0) {
998
- entry = {
999
- enter: [],
1000
- leave: []
1001
- };
1002
- concrete.set(type, entry);
1003
- }
1004
- if (hooks.enter) entry.enter.push(hooks.enter);
1005
- if (hooks.leave) entry.leave.unshift(hooks.leave);
1006
- };
1007
- for (const [name, value] of Object.entries(visitors)) {
1008
- if (value == null) continue;
1009
- if (name === "enter") enter = value;
1010
- else if (name === "leave") leave = value;
1011
- else if (name in ALIAS_GROUPS) for (const type of ALIAS_GROUPS[name]) add(type, value);
1012
- }
1013
- for (const [name, value] of Object.entries(visitors)) {
1014
- if (value == null || name === "enter" || name === "leave" || name in ALIAS_GROUPS) continue;
1015
- add(name, value);
1016
- }
1017
- return {
1018
- enter,
1019
- leave,
1020
- typed: (type) => concrete.get(type)
1021
- };
1022
- }
1023
- /**
1024
- * Walk an AST depth-first, dispatching to typed visitors and mutating
1025
- * in place. Traversal order is driven by tables generated from the
1026
- * parser's AST definition, so it can never drift. Returns the root.
1027
- */
1028
- function walk(root, visitors, state) {
1029
- _walk(root, visitors, state, new WalkContext());
1030
- return root;
1031
- }
1032
- /**
1033
- * The async counterpart of {@link walk}: identical traversal order and
1034
- * mutation semantics, with every handler awaited before the walk moves
1035
- * on. Resolves to the root.
1036
- */
1037
- async function walkAsync(root, visitors, state) {
1038
- await _walkAsync(root, visitors, state, new WalkContext());
1039
- return root;
1040
- }
1041
- function position(ctx, node, key, list, frame) {
1042
- ctx._node = node;
1043
- ctx._key = key;
1044
- ctx._list = list;
1045
- ctx._frame = frame;
1046
- }
1047
- function applyReplace(ctx, parent, key, list, frame) {
1048
- const next = ctx._replacement;
1049
- ctx._replacement = null;
1050
- if (list !== null) list[frame.i] = next;
1051
- else parent[key] = next;
1052
- return next;
1053
- }
1054
- function applyRemove(ctx, parent, key, list, frame) {
1055
- ctx._removed = false;
1056
- if (list !== null) {
1057
- list.splice(frame.i, 1);
1058
- frame.i--;
1059
- } else parent[key] = null;
1060
- }
1061
- function _walk(root, visitors, state, ctx) {
1062
- const d = createDispatch(visitors);
1063
- ctx.state = state;
1064
- const ancestors = ctx._ancestors;
1065
- (function visit(node, key, list, frame) {
1066
- let typed = d.typed(node.type);
1067
- const parent = ctx.parent;
1068
- position(ctx, node, key, list, frame);
1069
- if (d.enter !== null) {
1070
- d.enter(node, ctx);
1071
- if (ctx._stopped) return false;
1072
- }
1073
- if (typed !== void 0) for (const handler of typed.enter) {
1074
- handler(node, ctx);
1075
- if (ctx._stopped) return false;
1076
- }
1077
- if (ctx._removed) {
1078
- applyRemove(ctx, parent, key, list, frame);
1079
- return true;
1080
- }
1081
- if (ctx._replacement !== null) {
1082
- node = applyReplace(ctx, parent, key, list, frame);
1083
- typed = d.typed(node.type);
1084
- }
1085
- const skipped = ctx._skip;
1086
- ctx._skip = false;
1087
- if (!skipped) {
1088
- const keys = CHILD_KEYS[node.type];
1089
- if (keys !== void 0 && keys.length > 0) {
1090
- ancestors.push(node);
1091
- for (let k = 0; k < keys.length; k++) {
1092
- const key2 = keys[k];
1093
- const value = node[key2];
1094
- if (value === null || value === void 0 || typeof value !== "object") continue;
1095
- if (Array.isArray(value)) {
1096
- const childFrame = { i: 0 };
1097
- for (; childFrame.i < value.length; childFrame.i++) {
1098
- const item = value[childFrame.i];
1099
- if (item !== null && !visit(item, key2, value, childFrame)) return false;
1100
- }
1101
- } else if (!visit(value, key2, null, null)) return false;
1102
- }
1103
- ancestors.pop();
1104
- }
1105
- }
1106
- position(ctx, node, key, list, frame);
1107
- if (typed !== void 0) for (const handler of typed.leave) {
1108
- handler(node, ctx);
1109
- if (ctx._stopped) return false;
1110
- }
1111
- if (d.leave !== null) {
1112
- d.leave(node, ctx);
1113
- if (ctx._stopped) return false;
1114
- }
1115
- if (ctx._removed) applyRemove(ctx, parent, key, list, frame);
1116
- else if (ctx._replacement !== null) applyReplace(ctx, parent, key, list, frame);
1117
- return true;
1118
- })(root, null, null, null);
1119
- }
1120
- async function _walkAsync(root, visitors, state, ctx) {
1121
- const d = createDispatch(visitors);
1122
- ctx.state = state;
1123
- const ancestors = ctx._ancestors;
1124
- await (async function visit(node, key, list, frame) {
1125
- let typed = d.typed(node.type);
1126
- const parent = ctx.parent;
1127
- position(ctx, node, key, list, frame);
1128
- if (d.enter !== null) {
1129
- await d.enter(node, ctx);
1130
- if (ctx._stopped) return false;
1131
- }
1132
- if (typed !== void 0) for (const handler of typed.enter) {
1133
- await handler(node, ctx);
1134
- if (ctx._stopped) return false;
1135
- }
1136
- if (ctx._removed) {
1137
- applyRemove(ctx, parent, key, list, frame);
1138
- return true;
1139
- }
1140
- if (ctx._replacement !== null) {
1141
- node = applyReplace(ctx, parent, key, list, frame);
1142
- typed = d.typed(node.type);
1143
- }
1144
- const skipped = ctx._skip;
1145
- ctx._skip = false;
1146
- if (!skipped) {
1147
- const keys = CHILD_KEYS[node.type];
1148
- if (keys !== void 0 && keys.length > 0) {
1149
- ancestors.push(node);
1150
- for (let k = 0; k < keys.length; k++) {
1151
- const key2 = keys[k];
1152
- const value = node[key2];
1153
- if (value === null || value === void 0 || typeof value !== "object") continue;
1154
- if (Array.isArray(value)) {
1155
- const childFrame = { i: 0 };
1156
- for (; childFrame.i < value.length; childFrame.i++) {
1157
- const item = value[childFrame.i];
1158
- if (item !== null && !await visit(item, key2, value, childFrame)) return false;
1159
- }
1160
- } else if (!await visit(value, key2, null, null)) return false;
1161
- }
1162
- ancestors.pop();
1163
- }
1164
- }
1165
- position(ctx, node, key, list, frame);
1166
- if (typed !== void 0) for (const handler of typed.leave) {
1167
- await handler(node, ctx);
1168
- if (ctx._stopped) return false;
1169
- }
1170
- if (d.leave !== null) {
1171
- await d.leave(node, ctx);
1172
- if (ctx._stopped) return false;
1173
- }
1174
- if (ctx._removed) applyRemove(ctx, parent, key, list, frame);
1175
- else if (ctx._replacement !== null) applyReplace(ctx, parent, key, list, frame);
1176
- return true;
1177
- })(root, null, null, null);
1178
- }
1179
- //#endregion
1180
- //#region ../../node_modules/.pnpm/yuku-ast@0.10.2/node_modules/yuku-ast/dist/utils.js
1181
- function nameOf(node) {
1182
- if (node == null) return null;
1183
- if (node.type === "Identifier") return node.name;
1184
- if (node.type === "Literal" && typeof node.value === "string") return node.value;
1185
- return null;
1186
- }
1187
- //#endregion
1188
- //#region ../../node_modules/.pnpm/dts-resolver@3.0.0_oxc-resolver@11.24.2/node_modules/dts-resolver/dist/index.mjs
1189
- var __require = /* @__PURE__ */ createRequire(import.meta.url);
1190
- function createResolver({ tsconfig, cwd = process.cwd(), resolveNodeModules = false, ResolverFactory } = {}) {
1191
- ResolverFactory ||= __require("oxc-resolver").ResolverFactory;
1192
- const resolver = new ResolverFactory({
1193
- mainFields: [
1194
- "types",
1195
- "typings",
1196
- "module",
1197
- "main"
1198
- ],
1199
- conditionNames: [
1200
- "types",
1201
- "typings",
1202
- "import",
1203
- "require"
1204
- ],
1205
- extensions: [
1206
- ".d.ts",
1207
- ".d.mts",
1208
- ".d.cts",
1209
- ".ts",
1210
- ".mts",
1211
- ".cts",
1212
- ".tsx",
1213
- ".js",
1214
- ".mjs",
1215
- ".cjs",
1216
- ".jsx"
1217
- ],
1218
- extensionAlias: {
1219
- ".js": [
1220
- ".d.ts",
1221
- ".ts",
1222
- ".tsx",
1223
- ".js",
1224
- ".jsx"
1225
- ],
1226
- ".jsx": [
1227
- ".d.ts",
1228
- ".ts",
1229
- ".tsx",
1230
- ".jsx",
1231
- ".js"
1232
- ],
1233
- ".mjs": [
1234
- ".d.mts",
1235
- ".mts",
1236
- ".mjs"
1237
- ],
1238
- ".cjs": [
1239
- ".d.cts",
1240
- ".cts",
1241
- ".cjs"
1242
- ],
1243
- ".ts": [
1244
- ".d.ts",
1245
- ".ts",
1246
- ".tsx",
1247
- ".js",
1248
- ".jsx"
1249
- ],
1250
- ".tsx": [
1251
- ".d.ts",
1252
- ".tsx",
1253
- ".ts",
1254
- ".js",
1255
- ".jsx"
1256
- ],
1257
- ".mts": [
1258
- ".d.mts",
1259
- ".mts",
1260
- ".mjs"
1261
- ],
1262
- ".cts": [
1263
- ".d.cts",
1264
- ".cts",
1265
- ".cjs"
1266
- ]
1267
- },
1268
- modules: resolveNodeModules ? ["node_modules", "node_modules/@types"] : [],
1269
- tsconfig: tsconfig ? {
1270
- configFile: tsconfig,
1271
- references: "auto"
1272
- } : void 0
1273
- });
1274
- return (id, importer) => {
1275
- const directory = importer ? dirname(importer) : cwd;
1276
- const resolution = resolver.sync(directory, id);
1277
- if (!resolution.path) return null;
1278
- const resolved = resolution.path;
1279
- return ensureValue(resolved);
1280
- };
1281
- }
1282
- const ALLOW_EXTENSIONS = /* @__PURE__ */ new Set([
1283
- ".js",
1284
- ".cjs",
1285
- ".mjs",
1286
- ".jsx",
1287
- ".ts",
1288
- ".cts",
1289
- ".mts",
1290
- ".tsx",
1291
- ".json",
1292
- ".vue",
1293
- ".svelte",
1294
- ".astro"
1295
- ]);
1296
- function ensureValue(value) {
1297
- return value && ALLOW_EXTENSIONS.has(extname(value)) ? value.replaceAll("\\", "/") : null;
1298
- }
1299
- //#endregion
1300
- //#region ../../node_modules/.pnpm/rolldown-plugin-dts@0.28.6_@typescript+native-preview@7.0.0-dev.20260605.1_oxc-resolver_d7b1f0f9db662f38e672c8f14bf9ba00/node_modules/rolldown-plugin-dts/dist/index.mjs
1301
- function createDtsInputPlugin({ sideEffects }) {
1302
- return {
1303
- name: "rolldown-plugin-dts:dts-input",
1304
- options: sideEffects === false ? (options) => {
1305
- return {
1306
- treeshake: options.treeshake === false ? false : {
1307
- ...options.treeshake === true ? {} : options.treeshake,
1308
- moduleSideEffects: false
1309
- },
1310
- ...options
1311
- };
1312
- } : void 0,
1313
- outputOptions(options) {
1314
- return {
1315
- ...options,
1316
- entryFileNames(chunk) {
1317
- const { entryFileNames } = options;
1318
- if (entryFileNames) {
1319
- const nameTemplate = resolveTemplateFn(entryFileNames, chunk);
1320
- const renderedName = replaceTemplateName(nameTemplate, chunk.name);
1321
- if (RE_DTS.test(renderedName)) return nameTemplate;
1322
- const renderedNameWithD = replaceTemplateName(nameTemplate, `${chunk.name}.d`);
1323
- if (RE_DTS.test(renderedNameWithD)) return renderedNameWithD;
1324
- }
1325
- if (RE_DTS.test(chunk.name)) return chunk.name;
1326
- if (chunk.name.endsWith(".d")) return "[name].ts";
1327
- return "[name].d.ts";
1328
- }
1329
- };
1330
- }
1331
- };
1332
- }
1333
- var OxcGenerator = class {
1334
- options;
1335
- languageContext;
1336
- constructor(options, languageContext) {
1337
- this.options = options;
1338
- this.languageContext = languageContext;
1339
- }
1340
- emit(code, fileName) {
1341
- const result = isolatedDeclarationSync(this.languageContext.toTsFilename(fileName), code, this.options);
1342
- if (result.errors.length) {
1343
- const [error] = result.errors;
1344
- return { error: {
1345
- message: error.message,
1346
- frame: error.codeframe || void 0
1347
- } };
1348
- }
1349
- let map;
1350
- if (result.map) {
1351
- map = result.map;
1352
- map.sources = [fileName];
1353
- map.sourcesContent = void 0;
1354
- }
1355
- return {
1356
- code: result.code,
1357
- map
1358
- };
1359
- }
1360
- };
1361
- const WORKER_URL = "./tsc-worker.mjs";
1362
- var TscGenerator = class {
1363
- options;
1364
- parallel;
1365
- newContext;
1366
- getEntries;
1367
- worker;
1368
- tscModule;
1369
- context;
1370
- constructor({ parallel, newContext, getEntries, ...options }) {
1371
- this.options = options;
1372
- this.parallel = parallel;
1373
- this.newContext = newContext;
1374
- this.getEntries = getEntries;
1375
- }
1376
- async init() {
1377
- if (this.parallel) {
1378
- this.worker = createTscWorker();
1379
- return;
1380
- }
1381
- this.tscModule = await import("./tsc-BLb4pSBY.js");
1382
- if (this.newContext) this.context = createContext();
1383
- }
1384
- async emit(_code, fileName) {
1385
- const options = {
1386
- ...this.options,
1387
- entries: this.getEntries(),
1388
- id: fileName,
1389
- context: this.context
1390
- };
1391
- let result;
1392
- if (this.parallel) {
1393
- if (!this.worker) throw new Error("TscGenerator has not been initialized.");
1394
- result = await this.worker.emit(options);
1395
- } else {
1396
- if (!this.tscModule) throw new Error("TscGenerator has not been initialized.");
1397
- result = this.tscModule.tscEmit(options);
1398
- }
1399
- if (result.code && RE_JSON.test(fileName)) result.code = patchJsonDts(result.code);
1400
- return result;
1401
- }
1402
- dispose() {
1403
- this.worker?.kill();
1404
- this.worker = void 0;
1405
- this.tscModule = void 0;
1406
- if (this.newContext) this.context = void 0;
1407
- }
1408
- invalidate(fileName) {
1409
- if (this.parallel) return;
1410
- if (this.newContext) {
1411
- if (this.context) invalidateContextFile(this.context, fileName);
1412
- } else invalidateContextFile(globalContext, fileName);
1413
- }
1414
- };
1415
- function createTscWorker() {
1416
- const childProcess = fork(new URL(WORKER_URL, import.meta.url), {
1417
- stdio: "inherit",
1418
- serialization: "advanced"
1419
- });
1420
- const pending = /* @__PURE__ */ new Map();
1421
- let nextId = 0;
1422
- childProcess.on("message", (response) => {
1423
- const handler = pending.get(response.id);
1424
- if (!handler) return;
1425
- pending.delete(response.id);
1426
- if (response.error) handler.reject(response.error);
1427
- else handler.resolve(response.result);
1428
- });
1429
- childProcess.on("exit", (code) => {
1430
- for (const handler of pending.values()) handler.reject(/* @__PURE__ */ new Error(`tsc worker exited with code ${code}`));
1431
- pending.clear();
1432
- });
1433
- return {
1434
- emit: (options) => new Promise((resolve, reject) => {
1435
- const id = nextId++;
1436
- pending.set(id, {
1437
- resolve,
1438
- reject
1439
- });
1440
- childProcess.send({
1441
- id,
1442
- options
1443
- });
1444
- }),
1445
- kill: () => childProcess.kill()
1446
- };
1447
- }
1448
- function patchJsonDts(code) {
1449
- if (code.includes("declare const _exports")) {
1450
- if (code.includes("declare const _exports: {") && !code.includes("\n}[];")) {
1451
- const exports = collectJsonExports(code);
1452
- let index = 0;
1453
- code += exports.map((exported) => {
1454
- const valid = `_${exported.replaceAll(/[^\w$]/g, "_")}${index++}`;
1455
- const jsonKey = JSON.stringify(exported);
1456
- return `declare let ${valid}: typeof _exports[${jsonKey}]\nexport { ${valid} as ${jsonKey} }`;
1457
- }).join("\n");
1458
- }
1459
- return code;
1460
- }
1461
- const exportMap = collectJsonExportMap(code);
1462
- code += `
1463
- declare namespace __json_default_export {
1464
- export { ${Array.from(exportMap.entries(), ([exported, local]) => exported === local ? exported : `${local} as ${exported}`).join(", ")} }
1465
- }
1466
- export { __json_default_export as default }`;
1467
- return code;
1468
- }
1469
- function collectJsonExportMap(code) {
1470
- const exportMap = /* @__PURE__ */ new Map();
1471
- const { program } = parse$1(code, {
1472
- sourceType: "module",
1473
- lang: "dts"
1474
- });
1475
- for (const decl of program.body) if (decl.type === "ExportNamedDeclaration") {
1476
- if (decl.declaration) {
1477
- if (decl.declaration.type === "VariableDeclaration") {
1478
- for (const vdecl of decl.declaration.declarations) if (vdecl.id.type === "Identifier") exportMap.set(vdecl.id.name, vdecl.id.name);
1479
- } else if (decl.declaration.type === "TSModuleDeclaration" && decl.declaration.id.type === "Identifier") exportMap.set(decl.declaration.id.name, decl.declaration.id.name);
1480
- } else if (decl.specifiers.length) {
1481
- 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);
1482
- }
1483
- }
1484
- return exportMap;
1485
- }
1486
- /** `declare const _exports` mode */
1487
- function collectJsonExports(code) {
1488
- const exports = [];
1489
- const { program } = parse$1(code, {
1490
- sourceType: "module",
1491
- lang: "dts"
1492
- });
1493
- const members = program.body[0].declarations[0].id.typeAnnotation.typeAnnotation.members;
1494
- for (const member of members) if (member.key.type === "Identifier") exports.push(member.key.name);
1495
- else if (is.StringLiteral(member.key)) exports.push(member.key.value);
1496
- return exports;
1497
- }
1498
- const debug$5 = createDebug("rolldown-plugin-dts:tsgo");
1499
- const spawnAsync = (...args) => new Promise((resolve, reject) => {
1500
- const child = spawn(...args);
1501
- child.on("close", (code, signal) => {
1502
- if (code === 0) resolve();
1503
- else if (signal) reject(/* @__PURE__ */ new Error(`tsgo process terminated by signal ${signal}`));
1504
- else reject(/* @__PURE__ */ new Error(`tsgo process exited with code ${code}`));
1505
- });
1506
- child.on("error", (error) => reject(error));
1507
- });
1508
- let tsgoPathCache;
1509
- function resolveTsgoPath(logger) {
1510
- if (tsgoPathCache) return tsgoPathCache;
1511
- const pkgName = isTS70Installed() ? "typescript" : "@typescript/native-preview";
1512
- const pkgJsonPath = tryResolve(`${pkgName}/package.json`);
1513
- 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.");
1514
- const { version } = require(pkgJsonPath);
1515
- logger.info(`Emit types with ${styleText("underline", `${pkgName}@${version}`)}`);
1516
- const getExePath = require(path.join(path.dirname(pkgJsonPath), "lib/getExePath.js"));
1517
- return tsgoPathCache = (typeof getExePath === "function" ? getExePath : getExePath.default)();
1518
- }
1519
- var TsgoGenerator = class {
1520
- options;
1521
- context;
1522
- constructor(options) {
1523
- this.options = options;
1524
- }
1525
- async init() {
1526
- const { tsgoPath, rootDir, tsconfig, sourcemap } = this.options;
1527
- this.context = await runTsgo(tsgoPath, rootDir, tsconfig, sourcemap);
1528
- }
1529
- async emit(_code, fileName) {
1530
- const { rootDir, languageContext } = this.options;
1531
- if (languageContext.isCustomLanguageFile(fileName)) return { error: `tsgo does not support ${path.extname(fileName)} files.` };
1532
- if (!this.context) throw new Error("TsgoGenerator has not been initialized.");
1533
- const dtsPath = path.resolve(this.context.path, path.relative(path.resolve(rootDir), filename_to_dts(fileName, languageContext)));
1534
- if (!existsSync(dtsPath)) {
1535
- debug$5("[tsgo]", dtsPath, "is missing");
1536
- return { error: `tsgo did not generate dts file for ${fileName}, please check your tsconfig.` };
1537
- }
1538
- const code = await readFile(dtsPath, "utf8");
1539
- let map;
1540
- const mapPath = `${dtsPath}.map`;
1541
- if (existsSync(mapPath)) {
1542
- const mapRaw = await readFile(mapPath, "utf8");
1543
- map = {
1544
- ...JSON.parse(mapRaw),
1545
- sources: [fileName]
1546
- };
1547
- }
1548
- return {
1549
- code,
1550
- map
1551
- };
1552
- }
1553
- async dispose() {
1554
- await this.context?.dispose();
1555
- this.context = void 0;
1556
- }
1557
- };
1558
- async function runTsgo(tsgoPath, rootDir, tsconfig, sourcemap) {
1559
- debug$5("[tsgo] rootDir", rootDir);
1560
- debug$5("[tsgo] using tsgo binary", tsgoPath);
1561
- const tsgoDist = await mkdtemp(path.join(tmpdir(), "rolldown-plugin-dts-"));
1562
- debug$5("[tsgo] tsgoDist", tsgoDist);
1563
- const args = [
1564
- "--noEmit",
1565
- "false",
1566
- "--declaration",
1567
- "--emitDeclarationOnly",
1568
- "-p",
1569
- tsconfig,
1570
- "--outDir",
1571
- tsgoDist,
1572
- "--rootDir",
1573
- rootDir,
1574
- "--noCheck",
1575
- ...sourcemap ? ["--declarationMap"] : []
1576
- ];
1577
- debug$5("[tsgo] args %o", args);
1578
- await spawnAsync(tsgoPath, args, { stdio: "inherit" });
1579
- return {
1580
- path: tsgoDist,
1581
- async dispose() {
1582
- if (debug$5.enabled) debug$5("[tsgo] skip cleanup of tsgoDist", tsgoDist);
1583
- else {
1584
- debug$5("[tsgo] disposing tsgoDist", tsgoDist);
1585
- await rm(tsgoDist, {
1586
- recursive: true,
1587
- force: true
1588
- }).catch(() => {});
1589
- }
1590
- }
1591
- };
1592
- }
1593
- function createGenerator({ generator, tsconfig, tsconfigRaw, build, incremental, cwd, oxc, languageContext, parallel, tsgo, newContext, sourcemap }, getEntries) {
1594
- if (generator === "oxc") return new OxcGenerator(oxc, languageContext);
1595
- if (generator === "tsgo") return new TsgoGenerator({
1596
- tsgoPath: tsgo.path,
1597
- rootDir: tsconfig ? path.dirname(tsconfig) : cwd,
1598
- tsconfig,
1599
- sourcemap,
1600
- languageContext
1601
- });
1602
- return new TscGenerator({
1603
- tsconfig,
1604
- tsconfigRaw,
1605
- build,
1606
- incremental,
1607
- cwd,
1608
- sourcemap,
1609
- languageContext,
1610
- parallel,
1611
- newContext,
1612
- getEntries
1613
- });
1614
- }
1615
- const debug$4 = createDebug("rolldown-plugin-dts:generate");
1616
- const EMPTY_STUB = `export {}`;
1617
- function createGeneratePlugin(options) {
1618
- const { entry, cwd, emitDtsOnly, languageContext, eager, emitJs } = options;
1619
- const entryIncludes = entry?.filter((p) => p[0] !== "!");
1620
- const entryIgnores = entry?.filter((p) => p[0] === "!").map((p) => p.slice(1));
1621
- const entryMatcher = entry ? (file) => entryIncludes.some((p) => path.matchesGlob(file, p)) && entryIgnores.every((p) => !path.matchesGlob(file, p)) : void 0;
1622
- const dtsMap = /* @__PURE__ */ new Map();
1623
- /**
1624
- * A map of input id to output file name
1625
- *
1626
- * @example
1627
- *
1628
- * inputAlias = new Map([
1629
- * ['/absolute/path/to/src/source_file.ts', 'dist/foo/index'],
1630
- * ])
1631
- */
1632
- const inputAliasMap = /* @__PURE__ */ new Map();
1633
- const declarationGenerator = createGenerator(options, () => eager ? void 0 : Array.from(dtsMap.values()).filter((module) => module.isEntry).map((module) => module.id));
1634
- return {
1635
- name: "rolldown-plugin-dts:generate",
1636
- async buildStart(options) {
1637
- await declarationGenerator.init?.();
1638
- if (!Array.isArray(options.input)) for (const [name, id] of Object.entries(options.input)) {
1639
- debug$4("resolving input alias %s -> %s", name, id);
1640
- let resolved = await this.resolve(id);
1641
- if (!id.startsWith("./")) resolved ||= await this.resolve(`./${id}`);
1642
- const resolvedId = resolved?.id || id;
1643
- debug$4("resolved input alias %s -> %s", id, resolvedId);
1644
- inputAliasMap.set(resolvedId, name);
1645
- }
1646
- },
1647
- outputOptions(options) {
1648
- return {
1649
- ...options,
1650
- entryFileNames(chunk) {
1651
- const { entryFileNames } = options;
1652
- const nameTemplate = resolveTemplateFn(entryFileNames || "[name].js", chunk);
1653
- if (chunk.name.endsWith(".d")) {
1654
- if (RE_DTS.test(nameTemplate)) return replaceTemplateName(nameTemplate, chunk.name.slice(0, -2));
1655
- if (RE_JS.test(nameTemplate)) return nameTemplate.replace(RE_JS, ".$1ts");
1656
- }
1657
- return nameTemplate;
1658
- }
1659
- };
1660
- },
1661
- resolveId(id) {
1662
- if (!dtsMap.has(id)) return;
1663
- debug$4("resolve dts id %s", id);
1664
- return { id };
1665
- },
1666
- transform: {
1667
- order: "pre",
1668
- filter: { id: {
1669
- include: [
1670
- RE_JS,
1671
- RE_TS,
1672
- RE_JSON,
1673
- ...languageContext.patterns
1674
- ],
1675
- exclude: [
1676
- RE_DTS,
1677
- RE_NODE_MODULES,
1678
- RE_ROLLDOWN_RUNTIME
1679
- ]
1680
- } },
1681
- handler(code, id) {
1682
- const jsFile = RE_JS.test(id);
1683
- if (!jsFile || emitJs) {
1684
- const mod = this.getModuleInfo(id);
1685
- const isEntry = entryMatcher ? entryMatcher(path.relative(cwd, id)) : !!mod?.isEntry;
1686
- const dtsId = filename_to_dts(id, languageContext);
1687
- dtsMap.set(dtsId, {
1688
- code,
1689
- id,
1690
- isEntry,
1691
- jsFile
1692
- });
1693
- debug$4("register dts source: %s", id);
1694
- if (isEntry) {
1695
- const name = inputAliasMap.get(id);
1696
- this.emitFile({
1697
- type: "chunk",
1698
- id: dtsId,
1699
- name: name ? `${name}.d` : void 0
1700
- });
1701
- }
1702
- }
1703
- if (emitDtsOnly) {
1704
- if (RE_JSON.test(id)) return "{}";
1705
- return EMPTY_STUB;
1706
- }
1707
- }
1708
- },
1709
- load: {
1710
- filter: { id: {
1711
- include: [RE_DTS],
1712
- exclude: [RE_NODE_MODULES]
1713
- } },
1714
- async handler(dtsId) {
1715
- const module = dtsMap.get(dtsId);
1716
- if (!module) return;
1717
- const { code, id, jsFile } = module;
1718
- if (jsFile && await access(dtsId).then(() => true).catch(() => false)) {
1719
- debug$4("dts file already exists for %s, skipping generation", id);
1720
- return;
1721
- }
1722
- debug$4("generate dts %s from %s", dtsId, id);
1723
- const result = await declarationGenerator.emit(code, id);
1724
- if (result.error) return this.error(result.error);
1725
- return {
1726
- code: result.code || "",
1727
- map: result.map
1728
- };
1729
- }
1730
- },
1731
- generateBundle: emitDtsOnly ? (options, bundle) => {
1732
- for (const fileName of Object.keys(bundle)) if (bundle[fileName].type === "chunk" && !RE_DTS.test(fileName) && !RE_DTS_MAP.test(fileName)) delete bundle[fileName];
1733
- } : void 0,
1734
- async buildEnd() {
1735
- await declarationGenerator.dispose?.();
1736
- },
1737
- watchChange(id) {
1738
- declarationGenerator.invalidate?.(id);
1739
- }
1740
- };
1741
- }
1742
- function isThisExpression(node) {
1743
- return is.Identifier(node, "this") || node.type === "ThisExpression" || node.type === "MemberExpression" && isThisExpression(node.object);
1744
- }
1745
- function isInfer(node) {
1746
- return is.Identifier(node, "infer");
1747
- }
1748
- function TSEntityNameToRuntime(node) {
1749
- if (node.type === "Identifier" || node.type === "ThisExpression") return node;
1750
- const left = TSEntityNameToRuntime(node.left);
1751
- return Object.assign(node, {
1752
- type: "MemberExpression",
1753
- object: left,
1754
- property: node.right,
1755
- computed: false
1756
- });
1757
- }
1758
- function getIdFromTSEntityName(node) {
1759
- if (node.type === "Identifier" || node.type === "ThisExpression") return node;
1760
- return getIdFromTSEntityName(node.left);
1761
- }
1762
- function isReferenceId(node) {
1763
- return is.oneOf(node, ["Identifier", "MemberExpression"]);
1764
- }
1765
- function isHelperImport(node) {
1766
- 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));
1767
- }
1768
- const REFERENCE_RE = /\/\s*<reference\s+(?:path|types)=/;
1769
- function collectReferenceDirectives(comment, negative = false) {
1770
- return comment.filter((c) => REFERENCE_RE.test(c.value) !== negative);
1771
- }
1772
- const SOURCE_MAP_PRAGMA_RE = /^#\s*source(?:Mapping)?URL=/;
1773
- function isSourceMapPragma(comment) {
1774
- return SOURCE_MAP_PRAGMA_RE.test(comment.value);
1775
- }
1776
- function isCjsDtsInputSyntax(node) {
1777
- return node.type === "TSExportAssignment" || node.type === "TSImportEqualsDeclaration" && node.moduleReference.type === "TSExternalModuleReference";
1778
- }
1779
- function overwriteNode(node, newNode) {
1780
- for (const key of Object.keys(node)) Reflect.deleteProperty(node, key);
1781
- Object.assign(node, newNode);
1782
- return node;
1783
- }
1784
- /**
1785
- * Region markers and alike, the comments worth keeping when their node is
1786
- * replaced or dropped
1787
- */
1788
- function pragmaComments(node) {
1789
- return node.comments?.filter((comment) => comment.position === "before" && comment.value.startsWith("#") && !isSourceMapPragma(comment)) || [];
1790
- }
1791
- function inheritNodeComments(oldNode, newNode) {
1792
- newNode.comments ||= [];
1793
- newNode.comments.unshift(...pragmaComments(oldNode));
1794
- newNode.comments = newNode.comments.filter((comment) => !REFERENCE_RE.test(comment.value) && !isSourceMapPragma(comment));
1795
- return newNode;
1796
- }
1797
- function getIdentifierIndex(identifierMap, name) {
1798
- if (name in identifierMap) return ++identifierMap[name];
1799
- return identifierMap[name] = 0;
1800
- }
1801
- /**
1802
- * Collects all TSTypeParameter nodes from the given node and groups them by
1803
- * their name. One name can associate with one or more type parameters. These
1804
- * names will be used as the parameter name in the generated JavaScript
1805
- * dependency function.
1806
- */
1807
- function collectParams(node) {
1808
- const typeParams = [];
1809
- walk(node, { leave(node) {
1810
- if ("typeParameters" in node && node.typeParameters?.type === "TSTypeParameterDeclaration") typeParams.push(...node.typeParameters.params.map(({ name }) => name));
1811
- } });
1812
- const paramMap = /* @__PURE__ */ new Map();
1813
- for (const typeParam of typeParams) {
1814
- const name = typeParam.name;
1815
- const group = paramMap.get(name);
1816
- if (group) group.push(typeParam);
1817
- else paramMap.set(name, [typeParam]);
1818
- }
1819
- return Array.from(paramMap, ([name, typeParams]) => ({
1820
- name,
1821
- typeParams
1822
- }));
1823
- }
1824
- async function collectDependencies(context, node, importer, namespaceStmts, children, identifierMap) {
1825
- const deps = /* @__PURE__ */ new Set();
1826
- const seen = /* @__PURE__ */ new Set();
1827
- const preserveImportTypeCache = /* @__PURE__ */ new Map();
1828
- const inferredStack = [];
1829
- let currentInferred = /* @__PURE__ */ new Set();
1830
- function isInferred(node) {
1831
- return node.type === "Identifier" && currentInferred.has(node.name);
1832
- }
1833
- await walkAsync(node, {
1834
- enter(node) {
1835
- if (node.type !== "TSConditionalType") return;
1836
- const inferred = collectInferredNames(node.extendsType);
1837
- inferredStack.push(inferred);
1838
- },
1839
- async leave(node, path) {
1840
- const { parent } = path;
1841
- if (node.type === "TSConditionalType") inferredStack.pop();
1842
- else if (parent?.type === "TSConditionalType") {
1843
- const trueBranch = parent.trueType === node;
1844
- currentInferred = new Set((trueBranch ? inferredStack : inferredStack.slice(0, -1)).flat());
1845
- } else currentInferred = /* @__PURE__ */ new Set();
1846
- if (node.type === "ExportNamedDeclaration") {
1847
- for (const specifier of node.specifiers) if (specifier.type === "ExportSpecifier") addDependency(specifier.local);
1848
- } else if (node.type === "TSInterfaceDeclaration" && node.extends) for (const heritage of node.extends || []) addDependency(heritage.expression);
1849
- else if (node.type === "ClassDeclaration") {
1850
- if (node.superClass) addDependency(node.superClass);
1851
- if (node.implements) for (const implement of node.implements) addDependency(implement.expression);
1852
- } else if (is.oneOf(node, [
1853
- "Property",
1854
- "PropertyDefinition",
1855
- "TSAbstractPropertyDefinition",
1856
- "MethodDefinition",
1857
- "TSAbstractMethodDefinition",
1858
- "TSPropertySignature",
1859
- "TSMethodSignature"
1860
- ])) {
1861
- if (node.computed && isReferenceId(node.key)) addDependency(node.key);
1862
- if ("value" in node && isReferenceId(node.value)) addDependency(node.value);
1863
- } else switch (node.type) {
1864
- case "TSTypeReference":
1865
- addDependency(TSEntityNameToRuntime(node.typeName));
1866
- break;
1867
- case "TSQualifiedName":
1868
- addDependency(getIdFromTSEntityName(node.left));
1869
- break;
1870
- case "TSTypeQuery":
1871
- if (seen.has(node.exprName)) return;
1872
- if (node.exprName.type === "TSImportType") break;
1873
- addDependency(TSEntityNameToRuntime(node.exprName));
1874
- break;
1875
- case "TSImportType": {
1876
- seen.add(node);
1877
- const { source, qualifier } = node;
1878
- const resolved = await context.resolve(source.value, importer);
1879
- if (!resolved || !!resolved.external) {
1880
- preserveImportTypeCache.set(source.value, true);
1881
- break;
1882
- }
1883
- const dep = importNamespace(node, qualifier, source, namespaceStmts, identifierMap);
1884
- if (dep) addDependency(dep);
1885
- break;
1886
- }
1887
- }
1888
- if (parent && !deps.has(node) && isChildSymbol(node, parent)) children.add(node);
1889
- }
1890
- });
1891
- return Array.from(deps);
1892
- function addDependency(node) {
1893
- if (isThisExpression(node) || isInferred(node)) return;
1894
- deps.add(node);
1895
- }
1896
- }
1897
- function importNamespace(node, imported, source, namespaceStmts, identifierMap) {
1898
- const sourceText = source.value.replaceAll(/\W/g, "_");
1899
- const localName = `_$${isIdentifierName(source.value) ? source.value : `${sourceText}${getIdentifierIndex(identifierMap, sourceText)}`}`;
1900
- let local = b.Identifier({ name: localName });
1901
- if (namespaceStmts.has(source.value)) local = namespaceStmts.get(source.value).local;
1902
- else namespaceStmts.set(source.value, {
1903
- stmt: b.ImportDeclaration({
1904
- specifiers: [b.ImportNamespaceSpecifier({ local })],
1905
- source,
1906
- phase: null,
1907
- attributes: []
1908
- }),
1909
- local
1910
- });
1911
- if (imported) {
1912
- const importedLeft = getIdFromTSEntityName(imported);
1913
- if (imported.type === "ThisExpression" || importedLeft.type === "ThisExpression") throw new Error("Cannot import `this` from module.");
1914
- overwriteNode(importedLeft, b.TSQualifiedName({
1915
- left: local,
1916
- right: { ...importedLeft }
1917
- }));
1918
- local = imported;
1919
- }
1920
- let replacement = node;
1921
- if (node.typeArguments) {
1922
- overwriteNode(node, b.TSTypeReference({
1923
- typeName: local,
1924
- typeArguments: node.typeArguments
1925
- }));
1926
- replacement = local;
1927
- } else overwriteNode(node, local);
1928
- return {
1929
- ...TSEntityNameToRuntime(local),
1930
- replace(newNode) {
1931
- overwriteNode(replacement, newNode);
1932
- }
1933
- };
1934
- }
1935
- function isChildSymbol(node, parent) {
1936
- if (node.type === "Identifier") return true;
1937
- if (is.oneOf(parent, ["TSPropertySignature", "TSMethodSignature"]) && parent.key === node) return true;
1938
- return false;
1939
- }
1940
- function collectInferredNames(node) {
1941
- const inferred = [];
1942
- walk(node, { enter(node) {
1943
- if (node.type === "TSInferType" && node.typeParameter) inferred.push(node.typeParameter.name.name);
1944
- } });
1945
- return inferred;
1946
- }
1947
- /**
1948
- * Check if the given node is a {@link RuntimeBindingVariableDeclration}
1949
- */
1950
- function isRuntimeBindingVariableDeclaration(node) {
1951
- return node?.type === "VariableDeclaration" && node.declarations.length === 1 && node.declarations[0].type === "VariableDeclarator" && node.declarations[0].id.type === "ArrayPattern" && isRuntimeBindingArrayExpression(node.declarations[0].init);
1952
- }
1953
- /**
1954
- * Check if the given node is a {@link RuntimeBindingArrayExpression}
1955
- */
1956
- function isRuntimeBindingArrayExpression(node) {
1957
- return node?.type === "ArrayExpression" && isRuntimeBindingArrayElements(node.elements);
1958
- }
1959
- /**
1960
- * Check if the given array is a {@link RuntimeBindingArrayElements}
1961
- */
1962
- function isRuntimeBindingArrayElements(elements) {
1963
- const [declarationId, deps, children, effect] = elements;
1964
- return is.NumericLiteral(declarationId) && deps?.type === "ArrowFunctionExpression" && children?.type === "ArrayExpression" && (!effect || effect.type === "CallExpression");
1965
- }
1966
- function runtimeBindingArrayExpression(elements) {
1967
- return b.ArrayExpression({ elements: [...elements] });
1968
- }
1969
- async function collectModuleExports(context, nodes, id) {
1970
- const info = {
1971
- typeOnlyLocals: /* @__PURE__ */ new Set(),
1972
- exports: /* @__PURE__ */ new Map(),
1973
- reExports: [],
1974
- exportAlls: []
1975
- };
1976
- for (const node of nodes) collectTypeOnlyLocals(node, info.typeOnlyLocals);
1977
- for (const node of nodes) await collectExportInfo(context, node, id, info);
1978
- return info;
1979
- }
1980
- function collectTypeOnlyLocals(node, typeOnlyLocals) {
1981
- if (node.type !== "ImportDeclaration") return;
1982
- for (const specifier of node.specifiers) if (node.importKind === "type" || "importKind" in specifier && specifier.importKind === "type") typeOnlyLocals.add(specifier.local.name);
1983
- }
1984
- function collectDeclarationNames(node) {
1985
- if (node.type === "VariableDeclaration") return node.declarations.flatMap((decl) => collectPatternNames(decl.id));
1986
- if ("id" in node && node.id) {
1987
- if (node.id.type !== "Identifier" && node.id.type !== "TSQualifiedName") return [];
1988
- const id = getIdFromTSEntityName(node.id);
1989
- return id.type === "Identifier" ? [id.name] : [];
1990
- }
1991
- return [];
1992
- }
1993
- function collectPatternNames(node) {
1994
- if (!node) return [];
1995
- if (node.type === "Identifier") return [node.name];
1996
- if (node.type === "RestElement") return collectPatternNames(node.argument);
1997
- if (node.type === "AssignmentPattern") return collectPatternNames(node.left);
1998
- if (node.type === "ArrayPattern") return node.elements.flatMap((element) => collectPatternNames(element));
1999
- if (node.type === "ObjectPattern") return node.properties.flatMap((property) => {
2000
- if (property.type === "RestElement") return collectPatternNames(property.argument);
2001
- return collectPatternNames(property.value);
2002
- });
2003
- return [];
2004
- }
2005
- function isTypeOnlyExport(node, specifier) {
2006
- return node.exportKind === "type" || specifier.exportKind === "type";
2007
- }
2008
- async function collectExportInfo(context, node, id, info) {
2009
- if (node.type === "ExportNamedDeclaration") {
2010
- if (node.declaration) {
2011
- for (const name of collectDeclarationNames(node.declaration)) info.exports.set(name, false);
2012
- return;
2013
- }
2014
- const source = await resolveExportSource(context, node.source, id);
2015
- for (const specifier of node.specifiers) {
2016
- const typeOnly = isTypeOnlyExport(node, specifier);
2017
- const exported = nameOf(specifier.exported);
2018
- const local = nameOf(specifier.local);
2019
- if (source) info.reExports.push({
2020
- source,
2021
- local,
2022
- exported,
2023
- typeOnly
2024
- });
2025
- else info.exports.set(exported, typeOnly || info.typeOnlyLocals.has(local));
2026
- }
2027
- return;
2028
- }
2029
- if (node.type === "ExportDefaultDeclaration") {
2030
- info.exports.set("default", false);
2031
- return;
2032
- }
2033
- if (node.type === "ExportAllDeclaration") {
2034
- if (node.exported) {
2035
- info.exports.set(nameOf(node.exported), node.exportKind === "type");
2036
- return;
2037
- }
2038
- info.exportAlls.push({
2039
- source: await resolveExportSource(context, node.source, id),
2040
- rawSource: node.source.value,
2041
- typeOnly: node.exportKind === "type"
2042
- });
2043
- }
2044
- }
2045
- async function resolveExportSource(context, source, importer) {
2046
- if (!source) return;
2047
- const resolved = await context.resolve(source.value, importer);
2048
- if (!resolved || resolved.external) return;
2049
- return resolved.id;
2050
- }
2051
- /**
2052
- * Resolves what the chunk exports and how each export is emitted: which names
2053
- * are type only, and which declarations get their `export` keyword back.
2054
- */
2055
- function planChunkExports(chunk, moduleExportsMap, nodes, getDeclaration, cjsDefault) {
2056
- const { typeOnlyNames, typeOnlyExportAllSources, inlineNames } = collectChunkExports(chunk, moduleExportsMap);
2057
- const { kinds, allowExportAssignment } = planInlineExports(nodes, inlineNames, getDeclaration, cjsDefault);
2058
- return {
2059
- typeOnlyNames,
2060
- typeOnlyExportAllSources,
2061
- inlineKinds: kinds,
2062
- allowExportAssignment
2063
- };
2064
- }
2065
- function collectChunkExports(chunk, moduleExportsMap) {
2066
- const exportsByModule = resolveAllModuleExports(moduleExportsMap);
2067
- const roots = chunk.facadeModuleId && moduleExportsMap.has(chunk.facadeModuleId) ? [chunk.facadeModuleId] : chunk.moduleIds;
2068
- const mergedExports = /* @__PURE__ */ new Map();
2069
- const typeOnlyExportAllSources = /* @__PURE__ */ new Set();
2070
- for (const root of roots) {
2071
- const exports = exportsByModule.get(root);
2072
- if (exports) for (const [name, typeOnly] of exports) setExportTypeOnly(mergedExports, name, typeOnly);
2073
- const moduleExports = moduleExportsMap.get(root);
2074
- if (!moduleExports) continue;
2075
- for (const exportAll of moduleExports.exportAlls) {
2076
- if (!exportAll.typeOnly || exportAll.source) continue;
2077
- typeOnlyExportAllSources.add(exportAll.rawSource);
2078
- }
2079
- }
2080
- const typeOnlyNames = /* @__PURE__ */ new Set();
2081
- const inlineNames = /* @__PURE__ */ new Set();
2082
- for (const [name, typeOnly] of mergedExports) if (typeOnly) typeOnlyNames.add(name);
2083
- else inlineNames.add(name);
2084
- return {
2085
- typeOnlyNames,
2086
- typeOnlyExportAllSources,
2087
- inlineNames
2088
- };
2089
- }
2090
- function resolveAllModuleExports(moduleExportsMap) {
2091
- const exportsByModule = /* @__PURE__ */ new Map();
2092
- for (const [id, info] of moduleExportsMap) exportsByModule.set(id, new Map(info.exports));
2093
- let changed = true;
2094
- while (changed) {
2095
- changed = false;
2096
- for (const [id, info] of moduleExportsMap) {
2097
- const exports = exportsByModule.get(id);
2098
- for (const reExport of info.reExports) {
2099
- const sourceTypeOnly = (reExport.source ? exportsByModule.get(reExport.source) : void 0)?.get(reExport.local) ?? false;
2100
- if (setExportTypeOnly(exports, reExport.exported, reExport.typeOnly || sourceTypeOnly)) changed = true;
2101
- }
2102
- for (const exportAll of info.exportAlls) {
2103
- if (!exportAll.source) continue;
2104
- const sourceExports = exportsByModule.get(exportAll.source);
2105
- if (!sourceExports) continue;
2106
- for (const [name, typeOnly] of sourceExports) {
2107
- if (name === "default") continue;
2108
- if (setExportTypeOnly(exports, name, exportAll.typeOnly || typeOnly)) changed = true;
2109
- }
2110
- }
2111
- }
2112
- }
2113
- return exportsByModule;
2114
- }
2115
- function setExportTypeOnly(exports, name, typeOnly) {
2116
- const current = exports.get(name);
2117
- if (current === false || current === typeOnly) return false;
2118
- if (current === void 0 || !typeOnly) {
2119
- exports.set(name, typeOnly);
2120
- return true;
2121
- }
2122
- return false;
2123
- }
2124
- /**
2125
- * Collects the `export { local as exported }` statements of a chunk, i.e. the
2126
- * exports that could be attached back to their declaration. Re-exports
2127
- * (`export { x } from '...'`) are not local and therefore skipped.
2128
- */
2129
- function getLocalExportsMap(nodes) {
2130
- const exportsMap = /* @__PURE__ */ new Map();
2131
- for (const node of nodes) {
2132
- if (node.type !== "ExportNamedDeclaration" || node.declaration || node.source) continue;
2133
- for (const specifier of node.specifiers) {
2134
- if (specifier.type !== "ExportSpecifier") continue;
2135
- exportsMap.set(nameOf(specifier.exported), {
2136
- local: nameOf(specifier.local),
2137
- typeOnly: node.exportKind === "type" || specifier.exportKind === "type",
2138
- specifier
2139
- });
2140
- }
2141
- }
2142
- return exportsMap;
2143
- }
2144
- /**
2145
- * Decides which declarations get their `export` keyword back, so that a
2146
- * declaration written as `export declare const x` is emitted as
2147
- * `export declare const x` instead of `declare const x` + `export { x }`.
2148
- *
2149
- * A declaration qualifies only if it was exported inline in its own source
2150
- * file, the chunk exports it as a value under its own name, and every
2151
- * declaration it merges with qualifies as well. The specifiers of the
2152
- * re-attached exports are removed here, before `patchImportExport` runs, so
2153
- * that both stay in sync.
2154
- */
2155
- function planInlineExports(nodes, inlineNames, getDeclaration, cjsDefault) {
2156
- const exportsMap = getLocalExportsMap(nodes);
2157
- const allowExportAssignment = hasOnlyDefaultExport(nodes);
2158
- const kinds = /* @__PURE__ */ new Map();
2159
- const removed = /* @__PURE__ */ new Set();
2160
- const declNames = /* @__PURE__ */ new Map();
2161
- const nameDecls = /* @__PURE__ */ new Map();
2162
- for (const node of nodes) {
2163
- if (!isRuntimeBindingVariableDeclaration(node)) continue;
2164
- const { id, init } = node.declarations[0];
2165
- const declarationId = init.elements[0].value;
2166
- const names = id.elements.map(({ name }) => name);
2167
- declNames.set(declarationId, names);
2168
- for (const name of names) {
2169
- const decls = nameDecls.get(name);
2170
- if (decls) decls.push(declarationId);
2171
- else nameDecls.set(name, [declarationId]);
2172
- }
2173
- }
2174
- const named = /* @__PURE__ */ new Set();
2175
- for (const [declarationId, names] of declNames) {
2176
- if (getDeclaration(declarationId).exportType !== "named") continue;
2177
- if (names.every(isInlinableName)) named.add(declarationId);
2178
- }
2179
- let changed = true;
2180
- while (changed) {
2181
- changed = false;
2182
- for (const declarationId of named) if (!declNames.get(declarationId).every((name) => nameDecls.get(name).every((id) => named.has(id)))) {
2183
- named.delete(declarationId);
2184
- changed = true;
2185
- }
2186
- }
2187
- for (const declarationId of named) {
2188
- kinds.set(declarationId, "named");
2189
- for (const name of declNames.get(declarationId)) removed.add(exportsMap.get(name).specifier);
2190
- }
2191
- const defaultExport = exportsMap.get("default");
2192
- if (defaultExport && !defaultExport.typeOnly && inlineNames.has("default") && (!cjsDefault || !allowExportAssignment)) for (const [declarationId, names] of declNames) {
2193
- const declaration = getDeclaration(declarationId);
2194
- if (declaration.exportType !== "default" || names.length !== 1 || names[0] !== defaultExport.local || nameDecls.get(names[0]).length !== 1 || !isInlinableDefaultDeclaration(declaration.decl)) continue;
2195
- kinds.set(declarationId, "default");
2196
- removed.add(defaultExport.specifier);
2197
- break;
2198
- }
2199
- if (removed.size) for (const node of nodes) {
2200
- if (node.type !== "ExportNamedDeclaration") continue;
2201
- node.specifiers = node.specifiers.filter((specifier) => !removed.has(specifier));
2202
- }
2203
- return {
2204
- kinds,
2205
- allowExportAssignment
2206
- };
2207
- function isInlinableName(name) {
2208
- if (!inlineNames.has(name)) return false;
2209
- const exported = exportsMap.get(name);
2210
- return !!exported && exported.local === name && !exported.typeOnly;
2211
- }
2212
- }
2213
- /** Whether `default` is the only name the chunk exports */
2214
- function hasOnlyDefaultExport(nodes) {
2215
- let hasDefault = false;
2216
- for (const node of nodes) {
2217
- if (node.type === "ExportAllDeclaration") return false;
2218
- if (node.type === "ExportDefaultDeclaration") {
2219
- hasDefault = true;
2220
- continue;
2221
- }
2222
- if (node.type !== "ExportNamedDeclaration") continue;
2223
- if (node.declaration) return false;
2224
- for (const specifier of node.specifiers) {
2225
- if (nameOf(specifier.exported) !== "default") return false;
2226
- hasDefault = true;
2227
- }
2228
- }
2229
- return hasDefault;
2230
- }
2231
- /** `export default` only accepts a class, function or interface declaration */
2232
- function isInlinableDefaultDeclaration(node) {
2233
- return is.oneOf(node, [
2234
- "ClassDeclaration",
2235
- "FunctionDeclaration",
2236
- "TSDeclareFunction",
2237
- "TSInterfaceDeclaration"
2238
- ]);
2239
- }
2240
- function inlineExportDeclaration(decl, kind) {
2241
- if (kind === "default" && "declare" in decl) decl.declare = false;
2242
- const exported = kind === "default" ? b.ExportDefaultDeclaration({ declaration: decl }) : b.ExportNamedDeclaration({
2243
- declaration: decl,
2244
- specifiers: [],
2245
- source: null,
2246
- attributes: []
2247
- });
2248
- exported.comments = decl.comments;
2249
- decl.comments = void 0;
2250
- return exported;
2251
- }
2252
- /**
2253
- * patch `.d.ts` suffix in import source to `.js`
2254
- */
2255
- function patchImportExport(node, exportPlan, cjsDefault) {
2256
- if (node.type === "ExportNamedDeclaration" && !node.declaration && !node.source && !node.specifiers.length && !node.attributes?.length) return false;
2257
- if (node.type === "ImportDeclaration" && node.specifiers.length) {
2258
- for (const specifier of node.specifiers) if (isInfer(specifier.local)) specifier.local.name = "__Infer";
2259
- }
2260
- if (is.oneOf(node, [
2261
- "ImportDeclaration",
2262
- "ExportAllDeclaration",
2263
- "ExportNamedDeclaration"
2264
- ])) {
2265
- if (node.type === "ExportAllDeclaration" && node.source && exportPlan.typeOnlyExportAllSources.has(node.source.value)) node.exportKind = "type";
2266
- if (node.type === "ExportNamedDeclaration" && exportPlan.typeOnlyNames.size) {
2267
- for (const spec of node.specifiers) {
2268
- const name = nameOf(spec.exported);
2269
- if (exportPlan.typeOnlyNames.has(name)) {
2270
- if (spec.type === "ExportSpecifier") spec.exportKind = "type";
2271
- else node.exportKind = "type";
2272
- }
2273
- }
2274
- normalizeTypeOnlyExport(node);
2275
- }
2276
- if (node.source?.value && RE_DTS.test(node.source.value)) {
2277
- node.source.value = filename_dts_to(node.source.value, "js");
2278
- return node;
2279
- }
2280
- if (cjsDefault && exportPlan.allowExportAssignment && node.type === "ExportNamedDeclaration" && !node.source && node.specifiers.length === 1 && node.specifiers[0].type === "ExportSpecifier" && nameOf(node.specifiers[0].exported) === "default") {
2281
- const defaultExport = node.specifiers[0];
2282
- return b.TSExportAssignment({ expression: defaultExport.local });
2283
- }
2284
- }
2285
- }
2286
- function normalizeTypeOnlyExport(node) {
2287
- if (node.declaration || !node.specifiers.length) return;
2288
- for (const specifier of node.specifiers) if (specifier.type !== "ExportSpecifier" || specifier.exportKind !== "type") return;
2289
- node.exportKind = "type";
2290
- for (const specifier of node.specifiers) if (specifier.type === "ExportSpecifier") specifier.exportKind = "value";
2291
- }
2292
- /**
2293
- * Handle `__exportAll` call
2294
- */
2295
- function patchTsNamespace(nodes) {
2296
- const removed = /* @__PURE__ */ new Set();
2297
- for (const [i, node] of nodes.entries()) {
2298
- const result = getExportAllNamespace(node);
2299
- if (!result) continue;
2300
- const [binding, exports] = result;
2301
- if (!exports.properties.length) continue;
2302
- const namespaceExport = b.ExportNamedDeclaration({
2303
- declaration: null,
2304
- specifiers: exports.properties.filter((property) => property.type === "Property").map((property) => {
2305
- const local = property.value.body;
2306
- const exported = property.key;
2307
- return b.ExportSpecifier({
2308
- local,
2309
- exported
2310
- });
2311
- }),
2312
- source: null,
2313
- attributes: []
2314
- });
2315
- nodes[i] = b.TSModuleDeclaration({
2316
- id: binding,
2317
- body: b.TSModuleBlock({ body: [namespaceExport] }),
2318
- kind: "namespace",
2319
- declare: true,
2320
- global: false
2321
- });
2322
- }
2323
- return nodes.filter((node) => !removed.has(node));
2324
- }
2325
- function getExportAllNamespace(node) {
2326
- 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;
2327
- return [node.declarations[0].id, node.declarations[0].init.arguments[0]];
2328
- }
2329
- /**
2330
- * Handle `__reExport` call
2331
- */
2332
- function patchReExport(nodes) {
2333
- const exportsNames = /* @__PURE__ */ new Map();
2334
- 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);
2335
- else if (node.type === "ExpressionStatement" && node.expression.type === "CallExpression" && is.Identifier(node.expression.callee, "__reExport")) {
2336
- const args = node.expression.arguments;
2337
- exportsNames.set(args[0].name, args[1].name);
2338
- } 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({
2339
- id: b.Identifier({ name: node.declarations[0].id.name }),
2340
- typeParameters: null,
2341
- typeAnnotation: b.TSTypeReference({
2342
- typeName: b.TSQualifiedName({
2343
- left: b.Identifier({ name: exportsNames.get(node.declarations[0].init.object.name) }),
2344
- right: b.Identifier({ name: node.declarations[0].init.property.name })
2345
- }),
2346
- typeArguments: null
2347
- }),
2348
- declare: false
2349
- });
2350
- 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);
2351
- return nodes;
2352
- }
2353
- function rewriteImportExport(node, set, appendStmts) {
2354
- if (node.type === "ImportDeclaration" || node.type === "ExportNamedDeclaration" && !node.declaration) {
2355
- for (const specifier of node.specifiers) if (specifier.type === "ImportSpecifier") specifier.importKind = "value";
2356
- else if (specifier.type === "ExportSpecifier") specifier.exportKind = "value";
2357
- if (node.type === "ImportDeclaration") node.importKind = "value";
2358
- else if (node.type === "ExportNamedDeclaration") node.exportKind = "value";
2359
- return true;
2360
- } else if (node.type === "ExportAllDeclaration") {
2361
- node.exportKind = "value";
2362
- return true;
2363
- } else if (node.type === "TSImportEqualsDeclaration" || node.type === "ExportNamedDeclaration" && node.declaration?.type === "TSImportEqualsDeclaration") {
2364
- const decl = node.type === "ExportNamedDeclaration" ? node.declaration : node;
2365
- if (decl.moduleReference.type === "TSExternalModuleReference") {
2366
- set(b.ImportDeclaration({
2367
- specifiers: [b.ImportNamespaceSpecifier({ local: decl.id })],
2368
- source: decl.moduleReference.expression,
2369
- phase: null,
2370
- attributes: []
2371
- }));
2372
- if (node.type === "ExportNamedDeclaration") appendStmts.push(b.ExportNamedDeclaration({
2373
- declaration: null,
2374
- specifiers: [b.ExportSpecifier({
2375
- local: decl.id,
2376
- exported: decl.id
2377
- })],
2378
- source: null,
2379
- attributes: []
2380
- }));
2381
- return true;
2382
- }
2383
- } else if (node.type === "TSExportAssignment" && node.expression.type === "Identifier") {
2384
- set(b.ExportNamedDeclaration({
2385
- declaration: null,
2386
- specifiers: [b.ExportSpecifier({
2387
- local: node.expression,
2388
- exported: b.Identifier({ name: "default" })
2389
- })],
2390
- source: null,
2391
- attributes: []
2392
- }));
2393
- return true;
2394
- } else if (node.type === "ExportDefaultDeclaration" && node.declaration.type === "Identifier") {
2395
- set(b.ExportNamedDeclaration({
2396
- declaration: null,
2397
- specifiers: [b.ExportSpecifier({
2398
- local: node.declaration,
2399
- exported: b.Identifier({ name: "default" })
2400
- })],
2401
- source: null,
2402
- attributes: []
2403
- }));
2404
- return true;
2405
- }
2406
- return false;
2407
- }
2408
- function createFakeJsPlugin({ sourcemap, cjsDefault, sideEffects }) {
2409
- let declarationIdx = 0;
2410
- const declarationMap = /* @__PURE__ */ new Map();
2411
- const commentsMap = /* @__PURE__ */ new Map();
2412
- const moduleExportsMap = /* @__PURE__ */ new Map();
2413
- const warnedCjsDtsInputs = /* @__PURE__ */ new Set();
2414
- return {
2415
- name: "rolldown-plugin-dts:fake-js",
2416
- outputOptions(options) {
2417
- if (options.format === "cjs" || options.format === "commonjs") throw new Error("[rolldown-plugin-dts] Cannot bundle dts files with `cjs` format.");
2418
- const { chunkFileNames, entryFileNames } = options;
2419
- return {
2420
- ...options,
2421
- sourcemap: options.sourcemap || sourcemap,
2422
- chunkFileNames(chunk) {
2423
- const nameTemplate = resolveTemplateFn(chunk.isEntry ? entryFileNames || "[name].js" : chunkFileNames || "[name]-[hash].js", chunk);
2424
- if (chunk.name.endsWith(".d")) {
2425
- const renderedNameWithoutD = filename_js_to_dts(replaceTemplateName(nameTemplate, chunk.name.slice(0, -2)));
2426
- if (RE_DTS.test(renderedNameWithoutD)) return renderedNameWithoutD;
2427
- const renderedName = filename_js_to_dts(replaceTemplateName(nameTemplate, chunk.name));
2428
- if (RE_DTS.test(renderedName)) return renderedName;
2429
- }
2430
- return nameTemplate;
2431
- }
2432
- };
2433
- },
2434
- transform: {
2435
- filter: { id: RE_DTS },
2436
- handler: transform
2437
- },
2438
- renderChunk,
2439
- generateBundle(options, bundle) {
2440
- for (const chunk of Object.values(bundle)) {
2441
- if (!RE_DTS_MAP.test(chunk.fileName)) continue;
2442
- if (sourcemap) {
2443
- if (chunk.type === "chunk" || typeof chunk.source !== "string") continue;
2444
- const map = JSON.parse(chunk.source);
2445
- map.sourcesContent = void 0;
2446
- chunk.source = JSON.stringify(map);
2447
- } else delete bundle[chunk.fileName];
2448
- }
2449
- }
2450
- };
2451
- async function transform(code, id) {
2452
- let file;
2453
- try {
2454
- file = parse$1(code, {
2455
- lang: "dts",
2456
- sourceType: "module",
2457
- attachComments: true
2458
- });
2459
- } catch (error) {
2460
- 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 });
2461
- }
2462
- const { program } = file;
2463
- moduleExportsMap.set(id, await collectModuleExports(this, program.body, id));
2464
- const identifierMap = Object.create(null);
2465
- if (!warnedCjsDtsInputs.has(id) && program.body.some(isCjsDtsInputSyntax)) {
2466
- warnedCjsDtsInputs.add(id);
2467
- 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.`}`);
2468
- }
2469
- const directives = collectReferenceDirectives(file.comments);
2470
- if (directives.length) commentsMap.set(id, directives);
2471
- const appendStmts = [];
2472
- const namespaceStmts = /* @__PURE__ */ new Map();
2473
- for (const [i, stmt] of program.body.entries()) {
2474
- const setStmt = (stmt) => program.body[i] = stmt;
2475
- if (rewriteImportExport(stmt, setStmt, appendStmts)) continue;
2476
- const sideEffect = stmt.type === "TSModuleDeclaration" && stmt.kind !== "namespace";
2477
- 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}.`);
2478
- const isDefaultExport = stmt.type === "ExportDefaultDeclaration";
2479
- const isExportDecl = is.oneOf(stmt, ["ExportNamedDeclaration", "ExportDefaultDeclaration"]) && !!stmt.declaration;
2480
- const decl = isExportDecl ? stmt.declaration : stmt;
2481
- const setDecl = isExportDecl ? (decl) => stmt.declaration = decl : setStmt;
2482
- if (decl.type !== "TSDeclareFunction" && !is.Declaration(decl)) continue;
2483
- if (is.oneOf(decl, [
2484
- "TSEnumDeclaration",
2485
- "ClassDeclaration",
2486
- "FunctionDeclaration",
2487
- "TSDeclareFunction",
2488
- "TSModuleDeclaration",
2489
- "VariableDeclaration"
2490
- ])) decl.declare = true;
2491
- const bindings = [];
2492
- if (decl.type === "VariableDeclaration") bindings.push(...decl.declarations.map((decl) => decl.id));
2493
- else if ("id" in decl && decl.id) {
2494
- let binding = decl.id;
2495
- if (binding.type === "TSQualifiedName") binding = getIdFromTSEntityName(binding);
2496
- if (sideEffect) binding = b.Identifier({ name: `_${getIdentifierIndex(identifierMap, "")}` });
2497
- if (binding.type !== "Identifier") throw new Error(`Unexpected ${binding.type} declaration id`);
2498
- bindings.push(binding);
2499
- } else {
2500
- const binding = b.Identifier({ name: "export_default" });
2501
- bindings.push(binding);
2502
- decl.id = binding;
2503
- }
2504
- const params = collectParams(decl);
2505
- const childrenSet = /* @__PURE__ */ new Set();
2506
- const deps = await collectDependencies(this, decl, id, namespaceStmts, childrenSet, identifierMap);
2507
- const children = Array.from(childrenSet).filter((child) => bindings.every((b) => child !== b));
2508
- if (decl !== stmt) decl.comments = stmt.comments;
2509
- const declarationId = registerDeclaration({
2510
- decl,
2511
- deps,
2512
- bindings,
2513
- params,
2514
- children,
2515
- exportType: isDefaultExport ? "default" : isExportDecl ? "named" : void 0,
2516
- comments: decl.comments && [...decl.comments]
2517
- });
2518
- const declarationIdNode = b.Literal({
2519
- value: declarationId,
2520
- raw: String(declarationId)
2521
- });
2522
- const depsBody = b.ArrayExpression({ elements: deps });
2523
- const depsNode = b.ArrowFunctionExpression({
2524
- id: null,
2525
- generator: false,
2526
- async: false,
2527
- params: params.map(({ name }) => b.Identifier({ name })),
2528
- body: depsBody,
2529
- expression: true
2530
- });
2531
- const childrenNode = b.ArrayExpression({ elements: children.map((node) => b.Literal({
2532
- value: "",
2533
- raw: "\"\"",
2534
- start: node.start,
2535
- end: node.end
2536
- })) });
2537
- const sideEffectNode = sideEffect && b.CallExpression({
2538
- callee: b.Identifier({ name: "sideEffect" }),
2539
- arguments: [bindings[0]],
2540
- optional: false
2541
- });
2542
- const runtimeArrayNode = runtimeBindingArrayExpression([
2543
- declarationIdNode,
2544
- depsNode,
2545
- childrenNode,
2546
- ...sideEffectNode ? [sideEffectNode] : []
2547
- ]);
2548
- const runtimeAssignment = b.VariableDeclaration({
2549
- kind: "var",
2550
- declarations: [b.VariableDeclarator({
2551
- id: b.ArrayPattern({ elements: bindings.map((binding) => ({
2552
- ...binding,
2553
- typeAnnotation: null
2554
- })) }),
2555
- init: runtimeArrayNode
2556
- })]
2557
- });
2558
- if (isDefaultExport) {
2559
- appendStmts.push(b.ExportNamedDeclaration({
2560
- declaration: null,
2561
- specifiers: [b.ExportSpecifier({
2562
- local: bindings[0],
2563
- exported: b.Identifier({ name: "default" })
2564
- })],
2565
- source: null,
2566
- attributes: []
2567
- }));
2568
- setStmt(runtimeAssignment);
2569
- } else setDecl(runtimeAssignment);
2570
- }
2571
- if (sideEffects) appendStmts.push(b.ExpressionStatement({ expression: b.CallExpression({
2572
- callee: b.Identifier({ name: "sideEffect" }),
2573
- arguments: [],
2574
- optional: false
2575
- }) }));
2576
- program.body = [
2577
- ...Array.from(namespaceStmts.values(), ({ stmt }) => stmt),
2578
- ...program.body,
2579
- ...appendStmts
2580
- ];
2581
- const result = generate(program, {
2582
- comments: false,
2583
- ...sourcemap && { sourceMaps: {
2584
- source: code,
2585
- sourceFileName: id
2586
- } }
2587
- });
2588
- return {
2589
- code: result.code,
2590
- map: result.map ?? null
2591
- };
2592
- }
2593
- function renderChunk(code, chunk) {
2594
- if (!RE_DTS.test(chunk.fileName)) return;
2595
- let file;
2596
- try {
2597
- file = parse$1(code, {
2598
- lang: "ts",
2599
- sourceType: "module",
2600
- attachComments: true
2601
- });
2602
- } catch (error) {
2603
- 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 });
2604
- }
2605
- const { program } = file;
2606
- program.body = patchTsNamespace(program.body);
2607
- program.body = patchReExport(program.body);
2608
- const exportPlan = planChunkExports(chunk, moduleExportsMap, program.body, getDeclaration, cjsDefault);
2609
- function renderStatement(node) {
2610
- if (isHelperImport(node)) return null;
2611
- if (node.type === "ExpressionStatement") return null;
2612
- const newNode = patchImportExport(node, exportPlan, cjsDefault);
2613
- if (newNode || newNode === false) return newNode;
2614
- if (node.type !== "VariableDeclaration") return node;
2615
- if (!isRuntimeBindingVariableDeclaration(node)) return null;
2616
- const decl = node.declarations[0];
2617
- const [declarationIdNode, depsFn, children] = decl.init.elements;
2618
- const declarationId = declarationIdNode.value;
2619
- const declaration = getDeclaration(declarationId);
2620
- declaration.decl.comments = declaration.comments && [...declaration.comments];
2621
- if (sourcemap) walk(declaration.decl, { enter(node) {
2622
- node.start = void 0;
2623
- node.end = void 0;
2624
- } });
2625
- for (const [i, id] of decl.id.elements.entries()) {
2626
- const transformedBinding = {
2627
- ...id,
2628
- typeAnnotation: declaration.bindings[i].typeAnnotation
2629
- };
2630
- overwriteNode(declaration.bindings[i], transformedBinding);
2631
- }
2632
- if (sourcemap) for (const [i, child] of children.elements.entries()) Object.assign(declaration.children[i], {
2633
- start: child.start,
2634
- end: child.end
2635
- });
2636
- const transformedParams = depsFn.params;
2637
- for (const [i, transformedParam] of transformedParams.entries()) {
2638
- const transformedName = transformedParam.name;
2639
- for (const originalTypeParam of declaration.params[i].typeParams) originalTypeParam.name = transformedName;
2640
- }
2641
- const transformedDeps = depsFn.body.elements;
2642
- for (const [i, originalDep] of declaration.deps.entries()) {
2643
- let transformedDep = transformedDeps[i];
2644
- if (transformedDep.type === "UnaryExpression" && transformedDep.operator === "void") {
2645
- const undefinedDep = b.Identifier({ name: "undefined" });
2646
- undefinedDep.start = transformedDep.start;
2647
- undefinedDep.end = transformedDep.end;
2648
- transformedDep = undefinedDep;
2649
- } else if (isInfer(transformedDep)) transformedDep.name = "__Infer";
2650
- if (originalDep.replace) originalDep.replace(transformedDep);
2651
- else Object.assign(originalDep, transformedDep);
2652
- }
2653
- const kind = exportPlan.inlineKinds.get(declarationId);
2654
- return inheritNodeComments(node, kind ? inlineExportDeclaration(declaration.decl, kind) : declaration.decl);
2655
- }
2656
- const body = [];
2657
- let danglingComments = [];
2658
- for (const node of program.body) {
2659
- const rendered = renderStatement(node);
2660
- if (rendered === false) {
2661
- danglingComments.push(...pragmaComments(node));
2662
- continue;
2663
- }
2664
- if (!rendered) continue;
2665
- if (danglingComments.length) {
2666
- rendered.comments = [...danglingComments, ...rendered.comments || []];
2667
- danglingComments = [];
2668
- }
2669
- body.push(rendered);
2670
- }
2671
- const lastNode = body.at(-1);
2672
- if (danglingComments.length && lastNode) lastNode.comments = [...lastNode.comments || [], ...danglingComments.map((comment) => ({
2673
- ...comment,
2674
- position: "after",
2675
- sameLine: false
2676
- }))];
2677
- program.body = body;
2678
- if (program.body.length === 0) return {
2679
- code: EMPTY_STUB,
2680
- map: null
2681
- };
2682
- if (!program.body.some(isModuleStatement)) program.body.push(b.ExportNamedDeclaration({
2683
- declaration: null,
2684
- specifiers: [],
2685
- source: null,
2686
- attributes: []
2687
- }));
2688
- const comments = /* @__PURE__ */ new Set();
2689
- const commentsValue = /* @__PURE__ */ new Set();
2690
- for (const id of chunk.moduleIds) {
2691
- const preserveComments = commentsMap.get(id);
2692
- if (preserveComments) {
2693
- preserveComments.forEach((c) => {
2694
- const id = c.type + c.value;
2695
- if (commentsValue.has(id)) return;
2696
- commentsValue.add(id);
2697
- comments.add(c);
2698
- });
2699
- commentsMap.delete(id);
2700
- }
2701
- }
2702
- if (comments.size) {
2703
- program.body[0].comments ||= [];
2704
- program.body[0].comments.unshift(...Array.from(comments, (c) => ({
2705
- type: c.type,
2706
- value: c.value,
2707
- position: "before",
2708
- sameLine: false
2709
- })));
2710
- }
2711
- const result = generate(program, {
2712
- comments: true,
2713
- ...sourcemap && { sourceMaps: {
2714
- source: code,
2715
- sourceFileName: chunk.fileName
2716
- } }
2717
- });
2718
- return {
2719
- code: result.code.trimEnd(),
2720
- map: result.map ?? null
2721
- };
2722
- }
2723
- function registerDeclaration(info) {
2724
- const declarationId = declarationIdx++;
2725
- declarationMap.set(declarationId, info);
2726
- return declarationId;
2727
- }
2728
- function getDeclaration(declarationId) {
2729
- return declarationMap.get(declarationId);
2730
- }
2731
- }
2732
- function isModuleStatement(node) {
2733
- return is.oneOf(node, [
2734
- "ImportDeclaration",
2735
- "ExportAllDeclaration",
2736
- "ExportDefaultDeclaration",
2737
- "ExportNamedDeclaration",
2738
- "TSExportAssignment"
2739
- ]) || node.type === "TSImportEqualsDeclaration" && node.moduleReference.type === "TSExternalModuleReference";
2740
- }
2741
- const debug$3 = createDebug("rolldown-plugin-dts:vue");
2742
- const RE_VUE = /\.vue$/;
2743
- function createVueLanguage(userOptions = {}) {
2744
- requireTSApi("Vue");
2745
- const [volarTypeScript, vue] = loadVueLanguageTools();
2746
- const getLanguagePlugin = (ts, options) => {
2747
- const $rootDir = options.options.$rootDir;
2748
- const $configRaw = options.options.$configRaw;
2749
- const resolver = new vue.CompilerOptionsResolver(ts, ts.sys.readFile);
2750
- const rawOptions = {
2751
- ...$configRaw?.vueCompilerOptions,
2752
- ...userOptions?.vueCompilerOptions
2753
- };
2754
- resolver.addConfig(rawOptions, $rootDir);
2755
- const vueOptions = resolver.build();
2756
- return vue.createVueLanguagePlugin(ts, options.options, vueOptions, (id) => id);
2757
- };
2758
- return {
2759
- extensionPatterns: [RE_VUE],
2760
- tsFileExtensionInfos: [{
2761
- extension: "vue",
2762
- isMixedContent: true,
2763
- scriptKind: 7
2764
- }],
2765
- volarTypeScript,
2766
- createVolarPlugins(ts, options) {
2767
- return [getLanguagePlugin(ts, options)];
2768
- },
2769
- toTsFilename(id) {
2770
- return id.replace(RE_VUE, ".vue.ts");
2771
- }
2772
- };
2773
- }
2774
- function loadVueLanguageTools() {
2775
- debug$3("loading vue language tools");
2776
- try {
2777
- const vueTscPath = require.resolve("vue-tsc");
2778
- return [require(require.resolve("@volar/typescript", { paths: [vueTscPath] })), require(require.resolve("@vue/language-core", { paths: [vueTscPath] }))];
2779
- } catch (cause) {
2780
- debug$3("vue language tools not found", cause);
2781
- throw new Error("Failed to load Vue language tools. Please install `vue-tsc` manually.", { cause });
2782
- }
2783
- }
2784
- const debug$2 = createDebug("rolldown-plugin-dts:options");
2785
- let warnedTsgo = false;
2786
- 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 }) {
2787
- let resolvedTsconfig;
2788
- if (tsconfig === true || tsconfig == null) {
2789
- const { config, path } = mt(cwd) || {};
2790
- tsconfig = path;
2791
- resolvedTsconfig = config;
2792
- } else if (typeof tsconfig === "string") {
2793
- tsconfig = path.resolve(cwd || process.cwd(), tsconfig);
2794
- resolvedTsconfig = te(tsconfig).config;
2795
- } else tsconfig = void 0;
2796
- compilerOptions = {
2797
- ...resolvedTsconfig?.compilerOptions,
2798
- ...compilerOptions
2799
- };
2800
- incremental ||= compilerOptions.incremental || !!compilerOptions.tsBuildInfoFile;
2801
- sourcemap ??= !!compilerOptions.declarationMap;
2802
- compilerOptions.declarationMap = sourcemap;
2803
- const tsconfigRaw = {
2804
- ...resolvedTsconfig,
2805
- ...overriddenTsconfigRaw,
2806
- compilerOptions
2807
- };
2808
- customLanguages ||= [];
2809
- if (vue) customLanguages.push(createVueLanguage(typeof vue === "object" ? vue : {}));
2810
- const languageContext = new LanguageContext(customLanguages);
2811
- if (customLanguages.length) {
2812
- if (languageContext.isUsingVolar()) {
2813
- requireTSApi("custom languages", ". Custom languages (including the `vue` option) require the TypeScript API.");
2814
- if (generator && generator !== "tsc") throw new Error("Volar-based custom languages (including the `vue` option) require the `tsc` generator.");
2815
- generator = "tsc";
2816
- } else if (generator === "tsgo") throw new Error("The `tsgo` generator does not support custom languages.");
2817
- }
2818
- if (!generator) {
2819
- if (compilerOptions.isolatedDeclarations) generator = "oxc";
2820
- else if (isTS70Installed()) {
2821
- 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.");
2822
- generator = "tsgo";
2823
- } else generator = "tsc";
2824
- }
2825
- oxc ||= {};
2826
- tsgo ||= {};
2827
- if (generator === "tsc") requireTSApi("tsc", ", or enable `isolatedDeclarations` in your `tsconfig.json` to use Oxc instead.");
2828
- else if (generator === "tsgo") {
2829
- if (!tsconfig) throw new Error("The `tsgo` generator requires a tsconfig file to be specified.");
2830
- if (!warnedTsgo) {
2831
- warnedTsgo = true;
2832
- logger.warn("TypeScript 7.0 does not yet have a stable API and is experimental. Some options will be unavailable.");
2833
- }
2834
- tsgo.path ??= resolveTsgoPath(logger);
2835
- }
2836
- oxc.stripInternal ??= !!compilerOptions.stripInternal;
2837
- oxc.sourcemap = !!compilerOptions.declarationMap;
2838
- emitJs ??= !!(compilerOptions.checkJs || compilerOptions.allowJs);
2839
- const resolved = {
2840
- generator,
2841
- entry: entry ? Array.isArray(entry) ? entry : [entry] : void 0,
2842
- cwd,
2843
- dtsInput,
2844
- emitDtsOnly,
2845
- tsconfig,
2846
- tsconfigRaw,
2847
- sourcemap,
2848
- resolver,
2849
- cjsDefault,
2850
- sideEffects,
2851
- build,
2852
- incremental,
2853
- parallel,
2854
- eager,
2855
- newContext,
2856
- emitJs,
2857
- languageContext,
2858
- oxc,
2859
- tsgo,
2860
- logger
2861
- };
2862
- debug$2("Resolved Options: %O", resolved);
2863
- return resolved;
2864
- }
2865
- const debug$1 = createDebug("rolldown-plugin-dts:resolver");
2866
- function createDtsResolvePlugin({ cwd, tsconfig, tsconfigRaw, resolver, sideEffects, languageContext }) {
2867
- function isSourceFile(id) {
2868
- return RE_TS.test(id) || RE_JSON.test(id) || languageContext.isCustomLanguageFile(id);
2869
- }
2870
- const baseDtsResolver = createResolver({
2871
- tsconfig,
2872
- resolveNodeModules: true,
2873
- ResolverFactory
2874
- });
2875
- const moduleSideEffects = sideEffects ? true : null;
2876
- return {
2877
- name: "rolldown-plugin-dts:resolver",
2878
- resolveId: {
2879
- order: "pre",
2880
- filter: [include(importerId(RE_DTS))],
2881
- async handler(id, importer, options) {
2882
- if (!importer) return;
2883
- const external = {
2884
- id,
2885
- external: true,
2886
- moduleSideEffects: sideEffects
2887
- };
2888
- const rolldownResolution = await this.resolve(id, importer, options);
2889
- debug$1("Rolldown resolution for dts import %O from %O: %O", id, importer, rolldownResolution);
2890
- if (rolldownResolution?.external) {
2891
- debug$1("Rolldown marked dts import as external:", id);
2892
- return rolldownResolution;
2893
- }
2894
- const dtsResolution = await resolveDtsPath(id, importer, rolldownResolution);
2895
- debug$1("Dts resolution for dts import %O from %O: %O", id, importer, dtsResolution);
2896
- if (!dtsResolution) {
2897
- if (RE_CSS.test(id)) {
2898
- debug$1("Externalizing css import:", id);
2899
- return external;
2900
- }
2901
- debug$1("Unresolvable dts import:", id, "from", importer);
2902
- return isFilePath(id) ? null : external;
2903
- }
2904
- if (RE_DTS.test(dtsResolution)) {
2905
- debug$1("Resolving dts import to declaration file:", id);
2906
- return {
2907
- id: dtsResolution,
2908
- moduleSideEffects
2909
- };
2910
- }
2911
- if (isSourceFile(dtsResolution)) {
2912
- debug$1("Resolving dts import to source file:", id);
2913
- await this.load({ id: dtsResolution });
2914
- return {
2915
- id: filename_to_dts(dtsResolution, languageContext),
2916
- moduleSideEffects
2917
- };
2918
- }
2919
- }
2920
- }
2921
- };
2922
- async function resolveDtsPath(id, importer, rolldownResolution) {
2923
- let dtsPath;
2924
- if (resolver === "tsc") {
2925
- const { tscResolve } = await import("./resolver-DE0_sy8o-Bi3xbRxi.js");
2926
- dtsPath = tscResolve(id, importer, cwd, tsconfig, tsconfigRaw);
2927
- } else dtsPath = baseDtsResolver(id, importer);
2928
- debug$1("Using %s for dts import: %O -> %O", resolver, id, dtsPath);
2929
- if (dtsPath) dtsPath = path.normalize(dtsPath);
2930
- if (!dtsPath || !isSourceFile(dtsPath)) {
2931
- if (rolldownResolution && isFilePath(rolldownResolution.id) && isSourceFile(rolldownResolution.id) && !rolldownResolution.external) return rolldownResolution.id;
2932
- return null;
2933
- }
2934
- return dtsPath;
2935
- }
2936
- }
2937
- function isFilePath(id) {
2938
- return id.startsWith(".") || path.isAbsolute(id);
2939
- }
2940
- const debug = createDebug("rolldown-plugin-dts:options");
2941
- function dts(options = {}) {
2942
- debug("resolving dts options");
2943
- const resolved = resolveOptions(options);
2944
- debug("resolved dts options %o", resolved);
2945
- const plugins = [];
2946
- if (options.dtsInput) plugins.push(createDtsInputPlugin(resolved));
2947
- else plugins.push(createGeneratePlugin(resolved));
2948
- plugins.push(createDtsResolvePlugin(resolved), createFakeJsPlugin(resolved));
2949
- return plugins;
2950
- }
2951
- //#endregion
2952
- export { dts, globalContext as t };