import { augmentCodeLocation, colors, error, import_binding, logCycleLoading, logInputHookInOutputPlugin, logInvalidLogPosition, logMinifyWarning, logMultiplyNotifyOption, logPluginError, parseAst } from "./parse-ast-index-CVCVLNV5.mjs";
import path from "node:path";
import * as v from "valibot";
import { toJsonSchema } from "@valibot/to-json-schema";
import { Buffer } from "node:buffer";
import { Worker } from "node:worker_threads";
import { availableParallelism } from "node:os";

//#region src/utils/define-config.ts
function defineConfig(config) {
	return config;
}

//#endregion
//#region src/utils/misc.ts
function arraify(value) {
	return Array.isArray(value) ? value : [value];
}
function isNullish(value) {
	return value === null || value === void 0;
}
function unimplemented(info) {
	if (info) throw new Error(`unimplemented: ${info}`);
	throw new Error("unimplemented");
}
function unreachable(info) {
	if (info) throw new Error(`unreachable: ${info}`);
	throw new Error("unreachable");
}
function unsupported(info) {
	throw new Error(`UNSUPPORTED: ${info}`);
}
function noop(..._args) {}

//#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/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/log/logger.ts
function getLogger(plugins, onLog, logLevel) {
	const minimalPriority = logLevelPriority[logLevel];
	const logger = (level, log, skipped = new Set()) => {
		const logPriority = logLevelPriority[level];
		if (logPriority < 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));
				};
				const handler = "handler" in pluginOnLog ? pluginOnLog.handler : pluginOnLog;
				if (handler.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: false
					},
					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/builtin-plugin/utils.ts
function makeBuiltinPluginCallable(plugin) {
	let callablePlugin = new import_binding.BindingCallableBuiltinPlugin(bindingifyBuiltInPlugin(plugin));
	const wrappedPlugin = plugin;
	for (const key in callablePlugin) wrappedPlugin[key] = function(...args) {
		return callablePlugin[key](...args);
	};
	return wrappedPlugin;
}
function bindingifyBuiltInPlugin(plugin) {
	return {
		__name: plugin.name,
		options: plugin._options
	};
}

//#endregion
//#region src/builtin-plugin/constructors.ts
var BuiltinPlugin = class {
	constructor(name, _options) {
		this.name = name;
		this._options = _options;
	}
};
function modulePreloadPolyfillPlugin(config) {
	return new BuiltinPlugin("builtin:module-preload-polyfill", config);
}
function dynamicImportVarsPlugin() {
	return new BuiltinPlugin("builtin:dynamic-import-vars");
}
function importGlobPlugin(config) {
	return new BuiltinPlugin("builtin:import-glob", config);
}
function manifestPlugin(config) {
	return new BuiltinPlugin("builtin:manifest", config);
}
function wasmHelperPlugin() {
	return new BuiltinPlugin("builtin:wasm-helper");
}
function wasmFallbackPlugin() {
	return new BuiltinPlugin("builtin:wasm-fallback");
}
function loadFallbackPlugin() {
	return new BuiltinPlugin("builtin:load-fallback");
}
function jsonPlugin(config) {
	return new BuiltinPlugin("builtin:json", config);
}
function buildImportAnalysisPlugin(config) {
	return new BuiltinPlugin("builtin:build-import-analysis", config);
}
function viteResolvePlugin(config) {
	const builtinPlugin = new BuiltinPlugin("builtin:vite-resolve", {
		...config,
		runtime: process.versions.deno ? "deno" : process.versions.bun ? "bun" : "node"
	});
	return makeBuiltinPluginCallable(builtinPlugin);
}
function moduleFederationPlugin(config) {
	return new BuiltinPlugin("builtin:module-federation", {
		...config,
		remotes: config.remotes && Object.entries(config.remotes).map(([name, remote]) => {
			if (typeof remote === "string") {
				const [entryGlobalName] = remote.split("@");
				const entry = remote.replace(entryGlobalName + "@", "");
				return {
					entry,
					name,
					entryGlobalName
				};
			}
			return {
				...remote,
				name: remote.name ?? name
			};
		}),
		manifest: config.manifest === false ? void 0 : config.manifest === true ? {} : config.manifest
	});
}
function isolatedDeclarationPlugin(config) {
	return new BuiltinPlugin("builtin:isolated-declaration", config);
}

//#endregion
//#region src/utils/async-flatten.ts
async function asyncFlatten(array) {
	do
		array = (await Promise.all(array)).flat(Infinity);
	while (array.some((v$1) => v$1?.then));
	return array;
}

