Object.defineProperties(exports, {
	__esModule: { value: true },
	[Symbol.toStringTag]: { value: "Module" }
});
//#region \0rolldown/runtime.js
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __copyProps = (to, from, except, desc) => {
	if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
		key = keys[i];
		if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
			get: ((k) => from[k]).bind(null, key),
			enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
		});
	}
	return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
	value: mod,
	enumerable: true
}) : target, mod));
//#endregion
let path = require("path");
path = __toESM(path);
let fs = require("fs");
fs = __toESM(fs);
let os = require("os");
os = __toESM(os);
let fs_promises = require("fs/promises");
//#region src/vite/mime-types.ts
/**
* Нам не нужен огромный универсальный справочник MIME:
* этот dev-server отдает только типичные веб-ассеты из npm-пакета.
* Чем меньше таблица, тем меньше она попадает в итоговый JS-бандл.
*/
var COMMON_MIME_TYPES = {
	css: "text/css; charset=utf-8",
	eot: "application/vnd.ms-fontobject",
	gif: "image/gif",
	htm: "text/html; charset=utf-8",
	html: "text/html; charset=utf-8",
	ico: "image/x-icon",
	jpeg: "image/jpeg",
	jpg: "image/jpeg",
	js: "application/javascript; charset=utf-8",
	json: "application/json; charset=utf-8",
	map: "application/json; charset=utf-8",
	mjs: "application/javascript; charset=utf-8",
	otf: "font/otf",
	png: "image/png",
	svg: "image/svg+xml",
	txt: "text/plain; charset=utf-8",
	ttf: "font/ttf",
	wasm: "application/wasm",
	webp: "image/webp",
	woff: "font/woff",
	woff2: "font/woff2"
};
function getMimeTypeByExtension(ext) {
	if (!ext) return "application/octet-stream";
	return COMMON_MIME_TYPES[ext.toLowerCase()] || "application/octet-stream";
}
//#endregion
//#region src/vite/utils.ts
function slash(p) {
	return p.replace(/\\/g, "/");
}
var cleanUrl = (url) => {
	return url.replace(/#.*$/s, "").replace(/\?.*$/s, "");
};
function normalizePath(id) {
	const isWindows = os.default.platform() === "win32";
	return path.default.posix.normalize(isWindows ? slash(id) : id);
}
var fileExists = async (p) => !!await (0, fs_promises.stat)(p).catch(() => false);
async function copyFolder(src, dest, filter) {
	if (!await fileExists(dest)) await (0, fs_promises.mkdir)(dest, { recursive: true });
	const entries = await (0, fs_promises.readdir)(src);
	await Promise.all(entries.map(async (entry) => {
		const srcPath = path.default.join(src, entry);
		if (filter(srcPath)) {
			const destPath = path.default.join(dest, entry);
			const st = await (0, fs_promises.stat)(srcPath);
			if (st.isFile()) await (0, fs_promises.copyFile)(srcPath, destPath);
			else if (st.isDirectory()) await copyFolder(srcPath, destPath, filter);
		}
	}));
}
//#endregion
//#region src/shared/hostBootstrap.ts
/**
* Host plugin bootstrap: sets contractual `window.__ns__.publicPath` (e.g. `/product/`)
* before product entry runs. Publish bootstrap uses script/meta detection only when
* `publicPath` is still unset — plugin-dev must rely on host prepend, not detection.
*/
function createNormalizedPublicPathAssignment(environmentVariable, rawPath) {
	const literal = JSON.stringify(String(rawPath || ""));
	return [
		`if (!window.${environmentVariable}.publicPath) window.${environmentVariable}.publicPath = (function() {`,
		`  var rawPath = ${literal};`,
		"  if (!rawPath) {",
		"    rawPath = './';",
		"  }",
		"  try {",
		"    var normalizedPath = String(rawPath);",
		"    if (/^[a-zA-Z][a-zA-Z\\d+\\-.]*:/.test(normalizedPath) || normalizedPath.indexOf('//') === 0) {",
		"      return normalizedPath;",
		"    }",
		"    var baseUrl = typeof document !== 'undefined' && document.baseURI",
		"      ? document.baseURI",
		"      : (typeof window !== 'undefined' && window.location ? window.location.href : '');",
		"    return baseUrl ? new URL(normalizedPath, baseUrl).href : normalizedPath;",
		"  } catch (_error) {",
		"    return String(rawPath);",
		"  }",
		"})();"
	].join(" ");
}
function createInitFragment$1(environmentVariable, publicPath, startupPrefetchMode) {
	return [
		`window.${environmentVariable} = window.${environmentVariable} || {};`,
		createNormalizedPublicPathAssignment(environmentVariable, publicPath),
		`if (!window.${environmentVariable}.startupPrefetchMode) window.${environmentVariable}.startupPrefetchMode = "${startupPrefetchMode}";`
	].join(" ");
}
//#endregion
//#region src/shared/hostPackageEntryMatch.ts
/**
* Match main product entry modules for host bootstrap injection (Vite + Webpack).
* Uses suffix matching so absolute node_modules ids ending with `{packagePath}/{appName}-esm.js`
* match the same way as Webpack `renderModuleContent` (endsWith), not exact relative paths.
*/
function normalizeHostModulePath(value) {
	return String(value || "").replace(/#.*$/s, "").replace(/\?.*$/s, "").replace(/\\/g, "/");
}
function getProductEntrySuffixes(packagePath, appName) {
	return [
		`${packagePath}/${appName}-esm.js`,
		`${packagePath}/${appName}.js`,
		`${packagePath.replace(/[\\/]/g, "_")}.js`
	].map(normalizeHostModulePath);
}
function shouldMatchProductPackageEntry(moduleId, packagePath, appName, optimizedDepFileName) {
	const normalized = normalizeHostModulePath(moduleId);
	if (!normalized) return false;
	if (getProductEntrySuffixes(packagePath, appName).some((suffix) => normalized === suffix || normalized.endsWith(`/${suffix}`))) return true;
	if (optimizedDepFileName) {
		const depName = normalizeHostModulePath(optimizedDepFileName);
		return normalized.includes("/.vite/deps/") && normalized.endsWith(`/${depName}`);
	}
	return false;
}
//#endregion
//#region src/shared/branding.ts
/**
* Чтение `process.env.REACT_APP_*` — как в основном приложении.
* На этапе сборки `build.ts` подставляет в `define` итоговые строки (см. `bundlerDefines()`).
*/
var BUNDLER_DEFAULT_PACKAGE_NAME = "useblocks";
var BUNDLER_DEFAULT_APP_NAME = "useblocks";
`${BUNDLER_DEFAULT_APP_NAME}`;
//#endregion
//#region src/vite/depsRuntimePaths.ts
/** Для тестов и плагина: один RegExp на процесс, без пересборки в hot-path. */
function createAppCoreOptimizedDepRe(appName) {
	return new RegExp(`^${appName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}-core\\.[a-f0-9]+\\.js$`);
}
function normalizeDepsPathname(value) {
	return cleanUrl(String(value || "")).replace(/\\/g, "/");
}
var STATIC_CORE_IN_DEPS_RE = /^static\/core\/[^/]+\.js$/;
/**
* Vite prebundles may rewrite runtime asset requests under `/.vite/deps/`.
* Maps request pathname → абсолютный путь файла в корне runtime-пакета.
*/
function getDepsRuntimeFilePath(pathname, packageRoot, appCoreOptimizedDepRe) {
	const normalizedPathname = normalizeDepsPathname(pathname);
	const markerIndex = normalizedPathname.indexOf("/.vite/deps/");
	if (markerIndex === -1) return null;
	const depsRelativePath = normalizedPathname.slice(markerIndex + 12);
	if (!depsRelativePath) return null;
	if (STATIC_CORE_IN_DEPS_RE.test(depsRelativePath)) return path.default.join(packageRoot, depsRelativePath);
	const segments = depsRelativePath.split("/").filter(Boolean);
	const base = segments.length ? segments[segments.length - 1] : "";
	return appCoreOptimizedDepRe.test(base) ? path.default.join(packageRoot, base) : null;
}
//#endregion
//#region src/vite/depsStaleDetector.ts
/**
* Детектор stale `.vite/deps` относительно установленной версии main package.
*
* Сценарий: integrator обновил `@<scope>/<main>` (через `npm link`, workspace,
* `file:` dependency или ручную правку байтов в `node_modules`). Lockfile hash
* мог не измениться, Vite optimizer не перепрбандлит — `.vite/deps` остаются с
* прежним содержимым main, плагин-автор видит «странные» ошибки (отсутствующие
* экспорты, старые APIs).
*
* Эта эвристика срабатывает в `configResolved` host plugin'а: если
* `<packageRoot>/package.json` новее `<.vite/deps>/_metadata.json` — выводится
* `console.warn` со подсказкой как инвалидировать кэш. Никаких side-effect'ов
* на FS — только diagnostic.
*
* Pure: возвращает результат-решение, caller рендерит warn в нужный канал.
*
* @module depsStaleDetector
*/
function safeStat(p, statSync) {
	try {
		return statSync(p);
	} catch {
		return null;
	}
}
function checkViteDepsStale(input) {
	const existsSync = input.existsSync ?? fs.default.existsSync;
	const statSync = input.statSync ?? ((p) => existsSync(p) ? fs.default.statSync(p) : null);
	const metadataPath = path.default.join(input.viteCacheDir, "deps", "_metadata.json");
	if (!existsSync(metadataPath)) return { status: "no-prebundle" };
	const metadataStat = safeStat(metadataPath, statSync);
	if (!metadataStat) return { status: "no-prebundle" };
	const freshnessPaths = [
		path.default.join(input.packageRoot, "package.json"),
		path.default.join(input.packageRoot, "runtime", "index.js"),
		path.default.join(input.packageRoot, "ui-kit", "index.js")
	];
	let newestPackageMtime;
	for (const candidatePath of freshnessPaths) {
		if (!existsSync(candidatePath)) continue;
		const stat = safeStat(candidatePath, statSync);
		if (!stat) continue;
		newestPackageMtime = newestPackageMtime === void 0 ? stat.mtimeMs : Math.max(newestPackageMtime, stat.mtimeMs);
	}
	if (newestPackageMtime === void 0) return { status: "no-package-mtime" };
	if (newestPackageMtime <= metadataStat.mtimeMs + 1e3) return {
		status: "fresh",
		packageMtime: newestPackageMtime,
		metadataMtime: metadataStat.mtimeMs
	};
	return {
		status: "stale",
		packageMtime: newestPackageMtime,
		metadataMtime: metadataStat.mtimeMs,
		warnMessage: [
			`[${input.pluginName}] Detected stale Vite prebundle: ${input.mainPackage}/package.json was modified after .vite/deps/_metadata.json was written.`,
			`This usually happens when ${input.mainPackage} was upgraded (npm link, workspace, manual edit) without lockfile change — Vite's optimizer may not invalidate automatically.`,
			`If you see "missing export", "undefined is not a function" or stale APIs, force a re-prebundle:`,
			`  • rm -rf node_modules/.vite   (recommended)`,
			`  • or restart vite with --force flag`
		].join("\n")
	};
}
//#endregion
//#region src/shared/reactDuplicateDetector.ts
/**
* Детектор дублированных runtime-копий React/antd в Vite-prebundle integrator'а.
*
* Симптом: на странице одновременно живут два набора React-чанков —
* наш singleton (`<main>/runtime/react`) и собственный prebundle Vite
* (`react`, `react-dom`, `react/jsx-runtime`). Любой компонент, который
* импортирует bare `react` (например, independent `@<scope>/ui-kit` с
* `peerDependencies.react`), линкуется ко второй копии. Provider в host
* и Consumer в plugin оказываются в разных React'ах →
* `Invalid hook call` / `useContext returned null`.
*
* Эта функция читает `.vite/deps/_metadata.json` integrator'а и выдаёт
* pure-decision: какие пары `<bare> ↔ <main>/runtime/<bare>` обнаружены.
* Никаких side-effects на FS — caller (host plugin) рендерит warn в нужный
* канал и/или throw'ит под env-флагом.
*
* @module reactDuplicateDetector
*/
/**
* Bare-имена пакетов, для которых дубликат с `<main>/runtime/<name>` критичен
* (нарушает singleton invariant и приводит к Invalid hook call / Provider/Consumer
* на разных React'ах). Источник истины — пакеты из `runtime-contract` группы
* `runtime-bundle` (react / react-dom / antd / @ant-design/icons и их subpath'ы).
*
* Жёстко перечислены, потому что host plugin рантаймно НЕ читает контракт
* (контракт замораживается в branding на этапе сборки bundler-plugins).
*/
var SINGLETON_BARE_NAMES = [
	"react",
	"react-dom",
	"react-dom/client",
	"react/jsx-runtime",
	"react/jsx-dev-runtime",
	"antd",
	"@ant-design/icons"
];
function safeRead(p, existsSync, readFileSync) {
	if (!existsSync(p)) return null;
	try {
		return JSON.parse(readFileSync(p, "utf-8"));
	} catch {
		return null;
	}
}
/**
* Возвращает `<mainPackage>/runtime/<bare>` (например, `@scope/main/runtime/react`).
* Учитывает subpath'ы вида `react/jsx-runtime` → `<main>/runtime/react/jsx-runtime`.
*/
function buildRuntimeSubpath(mainPackage, bare) {
	return `${mainPackage}/runtime/${bare}`;
}
function checkReactDuplicatePrebundle(input) {
	const existsSync = input.existsSync ?? fs.default.existsSync;
	const readFileSync = input.readFileSync ?? fs.default.readFileSync;
	const metadata = safeRead(path.default.join(input.viteCacheDir, "deps", "_metadata.json"), existsSync, readFileSync);
	if (!metadata || !metadata.optimized) return { status: "no-prebundle" };
	const optimized = metadata.optimized;
	if (Object.keys(optimized).filter((k) => k.startsWith(`${input.mainPackage}/runtime/`)).length === 0) return { status: "no-runtime-resolved" };
	const duplicates = [];
	for (const bare of SINGLETON_BARE_NAMES) {
		const bareEntry = optimized[bare];
		if (!bareEntry) continue;
		const runtimeSubpath = buildRuntimeSubpath(input.mainPackage, bare);
		const runtimeEntry = optimized[runtimeSubpath];
		if (!runtimeEntry) continue;
		duplicates.push({
			bare,
			bareSrc: String(bareEntry.src || bareEntry.file || "?"),
			runtimeSubpath,
			runtimeSrc: String(runtimeEntry.src || runtimeEntry.file || "?")
		});
	}
	if (duplicates.length === 0) return { status: "clean" };
	return {
		status: "duplicate",
		duplicates,
		warnMessage: renderDuplicateWarn(input.pluginName, input.mainPackage, duplicates)
	};
}
function renderDuplicateWarn(pluginName, mainPackage, duplicates) {
	const lines = [];
	lines.push(`[${pluginName}] Detected DUPLICATE React/antd copies in Vite prebundle (singleton invariant broken).`, `This causes "Invalid hook call" / "useContext returned null" when plugin code consumes a context whose Provider was set up against ${mainPackage}/runtime/* singleton (or vice versa).`, ``, `Found in .vite/deps/_metadata.json:`);
	for (const pair of duplicates) {
		lines.push(`  • ${pair.bare}`);
		lines.push(`      bare  → ${pair.bareSrc}`);
		lines.push(`      via   → ${pair.runtimeSubpath}`);
		lines.push(`      via   → ${pair.runtimeSrc}`);
	}
	lines.push(``, `Likely root cause: some node_modules dependency (e.g. independent @scope/ui-kit) declares peerDependencies.react`, `and is reachable from the integrator's release-host. Vite sees a bare \`import 'react'\` and prebundles it`, `independently of ${mainPackage}/runtime/react.`, ``, `Fix (release-host vite config of the integrator / CLI-generated plugin):`, `  1. Either alias bare ids to main subpath:`, `     resolve: { alias: { 'react': '${mainPackage}/runtime/react', 'react-dom': '${mainPackage}/runtime/react-dom', ... } }`, `  2. Or pre-bundle only via main and disable bare-id optimizer:`, `     optimizeDeps: { exclude: ['react', 'react-dom', 'react/jsx-runtime', 'antd'] }`, ``, `For full diagnostic run:  npx tsx build-tools/scripts/diagnose/diagnose-react-duplicates.ts --plugin-dir <path>`);
	return lines.join("\n");
}
//#endregion
//#region src/vite/reactDuplicateRuntimeCheck.ts
/**
* Env-флаг `BUNDLER_RUNTIME_STRICT=1` переводит defensive детекторы в throw-режим.
* CLI устанавливает его автоматически при локальной сборке плагина из нашего репо.
*/
var STRICT_ENV_FLAG = "BUNDLER_RUNTIME_STRICT";
function isStrictMode(envSource = process.env) {
	const raw = envSource[STRICT_ENV_FLAG];
	return raw === "1" || raw === "true";
}
function runReactDuplicateRuntimeCheck(opts, signals = {}) {
	const result = checkReactDuplicatePrebundle({
		viteCacheDir: opts.viteCacheDir,
		mainPackage: opts.mainPackage,
		pluginName: opts.pluginName,
		existsSync: opts.existsSync,
		readFileSync: opts.readFileSync
	});
	if (result.status !== "duplicate" || !result.warnMessage) return result.status;
	if (isStrictMode(signals.env)) {
		(signals.fail ?? ((message) => {
			throw new Error(message);
		}))(result.warnMessage);
		return "duplicate-throw";
	}
	(signals.warn ?? ((message) => console.warn(message)))(result.warnMessage);
	return "duplicate-warned";
}
//#endregion
//#region src/vite/index.ts
/**
* Package name and appName are injected at build time via `build.ts` (Vite `define` from `REACT_APP_*`).
*/
var ENVIRONMENT_VARIABLE = `__${BUNDLER_DEFAULT_APP_NAME}__`;
var PLUGIN_NAME = `${BUNDLER_DEFAULT_APP_NAME}-vite-plugin`;
var PACKAGE_ENTRY_NAME = `${BUNDLER_DEFAULT_APP_NAME}.js`;
var ESM_PACKAGE_ENTRY_NAME = `${BUNDLER_DEFAULT_APP_NAME}-esm.js`;
var APP_CORE_OPTIMIZED_DEP_RE = createAppCoreOptimizedDepRe(BUNDLER_DEFAULT_APP_NAME);
var DEFAULT_OUTPUT_FOLDER = `/${BUNDLER_DEFAULT_APP_NAME}`;
var DEFAULT_MODULES_PATH = "node_modules";
var DEFAULT_STARTUP_PREFETCH_MODE = "eager";
function outputFolderFsSegment(folder, appName) {
	return (folder != null && folder !== "" ? String(folder) : `/${appName}`).replace(/^\/+/, "") || appName;
}
var IGNORED_PATTERNS = [
	/.*\.npmignore/,
	/.*\.gitignore/,
	/.*\.md$/,
	/.*\.ts$/,
	/.*\.d\.ts$/,
	/.*\.json$/,
	/.*\.ico$/,
	/.*\.pot$/,
	/^.*(?<!iframe\..{1,})\.html$/,
	/vite\?.*$/,
	/webpack\?.*$/,
	/react\?.*$/,
	/robots.txt$/,
	/main\..*\.js$/,
	/.*\\sandbox-eblock.*$/,
	new RegExp(PACKAGE_ENTRY_NAME.replace(/\./g, "\\.") + "$"),
	new RegExp(ESM_PACKAGE_ENTRY_NAME.replace(/\./g, "\\.") + "$"),
	/\.js\.map$/
];
function createInitFragment(publicPath, startupPrefetchMode) {
	return createInitFragment$1(ENVIRONMENT_VARIABLE, publicPath, startupPrefetchMode);
}
function createBootstrapPrefix(publicPath, startupPrefetchMode) {
	return `${createInitFragment(publicPath, startupPrefetchMode)};\n`;
}
function prependBootstrap(code, publicPath, startupPrefetchMode) {
	return `${createBootstrapPrefix(publicPath, startupPrefetchMode)}${code}`;
}
function shouldPatchPackageEntry(id, optimizedFileName) {
	return shouldMatchProductPackageEntry(id, BUNDLER_DEFAULT_PACKAGE_NAME, BUNDLER_DEFAULT_APP_NAME, optimizedFileName || getFlattenedOptimizedDepFileName());
}
function getFlattenedOptimizedDepFileName() {
	return `${BUNDLER_DEFAULT_PACKAGE_NAME.replace(/[\\/]/g, "_")}.js`;
}
function readOptimizedDepFileName(depsMetadataPath) {
	if (!fs.default.existsSync(depsMetadataPath)) return getFlattenedOptimizedDepFileName();
	try {
		const metadata = JSON.parse(fs.default.readFileSync(depsMetadataPath, "utf-8"));
		const optimized = metadata && metadata.optimized;
		const depInfo = optimized && optimized["useblocks"];
		return depInfo && typeof depInfo.file === "string" ? depInfo.file : getFlattenedOptimizedDepFileName();
	} catch {
		return getFlattenedOptimizedDepFileName();
	}
}
var ViteServePlugin = (options) => {
	const rootPath = process.cwd();
	const mountSeg = outputFolderFsSegment(options.outputFolder, BUNDLER_DEFAULT_APP_NAME);
	const destPath = path.default.normalize(path.default.join(rootPath, mountSeg));
	const packageRoot = path.default.join(options.modulesPath || DEFAULT_MODULES_PATH, BUNDLER_DEFAULT_PACKAGE_NAME);
	const publicPath = `${String(options.outputFolder || DEFAULT_OUTPUT_FOLDER).replace(/\/$/, "")}/`;
	const startupPrefetchMode = options.startupPrefetchMode || DEFAULT_STARTUP_PREFETCH_MODE;
	let optimizedFacadeFile = getFlattenedOptimizedDepFileName();
	return {
		name: `${PLUGIN_NAME}-serve`,
		enforce: "pre",
		apply: "serve",
		configResolved(config) {
			optimizedFacadeFile = readOptimizedDepFileName(path.default.join(config.cacheDir, "deps", "_metadata.json"));
			/**
			* Эвристика: предупредить integrator'а если main package был обновлён
			* после prebundle Vite'а. Только diagnostic — никаких FS-side-effect.
			*/
			const staleCheck = checkViteDepsStale({
				packageRoot,
				viteCacheDir: config.cacheDir,
				pluginName: `${PLUGIN_NAME}-serve`,
				mainPackage: BUNDLER_DEFAULT_PACKAGE_NAME
			});
			if (staleCheck.status === "stale" && staleCheck.warnMessage) console.warn(staleCheck.warnMessage);
			/**
			* Defensive: детектор двух React'ов (singleton invariant).
			* См. `shared/reactDuplicateDetector.ts` и
			* `docs/build-architecture/RUNTIME_DELIVERY_CR.md` §12 «Defensive checks».
			*
			* Read-only — host plugin не патчит `optimizeDeps` (запрещено правилом
			* `bundler-host-plugin.mdc`); только сигналит.
			*/
			runReactDuplicateRuntimeCheck({
				viteCacheDir: config.cacheDir,
				mainPackage: BUNDLER_DEFAULT_PACKAGE_NAME,
				pluginName: `${PLUGIN_NAME}-serve`
			});
		},
		transform(code, id) {
			if (!shouldPatchPackageEntry(id, optimizedFacadeFile)) return code;
			return prependBootstrap(code, publicPath, startupPrefetchMode);
		},
		configureServer: (server) => {
			let metadataDebounceTimer = null;
			let metadataWatcher;
			const depsDir = path.default.join(server.config.cacheDir, "deps");
			const depsMetadataPath = path.default.join(depsDir, "_metadata.json");
			let metadataWatcherCoarse = false;
			function refreshOptimizedFacadeFromMetadata() {
				optimizedFacadeFile = readOptimizedDepFileName(depsMetadataPath);
			}
			function scheduleMetadataRefresh() {
				if (metadataDebounceTimer) clearTimeout(metadataDebounceTimer);
				metadataDebounceTimer = setTimeout(() => {
					metadataDebounceTimer = null;
					refreshOptimizedFacadeFromMetadata();
					if (metadataWatcherCoarse && fs.default.existsSync(depsMetadataPath)) tryAttachMetadataWatcher();
				}, 100);
			}
			function tryAttachMetadataWatcher() {
				metadataWatcher?.close();
				metadataWatcher = void 0;
				metadataWatcherCoarse = false;
				refreshOptimizedFacadeFromMetadata();
				try {
					if (fs.default.existsSync(depsMetadataPath)) {
						metadataWatcher = fs.default.watch(depsMetadataPath, { persistent: false }, scheduleMetadataRefresh);
						return;
					}
					if (fs.default.existsSync(depsDir)) {
						metadataWatcher = fs.default.watch(depsDir, { persistent: false }, scheduleMetadataRefresh);
						metadataWatcherCoarse = true;
						return;
					}
					metadataWatcher = fs.default.watch(server.config.cacheDir, { persistent: false }, scheduleMetadataRefresh);
					metadataWatcherCoarse = true;
				} catch {}
			}
			tryAttachMetadataWatcher();
			server.middlewares.use("/", async (req, res, next) => {
				async function sendContentByFilePath(filePath) {
					const handledPath = normalizePath(filePath);
					if (!fs.default.existsSync(handledPath)) {
						next();
						return;
					}
					if (!fs.default.statSync(handledPath).isFile()) {
						next();
						return;
					}
					const content = await fs.default.promises.readFile(handledPath);
					const filePathParts = filePath.split(".");
					const ext = filePathParts.length > 1 ? filePathParts[filePathParts.length - 1] : "";
					res.writeHead(200, { "Content-Type": getMimeTypeByExtension(ext) });
					res.end(content);
				}
				if (!req.url) {
					next();
					return;
				}
				const pathname = cleanUrl(req.url).replace(/^\/+/, "");
				if (!pathname) {
					next();
					return;
				}
				const depsRuntimeFilePath = getDepsRuntimeFilePath(pathname, packageRoot, APP_CORE_OPTIMIZED_DEP_RE);
				if (depsRuntimeFilePath) {
					if (fs.default.existsSync(depsRuntimeFilePath) && fs.default.statSync(depsRuntimeFilePath).isFile()) {
						const content = await fs.default.promises.readFile(depsRuntimeFilePath, "utf-8");
						res.writeHead(200, { "Content-Type": getMimeTypeByExtension("js") });
						res.end(content);
						return;
					}
				}
				if (shouldMatchProductPackageEntry(pathname, "useblocks", "useblocks", optimizedFacadeFile)) {
					const optimizedFilePath = path.default.join(server.config.cacheDir, "deps", optimizedFacadeFile);
					if (fs.default.existsSync(optimizedFilePath) && fs.default.statSync(optimizedFilePath).isFile()) {
						const content = await fs.default.promises.readFile(optimizedFilePath, "utf-8");
						res.writeHead(200, { "Content-Type": getMimeTypeByExtension("js") });
						res.end(prependBootstrap(content, publicPath, startupPrefetchMode));
						return;
					}
				}
				const absReqPath = path.default.normalize(path.default.join(rootPath, ...pathname.split("/").filter(Boolean)));
				const normDest = path.default.normalize(destPath);
				if (absReqPath === normDest || absReqPath.startsWith(normDest + path.default.sep)) {
					const rel = path.default.relative(normDest, absReqPath);
					if (rel.startsWith("..") || path.default.isAbsolute(rel)) {
						next();
						return;
					}
					const sourcePath = path.default.join(options.modulesPath || DEFAULT_MODULES_PATH, BUNDLER_DEFAULT_PACKAGE_NAME, rel);
					if (!IGNORED_PATTERNS.some((pattern) => pattern.test(sourcePath)) && fs.default.existsSync(sourcePath)) {
						await sendContentByFilePath(sourcePath);
						return;
					}
				}
				next();
			});
			return () => {
				if (metadataDebounceTimer) clearTimeout(metadataDebounceTimer);
				metadataWatcher?.close();
			};
		}
	};
};
var ViteBuildPlugin = (options) => {
	const publicPath = options.publicPath || "";
	const sourcePath = path.default.join(options.modulesPath || DEFAULT_MODULES_PATH, BUNDLER_DEFAULT_PACKAGE_NAME);
	let resolvedConfig;
	const normalizedPublicPath = `${String(path.default.posix.join(publicPath, options.outputFolder || DEFAULT_OUTPUT_FOLDER)).replace(/\/$/, "")}/`;
	const startupPrefetchMode = options.startupPrefetchMode || DEFAULT_STARTUP_PREFETCH_MODE;
	return {
		name: `${PLUGIN_NAME}-build`,
		enforce: "pre",
		apply: "build",
		transform(code, id) {
			if (!shouldPatchPackageEntry(id)) return code;
			return prependBootstrap(code, normalizedPublicPath, startupPrefetchMode);
		},
		configResolved(config) {
			resolvedConfig = config;
		},
		async closeBundle() {
			if (!resolvedConfig) return;
			const outDir = path.default.join(resolvedConfig.root, resolvedConfig.build.outDir);
			const outSeg = outputFolderFsSegment(options.outputFolder, BUNDLER_DEFAULT_APP_NAME);
			const destPath = path.default.join(outDir, outSeg);
			if (!fs.default.existsSync(sourcePath)) return;
			if ((await fs.default.promises.stat(sourcePath)).isDirectory()) await copyFolder(sourcePath, destPath, (sp) => {
				return !IGNORED_PATTERNS.some((pattern) => pattern.test(sp));
			});
		}
	};
};
/**
* Vite plugin for host applications.
* Copies static assets (images, iframe, fonts, monaco workers) to the build output
* and injects publicPath into the entry module so the editor can locate them at runtime.
* The thin facade entry is still handled by the consumer bundler, while
* browser-loaded core assets are copied to the host output and served from publicPath.
*
* For plugin development (externals + alias), use a separate plugin
* from the `vite/pluginDev` subpath.
*/
var VitePlugin = (options = {}) => {
	return [ViteServePlugin(options), ViteBuildPlugin(options)];
};
//#endregion
exports.STRICT_ENV_FLAG = STRICT_ENV_FLAG;
exports.createAppCoreOptimizedDepRe = createAppCoreOptimizedDepRe;
exports.default = VitePlugin;
exports.getDepsRuntimeFilePath = getDepsRuntimeFilePath;
exports.isStrictMode = isStrictMode;
exports.runReactDuplicateRuntimeCheck = runReactDuplicateRuntimeCheck;
