@rolldown/browser 1.0.0-beta.10

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 (56) hide show
  1. package/LICENSE +25 -0
  2. package/bin/cli.mjs +2 -0
  3. package/dist/cli.cjs +1748 -0
  4. package/dist/cli.d.cts +1 -0
  5. package/dist/cli.d.mts +1 -0
  6. package/dist/cli.mjs +1771 -0
  7. package/dist/config.cjs +12 -0
  8. package/dist/config.d.cts +11 -0
  9. package/dist/config.d.mts +11 -0
  10. package/dist/config.mjs +10 -0
  11. package/dist/experimental-index.browser.mjs +76 -0
  12. package/dist/experimental-index.cjs +129 -0
  13. package/dist/experimental-index.d.cts +96 -0
  14. package/dist/experimental-index.d.mts +96 -0
  15. package/dist/experimental-index.mjs +84 -0
  16. package/dist/filter-index.cjs +53 -0
  17. package/dist/filter-index.d.cts +3 -0
  18. package/dist/filter-index.d.mts +3 -0
  19. package/dist/filter-index.mjs +43 -0
  20. package/dist/index.browser.mjs +3 -0
  21. package/dist/index.cjs +9 -0
  22. package/dist/index.d.cts +3 -0
  23. package/dist/index.d.mts +3 -0
  24. package/dist/index.mjs +5 -0
  25. package/dist/parallel-plugin-worker.cjs +33 -0
  26. package/dist/parallel-plugin-worker.d.cts +1 -0
  27. package/dist/parallel-plugin-worker.d.mts +1 -0
  28. package/dist/parallel-plugin-worker.mjs +32 -0
  29. package/dist/parallel-plugin.cjs +8 -0
  30. package/dist/parallel-plugin.d.cts +14 -0
  31. package/dist/parallel-plugin.d.mts +14 -0
  32. package/dist/parallel-plugin.mjs +7 -0
  33. package/dist/parse-ast-index.cjs +4 -0
  34. package/dist/parse-ast-index.d.cts +9 -0
  35. package/dist/parse-ast-index.d.mts +9 -0
  36. package/dist/parse-ast-index.mjs +3 -0
  37. package/dist/rolldown-binding.wasi-browser.js +111 -0
  38. package/dist/rolldown-binding.wasi.cjs +135 -0
  39. package/dist/rolldown-binding.wasm32-wasi.wasm +0 -0
  40. package/dist/shared/chunk-DDkG_k5U.cjs +39 -0
  41. package/dist/shared/define-config.d-BBxr6_Bs.d.mts +1167 -0
  42. package/dist/shared/define-config.d-DII1FzpF.d.cts +1167 -0
  43. package/dist/shared/dist-BMVjvV-v.cjs +249 -0
  44. package/dist/shared/dist-JdACkHJM.mjs +147 -0
  45. package/dist/shared/load-config-CS9U8pRI.cjs +125 -0
  46. package/dist/shared/load-config-MCu-vRGz.mjs +119 -0
  47. package/dist/shared/parse-ast-index-BuelS_NF.cjs +314 -0
  48. package/dist/shared/parse-ast-index-C31FpvkE.mjs +260 -0
  49. package/dist/shared/prompt-8EeOGx1_.cjs +854 -0
  50. package/dist/shared/prompt-C3zHEaSG.mjs +852 -0
  51. package/dist/shared/src-AQQVsE86.mjs +4449 -0
  52. package/dist/shared/src-DKImwtxN.cjs +4647 -0
  53. package/dist/src-8Q9XjZLd.js +4329 -0
  54. package/dist/wasi-worker-browser.mjs +39 -0
  55. package/dist/wasi-worker.mjs +63 -0
  56. package/package.json +71 -0