//#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"
];
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/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/plugin-driver.ts
var PluginDriver = class {
	static async callOptionsHook(inputOptions) {
		const logLevel = inputOptions.logLevel || LOG_LEVEL_INFO;
		const plugins = getSortedPlugins("options", getObjectPlugins(await normalizePluginOption(inputOptions.plugins)));
		const logger = getLogger(plugins, getOnLog(inputOptions, logLevel), logLevel);
		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({
					debug: getLogHandler(LOG_LEVEL_DEBUG, "PLUGIN_LOG", logger, name, logLevel),
					error: (e) => error(logPluginError(normalizeLog(e), name, { hook: "onLog" })),
					info: getLogHandler(LOG_LEVEL_INFO, "PLUGIN_LOG", logger, name, logLevel),
					meta: {
						rollupVersion: "4.23.0",
						rolldownVersion: VERSION,
						watchMode: false
					},
					warn: getLogHandler(LOG_LEVEL_WARN, "PLUGIN_WARNING", logger, name, logLevel),
					pluginName: name
				}, inputOptions);
				if (result) inputOptions = result;
			}
		}
		return inputOptions;
	}
	static callOutputOptionsHook(rawPlugins, outputOptions) {
		const sortedPlugins = getSortedPlugins("outputOptions", getObjectPlugins(rawPlugins));
		for (const plugin of sortedPlugins) {
			const options = plugin.outputOptions;
			if (options) {
				const { handler } = normalizeHook(options);
				const result = handler.call(null, outputOptions);
				if (result) outputOptions = result;
			}
		}
		return outputOptions;
	}
};
function getObjectPlugins(plugins) {
	return plugins.filter((plugin) => {
		if (!plugin) return void 0;
		if ("_parallel" in plugin) return void 0;
		if (plugin instanceof BuiltinPlugin) return void 0;
		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 src/utils/validator.ts
const StringOrRegExpSchema = v.union([v.string(), v.instance(RegExp)]);
const LogLevelSchema = v.union([
	v.literal("debug"),
	v.literal("info"),
	v.literal("warn")
]);
const LogLevelOptionSchema = v.union([LogLevelSchema, v.literal("silent")]);
const LogLevelWithErrorSchema = v.union([LogLevelSchema, v.literal("error")]);
const RollupLogSchema = v.any();
const RollupLogWithStringSchema = v.union([RollupLogSchema, v.string()]);
const InputOptionSchema = v.union([
	v.string(),
	v.array(v.string()),
	v.record(v.string(), v.string())
]);
const ExternalSchema = v.union([
	StringOrRegExpSchema,
	v.array(StringOrRegExpSchema),
	v.pipe(v.function(), v.args(v.tuple([
		v.string(),
		v.optional(v.string()),
		v.boolean()
	])), v.returns(v.nullish(v.boolean())))
]);
const ModuleTypesSchema = v.record(v.string(), v.union([
	v.literal("base64"),
	v.literal("binary"),
	v.literal("css"),
	v.literal("dataurl"),
	v.literal("empty"),
	v.literal("js"),
	v.literal("json"),
	v.literal("jsx"),
	v.literal("text"),
	v.literal("ts"),
	v.literal("tsx")
]));
const JsxOptionsSchema = v.strictObject({
	development: v.pipe(v.optional(v.boolean()), v.description("Development specific information")),
	factory: v.pipe(v.optional(v.string()), v.description("Jsx element transformation")),
	fragment: v.pipe(v.optional(v.string()), v.description("Jsx fragment transformation")),
	importSource: v.pipe(v.optional(v.string()), v.description("Import the factory of element and fragment if mode is classic")),
	jsxImportSource: v.pipe(v.optional(v.string()), v.description("Import the factory of element and fragment if mode is automatic")),
	mode: v.pipe(v.optional(v.union([
		v.literal("classic"),
		v.literal("automatic"),
		v.literal("preserve")
	])), v.description("Jsx transformation mode")),
	refresh: v.pipe(v.optional(v.boolean()), v.description("React refresh transformation"))
});
const HelperModeSchema = v.union([v.literal("Runtime"), v.literal("External")]);
const DecoratorOptionSchema = v.object({
	legacy: v.optional(v.boolean()),
	emitDecoratorMetadata: v.optional(v.boolean())
});
const HelpersSchema = v.object({ mode: v.optional(HelperModeSchema) });
const RewriteImportExtensionsSchema = v.union([
	v.literal("rewrite"),
	v.literal("remove"),
	v.boolean()
]);
const TypescriptSchema = v.object({
	jsxPragma: v.optional(v.string()),
	jsxPragmaFrag: v.optional(v.string()),
	onlyRemoveTypeImports: v.optional(v.boolean()),
	allowNamespaces: v.optional(v.boolean()),
	allowDeclareFields: v.optional(v.boolean()),
	declaration: v.optional(v.object({
		stripInternal: v.optional(v.boolean()),
		sourcemap: v.optional(v.boolean())
	})),
	rewriteImportExtensions: v.optional(RewriteImportExtensionsSchema)
});
const AssumptionsSchema = v.object({
	ignoreFunctionLength: v.optional(v.boolean()),
	noDocumentAll: v.optional(v.boolean()),
	objectRestNoSymbols: v.optional(v.boolean()),
	pureGetters: v.optional(v.boolean()),
	setPublicClassFields: v.optional(v.boolean())
});
const TransformOptionsSchema = v.object({
	assumptions: v.optional(AssumptionsSchema),
	typescript: v.optional(TypescriptSchema),
	helpers: v.optional(HelpersSchema),
	decorators: v.optional(DecoratorOptionSchema)
});
const WatchOptionsSchema = v.strictObject({
	chokidar: v.optional(v.never(`The "watch.chokidar" option is deprecated, please use "watch.notify" instead of it`)),
	exclude: v.optional(v.union([StringOrRegExpSchema, v.array(StringOrRegExpSchema)])),
	include: v.optional(v.union([StringOrRegExpSchema, v.array(StringOrRegExpSchema)])),
	notify: v.pipe(v.optional(v.strictObject({
		compareContents: v.optional(v.boolean()),
		pollInterval: v.optional(v.number())
	})), v.description("Notify options")),
	skipWrite: v.pipe(v.optional(v.boolean()), v.description("Skip the bundle.write() step")),
	buildDelay: v.pipe(v.optional(v.number()), v.description("Throttle watch rebuilds"))
});
const ChecksOptionsSchema = v.strictObject({
	circularDependency: v.pipe(v.optional(v.boolean()), v.description("Whether to emit warning when detecting circular dependency")),
	eval: v.pipe(v.optional(v.boolean()), v.description("Whether to emit warning when detecting eval")),
	missingGlobalName: v.pipe(v.optional(v.boolean()), v.description("Whether to emit warning when detecting missing global name")),
	missingNameOptionForIifeExport: v.pipe(v.optional(v.boolean()), v.description("Whether to emit warning when detecting missing name option for iife export")),
	mixedExport: v.pipe(v.optional(v.boolean()), v.description("Whether to emit warning when detecting mixed export")),
	unresolvedEntry: v.pipe(v.optional(v.boolean()), v.description("Whether to emit warning when detecting unresolved entry")),
	unresolvedImport: v.pipe(v.optional(v.boolean()), v.description("Whether to emit warning when detecting unresolved import")),
	filenameConflict: v.pipe(v.optional(v.boolean()), v.description("Whether to emit warning when detecting filename conflict")),
	commonJsVariableInEsm: v.pipe(v.optional(v.boolean()), v.description("Whether to emit warning when detecting common js variable in esm")),
	importIsUndefined: v.pipe(v.optional(v.boolean()), v.description("Whether to emit warning when detecting import is undefined")),
	configurationFieldConflict: v.pipe(v.optional(v.boolean()), v.description("Whether to emit warning when detecting configuration field conflict"))
});
const MinifyOptionsSchema = v.strictObject({
	mangle: v.boolean(),
	compress: v.boolean(),
	deadCodeElimination: v.boolean(),
	removeWhitespace: v.boolean()
});
const ResolveOptionsSchema = v.strictObject({
	alias: v.optional(v.record(v.string(), v.union([v.string(), v.array(v.string())]))),
	aliasFields: v.optional(v.array(v.array(v.string()))),
	conditionNames: v.optional(v.array(v.string())),
	extensionAlias: v.optional(v.record(v.string(), v.array(v.string()))),
	exportsFields: v.optional(v.array(v.array(v.string()))),
	extensions: v.optional(v.array(v.string())),
	mainFields: v.optional(v.array(v.string())),
	mainFiles: v.optional(v.array(v.string())),
	modules: v.optional(v.array(v.string())),
	symlinks: v.optional(v.boolean()),
	tsconfigFilename: v.optional(v.string())
});
const TreeshakingOptionsSchema = v.union([v.boolean(), v.looseObject({
	annotations: v.optional(v.boolean()),
	manualPureFunctions: v.optional(v.array(v.string())),
	unknownGlobalSideEffects: v.optional(v.boolean())
})]);
const OnLogSchema = v.pipe(v.function(), v.args(v.tuple([
	LogLevelSchema,
	RollupLogSchema,
	v.pipe(v.function(), v.args(v.tuple([LogLevelWithErrorSchema, RollupLogWithStringSchema])))
])));
const OnwarnSchema = v.pipe(v.function(), v.args(v.tuple([RollupLogSchema, v.pipe(v.function(), v.args(v.tuple([v.union([RollupLogWithStringSchema, v.pipe(v.function(), v.returns(RollupLogWithStringSchema))])])))])));
const InputOptionsSchema = v.strictObject({
	input: v.optional(InputOptionSchema),
	plugins: v.optional(v.custom(() => true)),
	external: v.optional(ExternalSchema),
	resolve: v.optional(ResolveOptionsSchema),
	cwd: v.pipe(v.optional(v.string()), v.description("Current working directory")),
	platform: v.pipe(v.optional(v.union([
		v.literal("browser"),
		v.literal("neutral"),
		v.literal("node")
	])), v.description(`Platform for which the code should be generated (node, ${colors.underline("browser")}, neutral)`)),
	shimMissingExports: v.pipe(v.optional(v.boolean()), v.description("Create shim variables for missing exports")),
	treeshake: v.optional(TreeshakingOptionsSchema),
	logLevel: v.pipe(v.optional(LogLevelOptionSchema), v.description(`Log level (${colors.dim("silent")}, ${colors.underline(colors.gray("info"))}, debug, ${colors.yellow("warn")})`)),
	onLog: v.optional(OnLogSchema),
	onwarn: v.optional(OnwarnSchema),
	moduleTypes: v.pipe(v.optional(ModuleTypesSchema), v.description("Module types for customized extensions")),
	experimental: v.optional(v.strictObject({
		disableLiveBindings: v.optional(v.boolean()),
		enableComposingJsPlugins: v.optional(v.boolean()),
		resolveNewUrlToAsset: v.optional(v.boolean()),
		strictExecutionOrder: v.optional(v.boolean()),
		hmr: v.optional(v.boolean())
	})),
	define: v.pipe(v.optional(v.record(v.string(), v.string())), v.description("Define global variables")),
	inject: v.optional(v.record(v.string(), v.union([v.string(), v.tuple([v.string(), v.string()])]))),
	profilerNames: v.optional(v.boolean()),
	jsx: v.optional(v.union([
		v.boolean(),
		JsxOptionsSchema,
		v.string("react"),
		v.string("react-jsx"),
		v.string("preserve")
	])),
	transform: v.optional(TransformOptionsSchema),
	watch: v.optional(v.union([WatchOptionsSchema, v.literal(false)])),
	dropLabels: v.pipe(v.optional(v.array(v.string())), v.description("Remove labeled statements with these label names")),
	checks: v.optional(ChecksOptionsSchema),
	keepNames: v.pipe(v.optional(v.boolean()), v.description("Keep function/class name"))
});
const InputCliOverrideSchema = v.strictObject({
	external: v.pipe(v.optional(v.array(v.string())), v.description("Comma-separated list of module ids to exclude from the bundle `<module-id>,...`")),
	inject: v.pipe(v.optional(v.record(v.string(), v.string())), v.description("Inject import statements on demand")),
	treeshake: v.pipe(v.optional(v.boolean()), v.description("enable treeshaking")),
	jsx: v.pipe(v.optional(JsxOptionsSchema), v.description("enable jsx"))
});
const InputCliOptionsSchema = v.omit(v.strictObject({
	...InputOptionsSchema.entries,
	...InputCliOverrideSchema.entries
}), [
	"input",
	"plugins",
	"onwarn",
	"onLog",
	"resolve",
	"experimental",
	"profilerNames",
	"watch"
]);
var ESTarget = /* @__PURE__ */ function(ESTarget$1) {
	ESTarget$1["ES6"] = "es6";
	ESTarget$1["ES2015"] = "es2015";
	ESTarget$1["ES2016"] = "es2016";
	ESTarget$1["ES2017"] = "es2017";
	ESTarget$1["ES2018"] = "es2018";
	ESTarget$1["ES2019"] = "es2019";
	ESTarget$1["ES2020"] = "es2020";
	ESTarget$1["ES2021"] = "es2021";
	ESTarget$1["ES2022"] = "es2022";
	ESTarget$1["ES2023"] = "es2023";
	ESTarget$1["ES2024"] = "es2024";
	ESTarget$1["ESNext"] = "esnext";
	return ESTarget$1;
}(ESTarget || {});
const ModuleFormatSchema = v.union([
	v.literal("es"),
	v.literal("cjs"),
	v.literal("esm"),
	v.literal("module"),
	v.literal("commonjs"),
	v.literal("iife"),
	v.literal("umd")
]);
const AddonFunctionSchema = v.pipe(v.function(), v.args(v.tuple([v.custom(() => true)])), v.returnsAsync(v.unionAsync([v.string(), v.pipeAsync(v.promise(), v.awaitAsync(), v.string())])));
const ChunkFileNamesSchema = v.union([v.string(), v.pipe(v.function(), v.args(v.tuple([v.custom(() => true)])), v.returns(v.string()))]);
const AssetFileNamesSchema = v.union([v.string(), v.pipe(v.function(), v.args(v.tuple([v.custom(() => true)])), v.returns(v.string()))]);
const SanitizeFileNameSchema = v.union([v.boolean(), v.pipe(v.function(), v.args(v.tuple([v.string()])), v.returns(v.string()))]);
const GlobalsFunctionSchema = v.pipe(v.function(), v.args(v.tuple([v.string()])), v.returns(v.string()));
const AdvancedChunksSchema = v.strictObject({
	minSize: v.optional(v.number()),
	maxSize: v.optional(v.number()),
	minModuleSize: v.optional(v.number()),
	maxModuleSize: v.optional(v.number()),
	minShareCount: v.optional(v.number()),
	groups: v.optional(v.array(v.strictObject({
		name: v.string(),
		test: v.optional(v.union([v.string(), v.instance(RegExp)])),
		priority: v.optional(v.number()),
		minSize: v.optional(v.number()),
		minShareCount: v.optional(v.number()),
		maxSize: v.optional(v.number()),
		minModuleSize: v.optional(v.number()),
		maxModuleSize: v.optional(v.number())
	})))
});
const OutputOptionsSchema = v.strictObject({
	dir: v.pipe(v.optional(v.string()), v.description("Output directory, defaults to `dist` if `file` is not set")),
	file: v.pipe(v.optional(v.string()), v.description("Single output file")),
	exports: v.pipe(v.optional(v.union([
		v.literal("auto"),
		v.literal("named"),
		v.literal("default"),
		v.literal("none")
	])), v.description(`Specify a export mode (${colors.underline("auto")}, named, default, none)`)),
	hashCharacters: v.pipe(v.optional(v.union([
		v.literal("base64"),
		v.literal("base36"),
		v.literal("hex")
	])), v.description("Use the specified character set for file hashes")),
	format: v.pipe(v.optional(ModuleFormatSchema), v.description(`Output format of the generated bundle (supports ${colors.underline("esm")}, cjs, and iife)`)),
	sourcemap: v.pipe(v.optional(v.union([
		v.boolean(),
		v.literal("inline"),
		v.literal("hidden")
	])), v.description(`Generate sourcemap (\`-s inline\` for inline, or ${colors.bold("pass the `-s` on the last argument if you want to generate `.map` file")})`)),
	sourcemapDebugIds: v.pipe(v.optional(v.boolean()), v.description("Inject sourcemap debug IDs")),
	sourcemapIgnoreList: v.optional(v.union([v.boolean(), v.custom(() => true)])),
	sourcemapPathTransform: v.optional(v.custom(() => true)),
	banner: v.optional(v.union([v.string(), AddonFunctionSchema])),
	footer: v.optional(v.union([v.string(), AddonFunctionSchema])),
	intro: v.optional(v.union([v.string(), AddonFunctionSchema])),
	outro: v.optional(v.union([v.string(), AddonFunctionSchema])),
	extend: v.pipe(v.optional(v.boolean()), v.description("Extend global variable defined by name in IIFE / UMD formats")),
	esModule: v.optional(v.union([v.boolean(), v.literal("if-default-prop")])),
	assetFileNames: v.optional(AssetFileNamesSchema),
	entryFileNames: v.optional(ChunkFileNamesSchema),
	chunkFileNames: v.optional(ChunkFileNamesSchema),
	cssEntryFileNames: v.optional(ChunkFileNamesSchema),
	cssChunkFileNames: v.optional(ChunkFileNamesSchema),
	sanitizeFileName: v.optional(SanitizeFileNameSchema),
	minify: v.pipe(v.optional(v.union([
		v.boolean(),
		v.string("dce-only"),
		MinifyOptionsSchema
	])), v.description("Minify the bundled file")),
	name: v.pipe(v.optional(v.string()), v.description("Name for UMD / IIFE format outputs")),
	globals: v.pipe(v.optional(v.union([v.record(v.string(), v.string()), GlobalsFunctionSchema])), v.description("Global variable of UMD / IIFE dependencies (syntax: `key=value`)")),
	externalLiveBindings: v.pipe(v.optional(v.boolean()), v.description("external live bindings")),
	inlineDynamicImports: v.pipe(v.optional(v.boolean()), v.description("Inline dynamic imports")),
	advancedChunks: v.optional(AdvancedChunksSchema),
	comments: v.pipe(v.optional(v.union([v.literal("none"), v.literal("preserve-legal")])), v.description("Control comments in the output")),
	target: v.pipe(v.optional(v.enum(ESTarget)), v.description("The JavaScript target environment")),
	plugins: v.optional(v.custom(() => true))
});
const getAddonDescription = (placement, wrapper) => {
	return `Code to insert the ${colors.bold(placement)} of the bundled file (${colors.bold(wrapper)} the wrapper function)`;
};
const OutputCliOverrideSchema = v.strictObject({
	assetFileNames: v.pipe(v.optional(v.string()), v.description("Name pattern for asset files")),
	entryFileNames: v.pipe(v.optional(v.string()), v.description("Name pattern for emitted entry chunks")),
	chunkFileNames: v.pipe(v.optional(v.string()), v.description("Name pattern for emitted secondary chunks")),
	cssEntryFileNames: v.pipe(v.optional(v.string()), v.description("Name pattern for emitted css entry chunks")),
	cssChunkFileNames: v.pipe(v.optional(v.string()), v.description("Name pattern for emitted css secondary chunks")),
	sanitizeFileName: v.pipe(v.optional(v.boolean()), v.description("Sanitize file name")),
	banner: v.pipe(v.optional(v.string()), v.description(getAddonDescription("top", "outside"))),
	footer: v.pipe(v.optional(v.string()), v.description(getAddonDescription("bottom", "outside"))),
	intro: v.pipe(v.optional(v.string()), v.description(getAddonDescription("top", "inside"))),
	outro: v.pipe(v.optional(v.string()), v.description(getAddonDescription("bottom", "inside"))),
	esModule: v.pipe(v.optional(v.boolean()), v.description("Always generate `__esModule` marks in non-ESM formats, defaults to `if-default-prop` (use `--no-esModule` to always disable)")),
	globals: v.pipe(v.optional(v.record(v.string(), v.string())), v.description("Global variable of UMD / IIFE dependencies (syntax: `key=value`)")),
	advancedChunks: v.pipe(v.optional(v.strictObject({
		minSize: v.pipe(v.optional(v.number()), v.description("Minimum size of the chunk")),
		minShareCount: v.pipe(v.optional(v.number()), v.description("Minimum share count of the chunk"))
	})), v.description("Global variable of UMD / IIFE dependencies (syntax: `key=value`)")),
	minify: v.pipe(v.optional(v.boolean()), v.description("Minify the bundled file"))
});
const OutputCliOptionsSchema = v.omit(v.strictObject({
	...OutputOptionsSchema.entries,
	...OutputCliOverrideSchema.entries
}), [
	"sourcemapIgnoreList",
	"sourcemapPathTransform",
	"plugins"
]);
const CliOptionsSchema = v.strictObject({
	config: v.pipe(v.optional(v.union([v.string(), v.boolean()])), v.description("Path to the config file (default: `rolldown.config.js`)")),
	help: v.pipe(v.optional(v.boolean()), v.description("Show help")),
	version: v.pipe(v.optional(v.boolean()), v.description("Show version number")),
	watch: v.pipe(v.optional(v.boolean()), v.description("Watch files in bundle and rebuild on changes")),
	...InputCliOptionsSchema.entries,
	...OutputCliOptionsSchema.entries
});
function validateCliOptions(options) {
	let parsed = v.safeParse(CliOptionsSchema, options);
	return [parsed.output, parsed.issues?.map((issue) => {
		const option = issue.path?.map((pathItem) => pathItem.key).join(" ");
		return `Invalid value for option ${option}: ${issue.message}`;
	})];
}
const inputHelperMsgRecord = { output: { ignored: true } };
const outputHelperMsgRecord = {};
function validateOption(key, options) {
	if (process.env.ROLLDOWN_OPTIONS_VALIDATION === "loose") return;
	let parsed = v.safeParse(key === "input" ? InputOptionsSchema : OutputOptionsSchema, options);
	if (!parsed.success) {
		const errors = parsed.issues.map((issue) => {
			const issuePaths = issue.path.map((path$1) => path$1.key);
			let issueMsg = issue.message;
			if (issue.type === "union") {
				const subIssue = issue.issues?.find((i) => !(i.type !== issue.received && i.input === issue.input));
				if (subIssue) {
					if (subIssue.path) issuePaths.push(subIssue.path.map((path$1) => path$1.key));
					issueMsg = subIssue.message;
				}
			}
			const stringPath = issuePaths.join(".");
			const helper = key === "input" ? inputHelperMsgRecord[stringPath] : outputHelperMsgRecord[stringPath];
			if (helper && helper.ignored) return "";
			return `- For the "${stringPath}". ${issueMsg}. ${helper ? helper.msg : ""}`;
		}).filter(Boolean);
		if (errors.length) throw new Error(`Failed validate ${key} options.\n` + errors.join("\n"));
	}
}
function getInputCliKeys() {
	return v.keyof(InputCliOptionsSchema).options;
}
function getOutputCliKeys() {
	return v.keyof(OutputCliOptionsSchema).options;
}
function getJsonSchema() {
	return toJsonSchema(CliOptionsSchema);
}

//#endregion
//#region src/utils/asset-source.ts
function transformAssetSource(bindingAssetSource$1) {
	return bindingAssetSource$1.inner;
}
function bindingAssetSource(source) {
	return { inner: source };
}

//#endregion
//#region src/types/sourcemap.ts
function bindingifySourcemap$1(map) {
	if (map == null) return;
	return { inner: typeof map === "string" ? map : {
		file: map.file ?? void 0,
		mappings: map.mappings,
		sourceRoot: "sourceRoot" in map ? map.sourceRoot ?? void 0 : void 0,
		sources: map.sources?.map((s) => s ?? void 0),
		sourcesContent: map.sourcesContent?.map((s) => s ?? void 0),
		names: map.names,
		x_google_ignoreList: map.x_google_ignoreList,
		debugId: "debugId" in map ? map.debugId : void 0
	} };
}

//#endregion
//#region src/utils/error.ts
function normalizeErrors(rawErrors) {
	const errors = rawErrors.map((e) => e instanceof Error ? e : Object.assign(new Error(), {
		kind: e.kind,
		message: e.message,
		stack: void 0
	}));
	let summary = `Build failed with ${errors.length} error${errors.length < 2 ? "" : "s"}:\n`;
	for (let i = 0; i < errors.length; i++) {
		summary += "\n";
		if (i >= 5) {
			summary += "...";
			break;
		}
		summary += getErrorMessage(errors[i]);
	}
	const wrapper = new Error(summary);
	Object.defineProperty(wrapper, "errors", {
		configurable: true,
		enumerable: true,
		get: () => errors,
		set: (value) => Object.defineProperty(wrapper, "errors", {
			configurable: true,
			enumerable: true,
			value
		})
	});
	return wrapper;
}
function getErrorMessage(e) {
	if (Object.hasOwn(e, "kind")) return e.message;
	let s = "";
	if (e.plugin) s += `[plugin ${e.plugin}]`;
	const id = e.id ?? e.loc?.file;
	if (id) {
		s += " " + id;
		if (e.loc) s += `:${e.loc.line}:${e.loc.column}`;
	}
	if (s) s += "\n";
	const message = `${e.name ?? "Error"}: ${e.message}`;
	s += message;
	if (e.frame) s = joinNewLine(s, e.frame);
	if (e.stack) s = joinNewLine(s, e.stack.replace(message, ""));
	return s;
}
function joinNewLine(s1, s2) {
	return s1.replace(/\n+$/, "") + "\n" + s2.replace(/^\n+/, "");
}

//#endregion
//#region src/utils/transform-rendered-module.ts
function transformToRenderedModule(bindingRenderedModule) {
	return {
		get code() {
			return bindingRenderedModule.code;
		},
		get renderedLength() {
			return bindingRenderedModule.code?.length || 0;
		},
		get renderedExports() {
			return bindingRenderedModule.renderedExports;
		}
	};
}

//#endregion
//#region src/utils/transform-rendered-chunk.ts
function transformRenderedChunk(chunk) {
	return {
		get name() {
			return chunk.name;
		},
		get isEntry() {
			return chunk.isEntry;
		},
		get isDynamicEntry() {
			return chunk.isDynamicEntry;
		},
		get facadeModuleId() {
			return chunk.facadeModuleId;
		},
		get moduleIds() {
			return chunk.moduleIds;
		},
		get exports() {
			return chunk.exports;
		},
		get fileName() {
			return chunk.fileName;
		},
		get imports() {
			return chunk.imports;
		},
		get dynamicImports() {
			return chunk.dynamicImports;
		},
		get modules() {
			return transformChunkModules(chunk.modules);
		}
	};
}
function transformChunkModules(modules) {
	const result = {};
	for (let i = 0; i < modules.values.length; i++) {
		let key = modules.keys[i];
		const mod = modules.values[i];
		result[key] = transformToRenderedModule(mod);
	}
	return result;
}

//#endregion
//#region src/utils/transform-to-rollup-output.ts
function transformToRollupSourceMap(map) {
	const parsed = JSON.parse(map);
	const obj = {
		...parsed,
		toString() {
			return JSON.stringify(obj);
		},
		toUrl() {
			return `data:application/json;charset=utf-8;base64,${Buffer.from(obj.toString(), "utf-8").toString("base64")}`;
		}
	};
	return obj;
}
function transformToRollupOutputChunk(bindingChunk, changed) {
	const chunk = {
		type: "chunk",
		get code() {
			return bindingChunk.code;
		},
		fileName: bindingChunk.fileName,
		name: bindingChunk.name,
		get modules() {
			return transformChunkModules(bindingChunk.modules);
		},
		get imports() {
			return bindingChunk.imports;
		},
		get dynamicImports() {
			return bindingChunk.dynamicImports;
		},
		exports: bindingChunk.exports,
		isEntry: bindingChunk.isEntry,
		facadeModuleId: bindingChunk.facadeModuleId || null,
		isDynamicEntry: bindingChunk.isDynamicEntry,
		get moduleIds() {
			return bindingChunk.moduleIds;
		},
		get map() {
			return bindingChunk.map ? transformToRollupSourceMap(bindingChunk.map) : null;
		},
		sourcemapFileName: bindingChunk.sourcemapFileName || null,
		preliminaryFileName: bindingChunk.preliminaryFileName
	};
	const cache = {};
	return new Proxy(chunk, {
		get(target, p) {
			if (p in cache) return cache[p];
			return target[p];
		},
		set(target, p, newValue) {
			cache[p] = newValue;
			changed?.updated.add(bindingChunk.fileName);
			return true;
		},
		has(target, p) {
			if (p in cache) return true;
			return p in target;
		}
	});
}
function transformToRollupOutputAsset(bindingAsset, changed) {
	const asset = {
		type: "asset",
		fileName: bindingAsset.fileName,
		originalFileName: bindingAsset.originalFileName || null,
		originalFileNames: bindingAsset.originalFileNames,
		get source() {
			return transformAssetSource(bindingAsset.source);
		},
		name: bindingAsset.name ?? void 0,
		names: bindingAsset.names
	};
	const cache = {};
	return new Proxy(asset, {
		get(target, p) {
			if (p in cache) return cache[p];
			return target[p];
		},
		set(target, p, newValue) {
			cache[p] = newValue;
			changed?.updated.add(bindingAsset.fileName);
			return true;
		}
	});
}
function transformToRollupOutput(output, changed) {
	handleOutputErrors(output);
	const { chunks, assets } = output;
	return { output: [...chunks.map((chunk) => transformToRollupOutputChunk(chunk, changed)), ...assets.map((asset) => transformToRollupOutputAsset(asset, changed))] };
}
function handleOutputErrors(output) {
	const rawErrors = output.errors;
	if (rawErrors.length > 0) throw normalizeErrors(rawErrors);
}
function transformToOutputBundle(output, changed) {
	const bundle = Object.fromEntries(transformToRollupOutput(output, changed).output.map((item) => [item.fileName, item]));
	return new Proxy(bundle, { deleteProperty(target, property) {
		if (typeof property === "string") changed.deleted.add(property);
		return true;
	} });
}
function collectChangedBundle(changed, bundle) {
	const assets = [];
	const chunks = [];
	for (const key in bundle) {
		if (changed.deleted.has(key) || !changed.updated.has(key)) continue;
		const item = bundle[key];
		if (item.type === "asset") assets.push({
			filename: item.fileName,
			originalFileNames: item.originalFileNames,
			source: bindingAssetSource(item.source),
			names: item.names
		});
		else chunks.push({
			code: item.code,
			filename: item.fileName,
			name: item.name,
			isEntry: item.isEntry,
			exports: item.exports,
			modules: {},
			imports: item.imports,
			dynamicImports: item.dynamicImports,
			facadeModuleId: item.facadeModuleId || void 0,
			isDynamicEntry: item.isDynamicEntry,
			moduleIds: item.moduleIds,
			map: bindingifySourcemap$1(item.map),
			sourcemapFilename: item.sourcemapFileName || void 0,
			preliminaryFilename: item.preliminaryFileName
		});
	}
	return {
		assets,
		chunks,
		deleted: Array.from(changed.deleted)
	};
}

//#endregion
//#region src/utils/transform-sourcemap.ts
function isEmptySourcemapFiled(array) {
	if (!array) return true;
	if (array.length === 0 || !array[0]) return true;
	return false;
}
function normalizeTransformHookSourcemap(id, originalCode, rawMap) {
	if (!rawMap) return;
	let map = typeof rawMap === "object" ? rawMap : JSON.parse(rawMap);
	if (isEmptySourcemapFiled(map.sourcesContent)) map.sourcesContent = [originalCode];
	if (isEmptySourcemapFiled(map.sources) || map.sources && map.sources.length === 1 && map.sources[0] !== id) map.sources = [id];
	return map;
}

//#endregion
//#region src/utils/transform-module-info.ts
function transformModuleInfo(info, option) {
	return {
		get ast() {
			return unsupported("ModuleInfo#ast");
		},
		get code() {
			return info.code;
		},
		id: info.id,
		importers: info.importers,
		dynamicImporters: info.dynamicImporters,
		importedIds: info.importedIds,
		dynamicallyImportedIds: info.dynamicallyImportedIds,
		exports: info.exports,
		isEntry: info.isEntry,
		...option
	};
}

//#endregion
//#region src/plugin/minimal-plugin-context.ts
var MinimalPluginContextImpl = class {
	info;
	warn;
	debug;
	meta;
	constructor(onLog, logLevel, pluginName) {
		this.pluginName = pluginName;
		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: false
		};
	}
	error(e) {
		return error(logPluginError(normalizeLog(e), this.pluginName));
	}
};

//#endregion
//#region src/utils/transform-side-effects.ts
function bindingifySideEffects(sideEffects) {
	switch (sideEffects) {
		case true: return import_binding.BindingHookSideEffects.True;
		case false: return import_binding.BindingHookSideEffects.False;
		case "no-treeshake": return import_binding.BindingHookSideEffects.NoTreeshake;
		case null:
		case void 0: return void 0;
		default: throw new Error(`Unexpected side effects: ${sideEffects}`);
	}
}

//#endregion
//#region src/utils/resolved-external.ts
function transformResolvedExternal(bindingResolvedExternal$1) {
	switch (bindingResolvedExternal$1.type) {
		case "Bool": return bindingResolvedExternal$1.field0;
		case "Absolute": return "absolute";
		case "Relative": unreachable(`The PluginContext resolve result external couldn't be 'relative'`);
	}
}
function bindingResolvedExternal(external) {
	if (typeof external === "boolean") return {
		type: "Bool",
		field0: external
	};
	if (external === "absolute") return { type: "Absolute" };
	if (external === "relative") return { type: "Relative" };
}

//#endregion
//#region src/plugin/plugin-context.ts
var PluginContextImpl = class extends MinimalPluginContextImpl {
	getModuleInfo;
	constructor(outputOptions, context, plugin, data, onLog, logLevel, currentLoadingModule) {
		super(onLog, logLevel, plugin.name);
		this.outputOptions = outputOptions;
		this.context = context;
		this.data = data;
		this.onLog = onLog;
		this.currentLoadingModule = currentLoadingModule;
		this.getModuleInfo = (id) => this.data.getModuleInfo(id, context);
	}
	async load(options) {
		const id = options.id;
		if (id === this.currentLoadingModule) this.onLog(LOG_LEVEL_WARN, logCycleLoading(this.pluginName, this.currentLoadingModule));
		const moduleInfo = this.data.getModuleInfo(id, this.context);
		if (moduleInfo && moduleInfo.code !== null) return moduleInfo;
		const rawOptions = {
			meta: options.meta || {},
			moduleSideEffects: options.moduleSideEffects || null,
			invalidate: false
		};
		this.data.updateModuleOption(id, rawOptions);
		async function createLoadModulePromise(context, data) {
			const loadPromise = data.loadModulePromiseMap.get(id);
			if (loadPromise) return loadPromise;
			let resolveFn;
			const promise = new Promise((resolve, _) => {
				resolveFn = resolve;
			});
			data.loadModulePromiseMap.set(id, promise);
			try {
				await context.load(id, bindingifySideEffects(options.moduleSideEffects), resolveFn);
			} finally {
				data.loadModulePromiseMap.delete(id);
			}
			return promise;
		}
		await createLoadModulePromise(this.context, this.data);
		return this.data.getModuleInfo(id, this.context);
	}
	async resolve(source, importer, options) {
		let receipt = void 0;
		if (options != null) receipt = this.data.saveResolveOptions(options);
		const res = await this.context.resolve(source, importer, {
			custom: receipt,
			skipSelf: options?.skipSelf
		});
		if (receipt != null) this.data.removeSavedResolveOptions(receipt);
		if (res == null) return null;
		const info = this.data.getModuleOption(res.id) || {};
		return {
			...res,
			external: transformResolvedExternal(res.external),
			...info
		};
	}
	emitFile = (file) => {
		if (file.type === "prebuilt-chunk") return unimplemented("PluginContext.emitFile with type prebuilt-chunk");
		if (file.type === "chunk") return this.context.emitChunk(file);
		const fnSanitizedFileName = file.fileName || typeof this.outputOptions.sanitizeFileName !== "function" ? void 0 : this.outputOptions.sanitizeFileName(file.name || "asset");
		const filename = file.fileName ? void 0 : this.getAssetFileNames(file);
		return this.context.emitFile({
			...file,
			originalFileName: file.originalFileName || void 0,
			source: bindingAssetSource(file.source)
		}, filename, fnSanitizedFileName);
	};
	getAssetFileNames(file) {
		if (typeof this.outputOptions.assetFileNames === "function") return this.outputOptions.assetFileNames({
			names: file.name ? [file.name] : [],
			originalFileNames: file.originalFileName ? [file.originalFileName] : [],
			source: file.source,
			type: "asset"
		});
	}
	getFileName(referenceId) {
		return this.context.getFileName(referenceId);
	}
	getModuleIds() {
		return this.data.getModuleIds(this.context);
	}
	addWatchFile(id) {
		this.context.addWatchFile(id);
	}
	parse(input, options) {
		return parseAst(input, options);
	}
};

//#endregion
//#region src/plugin/transform-plugin-context.ts
var TransformPluginContextImpl = class extends PluginContextImpl {
	constructor(outputOptions, context, plugin, data, inner, moduleId, moduleSource, onLog, LogLevelOption) {
		super(outputOptions, context, plugin, data, onLog, LogLevelOption, moduleId);
		this.inner = inner;
		this.moduleId = moduleId;
		this.moduleSource = moduleSource;
		const getLogHandler$1 = (handler) => (log, pos) => {
			log = normalizeLog(log);
			if (pos) augmentCodeLocation(log, pos, moduleSource, moduleId);
			log.id = moduleId;
			log.hook = "transform";
			handler(log);
		};
		this.debug = getLogHandler$1(this.debug);
		this.warn = getLogHandler$1(this.warn);
		this.info = getLogHandler$1(this.info);
	}
	error(e, pos) {
		if (typeof e === "string") e = { message: e };
		if (pos) augmentCodeLocation(e, pos, this.moduleSource, this.moduleId);
		e.id = this.moduleId;
		e.hook = "transform";
		return error(logPluginError(normalizeLog(e), this.pluginName));
	}
	getCombinedSourcemap() {
		return JSON.parse(this.inner.getCombinedSourcemap());
	}
};

//#endregion
//#region src/plugin/bindingify-plugin-hook-meta.ts
function bindingifyPluginHookMeta(options) {
	return { order: bindingPluginOrder(options.order) };
}
function bindingPluginOrder(order) {
	switch (order) {
		case "post": return import_binding.BindingPluginOrder.Post;
		case "pre": return import_binding.BindingPluginOrder.Pre;
		case null:
		case void 0: return void 0;
		default: throw new Error(`Unknown plugin order: ${order}`);
	}
}

//#endregion
//#region src/constants/plugin-context.ts
const SYMBOL_FOR_RESOLVE_CALLER_THAT_SKIP_SELF = Symbol("plugin-context-resolve-caller");

//#endregion
//#region src/plugin/bindingify-hook-filter.ts
function bindingifyStringFilter(matcher) {
	if (typeof matcher === "string" || matcher instanceof RegExp) return { include: [matcher] };
	if (Array.isArray(matcher)) return { include: matcher };
	return {
		include: matcher.include ? arraify(matcher.include) : void 0,
		exclude: matcher.exclude ? arraify(matcher.exclude) : void 0
	};
}
function bindingifyResolveIdFilter(filterOption) {
	return filterOption?.id ? bindingifyStringFilter(filterOption.id) : void 0;
}
function bindingifyLoadFilter(filterOption) {
	return filterOption?.id ? bindingifyStringFilter(filterOption.id) : void 0;
}
function bindingifyTransformFilter(filterOption) {
	if (!filterOption) return void 0;
	const { id, code, moduleType } = filterOption;
	let moduleTypeRet;
	if (moduleType) if (Array.isArray(moduleType)) moduleTypeRet = moduleType;
	else moduleTypeRet = moduleType.include;
	return {
		id: id ? bindingifyStringFilter(id) : void 0,
		code: code ? bindingifyStringFilter(code) : void 0,
		moduleType: moduleTypeRet
	};
}

//#endregion
//#region src/options/normalized-input-options.ts
var NormalizedInputOptionsImpl = class {
	inner;
	constructor(inner, onLog) {
		this.onLog = onLog;
		this.inner = inner;
	}
	get shimMissingExports() {
		return this.inner.shimMissingExports;
	}
	get input() {
		return this.inner.input;
	}
	get cwd() {
		return this.inner.cwd ?? void 0;
	}
	get platform() {
		return this.inner.platform;
	}
};

//#endregion
//#region src/plugin/bindingify-build-hooks.ts
function bindingifyBuildStart(args) {
	const hook = args.plugin.buildStart;
	if (!hook) return {};
	const { handler, meta } = normalizeHook(hook);
	return {
		plugin: async (ctx, opts) => {
			await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), new NormalizedInputOptionsImpl(opts, args.onLog));
		},
		meta: bindingifyPluginHookMeta(meta)
	};
}
function bindingifyBuildEnd(args) {
	const hook = args.plugin.buildEnd;
	if (!hook) return {};
	const { handler, meta } = normalizeHook(hook);
	return {
		plugin: async (ctx, err) => {
			await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), err ? normalizeErrors(err) : void 0);
		},
		meta: bindingifyPluginHookMeta(meta)
	};
}
function bindingifyResolveId(args) {
	const hook = args.plugin.resolveId;
	if (!hook) return {};
	const { handler, meta, options } = normalizeHook(hook);
	return {
		plugin: async (ctx, specifier, importer, extraOptions) => {
			const contextResolveOptions = extraOptions.custom != null ? args.pluginContextData.getSavedResolveOptions(extraOptions.custom) : void 0;
			const newExtraOptions = {
				...extraOptions,
				custom: contextResolveOptions?.custom,
				[SYMBOL_FOR_RESOLVE_CALLER_THAT_SKIP_SELF]: contextResolveOptions?.[SYMBOL_FOR_RESOLVE_CALLER_THAT_SKIP_SELF]
			};
			const ret = await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), specifier, importer ?? void 0, newExtraOptions);
			if (ret == null) return;
			if (ret === false) return {
				id: specifier,
				external: bindingResolvedExternal(true),
				normalizeExternalId: true
			};
			if (typeof ret === "string") return {
				id: ret,
				normalizeExternalId: true
			};
			let exist = args.pluginContextData.updateModuleOption(ret.id, {
				meta: ret.meta || {},
				moduleSideEffects: ret.moduleSideEffects ?? null,
				invalidate: false
			});
			return {
				id: ret.id,
				external: bindingResolvedExternal(ret.external),
				normalizeExternalId: false,
				sideEffects: bindingifySideEffects(exist.moduleSideEffects)
			};
		},
		meta: bindingifyPluginHookMeta(meta),
		filter: bindingifyResolveIdFilter(options.filter)
	};
}
function bindingifyResolveDynamicImport(args) {
	const hook = args.plugin.resolveDynamicImport;
	if (!hook) return {};
	const { handler, meta } = normalizeHook(hook);
	return {
		plugin: async (ctx, specifier, importer) => {
			const ret = await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), specifier, importer ?? void 0);
			if (ret == null) return;
			if (ret === false) return {
				id: specifier,
				external: bindingResolvedExternal(true)
			};
			if (typeof ret === "string") return { id: ret };
			const result = {
				id: ret.id,
				external: bindingResolvedExternal(ret.external)
			};
			if (ret.moduleSideEffects !== null) result.sideEffects = bindingifySideEffects(ret.moduleSideEffects);
			args.pluginContextData.updateModuleOption(ret.id, {
				meta: ret.meta || {},
				moduleSideEffects: ret.moduleSideEffects || null,
				invalidate: false
			});
			return result;
		},
		meta: bindingifyPluginHookMeta(meta)
	};
}
function bindingifyTransform(args) {
	const hook = args.plugin.transform;
	if (!hook) return {};
	const { handler, meta, options } = normalizeHook(hook);
	return {
		plugin: async (ctx, code, id, meta$1) => {
			const ret = await handler.call(new TransformPluginContextImpl(args.outputOptions, ctx.inner(), args.plugin, args.pluginContextData, ctx, id, code, args.onLog, args.logLevel), code, id, meta$1);
			if (ret == null) return void 0;
			if (typeof ret === "string") return { code: ret };
			let moduleOption = args.pluginContextData.updateModuleOption(id, {
				meta: ret.meta ?? {},
				moduleSideEffects: ret.moduleSideEffects ?? null,
				invalidate: false
			});
			return {
				code: ret.code,
				map: bindingifySourcemap$1(normalizeTransformHookSourcemap(id, code, ret.map)),
				sideEffects: bindingifySideEffects(moduleOption.moduleSideEffects),
				moduleType: ret.moduleType
			};
		},
		meta: bindingifyPluginHookMeta(meta),
		filter: bindingifyTransformFilter(options.filter)
	};
}
function bindingifyLoad(args) {
	const hook = args.plugin.load;
	if (!hook) return {};
	const { handler, meta, options } = normalizeHook(hook);
	return {
		plugin: async (ctx, id) => {
			const ret = await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel, id), id);
			if (ret == null) return;
			if (typeof ret === "string") return { code: ret };
			let moduleOption = args.pluginContextData.updateModuleOption(id, {
				meta: ret.meta || {},
				moduleSideEffects: ret.moduleSideEffects ?? null,
				invalidate: false
			});
			let map = preProcessSourceMap(ret, id);
			return {
				code: ret.code,
				map: bindingifySourcemap$1(map),
				moduleType: ret.moduleType,
				sideEffects: bindingifySideEffects(moduleOption.moduleSideEffects)
			};
		},
		meta: bindingifyPluginHookMeta(meta),
		filter: bindingifyLoadFilter(options.filter)
	};
}
function preProcessSourceMap(ret, id) {
	if (!ret.map) return;
	let map = typeof ret.map === "object" ? ret.map : JSON.parse(ret.map);
	if (!isEmptySourcemapFiled(map.sources)) {
		const directory = path.dirname(id) || ".";
		const sourceRoot = map.sourceRoot || ".";
		map.sources = map.sources.map((source) => path.resolve(directory, sourceRoot, source));
	}
	return map;
}
function bindingifyModuleParsed(args) {
	const hook = args.plugin.moduleParsed;
	if (!hook) return {};
	const { handler, meta } = normalizeHook(hook);
	return {
		plugin: async (ctx, moduleInfo) => {
			await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), transformModuleInfo(moduleInfo, args.pluginContextData.getModuleOption(moduleInfo.id)));
		},
		meta: bindingifyPluginHookMeta(meta)
	};
}

