rolldown 1.0.0-beta.3-commit.e170e6e → 1.0.0-beta.30

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 (149) hide show
  1. package/bin/cli.mjs +2 -0
  2. package/dist/{cjs/cli.cjs → cli.cjs} +620 -620
  3. package/dist/cli.d.cts +1 -0
  4. package/dist/cli.d.mts +1 -0
  5. package/dist/{esm/cli.mjs → cli.mjs} +596 -593
  6. package/dist/config.cjs +12 -0
  7. package/dist/config.d.cts +10 -0
  8. package/dist/config.d.mts +10 -0
  9. package/dist/config.mjs +10 -0
  10. package/dist/experimental-index.cjs +105 -0
  11. package/dist/experimental-index.d.cts +58 -0
  12. package/dist/experimental-index.d.mts +58 -0
  13. package/dist/experimental-index.mjs +82 -0
  14. package/dist/experimental-runtime-types.d.ts +66 -0
  15. package/dist/filter-index.cjs +105 -0
  16. package/dist/filter-index.d.cts +4 -0
  17. package/dist/filter-index.d.mts +4 -0
  18. package/dist/filter-index.mjs +44 -0
  19. package/dist/index.cjs +9 -0
  20. package/dist/index.d.cts +3 -0
  21. package/dist/index.d.mts +3 -0
  22. package/dist/index.mjs +5 -0
  23. package/dist/{cjs/parallel-plugin-worker.cjs → parallel-plugin-worker.cjs} +6 -15
  24. package/dist/parallel-plugin-worker.d.cts +1 -0
  25. package/dist/parallel-plugin-worker.d.mts +1 -0
  26. package/dist/{esm/parallel-plugin-worker.mjs → parallel-plugin-worker.mjs} +5 -13
  27. package/dist/{cjs/parallel-plugin.cjs → parallel-plugin.cjs} +1 -2
  28. package/dist/parallel-plugin.d.cts +14 -0
  29. package/dist/parallel-plugin.d.mts +14 -0
  30. package/dist/{esm/parallel-plugin.mjs → parallel-plugin.mjs} +0 -1
  31. package/dist/parse-ast-index.cjs +4 -0
  32. package/dist/parse-ast-index.d.cts +8 -0
  33. package/dist/parse-ast-index.d.mts +8 -0
  34. package/dist/parse-ast-index.mjs +3 -0
  35. package/dist/shared/binding-BAyrv67G.d.cts +1309 -0
  36. package/dist/shared/binding-DUz1Q2JW.d.mts +1309 -0
  37. package/dist/shared/{chunk-qZFfknuJ.cjs → chunk-DDkG_k5U.cjs} +0 -1
  38. package/dist/shared/define-config-CMH1jWhX.d.cts +1331 -0
  39. package/dist/shared/define-config-D_KKKWbo.d.mts +1331 -0
  40. package/dist/shared/load-config-BWjPkvnW.mjs +119 -0
  41. package/dist/shared/load-config-BtTrX40c.cjs +125 -0
  42. package/dist/shared/misc-CQeo-AFx.mjs +22 -0
  43. package/dist/shared/misc-DksvspN4.cjs +58 -0
  44. package/dist/shared/parse-ast-index-DrqwhzH4.cjs +784 -0
  45. package/dist/shared/parse-ast-index-DyFjvjrb.mjs +656 -0
  46. package/dist/shared/{prompt-CxK9euq3.mjs → prompt-C5jz26Zn.mjs} +241 -240
  47. package/dist/shared/{prompt-ZZScCEWI.cjs → prompt-QNI93ne7.cjs} +245 -245
  48. package/dist/shared/src-CRRyjCYJ.cjs +4573 -0
  49. package/dist/shared/src-DR2upIfp.mjs +4381 -0
  50. package/package.json +69 -69
  51. package/bin/cli.js +0 -2
  52. package/dist/cjs/experimental-index.cjs +0 -85
  53. package/dist/cjs/index.cjs +0 -8
  54. package/dist/cjs/parse-ast-index.cjs +0 -4
  55. package/dist/esm/experimental-index.mjs +0 -57
  56. package/dist/esm/index.mjs +0 -4
  57. package/dist/esm/parse-ast-index.mjs +0 -3
  58. package/dist/shared/parse-ast-index-DIxeQDpE.mjs +0 -674
  59. package/dist/shared/parse-ast-index-Dh_sWnMa.cjs +0 -719
  60. package/dist/shared/src-CLo-BgXK.cjs +0 -3007
  61. package/dist/shared/src-CTS_IQ3m.mjs +0 -2826
  62. package/dist/types/api/build.d.ts +0 -18
  63. package/dist/types/api/experimental.d.ts +0 -7
  64. package/dist/types/api/rolldown/index.d.ts +0 -3
  65. package/dist/types/api/rolldown/rolldown-build.d.ts +0 -13
  66. package/dist/types/api/watch/index.d.ts +0 -3
  67. package/dist/types/api/watch/watch-emitter.d.ts +0 -31
  68. package/dist/types/api/watch/watcher.d.ts +0 -13
  69. package/dist/types/binding.d.ts +0 -1435
  70. package/dist/types/builtin-plugin/alias-plugin.d.ts +0 -10
  71. package/dist/types/builtin-plugin/constructors.d.ts +0 -21
  72. package/dist/types/builtin-plugin/replace-plugin.d.ts +0 -28
  73. package/dist/types/builtin-plugin/transform-plugin.d.ts +0 -9
  74. package/dist/types/builtin-plugin/utils.d.ts +0 -8
  75. package/dist/types/cli/arguments/alias.d.ts +0 -16
  76. package/dist/types/cli/arguments/index.d.ts +0 -15
  77. package/dist/types/cli/arguments/normalize.d.ts +0 -12
  78. package/dist/types/cli/arguments/utils.d.ts +0 -8
  79. package/dist/types/cli/colors.d.ts +0 -11
  80. package/dist/types/cli/commands/bundle.d.ts +0 -3
  81. package/dist/types/cli/commands/help.d.ts +0 -1
  82. package/dist/types/cli/index.d.ts +0 -1
  83. package/dist/types/cli/load-config.d.ts +0 -5
  84. package/dist/types/cli/logger.d.ts +0 -5
  85. package/dist/types/constants/plugin-context.d.ts +0 -7
  86. package/dist/types/constants/plugin.d.ts +0 -45
  87. package/dist/types/experimental-index.d.ts +0 -9
  88. package/dist/types/index.d.ts +0 -30
  89. package/dist/types/log/log-handler.d.ts +0 -4
  90. package/dist/types/log/logger.d.ts +0 -6
  91. package/dist/types/log/logging.d.ts +0 -12
  92. package/dist/types/log/logs.d.ts +0 -18
  93. package/dist/types/options/input-options.d.ts +0 -181
  94. package/dist/types/options/normalized-input-options.d.ts +0 -18
  95. package/dist/types/options/normalized-output-options.d.ts +0 -70
  96. package/dist/types/options/output-options.d.ts +0 -182
  97. package/dist/types/options/watch-options.d.ts +0 -5
  98. package/dist/types/parallel-plugin-worker.d.ts +0 -1
  99. package/dist/types/parallel-plugin.d.ts +0 -1
  100. package/dist/types/parse-ast-index.d.ts +0 -5
  101. package/dist/types/plugin/bindingify-build-hooks.d.ts +0 -10
  102. package/dist/types/plugin/bindingify-hook-filter.d.ts +0 -7
  103. package/dist/types/plugin/bindingify-output-hooks.d.ts +0 -14
  104. package/dist/types/plugin/bindingify-plugin-hook-meta.d.ts +0 -8
  105. package/dist/types/plugin/bindingify-plugin.d.ts +0 -16
  106. package/dist/types/plugin/bindingify-watch-hooks.d.ts +0 -5
  107. package/dist/types/plugin/hook-filter.d.ts +0 -48
  108. package/dist/types/plugin/index.d.ts +0 -134
  109. package/dist/types/plugin/minimal-plugin-context.d.ts +0 -23
  110. package/dist/types/plugin/parallel-plugin-implementation.d.ts +0 -10
  111. package/dist/types/plugin/parallel-plugin.d.ts +0 -9
  112. package/dist/types/plugin/plugin-context-data.d.ts +0 -17
  113. package/dist/types/plugin/plugin-context.d.ts +0 -67
  114. package/dist/types/plugin/plugin-driver.d.ts +0 -8
  115. package/dist/types/plugin/transform-plugin-context.d.ts +0 -28
  116. package/dist/types/types/assert.d.ts +0 -14
  117. package/dist/types/types/config-export.d.ts +0 -5
  118. package/dist/types/types/misc.d.ts +0 -40
  119. package/dist/types/types/module-info.d.ts +0 -15
  120. package/dist/types/types/module-side-effects.d.ts +0 -12
  121. package/dist/types/types/output-bundle.d.ts +0 -4
  122. package/dist/types/types/rolldown-options.d.ts +0 -5
  123. package/dist/types/types/rolldown-output.d.ts +0 -66
  124. package/dist/types/types/schema.d.ts +0 -33
  125. package/dist/types/types/sourcemap.d.ts +0 -14
  126. package/dist/types/types/utils.d.ts +0 -13
  127. package/dist/types/utils/asset-source.d.ts +0 -4
  128. package/dist/types/utils/async-flatten.d.ts +0 -1
  129. package/dist/types/utils/bindingify-input-options.d.ts +0 -7
  130. package/dist/types/utils/bindingify-output-options.d.ts +0 -5
  131. package/dist/types/utils/code-frame.d.ts +0 -1
  132. package/dist/types/utils/compose-js-plugins.d.ts +0 -2
  133. package/dist/types/utils/create-bundler-option.d.ts +0 -11
  134. package/dist/types/utils/create-bundler.d.ts +0 -8
  135. package/dist/types/utils/define-config.d.ts +0 -5
  136. package/dist/types/utils/error.d.ts +0 -2
  137. package/dist/types/utils/initialize-parallel-plugins.d.ts +0 -19
  138. package/dist/types/utils/misc.d.ts +0 -6
  139. package/dist/types/utils/normalize-hook.d.ts +0 -7
  140. package/dist/types/utils/normalize-plugin-option.d.ts +0 -13
  141. package/dist/types/utils/normalize-string-or-regex.d.ts +0 -2
  142. package/dist/types/utils/plugin/index.d.ts +0 -2
  143. package/dist/types/utils/transform-module-info.d.ts +0 -4
  144. package/dist/types/utils/transform-rendered-chunk.d.ts +0 -4
  145. package/dist/types/utils/transform-rendered-module.d.ts +0 -3
  146. package/dist/types/utils/transform-side-effects.d.ts +0 -3
  147. package/dist/types/utils/transform-sourcemap.d.ts +0 -3
  148. package/dist/types/utils/transform-to-rollup-output.d.ts +0 -11
  149. package/dist/types/utils/validator.d.ts +0 -6
