vinext 0.0.39 → 0.0.41
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/build/standalone.js +7 -0
- package/dist/build/standalone.js.map +1 -1
- package/dist/check.js +2 -2
- package/dist/check.js.map +1 -1
- package/dist/cli.js.map +1 -1
- package/dist/entries/app-rsc-entry.d.ts +2 -1
- package/dist/entries/app-rsc-entry.js +185 -264
- package/dist/entries/app-rsc-entry.js.map +1 -1
- package/dist/entries/pages-server-entry.js +205 -199
- package/dist/entries/pages-server-entry.js.map +1 -1
- package/dist/index.d.ts +32 -1
- package/dist/index.js +81 -6
- package/dist/index.js.map +1 -1
- package/dist/init.d.ts +1 -1
- package/dist/init.js +2 -2
- package/dist/init.js.map +1 -1
- package/dist/plugins/fonts.js +1 -0
- package/dist/plugins/fonts.js.map +1 -1
- package/dist/plugins/server-externals-manifest.d.ts +11 -1
- package/dist/plugins/server-externals-manifest.js +10 -3
- package/dist/plugins/server-externals-manifest.js.map +1 -1
- package/dist/routing/app-router.d.ts +10 -2
- package/dist/routing/app-router.js +37 -22
- package/dist/routing/app-router.js.map +1 -1
- package/dist/server/app-page-boundary-render.d.ts +1 -0
- package/dist/server/app-page-boundary-render.js +1 -0
- package/dist/server/app-page-boundary-render.js.map +1 -1
- package/dist/server/app-page-render.d.ts +1 -0
- package/dist/server/app-page-render.js +2 -0
- package/dist/server/app-page-render.js.map +1 -1
- package/dist/server/app-page-response.d.ts +4 -1
- package/dist/server/app-page-response.js +14 -8
- package/dist/server/app-page-response.js.map +1 -1
- package/dist/server/app-page-route-wiring.d.ts +79 -0
- package/dist/server/app-page-route-wiring.js +167 -0
- package/dist/server/app-page-route-wiring.js.map +1 -0
- package/dist/server/app-page-stream.d.ts +4 -1
- package/dist/server/app-page-stream.js +5 -1
- package/dist/server/app-page-stream.js.map +1 -1
- package/dist/server/app-route-handler-response.js +6 -2
- package/dist/server/app-route-handler-response.js.map +1 -1
- package/dist/server/app-router-entry.d.ts +6 -1
- package/dist/server/app-router-entry.js +9 -2
- package/dist/server/app-router-entry.js.map +1 -1
- package/dist/server/app-ssr-entry.d.ts +3 -1
- package/dist/server/app-ssr-entry.js +17 -17
- package/dist/server/app-ssr-entry.js.map +1 -1
- package/dist/server/app-ssr-stream.d.ts +1 -1
- package/dist/server/app-ssr-stream.js +4 -4
- package/dist/server/app-ssr-stream.js.map +1 -1
- package/dist/server/csp.d.ts +12 -0
- package/dist/server/csp.js +46 -0
- package/dist/server/csp.js.map +1 -0
- package/dist/server/dev-server.js +20 -14
- package/dist/server/dev-server.js.map +1 -1
- package/dist/server/html.d.ts +4 -1
- package/dist/server/html.js +11 -1
- package/dist/server/html.js.map +1 -1
- package/dist/server/middleware-response-headers.d.ts +12 -0
- package/dist/server/middleware-response-headers.js +23 -0
- package/dist/server/middleware-response-headers.js.map +1 -0
- package/dist/server/pages-page-data.d.ts +1 -0
- package/dist/server/pages-page-data.js +2 -2
- package/dist/server/pages-page-data.js.map +1 -1
- package/dist/server/pages-page-response.d.ts +2 -1
- package/dist/server/pages-page-response.js +16 -14
- package/dist/server/pages-page-response.js.map +1 -1
- package/dist/server/prod-server.d.ts +1 -1
- package/dist/server/prod-server.js +41 -14
- package/dist/server/prod-server.js.map +1 -1
- package/dist/server/request-pipeline.d.ts +14 -1
- package/dist/server/request-pipeline.js +55 -1
- package/dist/server/request-pipeline.js.map +1 -1
- package/dist/server/worker-utils.d.ts +4 -1
- package/dist/server/worker-utils.js +31 -1
- package/dist/server/worker-utils.js.map +1 -1
- package/dist/shims/error-boundary.d.ts +14 -5
- package/dist/shims/error-boundary.js +23 -3
- package/dist/shims/error-boundary.js.map +1 -1
- package/dist/shims/head.js.map +1 -1
- package/dist/shims/navigation.d.ts +16 -1
- package/dist/shims/navigation.js +18 -3
- package/dist/shims/navigation.js.map +1 -1
- package/dist/shims/router.js +127 -38
- package/dist/shims/router.js.map +1 -1
- package/dist/shims/script-nonce-context.d.ts +12 -0
- package/dist/shims/script-nonce-context.js +17 -0
- package/dist/shims/script-nonce-context.js.map +1 -0
- package/dist/shims/script.js +41 -10
- package/dist/shims/script.js.map +1 -1
- package/dist/shims/server.d.ts +17 -4
- package/dist/shims/server.js +97 -74
- package/dist/shims/server.js.map +1 -1
- package/dist/shims/slot.d.ts +28 -0
- package/dist/shims/slot.js +49 -0
- package/dist/shims/slot.js.map +1 -0
- package/dist/shims/url-safety.js +25 -4
- package/dist/shims/url-safety.js.map +1 -1
- package/package.json +7 -8
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["generateServerEntry","_generateServerEntry","generateClientEntry","_generateClientEntry","normalizePath"],"sources":["../src/index.ts"],"sourcesContent":["import type { Plugin, PluginOption, UserConfig, ViteDevServer } from \"vite\";\nimport { loadEnv, parseAst } from \"vite\";\nimport {\n pagesRouter,\n apiRouter,\n invalidateRouteCache,\n matchRoute,\n} from \"./routing/pages-router.js\";\nimport { generateServerEntry as _generateServerEntry } from \"./entries/pages-server-entry.js\";\nimport { generateClientEntry as _generateClientEntry } from \"./entries/pages-client-entry.js\";\nimport { appRouter, invalidateAppRouteCache } from \"./routing/app-router.js\";\nimport type { NitroRouteRuleConfig } from \"./build/nitro-route-rules.js\";\nimport { createValidFileMatcher } from \"./routing/file-matcher.js\";\nimport { createSSRHandler } from \"./server/dev-server.js\";\nimport { handleApiRoute } from \"./server/api-handler.js\";\nimport { createDirectRunner } from \"./server/dev-module-runner.js\";\nimport { generateRscEntry } from \"./entries/app-rsc-entry.js\";\nimport { generateSsrEntry } from \"./entries/app-ssr-entry.js\";\nimport { generateBrowserEntry } from \"./entries/app-browser-entry.js\";\nimport { normalizePathnameForRouteMatchStrict } from \"./routing/utils.js\";\nimport {\n findNextConfigPath,\n loadNextConfig,\n resolveNextConfigInput,\n resolveNextConfig,\n type NextConfig,\n type NextConfigInput,\n type ResolvedNextConfig,\n type NextRedirect,\n type NextRewrite,\n type NextHeader,\n} from \"./config/next-config.js\";\n\nimport { findMiddlewareFile, runMiddleware } from \"./server/middleware.js\";\nimport { logRequest, now } from \"./server/request-log.js\";\nimport { normalizePath } from \"./server/normalize-path.js\";\nimport {\n findInstrumentationClientFile,\n findInstrumentationFile,\n runInstrumentation,\n} from \"./server/instrumentation.js\";\nimport { PHASE_PRODUCTION_BUILD, PHASE_DEVELOPMENT_SERVER } from \"./shims/constants.js\";\nimport { precompressAssets } from \"./build/precompress.js\";\nimport { validateDevRequest } from \"./server/dev-origin-check.js\";\nimport {\n isExternalUrl,\n proxyExternalRequest,\n matchHeaders,\n matchRedirect,\n matchRewrite,\n requestContextFromRequest,\n sanitizeDestination,\n type RequestContext,\n} from \"./config/config-matchers.js\";\nimport { scanMetadataFiles } from \"./server/metadata-routes.js\";\nimport { buildRequestHeadersFromMiddlewareResponse } from \"./server/middleware-request-headers.js\";\nimport { detectPackageManager } from \"./utils/project.js\";\nimport {\n manifestFileWithBase,\n manifestFilesWithBase,\n normalizeManifestFile,\n} from \"./utils/manifest-paths.js\";\nimport { hasBasePath } from \"./utils/base-path.js\";\nimport { asyncHooksStubPlugin } from \"./plugins/async-hooks-stub.js\";\nimport { clientReferenceDedupPlugin } from \"./plugins/client-reference-dedup.js\";\nimport { createInstrumentationClientTransformPlugin } from \"./plugins/instrumentation-client.js\";\nimport { createOptimizeImportsPlugin } from \"./plugins/optimize-imports.js\";\nimport { fixUseServerClosureCollisionPlugin } from \"./plugins/fix-use-server-closure-collision.js\";\nimport { createOgInlineFetchAssetsPlugin, ogAssetsPlugin } from \"./plugins/og-assets.js\";\nimport { createServerExternalsManifestPlugin } from \"./plugins/server-externals-manifest.js\";\nimport {\n VIRTUAL_GOOGLE_FONTS,\n RESOLVED_VIRTUAL_GOOGLE_FONTS,\n parseStaticObjectLiteral,\n generateGoogleFontsVirtualModule,\n createGoogleFontsPlugin,\n createLocalFontsPlugin,\n _findBalancedObject,\n _findCallEnd,\n} from \"./plugins/fonts.js\";\nimport { hasWranglerConfig, formatMissingCloudflarePluginError } from \"./deploy.js\";\nimport { computeLazyChunks } from \"./utils/lazy-chunks.js\";\nimport tsconfigPaths from \"vite-tsconfig-paths\";\nimport type { Options as VitePluginReactOptions } from \"@vitejs/plugin-react\";\nimport MagicString from \"magic-string\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { createRequire } from \"node:module\";\nimport fs from \"node:fs\";\nimport { randomBytes } from \"node:crypto\";\nimport commonjs from \"vite-plugin-commonjs\";\n\ntype ASTNode = ReturnType<typeof parseAst>[\"body\"][number][\"parent\"];\n\nconst __dirname = import.meta.dirname;\ntype VitePluginReactModule = typeof import(\"@vitejs/plugin-react\");\n\nfunction resolveOptionalDependency(projectRoot: string, specifier: string): string | null {\n try {\n const projectRequire = createRequire(path.join(projectRoot, \"package.json\"));\n return projectRequire.resolve(specifier);\n } catch {}\n\n try {\n const selfRequire = createRequire(import.meta.url);\n return selfRequire.resolve(specifier);\n } catch {}\n\n return null;\n}\n\nfunction resolveShimModulePath(shimsDir: string, moduleName: string): string {\n // Source checkouts only ship TypeScript shims, while built packages only ship\n // JavaScript. Check .ts first to avoid an extra stat in development.\n const candidates = [\".ts\", \".js\"];\n for (const ext of candidates) {\n const candidate = path.join(shimsDir, `${moduleName}${ext}`);\n if (fs.existsSync(candidate)) {\n return candidate;\n }\n }\n return path.join(shimsDir, `${moduleName}.js`);\n}\n\nfunction toRelativeFileEntry(root: string, absPath: string): string {\n return path.relative(root, absPath).split(path.sep).join(\"/\");\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return !!value && typeof value === \"object\" && !Array.isArray(value);\n}\n\nconst TSCONFIG_FILES = [\"tsconfig.json\", \"jsconfig.json\"];\n\nfunction resolveTsconfigPathCandidate(candidate: string): string | null {\n const candidates = candidate.endsWith(\".json\")\n ? [candidate]\n : [candidate, `${candidate}.json`, path.join(candidate, \"tsconfig.json\")];\n\n for (const item of candidates) {\n if (fs.existsSync(item) && fs.statSync(item).isFile()) {\n return item;\n }\n }\n\n return null;\n}\n\nfunction resolveTsconfigExtends(configPath: string, specifier: string): string | null {\n const fromDir = path.dirname(configPath);\n if (specifier.startsWith(\".\") || specifier.startsWith(\"/\") || specifier.startsWith(\"\\\\\")) {\n return resolveTsconfigPathCandidate(path.resolve(fromDir, specifier));\n }\n\n const requireFromConfig = createRequire(configPath);\n const candidates = [specifier, `${specifier}.json`, path.join(specifier, \"tsconfig.json\")];\n\n for (const item of candidates) {\n try {\n return requireFromConfig.resolve(item);\n } catch {}\n }\n\n return null;\n}\n\nfunction materializeTsconfigPathAliases(\n pathsConfig: Record<string, unknown>,\n baseUrl: string,\n projectRoot: string,\n): Record<string, string> {\n const aliases: Record<string, string> = {};\n\n for (const [find, rawTargets] of Object.entries(pathsConfig)) {\n const target = Array.isArray(rawTargets)\n ? rawTargets.find((value): value is string => typeof value === \"string\")\n : typeof rawTargets === \"string\"\n ? rawTargets\n : null;\n if (!target) continue;\n\n if (find.includes(\"*\") || target.includes(\"*\")) {\n if (!find.endsWith(\"/*\") || !target.endsWith(\"/*\")) continue;\n if (find.indexOf(\"*\") !== find.length - 1 || target.indexOf(\"*\") !== target.length - 1) {\n continue;\n }\n\n const aliasKey = find.slice(0, -2);\n const targetDir = target.slice(0, -2);\n if (!aliasKey || !targetDir) continue;\n\n aliases[aliasKey] = toViteAliasReplacement(path.resolve(baseUrl, targetDir), projectRoot);\n continue;\n }\n\n aliases[find] = toViteAliasReplacement(path.resolve(baseUrl, target), projectRoot);\n }\n\n return aliases;\n}\n\nfunction toViteAliasReplacement(absolutePath: string, projectRoot: string): string {\n const normalizedPath = absolutePath.replace(/\\\\/g, \"/\");\n const rootCandidates = new Set<string>([projectRoot]);\n const realRoot = tryRealpathSync(projectRoot);\n if (realRoot) rootCandidates.add(realRoot);\n\n const pathCandidates = new Set<string>([absolutePath]);\n const realPath = tryRealpathSync(absolutePath);\n if (realPath) pathCandidates.add(realPath);\n\n for (const rootCandidate of rootCandidates) {\n for (const pathCandidate of pathCandidates) {\n if (pathCandidate === rootCandidate) {\n return normalizedPath;\n }\n const relativeId = relativeWithinRoot(rootCandidate, pathCandidate);\n if (relativeId) return \"/\" + relativeId;\n }\n }\n\n return normalizedPath;\n}\n\nfunction loadTsconfigPathAliases(\n configPath: string,\n projectRoot: string,\n seen = new Set<string>(),\n): Record<string, string> {\n const normalizedPath = tryRealpathSync(configPath) ?? configPath;\n if (seen.has(normalizedPath)) return {};\n seen.add(normalizedPath);\n\n let parsed: Record<string, unknown> | null = null;\n try {\n parsed = parseStaticObjectLiteral(fs.readFileSync(normalizedPath, \"utf-8\"));\n } catch {\n return {};\n }\n if (!parsed) return {};\n\n let aliases: Record<string, string> = {};\n if (typeof parsed.extends === \"string\") {\n const extendedPath = resolveTsconfigExtends(normalizedPath, parsed.extends);\n if (extendedPath) {\n aliases = loadTsconfigPathAliases(extendedPath, projectRoot, seen);\n }\n }\n\n const compilerOptions = isRecord(parsed.compilerOptions) ? parsed.compilerOptions : null;\n const pathsConfig =\n compilerOptions && isRecord(compilerOptions.paths) ? compilerOptions.paths : null;\n if (!pathsConfig) return aliases;\n\n const baseUrl =\n compilerOptions && typeof compilerOptions.baseUrl === \"string\" ? compilerOptions.baseUrl : \".\";\n const resolvedBaseUrl = path.resolve(path.dirname(normalizedPath), baseUrl);\n\n return {\n ...aliases,\n ...materializeTsconfigPathAliases(pathsConfig, resolvedBaseUrl, projectRoot),\n };\n}\n\n/**\n * Detect Vite major version at runtime by resolving from cwd.\n * The plugin may be installed in a workspace root with Vite 7 but used\n * by a project that has Vite 8 — so we resolve from cwd, not from\n * the plugin's own location.\n */\nfunction getViteMajorVersion(): number {\n try {\n const require = createRequire(path.join(process.cwd(), \"package.json\"));\n const vitePkg = require(\"vite/package.json\");\n\n const viteMajor = parseInt(vitePkg?.version, 10);\n if (vitePkg?.name === \"vite\" && Number.isFinite(viteMajor)) {\n return viteMajor;\n }\n\n const bundledViteMajor = parseInt(vitePkg?.bundledVersions?.vite, 10);\n if (Number.isFinite(bundledViteMajor)) {\n return bundledViteMajor;\n }\n\n // npm aliases like `vite: npm:@voidzero-dev/vite-plus-core@...` expose the\n // aliased package.json, whose own version is not Vite's version.\n console.warn(\n `[vinext] Could not determine Vite major version from ${vitePkg?.name ?? \"vite/package.json\"}; assuming Vite 7`,\n );\n return 7;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n console.warn(`[vinext] Failed to resolve vite/package.json (${message}); assuming Vite 7`);\n return 7;\n }\n}\n\ntype UserResolveConfigWithTsconfigPaths = NonNullable<UserConfig[\"resolve\"]> & {\n tsconfigPaths?: boolean;\n};\n\n/**\n * PostCSS config file names to search for, in priority order.\n * Matches the same search order as postcss-load-config / lilconfig.\n */\nconst POSTCSS_CONFIG_FILES = [\n \"postcss.config.js\",\n \"postcss.config.cjs\",\n \"postcss.config.mjs\",\n \"postcss.config.ts\",\n \"postcss.config.cts\",\n \"postcss.config.mts\",\n \".postcssrc\",\n \".postcssrc.js\",\n \".postcssrc.cjs\",\n \".postcssrc.mjs\",\n \".postcssrc.ts\",\n \".postcssrc.cts\",\n \".postcssrc.mts\",\n \".postcssrc.json\",\n \".postcssrc.yaml\",\n \".postcssrc.yml\",\n];\n\n/**\n * Module-level cache for resolvePostcssStringPlugins — avoids re-scanning per Vite environment.\n * Stores the Promise itself so concurrent calls (RSC/SSR/Client config() hooks firing in\n * parallel) all await the same in-flight scan rather than each starting their own.\n */\nconst _postcssCache = new Map<string, Promise<{ plugins: unknown[] } | undefined>>();\n// Cache materialized tsconfig/jsconfig aliases so Vite's glob and dynamic-import\n// transforms can see them via resolve.alias without re-reading config files per env.\nconst _tsconfigAliasCache = new Map<string, Record<string, string>>();\n\nfunction resolveTsconfigAliases(projectRoot: string): Record<string, string> {\n if (_tsconfigAliasCache.has(projectRoot)) {\n return _tsconfigAliasCache.get(projectRoot)!;\n }\n\n let aliases: Record<string, string> = {};\n for (const name of TSCONFIG_FILES) {\n const candidate = path.join(projectRoot, name);\n if (!fs.existsSync(candidate)) continue;\n aliases = loadTsconfigPathAliases(candidate, projectRoot);\n break;\n }\n\n _tsconfigAliasCache.set(projectRoot, aliases);\n return aliases;\n}\n\n/**\n * Resolve PostCSS string plugin names in a project's PostCSS config.\n *\n * Next.js (via postcss-load-config) resolves string plugin names in the\n * object form `{ plugins: { \"pkg-name\": opts } }` but NOT in the array form\n * `{ plugins: [\"pkg-name\"] }`. Since many Next.js projects use the array\n * form (particularly with Tailwind CSS v4), we detect this case and resolve\n * the string names to actual plugin functions so Vite can use them.\n *\n * Returns the resolved PostCSS config object to inject into Vite's\n * `css.postcss`, or `undefined` if no resolution is needed.\n */\nfunction resolvePostcssStringPlugins(\n projectRoot: string,\n): Promise<{ plugins: unknown[] } | undefined> {\n if (_postcssCache.has(projectRoot)) return _postcssCache.get(projectRoot)!;\n\n const promise = _resolvePostcssStringPluginsUncached(projectRoot);\n _postcssCache.set(projectRoot, promise);\n return promise;\n}\n\nasync function _resolvePostcssStringPluginsUncached(\n projectRoot: string,\n): Promise<{ plugins: unknown[] } | undefined> {\n // Find the PostCSS config file\n let configPath: string | null = null;\n for (const name of POSTCSS_CONFIG_FILES) {\n const candidate = path.join(projectRoot, name);\n if (fs.existsSync(candidate)) {\n configPath = candidate;\n break;\n }\n }\n if (!configPath) {\n return undefined;\n }\n\n // Load the config file\n // oxlint-disable-next-line typescript/no-explicit-any\n let config: any;\n try {\n if (\n configPath.endsWith(\".json\") ||\n configPath.endsWith(\".yaml\") ||\n configPath.endsWith(\".yml\")\n ) {\n // JSON/YAML configs use object form — postcss-load-config handles these fine\n return undefined;\n }\n // For .postcssrc without extension, check if it's JSON\n if (configPath.endsWith(\".postcssrc\")) {\n const content = fs.readFileSync(configPath, \"utf-8\").trim();\n if (content.startsWith(\"{\")) {\n // JSON format — postcss-load-config handles object form\n return undefined;\n }\n }\n const mod = await import(pathToFileURL(configPath).href);\n config = mod.default ?? mod;\n } catch {\n // If we can't load the config, let Vite/postcss-load-config handle it\n return undefined;\n }\n\n // Only process array-form plugins that contain string entries\n // (either bare strings or tuple form [\"plugin-name\", { options }])\n if (!config || !Array.isArray(config.plugins)) {\n return undefined;\n }\n const hasStringPlugins = config.plugins.some(\n (p: unknown) => typeof p === \"string\" || (Array.isArray(p) && typeof p[0] === \"string\"),\n );\n if (!hasStringPlugins) {\n return undefined;\n }\n\n // Resolve string plugin names to actual plugin functions\n const req = createRequire(path.join(projectRoot, \"package.json\"));\n const resolved = await Promise.all(\n config.plugins.filter(Boolean).map(async (plugin: unknown) => {\n if (typeof plugin === \"string\") {\n const resolved = req.resolve(plugin);\n const mod = await import(pathToFileURL(resolved).href);\n const fn = mod.default ?? mod;\n // If the export is a function, call it to get the plugin instance\n return typeof fn === \"function\" ? fn() : fn;\n }\n // Array tuple form: [\"plugin-name\", { options }]\n if (Array.isArray(plugin) && typeof plugin[0] === \"string\") {\n const [name, options] = plugin;\n const resolved = req.resolve(name);\n const mod = await import(pathToFileURL(resolved).href);\n const fn = mod.default ?? mod;\n return typeof fn === \"function\" ? fn(options) : fn;\n }\n // Already a function or plugin object — pass through\n return plugin;\n }),\n );\n\n return { plugins: resolved };\n}\n\n// Virtual module IDs for Pages Router production build\nconst VIRTUAL_SERVER_ENTRY = \"virtual:vinext-server-entry\";\nconst RESOLVED_SERVER_ENTRY = \"\\0\" + VIRTUAL_SERVER_ENTRY;\nconst VIRTUAL_CLIENT_ENTRY = \"virtual:vinext-client-entry\";\nconst RESOLVED_CLIENT_ENTRY = \"\\0\" + VIRTUAL_CLIENT_ENTRY;\n\n// Virtual module IDs for App Router entries\nconst VIRTUAL_RSC_ENTRY = \"virtual:vinext-rsc-entry\";\nconst RESOLVED_RSC_ENTRY = \"\\0\" + VIRTUAL_RSC_ENTRY;\nconst VIRTUAL_APP_SSR_ENTRY = \"virtual:vinext-app-ssr-entry\";\nconst RESOLVED_APP_SSR_ENTRY = \"\\0\" + VIRTUAL_APP_SSR_ENTRY;\nconst VIRTUAL_APP_BROWSER_ENTRY = \"virtual:vinext-app-browser-entry\";\nconst RESOLVED_APP_BROWSER_ENTRY = \"\\0\" + VIRTUAL_APP_BROWSER_ENTRY;\n/** Image file extensions handled by the vinext:image-imports plugin.\n * Shared between the Rolldown hook filter and the transform handler regex. */\nconst IMAGE_EXTS = \"png|jpe?g|gif|webp|avif|svg|ico|bmp|tiff?\";\n\n/**\n * Extract the npm package name from a module ID (file path).\n * Returns null if not in node_modules.\n *\n * Handles scoped packages (@org/pkg) and pnpm-style paths\n * (node_modules/.pnpm/pkg@ver/node_modules/pkg).\n */\nfunction getPackageName(id: string): string | null {\n const nmIdx = id.lastIndexOf(\"node_modules/\");\n if (nmIdx === -1) return null;\n const rest = id.slice(nmIdx + \"node_modules/\".length);\n if (rest.startsWith(\"@\")) {\n // Scoped package: @org/pkg\n const parts = rest.split(\"/\");\n return parts.length >= 2 ? parts[0] + \"/\" + parts[1] : null;\n }\n return rest.split(\"/\")[0] || null;\n}\n\n/** Absolute path to vinext's shims directory, used by clientManualChunks. */\nconst _shimsDir = path.resolve(__dirname, \"shims\") + \"/\";\nconst _fontGoogleShimPath = resolveShimModulePath(_shimsDir, \"font-google\");\n\n/**\n * manualChunks function for client builds.\n *\n * Splits the client bundle into:\n * - \"framework\" — React, ReactDOM, and scheduler (loaded on every page)\n * - \"vinext\" — vinext shims (router, head, link, etc.)\n *\n * All other vendor code is left to Rollup's default chunk-splitting\n * algorithm. Rollup automatically deduplicates shared modules into\n * common chunks based on the import graph — no manual intervention\n * needed.\n *\n * Why not split every npm package into its own chunk?\n * - Per-package splitting (`vendor-X`) creates 50-200+ chunks for a\n * typical app, far exceeding the ~25-request sweet spot for HTTP/2.\n * - gzip/brotli compress small files poorly — each file restarts with\n * an empty dictionary, losing ~5-15% total compressed size vs fewer\n * larger chunks (Khan Academy measured +2.5% wire size with 10x\n * more files containing less raw code).\n * - ES module evaluation has per-module overhead that compounds on\n * mobile devices.\n * - No major Vite-based framework (Remix, SvelteKit, Astro, TanStack)\n * uses per-package splitting. Next.js only isolates packages >160KB.\n * - Rollup's graph-based splitting already handles the common case\n * well: shared dependencies between routes get their own chunks,\n * and route-specific code stays in route chunks.\n */\nfunction clientManualChunks(id: string): string | undefined {\n // React framework — always loaded, shared across all pages.\n // Isolating React into its own chunk is the single highest-value\n // split: it's ~130KB compressed, loaded on every page, and its\n // content hash rarely changes between deploys.\n if (id.includes(\"node_modules\")) {\n const pkg = getPackageName(id);\n if (!pkg) return undefined;\n if (pkg === \"react\" || pkg === \"react-dom\" || pkg === \"scheduler\") {\n return \"framework\";\n }\n // Let Rollup handle all other vendor code via its default\n // graph-based splitting. This produces a reasonable number of\n // shared chunks (typically 5-15) based on actual import patterns,\n // with good compression efficiency.\n return undefined;\n }\n\n // vinext shims — small runtime, shared across all pages.\n // Use the absolute shims directory path to avoid matching user files\n // that happen to have \"/shims/\" in their path.\n if (id.startsWith(_shimsDir)) {\n return \"vinext\";\n }\n\n return undefined;\n}\n\n/**\n * Rollup output config with manualChunks for client code-splitting.\n * Used by both CLI builds and multi-environment builds.\n *\n * experimentalMinChunkSize merges tiny shared chunks (< 10KB) back into\n * their importers. This reduces HTTP request count and improves gzip\n * compression efficiency — small files restart the compression dictionary,\n * adding ~5-15% wire overhead vs fewer larger chunks.\n */\nconst clientOutputConfig = {\n manualChunks: clientManualChunks,\n experimentalMinChunkSize: 10_000,\n};\n\nconst clientCodeSplittingConfig = {\n minSize: 10_000,\n groups: [\n {\n name(moduleId: string) {\n return clientManualChunks(moduleId) ?? null;\n },\n },\n ],\n};\n\n/**\n * Rollup treeshake configuration for production client builds.\n *\n * Uses the 'recommended' preset as a safe base, then overrides\n * moduleSideEffects to strip unused re-exports from npm packages.\n *\n * The 'no-external' value for moduleSideEffects means:\n * - Local project modules: preserve side effects (CSS imports, polyfills)\n * - node_modules packages: treat as side-effect-free unless exports are used\n *\n * This is the single highest-impact optimization for large barrel-exporting\n * libraries like mermaid, @mui/material, lucide-react, etc. These libraries\n * re-export hundreds of sub-modules through barrel files. Without this,\n * Rollup preserves every sub-module even when only a few exports are consumed.\n *\n * Why 'no-external' instead of false (global side-effect-free)?\n * - User code may rely on import-time side effects (e.g., `import './global.css'`)\n * - 'no-external' is safe for app code while still enabling aggressive DCE for deps\n *\n * Why not the 'smallest' preset?\n * - 'smallest' also sets propertyReadSideEffects: false and\n * tryCatchDeoptimization: false, which can break specific libraries\n * that rely on property access side effects or try/catch for feature detection\n * - 'recommended' + 'no-external' gives most of the benefit with less risk\n */\nconst clientTreeshakeConfig = {\n preset: \"recommended\" as const,\n moduleSideEffects: \"no-external\" as const,\n};\n\ntype VinextBuildConfig = NonNullable<UserConfig[\"build\"]>;\ntype VinextBuildBundlerOptions = NonNullable<VinextBuildConfig[\"rolldownOptions\"]>;\ntype VinextBuildConfigWithLegacy = VinextBuildConfig & {\n rollupOptions?: VinextBuildBundlerOptions;\n};\n\nfunction getBuildBundlerOptions(\n build: UserConfig[\"build\"] | undefined,\n): VinextBuildBundlerOptions | undefined {\n const buildConfig = build as VinextBuildConfigWithLegacy | undefined;\n return buildConfig?.rolldownOptions ?? buildConfig?.rollupOptions;\n}\n\nfunction withBuildBundlerOptions(\n viteMajorVersion: number,\n bundlerOptions: VinextBuildBundlerOptions,\n): Partial<VinextBuildConfigWithLegacy> {\n return viteMajorVersion >= 8\n ? { rolldownOptions: bundlerOptions }\n : { rollupOptions: bundlerOptions };\n}\n\nfunction getClientOutputConfigForVite(viteMajorVersion: number) {\n return viteMajorVersion >= 8\n ? {\n codeSplitting: clientCodeSplittingConfig,\n }\n : clientOutputConfig;\n}\n\ntype BundleBackfillChunk = {\n type: \"chunk\";\n fileName: string;\n imports?: string[];\n modules?: Record<string, unknown>;\n viteMetadata?: {\n importedCss?: Set<string>;\n importedAssets?: Set<string>;\n };\n};\n\nfunction tryRealpathSync(candidate: string): string | null {\n try {\n return fs.realpathSync.native(candidate);\n } catch {\n return null;\n }\n}\n\nfunction isWindowsAbsolutePath(candidate: string): boolean {\n return /^[a-zA-Z]:[\\\\/]/.test(candidate) || candidate.startsWith(\"\\\\\\\\\");\n}\n\nfunction relativeWithinRoot(root: string, moduleId: string): string | null {\n const useWindowsPath = isWindowsAbsolutePath(root) || isWindowsAbsolutePath(moduleId);\n const relativeId = (\n useWindowsPath ? path.win32.relative(root, moduleId) : path.relative(root, moduleId)\n ).replace(/\\\\/g, \"/\");\n // path.relative(root, root) returns \"\", which is not a usable manifest key and should be\n // treated the same as \"outside root\" for this helper.\n if (!relativeId || relativeId === \"..\" || relativeId.startsWith(\"../\")) return null;\n return relativeId;\n}\n\nfunction normalizeManifestModuleId(moduleId: string, root: string): string {\n const normalizedId = moduleId.replace(/\\\\/g, \"/\");\n if (normalizedId.startsWith(\"\\0\")) return normalizedId;\n if (normalizedId.startsWith(\"node_modules/\") || normalizedId.includes(\"/node_modules/\")) {\n return normalizedId;\n }\n\n if (!isWindowsAbsolutePath(moduleId) && !path.isAbsolute(moduleId)) {\n if (!normalizedId.startsWith(\".\") && !normalizedId.includes(\"../\")) {\n // Preserve bare specifiers like \"pages/counter.tsx\". These are already\n // stable manifest keys and resolving them against root would rewrite them\n // into filesystem paths that no longer match the bundle/module graph.\n return normalizedId;\n }\n }\n\n const rootCandidates = new Set<string>([root]);\n const realRoot = tryRealpathSync(root);\n if (realRoot) rootCandidates.add(realRoot);\n\n const moduleCandidates = new Set<string>();\n if (isWindowsAbsolutePath(moduleId) || path.isAbsolute(moduleId)) {\n moduleCandidates.add(moduleId);\n } else {\n moduleCandidates.add(path.resolve(root, moduleId));\n }\n\n for (const candidate of moduleCandidates) {\n const realCandidate = tryRealpathSync(candidate);\n // Set iteration stays live as entries are appended, so this also checks the\n // realpath variant without needing a second pass or an intermediate array.\n if (realCandidate) moduleCandidates.add(realCandidate);\n }\n\n for (const rootCandidate of rootCandidates) {\n for (const moduleCandidate of moduleCandidates) {\n const relativeId = relativeWithinRoot(rootCandidate, moduleCandidate);\n if (relativeId) return relativeId;\n }\n }\n\n return normalizedId;\n}\n\nfunction augmentSsrManifestFromBundle(\n ssrManifest: Record<string, string[]>,\n bundle: Record<string, BundleBackfillChunk | { type: string }>,\n root: string,\n base = \"/\",\n): Record<string, string[]> {\n const nextManifest = {} as Record<string, Set<string>>;\n\n for (const [key, files] of Object.entries(ssrManifest)) {\n const normalizedKey = normalizeManifestModuleId(key, root);\n if (!nextManifest[normalizedKey]) nextManifest[normalizedKey] = new Set<string>();\n for (const file of files) {\n nextManifest[normalizedKey].add(normalizeManifestFile(file));\n }\n }\n\n for (const item of Object.values(bundle)) {\n if (item.type !== \"chunk\") continue;\n const chunk = item as BundleBackfillChunk;\n\n const files = new Set<string>();\n files.add(manifestFileWithBase(chunk.fileName, base));\n for (const importedFile of chunk.imports ?? []) {\n files.add(manifestFileWithBase(importedFile, base));\n }\n for (const cssFile of chunk.viteMetadata?.importedCss ?? []) {\n files.add(manifestFileWithBase(cssFile, base));\n }\n for (const assetFile of chunk.viteMetadata?.importedAssets ?? []) {\n files.add(manifestFileWithBase(assetFile, base));\n }\n\n for (const moduleId of Object.keys(chunk.modules ?? {})) {\n const key = normalizeManifestModuleId(moduleId, root);\n if (key.startsWith(\"node_modules/\") || key.includes(\"/node_modules/\")) continue;\n if (key.startsWith(\"\\0\")) continue;\n if (!nextManifest[key]) nextManifest[key] = new Set<string>();\n for (const file of files) {\n nextManifest[key].add(file);\n }\n }\n }\n\n return Object.fromEntries(\n Object.entries(nextManifest).map(([key, files]) => [key, [...files]]),\n ) as Record<string, string[]>;\n}\n\nexport type VinextOptions = {\n /**\n * Base directory containing the app/ and pages/ directories.\n * Can be an absolute path or a path relative to the Vite root.\n *\n * By default, vinext auto-detects: checks for app/ and pages/ at the\n * project root first, then falls back to src/app/ and src/pages/.\n */\n appDir?: string;\n /**\n * Force-disable App Router detection even when an app/ directory exists.\n * Only the Pages Router pipeline will be active.\n * Intended for testing and tools that need to build only the Pages Router\n * bundle from a hybrid (app + pages) project.\n * @default false\n */\n disableAppRouter?: boolean;\n /**\n * Override the output directory for the RSC server bundle.\n * Absolute paths are used as-is; relative paths are resolved from the\n * Vite root. Defaults to \"dist/server\".\n * Intended for tests that need to build multiple fixtures in parallel\n * without clobbering each other's output.\n */\n rscOutDir?: string;\n /**\n * Override the output directory for the SSR bundle.\n * Defaults to \"dist/server/ssr\".\n */\n ssrOutDir?: string;\n /**\n * Override the output directory for the client bundle.\n * Defaults to Vite's default (dist/client or dist).\n */\n clientOutDir?: string;\n /**\n * Inline Next.js config for projects that want to configure vinext from\n * vite.config without a separate next.config file.\n *\n * When provided, vinext skips loading next.config.* from disk and uses this\n * value instead. Supports both object-form and function-form config.\n */\n nextConfig?: NextConfigInput;\n /**\n * Auto-register @vitejs/plugin-rsc when an app/ directory is detected.\n * Set to `false` to disable auto-registration (e.g. if you configure\n * @vitejs/plugin-rsc manually with custom options).\n * @default true\n */\n rsc?: boolean;\n /**\n * Options passed to @vitejs/plugin-react (React Fast Refresh + JSX transform).\n * Enabled by default. Set to `false` to disable (e.g. if you configure\n * @vitejs/plugin-react manually in your vite.config.ts), or pass an options\n * object to customize the Babel transform.\n * @default true\n */\n react?: VitePluginReactOptions | boolean;\n /**\n * Enable build-time precompression of static assets (.br, .gz, .zst).\n *\n * When enabled, hashed assets in the client build are precompressed at\n * build time so the production server can serve them without on-the-fly\n * compression overhead.\n *\n * Disabled by default. Not useful when deploying to edge platforms\n * (Cloudflare Workers, Nitro) that handle compression at the CDN layer.\n *\n * Can also be enabled via the `--precompress` CLI flag or by setting the\n * `VINEXT_PRECOMPRESS=1` environment variable (useful for CI pipelines\n * that need to enable precompression without modifying vite.config.ts).\n * @default false\n */\n precompress?: boolean;\n /**\n * Experimental vinext-only feature flags.\n */\n experimental?: {\n /**\n * Dedup client references emitted from RSC proxy modules in dev.\n * Disabled by default until the behavior is better proven across\n * ecosystem apps.\n * @default false\n */\n clientReferenceDedup?: boolean;\n };\n};\n\ntype NitroSetupContext = {\n options: {\n dev?: boolean;\n routeRules?: Record<string, NitroRouteRuleConfig>;\n };\n logger?: {\n warn?: (message: string) => void;\n };\n};\n\nexport default function vinext(options: VinextOptions = {}): PluginOption[] {\n const viteMajorVersion = getViteMajorVersion();\n let root: string;\n let pagesDir: string;\n let appDir: string;\n let hasAppDir = false;\n let hasPagesDir = false;\n let nextConfig: ResolvedNextConfig;\n let fileMatcher: ReturnType<typeof createValidFileMatcher>;\n let middlewarePath: string | null = null;\n let instrumentationPath: string | null = null;\n let instrumentationClientPath: string | null = null;\n let hasCloudflarePlugin = false;\n let warnedInlineNextConfigOverride = false;\n let hasNitroPlugin = false;\n\n // Resolve shim paths - works both from source (.ts) and built (.js)\n const shimsDir = path.resolve(__dirname, \"shims\");\n\n // Shim alias map — populated in config(), used by resolveId() for .js variants\n let nextShimMap: Record<string, string> = {};\n\n /**\n * Generate the virtual SSR server entry module.\n * This is the entry point for `vite build --ssr`.\n */\n async function generateServerEntry(): Promise<string> {\n return _generateServerEntry(\n pagesDir,\n nextConfig,\n fileMatcher,\n middlewarePath,\n instrumentationPath,\n );\n }\n\n /**\n * Generate the virtual client hydration entry module.\n * This is the entry point for `vite build` (client bundle).\n *\n * It maps route patterns to dynamic imports of page modules so Vite\n * code-splits each page into its own chunk. At runtime it reads\n * __NEXT_DATA__ to determine which page to hydrate.\n */\n async function generateClientEntry(): Promise<string> {\n return _generateClientEntry(pagesDir, nextConfig, fileMatcher);\n }\n\n // Auto-register @vitejs/plugin-rsc when App Router is detected.\n // Check eagerly at call time using the same heuristic as config().\n // Must mirror the full detection logic: check {base}/app then {base}/src/app.\n const autoRsc = options.rsc !== false;\n const earlyBaseDir = options.appDir ?? process.cwd();\n const earlyAppDirExists =\n !options.disableAppRouter &&\n (fs.existsSync(path.join(earlyBaseDir, \"app\")) ||\n fs.existsSync(path.join(earlyBaseDir, \"src\", \"app\")));\n\n // IMPORTANT: Resolve @vitejs/plugin-rsc subpath imports from the user's\n // project root, not from vinext's own package location. When vinext is\n // installed via symlink (npm file: deps, pnpm workspace:*), a bare\n // import() resolves from vinext's realpath, which can find a different\n // copy of the RSC plugin (and transitively a different copy of vite).\n // This causes instanceof RunnableDevEnvironment checks to fail at\n // runtime because the Vite server and the RSC plugin end up with\n // different class identities. Resolving from the project root ensures a\n // single shared vite instance.\n //\n // Pre-resolve both the main plugin and the /transforms subpath eagerly\n // so all import() calls in this module use consistent resolution.\n let resolvedReactPath: string | null = null;\n let resolvedRscPath: string | null = null;\n let resolvedRscTransformsPath: string | null = null;\n // Prefer the user's project graph so vinext shares the app's Vite/plugin\n // instances. In source/workspace development, test fixtures may not declare\n // peer deps explicitly, so fall back to vinext's own install location.\n resolvedReactPath = resolveOptionalDependency(earlyBaseDir, \"@vitejs/plugin-react\");\n resolvedRscPath = resolveOptionalDependency(earlyBaseDir, \"@vitejs/plugin-rsc\");\n resolvedRscTransformsPath = resolveOptionalDependency(\n earlyBaseDir,\n \"@vitejs/plugin-rsc/transforms\",\n );\n\n // If app/ exists and auto-RSC is enabled, create a lazy Promise that\n // resolves to the configured RSC plugin array. Vite's asyncFlatten\n // will resolve this before processing the plugin list.\n let rscPluginPromise: Promise<Plugin[]> | null = null;\n if (earlyAppDirExists && autoRsc) {\n if (!resolvedRscPath) {\n throw new Error(\n \"vinext: App Router detected but @vitejs/plugin-rsc is not installed.\\n\" +\n \"Run: \" +\n detectPackageManager(process.cwd()) +\n \" @vitejs/plugin-rsc\",\n );\n }\n const rscImport = import(pathToFileURL(resolvedRscPath).href);\n rscPluginPromise = rscImport\n .then((mod) => {\n const rsc = mod.default;\n return rsc({\n entries: {\n rsc: VIRTUAL_RSC_ENTRY,\n ssr: VIRTUAL_APP_SSR_ENTRY,\n client: VIRTUAL_APP_BROWSER_ENTRY,\n },\n });\n })\n .catch((cause) => {\n throw new Error(\"vinext: Failed to load @vitejs/plugin-rsc.\", { cause });\n });\n }\n\n const reactOptions = options.react && options.react !== true ? options.react : undefined;\n\n let reactPluginPromise: Promise<PluginOption[]> | null = null;\n if (options.react !== false) {\n if (!resolvedReactPath) {\n throw new Error(\n \"vinext: @vitejs/plugin-react is not installed.\\n\" +\n \"Run: \" +\n detectPackageManager(process.cwd()) +\n \" @vitejs/plugin-react\",\n );\n }\n const reactImport = import(pathToFileURL(resolvedReactPath).href);\n reactPluginPromise = reactImport\n .then((mod) => (mod as VitePluginReactModule).default(reactOptions))\n .catch((cause) => {\n throw new Error(\"vinext: Failed to load @vitejs/plugin-react.\", { cause });\n });\n }\n\n const imageImportDimCache = new Map<string, { width: number; height: number }>();\n\n // Shared state for the MDX proxy plugin. We auto-inject @mdx-js/rollup when\n // MDX is detected in app/pages during config(), and lazily on first plain\n // .mdx transform for MDX that only enters the graph via import.meta.glob.\n let mdxDelegate: Plugin | null = null;\n // Cached across calls — only the first invocation's `reason` affects logging.\n // This is correct because config() always runs before transform() in the same build.\n let mdxDelegatePromise: Promise<Plugin | null> | null = null;\n let hasUserMdxPlugin = false;\n let warnedMissingMdxPlugin = false;\n\n async function ensureMdxDelegate(reason: \"detected\" | \"on-demand\"): Promise<Plugin | null> {\n // Reuse the auto-injected delegate once it has been created.\n // If the user registered their own MDX plugin and `mdxDelegate` is still null,\n // return null here so transform() falls through without handling the file and\n // the user's plugin can process the .mdx module later in the pipeline.\n // Note: hasUserMdxPlugin is set during config(), which runs before transform().\n if (mdxDelegate || hasUserMdxPlugin) return mdxDelegate;\n if (!mdxDelegatePromise) {\n mdxDelegatePromise = (async () => {\n try {\n const mdxRollup = await import(\"@mdx-js/rollup\");\n const mdxFactory = (mdxRollup.default ?? mdxRollup) as (\n options: Record<string, unknown>,\n ) => Plugin;\n const mdxOpts: Record<string, unknown> = {};\n if (nextConfig.mdx) {\n if (nextConfig.mdx.remarkPlugins) mdxOpts.remarkPlugins = nextConfig.mdx.remarkPlugins;\n if (nextConfig.mdx.rehypePlugins) mdxOpts.rehypePlugins = nextConfig.mdx.rehypePlugins;\n if (nextConfig.mdx.recmaPlugins) mdxOpts.recmaPlugins = nextConfig.mdx.recmaPlugins;\n }\n const delegate = mdxFactory(mdxOpts);\n mdxDelegate = delegate;\n if (reason === \"detected\") {\n if (nextConfig.mdx) {\n console.log(\n \"[vinext] Auto-injected @mdx-js/rollup with remark/rehype plugins from next.config\",\n );\n } else {\n console.log(\"[vinext] Auto-injected @mdx-js/rollup for MDX support\");\n }\n } else {\n console.log(\"[vinext] Auto-injected @mdx-js/rollup for on-demand MDX support\");\n }\n return delegate;\n } catch {\n // Only warn during \"detected\" path (MDX files in app/pages at config time).\n // For \"on-demand\" (MDX encountered during transform), the error thrown\n // in transform() is more actionable and immediate. Avoid double messaging.\n if (reason === \"detected\" && !warnedMissingMdxPlugin) {\n warnedMissingMdxPlugin = true;\n console.warn(\n \"[vinext] MDX files detected but @mdx-js/rollup is not installed. \" +\n \"Install it with: \" +\n detectPackageManager(process.cwd()) +\n \" @mdx-js/rollup\",\n );\n }\n return null;\n }\n })();\n }\n return mdxDelegatePromise;\n }\n\n const plugins: PluginOption[] = [\n // Resolve tsconfig paths/baseUrl aliases so real-world Next.js repos\n // that use @/*, #/*, or baseUrl imports work out of the box.\n // Vite 8+ supports this natively via resolve.tsconfigPaths.\n ...(viteMajorVersion >= 8 ? [] : [tsconfigPaths()]),\n // React Fast Refresh + JSX transform for client components.\n reactPluginPromise,\n // Transform CJS require()/module.exports to ESM before other plugins\n // analyze imports (RSC directive scanning, shim resolution, etc.)\n commonjs(),\n // Fix 'use server' closure variable collision with local declarations.\n // See packages/vinext/src/plugins/fix-use-server-closure-collision.ts for details.\n fixUseServerClosureCollisionPlugin,\n {\n name: \"vinext:config\",\n enforce: \"pre\",\n\n async config(config, env) {\n root = config.root ?? process.cwd();\n const userResolve = config.resolve as UserResolveConfigWithTsconfigPaths | undefined;\n const shouldEnableNativeTsconfigPaths =\n viteMajorVersion >= 8 && userResolve?.tsconfigPaths === undefined;\n const tsconfigPathAliases = resolveTsconfigAliases(root);\n\n // Load .env files into process.env before anything else.\n // Next.js loads .env files before evaluating next.config.js, so\n // env vars are available in config, server-side code, and as\n // NEXT_PUBLIC_* defines for the client bundle.\n // Pass '' as prefix to load ALL vars, not just VITE_-prefixed ones.\n const mode = env?.mode ?? \"development\";\n const envDir = config.envDir ?? root;\n const dotenvVars = loadEnv(mode, envDir, \"\");\n for (const [key, value] of Object.entries(dotenvVars)) {\n if (process.env[key] === undefined) {\n process.env[key] = value;\n }\n }\n // Align NODE_ENV with Next.js semantics: build -> production, serve -> development.\n // Next.js unconditionally forces NODE_ENV during build/dev, so we do the same.\n let resolvedNodeEnv: string;\n if (mode === \"test\") {\n resolvedNodeEnv = \"test\";\n } else if (env?.command === \"build\") {\n resolvedNodeEnv = \"production\";\n } else {\n resolvedNodeEnv = \"development\";\n }\n if (process.env.NODE_ENV !== resolvedNodeEnv) {\n process.env.NODE_ENV = resolvedNodeEnv;\n }\n\n // Resolve the base directory for app/pages detection.\n // If appDir is provided, resolve it (supports both relative and absolute paths).\n // If not provided, auto-detect: check root first, then src/ subdirectory.\n let baseDir: string;\n if (options.appDir) {\n baseDir = path.isAbsolute(options.appDir)\n ? options.appDir\n : path.resolve(root, options.appDir);\n } else {\n // Auto-detect: prefer root-level app/ and pages/, fall back to src/\n const hasRootApp = fs.existsSync(path.join(root, \"app\"));\n const hasRootPages = fs.existsSync(path.join(root, \"pages\"));\n const hasSrcApp = fs.existsSync(path.join(root, \"src\", \"app\"));\n const hasSrcPages = fs.existsSync(path.join(root, \"src\", \"pages\"));\n\n if (hasRootApp || hasRootPages) {\n baseDir = root;\n } else if (hasSrcApp || hasSrcPages) {\n baseDir = path.join(root, \"src\");\n } else {\n baseDir = root;\n }\n }\n\n pagesDir = path.join(baseDir, \"pages\");\n appDir = path.join(baseDir, \"app\");\n hasPagesDir = fs.existsSync(pagesDir);\n hasAppDir = !options.disableAppRouter && fs.existsSync(appDir);\n\n // Load next.config.js if present (always from project root, not src/),\n // unless vinext({ nextConfig }) explicitly overrides it.\n // Guard: resolve nextConfig only once per plugin instance. In Vite's\n // multi-environment build the config hook fires once per environment;\n // without this guard, resolveNextConfig() → resolveBuildId() generates\n // a fresh random UUID each time, causing different buildId values to be\n // baked into the RSC, SSR, and client bundles.\n // Note: fileMatcher, instrumentationPath, etc. are intentionally set\n // outside this guard — they are cheap and deterministic, and keeping\n // them here ensures they reflect the final resolved root on every call.\n if (!nextConfig) {\n const phase =\n env?.command === \"build\" ? PHASE_PRODUCTION_BUILD : PHASE_DEVELOPMENT_SERVER;\n let rawConfig: NextConfig | null;\n if (options.nextConfig) {\n const diskConfigPath = findNextConfigPath(root);\n if (diskConfigPath && !warnedInlineNextConfigOverride) {\n warnedInlineNextConfigOverride = true;\n console.warn(\n `[vinext] vinext({ nextConfig }) overrides ${path.basename(diskConfigPath)}. Remove one of the config sources to avoid drift.`,\n );\n }\n rawConfig = await resolveNextConfigInput(options.nextConfig, phase);\n } else {\n rawConfig = await loadNextConfig(root, phase);\n }\n nextConfig = await resolveNextConfig(rawConfig, root);\n }\n fileMatcher = createValidFileMatcher(nextConfig.pageExtensions);\n instrumentationPath = findInstrumentationFile(root, fileMatcher);\n instrumentationClientPath = findInstrumentationClientFile(root, fileMatcher);\n middlewarePath = findMiddlewareFile(root, fileMatcher);\n\n // Merge env from next.config.js with NEXT_PUBLIC_* env vars\n const defines = getNextPublicEnvDefines();\n if (\n !config.define ||\n typeof config.define !== \"object\" ||\n !(\"process.env.NODE_ENV\" in config.define)\n ) {\n defines[\"process.env.NODE_ENV\"] = JSON.stringify(resolvedNodeEnv);\n }\n for (const [key, value] of Object.entries(nextConfig.env)) {\n // Skip NODE_ENV from next.config.js env — Next.js ignores it too,\n // and it would silently override the value we just set above.\n if (key === \"NODE_ENV\") continue;\n defines[`process.env.${key}`] = JSON.stringify(value);\n }\n // Expose basePath to client-side code\n defines[\"process.env.__NEXT_ROUTER_BASEPATH\"] = JSON.stringify(nextConfig.basePath);\n // Expose image remote patterns for validation in next/image shim\n defines[\"process.env.__VINEXT_IMAGE_REMOTE_PATTERNS\"] = JSON.stringify(\n JSON.stringify(nextConfig.images?.remotePatterns ?? []),\n );\n defines[\"process.env.__VINEXT_IMAGE_DOMAINS\"] = JSON.stringify(\n JSON.stringify(nextConfig.images?.domains ?? []),\n );\n // Expose allowed image widths (union of deviceSizes + imageSizes) for\n // server-side validation. Matches Next.js behavior: only configured\n // sizes are accepted by the image optimization endpoint.\n {\n const deviceSizes = nextConfig.images?.deviceSizes ?? [\n 640, 750, 828, 1080, 1200, 1920, 2048, 3840,\n ];\n const imageSizes = nextConfig.images?.imageSizes ?? [16, 32, 48, 64, 96, 128, 256, 384];\n defines[\"process.env.__VINEXT_IMAGE_DEVICE_SIZES\"] = JSON.stringify(\n JSON.stringify(deviceSizes),\n );\n defines[\"process.env.__VINEXT_IMAGE_SIZES\"] = JSON.stringify(JSON.stringify(imageSizes));\n }\n // Expose dangerouslyAllowSVG flag for the image shim's auto-skip logic.\n // When false (default), .svg sources bypass the optimization endpoint.\n defines[\"process.env.__VINEXT_IMAGE_DANGEROUSLY_ALLOW_SVG\"] = JSON.stringify(\n String(nextConfig.images?.dangerouslyAllowSVG ?? false),\n );\n // Draft mode secret — generated once at build time so the\n // __prerender_bypass cookie is consistent across all server\n // instances (e.g. multiple Cloudflare Workers isolates).\n defines[\"process.env.__VINEXT_DRAFT_SECRET\"] = JSON.stringify(crypto.randomUUID());\n // Build ID — resolved from next.config generateBuildId() or random UUID.\n // Exposed so server entries and the next/server shim can inject it.\n // Also used to namespace ISR cache keys so old cached entries from a\n // previous deploy are never served by the new one.\n defines[\"process.env.__VINEXT_BUILD_ID\"] = JSON.stringify(nextConfig.buildId);\n\n // Build the shim alias map. Exact `.js` variants are included for the\n // public Next entrypoints that are file-backed in `next/package.json`.\n // Some libraries (for example `nuqs`) import `next/navigation.js`\n // directly; aliasing the `.js` form ensures optimizeDeps pre-bundles\n // vinext's shim instead of real Next.\n nextShimMap = Object.fromEntries(\n Object.entries({\n \"next/link\": path.join(shimsDir, \"link\"),\n \"next/head\": path.join(shimsDir, \"head\"),\n \"next/router\": path.join(shimsDir, \"router\"),\n \"next/compat/router\": path.join(shimsDir, \"compat-router\"),\n \"next/image\": path.join(shimsDir, \"image\"),\n \"next/legacy/image\": path.join(shimsDir, \"legacy-image\"),\n \"next/dynamic\": path.join(shimsDir, \"dynamic\"),\n \"next/app\": path.join(shimsDir, \"app\"),\n \"next/document\": path.join(shimsDir, \"document\"),\n \"next/config\": path.join(shimsDir, \"config\"),\n \"next/script\": path.join(shimsDir, \"script\"),\n \"next/server\": path.join(shimsDir, \"server\"),\n \"next/navigation\": path.join(shimsDir, \"navigation\"),\n \"next/headers\": path.join(shimsDir, \"headers\"),\n \"next/font/google\": path.join(shimsDir, \"font-google\"),\n \"next/font/local\": path.join(shimsDir, \"font-local\"),\n \"next/cache\": path.join(shimsDir, \"cache\"),\n \"next/form\": path.join(shimsDir, \"form\"),\n \"next/og\": path.join(shimsDir, \"og\"),\n \"next/web-vitals\": path.join(shimsDir, \"web-vitals\"),\n \"next/amp\": path.join(shimsDir, \"amp\"),\n \"next/error\": path.join(shimsDir, \"error\"),\n \"next/constants\": path.join(shimsDir, \"constants\"),\n // Internal next/dist/* paths used by popular libraries\n // (next-intl, @clerk/nextjs, @sentry/nextjs, next-nprogress-bar, etc.)\n \"next/dist/shared/lib/app-router-context.shared-runtime\": path.join(\n shimsDir,\n \"internal\",\n \"app-router-context\",\n ),\n \"next/dist/shared/lib/app-router-context\": path.join(\n shimsDir,\n \"internal\",\n \"app-router-context\",\n ),\n \"next/dist/shared/lib/router-context.shared-runtime\": path.join(\n shimsDir,\n \"internal\",\n \"router-context\",\n ),\n \"next/dist/shared/lib/utils\": path.join(shimsDir, \"internal\", \"utils\"),\n \"next/dist/server/api-utils\": path.join(shimsDir, \"internal\", \"api-utils\"),\n \"next/dist/server/web/spec-extension/cookies\": path.join(\n shimsDir,\n \"internal\",\n \"cookies\",\n ),\n \"next/dist/compiled/@edge-runtime/cookies\": path.join(shimsDir, \"internal\", \"cookies\"),\n \"next/dist/server/app-render/work-unit-async-storage.external\": path.join(\n shimsDir,\n \"internal\",\n \"work-unit-async-storage\",\n ),\n \"next/dist/client/components/work-unit-async-storage.external\": path.join(\n shimsDir,\n \"internal\",\n \"work-unit-async-storage\",\n ),\n \"next/dist/client/components/request-async-storage.external\": path.join(\n shimsDir,\n \"internal\",\n \"work-unit-async-storage\",\n ),\n \"next/dist/client/components/request-async-storage\": path.join(\n shimsDir,\n \"internal\",\n \"work-unit-async-storage\",\n ),\n // Re-export public modules for internal path imports\n \"next/dist/client/components/navigation\": path.join(shimsDir, \"navigation\"),\n \"next/dist/server/config-shared\": path.join(shimsDir, \"internal\", \"utils\"),\n // server-only / client-only marker packages\n \"server-only\": path.join(shimsDir, \"server-only\"),\n \"client-only\": path.join(shimsDir, \"client-only\"),\n \"vinext/error-boundary\": path.join(shimsDir, \"error-boundary\"),\n \"vinext/layout-segment-context\": path.join(shimsDir, \"layout-segment-context\"),\n \"vinext/metadata\": path.join(shimsDir, \"metadata\"),\n \"vinext/fetch-cache\": path.join(shimsDir, \"fetch-cache\"),\n \"vinext/cache-runtime\": path.join(shimsDir, \"cache-runtime\"),\n \"vinext/navigation-state\": path.join(shimsDir, \"navigation-state\"),\n \"vinext/unified-request-context\": path.join(shimsDir, \"unified-request-context\"),\n \"vinext/router-state\": path.join(shimsDir, \"router-state\"),\n \"vinext/head-state\": path.join(shimsDir, \"head-state\"),\n \"vinext/i18n-state\": path.join(shimsDir, \"i18n-state\"),\n \"vinext/i18n-context\": path.join(shimsDir, \"i18n-context\"),\n \"vinext/cache\": path.resolve(__dirname, \"cache\"),\n \"vinext/instrumentation\": path.resolve(__dirname, \"server\", \"instrumentation\"),\n \"vinext/instrumentation-client\": path.resolve(\n __dirname,\n \"client\",\n \"instrumentation-client\",\n ),\n \"vinext/html\": path.resolve(__dirname, \"server\", \"html\"),\n \"private-next-instrumentation-client\":\n instrumentationClientPath ?? path.resolve(__dirname, \"client\", \"empty-module\"),\n }).flatMap(([k, v]) =>\n k.startsWith(\"next/\")\n ? [\n [k, v],\n [`${k}.js`, v],\n ]\n : [[k, v]],\n ),\n );\n\n // Detect if Cloudflare's vite plugin is present — if so, skip\n // SSR externals (Workers bundle everything, can't have Node.js externals).\n const pluginsFlat: unknown[] = [];\n function flattenPlugins(arr: unknown[]) {\n for (const p of arr) {\n if (Array.isArray(p)) flattenPlugins(p);\n else if (p) pluginsFlat.push(p);\n }\n }\n flattenPlugins((config.plugins as unknown[]) ?? []);\n hasCloudflarePlugin = pluginsFlat.some(\n (p: unknown) =>\n p &&\n typeof p === \"object\" &&\n \"name\" in p &&\n typeof p.name === \"string\" &&\n (p.name === \"vite-plugin-cloudflare\" || p.name.startsWith(\"vite-plugin-cloudflare:\")),\n );\n hasNitroPlugin = pluginsFlat.some(\n (p: unknown) =>\n p &&\n typeof p === \"object\" &&\n \"name\" in p &&\n typeof p.name === \"string\" &&\n (p.name === \"nitro\" || p.name.startsWith(\"nitro:\")),\n );\n\n // Resolve PostCSS string plugin names that Vite can't handle.\n // Next.js projects commonly use array-form plugins like\n // `plugins: [\"@tailwindcss/postcss\"]` which postcss-load-config\n // doesn't resolve (only object-form keys are resolved). We detect\n // this and resolve the strings to actual plugin functions, then\n // inject via css.postcss so Vite uses the resolved plugins.\n // Only do this if the user hasn't already set css.postcss inline.\n // oxlint-disable-next-line typescript/no-explicit-any\n let postcssOverride: { plugins: any[] } | undefined;\n if (!config.css?.postcss || typeof config.css.postcss === \"string\") {\n postcssOverride = await resolvePostcssStringPlugins(root);\n }\n\n // Auto-inject @mdx-js/rollup when MDX files exist and no MDX plugin is\n // already configured. Applies remark/rehype plugins from next.config.\n hasUserMdxPlugin = pluginsFlat.some(\n (p: unknown) =>\n p &&\n typeof p === \"object\" &&\n \"name\" in p &&\n typeof p.name === \"string\" &&\n (p.name === \"@mdx-js/rollup\" || p.name === \"mdx\"),\n );\n if (\n !hasUserMdxPlugin &&\n hasMdxFiles(root, hasAppDir ? appDir : null, hasPagesDir ? pagesDir : null)\n ) {\n await ensureMdxDelegate(\"detected\");\n }\n\n // Detect if this is a standalone SSR build (set by `vite build --ssr`\n // or `build.ssr` in config). SSR builds must NOT use manualChunks\n // because they use inlineDynamicImports which is incompatible.\n const isSSR = !!config.build?.ssr;\n // Detect if this is a multi-environment build (App Router or Cloudflare).\n // In multi-env builds, manualChunks must only be set per-environment\n // (on the client env), not globally — otherwise it leaks into RSC/SSR\n // environments where it can cause asset resolution issues.\n const isMultiEnv = hasAppDir || hasCloudflarePlugin || hasNitroPlugin;\n\n const viteConfig: UserConfig = {\n // Disable Vite's default HTML serving - we handle all routing\n appType: \"custom\",\n build: {\n ...withBuildBundlerOptions(viteMajorVersion, {\n // Suppress \"Module level directives cause errors when bundled\"\n // warnings for \"use client\" / \"use server\" directives. Our shims\n // and third-party libraries legitimately use these directives;\n // they are handled by the RSC plugin and are harmless in the\n // final bundle. We preserve any user-supplied onwarn so custom\n // warning handling is not lost.\n onwarn: (() => {\n const userOnwarn = getBuildBundlerOptions(config.build)?.onwarn;\n return (warning, defaultHandler) => {\n if (\n warning.code === \"MODULE_LEVEL_DIRECTIVE\" &&\n (warning.message?.includes('\"use client\"') ||\n warning.message?.includes('\"use server\"'))\n ) {\n return;\n }\n // Dynamic route pages that don't export generateStaticParams\n // produce IMPORT_IS_UNDEFINED warnings because the virtual RSC\n // entry unconditionally references mod?.generateStaticParams for\n // every dynamic route. The ?. guards the access safely at runtime;\n // suppress the build-time noise.\n if (\n warning.code === \"IMPORT_IS_UNDEFINED\" &&\n warning.message?.includes(\"generateStaticParams\")\n ) {\n return;\n }\n if (userOnwarn) {\n userOnwarn(warning, defaultHandler);\n } else {\n defaultHandler(warning);\n }\n };\n })(),\n // Enable aggressive tree-shaking for client builds.\n // See clientTreeshakeConfig for rationale.\n // Only apply globally for standalone client builds (Pages Router\n // CLI). For multi-environment builds (App Router, Cloudflare),\n // treeshake is set per-environment on the client env below to\n // avoid leaking into RSC/SSR environments where\n // moduleSideEffects: 'no-external' could drop server packages\n // that rely on module-level side effects.\n ...(!isSSR && !isMultiEnv ? { treeshake: clientTreeshakeConfig } : {}),\n // Code-split client bundles: separate framework (React/ReactDOM),\n // vinext runtime (shims), and vendor packages into their own\n // chunks so pages only load the JS they need.\n // Only apply globally for standalone client builds (CLI Pages\n // Router). For multi-environment builds (App Router, Cloudflare),\n // manualChunks is set per-environment on the client env below\n // to avoid leaking into RSC/SSR environments.\n ...(!isSSR && !isMultiEnv\n ? { output: getClientOutputConfigForVite(viteMajorVersion) }\n : {}),\n }),\n },\n // Let OPTIONS requests pass through Vite's CORS middleware to our\n // route handlers so they can set the Allow header and run user-defined\n // OPTIONS handlers. Without this, Vite's CORS middleware responds to\n // OPTIONS with a 204 before the request reaches vinext's handler.\n // Keep Vite's default restrictive origin policy by explicitly\n // setting it. Without the `origin` field, `preflightContinue: true`\n // would override Vite's default and allow any origin.\n server: {\n cors: {\n preflightContinue: true,\n origin: /^https?:\\/\\/(?:(?:[^:]+\\.)?localhost|127\\.0\\.0\\.1|\\[::1\\])(?::\\d+)?$/,\n },\n },\n // Configure SSR transform behaviour for Node targets.\n // - `external`: React packages are loaded natively by Node (CJS)\n // rather than through Vite's ESM evaluator.\n // - `noExternal: true`: force everything else through Vite's\n // transform pipeline so non-JS imports (CSS, images) from\n // node_modules don't hit Node's native ESM loader.\n // Any user-provided `ssr.noExternal` is intentionally superseded\n // by this setting; only `ssr.external` entries escape Vite's transform.\n // Skip when targeting bundled runtimes (Cloudflare/Nitro bundle everything).\n // This also resolves extensionless-import issues in packages like\n // `validator` (see #189) by routing them through Vite's resolver.\n ...(hasCloudflarePlugin || hasNitroPlugin\n ? {}\n : {\n ssr: {\n external: [\"react\", \"react-dom\", \"react-dom/server\"],\n noExternal: true,\n },\n }),\n resolve: {\n // Materialize simple tsconfig/jsconfig path aliases into resolve.alias\n // so Vite can transform import.meta.glob(\"@/...\") and import(`@/...`).\n alias: { ...tsconfigPathAliases, ...nextConfig.aliases, ...nextShimMap },\n // Dedupe React packages to prevent dual-instance errors.\n // When vinext is linked (npm link / bun link) or any dependency\n // brings its own React copy, multiple React instances can load,\n // causing cryptic \"Invalid hook call\" errors. This is a no-op\n // when only one copy exists.\n dedupe: [\"react\", \"react-dom\", \"react/jsx-runtime\", \"react/jsx-dev-runtime\"],\n ...(shouldEnableNativeTsconfigPaths ? { tsconfigPaths: true } : {}),\n },\n // NOTE: top-level optimizeDeps is now set below (after capturing\n // incoming values from earlier plugins) so both Pages Router and\n // App Router builds merge correctly.\n // Enable JSX in .tsx/.jsx files\n // Vite 7 uses `esbuild` for transforms, Vite 8+ uses `oxc`\n ...(viteMajorVersion >= 8\n ? { oxc: { jsx: { runtime: \"automatic\" } } }\n : { esbuild: { jsx: \"automatic\" } }),\n // Define env vars for client bundle\n define: defines,\n // Set base path if configured\n ...(nextConfig.basePath ? { base: nextConfig.basePath + \"/\" } : {}),\n // Inject resolved PostCSS plugins if string names were found\n ...(postcssOverride ? { css: { postcss: postcssOverride } } : {}),\n };\n\n // Collect user-provided ssr.external so we can propagate it into\n // both the RSC and SSR environment configs. Vite's `ssr.*` config\n // only applies to the default `ssr` environment, not custom ones\n // like `rsc`. Native addon packages (e.g. better-sqlite3) listed\n // in ssr.external must be externalized from ALL server environments.\n // Vite's SSROptions.external is `string[] | true`; handle both forms.\n //\n // Also merge in `serverExternalPackages` from next.config (and the\n // legacy `experimental.serverComponentsExternalPackages` alias). These\n // are packages that Next.js intentionally skips bundling and loads\n // natively — e.g. packages that import Node-specific entry points via\n // conditional exports (like `file-type` which exports `fileTypeFromFile`\n // only from its `node` condition, not from the universal `default` one).\n // Without externalizing them, Vite's optimizer picks the wrong export\n // condition and the build fails with MISSING_EXPORT errors.\n const nextServerExternal: string[] = nextConfig?.serverExternalPackages ?? [];\n const userSsrExternal: string[] | true = Array.isArray(config.ssr?.external)\n ? [...config.ssr.external, ...nextServerExternal]\n : config.ssr?.external === true\n ? true\n : nextServerExternal;\n\n // Capture top-level optimizeDeps populated by earlier plugins\n // (e.g. @lingui/vite-plugin) so we merge rather than overwrite.\n // Moved above the hasAppDir branch so both Pages Router and App\n // Router code paths can use these values.\n const incomingExclude: string[] =\n (config.optimizeDeps?.exclude as string[] | undefined) ?? [];\n const incomingInclude: string[] =\n (config.optimizeDeps?.include as string[] | undefined) ?? [];\n\n // Merge incoming excludes into the top-level optimizeDeps so\n // Pages Router builds (which don't set per-environment configs)\n // also preserve entries from earlier plugins.\n viteConfig.optimizeDeps = {\n exclude: [...new Set([...incomingExclude, \"vinext\", \"@vercel/og\"])],\n ...(incomingInclude.length > 0 ? { include: incomingInclude } : {}),\n };\n const pagesOptimizeEntries = !hasAppDir\n ? [\n ...(hasPagesDir\n ? [toRelativeFileEntry(root, pagesDir) + \"/**/*.{tsx,ts,jsx,js}\"]\n : []),\n ...[instrumentationPath, instrumentationClientPath].flatMap((entry) =>\n entry ? [toRelativeFileEntry(root, entry)] : [],\n ),\n ]\n : [];\n\n // If app/ directory exists, configure RSC environments\n if (hasAppDir) {\n // Compute optimizeDeps.entries so Vite discovers server-side\n // dependencies at startup instead of on first request. Without\n // this, deps imported in rsc/ssr environments are found lazily,\n // causing re-optimisation cascades and runtime errors (e.g.\n // \"Invalid hook call\" from duplicate React instances).\n // The entries must be relative to the project root.\n const relAppDir = path.relative(root, appDir);\n const appEntries = [`${relAppDir}/**/*.{tsx,ts,jsx,js}`];\n const explicitInstrumentationEntries = [\n instrumentationPath,\n instrumentationClientPath,\n ].flatMap((entry) => (entry ? [toRelativeFileEntry(root, entry)] : []));\n const optimizeEntries = [...new Set([...appEntries, ...explicitInstrumentationEntries])];\n\n viteConfig.environments = {\n rsc: {\n ...(hasCloudflarePlugin || hasNitroPlugin\n ? {}\n : {\n resolve: {\n // Externalize native/heavy packages so the RSC environment\n // loads them natively via Node rather than through Vite's\n // ESM module evaluator (which can't handle native addons).\n // Note: Do NOT externalize react/react-dom here — they must\n // be bundled with the \"react-server\" condition for RSC.\n // Skip when targeting bundled runtimes (Cloudflare/Nitro).\n external:\n userSsrExternal === true\n ? true\n : [\"satori\", \"@resvg/resvg-js\", \"yoga-wasm-web\", ...userSsrExternal],\n // Force all node_modules through Vite's transform pipeline\n // so non-JS imports (CSS, images) don't hit Node's native\n // ESM loader. Matches Next.js behavior of bundling everything.\n // Packages in `external` above take precedence per Vite rules.\n // When user sets `ssr.external: true`, skip noExternal since\n // everything is already externalized.\n ...(userSsrExternal === true ? {} : { noExternal: true as const }),\n },\n }),\n optimizeDeps: {\n exclude: [...new Set([...incomingExclude, \"vinext\", \"@vercel/og\"])],\n entries: optimizeEntries,\n },\n build: {\n outDir: options.rscOutDir ?? \"dist/server\",\n ...withBuildBundlerOptions(viteMajorVersion, {\n input: { index: VIRTUAL_RSC_ENTRY },\n }),\n },\n },\n ssr: {\n ...(hasCloudflarePlugin || hasNitroPlugin\n ? {}\n : {\n resolve: {\n external: userSsrExternal === true ? true : [...userSsrExternal],\n // Force all node_modules through Vite's transform pipeline\n // so non-JS imports (CSS, images) don't hit Node's native\n // ESM loader. Matches Next.js behavior of bundling everything.\n // When user sets `ssr.external: true`, skip noExternal since\n // everything is already externalized.\n ...(userSsrExternal === true ? {} : { noExternal: true as const }),\n },\n }),\n optimizeDeps: {\n exclude: [...new Set([...incomingExclude, \"vinext\", \"@vercel/og\"])],\n entries: optimizeEntries,\n },\n build: {\n outDir: options.ssrOutDir ?? \"dist/server/ssr\",\n ...withBuildBundlerOptions(viteMajorVersion, {\n input: { index: VIRTUAL_APP_SSR_ENTRY },\n }),\n },\n },\n client: {\n // Explicitly mark as client consumer so other plugins (e.g. Nitro)\n // can detect this during configEnvironment hooks — before Vite\n // applies the default consumer based on environment name.\n // Without this, Nitro's configEnvironment creates a server-side\n // service for the client environment, causing virtual module\n // imports to leak to Node's native ESM loader (ERR_UNSUPPORTED_ESM_URL_SCHEME).\n consumer: \"client\",\n optimizeDeps: {\n // Exclude server-external packages from the client dep optimizer.\n // These packages are server-only by design (listed in next.config's\n // `serverExternalPackages`). If the client optimizer crawls into\n // them through app/ entries, it will use browser export conditions\n // and pick the wrong conditional export (e.g. `file-type` exports\n // `fileTypeFromFile` only from its `node` condition via `index.js`,\n // but the browser optimizer resolves to `core.js` which lacks it,\n // causing MISSING_EXPORT build failures).\n exclude: [\n ...new Set([...incomingExclude, \"vinext\", \"@vercel/og\", ...nextServerExternal]),\n ],\n // Crawl app/ source files up front so client-only deps imported\n // by user components are discovered during startup instead of\n // triggering a late re-optimisation + full page reload.\n entries: optimizeEntries,\n // React packages aren't crawled from app/ source files,\n // so must be pre-included to avoid late discovery (#25).\n include: [\n ...new Set([\n ...incomingInclude,\n \"react\",\n \"react-dom\",\n \"react-dom/client\",\n \"react/jsx-runtime\",\n \"react/jsx-dev-runtime\",\n ]),\n ],\n },\n build: {\n // When targeting Cloudflare Workers, enable manifest generation\n // so the vinext:cloudflare-build closeBundle hook can read the\n // client build manifest, compute lazy chunks (only reachable\n // via dynamic imports), and inject __VINEXT_LAZY_CHUNKS__ into\n // the worker entry. Without this, all chunks are modulepreloaded\n // on every page — defeating code-splitting for React.lazy() and\n // next/dynamic boundaries.\n ...(hasCloudflarePlugin ? { manifest: true } : {}),\n ...withBuildBundlerOptions(viteMajorVersion, {\n input: { index: VIRTUAL_APP_BROWSER_ENTRY },\n output: getClientOutputConfigForVite(viteMajorVersion),\n treeshake: clientTreeshakeConfig,\n }),\n },\n },\n };\n } else if (hasCloudflarePlugin) {\n // Pages Router on Cloudflare Workers: add a client environment\n // so the multi-environment build produces client JS bundles\n // alongside the worker. Without this, only the worker is built\n // and there's no client-side hydration.\n viteConfig.environments = {\n client: {\n consumer: \"client\",\n optimizeDeps:\n pagesOptimizeEntries.length > 0 ? { entries: pagesOptimizeEntries } : undefined,\n build: {\n manifest: true,\n ssrManifest: true,\n ...withBuildBundlerOptions(viteMajorVersion, {\n input: { index: VIRTUAL_CLIENT_ENTRY },\n output: getClientOutputConfigForVite(viteMajorVersion),\n treeshake: clientTreeshakeConfig,\n }),\n },\n },\n };\n } else if (!isSSR && !getBuildBundlerOptions(config.build)?.input) {\n // Plain Pages Router (Node): define client + ssr environments so\n // createBuilder + buildApp() produces both dist/client and\n // dist/server/entry.js. Without this, buildApp() only sees the\n // default client environment and never builds the server entry.\n // Guard with !isSSR and no explicit input so legacy vite.build()\n // calls that specify their own input (tests, hybrid build step)\n // still work via the single-build path — injecting environments\n // alongside an explicit build input conflicts with the caller's intent.\n viteConfig.environments = {\n client: {\n consumer: \"client\",\n optimizeDeps:\n pagesOptimizeEntries.length > 0 ? { entries: pagesOptimizeEntries } : undefined,\n build: {\n outDir: \"dist/client\",\n manifest: true,\n ssrManifest: true,\n ...withBuildBundlerOptions(viteMajorVersion, {\n input: { index: VIRTUAL_CLIENT_ENTRY },\n output: getClientOutputConfigForVite(viteMajorVersion),\n treeshake: clientTreeshakeConfig,\n }),\n },\n },\n ssr: {\n resolve: {\n external: [\"react\", \"react-dom\", \"react-dom/server\"],\n noExternal: true as const,\n },\n build: {\n outDir: \"dist/server\",\n ...withBuildBundlerOptions(viteMajorVersion, {\n input: { index: VIRTUAL_SERVER_ENTRY },\n output: {\n entryFileNames: \"entry.js\",\n },\n }),\n },\n },\n };\n }\n\n if (pagesOptimizeEntries.length > 0 && !hasCloudflarePlugin) {\n viteConfig.optimizeDeps = {\n ...viteConfig.optimizeDeps,\n entries: pagesOptimizeEntries,\n };\n }\n\n return viteConfig;\n },\n\n configResolved(config) {\n // Detect double React plugin registration. When vinext auto-injects\n // @vitejs/plugin-react AND the user also registers it manually, the\n // React transform / refresh pipeline runs twice.\n if (reactPluginPromise) {\n // Assumes @vitejs/plugin-react top-level plugin names continue to use\n // the vite:react* prefix across supported versions.\n const reactRootPlugins = config.plugins.filter(\n (p: unknown) =>\n p &&\n typeof p === \"object\" &&\n \"name\" in p &&\n typeof p.name === \"string\" &&\n p.name.startsWith(\"vite:react\"),\n );\n const counts = new Map<string, number>();\n for (const plugin of reactRootPlugins) {\n counts.set(plugin.name, (counts.get(plugin.name) ?? 0) + 1);\n }\n const hasDuplicateReactPlugin = [...counts.values()].some((count) => count > 1);\n if (hasDuplicateReactPlugin) {\n throw new Error(\n \"[vinext] Duplicate @vitejs/plugin-react detected.\\n\" +\n \" vinext auto-registers @vitejs/plugin-react by default.\\n\" +\n \" Your config also registers it manually, which duplicates React transforms.\\n\\n\" +\n \" Fix: remove the explicit react() call from your plugins array.\\n\" +\n \" Or: pass react: false to vinext() if you want to configure react() yourself.\",\n );\n }\n }\n\n // Detect double RSC plugin registration. When vinext auto-injects\n // @vitejs/plugin-rsc AND the user also registers it manually, the\n // RSC transform pipeline runs twice — doubling build time.\n // Rather than trying to magically fix this at runtime, fail fast\n // with a clear error telling the user how to fix their config.\n if (rscPluginPromise) {\n // Count top-level RSC plugins (name === \"rsc\") — each call to\n // the rsc() factory produces exactly one plugin with this name.\n const rscRootPlugins = config.plugins.filter(\n (p: unknown) => p && typeof p === \"object\" && \"name\" in p && p.name === \"rsc\",\n );\n if (rscRootPlugins.length > 1) {\n throw new Error(\n \"[vinext] Duplicate @vitejs/plugin-rsc detected.\\n\" +\n \" vinext auto-registers @vitejs/plugin-rsc when app/ is detected.\\n\" +\n \" Your config also registers it manually, which doubles build time.\\n\\n\" +\n \" Fix: remove the explicit rsc() call from your plugins array.\\n\" +\n \" Or: pass rsc: false to vinext() if you want to configure rsc() yourself.\",\n );\n }\n }\n\n // Fail the build when targeting Cloudflare Workers without the\n // cloudflare() plugin. Without it, wrangler's esbuild can't resolve\n // virtual:vinext-rsc-entry and produces a cryptic error. (#325)\n if (\n config.command === \"build\" &&\n !hasCloudflarePlugin &&\n !hasNitroPlugin &&\n hasWranglerConfig(root) &&\n !options.disableAppRouter\n ) {\n throw new Error(\n formatMissingCloudflarePluginError({\n isAppRouter: hasAppDir,\n configFile: config.configFile,\n }),\n );\n }\n },\n\n resolveId: {\n // Hook filter: only invoke JS for next/* imports and virtual:vinext-* modules.\n // Matches \"next/navigation\", \"next/router.js\", \"virtual:vinext-rsc-entry\",\n // and \\0-prefixed re-imports from @vitejs/plugin-rsc.\n filter: {\n id: /(?:next\\/|virtual:vinext-)/,\n },\n handler(id) {\n // Strip \\0 prefix if present — @vitejs/plugin-rsc's generated\n // browser entry imports our virtual module using the already-resolved\n // ID (with \\0 prefix). We need to re-resolve it so the client\n // environment's import-analysis can find it.\n const cleanId = id.startsWith(\"\\0\") ? id.slice(1) : id;\n\n // Pages Router virtual modules\n if (cleanId === VIRTUAL_SERVER_ENTRY) return RESOLVED_SERVER_ENTRY;\n if (cleanId === VIRTUAL_CLIENT_ENTRY) return RESOLVED_CLIENT_ENTRY;\n if (\n cleanId.endsWith(\"/\" + VIRTUAL_SERVER_ENTRY) ||\n cleanId.endsWith(\"\\\\\" + VIRTUAL_SERVER_ENTRY)\n ) {\n return RESOLVED_SERVER_ENTRY;\n }\n if (\n cleanId.endsWith(\"/\" + VIRTUAL_CLIENT_ENTRY) ||\n cleanId.endsWith(\"\\\\\" + VIRTUAL_CLIENT_ENTRY)\n ) {\n return RESOLVED_CLIENT_ENTRY;\n }\n // App Router virtual modules\n if (cleanId === VIRTUAL_RSC_ENTRY) return RESOLVED_RSC_ENTRY;\n if (cleanId === VIRTUAL_APP_SSR_ENTRY) return RESOLVED_APP_SSR_ENTRY;\n if (cleanId === VIRTUAL_APP_BROWSER_ENTRY) return RESOLVED_APP_BROWSER_ENTRY;\n if (cleanId.startsWith(VIRTUAL_GOOGLE_FONTS + \"?\")) {\n return RESOLVED_VIRTUAL_GOOGLE_FONTS + cleanId.slice(VIRTUAL_GOOGLE_FONTS.length);\n }\n if (\n cleanId.endsWith(\"/\" + VIRTUAL_RSC_ENTRY) ||\n cleanId.endsWith(\"\\\\\" + VIRTUAL_RSC_ENTRY)\n ) {\n return RESOLVED_RSC_ENTRY;\n }\n if (\n cleanId.endsWith(\"/\" + VIRTUAL_APP_SSR_ENTRY) ||\n cleanId.endsWith(\"\\\\\" + VIRTUAL_APP_SSR_ENTRY)\n ) {\n return RESOLVED_APP_SSR_ENTRY;\n }\n if (\n cleanId.endsWith(\"/\" + VIRTUAL_APP_BROWSER_ENTRY) ||\n cleanId.endsWith(\"\\\\\" + VIRTUAL_APP_BROWSER_ENTRY)\n ) {\n return RESOLVED_APP_BROWSER_ENTRY;\n }\n if (\n cleanId.includes(\"/\" + VIRTUAL_GOOGLE_FONTS + \"?\") ||\n cleanId.includes(\"\\\\\" + VIRTUAL_GOOGLE_FONTS + \"?\")\n ) {\n const queryIndex = cleanId.indexOf(VIRTUAL_GOOGLE_FONTS + \"?\");\n return (\n RESOLVED_VIRTUAL_GOOGLE_FONTS +\n cleanId.slice(queryIndex + VIRTUAL_GOOGLE_FONTS.length)\n );\n }\n },\n },\n\n async load(id) {\n // Pages Router virtual modules\n if (id === RESOLVED_SERVER_ENTRY) {\n return await generateServerEntry();\n }\n if (id === RESOLVED_CLIENT_ENTRY) {\n return await generateClientEntry();\n }\n // App Router virtual modules\n if (id === RESOLVED_RSC_ENTRY && hasAppDir) {\n const routes = await appRouter(appDir, nextConfig?.pageExtensions, fileMatcher);\n const metaRoutes = scanMetadataFiles(appDir);\n // Check for global-error.tsx at app root\n const globalErrorPath = findFileWithExts(appDir, \"global-error\", fileMatcher);\n return generateRscEntry(\n appDir,\n routes,\n middlewarePath,\n metaRoutes,\n globalErrorPath,\n nextConfig?.basePath,\n nextConfig?.trailingSlash,\n {\n redirects: nextConfig?.redirects,\n rewrites: nextConfig?.rewrites,\n headers: nextConfig?.headers,\n allowedOrigins: nextConfig?.serverActionsAllowedOrigins,\n allowedDevOrigins: nextConfig?.allowedDevOrigins,\n bodySizeLimit: nextConfig?.serverActionsBodySizeLimit,\n i18n: nextConfig?.i18n,\n hasPagesDir,\n },\n instrumentationPath,\n );\n }\n if (id === RESOLVED_APP_SSR_ENTRY && hasAppDir) {\n return generateSsrEntry(hasPagesDir);\n }\n if (id === RESOLVED_APP_BROWSER_ENTRY && hasAppDir) {\n return generateBrowserEntry();\n }\n if (id.startsWith(RESOLVED_VIRTUAL_GOOGLE_FONTS + \"?\")) {\n return generateGoogleFontsVirtualModule(id, _fontGoogleShimPath);\n }\n },\n },\n // Stub node:async_hooks in client builds — see src/plugins/async-hooks-stub.ts\n asyncHooksStubPlugin,\n createInstrumentationClientTransformPlugin(() => instrumentationClientPath),\n // Dedup client references from RSC proxy modules — see src/plugins/client-reference-dedup.ts\n ...(options.experimental?.clientReferenceDedup ? [clientReferenceDedupPlugin()] : []),\n // Proxy plugin for @mdx-js/rollup. The real MDX plugin is created lazily\n // during vinext:config's config() (when MDX files are detected), but\n // plugins returned from config() hooks run too late in the pipeline —\n // after vite:import-analysis. This top-level proxy with enforce:\"pre\"\n // ensures MDX transforms run at the correct stage. Both vinext:config\n // and this proxy are enforce:\"pre\", and vinext:config comes first in\n // the array, so mdxDelegate is already set when this proxy's hooks fire.\n {\n name: \"vinext:mdx\",\n enforce: \"pre\",\n config(config, env) {\n if (!mdxDelegate?.config) return;\n const hook = mdxDelegate.config;\n const fn = typeof hook === \"function\" ? hook : hook.handler;\n return fn.call(this, config, env);\n },\n async transform(code, id, options) {\n // Skip ?raw and other query imports — @mdx-js/rollup ignores the query\n // and would compile the file as MDX instead of returning raw text.\n if (id.includes(\"?\")) return;\n // Case-insensitive extension check for cross-platform compatibility\n // (Windows/macOS case-insensitive, Linux case-sensitive)\n if (!id.toLowerCase().endsWith(\".mdx\")) return;\n\n const delegate = mdxDelegate ?? (await ensureMdxDelegate(\"on-demand\"));\n if (delegate?.transform) {\n const hook = delegate.transform;\n const transform = typeof hook === \"function\" ? hook : hook.handler;\n return transform.call(this, code, id, options);\n }\n\n if (!hasUserMdxPlugin) {\n throw new Error(\n `[vinext] Encountered MDX module ${id} but no MDX plugin is configured. ` +\n `Install @mdx-js/rollup or register an MDX plugin manually.`,\n );\n }\n },\n },\n // Shim React canary/experimental APIs (ViewTransition, addTransitionType)\n // that exist in Next.js's bundled React canary but not in stable React 19.\n // Provides graceful no-op fallbacks so projects using these APIs degrade\n // instead of crashing with \"does not provide an export named 'ViewTransition'\".\n {\n name: \"vinext:react-canary\",\n enforce: \"pre\",\n\n resolveId(id) {\n if (id === \"virtual:vinext-react-canary\") return \"\\0virtual:vinext-react-canary\";\n },\n\n load(id) {\n if (id === \"\\0virtual:vinext-react-canary\") {\n return [\n `export * from \"react\";`,\n `export { default } from \"react\";`,\n `import * as _React from \"react\";`,\n `export const ViewTransition = _React.ViewTransition || function ViewTransition({ children }) { return children; };`,\n `export const addTransitionType = _React.addTransitionType || function addTransitionType() {};`,\n ].join(\"\\n\");\n }\n },\n\n transform(code, id) {\n // Only transform user source files, not node_modules or virtual modules\n if (id.includes(\"node_modules\")) return null;\n if (id.startsWith(\"\\0\")) return null;\n if (!/\\.(tsx?|jsx?|mjs)$/.test(id)) return null;\n\n // Quick check: does this file reference canary APIs and import from \"react\"?\n if (\n !(code.includes(\"ViewTransition\") || code.includes(\"addTransitionType\")) ||\n !/from\\s+['\"]react['\"]/.test(code)\n ) {\n return null;\n }\n\n // Only rewrite if the import actually destructures a canary API\n const canaryImportRegex =\n /import\\s*\\{[^}]*(ViewTransition|addTransitionType)[^}]*\\}\\s*from\\s*['\"]react['\"]/;\n if (!canaryImportRegex.test(code)) return null;\n\n // Rewrite all `from \"react\"` / `from 'react'` to use the canary shim.\n // This is safe because the virtual module re-exports everything from\n // react, so non-canary imports continue to work.\n const result = code.replace(/from\\s*['\"]react['\"]/g, 'from \"virtual:vinext-react-canary\"');\n if (result !== code) {\n return { code: result, map: null };\n }\n return null;\n },\n },\n {\n name: \"vinext:pages-router\",\n\n // HMR: trigger full-reload for Pages Router page changes.\n // Even with @vitejs/plugin-react providing React Fast Refresh,\n // the Pages Router injects hydration via inline <script type=\"module\">\n // which may not be tracked in Vite's module graph. Explicitly\n // sending full-reload ensures changes are always reflected in\n // the browser.\n hotUpdate(options: { file: string; server: ViteDevServer; modules: unknown[] }) {\n if (!hasPagesDir || hasAppDir) return;\n if (options.file.startsWith(pagesDir) && fileMatcher.extensionRegex.test(options.file)) {\n options.server.environments.client.hot.send({ type: \"full-reload\" });\n return [];\n }\n },\n\n configureServer(server: ViteDevServer) {\n // Watch pages directory for file additions/removals to invalidate route cache.\n const pageExtensions = fileMatcher.extensionRegex;\n\n // Build a long-lived ModuleRunner for loading all Pages Router modules\n // (middleware, API routes, SSR page rendering) on every request.\n //\n // We must NOT use server.ssrLoadModule() here: when @cloudflare/vite-plugin\n // is present its environments replace the SSR transport, causing\n // SSRCompatModuleRunner to crash with:\n // TypeError: Cannot read properties of undefined (reading 'outsideEmitter')\n // on the very first request.\n //\n // createDirectRunner() builds a runner on environment.fetchModule() which\n // is a plain async method — safe with all plugin combinations, including\n // @cloudflare/vite-plugin.\n //\n // The runner is created lazily on first use so that all environments are\n // fully registered before we inspect them. We prefer \"ssr\", then any\n // non-\"rsc\" environment, then whatever is available.\n let pagesRunner: import(\"vite/module-runner\").ModuleRunner | null = null;\n function getPagesRunner() {\n if (!pagesRunner) {\n const env =\n server.environments[\"ssr\"] ??\n Object.values(server.environments).find((e) => e !== server.environments[\"rsc\"]) ??\n Object.values(server.environments)[0];\n pagesRunner = createDirectRunner(env);\n }\n return pagesRunner;\n }\n\n /**\n * Invalidate the virtual RSC entry module in Vite's module graph.\n *\n * The App Router route table is baked into the virtual RSC entry\n * at generation time. When routes are added or removed, clearing\n * the route cache alone is not enough: the virtual module must\n * also be invalidated so Vite re-calls the load() hook to\n * regenerate the entry with the updated route table.\n */\n function invalidateRscEntryModule() {\n const rscEnv = server.environments[\"rsc\"];\n if (!rscEnv) return;\n const mod = rscEnv.moduleGraph.getModuleById(RESOLVED_RSC_ENTRY);\n if (mod) {\n rscEnv.moduleGraph.invalidateModule(mod);\n rscEnv.hot.send({ type: \"full-reload\" });\n }\n }\n\n server.watcher.on(\"add\", (filePath: string) => {\n if (hasPagesDir && filePath.startsWith(pagesDir) && pageExtensions.test(filePath)) {\n invalidateRouteCache(pagesDir);\n }\n if (hasAppDir && filePath.startsWith(appDir) && pageExtensions.test(filePath)) {\n invalidateAppRouteCache();\n invalidateRscEntryModule();\n }\n });\n server.watcher.on(\"unlink\", (filePath: string) => {\n if (hasPagesDir && filePath.startsWith(pagesDir) && pageExtensions.test(filePath)) {\n invalidateRouteCache(pagesDir);\n }\n if (hasAppDir && filePath.startsWith(appDir) && pageExtensions.test(filePath)) {\n invalidateAppRouteCache();\n invalidateRscEntryModule();\n }\n });\n\n // ── Dev request origin check ─────────────────────────────────────\n // Registered directly (not in the returned function) so it runs\n // BEFORE Vite's built-in middleware. This ensures all requests\n // (including /@*, /__vite*, /node_modules* paths) are validated\n // before Vite serves any content.\n server.middlewares.use((req, res, next) => {\n const blockReason = validateDevRequest(\n {\n origin: req.headers.origin as string | undefined,\n host: req.headers.host,\n \"x-forwarded-host\": req.headers[\"x-forwarded-host\"] as string | undefined,\n \"sec-fetch-site\": req.headers[\"sec-fetch-site\"] as string | undefined,\n \"sec-fetch-mode\": req.headers[\"sec-fetch-mode\"] as string | undefined,\n },\n nextConfig?.allowedDevOrigins,\n );\n if (blockReason) {\n console.warn(`[vinext] Blocked dev request: ${blockReason} (${req.url})`);\n res.writeHead(403, { \"Content-Type\": \"text/plain\" });\n res.end(\"Forbidden\");\n return;\n }\n next();\n });\n\n // Return a function to register middleware AFTER Vite's built-in middleware\n return () => {\n // Run instrumentation.ts register() if present (once at server startup).\n // Must be inside the returned function so that all environments are\n // fully registered before getPagesRunner() inspects them.\n //\n // App Router: register() is baked into the generated RSC entry as a\n // top-level await, so it runs inside the Worker process (or RSC Vite\n // environment) — the same process as request handling. Calling\n // runInstrumentation() here too would run it a second time in the host\n // process, which is wrong when @cloudflare/vite-plugin is present.\n //\n // Pages Router prod: register() is baked into generateServerEntry() as\n // a top-level await, so it runs inside the Worker bundle — the same\n // process as request handling. configureServer() is never called during\n // a prod build, so there is no double-invocation risk there either.\n //\n // We pass getPagesRunner() (createDirectRunner) rather than server so\n // that this is safe when @cloudflare/vite-plugin is present. That\n // plugin replaces the SSR environment's hot channel, causing\n // server.ssrLoadModule() to crash with outsideEmitter. The runner\n // calls environment.fetchModule() directly and never touches the hot\n // channel, making it safe with all Vite plugin combinations.\n if (instrumentationPath && !hasAppDir) {\n runInstrumentation(getPagesRunner(), instrumentationPath).catch((err) => {\n console.error(\"[vinext] Instrumentation error:\", err);\n });\n }\n // App Router request logging in dev server\n //\n // For App Router, the RSC plugin handles requests internally.\n // We install a timing middleware here that:\n // 1. Intercepts writeHead() to pluck the X-Vinext-Timing header\n // (compileMs,renderMs) that the RSC entry attaches before\n // it is flushed to the client.\n // 2. Logs the full request after res finishes, using those timings.\n if (hasAppDir) {\n server.middlewares.use((req, res, next) => {\n const url = req.url ?? \"/\";\n // Skip Vite internals, HMR, and static assets.\n // Do NOT skip .rsc-suffixed URLs or RSC wire requests (Accept: text/x-component)\n // — those are soft navigations and should be logged like any other page request.\n const [pathname] = url.split(\"?\");\n if (\n url.startsWith(\"/@\") ||\n url.startsWith(\"/__vite\") ||\n url.startsWith(\"/node_modules\") ||\n (url.includes(\".\") && !pathname.endsWith(\".html\") && !pathname.endsWith(\".rsc\"))\n ) {\n return next();\n }\n const _reqStart = now();\n let _compileMs: number | undefined;\n let _renderMs: number | undefined;\n\n // Intercept setHeader and writeHead so we can strip X-Vinext-Timing\n // before it reaches the client and capture the compile/render split.\n // The RSC plugin may set headers either way depending on its version.\n // Parse the three-part X-Vinext-Timing header:\n // \"handlerStart,inHandlerCompileMs,renderMs\"\n //\n // True compile time = time the RSC plugin spent loading/transforming\n // modules before our handler code ran, plus any in-handler work before\n // renderToReadableStream. Concretely:\n // compileMs = (handlerStart - _reqStart) + inHandlerCompileMs\n // renderMs = renderMs from header, or -1 for RSC-only (soft-nav)\n // responses where rendering is not measured in the handler.\n // In that case the middleware computes render time as\n // totalMs - compileMs.\n //\n // handlerStart is performance.now() recorded at the very top of\n // _handleRequest in the generated RSC entry. _reqStart is recorded\n // here in the Node middleware, one stack frame before the RSC plugin\n // loads the module. The gap between them is exactly the Vite\n // compile/transform cost.\n function _parseTiming(raw: unknown) {\n const [handlerStart, inHandlerCompileMs, renderMs] = String(raw)\n .split(\",\")\n .map((v) => Number(v));\n if (\n !Number.isNaN(handlerStart) &&\n !Number.isNaN(inHandlerCompileMs) &&\n inHandlerCompileMs !== -1\n ) {\n _compileMs =\n Math.max(0, Math.round(handlerStart - _reqStart)) + inHandlerCompileMs;\n }\n if (!Number.isNaN(renderMs) && renderMs !== -1) {\n _renderMs = renderMs;\n }\n }\n\n const _origSetHeader = res.setHeader.bind(res);\n res.setHeader = function (name, value) {\n if (name.toLowerCase() === \"x-vinext-timing\") {\n _parseTiming(value);\n return res; // drop the header — don't forward to client\n }\n return _origSetHeader(name, value);\n };\n\n const _origWriteHead = res.writeHead.bind(res);\n // oxlint-disable-next-line typescript/no-explicit-any\n res.writeHead = function (statusCode, ...args: any[]) {\n // Normalise the optional headers argument (may be reason, headers object, or both).\n let headers: Record<string, unknown> | undefined;\n const [reasonOrHeaders, maybeHeaders] = args;\n if (typeof reasonOrHeaders === \"string\") {\n headers = maybeHeaders;\n } else {\n headers = reasonOrHeaders;\n }\n\n // Pull timing out of the headers object when present.\n if (headers && typeof headers === \"object\" && !Array.isArray(headers)) {\n const timingKey = Object.keys(headers).find(\n (k) => k.toLowerCase() === \"x-vinext-timing\",\n );\n if (timingKey) {\n _parseTiming(headers[timingKey]);\n delete headers[timingKey];\n }\n }\n\n return _origWriteHead(statusCode, ...args);\n };\n\n res.on(\"finish\", () => {\n // Strip .rsc suffix — it's an internal RSC protocol detail,\n // not part of the actual page path the user navigated to.\n const logUrl = url.replace(/\\.rsc(\\?|$)/, \"$1\");\n const totalMs = now() - _reqStart;\n\n // For RSC-only responses (soft nav), renderMs is -1 (sentinel meaning\n // \"not measured in the handler\"). Compute it as totalMs - compileMs,\n // which is how long the RSC stream took to fully flush to the client —\n // matching what Next.js shows for soft navigations.\n const resolvedRenderMs =\n _renderMs !== undefined\n ? _renderMs\n : _compileMs !== undefined\n ? Math.max(0, Math.round(totalMs - _compileMs))\n : undefined;\n\n logRequest({\n method: req.method ?? \"GET\",\n url: logUrl,\n status: res.statusCode,\n totalMs,\n compileMs: _compileMs,\n renderMs: resolvedRenderMs,\n });\n });\n\n next();\n });\n }\n\n server.middlewares.use(async (req, res, next) => {\n try {\n let url: string = req.url ?? \"/\";\n\n // If no pages directory, skip this middleware entirely\n // (app router is handled by @vitejs/plugin-rsc's built-in middleware)\n if (!hasPagesDir) return next();\n\n // Skip Vite internal requests and static files\n if (\n url.startsWith(\"/@\") ||\n url.startsWith(\"/__vite\") ||\n url.startsWith(\"/node_modules\")\n ) {\n return next();\n }\n\n // Skip .rsc requests — those are for the App Router RSC handler\n if (url.split(\"?\")[0].endsWith(\".rsc\")) {\n return next();\n }\n\n // ── Cross-origin request protection (defense-in-depth) ──────\n // The pre-Vite middleware above already blocks cross-origin\n // requests before Vite serves any content. This second check\n // guards the Pages Router handler specifically, in case the\n // middleware ordering changes or new middleware is added between\n // the two. Both calls use the same validateDevRequest() function.\n const blockReason = validateDevRequest(\n {\n origin: req.headers.origin as string | undefined,\n host: req.headers.host,\n \"x-forwarded-host\": req.headers[\"x-forwarded-host\"] as string | undefined,\n \"sec-fetch-site\": req.headers[\"sec-fetch-site\"] as string | undefined,\n \"sec-fetch-mode\": req.headers[\"sec-fetch-mode\"] as string | undefined,\n },\n nextConfig?.allowedDevOrigins,\n );\n if (blockReason) {\n console.warn(`[vinext] Blocked dev request: ${blockReason} (${url})`);\n res.writeHead(403, { \"Content-Type\": \"text/plain\" });\n res.end(\"Forbidden\");\n return;\n }\n\n // ── Image optimization passthrough (dev mode) ─────────────\n // In dev, redirect to the original asset URL so Vite serves it.\n if (url.split(\"?\")[0] === \"/_vinext/image\") {\n const imgParams = new URLSearchParams(url.split(\"?\")[1] ?? \"\");\n const rawImgUrl = imgParams.get(\"url\");\n // Normalize backslashes: browsers and the URL constructor treat\n // /\\evil.com as //evil.com, bypassing the // check.\n const imgUrl = rawImgUrl?.replaceAll(\"\\\\\", \"/\") ?? null;\n // Allowlist: must start with \"/\" but not \"//\" — blocks absolute\n // URLs, protocol-relative, backslash variants, and exotic schemes.\n // Also block internal Vite paths (/@*, /__vite*, /node_modules*)\n // to prevent redirecting to dev server endpoints.\n if (\n !imgUrl ||\n !imgUrl.startsWith(\"/\") ||\n imgUrl.startsWith(\"//\") ||\n imgUrl.startsWith(\"/@\") ||\n imgUrl.startsWith(\"/__vite\") ||\n imgUrl.startsWith(\"/node_modules\")\n ) {\n res.writeHead(400);\n res.end(!rawImgUrl ? \"Missing url parameter\" : \"Only relative URLs allowed\");\n return;\n }\n // Validate the constructed URL's origin hasn't changed (defense in depth).\n const resolvedImg = new URL(imgUrl, `http://${req.headers.host || \"localhost\"}`);\n if (resolvedImg.origin !== `http://${req.headers.host || \"localhost\"}`) {\n res.writeHead(400);\n res.end(\"Only relative URLs allowed\");\n return;\n }\n const encodedLocation = resolvedImg.pathname + resolvedImg.search;\n res.writeHead(302, { Location: encodedLocation });\n res.end();\n return;\n }\n\n // Vite's built-in middleware may rewrite \"/\" to \"/index.html\".\n // Normalize it back so our router can match correctly.\n const rawPathname = url.split(\"?\")[0];\n if (rawPathname.endsWith(\"/index.html\")) {\n url = url.replace(\"/index.html\", \"/\");\n } else if (rawPathname.endsWith(\".html\")) {\n // Strip .html extensions (e.g. \"/about.html\" -> \"/about\")\n url = url.replace(/\\.html(?=\\?|$)/, \"\");\n }\n\n // Skip requests for files with extensions (static assets)\n let pathname = url.split(\"?\")[0];\n if (pathname.includes(\".\") && !pathname.endsWith(\".html\")) {\n return next();\n }\n\n // Guard against protocol-relative URL open redirects.\n // Normalize backslashes first: browsers treat /\\ as // in URL\n // context. Check the RAW pathname before normalizePath so the\n // guard fires before normalizePath collapses //.\n pathname = pathname.replaceAll(\"\\\\\", \"/\");\n if (pathname.startsWith(\"//\")) {\n res.writeHead(404);\n res.end(\"404 Not Found\");\n return;\n }\n\n // Normalize the pathname to prevent path-confusion attacks.\n // decodeURIComponent prevents /%61dmin bypassing /admin matchers.\n // normalizePath collapses // and resolves . / .. segments.\n try {\n pathname = normalizePath(normalizePathnameForRouteMatchStrict(pathname));\n } catch {\n // Malformed percent-encoding (e.g. /%E0%A4%A) — return 400 instead of crashing.\n res.writeHead(400);\n res.end(\"Bad Request\");\n return;\n }\n\n // Strip basePath prefix from URL for route matching.\n // All internal routing uses basePath-free paths.\n //\n // NOTE: When basePath is set, we also set Vite's `base` config to\n // `basePath + \"/\"`. Vite's connect middleware stack strips the base\n // prefix from req.url before passing it to our middleware, so the\n // URL will already lack the basePath prefix. We still attempt to\n // strip it (for robustness) but don't reject paths that don't start\n // with basePath — Vite has already done the filtering.\n const bp = nextConfig?.basePath ?? \"\";\n if (bp && pathname.startsWith(bp)) {\n const stripped = pathname.slice(bp.length) || \"/\";\n const qs = url.includes(\"?\") ? url.slice(url.indexOf(\"?\")) : \"\";\n url = stripped + qs;\n pathname = stripped;\n }\n\n // Normalize trailing slash based on next.config.js trailingSlash setting.\n // Redirect to the canonical form if needed.\n if (\n nextConfig &&\n pathname !== \"/\" &&\n pathname !== \"/api\" &&\n !pathname.startsWith(\"/api/\")\n ) {\n const hasTrailing = pathname.endsWith(\"/\");\n if (nextConfig.trailingSlash && !hasTrailing) {\n // trailingSlash: true — redirect /about → /about/\n const qs = url.includes(\"?\") ? url.slice(url.indexOf(\"?\")) : \"\";\n const dest = bp + pathname + \"/\" + qs;\n res.writeHead(308, { Location: dest });\n res.end();\n return;\n } else if (!nextConfig.trailingSlash && hasTrailing) {\n // trailingSlash: false (default) — redirect /about/ → /about\n const qs = url.includes(\"?\") ? url.slice(url.indexOf(\"?\")) : \"\";\n const dest = bp + pathname.replace(/\\/+$/, \"\") + qs;\n res.writeHead(308, { Location: dest });\n res.end();\n return;\n }\n }\n\n // When @cloudflare/vite-plugin is present, delegate the entire\n // Pages Router request pipeline to the Worker/miniflare side.\n // That keeps middleware, headers, redirects, rewrites, API\n // routes, and rendering in one place instead of mutating the\n // host request and forwarding post-middleware state downstream.\n if (hasCloudflarePlugin) return next();\n\n // Snapshot of req.headers before middleware runs. Used for both\n // preMiddlewareReqCtx and the middleware Request itself. Intentionally\n // captured once here — applyRequestHeadersToNodeRequest() mutates\n // req.headers later, but by then this Headers object is no longer read.\n const nodeRequestHeaders = new Headers(\n Object.fromEntries(\n Object.entries(req.headers)\n .filter(([, v]) => v !== undefined)\n .map(([k, v]) => [k, Array.isArray(v) ? v.join(\", \") : String(v)]),\n ),\n );\n\n const requestOrigin = `http://${req.headers.host || \"localhost\"}`;\n const preMiddlewareReqUrl = new URL(url, requestOrigin);\n const preMiddlewareReqCtx: RequestContext = requestContextFromRequest(\n new Request(preMiddlewareReqUrl, { headers: nodeRequestHeaders }),\n );\n\n // Config redirects run before middleware, but still match against\n // the original normalized pathname and request headers/cookies.\n if (nextConfig?.redirects.length) {\n const redirected = applyRedirects(\n pathname,\n res,\n nextConfig.redirects,\n preMiddlewareReqCtx,\n nextConfig.basePath ?? \"\",\n );\n if (redirected) return;\n }\n\n const applyRequestHeadersToNodeRequest = (nextRequestHeaders: Headers) => {\n for (const key of Object.keys(req.headers)) {\n delete req.headers[key];\n }\n for (const [key, value] of nextRequestHeaders) {\n req.headers[key] = value;\n }\n };\n\n let middlewareRequestHeaders: Headers | null = null;\n let deferredMwResponseHeaders: [string, string][] | null = null;\n\n const applyDeferredMwHeaders = () => {\n if (deferredMwResponseHeaders) {\n for (const [key, value] of deferredMwResponseHeaders) {\n res.appendHeader(key, value);\n }\n }\n };\n\n // Run middleware.ts if present\n if (middlewarePath) {\n // Only trust X-Forwarded-Proto when behind a trusted proxy\n const devTrustProxy =\n process.env.VINEXT_TRUST_PROXY === \"1\" ||\n (process.env.VINEXT_TRUSTED_HOSTS ?? \"\").split(\",\").some((h) => h.trim());\n const rawProto = devTrustProxy\n ? String(req.headers[\"x-forwarded-proto\"] || \"\")\n .split(\",\")[0]\n .trim()\n : \"\";\n const mwProto = rawProto === \"https\" || rawProto === \"http\" ? rawProto : \"http\";\n const origin = `${mwProto}://${req.headers.host || \"localhost\"}`;\n const middlewareRequest = new Request(new URL(url, origin), {\n method: req.method,\n headers: nodeRequestHeaders,\n });\n const result = await runMiddleware(\n getPagesRunner(),\n middlewarePath,\n middlewareRequest,\n nextConfig?.i18n,\n nextConfig?.basePath,\n );\n\n // Settle waitUntil promises — no ctx.waitUntil() in dev, but\n // promises must still run for parity with prod (session sync, telemetry, etc.)\n if (result.waitUntilPromises?.length) {\n void Promise.allSettled(result.waitUntilPromises);\n }\n\n if (!result.continue) {\n if (result.redirectUrl) {\n const redirectHeaders: Record<string, string | string[]> = {\n Location: result.redirectUrl,\n };\n if (result.responseHeaders) {\n for (const [key, value] of result.responseHeaders) {\n const existing = redirectHeaders[key];\n if (existing === undefined) {\n redirectHeaders[key] = value;\n } else if (Array.isArray(existing)) {\n existing.push(value);\n } else {\n redirectHeaders[key] = [existing, value];\n }\n }\n }\n res.writeHead(result.redirectStatus ?? 307, redirectHeaders);\n res.end();\n return;\n }\n if (result.response) {\n res.statusCode = result.response.status;\n for (const [key, value] of result.response.headers) {\n res.appendHeader(key, value);\n }\n const body = Buffer.from(await result.response.arrayBuffer());\n res.end(body);\n return;\n }\n }\n\n // Apply middleware response headers. Unpack\n // x-middleware-request-* headers into req.headers so\n // config has/missing conditions and downstream handlers\n // see middleware-modified cookies and headers.\n if (result.responseHeaders) {\n const currentRequestHeaders = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (Array.isArray(value)) {\n currentRequestHeaders.set(key, value.join(\", \"));\n } else if (value !== undefined) {\n currentRequestHeaders.set(key, value);\n }\n }\n\n middlewareRequestHeaders = buildRequestHeadersFromMiddlewareResponse(\n currentRequestHeaders,\n result.responseHeaders,\n );\n\n if (middlewareRequestHeaders && !hasAppDir) {\n applyRequestHeadersToNodeRequest(middlewareRequestHeaders);\n }\n\n if (hasAppDir) {\n // Hybrid app+pages: defer response headers. They'll be\n // applied to res for Pages routes or forwarded to the RSC\n // entry (via x-vinext-mw-ctx) for App Router routes.\n deferredMwResponseHeaders = [];\n for (const [key, value] of result.responseHeaders) {\n if (!key.startsWith(\"x-middleware-\")) {\n deferredMwResponseHeaders.push([key, value]);\n }\n }\n } else {\n for (const [key, value] of result.responseHeaders) {\n if (!key.startsWith(\"x-middleware-\")) {\n res.appendHeader(key, value);\n }\n }\n }\n }\n\n // Apply middleware rewrite (URL and optional status code)\n if (result.rewriteUrl) {\n url = result.rewriteUrl;\n // Write the rewritten URL back onto req.url so every subsequent\n // handler in the connect chain sees the correct path. The local\n // `url` variable is only visible within this handler — anything\n // further down the chain (Vite's built-in middleware, the\n // Cloudflare plugin's handler, or any other connect middleware)\n // reads req.url directly. Without this, a middleware rewrite\n // would be invisible to those handlers and the original URL\n // would be dispatched instead.\n req.url = url;\n }\n if (result.rewriteStatus) {\n req.__vinextRewriteStatus = result.rewriteStatus;\n }\n\n // Forward middleware context to the RSC entry so it can\n // populate _mwCtx without re-running the middleware function.\n // This prevents double execution in hybrid app+pages dev mode.\n if (hasAppDir) {\n const mwCtxEntries: [string, string][] = [];\n if (result.responseHeaders) {\n for (const [key, value] of result.responseHeaders) {\n // Exclude control headers that runMiddleware already\n // consumed — matches the RSC entry's inline filtering.\n if (key !== \"x-middleware-next\" && key !== \"x-middleware-rewrite\") {\n mwCtxEntries.push([key, value]);\n }\n }\n }\n req.headers[\"x-vinext-mw-ctx\"] = JSON.stringify({\n h: mwCtxEntries,\n s: result.rewriteStatus ?? null,\n r: result.rewriteUrl ?? null,\n });\n }\n }\n\n // Build request context once for has/missing condition checks\n // for config rules that execute after middleware (rewrites).\n // Convert Node.js IncomingMessage headers to a Web Request for\n // requestContextFromRequest(), which uses the standard Web API.\n const reqUrl = new URL(url, requestOrigin);\n const reqCtxHeaders = middlewareRequestHeaders ?? nodeRequestHeaders;\n const reqCtx: RequestContext = requestContextFromRequest(\n new Request(reqUrl, { headers: reqCtxHeaders }),\n );\n\n // Apply custom headers from next.config.js\n // Header matching still uses the original normalized pathname and\n // pre-middleware request state; middleware response headers win\n // later because they are already on the outgoing response.\n if (nextConfig?.headers.length) {\n applyHeaders(pathname, res, nextConfig.headers, preMiddlewareReqCtx);\n }\n\n // Apply rewrites from next.config.js (beforeFiles)\n let resolvedUrl = url;\n if (nextConfig?.rewrites.beforeFiles.length) {\n resolvedUrl =\n applyRewrites(pathname, nextConfig.rewrites.beforeFiles, reqCtx) ?? url;\n }\n\n // External rewrite from beforeFiles — proxy to external URL\n if (isExternalUrl(resolvedUrl)) {\n applyDeferredMwHeaders();\n await proxyExternalRewriteNode(req, res, resolvedUrl);\n return;\n }\n\n // Handle API routes first (pages/api/*)\n const resolvedPathname = resolvedUrl.split(\"?\")[0];\n if (resolvedPathname.startsWith(\"/api/\") || resolvedPathname === \"/api\") {\n const apiRoutes = await apiRouter(\n pagesDir,\n nextConfig?.pageExtensions,\n fileMatcher,\n );\n const apiMatch = matchRoute(resolvedUrl, apiRoutes);\n if (apiMatch) {\n applyDeferredMwHeaders();\n if (middlewareRequestHeaders) {\n applyRequestHeadersToNodeRequest(middlewareRequestHeaders);\n }\n }\n const handled = await handleApiRoute(\n getPagesRunner(),\n req,\n res,\n resolvedUrl,\n apiRoutes,\n );\n if (handled) return;\n\n // No API route matched — if app dir exists, let the RSC plugin handle it\n // (app/api/* route handlers live there). Otherwise hard-404.\n if (hasAppDir) return next();\n\n res.statusCode = 404;\n res.end(\"404 - API route not found\");\n return;\n }\n\n const routes = await pagesRouter(pagesDir, nextConfig?.pageExtensions, fileMatcher);\n\n // Apply afterFiles rewrites — these run after initial route matching\n // If beforeFiles already rewrote the URL, afterFiles still run on the\n // *resolved* pathname. Next.js applies these when route matching succeeds\n // but allows overriding with rewrites.\n if (nextConfig?.rewrites.afterFiles.length) {\n const afterRewrite = applyRewrites(\n resolvedUrl.split(\"?\")[0],\n nextConfig.rewrites.afterFiles,\n reqCtx,\n );\n if (afterRewrite) resolvedUrl = afterRewrite;\n }\n\n // External rewrite from afterFiles — proxy to external URL\n if (isExternalUrl(resolvedUrl)) {\n applyDeferredMwHeaders();\n await proxyExternalRewriteNode(req, res, resolvedUrl);\n return;\n }\n\n const handler = createSSRHandler(\n server,\n getPagesRunner(),\n routes,\n pagesDir,\n nextConfig?.i18n,\n fileMatcher,\n nextConfig?.basePath ?? \"\",\n nextConfig?.trailingSlash ?? false,\n );\n const mwStatus = req.__vinextRewriteStatus;\n\n // Try rendering the resolved URL\n const match = matchRoute(resolvedUrl.split(\"?\")[0], routes);\n if (match) {\n applyDeferredMwHeaders();\n if (middlewareRequestHeaders) {\n applyRequestHeadersToNodeRequest(middlewareRequestHeaders);\n }\n await handler(req, res, resolvedUrl, mwStatus);\n return;\n }\n\n // No route matched — try fallback rewrites\n if (nextConfig?.rewrites.fallback.length) {\n const fallbackRewrite = applyRewrites(\n resolvedUrl.split(\"?\")[0],\n nextConfig.rewrites.fallback,\n reqCtx,\n );\n if (fallbackRewrite) {\n // External fallback rewrite — proxy to external URL\n if (isExternalUrl(fallbackRewrite)) {\n applyDeferredMwHeaders();\n await proxyExternalRewriteNode(req, res, fallbackRewrite);\n return;\n }\n const fallbackMatch = matchRoute(fallbackRewrite.split(\"?\")[0], routes);\n if (!fallbackMatch && hasAppDir) {\n return next();\n }\n applyDeferredMwHeaders();\n if (middlewareRequestHeaders) {\n applyRequestHeadersToNodeRequest(middlewareRequestHeaders);\n }\n await handler(req, res, fallbackRewrite, mwStatus);\n return;\n }\n }\n\n // No fallback matched - if app dir exists, let the RSC plugin handle it,\n // otherwise render via the pages SSR handler (will 404 for unknown routes).\n if (hasAppDir) return next();\n\n await handler(req, res, resolvedUrl, mwStatus);\n } catch (e) {\n next(e);\n }\n });\n };\n },\n },\n // Strip server-only data-fetching exports (getServerSideProps, getStaticProps,\n // getStaticPaths) from page modules in the client bundle. These functions\n // often import server-only modules (database drivers, fs, etc.) that would\n // break or bloat the client bundle. Next.js does this via an SWC transform\n // (next-ssg-transform); we use Vite's parseAst + MagicString.\n //\n // Only applies to client builds (not SSR) and only to files under the\n // pages/ directory.\n {\n name: \"vinext:strip-server-exports\",\n transform: {\n // Only match page source files, not node_modules\n filter: { id: /\\.(tsx?|jsx?|mjs)$/ },\n handler(code, id) {\n const ssr = this.environment?.name !== \"client\";\n if (ssr) return null;\n if (!hasPagesDir) return null;\n // Only transform files under the pages/ directory\n if (!id.startsWith(pagesDir)) return null;\n // Skip API routes, _app, _document, _error\n const relativePath = id.slice(pagesDir.length);\n if (relativePath.startsWith(\"/api/\") || relativePath === \"/api\") return null;\n if (/\\/_(?:app|document|error)\\b/.test(relativePath)) return null;\n\n const result = stripServerExports(code);\n if (!result) return null;\n return { code: result, map: null };\n },\n },\n },\n // Local image import transform:\n // When a source file imports a local image (e.g., `import hero from './hero.jpg'`),\n // this plugin transforms the default import to a StaticImageData object with\n // { src, width, height } so the next/image shim can set correct dimensions\n // on <img> tags, preventing CLS.\n //\n // Vite's default image import returns a URL string. We intercept this by\n // adding a `?vinext-meta` suffix: the original import gets the URL from Vite,\n // and we resolve the `?vinext-meta` virtual module to provide dimensions.\n {\n name: \"vinext:image-imports\",\n enforce: \"pre\",\n\n // Cache of image dimensions to avoid re-reading files\n _dimCache: imageImportDimCache,\n\n resolveId: {\n filter: { id: /\\?vinext-meta$/ },\n handler(source, _importer) {\n if (!source.endsWith(\"?vinext-meta\")) return null;\n // Resolve the real image path from the importer\n const realPath = source.replace(\"?vinext-meta\", \"\");\n return `\\0vinext-image-meta:${realPath}`;\n },\n },\n\n async load(id) {\n if (!id.startsWith(\"\\0vinext-image-meta:\")) return null;\n const imagePath = id.replace(\"\\0vinext-image-meta:\", \"\");\n\n // Read from cache first\n const cache = imageImportDimCache;\n let dims = cache.get(imagePath);\n if (!dims) {\n try {\n const { imageSize } = await import(\"image-size\");\n const buffer = fs.readFileSync(imagePath);\n const result = imageSize(buffer);\n dims = { width: result.width ?? 0, height: result.height ?? 0 };\n cache.set(imagePath, dims);\n } catch {\n dims = { width: 0, height: 0 };\n }\n }\n\n return `export default ${JSON.stringify(dims)};`;\n },\n\n transform: {\n // Hook filter: Rolldown evaluates these on the Rust side, skipping\n // the JS handler entirely for files that don't match.\n filter: {\n id: {\n include: /\\.(tsx?|jsx?|mjs)$/,\n exclude: /node_modules/,\n },\n code: new RegExp(`import\\\\s+\\\\w+\\\\s+from\\\\s+['\"][^'\"]+\\\\.(${IMAGE_EXTS})['\"]`),\n },\n async handler(code, id) {\n // Defensive guard — duplicates filter logic\n if (id.includes(\"node_modules\")) return null;\n if (id.startsWith(\"\\0\")) return null;\n if (!id.match(/\\.(tsx?|jsx?|mjs)$/)) return null;\n\n const imageImportRe = new RegExp(\n `import\\\\s+(\\\\w+)\\\\s+from\\\\s+['\"]([^'\"]+\\\\.(${IMAGE_EXTS}))['\"];?`,\n \"g\",\n );\n if (!imageImportRe.test(code)) return null;\n\n imageImportRe.lastIndex = 0;\n\n const s = new MagicString(code);\n let hasChanges = false;\n\n let match;\n while ((match = imageImportRe.exec(code)) !== null) {\n const [fullMatch, varName, importPath] = match;\n const matchStart = match.index;\n const matchEnd = matchStart + fullMatch.length;\n\n // Resolve the absolute path of the image\n const dir = path.dirname(id);\n const absImagePath = path.resolve(dir, importPath);\n\n if (!fs.existsSync(absImagePath)) continue;\n\n // Replace the single import with two:\n // 1. Original import (Vite gives us the URL string)\n // 2. Meta import (we provide { width, height })\n // Combined into a StaticImageData object\n const urlVar = `__vinext_img_url_${varName}`;\n const metaVar = `__vinext_img_meta_${varName}`;\n const replacement =\n `import ${urlVar} from ${JSON.stringify(importPath)};\\n` +\n `import ${metaVar} from ${JSON.stringify(absImagePath + \"?vinext-meta\")};\\n` +\n `const ${varName} = { src: ${urlVar}, width: ${metaVar}.width, height: ${metaVar}.height };`;\n\n s.overwrite(matchStart, matchEnd, replacement);\n hasChanges = true;\n }\n\n if (!hasChanges) return null;\n\n return {\n code: s.toString(),\n map: s.generateMap({ hires: \"boundary\" }),\n };\n },\n },\n } as Plugin & { _dimCache: Map<string, { width: number; height: number }> },\n // Google Fonts import rewrite + self-hosting — see src/plugins/fonts.ts\n createGoogleFontsPlugin(_fontGoogleShimPath, _shimsDir),\n // Local font path resolution — see src/plugins/fonts.ts\n createLocalFontsPlugin(),\n // Barrel import optimization:\n // Rewrites `import { Slot } from \"radix-ui\"` → `import * as Slot from \"@radix-ui/react-slot\"`\n // for packages listed in optimizePackageImports or DEFAULT_OPTIMIZE_PACKAGES.\n // This prevents Vite from eagerly evaluating barrel re-exports that call\n // React.createContext() in RSC environments where createContext doesn't exist.\n createOptimizeImportsPlugin(\n () => nextConfig,\n () => root,\n ),\n // \"use cache\" directive transform:\n // Detects \"use cache\" at file-level or function-level and wraps the\n // exports/functions with registerCachedFunction() from vinext/cache-runtime.\n // Runs without enforce so it executes after JSX transform (parseAst needs plain JS).\n {\n name: \"vinext:use-cache\",\n\n transform: {\n // Hook filter: only invoke JS when code contains 'use cache'.\n // The vast majority of files don't use this directive.\n filter: {\n id: {\n include: /\\.(tsx?|jsx?|mjs)$/,\n exclude: /node_modules/,\n },\n code: \"use cache\",\n },\n async handler(code, id) {\n // Defensive guard — duplicates filter logic\n if (id.includes(\"node_modules\")) return null;\n if (id.startsWith(\"\\0\")) return null;\n if (!id.match(/\\.(tsx?|jsx?|mjs)$/)) return null;\n if (!code.includes(\"use cache\")) return null;\n\n // Parse the AST first to check for actual \"use cache\" directives before\n // throwing the missing-RSC error. The fast-path string check above can\n // fire on files that contain \"use cache\" only in comments or string\n // literals (e.g., in error messages), not as real directives.\n const ast = parseAst(code);\n\n // Check for file-level \"use cache\" directive\n const cacheDirective = ast.body.find(\n (node) =>\n node.type === \"ExpressionStatement\" &&\n node.expression?.type === \"Literal\" &&\n typeof node.expression.value === \"string\" &&\n node.expression.value.startsWith(\"use cache\"),\n );\n\n // Check for function-level \"use cache\" directives by walking function bodies.\n // Accepts any function-like node: FunctionDeclaration/Expression, ArrowFunctionExpression,\n // or MethodDefinition. MethodDefinition stores its FunctionExpression in `.value`, not\n // `.body`, so we unwrap it here rather than at each call site to keep the callee safe.\n function nodeHasInlineCacheDirective(node: ASTNode): boolean {\n if (!node || typeof node !== \"object\") return false;\n // MethodDefinition wraps its FunctionExpression in .value; unwrap to reach .body.\n const fn = node.type === \"MethodDefinition\" ? node.value : node;\n // fn.body is a BlockStatement node ({type:\"BlockStatement\", body:Statement[]}), not\n // a raw array. Unwrap it. Arrow functions with expression bodies have a non-array\n // .body — the BlockStatement check handles that case (body.body would be undefined).\n const stmts: ASTNode[] | null =\n // oxlint-disable-next-line typescript/no-explicit-any\n (fn as any)?.body?.type === \"BlockStatement\" ? (fn as any).body.body : null;\n if (Array.isArray(stmts)) {\n for (const stmt of stmts) {\n if (\n stmt?.type === \"ExpressionStatement\" &&\n stmt.expression?.type === \"Literal\" &&\n typeof stmt.expression?.value === \"string\" &&\n /^use cache(:\\s*\\w+)?$/.test(stmt.expression.value)\n ) {\n return true;\n }\n }\n }\n return false;\n }\n function astHasInlineCache(nodes: ASTNode[]): boolean {\n for (const node of nodes) {\n if (!node || typeof node !== \"object\") continue;\n if (\n (node.type === \"FunctionDeclaration\" ||\n node.type === \"FunctionExpression\" ||\n node.type === \"ArrowFunctionExpression\" ||\n node.type === \"MethodDefinition\") &&\n nodeHasInlineCacheDirective(node)\n ) {\n return true;\n }\n // Walk into variable declarations, export declarations, etc.\n for (const key of Object.keys(node)) {\n if (key === \"type\" || key === \"start\" || key === \"end\" || key === \"loc\") continue;\n const child = node[key as keyof typeof node] as ASTNode;\n if (Array.isArray(child) && child.some((c) => c && typeof c === \"object\")) {\n if (astHasInlineCache(child)) return true;\n } else if (child && typeof child === \"object\" && child.type) {\n if (astHasInlineCache([child])) return true;\n }\n }\n }\n return false;\n }\n const hasInlineCache = !cacheDirective && astHasInlineCache(ast.body);\n\n if (!cacheDirective && !hasInlineCache) return null;\n\n if (!resolvedRscTransformsPath) {\n throw new Error(\n \"vinext: 'use cache' requires @vitejs/plugin-rsc to be installed.\\n\" +\n \"Run: \" +\n detectPackageManager(process.cwd()) +\n \" @vitejs/plugin-rsc\",\n );\n }\n const { transformWrapExport, transformHoistInlineDirective } = await import(\n pathToFileURL(resolvedRscTransformsPath).href\n );\n\n if (cacheDirective) {\n // File-level \"use cache\" — wrap function exports with\n // registerCachedFunction. Page default exports are wrapped directly\n // (they're leaf components). Layout/template defaults are excluded\n // because they receive {children} from the framework.\n // oxlint-disable-next-line typescript/no-explicit-any\n const directiveValue = (cacheDirective as any).expression.value;\n const variant =\n directiveValue === \"use cache\"\n ? \"\"\n : directiveValue.replace(\"use cache:\", \"\").replace(\"use cache: \", \"\").trim();\n\n // Only skip default export wrapping for layouts and templates —\n // they receive {children} from the framework which requires\n // temporary reference handling that registerCachedFunction doesn't\n // support yet. Pages, not-found, loading, error, and default are\n // leaf components with no {children} prop and can be cached directly.\n const isLayoutOrTemplate = /\\/(layout|template)\\.(tsx?|jsx?|mjs)$/.test(id);\n\n const runtimeModuleUrl = pathToFileURL(\n resolveShimModulePath(shimsDir, \"cache-runtime\"),\n ).href;\n const result = transformWrapExport(code, ast, {\n runtime: (value: string, name: string) =>\n `(await import(${JSON.stringify(runtimeModuleUrl)})).registerCachedFunction(${value}, ${JSON.stringify(id + \":\" + name)}, ${JSON.stringify(variant)})`,\n rejectNonAsyncFunction: false,\n filter: (name: string, meta: { isFunction?: boolean }) => {\n // Skip non-functions (constants, types, etc.)\n if (meta.isFunction === false) return false;\n // Skip the default export on layout/template files — these\n // receive {children} from the framework, and caching them\n // requires temporary reference handling for the children slot.\n // Named exports (e.g. generateMetadata) are still wrapped.\n if (isLayoutOrTemplate && name === \"default\") return false;\n return true;\n },\n });\n\n if (result.exportNames.length > 0) {\n // Remove the directive itself so it doesn't cause runtime errors\n const output = result.output;\n output.overwrite(\n cacheDirective.start,\n cacheDirective.end,\n `/* \"use cache\" — wrapped by vinext */`,\n );\n return {\n code: output.toString(),\n map: output.generateMap({ hires: \"boundary\" }),\n };\n }\n\n // Even if no exports were wrapped, still strip the directive\n // (e.g., layout/template file with only a default export)\n const output = new MagicString(code);\n output.overwrite(\n cacheDirective.start,\n cacheDirective.end,\n `/* \"use cache\" — handled by vinext */`,\n );\n return {\n code: output.toString(),\n map: output.generateMap({ hires: \"boundary\" }),\n };\n }\n\n // Check for function-level \"use cache\" directives\n // (e.g., async function getData() { \"use cache\"; ... })\n if (hasInlineCache) {\n const runtimeModuleUrl2 = pathToFileURL(\n resolveShimModulePath(shimsDir, \"cache-runtime\"),\n ).href;\n\n try {\n const result = transformHoistInlineDirective(code, ast, {\n directive: /^use cache(:\\s*\\w+)?$/,\n runtime: (value: string, name: string, meta: { directiveMatch: string[] }) => {\n const directiveMatch = meta.directiveMatch[0];\n const variant =\n directiveMatch === \"use cache\"\n ? \"\"\n : directiveMatch.replace(\"use cache:\", \"\").replace(\"use cache: \", \"\").trim();\n return `(await import(${JSON.stringify(runtimeModuleUrl2)})).registerCachedFunction(${value}, ${JSON.stringify(id + \":\" + name)}, ${JSON.stringify(variant)})`;\n },\n rejectNonAsyncFunction: false,\n });\n\n if (result.names.length > 0) {\n return {\n code: result.output.toString(),\n map: result.output.generateMap({ hires: \"boundary\" }),\n };\n }\n } catch {\n // If hoisting fails (e.g., complex closure), fall through\n }\n }\n\n return null;\n },\n },\n },\n // Inline binary assets fetched via `fetch(new URL(\"./asset\", import.meta.url))` —\n // see src/plugins/og-assets.ts\n createOgInlineFetchAssetsPlugin(),\n // Copy @vercel/og binary assets to the RSC output directory — see src/plugins/og-assets.ts\n ogAssetsPlugin,\n // Collect SSR/RSC bundle externals and write dist/server/vinext-externals.json.\n // Used by emitStandaloneOutput to determine which packages to copy into\n // standalone/node_modules/ — uses the bundler's own import graph instead of\n // fragile regex scanning of emitted files.\n createServerExternalsManifestPlugin(),\n // Write image config JSON for the App Router production server.\n // The App Router RSC entry doesn't export vinextConfig (that's a Pages\n // Router pattern), so we write a separate JSON file at build time that\n // prod-server.ts reads at startup for SVG/security header config.\n {\n name: \"vinext:image-config\",\n apply: \"build\",\n enforce: \"post\",\n writeBundle: {\n sequential: true,\n order: \"post\",\n handler(options) {\n const envName = this.environment?.name;\n if (envName !== \"rsc\") return;\n\n const outDir = options.dir;\n if (!outDir) return;\n\n const imageConfig = {\n dangerouslyAllowSVG: nextConfig?.images?.dangerouslyAllowSVG,\n contentDispositionType: nextConfig?.images?.contentDispositionType,\n contentSecurityPolicy: nextConfig?.images?.contentSecurityPolicy,\n };\n\n fs.writeFileSync(path.join(outDir, \"image-config.json\"), JSON.stringify(imageConfig));\n },\n },\n },\n // Write BUILD_ID to dist/server/ so post-build tools (TPR, seed-cache) can\n // read the build identifier without depending on the prerender manifest.\n // Uses closeBundle (not writeBundle) with a one-time write guard so the file\n // is written exactly once per build regardless of how many environments are\n // active (App Router RSC+SSR+client, Pages Router SSR+client, etc.).\n // The path is always dist/server/BUILD_ID — derived from root, not from the\n // per-environment options.dir — so it works for all router types.\n (() => {\n let buildIdWritten = false;\n return {\n name: \"vinext:build-id\",\n apply: \"build\" as const,\n enforce: \"post\" as const,\n closeBundle: {\n sequential: true,\n order: \"post\" as const,\n handler() {\n if (buildIdWritten) return;\n buildIdWritten = true;\n const outDir = path.join(root, \"dist\", \"server\");\n fs.mkdirSync(outDir, { recursive: true });\n fs.writeFileSync(path.join(outDir, \"BUILD_ID\"), nextConfig!.buildId);\n },\n },\n };\n })(),\n // Write vinext-server.json to dist/server/ with a per-build prerender secret.\n // The prerender secret is used by prod-server.ts to authenticate requests to\n // the internal /__vinext/prerender/* endpoints, which are only reachable during\n // the prerender phase of `vinext build`. A new secret is generated on every\n // build so it rotates with every deployment.\n //\n // The secret is generated once at plugin creation time so that both the rsc\n // and ssr environments write the exact same value (they share the same\n // closure). Without this, each env would call randomBytes() independently\n // and the second write would silently overwrite the first with a different\n // secret, causing prerender auth to fail for whichever env's server reads\n // the file last.\n (() => {\n const prerenderSecret = randomBytes(32).toString(\"hex\");\n return {\n name: \"vinext:server-manifest\",\n apply: \"build\" as const,\n enforce: \"post\" as const,\n writeBundle: {\n sequential: true,\n order: \"post\" as const,\n handler(options: { dir?: string }) {\n const envName = this.environment?.name;\n // Fire for App Router RSC builds (rsc env) and Pages Router SSR builds\n // (ssr env). Skip client and other environments.\n if (envName !== \"rsc\" && envName !== \"ssr\") return;\n\n const outDir = options.dir;\n if (!outDir) return;\n\n const manifest = { prerenderSecret };\n fs.writeFileSync(path.join(outDir, \"vinext-server.json\"), JSON.stringify(manifest));\n },\n },\n };\n })(),\n {\n name: \"vinext:nitro-route-rules\",\n nitro: {\n setup: async (nitro: NitroSetupContext) => {\n if (nitro.options.dev) return;\n if (!nextConfig) return;\n if (!hasAppDir && !hasPagesDir) return;\n\n const { collectNitroRouteRules, mergeNitroRouteRules } =\n await import(\"./build/nitro-route-rules.js\");\n const generatedRouteRules = await collectNitroRouteRules({\n appDir: hasAppDir ? appDir : null,\n pagesDir: hasPagesDir ? pagesDir : null,\n pageExtensions: nextConfig.pageExtensions,\n });\n\n if (Object.keys(generatedRouteRules).length === 0) return;\n\n const { routeRules, skippedRoutes } = mergeNitroRouteRules(\n nitro.options.routeRules,\n generatedRouteRules,\n );\n\n nitro.options.routeRules = routeRules;\n\n if (skippedRoutes.length > 0) {\n const warn = nitro.logger?.warn ?? console.warn;\n warn(\n `[vinext] Skipping generated Nitro routeRules for routes with existing exact cache config: ${skippedRoutes.join(\", \")}`,\n );\n }\n },\n },\n } as Plugin & { nitro: { setup: (nitro: NitroSetupContext) => Promise<void> } }, // Nitro plugin extension convention: https://nitro.build/guide/plugins\n // Vite can emit empty SSR manifest entries for modules that Rollup inlines\n // into another chunk. Pages Router looks up assets by page module path at\n // runtime, so rebuild those mappings from the emitted client bundle.\n {\n name: \"vinext:ssr-manifest-backfill\",\n apply: \"build\",\n enforce: \"post\",\n writeBundle: {\n sequential: true,\n order: \"post\",\n handler(options, bundle) {\n const outDir = options.dir;\n if (!outDir) return;\n\n const viteDir = path.join(outDir, \".vite\");\n const ssrManifestPath = path.join(viteDir, \"ssr-manifest.json\");\n if (!fs.existsSync(ssrManifestPath)) return;\n\n try {\n const ssrManifest = JSON.parse(fs.readFileSync(ssrManifestPath, \"utf-8\")) as Record<\n string,\n string[]\n >;\n const buildRoot = this.environment?.config.root ?? process.cwd();\n const buildBase = this.environment?.config.base ?? \"/\";\n const augmentedManifest = augmentSsrManifestFromBundle(\n ssrManifest,\n bundle as Record<string, BundleBackfillChunk | { type: string }>,\n buildRoot,\n buildBase,\n );\n fs.writeFileSync(ssrManifestPath, JSON.stringify(augmentedManifest, null, 2));\n } catch (err) {\n // Leave Vite's manifest untouched if parsing fails.\n console.warn(\"[vinext] Failed to augment SSR manifest:\", err);\n }\n },\n },\n },\n // Build-time precompression: generate .br, .gz, .zst for hashed assets.\n // Runs after the client bundle is written so compressed variants are\n // available for the production server's static file cache.\n // Opt-in via `precompress: true` in plugin options or `--precompress`\n // CLI flag. Not useful for edge platforms (Cloudflare Workers, Nitro)\n // that handle compression at the CDN layer.\n (() => {\n let pendingPrecompress: Promise<void> | null = null;\n let pendingPrecompressError: unknown = null;\n\n return {\n name: \"vinext:precompress\",\n apply: \"build\" as const,\n enforce: \"post\" as const,\n writeBundle: {\n sequential: true,\n order: \"post\" as const,\n handler(outputOptions: { dir?: string }) {\n if (this.environment?.name !== \"client\") return;\n\n if (!options.precompress && process.env.VINEXT_PRECOMPRESS !== \"1\") return;\n\n const outDir = outputOptions.dir;\n if (!outDir) return;\n\n // Only precompress hashed assets — public directory files use\n // on-the-fly compression since they may change between deploys.\n const assetsDir = path.join(outDir, \"assets\");\n if (!fs.existsSync(assetsDir)) return;\n\n const isTTY = process.stderr.isTTY;\n let lastLineLen = 0;\n\n // Start precompression as soon as the client bundle is written, but\n // defer awaiting it until the SSR environment finishes. This overlaps\n // the extra asset work with the final build phase instead of putting\n // the full precompression cost on the critical path of step 4/5.\n pendingPrecompressError = null;\n pendingPrecompress = (async () => {\n const result = await precompressAssets(outDir, (completed, total, file) => {\n if (!isTTY) return;\n const pct = total > 0 ? Math.floor((completed / total) * 100) : 0;\n const bar = `[${\"█\".repeat(Math.floor(pct / 5))}${\" \".repeat(20 - Math.floor(pct / 5))}]`;\n const maxFile = 30;\n const fileLabel = file.length > maxFile ? \"…\" + file.slice(-(maxFile - 1)) : file;\n const line = `Compressing assets... ${bar} ${String(completed).padStart(String(total).length)}/${total} ${fileLabel}`;\n const padded = line.padEnd(lastLineLen);\n lastLineLen = line.length;\n process.stderr.write(`\\r${padded}`);\n });\n if (isTTY) {\n process.stderr.write(`\\r${\" \".repeat(lastLineLen)}\\r`);\n }\n if (result.filesCompressed > 0) {\n const ratio = (\n (1 - result.totalBrotliBytes / result.totalOriginalBytes) *\n 100\n ).toFixed(1);\n console.log(\n ` Precompressed ${result.filesCompressed} assets (${ratio}% smaller with brotli)`,\n );\n }\n })().catch((error) => {\n pendingPrecompressError = error;\n // Log immediately so the error isn't invisible if closeBundle\n // never fires (e.g. a crash in a later SSR build plugin).\n console.error(\"[vinext] Precompression failed:\", error);\n });\n },\n },\n closeBundle: {\n sequential: true,\n order: \"post\" as const,\n async handler() {\n if (this.environment?.name !== \"ssr\") return;\n if (!pendingPrecompress) return;\n\n const task = pendingPrecompress;\n pendingPrecompress = null;\n await task;\n if (pendingPrecompressError) {\n const error = pendingPrecompressError;\n pendingPrecompressError = null;\n throw error;\n }\n },\n },\n };\n })(),\n // Cloudflare Workers production build integration:\n // After all environments are built, compute lazy chunks from the client\n // build manifest and inject globals into the worker entry.\n //\n // Pages Router: injects __VINEXT_CLIENT_ENTRY__, __VINEXT_SSR_MANIFEST__,\n // and __VINEXT_LAZY_CHUNKS__ into the worker entry (found via wrangler.json).\n // App Router: the RSC plugin handles __VINEXT_CLIENT_ENTRY__ via\n // loadBootstrapScriptContent(), but we still inject __VINEXT_LAZY_CHUNKS__\n // and __VINEXT_SSR_MANIFEST__ into the worker entry at dist/server/index.js.\n // Both: generates _headers file for immutable asset caching.\n {\n name: \"vinext:cloudflare-build\",\n apply: \"build\",\n enforce: \"post\",\n closeBundle: {\n sequential: true,\n order: \"post\",\n async handler() {\n const envName = this.environment?.name;\n if (!envName || !hasCloudflarePlugin) return;\n if (envName !== \"client\") return;\n\n const envConfig = this.environment?.config;\n if (!envConfig) return;\n const buildRoot = envConfig.root ?? process.cwd();\n const distDir = path.resolve(buildRoot, \"dist\");\n if (!fs.existsSync(distDir)) return;\n\n const clientDir = path.resolve(buildRoot, \"dist\", \"client\");\n const clientBase = envConfig.base ?? \"/\";\n\n // Read build manifest and compute lazy chunks (only reachable via\n // dynamic imports). This runs for BOTH App Router and Pages Router.\n // clientEntryFile is only used by the Pages Router path below —\n // App Router gets its client entry via the RSC plugin instead.\n let lazyChunksData: string[] | null = null;\n let clientEntryFile: string | null = null;\n const buildManifestPath = path.join(clientDir, \".vite\", \"manifest.json\");\n if (fs.existsSync(buildManifestPath)) {\n try {\n const buildManifest = JSON.parse(fs.readFileSync(buildManifestPath, \"utf-8\"));\n // oxlint-disable-next-line typescript/no-explicit-any\n for (const [, value] of Object.entries(buildManifest) as [string, any][]) {\n if (value && value.isEntry && value.file) {\n clientEntryFile = manifestFileWithBase(value.file, clientBase);\n break;\n }\n }\n const lazy = manifestFilesWithBase(computeLazyChunks(buildManifest), clientBase);\n if (lazy.length > 0) lazyChunksData = lazy;\n } catch {\n /* ignore parse errors */\n }\n }\n\n // Read SSR manifest for per-page CSS/JS injection\n let ssrManifestData: Record<string, string[]> | null = null;\n const ssrManifestPath = path.join(clientDir, \".vite\", \"ssr-manifest.json\");\n if (fs.existsSync(ssrManifestPath)) {\n try {\n ssrManifestData = JSON.parse(fs.readFileSync(ssrManifestPath, \"utf-8\"));\n } catch {\n /* ignore parse errors */\n }\n }\n\n if (hasAppDir) {\n // App Router: the RSC plugin handles __VINEXT_CLIENT_ENTRY__\n // via loadBootstrapScriptContent(), but we still need to inject\n // __VINEXT_LAZY_CHUNKS__ and __VINEXT_SSR_MANIFEST__ into the\n // worker entry at dist/server/index.js.\n const workerEntry = path.resolve(distDir, \"server\", \"index.js\");\n if (fs.existsSync(workerEntry) && (lazyChunksData || ssrManifestData)) {\n let code = fs.readFileSync(workerEntry, \"utf-8\");\n const globals: string[] = [];\n if (ssrManifestData) {\n globals.push(\n `globalThis.__VINEXT_SSR_MANIFEST__ = ${JSON.stringify(ssrManifestData)};`,\n );\n }\n if (lazyChunksData) {\n globals.push(\n `globalThis.__VINEXT_LAZY_CHUNKS__ = ${JSON.stringify(lazyChunksData)};`,\n );\n }\n code = globals.join(\"\\n\") + \"\\n\" + code;\n fs.writeFileSync(workerEntry, code);\n }\n } else {\n // Pages Router: find worker output by scanning dist/ for a\n // directory containing wrangler.json (Cloudflare plugin default).\n let workerOutDir: string | null = null;\n for (const entry of fs.readdirSync(distDir)) {\n const candidate = path.join(distDir, entry);\n if (entry === \"client\") continue;\n if (\n fs.statSync(candidate).isDirectory() &&\n fs.existsSync(path.join(candidate, \"wrangler.json\"))\n ) {\n workerOutDir = candidate;\n break;\n }\n }\n if (!workerOutDir) return;\n\n const workerEntry = path.join(workerOutDir, \"index.js\");\n if (!fs.existsSync(workerEntry)) return;\n\n // Fallback: scan dist/client/assets/ for the client entry chunk.\n // Pages Router uses \"vinext-client-entry\", App Router uses\n // \"vinext-app-browser-entry\".\n if (!clientEntryFile) {\n const assetsDir = path.join(clientDir, \"assets\");\n if (fs.existsSync(assetsDir)) {\n const files = fs.readdirSync(assetsDir);\n const entry = files.find(\n (f: string) =>\n (f.includes(\"vinext-client-entry\") || f.includes(\"vinext-app-browser-entry\")) &&\n f.endsWith(\".js\"),\n );\n if (entry) clientEntryFile = manifestFileWithBase(\"assets/\" + entry, clientBase);\n }\n }\n\n // Prepend globals to worker entry\n if (clientEntryFile || ssrManifestData || lazyChunksData) {\n let code = fs.readFileSync(workerEntry, \"utf-8\");\n const globals: string[] = [];\n if (clientEntryFile) {\n globals.push(\n `globalThis.__VINEXT_CLIENT_ENTRY__ = ${JSON.stringify(clientEntryFile)};`,\n );\n }\n if (ssrManifestData) {\n globals.push(\n `globalThis.__VINEXT_SSR_MANIFEST__ = ${JSON.stringify(ssrManifestData)};`,\n );\n }\n if (lazyChunksData) {\n globals.push(\n `globalThis.__VINEXT_LAZY_CHUNKS__ = ${JSON.stringify(lazyChunksData)};`,\n );\n }\n code = globals.join(\"\\n\") + \"\\n\" + code;\n fs.writeFileSync(workerEntry, code);\n }\n }\n\n // Generate _headers file for Cloudflare Workers static asset caching.\n // Vite outputs content-hashed files (JS, CSS, fonts) to the assetsDir\n // (defaults to \"assets\"). These are safe to cache indefinitely since\n // the hash changes on any content change. Without this, Cloudflare\n // serves them with max-age=0 which forces unnecessary revalidation\n // on every page load.\n const headersPath = path.join(clientDir, \"_headers\");\n if (!fs.existsSync(headersPath)) {\n const assetsDir = envConfig.build?.assetsDir ?? \"assets\";\n const headersContent = [\n \"# Cache content-hashed assets immutably (generated by vinext)\",\n `/${assetsDir}/*`,\n \" Cache-Control: public, max-age=31536000, immutable\",\n \"\",\n ].join(\"\\n\");\n fs.mkdirSync(clientDir, { recursive: true });\n fs.writeFileSync(headersPath, headersContent);\n }\n },\n },\n },\n {\n // @vercel/og WASM patch — universal (workerd + Node.js)\n //\n // @vercel/og/dist/index.edge.js uses two WASM modules that need special handling:\n //\n // 1. YOGA WASM: yoga-layout embeds its WASM as a base64 data URL and instantiates\n // it via WebAssembly.instantiate(bytes). workerd forbids this — WASM must be\n // loaded as a pre-compiled WebAssembly.Module via the module system.\n //\n // 2. RESVG WASM: imported as `import resvg_wasm from \"./resvg.wasm?module\"` which\n // only works on workerd. Node.js can't import WASM files as ESM modules.\n //\n // Fix: replace all static WASM imports with dynamic imports that try the ?module\n // path (for workerd) and fall back to compiling from bytes (for Node.js). This\n // produces a single build output that runs on both runtimes.\n name: \"vinext:og-font-patch\",\n enforce: \"pre\" as const,\n transform(code: string, id: string) {\n if (!id.includes(\"@vercel/og\") || !id.includes(\"index.edge.js\")) return null;\n let result = code;\n\n // ── Yoga WASM: dynamic import + inline base64 fallback ──────────────────────\n // yoga-layout's emscripten bundle sets H to a data URL containing the yoga WASM,\n // then later calls WebAssembly.instantiate(bytes, imports), which workerd rejects.\n // Emscripten supports a custom h2.instantiateWasm(imports, callback) escape hatch.\n //\n // Strategy: try dynamic import(\"./yoga.wasm?module\") for workerd (pre-compiled\n // module), fall back to compiling from inline base64 bytes for Node.js.\n // Yoga WASM is ~70KB so inlining the base64 (~95KB) is acceptable.\n const YOGA_DATA_URL_RE = /H = \"data:application\\/octet-stream;base64,([A-Za-z0-9+/]+=*)\";/;\n const yogaMatch = YOGA_DATA_URL_RE.exec(result);\n if (yogaMatch) {\n const yogaBase64 = yogaMatch[1];\n const distDir = path.dirname(id);\n const yogaWasmPath = path.join(distDir, \"yoga.wasm\");\n // Write yoga.wasm to disk idempotently at transform time (Node.js side)\n // so the ?module dynamic import can resolve it on workerd builds.\n if (!fs.existsSync(yogaWasmPath)) {\n fs.writeFileSync(yogaWasmPath, Buffer.from(yogaBase64, \"base64\"));\n }\n // Disable the data-URL branch so emscripten doesn't try to instantiate from bytes\n result = result.replace(yogaMatch[0], `H = \"\";`);\n // Patch the loadYoga call site to inject instantiateWasm with universal handler.\n // WebAssembly.instantiate(Module, imports) → Instance (workerd path)\n // WebAssembly.instantiate(bytes, imports) → { module, instance } (Node.js path)\n const YOGA_CALL = `yoga_wasm_base64_esm_default()`;\n const YOGA_CALL_PATCHED = [\n `yoga_wasm_base64_esm_default({ instantiateWasm: function(imports, callback) {`,\n ` __vi_yoga_mod.then(function(mod) {`,\n ` if (mod) {`,\n ` WebAssembly.instantiate(mod, imports).then(function(inst) { callback(inst); });`,\n ` } else {`,\n ` var b = Buffer.from(__vi_yoga_b64, \"base64\");`,\n ` WebAssembly.instantiate(b, imports).then(function(r) { callback(r.instance); });`,\n ` }`,\n ` });`,\n ` return {};`,\n `} })`,\n ].join(\"\\n\");\n result = result.replace(YOGA_CALL, YOGA_CALL_PATCHED);\n // Prepend dynamic import with base64 fallback (no static import — Node.js safe)\n const yogaPreamble = [\n `var __vi_yoga_b64 = ${JSON.stringify(yogaBase64)};`,\n `var __vi_yoga_mod = import(\"./yoga.wasm?module\").then(function(m) { return m.default; }).catch(function() { return null; });`,\n ].join(\"\\n\");\n result = yogaPreamble + \"\\n\" + result;\n }\n\n // ── Resvg WASM: dynamic import + disk fallback ──────────────────────────────\n // The edge entry has `import resvg_wasm from \"./resvg.wasm?module\"` which is a\n // static ESM import that only works on workerd. Node.js fails because the WASM\n // binary's emscripten imports (module \"a\") can't be resolved as npm packages.\n //\n // Strategy: replace the static import with a dynamic import for workerd, falling\n // back to reading the .wasm file from disk + WebAssembly.compile for Node.js.\n // Resvg WASM is ~1.3MB so we read from disk instead of inlining base64.\n const RESVG_STATIC_IMPORT_RE =\n /import\\s+resvg_wasm\\s+from\\s+[\"']\\.\\/resvg\\.wasm\\?module[\"']\\s*;?/;\n const resvgMatch = RESVG_STATIC_IMPORT_RE.exec(result);\n if (resvgMatch) {\n // Note: new URL(\"./resvg.wasm\", import.meta.url) MUST be inside the catch handler,\n // not at the top level. In workerd, import.meta.url is \"worker\" (not a valid URL\n // base), so new URL(..., \"worker\") throws TypeError at module load time.\n // The catch block only runs on Node.js where import.meta.url is a file:// URL.\n const resvgLoader = [\n `var resvg_wasm = import(\"./resvg.wasm?module\").then(function(m) { return m.default; }).catch(function() {`,\n ` return Promise.all([import(\"node:fs\"), import(\"node:url\")]).then(function(mods) {`,\n ` var p = mods[1].fileURLToPath(new URL(\"./resvg.wasm\", import.meta.url));`,\n ` return mods[0].promises.readFile(p).then(function(buf) { return WebAssembly.compile(buf); });`,\n ` });`,\n `});`,\n ].join(\"\\n\");\n result = result.replace(resvgMatch[0], resvgLoader);\n }\n\n if (result === code) return null;\n return { code: result, map: null };\n },\n },\n ];\n\n // Append auto-injected RSC plugins if applicable\n if (rscPluginPromise) {\n plugins.push(rscPluginPromise);\n }\n\n return plugins;\n}\n\n/**\n * Collect all NEXT_PUBLIC_* env vars and create Vite define entries\n * so they get inlined into the client bundle.\n */\nfunction getNextPublicEnvDefines(): Record<string, string> {\n const defines: Record<string, string> = {};\n for (const [key, value] of Object.entries(process.env)) {\n if (key.startsWith(\"NEXT_PUBLIC_\") && value !== undefined) {\n defines[`process.env.${key}`] = JSON.stringify(value);\n }\n }\n return defines;\n}\n\n// matchConfigPattern is imported from config-matchers.ts and re-exported\n// for tests and other consumers that import it from vinext's main entry.\n// The duplicate local implementation and its extractConstraint helper\n// have been removed in favor of the canonical config-matchers.ts version\n// which uses a single-pass tokenizer (fixing the chained .replace()\n// divergence that CodeQL flagged as incomplete sanitization).\nexport { matchConfigPattern } from \"./config/config-matchers.js\";\n\n/**\n * Strip server-only data-fetching exports (getServerSideProps,\n * getStaticProps, getStaticPaths) from page modules for the client\n * bundle. Uses Vite's parseAst (Rollup/acorn) for correct handling\n * of all export patterns including function expressions, arrow\n * functions with TS return types, and re-exports.\n *\n * Modeled after Next.js's SWC `next-ssg-transform`.\n */\nfunction stripServerExports(code: string): string | null {\n const SERVER_EXPORTS = new Set([\"getServerSideProps\", \"getStaticProps\", \"getStaticPaths\"]);\n if (![...SERVER_EXPORTS].some((name) => code.includes(name))) return null;\n\n let ast: ReturnType<typeof parseAst>;\n try {\n ast = parseAst(code);\n } catch {\n // If parsing fails (shouldn't happen post-JSX/TS transform), bail out\n return null;\n }\n\n const s = new MagicString(code);\n let changed = false;\n\n for (const node of ast.body) {\n if (node.type !== \"ExportNamedDeclaration\") continue;\n\n // Case 1: export function name() {} / export async function name() {}\n // Case 2: export const/let/var name = ...\n if (node.declaration) {\n const decl = node.declaration;\n if (decl.type === \"FunctionDeclaration\" && decl.id && SERVER_EXPORTS.has(decl.id.name)) {\n s.overwrite(\n node.start,\n node.end,\n `export function ${decl.id.name}() { return { props: {} }; }`,\n );\n changed = true;\n } else if (decl.type === \"VariableDeclaration\") {\n for (const declarator of decl.declarations) {\n if (declarator.id?.type === \"Identifier\" && SERVER_EXPORTS.has(declarator.id.name)) {\n s.overwrite(node.start, node.end, `export const ${declarator.id.name} = undefined;`);\n changed = true;\n }\n }\n }\n continue;\n }\n\n // Case 3: export { getServerSideProps } or export { getServerSideProps as gSSP }\n if (node.specifiers && node.specifiers.length > 0 && !node.source) {\n const kept: Extract<ASTNode, { type: \"ExportSpecifier\" }>[] = [];\n const stripped: string[] = [];\n for (const spec of node.specifiers) {\n // spec.local.name is the binding name, spec.exported.name is the export name\n // oxlint-disable-next-line typescript/no-explicit-any\n const exportedName = (spec.exported as any)?.name ?? (spec.exported as any)?.value;\n if (SERVER_EXPORTS.has(exportedName)) {\n stripped.push(exportedName);\n } else {\n kept.push(spec);\n }\n }\n if (stripped.length > 0) {\n // Build replacement: keep non-server specifiers, add stubs for stripped ones\n const parts: string[] = [];\n if (kept.length > 0) {\n const keptStr = kept\n // oxlint-disable-next-line typescript/no-explicit-any\n .map((sp: any) => {\n const local = sp.local.name;\n const exported = sp.exported?.name ?? sp.exported?.value;\n return local === exported ? local : `${local} as ${exported}`;\n })\n .join(\", \");\n parts.push(`export { ${keptStr} };`);\n }\n for (const name of stripped) {\n parts.push(`export const ${name} = undefined;`);\n }\n s.overwrite(node.start, node.end, parts.join(\"\\n\"));\n changed = true;\n }\n }\n }\n\n if (!changed) return null;\n return s.toString();\n}\n\n/**\n * Apply redirect rules from next.config.js.\n * Returns true if a redirect was applied.\n */\nfunction applyRedirects(\n pathname: string,\n // oxlint-disable-next-line typescript/no-explicit-any\n res: any,\n redirects: NextRedirect[],\n ctx: RequestContext,\n basePath = \"\",\n): boolean {\n const result = matchRedirect(pathname, redirects, ctx);\n if (result) {\n // Sanitize to prevent open redirect via protocol-relative URLs\n const dest = sanitizeDestination(\n basePath && !isExternalUrl(result.destination) && !hasBasePath(result.destination, basePath)\n ? basePath + result.destination\n : result.destination,\n );\n res.writeHead(result.permanent ? 308 : 307, { Location: dest });\n res.end();\n return true;\n }\n return false;\n}\n\n/*\n * Converts the Node.js IncomingMessage into a Web Request, calls\n * proxyExternalRequest(), and pipes the response back to the Node.js\n * ServerResponse.\n */\nasync function proxyExternalRewriteNode(\n req: import(\"node:http\").IncomingMessage,\n res: import(\"node:http\").ServerResponse,\n externalUrl: string,\n): Promise<void> {\n try {\n const proto = \"http\";\n const host = req.headers.host || \"localhost\";\n const origin = `${proto}://${host}`;\n const method = req.method ?? \"GET\";\n const hasBody = method !== \"GET\" && method !== \"HEAD\";\n const init: RequestInit & { duplex?: string } = {\n method,\n headers: Object.fromEntries(\n Object.entries(req.headers)\n .filter(([, v]) => v !== undefined)\n .map(([k, v]) => [k, Array.isArray(v) ? v.join(\", \") : String(v)]),\n ),\n };\n if (hasBody) {\n const { Readable } = await import(\"node:stream\");\n init.body = Readable.toWeb(req) as ReadableStream;\n init.duplex = \"half\";\n }\n const webRequest = new Request(new URL(req.url ?? \"/\", origin), init);\n const proxyResponse = await proxyExternalRequest(webRequest, externalUrl);\n\n // Preserve multi-value headers (e.g. Set-Cookie) — Object.fromEntries()\n // would collapse them into a single value.\n const nodeHeaders: Record<string, string | string[]> = {};\n proxyResponse.headers.forEach((value, key) => {\n const existing = nodeHeaders[key];\n if (existing !== undefined) {\n nodeHeaders[key] = Array.isArray(existing) ? [...existing, value] : [existing, value];\n } else {\n nodeHeaders[key] = value;\n }\n });\n res.writeHead(proxyResponse.status, nodeHeaders);\n\n if (proxyResponse.body) {\n const { Readable: ReadableImport } = await import(\"node:stream\");\n const nodeStream = ReadableImport.fromWeb(\n proxyResponse.body as import(\"stream/web\").ReadableStream,\n );\n nodeStream.pipe(res);\n } else {\n res.end();\n }\n } catch (e) {\n console.error(\"[vinext] External rewrite proxy error:\", e);\n if (!res.headersSent) {\n res.writeHead(502);\n res.end(\"Bad Gateway\");\n }\n }\n}\n\n/**\n * Apply rewrite rules from next.config.js.\n * Returns the rewritten URL or null if no rewrite matched.\n */\nfunction applyRewrites(\n pathname: string,\n rewrites: NextRewrite[],\n ctx: RequestContext,\n): string | null {\n const dest = matchRewrite(pathname, rewrites, ctx);\n if (dest) {\n // Sanitize to prevent open redirect via protocol-relative URLs\n return sanitizeDestination(dest);\n }\n return null;\n}\n\n/**\n * Apply custom header rules from next.config.js.\n * Middleware headers take precedence: if a header key was already set on the\n * response (by middleware), the config value is skipped for that key.\n */\nfunction applyHeaders(\n pathname: string,\n // oxlint-disable-next-line typescript/no-explicit-any\n res: any,\n headers: NextHeader[],\n ctx: RequestContext,\n): void {\n const matched = matchHeaders(pathname, headers, ctx);\n for (const header of matched) {\n // Use append semantics for headers where multiple values must coexist\n // (Vary, Set-Cookie). Using setHeader() on these would destroy\n // existing values like \"Vary: RSC, Accept\".\n const lk = header.key.toLowerCase();\n if (lk === \"set-cookie\") {\n // Node.js res.getHeader(\"set-cookie\") returns string[] when\n // multiple Set-Cookie headers have been set. Preserve the array.\n const existing = res.getHeader(lk);\n if (Array.isArray(existing)) {\n res.setHeader(header.key, [...existing, header.value]);\n } else if (existing) {\n res.setHeader(header.key, [String(existing), header.value]);\n } else {\n res.setHeader(header.key, header.value);\n }\n } else if (lk === \"vary\") {\n const existing = res.getHeader(lk);\n if (existing) {\n res.setHeader(header.key, existing + \", \" + header.value);\n } else {\n res.setHeader(header.key, header.value);\n }\n } else {\n // Middleware headers take precedence: skip config keys already set by\n // middleware so middleware always wins over next.config.js headers.\n if (!res.getHeader(lk)) {\n res.setHeader(header.key, header.value);\n }\n }\n }\n}\n\n/**\n * Find a file by name (without extension) in a directory.\n * Checks the configured page extensions.\n */\nfunction findFileWithExts(\n dir: string,\n name: string,\n matcher: ReturnType<typeof createValidFileMatcher>,\n): string | null {\n for (const ext of matcher.dottedExtensions) {\n const filePath = path.join(dir, name + ext);\n if (fs.existsSync(filePath)) return filePath;\n }\n return null;\n}\n\n/** Module-level cache for hasMdxFiles — avoids re-scanning per Vite environment. */\nconst _mdxScanCache = new Map<string, boolean>();\n\n/**\n * Check if the project has .mdx files in app/ or pages/ directories.\n */\nfunction hasMdxFiles(root: string, appDir: string | null, pagesDir: string | null): boolean {\n const cacheKey = `${root}\\0${appDir ?? \"\"}\\0${pagesDir ?? \"\"}`;\n if (_mdxScanCache.has(cacheKey)) return _mdxScanCache.get(cacheKey)!;\n const dirs = [appDir, pagesDir].filter(Boolean) as string[];\n for (const dir of dirs) {\n if (fs.existsSync(dir) && scanDirForMdx(dir)) {\n _mdxScanCache.set(cacheKey, true);\n return true;\n }\n }\n _mdxScanCache.set(cacheKey, false);\n return false;\n}\n\nfunction scanDirForMdx(dir: string): boolean {\n try {\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n for (const entry of entries) {\n if (entry.name.startsWith(\".\") || entry.name === \"node_modules\") continue;\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n if (scanDirForMdx(full)) return true;\n } else if (entry.isFile() && entry.name.toLowerCase().endsWith(\".mdx\")) {\n return true;\n }\n }\n } catch {\n // ignore unreadable dirs\n }\n return false;\n}\n\n// Public exports for static export\nexport { staticExportPages, staticExportApp } from \"./build/static-export.js\";\nexport type {\n StaticExportResult,\n StaticExportOptions,\n AppStaticExportOptions,\n} from \"./build/static-export.js\";\n\n// Export NextConfig type so next.config.ts files can import it from \"vinext\"\n// instead of \"next\".\nexport type { NextConfig } from \"./config/next-config.js\";\n\n// Exported for CLI and testing\nexport {\n clientManualChunks,\n clientOutputConfig,\n clientTreeshakeConfig,\n computeLazyChunks,\n getClientOutputConfigForVite,\n};\nexport { augmentSsrManifestFromBundle as _augmentSsrManifestFromBundle };\nexport { resolvePostcssStringPlugins as _resolvePostcssStringPlugins };\nexport { _postcssCache };\nexport { hasMdxFiles as _hasMdxFiles };\nexport { _mdxScanCache };\nexport { parseStaticObjectLiteral as _parseStaticObjectLiteral };\nexport { _findBalancedObject, _findCallEnd };\nexport { stripServerExports as _stripServerExports };\nexport { asyncHooksStubPlugin as _asyncHooksStubPlugin };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8FA,MAAM,YAAY,OAAO,KAAK;AAG9B,SAAS,0BAA0B,aAAqB,WAAkC;AACxF,KAAI;AAEF,SADuB,cAAc,KAAK,KAAK,aAAa,eAAe,CAAC,CACtD,QAAQ,UAAU;SAClC;AAER,KAAI;AAEF,SADoB,cAAc,OAAO,KAAK,IAAI,CAC/B,QAAQ,UAAU;SAC/B;AAER,QAAO;;AAGT,SAAS,sBAAsB,UAAkB,YAA4B;AAI3E,MAAK,MAAM,OADQ,CAAC,OAAO,MAAM,EACH;EAC5B,MAAM,YAAY,KAAK,KAAK,UAAU,GAA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AE;AAC5C,gBAAc,IAAI,UAAU,KAAK;AACjC,SAAO;;AAGX,eAAc,IAAI,UAAU,MAAM;AAClC,QAAO;;AAGT,SAAS,cAAc,KAAsB;AAC3C,KAAI;EACF,MAAM,UAAU,GAAG,YAAY,KAAK,EAAE,eAAe,MAAM,CAAC;AAC5D,OAAK,MAAM,SAAS,SAAS;AAC3B,OAAI,MAAM,KAAK,WAAW,IAAI,IAAI,MAAM,SAAS,eAAgB;GACjE,MAAM,OAAO,KAAK,KAAK,KAAK,MAAM,KAAK;AACvC,OAAI,MAAM,aAAa;QACjB,cAAc,KAAK,CAAE,QAAO;cACvB,MAAM,QAAQ,IAAI,MAAM,KAAK,aAAa,CAAC,SAAS,OAAO,CACpE,QAAO;;SAGL;AAGR,QAAO"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["generateServerEntry","_generateServerEntry","generateClientEntry","_generateClientEntry","normalizePath"],"sources":["../src/index.ts"],"sourcesContent":["import type { Plugin, PluginOption, UserConfig, ViteDevServer } from \"vite\";\nimport { loadEnv, parseAst } from \"vite\";\nimport {\n pagesRouter,\n apiRouter,\n invalidateRouteCache,\n matchRoute,\n} from \"./routing/pages-router.js\";\nimport { generateServerEntry as _generateServerEntry } from \"./entries/pages-server-entry.js\";\nimport { generateClientEntry as _generateClientEntry } from \"./entries/pages-client-entry.js\";\nimport { appRouter, invalidateAppRouteCache } from \"./routing/app-router.js\";\nimport type { NitroRouteRuleConfig } from \"./build/nitro-route-rules.js\";\nimport { createValidFileMatcher } from \"./routing/file-matcher.js\";\nimport { createSSRHandler } from \"./server/dev-server.js\";\nimport { handleApiRoute } from \"./server/api-handler.js\";\nimport { createDirectRunner } from \"./server/dev-module-runner.js\";\nimport { generateRscEntry } from \"./entries/app-rsc-entry.js\";\nimport { generateSsrEntry } from \"./entries/app-ssr-entry.js\";\nimport { generateBrowserEntry } from \"./entries/app-browser-entry.js\";\nimport { normalizePathnameForRouteMatchStrict } from \"./routing/utils.js\";\nimport {\n findNextConfigPath,\n loadNextConfig,\n resolveNextConfigInput,\n resolveNextConfig,\n type NextConfig,\n type NextConfigInput,\n type ResolvedNextConfig,\n type NextRedirect,\n type NextRewrite,\n type NextHeader,\n} from \"./config/next-config.js\";\n\nimport { findMiddlewareFile, runMiddleware } from \"./server/middleware.js\";\nimport { logRequest, now } from \"./server/request-log.js\";\nimport { normalizePath } from \"./server/normalize-path.js\";\nimport {\n findInstrumentationClientFile,\n findInstrumentationFile,\n runInstrumentation,\n} from \"./server/instrumentation.js\";\nimport { PHASE_PRODUCTION_BUILD, PHASE_DEVELOPMENT_SERVER } from \"./shims/constants.js\";\nimport { precompressAssets } from \"./build/precompress.js\";\nimport { validateDevRequest } from \"./server/dev-origin-check.js\";\nimport {\n isExternalUrl,\n proxyExternalRequest,\n matchHeaders,\n matchRedirect,\n matchRewrite,\n requestContextFromRequest,\n sanitizeDestination,\n type RequestContext,\n} from \"./config/config-matchers.js\";\nimport { scanMetadataFiles } from \"./server/metadata-routes.js\";\nimport { buildRequestHeadersFromMiddlewareResponse } from \"./server/middleware-request-headers.js\";\nimport { detectPackageManager } from \"./utils/project.js\";\nimport {\n manifestFileWithBase,\n manifestFilesWithBase,\n normalizeManifestFile,\n} from \"./utils/manifest-paths.js\";\nimport { hasBasePath } from \"./utils/base-path.js\";\nimport { asyncHooksStubPlugin } from \"./plugins/async-hooks-stub.js\";\nimport { clientReferenceDedupPlugin } from \"./plugins/client-reference-dedup.js\";\nimport { createInstrumentationClientTransformPlugin } from \"./plugins/instrumentation-client.js\";\nimport { createOptimizeImportsPlugin } from \"./plugins/optimize-imports.js\";\nimport { fixUseServerClosureCollisionPlugin } from \"./plugins/fix-use-server-closure-collision.js\";\nimport { createOgInlineFetchAssetsPlugin, ogAssetsPlugin } from \"./plugins/og-assets.js\";\nimport { createServerExternalsManifestPlugin } from \"./plugins/server-externals-manifest.js\";\nimport {\n VIRTUAL_GOOGLE_FONTS,\n RESOLVED_VIRTUAL_GOOGLE_FONTS,\n parseStaticObjectLiteral,\n generateGoogleFontsVirtualModule,\n createGoogleFontsPlugin,\n createLocalFontsPlugin,\n _findBalancedObject,\n _findCallEnd,\n} from \"./plugins/fonts.js\";\nimport { hasWranglerConfig, formatMissingCloudflarePluginError } from \"./deploy.js\";\nimport { computeLazyChunks } from \"./utils/lazy-chunks.js\";\nimport tsconfigPaths from \"vite-tsconfig-paths\";\nimport type { Options as VitePluginReactOptions } from \"@vitejs/plugin-react\";\nimport MagicString from \"magic-string\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { createRequire } from \"node:module\";\nimport fs from \"node:fs\";\nimport { randomBytes } from \"node:crypto\";\nimport commonjs from \"vite-plugin-commonjs\";\n\ntype ASTNode = ReturnType<typeof parseAst>[\"body\"][number][\"parent\"];\n\nconst __dirname = import.meta.dirname;\ntype VitePluginReactModule = typeof import(\"@vitejs/plugin-react\");\n\nfunction resolveOptionalDependency(projectRoot: string, specifier: string): string | null {\n try {\n const projectRequire = createRequire(path.join(projectRoot, \"package.json\"));\n return projectRequire.resolve(specifier);\n } catch {}\n\n try {\n const selfRequire = createRequire(import.meta.url);\n return selfRequire.resolve(specifier);\n } catch {}\n\n return null;\n}\n\nfunction resolveShimModulePath(shimsDir: string, moduleName: string): string {\n // Source checkouts only ship TypeScript shims, while built packages only ship\n // JavaScript. Check .ts first to avoid an extra stat in development.\n const candidates = [\".ts\", \".js\"];\n for (const ext of candidates) {\n const candidate = path.join(shimsDir, `${moduleName}${ext}`);\n if (fs.existsSync(candidate)) {\n return candidate;\n }\n }\n return path.join(shimsDir, `${moduleName}.js`);\n}\n\nfunction toRelativeFileEntry(root: string, absPath: string): string {\n return path.relative(root, absPath).split(path.sep).join(\"/\");\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return !!value && typeof value === \"object\" && !Array.isArray(value);\n}\n\nconst TSCONFIG_FILES = [\"tsconfig.json\", \"jsconfig.json\"];\n\nfunction resolveTsconfigPathCandidate(candidate: string): string | null {\n const candidates = candidate.endsWith(\".json\")\n ? [candidate]\n : [candidate, `${candidate}.json`, path.join(candidate, \"tsconfig.json\")];\n\n for (const item of candidates) {\n if (fs.existsSync(item) && fs.statSync(item).isFile()) {\n return item;\n }\n }\n\n return null;\n}\n\nfunction resolveTsconfigExtends(configPath: string, specifier: string): string | null {\n const fromDir = path.dirname(configPath);\n if (specifier.startsWith(\".\") || specifier.startsWith(\"/\") || specifier.startsWith(\"\\\\\")) {\n return resolveTsconfigPathCandidate(path.resolve(fromDir, specifier));\n }\n\n const requireFromConfig = createRequire(configPath);\n const candidates = [specifier, `${specifier}.json`, path.join(specifier, \"tsconfig.json\")];\n\n for (const item of candidates) {\n try {\n return requireFromConfig.resolve(item);\n } catch {}\n }\n\n return null;\n}\n\nfunction materializeTsconfigPathAliases(\n pathsConfig: Record<string, unknown>,\n baseUrl: string,\n projectRoot: string,\n): Record<string, string> {\n const aliases: Record<string, string> = {};\n\n for (const [find, rawTargets] of Object.entries(pathsConfig)) {\n const target = Array.isArray(rawTargets)\n ? rawTargets.find((value): value is string => typeof value === \"string\")\n : typeof rawTargets === \"string\"\n ? rawTargets\n : null;\n if (!target) continue;\n\n if (find.includes(\"*\") || target.includes(\"*\")) {\n if (!find.endsWith(\"/*\") || !target.endsWith(\"/*\")) continue;\n if (find.indexOf(\"*\") !== find.length - 1 || target.indexOf(\"*\") !== target.length - 1) {\n continue;\n }\n\n const aliasKey = find.slice(0, -2);\n const targetDir = target.slice(0, -2);\n if (!aliasKey || !targetDir) continue;\n\n aliases[aliasKey] = toViteAliasReplacement(path.resolve(baseUrl, targetDir), projectRoot);\n continue;\n }\n\n aliases[find] = toViteAliasReplacement(path.resolve(baseUrl, target), projectRoot);\n }\n\n return aliases;\n}\n\nfunction toViteAliasReplacement(absolutePath: string, projectRoot: string): string {\n const normalizedPath = absolutePath.replace(/\\\\/g, \"/\");\n const rootCandidates = new Set<string>([projectRoot]);\n const realRoot = tryRealpathSync(projectRoot);\n if (realRoot) rootCandidates.add(realRoot);\n\n const pathCandidates = new Set<string>([absolutePath]);\n const realPath = tryRealpathSync(absolutePath);\n if (realPath) pathCandidates.add(realPath);\n\n for (const rootCandidate of rootCandidates) {\n for (const pathCandidate of pathCandidates) {\n if (pathCandidate === rootCandidate) {\n return normalizedPath;\n }\n const relativeId = relativeWithinRoot(rootCandidate, pathCandidate);\n if (relativeId) return \"/\" + relativeId;\n }\n }\n\n return normalizedPath;\n}\n\nfunction loadTsconfigPathAliases(\n configPath: string,\n projectRoot: string,\n seen = new Set<string>(),\n): Record<string, string> {\n const normalizedPath = tryRealpathSync(configPath) ?? configPath;\n if (seen.has(normalizedPath)) return {};\n seen.add(normalizedPath);\n\n let parsed: Record<string, unknown> | null = null;\n try {\n parsed = parseStaticObjectLiteral(fs.readFileSync(normalizedPath, \"utf-8\"));\n } catch {\n return {};\n }\n if (!parsed) return {};\n\n let aliases: Record<string, string> = {};\n if (typeof parsed.extends === \"string\") {\n const extendedPath = resolveTsconfigExtends(normalizedPath, parsed.extends);\n if (extendedPath) {\n aliases = loadTsconfigPathAliases(extendedPath, projectRoot, seen);\n }\n }\n\n const compilerOptions = isRecord(parsed.compilerOptions) ? parsed.compilerOptions : null;\n const pathsConfig =\n compilerOptions && isRecord(compilerOptions.paths) ? compilerOptions.paths : null;\n if (!pathsConfig) return aliases;\n\n const baseUrl =\n compilerOptions && typeof compilerOptions.baseUrl === \"string\" ? compilerOptions.baseUrl : \".\";\n const resolvedBaseUrl = path.resolve(path.dirname(normalizedPath), baseUrl);\n\n return {\n ...aliases,\n ...materializeTsconfigPathAliases(pathsConfig, resolvedBaseUrl, projectRoot),\n };\n}\n\n/**\n * Detect Vite major version at runtime by resolving from cwd.\n * The plugin may be installed in a workspace root with Vite 7 but used\n * by a project that has Vite 8 — so we resolve from cwd, not from\n * the plugin's own location.\n */\nfunction getViteMajorVersion(): number {\n try {\n const require = createRequire(path.join(process.cwd(), \"package.json\"));\n const vitePkg = require(\"vite/package.json\");\n\n const viteMajor = parseInt(vitePkg?.version, 10);\n if (vitePkg?.name === \"vite\" && Number.isFinite(viteMajor)) {\n return viteMajor;\n }\n\n const bundledViteMajor = parseInt(vitePkg?.bundledVersions?.vite, 10);\n if (Number.isFinite(bundledViteMajor)) {\n return bundledViteMajor;\n }\n\n // npm aliases like `vite: npm:@voidzero-dev/vite-plus-core@...` expose the\n // aliased package.json, whose own version is not Vite's version.\n console.warn(\n `[vinext] Could not determine Vite major version from ${vitePkg?.name ?? \"vite/package.json\"}; assuming Vite 7`,\n );\n return 7;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n console.warn(`[vinext] Failed to resolve vite/package.json (${message}); assuming Vite 7`);\n return 7;\n }\n}\n\ntype UserResolveConfigWithTsconfigPaths = NonNullable<UserConfig[\"resolve\"]> & {\n tsconfigPaths?: boolean;\n};\n\n/**\n * PostCSS config file names to search for, in priority order.\n * Matches the same search order as postcss-load-config / lilconfig.\n */\nconst POSTCSS_CONFIG_FILES = [\n \"postcss.config.js\",\n \"postcss.config.cjs\",\n \"postcss.config.mjs\",\n \"postcss.config.ts\",\n \"postcss.config.cts\",\n \"postcss.config.mts\",\n \".postcssrc\",\n \".postcssrc.js\",\n \".postcssrc.cjs\",\n \".postcssrc.mjs\",\n \".postcssrc.ts\",\n \".postcssrc.cts\",\n \".postcssrc.mts\",\n \".postcssrc.json\",\n \".postcssrc.yaml\",\n \".postcssrc.yml\",\n];\n\n/**\n * Module-level cache for resolvePostcssStringPlugins — avoids re-scanning per Vite environment.\n * Stores the Promise itself so concurrent calls (RSC/SSR/Client config() hooks firing in\n * parallel) all await the same in-flight scan rather than each starting their own.\n */\nconst _postcssCache = new Map<string, Promise<{ plugins: unknown[] } | undefined>>();\n// Cache materialized tsconfig/jsconfig aliases so Vite's glob and dynamic-import\n// transforms can see them via resolve.alias without re-reading config files per env.\nconst _tsconfigAliasCache = new Map<string, Record<string, string>>();\n\nfunction resolveTsconfigAliases(projectRoot: string): Record<string, string> {\n if (_tsconfigAliasCache.has(projectRoot)) {\n return _tsconfigAliasCache.get(projectRoot)!;\n }\n\n let aliases: Record<string, string> = {};\n for (const name of TSCONFIG_FILES) {\n const candidate = path.join(projectRoot, name);\n if (!fs.existsSync(candidate)) continue;\n aliases = loadTsconfigPathAliases(candidate, projectRoot);\n break;\n }\n\n _tsconfigAliasCache.set(projectRoot, aliases);\n return aliases;\n}\n\n/**\n * Resolve PostCSS string plugin names in a project's PostCSS config.\n *\n * Next.js (via postcss-load-config) resolves string plugin names in the\n * object form `{ plugins: { \"pkg-name\": opts } }` but NOT in the array form\n * `{ plugins: [\"pkg-name\"] }`. Since many Next.js projects use the array\n * form (particularly with Tailwind CSS v4), we detect this case and resolve\n * the string names to actual plugin functions so Vite can use them.\n *\n * Returns the resolved PostCSS config object to inject into Vite's\n * `css.postcss`, or `undefined` if no resolution is needed.\n */\nfunction resolvePostcssStringPlugins(\n projectRoot: string,\n): Promise<{ plugins: unknown[] } | undefined> {\n if (_postcssCache.has(projectRoot)) return _postcssCache.get(projectRoot)!;\n\n const promise = _resolvePostcssStringPluginsUncached(projectRoot);\n _postcssCache.set(projectRoot, promise);\n return promise;\n}\n\nasync function _resolvePostcssStringPluginsUncached(\n projectRoot: string,\n): Promise<{ plugins: unknown[] } | undefined> {\n // Find the PostCSS config file\n let configPath: string | null = null;\n for (const name of POSTCSS_CONFIG_FILES) {\n const candidate = path.join(projectRoot, name);\n if (fs.existsSync(candidate)) {\n configPath = candidate;\n break;\n }\n }\n if (!configPath) {\n return undefined;\n }\n\n // Load the config file\n // oxlint-disable-next-line typescript/no-explicit-any\n let config: any;\n try {\n if (\n configPath.endsWith(\".json\") ||\n configPath.endsWith(\".yaml\") ||\n configPath.endsWith(\".yml\")\n ) {\n // JSON/YAML configs use object form — postcss-load-config handles these fine\n return undefined;\n }\n // For .postcssrc without extension, check if it's JSON\n if (configPath.endsWith(\".postcssrc\")) {\n const content = fs.readFileSync(configPath, \"utf-8\").trim();\n if (content.startsWith(\"{\")) {\n // JSON format — postcss-load-config handles object form\n return undefined;\n }\n }\n const mod = await import(pathToFileURL(configPath).href);\n config = mod.default ?? mod;\n } catch {\n // If we can't load the config, let Vite/postcss-load-config handle it\n return undefined;\n }\n\n // Only process array-form plugins that contain string entries\n // (either bare strings or tuple form [\"plugin-name\", { options }])\n if (!config || !Array.isArray(config.plugins)) {\n return undefined;\n }\n const hasStringPlugins = config.plugins.some(\n (p: unknown) => typeof p === \"string\" || (Array.isArray(p) && typeof p[0] === \"string\"),\n );\n if (!hasStringPlugins) {\n return undefined;\n }\n\n // Resolve string plugin names to actual plugin functions\n const req = createRequire(path.join(projectRoot, \"package.json\"));\n const resolved = await Promise.all(\n config.plugins.filter(Boolean).map(async (plugin: unknown) => {\n if (typeof plugin === \"string\") {\n const resolved = req.resolve(plugin);\n const mod = await import(pathToFileURL(resolved).href);\n const fn = mod.default ?? mod;\n // If the export is a function, call it to get the plugin instance\n return typeof fn === \"function\" ? fn() : fn;\n }\n // Array tuple form: [\"plugin-name\", { options }]\n if (Array.isArray(plugin) && typeof plugin[0] === \"string\") {\n const [name, options] = plugin;\n const resolved = req.resolve(name);\n const mod = await import(pathToFileURL(resolved).href);\n const fn = mod.default ?? mod;\n return typeof fn === \"function\" ? fn(options) : fn;\n }\n // Already a function or plugin object — pass through\n return plugin;\n }),\n );\n\n return { plugins: resolved };\n}\n\n// Virtual module IDs for Pages Router production build\nconst VIRTUAL_SERVER_ENTRY = \"virtual:vinext-server-entry\";\nconst RESOLVED_SERVER_ENTRY = \"\\0\" + VIRTUAL_SERVER_ENTRY;\nconst VIRTUAL_CLIENT_ENTRY = \"virtual:vinext-client-entry\";\nconst RESOLVED_CLIENT_ENTRY = \"\\0\" + VIRTUAL_CLIENT_ENTRY;\n\n// Virtual module IDs for App Router entries\nconst VIRTUAL_RSC_ENTRY = \"virtual:vinext-rsc-entry\";\nconst RESOLVED_RSC_ENTRY = \"\\0\" + VIRTUAL_RSC_ENTRY;\nconst VIRTUAL_APP_SSR_ENTRY = \"virtual:vinext-app-ssr-entry\";\nconst RESOLVED_APP_SSR_ENTRY = \"\\0\" + VIRTUAL_APP_SSR_ENTRY;\nconst VIRTUAL_APP_BROWSER_ENTRY = \"virtual:vinext-app-browser-entry\";\nconst RESOLVED_APP_BROWSER_ENTRY = \"\\0\" + VIRTUAL_APP_BROWSER_ENTRY;\n/** Image file extensions handled by the vinext:image-imports plugin.\n * Shared between the Rolldown hook filter and the transform handler regex. */\nconst IMAGE_EXTS = \"png|jpe?g|gif|webp|avif|svg|ico|bmp|tiff?\";\n\n/**\n * Extract the npm package name from a module ID (file path).\n * Returns null if not in node_modules.\n *\n * Handles scoped packages (@org/pkg) and pnpm-style paths\n * (node_modules/.pnpm/pkg@ver/node_modules/pkg).\n */\nfunction getPackageName(id: string): string | null {\n const nmIdx = id.lastIndexOf(\"node_modules/\");\n if (nmIdx === -1) return null;\n const rest = id.slice(nmIdx + \"node_modules/\".length);\n if (rest.startsWith(\"@\")) {\n // Scoped package: @org/pkg\n const parts = rest.split(\"/\");\n return parts.length >= 2 ? parts[0] + \"/\" + parts[1] : null;\n }\n return rest.split(\"/\")[0] || null;\n}\n\n/** Absolute path to vinext's shims directory, used by clientManualChunks. */\nconst _shimsDir = path.resolve(__dirname, \"shims\") + \"/\";\nconst _fontGoogleShimPath = resolveShimModulePath(_shimsDir, \"font-google\");\n\n/**\n * manualChunks function for client builds.\n *\n * Splits the client bundle into:\n * - \"framework\" — React, ReactDOM, and scheduler (loaded on every page)\n * - \"vinext\" — vinext shims (router, head, link, etc.)\n *\n * All other vendor code is left to Rollup's default chunk-splitting\n * algorithm. Rollup automatically deduplicates shared modules into\n * common chunks based on the import graph — no manual intervention\n * needed.\n *\n * Why not split every npm package into its own chunk?\n * - Per-package splitting (`vendor-X`) creates 50-200+ chunks for a\n * typical app, far exceeding the ~25-request sweet spot for HTTP/2.\n * - gzip/brotli compress small files poorly — each file restarts with\n * an empty dictionary, losing ~5-15% total compressed size vs fewer\n * larger chunks (Khan Academy measured +2.5% wire size with 10x\n * more files containing less raw code).\n * - ES module evaluation has per-module overhead that compounds on\n * mobile devices.\n * - No major Vite-based framework (Remix, SvelteKit, Astro, TanStack)\n * uses per-package splitting. Next.js only isolates packages >160KB.\n * - Rollup's graph-based splitting already handles the common case\n * well: shared dependencies between routes get their own chunks,\n * and route-specific code stays in route chunks.\n */\nfunction clientManualChunks(id: string): string | undefined {\n // React framework — always loaded, shared across all pages.\n // Isolating React into its own chunk is the single highest-value\n // split: it's ~130KB compressed, loaded on every page, and its\n // content hash rarely changes between deploys.\n if (id.includes(\"node_modules\")) {\n const pkg = getPackageName(id);\n if (!pkg) return undefined;\n if (pkg === \"react\" || pkg === \"react-dom\" || pkg === \"scheduler\") {\n return \"framework\";\n }\n // Let Rollup handle all other vendor code via its default\n // graph-based splitting. This produces a reasonable number of\n // shared chunks (typically 5-15) based on actual import patterns,\n // with good compression efficiency.\n return undefined;\n }\n\n // vinext shims — small runtime, shared across all pages.\n // Use the absolute shims directory path to avoid matching user files\n // that happen to have \"/shims/\" in their path.\n if (id.startsWith(_shimsDir)) {\n return \"vinext\";\n }\n\n return undefined;\n}\n\n/**\n * Rollup output config with manualChunks for client code-splitting.\n * Used by both CLI builds and multi-environment builds.\n *\n * experimentalMinChunkSize merges tiny shared chunks (< 10KB) back into\n * their importers. This reduces HTTP request count and improves gzip\n * compression efficiency — small files restart the compression dictionary,\n * adding ~5-15% wire overhead vs fewer larger chunks.\n */\nconst clientOutputConfig = {\n manualChunks: clientManualChunks,\n experimentalMinChunkSize: 10_000,\n};\n\nconst clientCodeSplittingConfig = {\n minSize: 10_000,\n groups: [\n {\n name(moduleId: string) {\n return clientManualChunks(moduleId) ?? null;\n },\n },\n ],\n};\n\n/**\n * Rollup treeshake configuration for production client builds.\n *\n * Uses the 'recommended' preset as a safe base, then overrides\n * moduleSideEffects to strip unused re-exports from npm packages.\n *\n * The 'no-external' value for moduleSideEffects means:\n * - Local project modules: preserve side effects (CSS imports, polyfills)\n * - node_modules packages: treat as side-effect-free unless exports are used\n *\n * This is the single highest-impact optimization for large barrel-exporting\n * libraries like mermaid, @mui/material, lucide-react, etc. These libraries\n * re-export hundreds of sub-modules through barrel files. Without this,\n * Rollup preserves every sub-module even when only a few exports are consumed.\n *\n * Why 'no-external' instead of false (global side-effect-free)?\n * - User code may rely on import-time side effects (e.g., `import './global.css'`)\n * - 'no-external' is safe for app code while still enabling aggressive DCE for deps\n *\n * Why not the 'smallest' preset?\n * - 'smallest' also sets propertyReadSideEffects: false and\n * tryCatchDeoptimization: false, which can break specific libraries\n * that rely on property access side effects or try/catch for feature detection\n * - 'recommended' + 'no-external' gives most of the benefit with less risk\n *\n * @deprecated Use getClientTreeshakeConfigForVite(viteMajorVersion) instead\n * for Vite version compatibility. Kept for backward compatibility.\n */\nconst clientTreeshakeConfig = {\n preset: \"recommended\" as const,\n moduleSideEffects: \"no-external\" as const,\n};\n\ntype VinextBuildConfig = NonNullable<UserConfig[\"build\"]>;\ntype VinextBuildBundlerOptions = NonNullable<VinextBuildConfig[\"rolldownOptions\"]>;\ntype VinextBuildConfigWithLegacy = VinextBuildConfig & {\n rollupOptions?: VinextBuildBundlerOptions;\n};\n\nfunction getBuildBundlerOptions(\n build: UserConfig[\"build\"] | undefined,\n): VinextBuildBundlerOptions | undefined {\n const buildConfig = build as VinextBuildConfigWithLegacy | undefined;\n return buildConfig?.rolldownOptions ?? buildConfig?.rollupOptions;\n}\n\nfunction withBuildBundlerOptions(\n viteMajorVersion: number,\n bundlerOptions: VinextBuildBundlerOptions,\n): Partial<VinextBuildConfigWithLegacy> {\n return viteMajorVersion >= 8\n ? { rolldownOptions: bundlerOptions }\n : { rollupOptions: bundlerOptions };\n}\n\nfunction getClientOutputConfigForVite(viteMajorVersion: number) {\n return viteMajorVersion >= 8\n ? {\n codeSplitting: clientCodeSplittingConfig,\n }\n : clientOutputConfig;\n}\n\n/**\n * Returns treeshake configuration appropriate for the Vite version.\n *\n * Rollup (Vite 7) supports presets like \"recommended\" which set multiple\n * treeshake options at once. Rolldown (Vite 8+) doesn't support presets,\n * so we only return moduleSideEffects for Vite 8+.\n *\n * The Rollup \"recommended\" preset sets:\n * - annotations: true (Rolldown default is also true)\n * - manualPureFunctions: [] (Rolldown default is also [])\n * - propertyReadSideEffects: true (Rolldown equivalent is 'always', the default)\n * - unknownGlobalSideEffects: false (Rolldown default is true — this is a known acceptable\n * divergence. Slightly less aggressive DCE on unknown globals, acceptable for client bundles)\n * - correctVarValueBeforeDeclaration and tryCatchDeoptimization (Rolldown handles these differently)\n *\n * The key optimization is moduleSideEffects: \"no-external\", which is supported\n * by both bundlers and provides the DCE benefits for barrel-exporting libraries.\n * It treats node_modules as side-effect-free (enabling aggressive DCE) while\n * preserving side effects in local code.\n */\nfunction getClientTreeshakeConfigForVite(viteMajorVersion: number) {\n if (viteMajorVersion >= 8) {\n // Rolldown (Vite 8+) - no preset support, only specific options.\n // Rolldown's built-in defaults already cover what Rollup's 'recommended'\n // preset provides (annotations, correctContext, tryCatchDeoptimization).\n return {\n moduleSideEffects: \"no-external\" as const,\n };\n }\n // Rollup (Vite 7) - supports presets for convenient option grouping\n return {\n preset: \"recommended\" as const,\n moduleSideEffects: \"no-external\" as const,\n };\n}\n\ntype BundleBackfillChunk = {\n type: \"chunk\";\n fileName: string;\n imports?: string[];\n modules?: Record<string, unknown>;\n viteMetadata?: {\n importedCss?: Set<string>;\n importedAssets?: Set<string>;\n };\n};\n\nfunction tryRealpathSync(candidate: string): string | null {\n try {\n return fs.realpathSync.native(candidate);\n } catch {\n return null;\n }\n}\n\nfunction isWindowsAbsolutePath(candidate: string): boolean {\n return /^[a-zA-Z]:[\\\\/]/.test(candidate) || candidate.startsWith(\"\\\\\\\\\");\n}\n\nfunction relativeWithinRoot(root: string, moduleId: string): string | null {\n const useWindowsPath = isWindowsAbsolutePath(root) || isWindowsAbsolutePath(moduleId);\n const relativeId = (\n useWindowsPath ? path.win32.relative(root, moduleId) : path.relative(root, moduleId)\n ).replace(/\\\\/g, \"/\");\n // path.relative(root, root) returns \"\", which is not a usable manifest key and should be\n // treated the same as \"outside root\" for this helper.\n if (!relativeId || relativeId === \"..\" || relativeId.startsWith(\"../\")) return null;\n return relativeId;\n}\n\nfunction normalizeManifestModuleId(moduleId: string, root: string): string {\n const normalizedId = moduleId.replace(/\\\\/g, \"/\");\n if (normalizedId.startsWith(\"\\0\")) return normalizedId;\n if (normalizedId.startsWith(\"node_modules/\") || normalizedId.includes(\"/node_modules/\")) {\n return normalizedId;\n }\n\n if (!isWindowsAbsolutePath(moduleId) && !path.isAbsolute(moduleId)) {\n if (!normalizedId.startsWith(\".\") && !normalizedId.includes(\"../\")) {\n // Preserve bare specifiers like \"pages/counter.tsx\". These are already\n // stable manifest keys and resolving them against root would rewrite them\n // into filesystem paths that no longer match the bundle/module graph.\n return normalizedId;\n }\n }\n\n const rootCandidates = new Set<string>([root]);\n const realRoot = tryRealpathSync(root);\n if (realRoot) rootCandidates.add(realRoot);\n\n const moduleCandidates = new Set<string>();\n if (isWindowsAbsolutePath(moduleId) || path.isAbsolute(moduleId)) {\n moduleCandidates.add(moduleId);\n } else {\n moduleCandidates.add(path.resolve(root, moduleId));\n }\n\n for (const candidate of moduleCandidates) {\n const realCandidate = tryRealpathSync(candidate);\n // Set iteration stays live as entries are appended, so this also checks the\n // realpath variant without needing a second pass or an intermediate array.\n if (realCandidate) moduleCandidates.add(realCandidate);\n }\n\n for (const rootCandidate of rootCandidates) {\n for (const moduleCandidate of moduleCandidates) {\n const relativeId = relativeWithinRoot(rootCandidate, moduleCandidate);\n if (relativeId) return relativeId;\n }\n }\n\n return normalizedId;\n}\n\nfunction augmentSsrManifestFromBundle(\n ssrManifest: Record<string, string[]>,\n bundle: Record<string, BundleBackfillChunk | { type: string }>,\n root: string,\n base = \"/\",\n): Record<string, string[]> {\n const nextManifest = {} as Record<string, Set<string>>;\n\n for (const [key, files] of Object.entries(ssrManifest)) {\n const normalizedKey = normalizeManifestModuleId(key, root);\n if (!nextManifest[normalizedKey]) nextManifest[normalizedKey] = new Set<string>();\n for (const file of files) {\n nextManifest[normalizedKey].add(normalizeManifestFile(file));\n }\n }\n\n for (const item of Object.values(bundle)) {\n if (item.type !== \"chunk\") continue;\n const chunk = item as BundleBackfillChunk;\n\n const files = new Set<string>();\n files.add(manifestFileWithBase(chunk.fileName, base));\n for (const importedFile of chunk.imports ?? []) {\n files.add(manifestFileWithBase(importedFile, base));\n }\n for (const cssFile of chunk.viteMetadata?.importedCss ?? []) {\n files.add(manifestFileWithBase(cssFile, base));\n }\n for (const assetFile of chunk.viteMetadata?.importedAssets ?? []) {\n files.add(manifestFileWithBase(assetFile, base));\n }\n\n for (const moduleId of Object.keys(chunk.modules ?? {})) {\n const key = normalizeManifestModuleId(moduleId, root);\n if (key.startsWith(\"node_modules/\") || key.includes(\"/node_modules/\")) continue;\n if (key.startsWith(\"\\0\")) continue;\n if (!nextManifest[key]) nextManifest[key] = new Set<string>();\n for (const file of files) {\n nextManifest[key].add(file);\n }\n }\n }\n\n return Object.fromEntries(\n Object.entries(nextManifest).map(([key, files]) => [key, [...files]]),\n ) as Record<string, string[]>;\n}\n\nexport type VinextOptions = {\n /**\n * Base directory containing the app/ and pages/ directories.\n * Can be an absolute path or a path relative to the Vite root.\n *\n * By default, vinext auto-detects: checks for app/ and pages/ at the\n * project root first, then falls back to src/app/ and src/pages/.\n */\n appDir?: string;\n /**\n * Force-disable App Router detection even when an app/ directory exists.\n * Only the Pages Router pipeline will be active.\n * Intended for testing and tools that need to build only the Pages Router\n * bundle from a hybrid (app + pages) project.\n * @default false\n */\n disableAppRouter?: boolean;\n /**\n * Override the output directory for the RSC server bundle.\n * Absolute paths are used as-is; relative paths are resolved from the\n * Vite root. Defaults to \"dist/server\".\n * Intended for tests that need to build multiple fixtures in parallel\n * without clobbering each other's output.\n */\n rscOutDir?: string;\n /**\n * Override the output directory for the SSR bundle.\n * Defaults to \"dist/server/ssr\".\n */\n ssrOutDir?: string;\n /**\n * Override the output directory for the client bundle.\n * Defaults to Vite's default (dist/client or dist).\n */\n clientOutDir?: string;\n /**\n * Inline Next.js config for projects that want to configure vinext from\n * vite.config without a separate next.config file.\n *\n * When provided, vinext skips loading next.config.* from disk and uses this\n * value instead. Supports both object-form and function-form config.\n */\n nextConfig?: NextConfigInput;\n /**\n * Auto-register @vitejs/plugin-rsc when an app/ directory is detected.\n * Set to `false` to disable auto-registration (e.g. if you configure\n * @vitejs/plugin-rsc manually with custom options).\n * @default true\n */\n rsc?: boolean;\n /**\n * Options passed to @vitejs/plugin-react (React Fast Refresh + JSX transform).\n * Enabled by default. Set to `false` to disable (e.g. if you configure\n * @vitejs/plugin-react manually in your vite.config.ts), or pass an options\n * object to customize the Babel transform.\n * @default true\n */\n react?: VitePluginReactOptions | boolean;\n /**\n * Enable build-time precompression of static assets (.br, .gz, .zst).\n *\n * When enabled, hashed assets in the client build are precompressed at\n * build time so the production server can serve them without on-the-fly\n * compression overhead.\n *\n * Disabled by default. Not useful when deploying to edge platforms\n * (Cloudflare Workers, Nitro) that handle compression at the CDN layer.\n *\n * Can also be enabled via the `--precompress` CLI flag or by setting the\n * `VINEXT_PRECOMPRESS=1` environment variable (useful for CI pipelines\n * that need to enable precompression without modifying vite.config.ts).\n * @default false\n */\n precompress?: boolean;\n /**\n * Experimental vinext-only feature flags.\n */\n experimental?: {\n /**\n * Dedup client references emitted from RSC proxy modules in dev.\n * Disabled by default until the behavior is better proven across\n * ecosystem apps.\n * @default false\n */\n clientReferenceDedup?: boolean;\n };\n};\n\ntype NitroSetupContext = {\n options: {\n dev?: boolean;\n routeRules?: Record<string, NitroRouteRuleConfig>;\n };\n logger?: {\n warn?: (message: string) => void;\n };\n};\n\nexport default function vinext(options: VinextOptions = {}): PluginOption[] {\n const viteMajorVersion = getViteMajorVersion();\n let root: string;\n let pagesDir: string;\n let appDir: string;\n let hasAppDir = false;\n let hasPagesDir = false;\n let nextConfig: ResolvedNextConfig;\n let fileMatcher: ReturnType<typeof createValidFileMatcher>;\n let middlewarePath: string | null = null;\n let instrumentationPath: string | null = null;\n let instrumentationClientPath: string | null = null;\n let hasCloudflarePlugin = false;\n let warnedInlineNextConfigOverride = false;\n let hasNitroPlugin = false;\n\n // Resolve shim paths - works both from source (.ts) and built (.js)\n const shimsDir = path.resolve(__dirname, \"shims\");\n\n // Shim alias map — populated in config(), used by resolveId() for .js variants\n let nextShimMap: Record<string, string> = {};\n\n /**\n * Generate the virtual SSR server entry module.\n * This is the entry point for `vite build --ssr`.\n */\n async function generateServerEntry(): Promise<string> {\n return _generateServerEntry(\n pagesDir,\n nextConfig,\n fileMatcher,\n middlewarePath,\n instrumentationPath,\n );\n }\n\n /**\n * Generate the virtual client hydration entry module.\n * This is the entry point for `vite build` (client bundle).\n *\n * It maps route patterns to dynamic imports of page modules so Vite\n * code-splits each page into its own chunk. At runtime it reads\n * __NEXT_DATA__ to determine which page to hydrate.\n */\n async function generateClientEntry(): Promise<string> {\n return _generateClientEntry(pagesDir, nextConfig, fileMatcher);\n }\n\n // Auto-register @vitejs/plugin-rsc when App Router is detected.\n // Check eagerly at call time using the same heuristic as config().\n // Must mirror the full detection logic: check {base}/app then {base}/src/app.\n const autoRsc = options.rsc !== false;\n const earlyBaseDir = options.appDir ?? process.cwd();\n const earlyAppDirExists =\n !options.disableAppRouter &&\n (fs.existsSync(path.join(earlyBaseDir, \"app\")) ||\n fs.existsSync(path.join(earlyBaseDir, \"src\", \"app\")));\n\n // IMPORTANT: Resolve @vitejs/plugin-rsc subpath imports from the user's\n // project root, not from vinext's own package location. When vinext is\n // installed via symlink (npm file: deps, pnpm workspace:*), a bare\n // import() resolves from vinext's realpath, which can find a different\n // copy of the RSC plugin (and transitively a different copy of vite).\n // This causes instanceof RunnableDevEnvironment checks to fail at\n // runtime because the Vite server and the RSC plugin end up with\n // different class identities. Resolving from the project root ensures a\n // single shared vite instance.\n //\n // Pre-resolve both the main plugin and the /transforms subpath eagerly\n // so all import() calls in this module use consistent resolution.\n let resolvedReactPath: string | null = null;\n let resolvedRscPath: string | null = null;\n let resolvedRscTransformsPath: string | null = null;\n // Prefer the user's project graph so vinext shares the app's Vite/plugin\n // instances. In source/workspace development, test fixtures may not declare\n // peer deps explicitly, so fall back to vinext's own install location.\n resolvedReactPath = resolveOptionalDependency(earlyBaseDir, \"@vitejs/plugin-react\");\n resolvedRscPath = resolveOptionalDependency(earlyBaseDir, \"@vitejs/plugin-rsc\");\n resolvedRscTransformsPath = resolveOptionalDependency(\n earlyBaseDir,\n \"@vitejs/plugin-rsc/transforms\",\n );\n\n // If app/ exists and auto-RSC is enabled, create a lazy Promise that\n // resolves to the configured RSC plugin array. Vite's asyncFlatten\n // will resolve this before processing the plugin list.\n let rscPluginPromise: Promise<Plugin[]> | null = null;\n if (earlyAppDirExists && autoRsc) {\n if (!resolvedRscPath) {\n throw new Error(\n \"vinext: App Router detected but @vitejs/plugin-rsc is not installed.\\n\" +\n \"Run: \" +\n detectPackageManager(process.cwd()) +\n \" @vitejs/plugin-rsc\",\n );\n }\n const rscImport = import(pathToFileURL(resolvedRscPath).href);\n rscPluginPromise = rscImport\n .then((mod) => {\n const rsc = mod.default;\n return rsc({\n entries: {\n rsc: VIRTUAL_RSC_ENTRY,\n ssr: VIRTUAL_APP_SSR_ENTRY,\n client: VIRTUAL_APP_BROWSER_ENTRY,\n },\n });\n })\n .catch((cause) => {\n throw new Error(\"vinext: Failed to load @vitejs/plugin-rsc.\", { cause });\n });\n }\n\n const reactOptions = options.react && options.react !== true ? options.react : undefined;\n\n let reactPluginPromise: Promise<PluginOption[]> | null = null;\n if (options.react !== false) {\n if (!resolvedReactPath) {\n throw new Error(\n \"vinext: @vitejs/plugin-react is not installed.\\n\" +\n \"Run: \" +\n detectPackageManager(process.cwd()) +\n \" @vitejs/plugin-react\",\n );\n }\n const reactImport = import(pathToFileURL(resolvedReactPath).href);\n reactPluginPromise = reactImport\n .then((mod) => (mod as VitePluginReactModule).default(reactOptions))\n .catch((cause) => {\n throw new Error(\"vinext: Failed to load @vitejs/plugin-react.\", { cause });\n });\n }\n\n const imageImportDimCache = new Map<string, { width: number; height: number }>();\n\n // Shared state for the MDX proxy plugin. We auto-inject @mdx-js/rollup when\n // MDX is detected in app/pages during config(), and lazily on first plain\n // .mdx transform for MDX that only enters the graph via import.meta.glob.\n let mdxDelegate: Plugin | null = null;\n // Cached across calls — only the first invocation's `reason` affects logging.\n // This is correct because config() always runs before transform() in the same build.\n let mdxDelegatePromise: Promise<Plugin | null> | null = null;\n let hasUserMdxPlugin = false;\n let warnedMissingMdxPlugin = false;\n\n async function ensureMdxDelegate(reason: \"detected\" | \"on-demand\"): Promise<Plugin | null> {\n // Reuse the auto-injected delegate once it has been created.\n // If the user registered their own MDX plugin and `mdxDelegate` is still null,\n // return null here so transform() falls through without handling the file and\n // the user's plugin can process the .mdx module later in the pipeline.\n // Note: hasUserMdxPlugin is set during config(), which runs before transform().\n if (mdxDelegate || hasUserMdxPlugin) return mdxDelegate;\n if (!mdxDelegatePromise) {\n mdxDelegatePromise = (async () => {\n try {\n const mdxRollup = await import(\"@mdx-js/rollup\");\n const mdxFactory = (mdxRollup.default ?? mdxRollup) as (\n options: Record<string, unknown>,\n ) => Plugin;\n const mdxOpts: Record<string, unknown> = {};\n if (nextConfig.mdx) {\n if (nextConfig.mdx.remarkPlugins) mdxOpts.remarkPlugins = nextConfig.mdx.remarkPlugins;\n if (nextConfig.mdx.rehypePlugins) mdxOpts.rehypePlugins = nextConfig.mdx.rehypePlugins;\n if (nextConfig.mdx.recmaPlugins) mdxOpts.recmaPlugins = nextConfig.mdx.recmaPlugins;\n }\n const delegate = mdxFactory(mdxOpts);\n mdxDelegate = delegate;\n if (reason === \"detected\") {\n if (nextConfig.mdx) {\n console.log(\n \"[vinext] Auto-injected @mdx-js/rollup with remark/rehype plugins from next.config\",\n );\n } else {\n console.log(\"[vinext] Auto-injected @mdx-js/rollup for MDX support\");\n }\n } else {\n console.log(\"[vinext] Auto-injected @mdx-js/rollup for on-demand MDX support\");\n }\n return delegate;\n } catch {\n // Only warn during \"detected\" path (MDX files in app/pages at config time).\n // For \"on-demand\" (MDX encountered during transform), the error thrown\n // in transform() is more actionable and immediate. Avoid double messaging.\n if (reason === \"detected\" && !warnedMissingMdxPlugin) {\n warnedMissingMdxPlugin = true;\n console.warn(\n \"[vinext] MDX files detected but @mdx-js/rollup is not installed. \" +\n \"Install it with: \" +\n detectPackageManager(process.cwd()) +\n \" @mdx-js/rollup\",\n );\n }\n return null;\n }\n })();\n }\n return mdxDelegatePromise;\n }\n\n const plugins: PluginOption[] = [\n // Resolve tsconfig paths/baseUrl aliases so real-world Next.js repos\n // that use @/*, #/*, or baseUrl imports work out of the box.\n // Vite 8+ supports this natively via resolve.tsconfigPaths.\n ...(viteMajorVersion >= 8 ? [] : [tsconfigPaths()]),\n // React Fast Refresh + JSX transform for client components.\n reactPluginPromise,\n // Transform CJS require()/module.exports to ESM before other plugins\n // analyze imports (RSC directive scanning, shim resolution, etc.)\n commonjs(),\n // Fix 'use server' closure variable collision with local declarations.\n // See packages/vinext/src/plugins/fix-use-server-closure-collision.ts for details.\n fixUseServerClosureCollisionPlugin,\n {\n name: \"vinext:config\",\n enforce: \"pre\",\n\n async config(config, env) {\n root = config.root ?? process.cwd();\n const userResolve = config.resolve as UserResolveConfigWithTsconfigPaths | undefined;\n const shouldEnableNativeTsconfigPaths =\n viteMajorVersion >= 8 && userResolve?.tsconfigPaths === undefined;\n const tsconfigPathAliases = resolveTsconfigAliases(root);\n\n // Load .env files into process.env before anything else.\n // Next.js loads .env files before evaluating next.config.js, so\n // env vars are available in config, server-side code, and as\n // NEXT_PUBLIC_* defines for the client bundle.\n // Pass '' as prefix to load ALL vars, not just VITE_-prefixed ones.\n const mode = env?.mode ?? \"development\";\n const envDir = config.envDir ?? root;\n const dotenvVars = loadEnv(mode, envDir, \"\");\n for (const [key, value] of Object.entries(dotenvVars)) {\n if (process.env[key] === undefined) {\n process.env[key] = value;\n }\n }\n // Align NODE_ENV with Next.js semantics: build -> production, serve -> development.\n // Next.js unconditionally forces NODE_ENV during build/dev, so we do the same.\n let resolvedNodeEnv: string;\n if (mode === \"test\") {\n resolvedNodeEnv = \"test\";\n } else if (env?.command === \"build\") {\n resolvedNodeEnv = \"production\";\n } else {\n resolvedNodeEnv = \"development\";\n }\n if (process.env.NODE_ENV !== resolvedNodeEnv) {\n process.env.NODE_ENV = resolvedNodeEnv;\n }\n\n // Resolve the base directory for app/pages detection.\n // If appDir is provided, resolve it (supports both relative and absolute paths).\n // If not provided, auto-detect: check root first, then src/ subdirectory.\n let baseDir: string;\n if (options.appDir) {\n baseDir = path.isAbsolute(options.appDir)\n ? options.appDir\n : path.resolve(root, options.appDir);\n } else {\n // Auto-detect: prefer root-level app/ and pages/, fall back to src/\n const hasRootApp = fs.existsSync(path.join(root, \"app\"));\n const hasRootPages = fs.existsSync(path.join(root, \"pages\"));\n const hasSrcApp = fs.existsSync(path.join(root, \"src\", \"app\"));\n const hasSrcPages = fs.existsSync(path.join(root, \"src\", \"pages\"));\n\n if (hasRootApp || hasRootPages) {\n baseDir = root;\n } else if (hasSrcApp || hasSrcPages) {\n baseDir = path.join(root, \"src\");\n } else {\n baseDir = root;\n }\n }\n\n pagesDir = path.join(baseDir, \"pages\");\n appDir = path.join(baseDir, \"app\");\n hasPagesDir = fs.existsSync(pagesDir);\n hasAppDir = !options.disableAppRouter && fs.existsSync(appDir);\n\n // Load next.config.js if present (always from project root, not src/),\n // unless vinext({ nextConfig }) explicitly overrides it.\n // Guard: resolve nextConfig only once per plugin instance. In Vite's\n // multi-environment build the config hook fires once per environment;\n // without this guard, resolveNextConfig() → resolveBuildId() generates\n // a fresh random UUID each time, causing different buildId values to be\n // baked into the RSC, SSR, and client bundles.\n // Note: fileMatcher, instrumentationPath, etc. are intentionally set\n // outside this guard — they are cheap and deterministic, and keeping\n // them here ensures they reflect the final resolved root on every call.\n if (!nextConfig) {\n const phase =\n env?.command === \"build\" ? PHASE_PRODUCTION_BUILD : PHASE_DEVELOPMENT_SERVER;\n let rawConfig: NextConfig | null;\n if (options.nextConfig) {\n const diskConfigPath = findNextConfigPath(root);\n if (diskConfigPath && !warnedInlineNextConfigOverride) {\n warnedInlineNextConfigOverride = true;\n console.warn(\n `[vinext] vinext({ nextConfig }) overrides ${path.basename(diskConfigPath)}. Remove one of the config sources to avoid drift.`,\n );\n }\n rawConfig = await resolveNextConfigInput(options.nextConfig, phase);\n } else {\n rawConfig = await loadNextConfig(root, phase);\n }\n nextConfig = await resolveNextConfig(rawConfig, root);\n }\n fileMatcher = createValidFileMatcher(nextConfig.pageExtensions);\n instrumentationPath = findInstrumentationFile(root, fileMatcher);\n instrumentationClientPath = findInstrumentationClientFile(root, fileMatcher);\n middlewarePath = findMiddlewareFile(root, fileMatcher);\n\n // Merge env from next.config.js with NEXT_PUBLIC_* env vars\n const defines = getNextPublicEnvDefines();\n if (\n !config.define ||\n typeof config.define !== \"object\" ||\n !(\"process.env.NODE_ENV\" in config.define)\n ) {\n defines[\"process.env.NODE_ENV\"] = JSON.stringify(resolvedNodeEnv);\n }\n for (const [key, value] of Object.entries(nextConfig.env)) {\n // Skip NODE_ENV from next.config.js env — Next.js ignores it too,\n // and it would silently override the value we just set above.\n if (key === \"NODE_ENV\") continue;\n defines[`process.env.${key}`] = JSON.stringify(value);\n }\n // Expose basePath to client-side code\n defines[\"process.env.__NEXT_ROUTER_BASEPATH\"] = JSON.stringify(nextConfig.basePath);\n // Expose image remote patterns for validation in next/image shim\n defines[\"process.env.__VINEXT_IMAGE_REMOTE_PATTERNS\"] = JSON.stringify(\n JSON.stringify(nextConfig.images?.remotePatterns ?? []),\n );\n defines[\"process.env.__VINEXT_IMAGE_DOMAINS\"] = JSON.stringify(\n JSON.stringify(nextConfig.images?.domains ?? []),\n );\n // Expose allowed image widths (union of deviceSizes + imageSizes) for\n // server-side validation. Matches Next.js behavior: only configured\n // sizes are accepted by the image optimization endpoint.\n {\n const deviceSizes = nextConfig.images?.deviceSizes ?? [\n 640, 750, 828, 1080, 1200, 1920, 2048, 3840,\n ];\n const imageSizes = nextConfig.images?.imageSizes ?? [16, 32, 48, 64, 96, 128, 256, 384];\n defines[\"process.env.__VINEXT_IMAGE_DEVICE_SIZES\"] = JSON.stringify(\n JSON.stringify(deviceSizes),\n );\n defines[\"process.env.__VINEXT_IMAGE_SIZES\"] = JSON.stringify(JSON.stringify(imageSizes));\n }\n // Expose dangerouslyAllowSVG flag for the image shim's auto-skip logic.\n // When false (default), .svg sources bypass the optimization endpoint.\n defines[\"process.env.__VINEXT_IMAGE_DANGEROUSLY_ALLOW_SVG\"] = JSON.stringify(\n String(nextConfig.images?.dangerouslyAllowSVG ?? false),\n );\n // Draft mode secret — generated once at build time so the\n // __prerender_bypass cookie is consistent across all server\n // instances (e.g. multiple Cloudflare Workers isolates).\n defines[\"process.env.__VINEXT_DRAFT_SECRET\"] = JSON.stringify(crypto.randomUUID());\n // Build ID — resolved from next.config generateBuildId() or random UUID.\n // Exposed so server entries and the next/server shim can inject it.\n // Also used to namespace ISR cache keys so old cached entries from a\n // previous deploy are never served by the new one.\n defines[\"process.env.__VINEXT_BUILD_ID\"] = JSON.stringify(nextConfig.buildId);\n\n // Build the shim alias map. Exact `.js` variants are included for the\n // public Next entrypoints that are file-backed in `next/package.json`.\n // Some libraries (for example `nuqs`) import `next/navigation.js`\n // directly; aliasing the `.js` form ensures optimizeDeps pre-bundles\n // vinext's shim instead of real Next.\n nextShimMap = Object.fromEntries(\n Object.entries({\n \"next/link\": path.join(shimsDir, \"link\"),\n \"next/head\": path.join(shimsDir, \"head\"),\n \"next/router\": path.join(shimsDir, \"router\"),\n \"next/compat/router\": path.join(shimsDir, \"compat-router\"),\n \"next/image\": path.join(shimsDir, \"image\"),\n \"next/legacy/image\": path.join(shimsDir, \"legacy-image\"),\n \"next/dynamic\": path.join(shimsDir, \"dynamic\"),\n \"next/app\": path.join(shimsDir, \"app\"),\n \"next/document\": path.join(shimsDir, \"document\"),\n \"next/config\": path.join(shimsDir, \"config\"),\n \"next/script\": path.join(shimsDir, \"script\"),\n \"next/server\": path.join(shimsDir, \"server\"),\n \"next/navigation\": path.join(shimsDir, \"navigation\"),\n \"next/headers\": path.join(shimsDir, \"headers\"),\n \"next/font/google\": path.join(shimsDir, \"font-google\"),\n \"next/font/local\": path.join(shimsDir, \"font-local\"),\n \"next/cache\": path.join(shimsDir, \"cache\"),\n \"next/form\": path.join(shimsDir, \"form\"),\n \"next/og\": path.join(shimsDir, \"og\"),\n \"next/web-vitals\": path.join(shimsDir, \"web-vitals\"),\n \"next/amp\": path.join(shimsDir, \"amp\"),\n \"next/error\": path.join(shimsDir, \"error\"),\n \"next/constants\": path.join(shimsDir, \"constants\"),\n // Internal next/dist/* paths used by popular libraries\n // (next-intl, @clerk/nextjs, @sentry/nextjs, next-nprogress-bar, etc.)\n \"next/dist/shared/lib/app-router-context.shared-runtime\": path.join(\n shimsDir,\n \"internal\",\n \"app-router-context\",\n ),\n \"next/dist/shared/lib/app-router-context\": path.join(\n shimsDir,\n \"internal\",\n \"app-router-context\",\n ),\n \"next/dist/shared/lib/router-context.shared-runtime\": path.join(\n shimsDir,\n \"internal\",\n \"router-context\",\n ),\n \"next/dist/shared/lib/utils\": path.join(shimsDir, \"internal\", \"utils\"),\n \"next/dist/server/api-utils\": path.join(shimsDir, \"internal\", \"api-utils\"),\n \"next/dist/server/web/spec-extension/cookies\": path.join(\n shimsDir,\n \"internal\",\n \"cookies\",\n ),\n \"next/dist/compiled/@edge-runtime/cookies\": path.join(shimsDir, \"internal\", \"cookies\"),\n \"next/dist/server/app-render/work-unit-async-storage.external\": path.join(\n shimsDir,\n \"internal\",\n \"work-unit-async-storage\",\n ),\n \"next/dist/client/components/work-unit-async-storage.external\": path.join(\n shimsDir,\n \"internal\",\n \"work-unit-async-storage\",\n ),\n \"next/dist/client/components/request-async-storage.external\": path.join(\n shimsDir,\n \"internal\",\n \"work-unit-async-storage\",\n ),\n \"next/dist/client/components/request-async-storage\": path.join(\n shimsDir,\n \"internal\",\n \"work-unit-async-storage\",\n ),\n // Re-export public modules for internal path imports\n \"next/dist/client/components/navigation\": path.join(shimsDir, \"navigation\"),\n \"next/dist/server/config-shared\": path.join(shimsDir, \"internal\", \"utils\"),\n // server-only / client-only marker packages\n \"server-only\": path.join(shimsDir, \"server-only\"),\n \"client-only\": path.join(shimsDir, \"client-only\"),\n \"vinext/error-boundary\": path.join(shimsDir, \"error-boundary\"),\n \"vinext/layout-segment-context\": path.join(shimsDir, \"layout-segment-context\"),\n \"vinext/metadata\": path.join(shimsDir, \"metadata\"),\n \"vinext/fetch-cache\": path.join(shimsDir, \"fetch-cache\"),\n \"vinext/cache-runtime\": path.join(shimsDir, \"cache-runtime\"),\n \"vinext/navigation-state\": path.join(shimsDir, \"navigation-state\"),\n \"vinext/unified-request-context\": path.join(shimsDir, \"unified-request-context\"),\n \"vinext/router-state\": path.join(shimsDir, \"router-state\"),\n \"vinext/head-state\": path.join(shimsDir, \"head-state\"),\n \"vinext/i18n-state\": path.join(shimsDir, \"i18n-state\"),\n \"vinext/i18n-context\": path.join(shimsDir, \"i18n-context\"),\n \"vinext/cache\": path.resolve(__dirname, \"cache\"),\n \"vinext/instrumentation\": path.resolve(__dirname, \"server\", \"instrumentation\"),\n \"vinext/instrumentation-client\": path.resolve(\n __dirname,\n \"client\",\n \"instrumentation-client\",\n ),\n \"vinext/html\": path.resolve(__dirname, \"server\", \"html\"),\n \"private-next-instrumentation-client\":\n instrumentationClientPath ?? path.resolve(__dirname, \"client\", \"empty-module\"),\n }).flatMap(([k, v]) =>\n k.startsWith(\"next/\")\n ? [\n [k, v],\n [`${k}.js`, v],\n ]\n : [[k, v]],\n ),\n );\n\n // Detect if Cloudflare's vite plugin is present — if so, skip\n // SSR externals (Workers bundle everything, can't have Node.js externals).\n const pluginsFlat: unknown[] = [];\n function flattenPlugins(arr: unknown[]) {\n for (const p of arr) {\n if (Array.isArray(p)) flattenPlugins(p);\n else if (p) pluginsFlat.push(p);\n }\n }\n flattenPlugins((config.plugins as unknown[]) ?? []);\n hasCloudflarePlugin = pluginsFlat.some(\n (p: unknown) =>\n p &&\n typeof p === \"object\" &&\n \"name\" in p &&\n typeof p.name === \"string\" &&\n (p.name === \"vite-plugin-cloudflare\" || p.name.startsWith(\"vite-plugin-cloudflare:\")),\n );\n hasNitroPlugin = pluginsFlat.some(\n (p: unknown) =>\n p &&\n typeof p === \"object\" &&\n \"name\" in p &&\n typeof p.name === \"string\" &&\n (p.name === \"nitro\" || p.name.startsWith(\"nitro:\")),\n );\n\n // Resolve PostCSS string plugin names that Vite can't handle.\n // Next.js projects commonly use array-form plugins like\n // `plugins: [\"@tailwindcss/postcss\"]` which postcss-load-config\n // doesn't resolve (only object-form keys are resolved). We detect\n // this and resolve the strings to actual plugin functions, then\n // inject via css.postcss so Vite uses the resolved plugins.\n // Only do this if the user hasn't already set css.postcss inline.\n // oxlint-disable-next-line typescript/no-explicit-any\n let postcssOverride: { plugins: any[] } | undefined;\n if (!config.css?.postcss || typeof config.css.postcss === \"string\") {\n postcssOverride = await resolvePostcssStringPlugins(root);\n }\n\n // Auto-inject @mdx-js/rollup when MDX files exist and no MDX plugin is\n // already configured. Applies remark/rehype plugins from next.config.\n hasUserMdxPlugin = pluginsFlat.some(\n (p: unknown) =>\n p &&\n typeof p === \"object\" &&\n \"name\" in p &&\n typeof p.name === \"string\" &&\n (p.name === \"@mdx-js/rollup\" || p.name === \"mdx\"),\n );\n if (\n !hasUserMdxPlugin &&\n hasMdxFiles(root, hasAppDir ? appDir : null, hasPagesDir ? pagesDir : null)\n ) {\n await ensureMdxDelegate(\"detected\");\n }\n\n // Detect if this is a standalone SSR build (set by `vite build --ssr`\n // or `build.ssr` in config). SSR builds must NOT use manualChunks\n // because they use inlineDynamicImports which is incompatible.\n const isSSR = !!config.build?.ssr;\n // Detect if this is a multi-environment build (App Router or Cloudflare).\n // In multi-env builds, manualChunks must only be set per-environment\n // (on the client env), not globally — otherwise it leaks into RSC/SSR\n // environments where it can cause asset resolution issues.\n const isMultiEnv = hasAppDir || hasCloudflarePlugin || hasNitroPlugin;\n\n const viteConfig: UserConfig = {\n // Disable Vite's default HTML serving - we handle all routing\n appType: \"custom\",\n build: {\n ...withBuildBundlerOptions(viteMajorVersion, {\n // Suppress \"Module level directives cause errors when bundled\"\n // warnings for \"use client\" / \"use server\" directives. Our shims\n // and third-party libraries legitimately use these directives;\n // they are handled by the RSC plugin and are harmless in the\n // final bundle. We preserve any user-supplied onwarn so custom\n // warning handling is not lost.\n onwarn: (() => {\n const userOnwarn = getBuildBundlerOptions(config.build)?.onwarn;\n return (warning, defaultHandler) => {\n if (\n warning.code === \"MODULE_LEVEL_DIRECTIVE\" &&\n (warning.message?.includes('\"use client\"') ||\n warning.message?.includes('\"use server\"'))\n ) {\n return;\n }\n // Dynamic route pages that don't export generateStaticParams\n // produce IMPORT_IS_UNDEFINED warnings because the virtual RSC\n // entry unconditionally references mod?.generateStaticParams for\n // every dynamic route. The ?. guards the access safely at runtime;\n // suppress the build-time noise.\n if (\n warning.code === \"IMPORT_IS_UNDEFINED\" &&\n warning.message?.includes(\"generateStaticParams\")\n ) {\n return;\n }\n // proxy.ts / middleware.ts may export either a named handler\n // or default export. The generated virtual entries probe both\n // forms and validate at runtime, which can trigger noisy\n // IMPORT_IS_UNDEFINED warnings when only one form exists.\n // Match any file extension because findMiddlewareFile() scans\n // all configured pageExtensions, not just .ts/.js.\n if (\n warning.code === \"IMPORT_IS_UNDEFINED\" &&\n /Import `(?:default|proxy|middleware)` will always be undefined/.test(\n warning.message ?? \"\",\n ) &&\n /\\b(?:proxy|middleware)\\.\\w+\\b/.test(warning.message ?? \"\") &&\n (warning.message?.includes(\"virtual:vinext-rsc-entry\") ||\n warning.message?.includes(\"virtual:vinext-server-entry\"))\n ) {\n return;\n }\n if (userOnwarn) {\n userOnwarn(warning, defaultHandler);\n } else {\n defaultHandler(warning);\n }\n };\n })(),\n // Enable aggressive tree-shaking for client builds.\n // See getClientTreeshakeConfigForVite JSDoc for rationale.\n // Only apply globally for standalone client builds (Pages Router\n // CLI). For multi-environment builds (App Router, Cloudflare),\n // treeshake is set per-environment on the client env below to\n // avoid leaking into RSC/SSR environments where\n // moduleSideEffects: 'no-external' could drop server packages\n // that rely on module-level side effects.\n ...(!isSSR && !isMultiEnv\n ? { treeshake: getClientTreeshakeConfigForVite(viteMajorVersion) }\n : {}),\n // Code-split client bundles: separate framework (React/ReactDOM),\n // vinext runtime (shims), and vendor packages into their own\n // chunks so pages only load the JS they need.\n // Only apply globally for standalone client builds (CLI Pages\n // Router). For multi-environment builds (App Router, Cloudflare),\n // manualChunks is set per-environment on the client env below\n // to avoid leaking into RSC/SSR environments.\n ...(!isSSR && !isMultiEnv\n ? { output: getClientOutputConfigForVite(viteMajorVersion) }\n : {}),\n }),\n },\n // Let OPTIONS requests pass through Vite's CORS middleware to our\n // route handlers so they can set the Allow header and run user-defined\n // OPTIONS handlers. Without this, Vite's CORS middleware responds to\n // OPTIONS with a 204 before the request reaches vinext's handler.\n // Keep Vite's default restrictive origin policy by explicitly\n // setting it. Without the `origin` field, `preflightContinue: true`\n // would override Vite's default and allow any origin.\n server: {\n cors: {\n preflightContinue: true,\n origin: /^https?:\\/\\/(?:(?:[^:]+\\.)?localhost|127\\.0\\.0\\.1|\\[::1\\])(?::\\d+)?$/,\n },\n },\n // Configure SSR transform behaviour for Node targets.\n // - `external`: React packages are loaded natively by Node (CJS)\n // rather than through Vite's ESM evaluator.\n // - `noExternal: true`: force everything else through Vite's\n // transform pipeline so non-JS imports (CSS, images) from\n // node_modules don't hit Node's native ESM loader.\n // Any user-provided `ssr.noExternal` is intentionally superseded\n // by this setting; only `ssr.external` entries escape Vite's transform.\n // Skip when targeting bundled runtimes (Cloudflare/Nitro bundle everything).\n // This also resolves extensionless-import issues in packages like\n // `validator` (see #189) by routing them through Vite's resolver.\n ...(hasCloudflarePlugin || hasNitroPlugin\n ? {}\n : {\n ssr: {\n external: [\"react\", \"react-dom\", \"react-dom/server\"],\n noExternal: true,\n },\n }),\n resolve: {\n // Materialize simple tsconfig/jsconfig path aliases into resolve.alias\n // so Vite can transform import.meta.glob(\"@/...\") and import(`@/...`).\n alias: { ...tsconfigPathAliases, ...nextConfig.aliases, ...nextShimMap },\n // Dedupe React packages to prevent dual-instance errors.\n // When vinext is linked (npm link / bun link) or any dependency\n // brings its own React copy, multiple React instances can load,\n // causing cryptic \"Invalid hook call\" errors. This is a no-op\n // when only one copy exists.\n dedupe: [\"react\", \"react-dom\", \"react/jsx-runtime\", \"react/jsx-dev-runtime\"],\n ...(shouldEnableNativeTsconfigPaths ? { tsconfigPaths: true } : {}),\n },\n // NOTE: top-level optimizeDeps is now set below (after capturing\n // incoming values from earlier plugins) so both Pages Router and\n // App Router builds merge correctly.\n // Enable JSX in .tsx/.jsx files\n // Vite 7 uses `esbuild` for transforms, Vite 8+ uses `oxc`\n ...(viteMajorVersion >= 8\n ? { oxc: { jsx: { runtime: \"automatic\" } } }\n : { esbuild: { jsx: \"automatic\" } }),\n // Define env vars for client bundle\n define: defines,\n // Set base path if configured\n ...(nextConfig.basePath ? { base: nextConfig.basePath + \"/\" } : {}),\n // Inject resolved PostCSS plugins if string names were found\n ...(postcssOverride ? { css: { postcss: postcssOverride } } : {}),\n };\n\n // Collect user-provided ssr.external so we can propagate it into\n // both the RSC and SSR environment configs. Vite's `ssr.*` config\n // only applies to the default `ssr` environment, not custom ones\n // like `rsc`. Native addon packages (e.g. better-sqlite3) listed\n // in ssr.external must be externalized from ALL server environments.\n // Vite's SSROptions.external is `string[] | true`; handle both forms.\n //\n // Also merge in `serverExternalPackages` from next.config (and the\n // legacy `experimental.serverComponentsExternalPackages` alias). These\n // are packages that Next.js intentionally skips bundling and loads\n // natively — e.g. packages that import Node-specific entry points via\n // conditional exports (like `file-type` which exports `fileTypeFromFile`\n // only from its `node` condition, not from the universal `default` one).\n // Without externalizing them, Vite's optimizer picks the wrong export\n // condition and the build fails with MISSING_EXPORT errors.\n const nextServerExternal: string[] = nextConfig?.serverExternalPackages ?? [];\n const userSsrExternal: string[] | true = Array.isArray(config.ssr?.external)\n ? [...config.ssr.external, ...nextServerExternal]\n : config.ssr?.external === true\n ? true\n : nextServerExternal;\n\n // Capture top-level optimizeDeps populated by earlier plugins\n // (e.g. @lingui/vite-plugin) so we merge rather than overwrite.\n // Moved above the hasAppDir branch so both Pages Router and App\n // Router code paths can use these values.\n const incomingExclude: string[] =\n (config.optimizeDeps?.exclude as string[] | undefined) ?? [];\n const incomingInclude: string[] =\n (config.optimizeDeps?.include as string[] | undefined) ?? [];\n\n // Merge incoming excludes into the top-level optimizeDeps so\n // Pages Router builds (which don't set per-environment configs)\n // also preserve entries from earlier plugins.\n viteConfig.optimizeDeps = {\n exclude: [...new Set([...incomingExclude, \"vinext\", \"@vercel/og\"])],\n ...(incomingInclude.length > 0 ? { include: incomingInclude } : {}),\n };\n const pagesOptimizeEntries = !hasAppDir\n ? [\n ...(hasPagesDir\n ? [toRelativeFileEntry(root, pagesDir) + \"/**/*.{tsx,ts,jsx,js}\"]\n : []),\n ...[instrumentationPath, instrumentationClientPath].flatMap((entry) =>\n entry ? [toRelativeFileEntry(root, entry)] : [],\n ),\n ]\n : [];\n\n // If app/ directory exists, configure RSC environments\n if (hasAppDir) {\n // Compute optimizeDeps.entries so Vite discovers server-side\n // dependencies at startup instead of on first request. Without\n // this, deps imported in rsc/ssr environments are found lazily,\n // causing re-optimisation cascades and runtime errors (e.g.\n // \"Invalid hook call\" from duplicate React instances).\n // The entries must be relative to the project root.\n const relAppDir = path.relative(root, appDir);\n const appEntries = [`${relAppDir}/**/*.{tsx,ts,jsx,js}`];\n const explicitInstrumentationEntries = [\n instrumentationPath,\n instrumentationClientPath,\n ].flatMap((entry) => (entry ? [toRelativeFileEntry(root, entry)] : []));\n const optimizeEntries = [...new Set([...appEntries, ...explicitInstrumentationEntries])];\n\n viteConfig.environments = {\n rsc: {\n ...(hasCloudflarePlugin || hasNitroPlugin\n ? {}\n : {\n resolve: {\n // Externalize native/heavy packages so the RSC environment\n // loads them natively via Node rather than through Vite's\n // ESM module evaluator (which can't handle native addons).\n // Note: Do NOT externalize react/react-dom here — they must\n // be bundled with the \"react-server\" condition for RSC.\n // Skip when targeting bundled runtimes (Cloudflare/Nitro).\n external:\n userSsrExternal === true\n ? true\n : [\"satori\", \"@resvg/resvg-js\", \"yoga-wasm-web\", ...userSsrExternal],\n // Force all node_modules through Vite's transform pipeline\n // so non-JS imports (CSS, images) don't hit Node's native\n // ESM loader. Matches Next.js behavior of bundling everything.\n // Packages in `external` above take precedence per Vite rules.\n // When user sets `ssr.external: true`, skip noExternal since\n // everything is already externalized.\n ...(userSsrExternal === true ? {} : { noExternal: true as const }),\n },\n }),\n optimizeDeps: {\n exclude: [...new Set([...incomingExclude, \"vinext\", \"@vercel/og\"])],\n entries: optimizeEntries,\n },\n build: {\n outDir: options.rscOutDir ?? \"dist/server\",\n ...withBuildBundlerOptions(viteMajorVersion, {\n input: { index: VIRTUAL_RSC_ENTRY },\n }),\n },\n },\n ssr: {\n ...(hasCloudflarePlugin || hasNitroPlugin\n ? {}\n : {\n resolve: {\n external: userSsrExternal === true ? true : [...userSsrExternal],\n // Force all node_modules through Vite's transform pipeline\n // so non-JS imports (CSS, images) don't hit Node's native\n // ESM loader. Matches Next.js behavior of bundling everything.\n // When user sets `ssr.external: true`, skip noExternal since\n // everything is already externalized.\n ...(userSsrExternal === true ? {} : { noExternal: true as const }),\n },\n }),\n optimizeDeps: {\n exclude: [...new Set([...incomingExclude, \"vinext\", \"@vercel/og\"])],\n entries: optimizeEntries,\n },\n build: {\n outDir: options.ssrOutDir ?? \"dist/server/ssr\",\n ...withBuildBundlerOptions(viteMajorVersion, {\n input: { index: VIRTUAL_APP_SSR_ENTRY },\n }),\n },\n },\n client: {\n // Explicitly mark as client consumer so other plugins (e.g. Nitro)\n // can detect this during configEnvironment hooks — before Vite\n // applies the default consumer based on environment name.\n // Without this, Nitro's configEnvironment creates a server-side\n // service for the client environment, causing virtual module\n // imports to leak to Node's native ESM loader (ERR_UNSUPPORTED_ESM_URL_SCHEME).\n consumer: \"client\",\n optimizeDeps: {\n // Exclude server-external packages from the client dep optimizer.\n // These packages are server-only by design (listed in next.config's\n // `serverExternalPackages`). If the client optimizer crawls into\n // them through app/ entries, it will use browser export conditions\n // and pick the wrong conditional export (e.g. `file-type` exports\n // `fileTypeFromFile` only from its `node` condition via `index.js`,\n // but the browser optimizer resolves to `core.js` which lacks it,\n // causing MISSING_EXPORT build failures).\n exclude: [\n ...new Set([...incomingExclude, \"vinext\", \"@vercel/og\", ...nextServerExternal]),\n ],\n // Crawl app/ source files up front so client-only deps imported\n // by user components are discovered during startup instead of\n // triggering a late re-optimisation + full page reload.\n entries: optimizeEntries,\n // React packages aren't crawled from app/ source files,\n // so must be pre-included to avoid late discovery (#25).\n include: [\n ...new Set([\n ...incomingInclude,\n \"react\",\n \"react-dom\",\n \"react-dom/client\",\n \"react/jsx-runtime\",\n \"react/jsx-dev-runtime\",\n ]),\n ],\n },\n build: {\n // When targeting Cloudflare Workers, enable manifest generation\n // so the vinext:cloudflare-build closeBundle hook can read the\n // client build manifest, compute lazy chunks (only reachable\n // via dynamic imports), and inject __VINEXT_LAZY_CHUNKS__ into\n // the worker entry. Without this, all chunks are modulepreloaded\n // on every page — defeating code-splitting for React.lazy() and\n // next/dynamic boundaries.\n ...(hasCloudflarePlugin ? { manifest: true } : {}),\n ...withBuildBundlerOptions(viteMajorVersion, {\n input: { index: VIRTUAL_APP_BROWSER_ENTRY },\n output: getClientOutputConfigForVite(viteMajorVersion),\n treeshake: getClientTreeshakeConfigForVite(viteMajorVersion),\n }),\n },\n },\n };\n } else if (hasCloudflarePlugin) {\n // Pages Router on Cloudflare Workers: add a client environment\n // so the multi-environment build produces client JS bundles\n // alongside the worker. Without this, only the worker is built\n // and there's no client-side hydration.\n viteConfig.environments = {\n client: {\n consumer: \"client\",\n optimizeDeps:\n pagesOptimizeEntries.length > 0 ? { entries: pagesOptimizeEntries } : undefined,\n build: {\n manifest: true,\n ssrManifest: true,\n ...withBuildBundlerOptions(viteMajorVersion, {\n input: { index: VIRTUAL_CLIENT_ENTRY },\n output: getClientOutputConfigForVite(viteMajorVersion),\n treeshake: getClientTreeshakeConfigForVite(viteMajorVersion),\n }),\n },\n },\n };\n } else if (!isSSR && !getBuildBundlerOptions(config.build)?.input) {\n // Plain Pages Router (Node): define client + ssr environments so\n // createBuilder + buildApp() produces both dist/client and\n // dist/server/entry.js. Without this, buildApp() only sees the\n // default client environment and never builds the server entry.\n // Guard with !isSSR and no explicit input so legacy vite.build()\n // calls that specify their own input (tests, hybrid build step)\n // still work via the single-build path — injecting environments\n // alongside an explicit build input conflicts with the caller's intent.\n viteConfig.environments = {\n client: {\n consumer: \"client\",\n optimizeDeps:\n pagesOptimizeEntries.length > 0 ? { entries: pagesOptimizeEntries } : undefined,\n build: {\n outDir: \"dist/client\",\n manifest: true,\n ssrManifest: true,\n ...withBuildBundlerOptions(viteMajorVersion, {\n input: { index: VIRTUAL_CLIENT_ENTRY },\n output: getClientOutputConfigForVite(viteMajorVersion),\n treeshake: getClientTreeshakeConfigForVite(viteMajorVersion),\n }),\n },\n },\n ssr: {\n resolve: {\n external: [\"react\", \"react-dom\", \"react-dom/server\"],\n noExternal: true as const,\n },\n build: {\n outDir: \"dist/server\",\n ...withBuildBundlerOptions(viteMajorVersion, {\n input: { index: VIRTUAL_SERVER_ENTRY },\n output: {\n entryFileNames: \"entry.js\",\n },\n }),\n },\n },\n };\n }\n\n if (pagesOptimizeEntries.length > 0 && !hasCloudflarePlugin) {\n viteConfig.optimizeDeps = {\n ...viteConfig.optimizeDeps,\n entries: pagesOptimizeEntries,\n };\n }\n\n return viteConfig;\n },\n\n configResolved(config) {\n // Detect double React plugin registration. When vinext auto-injects\n // @vitejs/plugin-react AND the user also registers it manually, the\n // React transform / refresh pipeline runs twice.\n if (reactPluginPromise) {\n // Assumes @vitejs/plugin-react top-level plugin names continue to use\n // the vite:react* prefix across supported versions.\n const reactRootPlugins = config.plugins.filter(\n (p: unknown) =>\n p &&\n typeof p === \"object\" &&\n \"name\" in p &&\n typeof p.name === \"string\" &&\n p.name.startsWith(\"vite:react\"),\n );\n const counts = new Map<string, number>();\n for (const plugin of reactRootPlugins) {\n counts.set(plugin.name, (counts.get(plugin.name) ?? 0) + 1);\n }\n const hasDuplicateReactPlugin = [...counts.values()].some((count) => count > 1);\n if (hasDuplicateReactPlugin) {\n throw new Error(\n \"[vinext] Duplicate @vitejs/plugin-react detected.\\n\" +\n \" vinext auto-registers @vitejs/plugin-react by default.\\n\" +\n \" Your config also registers it manually, which duplicates React transforms.\\n\\n\" +\n \" Fix: remove the explicit react() call from your plugins array.\\n\" +\n \" Or: pass react: false to vinext() if you want to configure react() yourself.\",\n );\n }\n }\n\n // Detect double RSC plugin registration. When vinext auto-injects\n // @vitejs/plugin-rsc AND the user also registers it manually, the\n // RSC transform pipeline runs twice — doubling build time.\n // Rather than trying to magically fix this at runtime, fail fast\n // with a clear error telling the user how to fix their config.\n if (rscPluginPromise) {\n // Count top-level RSC plugins (name === \"rsc\") — each call to\n // the rsc() factory produces exactly one plugin with this name.\n const rscRootPlugins = config.plugins.filter(\n (p: unknown) => p && typeof p === \"object\" && \"name\" in p && p.name === \"rsc\",\n );\n if (rscRootPlugins.length > 1) {\n throw new Error(\n \"[vinext] Duplicate @vitejs/plugin-rsc detected.\\n\" +\n \" vinext auto-registers @vitejs/plugin-rsc when app/ is detected.\\n\" +\n \" Your config also registers it manually, which doubles build time.\\n\\n\" +\n \" Fix: remove the explicit rsc() call from your plugins array.\\n\" +\n \" Or: pass rsc: false to vinext() if you want to configure rsc() yourself.\",\n );\n }\n }\n\n // Fail the build when targeting Cloudflare Workers without the\n // cloudflare() plugin. Without it, wrangler's esbuild can't resolve\n // virtual:vinext-rsc-entry and produces a cryptic error. (#325)\n if (\n config.command === \"build\" &&\n !hasCloudflarePlugin &&\n !hasNitroPlugin &&\n hasWranglerConfig(root) &&\n !options.disableAppRouter\n ) {\n throw new Error(\n formatMissingCloudflarePluginError({\n isAppRouter: hasAppDir,\n configFile: config.configFile,\n }),\n );\n }\n },\n\n resolveId: {\n // Hook filter: only invoke JS for next/* imports and virtual:vinext-* modules.\n // Matches \"next/navigation\", \"next/router.js\", \"virtual:vinext-rsc-entry\",\n // and \\0-prefixed re-imports from @vitejs/plugin-rsc.\n filter: {\n id: /(?:next\\/|virtual:vinext-)/,\n },\n handler(id) {\n // Strip \\0 prefix if present — @vitejs/plugin-rsc's generated\n // browser entry imports our virtual module using the already-resolved\n // ID (with \\0 prefix). We need to re-resolve it so the client\n // environment's import-analysis can find it.\n const cleanId = id.startsWith(\"\\0\") ? id.slice(1) : id;\n\n // Pages Router virtual modules\n if (cleanId === VIRTUAL_SERVER_ENTRY) return RESOLVED_SERVER_ENTRY;\n if (cleanId === VIRTUAL_CLIENT_ENTRY) return RESOLVED_CLIENT_ENTRY;\n if (\n cleanId.endsWith(\"/\" + VIRTUAL_SERVER_ENTRY) ||\n cleanId.endsWith(\"\\\\\" + VIRTUAL_SERVER_ENTRY)\n ) {\n return RESOLVED_SERVER_ENTRY;\n }\n if (\n cleanId.endsWith(\"/\" + VIRTUAL_CLIENT_ENTRY) ||\n cleanId.endsWith(\"\\\\\" + VIRTUAL_CLIENT_ENTRY)\n ) {\n return RESOLVED_CLIENT_ENTRY;\n }\n // App Router virtual modules\n if (cleanId === VIRTUAL_RSC_ENTRY) return RESOLVED_RSC_ENTRY;\n if (cleanId === VIRTUAL_APP_SSR_ENTRY) return RESOLVED_APP_SSR_ENTRY;\n if (cleanId === VIRTUAL_APP_BROWSER_ENTRY) return RESOLVED_APP_BROWSER_ENTRY;\n if (cleanId.startsWith(VIRTUAL_GOOGLE_FONTS + \"?\")) {\n return RESOLVED_VIRTUAL_GOOGLE_FONTS + cleanId.slice(VIRTUAL_GOOGLE_FONTS.length);\n }\n if (\n cleanId.endsWith(\"/\" + VIRTUAL_RSC_ENTRY) ||\n cleanId.endsWith(\"\\\\\" + VIRTUAL_RSC_ENTRY)\n ) {\n return RESOLVED_RSC_ENTRY;\n }\n if (\n cleanId.endsWith(\"/\" + VIRTUAL_APP_SSR_ENTRY) ||\n cleanId.endsWith(\"\\\\\" + VIRTUAL_APP_SSR_ENTRY)\n ) {\n return RESOLVED_APP_SSR_ENTRY;\n }\n if (\n cleanId.endsWith(\"/\" + VIRTUAL_APP_BROWSER_ENTRY) ||\n cleanId.endsWith(\"\\\\\" + VIRTUAL_APP_BROWSER_ENTRY)\n ) {\n return RESOLVED_APP_BROWSER_ENTRY;\n }\n if (\n cleanId.includes(\"/\" + VIRTUAL_GOOGLE_FONTS + \"?\") ||\n cleanId.includes(\"\\\\\" + VIRTUAL_GOOGLE_FONTS + \"?\")\n ) {\n const queryIndex = cleanId.indexOf(VIRTUAL_GOOGLE_FONTS + \"?\");\n return (\n RESOLVED_VIRTUAL_GOOGLE_FONTS +\n cleanId.slice(queryIndex + VIRTUAL_GOOGLE_FONTS.length)\n );\n }\n },\n },\n\n async load(id) {\n // Pages Router virtual modules\n if (id === RESOLVED_SERVER_ENTRY) {\n return await generateServerEntry();\n }\n if (id === RESOLVED_CLIENT_ENTRY) {\n return await generateClientEntry();\n }\n // App Router virtual modules\n if (id === RESOLVED_RSC_ENTRY && hasAppDir) {\n const routes = await appRouter(appDir, nextConfig?.pageExtensions, fileMatcher);\n const metaRoutes = scanMetadataFiles(appDir);\n // Check for global-error.tsx at app root\n const globalErrorPath = findFileWithExts(appDir, \"global-error\", fileMatcher);\n return generateRscEntry(\n appDir,\n routes,\n middlewarePath,\n metaRoutes,\n globalErrorPath,\n nextConfig?.basePath,\n nextConfig?.trailingSlash,\n {\n redirects: nextConfig?.redirects,\n rewrites: nextConfig?.rewrites,\n headers: nextConfig?.headers,\n allowedOrigins: nextConfig?.serverActionsAllowedOrigins,\n allowedDevOrigins: nextConfig?.allowedDevOrigins,\n bodySizeLimit: nextConfig?.serverActionsBodySizeLimit,\n i18n: nextConfig?.i18n,\n hasPagesDir,\n publicFiles: scanPublicFileRoutes(root),\n },\n instrumentationPath,\n );\n }\n if (id === RESOLVED_APP_SSR_ENTRY && hasAppDir) {\n return generateSsrEntry(hasPagesDir);\n }\n if (id === RESOLVED_APP_BROWSER_ENTRY && hasAppDir) {\n return generateBrowserEntry();\n }\n if (id.startsWith(RESOLVED_VIRTUAL_GOOGLE_FONTS + \"?\")) {\n return generateGoogleFontsVirtualModule(id, _fontGoogleShimPath);\n }\n },\n },\n // Stub node:async_hooks in client builds — see src/plugins/async-hooks-stub.ts\n asyncHooksStubPlugin,\n createInstrumentationClientTransformPlugin(() => instrumentationClientPath),\n // Dedup client references from RSC proxy modules — see src/plugins/client-reference-dedup.ts\n ...(options.experimental?.clientReferenceDedup ? [clientReferenceDedupPlugin()] : []),\n // Proxy plugin for @mdx-js/rollup. The real MDX plugin is created lazily\n // during vinext:config's config() (when MDX files are detected), but\n // plugins returned from config() hooks run too late in the pipeline —\n // after vite:import-analysis. This top-level proxy with enforce:\"pre\"\n // ensures MDX transforms run at the correct stage. Both vinext:config\n // and this proxy are enforce:\"pre\", and vinext:config comes first in\n // the array, so mdxDelegate is already set when this proxy's hooks fire.\n {\n name: \"vinext:mdx\",\n enforce: \"pre\",\n config(config, env) {\n if (!mdxDelegate?.config) return;\n const hook = mdxDelegate.config;\n const fn = typeof hook === \"function\" ? hook : hook.handler;\n return fn.call(this, config, env);\n },\n async transform(code, id, options) {\n // Skip ?raw and other query imports — @mdx-js/rollup ignores the query\n // and would compile the file as MDX instead of returning raw text.\n if (id.includes(\"?\")) return;\n // Case-insensitive extension check for cross-platform compatibility\n // (Windows/macOS case-insensitive, Linux case-sensitive)\n if (!id.toLowerCase().endsWith(\".mdx\")) return;\n\n const delegate = mdxDelegate ?? (await ensureMdxDelegate(\"on-demand\"));\n if (delegate?.transform) {\n const hook = delegate.transform;\n const transform = typeof hook === \"function\" ? hook : hook.handler;\n return transform.call(this, code, id, options);\n }\n\n if (!hasUserMdxPlugin) {\n throw new Error(\n `[vinext] Encountered MDX module ${id} but no MDX plugin is configured. ` +\n `Install @mdx-js/rollup or register an MDX plugin manually.`,\n );\n }\n },\n },\n // Shim React canary/experimental APIs (ViewTransition, addTransitionType)\n // that exist in Next.js's bundled React canary but not in stable React 19.\n // Provides graceful no-op fallbacks so projects using these APIs degrade\n // instead of crashing with \"does not provide an export named 'ViewTransition'\".\n {\n name: \"vinext:react-canary\",\n enforce: \"pre\",\n\n resolveId(id) {\n if (id === \"virtual:vinext-react-canary\") return \"\\0virtual:vinext-react-canary\";\n },\n\n load(id) {\n if (id === \"\\0virtual:vinext-react-canary\") {\n return [\n `export * from \"react\";`,\n `export { default } from \"react\";`,\n `import * as _React from \"react\";`,\n `export const ViewTransition = _React.ViewTransition || function ViewTransition({ children }) { return children; };`,\n `export const addTransitionType = _React.addTransitionType || function addTransitionType() {};`,\n ].join(\"\\n\");\n }\n },\n\n transform(code, id) {\n // Only transform user source files, not node_modules or virtual modules\n if (id.includes(\"node_modules\")) return null;\n if (id.startsWith(\"\\0\")) return null;\n if (!/\\.(tsx?|jsx?|mjs)$/.test(id)) return null;\n\n // Quick check: does this file reference canary APIs and import from \"react\"?\n if (\n !(code.includes(\"ViewTransition\") || code.includes(\"addTransitionType\")) ||\n !/from\\s+['\"]react['\"]/.test(code)\n ) {\n return null;\n }\n\n // Only rewrite if the import actually destructures a canary API\n const canaryImportRegex =\n /import\\s*\\{[^}]*(ViewTransition|addTransitionType)[^}]*\\}\\s*from\\s*['\"]react['\"]/;\n if (!canaryImportRegex.test(code)) return null;\n\n // Rewrite all `from \"react\"` / `from 'react'` to use the canary shim.\n // This is safe because the virtual module re-exports everything from\n // react, so non-canary imports continue to work.\n const result = code.replace(/from\\s*['\"]react['\"]/g, 'from \"virtual:vinext-react-canary\"');\n if (result !== code) {\n return { code: result, map: null };\n }\n return null;\n },\n },\n {\n name: \"vinext:pages-router\",\n\n // HMR: trigger full-reload for Pages Router page changes.\n // Even with @vitejs/plugin-react providing React Fast Refresh,\n // the Pages Router injects hydration via inline <script type=\"module\">\n // which may not be tracked in Vite's module graph. Explicitly\n // sending full-reload ensures changes are always reflected in\n // the browser.\n hotUpdate(options: { file: string; server: ViteDevServer; modules: unknown[] }) {\n if (!hasPagesDir || hasAppDir) return;\n if (options.file.startsWith(pagesDir) && fileMatcher.extensionRegex.test(options.file)) {\n options.server.environments.client.hot.send({ type: \"full-reload\" });\n return [];\n }\n },\n\n configureServer(server: ViteDevServer) {\n // Watch pages directory for file additions/removals to invalidate route cache.\n const pageExtensions = fileMatcher.extensionRegex;\n\n // Build a long-lived ModuleRunner for loading all Pages Router modules\n // (middleware, API routes, SSR page rendering) on every request.\n //\n // We must NOT use server.ssrLoadModule() here: when @cloudflare/vite-plugin\n // is present its environments replace the SSR transport, causing\n // SSRCompatModuleRunner to crash with:\n // TypeError: Cannot read properties of undefined (reading 'outsideEmitter')\n // on the very first request.\n //\n // createDirectRunner() builds a runner on environment.fetchModule() which\n // is a plain async method — safe with all plugin combinations, including\n // @cloudflare/vite-plugin.\n //\n // The runner is created lazily on first use so that all environments are\n // fully registered before we inspect them. We prefer \"ssr\", then any\n // non-\"rsc\" environment, then whatever is available.\n let pagesRunner: import(\"vite/module-runner\").ModuleRunner | null = null;\n function getPagesRunner() {\n if (!pagesRunner) {\n const env =\n server.environments[\"ssr\"] ??\n Object.values(server.environments).find((e) => e !== server.environments[\"rsc\"]) ??\n Object.values(server.environments)[0];\n pagesRunner = createDirectRunner(env);\n }\n return pagesRunner;\n }\n\n /**\n * Invalidate the virtual RSC entry module in Vite's module graph.\n *\n * The App Router route table is baked into the virtual RSC entry\n * at generation time. When routes are added or removed, clearing\n * the route cache alone is not enough: the virtual module must\n * also be invalidated so Vite re-calls the load() hook to\n * regenerate the entry with the updated route table.\n */\n function invalidateRscEntryModule() {\n const rscEnv = server.environments[\"rsc\"];\n if (!rscEnv) return;\n const mod = rscEnv.moduleGraph.getModuleById(RESOLVED_RSC_ENTRY);\n if (mod) {\n rscEnv.moduleGraph.invalidateModule(mod);\n rscEnv.hot.send({ type: \"full-reload\" });\n }\n }\n\n server.watcher.on(\"add\", (filePath: string) => {\n if (hasPagesDir && filePath.startsWith(pagesDir) && pageExtensions.test(filePath)) {\n invalidateRouteCache(pagesDir);\n }\n if (hasAppDir && filePath.startsWith(appDir) && pageExtensions.test(filePath)) {\n invalidateAppRouteCache();\n invalidateRscEntryModule();\n }\n });\n server.watcher.on(\"unlink\", (filePath: string) => {\n if (hasPagesDir && filePath.startsWith(pagesDir) && pageExtensions.test(filePath)) {\n invalidateRouteCache(pagesDir);\n }\n if (hasAppDir && filePath.startsWith(appDir) && pageExtensions.test(filePath)) {\n invalidateAppRouteCache();\n invalidateRscEntryModule();\n }\n });\n\n // ── Dev request origin check ─────────────────────────────────────\n // Registered directly (not in the returned function) so it runs\n // BEFORE Vite's built-in middleware. This ensures all requests\n // (including /@*, /__vite*, /node_modules* paths) are validated\n // before Vite serves any content.\n server.middlewares.use((req, res, next) => {\n const blockReason = validateDevRequest(\n {\n origin: req.headers.origin as string | undefined,\n host: req.headers.host,\n \"x-forwarded-host\": req.headers[\"x-forwarded-host\"] as string | undefined,\n \"sec-fetch-site\": req.headers[\"sec-fetch-site\"] as string | undefined,\n \"sec-fetch-mode\": req.headers[\"sec-fetch-mode\"] as string | undefined,\n },\n nextConfig?.allowedDevOrigins,\n );\n if (blockReason) {\n console.warn(`[vinext] Blocked dev request: ${blockReason} (${req.url})`);\n res.writeHead(403, { \"Content-Type\": \"text/plain\" });\n res.end(\"Forbidden\");\n return;\n }\n next();\n });\n\n // Return a function to register middleware AFTER Vite's built-in middleware\n return () => {\n // Run instrumentation.ts register() if present (once at server startup).\n // Must be inside the returned function so that all environments are\n // fully registered before getPagesRunner() inspects them.\n //\n // App Router: register() is baked into the generated RSC entry as a\n // top-level await, so it runs inside the Worker process (or RSC Vite\n // environment) — the same process as request handling. Calling\n // runInstrumentation() here too would run it a second time in the host\n // process, which is wrong when @cloudflare/vite-plugin is present.\n //\n // Pages Router prod: register() is baked into generateServerEntry() as\n // a top-level await, so it runs inside the Worker bundle — the same\n // process as request handling. configureServer() is never called during\n // a prod build, so there is no double-invocation risk there either.\n //\n // We pass getPagesRunner() (createDirectRunner) rather than server so\n // that this is safe when @cloudflare/vite-plugin is present. That\n // plugin replaces the SSR environment's hot channel, causing\n // server.ssrLoadModule() to crash with outsideEmitter. The runner\n // calls environment.fetchModule() directly and never touches the hot\n // channel, making it safe with all Vite plugin combinations.\n if (instrumentationPath && !hasAppDir) {\n runInstrumentation(getPagesRunner(), instrumentationPath).catch((err) => {\n console.error(\"[vinext] Instrumentation error:\", err);\n });\n }\n // App Router request logging in dev server\n //\n // For App Router, the RSC plugin handles requests internally.\n // We install a timing middleware here that:\n // 1. Intercepts writeHead() to pluck the X-Vinext-Timing header\n // (compileMs,renderMs) that the RSC entry attaches before\n // it is flushed to the client.\n // 2. Logs the full request after res finishes, using those timings.\n if (hasAppDir) {\n server.middlewares.use((req, res, next) => {\n const url = req.url ?? \"/\";\n // Skip Vite internals, HMR, and static assets.\n // Do NOT skip .rsc-suffixed URLs or RSC wire requests (Accept: text/x-component)\n // — those are soft navigations and should be logged like any other page request.\n const [pathname] = url.split(\"?\");\n if (\n url.startsWith(\"/@\") ||\n url.startsWith(\"/__vite\") ||\n url.startsWith(\"/node_modules\") ||\n (url.includes(\".\") && !pathname.endsWith(\".html\") && !pathname.endsWith(\".rsc\"))\n ) {\n return next();\n }\n const _reqStart = now();\n let _compileMs: number | undefined;\n let _renderMs: number | undefined;\n\n // Intercept setHeader and writeHead so we can strip X-Vinext-Timing\n // before it reaches the client and capture the compile/render split.\n // The RSC plugin may set headers either way depending on its version.\n // Parse the three-part X-Vinext-Timing header:\n // \"handlerStart,inHandlerCompileMs,renderMs\"\n //\n // True compile time = time the RSC plugin spent loading/transforming\n // modules before our handler code ran, plus any in-handler work before\n // renderToReadableStream. Concretely:\n // compileMs = (handlerStart - _reqStart) + inHandlerCompileMs\n // renderMs = renderMs from header, or -1 for RSC-only (soft-nav)\n // responses where rendering is not measured in the handler.\n // In that case the middleware computes render time as\n // totalMs - compileMs.\n //\n // handlerStart is performance.now() recorded at the very top of\n // _handleRequest in the generated RSC entry. _reqStart is recorded\n // here in the Node middleware, one stack frame before the RSC plugin\n // loads the module. The gap between them is exactly the Vite\n // compile/transform cost.\n function _parseTiming(raw: unknown) {\n const [handlerStart, inHandlerCompileMs, renderMs] = String(raw)\n .split(\",\")\n .map((v) => Number(v));\n if (\n !Number.isNaN(handlerStart) &&\n !Number.isNaN(inHandlerCompileMs) &&\n inHandlerCompileMs !== -1\n ) {\n _compileMs =\n Math.max(0, Math.round(handlerStart - _reqStart)) + inHandlerCompileMs;\n }\n if (!Number.isNaN(renderMs) && renderMs !== -1) {\n _renderMs = renderMs;\n }\n }\n\n const _origSetHeader = res.setHeader.bind(res);\n res.setHeader = function (name, value) {\n if (name.toLowerCase() === \"x-vinext-timing\") {\n _parseTiming(value);\n return res; // drop the header — don't forward to client\n }\n return _origSetHeader(name, value);\n };\n\n const _origWriteHead = res.writeHead.bind(res);\n // oxlint-disable-next-line typescript/no-explicit-any\n res.writeHead = function (statusCode, ...args: any[]) {\n // Normalise the optional headers argument (may be reason, headers object, or both).\n let headers: Record<string, unknown> | undefined;\n const [reasonOrHeaders, maybeHeaders] = args;\n if (typeof reasonOrHeaders === \"string\") {\n headers = maybeHeaders;\n } else {\n headers = reasonOrHeaders;\n }\n\n // Pull timing out of the headers object when present.\n if (headers && typeof headers === \"object\" && !Array.isArray(headers)) {\n const timingKey = Object.keys(headers).find(\n (k) => k.toLowerCase() === \"x-vinext-timing\",\n );\n if (timingKey) {\n _parseTiming(headers[timingKey]);\n delete headers[timingKey];\n }\n }\n\n return _origWriteHead(statusCode, ...args);\n };\n\n res.on(\"finish\", () => {\n // Strip .rsc suffix — it's an internal RSC protocol detail,\n // not part of the actual page path the user navigated to.\n const logUrl = url.replace(/\\.rsc(\\?|$)/, \"$1\");\n const totalMs = now() - _reqStart;\n\n // For RSC-only responses (soft nav), renderMs is -1 (sentinel meaning\n // \"not measured in the handler\"). Compute it as totalMs - compileMs,\n // which is how long the RSC stream took to fully flush to the client —\n // matching what Next.js shows for soft navigations.\n const resolvedRenderMs =\n _renderMs !== undefined\n ? _renderMs\n : _compileMs !== undefined\n ? Math.max(0, Math.round(totalMs - _compileMs))\n : undefined;\n\n logRequest({\n method: req.method ?? \"GET\",\n url: logUrl,\n status: res.statusCode,\n totalMs,\n compileMs: _compileMs,\n renderMs: resolvedRenderMs,\n });\n });\n\n next();\n });\n }\n\n server.middlewares.use(async (req, res, next) => {\n try {\n let url: string = req.url ?? \"/\";\n\n // If no pages directory, skip this middleware entirely\n // (app router is handled by @vitejs/plugin-rsc's built-in middleware)\n if (!hasPagesDir) return next();\n\n // Skip Vite internal requests and static files\n if (\n url.startsWith(\"/@\") ||\n url.startsWith(\"/__vite\") ||\n url.startsWith(\"/node_modules\")\n ) {\n return next();\n }\n\n // Skip .rsc requests — those are for the App Router RSC handler\n if (url.split(\"?\")[0].endsWith(\".rsc\")) {\n return next();\n }\n\n // ── Cross-origin request protection (defense-in-depth) ──────\n // The pre-Vite middleware above already blocks cross-origin\n // requests before Vite serves any content. This second check\n // guards the Pages Router handler specifically, in case the\n // middleware ordering changes or new middleware is added between\n // the two. Both calls use the same validateDevRequest() function.\n const blockReason = validateDevRequest(\n {\n origin: req.headers.origin as string | undefined,\n host: req.headers.host,\n \"x-forwarded-host\": req.headers[\"x-forwarded-host\"] as string | undefined,\n \"sec-fetch-site\": req.headers[\"sec-fetch-site\"] as string | undefined,\n \"sec-fetch-mode\": req.headers[\"sec-fetch-mode\"] as string | undefined,\n },\n nextConfig?.allowedDevOrigins,\n );\n if (blockReason) {\n console.warn(`[vinext] Blocked dev request: ${blockReason} (${url})`);\n res.writeHead(403, { \"Content-Type\": \"text/plain\" });\n res.end(\"Forbidden\");\n return;\n }\n\n // ── Image optimization passthrough (dev mode) ─────────────\n // In dev, redirect to the original asset URL so Vite serves it.\n if (url.split(\"?\")[0] === \"/_vinext/image\") {\n const imgParams = new URLSearchParams(url.split(\"?\")[1] ?? \"\");\n const rawImgUrl = imgParams.get(\"url\");\n // Normalize backslashes: browsers and the URL constructor treat\n // /\\evil.com as //evil.com, bypassing the // check.\n const imgUrl = rawImgUrl?.replaceAll(\"\\\\\", \"/\") ?? null;\n // Allowlist: must start with \"/\" but not \"//\" — blocks absolute\n // URLs, protocol-relative, backslash variants, and exotic schemes.\n // Also block internal Vite paths (/@*, /__vite*, /node_modules*)\n // to prevent redirecting to dev server endpoints.\n if (\n !imgUrl ||\n !imgUrl.startsWith(\"/\") ||\n imgUrl.startsWith(\"//\") ||\n imgUrl.startsWith(\"/@\") ||\n imgUrl.startsWith(\"/__vite\") ||\n imgUrl.startsWith(\"/node_modules\")\n ) {\n res.writeHead(400);\n res.end(!rawImgUrl ? \"Missing url parameter\" : \"Only relative URLs allowed\");\n return;\n }\n // Validate the constructed URL's origin hasn't changed (defense in depth).\n const resolvedImg = new URL(imgUrl, `http://${req.headers.host || \"localhost\"}`);\n if (resolvedImg.origin !== `http://${req.headers.host || \"localhost\"}`) {\n res.writeHead(400);\n res.end(\"Only relative URLs allowed\");\n return;\n }\n const encodedLocation = resolvedImg.pathname + resolvedImg.search;\n res.writeHead(302, { Location: encodedLocation });\n res.end();\n return;\n }\n\n // Vite's built-in middleware may rewrite \"/\" to \"/index.html\".\n // Normalize it back so our router can match correctly.\n const rawPathname = url.split(\"?\")[0];\n if (rawPathname.endsWith(\"/index.html\")) {\n url = url.replace(\"/index.html\", \"/\");\n } else if (rawPathname.endsWith(\".html\")) {\n // Strip .html extensions (e.g. \"/about.html\" -> \"/about\")\n url = url.replace(/\\.html(?=\\?|$)/, \"\");\n }\n\n // Skip requests for files with extensions (static assets)\n let pathname = url.split(\"?\")[0];\n if (pathname.includes(\".\") && !pathname.endsWith(\".html\")) {\n return next();\n }\n\n // Guard against protocol-relative URL open redirects.\n // Normalize backslashes first: browsers treat /\\ as // in URL\n // context. Check the RAW pathname before normalizePath so the\n // guard fires before normalizePath collapses //.\n pathname = pathname.replaceAll(\"\\\\\", \"/\");\n if (pathname.startsWith(\"//\")) {\n res.writeHead(404);\n res.end(\"404 Not Found\");\n return;\n }\n\n // Normalize the pathname to prevent path-confusion attacks.\n // decodeURIComponent prevents /%61dmin bypassing /admin matchers.\n // normalizePath collapses // and resolves . / .. segments.\n try {\n pathname = normalizePath(normalizePathnameForRouteMatchStrict(pathname));\n } catch {\n // Malformed percent-encoding (e.g. /%E0%A4%A) — return 400 instead of crashing.\n res.writeHead(400);\n res.end(\"Bad Request\");\n return;\n }\n\n // Strip basePath prefix from URL for route matching.\n // All internal routing uses basePath-free paths.\n //\n // NOTE: When basePath is set, we also set Vite's `base` config to\n // `basePath + \"/\"`. Vite's connect middleware stack strips the base\n // prefix from req.url before passing it to our middleware, so the\n // URL will already lack the basePath prefix. We still attempt to\n // strip it (for robustness) but don't reject paths that don't start\n // with basePath — Vite has already done the filtering.\n const bp = nextConfig?.basePath ?? \"\";\n if (bp && pathname.startsWith(bp)) {\n const stripped = pathname.slice(bp.length) || \"/\";\n const qs = url.includes(\"?\") ? url.slice(url.indexOf(\"?\")) : \"\";\n url = stripped + qs;\n pathname = stripped;\n }\n\n // Normalize trailing slash based on next.config.js trailingSlash setting.\n // Redirect to the canonical form if needed.\n if (\n nextConfig &&\n pathname !== \"/\" &&\n pathname !== \"/api\" &&\n !pathname.startsWith(\"/api/\")\n ) {\n const hasTrailing = pathname.endsWith(\"/\");\n if (nextConfig.trailingSlash && !hasTrailing) {\n // trailingSlash: true — redirect /about → /about/\n const qs = url.includes(\"?\") ? url.slice(url.indexOf(\"?\")) : \"\";\n const dest = bp + pathname + \"/\" + qs;\n res.writeHead(308, { Location: dest });\n res.end();\n return;\n } else if (!nextConfig.trailingSlash && hasTrailing) {\n // trailingSlash: false (default) — redirect /about/ → /about\n const qs = url.includes(\"?\") ? url.slice(url.indexOf(\"?\")) : \"\";\n const dest = bp + pathname.replace(/\\/+$/, \"\") + qs;\n res.writeHead(308, { Location: dest });\n res.end();\n return;\n }\n }\n\n // When @cloudflare/vite-plugin is present, delegate the entire\n // Pages Router request pipeline to the Worker/miniflare side.\n // That keeps middleware, headers, redirects, rewrites, API\n // routes, and rendering in one place instead of mutating the\n // host request and forwarding post-middleware state downstream.\n if (hasCloudflarePlugin) return next();\n\n // Snapshot of req.headers before middleware runs. Used for both\n // preMiddlewareReqCtx and the middleware Request itself. Intentionally\n // captured once here — applyRequestHeadersToNodeRequest() mutates\n // req.headers later, but by then this Headers object is no longer read.\n const nodeRequestHeaders = new Headers(\n Object.fromEntries(\n Object.entries(req.headers)\n .filter(([, v]) => v !== undefined)\n .map(([k, v]) => [k, Array.isArray(v) ? v.join(\", \") : String(v)]),\n ),\n );\n\n const requestOrigin = `http://${req.headers.host || \"localhost\"}`;\n const preMiddlewareReqUrl = new URL(url, requestOrigin);\n const preMiddlewareReqCtx: RequestContext = requestContextFromRequest(\n new Request(preMiddlewareReqUrl, { headers: nodeRequestHeaders }),\n );\n\n // Config redirects run before middleware, but still match against\n // the original normalized pathname and request headers/cookies.\n if (nextConfig?.redirects.length) {\n const redirected = applyRedirects(\n pathname,\n res,\n nextConfig.redirects,\n preMiddlewareReqCtx,\n nextConfig.basePath ?? \"\",\n );\n if (redirected) return;\n }\n\n const applyRequestHeadersToNodeRequest = (nextRequestHeaders: Headers) => {\n for (const key of Object.keys(req.headers)) {\n delete req.headers[key];\n }\n for (const [key, value] of nextRequestHeaders) {\n req.headers[key] = value;\n }\n };\n\n let middlewareRequestHeaders: Headers | null = null;\n let deferredMwResponseHeaders: [string, string][] | null = null;\n\n const applyDeferredMwHeaders = () => {\n if (deferredMwResponseHeaders) {\n for (const [key, value] of deferredMwResponseHeaders) {\n res.appendHeader(key, value);\n }\n }\n };\n\n // Run middleware.ts if present\n if (middlewarePath) {\n // Only trust X-Forwarded-Proto when behind a trusted proxy\n const devTrustProxy =\n process.env.VINEXT_TRUST_PROXY === \"1\" ||\n (process.env.VINEXT_TRUSTED_HOSTS ?? \"\").split(\",\").some((h) => h.trim());\n const rawProto = devTrustProxy\n ? String(req.headers[\"x-forwarded-proto\"] || \"\")\n .split(\",\")[0]\n .trim()\n : \"\";\n const mwProto = rawProto === \"https\" || rawProto === \"http\" ? rawProto : \"http\";\n const origin = `${mwProto}://${req.headers.host || \"localhost\"}`;\n const middlewareRequest = new Request(new URL(url, origin), {\n method: req.method,\n headers: nodeRequestHeaders,\n });\n const result = await runMiddleware(\n getPagesRunner(),\n middlewarePath,\n middlewareRequest,\n nextConfig?.i18n,\n nextConfig?.basePath,\n );\n\n // Settle waitUntil promises — no ctx.waitUntil() in dev, but\n // promises must still run for parity with prod (session sync, telemetry, etc.)\n if (result.waitUntilPromises?.length) {\n void Promise.allSettled(result.waitUntilPromises);\n }\n\n if (!result.continue) {\n if (result.redirectUrl) {\n const redirectHeaders: Record<string, string | string[]> = {\n Location: result.redirectUrl,\n };\n if (result.responseHeaders) {\n for (const [key, value] of result.responseHeaders) {\n const existing = redirectHeaders[key];\n if (existing === undefined) {\n redirectHeaders[key] = value;\n } else if (Array.isArray(existing)) {\n existing.push(value);\n } else {\n redirectHeaders[key] = [existing, value];\n }\n }\n }\n res.writeHead(result.redirectStatus ?? 307, redirectHeaders);\n res.end();\n return;\n }\n if (result.response) {\n res.statusCode = result.response.status;\n for (const [key, value] of result.response.headers) {\n res.appendHeader(key, value);\n }\n const body = Buffer.from(await result.response.arrayBuffer());\n res.end(body);\n return;\n }\n }\n\n // Apply middleware response headers. Unpack\n // x-middleware-request-* headers into req.headers so\n // config has/missing conditions and downstream handlers\n // see middleware-modified cookies and headers.\n if (result.responseHeaders) {\n const currentRequestHeaders = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (Array.isArray(value)) {\n currentRequestHeaders.set(key, value.join(\", \"));\n } else if (value !== undefined) {\n currentRequestHeaders.set(key, value);\n }\n }\n\n middlewareRequestHeaders = buildRequestHeadersFromMiddlewareResponse(\n currentRequestHeaders,\n result.responseHeaders,\n );\n\n if (middlewareRequestHeaders && !hasAppDir) {\n applyRequestHeadersToNodeRequest(middlewareRequestHeaders);\n }\n\n if (hasAppDir) {\n // Hybrid app+pages: defer response headers. They'll be\n // applied to res for Pages routes or forwarded to the RSC\n // entry (via x-vinext-mw-ctx) for App Router routes.\n deferredMwResponseHeaders = [];\n for (const [key, value] of result.responseHeaders) {\n if (!key.startsWith(\"x-middleware-\")) {\n deferredMwResponseHeaders.push([key, value]);\n }\n }\n } else {\n for (const [key, value] of result.responseHeaders) {\n if (!key.startsWith(\"x-middleware-\")) {\n res.appendHeader(key, value);\n }\n }\n }\n }\n\n // Apply middleware rewrite (URL and optional status code)\n if (result.rewriteUrl) {\n url = result.rewriteUrl;\n // Write the rewritten URL back onto req.url so every subsequent\n // handler in the connect chain sees the correct path. The local\n // `url` variable is only visible within this handler — anything\n // further down the chain (Vite's built-in middleware, the\n // Cloudflare plugin's handler, or any other connect middleware)\n // reads req.url directly. Without this, a middleware rewrite\n // would be invisible to those handlers and the original URL\n // would be dispatched instead.\n req.url = url;\n }\n if (result.rewriteStatus) {\n req.__vinextRewriteStatus = result.rewriteStatus;\n }\n\n // Forward middleware context to the RSC entry so it can\n // populate _mwCtx without re-running the middleware function.\n // This prevents double execution in hybrid app+pages dev mode.\n if (hasAppDir) {\n const mwCtxEntries: [string, string][] = [];\n if (result.responseHeaders) {\n for (const [key, value] of result.responseHeaders) {\n // Exclude control headers that runMiddleware already\n // consumed — matches the RSC entry's inline filtering.\n if (key !== \"x-middleware-next\" && key !== \"x-middleware-rewrite\") {\n mwCtxEntries.push([key, value]);\n }\n }\n }\n req.headers[\"x-vinext-mw-ctx\"] = JSON.stringify({\n h: mwCtxEntries,\n s: result.rewriteStatus ?? null,\n r: result.rewriteUrl ?? null,\n });\n }\n }\n\n // Build request context once for has/missing condition checks\n // for config rules that execute after middleware (rewrites).\n // Convert Node.js IncomingMessage headers to a Web Request for\n // requestContextFromRequest(), which uses the standard Web API.\n const reqUrl = new URL(url, requestOrigin);\n const reqCtxHeaders = middlewareRequestHeaders ?? nodeRequestHeaders;\n const reqCtx: RequestContext = requestContextFromRequest(\n new Request(reqUrl, { headers: reqCtxHeaders }),\n );\n\n // Apply custom headers from next.config.js\n // Header matching still uses the original normalized pathname and\n // pre-middleware request state; middleware response headers win\n // later because they are already on the outgoing response.\n if (nextConfig?.headers.length) {\n applyHeaders(pathname, res, nextConfig.headers, preMiddlewareReqCtx);\n }\n\n // Apply rewrites from next.config.js (beforeFiles)\n let resolvedUrl = url;\n if (nextConfig?.rewrites.beforeFiles.length) {\n resolvedUrl =\n applyRewrites(pathname, nextConfig.rewrites.beforeFiles, reqCtx) ?? url;\n }\n\n // External rewrite from beforeFiles — proxy to external URL\n if (isExternalUrl(resolvedUrl)) {\n applyDeferredMwHeaders();\n await proxyExternalRewriteNode(req, res, resolvedUrl);\n return;\n }\n\n // Handle API routes first (pages/api/*)\n const resolvedPathname = resolvedUrl.split(\"?\")[0];\n if (resolvedPathname.startsWith(\"/api/\") || resolvedPathname === \"/api\") {\n const apiRoutes = await apiRouter(\n pagesDir,\n nextConfig?.pageExtensions,\n fileMatcher,\n );\n const apiMatch = matchRoute(resolvedUrl, apiRoutes);\n if (apiMatch) {\n applyDeferredMwHeaders();\n if (middlewareRequestHeaders) {\n applyRequestHeadersToNodeRequest(middlewareRequestHeaders);\n }\n }\n const handled = await handleApiRoute(\n getPagesRunner(),\n req,\n res,\n resolvedUrl,\n apiRoutes,\n );\n if (handled) return;\n\n // No API route matched — if app dir exists, let the RSC plugin handle it\n // (app/api/* route handlers live there). Otherwise hard-404.\n if (hasAppDir) return next();\n\n res.statusCode = 404;\n res.end(\"404 - API route not found\");\n return;\n }\n\n const routes = await pagesRouter(pagesDir, nextConfig?.pageExtensions, fileMatcher);\n\n // Apply afterFiles rewrites — these run after initial route matching\n // If beforeFiles already rewrote the URL, afterFiles still run on the\n // *resolved* pathname. Next.js applies these when route matching succeeds\n // but allows overriding with rewrites.\n if (nextConfig?.rewrites.afterFiles.length) {\n const afterRewrite = applyRewrites(\n resolvedUrl.split(\"?\")[0],\n nextConfig.rewrites.afterFiles,\n reqCtx,\n );\n if (afterRewrite) resolvedUrl = afterRewrite;\n }\n\n // External rewrite from afterFiles — proxy to external URL\n if (isExternalUrl(resolvedUrl)) {\n applyDeferredMwHeaders();\n await proxyExternalRewriteNode(req, res, resolvedUrl);\n return;\n }\n\n const handler = createSSRHandler(\n server,\n getPagesRunner(),\n routes,\n pagesDir,\n nextConfig?.i18n,\n fileMatcher,\n nextConfig?.basePath ?? \"\",\n nextConfig?.trailingSlash ?? false,\n );\n const mwStatus = req.__vinextRewriteStatus;\n\n // Try rendering the resolved URL\n const match = matchRoute(resolvedUrl.split(\"?\")[0], routes);\n if (match) {\n applyDeferredMwHeaders();\n if (middlewareRequestHeaders) {\n applyRequestHeadersToNodeRequest(middlewareRequestHeaders);\n }\n await handler(req, res, resolvedUrl, mwStatus);\n return;\n }\n\n // No route matched — try fallback rewrites\n if (nextConfig?.rewrites.fallback.length) {\n const fallbackRewrite = applyRewrites(\n resolvedUrl.split(\"?\")[0],\n nextConfig.rewrites.fallback,\n reqCtx,\n );\n if (fallbackRewrite) {\n // External fallback rewrite — proxy to external URL\n if (isExternalUrl(fallbackRewrite)) {\n applyDeferredMwHeaders();\n await proxyExternalRewriteNode(req, res, fallbackRewrite);\n return;\n }\n const fallbackMatch = matchRoute(fallbackRewrite.split(\"?\")[0], routes);\n if (!fallbackMatch && hasAppDir) {\n return next();\n }\n applyDeferredMwHeaders();\n if (middlewareRequestHeaders) {\n applyRequestHeadersToNodeRequest(middlewareRequestHeaders);\n }\n await handler(req, res, fallbackRewrite, mwStatus);\n return;\n }\n }\n\n // No fallback matched - if app dir exists, let the RSC plugin handle it,\n // otherwise render via the pages SSR handler (will 404 for unknown routes).\n if (hasAppDir) return next();\n\n await handler(req, res, resolvedUrl, mwStatus);\n } catch (e) {\n next(e);\n }\n });\n };\n },\n },\n // Strip server-only data-fetching exports (getServerSideProps, getStaticProps,\n // getStaticPaths) from page modules in the client bundle. These functions\n // often import server-only modules (database drivers, fs, etc.) that would\n // break or bloat the client bundle. Next.js does this via an SWC transform\n // (next-ssg-transform); we use Vite's parseAst + MagicString.\n //\n // Only applies to client builds (not SSR) and only to files under the\n // pages/ directory.\n {\n name: \"vinext:strip-server-exports\",\n transform: {\n // Only match page source files, not node_modules\n filter: { id: /\\.(tsx?|jsx?|mjs)$/ },\n handler(code, id) {\n const ssr = this.environment?.name !== \"client\";\n if (ssr) return null;\n if (!hasPagesDir) return null;\n // Only transform files under the pages/ directory\n if (!id.startsWith(pagesDir)) return null;\n // Skip API routes, _app, _document, _error\n const relativePath = id.slice(pagesDir.length);\n if (relativePath.startsWith(\"/api/\") || relativePath === \"/api\") return null;\n if (/\\/_(?:app|document|error)\\b/.test(relativePath)) return null;\n\n const result = stripServerExports(code);\n if (!result) return null;\n return { code: result, map: null };\n },\n },\n },\n // Local image import transform:\n // When a source file imports a local image (e.g., `import hero from './hero.jpg'`),\n // this plugin transforms the default import to a StaticImageData object with\n // { src, width, height } so the next/image shim can set correct dimensions\n // on <img> tags, preventing CLS.\n //\n // Vite's default image import returns a URL string. We intercept this by\n // adding a `?vinext-meta` suffix: the original import gets the URL from Vite,\n // and we resolve the `?vinext-meta` virtual module to provide dimensions.\n {\n name: \"vinext:image-imports\",\n enforce: \"pre\",\n\n // Cache of image dimensions to avoid re-reading files\n _dimCache: imageImportDimCache,\n\n resolveId: {\n filter: { id: /\\?vinext-meta$/ },\n handler(source, _importer) {\n if (!source.endsWith(\"?vinext-meta\")) return null;\n // Resolve the real image path from the importer\n const realPath = source.replace(\"?vinext-meta\", \"\");\n return `\\0vinext-image-meta:${realPath}`;\n },\n },\n\n async load(id) {\n if (!id.startsWith(\"\\0vinext-image-meta:\")) return null;\n const imagePath = id.replace(\"\\0vinext-image-meta:\", \"\");\n\n // Read from cache first\n const cache = imageImportDimCache;\n let dims = cache.get(imagePath);\n if (!dims) {\n try {\n const { imageSize } = await import(\"image-size\");\n const buffer = fs.readFileSync(imagePath);\n const result = imageSize(buffer);\n dims = { width: result.width ?? 0, height: result.height ?? 0 };\n cache.set(imagePath, dims);\n } catch {\n dims = { width: 0, height: 0 };\n }\n }\n\n return `export default ${JSON.stringify(dims)};`;\n },\n\n transform: {\n // Hook filter: Rolldown evaluates these on the Rust side, skipping\n // the JS handler entirely for files that don't match.\n filter: {\n id: {\n include: /\\.(tsx?|jsx?|mjs)$/,\n exclude: /node_modules/,\n },\n code: new RegExp(`import\\\\s+\\\\w+\\\\s+from\\\\s+['\"][^'\"]+\\\\.(${IMAGE_EXTS})['\"]`),\n },\n async handler(code, id) {\n // Defensive guard — duplicates filter logic\n if (id.includes(\"node_modules\")) return null;\n if (id.startsWith(\"\\0\")) return null;\n if (!id.match(/\\.(tsx?|jsx?|mjs)$/)) return null;\n\n const imageImportRe = new RegExp(\n `import\\\\s+(\\\\w+)\\\\s+from\\\\s+['\"]([^'\"]+\\\\.(${IMAGE_EXTS}))['\"];?`,\n \"g\",\n );\n if (!imageImportRe.test(code)) return null;\n\n imageImportRe.lastIndex = 0;\n\n const s = new MagicString(code);\n let hasChanges = false;\n\n let match;\n while ((match = imageImportRe.exec(code)) !== null) {\n const [fullMatch, varName, importPath] = match;\n const matchStart = match.index;\n const matchEnd = matchStart + fullMatch.length;\n\n // Resolve the absolute path of the image\n const dir = path.dirname(id);\n const absImagePath = path.resolve(dir, importPath);\n\n if (!fs.existsSync(absImagePath)) continue;\n\n // Replace the single import with two:\n // 1. Original import (Vite gives us the URL string)\n // 2. Meta import (we provide { width, height })\n // Combined into a StaticImageData object\n const urlVar = `__vinext_img_url_${varName}`;\n const metaVar = `__vinext_img_meta_${varName}`;\n const replacement =\n `import ${urlVar} from ${JSON.stringify(importPath)};\\n` +\n `import ${metaVar} from ${JSON.stringify(absImagePath + \"?vinext-meta\")};\\n` +\n `const ${varName} = { src: ${urlVar}, width: ${metaVar}.width, height: ${metaVar}.height };`;\n\n s.overwrite(matchStart, matchEnd, replacement);\n hasChanges = true;\n }\n\n if (!hasChanges) return null;\n\n return {\n code: s.toString(),\n map: s.generateMap({ hires: \"boundary\" }),\n };\n },\n },\n } as Plugin & { _dimCache: Map<string, { width: number; height: number }> },\n // Google Fonts import rewrite + self-hosting — see src/plugins/fonts.ts\n createGoogleFontsPlugin(_fontGoogleShimPath, _shimsDir),\n // Local font path resolution — see src/plugins/fonts.ts\n createLocalFontsPlugin(),\n // Barrel import optimization:\n // Rewrites `import { Slot } from \"radix-ui\"` → `import * as Slot from \"@radix-ui/react-slot\"`\n // for packages listed in optimizePackageImports or DEFAULT_OPTIMIZE_PACKAGES.\n // This prevents Vite from eagerly evaluating barrel re-exports that call\n // React.createContext() in RSC environments where createContext doesn't exist.\n createOptimizeImportsPlugin(\n () => nextConfig,\n () => root,\n ),\n // \"use cache\" directive transform:\n // Detects \"use cache\" at file-level or function-level and wraps the\n // exports/functions with registerCachedFunction() from vinext/cache-runtime.\n // Runs without enforce so it executes after JSX transform (parseAst needs plain JS).\n {\n name: \"vinext:use-cache\",\n\n transform: {\n // Hook filter: only invoke JS when code contains 'use cache'.\n // The vast majority of files don't use this directive.\n filter: {\n id: {\n include: /\\.(tsx?|jsx?|mjs)$/,\n exclude: /node_modules/,\n },\n code: \"use cache\",\n },\n async handler(code, id) {\n // Defensive guard — duplicates filter logic\n if (id.includes(\"node_modules\")) return null;\n if (id.startsWith(\"\\0\")) return null;\n if (!id.match(/\\.(tsx?|jsx?|mjs)$/)) return null;\n if (!code.includes(\"use cache\")) return null;\n\n // Parse the AST first to check for actual \"use cache\" directives before\n // throwing the missing-RSC error. The fast-path string check above can\n // fire on files that contain \"use cache\" only in comments or string\n // literals (e.g., in error messages), not as real directives.\n const ast = parseAst(code);\n\n // Check for file-level \"use cache\" directive\n const cacheDirective = ast.body.find(\n (node) =>\n node.type === \"ExpressionStatement\" &&\n node.expression?.type === \"Literal\" &&\n typeof node.expression.value === \"string\" &&\n node.expression.value.startsWith(\"use cache\"),\n );\n\n // Check for function-level \"use cache\" directives by walking function bodies.\n // Accepts any function-like node: FunctionDeclaration/Expression, ArrowFunctionExpression,\n // or MethodDefinition. MethodDefinition stores its FunctionExpression in `.value`, not\n // `.body`, so we unwrap it here rather than at each call site to keep the callee safe.\n function nodeHasInlineCacheDirective(node: ASTNode): boolean {\n if (!node || typeof node !== \"object\") return false;\n // MethodDefinition wraps its FunctionExpression in .value; unwrap to reach .body.\n const fn = node.type === \"MethodDefinition\" ? node.value : node;\n // fn.body is a BlockStatement node ({type:\"BlockStatement\", body:Statement[]}), not\n // a raw array. Unwrap it. Arrow functions with expression bodies have a non-array\n // .body — the BlockStatement check handles that case (body.body would be undefined).\n const stmts: ASTNode[] | null =\n // oxlint-disable-next-line typescript/no-explicit-any\n (fn as any)?.body?.type === \"BlockStatement\" ? (fn as any).body.body : null;\n if (Array.isArray(stmts)) {\n for (const stmt of stmts) {\n if (\n stmt?.type === \"ExpressionStatement\" &&\n stmt.expression?.type === \"Literal\" &&\n typeof stmt.expression?.value === \"string\" &&\n /^use cache(:\\s*\\w+)?$/.test(stmt.expression.value)\n ) {\n return true;\n }\n }\n }\n return false;\n }\n function astHasInlineCache(nodes: ASTNode[]): boolean {\n for (const node of nodes) {\n if (!node || typeof node !== \"object\") continue;\n if (\n (node.type === \"FunctionDeclaration\" ||\n node.type === \"FunctionExpression\" ||\n node.type === \"ArrowFunctionExpression\" ||\n node.type === \"MethodDefinition\") &&\n nodeHasInlineCacheDirective(node)\n ) {\n return true;\n }\n // Walk into variable declarations, export declarations, etc.\n for (const key of Object.keys(node)) {\n if (key === \"type\" || key === \"start\" || key === \"end\" || key === \"loc\") continue;\n const child = node[key as keyof typeof node] as ASTNode;\n if (Array.isArray(child) && child.some((c) => c && typeof c === \"object\")) {\n if (astHasInlineCache(child)) return true;\n } else if (child && typeof child === \"object\" && child.type) {\n if (astHasInlineCache([child])) return true;\n }\n }\n }\n return false;\n }\n const hasInlineCache = !cacheDirective && astHasInlineCache(ast.body);\n\n if (!cacheDirective && !hasInlineCache) return null;\n\n if (!resolvedRscTransformsPath) {\n throw new Error(\n \"vinext: 'use cache' requires @vitejs/plugin-rsc to be installed.\\n\" +\n \"Run: \" +\n detectPackageManager(process.cwd()) +\n \" @vitejs/plugin-rsc\",\n );\n }\n const { transformWrapExport, transformHoistInlineDirective } = await import(\n pathToFileURL(resolvedRscTransformsPath).href\n );\n\n if (cacheDirective) {\n // File-level \"use cache\" — wrap function exports with\n // registerCachedFunction. Page default exports are wrapped directly\n // (they're leaf components). Layout/template defaults are excluded\n // because they receive {children} from the framework.\n // oxlint-disable-next-line typescript/no-explicit-any\n const directiveValue = (cacheDirective as any).expression.value;\n const variant =\n directiveValue === \"use cache\"\n ? \"\"\n : directiveValue.replace(\"use cache:\", \"\").replace(\"use cache: \", \"\").trim();\n\n // Only skip default export wrapping for layouts and templates —\n // they receive {children} from the framework which requires\n // temporary reference handling that registerCachedFunction doesn't\n // support yet. Pages, not-found, loading, error, and default are\n // leaf components with no {children} prop and can be cached directly.\n const isLayoutOrTemplate = /\\/(layout|template)\\.(tsx?|jsx?|mjs)$/.test(id);\n\n const runtimeModuleUrl = pathToFileURL(\n resolveShimModulePath(shimsDir, \"cache-runtime\"),\n ).href;\n const result = transformWrapExport(code, ast, {\n runtime: (value: string, name: string) =>\n `(await import(${JSON.stringify(runtimeModuleUrl)})).registerCachedFunction(${value}, ${JSON.stringify(id + \":\" + name)}, ${JSON.stringify(variant)})`,\n rejectNonAsyncFunction: false,\n filter: (name: string, meta: { isFunction?: boolean }) => {\n // Skip non-functions (constants, types, etc.)\n if (meta.isFunction === false) return false;\n // Skip the default export on layout/template files — these\n // receive {children} from the framework, and caching them\n // requires temporary reference handling for the children slot.\n // Named exports (e.g. generateMetadata) are still wrapped.\n if (isLayoutOrTemplate && name === \"default\") return false;\n return true;\n },\n });\n\n if (result.exportNames.length > 0) {\n // Remove the directive itself so it doesn't cause runtime errors\n const output = result.output;\n output.overwrite(\n cacheDirective.start,\n cacheDirective.end,\n `/* \"use cache\" — wrapped by vinext */`,\n );\n return {\n code: output.toString(),\n map: output.generateMap({ hires: \"boundary\" }),\n };\n }\n\n // Even if no exports were wrapped, still strip the directive\n // (e.g., layout/template file with only a default export)\n const output = new MagicString(code);\n output.overwrite(\n cacheDirective.start,\n cacheDirective.end,\n `/* \"use cache\" — handled by vinext */`,\n );\n return {\n code: output.toString(),\n map: output.generateMap({ hires: \"boundary\" }),\n };\n }\n\n // Check for function-level \"use cache\" directives\n // (e.g., async function getData() { \"use cache\"; ... })\n if (hasInlineCache) {\n const runtimeModuleUrl2 = pathToFileURL(\n resolveShimModulePath(shimsDir, \"cache-runtime\"),\n ).href;\n\n try {\n const result = transformHoistInlineDirective(code, ast, {\n directive: /^use cache(:\\s*\\w+)?$/,\n runtime: (value: string, name: string, meta: { directiveMatch: string[] }) => {\n const directiveMatch = meta.directiveMatch[0];\n const variant =\n directiveMatch === \"use cache\"\n ? \"\"\n : directiveMatch.replace(\"use cache:\", \"\").replace(\"use cache: \", \"\").trim();\n return `(await import(${JSON.stringify(runtimeModuleUrl2)})).registerCachedFunction(${value}, ${JSON.stringify(id + \":\" + name)}, ${JSON.stringify(variant)})`;\n },\n rejectNonAsyncFunction: false,\n });\n\n if (result.names.length > 0) {\n return {\n code: result.output.toString(),\n map: result.output.generateMap({ hires: \"boundary\" }),\n };\n }\n } catch {\n // If hoisting fails (e.g., complex closure), fall through\n }\n }\n\n return null;\n },\n },\n },\n // Inline binary assets fetched via `fetch(new URL(\"./asset\", import.meta.url))` —\n // see src/plugins/og-assets.ts\n createOgInlineFetchAssetsPlugin(),\n // Copy @vercel/og binary assets to the RSC output directory — see src/plugins/og-assets.ts\n ogAssetsPlugin,\n // Collect SSR/RSC bundle externals and write dist/server/vinext-externals.json.\n // Used by emitStandaloneOutput to determine which packages to copy into\n // standalone/node_modules/ — uses the bundler's own import graph instead of\n // fragile regex scanning of emitted files.\n createServerExternalsManifestPlugin(),\n // Write image config JSON for the App Router production server.\n // The App Router RSC entry doesn't export vinextConfig (that's a Pages\n // Router pattern), so we write a separate JSON file at build time that\n // prod-server.ts reads at startup for SVG/security header config.\n {\n name: \"vinext:image-config\",\n apply: \"build\",\n enforce: \"post\",\n writeBundle: {\n sequential: true,\n order: \"post\",\n handler(options) {\n const envName = this.environment?.name;\n if (envName !== \"rsc\") return;\n\n const outDir = options.dir;\n if (!outDir) return;\n\n const imageConfig = {\n dangerouslyAllowSVG: nextConfig?.images?.dangerouslyAllowSVG,\n contentDispositionType: nextConfig?.images?.contentDispositionType,\n contentSecurityPolicy: nextConfig?.images?.contentSecurityPolicy,\n };\n\n fs.writeFileSync(path.join(outDir, \"image-config.json\"), JSON.stringify(imageConfig));\n },\n },\n },\n // Write BUILD_ID to dist/server/ so post-build tools (TPR, seed-cache) can\n // read the build identifier without depending on the prerender manifest.\n // Uses closeBundle (not writeBundle) with a one-time write guard so the file\n // is written exactly once per build regardless of how many environments are\n // active (App Router RSC+SSR+client, Pages Router SSR+client, etc.).\n // The path is always dist/server/BUILD_ID — derived from root, not from the\n // per-environment options.dir — so it works for all router types.\n (() => {\n let buildIdWritten = false;\n return {\n name: \"vinext:build-id\",\n apply: \"build\" as const,\n enforce: \"post\" as const,\n closeBundle: {\n sequential: true,\n order: \"post\" as const,\n handler() {\n if (buildIdWritten) return;\n buildIdWritten = true;\n const outDir = path.join(root, \"dist\", \"server\");\n fs.mkdirSync(outDir, { recursive: true });\n fs.writeFileSync(path.join(outDir, \"BUILD_ID\"), nextConfig!.buildId);\n },\n },\n };\n })(),\n // Write vinext-server.json to dist/server/ with a per-build prerender secret.\n // The prerender secret is used by prod-server.ts to authenticate requests to\n // the internal /__vinext/prerender/* endpoints, which are only reachable during\n // the prerender phase of `vinext build`. A new secret is generated on every\n // build so it rotates with every deployment.\n //\n // The secret is generated once at plugin creation time so that both the rsc\n // and ssr environments write the exact same value (they share the same\n // closure). Without this, each env would call randomBytes() independently\n // and the second write would silently overwrite the first with a different\n // secret, causing prerender auth to fail for whichever env's server reads\n // the file last.\n (() => {\n const prerenderSecret = randomBytes(32).toString(\"hex\");\n return {\n name: \"vinext:server-manifest\",\n apply: \"build\" as const,\n enforce: \"post\" as const,\n writeBundle: {\n sequential: true,\n order: \"post\" as const,\n handler(options: { dir?: string }) {\n const envName = this.environment?.name;\n // Fire for App Router RSC builds (rsc env) and Pages Router SSR builds\n // (ssr env). Skip client and other environments.\n if (envName !== \"rsc\" && envName !== \"ssr\") return;\n\n const outDir = options.dir;\n if (!outDir) return;\n\n const manifest = { prerenderSecret };\n fs.writeFileSync(path.join(outDir, \"vinext-server.json\"), JSON.stringify(manifest));\n },\n },\n };\n })(),\n {\n name: \"vinext:nitro-route-rules\",\n nitro: {\n setup: async (nitro: NitroSetupContext) => {\n if (nitro.options.dev) return;\n if (!nextConfig) return;\n if (!hasAppDir && !hasPagesDir) return;\n\n const { collectNitroRouteRules, mergeNitroRouteRules } =\n await import(\"./build/nitro-route-rules.js\");\n const generatedRouteRules = await collectNitroRouteRules({\n appDir: hasAppDir ? appDir : null,\n pagesDir: hasPagesDir ? pagesDir : null,\n pageExtensions: nextConfig.pageExtensions,\n });\n\n if (Object.keys(generatedRouteRules).length === 0) return;\n\n const { routeRules, skippedRoutes } = mergeNitroRouteRules(\n nitro.options.routeRules,\n generatedRouteRules,\n );\n\n nitro.options.routeRules = routeRules;\n\n if (skippedRoutes.length > 0) {\n const warn = nitro.logger?.warn ?? console.warn;\n warn(\n `[vinext] Skipping generated Nitro routeRules for routes with existing exact cache config: ${skippedRoutes.join(\", \")}`,\n );\n }\n },\n },\n } as Plugin & { nitro: { setup: (nitro: NitroSetupContext) => Promise<void> } }, // Nitro plugin extension convention: https://nitro.build/guide/plugins\n // Vite can emit empty SSR manifest entries for modules that Rollup inlines\n // into another chunk. Pages Router looks up assets by page module path at\n // runtime, so rebuild those mappings from the emitted client bundle.\n {\n name: \"vinext:ssr-manifest-backfill\",\n apply: \"build\",\n enforce: \"post\",\n writeBundle: {\n sequential: true,\n order: \"post\",\n handler(options, bundle) {\n const outDir = options.dir;\n if (!outDir) return;\n\n const viteDir = path.join(outDir, \".vite\");\n const ssrManifestPath = path.join(viteDir, \"ssr-manifest.json\");\n if (!fs.existsSync(ssrManifestPath)) return;\n\n try {\n const ssrManifest = JSON.parse(fs.readFileSync(ssrManifestPath, \"utf-8\")) as Record<\n string,\n string[]\n >;\n const buildRoot = this.environment?.config.root ?? process.cwd();\n const buildBase = this.environment?.config.base ?? \"/\";\n const augmentedManifest = augmentSsrManifestFromBundle(\n ssrManifest,\n bundle as Record<string, BundleBackfillChunk | { type: string }>,\n buildRoot,\n buildBase,\n );\n fs.writeFileSync(ssrManifestPath, JSON.stringify(augmentedManifest, null, 2));\n } catch (err) {\n // Leave Vite's manifest untouched if parsing fails.\n console.warn(\"[vinext] Failed to augment SSR manifest:\", err);\n }\n },\n },\n },\n // Build-time precompression: generate .br, .gz, .zst for hashed assets.\n // Runs after the client bundle is written so compressed variants are\n // available for the production server's static file cache.\n // Opt-in via `precompress: true` in plugin options or `--precompress`\n // CLI flag. Not useful for edge platforms (Cloudflare Workers, Nitro)\n // that handle compression at the CDN layer.\n (() => {\n let pendingPrecompress: Promise<void> | null = null;\n let pendingPrecompressError: unknown = null;\n\n return {\n name: \"vinext:precompress\",\n apply: \"build\" as const,\n enforce: \"post\" as const,\n writeBundle: {\n sequential: true,\n order: \"post\" as const,\n handler(outputOptions: { dir?: string }) {\n if (this.environment?.name !== \"client\") return;\n\n if (!options.precompress && process.env.VINEXT_PRECOMPRESS !== \"1\") return;\n\n const outDir = outputOptions.dir;\n if (!outDir) return;\n\n // Only precompress hashed assets — public directory files use\n // on-the-fly compression since they may change between deploys.\n const assetsDir = path.join(outDir, \"assets\");\n if (!fs.existsSync(assetsDir)) return;\n\n const isTTY = process.stderr.isTTY;\n let lastLineLen = 0;\n\n // Start precompression as soon as the client bundle is written, but\n // defer awaiting it until the SSR environment finishes. This overlaps\n // the extra asset work with the final build phase instead of putting\n // the full precompression cost on the critical path of step 4/5.\n pendingPrecompressError = null;\n pendingPrecompress = (async () => {\n const result = await precompressAssets(outDir, (completed, total, file) => {\n if (!isTTY) return;\n const pct = total > 0 ? Math.floor((completed / total) * 100) : 0;\n const bar = `[${\"█\".repeat(Math.floor(pct / 5))}${\" \".repeat(20 - Math.floor(pct / 5))}]`;\n const maxFile = 30;\n const fileLabel = file.length > maxFile ? \"…\" + file.slice(-(maxFile - 1)) : file;\n const line = `Compressing assets... ${bar} ${String(completed).padStart(String(total).length)}/${total} ${fileLabel}`;\n const padded = line.padEnd(lastLineLen);\n lastLineLen = line.length;\n process.stderr.write(`\\r${padded}`);\n });\n if (isTTY) {\n process.stderr.write(`\\r${\" \".repeat(lastLineLen)}\\r`);\n }\n if (result.filesCompressed > 0) {\n const ratio = (\n (1 - result.totalBrotliBytes / result.totalOriginalBytes) *\n 100\n ).toFixed(1);\n console.log(\n ` Precompressed ${result.filesCompressed} assets (${ratio}% smaller with brotli)`,\n );\n }\n })().catch((error) => {\n pendingPrecompressError = error;\n // Log immediately so the error isn't invisible if closeBundle\n // never fires (e.g. a crash in a later SSR build plugin).\n console.error(\"[vinext] Precompression failed:\", error);\n });\n },\n },\n closeBundle: {\n sequential: true,\n order: \"post\" as const,\n async handler() {\n if (this.environment?.name !== \"ssr\") return;\n if (!pendingPrecompress) return;\n\n const task = pendingPrecompress;\n pendingPrecompress = null;\n await task;\n if (pendingPrecompressError) {\n const error = pendingPrecompressError;\n pendingPrecompressError = null;\n throw error;\n }\n },\n },\n };\n })(),\n // Cloudflare Workers production build integration:\n // After all environments are built, compute lazy chunks from the client\n // build manifest and inject globals into the worker entry.\n //\n // Pages Router: injects __VINEXT_CLIENT_ENTRY__, __VINEXT_SSR_MANIFEST__,\n // and __VINEXT_LAZY_CHUNKS__ into the worker entry (found via wrangler.json).\n // App Router: the RSC plugin handles __VINEXT_CLIENT_ENTRY__ via\n // loadBootstrapScriptContent(), but we still inject __VINEXT_LAZY_CHUNKS__\n // and __VINEXT_SSR_MANIFEST__ into the worker entry at dist/server/index.js.\n // Both: generates _headers file for immutable asset caching.\n {\n name: \"vinext:cloudflare-build\",\n apply: \"build\",\n enforce: \"post\",\n closeBundle: {\n sequential: true,\n order: \"post\",\n async handler() {\n const envName = this.environment?.name;\n if (!envName || !hasCloudflarePlugin) return;\n if (envName !== \"client\") return;\n\n const envConfig = this.environment?.config;\n if (!envConfig) return;\n const buildRoot = envConfig.root ?? process.cwd();\n const distDir = path.resolve(buildRoot, \"dist\");\n if (!fs.existsSync(distDir)) return;\n\n const clientDir = path.resolve(buildRoot, \"dist\", \"client\");\n const clientBase = envConfig.base ?? \"/\";\n\n // Read build manifest and compute lazy chunks (only reachable via\n // dynamic imports). This runs for BOTH App Router and Pages Router.\n // clientEntryFile is only used by the Pages Router path below —\n // App Router gets its client entry via the RSC plugin instead.\n let lazyChunksData: string[] | null = null;\n let clientEntryFile: string | null = null;\n const buildManifestPath = path.join(clientDir, \".vite\", \"manifest.json\");\n if (fs.existsSync(buildManifestPath)) {\n try {\n const buildManifest = JSON.parse(fs.readFileSync(buildManifestPath, \"utf-8\"));\n // oxlint-disable-next-line typescript/no-explicit-any\n for (const [, value] of Object.entries(buildManifest) as [string, any][]) {\n if (value && value.isEntry && value.file) {\n clientEntryFile = manifestFileWithBase(value.file, clientBase);\n break;\n }\n }\n const lazy = manifestFilesWithBase(computeLazyChunks(buildManifest), clientBase);\n if (lazy.length > 0) lazyChunksData = lazy;\n } catch {\n /* ignore parse errors */\n }\n }\n\n // Read SSR manifest for per-page CSS/JS injection\n let ssrManifestData: Record<string, string[]> | null = null;\n const ssrManifestPath = path.join(clientDir, \".vite\", \"ssr-manifest.json\");\n if (fs.existsSync(ssrManifestPath)) {\n try {\n ssrManifestData = JSON.parse(fs.readFileSync(ssrManifestPath, \"utf-8\"));\n } catch {\n /* ignore parse errors */\n }\n }\n\n if (hasAppDir) {\n // App Router: the RSC plugin handles __VINEXT_CLIENT_ENTRY__\n // via loadBootstrapScriptContent(), but we still need to inject\n // __VINEXT_LAZY_CHUNKS__ and __VINEXT_SSR_MANIFEST__ into the\n // worker entry at dist/server/index.js.\n const workerEntry = path.resolve(distDir, \"server\", \"index.js\");\n if (fs.existsSync(workerEntry) && (lazyChunksData || ssrManifestData)) {\n let code = fs.readFileSync(workerEntry, \"utf-8\");\n const globals: string[] = [];\n if (ssrManifestData) {\n globals.push(\n `globalThis.__VINEXT_SSR_MANIFEST__ = ${JSON.stringify(ssrManifestData)};`,\n );\n }\n if (lazyChunksData) {\n globals.push(\n `globalThis.__VINEXT_LAZY_CHUNKS__ = ${JSON.stringify(lazyChunksData)};`,\n );\n }\n code = globals.join(\"\\n\") + \"\\n\" + code;\n fs.writeFileSync(workerEntry, code);\n }\n } else {\n // Pages Router: find worker output by scanning dist/ for a\n // directory containing wrangler.json (Cloudflare plugin default).\n let workerOutDir: string | null = null;\n for (const entry of fs.readdirSync(distDir)) {\n const candidate = path.join(distDir, entry);\n if (entry === \"client\") continue;\n if (\n fs.statSync(candidate).isDirectory() &&\n fs.existsSync(path.join(candidate, \"wrangler.json\"))\n ) {\n workerOutDir = candidate;\n break;\n }\n }\n if (!workerOutDir) return;\n\n const workerEntry = path.join(workerOutDir, \"index.js\");\n if (!fs.existsSync(workerEntry)) return;\n\n // Fallback: scan dist/client/assets/ for the client entry chunk.\n // Pages Router uses \"vinext-client-entry\", App Router uses\n // \"vinext-app-browser-entry\".\n if (!clientEntryFile) {\n const assetsDir = path.join(clientDir, \"assets\");\n if (fs.existsSync(assetsDir)) {\n const files = fs.readdirSync(assetsDir);\n const entry = files.find(\n (f: string) =>\n (f.includes(\"vinext-client-entry\") || f.includes(\"vinext-app-browser-entry\")) &&\n f.endsWith(\".js\"),\n );\n if (entry) clientEntryFile = manifestFileWithBase(\"assets/\" + entry, clientBase);\n }\n }\n\n // Prepend globals to worker entry\n if (clientEntryFile || ssrManifestData || lazyChunksData) {\n let code = fs.readFileSync(workerEntry, \"utf-8\");\n const globals: string[] = [];\n if (clientEntryFile) {\n globals.push(\n `globalThis.__VINEXT_CLIENT_ENTRY__ = ${JSON.stringify(clientEntryFile)};`,\n );\n }\n if (ssrManifestData) {\n globals.push(\n `globalThis.__VINEXT_SSR_MANIFEST__ = ${JSON.stringify(ssrManifestData)};`,\n );\n }\n if (lazyChunksData) {\n globals.push(\n `globalThis.__VINEXT_LAZY_CHUNKS__ = ${JSON.stringify(lazyChunksData)};`,\n );\n }\n code = globals.join(\"\\n\") + \"\\n\" + code;\n fs.writeFileSync(workerEntry, code);\n }\n }\n\n // Generate _headers file for Cloudflare Workers static asset caching.\n // Vite outputs content-hashed files (JS, CSS, fonts) to the assetsDir\n // (defaults to \"assets\"). These are safe to cache indefinitely since\n // the hash changes on any content change. Without this, Cloudflare\n // serves them with max-age=0 which forces unnecessary revalidation\n // on every page load.\n const headersPath = path.join(clientDir, \"_headers\");\n if (!fs.existsSync(headersPath)) {\n const assetsDir = envConfig.build?.assetsDir ?? \"assets\";\n const headersContent = [\n \"# Cache content-hashed assets immutably (generated by vinext)\",\n `/${assetsDir}/*`,\n \" Cache-Control: public, max-age=31536000, immutable\",\n \"\",\n ].join(\"\\n\");\n fs.mkdirSync(clientDir, { recursive: true });\n fs.writeFileSync(headersPath, headersContent);\n }\n },\n },\n },\n {\n // @vercel/og WASM patch — universal (workerd + Node.js)\n //\n // @vercel/og/dist/index.edge.js uses two WASM modules that need special handling:\n //\n // 1. YOGA WASM: yoga-layout embeds its WASM as a base64 data URL and instantiates\n // it via WebAssembly.instantiate(bytes). workerd forbids this — WASM must be\n // loaded as a pre-compiled WebAssembly.Module via the module system.\n //\n // 2. RESVG WASM: imported as `import resvg_wasm from \"./resvg.wasm?module\"` which\n // only works on workerd. Node.js can't import WASM files as ESM modules.\n //\n // Fix: replace all static WASM imports with dynamic imports that try the ?module\n // path (for workerd) and fall back to compiling from bytes (for Node.js). This\n // produces a single build output that runs on both runtimes.\n name: \"vinext:og-font-patch\",\n enforce: \"pre\" as const,\n transform(code: string, id: string) {\n if (!id.includes(\"@vercel/og\") || !id.includes(\"index.edge.js\")) return null;\n let result = code;\n\n // ── Yoga WASM: dynamic import + inline base64 fallback ──────────────────────\n // yoga-layout's emscripten bundle sets H to a data URL containing the yoga WASM,\n // then later calls WebAssembly.instantiate(bytes, imports), which workerd rejects.\n // Emscripten supports a custom h2.instantiateWasm(imports, callback) escape hatch.\n //\n // Strategy: try dynamic import(\"./yoga.wasm?module\") for workerd (pre-compiled\n // module), fall back to compiling from inline base64 bytes for Node.js.\n // Yoga WASM is ~70KB so inlining the base64 (~95KB) is acceptable.\n const YOGA_DATA_URL_RE = /H = \"data:application\\/octet-stream;base64,([A-Za-z0-9+/]+=*)\";/;\n const yogaMatch = YOGA_DATA_URL_RE.exec(result);\n if (yogaMatch) {\n const yogaBase64 = yogaMatch[1];\n const distDir = path.dirname(id);\n const yogaWasmPath = path.join(distDir, \"yoga.wasm\");\n // Write yoga.wasm to disk idempotently at transform time (Node.js side)\n // so the ?module dynamic import can resolve it on workerd builds.\n if (!fs.existsSync(yogaWasmPath)) {\n fs.writeFileSync(yogaWasmPath, Buffer.from(yogaBase64, \"base64\"));\n }\n // Disable the data-URL branch so emscripten doesn't try to instantiate from bytes\n result = result.replace(yogaMatch[0], `H = \"\";`);\n // Patch the loadYoga call site to inject instantiateWasm with universal handler.\n // WebAssembly.instantiate(Module, imports) → Instance (workerd path)\n // WebAssembly.instantiate(bytes, imports) → { module, instance } (Node.js path)\n const YOGA_CALL = `yoga_wasm_base64_esm_default()`;\n const YOGA_CALL_PATCHED = [\n `yoga_wasm_base64_esm_default({ instantiateWasm: function(imports, callback) {`,\n ` __vi_yoga_mod.then(function(mod) {`,\n ` if (mod) {`,\n ` WebAssembly.instantiate(mod, imports).then(function(inst) { callback(inst); });`,\n ` } else {`,\n ` var b = Buffer.from(__vi_yoga_b64, \"base64\");`,\n ` WebAssembly.instantiate(b, imports).then(function(r) { callback(r.instance); });`,\n ` }`,\n ` });`,\n ` return {};`,\n `} })`,\n ].join(\"\\n\");\n result = result.replace(YOGA_CALL, YOGA_CALL_PATCHED);\n // Prepend dynamic import with base64 fallback (no static import — Node.js safe)\n const yogaPreamble = [\n `var __vi_yoga_b64 = ${JSON.stringify(yogaBase64)};`,\n `var __vi_yoga_mod = import(\"./yoga.wasm?module\").then(function(m) { return m.default; }).catch(function() { return null; });`,\n ].join(\"\\n\");\n result = yogaPreamble + \"\\n\" + result;\n }\n\n // ── Resvg WASM: dynamic import + disk fallback ──────────────────────────────\n // The edge entry has `import resvg_wasm from \"./resvg.wasm?module\"` which is a\n // static ESM import that only works on workerd. Node.js fails because the WASM\n // binary's emscripten imports (module \"a\") can't be resolved as npm packages.\n //\n // Strategy: replace the static import with a dynamic import for workerd, falling\n // back to reading the .wasm file from disk + WebAssembly.compile for Node.js.\n // Resvg WASM is ~1.3MB so we read from disk instead of inlining base64.\n const RESVG_STATIC_IMPORT_RE =\n /import\\s+resvg_wasm\\s+from\\s+[\"']\\.\\/resvg\\.wasm\\?module[\"']\\s*;?/;\n const resvgMatch = RESVG_STATIC_IMPORT_RE.exec(result);\n if (resvgMatch) {\n // Note: new URL(\"./resvg.wasm\", import.meta.url) MUST be inside the catch handler,\n // not at the top level. In workerd, import.meta.url is \"worker\" (not a valid URL\n // base), so new URL(..., \"worker\") throws TypeError at module load time.\n // The catch block only runs on Node.js where import.meta.url is a file:// URL.\n const resvgLoader = [\n `var resvg_wasm = import(\"./resvg.wasm?module\").then(function(m) { return m.default; }).catch(function() {`,\n ` return Promise.all([import(\"node:fs\"), import(\"node:url\")]).then(function(mods) {`,\n ` var p = mods[1].fileURLToPath(new URL(\"./resvg.wasm\", import.meta.url));`,\n ` return mods[0].promises.readFile(p).then(function(buf) { return WebAssembly.compile(buf); });`,\n ` });`,\n `});`,\n ].join(\"\\n\");\n result = result.replace(resvgMatch[0], resvgLoader);\n }\n\n if (result === code) return null;\n return { code: result, map: null };\n },\n },\n ];\n\n // Append auto-injected RSC plugins if applicable\n if (rscPluginPromise) {\n plugins.push(rscPluginPromise);\n }\n\n return plugins;\n}\n\n/**\n * Collect all NEXT_PUBLIC_* env vars and create Vite define entries\n * so they get inlined into the client bundle.\n */\nfunction getNextPublicEnvDefines(): Record<string, string> {\n const defines: Record<string, string> = {};\n for (const [key, value] of Object.entries(process.env)) {\n if (key.startsWith(\"NEXT_PUBLIC_\") && value !== undefined) {\n defines[`process.env.${key}`] = JSON.stringify(value);\n }\n }\n return defines;\n}\n\n// matchConfigPattern is imported from config-matchers.ts and re-exported\n// for tests and other consumers that import it from vinext's main entry.\n// The duplicate local implementation and its extractConstraint helper\n// have been removed in favor of the canonical config-matchers.ts version\n// which uses a single-pass tokenizer (fixing the chained .replace()\n// divergence that CodeQL flagged as incomplete sanitization).\nexport { matchConfigPattern } from \"./config/config-matchers.js\";\n\n/**\n * Strip server-only data-fetching exports (getServerSideProps,\n * getStaticProps, getStaticPaths) from page modules for the client\n * bundle. Uses Vite's parseAst (Rollup/acorn) for correct handling\n * of all export patterns including function expressions, arrow\n * functions with TS return types, and re-exports.\n *\n * Modeled after Next.js's SWC `next-ssg-transform`.\n */\nfunction stripServerExports(code: string): string | null {\n const SERVER_EXPORTS = new Set([\"getServerSideProps\", \"getStaticProps\", \"getStaticPaths\"]);\n if (![...SERVER_EXPORTS].some((name) => code.includes(name))) return null;\n\n let ast: ReturnType<typeof parseAst>;\n try {\n ast = parseAst(code);\n } catch {\n // If parsing fails (shouldn't happen post-JSX/TS transform), bail out\n return null;\n }\n\n const s = new MagicString(code);\n let changed = false;\n\n for (const node of ast.body) {\n if (node.type !== \"ExportNamedDeclaration\") continue;\n\n // Case 1: export function name() {} / export async function name() {}\n // Case 2: export const/let/var name = ...\n if (node.declaration) {\n const decl = node.declaration;\n if (decl.type === \"FunctionDeclaration\" && decl.id && SERVER_EXPORTS.has(decl.id.name)) {\n s.overwrite(\n node.start,\n node.end,\n `export function ${decl.id.name}() { return { props: {} }; }`,\n );\n changed = true;\n } else if (decl.type === \"VariableDeclaration\") {\n for (const declarator of decl.declarations) {\n if (declarator.id?.type === \"Identifier\" && SERVER_EXPORTS.has(declarator.id.name)) {\n s.overwrite(node.start, node.end, `export const ${declarator.id.name} = undefined;`);\n changed = true;\n }\n }\n }\n continue;\n }\n\n // Case 3: export { getServerSideProps } or export { getServerSideProps as gSSP }\n if (node.specifiers && node.specifiers.length > 0 && !node.source) {\n const kept: Extract<ASTNode, { type: \"ExportSpecifier\" }>[] = [];\n const stripped: string[] = [];\n for (const spec of node.specifiers) {\n // spec.local.name is the binding name, spec.exported.name is the export name\n // oxlint-disable-next-line typescript/no-explicit-any\n const exportedName = (spec.exported as any)?.name ?? (spec.exported as any)?.value;\n if (SERVER_EXPORTS.has(exportedName)) {\n stripped.push(exportedName);\n } else {\n kept.push(spec);\n }\n }\n if (stripped.length > 0) {\n // Build replacement: keep non-server specifiers, add stubs for stripped ones\n const parts: string[] = [];\n if (kept.length > 0) {\n const keptStr = kept\n // oxlint-disable-next-line typescript/no-explicit-any\n .map((sp: any) => {\n const local = sp.local.name;\n const exported = sp.exported?.name ?? sp.exported?.value;\n return local === exported ? local : `${local} as ${exported}`;\n })\n .join(\", \");\n parts.push(`export { ${keptStr} };`);\n }\n for (const name of stripped) {\n parts.push(`export const ${name} = undefined;`);\n }\n s.overwrite(node.start, node.end, parts.join(\"\\n\"));\n changed = true;\n }\n }\n }\n\n if (!changed) return null;\n return s.toString();\n}\n\n/**\n * Apply redirect rules from next.config.js.\n * Returns true if a redirect was applied.\n */\nfunction applyRedirects(\n pathname: string,\n // oxlint-disable-next-line typescript/no-explicit-any\n res: any,\n redirects: NextRedirect[],\n ctx: RequestContext,\n basePath = \"\",\n): boolean {\n const result = matchRedirect(pathname, redirects, ctx);\n if (result) {\n // Sanitize to prevent open redirect via protocol-relative URLs\n const dest = sanitizeDestination(\n basePath && !isExternalUrl(result.destination) && !hasBasePath(result.destination, basePath)\n ? basePath + result.destination\n : result.destination,\n );\n res.writeHead(result.permanent ? 308 : 307, { Location: dest });\n res.end();\n return true;\n }\n return false;\n}\n\n/*\n * Converts the Node.js IncomingMessage into a Web Request, calls\n * proxyExternalRequest(), and pipes the response back to the Node.js\n * ServerResponse.\n */\nasync function proxyExternalRewriteNode(\n req: import(\"node:http\").IncomingMessage,\n res: import(\"node:http\").ServerResponse,\n externalUrl: string,\n): Promise<void> {\n try {\n const proto = \"http\";\n const host = req.headers.host || \"localhost\";\n const origin = `${proto}://${host}`;\n const method = req.method ?? \"GET\";\n const hasBody = method !== \"GET\" && method !== \"HEAD\";\n const init: RequestInit & { duplex?: string } = {\n method,\n headers: Object.fromEntries(\n Object.entries(req.headers)\n .filter(([, v]) => v !== undefined)\n .map(([k, v]) => [k, Array.isArray(v) ? v.join(\", \") : String(v)]),\n ),\n };\n if (hasBody) {\n const { Readable } = await import(\"node:stream\");\n init.body = Readable.toWeb(req) as ReadableStream;\n init.duplex = \"half\";\n }\n const webRequest = new Request(new URL(req.url ?? \"/\", origin), init);\n const proxyResponse = await proxyExternalRequest(webRequest, externalUrl);\n\n // Preserve multi-value headers (e.g. Set-Cookie) — Object.fromEntries()\n // would collapse them into a single value.\n const nodeHeaders: Record<string, string | string[]> = {};\n proxyResponse.headers.forEach((value, key) => {\n const existing = nodeHeaders[key];\n if (existing !== undefined) {\n nodeHeaders[key] = Array.isArray(existing) ? [...existing, value] : [existing, value];\n } else {\n nodeHeaders[key] = value;\n }\n });\n res.writeHead(proxyResponse.status, nodeHeaders);\n\n if (proxyResponse.body) {\n const { Readable: ReadableImport } = await import(\"node:stream\");\n const nodeStream = ReadableImport.fromWeb(\n proxyResponse.body as import(\"stream/web\").ReadableStream,\n );\n nodeStream.pipe(res);\n } else {\n res.end();\n }\n } catch (e) {\n console.error(\"[vinext] External rewrite proxy error:\", e);\n if (!res.headersSent) {\n res.writeHead(502);\n res.end(\"Bad Gateway\");\n }\n }\n}\n\n/**\n * Apply rewrite rules from next.config.js.\n * Returns the rewritten URL or null if no rewrite matched.\n */\nfunction applyRewrites(\n pathname: string,\n rewrites: NextRewrite[],\n ctx: RequestContext,\n): string | null {\n const dest = matchRewrite(pathname, rewrites, ctx);\n if (dest) {\n // Sanitize to prevent open redirect via protocol-relative URLs\n return sanitizeDestination(dest);\n }\n return null;\n}\n\n/**\n * Apply custom header rules from next.config.js.\n * Middleware headers take precedence: if a header key was already set on the\n * response (by middleware), the config value is skipped for that key.\n */\nfunction applyHeaders(\n pathname: string,\n // oxlint-disable-next-line typescript/no-explicit-any\n res: any,\n headers: NextHeader[],\n ctx: RequestContext,\n): void {\n const matched = matchHeaders(pathname, headers, ctx);\n for (const header of matched) {\n // Use append semantics for headers where multiple values must coexist\n // (Vary, Set-Cookie). Using setHeader() on these would destroy\n // existing values like \"Vary: RSC, Accept\".\n const lk = header.key.toLowerCase();\n if (lk === \"set-cookie\") {\n // Node.js res.getHeader(\"set-cookie\") returns string[] when\n // multiple Set-Cookie headers have been set. Preserve the array.\n const existing = res.getHeader(lk);\n if (Array.isArray(existing)) {\n res.setHeader(header.key, [...existing, header.value]);\n } else if (existing) {\n res.setHeader(header.key, [String(existing), header.value]);\n } else {\n res.setHeader(header.key, header.value);\n }\n } else if (lk === \"vary\") {\n const existing = res.getHeader(lk);\n if (existing) {\n res.setHeader(header.key, existing + \", \" + header.value);\n } else {\n res.setHeader(header.key, header.value);\n }\n } else {\n // Middleware headers take precedence: skip config keys already set by\n // middleware so middleware always wins over next.config.js headers.\n if (!res.getHeader(lk)) {\n res.setHeader(header.key, header.value);\n }\n }\n }\n}\n\n/**\n * Find a file by name (without extension) in a directory.\n * Checks the configured page extensions.\n */\nfunction findFileWithExts(\n dir: string,\n name: string,\n matcher: ReturnType<typeof createValidFileMatcher>,\n): string | null {\n for (const ext of matcher.dottedExtensions) {\n const filePath = path.join(dir, name + ext);\n if (fs.existsSync(filePath)) return filePath;\n }\n return null;\n}\n\n/** Module-level cache for hasMdxFiles — avoids re-scanning per Vite environment. */\nconst _mdxScanCache = new Map<string, boolean>();\n/**\n * Check if the project has .mdx files in app/ or pages/ directories.\n */\nfunction hasMdxFiles(root: string, appDir: string | null, pagesDir: string | null): boolean {\n const cacheKey = `${root}\\0${appDir ?? \"\"}\\0${pagesDir ?? \"\"}`;\n if (_mdxScanCache.has(cacheKey)) return _mdxScanCache.get(cacheKey)!;\n const dirs = [appDir, pagesDir].filter(Boolean) as string[];\n for (const dir of dirs) {\n if (fs.existsSync(dir) && scanDirForMdx(dir)) {\n _mdxScanCache.set(cacheKey, true);\n return true;\n }\n }\n _mdxScanCache.set(cacheKey, false);\n return false;\n}\n\nfunction scanDirForMdx(dir: string): boolean {\n try {\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n for (const entry of entries) {\n if (entry.name.startsWith(\".\") || entry.name === \"node_modules\") continue;\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n if (scanDirForMdx(full)) return true;\n } else if (entry.isFile() && entry.name.toLowerCase().endsWith(\".mdx\")) {\n return true;\n }\n }\n } catch {\n // ignore unreadable dirs\n }\n return false;\n}\n\nfunction scanPublicFileRoutes(root: string): string[] {\n const publicDir = path.join(root, \"public\");\n const routes: string[] = [];\n const visitedDirs = new Set<string>();\n\n function walk(dir: string): void {\n let realDir: string;\n try {\n realDir = fs.realpathSync(dir);\n } catch {\n return;\n }\n if (visitedDirs.has(realDir)) return;\n visitedDirs.add(realDir);\n\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n walk(fullPath);\n continue;\n }\n if (entry.isSymbolicLink()) {\n let stat: fs.Stats;\n try {\n stat = fs.statSync(fullPath);\n } catch {\n continue;\n }\n if (stat.isDirectory()) {\n walk(fullPath);\n continue;\n }\n if (!stat.isFile()) continue;\n } else if (!entry.isFile()) {\n continue;\n }\n const relativePath = path.relative(publicDir, fullPath).split(path.sep).join(\"/\");\n routes.push(\"/\" + relativePath);\n }\n }\n\n if (fs.existsSync(publicDir)) {\n try {\n walk(publicDir);\n } catch {\n // ignore unreadable dirs\n }\n }\n\n routes.sort();\n return routes;\n}\n\n// Public exports for static export\nexport { staticExportPages, staticExportApp } from \"./build/static-export.js\";\nexport type {\n StaticExportResult,\n StaticExportOptions,\n AppStaticExportOptions,\n} from \"./build/static-export.js\";\n\n// Export NextConfig type so next.config.ts files can import it from \"vinext\"\n// instead of \"next\".\nexport type { NextConfig } from \"./config/next-config.js\";\n\n// Exported for CLI and testing\nexport {\n clientManualChunks,\n clientOutputConfig,\n clientTreeshakeConfig,\n computeLazyChunks,\n getClientOutputConfigForVite,\n getClientTreeshakeConfigForVite,\n};\nexport { augmentSsrManifestFromBundle as _augmentSsrManifestFromBundle };\nexport { resolvePostcssStringPlugins as _resolvePostcssStringPlugins };\nexport { _postcssCache };\nexport { hasMdxFiles as _hasMdxFiles };\nexport { _mdxScanCache };\nexport { scanPublicFileRoutes as _scanPublicFileRoutes };\nexport { parseStaticObjectLiteral as _parseStaticObjectLiteral };\nexport { _findBalancedObject, _findCallEnd };\nexport { stripServerExports as _stripServerExports };\nexport { asyncHooksStubPlugin as _asyncHooksStubPlugin };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8FA,MAAM,YAAY,OAAO,KAAK;AAG9B,SAAS,0BAA0B,aAAqB,WAAkC;AACxF,KAAI;AAEF,SADuB,cAAc,KAAK,KAAK,aAAa,eAAe,CAAC,CACtD,QAAQ,UAAU;SAClC;AAER,KAAI;AAEF,SADoB,cAAc,OAAO,KAAK,IAAI,CAC/B,QAAQ,UAAU;SAC/B;AAER,QAAO;;AAGT,SAAS,sBAAsB,UAAkB,YAA4B;AAI3E,MAAK,MAAM,OADQ,CAAC,OAAO,MAAM,EACH;EAC5B,MAAM,YAAY,KAAK,KAAK,UAAU,GAAG,aAAa,MAAM;AAC5D,MAAI,GAAG,WAAW,UAAU,CAC1B,QAAO;;AAGX,QAAO,KAAK,KAAK,UAAU,GAAG,WAAW,KAAK;;AAGhD,SAAS,oBAAoB,MAAc,SAAyB;AAClE,QAAO,KAAK,SAAS,MAAM,QAAQ,CAAC,MAAM,KAAK,IAAI,CAAC,KAAK,IAAI;;AAG/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