//#endregion
//#region src/utils/bindingify-output-options.ts
function bindingifyOutputOptions(outputOptions) {
	const { dir, format, exports, hashCharacters, sourcemap, sourcemapDebugIds, sourcemapIgnoreList, sourcemapPathTransform, name, assetFileNames, entryFileNames, chunkFileNames, cssEntryFileNames, cssChunkFileNames, banner, footer, intro, outro, esModule, globals, file, sanitizeFileName } = outputOptions;
	return {
		dir,
		file: file == null ? void 0 : file,
		format: bindingifyFormat(format),
		exports,
		hashCharacters,
		sourcemap: bindingifySourcemap(sourcemap),
		sourcemapDebugIds,
		sourcemapIgnoreList: bindingifySourcemapIgnoreList(sourcemapIgnoreList),
		sourcemapPathTransform,
		banner: bindingifyAddon(banner),
		footer: bindingifyAddon(footer),
		intro: bindingifyAddon(intro),
		outro: bindingifyAddon(outro),
		extend: outputOptions.extend,
		globals,
		esModule,
		name,
		assetFileNames: bindingifyAssetFilenames(assetFileNames),
		entryFileNames,
		chunkFileNames,
		cssEntryFileNames,
		cssChunkFileNames,
		plugins: [],
		minify: outputOptions.minify,
		externalLiveBindings: outputOptions.externalLiveBindings,
		inlineDynamicImports: outputOptions.inlineDynamicImports,
		advancedChunks: outputOptions.advancedChunks,
		polyfillRequire: outputOptions.polyfillRequire,
		target: outputOptions.target,
		sanitizeFileName
	};
}
function bindingifyAddon(configAddon) {
	return async (chunk) => {
		if (typeof configAddon === "function") return configAddon(transformRenderedChunk(chunk));
		return configAddon || "";
	};
}
function bindingifyFormat(format) {
	switch (format) {
		case void 0:
		case "es":
		case "esm":
		case "module": return "es";
		case "cjs":
		case "commonjs": return "cjs";
		case "iife": return "iife";
		case "umd": return "umd";
		case "experimental-app": return "app";
		default: unimplemented(`output.format: ${format}`);
	}
}
function bindingifySourcemap(sourcemap) {
	switch (sourcemap) {
		case true: return "file";
		case "inline": return "inline";
		case false:
		case void 0: return void 0;
		case "hidden": return "hidden";
		default: throw new Error(`unknown sourcemap: ${sourcemap}`);
	}
}
function bindingifySourcemapIgnoreList(sourcemapIgnoreList) {
	return typeof sourcemapIgnoreList === "function" ? sourcemapIgnoreList : sourcemapIgnoreList === false ? () => false : (relativeSourcePath, _sourcemapPath) => relativeSourcePath.includes("node_modules");
}
function bindingifyAssetFilenames(assetFileNames) {
	if (typeof assetFileNames === "function") return (asset) => {
		return assetFileNames({
			names: asset.names,
			originalFileNames: asset.originalFileNames,
			source: transformAssetSource(asset.source),
			type: "asset"
		});
	};
	return assetFileNames;
}