@@ -0,0 +1,4449 @@
1
+ import { and$1 as and, arraify, code$1 as code, exclude$1 as exclude, id$1 as id, include$1 as include, isNullish, moduleType$1 as moduleType, noop, or$1 as or, unimplemented, unreachable, unsupported } from "./dist-JdACkHJM.mjs";
2
+ import { augmentCodeLocation, error, logCycleLoading, logInputHookInOutputPlugin, logInvalidLogPosition, logMultiplyNotifyOption, logPluginError, parseAst } from "./parse-ast-index-C31FpvkE.mjs";
3
+ import { BindingCallableBuiltinPlugin, BindingHookSideEffects, BindingJsx, BindingLogLevel, BindingPluginOrder, BindingWatcher, Bundler, ParallelJsPluginRegistry, shutdownAsyncRuntime, startAsyncRuntime } from "../rolldown-binding.wasi.cjs";
4
+ import path from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import colors from "ansis";
7
+ import os from "node:os";
8
+ import { Worker } from "node:worker_threads";
9
+
10
+ //#region package.json
11
+ var version = "1.0.0-beta.10";
12
+ var description$1 = "Fast JavaScript/TypeScript bundler in Rust with Rollup-compatible API.";
13
+
14
+ //#endregion
15
+ //#region src/builtin-plugin/utils.ts
16
+ function makeBuiltinPluginCallable(plugin) {
17
+ let callablePlugin = new BindingCallableBuiltinPlugin(bindingifyBuiltInPlugin(plugin));
18
+ const wrappedPlugin = plugin;
19
+ for (const key in callablePlugin) wrappedPlugin[key] = function(...args$1) {
20
+ return callablePlugin[key](...args$1);
21
+ };
22
+ return wrappedPlugin;
23
+ }
24
+ function bindingifyBuiltInPlugin(plugin) {
25
+ return {
26
+ __name: plugin.name,
27
+ options: plugin._options
28
+ };
29
+ }
30
+
31
+ //#endregion
32
+ //#region src/builtin-plugin/constructors.ts
33
+ var BuiltinPlugin = class {
34
+ constructor(name, _options) {
35
+ this.name = name;
36
+ this._options = _options;
37
+ }
38
+ };
39
+ function modulePreloadPolyfillPlugin() {
40
+ return new BuiltinPlugin("builtin:module-preload-polyfill");
41
+ }
42
+ function dynamicImportVarsPlugin(config) {
43
+ return new BuiltinPlugin("builtin:dynamic-import-vars", config);
44
+ }
45
+ function importGlobPlugin(config) {
46
+ return new BuiltinPlugin("builtin:import-glob", config);
47
+ }
48
+ function reporterPlugin(config) {
49
+ return new BuiltinPlugin("builtin:reporter", config);
50
+ }
51
+ function manifestPlugin(config) {
52
+ return new BuiltinPlugin("builtin:manifest", config);
53
+ }
54
+ function wasmHelperPlugin() {
55
+ return new BuiltinPlugin("builtin:wasm-helper");
56
+ }
57
+ function wasmFallbackPlugin() {
58
+ return new BuiltinPlugin("builtin:wasm-fallback");
59
+ }
60
+ function loadFallbackPlugin() {
61
+ return new BuiltinPlugin("builtin:load-fallback");
62
+ }
63
+ function jsonPlugin(config) {
64
+ return new BuiltinPlugin("builtin:json", config);
65
+ }
66
+ function buildImportAnalysisPlugin(config) {
67
+ return new BuiltinPlugin("builtin:build-import-analysis", config);
68
+ }
69
+ function viteResolvePlugin(config) {
70
+ const builtinPlugin = new BuiltinPlugin("builtin:vite-resolve", config);
71
+ return makeBuiltinPluginCallable(builtinPlugin);
72
+ }
73
+ function moduleFederationPlugin(config) {
74
+ return new BuiltinPlugin("builtin:module-federation", {
75
+ ...config,
76
+ remotes: config.remotes && Object.entries(config.remotes).map(([name, remote]) => {
77
+ if (typeof remote === "string") {
78
+ const [entryGlobalName] = remote.split("@");
79
+ const entry = remote.replace(entryGlobalName + "@", "");
80
+ return {
81
+ entry,
82
+ name,
83
+ entryGlobalName
84
+ };
85
+ }
86
+ return {
87
+ ...remote,
88
+ name: remote.name ?? name
89
+ };
90
+ }),
91
+ manifest: config.manifest === false ? void 0 : config.manifest === true ? {} : config.manifest
92
+ });
93
+ }
94
+ function isolatedDeclarationPlugin(config) {
95
+ return new BuiltinPlugin("builtin:isolated-declaration", config);
96
+ }
97
+ function assetPlugin(config) {
98
+ return new BuiltinPlugin("builtin:asset", config);
99
+ }
100
+ function webWorkerPostPlugin() {
101
+ return new BuiltinPlugin("builtin:web-worker-post");
102
+ }
103
+ function oxcRuntimePlugin(config) {
104
+ return new BuiltinPlugin("builtin:oxc-runtime", config);
105
+ }
106
+
107
+ //#endregion
108
+ //#region src/log/logging.ts
109
+ const LOG_LEVEL_SILENT = "silent";
110
+ const LOG_LEVEL_ERROR = "error";
111
+ const LOG_LEVEL_WARN = "warn";
112
+ const LOG_LEVEL_INFO = "info";
113
+ const LOG_LEVEL_DEBUG = "debug";
114
+ const logLevelPriority = {
115
+ [LOG_LEVEL_DEBUG]: 0,
116
+ [LOG_LEVEL_INFO]: 1,
117
+ [LOG_LEVEL_WARN]: 2,
118
+ [LOG_LEVEL_SILENT]: 3
119
+ };
120
+
121
+ //#endregion
122
+ //#region src/log/log-handler.ts
123
+ const normalizeLog = (log) => typeof log === "string" ? { message: log } : typeof log === "function" ? normalizeLog(log()) : log;
124
+ function getLogHandler(level, code$1, logger, pluginName, logLevel) {
125
+ if (logLevelPriority[level] < logLevelPriority[logLevel]) return noop;
126
+ return (log, pos) => {
127
+ if (pos != null) logger(LOG_LEVEL_WARN, logInvalidLogPosition(pluginName));
128
+ log = normalizeLog(log);
129
+ if (log.code && !log.pluginCode) log.pluginCode = log.code;
130
+ log.code = code$1;
131
+ log.plugin = pluginName;
132
+ logger(level, log);
133
+ };
134
+ }
135
+
136
+ //#endregion
137
+ //#region src/log/logger.ts
138
+ function getLogger(plugins, onLog, logLevel, watchMode) {
139
+ const minimalPriority = logLevelPriority[logLevel];
140
+ const logger = (level, log, skipped = /* @__PURE__ */ new Set()) => {
141
+ const logPriority = logLevelPriority[level];
142
+ if (logPriority < minimalPriority) return;
143
+ for (const plugin of getSortedPlugins("onLog", plugins)) {
144
+ if (skipped.has(plugin)) continue;
145
+ const { onLog: pluginOnLog } = plugin;
146
+ if (pluginOnLog) {
147
+ const getLogHandler$1 = (level$1) => {
148
+ if (logLevelPriority[level$1] < minimalPriority) return () => {};
149
+ return (log$1) => logger(level$1, normalizeLog(log$1), new Set(skipped).add(plugin));
150
+ };
151
+ const handler = "handler" in pluginOnLog ? pluginOnLog.handler : pluginOnLog;
152
+ if (handler.call({
153
+ debug: getLogHandler$1(LOG_LEVEL_DEBUG),
154
+ error: (log$1) => error(normalizeLog(log$1)),
155
+ info: getLogHandler$1(LOG_LEVEL_INFO),
156
+ meta: {
157
+ rollupVersion: "4.23.0",
158
+ rolldownVersion: VERSION,
159
+ watchMode
160
+ },
161
+ warn: getLogHandler$1(LOG_LEVEL_WARN),
162
+ pluginName: plugin.name || "unknown"
163
+ }, level, log) === false) return;
164
+ }
165
+ }
166
+ onLog(level, log);
167
+ };
168
+ return logger;
169
+ }
170
+ const getOnLog = (config, logLevel, printLog = defaultPrintLog) => {
171
+ const { onwarn, onLog } = config;
172
+ const defaultOnLog = getDefaultOnLog(printLog, onwarn);
173
+ if (onLog) {
174
+ const minimalPriority = logLevelPriority[logLevel];
175
+ return (level, log) => onLog(level, addLogToString(log), (level$1, handledLog) => {
176
+ if (level$1 === LOG_LEVEL_ERROR) return error(normalizeLog(handledLog));
177
+ if (logLevelPriority[level$1] >= minimalPriority) defaultOnLog(level$1, normalizeLog(handledLog));
178
+ });
179
+ }
180
+ return defaultOnLog;
181
+ };
182
+ const getDefaultOnLog = (printLog, onwarn) => onwarn ? (level, log) => {
183
+ if (level === LOG_LEVEL_WARN) onwarn(addLogToString(log), (warning) => printLog(LOG_LEVEL_WARN, normalizeLog(warning)));
184
+ else printLog(level, log);
185
+ } : printLog;
186
+ const addLogToString = (log) => {
187
+ Object.defineProperty(log, "toString", {
188
+ value: () => getExtendedLogMessage(log),
189
+ writable: true
190
+ });
191
+ return log;
192
+ };
193
+ const defaultPrintLog = (level, log) => {
194
+ const message = getExtendedLogMessage(log);
195
+ switch (level) {
196
+ case LOG_LEVEL_WARN: return console.warn(message);
197
+ case LOG_LEVEL_DEBUG: return console.debug(message);
198
+ default: return console.info(message);
199
+ }
200
+ };
201
+ const getExtendedLogMessage = (log) => {
202
+ let prefix = "";
203
+ if (log.plugin) prefix += `(${log.plugin} plugin) `;
204
+ if (log.loc) prefix += `${relativeId(log.loc.file)} (${log.loc.line}:${log.loc.column}) `;
205
+ return prefix + log.message;
206
+ };
207
+ function relativeId(id$1) {
208
+ if (!path.isAbsolute(id$1)) return id$1;
209
+ return path.relative(path.resolve(), id$1);
210
+ }
211
+
212
+ //#endregion
213
+ //#region src/utils/normalize-hook.ts
214
+ function normalizeHook(hook) {
215
+ if (typeof hook === "function" || typeof hook === "string") return {
216
+ handler: hook,
217
+ options: {},
218
+ meta: {}
219
+ };
220
+ if (typeof hook === "object" && hook !== null) {
221
+ const { handler, order,...options } = hook;
222
+ return {
223
+ handler,
224
+ options,
225
+ meta: { order }
226
+ };
227
+ }
228
+ unreachable("Invalid hook type");
229
+ }
230
+
231
+ //#endregion
232
+ //#region src/constants/plugin.ts
233
+ const ENUMERATED_INPUT_PLUGIN_HOOK_NAMES = [
234
+ "options",
235
+ "buildStart",
236
+ "resolveId",
237
+ "load",
238
+ "transform",
239
+ "moduleParsed",
240
+ "buildEnd",
241
+ "onLog",
242
+ "resolveDynamicImport",
243
+ "closeBundle",
244
+ "closeWatcher",
245
+ "watchChange"
246
+ ];
247
+ const ENUMERATED_OUTPUT_PLUGIN_HOOK_NAMES = [
248
+ "augmentChunkHash",
249
+ "outputOptions",
250
+ "renderChunk",
251
+ "renderStart",
252
+ "renderError",
253
+ "writeBundle",
254
+ "generateBundle"
255
+ ];
256
+ const ENUMERATED_PLUGIN_HOOK_NAMES = [
257
+ ...ENUMERATED_INPUT_PLUGIN_HOOK_NAMES,
258
+ ...ENUMERATED_OUTPUT_PLUGIN_HOOK_NAMES,
259
+ "footer",
260
+ "banner",
261
+ "intro",
262
+ "outro"
263
+ ];
264
+ /**
265
+ * Names of all defined hooks. It's like
266
+ * ```js
267
+ * const DEFINED_HOOK_NAMES ={
268
+ * options: 'options',
269
+ * buildStart: 'buildStart',
270
+ * ...
271
+ * }
272
+ * ```
273
+ */
274
+ const DEFINED_HOOK_NAMES = {
275
+ [ENUMERATED_PLUGIN_HOOK_NAMES[0]]: ENUMERATED_PLUGIN_HOOK_NAMES[0],
276
+ [ENUMERATED_PLUGIN_HOOK_NAMES[1]]: ENUMERATED_PLUGIN_HOOK_NAMES[1],
277
+ [ENUMERATED_PLUGIN_HOOK_NAMES[2]]: ENUMERATED_PLUGIN_HOOK_NAMES[2],
278
+ [ENUMERATED_PLUGIN_HOOK_NAMES[3]]: ENUMERATED_PLUGIN_HOOK_NAMES[3],
279
+ [ENUMERATED_PLUGIN_HOOK_NAMES[4]]: ENUMERATED_PLUGIN_HOOK_NAMES[4],
280
+ [ENUMERATED_PLUGIN_HOOK_NAMES[5]]: ENUMERATED_PLUGIN_HOOK_NAMES[5],
281
+ [ENUMERATED_PLUGIN_HOOK_NAMES[6]]: ENUMERATED_PLUGIN_HOOK_NAMES[6],
282
+ [ENUMERATED_PLUGIN_HOOK_NAMES[7]]: ENUMERATED_PLUGIN_HOOK_NAMES[7],
283
+ [ENUMERATED_PLUGIN_HOOK_NAMES[8]]: ENUMERATED_PLUGIN_HOOK_NAMES[8],
284
+ [ENUMERATED_PLUGIN_HOOK_NAMES[9]]: ENUMERATED_PLUGIN_HOOK_NAMES[9],
285
+ [ENUMERATED_PLUGIN_HOOK_NAMES[10]]: ENUMERATED_PLUGIN_HOOK_NAMES[10],
286
+ [ENUMERATED_PLUGIN_HOOK_NAMES[11]]: ENUMERATED_PLUGIN_HOOK_NAMES[11],
287
+ [ENUMERATED_PLUGIN_HOOK_NAMES[12]]: ENUMERATED_PLUGIN_HOOK_NAMES[12],
288
+ [ENUMERATED_PLUGIN_HOOK_NAMES[13]]: ENUMERATED_PLUGIN_HOOK_NAMES[13],
289
+ [ENUMERATED_PLUGIN_HOOK_NAMES[14]]: ENUMERATED_PLUGIN_HOOK_NAMES[14],
290
+ [ENUMERATED_PLUGIN_HOOK_NAMES[15]]: ENUMERATED_PLUGIN_HOOK_NAMES[15],
291
+ [ENUMERATED_PLUGIN_HOOK_NAMES[16]]: ENUMERATED_PLUGIN_HOOK_NAMES[16],
292
+ [ENUMERATED_PLUGIN_HOOK_NAMES[17]]: ENUMERATED_PLUGIN_HOOK_NAMES[17],
293
+ [ENUMERATED_PLUGIN_HOOK_NAMES[18]]: ENUMERATED_PLUGIN_HOOK_NAMES[18],
294
+ [ENUMERATED_PLUGIN_HOOK_NAMES[19]]: ENUMERATED_PLUGIN_HOOK_NAMES[19],
295
+ [ENUMERATED_PLUGIN_HOOK_NAMES[20]]: ENUMERATED_PLUGIN_HOOK_NAMES[20],
296
+ [ENUMERATED_PLUGIN_HOOK_NAMES[21]]: ENUMERATED_PLUGIN_HOOK_NAMES[21],
297
+ [ENUMERATED_PLUGIN_HOOK_NAMES[22]]: ENUMERATED_PLUGIN_HOOK_NAMES[22]
298
+ };
299
+
300
+ //#endregion
301
+ //#region src/utils/async-flatten.ts
302
+ async function asyncFlatten(array$1) {
303
+ do
304
+ array$1 = (await Promise.all(array$1)).flat(Infinity);
305
+ while (array$1.some((v) => v?.then));
306
+ return array$1;
307
+ }
308
+
309
+ //#endregion
310
+ //#region src/utils/normalize-plugin-option.ts
311
+ const normalizePluginOption = async (plugins) => (await asyncFlatten([plugins])).filter(Boolean);
312
+ function checkOutputPluginOption(plugins, onLog) {
313
+ for (const plugin of plugins) for (const hook of ENUMERATED_INPUT_PLUGIN_HOOK_NAMES) if (hook in plugin) {
314
+ delete plugin[hook];
315
+ onLog(LOG_LEVEL_WARN, logInputHookInOutputPlugin(plugin.name, hook));
316
+ }
317
+ return plugins;
318
+ }
319
+ function normalizePlugins(plugins, anonymousPrefix) {
320
+ for (const [index, plugin] of plugins.entries()) {
321
+ if ("_parallel" in plugin) continue;
322
+ if (plugin instanceof BuiltinPlugin) continue;
323
+ if (!plugin.name) plugin.name = `${anonymousPrefix}${index + 1}`;
324
+ }
325
+ return plugins;
326
+ }
327
+ const ANONYMOUS_PLUGIN_PREFIX = "at position ";
328
+ const ANONYMOUS_OUTPUT_PLUGIN_PREFIX = "at output position ";
329
+ const BUILTIN_PLUGINS = [oxcRuntimePlugin({ resolveBase: fileURLToPath(import.meta.url) })];
330
+
331
+ //#endregion
332
+ //#region src/plugin/minimal-plugin-context.ts
333
+ var MinimalPluginContextImpl = class {
334
+ info;
335
+ warn;
336
+ debug;
337
+ meta;
338
+ constructor(onLog, logLevel, pluginName, watchMode, hookName) {
339
+ this.pluginName = pluginName;
340
+ this.hookName = hookName;
341
+ this.debug = getLogHandler(LOG_LEVEL_DEBUG, "PLUGIN_LOG", onLog, pluginName, logLevel);
342
+ this.info = getLogHandler(LOG_LEVEL_INFO, "PLUGIN_LOG", onLog, pluginName, logLevel);
343
+ this.warn = getLogHandler(LOG_LEVEL_WARN, "PLUGIN_WARNING", onLog, pluginName, logLevel);
344
+ this.meta = {
345
+ rollupVersion: "4.23.0",
346
+ rolldownVersion: VERSION,
347
+ watchMode
348
+ };
349
+ }
350
+ error(e) {
351
+ return error(logPluginError(normalizeLog(e), this.pluginName, { hook: this.hookName }));
352
+ }
353
+ };
354
+
355
+ //#endregion
356
+ //#region src/plugin/plugin-driver.ts
357
+ var PluginDriver = class {
358
+ static async callOptionsHook(inputOptions, watchMode = false) {
359
+ const logLevel = inputOptions.logLevel || LOG_LEVEL_INFO;
360
+ const plugins = getSortedPlugins("options", getObjectPlugins(await normalizePluginOption(inputOptions.plugins)));
361
+ const logger = getLogger(plugins, getOnLog(inputOptions, logLevel), logLevel, watchMode);
362
+ for (const plugin of plugins) {
363
+ const name = plugin.name || "unknown";
364
+ const options = plugin.options;
365
+ if (options) {
366
+ const { handler } = normalizeHook(options);
367
+ const result = await handler.call(new MinimalPluginContextImpl(logger, logLevel, name, watchMode, "onLog"), inputOptions);
368
+ if (result) inputOptions = result;
369
+ }
370
+ }
371
+ return inputOptions;
372
+ }
373
+ static callOutputOptionsHook(rawPlugins, outputOptions, onLog, logLevel, watchMode) {
374
+ const sortedPlugins = getSortedPlugins("outputOptions", getObjectPlugins(rawPlugins));
375
+ for (const plugin of sortedPlugins) {
376
+ const name = plugin.name || "unknown";
377
+ const options = plugin.outputOptions;
378
+ if (options) {
379
+ const { handler } = normalizeHook(options);
380
+ const result = handler.call(new MinimalPluginContextImpl(onLog, logLevel, name, watchMode), outputOptions);
381
+ if (result) outputOptions = result;
382
+ }
383
+ }
384
+ return outputOptions;
385
+ }
386
+ };
387
+ function getObjectPlugins(plugins) {
388
+ return plugins.filter((plugin) => {
389
+ if (!plugin) return void 0;
390
+ if ("_parallel" in plugin) return void 0;
391
+ if (plugin instanceof BuiltinPlugin) return void 0;
392
+ return plugin;
393
+ });
394
+ }
395
+ function getSortedPlugins(hookName, plugins) {
396
+ const pre = [];
397
+ const normal = [];
398
+ const post = [];
399
+ for (const plugin of plugins) {
400
+ const hook = plugin[hookName];
401
+ if (hook) {
402
+ if (typeof hook === "object") {
403
+ if (hook.order === "pre") {
404
+ pre.push(plugin);
405
+ continue;
406
+ }
407
+ if (hook.order === "post") {
408
+ post.push(plugin);
409
+ continue;
410
+ }
411
+ }
412
+ normal.push(plugin);
413
+ }
414
+ }
415
+ return [
416
+ ...pre,
417
+ ...normal,
418
+ ...post
419
+ ];
420
+ }
421
+
422
+ //#endregion
423
+ //#region ../../node_modules/.pnpm/valibot@1.1.0_typescript@5.8.3/node_modules/valibot/dist/index.js
424
+ var store$1;
425
+ /* @__NO_SIDE_EFFECTS__ */
426
+ function getGlobalConfig(config2) {
427
+ return {
428
+ lang: config2?.lang ?? store$1?.lang,
429
+ message: config2?.message,
430
+ abortEarly: config2?.abortEarly ?? store$1?.abortEarly,
431
+ abortPipeEarly: config2?.abortPipeEarly ?? store$1?.abortPipeEarly
432
+ };
433
+ }
434
+ var store2;
435
+ /* @__NO_SIDE_EFFECTS__ */
436
+ function getGlobalMessage(lang) {
437
+ return store2?.get(lang);
438
+ }
439
+ var store3;
440
+ /* @__NO_SIDE_EFFECTS__ */
441
+ function getSchemaMessage(lang) {
442
+ return store3?.get(lang);
443
+ }
444
+ var store4;
445
+ /* @__NO_SIDE_EFFECTS__ */
446
+ function getSpecificMessage(reference, lang) {
447
+ return store4?.get(reference)?.get(lang);
448
+ }
449
+ /* @__NO_SIDE_EFFECTS__ */
450
+ function _stringify(input) {
451
+ const type = typeof input;
452
+ if (type === "string") return `"${input}"`;
453
+ if (type === "number" || type === "bigint" || type === "boolean") return `${input}`;
454
+ if (type === "object" || type === "function") return (input && Object.getPrototypeOf(input)?.constructor?.name) ?? "null";
455
+ return type;
456
+ }
457
+ function _addIssue(context, label, dataset, config2, other) {
458
+ const input = other && "input" in other ? other.input : dataset.value;
459
+ const expected = other?.expected ?? context.expects ?? null;
460
+ const received = other?.received ?? /* @__PURE__ */ _stringify(input);
461
+ const issue = {
462
+ kind: context.kind,
463
+ type: context.type,
464
+ input,
465
+ expected,
466
+ received,
467
+ message: `Invalid ${label}: ${expected ? `Expected ${expected} but r` : "R"}eceived ${received}`,
468
+ requirement: context.requirement,
469
+ path: other?.path,
470
+ issues: other?.issues,
471
+ lang: config2.lang,
472
+ abortEarly: config2.abortEarly,
473
+ abortPipeEarly: config2.abortPipeEarly
474
+ };
475
+ const isSchema = context.kind === "schema";
476
+ const message2 = other?.message ?? context.message ?? /* @__PURE__ */ getSpecificMessage(context.reference, issue.lang) ?? (isSchema ? /* @__PURE__ */ getSchemaMessage(issue.lang) : null) ?? config2.message ?? /* @__PURE__ */ getGlobalMessage(issue.lang);
477
+ if (message2 !== void 0) issue.message = typeof message2 === "function" ? message2(issue) : message2;
478
+ if (isSchema) dataset.typed = false;
479
+ if (dataset.issues) dataset.issues.push(issue);
480
+ else dataset.issues = [issue];
481
+ }
482
+ /* @__NO_SIDE_EFFECTS__ */
483
+ function _getStandardProps(context) {
484
+ return {
485
+ version: 1,
486
+ vendor: "valibot",
487
+ validate(value2) {
488
+ return context["~run"]({ value: value2 }, /* @__PURE__ */ getGlobalConfig());
489
+ }
490
+ };
491
+ }
492
+ /* @__NO_SIDE_EFFECTS__ */
493
+ function _isValidObjectKey(object2, key) {
494
+ return Object.hasOwn(object2, key) && key !== "__proto__" && key !== "prototype" && key !== "constructor";
495
+ }
496
+ /* @__NO_SIDE_EFFECTS__ */
497
+ function _joinExpects(values2, separator) {
498
+ const list = [...new Set(values2)];
499
+ if (list.length > 1) return `(${list.join(` ${separator} `)})`;
500
+ return list[0] ?? "never";
501
+ }
502
+ var ValiError = class extends Error {
503
+ /**
504
+ * Creates a Valibot error with useful information.
505
+ *
506
+ * @param issues The error issues.
507
+ */
508
+ constructor(issues) {
509
+ super(issues[0].message);
510
+ this.name = "ValiError";
511
+ this.issues = issues;
512
+ }
513
+ };
514
+ /* @__NO_SIDE_EFFECTS__ */
515
+ function args(schema) {
516
+ return {
517
+ kind: "transformation",
518
+ type: "args",
519
+ reference: args,
520
+ async: false,
521
+ schema,
522
+ "~run"(dataset, config2) {
523
+ const func = dataset.value;
524
+ dataset.value = (...args_) => {
525
+ const argsDataset = this.schema["~run"]({ value: args_ }, config2);
526
+ if (argsDataset.issues) throw new ValiError(argsDataset.issues);
527
+ return func(...argsDataset.value);
528
+ };
529
+ return dataset;
530
+ }
531
+ };
532
+ }
533
+ /* @__NO_SIDE_EFFECTS__ */
534
+ function awaitAsync() {
535
+ return {
536
+ kind: "transformation",
537
+ type: "await",
538
+ reference: awaitAsync,
539
+ async: true,
540
+ async "~run"(dataset) {
541
+ dataset.value = await dataset.value;
542
+ return dataset;
543
+ }
544
+ };
545
+ }
546
+ /* @__NO_SIDE_EFFECTS__ */
547
+ function description(description_) {
548
+ return {
549
+ kind: "metadata",
550
+ type: "description",
551
+ reference: description,
552
+ description: description_
553
+ };
554
+ }
555
+ /* @__NO_SIDE_EFFECTS__ */
556
+ function returns(schema) {
557
+ return {
558
+ kind: "transformation",
559
+ type: "returns",
560
+ reference: returns,
561
+ async: false,
562
+ schema,
563
+ "~run"(dataset, config2) {
564
+ const func = dataset.value;
565
+ dataset.value = (...args_) => {
566
+ const returnsDataset = this.schema["~run"]({ value: func(...args_) }, config2);
567
+ if (returnsDataset.issues) throw new ValiError(returnsDataset.issues);
568
+ return returnsDataset.value;
569
+ };
570
+ return dataset;
571
+ }
572
+ };
573
+ }
574
+ /* @__NO_SIDE_EFFECTS__ */
575
+ function returnsAsync(schema) {
576
+ return {
577
+ kind: "transformation",
578
+ type: "returns",
579
+ reference: returnsAsync,
580
+ async: false,
581
+ schema,
582
+ "~run"(dataset, config2) {
583
+ const func = dataset.value;
584
+ dataset.value = async (...args_) => {
585
+ const returnsDataset = await this.schema["~run"]({ value: await func(...args_) }, config2);
586
+ if (returnsDataset.issues) throw new ValiError(returnsDataset.issues);
587
+ return returnsDataset.value;
588
+ };
589
+ return dataset;
590
+ }
591
+ };
592
+ }
593
+ /* @__NO_SIDE_EFFECTS__ */
594
+ function getFallback(schema, dataset, config2) {
595
+ return typeof schema.fallback === "function" ? schema.fallback(dataset, config2) : schema.fallback;
596
+ }
597
+ /* @__NO_SIDE_EFFECTS__ */
598
+ function getDefault(schema, dataset, config2) {
599
+ return typeof schema.default === "function" ? schema.default(dataset, config2) : schema.default;
600
+ }
601
+ /* @__NO_SIDE_EFFECTS__ */
602
+ function any() {
603
+ return {
604
+ kind: "schema",
605
+ type: "any",
606
+ reference: any,
607
+ expects: "any",
608
+ async: false,
609
+ get "~standard"() {
610
+ return /* @__PURE__ */ _getStandardProps(this);
611
+ },
612
+ "~run"(dataset) {
613
+ dataset.typed = true;
614
+ return dataset;
615
+ }
616
+ };
617
+ }
618
+ /* @__NO_SIDE_EFFECTS__ */
619
+ function array(item, message2) {
620
+ return {
621
+ kind: "schema",
622
+ type: "array",
623
+ reference: array,
624
+ expects: "Array",
625
+ async: false,
626
+ item,
627
+ message: message2,
628
+ get "~standard"() {
629
+ return /* @__PURE__ */ _getStandardProps(this);
630
+ },
631
+ "~run"(dataset, config2) {
632
+ const input = dataset.value;
633
+ if (Array.isArray(input)) {
634
+ dataset.typed = true;
635
+ dataset.value = [];
636
+ for (let key = 0; key < input.length; key++) {
637
+ const value2 = input[key];
638
+ const itemDataset = this.item["~run"]({ value: value2 }, config2);
639
+ if (itemDataset.issues) {
640
+ const pathItem = {
641
+ type: "array",
642
+ origin: "value",
643
+ input,
644
+ key,
645
+ value: value2
646
+ };
647
+ for (const issue of itemDataset.issues) {
648
+ if (issue.path) issue.path.unshift(pathItem);
649
+ else issue.path = [pathItem];
650
+ dataset.issues?.push(issue);
651
+ }
652
+ if (!dataset.issues) dataset.issues = itemDataset.issues;
653
+ if (config2.abortEarly) {
654
+ dataset.typed = false;
655
+ break;
656
+ }
657
+ }
658
+ if (!itemDataset.typed) dataset.typed = false;
659
+ dataset.value.push(itemDataset.value);
660
+ }
661
+ } else _addIssue(this, "type", dataset, config2);
662
+ return dataset;
663
+ }
664
+ };
665
+ }
666
+ /* @__NO_SIDE_EFFECTS__ */
667
+ function boolean(message2) {
668
+ return {
669
+ kind: "schema",
670
+ type: "boolean",
671
+ reference: boolean,
672
+ expects: "boolean",
673
+ async: false,
674
+ message: message2,
675
+ get "~standard"() {
676
+ return /* @__PURE__ */ _getStandardProps(this);
677
+ },
678
+ "~run"(dataset, config2) {
679
+ if (typeof dataset.value === "boolean") dataset.typed = true;
680
+ else _addIssue(this, "type", dataset, config2);
681
+ return dataset;
682
+ }
683
+ };
684
+ }
685
+ /* @__NO_SIDE_EFFECTS__ */
686
+ function custom(check2, message2) {
687
+ return {
688
+ kind: "schema",
689
+ type: "custom",
690
+ reference: custom,
691
+ expects: "unknown",
692
+ async: false,
693
+ check: check2,
694
+ message: message2,
695
+ get "~standard"() {
696
+ return /* @__PURE__ */ _getStandardProps(this);
697
+ },
698
+ "~run"(dataset, config2) {
699
+ if (this.check(dataset.value)) dataset.typed = true;
700
+ else _addIssue(this, "type", dataset, config2);
701
+ return dataset;
702
+ }
703
+ };
704
+ }
705
+ /* @__NO_SIDE_EFFECTS__ */
706
+ function function_(message2) {
707
+ return {
708
+ kind: "schema",
709
+ type: "function",
710
+ reference: function_,
711
+ expects: "Function",
712
+ async: false,
713
+ message: message2,
714
+ get "~standard"() {
715
+ return /* @__PURE__ */ _getStandardProps(this);
716
+ },
717
+ "~run"(dataset, config2) {
718
+ if (typeof dataset.value === "function") dataset.typed = true;
719
+ else _addIssue(this, "type", dataset, config2);
720
+ return dataset;
721
+ }
722
+ };
723
+ }
724
+ /* @__NO_SIDE_EFFECTS__ */
725
+ function instance(class_, message2) {
726
+ return {
727
+ kind: "schema",
728
+ type: "instance",
729
+ reference: instance,
730
+ expects: class_.name,
731
+ async: false,
732
+ class: class_,
733
+ message: message2,
734
+ get "~standard"() {
735
+ return /* @__PURE__ */ _getStandardProps(this);
736
+ },
737
+ "~run"(dataset, config2) {
738
+ if (dataset.value instanceof this.class) dataset.typed = true;
739
+ else _addIssue(this, "type", dataset, config2);
740
+ return dataset;
741
+ }
742
+ };
743
+ }
744
+ /* @__NO_SIDE_EFFECTS__ */
745
+ function literal(literal_, message2) {
746
+ return {
747
+ kind: "schema",
748
+ type: "literal",
749
+ reference: literal,
750
+ expects: /* @__PURE__ */ _stringify(literal_),
751
+ async: false,
752
+ literal: literal_,
753
+ message: message2,
754
+ get "~standard"() {
755
+ return /* @__PURE__ */ _getStandardProps(this);
756
+ },
757
+ "~run"(dataset, config2) {
758
+ if (dataset.value === this.literal) dataset.typed = true;
759
+ else _addIssue(this, "type", dataset, config2);
760
+ return dataset;
761
+ }
762
+ };
763
+ }
764
+ /* @__NO_SIDE_EFFECTS__ */
765
+ function looseObject(entries2, message2) {
766
+ return {
767
+ kind: "schema",
768
+ type: "loose_object",
769
+ reference: looseObject,
770
+ expects: "Object",
771
+ async: false,
772
+ entries: entries2,
773
+ message: message2,
774
+ get "~standard"() {
775
+ return /* @__PURE__ */ _getStandardProps(this);
776
+ },
777
+ "~run"(dataset, config2) {
778
+ const input = dataset.value;
779
+ if (input && typeof input === "object") {
780
+ dataset.typed = true;
781
+ dataset.value = {};
782
+ for (const key in this.entries) {
783
+ const valueSchema = this.entries[key];
784
+ if (key in input || (valueSchema.type === "exact_optional" || valueSchema.type === "optional" || valueSchema.type === "nullish") && valueSchema.default !== void 0) {
785
+ const value2 = key in input ? input[key] : /* @__PURE__ */ getDefault(valueSchema);
786
+ const valueDataset = valueSchema["~run"]({ value: value2 }, config2);
787
+ if (valueDataset.issues) {
788
+ const pathItem = {
789
+ type: "object",
790
+ origin: "value",
791
+ input,
792
+ key,
793
+ value: value2
794
+ };
795
+ for (const issue of valueDataset.issues) {
796
+ if (issue.path) issue.path.unshift(pathItem);
797
+ else issue.path = [pathItem];
798
+ dataset.issues?.push(issue);
799
+ }
800
+ if (!dataset.issues) dataset.issues = valueDataset.issues;
801
+ if (config2.abortEarly) {
802
+ dataset.typed = false;
803
+ break;
804
+ }
805
+ }
806
+ if (!valueDataset.typed) dataset.typed = false;
807
+ dataset.value[key] = valueDataset.value;
808
+ } else if (valueSchema.fallback !== void 0) dataset.value[key] = /* @__PURE__ */ getFallback(valueSchema);
809
+ else if (valueSchema.type !== "exact_optional" && valueSchema.type !== "optional" && valueSchema.type !== "nullish") {
810
+ _addIssue(this, "key", dataset, config2, {
811
+ input: void 0,
812
+ expected: `"${key}"`,
813
+ path: [{
814
+ type: "object",
815
+ origin: "key",
816
+ input,
817
+ key,
818
+ value: input[key]
819
+ }]
820
+ });
821
+ if (config2.abortEarly) break;
822
+ }
823
+ }
824
+ if (!dataset.issues || !config2.abortEarly) {
825
+ for (const key in input) if (/* @__PURE__ */ _isValidObjectKey(input, key) && !(key in this.entries)) dataset.value[key] = input[key];
826
+ }
827
+ } else _addIssue(this, "type", dataset, config2);
828
+ return dataset;
829
+ }
830
+ };
831
+ }
832
+ /* @__NO_SIDE_EFFECTS__ */
833
+ function never(message2) {
834
+ return {
835
+ kind: "schema",
836
+ type: "never",
837
+ reference: never,
838
+ expects: "never",
839
+ async: false,
840
+ message: message2,
841
+ get "~standard"() {
842
+ return /* @__PURE__ */ _getStandardProps(this);
843
+ },
844
+ "~run"(dataset, config2) {
845
+ _addIssue(this, "type", dataset, config2);
846
+ return dataset;
847
+ }
848
+ };
849
+ }
850
+ /* @__NO_SIDE_EFFECTS__ */
851
+ function nullish(wrapped, default_) {
852
+ return {
853
+ kind: "schema",
854
+ type: "nullish",
855
+ reference: nullish,
856
+ expects: `(${wrapped.expects} | null | undefined)`,
857
+ async: false,
858
+ wrapped,
859
+ default: default_,
860
+ get "~standard"() {
861
+ return /* @__PURE__ */ _getStandardProps(this);
862
+ },
863
+ "~run"(dataset, config2) {
864
+ if (dataset.value === null || dataset.value === void 0) {
865
+ if (this.default !== void 0) dataset.value = /* @__PURE__ */ getDefault(this, dataset, config2);
866
+ if (dataset.value === null || dataset.value === void 0) {
867
+ dataset.typed = true;
868
+ return dataset;
869
+ }
870
+ }
871
+ return this.wrapped["~run"](dataset, config2);
872
+ }
873
+ };
874
+ }
875
+ /* @__NO_SIDE_EFFECTS__ */
876
+ function number(message2) {
877
+ return {
878
+ kind: "schema",
879
+ type: "number",
880
+ reference: number,
881
+ expects: "number",
882
+ async: false,
883
+ message: message2,
884
+ get "~standard"() {
885
+ return /* @__PURE__ */ _getStandardProps(this);
886
+ },
887
+ "~run"(dataset, config2) {
888
+ if (typeof dataset.value === "number" && !isNaN(dataset.value)) dataset.typed = true;
889
+ else _addIssue(this, "type", dataset, config2);
890
+ return dataset;
891
+ }
892
+ };
893
+ }
894
+ /* @__NO_SIDE_EFFECTS__ */
895
+ function object(entries2, message2) {
896
+ return {
897
+ kind: "schema",
898
+ type: "object",
899
+ reference: object,
900
+ expects: "Object",
901
+ async: false,
902
+ entries: entries2,
903
+ message: message2,
904
+ get "~standard"() {
905
+ return /* @__PURE__ */ _getStandardProps(this);
906
+ },
907
+ "~run"(dataset, config2) {
908
+ const input = dataset.value;
909
+ if (input && typeof input === "object") {
910
+ dataset.typed = true;
911
+ dataset.value = {};
912
+ for (const key in this.entries) {
913
+ const valueSchema = this.entries[key];
914
+ if (key in input || (valueSchema.type === "exact_optional" || valueSchema.type === "optional" || valueSchema.type === "nullish") && valueSchema.default !== void 0) {
915
+ const value2 = key in input ? input[key] : /* @__PURE__ */ getDefault(valueSchema);
916
+ const valueDataset = valueSchema["~run"]({ value: value2 }, config2);
917
+ if (valueDataset.issues) {
918
+ const pathItem = {
919
+ type: "object",
920
+ origin: "value",
921
+ input,
922
+ key,
923
+ value: value2
924
+ };
925
+ for (const issue of valueDataset.issues) {
926
+ if (issue.path) issue.path.unshift(pathItem);
927
+ else issue.path = [pathItem];
928
+ dataset.issues?.push(issue);
929
+ }
930
+ if (!dataset.issues) dataset.issues = valueDataset.issues;
931
+ if (config2.abortEarly) {
932
+ dataset.typed = false;
933
+ break;
934
+ }
935
+ }
936
+ if (!valueDataset.typed) dataset.typed = false;
937
+ dataset.value[key] = valueDataset.value;
938
+ } else if (valueSchema.fallback !== void 0) dataset.value[key] = /* @__PURE__ */ getFallback(valueSchema);
939
+ else if (valueSchema.type !== "exact_optional" && valueSchema.type !== "optional" && valueSchema.type !== "nullish") {
940
+ _addIssue(this, "key", dataset, config2, {
941
+ input: void 0,
942
+ expected: `"${key}"`,
943
+ path: [{
944
+ type: "object",
945
+ origin: "key",
946
+ input,
947
+ key,
948
+ value: input[key]
949
+ }]
950
+ });
951
+ if (config2.abortEarly) break;
952
+ }
953
+ }
954
+ } else _addIssue(this, "type", dataset, config2);
955
+ return dataset;
956
+ }
957
+ };
958
+ }
959
+ /* @__NO_SIDE_EFFECTS__ */
960
+ function optional(wrapped, default_) {
961
+ return {
962
+ kind: "schema",
963
+ type: "optional",
964
+ reference: optional,
965
+ expects: `(${wrapped.expects} | undefined)`,
966
+ async: false,
967
+ wrapped,
968
+ default: default_,
969
+ get "~standard"() {
970
+ return /* @__PURE__ */ _getStandardProps(this);
971
+ },
972
+ "~run"(dataset, config2) {
973
+ if (dataset.value === void 0) {
974
+ if (this.default !== void 0) dataset.value = /* @__PURE__ */ getDefault(this, dataset, config2);
975
+ if (dataset.value === void 0) {
976
+ dataset.typed = true;
977
+ return dataset;
978
+ }
979
+ }
980
+ return this.wrapped["~run"](dataset, config2);
981
+ }
982
+ };
983
+ }
984
+ /* @__NO_SIDE_EFFECTS__ */
985
+ function picklist(options, message2) {
986
+ return {
987
+ kind: "schema",
988
+ type: "picklist",
989
+ reference: picklist,
990
+ expects: /* @__PURE__ */ _joinExpects(options.map(_stringify), "|"),
991
+ async: false,
992
+ options,
993
+ message: message2,
994
+ get "~standard"() {
995
+ return /* @__PURE__ */ _getStandardProps(this);
996
+ },
997
+ "~run"(dataset, config2) {
998
+ if (this.options.includes(dataset.value)) dataset.typed = true;
999
+ else _addIssue(this, "type", dataset, config2);
1000
+ return dataset;
1001
+ }
1002
+ };
1003
+ }
1004
+ /* @__NO_SIDE_EFFECTS__ */
1005
+ function promise(message2) {
1006
+ return {
1007
+ kind: "schema",
1008
+ type: "promise",
1009
+ reference: promise,
1010
+ expects: "Promise",
1011
+ async: false,
1012
+ message: message2,
1013
+ get "~standard"() {
1014
+ return /* @__PURE__ */ _getStandardProps(this);
1015
+ },
1016
+ "~run"(dataset, config2) {
1017
+ if (dataset.value instanceof Promise) dataset.typed = true;
1018
+ else _addIssue(this, "type", dataset, config2);
1019
+ return dataset;
1020
+ }
1021
+ };
1022
+ }
1023
+ /* @__NO_SIDE_EFFECTS__ */
1024
+ function record(key, value2, message2) {
1025
+ return {
1026
+ kind: "schema",
1027
+ type: "record",
1028
+ reference: record,
1029
+ expects: "Object",
1030
+ async: false,
1031
+ key,
1032
+ value: value2,
1033
+ message: message2,
1034
+ get "~standard"() {
1035
+ return /* @__PURE__ */ _getStandardProps(this);
1036
+ },
1037
+ "~run"(dataset, config2) {
1038
+ const input = dataset.value;
1039
+ if (input && typeof input === "object") {
1040
+ dataset.typed = true;
1041
+ dataset.value = {};
1042
+ for (const entryKey in input) if (/* @__PURE__ */ _isValidObjectKey(input, entryKey)) {
1043
+ const entryValue = input[entryKey];
1044
+ const keyDataset = this.key["~run"]({ value: entryKey }, config2);
1045
+ if (keyDataset.issues) {
1046
+ const pathItem = {
1047
+ type: "object",
1048
+ origin: "key",
1049
+ input,
1050
+ key: entryKey,
1051
+ value: entryValue
1052
+ };
1053
+ for (const issue of keyDataset.issues) {
1054
+ issue.path = [pathItem];
1055
+ dataset.issues?.push(issue);
1056
+ }
1057
+ if (!dataset.issues) dataset.issues = keyDataset.issues;
1058
+ if (config2.abortEarly) {
1059
+ dataset.typed = false;
1060
+ break;
1061
+ }
1062
+ }
1063
+ const valueDataset = this.value["~run"]({ value: entryValue }, config2);
1064
+ if (valueDataset.issues) {
1065
+ const pathItem = {
1066
+ type: "object",
1067
+ origin: "value",
1068
+ input,
1069
+ key: entryKey,
1070
+ value: entryValue
1071
+ };
1072
+ for (const issue of valueDataset.issues) {
1073
+ if (issue.path) issue.path.unshift(pathItem);
1074
+ else issue.path = [pathItem];
1075
+ dataset.issues?.push(issue);
1076
+ }
1077
+ if (!dataset.issues) dataset.issues = valueDataset.issues;
1078
+ if (config2.abortEarly) {
1079
+ dataset.typed = false;
1080
+ break;
1081
+ }
1082
+ }
1083
+ if (!keyDataset.typed || !valueDataset.typed) dataset.typed = false;
1084
+ if (keyDataset.typed) dataset.value[keyDataset.value] = valueDataset.value;
1085
+ }
1086
+ } else _addIssue(this, "type", dataset, config2);
1087
+ return dataset;
1088
+ }
1089
+ };
1090
+ }
1091
+ /* @__NO_SIDE_EFFECTS__ */
1092
+ function strictObject(entries2, message2) {
1093
+ return {
1094
+ kind: "schema",
1095
+ type: "strict_object",
1096
+ reference: strictObject,
1097
+ expects: "Object",
1098
+ async: false,
1099
+ entries: entries2,
1100
+ message: message2,
1101
+ get "~standard"() {
1102
+ return /* @__PURE__ */ _getStandardProps(this);
1103
+ },
1104
+ "~run"(dataset, config2) {
1105
+ const input = dataset.value;
1106
+ if (input && typeof input === "object") {
1107
+ dataset.typed = true;
1108
+ dataset.value = {};
1109
+ for (const key in this.entries) {
1110
+ const valueSchema = this.entries[key];
1111
+ if (key in input || (valueSchema.type === "exact_optional" || valueSchema.type === "optional" || valueSchema.type === "nullish") && valueSchema.default !== void 0) {
1112
+ const value2 = key in input ? input[key] : /* @__PURE__ */ getDefault(valueSchema);
1113
+ const valueDataset = valueSchema["~run"]({ value: value2 }, config2);
1114
+ if (valueDataset.issues) {
1115
+ const pathItem = {
1116
+ type: "object",
1117
+ origin: "value",
1118
+ input,
1119
+ key,
1120
+ value: value2
1121
+ };
1122
+ for (const issue of valueDataset.issues) {
1123
+ if (issue.path) issue.path.unshift(pathItem);
1124
+ else issue.path = [pathItem];
1125
+ dataset.issues?.push(issue);
1126
+ }
1127
+ if (!dataset.issues) dataset.issues = valueDataset.issues;
1128
+ if (config2.abortEarly) {
1129
+ dataset.typed = false;
1130
+ break;
1131
+ }
1132
+ }
1133
+ if (!valueDataset.typed) dataset.typed = false;
1134
+ dataset.value[key] = valueDataset.value;
1135
+ } else if (valueSchema.fallback !== void 0) dataset.value[key] = /* @__PURE__ */ getFallback(valueSchema);
1136
+ else if (valueSchema.type !== "exact_optional" && valueSchema.type !== "optional" && valueSchema.type !== "nullish") {
1137
+ _addIssue(this, "key", dataset, config2, {
1138
+ input: void 0,
1139
+ expected: `"${key}"`,
1140
+ path: [{
1141
+ type: "object",
1142
+ origin: "key",
1143
+ input,
1144
+ key,
1145
+ value: input[key]
1146
+ }]
1147
+ });
1148
+ if (config2.abortEarly) break;
1149
+ }
1150
+ }
1151
+ if (!dataset.issues || !config2.abortEarly) {
1152
+ for (const key in input) if (!(key in this.entries)) {
1153
+ _addIssue(this, "key", dataset, config2, {
1154
+ input: key,
1155
+ expected: "never",
1156
+ path: [{
1157
+ type: "object",
1158
+ origin: "key",
1159
+ input,
1160
+ key,
1161
+ value: input[key]
1162
+ }]
1163
+ });
1164
+ break;
1165
+ }
1166
+ }
1167
+ } else _addIssue(this, "type", dataset, config2);
1168
+ return dataset;
1169
+ }
1170
+ };
1171
+ }
1172
+ /* @__NO_SIDE_EFFECTS__ */
1173
+ function string(message2) {
1174
+ return {
1175
+ kind: "schema",
1176
+ type: "string",
1177
+ reference: string,
1178
+ expects: "string",
1179
+ async: false,
1180
+ message: message2,
1181
+ get "~standard"() {
1182
+ return /* @__PURE__ */ _getStandardProps(this);
1183
+ },
1184
+ "~run"(dataset, config2) {
1185
+ if (typeof dataset.value === "string") dataset.typed = true;
1186
+ else _addIssue(this, "type", dataset, config2);
1187
+ return dataset;
1188
+ }
1189
+ };
1190
+ }
1191
+ /* @__NO_SIDE_EFFECTS__ */
1192
+ function tuple(items, message2) {
1193
+ return {
1194
+ kind: "schema",
1195
+ type: "tuple",
1196
+ reference: tuple,
1197
+ expects: "Array",
1198
+ async: false,
1199
+ items,
1200
+ message: message2,
1201
+ get "~standard"() {
1202
+ return /* @__PURE__ */ _getStandardProps(this);
1203
+ },
1204
+ "~run"(dataset, config2) {
1205
+ const input = dataset.value;
1206
+ if (Array.isArray(input)) {
1207
+ dataset.typed = true;
1208
+ dataset.value = [];
1209
+ for (let key = 0; key < this.items.length; key++) {
1210
+ const value2 = input[key];
1211
+ const itemDataset = this.items[key]["~run"]({ value: value2 }, config2);
1212
+ if (itemDataset.issues) {
1213
+ const pathItem = {
1214
+ type: "array",
1215
+ origin: "value",
1216
+ input,
1217
+ key,
1218
+ value: value2
1219
+ };
1220
+ for (const issue of itemDataset.issues) {
1221
+ if (issue.path) issue.path.unshift(pathItem);
1222
+ else issue.path = [pathItem];
1223
+ dataset.issues?.push(issue);
1224
+ }
1225
+ if (!dataset.issues) dataset.issues = itemDataset.issues;
1226
+ if (config2.abortEarly) {
1227
+ dataset.typed = false;
1228
+ break;
1229
+ }
1230
+ }
1231
+ if (!itemDataset.typed) dataset.typed = false;
1232
+ dataset.value.push(itemDataset.value);
1233
+ }
1234
+ } else _addIssue(this, "type", dataset, config2);
1235
+ return dataset;
1236
+ }
1237
+ };
1238
+ }
1239
+ /* @__NO_SIDE_EFFECTS__ */
1240
+ function _subIssues(datasets) {
1241
+ let issues;
1242
+ if (datasets) for (const dataset of datasets) if (issues) issues.push(...dataset.issues);
1243
+ else issues = dataset.issues;
1244
+ return issues;
1245
+ }
1246
+ /* @__NO_SIDE_EFFECTS__ */
1247
+ function union(options, message2) {
1248
+ return {
1249
+ kind: "schema",
1250
+ type: "union",
1251
+ reference: union,
1252
+ expects: /* @__PURE__ */ _joinExpects(options.map((option) => option.expects), "|"),
1253
+ async: false,
1254
+ options,
1255
+ message: message2,
1256
+ get "~standard"() {
1257
+ return /* @__PURE__ */ _getStandardProps(this);
1258
+ },
1259
+ "~run"(dataset, config2) {
1260
+ let validDataset;
1261
+ let typedDatasets;
1262
+ let untypedDatasets;
1263
+ for (const schema of this.options) {
1264
+ const optionDataset = schema["~run"]({ value: dataset.value }, config2);
1265
+ if (optionDataset.typed) if (optionDataset.issues) if (typedDatasets) typedDatasets.push(optionDataset);
1266
+ else typedDatasets = [optionDataset];
1267
+ else {
1268
+ validDataset = optionDataset;
1269
+ break;
1270
+ }
1271
+ else if (untypedDatasets) untypedDatasets.push(optionDataset);
1272
+ else untypedDatasets = [optionDataset];
1273
+ }
1274
+ if (validDataset) return validDataset;
1275
+ if (typedDatasets) {
1276
+ if (typedDatasets.length === 1) return typedDatasets[0];
1277
+ _addIssue(this, "type", dataset, config2, { issues: /* @__PURE__ */ _subIssues(typedDatasets) });
1278
+ dataset.typed = true;
1279
+ } else if (untypedDatasets?.length === 1) return untypedDatasets[0];
1280
+ else _addIssue(this, "type", dataset, config2, { issues: /* @__PURE__ */ _subIssues(untypedDatasets) });
1281
+ return dataset;
1282
+ }
1283
+ };
1284
+ }
1285
+ /* @__NO_SIDE_EFFECTS__ */
1286
+ function unionAsync(options, message2) {
1287
+ return {
1288
+ kind: "schema",
1289
+ type: "union",
1290
+ reference: unionAsync,
1291
+ expects: /* @__PURE__ */ _joinExpects(options.map((option) => option.expects), "|"),
1292
+ async: true,
1293
+ options,
1294
+ message: message2,
1295
+ get "~standard"() {
1296
+ return /* @__PURE__ */ _getStandardProps(this);
1297
+ },
1298
+ async "~run"(dataset, config2) {
1299
+ let validDataset;
1300
+ let typedDatasets;
1301
+ let untypedDatasets;
1302
+ for (const schema of this.options) {
1303
+ const optionDataset = await schema["~run"]({ value: dataset.value }, config2);
1304
+ if (optionDataset.typed) if (optionDataset.issues) if (typedDatasets) typedDatasets.push(optionDataset);
1305
+ else typedDatasets = [optionDataset];
1306
+ else {
1307
+ validDataset = optionDataset;
1308
+ break;
1309
+ }
1310
+ else if (untypedDatasets) untypedDatasets.push(optionDataset);
1311
+ else untypedDatasets = [optionDataset];
1312
+ }
1313
+ if (validDataset) return validDataset;
1314
+ if (typedDatasets) {
1315
+ if (typedDatasets.length === 1) return typedDatasets[0];
1316
+ _addIssue(this, "type", dataset, config2, { issues: /* @__PURE__ */ _subIssues(typedDatasets) });
1317
+ dataset.typed = true;
1318
+ } else if (untypedDatasets?.length === 1) return untypedDatasets[0];
1319
+ else _addIssue(this, "type", dataset, config2, { issues: /* @__PURE__ */ _subIssues(untypedDatasets) });
1320
+ return dataset;
1321
+ }
1322
+ };
1323
+ }
1324
+ /* @__NO_SIDE_EFFECTS__ */
1325
+ function keyof(schema, message2) {
1326
+ return /* @__PURE__ */ picklist(Object.keys(schema.entries), message2);
1327
+ }
1328
+ /* @__NO_SIDE_EFFECTS__ */
1329
+ function omit(schema, keys) {
1330
+ const entries2 = { ...schema.entries };
1331
+ for (const key of keys) delete entries2[key];
1332
+ return {
1333
+ ...schema,
1334
+ entries: entries2,
1335
+ get "~standard"() {
1336
+ return /* @__PURE__ */ _getStandardProps(this);
1337
+ }
1338
+ };
1339
+ }
1340
+ /* @__NO_SIDE_EFFECTS__ */
1341
+ function pipe(...pipe2) {
1342
+ return {
1343
+ ...pipe2[0],
1344
+ pipe: pipe2,
1345
+ get "~standard"() {
1346
+ return /* @__PURE__ */ _getStandardProps(this);
1347
+ },
1348
+ "~run"(dataset, config2) {
1349
+ for (const item of pipe2) if (item.kind !== "metadata") {
1350
+ if (dataset.issues && (item.kind === "schema" || item.kind === "transformation")) {
1351
+ dataset.typed = false;
1352
+ break;
1353
+ }
1354
+ if (!dataset.issues || !config2.abortEarly && !config2.abortPipeEarly) dataset = item["~run"](dataset, config2);
1355
+ }
1356
+ return dataset;
1357
+ }
1358
+ };
1359
+ }
1360
+ /* @__NO_SIDE_EFFECTS__ */
1361
+ function pipeAsync(...pipe2) {
1362
+ return {
1363
+ ...pipe2[0],
1364
+ pipe: pipe2,
1365
+ async: true,
1366
+ get "~standard"() {
1367
+ return /* @__PURE__ */ _getStandardProps(this);
1368
+ },
1369
+ async "~run"(dataset, config2) {
1370
+ for (const item of pipe2) if (item.kind !== "metadata") {
1371
+ if (dataset.issues && (item.kind === "schema" || item.kind === "transformation")) {
1372
+ dataset.typed = false;
1373
+ break;
1374
+ }
1375
+ if (!dataset.issues || !config2.abortEarly && !config2.abortPipeEarly) dataset = await item["~run"](dataset, config2);
1376
+ }
1377
+ return dataset;
1378
+ }
1379
+ };
1380
+ }
1381
+ /* @__NO_SIDE_EFFECTS__ */
1382
+ function safeParse(schema, input, config2) {
1383
+ const dataset = schema["~run"]({ value: input }, /* @__PURE__ */ getGlobalConfig(config2));
1384
+ return {
1385
+ typed: dataset.typed,
1386
+ success: !dataset.issues,
1387
+ output: dataset.value,
1388
+ issues: dataset.issues
1389
+ };
1390
+ }
1391
+
1392
+ //#endregion
1393
+ //#region ../../node_modules/.pnpm/@valibot+to-json-schema@1.2.0_valibot@1.1.0_typescript@5.8.3_/node_modules/@valibot/to-json-schema/dist/index.js
1394
+ var store;
1395
+ function getGlobalDefs() {
1396
+ return store;
1397
+ }
1398
+ function addError(errors, message) {
1399
+ if (errors) {
1400
+ errors.push(message);
1401
+ return errors;
1402
+ }
1403
+ return [message];
1404
+ }
1405
+ function handleError(message, config) {
1406
+ switch (config?.errorMode) {
1407
+ case "ignore": break;
1408
+ case "warn": {
1409
+ console.warn(message);
1410
+ break;
1411
+ }
1412
+ default: throw new Error(message);
1413
+ }
1414
+ }
1415
+ function convertAction(jsonSchema, valibotAction, config) {
1416
+ let errors;
1417
+ switch (valibotAction.type) {
1418
+ case "base64": {
1419
+ jsonSchema.contentEncoding = "base64";
1420
+ break;
1421
+ }
1422
+ case "bic":
1423
+ case "cuid2":
1424
+ case "decimal":
1425
+ case "digits":
1426
+ case "emoji":
1427
+ case "hexadecimal":
1428
+ case "hex_color":
1429
+ case "nanoid":
1430
+ case "octal":
1431
+ case "ulid": {
1432
+ jsonSchema.pattern = valibotAction.requirement.source;
1433
+ break;
1434
+ }
1435
+ case "description": {
1436
+ jsonSchema.description = valibotAction.description;
1437
+ break;
1438
+ }
1439
+ case "email": {
1440
+ jsonSchema.format = "email";
1441
+ break;
1442
+ }
1443
+ case "empty": {
1444
+ if (jsonSchema.type === "array") jsonSchema.maxItems = 0;
1445
+ else {
1446
+ if (jsonSchema.type !== "string") errors = addError(errors, `The "${valibotAction.type}" action is not supported on type "${jsonSchema.type}".`);
1447
+ jsonSchema.maxLength = 0;
1448
+ }
1449
+ break;
1450
+ }
1451
+ case "entries": {
1452
+ jsonSchema.minProperties = valibotAction.requirement;
1453
+ jsonSchema.maxProperties = valibotAction.requirement;
1454
+ break;
1455
+ }
1456
+ case "integer": {
1457
+ jsonSchema.type = "integer";
1458
+ break;
1459
+ }
1460
+ case "ipv4": {
1461
+ jsonSchema.format = "ipv4";
1462
+ break;
1463
+ }
1464
+ case "ipv6": {
1465
+ jsonSchema.format = "ipv6";
1466
+ break;
1467
+ }
1468
+ case "iso_date": {
1469
+ jsonSchema.format = "date";
1470
+ break;
1471
+ }
1472
+ case "iso_date_time":
1473
+ case "iso_timestamp": {
1474
+ jsonSchema.format = "date-time";
1475
+ break;
1476
+ }
1477
+ case "iso_time": {
1478
+ jsonSchema.format = "time";
1479
+ break;
1480
+ }
1481
+ case "length": {
1482
+ if (jsonSchema.type === "array") {
1483
+ jsonSchema.minItems = valibotAction.requirement;
1484
+ jsonSchema.maxItems = valibotAction.requirement;
1485
+ } else {
1486
+ if (jsonSchema.type !== "string") errors = addError(errors, `The "${valibotAction.type}" action is not supported on type "${jsonSchema.type}".`);
1487
+ jsonSchema.minLength = valibotAction.requirement;
1488
+ jsonSchema.maxLength = valibotAction.requirement;
1489
+ }
1490
+ break;
1491
+ }
1492
+ case "max_entries": {
1493
+ jsonSchema.maxProperties = valibotAction.requirement;
1494
+ break;
1495
+ }
1496
+ case "max_length": {
1497
+ if (jsonSchema.type === "array") jsonSchema.maxItems = valibotAction.requirement;
1498
+ else {
1499
+ if (jsonSchema.type !== "string") errors = addError(errors, `The "${valibotAction.type}" action is not supported on type "${jsonSchema.type}".`);
1500
+ jsonSchema.maxLength = valibotAction.requirement;
1501
+ }
1502
+ break;
1503
+ }
1504
+ case "max_value": {
1505
+ if (jsonSchema.type !== "number") errors = addError(errors, `The "max_value" action is not supported on type "${jsonSchema.type}".`);
1506
+ jsonSchema.maximum = valibotAction.requirement;
1507
+ break;
1508
+ }
1509
+ case "metadata": {
1510
+ if (typeof valibotAction.metadata.title === "string") jsonSchema.title = valibotAction.metadata.title;
1511
+ if (typeof valibotAction.metadata.description === "string") jsonSchema.description = valibotAction.metadata.description;
1512
+ if (Array.isArray(valibotAction.metadata.examples)) jsonSchema.examples = valibotAction.metadata.examples;
1513
+ break;
1514
+ }
1515
+ case "min_entries": {
1516
+ jsonSchema.minProperties = valibotAction.requirement;
1517
+ break;
1518
+ }
1519
+ case "min_length": {
1520
+ if (jsonSchema.type === "array") jsonSchema.minItems = valibotAction.requirement;
1521
+ else {
1522
+ if (jsonSchema.type !== "string") errors = addError(errors, `The "${valibotAction.type}" action is not supported on type "${jsonSchema.type}".`);
1523
+ jsonSchema.minLength = valibotAction.requirement;
1524
+ }
1525
+ break;
1526
+ }
1527
+ case "min_value": {
1528
+ if (jsonSchema.type !== "number") errors = addError(errors, `The "min_value" action is not supported on type "${jsonSchema.type}".`);
1529
+ jsonSchema.minimum = valibotAction.requirement;
1530
+ break;
1531
+ }
1532
+ case "multiple_of": {
1533
+ jsonSchema.multipleOf = valibotAction.requirement;
1534
+ break;
1535
+ }
1536
+ case "non_empty": {
1537
+ if (jsonSchema.type === "array") jsonSchema.minItems = 1;
1538
+ else {
1539
+ if (jsonSchema.type !== "string") errors = addError(errors, `The "${valibotAction.type}" action is not supported on type "${jsonSchema.type}".`);
1540
+ jsonSchema.minLength = 1;
1541
+ }
1542
+ break;
1543
+ }
1544
+ case "regex": {
1545
+ if (valibotAction.requirement.flags) errors = addError(errors, "RegExp flags are not supported by JSON Schema.");
1546
+ jsonSchema.pattern = valibotAction.requirement.source;
1547
+ break;
1548
+ }
1549
+ case "title": {
1550
+ jsonSchema.title = valibotAction.title;
1551
+ break;
1552
+ }
1553
+ case "url": {
1554
+ jsonSchema.format = "uri";
1555
+ break;
1556
+ }
1557
+ case "uuid": {
1558
+ jsonSchema.format = "uuid";
1559
+ break;
1560
+ }
1561
+ case "value": {
1562
+ jsonSchema.const = valibotAction.requirement;
1563
+ break;
1564
+ }
1565
+ default: errors = addError(errors, `The "${valibotAction.type}" action cannot be converted to JSON Schema.`);
1566
+ }
1567
+ if (config?.overrideAction) {
1568
+ const actionOverride = config.overrideAction({
1569
+ valibotAction,
1570
+ jsonSchema,
1571
+ errors
1572
+ });
1573
+ if (actionOverride) return { ...actionOverride };
1574
+ }
1575
+ if (errors) for (const message of errors) handleError(message, config);
1576
+ return jsonSchema;
1577
+ }
1578
+ var refCount = 0;
1579
+ function convertSchema(jsonSchema, valibotSchema, config, context, skipRef = false) {
1580
+ if (!skipRef) {
1581
+ const referenceId = context.referenceMap.get(valibotSchema);
1582
+ if (referenceId) {
1583
+ jsonSchema.$ref = `#/$defs/${referenceId}`;
1584
+ if (config?.overrideRef) {
1585
+ const refOverride = config.overrideRef({
1586
+ ...context,
1587
+ referenceId,
1588
+ valibotSchema,
1589
+ jsonSchema
1590
+ });
1591
+ if (refOverride) jsonSchema.$ref = refOverride;
1592
+ }
1593
+ return jsonSchema;
1594
+ }
1595
+ }
1596
+ if ("pipe" in valibotSchema) {
1597
+ for (let index = 0; index < valibotSchema.pipe.length; index++) {
1598
+ const valibotPipeItem = valibotSchema.pipe[index];
1599
+ if (valibotPipeItem.kind === "schema") {
1600
+ if (index > 0) handleError("A \"pipe\" with multiple schemas cannot be converted to JSON Schema.", config);
1601
+ jsonSchema = convertSchema(jsonSchema, valibotPipeItem, config, context, true);
1602
+ } else jsonSchema = convertAction(jsonSchema, valibotPipeItem, config);
1603
+ }
1604
+ return jsonSchema;
1605
+ }
1606
+ let errors;
1607
+ switch (valibotSchema.type) {
1608
+ case "boolean": {
1609
+ jsonSchema.type = "boolean";
1610
+ break;
1611
+ }
1612
+ case "null": {
1613
+ jsonSchema.type = "null";
1614
+ break;
1615
+ }
1616
+ case "number": {
1617
+ jsonSchema.type = "number";
1618
+ break;
1619
+ }
1620
+ case "string": {
1621
+ jsonSchema.type = "string";
1622
+ break;
1623
+ }
1624
+ case "array": {
1625
+ jsonSchema.type = "array";
1626
+ jsonSchema.items = convertSchema({}, valibotSchema.item, config, context);
1627
+ break;
1628
+ }
1629
+ case "tuple":
1630
+ case "tuple_with_rest":
1631
+ case "loose_tuple":
1632
+ case "strict_tuple": {
1633
+ jsonSchema.type = "array";
1634
+ jsonSchema.items = [];
1635
+ jsonSchema.minItems = valibotSchema.items.length;
1636
+ for (const item of valibotSchema.items) jsonSchema.items.push(convertSchema({}, item, config, context));
1637
+ if (valibotSchema.type === "tuple_with_rest") jsonSchema.additionalItems = convertSchema({}, valibotSchema.rest, config, context);
1638
+ else if (valibotSchema.type === "strict_tuple") jsonSchema.additionalItems = false;
1639
+ break;
1640
+ }
1641
+ case "object":
1642
+ case "object_with_rest":
1643
+ case "loose_object":
1644
+ case "strict_object": {
1645
+ jsonSchema.type = "object";
1646
+ jsonSchema.properties = {};
1647
+ jsonSchema.required = [];
1648
+ for (const key in valibotSchema.entries) {
1649
+ const entry = valibotSchema.entries[key];
1650
+ jsonSchema.properties[key] = convertSchema({}, entry, config, context);
1651
+ if (entry.type !== "nullish" && entry.type !== "optional") jsonSchema.required.push(key);
1652
+ }
1653
+ if (valibotSchema.type === "object_with_rest") jsonSchema.additionalProperties = convertSchema({}, valibotSchema.rest, config, context);
1654
+ else if (valibotSchema.type === "strict_object") jsonSchema.additionalProperties = false;
1655
+ break;
1656
+ }
1657
+ case "record": {
1658
+ if ("pipe" in valibotSchema.key) errors = addError(errors, "The \"record\" schema with a schema for the key that contains a \"pipe\" cannot be converted to JSON Schema.");
1659
+ if (valibotSchema.key.type !== "string") errors = addError(errors, `The "record" schema with the "${valibotSchema.key.type}" schema for the key cannot be converted to JSON Schema.`);
1660
+ jsonSchema.type = "object";
1661
+ jsonSchema.additionalProperties = convertSchema({}, valibotSchema.value, config, context);
1662
+ break;
1663
+ }
1664
+ case "any":
1665
+ case "unknown": break;
1666
+ case "nullable":
1667
+ case "nullish": {
1668
+ jsonSchema.anyOf = [convertSchema({}, valibotSchema.wrapped, config, context), { type: "null" }];
1669
+ if (valibotSchema.default !== void 0) jsonSchema.default = getDefault(valibotSchema);
1670
+ break;
1671
+ }
1672
+ case "exact_optional":
1673
+ case "optional":
1674
+ case "undefinedable": {
1675
+ jsonSchema = convertSchema(jsonSchema, valibotSchema.wrapped, config, context);
1676
+ if (valibotSchema.default !== void 0) jsonSchema.default = getDefault(valibotSchema);
1677
+ break;
1678
+ }
1679
+ case "literal": {
1680
+ if (typeof valibotSchema.literal !== "boolean" && typeof valibotSchema.literal !== "number" && typeof valibotSchema.literal !== "string") errors = addError(errors, "The value of the \"literal\" schema is not JSON compatible.");
1681
+ jsonSchema.const = valibotSchema.literal;
1682
+ break;
1683
+ }
1684
+ case "enum": {
1685
+ jsonSchema.enum = valibotSchema.options;
1686
+ break;
1687
+ }
1688
+ case "picklist": {
1689
+ if (valibotSchema.options.some((option) => typeof option !== "number" && typeof option !== "string")) errors = addError(errors, "An option of the \"picklist\" schema is not JSON compatible.");
1690
+ jsonSchema.enum = valibotSchema.options;
1691
+ break;
1692
+ }
1693
+ case "union":
1694
+ case "variant": {
1695
+ jsonSchema.anyOf = valibotSchema.options.map((option) => convertSchema({}, option, config, context));
1696
+ break;
1697
+ }
1698
+ case "intersect": {
1699
+ jsonSchema.allOf = valibotSchema.options.map((option) => convertSchema({}, option, config, context));
1700
+ break;
1701
+ }
1702
+ case "lazy": {
1703
+ let wrappedValibotSchema = context.getterMap.get(valibotSchema.getter);
1704
+ if (!wrappedValibotSchema) {
1705
+ wrappedValibotSchema = valibotSchema.getter(void 0);
1706
+ context.getterMap.set(valibotSchema.getter, wrappedValibotSchema);
1707
+ }
1708
+ let referenceId = context.referenceMap.get(wrappedValibotSchema);
1709
+ if (!referenceId) {
1710
+ referenceId = `${refCount++}`;
1711
+ context.referenceMap.set(wrappedValibotSchema, referenceId);
1712
+ context.definitions[referenceId] = convertSchema({}, wrappedValibotSchema, config, context, true);
1713
+ }
1714
+ jsonSchema.$ref = `#/$defs/${referenceId}`;
1715
+ if (config?.overrideRef) {
1716
+ const refOverride = config.overrideRef({
1717
+ ...context,
1718
+ referenceId,
1719
+ valibotSchema,
1720
+ jsonSchema
1721
+ });
1722
+ if (refOverride) jsonSchema.$ref = refOverride;
1723
+ }
1724
+ break;
1725
+ }
1726
+ default: errors = addError(errors, `The "${valibotSchema.type}" schema cannot be converted to JSON Schema.`);
1727
+ }
1728
+ if (config?.overrideSchema) {
1729
+ const schemaOverride = config.overrideSchema({
1730
+ ...context,
1731
+ referenceId: context.referenceMap.get(valibotSchema),
1732
+ valibotSchema,
1733
+ jsonSchema,
1734
+ errors
1735
+ });
1736
+ if (schemaOverride) return { ...schemaOverride };
1737
+ }
1738
+ if (errors) for (const message of errors) handleError(message, config);
1739
+ return jsonSchema;
1740
+ }
1741
+ function toJsonSchema(schema, config) {
1742
+ const context = {
1743
+ definitions: {},
1744
+ referenceMap: /* @__PURE__ */ new Map(),
1745
+ getterMap: /* @__PURE__ */ new Map()
1746
+ };
1747
+ const definitions = config?.definitions ?? getGlobalDefs();
1748
+ if (definitions) {
1749
+ for (const key in definitions) context.referenceMap.set(definitions[key], key);
1750
+ for (const key in definitions) context.definitions[key] = convertSchema({}, definitions[key], config, context, true);
1751
+ }
1752
+ const jsonSchema = convertSchema({ $schema: "http://json-schema.org/draft-07/schema#" }, schema, config, context);
1753
+ if (context.referenceMap.size) jsonSchema.$defs = context.definitions;
1754
+ return jsonSchema;
1755
+ }
1756
+
1757
+ //#endregion
1758
+ //#region src/utils/validator.ts
1759
+ const StringOrRegExpSchema = union([string(), instance(RegExp)]);
1760
+ const LogLevelSchema = union([
1761
+ literal("debug"),
1762
+ literal("info"),
1763
+ literal("warn")
1764
+ ]);
1765
+ const LogLevelOptionSchema = union([LogLevelSchema, literal("silent")]);
1766
+ const LogLevelWithErrorSchema = union([LogLevelSchema, literal("error")]);
1767
+ const RollupLogSchema = any();
1768
+ const RollupLogWithStringSchema = union([RollupLogSchema, string()]);
1769
+ const InputOptionSchema = union([
1770
+ string(),
1771
+ array(string()),
1772
+ record(string(), string())
1773
+ ]);
1774
+ const ExternalSchema = union([
1775
+ StringOrRegExpSchema,
1776
+ array(StringOrRegExpSchema),
1777
+ pipe(function_(), args(tuple([
1778
+ string(),
1779
+ optional(string()),
1780
+ boolean()
1781
+ ])), returns(nullish(boolean())))
1782
+ ]);
1783
+ const ModuleTypesSchema = record(string(), union([
1784
+ literal("asset"),
1785
+ literal("base64"),
1786
+ literal("binary"),
1787
+ literal("css"),
1788
+ literal("dataurl"),
1789
+ literal("empty"),
1790
+ literal("js"),
1791
+ literal("json"),
1792
+ literal("jsx"),
1793
+ literal("text"),
1794
+ literal("ts"),
1795
+ literal("tsx")
1796
+ ]));
1797
+ const JsxOptionsSchema = strictObject({
1798
+ runtime: pipe(optional(union([literal("classic"), literal("automatic")])), description("Which runtime to use")),
1799
+ development: pipe(optional(boolean()), description("Development specific information")),
1800
+ throwIfNamespace: pipe(optional(string()), description("Toggles whether to throw an error when a tag name uses an XML namespace")),
1801
+ importSource: pipe(optional(string()), description("Import the factory of element and fragment if mode is classic")),
1802
+ pragma: pipe(optional(string()), description("Jsx element transformation")),
1803
+ pragmaFlag: pipe(optional(string()), description("Jsx fragment transformation")),
1804
+ refresh: pipe(optional(boolean()), description("Enable react fast refresh"))
1805
+ });
1806
+ const HelperModeSchema = union([literal("Runtime"), literal("External")]);
1807
+ const DecoratorOptionSchema = object({
1808
+ legacy: optional(boolean()),
1809
+ emitDecoratorMetadata: optional(boolean())
1810
+ });
1811
+ const HelpersSchema = object({ mode: optional(HelperModeSchema) });
1812
+ const RewriteImportExtensionsSchema = union([
1813
+ literal("rewrite"),
1814
+ literal("remove"),
1815
+ boolean()
1816
+ ]);
1817
+ const TypescriptSchema = object({
1818
+ jsxPragma: optional(string()),
1819
+ jsxPragmaFrag: optional(string()),
1820
+ onlyRemoveTypeImports: optional(boolean()),
1821
+ allowNamespaces: optional(boolean()),
1822
+ allowDeclareFields: optional(boolean()),
1823
+ declaration: optional(object({
1824
+ stripInternal: optional(boolean()),
1825
+ sourcemap: optional(boolean())
1826
+ })),
1827
+ rewriteImportExtensions: optional(RewriteImportExtensionsSchema)
1828
+ });
1829
+ const AssumptionsSchema = object({
1830
+ ignoreFunctionLength: optional(boolean()),
1831
+ noDocumentAll: optional(boolean()),
1832
+ objectRestNoSymbols: optional(boolean()),
1833
+ pureGetters: optional(boolean()),
1834
+ setPublicClassFields: optional(boolean())
1835
+ });
1836
+ const TransformOptionsSchema = object({
1837
+ assumptions: optional(AssumptionsSchema),
1838
+ typescript: optional(TypescriptSchema),
1839
+ helpers: optional(HelpersSchema),
1840
+ decorators: optional(DecoratorOptionSchema),
1841
+ jsx: optional(JsxOptionsSchema),
1842
+ target: pipe(optional(union([string(), array(string())])), description("The JavaScript target environment"))
1843
+ });
1844
+ const WatchOptionsSchema = strictObject({
1845
+ chokidar: optional(never(`The "watch.chokidar" option is deprecated, please use "watch.notify" instead of it`)),
1846
+ exclude: optional(union([StringOrRegExpSchema, array(StringOrRegExpSchema)])),
1847
+ include: optional(union([StringOrRegExpSchema, array(StringOrRegExpSchema)])),
1848
+ notify: pipe(optional(strictObject({
1849
+ compareContents: optional(boolean()),
1850
+ pollInterval: optional(number())
1851
+ })), description("Notify options")),
1852
+ skipWrite: pipe(optional(boolean()), description("Skip the bundle.write() step")),
1853
+ buildDelay: pipe(optional(number()), description("Throttle watch rebuilds"))
1854
+ });
1855
+ const ChecksOptionsSchema = strictObject({
1856
+ circularDependency: pipe(optional(boolean()), description("Whether to emit warning when detecting circular dependency")),
1857
+ eval: pipe(optional(boolean()), description("Whether to emit warning when detecting eval")),
1858
+ missingGlobalName: pipe(optional(boolean()), description("Whether to emit warning when detecting missing global name")),
1859
+ missingNameOptionForIifeExport: pipe(optional(boolean()), description("Whether to emit warning when detecting missing name option for iife export")),
1860
+ mixedExport: pipe(optional(boolean()), description("Whether to emit warning when detecting mixed export")),
1861
+ unresolvedEntry: pipe(optional(boolean()), description("Whether to emit warning when detecting unresolved entry")),
1862
+ unresolvedImport: pipe(optional(boolean()), description("Whether to emit warning when detecting unresolved import")),
1863
+ filenameConflict: pipe(optional(boolean()), description("Whether to emit warning when detecting filename conflict")),
1864
+ commonJsVariableInEsm: pipe(optional(boolean()), description("Whether to emit warning when detecting common js variable in esm")),
1865
+ importIsUndefined: pipe(optional(boolean()), description("Whether to emit warning when detecting import is undefined")),
1866
+ configurationFieldConflict: pipe(optional(boolean()), description("Whether to emit warning when detecting configuration field conflict"))
1867
+ });
1868
+ const MinifyOptionsSchema = strictObject({
1869
+ mangle: optional(boolean()),
1870
+ compress: optional(boolean()),
1871
+ removeWhitespace: optional(boolean())
1872
+ });
1873
+ const ResolveOptionsSchema = strictObject({
1874
+ alias: optional(record(string(), union([string(), array(string())]))),
1875
+ aliasFields: optional(array(array(string()))),
1876
+ conditionNames: optional(array(string())),
1877
+ extensionAlias: optional(record(string(), array(string()))),
1878
+ exportsFields: optional(array(array(string()))),
1879
+ extensions: optional(array(string())),
1880
+ mainFields: optional(array(string())),
1881
+ mainFiles: optional(array(string())),
1882
+ modules: optional(array(string())),
1883
+ symlinks: optional(boolean()),
1884
+ tsconfigFilename: optional(string())
1885
+ });
1886
+ const TreeshakingOptionsSchema = union([boolean(), looseObject({
1887
+ annotations: optional(boolean()),
1888
+ manualPureFunctions: optional(array(string())),
1889
+ unknownGlobalSideEffects: optional(boolean())
1890
+ })]);
1891
+ const OnLogSchema = pipe(function_(), args(tuple([
1892
+ LogLevelSchema,
1893
+ RollupLogSchema,
1894
+ pipe(function_(), args(tuple([LogLevelWithErrorSchema, RollupLogWithStringSchema])))
1895
+ ])));
1896
+ const OnwarnSchema = pipe(function_(), args(tuple([RollupLogSchema, pipe(function_(), args(tuple([union([RollupLogWithStringSchema, pipe(function_(), returns(RollupLogWithStringSchema))])])))])));
1897
+ const HmrSchema = union([boolean(), strictObject({
1898
+ port: optional(number()),
1899
+ host: optional(string()),
1900
+ implement: optional(string())
1901
+ })]);
1902
+ const InputOptionsSchema = strictObject({
1903
+ input: optional(InputOptionSchema),
1904
+ plugins: optional(custom(() => true)),
1905
+ external: optional(ExternalSchema),
1906
+ resolve: optional(ResolveOptionsSchema),
1907
+ cwd: pipe(optional(string()), description("Current working directory")),
1908
+ platform: pipe(optional(union([
1909
+ literal("browser"),
1910
+ literal("neutral"),
1911
+ literal("node")
1912
+ ])), description(`Platform for which the code should be generated (node, ${colors.underline("browser")}, neutral)`)),
1913
+ shimMissingExports: pipe(optional(boolean()), description("Create shim variables for missing exports")),
1914
+ treeshake: optional(TreeshakingOptionsSchema),
1915
+ logLevel: pipe(optional(LogLevelOptionSchema), description(`Log level (${colors.dim("silent")}, ${colors.underline(colors.gray("info"))}, debug, ${colors.yellow("warn")})`)),
1916
+ onLog: optional(OnLogSchema),
1917
+ onwarn: optional(OnwarnSchema),
1918
+ moduleTypes: pipe(optional(ModuleTypesSchema), description("Module types for customized extensions")),
1919
+ experimental: optional(strictObject({
1920
+ disableLiveBindings: optional(boolean()),
1921
+ enableComposingJsPlugins: optional(boolean()),
1922
+ resolveNewUrlToAsset: optional(boolean()),
1923
+ strictExecutionOrder: optional(boolean()),
1924
+ hmr: optional(HmrSchema),
1925
+ attachDebugInfo: optional(boolean())
1926
+ })),
1927
+ define: pipe(optional(record(string(), string())), description("Define global variables")),
1928
+ inject: optional(record(string(), union([string(), tuple([string(), string()])]))),
1929
+ profilerNames: optional(boolean()),
1930
+ jsx: pipe(optional(union([
1931
+ literal(false),
1932
+ literal("react"),
1933
+ literal("react-jsx"),
1934
+ literal("preserve")
1935
+ ])), description("Jsx options preset")),
1936
+ transform: optional(TransformOptionsSchema),
1937
+ watch: optional(union([WatchOptionsSchema, literal(false)])),
1938
+ dropLabels: pipe(optional(array(string())), description("Remove labeled statements with these label names")),
1939
+ checks: optional(ChecksOptionsSchema),
1940
+ keepNames: pipe(optional(boolean()), description("Keep function/class name")),
1941
+ debug: pipe(optional(object({ sessionId: pipe(optional(string()), description("Used to name the build.")) })), description("Enable debug mode. Emit debug information to disk. This might slow down the build process significantly."))
1942
+ });
1943
+ const InputCliOverrideSchema = strictObject({
1944
+ input: pipe(optional(array(string())), description("Entry file")),
1945
+ external: pipe(optional(array(string())), description("Comma-separated list of module ids to exclude from the bundle `<module-id>,...`")),
1946
+ inject: pipe(optional(record(string(), string())), description("Inject import statements on demand")),
1947
+ treeshake: pipe(optional(boolean()), description("enable treeshaking"))
1948
+ });
1949
+ const InputCliOptionsSchema = omit(strictObject({
1950
+ ...InputOptionsSchema.entries,
1951
+ ...InputCliOverrideSchema.entries
1952
+ }), [
1953
+ "plugins",
1954
+ "onwarn",
1955
+ "onLog",
1956
+ "resolve",
1957
+ "experimental",
1958
+ "profilerNames",
1959
+ "watch"
1960
+ ]);
1961
+ const ModuleFormatSchema = union([
1962
+ literal("es"),
1963
+ literal("cjs"),
1964
+ literal("esm"),
1965
+ literal("module"),
1966
+ literal("commonjs"),
1967
+ literal("iife"),
1968
+ literal("umd")
1969
+ ]);
1970
+ const AddonFunctionSchema = pipe(function_(), args(tuple([custom(() => true)])), returnsAsync(unionAsync([string(), pipeAsync(promise(), awaitAsync(), string())])));
1971
+ const ChunkFileNamesSchema = union([string(), pipe(function_(), args(tuple([custom(() => true)])), returns(string()))]);
1972
+ const AssetFileNamesSchema = union([string(), pipe(function_(), args(tuple([custom(() => true)])), returns(string()))]);
1973
+ const SanitizeFileNameSchema = union([boolean(), pipe(function_(), args(tuple([string()])), returns(string()))]);
1974
+ const GlobalsFunctionSchema = pipe(function_(), args(tuple([string()])), returns(string()));
1975
+ const AdvancedChunksSchema = strictObject({
1976
+ minSize: optional(number()),
1977
+ maxSize: optional(number()),
1978
+ minModuleSize: optional(number()),
1979
+ maxModuleSize: optional(number()),
1980
+ minShareCount: optional(number()),
1981
+ groups: optional(array(strictObject({
1982
+ name: string(),
1983
+ test: optional(union([string(), instance(RegExp)])),
1984
+ priority: optional(number()),
1985
+ minSize: optional(number()),
1986
+ minShareCount: optional(number()),
1987
+ maxSize: optional(number()),
1988
+ minModuleSize: optional(number()),
1989
+ maxModuleSize: optional(number())
1990
+ })))
1991
+ });
1992
+ const OutputOptionsSchema = strictObject({
1993
+ dir: pipe(optional(string()), description("Output directory, defaults to `dist` if `file` is not set")),
1994
+ file: pipe(optional(string()), description("Single output file")),
1995
+ exports: pipe(optional(union([
1996
+ literal("auto"),
1997
+ literal("named"),
1998
+ literal("default"),
1999
+ literal("none")
2000
+ ])), description(`Specify a export mode (${colors.underline("auto")}, named, default, none)`)),
2001
+ hashCharacters: pipe(optional(union([
2002
+ literal("base64"),
2003
+ literal("base36"),
2004
+ literal("hex")
2005
+ ])), description("Use the specified character set for file hashes")),
2006
+ format: pipe(optional(ModuleFormatSchema), description(`Output format of the generated bundle (supports ${colors.underline("esm")}, cjs, and iife)`)),
2007
+ sourcemap: pipe(optional(union([
2008
+ boolean(),
2009
+ literal("inline"),
2010
+ literal("hidden")
2011
+ ])), description(`Generate sourcemap (\`-s inline\` for inline, or ${colors.bold("pass the `-s` on the last argument if you want to generate `.map` file")})`)),
2012
+ sourcemapDebugIds: pipe(optional(boolean()), description("Inject sourcemap debug IDs")),
2013
+ sourcemapIgnoreList: optional(union([boolean(), custom(() => true)])),
2014
+ sourcemapPathTransform: optional(custom(() => true)),
2015
+ banner: optional(union([string(), AddonFunctionSchema])),
2016
+ footer: optional(union([string(), AddonFunctionSchema])),
2017
+ intro: optional(union([string(), AddonFunctionSchema])),
2018
+ outro: optional(union([string(), AddonFunctionSchema])),
2019
+ extend: pipe(optional(boolean()), description("Extend global variable defined by name in IIFE / UMD formats")),
2020
+ esModule: optional(union([boolean(), literal("if-default-prop")])),
2021
+ assetFileNames: optional(AssetFileNamesSchema),
2022
+ entryFileNames: optional(ChunkFileNamesSchema),
2023
+ chunkFileNames: optional(ChunkFileNamesSchema),
2024
+ cssEntryFileNames: optional(ChunkFileNamesSchema),
2025
+ cssChunkFileNames: optional(ChunkFileNamesSchema),
2026
+ sanitizeFileName: optional(SanitizeFileNameSchema),
2027
+ minify: pipe(optional(union([
2028
+ boolean(),
2029
+ string("dce-only"),
2030
+ MinifyOptionsSchema
2031
+ ])), description("Minify the bundled file")),
2032
+ name: pipe(optional(string()), description("Name for UMD / IIFE format outputs")),
2033
+ globals: pipe(optional(union([record(string(), string()), GlobalsFunctionSchema])), description("Global variable of UMD / IIFE dependencies (syntax: `key=value`)")),
2034
+ externalLiveBindings: pipe(optional(boolean()), description("external live bindings")),
2035
+ inlineDynamicImports: pipe(optional(boolean()), description("Inline dynamic imports")),
2036
+ manualChunks: optional(never("manualChunks is not supported. Please use advancedChunks instead")),
2037
+ advancedChunks: optional(AdvancedChunksSchema),
2038
+ legalComments: pipe(optional(union([literal("none"), literal("inline")])), description("Control comments in the output")),
2039
+ plugins: optional(custom(() => true)),
2040
+ polyfillRequire: pipe(optional(boolean()), description("Disable require polyfill injection")),
2041
+ hoistTransitiveImports: optional(custom((input) => {
2042
+ if (input) return false;
2043
+ return true;
2044
+ }, () => `The 'true' value is not supported`)),
2045
+ preserveModules: pipe(optional(boolean()), description("Preserve module structure")),
2046
+ preserveModulesRoot: pipe(optional(string()), description("Put preserved modules under this path at root level")),
2047
+ virtualDirname: optional(string())
2048
+ });
2049
+ const getAddonDescription = (placement, wrapper) => {
2050
+ return `Code to insert the ${colors.bold(placement)} of the bundled file (${colors.bold(wrapper)} the wrapper function)`;
2051
+ };
2052
+ const OutputCliOverrideSchema = strictObject({
2053
+ assetFileNames: pipe(optional(string()), description("Name pattern for asset files")),
2054
+ entryFileNames: pipe(optional(string()), description("Name pattern for emitted entry chunks")),
2055
+ chunkFileNames: pipe(optional(string()), description("Name pattern for emitted secondary chunks")),
2056
+ cssEntryFileNames: pipe(optional(string()), description("Name pattern for emitted css entry chunks")),
2057
+ cssChunkFileNames: pipe(optional(string()), description("Name pattern for emitted css secondary chunks")),
2058
+ sanitizeFileName: pipe(optional(boolean()), description("Sanitize file name")),
2059
+ banner: pipe(optional(string()), description(getAddonDescription("top", "outside"))),
2060
+ footer: pipe(optional(string()), description(getAddonDescription("bottom", "outside"))),
2061
+ intro: pipe(optional(string()), description(getAddonDescription("top", "inside"))),
2062
+ outro: pipe(optional(string()), description(getAddonDescription("bottom", "inside"))),
2063
+ esModule: pipe(optional(boolean()), description("Always generate `__esModule` marks in non-ESM formats, defaults to `if-default-prop` (use `--no-esModule` to always disable)")),
2064
+ globals: pipe(optional(record(string(), string())), description("Global variable of UMD / IIFE dependencies (syntax: `key=value`)")),
2065
+ advancedChunks: pipe(optional(strictObject({
2066
+ minSize: pipe(optional(number()), description("Minimum size of the chunk")),
2067
+ minShareCount: pipe(optional(number()), description("Minimum share count of the chunk"))
2068
+ })), description("Global variable of UMD / IIFE dependencies (syntax: `key=value`)")),
2069
+ minify: pipe(optional(boolean()), description("Minify the bundled file"))
2070
+ });
2071
+ const OutputCliOptionsSchema = omit(strictObject({
2072
+ ...OutputOptionsSchema.entries,
2073
+ ...OutputCliOverrideSchema.entries
2074
+ }), [
2075
+ "sourcemapIgnoreList",
2076
+ "sourcemapPathTransform",
2077
+ "plugins",
2078
+ "hoistTransitiveImports"
2079
+ ]);
2080
+ const CliOptionsSchema = strictObject({
2081
+ config: pipe(optional(union([string(), boolean()])), description("Path to the config file (default: `rolldown.config.js`)")),
2082
+ help: pipe(optional(boolean()), description("Show help")),
2083
+ version: pipe(optional(boolean()), description("Show version number")),
2084
+ watch: pipe(optional(boolean()), description("Watch files in bundle and rebuild on changes")),
2085
+ ...InputCliOptionsSchema.entries,
2086
+ ...OutputCliOptionsSchema.entries
2087
+ });
2088
+ function validateCliOptions(options) {
2089
+ let parsed = safeParse(CliOptionsSchema, options);
2090
+ return [parsed.output, parsed.issues?.map((issue) => {
2091
+ const option = issue.path?.map((pathItem) => pathItem.key).join(" ");
2092
+ return `Invalid value for option ${option}: ${issue.message}`;
2093
+ })];
2094
+ }
2095
+ const inputHelperMsgRecord = { output: { ignored: true } };
2096
+ const outputHelperMsgRecord = {};
2097
+ function validateOption(key, options) {
2098
+ if (globalThis.process?.env?.ROLLUP_TEST) return;
2099
+ let parsed = safeParse(key === "input" ? InputOptionsSchema : OutputOptionsSchema, options);
2100
+ if (!parsed.success) {
2101
+ const errors = parsed.issues.map((issue) => {
2102
+ const issuePaths = issue.path.map((path$1) => path$1.key);
2103
+ let issueMsg = issue.message;
2104
+ if (issue.type === "union") {
2105
+ const subIssue = issue.issues?.find((i$1) => !(i$1.type !== issue.received && i$1.input === issue.input));
2106
+ if (subIssue) {
2107
+ if (subIssue.path) issuePaths.push(subIssue.path.map((path$1) => path$1.key));
2108
+ issueMsg = subIssue.message;
2109
+ }
2110
+ }
2111
+ const stringPath = issuePaths.join(".");
2112
+ const helper = key === "input" ? inputHelperMsgRecord[stringPath] : outputHelperMsgRecord[stringPath];
2113
+ if (helper && helper.ignored) return "";
2114
+ return `- For the "${stringPath}". ${issueMsg}. ${helper ? helper.msg : ""}`;
2115
+ }).filter(Boolean);
2116
+ if (errors.length) console.warn(`Warning validate ${key} options.\n` + errors.join("\n"));
2117
+ }
2118
+ }
2119
+ function getInputCliKeys() {
2120
+ return keyof(InputCliOptionsSchema).options;
2121
+ }
2122
+ function getOutputCliKeys() {
2123
+ return keyof(OutputCliOptionsSchema).options;
2124
+ }
2125
+ function getJsonSchema() {
2126
+ return toJsonSchema(CliOptionsSchema, { errorMode: "ignore" });
2127
+ }
2128
+
2129
+ //#endregion
2130
+ //#region src/constants/plugin-context.ts
2131
+ /**
2132
+ * If Composed plugins call `this.resolve` with `skipSelf: true`, the composed plugins will be skipped as a whole.
2133
+ * To prevent that, we use this symbol to store the actual caller of `this.resolve` with `skipSelf: true`. And we
2134
+ * will modify the skipSelf option to `false` and use this symbol to skip the caller itself in the composed plugins
2135
+ * internally.
2136
+ */
2137
+ const SYMBOL_FOR_RESOLVE_CALLER_THAT_SKIP_SELF = Symbol("plugin-context-resolve-caller");
2138
+
2139
+ //#endregion
2140
+ //#region src/options/normalized-input-options.ts
2141
+ var NormalizedInputOptionsImpl = class {
2142
+ inner;
2143
+ constructor(inner, onLog) {
2144
+ this.onLog = onLog;
2145
+ this.inner = inner;
2146
+ }
2147
+ get shimMissingExports() {
2148
+ return this.inner.shimMissingExports;
2149
+ }
2150
+ get input() {
2151
+ return this.inner.input;
2152
+ }
2153
+ get cwd() {
2154
+ return this.inner.cwd ?? void 0;
2155
+ }
2156
+ get platform() {
2157
+ return this.inner.platform;
2158
+ }
2159
+ };
2160
+
2161
+ //#endregion
2162
+ //#region src/types/sourcemap.ts
2163
+ function bindingifySourcemap(map) {
2164
+ if (map == null) return;
2165
+ return { inner: typeof map === "string" ? map : {
2166
+ file: map.file ?? void 0,
2167
+ mappings: map.mappings,
2168
+ sourceRoot: "sourceRoot" in map ? map.sourceRoot ?? void 0 : void 0,
2169
+ sources: map.sources?.map((s) => s ?? void 0),
2170
+ sourcesContent: map.sourcesContent?.map((s) => s ?? void 0),
2171
+ names: map.names,
2172
+ x_google_ignoreList: map.x_google_ignoreList,
2173
+ debugId: "debugId" in map ? map.debugId : void 0
2174
+ } };
2175
+ }
2176
+
2177
+ //#endregion
2178
+ //#region src/utils/error.ts
2179
+ function normalizeErrors(rawErrors) {
2180
+ const errors = rawErrors.map((e) => e instanceof Error ? e : Object.assign(new Error(), {
2181
+ kind: e.kind,
2182
+ message: e.message,
2183
+ stack: void 0
2184
+ }));
2185
+ let summary = `Build failed with ${errors.length} error${errors.length < 2 ? "" : "s"}:\n`;
2186
+ for (let i$1 = 0; i$1 < errors.length; i$1++) {
2187
+ summary += "\n";
2188
+ if (i$1 >= 5) {
2189
+ summary += "...";
2190
+ break;
2191
+ }
2192
+ summary += getErrorMessage(errors[i$1]);
2193
+ }
2194
+ const wrapper = new Error(summary);
2195
+ Object.defineProperty(wrapper, "errors", {
2196
+ configurable: true,
2197
+ enumerable: true,
2198
+ get: () => errors,
2199
+ set: (value) => Object.defineProperty(wrapper, "errors", {
2200
+ configurable: true,
2201
+ enumerable: true,
2202
+ value
2203
+ })
2204
+ });
2205
+ return wrapper;
2206
+ }
2207
+ function getErrorMessage(e) {
2208
+ if (Object.hasOwn(e, "kind")) return e.message;
2209
+ let s = "";
2210
+ if (e.plugin) s += `[plugin ${e.plugin}]`;
2211
+ const id$1 = e.id ?? e.loc?.file;
2212
+ if (id$1) {
2213
+ s += " " + id$1;
2214
+ if (e.loc) s += `:${e.loc.line}:${e.loc.column}`;
2215
+ }
2216
+ if (s) s += "\n";
2217
+ const message = `${e.name ?? "Error"}: ${e.message}`;
2218
+ s += message;
2219
+ if (e.frame) s = joinNewLine(s, e.frame);
2220
+ if (e.stack) s = joinNewLine(s, e.stack.replace(message, ""));
2221
+ return s;
2222
+ }
2223
+ function joinNewLine(s1, s2) {
2224
+ return s1.replace(/\n+$/, "") + "\n" + s2.replace(/^\n+/, "");
2225
+ }
2226
+
2227
+ //#endregion
2228
+ //#region src/utils/transform-module-info.ts
2229
+ function transformModuleInfo(info, option) {
2230
+ return {
2231
+ get ast() {
2232
+ return unsupported("ModuleInfo#ast");
2233
+ },
2234
+ get code() {
2235
+ return info.code;
2236
+ },
2237
+ id: info.id,
2238
+ importers: info.importers,
2239
+ dynamicImporters: info.dynamicImporters,
2240
+ importedIds: info.importedIds,
2241
+ dynamicallyImportedIds: info.dynamicallyImportedIds,
2242
+ exports: info.exports,
2243
+ isEntry: info.isEntry,
2244
+ ...option
2245
+ };
2246
+ }
2247
+
2248
+ //#endregion
2249
+ //#region src/utils/transform-side-effects.ts
2250
+ function bindingifySideEffects(sideEffects) {
2251
+ switch (sideEffects) {
2252
+ case true: return BindingHookSideEffects.True;
2253
+ case false: return BindingHookSideEffects.False;
2254
+ case "no-treeshake": return BindingHookSideEffects.NoTreeshake;
2255
+ case null:
2256
+ case void 0: return void 0;
2257
+ default: throw new Error(`Unexpected side effects: ${sideEffects}`);
2258
+ }
2259
+ }
2260
+
2261
+ //#endregion
2262
+ //#region src/utils/transform-sourcemap.ts
2263
+ function isEmptySourcemapFiled(array$1) {
2264
+ if (!array$1) return true;
2265
+ if (array$1.length === 0 || !array$1[0]) return true;
2266
+ return false;
2267
+ }
2268
+ function normalizeTransformHookSourcemap(id$1, originalCode, rawMap) {
2269
+ if (!rawMap) return;
2270
+ let map = typeof rawMap === "object" ? rawMap : JSON.parse(rawMap);
2271
+ if (isEmptySourcemapFiled(map.sourcesContent)) map.sourcesContent = [originalCode];
2272
+ if (isEmptySourcemapFiled(map.sources) || map.sources && map.sources.length === 1 && map.sources[0] !== id$1) map.sources = [id$1];
2273
+ return map;
2274
+ }
2275
+
2276
+ //#endregion
2277
+ //#region ../../node_modules/.pnpm/remeda@2.21.6/node_modules/remeda/dist/chunk-D6FCK2GA.js
2278
+ function u$1(o, n, a) {
2279
+ let t$1 = (r) => o(r, ...n);
2280
+ return a === void 0 ? t$1 : Object.assign(t$1, {
2281
+ lazy: a,
2282
+ lazyArgs: n
2283
+ });
2284
+ }
2285
+
2286
+ //#endregion
2287
+ //#region ../../node_modules/.pnpm/remeda@2.21.6/node_modules/remeda/dist/chunk-WIMGWYZL.js
2288
+ function u(r, n, o) {
2289
+ let a = r.length - n.length;
2290
+ if (a === 0) return r(...n);
2291
+ if (a === 1) return u$1(r, n, o);
2292
+ throw new Error("Wrong number of arguments");
2293
+ }
2294
+
2295
+ //#endregion
2296
+ //#region ../../node_modules/.pnpm/remeda@2.21.6/node_modules/remeda/dist/chunk-3IFJP4R5.js
2297
+ function d(...r) {
2298
+ return u(i, r);
2299
+ }
2300
+ var i = (r, t$1) => {
2301
+ let a = [[], []];
2302
+ for (let [o, e] of r.entries()) t$1(e, o, r) ? a[0].push(e) : a[1].push(e);
2303
+ return a;
2304
+ };
2305
+
2306
+ //#endregion
2307
+ //#region ../../node_modules/.pnpm/remeda@2.21.6/node_modules/remeda/dist/chunk-5NQBDF4H.js
2308
+ function t(...n) {
2309
+ return u(Object.keys, n);
2310
+ }
2311
+
2312
+ //#endregion
2313
+ //#region src/plugin/bindingify-hook-filter.ts
2314
+ function generalHookFilterMatcherToFilterExprs(matcher, stringKind) {
2315
+ if (typeof matcher === "string" || matcher instanceof RegExp) return [include(generateAtomMatcher(stringKind, matcher))];
2316
+ if (Array.isArray(matcher)) return matcher.map((m) => include(generateAtomMatcher(stringKind, m)));
2317
+ let ret = [];
2318
+ if (matcher.exclude) ret.push(...arraify(matcher.exclude).map((m) => exclude(generateAtomMatcher(stringKind, m))));
2319
+ if (matcher.include) ret.push(...arraify(matcher.include).map((m) => include(generateAtomMatcher(stringKind, m))));
2320
+ return ret;
2321
+ }
2322
+ function generateAtomMatcher(kind, matcher) {
2323
+ return kind === "code" ? code(matcher) : id(matcher);
2324
+ }
2325
+ function transformFilterMatcherToFilterExprs(filterOption) {
2326
+ if (!filterOption) return void 0;
2327
+ if (Array.isArray(filterOption)) return filterOption;
2328
+ const { id: id$1, code: code$1, moduleType: moduleType$1 } = filterOption;
2329
+ let ret = [];
2330
+ let idIncludes = [];
2331
+ let idExcludes = [];
2332
+ let codeIncludes = [];
2333
+ let codeExcludes = [];
2334
+ if (id$1) [idIncludes, idExcludes] = d(generalHookFilterMatcherToFilterExprs(id$1, "id") ?? [], (m) => m.kind === "include");
2335
+ if (code$1) [codeIncludes, codeExcludes] = d(generalHookFilterMatcherToFilterExprs(code$1, "code") ?? [], (m) => m.kind === "include");
2336
+ ret.push(...idExcludes);
2337
+ ret.push(...codeExcludes);
2338
+ let andExprList = [];
2339
+ if (moduleType$1) {
2340
+ let moduleTypes = Array.isArray(moduleType$1) ? moduleType$1 : moduleType$1.include ?? [];
2341
+ andExprList.push(or(...moduleTypes.map((m) => moduleType(m))));
2342
+ }
2343
+ if (idIncludes.length) andExprList.push(or(...idIncludes.map((item) => item.expr)));
2344
+ if (codeIncludes.length) andExprList.push(or(...codeIncludes.map((item) => item.expr)));
2345
+ if (andExprList.length) ret.push(include(and(...andExprList)));
2346
+ return ret;
2347
+ }
2348
+ function bindingifyGeneralHookFilter(stringKind, pattern) {
2349
+ let filterExprs = generalHookFilterMatcherToFilterExprs(pattern, stringKind);
2350
+ let ret = [];
2351
+ if (filterExprs) ret = filterExprs.map(bindingifyFilterExpr);
2352
+ return ret.length > 0 ? { value: ret } : void 0;
2353
+ }
2354
+ function bindingifyFilterExpr(expr) {
2355
+ let list = [];
2356
+ bindingifyFilterExprImpl(expr, list);
2357
+ return list;
2358
+ }
2359
+ function bindingifyFilterExprImpl(expr, list) {
2360
+ switch (expr.kind) {
2361
+ case "and": {
2362
+ let args$1 = expr.args;
2363
+ for (let i$1 = args$1.length - 1; i$1 >= 0; i$1--) bindingifyFilterExprImpl(args$1[i$1], list);
2364
+ list.push({
2365
+ kind: "And",
2366
+ payload: args$1.length
2367
+ });
2368
+ break;
2369
+ }
2370
+ case "or": {
2371
+ let args$1 = expr.args;
2372
+ for (let i$1 = args$1.length - 1; i$1 >= 0; i$1--) bindingifyFilterExprImpl(args$1[i$1], list);
2373
+ list.push({
2374
+ kind: "Or",
2375
+ payload: args$1.length
2376
+ });
2377
+ break;
2378
+ }
2379
+ case "not": {
2380
+ bindingifyFilterExprImpl(expr.expr, list);
2381
+ list.push({ kind: "Not" });
2382
+ break;
2383
+ }
2384
+ case "id": {
2385
+ list.push({
2386
+ kind: "Id",
2387
+ payload: expr.pattern
2388
+ });
2389
+ if (expr.params.cleanUrl) list.push({ kind: "CleanUrl" });
2390
+ break;
2391
+ }
2392
+ case "moduleType": {
2393
+ list.push({
2394
+ kind: "ModuleType",
2395
+ payload: expr.pattern
2396
+ });
2397
+ break;
2398
+ }
2399
+ case "code": {
2400
+ list.push({
2401
+ kind: "Code",
2402
+ payload: expr.pattern
2403
+ });
2404
+ break;
2405
+ }
2406
+ case "include": {
2407
+ bindingifyFilterExprImpl(expr.expr, list);
2408
+ list.push({ kind: "Include" });
2409
+ break;
2410
+ }
2411
+ case "exclude": {
2412
+ bindingifyFilterExprImpl(expr.expr, list);
2413
+ list.push({ kind: "Exclude" });
2414
+ break;
2415
+ }
2416
+ case "query": {
2417
+ list.push({
2418
+ kind: "QueryKey",
2419
+ payload: expr.key
2420
+ });
2421
+ list.push({
2422
+ kind: "QueryValue",
2423
+ payload: expr.pattern
2424
+ });
2425
+ break;
2426
+ }
2427
+ default: throw new Error(`Unknown filter expression: ${expr}`);
2428
+ }
2429
+ }
2430
+ function bindingifyResolveIdFilter(filterOption) {
2431
+ if (!filterOption) return void 0;
2432
+ if (Array.isArray(filterOption)) return { value: filterOption.map(bindingifyFilterExpr) };
2433
+ return filterOption.id ? bindingifyGeneralHookFilter("id", filterOption.id) : void 0;
2434
+ }
2435
+ function bindingifyLoadFilter(filterOption) {
2436
+ if (!filterOption) return void 0;
2437
+ if (Array.isArray(filterOption)) return { value: filterOption.map(bindingifyFilterExpr) };
2438
+ return filterOption.id ? bindingifyGeneralHookFilter("id", filterOption.id) : void 0;
2439
+ }
2440
+ function bindingifyTransformFilter(filterOption) {
2441
+ if (!filterOption) return void 0;
2442
+ let filterExprs = transformFilterMatcherToFilterExprs(filterOption);
2443
+ let ret = [];
2444
+ if (filterExprs) ret = filterExprs.map(bindingifyFilterExpr);
2445
+ return { value: ret.length > 0 ? ret : void 0 };
2446
+ }
2447
+ function bindingifyRenderChunkFilter(filterOption) {
2448
+ if (!filterOption) return void 0;
2449
+ if (Array.isArray(filterOption)) return { value: filterOption.map(bindingifyFilterExpr) };
2450
+ return filterOption.code ? bindingifyGeneralHookFilter("code", filterOption.code) : void 0;
2451
+ }
2452
+
2453
+ //#endregion
2454
+ //#region src/plugin/bindingify-plugin-hook-meta.ts
2455
+ function bindingifyPluginHookMeta(options) {
2456
+ return { order: bindingPluginOrder(options.order) };
2457
+ }
2458
+ function bindingPluginOrder(order) {
2459
+ switch (order) {
2460
+ case "post": return BindingPluginOrder.Post;
2461
+ case "pre": return BindingPluginOrder.Pre;
2462
+ case null:
2463
+ case void 0: return void 0;
2464
+ default: throw new Error(`Unknown plugin order: ${order}`);
2465
+ }
2466
+ }
2467
+
2468
+ //#endregion
2469
+ //#region src/utils/asset-source.ts
2470
+ function transformAssetSource(bindingAssetSource$1) {
2471
+ return bindingAssetSource$1.inner;
2472
+ }
2473
+ function bindingAssetSource(source) {
2474
+ return { inner: source };
2475
+ }
2476
+
2477
+ //#endregion
2478
+ //#region src/plugin/plugin-context.ts
2479
+ var PluginContextImpl = class extends MinimalPluginContextImpl {
2480
+ getModuleInfo;
2481
+ constructor(outputOptions, context, plugin, data, onLog, logLevel, watchMode, currentLoadingModule) {
2482
+ super(onLog, logLevel, plugin.name, watchMode);
2483
+ this.outputOptions = outputOptions;
2484
+ this.context = context;
2485
+ this.data = data;
2486
+ this.onLog = onLog;
2487
+ this.currentLoadingModule = currentLoadingModule;
2488
+ this.getModuleInfo = (id$1) => this.data.getModuleInfo(id$1, context);
2489
+ }
2490
+ async load(options) {
2491
+ const id$1 = options.id;
2492
+ if (id$1 === this.currentLoadingModule) this.onLog(LOG_LEVEL_WARN, logCycleLoading(this.pluginName, this.currentLoadingModule));
2493
+ const moduleInfo = this.data.getModuleInfo(id$1, this.context);
2494
+ if (moduleInfo && moduleInfo.code !== null) return moduleInfo;
2495
+ const rawOptions = {
2496
+ meta: options.meta || {},
2497
+ moduleSideEffects: options.moduleSideEffects || null,
2498
+ invalidate: false
2499
+ };
2500
+ this.data.updateModuleOption(id$1, rawOptions);
2501
+ async function createLoadModulePromise(context, data) {
2502
+ const loadPromise = data.loadModulePromiseMap.get(id$1);
2503
+ if (loadPromise) return loadPromise;
2504
+ const promise$1 = new Promise((resolve, _) => {
2505
+ data.loadModulePromiseResolveFnMap.set(id$1, resolve);
2506
+ });
2507
+ data.loadModulePromiseMap.set(id$1, promise$1);
2508
+ try {
2509
+ await context.load(id$1, bindingifySideEffects(options.moduleSideEffects));
2510
+ } catch (e) {
2511
+ data.loadModulePromiseMap.delete(id$1);
2512
+ data.loadModulePromiseResolveFnMap.delete(id$1);
2513
+ throw e;
2514
+ }
2515
+ return promise$1;
2516
+ }
2517
+ await createLoadModulePromise(this.context, this.data);
2518
+ return this.data.getModuleInfo(id$1, this.context);
2519
+ }
2520
+ async resolve(source, importer, options) {
2521
+ let receipt = void 0;
2522
+ if (options != null) receipt = this.data.saveResolveOptions(options);
2523
+ const res = await this.context.resolve(source, importer, {
2524
+ custom: receipt,
2525
+ skipSelf: options?.skipSelf
2526
+ });
2527
+ if (receipt != null) this.data.removeSavedResolveOptions(receipt);
2528
+ if (res == null) return null;
2529
+ const info = this.data.getModuleOption(res.id) || {};
2530
+ return {
2531
+ ...res,
2532
+ external: res.external === "relative" ? unreachable(`The PluginContext resolve result external couldn't be 'relative'`) : res.external,
2533
+ ...info
2534
+ };
2535
+ }
2536
+ emitFile = (file) => {
2537
+ if (file.type === "prebuilt-chunk") return unimplemented("PluginContext.emitFile with type prebuilt-chunk");
2538
+ if (file.type === "chunk") return this.context.emitChunk(file);
2539
+ const fnSanitizedFileName = file.fileName || typeof this.outputOptions.sanitizeFileName !== "function" ? void 0 : this.outputOptions.sanitizeFileName(file.name || "asset");
2540
+ const filename = file.fileName ? void 0 : this.getAssetFileNames(file);
2541
+ return this.context.emitFile({
2542
+ ...file,
2543
+ originalFileName: file.originalFileName || void 0,
2544
+ source: bindingAssetSource(file.source)
2545
+ }, filename, fnSanitizedFileName);
2546
+ };
2547
+ getAssetFileNames(file) {
2548
+ if (typeof this.outputOptions.assetFileNames === "function") return this.outputOptions.assetFileNames({
2549
+ names: file.name ? [file.name] : [],
2550
+ originalFileNames: file.originalFileName ? [file.originalFileName] : [],
2551
+ source: file.source,
2552
+ type: "asset"
2553
+ });
2554
+ }
2555
+ getFileName(referenceId) {
2556
+ return this.context.getFileName(referenceId);
2557
+ }
2558
+ getModuleIds() {
2559
+ return this.data.getModuleIds(this.context);
2560
+ }
2561
+ addWatchFile(id$1) {
2562
+ this.context.addWatchFile(id$1);
2563
+ }
2564
+ parse(input, options) {
2565
+ return parseAst(input, options);
2566
+ }
2567
+ };
2568
+
2569
+ //#endregion
2570
+ //#region src/plugin/transform-plugin-context.ts
2571
+ var TransformPluginContextImpl = class extends PluginContextImpl {
2572
+ constructor(outputOptions, context, plugin, data, inner, moduleId, moduleSource, onLog, LogLevelOption, watchMode) {
2573
+ super(outputOptions, context, plugin, data, onLog, LogLevelOption, watchMode, moduleId);
2574
+ this.inner = inner;
2575
+ this.moduleId = moduleId;
2576
+ this.moduleSource = moduleSource;
2577
+ const getLogHandler$1 = (handler) => (log, pos) => {
2578
+ log = normalizeLog(log);
2579
+ if (pos) augmentCodeLocation(log, pos, moduleSource, moduleId);
2580
+ log.id = moduleId;
2581
+ log.hook = "transform";
2582
+ handler(log);
2583
+ };
2584
+ this.debug = getLogHandler$1(this.debug);
2585
+ this.warn = getLogHandler$1(this.warn);
2586
+ this.info = getLogHandler$1(this.info);
2587
+ }
2588
+ error(e, pos) {
2589
+ if (typeof e === "string") e = { message: e };
2590
+ if (pos) augmentCodeLocation(e, pos, this.moduleSource, this.moduleId);
2591
+ e.id = this.moduleId;
2592
+ e.hook = "transform";
2593
+ return error(logPluginError(normalizeLog(e), this.pluginName));
2594
+ }
2595
+ getCombinedSourcemap() {
2596
+ return JSON.parse(this.inner.getCombinedSourcemap());
2597
+ }
2598
+ };
2599
+
2600
+ //#endregion
2601
+ //#region src/plugin/bindingify-build-hooks.ts
2602
+ function bindingifyBuildStart(args$1) {
2603
+ const hook = args$1.plugin.buildStart;
2604
+ if (!hook) return {};
2605
+ const { handler, meta } = normalizeHook(hook);
2606
+ return {
2607
+ plugin: async (ctx, opts) => {
2608
+ await handler.call(new PluginContextImpl(args$1.outputOptions, ctx, args$1.plugin, args$1.pluginContextData, args$1.onLog, args$1.logLevel, args$1.watchMode), new NormalizedInputOptionsImpl(opts, args$1.onLog));
2609
+ },
2610
+ meta: bindingifyPluginHookMeta(meta)
2611
+ };
2612
+ }
2613
+ function bindingifyBuildEnd(args$1) {
2614
+ const hook = args$1.plugin.buildEnd;
2615
+ if (!hook) return {};
2616
+ const { handler, meta } = normalizeHook(hook);
2617
+ return {
2618
+ plugin: async (ctx, err) => {
2619
+ await handler.call(new PluginContextImpl(args$1.outputOptions, ctx, args$1.plugin, args$1.pluginContextData, args$1.onLog, args$1.logLevel, args$1.watchMode), err ? normalizeErrors(err) : void 0);
2620
+ },
2621
+ meta: bindingifyPluginHookMeta(meta)
2622
+ };
2623
+ }
2624
+ function bindingifyResolveId(args$1) {
2625
+ const hook = args$1.plugin.resolveId;
2626
+ if (!hook) return {};
2627
+ const { handler, meta, options } = normalizeHook(hook);
2628
+ return {
2629
+ plugin: async (ctx, specifier, importer, extraOptions) => {
2630
+ const contextResolveOptions = extraOptions.custom != null ? args$1.pluginContextData.getSavedResolveOptions(extraOptions.custom) : void 0;
2631
+ const newExtraOptions = {
2632
+ ...extraOptions,
2633
+ custom: contextResolveOptions?.custom,
2634
+ [SYMBOL_FOR_RESOLVE_CALLER_THAT_SKIP_SELF]: contextResolveOptions?.[SYMBOL_FOR_RESOLVE_CALLER_THAT_SKIP_SELF]
2635
+ };
2636
+ const ret = await handler.call(new PluginContextImpl(args$1.outputOptions, ctx, args$1.plugin, args$1.pluginContextData, args$1.onLog, args$1.logLevel, args$1.watchMode), specifier, importer ?? void 0, newExtraOptions);
2637
+ if (ret == null) return;
2638
+ if (ret === false) return {
2639
+ id: specifier,
2640
+ external: true,
2641
+ normalizeExternalId: true
2642
+ };
2643
+ if (typeof ret === "string") return {
2644
+ id: ret,
2645
+ normalizeExternalId: true
2646
+ };
2647
+ let exist = args$1.pluginContextData.updateModuleOption(ret.id, {
2648
+ meta: ret.meta || {},
2649
+ moduleSideEffects: ret.moduleSideEffects ?? null,
2650
+ invalidate: false
2651
+ });
2652
+ return {
2653
+ id: ret.id,
2654
+ external: ret.external,
2655
+ normalizeExternalId: false,
2656
+ sideEffects: bindingifySideEffects(exist.moduleSideEffects)
2657
+ };
2658
+ },
2659
+ meta: bindingifyPluginHookMeta(meta),
2660
+ filter: bindingifyResolveIdFilter(options.filter)
2661
+ };
2662
+ }
2663
+ function bindingifyResolveDynamicImport(args$1) {
2664
+ const hook = args$1.plugin.resolveDynamicImport;
2665
+ if (!hook) return {};
2666
+ const { handler, meta } = normalizeHook(hook);
2667
+ return {
2668
+ plugin: async (ctx, specifier, importer) => {
2669
+ const ret = await handler.call(new PluginContextImpl(args$1.outputOptions, ctx, args$1.plugin, args$1.pluginContextData, args$1.onLog, args$1.logLevel, args$1.watchMode), specifier, importer ?? void 0);
2670
+ if (ret == null) return;
2671
+ if (ret === false) return {
2672
+ id: specifier,
2673
+ external: true
2674
+ };
2675
+ if (typeof ret === "string") return { id: ret };
2676
+ const result = {
2677
+ id: ret.id,
2678
+ external: ret.external
2679
+ };
2680
+ if (ret.moduleSideEffects !== null) result.sideEffects = bindingifySideEffects(ret.moduleSideEffects);
2681
+ args$1.pluginContextData.updateModuleOption(ret.id, {
2682
+ meta: ret.meta || {},
2683
+ moduleSideEffects: ret.moduleSideEffects || null,
2684
+ invalidate: false
2685
+ });
2686
+ return result;
2687
+ },
2688
+ meta: bindingifyPluginHookMeta(meta)
2689
+ };
2690
+ }
2691
+ function bindingifyTransform(args$1) {
2692
+ const hook = args$1.plugin.transform;
2693
+ if (!hook) return {};
2694
+ const { handler, meta, options } = normalizeHook(hook);
2695
+ return {
2696
+ plugin: async (ctx, code$1, id$1, meta$1) => {
2697
+ const ret = await handler.call(new TransformPluginContextImpl(args$1.outputOptions, ctx.inner(), args$1.plugin, args$1.pluginContextData, ctx, id$1, code$1, args$1.onLog, args$1.logLevel, args$1.watchMode), code$1, id$1, meta$1);
2698
+ if (ret == null) return void 0;
2699
+ if (typeof ret === "string") return { code: ret };
2700
+ let moduleOption = args$1.pluginContextData.updateModuleOption(id$1, {
2701
+ meta: ret.meta ?? {},
2702
+ moduleSideEffects: ret.moduleSideEffects ?? null,
2703
+ invalidate: false
2704
+ });
2705
+ return {
2706
+ code: ret.code,
2707
+ map: bindingifySourcemap(normalizeTransformHookSourcemap(id$1, code$1, ret.map)),
2708
+ sideEffects: bindingifySideEffects(moduleOption.moduleSideEffects),
2709
+ moduleType: ret.moduleType
2710
+ };
2711
+ },
2712
+ meta: bindingifyPluginHookMeta(meta),
2713
+ filter: bindingifyTransformFilter(options.filter)
2714
+ };
2715
+ }
2716
+ function bindingifyLoad(args$1) {
2717
+ const hook = args$1.plugin.load;
2718
+ if (!hook) return {};
2719
+ const { handler, meta, options } = normalizeHook(hook);
2720
+ return {
2721
+ plugin: async (ctx, id$1) => {
2722
+ const ret = await handler.call(new PluginContextImpl(args$1.outputOptions, ctx, args$1.plugin, args$1.pluginContextData, args$1.onLog, args$1.logLevel, args$1.watchMode, id$1), id$1);
2723
+ if (ret == null) return;
2724
+ if (typeof ret === "string") return { code: ret };
2725
+ let moduleOption = args$1.pluginContextData.updateModuleOption(id$1, {
2726
+ meta: ret.meta || {},
2727
+ moduleSideEffects: ret.moduleSideEffects ?? null,
2728
+ invalidate: false
2729
+ });
2730
+ let map = preProcessSourceMap(ret, id$1);
2731
+ return {
2732
+ code: ret.code,
2733
+ map: bindingifySourcemap(map),
2734
+ moduleType: ret.moduleType,
2735
+ sideEffects: bindingifySideEffects(moduleOption.moduleSideEffects)
2736
+ };
2737
+ },
2738
+ meta: bindingifyPluginHookMeta(meta),
2739
+ filter: bindingifyLoadFilter(options.filter)
2740
+ };
2741
+ }
2742
+ function preProcessSourceMap(ret, id$1) {
2743
+ if (!ret.map) return;
2744
+ let map = typeof ret.map === "object" ? ret.map : JSON.parse(ret.map);
2745
+ if (!isEmptySourcemapFiled(map.sources)) {
2746
+ const directory = path.dirname(id$1) || ".";
2747
+ const sourceRoot = map.sourceRoot || ".";
2748
+ map.sources = map.sources.map((source) => path.resolve(directory, sourceRoot, source));
2749
+ }
2750
+ return map;
2751
+ }
2752
+ function bindingifyModuleParsed(args$1) {
2753
+ const hook = args$1.plugin.moduleParsed;
2754
+ if (!hook) return {};
2755
+ const { handler, meta } = normalizeHook(hook);
2756
+ return {
2757
+ plugin: async (ctx, moduleInfo) => {
2758
+ await handler.call(new PluginContextImpl(args$1.outputOptions, ctx, args$1.plugin, args$1.pluginContextData, args$1.onLog, args$1.logLevel, args$1.watchMode), transformModuleInfo(moduleInfo, args$1.pluginContextData.getModuleOption(moduleInfo.id)));
2759
+ },
2760
+ meta: bindingifyPluginHookMeta(meta)
2761
+ };
2762
+ }
2763
+
2764
+ //#endregion
2765
+ //#region src/utils/transform-rendered-module.ts
2766
+ function transformToRenderedModule(bindingRenderedModule) {
2767
+ return {
2768
+ get code() {
2769
+ return bindingRenderedModule.code;
2770
+ },
2771
+ get renderedLength() {
2772
+ return bindingRenderedModule.code?.length || 0;
2773
+ },
2774
+ get renderedExports() {
2775
+ return bindingRenderedModule.renderedExports;
2776
+ }
2777
+ };
2778
+ }
2779
+
2780
+ //#endregion
2781
+ //#region src/utils/transform-rendered-chunk.ts
2782
+ function transformRenderedChunk(chunk) {
2783
+ let modules = null;
2784
+ return {
2785
+ type: "chunk",
2786
+ get name() {
2787
+ return chunk.name;
2788
+ },
2789
+ get isEntry() {
2790
+ return chunk.isEntry;
2791
+ },
2792
+ get isDynamicEntry() {
2793
+ return chunk.isDynamicEntry;
2794
+ },
2795
+ get facadeModuleId() {
2796
+ return chunk.facadeModuleId;
2797
+ },
2798
+ get moduleIds() {
2799
+ return chunk.moduleIds;
2800
+ },
2801
+ get exports() {
2802
+ return chunk.exports;
2803
+ },
2804
+ get fileName() {
2805
+ return chunk.fileName;
2806
+ },
2807
+ get imports() {
2808
+ return chunk.imports;
2809
+ },
2810
+ get dynamicImports() {
2811
+ return chunk.dynamicImports;
2812
+ },
2813
+ get modules() {
2814
+ if (!modules) modules = transformChunkModules(chunk.modules);
2815
+ return modules;
2816
+ }
2817
+ };
2818
+ }
2819
+ function transformChunkModules(modules) {
2820
+ const result = {};
2821
+ for (let i$1 = 0; i$1 < modules.values.length; i$1++) {
2822
+ let key = modules.keys[i$1];
2823
+ const mod = modules.values[i$1];
2824
+ result[key] = transformToRenderedModule(mod);
2825
+ }
2826
+ return result;
2827
+ }
2828
+
2829
+ //#endregion
2830
+ //#region src/utils/bindingify-output-options.ts
2831
+ function bindingifyOutputOptions(outputOptions) {
2832
+ const { dir, format, exports, hashCharacters, sourcemap, sourcemapDebugIds, sourcemapIgnoreList, sourcemapPathTransform, name, assetFileNames, entryFileNames, chunkFileNames, cssEntryFileNames, cssChunkFileNames, banner, footer, intro, outro, esModule, globals, file, sanitizeFileName, preserveModules, virtualDirname, legalComments, preserveModulesRoot } = outputOptions;
2833
+ return {
2834
+ dir,
2835
+ file: file == null ? void 0 : file,
2836
+ format: bindingifyFormat(format),
2837
+ exports,
2838
+ hashCharacters,
2839
+ sourcemap: bindingifySourcemap$1(sourcemap),
2840
+ sourcemapDebugIds,
2841
+ sourcemapIgnoreList: bindingifySourcemapIgnoreList(sourcemapIgnoreList),
2842
+ sourcemapPathTransform,
2843
+ banner: bindingifyAddon(banner),
2844
+ footer: bindingifyAddon(footer),
2845
+ intro: bindingifyAddon(intro),
2846
+ outro: bindingifyAddon(outro),
2847
+ extend: outputOptions.extend,
2848
+ globals,
2849
+ esModule,
2850
+ name,
2851
+ assetFileNames: bindingifyAssetFilenames(assetFileNames),
2852
+ entryFileNames,
2853
+ chunkFileNames,
2854
+ cssEntryFileNames,
2855
+ cssChunkFileNames,
2856
+ plugins: [],
2857
+ minify: outputOptions.minify,
2858
+ externalLiveBindings: outputOptions.externalLiveBindings,
2859
+ inlineDynamicImports: outputOptions.inlineDynamicImports,
2860
+ advancedChunks: outputOptions.advancedChunks,
2861
+ polyfillRequire: outputOptions.polyfillRequire,
2862
+ sanitizeFileName,
2863
+ preserveModules,
2864
+ virtualDirname,
2865
+ legalComments,
2866
+ preserveModulesRoot
2867
+ };
2868
+ }
2869
+ function bindingifyAddon(configAddon) {
2870
+ return async (chunk) => {
2871
+ if (typeof configAddon === "function") return configAddon(transformRenderedChunk(chunk));
2872
+ return configAddon || "";
2873
+ };
2874
+ }
2875
+ function bindingifyFormat(format) {
2876
+ switch (format) {
2877
+ case void 0:
2878
+ case "es":
2879
+ case "esm":
2880
+ case "module": return "es";
2881
+ case "cjs":
2882
+ case "commonjs": return "cjs";
2883
+ case "iife": return "iife";
2884
+ case "umd": return "umd";
2885
+ case "experimental-app": return "app";
2886
+ default: unimplemented(`output.format: ${format}`);
2887
+ }
2888
+ }
2889
+ function bindingifySourcemap$1(sourcemap) {
2890
+ switch (sourcemap) {
2891
+ case true: return "file";
2892
+ case "inline": return "inline";
2893
+ case false:
2894
+ case void 0: return void 0;
2895
+ case "hidden": return "hidden";
2896
+ default: throw new Error(`unknown sourcemap: ${sourcemap}`);
2897
+ }
2898
+ }
2899
+ function bindingifySourcemapIgnoreList(sourcemapIgnoreList) {
2900
+ return typeof sourcemapIgnoreList === "function" ? sourcemapIgnoreList : sourcemapIgnoreList === false ? () => false : (relativeSourcePath, _sourcemapPath) => relativeSourcePath.includes("node_modules");
2901
+ }
2902
+ function bindingifyAssetFilenames(assetFileNames) {
2903
+ if (typeof assetFileNames === "function") return (asset) => {
2904
+ return assetFileNames({
2905
+ names: asset.names,
2906
+ originalFileNames: asset.originalFileNames,
2907
+ source: transformAssetSource(asset.source),
2908
+ type: "asset"
2909
+ });
2910
+ };
2911
+ return assetFileNames;
2912
+ }
2913
+
2914
+ //#endregion
2915
+ //#region src/options/normalized-output-options.ts
2916
+ var NormalizedOutputOptionsImpl = class {
2917
+ constructor(inner, outputOptions, normalizedOutputPlugins) {
2918
+ this.inner = inner;
2919
+ this.outputOptions = outputOptions;
2920
+ this.normalizedOutputPlugins = normalizedOutputPlugins;
2921
+ }
2922
+ get dir() {
2923
+ return this.inner.dir ?? void 0;
2924
+ }
2925
+ get entryFileNames() {
2926
+ return this.inner.entryFilenames || this.outputOptions.entryFileNames;
2927
+ }
2928
+ get chunkFileNames() {
2929
+ return this.inner.chunkFilenames || this.outputOptions.chunkFileNames;
2930
+ }
2931
+ get assetFileNames() {
2932
+ return this.inner.assetFilenames || this.outputOptions.assetFileNames;
2933
+ }
2934
+ get format() {
2935
+ return this.inner.format;
2936
+ }
2937
+ get exports() {
2938
+ return this.inner.exports;
2939
+ }
2940
+ get sourcemap() {
2941
+ return this.inner.sourcemap;
2942
+ }
2943
+ get cssEntryFileNames() {
2944
+ return this.inner.cssEntryFilenames || this.outputOptions.cssEntryFileNames;
2945
+ }
2946
+ get cssChunkFileNames() {
2947
+ return this.inner.cssChunkFilenames || this.outputOptions.cssChunkFileNames;
2948
+ }
2949
+ get shimMissingExports() {
2950
+ return this.inner.shimMissingExports;
2951
+ }
2952
+ get name() {
2953
+ return this.inner.name ?? void 0;
2954
+ }
2955
+ get file() {
2956
+ return this.inner.file ?? void 0;
2957
+ }
2958
+ get inlineDynamicImports() {
2959
+ return this.inner.inlineDynamicImports;
2960
+ }
2961
+ get externalLiveBindings() {
2962
+ return this.inner.externalLiveBindings;
2963
+ }
2964
+ get banner() {
2965
+ return normalizeAddon(this.outputOptions.banner);
2966
+ }
2967
+ get footer() {
2968
+ return normalizeAddon(this.outputOptions.footer);
2969
+ }
2970
+ get intro() {
2971
+ return normalizeAddon(this.outputOptions.intro);
2972
+ }
2973
+ get outro() {
2974
+ return normalizeAddon(this.outputOptions.outro);
2975
+ }
2976
+ get esModule() {
2977
+ return this.inner.esModule;
2978
+ }
2979
+ get extend() {
2980
+ return this.inner.extend;
2981
+ }
2982
+ get globals() {
2983
+ return this.inner.globals || this.outputOptions.globals;
2984
+ }
2985
+ get hashCharacters() {
2986
+ return this.inner.hashCharacters;
2987
+ }
2988
+ get sourcemapDebugIds() {
2989
+ return this.inner.sourcemapDebugIds;
2990
+ }
2991
+ get sourcemapIgnoreList() {
2992
+ return bindingifySourcemapIgnoreList(this.outputOptions.sourcemapIgnoreList);
2993
+ }
2994
+ get sourcemapPathTransform() {
2995
+ return this.outputOptions.sourcemapPathTransform;
2996
+ }
2997
+ get minify() {
2998
+ return this.inner.minify;
2999
+ }
3000
+ get legalComments() {
3001
+ return this.inner.legalComments;
3002
+ }
3003
+ get polyfillRequire() {
3004
+ return this.inner.polyfillRequire;
3005
+ }
3006
+ get plugins() {
3007
+ return this.normalizedOutputPlugins;
3008
+ }
3009
+ get preserveModules() {
3010
+ return this.preserveModules;
3011
+ }
3012
+ get preserveModulesRoot() {
3013
+ return this.preserveModulesRoot;
3014
+ }
3015
+ get virtualDirname() {
3016
+ return this.virtualDirname;
3017
+ }
3018
+ };
3019
+ function normalizeAddon(value) {
3020
+ if (typeof value === "function") return value;
3021
+ return () => value || "";
3022
+ }
3023
+
3024
+ //#endregion
3025
+ //#region src/utils/transform-to-rollup-output.ts
3026
+ function transformToRollupSourceMap(map) {
3027
+ const parsed = JSON.parse(map);
3028
+ const obj = {
3029
+ ...parsed,
3030
+ toString() {
3031
+ return JSON.stringify(obj);
3032
+ },
3033
+ toUrl() {
3034
+ return `data:application/json;charset=utf-8;base64,${Buffer.from(obj.toString(), "utf-8").toString("base64")}`;
3035
+ }
3036
+ };
3037
+ return obj;
3038
+ }
3039
+ function transformToRollupOutputChunk(bindingChunk, changed) {
3040
+ const chunk = {
3041
+ type: "chunk",
3042
+ get code() {
3043
+ return bindingChunk.code;
3044
+ },
3045
+ fileName: bindingChunk.fileName,
3046
+ name: bindingChunk.name,
3047
+ get modules() {
3048
+ return transformChunkModules(bindingChunk.modules);
3049
+ },
3050
+ get imports() {
3051
+ return bindingChunk.imports;
3052
+ },
3053
+ get dynamicImports() {
3054
+ return bindingChunk.dynamicImports;
3055
+ },
3056
+ exports: bindingChunk.exports,
3057
+ isEntry: bindingChunk.isEntry,
3058
+ facadeModuleId: bindingChunk.facadeModuleId || null,
3059
+ isDynamicEntry: bindingChunk.isDynamicEntry,
3060
+ get moduleIds() {
3061
+ return bindingChunk.moduleIds;
3062
+ },
3063
+ get map() {
3064
+ return bindingChunk.map ? transformToRollupSourceMap(bindingChunk.map) : null;
3065
+ },
3066
+ sourcemapFileName: bindingChunk.sourcemapFileName || null,
3067
+ preliminaryFileName: bindingChunk.preliminaryFileName
3068
+ };
3069
+ const cache = {};
3070
+ return new Proxy(chunk, {
3071
+ get(target, p) {
3072
+ if (p in cache) return cache[p];
3073
+ const value = target[p];
3074
+ cache[p] = value;
3075
+ return value;
3076
+ },
3077
+ set(target, p, newValue) {
3078
+ cache[p] = newValue;
3079
+ changed?.updated.add(bindingChunk.fileName);
3080
+ return true;
3081
+ },
3082
+ has(target, p) {
3083
+ if (p in cache) return true;
3084
+ return p in target;
3085
+ }
3086
+ });
3087
+ }
3088
+ function transformToRollupOutputAsset(bindingAsset, changed) {
3089
+ const asset = {
3090
+ type: "asset",
3091
+ fileName: bindingAsset.fileName,
3092
+ originalFileName: bindingAsset.originalFileName || null,
3093
+ originalFileNames: bindingAsset.originalFileNames,
3094
+ get source() {
3095
+ return transformAssetSource(bindingAsset.source);
3096
+ },
3097
+ name: bindingAsset.name ?? void 0,
3098
+ names: bindingAsset.names
3099
+ };
3100
+ const cache = {};
3101
+ return new Proxy(asset, {
3102
+ get(target, p) {
3103
+ if (p in cache) return cache[p];
3104
+ const value = target[p];
3105
+ cache[p] = value;
3106
+ return value;
3107
+ },
3108
+ set(target, p, newValue) {
3109
+ cache[p] = newValue;
3110
+ changed?.updated.add(bindingAsset.fileName);
3111
+ return true;
3112
+ }
3113
+ });
3114
+ }
3115
+ function transformToRollupOutput(output, changed) {
3116
+ handleOutputErrors(output);
3117
+ const { chunks, assets } = output;
3118
+ return { output: [...chunks.map((chunk) => transformToRollupOutputChunk(chunk, changed)), ...assets.map((asset) => transformToRollupOutputAsset(asset, changed))] };
3119
+ }
3120
+ function handleOutputErrors(output) {
3121
+ const rawErrors = output.errors;
3122
+ if (rawErrors.length > 0) throw normalizeErrors(rawErrors);
3123
+ }
3124
+ function transformToOutputBundle(output, changed) {
3125
+ const bundle = Object.fromEntries(transformToRollupOutput(output, changed).output.map((item) => [item.fileName, item]));
3126
+ return new Proxy(bundle, { deleteProperty(target, property) {
3127
+ if (typeof property === "string") changed.deleted.add(property);
3128
+ return true;
3129
+ } });
3130
+ }
3131
+ function collectChangedBundle(changed, bundle) {
3132
+ const assets = [];
3133
+ const chunks = [];
3134
+ for (const key in bundle) {
3135
+ if (changed.deleted.has(key) || !changed.updated.has(key)) continue;
3136
+ const item = bundle[key];
3137
+ if (item.type === "asset") assets.push({
3138
+ filename: item.fileName,
3139
+ originalFileNames: item.originalFileNames,
3140
+ source: bindingAssetSource(item.source),
3141
+ names: item.names
3142
+ });
3143
+ else chunks.push({
3144
+ code: item.code,
3145
+ filename: item.fileName,
3146
+ name: item.name,
3147
+ isEntry: item.isEntry,
3148
+ exports: item.exports,
3149
+ modules: {},
3150
+ imports: item.imports,
3151
+ dynamicImports: item.dynamicImports,
3152
+ facadeModuleId: item.facadeModuleId || void 0,
3153
+ isDynamicEntry: item.isDynamicEntry,
3154
+ moduleIds: item.moduleIds,
3155
+ map: bindingifySourcemap(item.map),
3156
+ sourcemapFilename: item.sourcemapFileName || void 0,
3157
+ preliminaryFilename: item.preliminaryFileName
3158
+ });
3159
+ }
3160
+ return {
3161
+ assets,
3162
+ chunks,
3163
+ deleted: Array.from(changed.deleted)
3164
+ };
3165
+ }
3166
+
3167
+ //#endregion
3168
+ //#region src/plugin/bindingify-output-hooks.ts
3169
+ function bindingifyRenderStart(args$1) {
3170
+ const hook = args$1.plugin.renderStart;
3171
+ if (!hook) return {};
3172
+ const { handler, meta } = normalizeHook(hook);
3173
+ return {
3174
+ plugin: async (ctx, opts) => {
3175
+ handler.call(new PluginContextImpl(args$1.outputOptions, ctx, args$1.plugin, args$1.pluginContextData, args$1.onLog, args$1.logLevel, args$1.watchMode), new NormalizedOutputOptionsImpl(opts, args$1.outputOptions, args$1.normalizedOutputPlugins), new NormalizedInputOptionsImpl(opts, args$1.onLog));
3176
+ },
3177
+ meta: bindingifyPluginHookMeta(meta)
3178
+ };
3179
+ }
3180
+ function bindingifyRenderChunk(args$1) {
3181
+ const hook = args$1.plugin.renderChunk;
3182
+ if (!hook) return {};
3183
+ const { handler, meta, options } = normalizeHook(hook);
3184
+ return {
3185
+ plugin: async (ctx, code$1, chunk, opts, meta$1) => {
3186
+ if (args$1.pluginContextData.getRenderChunkMeta() == null) args$1.pluginContextData.setRenderChunkMeta({ chunks: Object.fromEntries(Object.entries(meta$1.chunks).map(([key, value]) => [key, transformRenderedChunk(value)])) });
3187
+ const ret = await handler.call(new PluginContextImpl(args$1.outputOptions, ctx, args$1.plugin, args$1.pluginContextData, args$1.onLog, args$1.logLevel, args$1.watchMode), code$1, transformRenderedChunk(chunk), new NormalizedOutputOptionsImpl(opts, args$1.outputOptions, args$1.normalizedOutputPlugins), args$1.pluginContextData.getRenderChunkMeta());
3188
+ if (ret == null) return;
3189
+ if (typeof ret === "string") return { code: ret };
3190
+ if (!ret.map) return { code: ret.code };
3191
+ return {
3192
+ code: ret.code,
3193
+ map: bindingifySourcemap(ret.map)
3194
+ };
3195
+ },
3196
+ meta: bindingifyPluginHookMeta(meta),
3197
+ filter: bindingifyRenderChunkFilter(options.filter)
3198
+ };
3199
+ }
3200
+ function bindingifyAugmentChunkHash(args$1) {
3201
+ const hook = args$1.plugin.augmentChunkHash;
3202
+ if (!hook) return {};
3203
+ const { handler, meta } = normalizeHook(hook);
3204
+ return {
3205
+ plugin: async (ctx, chunk) => {
3206
+ return await handler.call(new PluginContextImpl(args$1.outputOptions, ctx, args$1.plugin, args$1.pluginContextData, args$1.onLog, args$1.logLevel, args$1.watchMode), transformRenderedChunk(chunk));
3207
+ },
3208
+ meta: bindingifyPluginHookMeta(meta)
3209
+ };
3210
+ }
3211
+ function bindingifyRenderError(args$1) {
3212
+ const hook = args$1.plugin.renderError;
3213
+ if (!hook) return {};
3214
+ const { handler, meta } = normalizeHook(hook);
3215
+ return {
3216
+ plugin: async (ctx, err) => {
3217
+ handler.call(new PluginContextImpl(args$1.outputOptions, ctx, args$1.plugin, args$1.pluginContextData, args$1.onLog, args$1.logLevel, args$1.watchMode), normalizeErrors(err));
3218
+ },
3219
+ meta: bindingifyPluginHookMeta(meta)
3220
+ };
3221
+ }
3222
+ function bindingifyGenerateBundle(args$1) {
3223
+ const hook = args$1.plugin.generateBundle;
3224
+ if (!hook) return {};
3225
+ const { handler, meta } = normalizeHook(hook);
3226
+ return {
3227
+ plugin: async (ctx, bundle, isWrite, opts) => {
3228
+ const changed = {
3229
+ updated: /* @__PURE__ */ new Set(),
3230
+ deleted: /* @__PURE__ */ new Set()
3231
+ };
3232
+ const output = transformToOutputBundle(bundle, changed);
3233
+ await handler.call(new PluginContextImpl(args$1.outputOptions, ctx, args$1.plugin, args$1.pluginContextData, args$1.onLog, args$1.logLevel, args$1.watchMode), new NormalizedOutputOptionsImpl(opts, args$1.outputOptions, args$1.normalizedOutputPlugins), output, isWrite);
3234
+ return collectChangedBundle(changed, output);
3235
+ },
3236
+ meta: bindingifyPluginHookMeta(meta)
3237
+ };
3238
+ }
3239
+ function bindingifyWriteBundle(args$1) {
3240
+ const hook = args$1.plugin.writeBundle;
3241
+ if (!hook) return {};
3242
+ const { handler, meta } = normalizeHook(hook);
3243
+ return {
3244
+ plugin: async (ctx, bundle, opts) => {
3245
+ const changed = {
3246
+ updated: /* @__PURE__ */ new Set(),
3247
+ deleted: /* @__PURE__ */ new Set()
3248
+ };
3249
+ const output = transformToOutputBundle(bundle, changed);
3250
+ await handler.call(new PluginContextImpl(args$1.outputOptions, ctx, args$1.plugin, args$1.pluginContextData, args$1.onLog, args$1.logLevel, args$1.watchMode), new NormalizedOutputOptionsImpl(opts, args$1.outputOptions, args$1.normalizedOutputPlugins), output);
3251
+ return collectChangedBundle(changed, output);
3252
+ },
3253
+ meta: bindingifyPluginHookMeta(meta)
3254
+ };
3255
+ }
3256
+ function bindingifyCloseBundle(args$1) {
3257
+ const hook = args$1.plugin.closeBundle;
3258
+ if (!hook) return {};
3259
+ const { handler, meta } = normalizeHook(hook);
3260
+ return {
3261
+ plugin: async (ctx) => {
3262
+ await handler.call(new PluginContextImpl(args$1.outputOptions, ctx, args$1.plugin, args$1.pluginContextData, args$1.onLog, args$1.logLevel, args$1.watchMode));
3263
+ },
3264
+ meta: bindingifyPluginHookMeta(meta)
3265
+ };
3266
+ }
3267
+ function bindingifyBanner(args$1) {
3268
+ const hook = args$1.plugin.banner;
3269
+ if (!hook) return {};
3270
+ const { handler, meta } = normalizeHook(hook);
3271
+ return {
3272
+ plugin: async (ctx, chunk) => {
3273
+ if (typeof handler === "string") return handler;
3274
+ return handler.call(new PluginContextImpl(args$1.outputOptions, ctx, args$1.plugin, args$1.pluginContextData, args$1.onLog, args$1.logLevel, args$1.watchMode), transformRenderedChunk(chunk));
3275
+ },
3276
+ meta: bindingifyPluginHookMeta(meta)
3277
+ };
3278
+ }
3279
+ function bindingifyFooter(args$1) {
3280
+ const hook = args$1.plugin.footer;
3281
+ if (!hook) return {};
3282
+ const { handler, meta } = normalizeHook(hook);
3283
+ return {
3284
+ plugin: async (ctx, chunk) => {
3285
+ if (typeof handler === "string") return handler;
3286
+ return handler.call(new PluginContextImpl(args$1.outputOptions, ctx, args$1.plugin, args$1.pluginContextData, args$1.onLog, args$1.logLevel, args$1.watchMode), transformRenderedChunk(chunk));
3287
+ },
3288
+ meta: bindingifyPluginHookMeta(meta)
3289
+ };
3290
+ }
3291
+ function bindingifyIntro(args$1) {
3292
+ const hook = args$1.plugin.intro;
3293
+ if (!hook) return {};
3294
+ const { handler, meta } = normalizeHook(hook);
3295
+ return {
3296
+ plugin: async (ctx, chunk) => {
3297
+ if (typeof handler === "string") return handler;
3298
+ return handler.call(new PluginContextImpl(args$1.outputOptions, ctx, args$1.plugin, args$1.pluginContextData, args$1.onLog, args$1.logLevel, args$1.watchMode), transformRenderedChunk(chunk));
3299
+ },
3300
+ meta: bindingifyPluginHookMeta(meta)
3301
+ };
3302
+ }
3303
+ function bindingifyOutro(args$1) {
3304
+ const hook = args$1.plugin.outro;
3305
+ if (!hook) return {};
3306
+ const { handler, meta } = normalizeHook(hook);
3307
+ return {
3308
+ plugin: async (ctx, chunk) => {
3309
+ if (typeof handler === "string") return handler;
3310
+ return handler.call(new PluginContextImpl(args$1.outputOptions, ctx, args$1.plugin, args$1.pluginContextData, args$1.onLog, args$1.logLevel, args$1.watchMode), transformRenderedChunk(chunk));
3311
+ },
3312
+ meta: bindingifyPluginHookMeta(meta)
3313
+ };
3314
+ }
3315
+
3316
+ //#endregion
3317
+ //#region src/plugin/bindingify-watch-hooks.ts
3318
+ function bindingifyWatchChange(args$1) {
3319
+ const hook = args$1.plugin.watchChange;
3320
+ if (!hook) return {};
3321
+ const { handler, meta } = normalizeHook(hook);
3322
+ return {
3323
+ plugin: async (ctx, id$1, event) => {
3324
+ await handler.call(new PluginContextImpl(args$1.outputOptions, ctx, args$1.plugin, args$1.pluginContextData, args$1.onLog, args$1.logLevel, args$1.watchMode), id$1, { event });
3325
+ },
3326
+ meta: bindingifyPluginHookMeta(meta)
3327
+ };
3328
+ }
3329
+ function bindingifyCloseWatcher(args$1) {
3330
+ const hook = args$1.plugin.closeWatcher;
3331
+ if (!hook) return {};
3332
+ const { handler, meta } = normalizeHook(hook);
3333
+ return {
3334
+ plugin: async (ctx) => {
3335
+ await handler.call(new PluginContextImpl(args$1.outputOptions, ctx, args$1.plugin, args$1.pluginContextData, args$1.onLog, args$1.logLevel, args$1.watchMode));
3336
+ },
3337
+ meta: bindingifyPluginHookMeta(meta)
3338
+ };
3339
+ }
3340
+
3341
+ //#endregion
3342
+ //#region src/plugin/generated/hook-usage.ts
3343
+ let HookUsageKind = /* @__PURE__ */ function(HookUsageKind$1) {
3344
+ HookUsageKind$1[HookUsageKind$1["buildStart"] = 1] = "buildStart";
3345
+ HookUsageKind$1[HookUsageKind$1["resolveId"] = 2] = "resolveId";
3346
+ HookUsageKind$1[HookUsageKind$1["resolveDynamicImport"] = 4] = "resolveDynamicImport";
3347
+ HookUsageKind$1[HookUsageKind$1["load"] = 8] = "load";
3348
+ HookUsageKind$1[HookUsageKind$1["transform"] = 16] = "transform";
3349
+ HookUsageKind$1[HookUsageKind$1["moduleParsed"] = 32] = "moduleParsed";
3350
+ HookUsageKind$1[HookUsageKind$1["buildEnd"] = 64] = "buildEnd";
3351
+ HookUsageKind$1[HookUsageKind$1["renderStart"] = 128] = "renderStart";
3352
+ HookUsageKind$1[HookUsageKind$1["renderError"] = 256] = "renderError";
3353
+ HookUsageKind$1[HookUsageKind$1["renderChunk"] = 512] = "renderChunk";
3354
+ HookUsageKind$1[HookUsageKind$1["augmentChunkHash"] = 1024] = "augmentChunkHash";
3355
+ HookUsageKind$1[HookUsageKind$1["generateBundle"] = 2048] = "generateBundle";
3356
+ HookUsageKind$1[HookUsageKind$1["writeBundle"] = 4096] = "writeBundle";
3357
+ HookUsageKind$1[HookUsageKind$1["closeBundle"] = 8192] = "closeBundle";
3358
+ HookUsageKind$1[HookUsageKind$1["watchChange"] = 16384] = "watchChange";
3359
+ HookUsageKind$1[HookUsageKind$1["closeWatcher"] = 32768] = "closeWatcher";
3360
+ HookUsageKind$1[HookUsageKind$1["transformAst"] = 65536] = "transformAst";
3361
+ HookUsageKind$1[HookUsageKind$1["banner"] = 131072] = "banner";
3362
+ HookUsageKind$1[HookUsageKind$1["footer"] = 262144] = "footer";
3363
+ HookUsageKind$1[HookUsageKind$1["intro"] = 524288] = "intro";
3364
+ HookUsageKind$1[HookUsageKind$1["outro"] = 1048576] = "outro";
3365
+ return HookUsageKind$1;
3366
+ }({});
3367
+ var HookUsage = class {
3368
+ bitflag = BigInt(0);
3369
+ constructor() {}
3370
+ union(kind) {
3371
+ this.bitflag |= BigInt(kind);
3372
+ }
3373
+ inner() {
3374
+ return Number(this.bitflag);
3375
+ }
3376
+ };
3377
+ function extractHookUsage(plugin) {
3378
+ let hookUsage = new HookUsage();
3379
+ if (plugin.buildStart) hookUsage.union(HookUsageKind.buildStart);
3380
+ if (plugin.resolveId) hookUsage.union(HookUsageKind.resolveId);
3381
+ if (plugin.resolveDynamicImport) hookUsage.union(HookUsageKind.resolveDynamicImport);
3382
+ if (plugin.load) hookUsage.union(HookUsageKind.load);
3383
+ if (plugin.transform) hookUsage.union(HookUsageKind.transform);
3384
+ if (plugin.moduleParsed) hookUsage.union(HookUsageKind.moduleParsed);
3385
+ if (plugin.buildEnd) hookUsage.union(HookUsageKind.buildEnd);
3386
+ if (plugin.renderStart) hookUsage.union(HookUsageKind.renderStart);
3387
+ if (plugin.renderError) hookUsage.union(HookUsageKind.renderError);
3388
+ if (plugin.renderChunk) hookUsage.union(HookUsageKind.renderChunk);
3389
+ if (plugin.augmentChunkHash) hookUsage.union(HookUsageKind.augmentChunkHash);
3390
+ if (plugin.generateBundle) hookUsage.union(HookUsageKind.generateBundle);
3391
+ if (plugin.writeBundle) hookUsage.union(HookUsageKind.writeBundle);
3392
+ if (plugin.closeBundle) hookUsage.union(HookUsageKind.closeBundle);
3393
+ if (plugin.watchChange) hookUsage.union(HookUsageKind.watchChange);
3394
+ if (plugin.closeWatcher) hookUsage.union(HookUsageKind.closeWatcher);
3395
+ if (plugin.banner) hookUsage.union(HookUsageKind.banner);
3396
+ if (plugin.footer) hookUsage.union(HookUsageKind.footer);
3397
+ if (plugin.intro) hookUsage.union(HookUsageKind.intro);
3398
+ if (plugin.outro) hookUsage.union(HookUsageKind.outro);
3399
+ return hookUsage;
3400
+ }
3401
+
3402
+ //#endregion
3403
+ //#region src/plugin/bindingify-plugin.ts
3404
+ function bindingifyPlugin(plugin, options, outputOptions, pluginContextData, normalizedOutputPlugins, onLog, logLevel, watchMode) {
3405
+ const args$1 = {
3406
+ plugin,
3407
+ options,
3408
+ outputOptions,
3409
+ pluginContextData,
3410
+ onLog,
3411
+ logLevel,
3412
+ watchMode,
3413
+ normalizedOutputPlugins
3414
+ };
3415
+ const { plugin: buildStart, meta: buildStartMeta } = bindingifyBuildStart(args$1);
3416
+ const { plugin: resolveId, meta: resolveIdMeta, filter: resolveIdFilter } = bindingifyResolveId(args$1);
3417
+ const { plugin: resolveDynamicImport, meta: resolveDynamicImportMeta } = bindingifyResolveDynamicImport(args$1);
3418
+ const { plugin: buildEnd, meta: buildEndMeta } = bindingifyBuildEnd(args$1);
3419
+ const { plugin: transform, meta: transformMeta, filter: transformFilter } = bindingifyTransform(args$1);
3420
+ const { plugin: moduleParsed, meta: moduleParsedMeta } = bindingifyModuleParsed(args$1);
3421
+ const { plugin: load, meta: loadMeta, filter: loadFilter } = bindingifyLoad(args$1);
3422
+ const { plugin: renderChunk, meta: renderChunkMeta, filter: renderChunkFilter } = bindingifyRenderChunk(args$1);
3423
+ const { plugin: augmentChunkHash, meta: augmentChunkHashMeta } = bindingifyAugmentChunkHash(args$1);
3424
+ const { plugin: renderStart, meta: renderStartMeta } = bindingifyRenderStart(args$1);
3425
+ const { plugin: renderError, meta: renderErrorMeta } = bindingifyRenderError(args$1);
3426
+ const { plugin: generateBundle, meta: generateBundleMeta } = bindingifyGenerateBundle(args$1);
3427
+ const { plugin: writeBundle, meta: writeBundleMeta } = bindingifyWriteBundle(args$1);
3428
+ const { plugin: closeBundle, meta: closeBundleMeta } = bindingifyCloseBundle(args$1);
3429
+ const { plugin: banner, meta: bannerMeta } = bindingifyBanner(args$1);
3430
+ const { plugin: footer, meta: footerMeta } = bindingifyFooter(args$1);
3431
+ const { plugin: intro, meta: introMeta } = bindingifyIntro(args$1);
3432
+ const { plugin: outro, meta: outroMeta } = bindingifyOutro(args$1);
3433
+ const { plugin: watchChange, meta: watchChangeMeta } = bindingifyWatchChange(args$1);
3434
+ const { plugin: closeWatcher, meta: closeWatcherMeta } = bindingifyCloseWatcher(args$1);
3435
+ let hookUsage = extractHookUsage(plugin).inner();
3436
+ const result = {
3437
+ name: plugin.name,
3438
+ buildStart,
3439
+ buildStartMeta,
3440
+ resolveId,
3441
+ resolveIdMeta,
3442
+ resolveIdFilter,
3443
+ resolveDynamicImport,
3444
+ resolveDynamicImportMeta,
3445
+ buildEnd,
3446
+ buildEndMeta,
3447
+ transform,
3448
+ transformMeta,
3449
+ transformFilter,
3450
+ moduleParsed,
3451
+ moduleParsedMeta,
3452
+ load,
3453
+ loadMeta,
3454
+ loadFilter,
3455
+ renderChunk,
3456
+ renderChunkMeta,
3457
+ renderChunkFilter,
3458
+ augmentChunkHash,
3459
+ augmentChunkHashMeta,
3460
+ renderStart,
3461
+ renderStartMeta,
3462
+ renderError,
3463
+ renderErrorMeta,
3464
+ generateBundle,
3465
+ generateBundleMeta,
3466
+ writeBundle,
3467
+ writeBundleMeta,
3468
+ closeBundle,
3469
+ closeBundleMeta,
3470
+ banner,
3471
+ bannerMeta,
3472
+ footer,
3473
+ footerMeta,
3474
+ intro,
3475
+ introMeta,
3476
+ outro,
3477
+ outroMeta,
3478
+ watchChange,
3479
+ watchChangeMeta,
3480
+ closeWatcher,
3481
+ closeWatcherMeta,
3482
+ hookUsage
3483
+ };
3484
+ return wrapHandlers(result);
3485
+ }
3486
+ function wrapHandlers(plugin) {
3487
+ for (const hookName of [
3488
+ "buildStart",
3489
+ "resolveId",
3490
+ "resolveDynamicImport",
3491
+ "buildEnd",
3492
+ "transform",
3493
+ "moduleParsed",
3494
+ "load",
3495
+ "renderChunk",
3496
+ "augmentChunkHash",
3497
+ "renderStart",
3498
+ "renderError",
3499
+ "generateBundle",
3500
+ "writeBundle",
3501
+ "closeBundle",
3502
+ "banner",
3503
+ "footer",
3504
+ "intro",
3505
+ "outro",
3506
+ "watchChange",
3507
+ "closeWatcher"
3508
+ ]) {
3509
+ const handler = plugin[hookName];
3510
+ if (handler) plugin[hookName] = async (...args$1) => {
3511
+ try {
3512
+ return await handler(...args$1);
3513
+ } catch (e) {
3514
+ return error(logPluginError(e, plugin.name, {
3515
+ hook: hookName,
3516
+ id: hookName === "transform" ? args$1[2] : void 0
3517
+ }));
3518
+ }
3519
+ };
3520
+ }
3521
+ return plugin;
3522
+ }
3523
+
3524
+ //#endregion
3525
+ //#region src/plugin/plugin-context-data.ts
3526
+ var PluginContextData = class {
3527
+ moduleOptionMap = /* @__PURE__ */ new Map();
3528
+ resolveOptionsMap = /* @__PURE__ */ new Map();
3529
+ loadModulePromiseMap = /* @__PURE__ */ new Map();
3530
+ loadModulePromiseResolveFnMap = /* @__PURE__ */ new Map();
3531
+ renderedChunkMeta = null;
3532
+ updateModuleOption(id$1, option) {
3533
+ const existing = this.moduleOptionMap.get(id$1);
3534
+ if (existing) {
3535
+ if (option.moduleSideEffects != null) existing.moduleSideEffects = option.moduleSideEffects;
3536
+ if (option.meta != null) Object.assign(existing.meta, option.meta);
3537
+ if (option.invalidate != null) existing.invalidate = option.invalidate;
3538
+ } else {
3539
+ this.moduleOptionMap.set(id$1, option);
3540
+ return option;
3541
+ }
3542
+ return existing;
3543
+ }
3544
+ getModuleOption(id$1) {
3545
+ const option = this.moduleOptionMap.get(id$1);
3546
+ if (!option) {
3547
+ const raw = {
3548
+ moduleSideEffects: null,
3549
+ meta: {}
3550
+ };
3551
+ this.moduleOptionMap.set(id$1, raw);
3552
+ return raw;
3553
+ }
3554
+ return option;
3555
+ }
3556
+ getModuleInfo(id$1, context) {
3557
+ const bindingInfo = context.getModuleInfo(id$1);
3558
+ if (bindingInfo) {
3559
+ const info = transformModuleInfo(bindingInfo, this.getModuleOption(id$1));
3560
+ return this.proxyModuleInfo(id$1, info);
3561
+ }
3562
+ return null;
3563
+ }
3564
+ proxyModuleInfo(id$1, info) {
3565
+ let moduleSideEffects = info.moduleSideEffects;
3566
+ Object.defineProperty(info, "moduleSideEffects", {
3567
+ get() {
3568
+ return moduleSideEffects;
3569
+ },
3570
+ set: (v) => {
3571
+ this.updateModuleOption(id$1, {
3572
+ moduleSideEffects: v,
3573
+ meta: info.meta,
3574
+ invalidate: true
3575
+ });
3576
+ moduleSideEffects = v;
3577
+ }
3578
+ });
3579
+ return info;
3580
+ }
3581
+ getModuleIds(context) {
3582
+ const moduleIds = context.getModuleIds();
3583
+ return moduleIds.values();
3584
+ }
3585
+ saveResolveOptions(options) {
3586
+ const index = this.resolveOptionsMap.size;
3587
+ this.resolveOptionsMap.set(index, options);
3588
+ return index;
3589
+ }
3590
+ getSavedResolveOptions(receipt) {
3591
+ return this.resolveOptionsMap.get(receipt);
3592
+ }
3593
+ removeSavedResolveOptions(receipt) {
3594
+ this.resolveOptionsMap.delete(receipt);
3595
+ }
3596
+ setRenderChunkMeta(meta) {
3597
+ this.renderedChunkMeta = meta;
3598
+ }
3599
+ getRenderChunkMeta() {
3600
+ return this.renderedChunkMeta;
3601
+ }
3602
+ markModuleLoaded(id$1, _success) {
3603
+ const resolve = this.loadModulePromiseResolveFnMap.get(id$1);
3604
+ if (resolve) resolve();
3605
+ }
3606
+ clear() {
3607
+ this.renderedChunkMeta = null;
3608
+ this.loadModulePromiseMap.clear();
3609
+ this.loadModulePromiseResolveFnMap.clear();
3610
+ }
3611
+ };
3612
+
3613
+ //#endregion
3614
+ //#region src/utils/normalize-string-or-regex.ts
3615
+ function normalizedStringOrRegex(pattern) {
3616
+ if (!pattern) return void 0;
3617
+ if (!isReadonlyArray(pattern)) return [pattern];
3618
+ return pattern;
3619
+ }
3620
+ function isReadonlyArray(input) {
3621
+ return Array.isArray(input);
3622
+ }
3623
+
3624
+ //#endregion
3625
+ //#region src/utils/bindingify-input-options.ts
3626
+ function bindingifyInputOptions(rawPlugins, inputOptions, outputOptions, normalizedOutputPlugins, onLog, logLevel, watchMode) {
3627
+ const pluginContextData = new PluginContextData();
3628
+ const plugins = rawPlugins.map((plugin) => {
3629
+ if ("_parallel" in plugin) return void 0;
3630
+ if (plugin instanceof BuiltinPlugin) return bindingifyBuiltInPlugin(plugin);
3631
+ return bindingifyPlugin(plugin, inputOptions, outputOptions, pluginContextData, normalizedOutputPlugins, onLog, logLevel, watchMode);
3632
+ });
3633
+ return {
3634
+ input: bindingifyInput(inputOptions.input),
3635
+ plugins,
3636
+ cwd: inputOptions.cwd ?? process.cwd(),
3637
+ external: bindingifyExternal(inputOptions.external),
3638
+ resolve: bindingifyResolve(inputOptions.resolve),
3639
+ platform: inputOptions.platform,
3640
+ shimMissingExports: inputOptions.shimMissingExports,
3641
+ logLevel: bindingifyLogLevel(logLevel),
3642
+ onLog,
3643
+ treeshake: bindingifyTreeshakeOptions(inputOptions.treeshake),
3644
+ moduleTypes: inputOptions.moduleTypes,
3645
+ define: inputOptions.define ? Object.entries(inputOptions.define) : void 0,
3646
+ inject: bindingifyInject(inputOptions.inject),
3647
+ experimental: {
3648
+ strictExecutionOrder: inputOptions.experimental?.strictExecutionOrder,
3649
+ disableLiveBindings: inputOptions.experimental?.disableLiveBindings,
3650
+ viteMode: inputOptions.experimental?.viteMode,
3651
+ resolveNewUrlToAsset: inputOptions.experimental?.resolveNewUrlToAsset,
3652
+ hmr: bindingifyHmr(inputOptions.experimental?.hmr),
3653
+ attachDebugInfo: inputOptions.experimental?.attachDebugInfo
3654
+ },
3655
+ profilerNames: inputOptions?.profilerNames,
3656
+ jsx: bindingifyJsx(inputOptions.jsx),
3657
+ transform: inputOptions.transform,
3658
+ watch: bindingifyWatch(inputOptions.watch),
3659
+ dropLabels: inputOptions.dropLabels,
3660
+ keepNames: inputOptions.keepNames,
3661
+ checks: inputOptions.checks,
3662
+ deferSyncScanData: () => {
3663
+ let ret = [];
3664
+ pluginContextData.moduleOptionMap.forEach((value, key) => {
3665
+ if (value.invalidate) ret.push({
3666
+ id: key,
3667
+ sideEffects: bindingifySideEffects(value.moduleSideEffects)
3668
+ });
3669
+ });
3670
+ return ret;
3671
+ },
3672
+ makeAbsoluteExternalsRelative: bindingifyMakeAbsoluteExternalsRelative(inputOptions.makeAbsoluteExternalsRelative),
3673
+ debug: inputOptions.debug,
3674
+ invalidateJsSideCache: pluginContextData.clear.bind(pluginContextData),
3675
+ markModuleLoaded: pluginContextData.markModuleLoaded.bind(pluginContextData)
3676
+ };
3677
+ }
3678
+ function bindingifyHmr(hmr) {
3679
+ if (hmr) {
3680
+ if (typeof hmr === "boolean") return hmr ? {} : void 0;
3681
+ return hmr;
3682
+ }
3683
+ }
3684
+ function bindingifyExternal(external) {
3685
+ if (external) {
3686
+ if (typeof external === "function") return (id$1, importer, isResolved) => {
3687
+ if (id$1.startsWith("\0")) return false;
3688
+ return external(id$1, importer, isResolved) ?? false;
3689
+ };
3690
+ const externalArr = arraify(external);
3691
+ return (id$1, _importer, _isResolved) => {
3692
+ return externalArr.some((pat) => {
3693
+ if (pat instanceof RegExp) return pat.test(id$1);
3694
+ return id$1 === pat;
3695
+ });
3696
+ };
3697
+ }
3698
+ }
3699
+ function bindingifyResolve(resolve) {
3700
+ if (resolve) {
3701
+ const { alias, extensionAlias,...rest } = resolve;
3702
+ return {
3703
+ alias: alias ? Object.entries(alias).map(([name, replacement]) => ({
3704
+ find: name,
3705
+ replacements: arraify(replacement)
3706
+ })) : void 0,
3707
+ extensionAlias: extensionAlias ? Object.entries(extensionAlias).map(([name, value]) => ({
3708
+ target: name,
3709
+ replacements: value
3710
+ })) : void 0,
3711
+ ...rest
3712
+ };
3713
+ }
3714
+ }
3715
+ function bindingifyInject(inject) {
3716
+ if (inject) return Object.entries(inject).map(([alias, item]) => {
3717
+ if (Array.isArray(item)) {
3718
+ if (item[1] === "*") return {
3719
+ tagNamespace: true,
3720
+ alias,
3721
+ from: item[0]
3722
+ };
3723
+ return {
3724
+ tagNamed: true,
3725
+ alias,
3726
+ from: item[0],
3727
+ imported: item[1]
3728
+ };
3729
+ } else return {
3730
+ tagNamed: true,
3731
+ imported: "default",
3732
+ alias,
3733
+ from: item
3734
+ };
3735
+ });
3736
+ }
3737
+ function bindingifyLogLevel(logLevel) {
3738
+ switch (logLevel) {
3739
+ case "silent": return BindingLogLevel.Silent;
3740
+ case "debug": return BindingLogLevel.Debug;
3741
+ case "warn": return BindingLogLevel.Warn;
3742
+ case "info": return BindingLogLevel.Info;
3743
+ default: throw new Error(`Unexpected log level: ${logLevel}`);
3744
+ }
3745
+ }
3746
+ function bindingifyInput(input) {
3747
+ if (input === void 0) return [];
3748
+ if (typeof input === "string") return [{ import: input }];
3749
+ if (Array.isArray(input)) return input.map((src) => ({ import: src }));
3750
+ return Object.entries(input).map(([name, import_path]) => {
3751
+ return {
3752
+ name,
3753
+ import: import_path
3754
+ };
3755
+ });
3756
+ }
3757
+ function bindingifyJsx(input) {
3758
+ switch (input) {
3759
+ case false: return BindingJsx.Disable;
3760
+ case "react": return BindingJsx.React;
3761
+ case "react-jsx": return BindingJsx.ReactJsx;
3762
+ case "preserve": return BindingJsx.Preserve;
3763
+ default: return void 0;
3764
+ }
3765
+ }
3766
+ function bindingifyWatch(watch$1) {
3767
+ if (watch$1) return {
3768
+ buildDelay: watch$1.buildDelay,
3769
+ skipWrite: watch$1.skipWrite,
3770
+ include: normalizedStringOrRegex(watch$1.include),
3771
+ exclude: normalizedStringOrRegex(watch$1.exclude)
3772
+ };
3773
+ }
3774
+ function bindingifyTreeshakeOptions(config) {
3775
+ if (config === false) return void 0;
3776
+ if (config === true || config === void 0) return { moduleSideEffects: true };
3777
+ let normalizedConfig = {
3778
+ moduleSideEffects: true,
3779
+ annotations: config.annotations,
3780
+ manualPureFunctions: config.manualPureFunctions,
3781
+ unknownGlobalSideEffects: config.unknownGlobalSideEffects
3782
+ };
3783
+ if (config.moduleSideEffects === void 0) normalizedConfig.moduleSideEffects = true;
3784
+ else if (config.moduleSideEffects === "no-external") normalizedConfig.moduleSideEffects = [{
3785
+ external: true,
3786
+ sideEffects: false
3787
+ }, {
3788
+ external: false,
3789
+ sideEffects: true
3790
+ }];
3791
+ else normalizedConfig.moduleSideEffects = config.moduleSideEffects;
3792
+ return normalizedConfig;
3793
+ }
3794
+ function bindingifyMakeAbsoluteExternalsRelative(makeAbsoluteExternalsRelative) {
3795
+ if (makeAbsoluteExternalsRelative === "ifRelativeSource") return { type: "IfRelativeSource" };
3796
+ if (typeof makeAbsoluteExternalsRelative === "boolean") return {
3797
+ type: "Bool",
3798
+ field0: makeAbsoluteExternalsRelative
3799
+ };
3800
+ }
3801
+
3802
+ //#endregion
3803
+ //#region src/utils/plugin/index.ts
3804
+ const isPluginHookName = function() {
3805
+ const PLUGIN_HOOK_NAMES_SET = new Set(ENUMERATED_PLUGIN_HOOK_NAMES);
3806
+ return function isPluginHookName$1(hookName) {
3807
+ return PLUGIN_HOOK_NAMES_SET.has(hookName);
3808
+ };
3809
+ }();
3810
+
3811
+ //#endregion
3812
+ //#region src/utils/compose-js-plugins.ts
3813
+ const unsupportedHookName = [
3814
+ "augmentChunkHash",
3815
+ "generateBundle",
3816
+ "moduleParsed",
3817
+ "onLog",
3818
+ "options",
3819
+ "outputOptions",
3820
+ "renderError",
3821
+ "renderStart",
3822
+ "resolveDynamicImport",
3823
+ "writeBundle"
3824
+ ];
3825
+ const unsupportedHooks = new Set(unsupportedHookName);
3826
+ function isUnsupportedHooks(hookName) {
3827
+ return unsupportedHooks.has(hookName);
3828
+ }
3829
+ function createComposedPlugin(plugins) {
3830
+ const names = [];
3831
+ const batchedHooks = {};
3832
+ plugins.forEach((plugin, index) => {
3833
+ const pluginName = plugin.name || `Anonymous(index: ${index})`;
3834
+ names.push(pluginName);
3835
+ t(plugin).forEach((pluginProp) => {
3836
+ if (isUnsupportedHooks(pluginProp)) throw new Error(`Failed to compose js plugins. Plugin ${pluginName} has an unsupported hook: ${pluginProp}`);
3837
+ if (!isPluginHookName(pluginProp)) return;
3838
+ switch (pluginProp) {
3839
+ case "buildStart": {
3840
+ const handlers = batchedHooks.buildStart ?? [];
3841
+ batchedHooks.buildStart = handlers;
3842
+ if (plugin.buildStart) handlers.push([plugin.buildStart, plugin]);
3843
+ break;
3844
+ }
3845
+ case "load": {
3846
+ const handlers = batchedHooks.load ?? [];
3847
+ batchedHooks.load = handlers;
3848
+ if (plugin.load) handlers.push([plugin.load, plugin]);
3849
+ break;
3850
+ }
3851
+ case "transform": {
3852
+ const handlers = batchedHooks.transform ?? [];
3853
+ batchedHooks.transform = handlers;
3854
+ if (plugin.transform) handlers.push([plugin.transform, plugin]);
3855
+ break;
3856
+ }
3857
+ case "resolveId": {
3858
+ const handlers = batchedHooks.resolveId ?? [];
3859
+ batchedHooks.resolveId = handlers;
3860
+ if (plugin.resolveId) handlers.push([plugin.resolveId, plugin]);
3861
+ break;
3862
+ }
3863
+ case "buildEnd": {
3864
+ const handlers = batchedHooks.buildEnd ?? [];
3865
+ batchedHooks.buildEnd = handlers;
3866
+ if (plugin.buildEnd) handlers.push([plugin.buildEnd, plugin]);
3867
+ break;
3868
+ }
3869
+ case "renderChunk": {
3870
+ const handlers = batchedHooks.renderChunk ?? [];
3871
+ batchedHooks.renderChunk = handlers;
3872
+ if (plugin.renderChunk) handlers.push([plugin.renderChunk, plugin]);
3873
+ break;
3874
+ }
3875
+ case "banner":
3876
+ case "footer":
3877
+ case "intro":
3878
+ case "outro": {
3879
+ const hook = plugin[pluginProp];
3880
+ if (hook) (batchedHooks[pluginProp] ??= []).push([hook, plugin]);
3881
+ break;
3882
+ }
3883
+ case "closeBundle": {
3884
+ const handlers = batchedHooks.closeBundle ?? [];
3885
+ batchedHooks.closeBundle = handlers;
3886
+ if (plugin.closeBundle) handlers.push([plugin.closeBundle, plugin]);
3887
+ break;
3888
+ }
3889
+ case "watchChange": {
3890
+ const handlers = batchedHooks.watchChange ?? [];
3891
+ batchedHooks.watchChange = handlers;
3892
+ if (plugin.watchChange) handlers.push([plugin.watchChange, plugin]);
3893
+ break;
3894
+ }
3895
+ case "closeWatcher": {
3896
+ const handlers = batchedHooks.closeWatcher ?? [];
3897
+ batchedHooks.closeWatcher = handlers;
3898
+ if (plugin.closeWatcher) handlers.push([plugin.closeWatcher, plugin]);
3899
+ break;
3900
+ }
3901
+ default: {}
3902
+ }
3903
+ });
3904
+ });
3905
+ const composed = { name: `Composed(${names.join(", ")})` };
3906
+ const createFixedPluginResolveFnMap = /* @__PURE__ */ new Map();
3907
+ function applyFixedPluginResolveFn(ctx, plugin) {
3908
+ const createFixedPluginResolveFn = createFixedPluginResolveFnMap.get(plugin);
3909
+ if (createFixedPluginResolveFn) ctx.resolve = createFixedPluginResolveFn(ctx, ctx.resolve.bind(ctx));
3910
+ return ctx;
3911
+ }
3912
+ if (batchedHooks.resolveId) {
3913
+ const batchedHandlers = batchedHooks.resolveId;
3914
+ const handlerSymbols = batchedHandlers.map(([_handler, plugin]) => Symbol(plugin.name ?? `Anonymous`));
3915
+ for (let handlerIdx = 0; handlerIdx < batchedHandlers.length; handlerIdx++) {
3916
+ const [_handler, plugin] = batchedHandlers[handlerIdx];
3917
+ const handlerSymbol = handlerSymbols[handlerIdx];
3918
+ const createFixedPluginResolveFn = (ctx, resolve) => {
3919
+ return (source, importer, rawContextResolveOptions) => {
3920
+ const contextResolveOptions = rawContextResolveOptions ?? {};
3921
+ if (contextResolveOptions.skipSelf) {
3922
+ contextResolveOptions[SYMBOL_FOR_RESOLVE_CALLER_THAT_SKIP_SELF] = handlerSymbol;
3923
+ contextResolveOptions.skipSelf = false;
3924
+ }
3925
+ return resolve(source, importer, contextResolveOptions);
3926
+ };
3927
+ };
3928
+ createFixedPluginResolveFnMap.set(plugin, createFixedPluginResolveFn);
3929
+ }
3930
+ composed.resolveId = async function(source, importer, rawHookResolveIdOptions) {
3931
+ const hookResolveIdOptions = rawHookResolveIdOptions;
3932
+ const symbolForCallerThatSkipSelf = hookResolveIdOptions?.[SYMBOL_FOR_RESOLVE_CALLER_THAT_SKIP_SELF];
3933
+ for (let handlerIdx = 0; handlerIdx < batchedHandlers.length; handlerIdx++) {
3934
+ const [handler, plugin] = batchedHandlers[handlerIdx];
3935
+ const handlerSymbol = handlerSymbols[handlerIdx];
3936
+ if (symbolForCallerThatSkipSelf === handlerSymbol) continue;
3937
+ const { handler: handlerFn } = normalizeHook(handler);
3938
+ const result = await handlerFn.call(applyFixedPluginResolveFn(this, plugin), source, importer, rawHookResolveIdOptions);
3939
+ if (!isNullish(result)) return result;
3940
+ }
3941
+ };
3942
+ }
3943
+ t(batchedHooks).forEach((hookName) => {
3944
+ switch (hookName) {
3945
+ case "resolveId": break;
3946
+ case "buildStart": {
3947
+ if (batchedHooks.buildStart) {
3948
+ const batchedHandlers = batchedHooks.buildStart;
3949
+ composed.buildStart = async function(options) {
3950
+ await Promise.all(batchedHandlers.map(([handler, plugin]) => {
3951
+ const { handler: handlerFn } = normalizeHook(handler);
3952
+ return handlerFn.call(applyFixedPluginResolveFn(this, plugin), options);
3953
+ }));
3954
+ };
3955
+ }
3956
+ break;
3957
+ }
3958
+ case "load": {
3959
+ if (batchedHooks.load) {
3960
+ const batchedHandlers = batchedHooks.load;
3961
+ composed.load = async function(id$1) {
3962
+ for (const [handler, plugin] of batchedHandlers) {
3963
+ const { handler: handlerFn } = normalizeHook(handler);
3964
+ const result = await handlerFn.call(applyFixedPluginResolveFn(this, plugin), id$1);
3965
+ if (!isNullish(result)) return result;
3966
+ }
3967
+ };
3968
+ }
3969
+ break;
3970
+ }
3971
+ case "transform": {
3972
+ if (batchedHooks.transform) {
3973
+ const batchedHandlers = batchedHooks.transform;
3974
+ composed.transform = async function(initialCode, id$1, moduleType$1) {
3975
+ let code$1 = initialCode;
3976
+ let moduleSideEffects = void 0;
3977
+ function updateOutput(newCode, newModuleSideEffects) {
3978
+ code$1 = newCode;
3979
+ moduleSideEffects = newModuleSideEffects ?? void 0;
3980
+ }
3981
+ for (const [handler, plugin] of batchedHandlers) {
3982
+ const { handler: handlerFn } = normalizeHook(handler);
3983
+ this.getCombinedSourcemap = () => {
3984
+ throw new Error(`The getCombinedSourcemap is not implement in transform hook at composedJsPlugins`);
3985
+ };
3986
+ const result = await handlerFn.call(applyFixedPluginResolveFn(this, plugin), code$1, id$1, moduleType$1);
3987
+ if (!isNullish(result)) {
3988
+ if (typeof result === "string") updateOutput(result);
3989
+ else if (result.code) updateOutput(result.code, result.moduleSideEffects);
3990
+ }
3991
+ }
3992
+ return {
3993
+ code: code$1,
3994
+ moduleSideEffects
3995
+ };
3996
+ };
3997
+ }
3998
+ break;
3999
+ }
4000
+ case "buildEnd": {
4001
+ if (batchedHooks.buildEnd) {
4002
+ const batchedHandlers = batchedHooks.buildEnd;
4003
+ composed.buildEnd = async function(err) {
4004
+ await Promise.all(batchedHandlers.map(([handler, plugin]) => {
4005
+ const { handler: handlerFn } = normalizeHook(handler);
4006
+ return handlerFn.call(applyFixedPluginResolveFn(this, plugin), err);
4007
+ }));
4008
+ };
4009
+ }
4010
+ break;
4011
+ }
4012
+ case "renderChunk": {
4013
+ if (batchedHooks.renderChunk) {
4014
+ const batchedHandlers = batchedHooks.renderChunk;
4015
+ composed.renderChunk = async function(code$1, chunk, options, meta) {
4016
+ for (const [handler, plugin] of batchedHandlers) {
4017
+ const { handler: handlerFn } = normalizeHook(handler);
4018
+ const result = await handlerFn.call(applyFixedPluginResolveFn(this, plugin), code$1, chunk, options, meta);
4019
+ if (!isNullish(result)) return result;
4020
+ }
4021
+ };
4022
+ }
4023
+ break;
4024
+ }
4025
+ case "banner":
4026
+ case "footer":
4027
+ case "intro":
4028
+ case "outro": {
4029
+ const hooks = batchedHooks[hookName];
4030
+ if (hooks?.length) composed[hookName] = async function(chunk) {
4031
+ const ret = [];
4032
+ for (const [hook, plugin] of hooks) {
4033
+ const { handler } = normalizeHook(hook);
4034
+ ret.push(typeof handler === "string" ? handler : await handler.call(applyFixedPluginResolveFn(this, plugin), chunk));
4035
+ }
4036
+ return ret.join("\n");
4037
+ };
4038
+ break;
4039
+ }
4040
+ case "closeBundle": {
4041
+ if (batchedHooks.closeBundle) {
4042
+ const batchedHandlers = batchedHooks.closeBundle;
4043
+ composed.closeBundle = async function() {
4044
+ await Promise.all(batchedHandlers.map(([handler, plugin]) => {
4045
+ const { handler: handlerFn } = normalizeHook(handler);
4046
+ return handlerFn.call(applyFixedPluginResolveFn(this, plugin));
4047
+ }));
4048
+ };
4049
+ }
4050
+ break;
4051
+ }
4052
+ case "watchChange": {
4053
+ if (batchedHooks.watchChange) {
4054
+ const batchedHandlers = batchedHooks.watchChange;
4055
+ composed.watchChange = async function(id$1, event) {
4056
+ await Promise.all(batchedHandlers.map(([handler, plugin]) => {
4057
+ const { handler: handlerFn } = normalizeHook(handler);
4058
+ return handlerFn.call(applyFixedPluginResolveFn(this, plugin), id$1, event);
4059
+ }));
4060
+ };
4061
+ }
4062
+ break;
4063
+ }
4064
+ case "closeWatcher": {
4065
+ if (batchedHooks.closeWatcher) {
4066
+ const batchedHandlers = batchedHooks.closeWatcher;
4067
+ composed.closeWatcher = async function() {
4068
+ await Promise.all(batchedHandlers.map(([handler, plugin]) => {
4069
+ const { handler: handlerFn } = normalizeHook(handler);
4070
+ return handlerFn.call(applyFixedPluginResolveFn(this, plugin));
4071
+ }));
4072
+ };
4073
+ }
4074
+ break;
4075
+ }
4076
+ default: {}
4077
+ }
4078
+ });
4079
+ return composed;
4080
+ }
4081
+ function isComposablePlugin(plugin) {
4082
+ if (plugin instanceof BuiltinPlugin) return false;
4083
+ if ("_parallel" in plugin) return false;
4084
+ const hasNotComposablePattern = t(plugin).some((hookName) => {
4085
+ if (!isPluginHookName(hookName)) return false;
4086
+ const OK_TO_COMPOSE = false;
4087
+ if (isUnsupportedHooks(hookName)) return !OK_TO_COMPOSE;
4088
+ if (plugin[hookName]) {
4089
+ const { meta } = normalizeHook(plugin[hookName]);
4090
+ if (meta.order === "pre" || meta.order === "post") return !OK_TO_COMPOSE;
4091
+ }
4092
+ return OK_TO_COMPOSE;
4093
+ });
4094
+ if (hasNotComposablePattern) return false;
4095
+ return true;
4096
+ }
4097
+ function composeJsPlugins(plugins) {
4098
+ const newPlugins = [];
4099
+ const toBeComposed = [];
4100
+ plugins.forEach((plugin) => {
4101
+ if (isComposablePlugin(plugin)) toBeComposed.push(plugin);
4102
+ else {
4103
+ if (toBeComposed.length > 0) {
4104
+ if (toBeComposed.length > 1) newPlugins.push(createComposedPlugin(toBeComposed));
4105
+ else newPlugins.push(toBeComposed[0]);
4106
+ toBeComposed.length = 0;
4107
+ }
4108
+ newPlugins.push(plugin);
4109
+ }
4110
+ });
4111
+ if (toBeComposed.length > 0) {
4112
+ if (toBeComposed.length > 1) newPlugins.push(createComposedPlugin(toBeComposed));
4113
+ else newPlugins.push(toBeComposed[0]);
4114
+ toBeComposed.length = 0;
4115
+ }
4116
+ return newPlugins;
4117
+ }
4118
+
4119
+ //#endregion
4120
+ //#region src/utils/initialize-parallel-plugins.ts
4121
+ async function initializeParallelPlugins(plugins) {
4122
+ const pluginInfos = [];
4123
+ for (const [index, plugin] of plugins.entries()) if ("_parallel" in plugin) {
4124
+ const { fileUrl, options } = plugin._parallel;
4125
+ pluginInfos.push({
4126
+ index,
4127
+ fileUrl,
4128
+ options
4129
+ });
4130
+ }
4131
+ if (pluginInfos.length <= 0) return void 0;
4132
+ const count = availableParallelism();
4133
+ const parallelJsPluginRegistry = new ParallelJsPluginRegistry(count);
4134
+ const registryId = parallelJsPluginRegistry.id;
4135
+ const workers = await initializeWorkers(registryId, count, pluginInfos);
4136
+ const stopWorkers = async () => {
4137
+ await Promise.all(workers.map((worker) => worker.terminate()));
4138
+ };
4139
+ return {
4140
+ registry: parallelJsPluginRegistry,
4141
+ stopWorkers
4142
+ };
4143
+ }
4144
+ function initializeWorkers(registryId, count, pluginInfos) {
4145
+ return Promise.all(Array.from({ length: count }, (_, i$1) => initializeWorker(registryId, pluginInfos, i$1)));
4146
+ }
4147
+ async function initializeWorker(registryId, pluginInfos, threadNumber) {
4148
+ const urlString = import.meta.resolve("#parallel-plugin-worker");
4149
+ const workerData$1 = {
4150
+ registryId,
4151
+ pluginInfos,
4152
+ threadNumber
4153
+ };
4154
+ let worker;
4155
+ try {
4156
+ worker = new Worker(new URL(urlString), { workerData: workerData$1 });
4157
+ worker.unref();
4158
+ await new Promise((resolve, reject) => {
4159
+ worker.once("message", async (message) => {
4160
+ if (message.type === "error") reject(message.error);
4161
+ else resolve();
4162
+ });
4163
+ });
4164
+ return worker;
4165
+ } catch (e) {
4166
+ worker?.terminate();
4167
+ throw e;
4168
+ }
4169
+ }
4170
+ const availableParallelism = () => {
4171
+ let availableParallelism$1 = 1;
4172
+ try {
4173
+ availableParallelism$1 = os.availableParallelism();
4174
+ } catch {
4175
+ const cpus = os.cpus();
4176
+ if (Array.isArray(cpus) && cpus.length > 0) availableParallelism$1 = cpus.length;
4177
+ }
4178
+ return Math.min(availableParallelism$1, 8);
4179
+ };
4180
+
4181
+ //#endregion
4182
+ //#region src/utils/create-bundler-option.ts
4183
+ async function createBundlerOptions(inputOptions, outputOptions, watchMode, isClose) {
4184
+ const inputPlugins = await normalizePluginOption(inputOptions.plugins);
4185
+ const outputPlugins = await normalizePluginOption(outputOptions.plugins);
4186
+ const logLevel = inputOptions.logLevel || LOG_LEVEL_INFO;
4187
+ const onLog = getLogger(getObjectPlugins(inputPlugins), getOnLog(inputOptions, logLevel), logLevel, watchMode);
4188
+ if (!isClose) outputOptions = PluginDriver.callOutputOptionsHook([...inputPlugins, ...outputPlugins], outputOptions, onLog, logLevel, watchMode);
4189
+ const normalizedOutputPlugins = await normalizePluginOption(outputOptions.plugins);
4190
+ let plugins = [
4191
+ ...BUILTIN_PLUGINS,
4192
+ ...normalizePlugins(inputPlugins, ANONYMOUS_PLUGIN_PREFIX),
4193
+ ...checkOutputPluginOption(normalizePlugins(normalizedOutputPlugins, ANONYMOUS_OUTPUT_PLUGIN_PREFIX), onLog)
4194
+ ];
4195
+ if (inputOptions.experimental?.enableComposingJsPlugins ?? false) plugins = composeJsPlugins(plugins);
4196
+ const parallelPluginInitResult = await initializeParallelPlugins(plugins);
4197
+ try {
4198
+ const bindingInputOptions = bindingifyInputOptions(plugins, inputOptions, outputOptions, normalizedOutputPlugins, onLog, logLevel, watchMode);
4199
+ const bindingOutputOptions = bindingifyOutputOptions(outputOptions);
4200
+ return {
4201
+ bundlerOptions: {
4202
+ inputOptions: bindingInputOptions,
4203
+ outputOptions: bindingOutputOptions,
4204
+ parallelPluginsRegistry: parallelPluginInitResult?.registry
4205
+ },
4206
+ inputOptions,
4207
+ onLog,
4208
+ stopWorkers: parallelPluginInitResult?.stopWorkers
4209
+ };
4210
+ } catch (e) {
4211
+ await parallelPluginInitResult?.stopWorkers();
4212
+ throw e;
4213
+ }
4214
+ }
4215
+
4216
+ //#endregion
4217
+ //#region src/utils/create-bundler.ts
4218
+ let asyncRuntimeShutdown = false;
4219
+ async function createBundler(inputOptions, outputOptions, isClose) {
4220
+ const option = await createBundlerOptions(inputOptions, outputOptions, false, isClose);
4221
+ if (asyncRuntimeShutdown) startAsyncRuntime();
4222
+ try {
4223
+ return {
4224
+ bundler: new Bundler(option.bundlerOptions),
4225
+ stopWorkers: option.stopWorkers,
4226
+ shutdown: () => {
4227
+ shutdownAsyncRuntime();
4228
+ asyncRuntimeShutdown = true;
4229
+ }
4230
+ };
4231
+ } catch (e) {
4232
+ await option.stopWorkers?.();
4233
+ throw e;
4234
+ }
4235
+ }
4236
+
4237
+ //#endregion
4238
+ //#region src/api/rolldown/rolldown-build.ts
4239
+ Symbol.asyncDispose ??= Symbol("Symbol.asyncDispose");
4240
+ var RolldownBuild = class {
4241
+ #inputOptions;
4242
+ #bundler;
4243
+ constructor(inputOptions) {
4244
+ this.#inputOptions = inputOptions;
4245
+ }
4246
+ get closed() {
4247
+ return this.#bundler?.bundler.closed ?? false;
4248
+ }
4249
+ async #getBundlerWithStopWorker(outputOptions, isClose) {
4250
+ if (this.#bundler) await this.#bundler.stopWorkers?.();
4251
+ return this.#bundler = await createBundler(this.#inputOptions, outputOptions, isClose);
4252
+ }
4253
+ async generate(outputOptions = {}) {
4254
+ validateOption("output", outputOptions);
4255
+ const { bundler } = await this.#getBundlerWithStopWorker(outputOptions);
4256
+ const output = await bundler.generate();
4257
+ return transformToRollupOutput(output);
4258
+ }
4259
+ async write(outputOptions = {}) {
4260
+ validateOption("output", outputOptions);
4261
+ const { bundler } = await this.#getBundlerWithStopWorker(outputOptions);
4262
+ const output = await bundler.write();
4263
+ return transformToRollupOutput(output);
4264
+ }
4265
+ async close() {
4266
+ const { bundler, stopWorkers, shutdown } = await this.#getBundlerWithStopWorker({}, true);
4267
+ await stopWorkers?.();
4268
+ await bundler.close();
4269
+ shutdown();
4270
+ }
4271
+ async [Symbol.asyncDispose]() {
4272
+ await this.close();
4273
+ }
4274
+ async generateHmrPatch(changedFiles) {
4275
+ return this.#bundler?.bundler.generateHmrPatch(changedFiles);
4276
+ }
4277
+ async hmrInvalidate(file, firstInvalidatedBy) {
4278
+ return this.#bundler?.bundler.hmrInvalidate(file, firstInvalidatedBy);
4279
+ }
4280
+ get watchFiles() {
4281
+ return this.#bundler?.bundler.getWatchFiles() ?? Promise.resolve([]);
4282
+ }
4283
+ };
4284
+
4285
+ //#endregion
4286
+ //#region src/api/rolldown/index.ts
4287
+ const rolldown = async (input) => {
4288
+ validateOption("input", input);
4289
+ const inputOptions = await PluginDriver.callOptionsHook(input);
4290
+ return new RolldownBuild(inputOptions);
4291
+ };
4292
+
4293
+ //#endregion
4294
+ //#region src/api/build.ts
4295
+ async function build(options) {
4296
+ if (Array.isArray(options)) return Promise.all(options.map((opts) => build(opts)));
4297
+ else {
4298
+ const { output, write = true,...inputOptions } = options;
4299
+ const build$1 = await rolldown(inputOptions);
4300
+ try {
4301
+ if (write) return await build$1.write(output);
4302
+ else return await build$1.generate(output);
4303
+ } finally {
4304
+ await build$1.close();
4305
+ }
4306
+ }
4307
+ }
4308
+
4309
+ //#endregion
4310
+ //#region src/api/watch/watch-emitter.ts
4311
+ var WatcherEmitter = class {
4312
+ listeners = /* @__PURE__ */ new Map();
4313
+ timer;
4314
+ constructor() {
4315
+ this.timer = setInterval(() => {}, 1e9);
4316
+ }
4317
+ on(event, listener) {
4318
+ const listeners = this.listeners.get(event);
4319
+ if (listeners) listeners.push(listener);
4320
+ else this.listeners.set(event, [listener]);
4321
+ return this;
4322
+ }
4323
+ off(event, listener) {
4324
+ const listeners = this.listeners.get(event);
4325
+ if (listeners) {
4326
+ const index = listeners.indexOf(listener);
4327
+ if (index !== -1) listeners.splice(index, 1);
4328
+ }
4329
+ return this;
4330
+ }
4331
+ async onEvent(event) {
4332
+ const listeners = this.listeners.get(event.eventKind());
4333
+ if (listeners) switch (event.eventKind()) {
4334
+ case "close":
4335
+ case "restart":
4336
+ for (const listener of listeners) await listener();
4337
+ break;
4338
+ case "event":
4339
+ for (const listener of listeners) {
4340
+ const code$1 = event.bundleEventKind();
4341
+ switch (code$1) {
4342
+ case "BUNDLE_END":
4343
+ const { duration, output, result } = event.bundleEndData();
4344
+ await listener({
4345
+ code: "BUNDLE_END",
4346
+ duration,
4347
+ output: [output],
4348
+ result
4349
+ });
4350
+ break;
4351
+ case "ERROR":
4352
+ const data = event.bundleErrorData();
4353
+ await listener({
4354
+ code: "ERROR",
4355
+ error: normalizeErrors(data.error),
4356
+ result: data.result
4357
+ });
4358
+ break;
4359
+ default:
4360
+ await listener({ code: code$1 });
4361
+ break;
4362
+ }
4363
+ }
4364
+ break;
4365
+ case "change":
4366
+ for (const listener of listeners) {
4367
+ const { path: path$1, kind } = event.watchChangeData();
4368
+ await listener(path$1, { event: kind });
4369
+ }
4370
+ break;
4371
+ default: throw new Error(`Unknown event: ${event}`);
4372
+ }
4373
+ }
4374
+ async close() {
4375
+ clearInterval(this.timer);
4376
+ }
4377
+ };
4378
+
4379
+ //#endregion
4380
+ //#region src/api/watch/watcher.ts
4381
+ var Watcher = class {
4382
+ closed;
4383
+ inner;
4384
+ emitter;
4385
+ stopWorkers;
4386
+ constructor(emitter, inner, stopWorkers) {
4387
+ this.closed = false;
4388
+ this.inner = inner;
4389
+ this.emitter = emitter;
4390
+ const originClose = emitter.close.bind(emitter);
4391
+ emitter.close = async () => {
4392
+ await this.close();
4393
+ originClose();
4394
+ };
4395
+ this.stopWorkers = stopWorkers;
4396
+ }
4397
+ async close() {
4398
+ if (this.closed) return;
4399
+ this.closed = true;
4400
+ for (const stop of this.stopWorkers) await stop?.();
4401
+ await this.inner.close();
4402
+ shutdownAsyncRuntime();
4403
+ }
4404
+ start() {
4405
+ process.nextTick(() => this.inner.start(this.emitter.onEvent.bind(this.emitter)));
4406
+ }
4407
+ };
4408
+ async function createWatcher(emitter, input) {
4409
+ const options = arraify(input);
4410
+ const bundlerOptions = await Promise.all(options.map((option) => arraify(option.output || {}).map(async (output) => {
4411
+ const inputOptions = await PluginDriver.callOptionsHook(option, true);
4412
+ return createBundlerOptions(inputOptions, output, true);
4413
+ })).flat());
4414
+ const notifyOptions = getValidNotifyOption(bundlerOptions);
4415
+ const bindingWatcher = new BindingWatcher(bundlerOptions.map((option) => option.bundlerOptions), notifyOptions);
4416
+ const watcher = new Watcher(emitter, bindingWatcher, bundlerOptions.map((option) => option.stopWorkers));
4417
+ watcher.start();
4418
+ }
4419
+ function getValidNotifyOption(bundlerOptions) {
4420
+ let result;
4421
+ for (const option of bundlerOptions) if (option.inputOptions.watch) {
4422
+ const notifyOption = option.inputOptions.watch.notify;
4423
+ if (notifyOption) if (result) {
4424
+ option.onLog(LOG_LEVEL_WARN, logMultiplyNotifyOption());
4425
+ return result;
4426
+ } else result = notifyOption;
4427
+ }
4428
+ }
4429
+
4430
+ //#endregion
4431
+ //#region src/api/watch/index.ts
4432
+ const watch = (input) => {
4433
+ const emitter = new WatcherEmitter();
4434
+ createWatcher(emitter, input);
4435
+ return emitter;
4436
+ };
4437
+
4438
+ //#endregion
4439
+ //#region src/utils/define-config.ts
4440
+ function defineConfig(config) {
4441
+ return config;
4442
+ }
4443
+
4444
+ //#endregion
4445
+ //#region src/index.ts
4446
+ const VERSION = version;
4447
+
4448
+ //#endregion
4449
+ export { BuiltinPlugin, PluginContextData, VERSION, assetPlugin, bindingifyPlugin, build, buildImportAnalysisPlugin, composeJsPlugins, createBundler, defineConfig, description$1 as description, dynamicImportVarsPlugin, getInputCliKeys, getJsonSchema, getOutputCliKeys, handleOutputErrors, importGlobPlugin, isolatedDeclarationPlugin, jsonPlugin, loadFallbackPlugin, manifestPlugin, moduleFederationPlugin, modulePreloadPolyfillPlugin, normalizedStringOrRegex, reporterPlugin, rolldown, validateCliOptions, version, viteResolvePlugin, wasmFallbackPlugin, wasmHelperPlugin, watch, webWorkerPostPlugin };