@ohos-ports/rolldown 1.2.6-beta.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 (54) hide show
  1. package/LICENSE +25 -0
  2. package/README.md +11 -0
  3. package/THIRD-PARTY-LICENSE +33 -0
  4. package/bin/cli.mjs +11 -0
  5. package/dist/cli.d.mts +1 -0
  6. package/dist/cli.mjs +1208 -0
  7. package/dist/config.d.mts +26 -0
  8. package/dist/config.mjs +4 -0
  9. package/dist/experimental-default-runtime.mjs +116 -0
  10. package/dist/experimental-index.d.mts +324 -0
  11. package/dist/experimental-index.mjs +383 -0
  12. package/dist/experimental-runtime-base.mjs +95 -0
  13. package/dist/experimental-runtime-types.d.ts +177 -0
  14. package/dist/experimental-runtime.d.ts +177 -0
  15. package/dist/experimental-runtime.mjs +257 -0
  16. package/dist/filter-index.d.mts +196 -0
  17. package/dist/filter-index.mjs +376 -0
  18. package/dist/get-log-filter.d.mts +3 -0
  19. package/dist/get-log-filter.mjs +68 -0
  20. package/dist/index.d.mts +4 -0
  21. package/dist/index.mjs +56 -0
  22. package/dist/parallel-plugin-worker.d.mts +1 -0
  23. package/dist/parallel-plugin-worker.mjs +29 -0
  24. package/dist/parallel-plugin.d.mts +12 -0
  25. package/dist/parallel-plugin.mjs +6 -0
  26. package/dist/parse-ast-index.d.mts +30 -0
  27. package/dist/parse-ast-index.mjs +60 -0
  28. package/dist/plugins-index.d.mts +32 -0
  29. package/dist/plugins-index.mjs +40 -0
  30. package/dist/shared/binding-CtPG-2KR.mjs +675 -0
  31. package/dist/shared/binding-Og__jmUi.d.mts +2065 -0
  32. package/dist/shared/bindingify-input-options-4JJxbZl2.mjs +2416 -0
  33. package/dist/shared/constructors-Qrp2Xr6w.d.mts +35 -0
  34. package/dist/shared/constructors-ltBDfHX1.mjs +69 -0
  35. package/dist/shared/create-bundler-option-DSPiA5F7.mjs +3220 -0
  36. package/dist/shared/define-config-Demdg3_4.mjs +6 -0
  37. package/dist/shared/define-config-Nbz-lniw.d.mts +4101 -0
  38. package/dist/shared/dist-DKbukT1H.mjs +154 -0
  39. package/dist/shared/error-HDibX49O.mjs +85 -0
  40. package/dist/shared/get-log-filter-AjBknEEO.d.mts +34 -0
  41. package/dist/shared/load-config-BMUrE9HH.mjs +137 -0
  42. package/dist/shared/logging-xuHO4mAy.d.mts +50 -0
  43. package/dist/shared/logs-DmYCAKcW.mjs +192 -0
  44. package/dist/shared/misc-DOSKtd97.mjs +29 -0
  45. package/dist/shared/normalize-string-or-regex-DWz4it3p.mjs +68 -0
  46. package/dist/shared/parse-D0g29RgN.mjs +74 -0
  47. package/dist/shared/prompt-CH6TK0bC.mjs +885 -0
  48. package/dist/shared/resolve-tsconfig-CLYpUIZC.mjs +128 -0
  49. package/dist/shared/rolldown-C9Hfg50O.mjs +179 -0
  50. package/dist/shared/transform-DR4CXeQm.d.mts +152 -0
  51. package/dist/shared/watch-UbzgabQn.mjs +377 -0
  52. package/dist/utils-index.d.mts +375 -0
  53. package/dist/utils-index.mjs +2416 -0
  54. package/package.json +159 -0