//#endregion
//#region src/options/normalized-output-options.ts
var NormalizedOutputOptionsImpl = class {
	constructor(inner, outputOptions, normalizedOutputPlugins) {
		this.inner = inner;
		this.outputOptions = outputOptions;
		this.normalizedOutputPlugins = normalizedOutputPlugins;
	}
	get dir() {
		return this.inner.dir ?? void 0;
	}
	get entryFileNames() {
		return this.inner.entryFilenames || this.outputOptions.entryFileNames;
	}
	get chunkFileNames() {
		return this.inner.chunkFilenames || this.outputOptions.chunkFileNames;
	}
	get assetFileNames() {
		return this.inner.assetFilenames || this.outputOptions.assetFileNames;
	}
	get format() {
		return this.inner.format;
	}
	get exports() {
		return this.inner.exports;
	}
	get sourcemap() {
		return this.inner.sourcemap;
	}
	get cssEntryFileNames() {
		return this.inner.cssEntryFilenames || this.outputOptions.cssEntryFileNames;
	}
	get cssChunkFileNames() {
		return this.inner.cssChunkFilenames || this.outputOptions.cssChunkFileNames;
	}
	get shimMissingExports() {
		return this.inner.shimMissingExports;
	}
	get name() {
		return this.inner.name ?? void 0;
	}
	get file() {
		return this.inner.file ?? void 0;
	}
	get inlineDynamicImports() {
		return this.inner.inlineDynamicImports;
	}
	get externalLiveBindings() {
		return this.inner.externalLiveBindings;
	}
	get banner() {
		return normalizeAddon(this.outputOptions.banner);
	}
	get footer() {
		return normalizeAddon(this.outputOptions.footer);
	}
	get intro() {
		return normalizeAddon(this.outputOptions.intro);
	}
	get outro() {
		return normalizeAddon(this.outputOptions.outro);
	}
	get esModule() {
		return this.inner.esModule;
	}
	get extend() {
		return this.inner.extend;
	}
	get globals() {
		return this.inner.globals || this.outputOptions.globals;
	}
	get hashCharacters() {
		return this.inner.hashCharacters;
	}
	get sourcemapDebugIds() {
		return this.inner.sourcemapDebugIds;
	}
	get sourcemapIgnoreList() {
		return bindingifySourcemapIgnoreList(this.outputOptions.sourcemapIgnoreList);
	}
	get sourcemapPathTransform() {
		return this.outputOptions.sourcemapPathTransform;
	}
	get minify() {
		return this.inner.minify;
	}
	get comments() {
		return this.inner.comments;
	}
	get polyfillRequire() {
		return this.inner.polyfillRequire;
	}
	get plugins() {
		return this.normalizedOutputPlugins;
	}
};
function normalizeAddon(value) {
	if (typeof value === "function") return value;
	return () => value || "";
}

