UNPKG

rolldown

Version:

Fast JavaScript/TypeScript bundler in Rust with Rollup-compatible API.

1,637 lines (1,621 loc) • 149 kB
import { C as startAsyncRuntime, S as shutdownAsyncRuntime, c as BindingPluginOrder, f as BindingWatcher, g as initTraceSubscriber, i as BindingChunkModuleOrderBy, l as BindingPropertyReadSideEffects, n as BindingBundler, o as BindingLogLevel, p as ParallelJsPluginRegistry, r as BindingCallableBuiltinPlugin, s as BindingMagicString, t as BindingAttachDebugInfo, u as BindingPropertyWriteSideEffects } from "./binding-D7oxcV7l.mjs"; import { a as logCycleLoading, c as logDeprecatedInject, d as logInputHookInOutputPlugin, f as logInvalidLogPosition, h as styleText, i as error, l as logDeprecatedKeepNames, m as logPluginError, o as logDeprecatedDefine, p as logMultiplyNotifyOption, r as augmentCodeLocation, s as logDeprecatedDropLabels, t as parseAst, u as logDeprecatedProfilerNames } from "./parse-ast-index-lp33x2Wb.mjs"; import { a as unreachable, i as unimplemented, o as unsupported, r as noop, t as arraify } from "./misc-usdOVIou.mjs"; import { Worker, isMainThread } from "node:worker_threads"; import path from "node:path"; import * as filter from "@rolldown/pluginutils"; import fsp from "node:fs/promises"; import os from "node:os"; //#region ../../node_modules/.pnpm/signal-exit@4.1.0/node_modules/signal-exit/dist/mjs/signals.js /** * This is not the set of all possible signals. * * It IS, however, the set of all signals that trigger * an exit on either Linux or BSD systems. Linux is a * superset of the signal names supported on BSD, and * the unknown signals just fail to register, so we can * catch that easily enough. * * Windows signals are a different set, since there are * signals that terminate Windows processes, but don't * terminate (or don't even exist) on Posix systems. * * Don't bother with SIGKILL. It's uncatchable, which * means that we can't fire any callbacks anyway. * * If a user does happen to register a handler on a non- * fatal signal like SIGWINCH or something, and then * exit, it'll end up firing `process.emit('exit')`, so * the handler will be fired anyway. * * SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised * artificially, inherently leave the process in a * state from which it is not safe to try and enter JS * listeners. */ const signals = []; signals.push("SIGHUP", "SIGINT", "SIGTERM"); if (process.platform !== "win32") signals.push("SIGALRM", "SIGABRT", "SIGVTALRM", "SIGXCPU", "SIGXFSZ", "SIGUSR2", "SIGTRAP", "SIGSYS", "SIGQUIT", "SIGIOT"); if (process.platform === "linux") signals.push("SIGIO", "SIGPOLL", "SIGPWR", "SIGSTKFLT"); //#endregion //#region ../../node_modules/.pnpm/signal-exit@4.1.0/node_modules/signal-exit/dist/mjs/index.js const processOk = (process$2) => !!process$2 && typeof process$2 === "object" && typeof process$2.removeListener === "function" && typeof process$2.emit === "function" && typeof process$2.reallyExit === "function" && typeof process$2.listeners === "function" && typeof process$2.kill === "function" && typeof process$2.pid === "number" && typeof process$2.on === "function"; const kExitEmitter = Symbol.for("signal-exit emitter"); const global = globalThis; const ObjectDefineProperty = Object.defineProperty.bind(Object); var Emitter = class { emitted = { afterExit: false, exit: false }; listeners = { afterExit: [], exit: [] }; count = 0; id = Math.random(); constructor() { if (global[kExitEmitter]) return global[kExitEmitter]; ObjectDefineProperty(global, kExitEmitter, { value: this, writable: false, enumerable: false, configurable: false }); } on(ev, fn) { this.listeners[ev].push(fn); } removeListener(ev, fn) { const list = this.listeners[ev]; const i = list.indexOf(fn); /* c8 ignore start */ if (i === -1) return; /* c8 ignore stop */ if (i === 0 && list.length === 1) list.length = 0; else list.splice(i, 1); } emit(ev, code, signal) { if (this.emitted[ev]) return false; this.emitted[ev] = true; let ret = false; for (const fn of this.listeners[ev]) ret = fn(code, signal) === true || ret; if (ev === "exit") ret = this.emit("afterExit", code, signal) || ret; return ret; } }; var SignalExitBase = class {}; const signalExitWrap = (handler) => { return { onExit(cb, opts) { return handler.onExit(cb, opts); }, load() { return handler.load(); }, unload() { return handler.unload(); } }; }; var SignalExitFallback = class extends SignalExitBase { onExit() { return () => {}; } load() {} unload() {} }; var SignalExit = class extends SignalExitBase { /* c8 ignore start */ #hupSig = process$1.platform === "win32" ? "SIGINT" : "SIGHUP"; /* c8 ignore stop */ #emitter = new Emitter(); #process; #originalProcessEmit; #originalProcessReallyExit; #sigListeners = {}; #loaded = false; constructor(process$2) { super(); this.#process = process$2; this.#sigListeners = {}; for (const sig of signals) this.#sigListeners[sig] = () => { const listeners = this.#process.listeners(sig); let { count } = this.#emitter; /* c8 ignore start */ const p = process$2; if (typeof p.__signal_exit_emitter__ === "object" && typeof p.__signal_exit_emitter__.count === "number") count += p.__signal_exit_emitter__.count; /* c8 ignore stop */ if (listeners.length === count) { this.unload(); const ret = this.#emitter.emit("exit", null, sig); /* c8 ignore start */ const s = sig === "SIGHUP" ? this.#hupSig : sig; if (!ret) process$2.kill(process$2.pid, s); } }; this.#originalProcessReallyExit = process$2.reallyExit; this.#originalProcessEmit = process$2.emit; } onExit(cb, opts) { /* c8 ignore start */ if (!processOk(this.#process)) return () => {}; /* c8 ignore stop */ if (this.#loaded === false) this.load(); const ev = opts?.alwaysLast ? "afterExit" : "exit"; this.#emitter.on(ev, cb); return () => { this.#emitter.removeListener(ev, cb); if (this.#emitter.listeners["exit"].length === 0 && this.#emitter.listeners["afterExit"].length === 0) this.unload(); }; } load() { if (this.#loaded) return; this.#loaded = true; this.#emitter.count += 1; for (const sig of signals) try { const fn = this.#sigListeners[sig]; if (fn) this.#process.on(sig, fn); } catch (_) {} this.#process.emit = (ev, ...a) => { return this.#processEmit(ev, ...a); }; this.#process.reallyExit = (code) => { return this.#processReallyExit(code); }; } unload() { if (!this.#loaded) return; this.#loaded = false; signals.forEach((sig) => { const listener = this.#sigListeners[sig]; /* c8 ignore start */ if (!listener) throw new Error("Listener not defined for signal: " + sig); /* c8 ignore stop */ try { this.#process.removeListener(sig, listener); } catch (_) {} /* c8 ignore stop */ }); this.#process.emit = this.#originalProcessEmit; this.#process.reallyExit = this.#originalProcessReallyExit; this.#emitter.count -= 1; } #processReallyExit(code) { /* c8 ignore start */ if (!processOk(this.#process)) return 0; this.#process.exitCode = code || 0; /* c8 ignore stop */ this.#emitter.emit("exit", this.#process.exitCode, null); return this.#originalProcessReallyExit.call(this.#process, this.#process.exitCode); } #processEmit(ev, ...args$1) { const og = this.#originalProcessEmit; if (ev === "exit" && processOk(this.#process)) { if (typeof args$1[0] === "number") this.#process.exitCode = args$1[0]; /* c8 ignore start */ const ret = og.call(this.#process, ev, ...args$1); /* c8 ignore start */ this.#emitter.emit("exit", this.#process.exitCode, null); /* c8 ignore stop */ return ret; } else return og.call(this.#process, ev, ...args$1); } }; const process$1 = globalThis.process; const { onExit, load, unload } = signalExitWrap(processOk(process$1) ? new SignalExit(process$1) : new SignalExitFallback()); //#endregion //#region src/setup.ts if (isMainThread) { const subscriberGuard = initTraceSubscriber(); onExit(() => { subscriberGuard?.close(); }); } //#endregion //#region package.json var version = "1.0.0-beta.45"; var description$1 = "Fast JavaScript/TypeScript bundler in Rust with Rollup-compatible API."; //#endregion //#region src/builtin-plugin/utils.ts var BuiltinPlugin = class { constructor(name, _options) { this.name = name; this._options = _options; } }; function makeBuiltinPluginCallable(plugin) { let callablePlugin = new BindingCallableBuiltinPlugin(bindingifyBuiltInPlugin(plugin)); const wrappedPlugin = plugin; for (const key in callablePlugin) wrappedPlugin[key] = async function(...args$1) { try { return await callablePlugin[key](...args$1); } catch (e$1) { if (e$1 instanceof Error && !e$1.stack?.includes("at ")) Error.captureStackTrace(e$1, wrappedPlugin[key]); return error(logPluginError(e$1, plugin.name, { hook: key, id: key === "transform" ? args$1[2] : void 0 })); } }; return wrappedPlugin; } function bindingifyBuiltInPlugin(plugin) { return { __name: plugin.name, options: plugin._options }; } //#endregion //#region src/log/logging.ts const LOG_LEVEL_SILENT = "silent"; const LOG_LEVEL_ERROR = "error"; const LOG_LEVEL_WARN = "warn"; const LOG_LEVEL_INFO = "info"; const LOG_LEVEL_DEBUG = "debug"; const logLevelPriority = { [LOG_LEVEL_DEBUG]: 0, [LOG_LEVEL_INFO]: 1, [LOG_LEVEL_WARN]: 2, [LOG_LEVEL_SILENT]: 3 }; //#endregion //#region src/log/log-handler.ts const normalizeLog = (log) => typeof log === "string" ? { message: log } : typeof log === "function" ? normalizeLog(log()) : log; function getLogHandler(level, code, logger, pluginName, logLevel) { if (logLevelPriority[level] < logLevelPriority[logLevel]) return noop; return (log, pos) => { if (pos != null) logger(LOG_LEVEL_WARN, logInvalidLogPosition(pluginName)); log = normalizeLog(log); if (log.code && !log.pluginCode) log.pluginCode = log.code; log.code = code; log.plugin = pluginName; logger(level, log); }; } //#endregion //#region src/log/logger.ts function getLogger(plugins, onLog, logLevel, watchMode) { const minimalPriority = logLevelPriority[logLevel]; const logger = (level, log, skipped = /* @__PURE__ */ new Set()) => { if (logLevelPriority[level] < minimalPriority) return; for (const plugin of getSortedPlugins("onLog", plugins)) { if (skipped.has(plugin)) continue; const { onLog: pluginOnLog } = plugin; if (pluginOnLog) { const getLogHandler$1 = (level$1) => { if (logLevelPriority[level$1] < minimalPriority) return () => {}; return (log$1) => logger(level$1, normalizeLog(log$1), new Set(skipped).add(plugin)); }; if (("handler" in pluginOnLog ? pluginOnLog.handler : pluginOnLog).call({ debug: getLogHandler$1(LOG_LEVEL_DEBUG), error: (log$1) => error(normalizeLog(log$1)), info: getLogHandler$1(LOG_LEVEL_INFO), meta: { rollupVersion: "4.23.0", rolldownVersion: VERSION, watchMode }, warn: getLogHandler$1(LOG_LEVEL_WARN), pluginName: plugin.name || "unknown" }, level, log) === false) return; } } onLog(level, log); }; return logger; } const getOnLog = (config, logLevel, printLog = defaultPrintLog) => { const { onwarn, onLog } = config; const defaultOnLog = getDefaultOnLog(printLog, onwarn); if (onLog) { const minimalPriority = logLevelPriority[logLevel]; return (level, log) => onLog(level, addLogToString(log), (level$1, handledLog) => { if (level$1 === LOG_LEVEL_ERROR) return error(normalizeLog(handledLog)); if (logLevelPriority[level$1] >= minimalPriority) defaultOnLog(level$1, normalizeLog(handledLog)); }); } return defaultOnLog; }; const getDefaultOnLog = (printLog, onwarn) => onwarn ? (level, log) => { if (level === LOG_LEVEL_WARN) onwarn(addLogToString(log), (warning) => printLog(LOG_LEVEL_WARN, normalizeLog(warning))); else printLog(level, log); } : printLog; const addLogToString = (log) => { Object.defineProperty(log, "toString", { value: () => getExtendedLogMessage(log), writable: true }); return log; }; const defaultPrintLog = (level, log) => { const message = getExtendedLogMessage(log); switch (level) { case LOG_LEVEL_WARN: return console.warn(message); case LOG_LEVEL_DEBUG: return console.debug(message); default: return console.info(message); } }; const getExtendedLogMessage = (log) => { let prefix = ""; if (log.plugin) prefix += `(${log.plugin} plugin) `; if (log.loc) prefix += `${relativeId(log.loc.file)} (${log.loc.line}:${log.loc.column}) `; return prefix + log.message; }; function relativeId(id) { if (!path.isAbsolute(id)) return id; return path.relative(path.resolve(), id); } //#endregion //#region src/utils/normalize-hook.ts function normalizeHook(hook) { if (typeof hook === "function" || typeof hook === "string") return { handler: hook, options: {}, meta: {} }; if (typeof hook === "object" && hook !== null) { const { handler, order,...options } = hook; return { handler, options, meta: { order } }; } unreachable("Invalid hook type"); } //#endregion //#region src/constants/plugin.ts const ENUMERATED_INPUT_PLUGIN_HOOK_NAMES = [ "options", "buildStart", "resolveId", "load", "transform", "moduleParsed", "buildEnd", "onLog", "resolveDynamicImport", "closeBundle", "closeWatcher", "watchChange" ]; const ENUMERATED_OUTPUT_PLUGIN_HOOK_NAMES = [ "augmentChunkHash", "outputOptions", "renderChunk", "renderStart", "renderError", "writeBundle", "generateBundle" ]; const ENUMERATED_PLUGIN_HOOK_NAMES = [ ...ENUMERATED_INPUT_PLUGIN_HOOK_NAMES, ...ENUMERATED_OUTPUT_PLUGIN_HOOK_NAMES, "footer", "banner", "intro", "outro" ]; /** * Names of all defined hooks. It's like * ```js * const DEFINED_HOOK_NAMES ={ * options: 'options', * buildStart: 'buildStart', * ... * } * ``` */ const DEFINED_HOOK_NAMES = { [ENUMERATED_PLUGIN_HOOK_NAMES[0]]: ENUMERATED_PLUGIN_HOOK_NAMES[0], [ENUMERATED_PLUGIN_HOOK_NAMES[1]]: ENUMERATED_PLUGIN_HOOK_NAMES[1], [ENUMERATED_PLUGIN_HOOK_NAMES[2]]: ENUMERATED_PLUGIN_HOOK_NAMES[2], [ENUMERATED_PLUGIN_HOOK_NAMES[3]]: ENUMERATED_PLUGIN_HOOK_NAMES[3], [ENUMERATED_PLUGIN_HOOK_NAMES[4]]: ENUMERATED_PLUGIN_HOOK_NAMES[4], [ENUMERATED_PLUGIN_HOOK_NAMES[5]]: ENUMERATED_PLUGIN_HOOK_NAMES[5], [ENUMERATED_PLUGIN_HOOK_NAMES[6]]: ENUMERATED_PLUGIN_HOOK_NAMES[6], [ENUMERATED_PLUGIN_HOOK_NAMES[7]]: ENUMERATED_PLUGIN_HOOK_NAMES[7], [ENUMERATED_PLUGIN_HOOK_NAMES[8]]: ENUMERATED_PLUGIN_HOOK_NAMES[8], [ENUMERATED_PLUGIN_HOOK_NAMES[9]]: ENUMERATED_PLUGIN_HOOK_NAMES[9], [ENUMERATED_PLUGIN_HOOK_NAMES[10]]: ENUMERATED_PLUGIN_HOOK_NAMES[10], [ENUMERATED_PLUGIN_HOOK_NAMES[11]]: ENUMERATED_PLUGIN_HOOK_NAMES[11], [ENUMERATED_PLUGIN_HOOK_NAMES[12]]: ENUMERATED_PLUGIN_HOOK_NAMES[12], [ENUMERATED_PLUGIN_HOOK_NAMES[13]]: ENUMERATED_PLUGIN_HOOK_NAMES[13], [ENUMERATED_PLUGIN_HOOK_NAMES[14]]: ENUMERATED_PLUGIN_HOOK_NAMES[14], [ENUMERATED_PLUGIN_HOOK_NAMES[15]]: ENUMERATED_PLUGIN_HOOK_NAMES[15], [ENUMERATED_PLUGIN_HOOK_NAMES[16]]: ENUMERATED_PLUGIN_HOOK_NAMES[16], [ENUMERATED_PLUGIN_HOOK_NAMES[17]]: ENUMERATED_PLUGIN_HOOK_NAMES[17], [ENUMERATED_PLUGIN_HOOK_NAMES[18]]: ENUMERATED_PLUGIN_HOOK_NAMES[18], [ENUMERATED_PLUGIN_HOOK_NAMES[19]]: ENUMERATED_PLUGIN_HOOK_NAMES[19], [ENUMERATED_PLUGIN_HOOK_NAMES[20]]: ENUMERATED_PLUGIN_HOOK_NAMES[20], [ENUMERATED_PLUGIN_HOOK_NAMES[21]]: ENUMERATED_PLUGIN_HOOK_NAMES[21], [ENUMERATED_PLUGIN_HOOK_NAMES[22]]: ENUMERATED_PLUGIN_HOOK_NAMES[22] }; //#endregion //#region src/utils/async-flatten.ts async function asyncFlatten(array$1) { do array$1 = (await Promise.all(array$1)).flat(Infinity); while (array$1.some((v) => v?.then)); return array$1; } //#endregion //#region src/utils/normalize-plugin-option.ts const normalizePluginOption = async (plugins) => (await asyncFlatten([plugins])).filter(Boolean); function checkOutputPluginOption(plugins, onLog) { for (const plugin of plugins) for (const hook of ENUMERATED_INPUT_PLUGIN_HOOK_NAMES) if (hook in plugin) { delete plugin[hook]; onLog(LOG_LEVEL_WARN, logInputHookInOutputPlugin(plugin.name, hook)); } return plugins; } function normalizePlugins(plugins, anonymousPrefix) { for (const [index, plugin] of plugins.entries()) { if ("_parallel" in plugin) continue; if (plugin instanceof BuiltinPlugin) continue; if (!plugin.name) plugin.name = `${anonymousPrefix}${index + 1}`; } return plugins; } const ANONYMOUS_PLUGIN_PREFIX = "at position "; const ANONYMOUS_OUTPUT_PLUGIN_PREFIX = "at output position "; //#endregion //#region src/plugin/minimal-plugin-context.ts var MinimalPluginContextImpl = class { info; warn; debug; meta; constructor(onLog, logLevel, pluginName, watchMode, hookName) { this.pluginName = pluginName; this.hookName = hookName; this.debug = getLogHandler(LOG_LEVEL_DEBUG, "PLUGIN_LOG", onLog, pluginName, logLevel); this.info = getLogHandler(LOG_LEVEL_INFO, "PLUGIN_LOG", onLog, pluginName, logLevel); this.warn = getLogHandler(LOG_LEVEL_WARN, "PLUGIN_WARNING", onLog, pluginName, logLevel); this.meta = { rollupVersion: "4.23.0", rolldownVersion: VERSION, watchMode }; } error(e$1) { return error(logPluginError(normalizeLog(e$1), this.pluginName, { hook: this.hookName })); } }; //#endregion //#region src/plugin/plugin-driver.ts var PluginDriver = class { static async callOptionsHook(inputOptions, watchMode = false) { const logLevel = inputOptions.logLevel || LOG_LEVEL_INFO; const plugins = getSortedPlugins("options", getObjectPlugins(await normalizePluginOption(inputOptions.plugins))); const logger = getLogger(plugins, getOnLog(inputOptions, logLevel), logLevel, watchMode); for (const plugin of plugins) { const name = plugin.name || "unknown"; const options = plugin.options; if (options) { const { handler } = normalizeHook(options); const result = await handler.call(new MinimalPluginContextImpl(logger, logLevel, name, watchMode, "onLog"), inputOptions); if (result) inputOptions = result; } } return inputOptions; } static callOutputOptionsHook(rawPlugins, outputOptions, onLog, logLevel, watchMode) { const sortedPlugins = getSortedPlugins("outputOptions", getObjectPlugins(rawPlugins)); for (const plugin of sortedPlugins) { const name = plugin.name || "unknown"; const options = plugin.outputOptions; if (options) { const { handler } = normalizeHook(options); const result = handler.call(new MinimalPluginContextImpl(onLog, logLevel, name, watchMode), outputOptions); if (result) outputOptions = result; } } return outputOptions; } }; function getObjectPlugins(plugins) { return plugins.filter((plugin) => { if (!plugin) return; if ("_parallel" in plugin) return; if (plugin instanceof BuiltinPlugin) return; return plugin; }); } function getSortedPlugins(hookName, plugins) { const pre = []; const normal = []; const post = []; for (const plugin of plugins) { const hook = plugin[hookName]; if (hook) { if (typeof hook === "object") { if (hook.order === "pre") { pre.push(plugin); continue; } if (hook.order === "post") { post.push(plugin); continue; } } normal.push(plugin); } } return [ ...pre, ...normal, ...post ]; } //#endregion //#region ../../node_modules/.pnpm/valibot@1.1.0_typescript@5.9.3/node_modules/valibot/dist/index.js var store; /* @__NO_SIDE_EFFECTS__ */ function getGlobalConfig(config2) { return { lang: config2?.lang ?? store?.lang, message: config2?.message, abortEarly: config2?.abortEarly ?? store?.abortEarly, abortPipeEarly: config2?.abortPipeEarly ?? store?.abortPipeEarly }; } var store2; /* @__NO_SIDE_EFFECTS__ */ function getGlobalMessage(lang) { return store2?.get(lang); } var store3; /* @__NO_SIDE_EFFECTS__ */ function getSchemaMessage(lang) { return store3?.get(lang); } var store4; /* @__NO_SIDE_EFFECTS__ */ function getSpecificMessage(reference, lang) { return store4?.get(reference)?.get(lang); } /* @__NO_SIDE_EFFECTS__ */ function _stringify(input) { const type = typeof input; if (type === "string") return `"${input}"`; if (type === "number" || type === "bigint" || type === "boolean") return `${input}`; if (type === "object" || type === "function") return (input && Object.getPrototypeOf(input)?.constructor?.name) ?? "null"; return type; } function _addIssue(context, label, dataset, config2, other) { const input = other && "input" in other ? other.input : dataset.value; const expected = other?.expected ?? context.expects ?? null; const received = other?.received ?? /* @__PURE__ */ _stringify(input); const issue = { kind: context.kind, type: context.type, input, expected, received, message: `Invalid ${label}: ${expected ? `Expected ${expected} but r` : "R"}eceived ${received}`, requirement: context.requirement, path: other?.path, issues: other?.issues, lang: config2.lang, abortEarly: config2.abortEarly, abortPipeEarly: config2.abortPipeEarly }; const isSchema = context.kind === "schema"; const message2 = other?.message ?? context.message ?? /* @__PURE__ */ getSpecificMessage(context.reference, issue.lang) ?? (isSchema ? /* @__PURE__ */ getSchemaMessage(issue.lang) : null) ?? config2.message ?? /* @__PURE__ */ getGlobalMessage(issue.lang); if (message2 !== void 0) issue.message = typeof message2 === "function" ? message2(issue) : message2; if (isSchema) dataset.typed = false; if (dataset.issues) dataset.issues.push(issue); else dataset.issues = [issue]; } /* @__NO_SIDE_EFFECTS__ */ function _getStandardProps(context) { return { version: 1, vendor: "valibot", validate(value2) { return context["~run"]({ value: value2 }, /* @__PURE__ */ getGlobalConfig()); } }; } /* @__NO_SIDE_EFFECTS__ */ function _isValidObjectKey(object2, key) { return Object.hasOwn(object2, key) && key !== "__proto__" && key !== "prototype" && key !== "constructor"; } /* @__NO_SIDE_EFFECTS__ */ function _joinExpects(values2, separator) { const list = [...new Set(values2)]; if (list.length > 1) return `(${list.join(` ${separator} `)})`; return list[0] ?? "never"; } var ValiError = class extends Error { /** * Creates a Valibot error with useful information. * * @param issues The error issues. */ constructor(issues) { super(issues[0].message); this.name = "ValiError"; this.issues = issues; } }; /* @__NO_SIDE_EFFECTS__ */ function args(schema) { return { kind: "transformation", type: "args", reference: args, async: false, schema, "~run"(dataset, config2) { const func = dataset.value; dataset.value = (...args_) => { const argsDataset = this.schema["~run"]({ value: args_ }, config2); if (argsDataset.issues) throw new ValiError(argsDataset.issues); return func(...argsDataset.value); }; return dataset; } }; } /* @__NO_SIDE_EFFECTS__ */ function awaitAsync() { return { kind: "transformation", type: "await", reference: awaitAsync, async: true, async "~run"(dataset) { dataset.value = await dataset.value; return dataset; } }; } /* @__NO_SIDE_EFFECTS__ */ function description(description_) { return { kind: "metadata", type: "description", reference: description, description: description_ }; } /* @__NO_SIDE_EFFECTS__ */ function returns(schema) { return { kind: "transformation", type: "returns", reference: returns, async: false, schema, "~run"(dataset, config2) { const func = dataset.value; dataset.value = (...args_) => { const returnsDataset = this.schema["~run"]({ value: func(...args_) }, config2); if (returnsDataset.issues) throw new ValiError(returnsDataset.issues); return returnsDataset.value; }; return dataset; } }; } /* @__NO_SIDE_EFFECTS__ */ function returnsAsync(schema) { return { kind: "transformation", type: "returns", reference: returnsAsync, async: false, schema, "~run"(dataset, config2) { const func = dataset.value; dataset.value = async (...args_) => { const returnsDataset = await this.schema["~run"]({ value: await func(...args_) }, config2); if (returnsDataset.issues) throw new ValiError(returnsDataset.issues); return returnsDataset.value; }; return dataset; } }; } /* @__NO_SIDE_EFFECTS__ */ function getFallback(schema, dataset, config2) { return typeof schema.fallback === "function" ? schema.fallback(dataset, config2) : schema.fallback; } /* @__NO_SIDE_EFFECTS__ */ function getDefault(schema, dataset, config2) { return typeof schema.default === "function" ? schema.default(dataset, config2) : schema.default; } /* @__NO_SIDE_EFFECTS__ */ function any() { return { kind: "schema", type: "any", reference: any, expects: "any", async: false, get "~standard"() { return /* @__PURE__ */ _getStandardProps(this); }, "~run"(dataset) { dataset.typed = true; return dataset; } }; } /* @__NO_SIDE_EFFECTS__ */ function array(item, message2) { return { kind: "schema", type: "array", reference: array, expects: "Array", async: false, item, message: message2, get "~standard"() { return /* @__PURE__ */ _getStandardProps(this); }, "~run"(dataset, config2) { const input = dataset.value; if (Array.isArray(input)) { dataset.typed = true; dataset.value = []; for (let key = 0; key < input.length; key++) { const value2 = input[key]; const itemDataset = this.item["~run"]({ value: value2 }, config2); if (itemDataset.issues) { const pathItem = { type: "array", origin: "value", input, key, value: value2 }; for (const issue of itemDataset.issues) { if (issue.path) issue.path.unshift(pathItem); else issue.path = [pathItem]; dataset.issues?.push(issue); } if (!dataset.issues) dataset.issues = itemDataset.issues; if (config2.abortEarly) { dataset.typed = false; break; } } if (!itemDataset.typed) dataset.typed = false; dataset.value.push(itemDataset.value); } } else _addIssue(this, "type", dataset, config2); return dataset; } }; } /* @__NO_SIDE_EFFECTS__ */ function boolean(message2) { return { kind: "schema", type: "boolean", reference: boolean, expects: "boolean", async: false, message: message2, get "~standard"() { return /* @__PURE__ */ _getStandardProps(this); }, "~run"(dataset, config2) { if (typeof dataset.value === "boolean") dataset.typed = true; else _addIssue(this, "type", dataset, config2); return dataset; } }; } /* @__NO_SIDE_EFFECTS__ */ function custom(check2, message2) { return { kind: "schema", type: "custom", reference: custom, expects: "unknown", async: false, check: check2, message: message2, get "~standard"() { return /* @__PURE__ */ _getStandardProps(this); }, "~run"(dataset, config2) { if (this.check(dataset.value)) dataset.typed = true; else _addIssue(this, "type", dataset, config2); return dataset; } }; } /* @__NO_SIDE_EFFECTS__ */ function function_(message2) { return { kind: "schema", type: "function", reference: function_, expects: "Function", async: false, message: message2, get "~standard"() { return /* @__PURE__ */ _getStandardProps(this); }, "~run"(dataset, config2) { if (typeof dataset.value === "function") dataset.typed = true; else _addIssue(this, "type", dataset, config2); return dataset; } }; } /* @__NO_SIDE_EFFECTS__ */ function instance(class_, message2) { return { kind: "schema", type: "instance", reference: instance, expects: class_.name, async: false, class: class_, message: message2, get "~standard"() { return /* @__PURE__ */ _getStandardProps(this); }, "~run"(dataset, config2) { if (dataset.value instanceof this.class) dataset.typed = true; else _addIssue(this, "type", dataset, config2); return dataset; } }; } /* @__NO_SIDE_EFFECTS__ */ function literal(literal_, message2) { return { kind: "schema", type: "literal", reference: literal, expects: /* @__PURE__ */ _stringify(literal_), async: false, literal: literal_, message: message2, get "~standard"() { return /* @__PURE__ */ _getStandardProps(this); }, "~run"(dataset, config2) { if (dataset.value === this.literal) dataset.typed = true; else _addIssue(this, "type", dataset, config2); return dataset; } }; } /* @__NO_SIDE_EFFECTS__ */ function looseObject(entries2, message2) { return { kind: "schema", type: "loose_object", reference: looseObject, expects: "Object", async: false, entries: entries2, message: message2, get "~standard"() { return /* @__PURE__ */ _getStandardProps(this); }, "~run"(dataset, config2) { const input = dataset.value; if (input && typeof input === "object") { dataset.typed = true; dataset.value = {}; for (const key in this.entries) { const valueSchema = this.entries[key]; if (key in input || (valueSchema.type === "exact_optional" || valueSchema.type === "optional" || valueSchema.type === "nullish") && valueSchema.default !== void 0) { const value2 = key in input ? input[key] : /* @__PURE__ */ getDefault(valueSchema); const valueDataset = valueSchema["~run"]({ value: value2 }, config2); if (valueDataset.issues) { const pathItem = { type: "object", origin: "value", input, key, value: value2 }; for (const issue of valueDataset.issues) { if (issue.path) issue.path.unshift(pathItem); else issue.path = [pathItem]; dataset.issues?.push(issue); } if (!dataset.issues) dataset.issues = valueDataset.issues; if (config2.abortEarly) { dataset.typed = false; break; } } if (!valueDataset.typed) dataset.typed = false; dataset.value[key] = valueDataset.value; } else if (valueSchema.fallback !== void 0) dataset.value[key] = /* @__PURE__ */ getFallback(valueSchema); else if (valueSchema.type !== "exact_optional" && valueSchema.type !== "optional" && valueSchema.type !== "nullish") { _addIssue(this, "key", dataset, config2, { input: void 0, expected: `"${key}"`, path: [{ type: "object", origin: "key", input, key, value: input[key] }] }); if (config2.abortEarly) break; } } if (!dataset.issues || !config2.abortEarly) { for (const key in input) if (/* @__PURE__ */ _isValidObjectKey(input, key) && !(key in this.entries)) dataset.value[key] = input[key]; } } else _addIssue(this, "type", dataset, config2); return dataset; } }; } /* @__NO_SIDE_EFFECTS__ */ function never(message2) { return { kind: "schema", type: "never", reference: never, expects: "never", async: false, message: message2, get "~standard"() { return /* @__PURE__ */ _getStandardProps(this); }, "~run"(dataset, config2) { _addIssue(this, "type", dataset, config2); return dataset; } }; } /* @__NO_SIDE_EFFECTS__ */ function nullish(wrapped, default_) { return { kind: "schema", type: "nullish", reference: nullish, expects: `(${wrapped.expects} | null | undefined)`, async: false, wrapped, default: default_, get "~standard"() { return /* @__PURE__ */ _getStandardProps(this); }, "~run"(dataset, config2) { if (dataset.value === null || dataset.value === void 0) { if (this.default !== void 0) dataset.value = /* @__PURE__ */ getDefault(this, dataset, config2); if (dataset.value === null || dataset.value === void 0) { dataset.typed = true; return dataset; } } return this.wrapped["~run"](dataset, config2); } }; } /* @__NO_SIDE_EFFECTS__ */ function number(message2) { return { kind: "schema", type: "number", reference: number, expects: "number", async: false, message: message2, get "~standard"() { return /* @__PURE__ */ _getStandardProps(this); }, "~run"(dataset, config2) { if (typeof dataset.value === "number" && !isNaN(dataset.value)) dataset.typed = true; else _addIssue(this, "type", dataset, config2); return dataset; } }; } /* @__NO_SIDE_EFFECTS__ */ function object(entries2, message2) { return { kind: "schema", type: "object", reference: object, expects: "Object", async: false, entries: entries2, message: message2, get "~standard"() { return /* @__PURE__ */ _getStandardProps(this); }, "~run"(dataset, config2) { const input = dataset.value; if (input && typeof input === "object") { dataset.typed = true; dataset.value = {}; for (const key in this.entries) { const valueSchema = this.entries[key]; if (key in input || (valueSchema.type === "exact_optional" || valueSchema.type === "optional" || valueSchema.type === "nullish") && valueSchema.default !== void 0) { const value2 = key in input ? input[key] : /* @__PURE__ */ getDefault(valueSchema); const valueDataset = valueSchema["~run"]({ value: value2 }, config2); if (valueDataset.issues) { const pathItem = { type: "object", origin: "value", input, key, value: value2 }; for (const issue of valueDataset.issues) { if (issue.path) issue.path.unshift(pathItem); else issue.path = [pathItem]; dataset.issues?.push(issue); } if (!dataset.issues) dataset.issues = valueDataset.issues; if (config2.abortEarly) { dataset.typed = false; break; } } if (!valueDataset.typed) dataset.typed = false; dataset.value[key] = valueDataset.value; } else if (valueSchema.fallback !== void 0) dataset.value[key] = /* @__PURE__ */ getFallback(valueSchema); else if (valueSchema.type !== "exact_optional" && valueSchema.type !== "optional" && valueSchema.type !== "nullish") { _addIssue(this, "key", dataset, config2, { input: void 0, expected: `"${key}"`, path: [{ type: "object", origin: "key", input, key, value: input[key] }] }); if (config2.abortEarly) break; } } } else _addIssue(this, "type", dataset, config2); return dataset; } }; } /* @__NO_SIDE_EFFECTS__ */ function optional(wrapped, default_) { return { kind: "schema", type: "optional", reference: optional, expects: `(${wrapped.expects} | undefined)`, async: false, wrapped, default: default_, get "~standard"() { return /* @__PURE__ */ _getStandardProps(this); }, "~run"(dataset, config2) { if (dataset.value === void 0) { if (this.default !== void 0) dataset.value = /* @__PURE__ */ getDefault(this, dataset, config2); if (dataset.value === void 0) { dataset.typed = true; return dataset; } } return this.wrapped["~run"](dataset, config2); } }; } /* @__NO_SIDE_EFFECTS__ */ function picklist(options, message2) { return { kind: "schema", type: "picklist", reference: picklist, expects: /* @__PURE__ */ _joinExpects(options.map(_stringify), "|"), async: false, options, message: message2, get "~standard"() { return /* @__PURE__ */ _getStandardProps(this); }, "~run"(dataset, config2) { if (this.options.includes(dataset.value)) dataset.typed = true; else _addIssue(this, "type", dataset, config2); return dataset; } }; } /* @__NO_SIDE_EFFECTS__ */ function promise(message2) { return { kind: "schema", type: "promise", reference: promise, expects: "Promise", async: false, message: message2, get "~standard"() { return /* @__PURE__ */ _getStandardProps(this); }, "~run"(dataset, config2) { if (dataset.value instanceof Promise) dataset.typed = true; else _addIssue(this, "type", dataset, config2); return dataset; } }; } /* @__NO_SIDE_EFFECTS__ */ function record(key, value2, message2) { return { kind: "schema", type: "record", reference: record, expects: "Object", async: false, key, value: value2, message: message2, get "~standard"() { return /* @__PURE__ */ _getStandardProps(this); }, "~run"(dataset, config2) { const input = dataset.value; if (input && typeof input === "object") { dataset.typed = true; dataset.value = {}; for (const entryKey in input) if (/* @__PURE__ */ _isValidObjectKey(input, entryKey)) { const entryValue = input[entryKey]; const keyDataset = this.key["~run"]({ value: entryKey }, config2); if (keyDataset.issues) { const pathItem = { type: "object", origin: "key", input, key: entryKey, value: entryValue }; for (const issue of keyDataset.issues) { issue.path = [pathItem]; dataset.issues?.push(issue); } if (!dataset.issues) dataset.issues = keyDataset.issues; if (config2.abortEarly) { dataset.typed = false; break; } } const valueDataset = this.value["~run"]({ value: entryValue }, config2); if (valueDataset.issues) { const pathItem = { type: "object", origin: "value", input, key: entryKey, value: entryValue }; for (const issue of valueDataset.issues) { if (issue.path) issue.path.unshift(pathItem); else issue.path = [pathItem]; dataset.issues?.push(issue); } if (!dataset.issues) dataset.issues = valueDataset.issues; if (config2.abortEarly) { dataset.typed = false; break; } } if (!keyDataset.typed || !valueDataset.typed) dataset.typed = false; if (keyDataset.typed) dataset.value[keyDataset.value] = valueDataset.value; } } else _addIssue(this, "type", dataset, config2); return dataset; } }; } /* @__NO_SIDE_EFFECTS__ */ function strictObject(entries2, message2) { return { kind: "schema", type: "strict_object", reference: strictObject, expects: "Object", async: false, entries: entries2, message: message2, get "~standard"() { return /* @__PURE__ */ _getStandardProps(this); }, "~run"(dataset, config2) { const input = dataset.value; if (input && typeof input === "object") { dataset.typed = true; dataset.value = {}; for (const key in this.entries) { const valueSchema = this.entries[key]; if (key in input || (valueSchema.type === "exact_optional" || valueSchema.type === "optional" || valueSchema.type === "nullish") && valueSchema.default !== void 0) { const value2 = key in input ? input[key] : /* @__PURE__ */ getDefault(valueSchema); const valueDataset = valueSchema["~run"]({ value: value2 }, config2); if (valueDataset.issues) { const pathItem = { type: "object", origin: "value", input, key, value: value2 }; for (const issue of valueDataset.issues) { if (issue.path) issue.path.unshift(pathItem); else issue.path = [pathItem]; dataset.issues?.push(issue); } if (!dataset.issues) dataset.issues = valueDataset.issues; if (config2.abortEarly) { dataset.typed = false; break; } } if (!valueDataset.typed) dataset.typed = false; dataset.value[key] = valueDataset.value; } else if (valueSchema.fallback !== void 0) dataset.value[key] = /* @__PURE__ */ getFallback(valueSchema); else if (valueSchema.type !== "exact_optional" && valueSchema.type !== "optional" && valueSchema.type !== "nullish") { _addIssue(this, "key", dataset, config2, { input: void 0, expected: `"${key}"`, path: [{ type: "object", origin: "key", input, key, value: input[key] }] }); if (config2.abortEarly) break; } } if (!dataset.issues || !config2.abortEarly) { for (const key in input) if (!(key in this.entries)) { _addIssue(this, "key", dataset, config2, { input: key, expected: "never", path: [{ type: "object", origin: "key", input, key, value: input[key] }] }); break; } } } else _addIssue(this, "type", dataset, config2); return dataset; } }; } /* @__NO_SIDE_EFFECTS__ */ function string(message2) { return { kind: "schema", type: "string", reference: string, expects: "string", async: false, message: message2, get "~standard"() { return /* @__PURE__ */ _getStandardProps(this); }, "~run"(dataset, config2) { if (typeof dataset.value === "string") dataset.typed = true; else _addIssue(this, "type", dataset, config2); return dataset; } }; } /* @__NO_SIDE_EFFECTS__ */ function tuple(items, message2) { return { kind: "schema", type: "tuple", reference: tuple, expects: "Array", async: false, items, message: message2, get "~standard"() { return /* @__PURE__ */ _getStandardProps(this); }, "~run"(dataset, config2) { const input = dataset.value; if (Array.isArray(input)) { dataset.typed = true; dataset.value = []; for (let key = 0; key < this.items.length; key++) { const value2 = input[key]; const itemDataset = this.items[key]["~run"]({ value: value2 }, config2); if (itemDataset.issues) { const pathItem = { type: "array", origin: "value", input, key, value: value2 }; for (const issue of itemDataset.issues) { if (issue.path) issue.path.unshift(pathItem); else issue.path = [pathItem]; dataset.issues?.push(issue); } if (!dataset.issues) dataset.issues = itemDataset.issues; if (config2.abortEarly) { dataset.typed = false; break; } } if (!itemDataset.typed) dataset.typed = false; dataset.value.push(itemDataset.value); } } else _addIssue(this, "type", dataset, config2); return dataset; } }; } /* @__NO_SIDE_EFFECTS__ */ function undefined_(message2) { return { kind: "schema", type: "undefined", reference: undefined_, expects: "undefined", async: false, message: message2, get "~standard"() { return /* @__PURE__ */ _getStandardProps(this); }, "~run"(dataset, config2) { if (dataset.value === void 0) dataset.typed = true; else _addIssue(this, "type", dataset, config2); return dataset; } }; } /* @__NO_SIDE_EFFECTS__ */ function _subIssues(datasets) { let issues; if (datasets) for (const dataset of datasets) if (issues) issues.push(...dataset.issues); else issues = dataset.issues; return issues; } /* @__NO_SIDE_EFFECTS__ */ function union(options, message2) { return { kind: "schema", type: "union", reference: union, expects: /* @__PURE__ */ _joinExpects(options.map((option) => option.expects), "|"), async: false, options, message: message2, get "~standard"() { return /* @__PURE__ */ _getStandardProps(this); }, "~run"(dataset, config2) { let validDataset; let typedDatasets; let untypedDatasets; for (const schema of this.options) { const optionDataset = schema["~run"]({ value: dataset.value }, config2); if (optionDataset.typed) if (optionDataset.issues) if (typedDatasets) typedDatasets.push(optionDataset); else typedDatasets = [optionDataset]; else { validDataset = optionDataset; break; } else if (untypedDatasets) untypedDatasets.push(optionDataset); else untypedDatasets = [optionDataset]; } if (validDataset) return validDataset; if (typedDatasets) { if (typedDatasets.length === 1) return typedDatasets[0]; _addIssue(this, "type", dataset, config2, { issues: /* @__PURE__ */ _subIssues(typedDatasets) }); dataset.typed = true; } else if (untypedDatasets?.length === 1) return untypedDatasets[0]; else _addIssue(this, "type", dataset, config2, { issues: /* @__PURE__ */ _subIssues(untypedDatasets) }); return dataset; } }; } /* @__NO_SIDE_EFFECTS__ */ function unionAsync(options, message2) { return { kind: "schema", type: "union", reference: unionAsync, expects: /* @__PURE__ */ _joinExpects(options.map((option) => option.expects), "|"), async: true, options, message: message2, get "~standard"() { return /* @__PURE__ */ _getStandardProps(this); }, async "~run"(dataset, config2) { let validDataset; let typedDatasets; let untypedDatasets; for (const schema of this.options) { const optionDataset = await schema["~run"]({ value: dataset.value }, config2); if (optionDataset.typed) if (optionDataset.issues) if (typedDatasets) typedDatasets.push(optionDataset); else typedDatasets = [optionDataset]; else { validDataset = optionDataset; break; } else if (untypedDatasets) untypedDatasets.push(optionDataset); else untypedDatasets = [optionDataset]; } if (validDataset) return validDataset; if (typedDatasets) { if (typedDatasets.length === 1) return typedDatasets[0]; _addIssue(this, "type", dataset, config2, { issues: /* @__PURE__ */ _subIssues(typedDatasets) }); dataset.typed = true; } else if (untypedDatasets?.length === 1) return untypedDatasets[0]; else _addIssue(this, "type", dataset, config2, { issues: /* @__PURE__ */ _subIssues(untypedDatasets) }); return dataset; } }; } /* @__NO_SIDE_EFFECTS__ */ function void_(message2) { return { kind: "schema", type: "void", reference: void_, expects: "void", async: false, message: message2, get "~standard"() { return /* @__PURE__ */ _getStandardProps(this); }, "~run"(dataset, config2) { if (dataset.value === void 0) dataset.typed = true; else _addIssue(this, "type", dataset, config2); return dataset; } }; } /* @__NO_SIDE_EFFECTS__ */ function keyof(schema, message2) { return /* @__PURE__ */ picklist(Object.keys(schema.entries), message2); } /* @__NO_SIDE_EFFECTS__ */ function omit(schema, keys) { const entries2 = { ...schema.entries }; for (const key of keys) delete entries2[key]; return { ...schema, entries: entries2, get "~standard"() { return /* @__PURE__ */ _getStandardProps(this); } }; } /* @__NO_SIDE_EFFECTS__ */ function partial(schema, keys) { const entries2 = {}; for (const key in schema.entries) entries2[key] = !keys || keys.includes(key) ? /* @__PURE__ */ optional(schema.entries[key]) : schema.entries[key]; return { ...schema, entries: entries2, get "~standard"() { return /* @__PURE__ */ _getStandardProps(this); } }; } /* @__NO_SIDE_EFFECTS__ */ function pipe(...pipe2) { return { ...pipe2[0], pipe: pipe2, get "~standard"() { return /* @__PURE__ */ _getStandardProps(this); }, "~run"(dataset, config2) { for (const item of pipe2) if (item.kind !== "metadata") { if (dataset.issues && (item.kind === "schema" || item.kind === "transformation")) { dataset.typed = false; break; } if (!dataset.issues || !config2.abortEarly && !config2.abortPipeEarly) dataset = item["~run"](dataset, config2); } return dataset; } }; } /* @__NO_SIDE_EFFECTS__ */ function pipeAsync(...pipe2) { return { ...pipe2[0], pipe: pipe2, async: true, get "~standard"() { return /* @__PURE__ */ _getStandardProps(this); }, async "~run"(dataset, config2) { for (const item of pipe2) if (item.kind !== "metadata") { if (dataset.issues && (item.kind === "schema" || item.kind === "transformation")) { dataset.typed = false; break; } if (!dataset.issues || !config2.abortEarly && !config2.abortPipeEarly) dataset = await item["~run"](dataset, config2); } return dataset; } }; } /* @__NO_SIDE_EFFECTS__ */ function safeParse(schema, input, config2) { const dataset = schema["~run"]({ value: input }, /* @__PURE__ */ getGlobalConfig(config2)); return { typed: dataset.typed, success: !dataset.issues, output: dataset.value, issues: dataset.issues }; } //#endregion //#region src/utils/flatten-valibot-schema.ts function unwrapSchema(schema) { if (!schema) return schema; if (schema.type === "optional" && schema.wrapped) return unwrapSchema(schema.wrapped); if (schema.type === "nullable" && schema.wrapped) return unwrapSchema(schema.wrapped); if (schema.type === "nullish" && schema.wrapped) return unwrapSchema(schema.wrapped); return schema; } function getValibotSchemaType(schema) { if (!schema) return "any"; if (schema.type) switch (schema.type) { case "string": return "string"; case "number": return "number"; case "boolean": return "boolean"; case "array": return "array"; case "object": case "strict_object": case "loose_object": return "object"; case "union": return "union"; case "literal": return typeof schema.literal; case "record": return "object"; case "optional": return getValibotSchemaType(schema.wrapped); case "nullable": return getValibotSchemaType(schema.wrapped); case "nullish": return getValibotSchemaType(schema.wrapped); case "never": return "never"; case "any": return "any"; case "custom": return "any"; case "function": return "never"; case "instance": return "object"; default: return "any"; } return "any"; } function getValibotDescription(schema) { if (!schema) return void 0; if (schema.pipe && Array.isArray(schema.pipe)) { for (const action of schema.pipe) if (action.type === "description" && action.description) return action.description; } if (schema.type === "optional" && schema.wrapped) return getValibotDescription(schema.wrapped); } function flattenValibotSchema(schema, result = {}, prefix = "") { if (!schema || typeof schema !== "object") return result; if (schema.type === "strict_object" || schema.type === "object" || schema.type === "loose_object") { if (schema.entries && typeof schema.entries === "object") for (const [key, value] of Object.entries(schema.entries)) { const fullKey = prefix ? `${prefix}.${key}` : key; const valueSchema = value; const type = getValibotSchemaType(valueSchema); const description$2 = getValibotDescription(valueSchema); if (type === "object") { const unwrappedSchema = unwrapSchema(