@@ -0,0 +1,2416 @@
1
+ import { n as __toESM, t as require_binding } from "./binding-CtPG-2KR.mjs";
2
+ import { i as logFailedValidation, l as logPluginError, n as error, o as logInvalidLogPosition, r as logCycleLoading, t as augmentCodeLocation } from "./logs-DmYCAKcW.mjs";
3
+ import { i as bindingifyManifestPlugin, n as BuiltinPlugin, r as bindingifyBuiltInPlugin, t as normalizedStringOrRegex } from "./normalize-string-or-regex-DWz4it3p.mjs";
4
+ import { i as noop, n as isPathFragment, o as unreachable, s as unsupported, t as arraify } from "./misc-DOSKtd97.mjs";
5
+ import { a as bindingifySourcemap, i as unwrapBindingResult, t as aggregateBindingErrorsIntoJsError } from "./error-HDibX49O.mjs";
6
+ import { parseAst } from "../parse-ast-index.mjs";
7
+ import fs from "node:fs";
8
+ import path from "node:path";
9
+ import * as filter from "@rolldown/pluginutils";
10
+ import fsp from "node:fs/promises";
11
+ import { fileURLToPath } from "node:url";
12
+ //#region package.json
13
+ var version = "1.2.6";
14
+ var description = "Fast JavaScript/TypeScript bundler in Rust with Rollup-compatible API.";
15
+ //#endregion
16
+ //#region src/constants/version.ts
17
+ /**
18
+ * The version of Rolldown.
19
+ * @example `'1.0.0'`
20
+ *
21
+ * @category Plugin APIs
22
+ */
23
+ const VERSION = version;
24
+ //#endregion
25
+ //#region src/log/logging.ts
26
+ const LOG_LEVEL_SILENT = "silent";
27
+ const LOG_LEVEL_ERROR = "error";
28
+ const LOG_LEVEL_WARN = "warn";
29
+ const LOG_LEVEL_INFO = "info";
30
+ const LOG_LEVEL_DEBUG = "debug";
31
+ const logLevelPriority = {
32
+ [LOG_LEVEL_DEBUG]: 0,
33
+ [LOG_LEVEL_INFO]: 1,
34
+ [LOG_LEVEL_WARN]: 2,
35
+ [LOG_LEVEL_SILENT]: 3
36
+ };
37
+ //#endregion
38
+ //#region src/log/log-handler.ts
39
+ const normalizeLog = (log) => typeof log === "string" ? { message: log } : typeof log === "function" ? normalizeLog(log()) : log;
40
+ function getLogHandler(level, code, logger, pluginName, logLevel) {
41
+ if (logLevelPriority[level] < logLevelPriority[logLevel]) return noop;
42
+ return (log, pos) => {
43
+ if (pos != null) logger(LOG_LEVEL_WARN, logInvalidLogPosition(pluginName));
44
+ log = normalizeLog(log);
45
+ if (log.code && !log.pluginCode) log.pluginCode = log.code;
46
+ log.code = code;
47
+ log.plugin = pluginName;
48
+ logger(level, log);
49
+ };
50
+ }
51
+ //#endregion
52
+ //#region src/utils/normalize-hook.ts
53
+ function normalizeHook(hook) {
54
+ if (typeof hook === "function" || typeof hook === "string") return {
55
+ handler: hook,
56
+ options: {},
57
+ meta: {}
58
+ };
59
+ if (typeof hook === "object" && hook !== null) {
60
+ const { handler, order, ...options } = hook;
61
+ return {
62
+ handler,
63
+ options,
64
+ meta: { order }
65
+ };
66
+ }
67
+ unreachable("Invalid hook type");
68
+ }
69
+ //#endregion
70
+ //#region src/utils/parallel-plugin.ts
71
+ /**
72
+ * Returns the `_parallel` marker of a parallel plugin, or `undefined` if the
73
+ * given plugin is not one.
74
+ *
75
+ * Detection is descriptor-based instead of using the `in` operator: only an
76
+ * own data property named `_parallel` with the expected shape counts. This
77
+ * avoids false positives from inherited or accessor `_parallel` properties on
78
+ * regular plugins, and guarantees that callers can safely read `fileUrl` and
79
+ * `options` from the returned value.
80
+ */
81
+ function getParallelPluginInfo(plugin) {
82
+ if (plugin === null || typeof plugin !== "object") return;
83
+ const descriptor = Object.getOwnPropertyDescriptor(plugin, "_parallel");
84
+ if (!descriptor || !("value" in descriptor)) return;
85
+ const parallel = descriptor.value;
86
+ if (parallel === null || typeof parallel !== "object" || typeof parallel.fileUrl !== "string") return;
87
+ return parallel;
88
+ }
89
+ //#endregion
90
+ //#region src/plugin/minimal-plugin-context.ts
91
+ var MinimalPluginContextImpl = class {
92
+ pluginName;
93
+ hookName;
94
+ info;
95
+ warn;
96
+ debug;
97
+ meta;
98
+ constructor(onLog, logLevel, pluginName, watchMode, hookName) {
99
+ this.pluginName = pluginName;
100
+ this.hookName = hookName;
101
+ this.debug = getLogHandler(LOG_LEVEL_DEBUG, "PLUGIN_LOG", onLog, pluginName, logLevel);
102
+ this.info = getLogHandler(LOG_LEVEL_INFO, "PLUGIN_LOG", onLog, pluginName, logLevel);
103
+ this.warn = getLogHandler(LOG_LEVEL_WARN, "PLUGIN_WARNING", onLog, pluginName, logLevel);
104
+ this.meta = {
105
+ rollupVersion: "4.23.0",
106
+ rolldownVersion: VERSION,
107
+ watchMode
108
+ };
109
+ }
110
+ error(e) {
111
+ return error(logPluginError(normalizeLog(e), this.pluginName, { hook: this.hookName }));
112
+ }
113
+ };
114
+ //#endregion
115
+ //#region src/types/plain-object-like.ts
116
+ var import_binding = /* @__PURE__ */ __toESM(require_binding(), 1);
117
+ const LAZY_FIELDS_KEY = Symbol("__lazy_fields__");
118
+ /**
119
+ * Base class for classes that use `@lazyProp` decorated properties.
120
+ *
121
+ * **Design Pattern in Rolldown:**
122
+ * This is a common pattern in Rolldown due to its three-layer architecture:
123
+ * TypeScript API → NAPI Bindings → Rust Core
124
+ *
125
+ * **Why we use getters:**
126
+ * For performance - to lazily fetch data from Rust bindings only when needed,
127
+ * rather than eagerly fetching all data during object construction.
128
+ *
129
+ * **The problem:**
130
+ * Getters defined on class prototypes are non-enumerable by default, which breaks:
131
+ * - Object spread operators ({...obj})
132
+ * - Object.keys() and similar methods
133
+ * - Standard JavaScript object semantics
134
+ *
135
+ * **The solution:**
136
+ * This base class automatically converts `@lazyProp` decorated getters into
137
+ * own enumerable getters on each instance during construction.
138
+ *
139
+ * **Result:**
140
+ * Objects get both lazy-loading performance benefits AND plain JavaScript object behavior.
141
+ *
142
+ * @example
143
+ * ```typescript
144
+ * class MyClass extends PlainObjectLike {
145
+ * @lazyProp
146
+ * get myProp() {
147
+ * return fetchFromRustBinding();
148
+ * }
149
+ * }
150
+ * ```
151
+ */
152
+ var PlainObjectLike = class {
153
+ constructor() {
154
+ setupLazyProperties(this);
155
+ }
156
+ };
157
+ /**
158
+ * Set up lazy properties as own getters on an instance.
159
+ * This is called automatically by the `PlainObjectLike` base class constructor.
160
+ *
161
+ * @param instance - The instance to set up lazy properties on
162
+ * @internal
163
+ */
164
+ function setupLazyProperties(instance) {
165
+ const lazyFields = instance.constructor[LAZY_FIELDS_KEY];
166
+ if (!lazyFields) return;
167
+ for (const [propertyKey, originalGetter] of lazyFields.entries()) {
168
+ let cachedValue;
169
+ let hasValue = false;
170
+ Object.defineProperty(instance, propertyKey, {
171
+ get() {
172
+ if (!hasValue) {
173
+ cachedValue = originalGetter.call(this);
174
+ hasValue = true;
175
+ }
176
+ return cachedValue;
177
+ },
178
+ enumerable: true,
179
+ configurable: true
180
+ });
181
+ }
182
+ }
183
+ /**
184
+ * Get all lazy field names from a class instance.
185
+ *
186
+ * @param instance - Instance to inspect
187
+ * @returns Set of lazy property names
188
+ */
189
+ function getLazyFields(instance) {
190
+ const lazyFields = instance.constructor[LAZY_FIELDS_KEY];
191
+ return lazyFields ? new Set(lazyFields.keys()) : /* @__PURE__ */ new Set();
192
+ }
193
+ //#endregion
194
+ //#region src/decorators/lazy.ts
195
+ /**
196
+ * Decorator that marks a getter as lazy-evaluated and cached.
197
+ *
198
+ * **What "lazy" means here:**
199
+ * 1. Data is lazily fetched from Rust bindings only when the property is accessed (not eagerly on construction)
200
+ * 2. Once fetched, the data is cached for subsequent accesses (performance optimization)
201
+ * 3. Despite being a getter, it behaves like a plain object property (enumerable, appears in Object.keys())
202
+ *
203
+ * **Important**: Properties decorated with `@lazyProp` are defined as own enumerable
204
+ * properties on each instance (not on the prototype). This ensures they:
205
+ * - Appear in Object.keys() and Object.getOwnPropertyNames()
206
+ * - Are included in object spreads ({...obj})
207
+ * - Are enumerable in for...in loops
208
+ *
209
+ * Classes using this decorator must extend `PlainObjectLike` base class.
210
+ *
211
+ * @example
212
+ * ```typescript
213
+ * class MyClass extends PlainObjectLike {
214
+ * @lazyProp
215
+ * get expensiveValue() {
216
+ * return someExpensiveComputation();
217
+ * }
218
+ * }
219
+ * ```
220
+ */
221
+ function lazyProp(target, propertyKey, descriptor) {
222
+ if (!target.constructor[LAZY_FIELDS_KEY]) target.constructor[LAZY_FIELDS_KEY] = /* @__PURE__ */ new Map();
223
+ const originalGetter = descriptor.get;
224
+ target.constructor[LAZY_FIELDS_KEY].set(propertyKey, originalGetter);
225
+ return {
226
+ enumerable: false,
227
+ configurable: true
228
+ };
229
+ }
230
+ //#endregion
231
+ //#region src/utils/asset-source.ts
232
+ function transformAssetSource(bindingAssetSource) {
233
+ return bindingAssetSource.inner;
234
+ }
235
+ function bindingAssetSource(source) {
236
+ return { inner: source };
237
+ }
238
+ //#endregion
239
+ //#region \0@oxc-project+runtime@0.147.0/helpers/esm/decorate.js
240
+ function __decorate(decorators, target, key, desc) {
241
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
242
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
243
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
244
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
245
+ }
246
+ //#endregion
247
+ //#region src/types/output-asset-impl.ts
248
+ var OutputAssetImpl = class extends PlainObjectLike {
249
+ bindingAsset;
250
+ type = "asset";
251
+ constructor(bindingAsset) {
252
+ super();
253
+ this.bindingAsset = bindingAsset;
254
+ }
255
+ get fileName() {
256
+ return this.bindingAsset.getFileName();
257
+ }
258
+ get originalFileName() {
259
+ return this.bindingAsset.getOriginalFileName() || null;
260
+ }
261
+ get originalFileNames() {
262
+ return this.bindingAsset.getOriginalFileNames();
263
+ }
264
+ get name() {
265
+ return this.bindingAsset.getName() ?? void 0;
266
+ }
267
+ get names() {
268
+ return this.bindingAsset.getNames();
269
+ }
270
+ get source() {
271
+ return transformAssetSource(this.bindingAsset.getSource());
272
+ }
273
+ __rolldown_external_memory_handle__(keepDataAlive) {
274
+ if (keepDataAlive) this.#evaluateAllLazyFields();
275
+ return this.bindingAsset.dropInner();
276
+ }
277
+ #evaluateAllLazyFields() {
278
+ for (const field of getLazyFields(this)) this[field];
279
+ }
280
+ };
281
+ __decorate([lazyProp], OutputAssetImpl.prototype, "fileName", null);
282
+ __decorate([lazyProp], OutputAssetImpl.prototype, "originalFileName", null);
283
+ __decorate([lazyProp], OutputAssetImpl.prototype, "originalFileNames", null);
284
+ __decorate([lazyProp], OutputAssetImpl.prototype, "name", null);
285
+ __decorate([lazyProp], OutputAssetImpl.prototype, "names", null);
286
+ __decorate([lazyProp], OutputAssetImpl.prototype, "source", null);
287
+ //#endregion
288
+ //#region src/utils/transform-rendered-module.ts
289
+ function transformToRenderedModule(bindingRenderedModule) {
290
+ return {
291
+ get code() {
292
+ return bindingRenderedModule.code;
293
+ },
294
+ get renderedLength() {
295
+ return bindingRenderedModule.code?.length || 0;
296
+ },
297
+ get renderedExports() {
298
+ return bindingRenderedModule.renderedExports;
299
+ }
300
+ };
301
+ }
302
+ //#endregion
303
+ //#region src/utils/transform-rendered-chunk.ts
304
+ function transformRenderedChunk(chunk) {
305
+ let modules = null;
306
+ return {
307
+ type: "chunk",
308
+ get name() {
309
+ return chunk.name;
310
+ },
311
+ get isEntry() {
312
+ return chunk.isEntry;
313
+ },
314
+ get isDynamicEntry() {
315
+ return chunk.isDynamicEntry;
316
+ },
317
+ get facadeModuleId() {
318
+ return chunk.facadeModuleId;
319
+ },
320
+ get moduleIds() {
321
+ return chunk.moduleIds;
322
+ },
323
+ get exports() {
324
+ return chunk.exports;
325
+ },
326
+ get fileName() {
327
+ return chunk.fileName;
328
+ },
329
+ get imports() {
330
+ return chunk.imports;
331
+ },
332
+ get dynamicImports() {
333
+ return chunk.dynamicImports;
334
+ },
335
+ get modules() {
336
+ if (!modules) modules = transformChunkModules(chunk.modules);
337
+ return modules;
338
+ }
339
+ };
340
+ }
341
+ function transformChunkModules(modules) {
342
+ const result = {};
343
+ for (let i = 0; i < modules.values.length; i++) {
344
+ let key = modules.keys[i];
345
+ const mod = modules.values[i];
346
+ result[key] = transformToRenderedModule(mod);
347
+ }
348
+ return result;
349
+ }
350
+ //#endregion
351
+ //#region src/types/output-chunk-impl.ts
352
+ var OutputChunkImpl = class extends PlainObjectLike {
353
+ bindingChunk;
354
+ type = "chunk";
355
+ constructor(bindingChunk) {
356
+ super();
357
+ this.bindingChunk = bindingChunk;
358
+ }
359
+ get fileName() {
360
+ return this.bindingChunk.getFileName();
361
+ }
362
+ get name() {
363
+ return this.bindingChunk.getName();
364
+ }
365
+ get exports() {
366
+ return this.bindingChunk.getExports();
367
+ }
368
+ get isEntry() {
369
+ return this.bindingChunk.getIsEntry();
370
+ }
371
+ get facadeModuleId() {
372
+ return this.bindingChunk.getFacadeModuleId() || null;
373
+ }
374
+ get isDynamicEntry() {
375
+ return this.bindingChunk.getIsDynamicEntry();
376
+ }
377
+ get sourcemapFileName() {
378
+ return this.bindingChunk.getSourcemapFileName() || null;
379
+ }
380
+ get preliminaryFileName() {
381
+ return this.bindingChunk.getPreliminaryFileName();
382
+ }
383
+ get code() {
384
+ return this.bindingChunk.getCode();
385
+ }
386
+ get modules() {
387
+ return transformChunkModules(this.bindingChunk.getModules());
388
+ }
389
+ get imports() {
390
+ return this.bindingChunk.getImports();
391
+ }
392
+ get dynamicImports() {
393
+ return this.bindingChunk.getDynamicImports();
394
+ }
395
+ get moduleIds() {
396
+ return this.bindingChunk.getModuleIds();
397
+ }
398
+ get map() {
399
+ const mapString = this.bindingChunk.getMap();
400
+ return mapString ? transformToRollupSourceMap(mapString) : null;
401
+ }
402
+ __rolldown_external_memory_handle__(keepDataAlive) {
403
+ if (keepDataAlive) this.#evaluateAllLazyFields();
404
+ return this.bindingChunk.dropInner();
405
+ }
406
+ #evaluateAllLazyFields() {
407
+ for (const field of getLazyFields(this)) this[field];
408
+ }
409
+ };
410
+ __decorate([lazyProp], OutputChunkImpl.prototype, "fileName", null);
411
+ __decorate([lazyProp], OutputChunkImpl.prototype, "name", null);
412
+ __decorate([lazyProp], OutputChunkImpl.prototype, "exports", null);
413
+ __decorate([lazyProp], OutputChunkImpl.prototype, "isEntry", null);
414
+ __decorate([lazyProp], OutputChunkImpl.prototype, "facadeModuleId", null);
415
+ __decorate([lazyProp], OutputChunkImpl.prototype, "isDynamicEntry", null);
416
+ __decorate([lazyProp], OutputChunkImpl.prototype, "sourcemapFileName", null);
417
+ __decorate([lazyProp], OutputChunkImpl.prototype, "preliminaryFileName", null);
418
+ __decorate([lazyProp], OutputChunkImpl.prototype, "code", null);
419
+ __decorate([lazyProp], OutputChunkImpl.prototype, "modules", null);
420
+ __decorate([lazyProp], OutputChunkImpl.prototype, "imports", null);
421
+ __decorate([lazyProp], OutputChunkImpl.prototype, "dynamicImports", null);
422
+ __decorate([lazyProp], OutputChunkImpl.prototype, "moduleIds", null);
423
+ __decorate([lazyProp], OutputChunkImpl.prototype, "map", null);
424
+ //#endregion
425
+ //#region src/utils/transform-to-rollup-output.ts
426
+ function transformToRollupSourceMap(map) {
427
+ const obj = {
428
+ ...JSON.parse(map),
429
+ toString() {
430
+ return JSON.stringify(obj);
431
+ },
432
+ toUrl() {
433
+ return `data:application/json;charset=utf-8;base64,${Buffer.from(obj.toString(), "utf-8").toString("base64")}`;
434
+ }
435
+ };
436
+ return obj;
437
+ }
438
+ function transformToRollupOutputChunk(bindingChunk) {
439
+ return new OutputChunkImpl(bindingChunk);
440
+ }
441
+ function transformToMutableRollupOutputChunk(bindingChunk, changed) {
442
+ const chunk = {
443
+ type: "chunk",
444
+ get code() {
445
+ return bindingChunk.getCode();
446
+ },
447
+ fileName: bindingChunk.getFileName(),
448
+ name: bindingChunk.getName(),
449
+ get modules() {
450
+ return transformChunkModules(bindingChunk.getModules());
451
+ },
452
+ get imports() {
453
+ return bindingChunk.getImports();
454
+ },
455
+ get dynamicImports() {
456
+ return bindingChunk.getDynamicImports();
457
+ },
458
+ exports: bindingChunk.getExports(),
459
+ isEntry: bindingChunk.getIsEntry(),
460
+ facadeModuleId: bindingChunk.getFacadeModuleId() || null,
461
+ isDynamicEntry: bindingChunk.getIsDynamicEntry(),
462
+ get moduleIds() {
463
+ return bindingChunk.getModuleIds();
464
+ },
465
+ get map() {
466
+ const map = bindingChunk.getMap();
467
+ return map ? transformToRollupSourceMap(map) : null;
468
+ },
469
+ sourcemapFileName: bindingChunk.getSourcemapFileName() || null,
470
+ preliminaryFileName: bindingChunk.getPreliminaryFileName()
471
+ };
472
+ const cache = {};
473
+ return new Proxy(chunk, {
474
+ get(target, p) {
475
+ if (p in cache) return cache[p];
476
+ const value = target[p];
477
+ cache[p] = value;
478
+ return value;
479
+ },
480
+ set(_target, p, newValue) {
481
+ cache[p] = newValue;
482
+ changed.updated.add(bindingChunk.getFileName());
483
+ return true;
484
+ },
485
+ has(target, p) {
486
+ if (p in cache) return true;
487
+ return p in target;
488
+ }
489
+ });
490
+ }
491
+ function transformToRollupOutputAsset(bindingAsset) {
492
+ return new OutputAssetImpl(bindingAsset);
493
+ }
494
+ function transformToMutableRollupOutputAsset(bindingAsset, changed) {
495
+ const asset = {
496
+ type: "asset",
497
+ fileName: bindingAsset.getFileName(),
498
+ originalFileName: bindingAsset.getOriginalFileName() || null,
499
+ originalFileNames: bindingAsset.getOriginalFileNames(),
500
+ get source() {
501
+ return transformAssetSource(bindingAsset.getSource());
502
+ },
503
+ name: bindingAsset.getName() ?? void 0,
504
+ names: bindingAsset.getNames()
505
+ };
506
+ const cache = {};
507
+ return new Proxy(asset, {
508
+ get(target, p) {
509
+ if (p in cache) return cache[p];
510
+ const value = target[p];
511
+ cache[p] = value;
512
+ return value;
513
+ },
514
+ set(_target, p, newValue) {
515
+ cache[p] = newValue;
516
+ changed.updated.add(bindingAsset.getFileName());
517
+ return true;
518
+ }
519
+ });
520
+ }
521
+ function transformToRollupOutput(output) {
522
+ const { chunks, assets } = output;
523
+ const transformed = { output: [...chunks.map((chunk) => transformToRollupOutputChunk(chunk)), ...assets.map((asset) => transformToRollupOutputAsset(asset))] };
524
+ if (output.mangleCache !== void 0) transformed.mangleCache = output.mangleCache;
525
+ return transformed;
526
+ }
527
+ function transformToMutableRollupOutput(output, changed) {
528
+ const { chunks, assets } = output;
529
+ return { output: [...chunks.map((chunk) => transformToMutableRollupOutputChunk(chunk, changed)), ...assets.map((asset) => transformToMutableRollupOutputAsset(asset, changed))] };
530
+ }
531
+ function transformToOutputBundle(context, output, changed) {
532
+ const bundle = Object.fromEntries(transformToMutableRollupOutput(output, changed).output.map((item) => [item.fileName, item]));
533
+ return new Proxy(bundle, {
534
+ set(_target, _p, _newValue, _receiver) {
535
+ const originalStackTraceLimit = Error.stackTraceLimit;
536
+ Error.stackTraceLimit = 2;
537
+ const message = "This plugin assigns to bundle variable. This is discouraged by Rollup and is not supported by Rolldown. This will be ignored. https://rollupjs.org/plugin-development/#generatebundle:~:text=DANGER,this.emitFile.";
538
+ const stack = (/* @__PURE__ */ new Error(message)).stack ?? message;
539
+ Error.stackTraceLimit = originalStackTraceLimit;
540
+ context.warn({
541
+ message: stack,
542
+ code: "UNSUPPORTED_BUNDLE_ASSIGNMENT"
543
+ });
544
+ return true;
545
+ },
546
+ deleteProperty(target, property) {
547
+ if (typeof property === "string") changed.deleted.add(property);
548
+ return true;
549
+ }
550
+ });
551
+ }
552
+ function collectChangedBundle(changed, bundle) {
553
+ const changes = {};
554
+ for (const key in bundle) {
555
+ if (changed.deleted.has(key) || !changed.updated.has(key)) continue;
556
+ const item = bundle[key];
557
+ if (item.type === "asset") changes[key] = {
558
+ filename: item.fileName,
559
+ originalFileNames: item.originalFileNames,
560
+ source: bindingAssetSource(item.source),
561
+ names: item.names
562
+ };
563
+ else changes[key] = {
564
+ code: item.code,
565
+ filename: item.fileName,
566
+ name: item.name,
567
+ isEntry: item.isEntry,
568
+ exports: item.exports,
569
+ modules: {},
570
+ imports: item.imports,
571
+ dynamicImports: item.dynamicImports,
572
+ facadeModuleId: item.facadeModuleId || void 0,
573
+ isDynamicEntry: item.isDynamicEntry,
574
+ moduleIds: item.moduleIds,
575
+ map: bindingifySourcemap(item.map),
576
+ sourcemapFilename: item.sourcemapFileName || void 0,
577
+ preliminaryFilename: item.preliminaryFileName
578
+ };
579
+ }
580
+ return {
581
+ changes,
582
+ deleted: changed.deleted
583
+ };
584
+ }
585
+ //#endregion
586
+ //#region src/options/normalized-input-options.ts
587
+ var NormalizedInputOptionsImpl = class extends PlainObjectLike {
588
+ onLog;
589
+ inputPlugins;
590
+ inner;
591
+ constructor(inner, onLog, inputPlugins) {
592
+ super();
593
+ this.onLog = onLog;
594
+ this.inputPlugins = inputPlugins;
595
+ this.inner = inner;
596
+ }
597
+ get shimMissingExports() {
598
+ return this.inner.shimMissingExports;
599
+ }
600
+ get input() {
601
+ return this.inner.input;
602
+ }
603
+ get cwd() {
604
+ return this.inner.cwd;
605
+ }
606
+ get platform() {
607
+ return this.inner.platform;
608
+ }
609
+ get context() {
610
+ return this.inner.context;
611
+ }
612
+ get plugins() {
613
+ return this.inputPlugins;
614
+ }
615
+ };
616
+ __decorate([lazyProp], NormalizedInputOptionsImpl.prototype, "shimMissingExports", null);
617
+ __decorate([lazyProp], NormalizedInputOptionsImpl.prototype, "input", null);
618
+ __decorate([lazyProp], NormalizedInputOptionsImpl.prototype, "cwd", null);
619
+ __decorate([lazyProp], NormalizedInputOptionsImpl.prototype, "platform", null);
620
+ __decorate([lazyProp], NormalizedInputOptionsImpl.prototype, "context", null);
621
+ //#endregion
622
+ //#region src/options/normalized-output-options.ts
623
+ var NormalizedOutputOptionsImpl = class extends PlainObjectLike {
624
+ inner;
625
+ outputOptions;
626
+ normalizedOutputPlugins;
627
+ constructor(inner, outputOptions, normalizedOutputPlugins) {
628
+ super();
629
+ this.inner = inner;
630
+ this.outputOptions = outputOptions;
631
+ this.normalizedOutputPlugins = normalizedOutputPlugins;
632
+ }
633
+ get dir() {
634
+ return this.inner.dir ?? void 0;
635
+ }
636
+ get entryFileNames() {
637
+ return this.inner.entryFilenames || this.outputOptions.entryFileNames;
638
+ }
639
+ get chunkFileNames() {
640
+ return this.inner.chunkFilenames || this.outputOptions.chunkFileNames;
641
+ }
642
+ get assetFileNames() {
643
+ return this.inner.assetFilenames || this.outputOptions.assetFileNames;
644
+ }
645
+ get format() {
646
+ return this.inner.format;
647
+ }
648
+ get exports() {
649
+ return this.inner.exports;
650
+ }
651
+ get sourcemap() {
652
+ return this.inner.sourcemap;
653
+ }
654
+ get sourcemapFileNames() {
655
+ return this.inner.sourcemapFilenames || this.outputOptions.sourcemapFileNames;
656
+ }
657
+ get sourcemapBaseUrl() {
658
+ return this.inner.sourcemapBaseUrl ?? void 0;
659
+ }
660
+ get shimMissingExports() {
661
+ return this.inner.shimMissingExports;
662
+ }
663
+ get name() {
664
+ return this.inner.name ?? void 0;
665
+ }
666
+ get file() {
667
+ return this.inner.file ?? void 0;
668
+ }
669
+ get codeSplitting() {
670
+ return this.inner.codeSplitting;
671
+ }
672
+ /**
673
+ * @deprecated Use `codeSplitting` instead.
674
+ */
675
+ get inlineDynamicImports() {
676
+ return !this.inner.codeSplitting;
677
+ }
678
+ get dynamicImportInCjs() {
679
+ return this.inner.dynamicImportInCjs;
680
+ }
681
+ get externalLiveBindings() {
682
+ return this.inner.externalLiveBindings;
683
+ }
684
+ get banner() {
685
+ return normalizeAddon(this.outputOptions.banner);
686
+ }
687
+ get footer() {
688
+ return normalizeAddon(this.outputOptions.footer);
689
+ }
690
+ get postBanner() {
691
+ return normalizeAddon(this.outputOptions.postBanner);
692
+ }
693
+ get postFooter() {
694
+ return normalizeAddon(this.outputOptions.postFooter);
695
+ }
696
+ get intro() {
697
+ return normalizeAddon(this.outputOptions.intro);
698
+ }
699
+ get outro() {
700
+ return normalizeAddon(this.outputOptions.outro);
701
+ }
702
+ get esModule() {
703
+ return this.inner.esModule;
704
+ }
705
+ get extend() {
706
+ return this.inner.extend;
707
+ }
708
+ get globals() {
709
+ return this.inner.globals || this.outputOptions.globals;
710
+ }
711
+ get paths() {
712
+ return this.outputOptions.paths;
713
+ }
714
+ get hashCharacters() {
715
+ return this.inner.hashCharacters;
716
+ }
717
+ get sourcemapDebugIds() {
718
+ return this.inner.sourcemapDebugIds;
719
+ }
720
+ get sourcemapExcludeSources() {
721
+ return this.inner.sourcemapExcludeSources;
722
+ }
723
+ get sourcemapIgnoreList() {
724
+ return this.outputOptions.sourcemapIgnoreList;
725
+ }
726
+ get sourcemapPathTransform() {
727
+ return this.outputOptions.sourcemapPathTransform;
728
+ }
729
+ get minify() {
730
+ let ret = this.inner.minify;
731
+ if (typeof ret === "object" && ret !== null) {
732
+ delete ret["codegen"];
733
+ delete ret["module"];
734
+ delete ret["sourcemap"];
735
+ }
736
+ return ret;
737
+ }
738
+ get legalComments() {
739
+ return this.inner.legalComments;
740
+ }
741
+ get comments() {
742
+ const c = this.inner.comments;
743
+ return {
744
+ legal: c.legal ?? true,
745
+ annotation: c.annotation ?? true,
746
+ jsdoc: c.jsdoc ?? true
747
+ };
748
+ }
749
+ get polyfillRequire() {
750
+ return this.inner.polyfillRequire;
751
+ }
752
+ get plugins() {
753
+ return this.normalizedOutputPlugins;
754
+ }
755
+ get preserveModules() {
756
+ return this.inner.preserveModules;
757
+ }
758
+ get preserveModulesRoot() {
759
+ return this.inner.preserveModulesRoot;
760
+ }
761
+ get virtualDirname() {
762
+ return this.inner.virtualDirname;
763
+ }
764
+ get topLevelVar() {
765
+ return this.inner.topLevelVar ?? false;
766
+ }
767
+ get minifyInternalExports() {
768
+ return this.inner.minifyInternalExports ?? false;
769
+ }
770
+ };
771
+ __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "dir", null);
772
+ __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "entryFileNames", null);
773
+ __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "chunkFileNames", null);
774
+ __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "assetFileNames", null);
775
+ __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "format", null);
776
+ __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "exports", null);
777
+ __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "sourcemap", null);
778
+ __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "sourcemapFileNames", null);
779
+ __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "sourcemapBaseUrl", null);
780
+ __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "shimMissingExports", null);
781
+ __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "name", null);
782
+ __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "file", null);
783
+ __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "codeSplitting", null);
784
+ __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "inlineDynamicImports", null);
785
+ __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "dynamicImportInCjs", null);
786
+ __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "externalLiveBindings", null);
787
+ __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "banner", null);
788
+ __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "footer", null);
789
+ __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "postBanner", null);
790
+ __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "postFooter", null);
791
+ __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "intro", null);
792
+ __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "outro", null);
793
+ __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "esModule", null);
794
+ __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "extend", null);
795
+ __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "globals", null);
796
+ __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "paths", null);
797
+ __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "hashCharacters", null);
798
+ __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "sourcemapDebugIds", null);
799
+ __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "sourcemapExcludeSources", null);
800
+ __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "sourcemapIgnoreList", null);
801
+ __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "sourcemapPathTransform", null);
802
+ __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "minify", null);
803
+ __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "legalComments", null);
804
+ __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "comments", null);
805
+ __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "polyfillRequire", null);
806
+ __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "plugins", null);
807
+ __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "preserveModules", null);
808
+ __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "preserveModulesRoot", null);
809
+ __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "virtualDirname", null);
810
+ __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "topLevelVar", null);
811
+ __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "minifyInternalExports", null);
812
+ function normalizeAddon(value) {
813
+ if (typeof value === "function") return value;
814
+ return () => value || "";
815
+ }
816
+ //#endregion
817
+ //#region src/utils/transform-module-info.ts
818
+ function transformModuleInfo(info, option) {
819
+ return {
820
+ get ast() {
821
+ return unsupported("ModuleInfo#ast");
822
+ },
823
+ get code() {
824
+ return info.code;
825
+ },
826
+ id: info.id,
827
+ importers: info.importers,
828
+ dynamicImporters: info.dynamicImporters,
829
+ importedIds: info.importedIds,
830
+ dynamicallyImportedIds: info.dynamicallyImportedIds,
831
+ exports: info.exports,
832
+ isEntry: info.isEntry,
833
+ inputFormat: info.inputFormat,
834
+ ...option
835
+ };
836
+ }
837
+ //#endregion
838
+ //#region src/plugin/plugin-context-data.ts
839
+ var PluginContextData = class {
840
+ onLog;
841
+ outputOptions;
842
+ normalizedInputPlugins;
843
+ normalizedOutputPlugins;
844
+ moduleOptionMap = /* @__PURE__ */ new Map();
845
+ resolveOptionsMap = /* @__PURE__ */ new Map();
846
+ loadModulePromiseMap = /* @__PURE__ */ new Map();
847
+ renderedChunkMeta = null;
848
+ normalizedInputOptions = null;
849
+ normalizedOutputOptions = null;
850
+ constructor(onLog, outputOptions, normalizedInputPlugins, normalizedOutputPlugins) {
851
+ this.onLog = onLog;
852
+ this.outputOptions = outputOptions;
853
+ this.normalizedInputPlugins = normalizedInputPlugins;
854
+ this.normalizedOutputPlugins = normalizedOutputPlugins;
855
+ }
856
+ updateModuleOption(id, option) {
857
+ const existing = this.moduleOptionMap.get(id);
858
+ if (existing) {
859
+ if (option.moduleSideEffects != null) existing.moduleSideEffects = option.moduleSideEffects;
860
+ if (option.meta != null) Object.assign(existing.meta, option.meta);
861
+ if (option.invalidate != null) existing.invalidate = option.invalidate;
862
+ } else {
863
+ this.moduleOptionMap.set(id, option);
864
+ return option;
865
+ }
866
+ return existing;
867
+ }
868
+ getModuleOption(id) {
869
+ const option = this.moduleOptionMap.get(id);
870
+ if (!option) {
871
+ const raw = {
872
+ moduleSideEffects: null,
873
+ meta: {}
874
+ };
875
+ this.moduleOptionMap.set(id, raw);
876
+ return raw;
877
+ }
878
+ return option;
879
+ }
880
+ getModuleInfo(id, context) {
881
+ const bindingInfo = context.getModuleInfo(id);
882
+ if (bindingInfo) {
883
+ const info = transformModuleInfo(bindingInfo, this.getModuleOption(id));
884
+ return this.proxyModuleInfo(id, info);
885
+ }
886
+ return null;
887
+ }
888
+ proxyModuleInfo(id, info) {
889
+ let moduleSideEffects = info.moduleSideEffects;
890
+ Object.defineProperty(info, "moduleSideEffects", {
891
+ get() {
892
+ return moduleSideEffects;
893
+ },
894
+ set: (v) => {
895
+ this.updateModuleOption(id, {
896
+ moduleSideEffects: v,
897
+ meta: info.meta,
898
+ invalidate: true
899
+ });
900
+ moduleSideEffects = v;
901
+ }
902
+ });
903
+ return info;
904
+ }
905
+ getModuleIds(context) {
906
+ return context.getModuleIds().values();
907
+ }
908
+ saveResolveOptions(options) {
909
+ const index = this.resolveOptionsMap.size;
910
+ this.resolveOptionsMap.set(index, options);
911
+ return index;
912
+ }
913
+ getSavedResolveOptions(receipt) {
914
+ return this.resolveOptionsMap.get(receipt);
915
+ }
916
+ removeSavedResolveOptions(receipt) {
917
+ this.resolveOptionsMap.delete(receipt);
918
+ }
919
+ setRenderChunkMeta(meta) {
920
+ this.renderedChunkMeta = meta;
921
+ }
922
+ getRenderChunkMeta() {
923
+ return this.renderedChunkMeta;
924
+ }
925
+ getInputOptions(opts) {
926
+ this.normalizedInputOptions ??= new NormalizedInputOptionsImpl(opts, this.onLog, this.normalizedInputPlugins);
927
+ return this.normalizedInputOptions;
928
+ }
929
+ getOutputOptions(opts) {
930
+ this.normalizedOutputOptions ??= new NormalizedOutputOptionsImpl(opts, this.outputOptions, this.normalizedOutputPlugins);
931
+ return this.normalizedOutputOptions;
932
+ }
933
+ clear() {
934
+ this.renderedChunkMeta = null;
935
+ this.loadModulePromiseMap.clear();
936
+ }
937
+ };
938
+ //#endregion
939
+ //#region src/binding-magic-string.ts
940
+ Object.defineProperty(import_binding.BindingMagicString.prototype, "isRolldownMagicString", {
941
+ value: true,
942
+ writable: false,
943
+ configurable: false
944
+ });
945
+ function assertString(content, msg) {
946
+ if (typeof content !== "string") throw new TypeError(msg);
947
+ }
948
+ const nativeAppend = import_binding.BindingMagicString.prototype.append;
949
+ const nativePrepend = import_binding.BindingMagicString.prototype.prepend;
950
+ const nativeAppendLeft = import_binding.BindingMagicString.prototype.appendLeft;
951
+ const nativeAppendRight = import_binding.BindingMagicString.prototype.appendRight;
952
+ const nativePrependLeft = import_binding.BindingMagicString.prototype.prependLeft;
953
+ const nativePrependRight = import_binding.BindingMagicString.prototype.prependRight;
954
+ const nativeOverwrite = import_binding.BindingMagicString.prototype.overwrite;
955
+ const nativeUpdate = import_binding.BindingMagicString.prototype.update;
956
+ import_binding.BindingMagicString.prototype.append = function(content) {
957
+ assertString(content, "outro content must be a string");
958
+ return nativeAppend.call(this, content);
959
+ };
960
+ import_binding.BindingMagicString.prototype.prepend = function(content) {
961
+ assertString(content, "outro content must be a string");
962
+ return nativePrepend.call(this, content);
963
+ };
964
+ import_binding.BindingMagicString.prototype.appendLeft = function(index, content) {
965
+ assertString(content, "inserted content must be a string");
966
+ return nativeAppendLeft.call(this, index, content);
967
+ };
968
+ import_binding.BindingMagicString.prototype.appendRight = function(index, content) {
969
+ assertString(content, "inserted content must be a string");
970
+ return nativeAppendRight.call(this, index, content);
971
+ };
972
+ import_binding.BindingMagicString.prototype.prependLeft = function(index, content) {
973
+ assertString(content, "inserted content must be a string");
974
+ return nativePrependLeft.call(this, index, content);
975
+ };
976
+ import_binding.BindingMagicString.prototype.prependRight = function(index, content) {
977
+ assertString(content, "inserted content must be a string");
978
+ return nativePrependRight.call(this, index, content);
979
+ };
980
+ import_binding.BindingMagicString.prototype.overwrite = function(start, end, content, options) {
981
+ assertString(content, "replacement content must be a string");
982
+ return nativeOverwrite.call(this, start, end, content, options);
983
+ };
984
+ import_binding.BindingMagicString.prototype.update = function(start, end, content, options) {
985
+ assertString(content, "replacement content must be a string");
986
+ return nativeUpdate.call(this, start, end, content, options);
987
+ };
988
+ const nativeReplace = import_binding.BindingMagicString.prototype.replace;
989
+ const nativeReplaceAll = import_binding.BindingMagicString.prototype.replaceAll;
990
+ import_binding.BindingMagicString.prototype.replace = function(searchValue, replacement) {
991
+ if (typeof searchValue === "string") return nativeReplace.call(this, searchValue, replacement);
992
+ if (searchValue.global) searchValue.lastIndex = 0;
993
+ const lastMatchEnd = this.replaceRegex(searchValue, replacement);
994
+ if (searchValue.global) searchValue.lastIndex = 0;
995
+ else if (searchValue.sticky) searchValue.lastIndex = lastMatchEnd === -1 ? 0 : lastMatchEnd;
996
+ return this;
997
+ };
998
+ import_binding.BindingMagicString.prototype.replaceAll = function(searchValue, replacement) {
999
+ if (typeof searchValue === "string") return nativeReplaceAll.call(this, searchValue, replacement);
1000
+ if (!searchValue.global) throw new TypeError("MagicString.prototype.replaceAll called with a non-global RegExp argument");
1001
+ searchValue.lastIndex = 0;
1002
+ this.replaceRegex(searchValue, replacement);
1003
+ searchValue.lastIndex = 0;
1004
+ return this;
1005
+ };
1006
+ /**
1007
+ * A native MagicString implementation powered by Rust.
1008
+ *
1009
+ * @experimental
1010
+ */
1011
+ const RolldownMagicString = import_binding.BindingMagicString;
1012
+ //#endregion
1013
+ //#region src/utils/transform-sourcemap.ts
1014
+ function isEmptySourcemapFiled(array) {
1015
+ if (!array) return true;
1016
+ if (array.length === 0 || !array[0]) return true;
1017
+ return false;
1018
+ }
1019
+ function normalizeTransformHookSourcemap(id, originalCode, rawMap) {
1020
+ if (!rawMap) return;
1021
+ let map = typeof rawMap === "object" ? rawMap : JSON.parse(rawMap);
1022
+ if (isEmptySourcemapFiled(map.sourcesContent)) map.sourcesContent = [originalCode];
1023
+ if (isEmptySourcemapFiled(map.sources) || map.sources && map.sources.length === 1 && map.sources[0] !== id) map.sources = [id];
1024
+ return map;
1025
+ }
1026
+ //#endregion
1027
+ //#region ../../node_modules/.pnpm/remeda@2.42.0/node_modules/remeda/dist/lazyDataLastImpl--3B10z3s.js
1028
+ function e(e, t, n) {
1029
+ let r = (n) => e(n, ...t);
1030
+ return n === void 0 ? r : Object.assign(r, {
1031
+ lazy: n,
1032
+ lazyArgs: t
1033
+ });
1034
+ }
1035
+ //#endregion
1036
+ //#region ../../node_modules/.pnpm/remeda@2.42.0/node_modules/remeda/dist/purry.js
1037
+ function t$1(t, n, r) {
1038
+ let i = t.length - n.length;
1039
+ if (i === 0) return t(...n);
1040
+ if (i === 1) return e(t, n, r);
1041
+ throw Error(`Wrong number of arguments`);
1042
+ }
1043
+ //#endregion
1044
+ //#region ../../node_modules/.pnpm/remeda@2.42.0/node_modules/remeda/dist/partition.js
1045
+ function t(...t) {
1046
+ return t$1(n, t);
1047
+ }
1048
+ const n = (e, t) => {
1049
+ let n = [[], []];
1050
+ for (let [r, i] of e.entries()) t(i, r, e) ? n[0].push(i) : n[1].push(i);
1051
+ return n;
1052
+ };
1053
+ //#endregion
1054
+ //#region src/plugin/bindingify-hook-filter.ts
1055
+ function generalHookFilterMatcherToFilterExprs(matcher, stringKind) {
1056
+ if (typeof matcher === "string" || matcher instanceof RegExp) return [filter.include(generateAtomMatcher(stringKind, matcher))];
1057
+ if (Array.isArray(matcher)) return matcher.map((m) => filter.include(generateAtomMatcher(stringKind, m)));
1058
+ let ret = [];
1059
+ if (matcher.exclude) ret.push(...arraify(matcher.exclude).map((m) => filter.exclude(generateAtomMatcher(stringKind, m))));
1060
+ if (matcher.include) ret.push(...arraify(matcher.include).map((m) => filter.include(generateAtomMatcher(stringKind, m))));
1061
+ return ret;
1062
+ }
1063
+ function generateAtomMatcher(kind, matcher) {
1064
+ return kind === "code" ? filter.code(matcher) : filter.id(matcher);
1065
+ }
1066
+ function transformFilterMatcherToFilterExprs(filterOption) {
1067
+ if (!filterOption) return;
1068
+ if (Array.isArray(filterOption)) return filterOption;
1069
+ const { id, code, moduleType } = filterOption;
1070
+ let ret = [];
1071
+ let idIncludes = [];
1072
+ let idExcludes = [];
1073
+ let codeIncludes = [];
1074
+ let codeExcludes = [];
1075
+ if (id) [idIncludes, idExcludes] = t(generalHookFilterMatcherToFilterExprs(id, "id") ?? [], (m) => m.kind === "include");
1076
+ if (code) [codeIncludes, codeExcludes] = t(generalHookFilterMatcherToFilterExprs(code, "code") ?? [], (m) => m.kind === "include");
1077
+ ret.push(...idExcludes);
1078
+ ret.push(...codeExcludes);
1079
+ let andExprList = [];
1080
+ if (moduleType) {
1081
+ let moduleTypes = Array.isArray(moduleType) ? moduleType : moduleType.include ?? [];
1082
+ andExprList.push(filter.or(...moduleTypes.map((m) => filter.moduleType(m))));
1083
+ }
1084
+ if (idIncludes.length) andExprList.push(filter.or(...idIncludes.map((item) => item.expr)));
1085
+ if (codeIncludes.length) andExprList.push(filter.or(...codeIncludes.map((item) => item.expr)));
1086
+ if (andExprList.length) ret.push(filter.include(filter.and(...andExprList)));
1087
+ return ret;
1088
+ }
1089
+ function bindingifyGeneralHookFilter(stringKind, pattern) {
1090
+ let filterExprs = generalHookFilterMatcherToFilterExprs(pattern, stringKind);
1091
+ let ret = [];
1092
+ if (filterExprs) ret = filterExprs.map(bindingifyFilterExpr);
1093
+ return ret.length > 0 ? { value: ret } : void 0;
1094
+ }
1095
+ function bindingifyFilterExpr(expr) {
1096
+ let list = [];
1097
+ bindingifyFilterExprImpl(expr, list);
1098
+ return list;
1099
+ }
1100
+ function containsImporterId(expr) {
1101
+ switch (expr.kind) {
1102
+ case "and":
1103
+ case "or": return expr.args.some(containsImporterId);
1104
+ case "not":
1105
+ case "include":
1106
+ case "exclude": return containsImporterId(expr.expr);
1107
+ case "importerId": return true;
1108
+ default: return false;
1109
+ }
1110
+ }
1111
+ function assertNoImporterId(filterExprs, hookName) {
1112
+ if (filterExprs?.some(containsImporterId)) throw new Error(`The \`importerId\` filter can only be used with the \`resolveId\` hook, but it was used with the \`${hookName}\` hook.`);
1113
+ }
1114
+ function containsStringId(expr) {
1115
+ switch (expr.kind) {
1116
+ case "and":
1117
+ case "or": return expr.args.some(containsStringId);
1118
+ case "not":
1119
+ case "include":
1120
+ case "exclude": return containsStringId(expr.expr);
1121
+ case "id": return typeof expr.pattern === "string";
1122
+ default: return false;
1123
+ }
1124
+ }
1125
+ function assertNoStringId(filterExprs, hookName) {
1126
+ if (filterExprs?.some(containsStringId)) throw new Error(`A string \`id\` filter is not supported for the \`${hookName}\` hook, because its \`id\` is the import specifier rather than a resolved path. Use a RegExp instead.`);
1127
+ }
1128
+ function bindingifyFilterExprImpl(expr, list) {
1129
+ switch (expr.kind) {
1130
+ case "and": {
1131
+ let args = expr.args;
1132
+ for (let i = args.length - 1; i >= 0; i--) bindingifyFilterExprImpl(args[i], list);
1133
+ list.push({
1134
+ kind: "And",
1135
+ payload: args.length
1136
+ });
1137
+ break;
1138
+ }
1139
+ case "or": {
1140
+ let args = expr.args;
1141
+ for (let i = args.length - 1; i >= 0; i--) bindingifyFilterExprImpl(args[i], list);
1142
+ list.push({
1143
+ kind: "Or",
1144
+ payload: args.length
1145
+ });
1146
+ break;
1147
+ }
1148
+ case "not":
1149
+ bindingifyFilterExprImpl(expr.expr, list);
1150
+ list.push({ kind: "Not" });
1151
+ break;
1152
+ case "id":
1153
+ list.push({
1154
+ kind: "Id",
1155
+ payload: expr.pattern
1156
+ });
1157
+ if (expr.params.cleanUrl) list.push({ kind: "CleanUrl" });
1158
+ break;
1159
+ case "importerId":
1160
+ list.push({
1161
+ kind: "ImporterId",
1162
+ payload: expr.pattern
1163
+ });
1164
+ if (expr.params.cleanUrl) list.push({ kind: "CleanUrl" });
1165
+ break;
1166
+ case "moduleType":
1167
+ list.push({
1168
+ kind: "ModuleType",
1169
+ payload: expr.pattern
1170
+ });
1171
+ break;
1172
+ case "code":
1173
+ list.push({
1174
+ kind: "Code",
1175
+ payload: expr.pattern
1176
+ });
1177
+ break;
1178
+ case "include":
1179
+ bindingifyFilterExprImpl(expr.expr, list);
1180
+ list.push({ kind: "Include" });
1181
+ break;
1182
+ case "exclude":
1183
+ bindingifyFilterExprImpl(expr.expr, list);
1184
+ list.push({ kind: "Exclude" });
1185
+ break;
1186
+ case "query":
1187
+ list.push({
1188
+ kind: "QueryKey",
1189
+ payload: expr.key
1190
+ });
1191
+ list.push({
1192
+ kind: "QueryValue",
1193
+ payload: expr.pattern
1194
+ });
1195
+ break;
1196
+ default: throw new Error(`Unknown filter expression: ${expr}`);
1197
+ }
1198
+ }
1199
+ function bindingifyResolveIdFilter(filterOption) {
1200
+ if (!filterOption) return;
1201
+ const filterExprs = Array.isArray(filterOption) ? filterOption : filterOption.id ? generalHookFilterMatcherToFilterExprs(filterOption.id, "id") : void 0;
1202
+ assertNoStringId(filterExprs, "resolveId");
1203
+ if (!filterExprs) return;
1204
+ const value = filterExprs.map(bindingifyFilterExpr);
1205
+ return value.length > 0 ? { value } : void 0;
1206
+ }
1207
+ function bindingifyLoadFilter(filterOption) {
1208
+ if (!filterOption) return;
1209
+ if (Array.isArray(filterOption)) {
1210
+ assertNoImporterId(filterOption, "load");
1211
+ return { value: filterOption.map(bindingifyFilterExpr) };
1212
+ }
1213
+ return filterOption.id ? bindingifyGeneralHookFilter("id", filterOption.id) : void 0;
1214
+ }
1215
+ function bindingifyTransformFilter(filterOption) {
1216
+ if (!filterOption) return;
1217
+ let filterExprs = transformFilterMatcherToFilterExprs(filterOption);
1218
+ assertNoImporterId(filterExprs, "transform");
1219
+ let ret = [];
1220
+ if (filterExprs) ret = filterExprs.map(bindingifyFilterExpr);
1221
+ return { value: ret.length > 0 ? ret : void 0 };
1222
+ }
1223
+ function bindingifyRenderChunkFilter(filterOption) {
1224
+ if (!filterOption) return;
1225
+ if (Array.isArray(filterOption)) {
1226
+ assertNoImporterId(filterOption, "renderChunk");
1227
+ return { value: filterOption.map(bindingifyFilterExpr) };
1228
+ }
1229
+ return filterOption.code ? bindingifyGeneralHookFilter("code", filterOption.code) : void 0;
1230
+ }
1231
+ //#endregion
1232
+ //#region src/plugin/bindingify-plugin-hook-meta.ts
1233
+ function bindingifyPluginHookMeta(options) {
1234
+ return { order: bindingPluginOrder(options.order) };
1235
+ }
1236
+ function bindingPluginOrder(order) {
1237
+ switch (order) {
1238
+ case "post": return import_binding.BindingPluginOrder.Post;
1239
+ case "pre": return import_binding.BindingPluginOrder.Pre;
1240
+ case null:
1241
+ case void 0: return;
1242
+ default: throw new Error(`Unknown plugin order: ${order}`);
1243
+ }
1244
+ }
1245
+ function bindingifyHook(hook, build) {
1246
+ if (!hook) return {};
1247
+ const normalized = normalizeHook(hook);
1248
+ return {
1249
+ ...build(normalized),
1250
+ meta: bindingifyPluginHookMeta(normalized.meta)
1251
+ };
1252
+ }
1253
+ //#endregion
1254
+ //#region src/plugin/fs.ts
1255
+ const fsModule = {
1256
+ appendFile: fsp.appendFile,
1257
+ copyFile: fsp.copyFile,
1258
+ mkdir: fsp.mkdir,
1259
+ mkdtemp: fsp.mkdtemp,
1260
+ readdir: fsp.readdir,
1261
+ readFile: fsp.readFile,
1262
+ realpath: fsp.realpath,
1263
+ rename: fsp.rename,
1264
+ rmdir: fsp.rmdir,
1265
+ stat: fsp.stat,
1266
+ lstat: fsp.lstat,
1267
+ unlink: fsp.unlink,
1268
+ writeFile: fsp.writeFile
1269
+ };
1270
+ //#endregion
1271
+ //#region src/plugin/plugin-context.ts
1272
+ var PluginContextImpl = class extends MinimalPluginContextImpl {
1273
+ outputOptions;
1274
+ context;
1275
+ data;
1276
+ onLog;
1277
+ currentLoadingModule;
1278
+ fs = fsModule;
1279
+ getModuleInfo;
1280
+ constructor(outputOptions, context, plugin, data, onLog, logLevel, watchMode, currentLoadingModule) {
1281
+ super(onLog, logLevel, plugin.name, watchMode);
1282
+ this.outputOptions = outputOptions;
1283
+ this.context = context;
1284
+ this.data = data;
1285
+ this.onLog = onLog;
1286
+ this.currentLoadingModule = currentLoadingModule;
1287
+ this.getModuleInfo = (id) => this.data.getModuleInfo(id, context);
1288
+ }
1289
+ async load(options) {
1290
+ const id = options.id;
1291
+ if (id === this.currentLoadingModule) this.onLog(LOG_LEVEL_WARN, logCycleLoading(this.pluginName, this.currentLoadingModule));
1292
+ const moduleInfo = this.data.getModuleInfo(id, this.context);
1293
+ if (moduleInfo && moduleInfo.code !== null) return moduleInfo;
1294
+ const rawOptions = {
1295
+ meta: options.meta || {},
1296
+ moduleSideEffects: options.moduleSideEffects || null,
1297
+ invalidate: false
1298
+ };
1299
+ this.data.updateModuleOption(id, rawOptions);
1300
+ let loadPromise = this.data.loadModulePromiseMap.get(id);
1301
+ if (!loadPromise) {
1302
+ loadPromise = this.context.load(id, options.moduleSideEffects ?? void 0, options.packageJsonPath ?? void 0).catch(() => {
1303
+ this.data.loadModulePromiseMap.delete(id);
1304
+ });
1305
+ this.data.loadModulePromiseMap.set(id, loadPromise);
1306
+ }
1307
+ await loadPromise;
1308
+ return this.data.getModuleInfo(id, this.context);
1309
+ }
1310
+ async resolve(source, importer, options) {
1311
+ let receipt = void 0;
1312
+ if (options != null) receipt = this.data.saveResolveOptions(options);
1313
+ const vitePluginCustom = Object.entries(options?.custom ?? {}).reduce((acc, [key, value]) => {
1314
+ if (key.startsWith("vite:")) (acc ??= {})[key] = value;
1315
+ return acc;
1316
+ }, void 0);
1317
+ const res = await this.context.resolve(source, importer, {
1318
+ importKind: options?.kind,
1319
+ custom: receipt,
1320
+ isEntry: options?.isEntry,
1321
+ skipSelf: options?.skipSelf,
1322
+ vitePluginCustom
1323
+ });
1324
+ if (receipt != null) this.data.removeSavedResolveOptions(receipt);
1325
+ if (res == null) return null;
1326
+ const info = this.data.getModuleOption(res.id) || {};
1327
+ return {
1328
+ ...res,
1329
+ external: res.external === "relative" ? unreachable(`The PluginContext resolve result external couldn't be 'relative'`) : res.external,
1330
+ ...info,
1331
+ moduleSideEffects: info.moduleSideEffects ?? res.moduleSideEffects ?? null,
1332
+ packageJsonPath: res.packageJsonPath
1333
+ };
1334
+ }
1335
+ emitFile = (file) => {
1336
+ if (file.type === "prebuilt-chunk") {
1337
+ if (typeof file.code !== "string") return error(logFailedValidation(`Emitted prebuilt chunks need to have a valid string code, received "${file.code}".`));
1338
+ if (typeof file.fileName !== "string" || isPathFragment(file.fileName)) return error(logFailedValidation(`The "fileName" property of emitted prebuilt chunks must be strings that are neither absolute nor relative paths, received "${file.fileName}".`));
1339
+ return this.context.emitPrebuiltChunk({
1340
+ fileName: file.fileName,
1341
+ name: file.name,
1342
+ code: file.code,
1343
+ exports: file.exports,
1344
+ map: bindingifySourcemap(file.map),
1345
+ sourcemapFileName: file.sourcemapFileName,
1346
+ facadeModuleId: file.facadeModuleId,
1347
+ isEntry: file.isEntry,
1348
+ isDynamicEntry: file.isDynamicEntry
1349
+ });
1350
+ }
1351
+ const validatedName = file.fileName || file.name;
1352
+ if (typeof validatedName === "string" && isPathFragment(validatedName)) return error(logFailedValidation(`The "fileName" or "name" properties of emitted chunks and assets must be strings that are neither absolute nor relative paths, received "${validatedName}".`));
1353
+ if (file.type === "chunk") return this.context.emitChunk({
1354
+ preserveEntrySignatures: bindingifyPreserveEntrySignatures(file.preserveSignature),
1355
+ ...file
1356
+ });
1357
+ const fnSanitizedFileName = file.fileName || typeof this.outputOptions.sanitizeFileName !== "function" ? void 0 : this.outputOptions.sanitizeFileName(file.name || "asset");
1358
+ const filename = file.fileName ? void 0 : this.getAssetFileNames(file);
1359
+ return this.context.emitFile({
1360
+ ...file,
1361
+ originalFileName: file.originalFileName || void 0,
1362
+ source: bindingAssetSource(file.source)
1363
+ }, filename, fnSanitizedFileName);
1364
+ };
1365
+ getAssetFileNames(file) {
1366
+ if (typeof this.outputOptions.assetFileNames === "function") return this.outputOptions.assetFileNames({
1367
+ type: "asset",
1368
+ name: file.name,
1369
+ names: file.name ? [file.name] : [],
1370
+ originalFileName: file.originalFileName,
1371
+ originalFileNames: file.originalFileName ? [file.originalFileName] : [],
1372
+ source: file.source
1373
+ });
1374
+ }
1375
+ getFileName(referenceId) {
1376
+ return this.context.getFileName(referenceId);
1377
+ }
1378
+ getModuleIds() {
1379
+ return this.data.getModuleIds(this.context);
1380
+ }
1381
+ addWatchFile(id) {
1382
+ this.context.addWatchFile(id);
1383
+ }
1384
+ parse(input, options) {
1385
+ return parseAst(input, options);
1386
+ }
1387
+ };
1388
+ function createPluginContext(args, ctx) {
1389
+ return new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel, args.watchMode);
1390
+ }
1391
+ //#endregion
1392
+ //#region src/plugin/load-plugin-context.ts
1393
+ var LoadPluginContextImpl = class extends PluginContextImpl {
1394
+ inner;
1395
+ constructor(outputOptions, context, plugin, data, inner, moduleId, onLog, logLevelOption, watchMode) {
1396
+ super(outputOptions, context, plugin, data, onLog, logLevelOption, watchMode, moduleId);
1397
+ this.inner = inner;
1398
+ }
1399
+ addWatchFile(id) {
1400
+ this.inner.addWatchFile(id);
1401
+ }
1402
+ };
1403
+ //#endregion
1404
+ //#region src/plugin/transform-plugin-context.ts
1405
+ var TransformPluginContextImpl = class extends PluginContextImpl {
1406
+ inner;
1407
+ moduleId;
1408
+ moduleSource;
1409
+ constructor(outputOptions, context, plugin, data, inner, moduleId, moduleSource, onLog, LogLevelOption, watchMode) {
1410
+ super(outputOptions, context, plugin, data, onLog, LogLevelOption, watchMode, moduleId);
1411
+ this.inner = inner;
1412
+ this.moduleId = moduleId;
1413
+ this.moduleSource = moduleSource;
1414
+ const getLogHandler = (handler) => (log, pos) => {
1415
+ log = normalizeLog(log);
1416
+ if (pos) augmentCodeLocation(log, pos, moduleSource, moduleId);
1417
+ log.id = moduleId;
1418
+ log.hook = "transform";
1419
+ handler(log);
1420
+ };
1421
+ this.debug = getLogHandler(this.debug);
1422
+ this.warn = getLogHandler(this.warn);
1423
+ this.info = getLogHandler(this.info);
1424
+ }
1425
+ error(e, pos) {
1426
+ if (typeof e === "string") e = { message: e };
1427
+ if (pos) augmentCodeLocation(e, pos, this.moduleSource, this.moduleId);
1428
+ e.id = this.moduleId;
1429
+ e.hook = "transform";
1430
+ return error(logPluginError(normalizeLog(e), this.pluginName));
1431
+ }
1432
+ getCombinedSourcemap() {
1433
+ return JSON.parse(this.inner.getCombinedSourcemap());
1434
+ }
1435
+ addWatchFile(id) {
1436
+ this.inner.addWatchFile(id);
1437
+ }
1438
+ sendMagicString(s) {
1439
+ this.inner.sendMagicString(s);
1440
+ }
1441
+ };
1442
+ //#endregion
1443
+ //#region src/plugin/bindingify-build-hooks.ts
1444
+ function bindingifyBuildStart(args) {
1445
+ return bindingifyHook(args.plugin.buildStart, ({ handler }) => ({ plugin: async (ctx, opts) => {
1446
+ await handler.call(createPluginContext(args, ctx), args.pluginContextData.getInputOptions(opts));
1447
+ } }));
1448
+ }
1449
+ function bindingifyBuildEnd(args) {
1450
+ return bindingifyHook(args.plugin.buildEnd, ({ handler }) => ({ plugin: async (ctx, err) => {
1451
+ await handler.call(createPluginContext(args, ctx), err ? aggregateBindingErrorsIntoJsError(err) : void 0);
1452
+ } }));
1453
+ }
1454
+ function bindingifyResolveId(args) {
1455
+ const hook = args.plugin.resolveId;
1456
+ return bindingifyHook(hook, ({ handler, options }) => ({
1457
+ plugin: async (ctx, specifier, importer, extraOptions) => {
1458
+ const contextResolveOptions = extraOptions.custom != null ? args.pluginContextData.getSavedResolveOptions(extraOptions.custom) : void 0;
1459
+ const ret = await handler.call(createPluginContext(args, ctx), specifier, importer ?? void 0, {
1460
+ ...extraOptions,
1461
+ custom: contextResolveOptions?.custom
1462
+ });
1463
+ if (ret == null) return;
1464
+ if (ret === false) return {
1465
+ id: specifier,
1466
+ external: true,
1467
+ normalizeExternalId: true
1468
+ };
1469
+ if (typeof ret === "string") return {
1470
+ id: ret,
1471
+ normalizeExternalId: false
1472
+ };
1473
+ let exist = args.pluginContextData.updateModuleOption(ret.id, {
1474
+ meta: ret.meta || {},
1475
+ moduleSideEffects: ret.moduleSideEffects ?? null,
1476
+ invalidate: false
1477
+ });
1478
+ return {
1479
+ id: ret.id,
1480
+ external: ret.external,
1481
+ normalizeExternalId: false,
1482
+ moduleSideEffects: exist.moduleSideEffects ?? void 0,
1483
+ packageJsonPath: ret.packageJsonPath
1484
+ };
1485
+ },
1486
+ filter: bindingifyResolveIdFilter(options.filter)
1487
+ }));
1488
+ }
1489
+ function bindingifyResolveDynamicImport(args) {
1490
+ return bindingifyHook(args.plugin.resolveDynamicImport, ({ handler }) => ({ plugin: async (ctx, specifier, importer) => {
1491
+ const ret = await handler.call(createPluginContext(args, ctx), specifier, importer ?? void 0);
1492
+ if (ret == null) return;
1493
+ if (ret === false) return {
1494
+ id: specifier,
1495
+ external: true
1496
+ };
1497
+ if (typeof ret === "string") return { id: ret };
1498
+ const result = {
1499
+ id: ret.id,
1500
+ external: ret.external,
1501
+ packageJsonPath: ret.packageJsonPath
1502
+ };
1503
+ if (ret.moduleSideEffects !== null) result.moduleSideEffects = ret.moduleSideEffects;
1504
+ args.pluginContextData.updateModuleOption(ret.id, {
1505
+ meta: ret.meta || {},
1506
+ moduleSideEffects: ret.moduleSideEffects || null,
1507
+ invalidate: false
1508
+ });
1509
+ return result;
1510
+ } }));
1511
+ }
1512
+ function bindingifyTransform(args) {
1513
+ return bindingifyHook(args.plugin.transform, ({ handler, options }) => ({
1514
+ plugin: async (ctx, code, id, meta) => {
1515
+ let magicStringInstance, astInstance;
1516
+ Object.defineProperties(meta, {
1517
+ magicString: { get() {
1518
+ if (magicStringInstance) return magicStringInstance;
1519
+ magicStringInstance = new RolldownMagicString(code);
1520
+ return magicStringInstance;
1521
+ } },
1522
+ ast: { get() {
1523
+ if (astInstance) return astInstance;
1524
+ let lang = "js";
1525
+ switch (meta.moduleType) {
1526
+ case "js":
1527
+ case "jsx":
1528
+ case "ts":
1529
+ case "tsx": lang = meta.moduleType;
1530
+ }
1531
+ astInstance = parseAst(code, {
1532
+ astType: meta.moduleType.includes("ts") ? "ts" : "js",
1533
+ lang
1534
+ });
1535
+ return astInstance;
1536
+ } }
1537
+ });
1538
+ const transformCtx = new TransformPluginContextImpl(args.outputOptions, ctx.inner(), args.plugin, args.pluginContextData, ctx, id, code, args.onLog, args.logLevel, args.watchMode);
1539
+ const ret = await handler.call(transformCtx, code, id, meta);
1540
+ if (ret == null) return;
1541
+ if (typeof ret === "string") return { code: ret };
1542
+ let moduleOption = args.pluginContextData.updateModuleOption(id, {
1543
+ meta: ret.meta ?? {},
1544
+ moduleSideEffects: ret.moduleSideEffects ?? null,
1545
+ invalidate: false
1546
+ });
1547
+ let normalizedCode = void 0;
1548
+ let map = ret.map;
1549
+ let mapHandledByNativeChannel = false;
1550
+ if (typeof ret.code === "string") normalizedCode = ret.code;
1551
+ else if (ret.code instanceof RolldownMagicString) {
1552
+ let magicString = ret.code;
1553
+ normalizedCode = magicString.toString();
1554
+ let fallbackSourcemap = ctx.sendMagicString(magicString);
1555
+ if (fallbackSourcemap != void 0) map = fallbackSourcemap;
1556
+ else mapHandledByNativeChannel = true;
1557
+ }
1558
+ return {
1559
+ code: normalizedCode,
1560
+ map: bindingifySourcemap(normalizeTransformHookSourcemap(id, code, map)) ?? (mapHandledByNativeChannel || ret.map === null ? null : void 0),
1561
+ moduleSideEffects: moduleOption.moduleSideEffects ?? void 0,
1562
+ moduleType: ret.moduleType
1563
+ };
1564
+ },
1565
+ filter: bindingifyTransformFilter(options.filter)
1566
+ }));
1567
+ }
1568
+ function bindingifyLoad(args) {
1569
+ return bindingifyHook(args.plugin.load, ({ handler, options }) => ({
1570
+ plugin: async (ctx, id) => {
1571
+ const ret = await handler.call(new LoadPluginContextImpl(args.outputOptions, ctx.inner(), args.plugin, args.pluginContextData, ctx, id, args.onLog, args.logLevel, args.watchMode), id);
1572
+ if (ret == null) return;
1573
+ if (typeof ret === "string") return { code: ret };
1574
+ let moduleOption = args.pluginContextData.updateModuleOption(id, {
1575
+ meta: ret.meta || {},
1576
+ moduleSideEffects: ret.moduleSideEffects ?? null,
1577
+ invalidate: false
1578
+ });
1579
+ let map = preProcessSourceMap(ret, id);
1580
+ return {
1581
+ code: ret.code,
1582
+ map: bindingifySourcemap(map),
1583
+ moduleType: ret.moduleType,
1584
+ moduleSideEffects: moduleOption.moduleSideEffects ?? void 0
1585
+ };
1586
+ },
1587
+ filter: bindingifyLoadFilter(options.filter)
1588
+ }));
1589
+ }
1590
+ function preProcessSourceMap(ret, id) {
1591
+ if (!ret.map) return;
1592
+ let map = typeof ret.map === "object" ? ret.map : JSON.parse(ret.map);
1593
+ if (!isEmptySourcemapFiled(map.sources)) {
1594
+ const directory = path.dirname(id) || ".";
1595
+ const sourceRoot = map.sourceRoot || ".";
1596
+ map.sources = map.sources.map((source) => path.resolve(directory, sourceRoot, source));
1597
+ }
1598
+ return map;
1599
+ }
1600
+ function bindingifyModuleParsed(args) {
1601
+ return bindingifyHook(args.plugin.moduleParsed, ({ handler }) => ({ plugin: async (ctx, moduleInfo) => {
1602
+ await handler.call(createPluginContext(args, ctx), transformModuleInfo(moduleInfo, args.pluginContextData.getModuleOption(moduleInfo.id)));
1603
+ } }));
1604
+ }
1605
+ //#endregion
1606
+ //#region src/plugin/bindingify-output-hooks.ts
1607
+ function bindingifyRenderStart(args) {
1608
+ return bindingifyHook(args.plugin.renderStart, ({ handler }) => ({ plugin: async (ctx, opts) => {
1609
+ await handler.call(createPluginContext(args, ctx), args.pluginContextData.getOutputOptions(opts), args.pluginContextData.getInputOptions(opts));
1610
+ } }));
1611
+ }
1612
+ function bindingifyRenderChunk(args) {
1613
+ return bindingifyHook(args.plugin.renderChunk, ({ handler, options }) => ({
1614
+ plugin: async (ctx, code, chunk, opts, meta) => {
1615
+ if (args.pluginContextData.getRenderChunkMeta() == null) args.pluginContextData.setRenderChunkMeta({ chunks: Object.fromEntries(Object.entries(meta.chunks).map(([key, value]) => [key, transformRenderedChunk(value)])) });
1616
+ const renderChunkMeta = args.pluginContextData.getRenderChunkMeta();
1617
+ let magicStringInstance;
1618
+ if (args.options.experimental?.nativeMagicString) Object.defineProperty(renderChunkMeta, "magicString", {
1619
+ get() {
1620
+ if (magicStringInstance) return magicStringInstance;
1621
+ magicStringInstance = new RolldownMagicString(code);
1622
+ return magicStringInstance;
1623
+ },
1624
+ configurable: true
1625
+ });
1626
+ const ret = await handler.call(createPluginContext(args, ctx), code, transformRenderedChunk(chunk), args.pluginContextData.getOutputOptions(opts), renderChunkMeta);
1627
+ if (ret == null) return;
1628
+ if (ret instanceof RolldownMagicString) {
1629
+ const normalizedCode = ret.toString();
1630
+ const generatedMap = ret.generateMap();
1631
+ return {
1632
+ code: normalizedCode,
1633
+ map: bindingifySourcemap({
1634
+ file: generatedMap.file,
1635
+ mappings: generatedMap.mappings,
1636
+ names: generatedMap.names,
1637
+ sources: generatedMap.sources,
1638
+ sourcesContent: generatedMap.sourcesContent.map((s) => s ?? null)
1639
+ })
1640
+ };
1641
+ }
1642
+ if (typeof ret === "string") return { code: ret };
1643
+ if (ret.code instanceof RolldownMagicString) {
1644
+ const magicString = ret.code;
1645
+ const normalizedCode = magicString.toString();
1646
+ if (ret.map === null) return {
1647
+ code: normalizedCode,
1648
+ map: null
1649
+ };
1650
+ if (ret.map === void 0) {
1651
+ const generatedMap = magicString.generateMap();
1652
+ return {
1653
+ code: normalizedCode,
1654
+ map: bindingifySourcemap({
1655
+ file: generatedMap.file,
1656
+ mappings: generatedMap.mappings,
1657
+ names: generatedMap.names,
1658
+ sources: generatedMap.sources,
1659
+ sourcesContent: generatedMap.sourcesContent.map((s) => s ?? null)
1660
+ })
1661
+ };
1662
+ }
1663
+ return {
1664
+ code: normalizedCode,
1665
+ map: bindingifySourcemap(ret.map)
1666
+ };
1667
+ }
1668
+ if (ret.map === null) return {
1669
+ code: ret.code,
1670
+ map: null
1671
+ };
1672
+ return {
1673
+ code: ret.code,
1674
+ map: bindingifySourcemap(ret.map)
1675
+ };
1676
+ },
1677
+ filter: bindingifyRenderChunkFilter(options.filter)
1678
+ }));
1679
+ }
1680
+ function bindingifyAugmentChunkHash(args) {
1681
+ return bindingifyHook(args.plugin.augmentChunkHash, ({ handler }) => ({ plugin: async (ctx, chunk) => {
1682
+ return handler.call(createPluginContext(args, ctx), transformRenderedChunk(chunk));
1683
+ } }));
1684
+ }
1685
+ function bindingifyResolveFileUrl(args) {
1686
+ return bindingifyHook(args.plugin.resolveFileUrl, ({ handler }) => ({ plugin: async (ctx, resolveFileUrlArgs) => {
1687
+ return handler.call(createPluginContext(args, ctx), resolveFileUrlArgs);
1688
+ } }));
1689
+ }
1690
+ function bindingifyRenderError(args) {
1691
+ return bindingifyHook(args.plugin.renderError, ({ handler }) => ({ plugin: async (ctx, err) => {
1692
+ await handler.call(createPluginContext(args, ctx), aggregateBindingErrorsIntoJsError(err));
1693
+ } }));
1694
+ }
1695
+ function createOutputBundle(args, ctx, bundle) {
1696
+ const changed = {
1697
+ updated: /* @__PURE__ */ new Set(),
1698
+ deleted: /* @__PURE__ */ new Set()
1699
+ };
1700
+ const context = createPluginContext(args, ctx);
1701
+ return {
1702
+ changed,
1703
+ context,
1704
+ output: transformToOutputBundle(context, unwrapBindingResult(bundle), changed)
1705
+ };
1706
+ }
1707
+ function bindingifyGenerateBundle(args) {
1708
+ return bindingifyHook(args.plugin.generateBundle, ({ handler }) => ({ plugin: async (ctx, bundle, isWrite, opts) => {
1709
+ const { changed, context, output } = createOutputBundle(args, ctx, bundle);
1710
+ await handler.call(context, args.pluginContextData.getOutputOptions(opts), output, isWrite);
1711
+ return collectChangedBundle(changed, output);
1712
+ } }));
1713
+ }
1714
+ function bindingifyWriteBundle(args) {
1715
+ return bindingifyHook(args.plugin.writeBundle, ({ handler }) => ({ plugin: async (ctx, bundle, opts) => {
1716
+ const { changed, context, output } = createOutputBundle(args, ctx, bundle);
1717
+ await handler.call(context, args.pluginContextData.getOutputOptions(opts), output);
1718
+ return collectChangedBundle(changed, output);
1719
+ } }));
1720
+ }
1721
+ function bindingifyCloseBundle(args) {
1722
+ return bindingifyHook(args.plugin.closeBundle, ({ handler }) => ({ plugin: async (ctx, err) => {
1723
+ await handler.call(createPluginContext(args, ctx), err ? aggregateBindingErrorsIntoJsError(err) : void 0);
1724
+ } }));
1725
+ }
1726
+ function bindingifyAddonHook(args, name) {
1727
+ return bindingifyHook(args.plugin[name], ({ handler }) => ({ plugin: async (ctx, chunk) => {
1728
+ if (typeof handler === "string") return handler;
1729
+ return handler.call(createPluginContext(args, ctx), transformRenderedChunk(chunk));
1730
+ } }));
1731
+ }
1732
+ //#endregion
1733
+ //#region src/plugin/bindingify-watch-hooks.ts
1734
+ function bindingifyHotUpdate(args) {
1735
+ return bindingifyHook(args.plugin.hotUpdate, ({ handler }) => ({ plugin: async (ctx, hookArgs) => {
1736
+ return await handler.call(createPluginContext(args, ctx), {
1737
+ type: hookArgs.kind,
1738
+ file: hookArgs.file,
1739
+ modules: hookArgs.modules
1740
+ }) ?? void 0;
1741
+ } }));
1742
+ }
1743
+ function bindingifyWatchChange(args) {
1744
+ return bindingifyHook(args.plugin.watchChange, ({ handler }) => ({ plugin: async (ctx, id, event) => {
1745
+ await handler.call(createPluginContext(args, ctx), id, { event });
1746
+ } }));
1747
+ }
1748
+ function bindingifyCloseWatcher(args) {
1749
+ return bindingifyHook(args.plugin.closeWatcher, ({ handler }) => ({ plugin: async (ctx) => {
1750
+ await handler.call(createPluginContext(args, ctx));
1751
+ } }));
1752
+ }
1753
+ //#endregion
1754
+ //#region src/plugin/generated/hook-usage.ts
1755
+ var HookUsage = class {
1756
+ bitflag = BigInt(0);
1757
+ constructor() {}
1758
+ union(kind) {
1759
+ this.bitflag |= BigInt(kind);
1760
+ }
1761
+ inner() {
1762
+ return Number(this.bitflag);
1763
+ }
1764
+ };
1765
+ function extractHookUsage(plugin) {
1766
+ let hookUsage = new HookUsage();
1767
+ if (plugin.buildStart) hookUsage.union(1);
1768
+ if (plugin.resolveId) hookUsage.union(2);
1769
+ if (plugin.resolveDynamicImport) hookUsage.union(4);
1770
+ if (plugin.load) hookUsage.union(8);
1771
+ if (plugin.transform) hookUsage.union(16);
1772
+ if (plugin.moduleParsed) hookUsage.union(32);
1773
+ if (plugin.buildEnd) hookUsage.union(64);
1774
+ if (plugin.renderStart) hookUsage.union(128);
1775
+ if (plugin.renderError) hookUsage.union(256);
1776
+ if (plugin.renderChunk) hookUsage.union(512);
1777
+ if (plugin.augmentChunkHash) hookUsage.union(1024);
1778
+ if (plugin.generateBundle) hookUsage.union(2048);
1779
+ if (plugin.writeBundle) hookUsage.union(4096);
1780
+ if (plugin.closeBundle) hookUsage.union(8192);
1781
+ if (plugin.watchChange) hookUsage.union(16384);
1782
+ if (plugin.closeWatcher) hookUsage.union(32768);
1783
+ if (plugin.banner) hookUsage.union(131072);
1784
+ if (plugin.footer) hookUsage.union(262144);
1785
+ if (plugin.intro) hookUsage.union(524288);
1786
+ if (plugin.outro) hookUsage.union(1048576);
1787
+ if (plugin.resolveFileUrl) hookUsage.union(2097152);
1788
+ if (plugin.hotUpdate) hookUsage.union(4194304);
1789
+ return hookUsage;
1790
+ }
1791
+ //#endregion
1792
+ //#region src/utils/plugin-timings.ts
1793
+ /**
1794
+ * Measure what plugin hooks cost, from inside the JavaScript callback.
1795
+ *
1796
+ * Internal to Rolldown. Nothing here is on a public entry point, and the measurement is not
1797
+ * offered as an API — the only consumer is the core, which pulls it while the build closes.
1798
+ *
1799
+ * The bundler core can only bracket *dispatch* and *completion*. For a hook it invokes
1800
+ * concurrently those two points are separated mostly by the queue the call waited in on
1801
+ * JavaScript's single thread, and the queue is deepest behind whichever callback is doing
1802
+ * the most work — so the hook blocking the thread dilutes its own credit while cheap hooks
1803
+ * collect credit for waiting. Ranking from those numbers reliably puts the *cheapest* hook
1804
+ * first.
1805
+ *
1806
+ * The missing quantity is when the callback began running, and that is known here. Starting
1807
+ * the clock inside the callback removes the dispatch queue by construction.
1808
+ *
1809
+ * ## `maxInFlight` decides whether a total means anything
1810
+ *
1811
+ * Entry-to-exit spans may be summed only if they never overlap. A synchronous callback
1812
+ * cannot overlap: it holds the thread until it returns. An `async` one can — it may suspend
1813
+ * at an `await` and let another call of the same hook begin, and then both spans cover the
1814
+ * same wall clock and the sum counts it twice.
1815
+ *
1816
+ * Overlap also changes what the span is measuring. A hook that awaits the bundler (say
1817
+ * `this.resolve`) spends most of its span waiting for Rust, so the number describes the
1818
+ * bundler rather than the plugin. Observed on a real build: one `resolveId` accumulated
1819
+ * ~47,000s of span inside a 44s module-loading window.
1820
+ *
1821
+ * So overlap is measured rather than assumed, per hook: `overlapMs` is the wall time
1822
+ * double counted in `ms` because two or more calls were in flight together. A hook is
1823
+ * reported with a number when that is a negligible share of its span, and named without one
1824
+ * when it is not.
1825
+ *
1826
+ * The test is deliberately a tolerance rather than "did this ever happen". A peak in-flight
1827
+ * count of 2 can mean one incidental overlap in twenty thousand calls, and discarding a
1828
+ * twelve-second measurement over that both throws away good data and makes the report
1829
+ * depend on scheduling luck — the same hook would appear in one run and vanish in the next.
1830
+ *
1831
+ * This keeps the rule the core followed — never present a number that cannot be defended —
1832
+ * while narrowing "cannot measure" from a property of the *call site* to a property of the
1833
+ * *callback*, which is where it actually lives. A hook dispatched concurrently but whose
1834
+ * body barely overlaps is measured to within the tolerance.
1835
+ *
1836
+ * A measured row is still wall time for that callback rather than CPU: a hook that awaits
1837
+ * I/O without overlapping another call of itself is charged for the wait. Excluding the
1838
+ * dispatch queue is what this buys; it does not distinguish running from awaiting.
1839
+ */
1840
+ /**
1841
+ * How much of a hook's span may be double counted before its total stops being reportable,
1842
+ * as a fraction of that span.
1843
+ */
1844
+ const OVERLAP_TOLERANCE = .01;
1845
+ /**
1846
+ * One recorder per build, keyed on the object that identifies it.
1847
+ *
1848
+ * Counters cannot be module-global. A plugin is free to run a nested `rolldown()` build of
1849
+ * its own, which finishes first; shared counters would let it flush the outer build's
1850
+ * half-accumulated totals and report a window belonging to neither.
1851
+ */
1852
+ const recorders = /* @__PURE__ */ new WeakMap();
1853
+ /** The recorder for one build, created on first use. */
1854
+ function pluginTimingsRecorderFor(key) {
1855
+ let recorder = recorders.get(key);
1856
+ if (recorder === void 0) {
1857
+ recorder = {
1858
+ costs: /* @__PURE__ */ new Map(),
1859
+ busyMs: 0,
1860
+ inFlight: 0,
1861
+ busyStart: 0
1862
+ };
1863
+ recorders.set(key, recorder);
1864
+ }
1865
+ return recorder;
1866
+ }
1867
+ function costFor(recorder, owner, hookName) {
1868
+ let byHook = recorder.costs.get(owner.key);
1869
+ if (byHook === void 0) {
1870
+ byHook = /* @__PURE__ */ new Map();
1871
+ recorder.costs.set(owner.key, byHook);
1872
+ }
1873
+ let cost = byHook.get(hookName);
1874
+ if (cost === void 0) {
1875
+ cost = {
1876
+ owner: owner.name,
1877
+ kind: owner.kind,
1878
+ hookName,
1879
+ calls: 0,
1880
+ ms: 0,
1881
+ inFlight: 0,
1882
+ maxInFlight: 0,
1883
+ overlapMs: 0,
1884
+ lastChange: 0
1885
+ };
1886
+ byHook.set(hookName, cost);
1887
+ }
1888
+ return cost;
1889
+ }
1890
+ /**
1891
+ * Fold the interval since the last in-flight change into `overlapMs`, then move the mark.
1892
+ * Call immediately before every increment and decrement of `cost.inFlight`.
1893
+ */
1894
+ function markInFlightChange(cost, at) {
1895
+ if (cost.inFlight > 1) cost.overlapMs += (cost.inFlight - 1) * (at - cost.lastChange);
1896
+ cost.lastChange = at;
1897
+ }
1898
+ /**
1899
+ * Close out one call. A module-level function rather than a closure per invocation: hooks
1900
+ * run hundreds of thousands of times in a large build, and the synchronous path would
1901
+ * otherwise allocate one closure per call only to invoke it immediately.
1902
+ */
1903
+ function settle(recorder, cost, started) {
1904
+ const ended = performance.now();
1905
+ markInFlightChange(cost, ended);
1906
+ cost.inFlight -= 1;
1907
+ cost.ms += ended - started;
1908
+ recorder.inFlight -= 1;
1909
+ if (recorder.inFlight === 0) recorder.busyMs += ended - recorder.busyStart;
1910
+ }
1911
+ /**
1912
+ * Wrap one callback so its execution time is recorded.
1913
+ *
1914
+ * Returns the callback untouched when there is no recorder, so a build that is not
1915
+ * measuring pays nothing beyond one branch at setup.
1916
+ */
1917
+ function measureHookCost(recorder, owner, hookName, handler) {
1918
+ if (recorder === void 0) return handler;
1919
+ const cost = costFor(recorder, owner, hookName);
1920
+ return function(...args) {
1921
+ const started = performance.now();
1922
+ markInFlightChange(cost, started);
1923
+ cost.calls += 1;
1924
+ cost.inFlight += 1;
1925
+ if (cost.inFlight > cost.maxInFlight) cost.maxInFlight = cost.inFlight;
1926
+ if (recorder.inFlight === 0) recorder.busyStart = started;
1927
+ recorder.inFlight += 1;
1928
+ let result;
1929
+ try {
1930
+ result = handler.apply(this, args);
1931
+ } catch (error) {
1932
+ settle(recorder, cost, started);
1933
+ throw error;
1934
+ }
1935
+ if (typeof result?.then === "function") return result.then((value) => {
1936
+ settle(recorder, cost, started);
1937
+ return value;
1938
+ }, (error) => {
1939
+ settle(recorder, cost, started);
1940
+ throw error;
1941
+ });
1942
+ settle(recorder, cost, started);
1943
+ return result;
1944
+ };
1945
+ }
1946
+ /**
1947
+ * The owner shown for user callbacks the core invokes directly rather than through a
1948
+ * plugin. One shared identity: they are all configured on the same options object.
1949
+ */
1950
+ const OUTPUT_OPTIONS_OWNER = {
1951
+ key: Symbol("output options"),
1952
+ name: "output options",
1953
+ kind: "outputOption"
1954
+ };
1955
+ /** As {@link OUTPUT_OPTIONS_OWNER}, for callbacks configured on the input options. */
1956
+ const INPUT_OPTIONS_OWNER = {
1957
+ key: Symbol("input options"),
1958
+ name: "input options",
1959
+ kind: "inputOption"
1960
+ };
1961
+ /**
1962
+ * Wrap `value` when the user supplied a function, and leave every other form alone.
1963
+ *
1964
+ * Most option callbacks are declared as `string | RegExp | Function | ...`, so this keeps
1965
+ * the one cast the wrapping needs in a single place.
1966
+ */
1967
+ function measureIfFunction(recorder, owner, hookName, value) {
1968
+ if (typeof value !== "function") return value;
1969
+ return measureHookCost(recorder, owner, hookName, value);
1970
+ }
1971
+ /**
1972
+ * What the build's callbacks have cost so far, leaving the recorder in place.
1973
+ *
1974
+ * Ungated on purpose: whether a build is worth reporting on is decided from the clocks Rust
1975
+ * holds, so the question is not this side's to ask.
1976
+ *
1977
+ * Rust calls this while the build is closing, so what it gets includes `closeBundle`.
1978
+ */
1979
+ function summarizePluginTimings(key) {
1980
+ const recorder = recorders.get(key);
1981
+ if (recorder === void 0) return {
1982
+ busyMs: 0,
1983
+ rows: []
1984
+ };
1985
+ const rows = [];
1986
+ for (const byHook of recorder.costs.values()) for (const cost of byHook.values()) {
1987
+ if (cost.calls === 0) continue;
1988
+ rows.push({
1989
+ owner: cost.owner,
1990
+ kind: cost.kind,
1991
+ hook: cost.hookName,
1992
+ calls: cost.calls,
1993
+ ms: cost.ms,
1994
+ maxInFlight: cost.maxInFlight,
1995
+ overlapMs: cost.overlapMs,
1996
+ rankable: cost.overlapMs <= cost.ms * OVERLAP_TOLERANCE
1997
+ });
1998
+ }
1999
+ return {
2000
+ busyMs: recorder.busyMs,
2001
+ rows
2002
+ };
2003
+ }
2004
+ //#endregion
2005
+ //#region src/plugin/bindingify-plugin.ts
2006
+ function bindingifyPlugin(plugin, options, outputOptions, pluginContextData, normalizedOutputPlugins, onLog, logLevel, watchMode, timings) {
2007
+ const args = {
2008
+ plugin,
2009
+ options,
2010
+ outputOptions,
2011
+ pluginContextData,
2012
+ onLog,
2013
+ logLevel,
2014
+ watchMode,
2015
+ normalizedOutputPlugins
2016
+ };
2017
+ const { plugin: buildStart, meta: buildStartMeta } = bindingifyBuildStart(args);
2018
+ const { plugin: resolveId, meta: resolveIdMeta, filter: resolveIdFilter } = bindingifyResolveId(args);
2019
+ const { plugin: resolveDynamicImport, meta: resolveDynamicImportMeta } = bindingifyResolveDynamicImport(args);
2020
+ const { plugin: buildEnd, meta: buildEndMeta } = bindingifyBuildEnd(args);
2021
+ const { plugin: transform, meta: transformMeta, filter: transformFilter } = bindingifyTransform(args);
2022
+ const { plugin: moduleParsed, meta: moduleParsedMeta } = bindingifyModuleParsed(args);
2023
+ const { plugin: load, meta: loadMeta, filter: loadFilter } = bindingifyLoad(args);
2024
+ const { plugin: renderChunk, meta: renderChunkMeta, filter: renderChunkFilter } = bindingifyRenderChunk(args);
2025
+ const { plugin: augmentChunkHash, meta: augmentChunkHashMeta } = bindingifyAugmentChunkHash(args);
2026
+ const { plugin: resolveFileUrl, meta: resolveFileUrlMeta } = bindingifyResolveFileUrl(args);
2027
+ const { plugin: renderStart, meta: renderStartMeta } = bindingifyRenderStart(args);
2028
+ const { plugin: renderError, meta: renderErrorMeta } = bindingifyRenderError(args);
2029
+ const { plugin: generateBundle, meta: generateBundleMeta } = bindingifyGenerateBundle(args);
2030
+ const { plugin: writeBundle, meta: writeBundleMeta } = bindingifyWriteBundle(args);
2031
+ const { plugin: closeBundle, meta: closeBundleMeta } = bindingifyCloseBundle(args);
2032
+ const { plugin: banner, meta: bannerMeta } = bindingifyAddonHook(args, "banner");
2033
+ const { plugin: footer, meta: footerMeta } = bindingifyAddonHook(args, "footer");
2034
+ const { plugin: intro, meta: introMeta } = bindingifyAddonHook(args, "intro");
2035
+ const { plugin: outro, meta: outroMeta } = bindingifyAddonHook(args, "outro");
2036
+ const { plugin: watchChange, meta: watchChangeMeta } = bindingifyWatchChange(args);
2037
+ const { plugin: hotUpdate, meta: hotUpdateMeta } = bindingifyHotUpdate(args);
2038
+ const { plugin: closeWatcher, meta: closeWatcherMeta } = bindingifyCloseWatcher(args);
2039
+ let hookUsage = extractHookUsage(plugin).inner();
2040
+ const result = {
2041
+ name: plugin.name,
2042
+ buildStart,
2043
+ buildStartMeta,
2044
+ resolveId,
2045
+ resolveIdMeta,
2046
+ resolveIdFilter,
2047
+ resolveDynamicImport,
2048
+ resolveDynamicImportMeta,
2049
+ buildEnd,
2050
+ buildEndMeta,
2051
+ transform,
2052
+ transformMeta,
2053
+ transformFilter,
2054
+ moduleParsed,
2055
+ moduleParsedMeta,
2056
+ load,
2057
+ loadMeta,
2058
+ loadFilter,
2059
+ renderChunk,
2060
+ renderChunkMeta,
2061
+ renderChunkFilter,
2062
+ augmentChunkHash,
2063
+ augmentChunkHashMeta,
2064
+ resolveFileUrl,
2065
+ resolveFileUrlMeta,
2066
+ renderStart,
2067
+ renderStartMeta,
2068
+ renderError,
2069
+ renderErrorMeta,
2070
+ generateBundle,
2071
+ generateBundleMeta,
2072
+ writeBundle,
2073
+ writeBundleMeta,
2074
+ closeBundle,
2075
+ closeBundleMeta,
2076
+ banner,
2077
+ bannerMeta,
2078
+ footer,
2079
+ footerMeta,
2080
+ intro,
2081
+ introMeta,
2082
+ outro,
2083
+ outroMeta,
2084
+ watchChange,
2085
+ watchChangeMeta,
2086
+ hotUpdate,
2087
+ hotUpdateMeta,
2088
+ closeWatcher,
2089
+ closeWatcherMeta,
2090
+ hookUsage
2091
+ };
2092
+ return wrapHandlers(result, {
2093
+ key: plugin,
2094
+ name: result.name,
2095
+ kind: "plugin"
2096
+ }, timings);
2097
+ }
2098
+ function wrapHandlers(plugin, owner, timings) {
2099
+ for (const hookName of [
2100
+ "buildStart",
2101
+ "resolveId",
2102
+ "resolveDynamicImport",
2103
+ "buildEnd",
2104
+ "transform",
2105
+ "moduleParsed",
2106
+ "load",
2107
+ "renderChunk",
2108
+ "augmentChunkHash",
2109
+ "resolveFileUrl",
2110
+ "renderStart",
2111
+ "renderError",
2112
+ "generateBundle",
2113
+ "writeBundle",
2114
+ "closeBundle",
2115
+ "banner",
2116
+ "footer",
2117
+ "intro",
2118
+ "outro",
2119
+ "watchChange",
2120
+ "hotUpdate",
2121
+ "closeWatcher"
2122
+ ]) {
2123
+ const raw = plugin[hookName];
2124
+ const handler = raw && measureHookCost(timings, owner, hookName, raw);
2125
+ if (handler) plugin[hookName] = async (...args) => {
2126
+ try {
2127
+ return await handler(...args);
2128
+ } catch (e) {
2129
+ return error(logPluginError(e, plugin.name, {
2130
+ hook: hookName,
2131
+ id: hookName === "transform" ? args[2] : void 0
2132
+ }));
2133
+ }
2134
+ };
2135
+ }
2136
+ return plugin;
2137
+ }
2138
+ //#endregion
2139
+ //#region src/utils/normalize-transform-options.ts
2140
+ /**
2141
+ * Normalizes transform options by extracting `define`, `inject`, and `dropLabels` separately from OXC transform options.
2142
+ *
2143
+ * Prioritizes values from `transform.define`, `transform.inject`, and `transform.dropLabels` over deprecated top-level options.
2144
+ */
2145
+ function normalizeTransformOptions(inputOptions) {
2146
+ const transform = inputOptions.transform;
2147
+ const define = transform?.define ? Object.entries(transform.define) : void 0;
2148
+ const inject = transform?.inject;
2149
+ const dropLabels = transform?.dropLabels;
2150
+ let oxcTransformOptions;
2151
+ if (transform) {
2152
+ const { define: _define, inject: _inject, dropLabels: _dropLabels, ...rest } = transform;
2153
+ if (Object.keys(rest).length > 0) {
2154
+ if (rest.jsx === false) rest.jsx = "disable";
2155
+ oxcTransformOptions = rest;
2156
+ }
2157
+ }
2158
+ return {
2159
+ define,
2160
+ inject,
2161
+ dropLabels,
2162
+ oxcTransformOptions
2163
+ };
2164
+ }
2165
+ //#endregion
2166
+ //#region src/utils/default-dev-runtime.ts
2167
+ function getDefaultDevRuntime(host = "localhost", port = 3e3) {
2168
+ const runtimeEntry = fs.readFileSync(fileURLToPath(import.meta.resolve("#runtime")), "utf8");
2169
+ const runtimeHelperImportEnd = runtimeEntry.indexOf("\n");
2170
+ if (!runtimeEntry.startsWith("import ") || runtimeHelperImportEnd === -1) throw new Error("Expected the standalone runtime to start with a helper import");
2171
+ return `${runtimeEntry.slice(runtimeHelperImportEnd + 1)}\n${fs.readFileSync(fileURLToPath(import.meta.resolve("#default-runtime")), "utf8").replaceAll("$ADDR", `${host}:${port}`)}`;
2172
+ }
2173
+ //#endregion
2174
+ //#region src/utils/bindingify-input-options.ts
2175
+ function bindingifyInputOptions(rawPlugins, inputOptions, outputOptions, pluginContextData, normalizedOutputPlugins, onLog, logLevel, watchMode, timings) {
2176
+ const plugins = rawPlugins.map((plugin) => {
2177
+ if (getParallelPluginInfo(plugin)) return;
2178
+ if (plugin instanceof BuiltinPlugin) switch (plugin.name) {
2179
+ case "builtin:vite-manifest": return bindingifyManifestPlugin(plugin, pluginContextData);
2180
+ default: return bindingifyBuiltInPlugin(plugin);
2181
+ }
2182
+ return bindingifyPlugin(plugin, inputOptions, outputOptions, pluginContextData, normalizedOutputPlugins, onLog, logLevel, watchMode, timings);
2183
+ });
2184
+ const normalizedTransform = normalizeTransformOptions(inputOptions);
2185
+ return {
2186
+ input: bindingifyInput(inputOptions.input),
2187
+ plugins,
2188
+ cwd: inputOptions.cwd ?? process.cwd(),
2189
+ external: bindingifyExternal(inputOptions.external, timings),
2190
+ resolve: bindingifyResolve(inputOptions.resolve),
2191
+ platform: inputOptions.platform,
2192
+ shimMissingExports: inputOptions.shimMissingExports,
2193
+ logLevel: bindingifyLogLevel(logLevel),
2194
+ onLog,
2195
+ treeshake: bindingifyTreeshakeOptions(inputOptions.treeshake, timings),
2196
+ moduleTypes: inputOptions.moduleTypes,
2197
+ define: normalizedTransform.define,
2198
+ inject: bindingifyInject(normalizedTransform.inject),
2199
+ experimental: bindingifyExperimental(inputOptions.experimental),
2200
+ profilerNames: outputOptions.generatedCode?.profilerNames,
2201
+ transform: normalizedTransform.oxcTransformOptions,
2202
+ watch: bindingifyWatch(inputOptions.watch),
2203
+ dropLabels: normalizedTransform.dropLabels,
2204
+ keepNames: outputOptions.keepNames,
2205
+ checks: inputOptions.checks,
2206
+ pluginTimings: timings ? () => summarizePluginTimings(inputOptions) : void 0,
2207
+ deferSyncScanData: () => {
2208
+ let ret = [];
2209
+ pluginContextData.moduleOptionMap.forEach((value, key) => {
2210
+ if (value.invalidate) ret.push({
2211
+ id: key,
2212
+ sideEffects: value.moduleSideEffects ?? void 0
2213
+ });
2214
+ });
2215
+ return ret;
2216
+ },
2217
+ makeAbsoluteExternalsRelative: bindingifyMakeAbsoluteExternalsRelative(inputOptions.makeAbsoluteExternalsRelative),
2218
+ devtools: inputOptions.devtools,
2219
+ invalidateJsSideCache: pluginContextData.clear.bind(pluginContextData),
2220
+ preserveEntrySignatures: bindingifyPreserveEntrySignatures(inputOptions.preserveEntrySignatures),
2221
+ optimization: inputOptions.optimization,
2222
+ context: inputOptions.context,
2223
+ tsconfig: inputOptions.resolve?.tsconfigFilename ?? inputOptions.tsconfig
2224
+ };
2225
+ }
2226
+ function bindingifyDevMode(devMode) {
2227
+ if (devMode) {
2228
+ if (typeof devMode === "boolean") return devMode ? {
2229
+ implement: getDefaultDevRuntime(),
2230
+ skipCommonRuntimeInjection: true
2231
+ } : void 0;
2232
+ const usesDefaultRuntime = devMode.implement == null;
2233
+ return {
2234
+ ...devMode,
2235
+ implement: devMode.implement ?? getDefaultDevRuntime(devMode.host, devMode.port),
2236
+ skipCommonRuntimeInjection: usesDefaultRuntime ? true : devMode.skipCommonRuntimeInjection
2237
+ };
2238
+ }
2239
+ }
2240
+ function bindingifyAttachDebugInfo(attachDebugInfo) {
2241
+ switch (attachDebugInfo) {
2242
+ case void 0: return;
2243
+ case "full": return import_binding.BindingAttachDebugInfo.Full;
2244
+ case "simple": return import_binding.BindingAttachDebugInfo.Simple;
2245
+ case "none": return import_binding.BindingAttachDebugInfo.None;
2246
+ }
2247
+ }
2248
+ function bindingifyExternal(external, timings) {
2249
+ if (external) {
2250
+ if (typeof external === "function") {
2251
+ const measured = measureHookCost(timings, INPUT_OPTIONS_OWNER, "external", external);
2252
+ return (id, importer, isResolved) => {
2253
+ if (id.startsWith("\0")) return false;
2254
+ return measured(id, importer, isResolved) ?? false;
2255
+ };
2256
+ }
2257
+ return arraify(external);
2258
+ }
2259
+ }
2260
+ function bindingifyExperimental(experimental) {
2261
+ let chunkModulesOrder = import_binding.BindingChunkModuleOrderBy.ExecOrder;
2262
+ if (experimental?.chunkModulesOrder) switch (experimental.chunkModulesOrder) {
2263
+ case "exec-order":
2264
+ chunkModulesOrder = import_binding.BindingChunkModuleOrderBy.ExecOrder;
2265
+ break;
2266
+ case "module-id":
2267
+ chunkModulesOrder = import_binding.BindingChunkModuleOrderBy.ModuleId;
2268
+ break;
2269
+ default: throw new Error(`Unexpected chunkModulesOrder: ${experimental.chunkModulesOrder}`);
2270
+ }
2271
+ return {
2272
+ viteMode: experimental?.viteMode,
2273
+ resolveNewUrlToAsset: experimental?.resolveNewUrlToAsset,
2274
+ devMode: bindingifyDevMode(experimental?.devMode),
2275
+ attachDebugInfo: bindingifyAttachDebugInfo(experimental?.attachDebugInfo),
2276
+ chunkModulesOrder,
2277
+ chunkImportMap: experimental?.chunkImportMap,
2278
+ onDemandWrapping: experimental?.onDemandWrapping,
2279
+ incrementalBuild: experimental?.incrementalBuild,
2280
+ nativeMagicString: experimental?.nativeMagicString,
2281
+ chunkOptimization: experimental?.chunkOptimization,
2282
+ lazyBarrel: experimental?.lazyBarrel
2283
+ };
2284
+ }
2285
+ function bindingifyResolve(resolve) {
2286
+ const yarnPnp = typeof process === "object" && !!process.versions?.pnp;
2287
+ if (resolve) {
2288
+ const { alias, extensionAlias, ...rest } = resolve;
2289
+ return {
2290
+ alias: alias ? Object.entries(alias).map(([name, replacement]) => ({
2291
+ find: name,
2292
+ replacements: replacement === false ? [void 0] : arraify(replacement)
2293
+ })) : void 0,
2294
+ extensionAlias: extensionAlias ? Object.entries(extensionAlias).map(([name, value]) => ({
2295
+ target: name,
2296
+ replacements: value
2297
+ })) : void 0,
2298
+ yarnPnp,
2299
+ ...rest
2300
+ };
2301
+ } else return { yarnPnp };
2302
+ }
2303
+ function bindingifyInject(inject) {
2304
+ if (inject) return Object.entries(inject).map(([alias, item]) => {
2305
+ if (Array.isArray(item)) {
2306
+ if (item[1] === "*") return {
2307
+ tagNamespace: true,
2308
+ alias,
2309
+ from: item[0]
2310
+ };
2311
+ return {
2312
+ tagNamed: true,
2313
+ alias,
2314
+ from: item[0],
2315
+ imported: item[1]
2316
+ };
2317
+ } else return {
2318
+ tagNamed: true,
2319
+ imported: "default",
2320
+ alias,
2321
+ from: item
2322
+ };
2323
+ });
2324
+ }
2325
+ function bindingifyLogLevel(logLevel) {
2326
+ switch (logLevel) {
2327
+ case "silent": return import_binding.BindingLogLevel.Silent;
2328
+ case "debug": return import_binding.BindingLogLevel.Debug;
2329
+ case "warn": return import_binding.BindingLogLevel.Warn;
2330
+ case "info": return import_binding.BindingLogLevel.Info;
2331
+ default: throw new Error(`Unexpected log level: ${logLevel}`);
2332
+ }
2333
+ }
2334
+ function bindingifyInput(input) {
2335
+ if (input === void 0) return [];
2336
+ if (typeof input === "string") return [{ import: input }];
2337
+ if (Array.isArray(input)) return input.map((src) => ({ import: src }));
2338
+ return Object.entries(input).map(([name, import_path]) => {
2339
+ return {
2340
+ name,
2341
+ import: import_path
2342
+ };
2343
+ });
2344
+ }
2345
+ function bindingifyWatch(watch) {
2346
+ if (watch) {
2347
+ const watcher = watch.watcher ?? {};
2348
+ return {
2349
+ buildDelay: watch.buildDelay,
2350
+ skipWrite: watch.skipWrite,
2351
+ usePolling: watcher.usePolling,
2352
+ pollInterval: watcher.pollInterval,
2353
+ compareContentsForPolling: watcher.compareContentsForPolling,
2354
+ useDebounce: watcher.useDebounce,
2355
+ debounceDelay: watcher.debounceDelay,
2356
+ debounceTickRate: watcher.debounceTickRate,
2357
+ include: normalizedStringOrRegex(watch.include),
2358
+ exclude: normalizedStringOrRegex(watch.exclude),
2359
+ onInvalidate: (...args) => watch.onInvalidate?.(...args)
2360
+ };
2361
+ }
2362
+ }
2363
+ function bindingifyTreeshakeOptions(config, timings) {
2364
+ if (config === false) return;
2365
+ if (config === true || config === void 0) return { moduleSideEffects: true };
2366
+ let normalizedConfig = {
2367
+ moduleSideEffects: true,
2368
+ annotations: config.annotations,
2369
+ manualPureFunctions: config.manualPureFunctions,
2370
+ unknownGlobalSideEffects: config.unknownGlobalSideEffects,
2371
+ invalidImportSideEffects: config.invalidImportSideEffects,
2372
+ commonjs: config.commonjs
2373
+ };
2374
+ switch (config.propertyReadSideEffects) {
2375
+ case "always":
2376
+ normalizedConfig.propertyReadSideEffects = import_binding.BindingPropertyReadSideEffects.Always;
2377
+ break;
2378
+ case false: normalizedConfig.propertyReadSideEffects = import_binding.BindingPropertyReadSideEffects.False;
2379
+ }
2380
+ switch (config.propertyWriteSideEffects) {
2381
+ case "always":
2382
+ normalizedConfig.propertyWriteSideEffects = import_binding.BindingPropertyWriteSideEffects.Always;
2383
+ break;
2384
+ case false: normalizedConfig.propertyWriteSideEffects = import_binding.BindingPropertyWriteSideEffects.False;
2385
+ }
2386
+ if (config.moduleSideEffects === void 0) normalizedConfig.moduleSideEffects = true;
2387
+ else if (config.moduleSideEffects === "no-external") normalizedConfig.moduleSideEffects = [{
2388
+ external: true,
2389
+ sideEffects: false
2390
+ }, {
2391
+ external: false,
2392
+ sideEffects: true
2393
+ }];
2394
+ else normalizedConfig.moduleSideEffects = measureIfFunction(timings, INPUT_OPTIONS_OWNER, "treeshake.moduleSideEffects", config.moduleSideEffects);
2395
+ return normalizedConfig;
2396
+ }
2397
+ function bindingifyMakeAbsoluteExternalsRelative(makeAbsoluteExternalsRelative) {
2398
+ if (makeAbsoluteExternalsRelative === "ifRelativeSource") return { type: "IfRelativeSource" };
2399
+ if (typeof makeAbsoluteExternalsRelative === "boolean") return {
2400
+ type: "Bool",
2401
+ field0: makeAbsoluteExternalsRelative
2402
+ };
2403
+ }
2404
+ function bindingifyPreserveEntrySignatures(preserveEntrySignatures) {
2405
+ if (preserveEntrySignatures == void 0) return;
2406
+ else if (typeof preserveEntrySignatures === "string") return {
2407
+ type: "String",
2408
+ field0: preserveEntrySignatures
2409
+ };
2410
+ else return {
2411
+ type: "Bool",
2412
+ field0: preserveEntrySignatures
2413
+ };
2414
+ }
2415
+ //#endregion
2416
+ export { LOG_LEVEL_WARN as C, version as D, description as E, LOG_LEVEL_INFO as S, VERSION as T, getParallelPluginInfo as _, measureIfFunction as a, LOG_LEVEL_DEBUG as b, PluginContextData as c, transformRenderedChunk as d, __decorate as f, MinimalPluginContextImpl as g, PlainObjectLike as h, measureHookCost as i, transformModuleInfo as l, lazyProp as m, bindingifyPlugin as n, pluginTimingsRecorderFor as o, transformAssetSource as p, OUTPUT_OPTIONS_OWNER as r, RolldownMagicString as s, bindingifyInputOptions as t, transformToRollupOutput as u, normalizeHook as v, logLevelPriority as w, LOG_LEVEL_ERROR as x, normalizeLog as y };