//#endregion
//#region src/plugin/bindingify-output-hooks.ts
function bindingifyRenderStart(args) {
	const hook = args.plugin.renderStart;
	if (!hook) return {};
	const { handler, meta } = normalizeHook(hook);
	return {
		plugin: async (ctx, opts) => {
			handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), new NormalizedOutputOptionsImpl(opts, args.outputOptions, args.normalizedOutputPlugins), new NormalizedInputOptionsImpl(opts, args.onLog));
		},
		meta: bindingifyPluginHookMeta(meta)
	};
}
function bindingifyRenderChunk(args) {
	const hook = args.plugin.renderChunk;
	if (!hook) return {};
	const { handler, meta } = normalizeHook(hook);
	return {
		plugin: async (ctx, code, chunk, opts, chunks) => {
			const ret = await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), code, transformRenderedChunk(chunk), new NormalizedOutputOptionsImpl(opts, args.outputOptions, args.normalizedOutputPlugins), { chunks: Object.fromEntries(Object.entries(chunks).map(([key, value]) => [key, transformRenderedChunk(value)])) });
			if (ret == null) return;
			if (typeof ret === "string") return { code: ret };
			if (!ret.map) return { code: ret.code };
			return {
				code: ret.code,
				map: bindingifySourcemap$1(ret.map)
			};
		},
		meta: bindingifyPluginHookMeta(meta)
	};
}
function bindingifyAugmentChunkHash(args) {
	const hook = args.plugin.augmentChunkHash;
	if (!hook) return {};
	const { handler, meta } = normalizeHook(hook);
	return {
		plugin: async (ctx, chunk) => {
			return await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), transformRenderedChunk(chunk));
		},
		meta: bindingifyPluginHookMeta(meta)
	};
}
function bindingifyRenderError(args) {
	const hook = args.plugin.renderError;
	if (!hook) return {};
	const { handler, meta } = normalizeHook(hook);
	return {
		plugin: async (ctx, err) => {
			handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), normalizeErrors(err));
		},
		meta: bindingifyPluginHookMeta(meta)
	};
}
function bindingifyGenerateBundle(args) {
	const hook = args.plugin.generateBundle;
	if (!hook) return {};
	const { handler, meta } = normalizeHook(hook);
	return {
		plugin: async (ctx, bundle, isWrite, opts) => {
			const changed = {
				updated: new Set(),
				deleted: new Set()
			};
			const output = transformToOutputBundle(bundle, changed);
			await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), new NormalizedOutputOptionsImpl(opts, args.outputOptions, args.normalizedOutputPlugins), output, isWrite);
			return collectChangedBundle(changed, output);
		},
		meta: bindingifyPluginHookMeta(meta)
	};
}
function bindingifyWriteBundle(args) {
	const hook = args.plugin.writeBundle;
	if (!hook) return {};
	const { handler, meta } = normalizeHook(hook);
	return {
		plugin: async (ctx, bundle, opts) => {
			const changed = {
				updated: new Set(),
				deleted: new Set()
			};
			const output = transformToOutputBundle(bundle, changed);
			await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), new NormalizedOutputOptionsImpl(opts, args.outputOptions, args.normalizedOutputPlugins), output);
			return collectChangedBundle(changed, output);
		},
		meta: bindingifyPluginHookMeta(meta)
	};
}
function bindingifyCloseBundle(args) {
	const hook = args.plugin.closeBundle;
	if (!hook) return {};
	const { handler, meta } = normalizeHook(hook);
	return {
		plugin: async (ctx) => {
			await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel));
		},
		meta: bindingifyPluginHookMeta(meta)
	};
}
function bindingifyBanner(args) {
	const hook = args.plugin.banner;
	if (!hook) return {};
	const { handler, meta } = normalizeHook(hook);
	return {
		plugin: async (ctx, chunk) => {
			if (typeof handler === "string") return handler;
			return handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), transformRenderedChunk(chunk));
		},
		meta: bindingifyPluginHookMeta(meta)
	};
}
function bindingifyFooter(args) {
	const hook = args.plugin.footer;
	if (!hook) return {};
	const { handler, meta } = normalizeHook(hook);
	return {
		plugin: async (ctx, chunk) => {
			if (typeof handler === "string") return handler;
			return handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), transformRenderedChunk(chunk));
		},
		meta: bindingifyPluginHookMeta(meta)
	};
}
function bindingifyIntro(args) {
	const hook = args.plugin.intro;
	if (!hook) return {};
	const { handler, meta } = normalizeHook(hook);
	return {
		plugin: async (ctx, chunk) => {
			if (typeof handler === "string") return handler;
			return handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), transformRenderedChunk(chunk));
		},
		meta: bindingifyPluginHookMeta(meta)
	};
}
function bindingifyOutro(args) {
	const hook = args.plugin.outro;
	if (!hook) return {};
	const { handler, meta } = normalizeHook(hook);
	return {
		plugin: async (ctx, chunk) => {
			if (typeof handler === "string") return handler;
			return handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), transformRenderedChunk(chunk));
		},
		meta: bindingifyPluginHookMeta(meta)
	};
}