@@ -1,2826 +0,0 @@
1
- import { augmentCodeLocation, colors, error, import_binding, logCycleLoading, logInputHookInOutputPlugin, logInvalidLogPosition, logMinifyWarning, logMultiplyNotifyOption, logPluginError, parseAst } from "./parse-ast-index-DIxeQDpE.mjs";
2
- import path from "node:path";
3
- import * as v from "valibot";
4
- import { toJsonSchema } from "@valibot/to-json-schema";
5
- import { Buffer } from "node:buffer";
6
- import { Worker } from "node:worker_threads";
7
- import { availableParallelism } from "node:os";
8
-
9
- //#region src/utils/define-config.ts
10
- function defineConfig(config) {
11
- return config;
12
- }
13
-
14
- //#endregion
15
- //#region src/utils/misc.ts
16
- function arraify(value) {
17
- return Array.isArray(value) ? value : [value];
18
- }
19
- function isNullish(value) {
20
- return value === null || value === void 0;
21
- }
22
- function unimplemented(info) {
23
- if (info) throw new Error(`unimplemented: ${info}`);
24
- throw new Error("unimplemented");
25
- }
26
- function unreachable(info) {
27
- if (info) throw new Error(`unreachable: ${info}`);
28
- throw new Error("unreachable");
29
- }
30
- function unsupported(info) {
31
- throw new Error(`UNSUPPORTED: ${info}`);
32
- }
33
- function noop(..._args) {}
34
-
35
- //#endregion
36
- //#region src/log/logging.ts
37
- const LOG_LEVEL_SILENT = "silent";
38
- const LOG_LEVEL_ERROR = "error";
39
- const LOG_LEVEL_WARN = "warn";
40
- const LOG_LEVEL_INFO = "info";
41
- const LOG_LEVEL_DEBUG = "debug";
42
- const logLevelPriority = {
43
- [LOG_LEVEL_DEBUG]: 0,
44
- [LOG_LEVEL_INFO]: 1,
45
- [LOG_LEVEL_WARN]: 2,
46
- [LOG_LEVEL_SILENT]: 3
47
- };
48
-
49
- //#endregion
50
- //#region src/log/log-handler.ts
51
- const normalizeLog = (log) => typeof log === "string" ? { message: log } : typeof log === "function" ? normalizeLog(log()) : log;
52
- function getLogHandler(level, code, logger, pluginName, logLevel) {
53
- if (logLevelPriority[level] < logLevelPriority[logLevel]) return noop;
54
- return (log, pos) => {
55
- if (pos != null) logger(LOG_LEVEL_WARN, logInvalidLogPosition(pluginName));
56
- log = normalizeLog(log);
57
- if (log.code && !log.pluginCode) log.pluginCode = log.code;
58
- log.code = code;
59
- log.plugin = pluginName;
60
- logger(level, log);
61
- };
62
- }
63
-
64
- //#endregion
65
- //#region src/utils/normalize-hook.ts
66
- function normalizeHook(hook) {
67
- if (typeof hook === "function" || typeof hook === "string") return {
68
- handler: hook,
69
- options: {},
70
- meta: {}
71
- };
72
- if (typeof hook === "object" && hook !== null) {
73
- const { handler, order,...options } = hook;
74
- return {
75
- handler,
76
- options,
77
- meta: { order }
78
- };
79
- }
80
- unreachable("Invalid hook type");
81
- }
82
-
83
- //#endregion
84
- //#region src/log/logger.ts
85
- function getLogger(plugins, onLog, logLevel) {
86
- const minimalPriority = logLevelPriority[logLevel];
87
- const logger = (level, log, skipped = new Set()) => {
88
- const logPriority = logLevelPriority[level];
89
- if (logPriority < minimalPriority) return;
90
- for (const plugin of getSortedPlugins("onLog", plugins)) {
91
- if (skipped.has(plugin)) continue;
92
- const { onLog: pluginOnLog } = plugin;
93
- if (pluginOnLog) {
94
- const getLogHandler$1 = (level$1) => {
95
- if (logLevelPriority[level$1] < minimalPriority) return () => {};
96
- return (log$1) => logger(level$1, normalizeLog(log$1), new Set(skipped).add(plugin));
97
- };
98
- const handler = "handler" in pluginOnLog ? pluginOnLog.handler : pluginOnLog;
99
- if (handler.call({
100
- debug: getLogHandler$1(LOG_LEVEL_DEBUG),
101
- error: (log$1) => error(normalizeLog(log$1)),
102
- info: getLogHandler$1(LOG_LEVEL_INFO),
103
- meta: {
104
- rollupVersion: "4.23.0",
105
- rolldownVersion: VERSION,
106
- watchMode: false
107
- },
108
- warn: getLogHandler$1(LOG_LEVEL_WARN),
109
- pluginName: plugin.name || "unknown"
110
- }, level, log) === false) return;
111
- }
112
- }
113
- onLog(level, log);
114
- };
115
- return logger;
116
- }
117
- const getOnLog = (config, logLevel, printLog = defaultPrintLog) => {
118
- const { onwarn, onLog } = config;
119
- const defaultOnLog = getDefaultOnLog(printLog, onwarn);
120
- if (onLog) {
121
- const minimalPriority = logLevelPriority[logLevel];
122
- return (level, log) => onLog(level, addLogToString(log), (level$1, handledLog) => {
123
- if (level$1 === LOG_LEVEL_ERROR) return error(normalizeLog(handledLog));
124
- if (logLevelPriority[level$1] >= minimalPriority) defaultOnLog(level$1, normalizeLog(handledLog));
125
- });
126
- }
127
- return defaultOnLog;
128
- };
129
- const getDefaultOnLog = (printLog, onwarn) => onwarn ? (level, log) => {
130
- if (level === LOG_LEVEL_WARN) onwarn(addLogToString(log), (warning) => printLog(LOG_LEVEL_WARN, normalizeLog(warning)));
131
- else printLog(level, log);
132
- } : printLog;
133
- const addLogToString = (log) => {
134
- Object.defineProperty(log, "toString", {
135
- value: () => getExtendedLogMessage(log),
136
- writable: true
137
- });
138
- return log;
139
- };
140
- const defaultPrintLog = (level, log) => {
141
- const message = getExtendedLogMessage(log);
142
- switch (level) {
143
- case LOG_LEVEL_WARN: return console.warn(message);
144
- case LOG_LEVEL_DEBUG: return console.debug(message);
145
- default: return console.info(message);
146
- }
147
- };
148
- const getExtendedLogMessage = (log) => {
149
- let prefix = "";
150
- if (log.plugin) prefix += `(${log.plugin} plugin) `;
151
- if (log.loc) prefix += `${relativeId(log.loc.file)} (${log.loc.line}:${log.loc.column}) `;
152
- return prefix + log.message;
153
- };
154
- function relativeId(id) {
155
- if (!path.isAbsolute(id)) return id;
156
- return path.relative(path.resolve(), id);
157
- }
158
-
159
- //#endregion
160
- //#region src/builtin-plugin/utils.ts
161
- function makeBuiltinPluginCallable(plugin) {
162
- let callablePlugin = new import_binding.BindingCallableBuiltinPlugin(bindingifyBuiltInPlugin(plugin));
163
- const wrappedPlugin = plugin;
164
- for (const key in callablePlugin) wrappedPlugin[key] = function(...args) {
165
- return callablePlugin[key](...args);
166
- };
167
- return wrappedPlugin;
168
- }
169
- function bindingifyBuiltInPlugin(plugin) {
170
- return {
171
- __name: plugin.name,
172
- options: plugin._options
173
- };
174
- }
175
-
176
- //#endregion
177
- //#region src/builtin-plugin/constructors.ts
178
- var BuiltinPlugin = class {
179
- constructor(name, _options) {
180
- this.name = name;
181
- this._options = _options;
182
- }
183
- };
184
- function modulePreloadPolyfillPlugin(config) {
185
- return new BuiltinPlugin("builtin:module-preload-polyfill", config);
186
- }
187
- function dynamicImportVarsPlugin() {
188
- return new BuiltinPlugin("builtin:dynamic-import-vars");
189
- }
190
- function importGlobPlugin(config) {
191
- return new BuiltinPlugin("builtin:import-glob", config);
192
- }
193
- function manifestPlugin(config) {
194
- return new BuiltinPlugin("builtin:manifest", config);
195
- }
196
- function wasmHelperPlugin() {
197
- return new BuiltinPlugin("builtin:wasm-helper");
198
- }
199
- function wasmFallbackPlugin() {
200
- return new BuiltinPlugin("builtin:wasm-fallback");
201
- }
202
- function loadFallbackPlugin() {
203
- return new BuiltinPlugin("builtin:load-fallback");
204
- }
205
- function jsonPlugin(config) {
206
- return new BuiltinPlugin("builtin:json", config);
207
- }
208
- function buildImportAnalysisPlugin(config) {
209
- return new BuiltinPlugin("builtin:build-import-analysis", config);
210
- }
211
- function viteResolvePlugin(config) {
212
- const builtinPlugin = new BuiltinPlugin("builtin:vite-resolve", {
213
- ...config,
214
- runtime: process.versions.deno ? "deno" : process.versions.bun ? "bun" : "node"
215
- });
216
- return makeBuiltinPluginCallable(builtinPlugin);
217
- }
218
- function moduleFederationPlugin(config) {
219
- return new BuiltinPlugin("builtin:module-federation", {
220
- ...config,
221
- remotes: config.remotes && Object.entries(config.remotes).map(([name, remote]) => {
222
- if (typeof remote === "string") {
223
- const [entryGlobalName] = remote.split("@");
224
- const entry = remote.replace(entryGlobalName + "@", "");
225
- return {
226
- entry,
227
- name,
228
- entryGlobalName
229
- };
230
- }
231
- return {
232
- ...remote,
233
- name: remote.name ?? name
234
- };
235
- }),
236
- manifest: config.manifest === false ? void 0 : config.manifest === true ? {} : config.manifest
237
- });
238
- }
239
-
240
- //#endregion
241
- //#region src/utils/async-flatten.ts
242
- async function asyncFlatten(array) {
243
- do
244
- array = (await Promise.all(array)).flat(Infinity);
245
- while (array.some((v$1) => v$1?.then));
246
- return array;
247
- }
248
-
249
- //#endregion
250
- //#region src/constants/plugin.ts
251
- const ENUMERATED_INPUT_PLUGIN_HOOK_NAMES = [
252
- "options",
253
- "buildStart",
254
- "resolveId",
255
- "load",
256
- "transform",
257
- "moduleParsed",
258
- "buildEnd",
259
- "onLog",
260
- "resolveDynamicImport",
261
- "closeBundle",
262
- "closeWatcher",
263
- "watchChange"
264
- ];
265
- const ENUMERATED_OUTPUT_PLUGIN_HOOK_NAMES = [
266
- "augmentChunkHash",
267
- "outputOptions",
268
- "renderChunk",
269
- "renderStart",
270
- "renderError",
271
- "writeBundle",
272
- "generateBundle"
273
- ];
274
- const ENUMERATED_PLUGIN_HOOK_NAMES = [
275
- ...ENUMERATED_INPUT_PLUGIN_HOOK_NAMES,
276
- ...ENUMERATED_OUTPUT_PLUGIN_HOOK_NAMES,
277
- "footer",
278
- "banner",
279
- "intro",
280
- "outro"
281
- ];
282
- const DEFINED_HOOK_NAMES = {
283
- [ENUMERATED_PLUGIN_HOOK_NAMES[0]]: ENUMERATED_PLUGIN_HOOK_NAMES[0],
284
- [ENUMERATED_PLUGIN_HOOK_NAMES[1]]: ENUMERATED_PLUGIN_HOOK_NAMES[1],
285
- [ENUMERATED_PLUGIN_HOOK_NAMES[2]]: ENUMERATED_PLUGIN_HOOK_NAMES[2],
286
- [ENUMERATED_PLUGIN_HOOK_NAMES[3]]: ENUMERATED_PLUGIN_HOOK_NAMES[3],
287
- [ENUMERATED_PLUGIN_HOOK_NAMES[4]]: ENUMERATED_PLUGIN_HOOK_NAMES[4],
288
- [ENUMERATED_PLUGIN_HOOK_NAMES[5]]: ENUMERATED_PLUGIN_HOOK_NAMES[5],
289
- [ENUMERATED_PLUGIN_HOOK_NAMES[6]]: ENUMERATED_PLUGIN_HOOK_NAMES[6],
290
- [ENUMERATED_PLUGIN_HOOK_NAMES[7]]: ENUMERATED_PLUGIN_HOOK_NAMES[7],
291
- [ENUMERATED_PLUGIN_HOOK_NAMES[8]]: ENUMERATED_PLUGIN_HOOK_NAMES[8],
292
- [ENUMERATED_PLUGIN_HOOK_NAMES[9]]: ENUMERATED_PLUGIN_HOOK_NAMES[9],
293
- [ENUMERATED_PLUGIN_HOOK_NAMES[10]]: ENUMERATED_PLUGIN_HOOK_NAMES[10],
294
- [ENUMERATED_PLUGIN_HOOK_NAMES[11]]: ENUMERATED_PLUGIN_HOOK_NAMES[11],
295
- [ENUMERATED_PLUGIN_HOOK_NAMES[12]]: ENUMERATED_PLUGIN_HOOK_NAMES[12],
296
- [ENUMERATED_PLUGIN_HOOK_NAMES[13]]: ENUMERATED_PLUGIN_HOOK_NAMES[13],
297
- [ENUMERATED_PLUGIN_HOOK_NAMES[14]]: ENUMERATED_PLUGIN_HOOK_NAMES[14],
298
- [ENUMERATED_PLUGIN_HOOK_NAMES[15]]: ENUMERATED_PLUGIN_HOOK_NAMES[15],
299
- [ENUMERATED_PLUGIN_HOOK_NAMES[16]]: ENUMERATED_PLUGIN_HOOK_NAMES[16],
300
- [ENUMERATED_PLUGIN_HOOK_NAMES[17]]: ENUMERATED_PLUGIN_HOOK_NAMES[17],
301
- [ENUMERATED_PLUGIN_HOOK_NAMES[18]]: ENUMERATED_PLUGIN_HOOK_NAMES[18],
302
- [ENUMERATED_PLUGIN_HOOK_NAMES[19]]: ENUMERATED_PLUGIN_HOOK_NAMES[19],
303
- [ENUMERATED_PLUGIN_HOOK_NAMES[20]]: ENUMERATED_PLUGIN_HOOK_NAMES[20],
304
- [ENUMERATED_PLUGIN_HOOK_NAMES[21]]: ENUMERATED_PLUGIN_HOOK_NAMES[21],
305
- [ENUMERATED_PLUGIN_HOOK_NAMES[22]]: ENUMERATED_PLUGIN_HOOK_NAMES[22]
306
- };
307
-
308
- //#endregion
309
- //#region src/utils/normalize-plugin-option.ts
310
- const normalizePluginOption = async (plugins) => (await asyncFlatten([plugins])).filter(Boolean);
311
- function checkOutputPluginOption(plugins, onLog) {
312
- for (const plugin of plugins) for (const hook of ENUMERATED_INPUT_PLUGIN_HOOK_NAMES) if (hook in plugin) {
313
- delete plugin[hook];
314
- onLog(LOG_LEVEL_WARN, logInputHookInOutputPlugin(plugin.name, hook));
315
- }
316
- return plugins;
317
- }
318
- function normalizePlugins(plugins, anonymousPrefix) {
319
- for (const [index, plugin] of plugins.entries()) {
320
- if ("_parallel" in plugin) continue;
321
- if (plugin instanceof BuiltinPlugin) continue;
322
- if (!plugin.name) plugin.name = `${anonymousPrefix}${index + 1}`;
323
- }
324
- return plugins;
325
- }
326
- const ANONYMOUS_PLUGIN_PREFIX = "at position ";
327
- const ANONYMOUS_OUTPUT_PLUGIN_PREFIX = "at output position ";
328
-
329
- //#endregion
330
- //#region src/plugin/plugin-driver.ts
331
- var PluginDriver = class {
332
- static async callOptionsHook(inputOptions) {
333
- const logLevel = inputOptions.logLevel || LOG_LEVEL_INFO;
334
- const plugins = getSortedPlugins("options", getObjectPlugins(await normalizePluginOption(inputOptions.plugins)));
335
- const logger = getLogger(plugins, getOnLog(inputOptions, logLevel), logLevel);
336
- for (const plugin of plugins) {
337
- const name = plugin.name || "unknown";
338
- const options = plugin.options;
339
- if (options) {
340
- const { handler } = normalizeHook(options);
341
- const result = await handler.call({
342
- debug: getLogHandler(LOG_LEVEL_DEBUG, "PLUGIN_LOG", logger, name, logLevel),
343
- error: (e) => error(logPluginError(normalizeLog(e), name, { hook: "onLog" })),
344
- info: getLogHandler(LOG_LEVEL_INFO, "PLUGIN_LOG", logger, name, logLevel),
345
- meta: {
346
- rollupVersion: "4.23.0",
347
- rolldownVersion: VERSION,
348
- watchMode: false
349
- },
350
- warn: getLogHandler(LOG_LEVEL_WARN, "PLUGIN_WARNING", logger, name, logLevel),
351
- pluginName: name
352
- }, inputOptions);
353
- if (result) inputOptions = result;
354
- }
355
- }
356
- return inputOptions;
357
- }
358
- static callOutputOptionsHook(rawPlugins, outputOptions) {
359
- const sortedPlugins = getSortedPlugins("outputOptions", getObjectPlugins(rawPlugins));
360
- for (const plugin of sortedPlugins) {
361
- const options = plugin.outputOptions;
362
- if (options) {
363
- const { handler } = normalizeHook(options);
364
- const result = handler.call(null, outputOptions);
365
- if (result) outputOptions = result;
366
- }
367
- }
368
- return outputOptions;
369
- }
370
- };
371
- function getObjectPlugins(plugins) {
372
- return plugins.filter((plugin) => {
373
- if (!plugin) return void 0;
374
- if ("_parallel" in plugin) return void 0;
375
- if (plugin instanceof BuiltinPlugin) return void 0;
376
- return plugin;
377
- });
378
- }
379
- function getSortedPlugins(hookName, plugins) {
380
- const pre = [];
381
- const normal = [];
382
- const post = [];
383
- for (const plugin of plugins) {
384
- const hook = plugin[hookName];
385
- if (hook) {
386
- if (typeof hook === "object") {
387
- if (hook.order === "pre") {
388
- pre.push(plugin);
389
- continue;
390
- }
391
- if (hook.order === "post") {
392
- post.push(plugin);
393
- continue;
394
- }
395
- }
396
- normal.push(plugin);
397
- }
398
- }
399
- return [
400
- ...pre,
401
- ...normal,
402
- ...post
403
- ];
404
- }
405
-
406
- //#endregion
407
- //#region src/utils/validator.ts
408
- const StringOrRegExpSchema = v.union([v.string(), v.instance(RegExp)]);
409
- const LogLevelSchema = v.union([
410
- v.literal("debug"),
411
- v.literal("info"),
412
- v.literal("warn")
413
- ]);
414
- const LogLevelOptionSchema = v.union([LogLevelSchema, v.literal("silent")]);
415
- const LogLevelWithErrorSchema = v.union([LogLevelSchema, v.literal("error")]);
416
- const RollupLogSchema = v.any();
417
- const RollupLogWithStringSchema = v.union([RollupLogSchema, v.string()]);
418
- const InputOptionSchema = v.union([
419
- v.string(),
420
- v.array(v.string()),
421
- v.record(v.string(), v.string())
422
- ]);
423
- const ExternalSchema = v.union([
424
- StringOrRegExpSchema,
425
- v.array(StringOrRegExpSchema),
426
- v.pipe(v.function(), v.args(v.tuple([
427
- v.string(),
428
- v.optional(v.string()),
429
- v.boolean()
430
- ])), v.returns(v.nullish(v.boolean())))
431
- ]);
432
- const ModuleTypesSchema = v.record(v.string(), v.union([
433
- v.literal("base64"),
434
- v.literal("binary"),
435
- v.literal("css"),
436
- v.literal("dataurl"),
437
- v.literal("empty"),
438
- v.literal("js"),
439
- v.literal("json"),
440
- v.literal("jsx"),
441
- v.literal("text"),
442
- v.literal("ts"),
443
- v.literal("tsx")
444
- ]));
445
- const JsxOptionsSchema = v.strictObject({
446
- development: v.pipe(v.optional(v.boolean()), v.description("Development specific information")),
447
- factory: v.pipe(v.optional(v.string()), v.description("Jsx element transformation")),
448
- fragment: v.pipe(v.optional(v.string()), v.description("Jsx fragment transformation")),
449
- importSource: v.pipe(v.optional(v.string()), v.description("Import the factory of element and fragment if mode is classic")),
450
- jsxImportSource: v.pipe(v.optional(v.string()), v.description("Import the factory of element and fragment if mode is automatic")),
451
- mode: v.pipe(v.optional(v.union([
452
- v.literal("classic"),
453
- v.literal("automatic"),
454
- v.literal("preserve")
455
- ])), v.description("Jsx transformation mode")),
456
- refresh: v.pipe(v.optional(v.boolean()), v.description("React refresh transformation"))
457
- });
458
- const HelperModeSchema = v.union([v.literal("Runtime"), v.literal("External")]);
459
- const DecoratorOptionSchema = v.object({
460
- legacy: v.optional(v.boolean()),
461
- emitDecoratorMetadata: v.optional(v.boolean())
462
- });
463
- const HelpersSchema = v.object({ mode: v.optional(HelperModeSchema) });
464
- const RewriteImportExtensionsSchema = v.union([
465
- v.literal("rewrite"),
466
- v.literal("remove"),
467
- v.boolean()
468
- ]);
469
- const TypescriptSchema = v.object({
470
- jsxPragma: v.optional(v.string()),
471
- jsxPragmaFrag: v.optional(v.string()),
472
- onlyRemoveTypeImports: v.optional(v.boolean()),
473
- allowNamespaces: v.optional(v.boolean()),
474
- allowDeclareFields: v.optional(v.boolean()),
475
- declaration: v.optional(v.object({
476
- stripInternal: v.optional(v.boolean()),
477
- sourcemap: v.optional(v.boolean())
478
- })),
479
- rewriteImportExtensions: v.optional(RewriteImportExtensionsSchema)
480
- });
481
- const AssumptionsSchema = v.object({
482
- ignoreFunctionLength: v.optional(v.boolean()),
483
- noDocumentAll: v.optional(v.boolean()),
484
- objectRestNoSymbols: v.optional(v.boolean()),
485
- pureGetters: v.optional(v.boolean()),
486
- setPublicClassFields: v.optional(v.boolean())
487
- });
488
- const TransformOptionsSchema = v.object({
489
- assumptions: v.optional(AssumptionsSchema),
490
- typescript: v.optional(TypescriptSchema),
491
- helpers: v.optional(HelpersSchema),
492
- decorators: v.optional(DecoratorOptionSchema)
493
- });
494
- const WatchOptionsSchema = v.strictObject({
495
- chokidar: v.optional(v.never(`The "watch.chokidar" option is deprecated, please use "watch.notify" instead of it`)),
496
- exclude: v.optional(v.union([StringOrRegExpSchema, v.array(StringOrRegExpSchema)])),
497
- include: v.optional(v.union([StringOrRegExpSchema, v.array(StringOrRegExpSchema)])),
498
- notify: v.pipe(v.optional(v.strictObject({
499
- compareContents: v.optional(v.boolean()),
500
- pollInterval: v.optional(v.number())
501
- })), v.description("Notify options")),
502
- skipWrite: v.pipe(v.optional(v.boolean()), v.description("Skip the bundle.write() step")),
503
- buildDelay: v.pipe(v.optional(v.number()), v.description("Throttle watch rebuilds"))
504
- });
505
- const ChecksOptionsSchema = v.strictObject({ circularDependency: v.pipe(v.optional(v.boolean()), v.description("Whether to emit warnings when detecting circular dependencies")) });
506
- const MinifyOptionsSchema = v.strictObject({
507
- mangle: v.boolean(),
508
- compress: v.boolean(),
509
- deadCodeElimination: v.boolean(),
510
- removeWhitespace: v.boolean()
511
- });
512
- const ResolveOptionsSchema = v.strictObject({
513
- alias: v.optional(v.record(v.string(), v.union([v.string(), v.array(v.string())]))),
514
- aliasFields: v.optional(v.array(v.array(v.string()))),
515
- conditionNames: v.optional(v.array(v.string())),
516
- extensionAlias: v.optional(v.record(v.string(), v.array(v.string()))),
517
- exportsFields: v.optional(v.array(v.array(v.string()))),
518
- extensions: v.optional(v.array(v.string())),
519
- mainFields: v.optional(v.array(v.string())),
520
- mainFiles: v.optional(v.array(v.string())),
521
- modules: v.optional(v.array(v.string())),
522
- symlinks: v.optional(v.boolean()),
523
- tsconfigFilename: v.optional(v.string())
524
- });
525
- const TreeshakingOptionsSchema = v.union([v.boolean(), v.looseObject({
526
- annotations: v.optional(v.boolean()),
527
- manualPureFunctions: v.optional(v.array(v.string())),
528
- unknownGlobalSideEffects: v.optional(v.boolean())
529
- })]);
530
- const OnLogSchema = v.pipe(v.function(), v.args(v.tuple([
531
- LogLevelSchema,
532
- RollupLogSchema,
533
- v.pipe(v.function(), v.args(v.tuple([LogLevelWithErrorSchema, RollupLogWithStringSchema])))
534
- ])));
535
- const OnwarnSchema = v.pipe(v.function(), v.args(v.tuple([RollupLogSchema, v.pipe(v.function(), v.args(v.tuple([v.union([RollupLogWithStringSchema, v.pipe(v.function(), v.returns(RollupLogWithStringSchema))])])))])));
536
- const InputOptionsSchema = v.strictObject({
537
- input: v.optional(InputOptionSchema),
538
- plugins: v.optional(v.custom(() => true)),
539
- external: v.optional(ExternalSchema),
540
- resolve: v.optional(ResolveOptionsSchema),
541
- cwd: v.pipe(v.optional(v.string()), v.description("Current working directory")),
542
- platform: v.pipe(v.optional(v.union([
543
- v.literal("browser"),
544
- v.literal("neutral"),
545
- v.literal("node")
546
- ])), v.description(`Platform for which the code should be generated (node, ${colors.underline("browser")}, neutral)`)),
547
- shimMissingExports: v.pipe(v.optional(v.boolean()), v.description("Create shim variables for missing exports")),
548
- treeshake: v.optional(TreeshakingOptionsSchema),
549
- logLevel: v.pipe(v.optional(LogLevelOptionSchema), v.description(`Log level (${colors.dim("silent")}, ${colors.underline(colors.gray("info"))}, debug, ${colors.yellow("warn")})`)),
550
- onLog: v.optional(OnLogSchema),
551
- onwarn: v.optional(OnwarnSchema),
552
- moduleTypes: v.pipe(v.optional(ModuleTypesSchema), v.description("Module types for customized extensions")),
553
- experimental: v.optional(v.strictObject({
554
- disableLiveBindings: v.optional(v.boolean()),
555
- enableComposingJsPlugins: v.optional(v.boolean()),
556
- resolveNewUrlToAsset: v.optional(v.boolean()),
557
- strictExecutionOrder: v.optional(v.boolean()),
558
- hmr: v.optional(v.boolean())
559
- })),
560
- define: v.pipe(v.optional(v.record(v.string(), v.string())), v.description("Define global variables")),
561
- inject: v.optional(v.record(v.string(), v.union([v.string(), v.tuple([v.string(), v.string()])]))),
562
- profilerNames: v.optional(v.boolean()),
563
- jsx: v.optional(v.union([
564
- v.boolean(),
565
- JsxOptionsSchema,
566
- v.string("react"),
567
- v.string("react-jsx"),
568
- v.string("preserve")
569
- ])),
570
- transform: v.optional(TransformOptionsSchema),
571
- watch: v.optional(v.union([WatchOptionsSchema, v.literal(false)])),
572
- dropLabels: v.pipe(v.optional(v.array(v.string())), v.description("Remove labeled statements with these label names")),
573
- checks: v.optional(ChecksOptionsSchema),
574
- keepNames: v.pipe(v.optional(v.boolean()), v.description("Keep function/class name"))
575
- });
576
- const InputCliOverrideSchema = v.strictObject({
577
- external: v.pipe(v.optional(v.array(v.string())), v.description("Comma-separated list of module ids to exclude from the bundle `<module-id>,...`")),
578
- inject: v.pipe(v.optional(v.record(v.string(), v.string())), v.description("Inject import statements on demand")),
579
- treeshake: v.pipe(v.optional(v.boolean()), v.description("enable treeshaking")),
580
- jsx: v.pipe(v.optional(JsxOptionsSchema), v.description("enable jsx"))
581
- });
582
- const InputCliOptionsSchema = v.omit(v.strictObject({
583
- ...InputOptionsSchema.entries,
584
- ...InputCliOverrideSchema.entries
585
- }), [
586
- "input",
587
- "plugins",
588
- "onwarn",
589
- "onLog",
590
- "resolve",
591
- "experimental",
592
- "profilerNames",
593
- "watch"
594
- ]);
595
- var ESTarget = /* @__PURE__ */ function(ESTarget$1) {
596
- ESTarget$1["ES6"] = "es6";
597
- ESTarget$1["ES2015"] = "es2015";
598
- ESTarget$1["ES2016"] = "es2016";
599
- ESTarget$1["ES2017"] = "es2017";
600
- ESTarget$1["ES2018"] = "es2018";
601
- ESTarget$1["ES2019"] = "es2019";
602
- ESTarget$1["ES2020"] = "es2020";
603
- ESTarget$1["ES2021"] = "es2021";
604
- ESTarget$1["ES2022"] = "es2022";
605
- ESTarget$1["ES2023"] = "es2023";
606
- ESTarget$1["ES2024"] = "es2024";
607
- ESTarget$1["ESNext"] = "esnext";
608
- return ESTarget$1;
609
- }(ESTarget || {});
610
- const ModuleFormatSchema = v.union([
611
- v.literal("es"),
612
- v.literal("cjs"),
613
- v.literal("esm"),
614
- v.literal("module"),
615
- v.literal("commonjs"),
616
- v.literal("iife"),
617
- v.literal("umd")
618
- ]);
619
- const AddonFunctionSchema = v.pipe(v.function(), v.args(v.tuple([v.custom(() => true)])), v.returnsAsync(v.unionAsync([v.string(), v.pipeAsync(v.promise(), v.awaitAsync(), v.string())])));
620
- const ChunkFileNamesSchema = v.union([v.string(), v.pipe(v.function(), v.args(v.tuple([v.custom(() => true)])), v.returns(v.string()))]);
621
- const AssetFileNamesSchema = v.union([v.string(), v.pipe(v.function(), v.args(v.tuple([v.custom(() => true)])), v.returns(v.string()))]);
622
- const SanitizeFileNameSchema = v.union([v.boolean(), v.pipe(v.function(), v.args(v.tuple([v.string()])), v.returns(v.string()))]);
623
- const GlobalsFunctionSchema = v.pipe(v.function(), v.args(v.tuple([v.string()])), v.returns(v.string()));
624
- const AdvancedChunksSchema = v.strictObject({
625
- minSize: v.optional(v.number()),
626
- maxSize: v.optional(v.number()),
627
- minModuleSize: v.optional(v.number()),
628
- maxModuleSize: v.optional(v.number()),
629
- minShareCount: v.optional(v.number()),
630
- groups: v.optional(v.array(v.strictObject({
631
- name: v.string(),
632
- test: v.optional(v.union([v.string(), v.instance(RegExp)])),
633
- priority: v.optional(v.number()),
634
- minSize: v.optional(v.number()),
635
- minShareCount: v.optional(v.number()),
636
- maxSize: v.optional(v.number()),
637
- minModuleSize: v.optional(v.number()),
638
- maxModuleSize: v.optional(v.number())
639
- })))
640
- });
641
- const OutputOptionsSchema = v.strictObject({
642
- dir: v.pipe(v.optional(v.string()), v.description("Output directory, defaults to `dist` if `file` is not set")),
643
- file: v.pipe(v.optional(v.string()), v.description("Single output file")),
644
- exports: v.pipe(v.optional(v.union([
645
- v.literal("auto"),
646
- v.literal("named"),
647
- v.literal("default"),
648
- v.literal("none")
649
- ])), v.description(`Specify a export mode (${colors.underline("auto")}, named, default, none)`)),
650
- hashCharacters: v.pipe(v.optional(v.union([
651
- v.literal("base64"),
652
- v.literal("base36"),
653
- v.literal("hex")
654
- ])), v.description("Use the specified character set for file hashes")),
655
- format: v.pipe(v.optional(ModuleFormatSchema), v.description(`Output format of the generated bundle (supports ${colors.underline("esm")}, cjs, and iife)`)),
656
- sourcemap: v.pipe(v.optional(v.union([
657
- v.boolean(),
658
- v.literal("inline"),
659
- v.literal("hidden")
660
- ])), v.description(`Generate sourcemap (\`-s inline\` for inline, or ${colors.bold("pass the `-s` on the last argument if you want to generate `.map` file")})`)),
661
- sourcemapDebugIds: v.pipe(v.optional(v.boolean()), v.description("Inject sourcemap debug IDs")),
662
- sourcemapIgnoreList: v.optional(v.union([v.boolean(), v.custom(() => true)])),
663
- sourcemapPathTransform: v.optional(v.custom(() => true)),
664
- banner: v.optional(v.union([v.string(), AddonFunctionSchema])),
665
- footer: v.optional(v.union([v.string(), AddonFunctionSchema])),
666
- intro: v.optional(v.union([v.string(), AddonFunctionSchema])),
667
- outro: v.optional(v.union([v.string(), AddonFunctionSchema])),
668
- extend: v.pipe(v.optional(v.boolean()), v.description("Extend global variable defined by name in IIFE / UMD formats")),
669
- esModule: v.optional(v.union([v.boolean(), v.literal("if-default-prop")])),
670
- assetFileNames: v.optional(AssetFileNamesSchema),
671
- entryFileNames: v.optional(ChunkFileNamesSchema),
672
- chunkFileNames: v.optional(ChunkFileNamesSchema),
673
- cssEntryFileNames: v.optional(ChunkFileNamesSchema),
674
- cssChunkFileNames: v.optional(ChunkFileNamesSchema),
675
- sanitizeFileName: v.optional(SanitizeFileNameSchema),
676
- minify: v.pipe(v.optional(v.union([
677
- v.boolean(),
678
- v.string("dce-only"),
679
- MinifyOptionsSchema
680
- ])), v.description("Minify the bundled file")),
681
- name: v.pipe(v.optional(v.string()), v.description("Name for UMD / IIFE format outputs")),
682
- globals: v.pipe(v.optional(v.union([v.record(v.string(), v.string()), GlobalsFunctionSchema])), v.description("Global variable of UMD / IIFE dependencies (syntax: `key=value`)")),
683
- externalLiveBindings: v.pipe(v.optional(v.boolean()), v.description("external live bindings")),
684
- inlineDynamicImports: v.pipe(v.optional(v.boolean()), v.description("Inline dynamic imports")),
685
- advancedChunks: v.optional(AdvancedChunksSchema),
686
- comments: v.pipe(v.optional(v.union([v.literal("none"), v.literal("preserve-legal")])), v.description("Control comments in the output")),
687
- target: v.pipe(v.optional(v.enum(ESTarget)), v.description("The JavaScript target environment")),
688
- plugins: v.optional(v.custom(() => true))
689
- });
690
- const getAddonDescription = (placement, wrapper) => {
691
- return `Code to insert the ${colors.bold(placement)} of the bundled file (${colors.bold(wrapper)} the wrapper function)`;
692
- };
693
- const OutputCliOverrideSchema = v.strictObject({
694
- assetFileNames: v.pipe(v.optional(v.string()), v.description("Name pattern for asset files")),
695
- entryFileNames: v.pipe(v.optional(v.string()), v.description("Name pattern for emitted entry chunks")),
696
- chunkFileNames: v.pipe(v.optional(v.string()), v.description("Name pattern for emitted secondary chunks")),
697
- cssEntryFileNames: v.pipe(v.optional(v.string()), v.description("Name pattern for emitted css entry chunks")),
698
- cssChunkFileNames: v.pipe(v.optional(v.string()), v.description("Name pattern for emitted css secondary chunks")),
699
- sanitizeFileName: v.pipe(v.optional(v.boolean()), v.description("Sanitize file name")),
700
- banner: v.pipe(v.optional(v.string()), v.description(getAddonDescription("top", "outside"))),
701
- footer: v.pipe(v.optional(v.string()), v.description(getAddonDescription("bottom", "outside"))),
702
- intro: v.pipe(v.optional(v.string()), v.description(getAddonDescription("top", "inside"))),
703
- outro: v.pipe(v.optional(v.string()), v.description(getAddonDescription("bottom", "inside"))),
704
- esModule: v.pipe(v.optional(v.boolean()), v.description("Always generate `__esModule` marks in non-ESM formats, defaults to `if-default-prop` (use `--no-esModule` to always disable)")),
705
- globals: v.pipe(v.optional(v.record(v.string(), v.string())), v.description("Global variable of UMD / IIFE dependencies (syntax: `key=value`)")),
706
- advancedChunks: v.pipe(v.optional(v.strictObject({
707
- minSize: v.pipe(v.optional(v.number()), v.description("Minimum size of the chunk")),
708
- minShareCount: v.pipe(v.optional(v.number()), v.description("Minimum share count of the chunk"))
709
- })), v.description("Global variable of UMD / IIFE dependencies (syntax: `key=value`)")),
710
- minify: v.pipe(v.optional(v.boolean()), v.description("Minify the bundled file"))
711
- });
712
- const OutputCliOptionsSchema = v.omit(v.strictObject({
713
- ...OutputOptionsSchema.entries,
714
- ...OutputCliOverrideSchema.entries
715
- }), [
716
- "sourcemapIgnoreList",
717
- "sourcemapPathTransform",
718
- "plugins"
719
- ]);
720
- const CliOptionsSchema = v.strictObject({
721
- config: v.pipe(v.optional(v.union([v.string(), v.boolean()])), v.description("Path to the config file (default: `rolldown.config.js`)")),
722
- help: v.pipe(v.optional(v.boolean()), v.description("Show help")),
723
- version: v.pipe(v.optional(v.boolean()), v.description("Show version number")),
724
- watch: v.pipe(v.optional(v.boolean()), v.description("Watch files in bundle and rebuild on changes")),
725
- ...InputCliOptionsSchema.entries,
726
- ...OutputCliOptionsSchema.entries
727
- });
728
- function validateCliOptions(options) {
729
- let parsed = v.safeParse(CliOptionsSchema, options);
730
- return [parsed.output, parsed.issues?.map((issue) => issue.path?.join(", ")).filter((v$1) => v$1 !== void 0)];
731
- }
732
- const inputHelperMsgRecord = { output: { ignored: true } };
733
- const outputHelperMsgRecord = {};
734
- function validateOption(key, options) {
735
- if (process.env.ROLLDOWN_OPTIONS_VALIDATION === "loose") return;
736
- let parsed = v.safeParse(key === "input" ? InputOptionsSchema : OutputOptionsSchema, options);
737
- if (!parsed.success) {
738
- const errors = parsed.issues.map((issue) => {
739
- const issuePaths = issue.path.map((path$1) => path$1.key);
740
- let issueMsg = issue.message;
741
- if (issue.type === "union") {
742
- const subIssue = issue.issues?.find((i) => !(i.type !== issue.received && i.input === issue.input));
743
- if (subIssue) {
744
- if (subIssue.path) issuePaths.push(subIssue.path.map((path$1) => path$1.key));
745
- issueMsg = subIssue.message;
746
- }
747
- }
748
- const stringPath = issuePaths.join(".");
749
- const helper = key === "input" ? inputHelperMsgRecord[stringPath] : outputHelperMsgRecord[stringPath];
750
- if (helper && helper.ignored) return "";
751
- return `- For the "${stringPath}". ${issueMsg}. ${helper ? helper.msg : ""}`;
752
- }).filter(Boolean);
753
- if (errors.length) throw new Error(`Failed validate ${key} options.\n` + errors.join("\n"));
754
- }
755
- }
756
- function getInputCliKeys() {
757
- return v.keyof(InputCliOptionsSchema).options;
758
- }
759
- function getOutputCliKeys() {
760
- return v.keyof(OutputCliOptionsSchema).options;
761
- }
762
- function getJsonSchema() {
763
- return toJsonSchema(CliOptionsSchema);
764
- }
765
-
766
- //#endregion
767
- //#region src/utils/asset-source.ts
768
- function transformAssetSource(bindingAssetSource$1) {
769
- return bindingAssetSource$1.inner;
770
- }
771
- function bindingAssetSource(source) {
772
- return { inner: source };
773
- }
774
-
775
- //#endregion
776
- //#region src/types/sourcemap.ts
777
- function bindingifySourcemap$1(map) {
778
- if (map == null) return;
779
- return { inner: typeof map === "string" ? map : {
780
- file: map.file ?? void 0,
781
- mappings: map.mappings,
782
- sourceRoot: "sourceRoot" in map ? map.sourceRoot ?? void 0 : void 0,
783
- sources: map.sources?.map((s) => s ?? void 0),
784
- sourcesContent: map.sourcesContent?.map((s) => s ?? void 0),
785
- names: map.names,
786
- x_google_ignoreList: map.x_google_ignoreList,
787
- debugId: "debugId" in map ? map.debugId : void 0
788
- } };
789
- }
790
-
791
- //#endregion
792
- //#region src/utils/error.ts
793
- function normalizeErrors(rawErrors) {
794
- const errors = rawErrors.map((e) => e instanceof Error ? e : Object.assign(new Error(), {
795
- kind: e.kind,
796
- message: e.message,
797
- stack: void 0
798
- }));
799
- let summary = `Build failed with ${errors.length} error${errors.length < 2 ? "" : "s"}:\n`;
800
- for (let i = 0; i < errors.length; i++) {
801
- if (i >= 5) {
802
- summary += "\n...";
803
- break;
804
- }
805
- summary += getErrorMessage(errors[i]) + "\n";
806
- }
807
- const wrapper = new Error(summary);
808
- Object.defineProperty(wrapper, "errors", {
809
- configurable: true,
810
- enumerable: true,
811
- get: () => errors,
812
- set: (value) => Object.defineProperty(wrapper, "errors", {
813
- configurable: true,
814
- enumerable: true,
815
- value
816
- })
817
- });
818
- return wrapper;
819
- }
820
- function getErrorMessage(e) {
821
- let s = "";
822
- if (e.plugin) s += `[plugin ${e.plugin}]`;
823
- const id = e.id ?? e.loc?.file;
824
- if (id) {
825
- s += " " + id;
826
- if (e.loc) s += `:${e.loc.line}:${e.loc.column}`;
827
- }
828
- if (s) s += "\n";
829
- const message = `${e.name ?? "Error"}: ${e.message}`;
830
- s += message;
831
- if (e.frame) s = joinNewLine(s, e.frame);
832
- if (e.stack) s = joinNewLine(s, e.stack.replace(message, ""));
833
- return s;
834
- }
835
- function joinNewLine(s1, s2) {
836
- return s1.replace(/\n+$/, "") + "\n" + s2.replace(/^\n+/, "");
837
- }
838
-
839
- //#endregion
840
- //#region src/utils/transform-rendered-module.ts
841
- function transformToRenderedModule(bindingRenderedModule) {
842
- return {
843
- get code() {
844
- return bindingRenderedModule.code;
845
- },
846
- get renderedLength() {
847
- return bindingRenderedModule.code?.length || 0;
848
- },
849
- get renderedExports() {
850
- return bindingRenderedModule.renderedExports;
851
- }
852
- };
853
- }
854
-
855
- //#endregion
856
- //#region src/utils/transform-rendered-chunk.ts
857
- function transformRenderedChunk(chunk) {
858
- return {
859
- get name() {
860
- return chunk.name;
861
- },
862
- get isEntry() {
863
- return chunk.isEntry;
864
- },
865
- get isDynamicEntry() {
866
- return chunk.isDynamicEntry;
867
- },
868
- get facadeModuleId() {
869
- return chunk.facadeModuleId;
870
- },
871
- get moduleIds() {
872
- return chunk.moduleIds;
873
- },
874
- get exports() {
875
- return chunk.exports;
876
- },
877
- get fileName() {
878
- return chunk.fileName;
879
- },
880
- get imports() {
881
- return chunk.imports;
882
- },
883
- get dynamicImports() {
884
- return chunk.dynamicImports;
885
- },
886
- get modules() {
887
- return transformChunkModules(chunk.modules);
888
- }
889
- };
890
- }
891
- function transformChunkModules(modules) {
892
- const result = {};
893
- for (let i = 0; i < modules.values.length; i++) {
894
- let key = modules.keys[i];
895
- const mod = modules.values[i];
896
- result[key] = transformToRenderedModule(mod);
897
- }
898
- return result;
899
- }
900
-
901
- //#endregion
902
- //#region src/utils/transform-to-rollup-output.ts
903
- function transformToRollupSourceMap(map) {
904
- const parsed = JSON.parse(map);
905
- const obj = {
906
- ...parsed,
907
- toString() {
908
- return JSON.stringify(obj);
909
- },
910
- toUrl() {
911
- return `data:application/json;charset=utf-8;base64,${Buffer.from(obj.toString(), "utf-8").toString("base64")}`;
912
- }
913
- };
914
- return obj;
915
- }
916
- function transformToRollupOutputChunk(bindingChunk, changed) {
917
- const chunk = {
918
- type: "chunk",
919
- get code() {
920
- return bindingChunk.code;
921
- },
922
- fileName: bindingChunk.fileName,
923
- name: bindingChunk.name,
924
- get modules() {
925
- return transformChunkModules(bindingChunk.modules);
926
- },
927
- get imports() {
928
- return bindingChunk.imports;
929
- },
930
- get dynamicImports() {
931
- return bindingChunk.dynamicImports;
932
- },
933
- exports: bindingChunk.exports,
934
- isEntry: bindingChunk.isEntry,
935
- facadeModuleId: bindingChunk.facadeModuleId || null,
936
- isDynamicEntry: bindingChunk.isDynamicEntry,
937
- get moduleIds() {
938
- return bindingChunk.moduleIds;
939
- },
940
- get map() {
941
- return bindingChunk.map ? transformToRollupSourceMap(bindingChunk.map) : null;
942
- },
943
- sourcemapFileName: bindingChunk.sourcemapFileName || null,
944
- preliminaryFileName: bindingChunk.preliminaryFileName
945
- };
946
- const cache = {};
947
- return new Proxy(chunk, {
948
- get(target, p) {
949
- if (p in cache) return cache[p];
950
- return target[p];
951
- },
952
- set(target, p, newValue) {
953
- cache[p] = newValue;
954
- changed?.updated.add(bindingChunk.fileName);
955
- return true;
956
- },
957
- has(target, p) {
958
- if (p in cache) return true;
959
- return p in target;
960
- }
961
- });
962
- }
963
- function transformToRollupOutputAsset(bindingAsset, changed) {
964
- const asset = {
965
- type: "asset",
966
- fileName: bindingAsset.fileName,
967
- originalFileName: bindingAsset.originalFileName || null,
968
- originalFileNames: bindingAsset.originalFileNames,
969
- get source() {
970
- return transformAssetSource(bindingAsset.source);
971
- },
972
- name: bindingAsset.name ?? void 0,
973
- names: bindingAsset.names
974
- };
975
- const cache = {};
976
- return new Proxy(asset, {
977
- get(target, p) {
978
- if (p in cache) return cache[p];
979
- return target[p];
980
- },
981
- set(target, p, newValue) {
982
- cache[p] = newValue;
983
- changed?.updated.add(bindingAsset.fileName);
984
- return true;
985
- }
986
- });
987
- }
988
- function transformToRollupOutput(output, changed) {
989
- handleOutputErrors(output);
990
- const { chunks, assets } = output;
991
- return { output: [...chunks.map((chunk) => transformToRollupOutputChunk(chunk, changed)), ...assets.map((asset) => transformToRollupOutputAsset(asset, changed))] };
992
- }
993
- function handleOutputErrors(output) {
994
- const rawErrors = output.errors;
995
- if (rawErrors.length > 0) throw normalizeErrors(rawErrors);
996
- }
997
- function transformToOutputBundle(output, changed) {
998
- const bundle = Object.fromEntries(transformToRollupOutput(output, changed).output.map((item) => [item.fileName, item]));
999
- return new Proxy(bundle, { deleteProperty(target, property) {
1000
- if (typeof property === "string") changed.deleted.add(property);
1001
- return true;
1002
- } });
1003
- }
1004
- function collectChangedBundle(changed, bundle) {
1005
- const assets = [];
1006
- const chunks = [];
1007
- for (const key in bundle) {
1008
- if (changed.deleted.has(key) || !changed.updated.has(key)) continue;
1009
- const item = bundle[key];
1010
- if (item.type === "asset") assets.push({
1011
- filename: item.fileName,
1012
- originalFileNames: item.originalFileNames,
1013
- source: bindingAssetSource(item.source),
1014
- names: item.names
1015
- });
1016
- else chunks.push({
1017
- code: item.code,
1018
- filename: item.fileName,
1019
- name: item.name,
1020
- isEntry: item.isEntry,
1021
- exports: item.exports,
1022
- modules: {},
1023
- imports: item.imports,
1024
- dynamicImports: item.dynamicImports,
1025
- facadeModuleId: item.facadeModuleId || void 0,
1026
- isDynamicEntry: item.isDynamicEntry,
1027
- moduleIds: item.moduleIds,
1028
- map: bindingifySourcemap$1(item.map),
1029
- sourcemapFilename: item.sourcemapFileName || void 0,
1030
- preliminaryFilename: item.preliminaryFileName
1031
- });
1032
- }
1033
- return {
1034
- assets,
1035
- chunks,
1036
- deleted: Array.from(changed.deleted)
1037
- };
1038
- }
1039
-
1040
- //#endregion
1041
- //#region src/utils/transform-sourcemap.ts
1042
- function isEmptySourcemapFiled(array) {
1043
- if (!array) return true;
1044
- if (array.length === 0 || !array[0]) return true;
1045
- return false;
1046
- }
1047
- function normalizeTransformHookSourcemap(id, originalCode, rawMap) {
1048
- if (!rawMap) return;
1049
- let map = typeof rawMap === "object" ? rawMap : JSON.parse(rawMap);
1050
- if (isEmptySourcemapFiled(map.sourcesContent)) map.sourcesContent = [originalCode];
1051
- if (isEmptySourcemapFiled(map.sources) || map.sources && map.sources.length === 1 && map.sources[0] !== id) map.sources = [id];
1052
- return map;
1053
- }
1054
-
1055
- //#endregion
1056
- //#region src/utils/transform-module-info.ts
1057
- function transformModuleInfo(info, option) {
1058
- return {
1059
- get ast() {
1060
- return unsupported("ModuleInfo#ast");
1061
- },
1062
- get code() {
1063
- return info.code;
1064
- },
1065
- id: info.id,
1066
- importers: info.importers,
1067
- dynamicImporters: info.dynamicImporters,
1068
- importedIds: info.importedIds,
1069
- dynamicallyImportedIds: info.dynamicallyImportedIds,
1070
- exports: info.exports,
1071
- isEntry: info.isEntry,
1072
- ...option
1073
- };
1074
- }
1075
-
1076
- //#endregion
1077
- //#region src/plugin/minimal-plugin-context.ts
1078
- var MinimalPluginContextImpl = class {
1079
- info;
1080
- warn;
1081
- debug;
1082
- meta;
1083
- constructor(onLog, logLevel, pluginName) {
1084
- this.pluginName = pluginName;
1085
- this.debug = getLogHandler(LOG_LEVEL_DEBUG, "PLUGIN_LOG", onLog, pluginName, logLevel);
1086
- this.info = getLogHandler(LOG_LEVEL_INFO, "PLUGIN_LOG", onLog, pluginName, logLevel);
1087
- this.warn = getLogHandler(LOG_LEVEL_WARN, "PLUGIN_WARNING", onLog, pluginName, logLevel);
1088
- this.meta = {
1089
- rollupVersion: "4.23.0",
1090
- rolldownVersion: VERSION,
1091
- watchMode: false
1092
- };
1093
- }
1094
- error(e) {
1095
- return error(logPluginError(normalizeLog(e), this.pluginName));
1096
- }
1097
- };
1098
-
1099
- //#endregion
1100
- //#region src/utils/transform-side-effects.ts
1101
- function bindingifySideEffects(sideEffects) {
1102
- switch (sideEffects) {
1103
- case true: return import_binding.BindingHookSideEffects.True;
1104
- case false: return import_binding.BindingHookSideEffects.False;
1105
- case "no-treeshake": return import_binding.BindingHookSideEffects.NoTreeshake;
1106
- case null:
1107
- case void 0: return void 0;
1108
- default: throw new Error(`Unexpected side effects: ${sideEffects}`);
1109
- }
1110
- }
1111
-
1112
- //#endregion
1113
- //#region src/plugin/plugin-context.ts
1114
- var PluginContextImpl = class extends MinimalPluginContextImpl {
1115
- getModuleInfo;
1116
- constructor(outputOptions, context, plugin, data, onLog, logLevel, currentLoadingModule) {
1117
- super(onLog, logLevel, plugin.name);
1118
- this.outputOptions = outputOptions;
1119
- this.context = context;
1120
- this.data = data;
1121
- this.onLog = onLog;
1122
- this.currentLoadingModule = currentLoadingModule;
1123
- this.getModuleInfo = (id) => this.data.getModuleInfo(id, context);
1124
- }
1125
- async load(options) {
1126
- const id = options.id;
1127
- if (id === this.currentLoadingModule) this.onLog(LOG_LEVEL_WARN, logCycleLoading(this.pluginName, this.currentLoadingModule));
1128
- const moduleInfo = this.data.getModuleInfo(id, this.context);
1129
- if (moduleInfo && moduleInfo.code !== null) return moduleInfo;
1130
- const rawOptions = {
1131
- meta: options.meta || {},
1132
- moduleSideEffects: options.moduleSideEffects || null,
1133
- invalidate: false
1134
- };
1135
- this.data.updateModuleOption(id, rawOptions);
1136
- async function createLoadModulePromise(context, data) {
1137
- const loadPromise = data.loadModulePromiseMap.get(id);
1138
- if (loadPromise) return loadPromise;
1139
- let resolveFn;
1140
- const promise = new Promise((resolve, _) => {
1141
- resolveFn = resolve;
1142
- });
1143
- data.loadModulePromiseMap.set(id, promise);
1144
- try {
1145
- await context.load(id, bindingifySideEffects(options.moduleSideEffects), resolveFn);
1146
- } finally {
1147
- data.loadModulePromiseMap.delete(id);
1148
- }
1149
- return promise;
1150
- }
1151
- await createLoadModulePromise(this.context, this.data);
1152
- return this.data.getModuleInfo(id, this.context);
1153
- }
1154
- async resolve(source, importer, options) {
1155
- let receipt = void 0;
1156
- if (options != null) receipt = this.data.saveResolveOptions(options);
1157
- const res = await this.context.resolve(source, importer, {
1158
- custom: receipt,
1159
- skipSelf: options?.skipSelf
1160
- });
1161
- if (receipt != null) this.data.removeSavedResolveOptions(receipt);
1162
- if (res == null) return null;
1163
- const info = this.data.getModuleOption(res.id) || {};
1164
- return {
1165
- ...res,
1166
- ...info
1167
- };
1168
- }
1169
- emitFile = (file) => {
1170
- if (file.type === "prebuilt-chunk") return unimplemented("PluginContext.emitFile with type prebuilt-chunk");
1171
- if (file.type === "chunk") return this.context.emitChunk(file);
1172
- const fnSanitizedFileName = file.fileName || typeof this.outputOptions.sanitizeFileName !== "function" ? void 0 : this.outputOptions.sanitizeFileName(file.name || "asset");
1173
- const filename = file.fileName ? void 0 : this.getAssetFileNames(file);
1174
- return this.context.emitFile({
1175
- ...file,
1176
- originalFileName: file.originalFileName || void 0,
1177
- source: bindingAssetSource(file.source)
1178
- }, filename, fnSanitizedFileName);
1179
- };
1180
- getAssetFileNames(file) {
1181
- if (typeof this.outputOptions.assetFileNames === "function") return this.outputOptions.assetFileNames({
1182
- names: file.name ? [file.name] : [],
1183
- originalFileNames: file.originalFileName ? [file.originalFileName] : [],
1184
- source: file.source,
1185
- type: "asset"
1186
- });
1187
- }
1188
- getFileName(referenceId) {
1189
- return this.context.getFileName(referenceId);
1190
- }
1191
- getModuleIds() {
1192
- return this.data.getModuleIds(this.context);
1193
- }
1194
- addWatchFile(id) {
1195
- this.context.addWatchFile(id);
1196
- }
1197
- parse(input, options) {
1198
- return parseAst(input, options);
1199
- }
1200
- };
1201
-
1202
- //#endregion
1203
- //#region src/plugin/transform-plugin-context.ts
1204
- var TransformPluginContextImpl = class extends PluginContextImpl {
1205
- constructor(outputOptions, context, plugin, data, inner, moduleId, moduleSource, onLog, LogLevelOption) {
1206
- super(outputOptions, context, plugin, data, onLog, LogLevelOption, moduleId);
1207
- this.inner = inner;
1208
- this.moduleId = moduleId;
1209
- this.moduleSource = moduleSource;
1210
- const getLogHandler$1 = (handler) => (log, pos) => {
1211
- log = normalizeLog(log);
1212
- if (pos) augmentCodeLocation(log, pos, moduleSource, moduleId);
1213
- log.id = moduleId;
1214
- log.hook = "transform";
1215
- handler(log);
1216
- };
1217
- this.debug = getLogHandler$1(this.debug);
1218
- this.warn = getLogHandler$1(this.warn);
1219
- this.info = getLogHandler$1(this.info);
1220
- }
1221
- error(e, pos) {
1222
- if (typeof e === "string") e = { message: e };
1223
- if (pos) augmentCodeLocation(e, pos, this.moduleSource, this.moduleId);
1224
- e.id = this.moduleId;
1225
- e.hook = "transform";
1226
- return error(logPluginError(normalizeLog(e), this.pluginName));
1227
- }
1228
- getCombinedSourcemap() {
1229
- return JSON.parse(this.inner.getCombinedSourcemap());
1230
- }
1231
- };
1232
-
1233
- //#endregion
1234
- //#region src/plugin/bindingify-plugin-hook-meta.ts
1235
- function bindingifyPluginHookMeta(options) {
1236
- return { order: bindingPluginOrder(options.order) };
1237
- }
1238
- function bindingPluginOrder(order) {
1239
- switch (order) {
1240
- case "post": return import_binding.BindingPluginOrder.Post;
1241
- case "pre": return import_binding.BindingPluginOrder.Pre;
1242
- case null:
1243
- case void 0: return void 0;
1244
- default: throw new Error(`Unknown plugin order: ${order}`);
1245
- }
1246
- }
1247
-
1248
- //#endregion
1249
- //#region src/constants/plugin-context.ts
1250
- const SYMBOL_FOR_RESOLVE_CALLER_THAT_SKIP_SELF = Symbol("plugin-context-resolve-caller");
1251
-
1252
- //#endregion
1253
- //#region src/plugin/bindingify-hook-filter.ts
1254
- function bindingifyStringFilter(matcher) {
1255
- if (typeof matcher === "string" || matcher instanceof RegExp) return { include: [matcher] };
1256
- if (Array.isArray(matcher)) return { include: matcher };
1257
- return {
1258
- include: matcher.include ? arraify(matcher.include) : void 0,
1259
- exclude: matcher.exclude ? arraify(matcher.exclude) : void 0
1260
- };
1261
- }
1262
- function bindingifyResolveIdFilter(filterOption) {
1263
- return filterOption?.id ? bindingifyStringFilter(filterOption.id) : void 0;
1264
- }
1265
- function bindingifyLoadFilter(filterOption) {
1266
- return filterOption?.id ? bindingifyStringFilter(filterOption.id) : void 0;
1267
- }
1268
- function bindingifyTransformFilter(filterOption) {
1269
- if (!filterOption) return void 0;
1270
- const { id, code, moduleType } = filterOption;
1271
- let moduleTypeRet;
1272
- if (moduleType) if (Array.isArray(moduleType)) moduleTypeRet = moduleType;
1273
- else moduleTypeRet = moduleType.include;
1274
- return {
1275
- id: id ? bindingifyStringFilter(id) : void 0,
1276
- code: code ? bindingifyStringFilter(code) : void 0,
1277
- moduleType: moduleTypeRet
1278
- };
1279
- }
1280
-
1281
- //#endregion
1282
- //#region src/options/normalized-input-options.ts
1283
- var NormalizedInputOptionsImpl = class {
1284
- inner;
1285
- constructor(inner, onLog) {
1286
- this.onLog = onLog;
1287
- this.inner = inner;
1288
- }
1289
- get shimMissingExports() {
1290
- return this.inner.shimMissingExports;
1291
- }
1292
- get input() {
1293
- return this.inner.input;
1294
- }
1295
- get cwd() {
1296
- return this.inner.cwd ?? void 0;
1297
- }
1298
- get platform() {
1299
- return this.inner.platform;
1300
- }
1301
- };
1302
-
1303
- //#endregion
1304
- //#region src/plugin/bindingify-build-hooks.ts
1305
- function bindingifyBuildStart(args) {
1306
- const hook = args.plugin.buildStart;
1307
- if (!hook) return {};
1308
- const { handler, meta } = normalizeHook(hook);
1309
- return {
1310
- plugin: async (ctx, opts) => {
1311
- await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), new NormalizedInputOptionsImpl(opts, args.onLog));
1312
- },
1313
- meta: bindingifyPluginHookMeta(meta)
1314
- };
1315
- }
1316
- function bindingifyBuildEnd(args) {
1317
- const hook = args.plugin.buildEnd;
1318
- if (!hook) return {};
1319
- const { handler, meta } = normalizeHook(hook);
1320
- return {
1321
- plugin: async (ctx, err) => {
1322
- await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), err ? normalizeErrors(err) : void 0);
1323
- },
1324
- meta: bindingifyPluginHookMeta(meta)
1325
- };
1326
- }
1327
- function bindingifyResolveId(args) {
1328
- const hook = args.plugin.resolveId;
1329
- if (!hook) return {};
1330
- const { handler, meta, options } = normalizeHook(hook);
1331
- return {
1332
- plugin: async (ctx, specifier, importer, extraOptions) => {
1333
- const contextResolveOptions = extraOptions.custom != null ? args.pluginContextData.getSavedResolveOptions(extraOptions.custom) : void 0;
1334
- const newExtraOptions = {
1335
- ...extraOptions,
1336
- custom: contextResolveOptions?.custom,
1337
- [SYMBOL_FOR_RESOLVE_CALLER_THAT_SKIP_SELF]: contextResolveOptions?.[SYMBOL_FOR_RESOLVE_CALLER_THAT_SKIP_SELF]
1338
- };
1339
- const ret = await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), specifier, importer ?? void 0, newExtraOptions);
1340
- if (ret == null) return;
1341
- if (ret === false) return {
1342
- id: specifier,
1343
- external: true
1344
- };
1345
- if (typeof ret === "string") return { id: ret };
1346
- let exist = args.pluginContextData.updateModuleOption(ret.id, {
1347
- meta: ret.meta || {},
1348
- moduleSideEffects: ret.moduleSideEffects ?? null,
1349
- invalidate: false
1350
- });
1351
- return {
1352
- id: ret.id,
1353
- external: ret.external,
1354
- sideEffects: bindingifySideEffects(exist.moduleSideEffects)
1355
- };
1356
- },
1357
- meta: bindingifyPluginHookMeta(meta),
1358
- filter: bindingifyResolveIdFilter(options.filter)
1359
- };
1360
- }
1361
- function bindingifyResolveDynamicImport(args) {
1362
- const hook = args.plugin.resolveDynamicImport;
1363
- if (!hook) return {};
1364
- const { handler, meta } = normalizeHook(hook);
1365
- return {
1366
- plugin: async (ctx, specifier, importer) => {
1367
- const ret = await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), specifier, importer ?? void 0);
1368
- if (ret == null) return;
1369
- if (ret === false) return {
1370
- id: specifier,
1371
- external: true
1372
- };
1373
- if (typeof ret === "string") return { id: ret };
1374
- const result = {
1375
- id: ret.id,
1376
- external: ret.external
1377
- };
1378
- if (ret.moduleSideEffects !== null) result.sideEffects = bindingifySideEffects(ret.moduleSideEffects);
1379
- args.pluginContextData.updateModuleOption(ret.id, {
1380
- meta: ret.meta || {},
1381
- moduleSideEffects: ret.moduleSideEffects || null,
1382
- invalidate: false
1383
- });
1384
- return result;
1385
- },
1386
- meta: bindingifyPluginHookMeta(meta)
1387
- };
1388
- }
1389
- function bindingifyTransform(args) {
1390
- const hook = args.plugin.transform;
1391
- if (!hook) return {};
1392
- const { handler, meta, options } = normalizeHook(hook);
1393
- return {
1394
- plugin: async (ctx, code, id, meta$1) => {
1395
- const ret = await handler.call(new TransformPluginContextImpl(args.outputOptions, ctx.inner(), args.plugin, args.pluginContextData, ctx, id, code, args.onLog, args.logLevel), code, id, meta$1);
1396
- if (ret == null) return void 0;
1397
- if (typeof ret === "string") return { code: ret };
1398
- let moduleOption = args.pluginContextData.updateModuleOption(id, {
1399
- meta: ret.meta ?? {},
1400
- moduleSideEffects: ret.moduleSideEffects ?? null,
1401
- invalidate: false
1402
- });
1403
- return {
1404
- code: ret.code,
1405
- map: bindingifySourcemap$1(normalizeTransformHookSourcemap(id, code, ret.map)),
1406
- sideEffects: bindingifySideEffects(moduleOption.moduleSideEffects),
1407
- moduleType: ret.moduleType
1408
- };
1409
- },
1410
- meta: bindingifyPluginHookMeta(meta),
1411
- filter: bindingifyTransformFilter(options.filter)
1412
- };
1413
- }
1414
- function bindingifyLoad(args) {
1415
- const hook = args.plugin.load;
1416
- if (!hook) return {};
1417
- const { handler, meta, options } = normalizeHook(hook);
1418
- return {
1419
- plugin: async (ctx, id) => {
1420
- const ret = await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel, id), id);
1421
- if (ret == null) return;
1422
- if (typeof ret === "string") return { code: ret };
1423
- let moduleOption = args.pluginContextData.updateModuleOption(id, {
1424
- meta: ret.meta || {},
1425
- moduleSideEffects: ret.moduleSideEffects ?? null,
1426
- invalidate: false
1427
- });
1428
- let map = preProcessSourceMap(ret, id);
1429
- return {
1430
- code: ret.code,
1431
- map: bindingifySourcemap$1(map),
1432
- moduleType: ret.moduleType,
1433
- sideEffects: bindingifySideEffects(moduleOption.moduleSideEffects)
1434
- };
1435
- },
1436
- meta: bindingifyPluginHookMeta(meta),
1437
- filter: bindingifyLoadFilter(options.filter)
1438
- };
1439
- }
1440
- function preProcessSourceMap(ret, id) {
1441
- if (!ret.map) return;
1442
- let map = typeof ret.map === "object" ? ret.map : JSON.parse(ret.map);
1443
- if (!isEmptySourcemapFiled(map.sources)) {
1444
- const directory = path.dirname(id) || ".";
1445
- const sourceRoot = map.sourceRoot || ".";
1446
- map.sources = map.sources.map((source) => path.resolve(directory, sourceRoot, source));
1447
- }
1448
- return map;
1449
- }
1450
- function bindingifyModuleParsed(args) {
1451
- const hook = args.plugin.moduleParsed;
1452
- if (!hook) return {};
1453
- const { handler, meta } = normalizeHook(hook);
1454
- return {
1455
- plugin: async (ctx, moduleInfo) => {
1456
- await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), transformModuleInfo(moduleInfo, args.pluginContextData.getModuleOption(moduleInfo.id)));
1457
- },
1458
- meta: bindingifyPluginHookMeta(meta)
1459
- };
1460
- }
1461
-
1462
- //#endregion
1463
- //#region src/utils/bindingify-output-options.ts
1464
- function bindingifyOutputOptions(outputOptions) {
1465
- const { dir, format, exports, hashCharacters, sourcemap, sourcemapDebugIds, sourcemapIgnoreList, sourcemapPathTransform, name, assetFileNames, entryFileNames, chunkFileNames, cssEntryFileNames, cssChunkFileNames, banner, footer, intro, outro, esModule, globals, file, sanitizeFileName } = outputOptions;
1466
- return {
1467
- dir,
1468
- file: file == null ? void 0 : file,
1469
- format: bindingifyFormat(format),
1470
- exports,
1471
- hashCharacters,
1472
- sourcemap: bindingifySourcemap(sourcemap),
1473
- sourcemapDebugIds,
1474
- sourcemapIgnoreList: bindingifySourcemapIgnoreList(sourcemapIgnoreList),
1475
- sourcemapPathTransform,
1476
- banner: bindingifyAddon(banner),
1477
- footer: bindingifyAddon(footer),
1478
- intro: bindingifyAddon(intro),
1479
- outro: bindingifyAddon(outro),
1480
- extend: outputOptions.extend,
1481
- globals,
1482
- esModule,
1483
- name,
1484
- assetFileNames: bindingifyAssetFilenames(assetFileNames),
1485
- entryFileNames,
1486
- chunkFileNames,
1487
- cssEntryFileNames,
1488
- cssChunkFileNames,
1489
- plugins: [],
1490
- minify: outputOptions.minify,
1491
- externalLiveBindings: outputOptions.externalLiveBindings,
1492
- inlineDynamicImports: outputOptions.inlineDynamicImports,
1493
- advancedChunks: outputOptions.advancedChunks,
1494
- polyfillRequire: outputOptions.polyfillRequire,
1495
- target: outputOptions.target,
1496
- sanitizeFileName
1497
- };
1498
- }
1499
- function bindingifyAddon(configAddon) {
1500
- return async (chunk) => {
1501
- if (typeof configAddon === "function") return configAddon(transformRenderedChunk(chunk));
1502
- return configAddon || "";
1503
- };
1504
- }
1505
- function bindingifyFormat(format) {
1506
- switch (format) {
1507
- case void 0:
1508
- case "es":
1509
- case "esm":
1510
- case "module": return "es";
1511
- case "cjs":
1512
- case "commonjs": return "cjs";
1513
- case "iife": return "iife";
1514
- case "umd": return "umd";
1515
- case "experimental-app": return "app";
1516
- default: unimplemented(`output.format: ${format}`);
1517
- }
1518
- }
1519
- function bindingifySourcemap(sourcemap) {
1520
- switch (sourcemap) {
1521
- case true: return "file";
1522
- case "inline": return "inline";
1523
- case false:
1524
- case void 0: return void 0;
1525
- case "hidden": return "hidden";
1526
- default: throw new Error(`unknown sourcemap: ${sourcemap}`);
1527
- }
1528
- }
1529
- function bindingifySourcemapIgnoreList(sourcemapIgnoreList) {
1530
- return typeof sourcemapIgnoreList === "function" ? sourcemapIgnoreList : sourcemapIgnoreList === false ? () => false : (relativeSourcePath, _sourcemapPath) => relativeSourcePath.includes("node_modules");
1531
- }
1532
- function bindingifyAssetFilenames(assetFileNames) {
1533
- if (typeof assetFileNames === "function") return (asset) => {
1534
- return assetFileNames({
1535
- names: asset.names,
1536
- originalFileNames: asset.originalFileNames,
1537
- source: transformAssetSource(asset.source),
1538
- type: "asset"
1539
- });
1540
- };
1541
- return assetFileNames;
1542
- }
1543
-
1544
- //#endregion
1545
- //#region src/options/normalized-output-options.ts
1546
- var NormalizedOutputOptionsImpl = class {
1547
- constructor(inner, outputOptions, normalizedOutputPlugins) {
1548
- this.inner = inner;
1549
- this.outputOptions = outputOptions;
1550
- this.normalizedOutputPlugins = normalizedOutputPlugins;
1551
- }
1552
- get dir() {
1553
- return this.inner.dir ?? void 0;
1554
- }
1555
- get entryFileNames() {
1556
- return this.inner.entryFilenames || this.outputOptions.entryFileNames;
1557
- }
1558
- get chunkFileNames() {
1559
- return this.inner.chunkFilenames || this.outputOptions.chunkFileNames;
1560
- }
1561
- get assetFileNames() {
1562
- return this.inner.assetFilenames || this.outputOptions.assetFileNames;
1563
- }
1564
- get format() {
1565
- return this.inner.format;
1566
- }
1567
- get exports() {
1568
- return this.inner.exports;
1569
- }
1570
- get sourcemap() {
1571
- return this.inner.sourcemap;
1572
- }
1573
- get cssEntryFileNames() {
1574
- return this.inner.cssEntryFilenames || this.outputOptions.cssEntryFileNames;
1575
- }
1576
- get cssChunkFileNames() {
1577
- return this.inner.cssChunkFilenames || this.outputOptions.cssChunkFileNames;
1578
- }
1579
- get shimMissingExports() {
1580
- return this.inner.shimMissingExports;
1581
- }
1582
- get name() {
1583
- return this.inner.name ?? void 0;
1584
- }
1585
- get file() {
1586
- return this.inner.file ?? void 0;
1587
- }
1588
- get inlineDynamicImports() {
1589
- return this.inner.inlineDynamicImports;
1590
- }
1591
- get externalLiveBindings() {
1592
- return this.inner.externalLiveBindings;
1593
- }
1594
- get banner() {
1595
- return normalizeAddon(this.outputOptions.banner);
1596
- }
1597
- get footer() {
1598
- return normalizeAddon(this.outputOptions.footer);
1599
- }
1600
- get intro() {
1601
- return normalizeAddon(this.outputOptions.intro);
1602
- }
1603
- get outro() {
1604
- return normalizeAddon(this.outputOptions.outro);
1605
- }
1606
- get esModule() {
1607
- return this.inner.esModule;
1608
- }
1609
- get extend() {
1610
- return this.inner.extend;
1611
- }
1612
- get globals() {
1613
- return this.inner.globals || this.outputOptions.globals;
1614
- }
1615
- get hashCharacters() {
1616
- return this.inner.hashCharacters;
1617
- }
1618
- get sourcemapDebugIds() {
1619
- return this.inner.sourcemapDebugIds;
1620
- }
1621
- get sourcemapIgnoreList() {
1622
- return bindingifySourcemapIgnoreList(this.outputOptions.sourcemapIgnoreList);
1623
- }
1624
- get sourcemapPathTransform() {
1625
- return this.outputOptions.sourcemapPathTransform;
1626
- }
1627
- get minify() {
1628
- return this.inner.minify;
1629
- }
1630
- get comments() {
1631
- return this.inner.comments;
1632
- }
1633
- get polyfillRequire() {
1634
- return this.inner.polyfillRequire;
1635
- }
1636
- get plugins() {
1637
- return this.normalizedOutputPlugins;
1638
- }
1639
- };
1640
- function normalizeAddon(value) {
1641
- if (typeof value === "function") return value;
1642
- return () => value || "";
1643
- }
1644
-
1645
- //#endregion
1646
- //#region src/plugin/bindingify-output-hooks.ts
1647
- function bindingifyRenderStart(args) {
1648
- const hook = args.plugin.renderStart;
1649
- if (!hook) return {};
1650
- const { handler, meta } = normalizeHook(hook);
1651
- return {
1652
- plugin: async (ctx, opts) => {
1653
- handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), new NormalizedOutputOptionsImpl(opts, args.outputOptions, args.normalizedOutputPlugins), new NormalizedInputOptionsImpl(opts, args.onLog));
1654
- },
1655
- meta: bindingifyPluginHookMeta(meta)
1656
- };
1657
- }
1658
- function bindingifyRenderChunk(args) {
1659
- const hook = args.plugin.renderChunk;
1660
- if (!hook) return {};
1661
- const { handler, meta } = normalizeHook(hook);
1662
- return {
1663
- plugin: async (ctx, code, chunk, opts) => {
1664
- const ret = await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), code, transformRenderedChunk(chunk), new NormalizedOutputOptionsImpl(opts, args.outputOptions, args.normalizedOutputPlugins));
1665
- if (ret == null) return;
1666
- if (typeof ret === "string") return { code: ret };
1667
- if (!ret.map) return { code: ret.code };
1668
- return {
1669
- code: ret.code,
1670
- map: bindingifySourcemap$1(ret.map)
1671
- };
1672
- },
1673
- meta: bindingifyPluginHookMeta(meta)
1674
- };
1675
- }
1676
- function bindingifyAugmentChunkHash(args) {
1677
- const hook = args.plugin.augmentChunkHash;
1678
- if (!hook) return {};
1679
- const { handler, meta } = normalizeHook(hook);
1680
- return {
1681
- plugin: async (ctx, chunk) => {
1682
- return await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), transformRenderedChunk(chunk));
1683
- },
1684
- meta: bindingifyPluginHookMeta(meta)
1685
- };
1686
- }
1687
- function bindingifyRenderError(args) {
1688
- const hook = args.plugin.renderError;
1689
- if (!hook) return {};
1690
- const { handler, meta } = normalizeHook(hook);
1691
- return {
1692
- plugin: async (ctx, err) => {
1693
- handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), normalizeErrors(err));
1694
- },
1695
- meta: bindingifyPluginHookMeta(meta)
1696
- };
1697
- }
1698
- function bindingifyGenerateBundle(args) {
1699
- const hook = args.plugin.generateBundle;
1700
- if (!hook) return {};
1701
- const { handler, meta } = normalizeHook(hook);
1702
- return {
1703
- plugin: async (ctx, bundle, isWrite, opts) => {
1704
- const changed = {
1705
- updated: new Set(),
1706
- deleted: new Set()
1707
- };
1708
- const output = transformToOutputBundle(bundle, changed);
1709
- await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), new NormalizedOutputOptionsImpl(opts, args.outputOptions, args.normalizedOutputPlugins), output, isWrite);
1710
- return collectChangedBundle(changed, output);
1711
- },
1712
- meta: bindingifyPluginHookMeta(meta)
1713
- };
1714
- }
1715
- function bindingifyWriteBundle(args) {
1716
- const hook = args.plugin.writeBundle;
1717
- if (!hook) return {};
1718
- const { handler, meta } = normalizeHook(hook);
1719
- return {
1720
- plugin: async (ctx, bundle, opts) => {
1721
- const changed = {
1722
- updated: new Set(),
1723
- deleted: new Set()
1724
- };
1725
- const output = transformToOutputBundle(bundle, changed);
1726
- await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), new NormalizedOutputOptionsImpl(opts, args.outputOptions, args.normalizedOutputPlugins), output);
1727
- return collectChangedBundle(changed, output);
1728
- },
1729
- meta: bindingifyPluginHookMeta(meta)
1730
- };
1731
- }
1732
- function bindingifyCloseBundle(args) {
1733
- const hook = args.plugin.closeBundle;
1734
- if (!hook) return {};
1735
- const { handler, meta } = normalizeHook(hook);
1736
- return {
1737
- plugin: async (ctx) => {
1738
- await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel));
1739
- },
1740
- meta: bindingifyPluginHookMeta(meta)
1741
- };
1742
- }
1743
- function bindingifyBanner(args) {
1744
- const hook = args.plugin.banner;
1745
- if (!hook) return {};
1746
- const { handler, meta } = normalizeHook(hook);
1747
- return {
1748
- plugin: async (ctx, chunk) => {
1749
- if (typeof handler === "string") return handler;
1750
- return handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), transformRenderedChunk(chunk));
1751
- },
1752
- meta: bindingifyPluginHookMeta(meta)
1753
- };
1754
- }
1755
- function bindingifyFooter(args) {
1756
- const hook = args.plugin.footer;
1757
- if (!hook) return {};
1758
- const { handler, meta } = normalizeHook(hook);
1759
- return {
1760
- plugin: async (ctx, chunk) => {
1761
- if (typeof handler === "string") return handler;
1762
- return handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), transformRenderedChunk(chunk));
1763
- },
1764
- meta: bindingifyPluginHookMeta(meta)
1765
- };
1766
- }
1767
- function bindingifyIntro(args) {
1768
- const hook = args.plugin.intro;
1769
- if (!hook) return {};
1770
- const { handler, meta } = normalizeHook(hook);
1771
- return {
1772
- plugin: async (ctx, chunk) => {
1773
- if (typeof handler === "string") return handler;
1774
- return handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), transformRenderedChunk(chunk));
1775
- },
1776
- meta: bindingifyPluginHookMeta(meta)
1777
- };
1778
- }
1779
- function bindingifyOutro(args) {
1780
- const hook = args.plugin.outro;
1781
- if (!hook) return {};
1782
- const { handler, meta } = normalizeHook(hook);
1783
- return {
1784
- plugin: async (ctx, chunk) => {
1785
- if (typeof handler === "string") return handler;
1786
- return handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), transformRenderedChunk(chunk));
1787
- },
1788
- meta: bindingifyPluginHookMeta(meta)
1789
- };
1790
- }
1791
-
1792
- //#endregion
1793
- //#region src/plugin/bindingify-watch-hooks.ts
1794
- function bindingifyWatchChange(args) {
1795
- const hook = args.plugin.watchChange;
1796
- if (!hook) return {};
1797
- const { handler, meta } = normalizeHook(hook);
1798
- return {
1799
- plugin: async (ctx, id, event) => {
1800
- await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), id, { event });
1801
- },
1802
- meta: bindingifyPluginHookMeta(meta)
1803
- };
1804
- }
1805
- function bindingifyCloseWatcher(args) {
1806
- const hook = args.plugin.closeWatcher;
1807
- if (!hook) return {};
1808
- const { handler, meta } = normalizeHook(hook);
1809
- return {
1810
- plugin: async (ctx) => {
1811
- await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel));
1812
- },
1813
- meta: bindingifyPluginHookMeta(meta)
1814
- };
1815
- }
1816
-
1817
- //#endregion
1818
- //#region src/plugin/bindingify-plugin.ts
1819
- function bindingifyPlugin(plugin, options, outputOptions, pluginContextData, normalizedOutputPlugins, onLog, logLevel) {
1820
- const args = {
1821
- plugin,
1822
- options,
1823
- outputOptions,
1824
- pluginContextData,
1825
- onLog,
1826
- logLevel,
1827
- normalizedOutputPlugins
1828
- };
1829
- const { plugin: buildStart, meta: buildStartMeta } = bindingifyBuildStart(args);
1830
- const { plugin: resolveId, meta: resolveIdMeta, filter: resolveIdFilter } = bindingifyResolveId(args);
1831
- const { plugin: resolveDynamicImport, meta: resolveDynamicImportMeta } = bindingifyResolveDynamicImport(args);
1832
- const { plugin: buildEnd, meta: buildEndMeta } = bindingifyBuildEnd(args);
1833
- const { plugin: transform, meta: transformMeta, filter: transformFilter } = bindingifyTransform(args);
1834
- const { plugin: moduleParsed, meta: moduleParsedMeta } = bindingifyModuleParsed(args);
1835
- const { plugin: load, meta: loadMeta, filter: loadFilter } = bindingifyLoad(args);
1836
- const { plugin: renderChunk, meta: renderChunkMeta } = bindingifyRenderChunk(args);
1837
- const { plugin: augmentChunkHash, meta: augmentChunkHashMeta } = bindingifyAugmentChunkHash(args);
1838
- const { plugin: renderStart, meta: renderStartMeta } = bindingifyRenderStart(args);
1839
- const { plugin: renderError, meta: renderErrorMeta } = bindingifyRenderError(args);
1840
- const { plugin: generateBundle, meta: generateBundleMeta } = bindingifyGenerateBundle(args);
1841
- const { plugin: writeBundle, meta: writeBundleMeta } = bindingifyWriteBundle(args);
1842
- const { plugin: closeBundle, meta: closeBundleMeta } = bindingifyCloseBundle(args);
1843
- const { plugin: banner, meta: bannerMeta } = bindingifyBanner(args);
1844
- const { plugin: footer, meta: footerMeta } = bindingifyFooter(args);
1845
- const { plugin: intro, meta: introMeta } = bindingifyIntro(args);
1846
- const { plugin: outro, meta: outroMeta } = bindingifyOutro(args);
1847
- const { plugin: watchChange, meta: watchChangeMeta } = bindingifyWatchChange(args);
1848
- const { plugin: closeWatcher, meta: closeWatcherMeta } = bindingifyCloseWatcher(args);
1849
- const result = {
1850
- name: plugin.name,
1851
- buildStart,
1852
- buildStartMeta,
1853
- resolveId,
1854
- resolveIdMeta,
1855
- resolveIdFilter,
1856
- resolveDynamicImport,
1857
- resolveDynamicImportMeta,
1858
- buildEnd,
1859
- buildEndMeta,
1860
- transform,
1861
- transformMeta,
1862
- transformFilter,
1863
- moduleParsed,
1864
- moduleParsedMeta,
1865
- load,
1866
- loadMeta,
1867
- loadFilter,
1868
- renderChunk,
1869
- renderChunkMeta,
1870
- augmentChunkHash,
1871
- augmentChunkHashMeta,
1872
- renderStart,
1873
- renderStartMeta,
1874
- renderError,
1875
- renderErrorMeta,
1876
- generateBundle,
1877
- generateBundleMeta,
1878
- writeBundle,
1879
- writeBundleMeta,
1880
- closeBundle,
1881
- closeBundleMeta,
1882
- banner,
1883
- bannerMeta,
1884
- footer,
1885
- footerMeta,
1886
- intro,
1887
- introMeta,
1888
- outro,
1889
- outroMeta,
1890
- watchChange,
1891
- watchChangeMeta,
1892
- closeWatcher,
1893
- closeWatcherMeta
1894
- };
1895
- return wrapHandlers(result);
1896
- }
1897
- function wrapHandlers(plugin) {
1898
- for (const hookName of [
1899
- "buildStart",
1900
- "resolveId",
1901
- "resolveDynamicImport",
1902
- "buildEnd",
1903
- "transform",
1904
- "moduleParsed",
1905
- "load",
1906
- "renderChunk",
1907
- "augmentChunkHash",
1908
- "renderStart",
1909
- "renderError",
1910
- "generateBundle",
1911
- "writeBundle",
1912
- "closeBundle",
1913
- "banner",
1914
- "footer",
1915
- "intro",
1916
- "outro",
1917
- "watchChange",
1918
- "closeWatcher"
1919
- ]) {
1920
- const handler = plugin[hookName];
1921
- if (handler) plugin[hookName] = async (...args) => {
1922
- try {
1923
- return await handler(...args);
1924
- } catch (e) {
1925
- return error(logPluginError(e, plugin.name, {
1926
- hook: hookName,
1927
- id: hookName === "transform" ? args[2] : void 0
1928
- }));
1929
- }
1930
- };
1931
- }
1932
- return plugin;
1933
- }
1934
-
1935
- //#endregion
1936
- //#region src/plugin/plugin-context-data.ts
1937
- var PluginContextData = class {
1938
- moduleOptionMap = new Map();
1939
- resolveOptionsMap = new Map();
1940
- loadModulePromiseMap = new Map();
1941
- updateModuleOption(id, option) {
1942
- const existing = this.moduleOptionMap.get(id);
1943
- if (existing) {
1944
- if (option.moduleSideEffects != null) existing.moduleSideEffects = option.moduleSideEffects;
1945
- if (option.meta != null) Object.assign(existing.meta, option.meta);
1946
- if (option.invalidate != null) existing.invalidate = option.invalidate;
1947
- } else {
1948
- this.moduleOptionMap.set(id, option);
1949
- return option;
1950
- }
1951
- return existing;
1952
- }
1953
- getModuleOption(id) {
1954
- const option = this.moduleOptionMap.get(id);
1955
- if (!option) {
1956
- const raw = {
1957
- moduleSideEffects: null,
1958
- meta: {}
1959
- };
1960
- this.moduleOptionMap.set(id, raw);
1961
- return raw;
1962
- }
1963
- return option;
1964
- }
1965
- getModuleInfo(id, context) {
1966
- const bindingInfo = context.getModuleInfo(id);
1967
- if (bindingInfo) {
1968
- const info = transformModuleInfo(bindingInfo, this.getModuleOption(id));
1969
- return this.proxyModuleInfo(id, info);
1970
- }
1971
- return null;
1972
- }
1973
- proxyModuleInfo(id, info) {
1974
- let moduleSideEffects = info.moduleSideEffects;
1975
- Object.defineProperty(info, "moduleSideEffects", {
1976
- get() {
1977
- return moduleSideEffects;
1978
- },
1979
- set: (v$1) => {
1980
- this.updateModuleOption(id, {
1981
- moduleSideEffects: v$1,
1982
- meta: info.meta,
1983
- invalidate: true
1984
- });
1985
- moduleSideEffects = v$1;
1986
- }
1987
- });
1988
- return info;
1989
- }
1990
- getModuleIds(context) {
1991
- const moduleIds = context.getModuleIds();
1992
- return moduleIds.values();
1993
- }
1994
- saveResolveOptions(options) {
1995
- const index = this.resolveOptionsMap.size;
1996
- this.resolveOptionsMap.set(index, options);
1997
- return index;
1998
- }
1999
- getSavedResolveOptions(receipt) {
2000
- return this.resolveOptionsMap.get(receipt);
2001
- }
2002
- removeSavedResolveOptions(receipt) {
2003
- this.resolveOptionsMap.delete(receipt);
2004
- }
2005
- };
2006
-
2007
- //#endregion
2008
- //#region src/utils/normalize-string-or-regex.ts
2009
- function normalizedStringOrRegex(pattern) {
2010
- if (!pattern) return void 0;
2011
- if (!Array.isArray(pattern)) pattern = [pattern];
2012
- return pattern;
2013
- }
2014
-
2015
- //#endregion
2016
- //#region src/utils/bindingify-input-options.ts
2017
- function bindingifyInputOptions(rawPlugins, inputOptions, outputOptions, normalizedOutputPlugins, onLog, logLevel) {
2018
- const pluginContextData = new PluginContextData();
2019
- const plugins = rawPlugins.map((plugin) => {
2020
- if ("_parallel" in plugin) return void 0;
2021
- if (plugin instanceof BuiltinPlugin) return bindingifyBuiltInPlugin(plugin);
2022
- return bindingifyPlugin(plugin, inputOptions, outputOptions, pluginContextData, normalizedOutputPlugins, onLog, logLevel);
2023
- });
2024
- return {
2025
- input: bindingifyInput(inputOptions.input),
2026
- plugins,
2027
- cwd: inputOptions.cwd ?? process.cwd(),
2028
- external: bindingifyExternal(inputOptions.external),
2029
- resolve: bindingifyResolve(inputOptions.resolve),
2030
- platform: inputOptions.platform,
2031
- shimMissingExports: inputOptions.shimMissingExports,
2032
- logLevel: bindingifyLogLevel(logLevel),
2033
- onLog,
2034
- treeshake: bindingifyTreeshakeOptions(inputOptions.treeshake),
2035
- moduleTypes: inputOptions.moduleTypes,
2036
- define: inputOptions.define ? Object.entries(inputOptions.define) : void 0,
2037
- inject: bindingifyInject(inputOptions.inject),
2038
- experimental: {
2039
- strictExecutionOrder: inputOptions.experimental?.strictExecutionOrder,
2040
- disableLiveBindings: inputOptions.experimental?.disableLiveBindings,
2041
- viteMode: inputOptions.experimental?.viteMode,
2042
- resolveNewUrlToAsset: inputOptions.experimental?.resolveNewUrlToAsset,
2043
- hmr: inputOptions.experimental?.hmr
2044
- },
2045
- profilerNames: inputOptions?.profilerNames,
2046
- jsx: bindingifyJsx(inputOptions.jsx),
2047
- transform: inputOptions.transform,
2048
- watch: bindingifyWatch(inputOptions.watch),
2049
- dropLabels: inputOptions.dropLabels,
2050
- keepNames: inputOptions.keepNames,
2051
- checks: inputOptions.checks,
2052
- deferSyncScanData: () => {
2053
- let ret = [];
2054
- pluginContextData.moduleOptionMap.forEach((value, key) => {
2055
- if (value.invalidate) ret.push({
2056
- id: key,
2057
- sideEffects: bindingifySideEffects(value.moduleSideEffects)
2058
- });
2059
- });
2060
- return ret;
2061
- }
2062
- };
2063
- }
2064
- function bindingifyExternal(external) {
2065
- if (external) {
2066
- if (typeof external === "function") return (id, importer, isResolved) => {
2067
- if (id.startsWith("\0")) return false;
2068
- return external(id, importer, isResolved) ?? false;
2069
- };
2070
- const externalArr = arraify(external);
2071
- return (id, _importer, _isResolved) => {
2072
- return externalArr.some((pat) => {
2073
- if (pat instanceof RegExp) return pat.test(id);
2074
- return id === pat;
2075
- });
2076
- };
2077
- }
2078
- }
2079
- function bindingifyResolve(resolve) {
2080
- if (resolve) {
2081
- const { alias, extensionAlias,...rest } = resolve;
2082
- return {
2083
- alias: alias ? Object.entries(alias).map(([name, replacement]) => ({
2084
- find: name,
2085
- replacements: arraify(replacement)
2086
- })) : void 0,
2087
- extensionAlias: extensionAlias ? Object.entries(extensionAlias).map(([name, value]) => ({
2088
- target: name,
2089
- replacements: value
2090
- })) : void 0,
2091
- ...rest
2092
- };
2093
- }
2094
- }
2095
- function bindingifyInject(inject) {
2096
- if (inject) return Object.entries(inject).map(([alias, item]) => {
2097
- if (Array.isArray(item)) {
2098
- if (item[1] === "*") return {
2099
- tagNamespace: true,
2100
- alias,
2101
- from: item[0]
2102
- };
2103
- return {
2104
- tagNamed: true,
2105
- alias,
2106
- from: item[0],
2107
- imported: item[1]
2108
- };
2109
- } else return {
2110
- tagNamed: true,
2111
- imported: "default",
2112
- alias,
2113
- from: item
2114
- };
2115
- });
2116
- }
2117
- function bindingifyLogLevel(logLevel) {
2118
- switch (logLevel) {
2119
- case "silent": return import_binding.BindingLogLevel.Silent;
2120
- case "debug": return import_binding.BindingLogLevel.Debug;
2121
- case "warn": return import_binding.BindingLogLevel.Warn;
2122
- case "info": return import_binding.BindingLogLevel.Info;
2123
- default: throw new Error(`Unexpected log level: ${logLevel}`);
2124
- }
2125
- }
2126
- function bindingifyInput(input) {
2127
- if (input === void 0) return [];
2128
- if (typeof input === "string") return [{ import: input }];
2129
- if (Array.isArray(input)) return input.map((src) => ({ import: src }));
2130
- return Object.entries(input).map(([name, import_path]) => {
2131
- return {
2132
- name,
2133
- import: import_path
2134
- };
2135
- });
2136
- }
2137
- function bindingifyJsx(input) {
2138
- switch (input) {
2139
- case false: return { type: "Disable" };
2140
- case "react": return { type: "React" };
2141
- case "react-jsx": return { type: "ReactJsx" };
2142
- case "preserve": return { type: "Preserve" };
2143
- case void 0: return void 0;
2144
- }
2145
- if (input.mode === "preserve") return { type: "Preserve" };
2146
- const mode = input.mode ?? "automatic";
2147
- return {
2148
- type: "Enable",
2149
- field0: {
2150
- runtime: mode,
2151
- importSource: mode === "classic" ? input.importSource : mode === "automatic" ? input.jsxImportSource : void 0,
2152
- pragma: input.factory,
2153
- pragmaFrag: input.fragment,
2154
- development: input.development,
2155
- refresh: input.refresh
2156
- }
2157
- };
2158
- }
2159
- function bindingifyWatch(watch$1) {
2160
- if (watch$1) return {
2161
- buildDelay: watch$1.buildDelay,
2162
- skipWrite: watch$1.skipWrite,
2163
- include: normalizedStringOrRegex(watch$1.include),
2164
- exclude: normalizedStringOrRegex(watch$1.exclude)
2165
- };
2166
- }
2167
- function bindingifyTreeshakeOptions(config) {
2168
- if (config === false) return void 0;
2169
- if (config === true || config === void 0) return { moduleSideEffects: true };
2170
- let normalizedConfig = {
2171
- moduleSideEffects: true,
2172
- annotations: config.annotations,
2173
- manualPureFunctions: config.manualPureFunctions,
2174
- unknownGlobalSideEffects: config.unknownGlobalSideEffects
2175
- };
2176
- if (config.moduleSideEffects === void 0) normalizedConfig.moduleSideEffects = true;
2177
- else if (config.moduleSideEffects === "no-external") normalizedConfig.moduleSideEffects = [{
2178
- external: true,
2179
- sideEffects: false
2180
- }, {
2181
- external: false,
2182
- sideEffects: true
2183
- }];
2184
- else normalizedConfig.moduleSideEffects = config.moduleSideEffects;
2185
- return normalizedConfig;
2186
- }
2187
-
2188
- //#endregion
2189
- //#region ../../node_modules/.pnpm/remeda@2.21.0/node_modules/remeda/dist/chunk-D6FCK2GA.js
2190
- function u$1(o, n, a) {
2191
- let t$1 = (r) => o(r, ...n);
2192
- return a === void 0 ? t$1 : Object.assign(t$1, {
2193
- lazy: a,
2194
- lazyArgs: n
2195
- });
2196
- }
2197
-
2198
- //#endregion
2199
- //#region ../../node_modules/.pnpm/remeda@2.21.0/node_modules/remeda/dist/chunk-WIMGWYZL.js
2200
- function u(r, n, o) {
2201
- let a = r.length - n.length;
2202
- if (a === 0) return r(...n);
2203
- if (a === 1) return u$1(r, n, o);
2204
- throw new Error("Wrong number of arguments");
2205
- }
2206
-
2207
- //#endregion
2208
- //#region ../../node_modules/.pnpm/remeda@2.21.0/node_modules/remeda/dist/chunk-5NQBDF4H.js
2209
- function t(...n) {
2210
- return u(Object.keys, n);
2211
- }
2212
-
2213
- //#endregion
2214
- //#region src/utils/plugin/index.ts
2215
- const isPluginHookName = function() {
2216
- const PLUGIN_HOOK_NAMES_SET = new Set(ENUMERATED_PLUGIN_HOOK_NAMES);
2217
- return function isPluginHookName$1(hookName) {
2218
- return PLUGIN_HOOK_NAMES_SET.has(hookName);
2219
- };
2220
- }();
2221
-
2222
- //#endregion
2223
- //#region src/utils/compose-js-plugins.ts
2224
- const unsupportedHookName = [
2225
- "augmentChunkHash",
2226
- "generateBundle",
2227
- "moduleParsed",
2228
- "onLog",
2229
- "options",
2230
- "outputOptions",
2231
- "renderError",
2232
- "renderStart",
2233
- "resolveDynamicImport",
2234
- "writeBundle"
2235
- ];
2236
- const unsupportedHooks = new Set(unsupportedHookName);
2237
- function isUnsupportedHooks(hookName) {
2238
- return unsupportedHooks.has(hookName);
2239
- }
2240
- function createComposedPlugin(plugins) {
2241
- const names = [];
2242
- const batchedHooks = {};
2243
- plugins.forEach((plugin, index) => {
2244
- const pluginName = plugin.name || `Anonymous(index: ${index})`;
2245
- names.push(pluginName);
2246
- t(plugin).forEach((pluginProp) => {
2247
- if (isUnsupportedHooks(pluginProp)) throw new Error(`Failed to compose js plugins. Plugin ${pluginName} has an unsupported hook: ${pluginProp}`);
2248
- if (!isPluginHookName(pluginProp)) return;
2249
- switch (pluginProp) {
2250
- case "buildStart": {
2251
- const handlers = batchedHooks.buildStart ?? [];
2252
- batchedHooks.buildStart = handlers;
2253
- if (plugin.buildStart) handlers.push([plugin.buildStart, plugin]);
2254
- break;
2255
- }
2256
- case "load": {
2257
- const handlers = batchedHooks.load ?? [];
2258
- batchedHooks.load = handlers;
2259
- if (plugin.load) handlers.push([plugin.load, plugin]);
2260
- break;
2261
- }
2262
- case "transform": {
2263
- const handlers = batchedHooks.transform ?? [];
2264
- batchedHooks.transform = handlers;
2265
- if (plugin.transform) handlers.push([plugin.transform, plugin]);
2266
- break;
2267
- }
2268
- case "resolveId": {
2269
- const handlers = batchedHooks.resolveId ?? [];
2270
- batchedHooks.resolveId = handlers;
2271
- if (plugin.resolveId) handlers.push([plugin.resolveId, plugin]);
2272
- break;
2273
- }
2274
- case "buildEnd": {
2275
- const handlers = batchedHooks.buildEnd ?? [];
2276
- batchedHooks.buildEnd = handlers;
2277
- if (plugin.buildEnd) handlers.push([plugin.buildEnd, plugin]);
2278
- break;
2279
- }
2280
- case "renderChunk": {
2281
- const handlers = batchedHooks.renderChunk ?? [];
2282
- batchedHooks.renderChunk = handlers;
2283
- if (plugin.renderChunk) handlers.push([plugin.renderChunk, plugin]);
2284
- break;
2285
- }
2286
- case "banner":
2287
- case "footer":
2288
- case "intro":
2289
- case "outro": {
2290
- const hook = plugin[pluginProp];
2291
- if (hook) (batchedHooks[pluginProp] ??= []).push([hook, plugin]);
2292
- break;
2293
- }
2294
- case "closeBundle": {
2295
- const handlers = batchedHooks.closeBundle ?? [];
2296
- batchedHooks.closeBundle = handlers;
2297
- if (plugin.closeBundle) handlers.push([plugin.closeBundle, plugin]);
2298
- break;
2299
- }
2300
- case "watchChange": {
2301
- const handlers = batchedHooks.watchChange ?? [];
2302
- batchedHooks.watchChange = handlers;
2303
- if (plugin.watchChange) handlers.push([plugin.watchChange, plugin]);
2304
- break;
2305
- }
2306
- case "closeWatcher": {
2307
- const handlers = batchedHooks.closeWatcher ?? [];
2308
- batchedHooks.closeWatcher = handlers;
2309
- if (plugin.closeWatcher) handlers.push([plugin.closeWatcher, plugin]);
2310
- break;
2311
- }
2312
- default: {}
2313
- }
2314
- });
2315
- });
2316
- const composed = { name: `Composed(${names.join(", ")})` };
2317
- const createFixedPluginResolveFnMap = new Map();
2318
- function applyFixedPluginResolveFn(ctx, plugin) {
2319
- const createFixedPluginResolveFn = createFixedPluginResolveFnMap.get(plugin);
2320
- if (createFixedPluginResolveFn) ctx.resolve = createFixedPluginResolveFn(ctx, ctx.resolve.bind(ctx));
2321
- return ctx;
2322
- }
2323
- if (batchedHooks.resolveId) {
2324
- const batchedHandlers = batchedHooks.resolveId;
2325
- const handlerSymbols = batchedHandlers.map(([_handler, plugin]) => Symbol(plugin.name ?? `Anonymous`));
2326
- for (let handlerIdx = 0; handlerIdx < batchedHandlers.length; handlerIdx++) {
2327
- const [_handler, plugin] = batchedHandlers[handlerIdx];
2328
- const handlerSymbol = handlerSymbols[handlerIdx];
2329
- const createFixedPluginResolveFn = (ctx, resolve) => {
2330
- return (source, importer, rawContextResolveOptions) => {
2331
- const contextResolveOptions = rawContextResolveOptions ?? {};
2332
- if (contextResolveOptions.skipSelf) {
2333
- contextResolveOptions[SYMBOL_FOR_RESOLVE_CALLER_THAT_SKIP_SELF] = handlerSymbol;
2334
- contextResolveOptions.skipSelf = false;
2335
- }
2336
- return resolve(source, importer, contextResolveOptions);
2337
- };
2338
- };
2339
- createFixedPluginResolveFnMap.set(plugin, createFixedPluginResolveFn);
2340
- }
2341
- composed.resolveId = async function(source, importer, rawHookResolveIdOptions) {
2342
- const hookResolveIdOptions = rawHookResolveIdOptions;
2343
- const symbolForCallerThatSkipSelf = hookResolveIdOptions?.[SYMBOL_FOR_RESOLVE_CALLER_THAT_SKIP_SELF];
2344
- for (let handlerIdx = 0; handlerIdx < batchedHandlers.length; handlerIdx++) {
2345
- const [handler, plugin] = batchedHandlers[handlerIdx];
2346
- const handlerSymbol = handlerSymbols[handlerIdx];
2347
- if (symbolForCallerThatSkipSelf === handlerSymbol) continue;
2348
- const { handler: handlerFn } = normalizeHook(handler);
2349
- const result = await handlerFn.call(applyFixedPluginResolveFn(this, plugin), source, importer, rawHookResolveIdOptions);
2350
- if (!isNullish(result)) return result;
2351
- }
2352
- };
2353
- }
2354
- t(batchedHooks).forEach((hookName) => {
2355
- switch (hookName) {
2356
- case "resolveId": break;
2357
- case "buildStart": {
2358
- if (batchedHooks.buildStart) {
2359
- const batchedHandlers = batchedHooks.buildStart;
2360
- composed.buildStart = async function(options) {
2361
- await Promise.all(batchedHandlers.map(([handler, plugin]) => {
2362
- const { handler: handlerFn } = normalizeHook(handler);
2363
- return handlerFn.call(applyFixedPluginResolveFn(this, plugin), options);
2364
- }));
2365
- };
2366
- }
2367
- break;
2368
- }
2369
- case "load": {
2370
- if (batchedHooks.load) {
2371
- const batchedHandlers = batchedHooks.load;
2372
- composed.load = async function(id) {
2373
- for (const [handler, plugin] of batchedHandlers) {
2374
- const { handler: handlerFn } = normalizeHook(handler);
2375
- const result = await handlerFn.call(applyFixedPluginResolveFn(this, plugin), id);
2376
- if (!isNullish(result)) return result;
2377
- }
2378
- };
2379
- }
2380
- break;
2381
- }
2382
- case "transform": {
2383
- if (batchedHooks.transform) {
2384
- const batchedHandlers = batchedHooks.transform;
2385
- composed.transform = async function(initialCode, id, moduleType) {
2386
- let code = initialCode;
2387
- let moduleSideEffects = void 0;
2388
- function updateOutput(newCode, newModuleSideEffects) {
2389
- code = newCode;
2390
- moduleSideEffects = newModuleSideEffects ?? void 0;
2391
- }
2392
- for (const [handler, plugin] of batchedHandlers) {
2393
- const { handler: handlerFn } = normalizeHook(handler);
2394
- this.getCombinedSourcemap = () => {
2395
- throw new Error(`The getCombinedSourcemap is not implement in transform hook at composedJsPlugins`);
2396
- };
2397
- const result = await handlerFn.call(applyFixedPluginResolveFn(this, plugin), code, id, moduleType);
2398
- if (!isNullish(result)) {
2399
- if (typeof result === "string") updateOutput(result);
2400
- else if (result.code) updateOutput(result.code, result.moduleSideEffects);
2401
- }
2402
- }
2403
- return {
2404
- code,
2405
- moduleSideEffects
2406
- };
2407
- };
2408
- }
2409
- break;
2410
- }
2411
- case "buildEnd": {
2412
- if (batchedHooks.buildEnd) {
2413
- const batchedHandlers = batchedHooks.buildEnd;
2414
- composed.buildEnd = async function(err) {
2415
- await Promise.all(batchedHandlers.map(([handler, plugin]) => {
2416
- const { handler: handlerFn } = normalizeHook(handler);
2417
- return handlerFn.call(applyFixedPluginResolveFn(this, plugin), err);
2418
- }));
2419
- };
2420
- }
2421
- break;
2422
- }
2423
- case "renderChunk": {
2424
- if (batchedHooks.renderChunk) {
2425
- const batchedHandlers = batchedHooks.renderChunk;
2426
- composed.renderChunk = async function(code, chunk, options) {
2427
- for (const [handler, plugin] of batchedHandlers) {
2428
- const { handler: handlerFn } = normalizeHook(handler);
2429
- const result = await handlerFn.call(applyFixedPluginResolveFn(this, plugin), code, chunk, options);
2430
- if (!isNullish(result)) return result;
2431
- }
2432
- };
2433
- }
2434
- break;
2435
- }
2436
- case "banner":
2437
- case "footer":
2438
- case "intro":
2439
- case "outro": {
2440
- const hooks = batchedHooks[hookName];
2441
- if (hooks?.length) composed[hookName] = async function(chunk) {
2442
- const ret = [];
2443
- for (const [hook, plugin] of hooks) {
2444
- const { handler } = normalizeHook(hook);
2445
- ret.push(typeof handler === "string" ? handler : await handler.call(applyFixedPluginResolveFn(this, plugin), chunk));
2446
- }
2447
- return ret.join("\n");
2448
- };
2449
- break;
2450
- }
2451
- case "closeBundle": {
2452
- if (batchedHooks.closeBundle) {
2453
- const batchedHandlers = batchedHooks.closeBundle;
2454
- composed.closeBundle = async function() {
2455
- await Promise.all(batchedHandlers.map(([handler, plugin]) => {
2456
- const { handler: handlerFn } = normalizeHook(handler);
2457
- return handlerFn.call(applyFixedPluginResolveFn(this, plugin));
2458
- }));
2459
- };
2460
- }
2461
- break;
2462
- }
2463
- case "watchChange": {
2464
- if (batchedHooks.watchChange) {
2465
- const batchedHandlers = batchedHooks.watchChange;
2466
- composed.watchChange = async function(id, event) {
2467
- await Promise.all(batchedHandlers.map(([handler, plugin]) => {
2468
- const { handler: handlerFn } = normalizeHook(handler);
2469
- return handlerFn.call(applyFixedPluginResolveFn(this, plugin), id, event);
2470
- }));
2471
- };
2472
- }
2473
- break;
2474
- }
2475
- case "closeWatcher": {
2476
- if (batchedHooks.closeWatcher) {
2477
- const batchedHandlers = batchedHooks.closeWatcher;
2478
- composed.closeWatcher = async function() {
2479
- await Promise.all(batchedHandlers.map(([handler, plugin]) => {
2480
- const { handler: handlerFn } = normalizeHook(handler);
2481
- return handlerFn.call(applyFixedPluginResolveFn(this, plugin));
2482
- }));
2483
- };
2484
- }
2485
- break;
2486
- }
2487
- default: {}
2488
- }
2489
- });
2490
- return composed;
2491
- }
2492
- function isComposablePlugin(plugin) {
2493
- if (plugin instanceof BuiltinPlugin) return false;
2494
- if ("_parallel" in plugin) return false;
2495
- const hasNotComposablePattern = t(plugin).some((hookName) => {
2496
- if (!isPluginHookName(hookName)) return false;
2497
- const OK_TO_COMPOSE = false;
2498
- if (isUnsupportedHooks(hookName)) return !OK_TO_COMPOSE;
2499
- if (plugin[hookName]) {
2500
- const { meta } = normalizeHook(plugin[hookName]);
2501
- if (meta.order === "pre" || meta.order === "post") return !OK_TO_COMPOSE;
2502
- }
2503
- return OK_TO_COMPOSE;
2504
- });
2505
- if (hasNotComposablePattern) return false;
2506
- return true;
2507
- }
2508
- function composeJsPlugins(plugins) {
2509
- const newPlugins = [];
2510
- const toBeComposed = [];
2511
- plugins.forEach((plugin) => {
2512
- if (isComposablePlugin(plugin)) toBeComposed.push(plugin);
2513
- else {
2514
- if (toBeComposed.length > 0) {
2515
- if (toBeComposed.length > 1) newPlugins.push(createComposedPlugin(toBeComposed));
2516
- else newPlugins.push(toBeComposed[0]);
2517
- toBeComposed.length = 0;
2518
- }
2519
- newPlugins.push(plugin);
2520
- }
2521
- });
2522
- if (toBeComposed.length > 0) {
2523
- if (toBeComposed.length > 1) newPlugins.push(createComposedPlugin(toBeComposed));
2524
- else newPlugins.push(toBeComposed[0]);
2525
- toBeComposed.length = 0;
2526
- }
2527
- return newPlugins;
2528
- }
2529
-
2530
- //#endregion
2531
- //#region src/utils/initialize-parallel-plugins.ts
2532
- async function initializeParallelPlugins(plugins) {
2533
- const pluginInfos = [];
2534
- for (const [index, plugin] of plugins.entries()) if ("_parallel" in plugin) {
2535
- const { fileUrl, options } = plugin._parallel;
2536
- pluginInfos.push({
2537
- index,
2538
- fileUrl,
2539
- options
2540
- });
2541
- }
2542
- if (pluginInfos.length <= 0) return void 0;
2543
- const count = Math.min(availableParallelism(), 8);
2544
- const parallelJsPluginRegistry = new import_binding.ParallelJsPluginRegistry(count);
2545
- const registryId = parallelJsPluginRegistry.id;
2546
- const workers = await initializeWorkers(registryId, count, pluginInfos);
2547
- const stopWorkers = async () => {
2548
- await Promise.all(workers.map((worker) => worker.terminate()));
2549
- };
2550
- return {
2551
- registry: parallelJsPluginRegistry,
2552
- stopWorkers
2553
- };
2554
- }
2555
- function initializeWorkers(registryId, count, pluginInfos) {
2556
- return Promise.all(Array.from({ length: count }, (_, i) => initializeWorker(registryId, pluginInfos, i)));
2557
- }
2558
- async function initializeWorker(registryId, pluginInfos, threadNumber) {
2559
- const urlString = import.meta.resolve("#parallel-plugin-worker");
2560
- const workerData$1 = {
2561
- registryId,
2562
- pluginInfos,
2563
- threadNumber
2564
- };
2565
- let worker;
2566
- try {
2567
- worker = new Worker(new URL(urlString), { workerData: workerData$1 });
2568
- worker.unref();
2569
- await new Promise((resolve, reject) => {
2570
- worker.once("message", async (message) => {
2571
- if (message.type === "error") reject(message.error);
2572
- else resolve();
2573
- });
2574
- });
2575
- return worker;
2576
- } catch (e) {
2577
- worker?.terminate();
2578
- throw e;
2579
- }
2580
- }
2581
-
2582
- //#endregion
2583
- //#region src/utils/create-bundler-option.ts
2584
- async function createBundlerOptions(inputOptions, outputOptions, isClose) {
2585
- const inputPlugins = await normalizePluginOption(inputOptions.plugins);
2586
- const outputPlugins = await normalizePluginOption(outputOptions.plugins);
2587
- const logLevel = inputOptions.logLevel || LOG_LEVEL_INFO;
2588
- const onLog = getLogger(getObjectPlugins(inputPlugins), getOnLog(inputOptions, logLevel), logLevel);
2589
- if (!isClose) outputOptions = PluginDriver.callOutputOptionsHook([...inputPlugins, ...outputPlugins], outputOptions);
2590
- if (outputOptions.minify === true) onLog(LOG_LEVEL_WARN, logMinifyWarning());
2591
- const normalizedOutputPlugins = await normalizePluginOption(outputOptions.plugins);
2592
- let plugins = [...normalizePlugins(inputPlugins, ANONYMOUS_PLUGIN_PREFIX), ...checkOutputPluginOption(normalizePlugins(normalizedOutputPlugins, ANONYMOUS_OUTPUT_PLUGIN_PREFIX), onLog)];
2593
- if (inputOptions.experimental?.enableComposingJsPlugins ?? false) plugins = composeJsPlugins(plugins);
2594
- const parallelPluginInitResult = await initializeParallelPlugins(plugins);
2595
- try {
2596
- const bindingInputOptions = bindingifyInputOptions(plugins, inputOptions, outputOptions, normalizedOutputPlugins, onLog, logLevel);
2597
- const bindingOutputOptions = bindingifyOutputOptions(outputOptions);
2598
- return {
2599
- bundlerOptions: {
2600
- inputOptions: bindingInputOptions,
2601
- outputOptions: bindingOutputOptions,
2602
- parallelPluginsRegistry: parallelPluginInitResult?.registry
2603
- },
2604
- inputOptions,
2605
- onLog,
2606
- stopWorkers: parallelPluginInitResult?.stopWorkers
2607
- };
2608
- } catch (e) {
2609
- await parallelPluginInitResult?.stopWorkers();
2610
- throw e;
2611
- }
2612
- }
2613
-
2614
- //#endregion
2615
- //#region src/utils/create-bundler.ts
2616
- async function createBundler(inputOptions, outputOptions, isClose) {
2617
- const option = await createBundlerOptions(inputOptions, outputOptions, isClose);
2618
- try {
2619
- return {
2620
- bundler: new import_binding.Bundler(option.bundlerOptions),
2621
- stopWorkers: option.stopWorkers
2622
- };
2623
- } catch (e) {
2624
- await option.stopWorkers?.();
2625
- throw e;
2626
- }
2627
- }
2628
-
2629
- //#endregion
2630
- //#region src/api/rolldown/rolldown-build.ts
2631
- Symbol.asyncDispose ??= Symbol("Symbol.asyncDispose");
2632
- var RolldownBuild = class {
2633
- #inputOptions;
2634
- #bundler;
2635
- constructor(inputOptions) {
2636
- this.#inputOptions = inputOptions;
2637
- }
2638
- get closed() {
2639
- return this.#bundler ? this.#bundler.bundler.closed : false;
2640
- }
2641
- async #getBundlerWithStopWorker(outputOptions, isClose) {
2642
- if (this.#bundler) this.#bundler.stopWorkers?.();
2643
- return this.#bundler = await createBundler(this.#inputOptions, outputOptions, isClose);
2644
- }
2645
- async generate(outputOptions = {}) {
2646
- validateOption("output", outputOptions);
2647
- const { bundler } = await this.#getBundlerWithStopWorker(outputOptions);
2648
- const output = await bundler.generate();
2649
- return transformToRollupOutput(output);
2650
- }
2651
- async write(outputOptions = {}) {
2652
- validateOption("output", outputOptions);
2653
- const { bundler } = await this.#getBundlerWithStopWorker(outputOptions);
2654
- const output = await bundler.write();
2655
- return transformToRollupOutput(output);
2656
- }
2657
- async close() {
2658
- const { bundler, stopWorkers } = await this.#getBundlerWithStopWorker({}, true);
2659
- await stopWorkers?.();
2660
- await bundler.close();
2661
- }
2662
- async [Symbol.asyncDispose]() {
2663
- await this.close();
2664
- }
2665
- async generateHmrPatch(changedFiles) {
2666
- return this.#bundler?.bundler.generateHmrPatch(changedFiles);
2667
- }
2668
- };
2669
-
2670
- //#endregion
2671
- //#region src/api/rolldown/index.ts
2672
- const rolldown = async (input) => {
2673
- validateOption("input", input);
2674
- const inputOptions = await PluginDriver.callOptionsHook(input);
2675
- return new RolldownBuild(inputOptions);
2676
- };
2677
-
2678
- //#endregion
2679
- //#region src/api/watch/watch-emitter.ts
2680
- var WatcherEmitter = class {
2681
- listeners = new Map();
2682
- timer;
2683
- constructor() {
2684
- this.timer = setInterval(
2685
- () => {},
2686
- 1e9
2687
- /* Low power usage */
2688
- );
2689
- }
2690
- on(event, listener) {
2691
- const listeners = this.listeners.get(event);
2692
- if (listeners) listeners.push(listener);
2693
- else this.listeners.set(event, [listener]);
2694
- return this;
2695
- }
2696
- async onEvent(event) {
2697
- const listeners = this.listeners.get(event.eventKind());
2698
- if (listeners) switch (event.eventKind()) {
2699
- case "close":
2700
- case "restart":
2701
- for (const listener of listeners) await listener();
2702
- break;
2703
- case "event":
2704
- for (const listener of listeners) {
2705
- const code = event.bundleEventKind();
2706
- switch (code) {
2707
- case "BUNDLE_END":
2708
- const { duration, output } = event.bundleEndData();
2709
- await listener({
2710
- code: "BUNDLE_END",
2711
- duration,
2712
- output: [output]
2713
- });
2714
- break;
2715
- case "ERROR":
2716
- const errors = event.errors();
2717
- await listener({
2718
- code: "ERROR",
2719
- error: normalizeErrors(errors)
2720
- });
2721
- break;
2722
- default:
2723
- await listener({ code });
2724
- break;
2725
- }
2726
- }
2727
- break;
2728
- case "change":
2729
- for (const listener of listeners) {
2730
- const { path: path$1, kind } = event.watchChangeData();
2731
- await listener(path$1, { event: kind });
2732
- }
2733
- break;
2734
- default: throw new Error(`Unknown event: ${event}`);
2735
- }
2736
- }
2737
- async close() {
2738
- clearInterval(this.timer);
2739
- }
2740
- };
2741
-
2742
- //#endregion
2743
- //#region src/api/watch/watcher.ts
2744
- var Watcher = class {
2745
- closed;
2746
- inner;
2747
- emitter;
2748
- stopWorkers;
2749
- constructor(emitter, inner, stopWorkers) {
2750
- this.closed = false;
2751
- this.inner = inner;
2752
- this.emitter = emitter;
2753
- const originClose = emitter.close.bind(emitter);
2754
- emitter.close = async () => {
2755
- await this.close();
2756
- originClose();
2757
- };
2758
- this.stopWorkers = stopWorkers;
2759
- }
2760
- async close() {
2761
- if (this.closed) return;
2762
- this.closed = true;
2763
- for (const stop of this.stopWorkers) await stop?.();
2764
- await this.inner.close();
2765
- }
2766
- start() {
2767
- process.nextTick(() => this.inner.start(this.emitter.onEvent.bind(this.emitter)));
2768
- }
2769
- };
2770
- async function createWatcher(emitter, input) {
2771
- const options = arraify(input);
2772
- const bundlerOptions = await Promise.all(options.map((option) => arraify(option.output || {}).map(async (output) => {
2773
- const inputOptions = await PluginDriver.callOptionsHook(option);
2774
- return createBundlerOptions(inputOptions, output);
2775
- })).flat());
2776
- const notifyOptions = getValidNotifyOption(bundlerOptions);
2777
- const bindingWatcher = new import_binding.BindingWatcher(bundlerOptions.map((option) => option.bundlerOptions), notifyOptions);
2778
- const watcher = new Watcher(emitter, bindingWatcher, bundlerOptions.map((option) => option.stopWorkers));
2779
- watcher.start();
2780
- }
2781
- function getValidNotifyOption(bundlerOptions) {
2782
- let result;
2783
- for (const option of bundlerOptions) if (option.inputOptions.watch) {
2784
- const notifyOption = option.inputOptions.watch.notify;
2785
- if (notifyOption) if (result) {
2786
- option.onLog(LOG_LEVEL_WARN, logMultiplyNotifyOption());
2787
- return result;
2788
- } else result = notifyOption;
2789
- }
2790
- }
2791
-
2792
- //#endregion
2793
- //#region src/api/watch/index.ts
2794
- const watch = (input) => {
2795
- const emitter = new WatcherEmitter();
2796
- createWatcher(emitter, input);
2797
- return emitter;
2798
- };
2799
-
2800
- //#endregion
2801
- //#region package.json
2802
- var version = "1.0.0-beta.3-commit.e170e6e";
2803
- var description = "Fast JavaScript/TypeScript bundler in Rust with Rollup-compatible API.";
2804
-
2805
- //#endregion
2806
- //#region src/api/build.ts
2807
- async function build(options) {
2808
- if (Array.isArray(options)) return Promise.all(options.map((opts) => build(opts)));
2809
- else {
2810
- const { output, write = true,...inputOptions } = options;
2811
- const build$1 = await rolldown(inputOptions);
2812
- try {
2813
- if (write) return await build$1.write(output);
2814
- else return await build$1.generate(output);
2815
- } finally {
2816
- await build$1.close();
2817
- }
2818
- }
2819
- }
2820
-
2821
- //#endregion
2822
- //#region src/index.ts
2823
- const VERSION = version;
2824
-
2825
- //#endregion
2826
- export { BuiltinPlugin, PluginContextData, VERSION, arraify, bindingifyPlugin, build, buildImportAnalysisPlugin, composeJsPlugins, createBundler, defineConfig, description, dynamicImportVarsPlugin, getInputCliKeys, getJsonSchema, getOutputCliKeys, handleOutputErrors, importGlobPlugin, jsonPlugin, loadFallbackPlugin, manifestPlugin, moduleFederationPlugin, modulePreloadPolyfillPlugin, normalizedStringOrRegex, rolldown, validateCliOptions, version, viteResolvePlugin, wasmFallbackPlugin, wasmHelperPlugin, watch };