rolldown 1.0.0-beta.2-commit.5deb279 → 1.0.0-beta.21

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