//#endregion
//#region src/plugin/bindingify-watch-hooks.ts
function bindingifyWatchChange(args) {
	const hook = args.plugin.watchChange;
	if (!hook) return {};
	const { handler, meta } = normalizeHook(hook);
	return {
		plugin: async (ctx, id, event) => {
			await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), id, { event });
		},
		meta: bindingifyPluginHookMeta(meta)
	};
}
function bindingifyCloseWatcher(args) {
	const hook = args.plugin.closeWatcher;
	if (!hook) return {};
	const { handler, meta } = normalizeHook(hook);
	return {
		plugin: async (ctx) => {
			await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel));
		},
		meta: bindingifyPluginHookMeta(meta)
	};
}

//#endregion
//#region src/plugin/bindingify-plugin.ts
function bindingifyPlugin(plugin, options, outputOptions, pluginContextData, normalizedOutputPlugins, onLog, logLevel) {
	const args = {
		plugin,
		options,
		outputOptions,
		pluginContextData,
		onLog,
		logLevel,
		normalizedOutputPlugins
	};
	const { plugin: buildStart, meta: buildStartMeta } = bindingifyBuildStart(args);
	const { plugin: resolveId, meta: resolveIdMeta, filter: resolveIdFilter } = bindingifyResolveId(args);
	const { plugin: resolveDynamicImport, meta: resolveDynamicImportMeta } = bindingifyResolveDynamicImport(args);
	const { plugin: buildEnd, meta: buildEndMeta } = bindingifyBuildEnd(args);
	const { plugin: transform, meta: transformMeta, filter: transformFilter } = bindingifyTransform(args);
	const { plugin: moduleParsed, meta: moduleParsedMeta } = bindingifyModuleParsed(args);
	const { plugin: load, meta: loadMeta, filter: loadFilter } = bindingifyLoad(args);
	const { plugin: renderChunk, meta: renderChunkMeta } = bindingifyRenderChunk(args);
	const { plugin: augmentChunkHash, meta: augmentChunkHashMeta } = bindingifyAugmentChunkHash(args);
	const { plugin: renderStart, meta: renderStartMeta } = bindingifyRenderStart(args);
	const { plugin: renderError, meta: renderErrorMeta } = bindingifyRenderError(args);
	const { plugin: generateBundle, meta: generateBundleMeta } = bindingifyGenerateBundle(args);
	const { plugin: writeBundle, meta: writeBundleMeta } = bindingifyWriteBundle(args);
	const { plugin: closeBundle, meta: closeBundleMeta } = bindingifyCloseBundle(args);
	const { plugin: banner, meta: bannerMeta } = bindingifyBanner(args);
	const { plugin: footer, meta: footerMeta } = bindingifyFooter(args);
	const { plugin: intro, meta: introMeta } = bindingifyIntro(args);
	const { plugin: outro, meta: outroMeta } = bindingifyOutro(args);
	const { plugin: watchChange, meta: watchChangeMeta } = bindingifyWatchChange(args);
	const { plugin: closeWatcher, meta: closeWatcherMeta } = bindingifyCloseWatcher(args);
	const result = {
		name: plugin.name,
		buildStart,
		buildStartMeta,
		resolveId,
		resolveIdMeta,
		resolveIdFilter,
		resolveDynamicImport,
		resolveDynamicImportMeta,
		buildEnd,
		buildEndMeta,
		transform,
		transformMeta,
		transformFilter,
		moduleParsed,
		moduleParsedMeta,
		load,
		loadMeta,
		loadFilter,
		renderChunk,
		renderChunkMeta,
		augmentChunkHash,
		augmentChunkHashMeta,
		renderStart,
		renderStartMeta,
		renderError,
		renderErrorMeta,
		generateBundle,
		generateBundleMeta,
		writeBundle,
		writeBundleMeta,
		closeBundle,
		closeBundleMeta,
		banner,
		bannerMeta,
		footer,
		footerMeta,
		intro,
		introMeta,
		outro,
		outroMeta,
		watchChange,
		watchChangeMeta,
		closeWatcher,
		closeWatcherMeta
	};
	return wrapHandlers(result);
}
function wrapHandlers(plugin) {
	for (const hookName of [
		"buildStart",
		"resolveId",
		"resolveDynamicImport",
		"buildEnd",
		"transform",
		"moduleParsed",
		"load",
		"renderChunk",
		"augmentChunkHash",
		"renderStart",
		"renderError",
		"generateBundle",
		"writeBundle",
		"closeBundle",
		"banner",
		"footer",
		"intro",
		"outro",
		"watchChange",
		"closeWatcher"
	]) {
		const handler = plugin[hookName];
		if (handler) plugin[hookName] = async (...args) => {
			try {
				return await handler(...args);
			} catch (e) {
				return error(logPluginError(e, plugin.name, {
					hook: hookName,
					id: hookName === "transform" ? args[2] : void 0
				}));
			}
		};
	}
	return plugin;
}

//#endregion
//#region src/plugin/plugin-context-data.ts
var PluginContextData = class {
	moduleOptionMap = new Map();
	resolveOptionsMap = new Map();
	loadModulePromiseMap = new Map();
	updateModuleOption(id, option) {
		const existing = this.moduleOptionMap.get(id);
		if (existing) {
			if (option.moduleSideEffects != null) existing.moduleSideEffects = option.moduleSideEffects;
			if (option.meta != null) Object.assign(existing.meta, option.meta);
			if (option.invalidate != null) existing.invalidate = option.invalidate;
		} else {
			this.moduleOptionMap.set(id, option);
			return option;
		}
		return existing;
	}
	getModuleOption(id) {
		const option = this.moduleOptionMap.get(id);
		if (!option) {
			const raw = {
				moduleSideEffects: null,
				meta: {}
			};
			this.moduleOptionMap.set(id, raw);
			return raw;
		}
		return option;
	}
	getModuleInfo(id, context) {
		const bindingInfo = context.getModuleInfo(id);
		if (bindingInfo) {
			const info = transformModuleInfo(bindingInfo, this.getModuleOption(id));
			return this.proxyModuleInfo(id, info);
		}
		return null;
	}
	proxyModuleInfo(id, info) {
		let moduleSideEffects = info.moduleSideEffects;
		Object.defineProperty(info, "moduleSideEffects", {
			get() {
				return moduleSideEffects;
			},
			set: (v$1) => {
				this.updateModuleOption(id, {
					moduleSideEffects: v$1,
					meta: info.meta,
					invalidate: true
				});
				moduleSideEffects = v$1;
			}
		});
		return info;
	}
	getModuleIds(context) {
		const moduleIds = context.getModuleIds();
		return moduleIds.values();
	}
	saveResolveOptions(options) {
		const index = this.resolveOptionsMap.size;
		this.resolveOptionsMap.set(index, options);
		return index;
	}
	getSavedResolveOptions(receipt) {
		return this.resolveOptionsMap.get(receipt);
	}
	removeSavedResolveOptions(receipt) {
		this.resolveOptionsMap.delete(receipt);
	}
};

//#endregion
//#region src/utils/normalize-string-or-regex.ts
function normalizedStringOrRegex(pattern) {
	if (!pattern) return void 0;
	if (!Array.isArray(pattern)) pattern = [pattern];
	return pattern;
}

//#endregion
//#region src/utils/bindingify-input-options.ts
function bindingifyInputOptions(rawPlugins, inputOptions, outputOptions, normalizedOutputPlugins, onLog, logLevel) {
	const pluginContextData = new PluginContextData();
	const plugins = rawPlugins.map((plugin) => {
		if ("_parallel" in plugin) return void 0;
		if (plugin instanceof BuiltinPlugin) return bindingifyBuiltInPlugin(plugin);
		return bindingifyPlugin(plugin, inputOptions, outputOptions, pluginContextData, normalizedOutputPlugins, onLog, logLevel);
	});
	return {
		input: bindingifyInput(inputOptions.input),
		plugins,
		cwd: inputOptions.cwd ?? process.cwd(),
		external: bindingifyExternal(inputOptions.external),
		resolve: bindingifyResolve(inputOptions.resolve),
		platform: inputOptions.platform,
		shimMissingExports: inputOptions.shimMissingExports,
		logLevel: bindingifyLogLevel(logLevel),
		onLog,
		treeshake: bindingifyTreeshakeOptions(inputOptions.treeshake),
		moduleTypes: inputOptions.moduleTypes,
		define: inputOptions.define ? Object.entries(inputOptions.define) : void 0,
		inject: bindingifyInject(inputOptions.inject),
		experimental: {
			strictExecutionOrder: inputOptions.experimental?.strictExecutionOrder,
			disableLiveBindings: inputOptions.experimental?.disableLiveBindings,
			viteMode: inputOptions.experimental?.viteMode,
			resolveNewUrlToAsset: inputOptions.experimental?.resolveNewUrlToAsset,
			hmr: inputOptions.experimental?.hmr
		},
		profilerNames: inputOptions?.profilerNames,
		jsx: bindingifyJsx(inputOptions.jsx),
		transform: inputOptions.transform,
		watch: bindingifyWatch(inputOptions.watch),
		dropLabels: inputOptions.dropLabels,
		keepNames: inputOptions.keepNames,
		checks: inputOptions.checks,
		deferSyncScanData: () => {
			let ret = [];
			pluginContextData.moduleOptionMap.forEach((value, key) => {
				if (value.invalidate) ret.push({
					id: key,
					sideEffects: bindingifySideEffects(value.moduleSideEffects)
				});
			});
			return ret;
		},
		makeAbsoluteExternalsRelative: bindingifyMakeAbsoluteExternalsRelative(inputOptions.makeAbsoluteExternalsRelative)
	};
}
function bindingifyExternal(external) {
	if (external) {
		if (typeof external === "function") return (id, importer, isResolved) => {
			if (id.startsWith("\0")) return false;
			return external(id, importer, isResolved) ?? false;
		};
		const externalArr = arraify(external);
		return (id, _importer, _isResolved) => {
			return externalArr.some((pat) => {
				if (pat instanceof RegExp) return pat.test(id);
				return id === pat;
			});
		};
	}
}
function bindingifyResolve(resolve) {
	if (resolve) {
		const { alias, extensionAlias,...rest } = resolve;
		return {
			alias: alias ? Object.entries(alias).map(([name, replacement]) => ({
				find: name,
				replacements: arraify(replacement)
			})) : void 0,
			extensionAlias: extensionAlias ? Object.entries(extensionAlias).map(([name, value]) => ({
				target: name,
				replacements: value
			})) : void 0,
			...rest
		};
	}
}
function bindingifyInject(inject) {
	if (inject) return Object.entries(inject).map(([alias, item]) => {
		if (Array.isArray(item)) {
			if (item[1] === "*") return {
				tagNamespace: true,
				alias,
				from: item[0]
			};
			return {
				tagNamed: true,
				alias,
				from: item[0],
				imported: item[1]
			};
		} else return {
			tagNamed: true,
			imported: "default",
			alias,
			from: item
		};
	});
}
function bindingifyLogLevel(logLevel) {
	switch (logLevel) {
		case "silent": return import_binding.BindingLogLevel.Silent;
		case "debug": return import_binding.BindingLogLevel.Debug;
		case "warn": return import_binding.BindingLogLevel.Warn;
		case "info": return import_binding.BindingLogLevel.Info;
		default: throw new Error(`Unexpected log level: ${logLevel}`);
	}
}
function bindingifyInput(input) {
	if (input === void 0) return [];
	if (typeof input === "string") return [{ import: input }];
	if (Array.isArray(input)) return input.map((src) => ({ import: src }));
	return Object.entries(input).map(([name, import_path]) => {
		return {
			name,
			import: import_path
		};
	});
}
function bindingifyJsx(input) {
	switch (input) {
		case false: return { type: "Disable" };
		case "react": return { type: "React" };
		case "react-jsx": return { type: "ReactJsx" };
		case "preserve": return { type: "Preserve" };
		case void 0: return void 0;
	}
	if (input.mode === "preserve") return { type: "Preserve" };
	const mode = input.mode ?? "automatic";
	return {
		type: "Enable",
		field0: {
			runtime: mode,
			importSource: mode === "classic" ? input.importSource : mode === "automatic" ? input.jsxImportSource : void 0,
			pragma: input.factory,
			pragmaFrag: input.fragment,
			development: input.development,
			refresh: input.refresh
		}
	};
}
function bindingifyWatch(watch$1) {
	if (watch$1) return {
		buildDelay: watch$1.buildDelay,
		skipWrite: watch$1.skipWrite,
		include: normalizedStringOrRegex(watch$1.include),
		exclude: normalizedStringOrRegex(watch$1.exclude)
	};
}
function bindingifyTreeshakeOptions(config) {
	if (config === false) return void 0;
	if (config === true || config === void 0) return { moduleSideEffects: true };
	let normalizedConfig = {
		moduleSideEffects: true,
		annotations: config.annotations,
		manualPureFunctions: config.manualPureFunctions,
		unknownGlobalSideEffects: config.unknownGlobalSideEffects
	};
	if (config.moduleSideEffects === void 0) normalizedConfig.moduleSideEffects = true;
	else if (config.moduleSideEffects === "no-external") normalizedConfig.moduleSideEffects = [{
		external: true,
		sideEffects: false
	}, {
		external: false,
		sideEffects: true
	}];
	else normalizedConfig.moduleSideEffects = config.moduleSideEffects;
	return normalizedConfig;
}
function bindingifyMakeAbsoluteExternalsRelative(makeAbsoluteExternalsRelative) {
	if (makeAbsoluteExternalsRelative === "ifRelativeSource") return { type: "IfRelativeSource" };
	if (typeof makeAbsoluteExternalsRelative === "boolean") return {
		type: "Bool",
		field0: makeAbsoluteExternalsRelative
	};
}

//#endregion
//#region ../../node_modules/.pnpm/remeda@2.21.2/node_modules/remeda/dist/chunk-D6FCK2GA.js
function u$1(o, n, a) {
	let t$1 = (r) => o(r, ...n);
	return a === void 0 ? t$1 : Object.assign(t$1, {
		lazy: a,
		lazyArgs: n
	});
}

//#endregion
//#region ../../node_modules/.pnpm/remeda@2.21.2/node_modules/remeda/dist/chunk-WIMGWYZL.js
function u(r, n, o) {
	let a = r.length - n.length;
	if (a === 0) return r(...n);
	if (a === 1) return u$1(r, n, o);
	throw new Error("Wrong number of arguments");
}

//#endregion
//#region ../../node_modules/.pnpm/remeda@2.21.2/node_modules/remeda/dist/chunk-5NQBDF4H.js
function t(...n) {
	return u(Object.keys, n);
}

//#endregion
//#region src/utils/plugin/index.ts
const isPluginHookName = function() {
	const PLUGIN_HOOK_NAMES_SET = new Set(ENUMERATED_PLUGIN_HOOK_NAMES);
	return function isPluginHookName$1(hookName) {
		return PLUGIN_HOOK_NAMES_SET.has(hookName);
	};
}();

//#endregion
//#region src/utils/compose-js-plugins.ts
const unsupportedHookName = [
	"augmentChunkHash",
	"generateBundle",
	"moduleParsed",
	"onLog",
	"options",
	"outputOptions",
	"renderError",
	"renderStart",
	"resolveDynamicImport",
	"writeBundle"
];
const unsupportedHooks = new Set(unsupportedHookName);
function isUnsupportedHooks(hookName) {
	return unsupportedHooks.has(hookName);
}
function createComposedPlugin(plugins) {
	const names = [];
	const batchedHooks = {};
	plugins.forEach((plugin, index) => {
		const pluginName = plugin.name || `Anonymous(index: ${index})`;
		names.push(pluginName);
		t(plugin).forEach((pluginProp) => {
			if (isUnsupportedHooks(pluginProp)) throw new Error(`Failed to compose js plugins. Plugin ${pluginName} has an unsupported hook: ${pluginProp}`);
			if (!isPluginHookName(pluginProp)) return;
			switch (pluginProp) {
				case "buildStart": {
					const handlers = batchedHooks.buildStart ?? [];
					batchedHooks.buildStart = handlers;
					if (plugin.buildStart) handlers.push([plugin.buildStart, plugin]);
					break;
				}
				case "load": {
					const handlers = batchedHooks.load ?? [];
					batchedHooks.load = handlers;
					if (plugin.load) handlers.push([plugin.load, plugin]);
					break;
				}
				case "transform": {
					const handlers = batchedHooks.transform ?? [];
					batchedHooks.transform = handlers;
					if (plugin.transform) handlers.push([plugin.transform, plugin]);
					break;
				}
				case "resolveId": {
					const handlers = batchedHooks.resolveId ?? [];
					batchedHooks.resolveId = handlers;
					if (plugin.resolveId) handlers.push([plugin.resolveId, plugin]);
					break;
				}
				case "buildEnd": {
					const handlers = batchedHooks.buildEnd ?? [];
					batchedHooks.buildEnd = handlers;
					if (plugin.buildEnd) handlers.push([plugin.buildEnd, plugin]);
					break;
				}
				case "renderChunk": {
					const handlers = batchedHooks.renderChunk ?? [];
					batchedHooks.renderChunk = handlers;
					if (plugin.renderChunk) handlers.push([plugin.renderChunk, plugin]);
					break;
				}
				case "banner":
				case "footer":
				case "intro":
				case "outro": {
					const hook = plugin[pluginProp];
					if (hook) (batchedHooks[pluginProp] ??= []).push([hook, plugin]);
					break;
				}
				case "closeBundle": {
					const handlers = batchedHooks.closeBundle ?? [];
					batchedHooks.closeBundle = handlers;
					if (plugin.closeBundle) handlers.push([plugin.closeBundle, plugin]);
					break;
				}
				case "watchChange": {
					const handlers = batchedHooks.watchChange ?? [];
					batchedHooks.watchChange = handlers;
					if (plugin.watchChange) handlers.push([plugin.watchChange, plugin]);
					break;
				}
				case "closeWatcher": {
					const handlers = batchedHooks.closeWatcher ?? [];
					batchedHooks.closeWatcher = handlers;
					if (plugin.closeWatcher) handlers.push([plugin.closeWatcher, plugin]);
					break;
				}
				default: {}
			}
		});
	});
	const composed = { name: `Composed(${names.join(", ")})` };
	const createFixedPluginResolveFnMap = new Map();
	function applyFixedPluginResolveFn(ctx, plugin) {
		const createFixedPluginResolveFn = createFixedPluginResolveFnMap.get(plugin);
		if (createFixedPluginResolveFn) ctx.resolve = createFixedPluginResolveFn(ctx, ctx.resolve.bind(ctx));
		return ctx;
	}
	if (batchedHooks.resolveId) {
		const batchedHandlers = batchedHooks.resolveId;
		const handlerSymbols = batchedHandlers.map(([_handler, plugin]) => Symbol(plugin.name ?? `Anonymous`));
		for (let handlerIdx = 0; handlerIdx < batchedHandlers.length; handlerIdx++) {
			const [_handler, plugin] = batchedHandlers[handlerIdx];
			const handlerSymbol = handlerSymbols[handlerIdx];
			const createFixedPluginResolveFn = (ctx, resolve) => {
				return (source, importer, rawContextResolveOptions) => {
					const contextResolveOptions = rawContextResolveOptions ?? {};
					if (contextResolveOptions.skipSelf) {
						contextResolveOptions[SYMBOL_FOR_RESOLVE_CALLER_THAT_SKIP_SELF] = handlerSymbol;
						contextResolveOptions.skipSelf = false;
					}
					return resolve(source, importer, contextResolveOptions);
				};
			};
			createFixedPluginResolveFnMap.set(plugin, createFixedPluginResolveFn);
		}
		composed.resolveId = async function(source, importer, rawHookResolveIdOptions) {
			const hookResolveIdOptions = rawHookResolveIdOptions;
			const symbolForCallerThatSkipSelf = hookResolveIdOptions?.[SYMBOL_FOR_RESOLVE_CALLER_THAT_SKIP_SELF];
			for (let handlerIdx = 0; handlerIdx < batchedHandlers.length; handlerIdx++) {
				const [handler, plugin] = batchedHandlers[handlerIdx];
				const handlerSymbol = handlerSymbols[handlerIdx];
				if (symbolForCallerThatSkipSelf === handlerSymbol) continue;
				const { handler: handlerFn } = normalizeHook(handler);
				const result = await handlerFn.call(applyFixedPluginResolveFn(this, plugin), source, importer, rawHookResolveIdOptions);
				if (!isNullish(result)) return result;
			}
		};
	}
	t(batchedHooks).forEach((hookName) => {
		switch (hookName) {
			case "resolveId": break;
			case "buildStart": {
				if (batchedHooks.buildStart) {
					const batchedHandlers = batchedHooks.buildStart;
					composed.buildStart = async function(options) {
						await Promise.all(batchedHandlers.map(([handler, plugin]) => {
							const { handler: handlerFn } = normalizeHook(handler);
							return handlerFn.call(applyFixedPluginResolveFn(this, plugin), options);
						}));
					};
				}
				break;
			}
			case "load": {
				if (batchedHooks.load) {
					const batchedHandlers = batchedHooks.load;
					composed.load = async function(id) {
						for (const [handler, plugin] of batchedHandlers) {
							const { handler: handlerFn } = normalizeHook(handler);
							const result = await handlerFn.call(applyFixedPluginResolveFn(this, plugin), id);
							if (!isNullish(result)) return result;
						}
					};
				}
				break;
			}
			case "transform": {
				if (batchedHooks.transform) {
					const batchedHandlers = batchedHooks.transform;
					composed.transform = async function(initialCode, id, moduleType) {
						let code = initialCode;
						let moduleSideEffects = void 0;
						function updateOutput(newCode, newModuleSideEffects) {
							code = newCode;
							moduleSideEffects = newModuleSideEffects ?? void 0;
						}
						for (const [handler, plugin] of batchedHandlers) {
							const { handler: handlerFn } = normalizeHook(handler);
							this.getCombinedSourcemap = () => {
								throw new Error(`The getCombinedSourcemap is not implement in transform hook at composedJsPlugins`);
							};
							const result = await handlerFn.call(applyFixedPluginResolveFn(this, plugin), code, id, moduleType);
							if (!isNullish(result)) {
								if (typeof result === "string") updateOutput(result);
								else if (result.code) updateOutput(result.code, result.moduleSideEffects);
							}
						}
						return {
							code,
							moduleSideEffects
						};
					};
				}
				break;
			}
			case "buildEnd": {
				if (batchedHooks.buildEnd) {
					const batchedHandlers = batchedHooks.buildEnd;
					composed.buildEnd = async function(err) {
						await Promise.all(batchedHandlers.map(([handler, plugin]) => {
							const { handler: handlerFn } = normalizeHook(handler);
							return handlerFn.call(applyFixedPluginResolveFn(this, plugin), err);
						}));
					};
				}
				break;
			}
			case "renderChunk": {
				if (batchedHooks.renderChunk) {
					const batchedHandlers = batchedHooks.renderChunk;
					composed.renderChunk = async function(code, chunk, options, meta) {
						for (const [handler, plugin] of batchedHandlers) {
							const { handler: handlerFn } = normalizeHook(handler);
							const result = await handlerFn.call(applyFixedPluginResolveFn(this, plugin), code, chunk, options, meta);
							if (!isNullish(result)) return result;
						}
					};
				}
				break;
			}
			case "banner":
			case "footer":
			case "intro":
			case "outro": {
				const hooks = batchedHooks[hookName];
				if (hooks?.length) composed[hookName] = async function(chunk) {
					const ret = [];
					for (const [hook, plugin] of hooks) {
						const { handler } = normalizeHook(hook);
						ret.push(typeof handler === "string" ? handler : await handler.call(applyFixedPluginResolveFn(this, plugin), chunk));
					}
					return ret.join("\n");
				};
				break;
			}
			case "closeBundle": {
				if (batchedHooks.closeBundle) {
					const batchedHandlers = batchedHooks.closeBundle;
					composed.closeBundle = async function() {
						await Promise.all(batchedHandlers.map(([handler, plugin]) => {
							const { handler: handlerFn } = normalizeHook(handler);
							return handlerFn.call(applyFixedPluginResolveFn(this, plugin));
						}));
					};
				}
				break;
			}
			case "watchChange": {
				if (batchedHooks.watchChange) {
					const batchedHandlers = batchedHooks.watchChange;
					composed.watchChange = async function(id, event) {
						await Promise.all(batchedHandlers.map(([handler, plugin]) => {
							const { handler: handlerFn } = normalizeHook(handler);
							return handlerFn.call(applyFixedPluginResolveFn(this, plugin), id, event);
						}));
					};
				}
				break;
			}
			case "closeWatcher": {
				if (batchedHooks.closeWatcher) {
					const batchedHandlers = batchedHooks.closeWatcher;
					composed.closeWatcher = async function() {
						await Promise.all(batchedHandlers.map(([handler, plugin]) => {
							const { handler: handlerFn } = normalizeHook(handler);
							return handlerFn.call(applyFixedPluginResolveFn(this, plugin));
						}));
					};
				}
				break;
			}
			default: {}
		}
	});
	return composed;
}
function isComposablePlugin(plugin) {
	if (plugin instanceof BuiltinPlugin) return false;
	if ("_parallel" in plugin) return false;
	const hasNotComposablePattern = t(plugin).some((hookName) => {
		if (!isPluginHookName(hookName)) return false;
		const OK_TO_COMPOSE = false;
		if (isUnsupportedHooks(hookName)) return !OK_TO_COMPOSE;
		if (plugin[hookName]) {
			const { meta } = normalizeHook(plugin[hookName]);
			if (meta.order === "pre" || meta.order === "post") return !OK_TO_COMPOSE;
		}
		return OK_TO_COMPOSE;
	});
	if (hasNotComposablePattern) return false;
	return true;
}
function composeJsPlugins(plugins) {
	const newPlugins = [];
	const toBeComposed = [];
	plugins.forEach((plugin) => {
		if (isComposablePlugin(plugin)) toBeComposed.push(plugin);
		else {
			if (toBeComposed.length > 0) {
				if (toBeComposed.length > 1) newPlugins.push(createComposedPlugin(toBeComposed));
				else newPlugins.push(toBeComposed[0]);
				toBeComposed.length = 0;
			}
			newPlugins.push(plugin);
		}
	});
	if (toBeComposed.length > 0) {
		if (toBeComposed.length > 1) newPlugins.push(createComposedPlugin(toBeComposed));
		else newPlugins.push(toBeComposed[0]);
		toBeComposed.length = 0;
	}
	return newPlugins;
}

//#endregion
//#region src/utils/initialize-parallel-plugins.ts
async function initializeParallelPlugins(plugins) {
	const pluginInfos = [];
	for (const [index, plugin] of plugins.entries()) if ("_parallel" in plugin) {
		const { fileUrl, options } = plugin._parallel;
		pluginInfos.push({
			index,
			fileUrl,
			options
		});
	}
	if (pluginInfos.length <= 0) return void 0;
	const count = Math.min(availableParallelism(), 8);
	const parallelJsPluginRegistry = new import_binding.ParallelJsPluginRegistry(count);
	const registryId = parallelJsPluginRegistry.id;
	const workers = await initializeWorkers(registryId, count, pluginInfos);
	const stopWorkers = async () => {
		await Promise.all(workers.map((worker) => worker.terminate()));
	};
	return {
		registry: parallelJsPluginRegistry,
		stopWorkers
	};
}
function initializeWorkers(registryId, count, pluginInfos) {
	return Promise.all(Array.from({ length: count }, (_, i) => initializeWorker(registryId, pluginInfos, i)));
}
async function initializeWorker(registryId, pluginInfos, threadNumber) {
	const urlString = import.meta.resolve("#parallel-plugin-worker");
	const workerData$1 = {
		registryId,
		pluginInfos,
		threadNumber
	};
	let worker;
	try {
		worker = new Worker(new URL(urlString), { workerData: workerData$1 });
		worker.unref();
		await new Promise((resolve, reject) => {
			worker.once("message", async (message) => {
				if (message.type === "error") reject(message.error);
				else resolve();
			});
		});
		return worker;
	} catch (e) {
		worker?.terminate();
		throw e;
	}
}

//#endregion
//#region src/utils/create-bundler-option.ts
async function createBundlerOptions(inputOptions, outputOptions, isClose) {
	const inputPlugins = await normalizePluginOption(inputOptions.plugins);
	const outputPlugins = await normalizePluginOption(outputOptions.plugins);
	const logLevel = inputOptions.logLevel || LOG_LEVEL_INFO;
	const onLog = getLogger(getObjectPlugins(inputPlugins), getOnLog(inputOptions, logLevel), logLevel);
	if (!isClose) outputOptions = PluginDriver.callOutputOptionsHook([...inputPlugins, ...outputPlugins], outputOptions);
	if (outputOptions.minify === true) onLog(LOG_LEVEL_WARN, logMinifyWarning());
	const normalizedOutputPlugins = await normalizePluginOption(outputOptions.plugins);
	let plugins = [...normalizePlugins(inputPlugins, ANONYMOUS_PLUGIN_PREFIX), ...checkOutputPluginOption(normalizePlugins(normalizedOutputPlugins, ANONYMOUS_OUTPUT_PLUGIN_PREFIX), onLog)];
	if (inputOptions.experimental?.enableComposingJsPlugins ?? false) plugins = composeJsPlugins(plugins);
	const parallelPluginInitResult = await initializeParallelPlugins(plugins);
	try {
		const bindingInputOptions = bindingifyInputOptions(plugins, inputOptions, outputOptions, normalizedOutputPlugins, onLog, logLevel);
		const bindingOutputOptions = bindingifyOutputOptions(outputOptions);
		return {
			bundlerOptions: {
				inputOptions: bindingInputOptions,
				outputOptions: bindingOutputOptions,
				parallelPluginsRegistry: parallelPluginInitResult?.registry
			},
			inputOptions,
			onLog,
			stopWorkers: parallelPluginInitResult?.stopWorkers
		};
	} catch (e) {
		await parallelPluginInitResult?.stopWorkers();
		throw e;
	}
}

//#endregion
//#region src/utils/create-bundler.ts
let asyncRuntimeShutdown = false;
async function createBundler(inputOptions, outputOptions, isClose) {
	const option = await createBundlerOptions(inputOptions, outputOptions, isClose);
	if (asyncRuntimeShutdown) (0, import_binding.startAsyncRuntime)();
	try {
		return {
			bundler: new import_binding.Bundler(option.bundlerOptions),
			stopWorkers: option.stopWorkers,
			shutdown: () => {
				(0, import_binding.shutdownAsyncRuntime)();
				asyncRuntimeShutdown = true;
			}
		};
	} catch (e) {
		await option.stopWorkers?.();
		throw e;
	}
}

//#endregion
//#region src/api/rolldown/rolldown-build.ts
Symbol.asyncDispose ??= Symbol("Symbol.asyncDispose");
var RolldownBuild = class {
	#inputOptions;
	#bundler;
	constructor(inputOptions) {
		this.#inputOptions = inputOptions;
	}
	get closed() {
		return this.#bundler?.bundler.closed ?? false;
	}
	async #getBundlerWithStopWorker(outputOptions, isClose) {
		if (this.#bundler) await this.#bundler.stopWorkers?.();
		return this.#bundler = await createBundler(this.#inputOptions, outputOptions, isClose);
	}
	async generate(outputOptions = {}) {
		validateOption("output", outputOptions);
		const { bundler } = await this.#getBundlerWithStopWorker(outputOptions);
		const output = await bundler.generate();
		return transformToRollupOutput(output);
	}
	async write(outputOptions = {}) {
		validateOption("output", outputOptions);
		const { bundler } = await this.#getBundlerWithStopWorker(outputOptions);
		const output = await bundler.write();
		return transformToRollupOutput(output);
	}
	async close() {
		const { bundler, stopWorkers, shutdown } = await this.#getBundlerWithStopWorker({}, true);
		await stopWorkers?.();
		await bundler.close();
		shutdown();
	}
	async [Symbol.asyncDispose]() {
		await this.close();
	}
	async generateHmrPatch(changedFiles) {
		return this.#bundler?.bundler.generateHmrPatch(changedFiles);
	}
};

//#endregion
//#region src/api/rolldown/index.ts
const rolldown = async (input) => {
	validateOption("input", input);
	const inputOptions = await PluginDriver.callOptionsHook(input);
	return new RolldownBuild(inputOptions);
};

//#endregion
//#region src/api/watch/watch-emitter.ts
var WatcherEmitter = class {
	listeners = new Map();
	timer;
	constructor() {
		this.timer = setInterval(
			() => {},
			1e9
			/* Low power usage */
);
	}
	on(event, listener) {
		const listeners = this.listeners.get(event);
		if (listeners) listeners.push(listener);
		else this.listeners.set(event, [listener]);
		return this;
	}
	async onEvent(event) {
		const listeners = this.listeners.get(event.eventKind());
		if (listeners) switch (event.eventKind()) {
			case "close":
			case "restart":
				for (const listener of listeners) await listener();
				break;
			case "event":
				for (const listener of listeners) {
					const code = event.bundleEventKind();
					switch (code) {
						case "BUNDLE_END":
							const { duration, output } = event.bundleEndData();
							await listener({
								code: "BUNDLE_END",
								duration,
								output: [output]
							});
							break;
						case "ERROR":
							const errors = event.errors();
							await listener({
								code: "ERROR",
								error: normalizeErrors(errors)
							});
							break;
						default:
							await listener({ code });
							break;
					}
				}
				break;
			case "change":
				for (const listener of listeners) {
					const { path: path$1, kind } = event.watchChangeData();
					await listener(path$1, { event: kind });
				}
				break;
			default: throw new Error(`Unknown event: ${event}`);
		}
	}
	async close() {
		clearInterval(this.timer);
	}
};

//#endregion
//#region src/api/watch/watcher.ts
var Watcher = class {
	closed;
	inner;
	emitter;
	stopWorkers;
	constructor(emitter, inner, stopWorkers) {
		this.closed = false;
		this.inner = inner;
		this.emitter = emitter;
		const originClose = emitter.close.bind(emitter);
		emitter.close = async () => {
			await this.close();
			originClose();
		};
		this.stopWorkers = stopWorkers;
	}
	async close() {
		if (this.closed) return;
		this.closed = true;
		for (const stop of this.stopWorkers) await stop?.();
		await this.inner.close();
		(0, import_binding.shutdownAsyncRuntime)();
	}
	start() {
		process.nextTick(() => this.inner.start(this.emitter.onEvent.bind(this.emitter)));
	}
};
async function createWatcher(emitter, input) {
	const options = arraify(input);
	const bundlerOptions = await Promise.all(options.map((option) => arraify(option.output || {}).map(async (output) => {
		const inputOptions = await PluginDriver.callOptionsHook(option);
		return createBundlerOptions(inputOptions, output);
	})).flat());
	const notifyOptions = getValidNotifyOption(bundlerOptions);
	const bindingWatcher = new import_binding.BindingWatcher(bundlerOptions.map((option) => option.bundlerOptions), notifyOptions);
	const watcher = new Watcher(emitter, bindingWatcher, bundlerOptions.map((option) => option.stopWorkers));
	watcher.start();
}
function getValidNotifyOption(bundlerOptions) {
	let result;
	for (const option of bundlerOptions) if (option.inputOptions.watch) {
		const notifyOption = option.inputOptions.watch.notify;
		if (notifyOption) if (result) {
			option.onLog(LOG_LEVEL_WARN, logMultiplyNotifyOption());
			return result;
		} else result = notifyOption;
	}
}

//#endregion
//#region src/api/watch/index.ts
const watch = (input) => {
	const emitter = new WatcherEmitter();
	createWatcher(emitter, input);
	return emitter;
};

//#endregion
//#region package.json
var version = "1.0.0-beta.7-commit.7452fa0";
var description = "Fast JavaScript/TypeScript bundler in Rust with Rollup-compatible API.";

//#endregion
//#region src/api/build.ts
async function build(options) {
	if (Array.isArray(options)) return Promise.all(options.map((opts) => build(opts)));
	else {
		const { output, write = true,...inputOptions } = options;
		const build$1 = await rolldown(inputOptions);
		try {
			if (write) return await build$1.write(output);
			else return await build$1.generate(output);
		} finally {
			await build$1.close();
		}
	}
}

//#endregion
//#region src/index.ts
const VERSION = version;

//#endregion
export { BuiltinPlugin, PluginContextData, VERSION, arraify, bindingifyPlugin, build, buildImportAnalysisPlugin, composeJsPlugins, createBundler, defineConfig, description, dynamicImportVarsPlugin, getInputCliKeys, getJsonSchema, getOutputCliKeys, handleOutputErrors, importGlobPlugin, isolatedDeclarationPlugin, jsonPlugin, loadFallbackPlugin, manifestPlugin, moduleFederationPlugin, modulePreloadPolyfillPlugin, normalizedStringOrRegex, rolldown, validateCliOptions, version, viteResolvePlugin, wasmFallbackPlugin, wasmHelperPlugin, watch };