vinext 0.0.34 → 0.0.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/README.md +1 -0
  2. package/dist/build/prerender.d.ts +9 -4
  3. package/dist/build/prerender.js +27 -9
  4. package/dist/build/prerender.js.map +1 -1
  5. package/dist/build/run-prerender.js +4 -1
  6. package/dist/build/run-prerender.js.map +1 -1
  7. package/dist/config/next-config.d.ts +7 -1
  8. package/dist/config/next-config.js +39 -26
  9. package/dist/config/next-config.js.map +1 -1
  10. package/dist/entries/pages-server-entry.js +59 -140
  11. package/dist/entries/pages-server-entry.js.map +1 -1
  12. package/dist/index.d.ts +9 -1
  13. package/dist/index.js +40 -4
  14. package/dist/index.js.map +1 -1
  15. package/dist/plugins/optimize-imports.js +28 -2
  16. package/dist/plugins/optimize-imports.js.map +1 -1
  17. package/dist/server/app-browser-entry.js +2 -2
  18. package/dist/server/app-browser-entry.js.map +1 -1
  19. package/dist/server/app-page-render.js +6 -4
  20. package/dist/server/app-page-render.js.map +1 -1
  21. package/dist/server/app-page-response.js +1 -1
  22. package/dist/server/app-page-response.js.map +1 -1
  23. package/dist/server/app-page-stream.d.ts +9 -1
  24. package/dist/server/app-page-stream.js +37 -4
  25. package/dist/server/app-page-stream.js.map +1 -1
  26. package/dist/server/app-ssr-stream.js +5 -3
  27. package/dist/server/app-ssr-stream.js.map +1 -1
  28. package/dist/server/pages-page-response.d.ts +54 -0
  29. package/dist/server/pages-page-response.js +140 -0
  30. package/dist/server/pages-page-response.js.map +1 -0
  31. package/dist/server/prod-server.js +3 -0
  32. package/dist/server/prod-server.js.map +1 -1
  33. package/dist/server/seed-cache.d.ts +44 -0
  34. package/dist/server/seed-cache.js +127 -0
  35. package/dist/server/seed-cache.js.map +1 -0
  36. package/dist/shims/image.js +4 -2
  37. package/dist/shims/image.js.map +1 -1
  38. package/package.json +1 -1
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["generateServerEntry","_generateServerEntry","generateClientEntry","_generateClientEntry"],"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 { 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 loadNextConfig,\n resolveNextConfig,\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 { findInstrumentationFile, runInstrumentation } from \"./server/instrumentation.js\";\nimport { PHASE_PRODUCTION_BUILD, PHASE_DEVELOPMENT_SERVER } from \"./shims/constants.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 { createOptimizeImportsPlugin } from \"./plugins/optimize-imports.js\";\nimport { hasWranglerConfig, formatMissingCloudflarePluginError } from \"./deploy.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 { fileURLToPath, 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\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\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\n/**\n * Fetch Google Fonts CSS, download .woff2 files, cache locally, and return\n * @font-face CSS with local file references.\n *\n * Cache dir structure: .vinext/fonts/<family-hash>/\n * - style.css (the rewritten @font-face CSS)\n * - *.woff2 (downloaded font files)\n */\nasync function fetchAndCacheFont(\n cssUrl: string,\n family: string,\n cacheDir: string,\n): Promise<string> {\n // Use a hash of the URL for the cache key\n const { createHash } = await import(\"node:crypto\");\n const urlHash = createHash(\"md5\").update(cssUrl).digest(\"hex\").slice(0, 12);\n const fontDir = path.join(cacheDir, `${family.toLowerCase().replace(/\\s+/g, \"-\")}-${urlHash}`);\n\n // Check if already cached\n const cachedCSSPath = path.join(fontDir, \"style.css\");\n if (fs.existsSync(cachedCSSPath)) {\n return fs.readFileSync(cachedCSSPath, \"utf-8\");\n }\n\n // Fetch CSS from Google Fonts (woff2 user-agent gives woff2 URLs)\n const cssResponse = await fetch(cssUrl, {\n headers: {\n \"User-Agent\":\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36\",\n },\n });\n if (!cssResponse.ok) {\n throw new Error(`Failed to fetch Google Fonts CSS: ${cssResponse.status}`);\n }\n let css = await cssResponse.text();\n\n // Extract all font file URLs\n const urlRe = /url\\((https:\\/\\/fonts\\.gstatic\\.com\\/[^)]+)\\)/g;\n const urls = new Map<string, string>(); // original URL -> local filename\n let urlMatch;\n while ((urlMatch = urlRe.exec(css)) !== null) {\n const fontUrl = urlMatch[1];\n if (!urls.has(fontUrl)) {\n const ext = fontUrl.includes(\".woff2\")\n ? \".woff2\"\n : fontUrl.includes(\".woff\")\n ? \".woff\"\n : \".ttf\";\n const fileHash = createHash(\"md5\").update(fontUrl).digest(\"hex\").slice(0, 8);\n urls.set(fontUrl, `${family.toLowerCase().replace(/\\s+/g, \"-\")}-${fileHash}${ext}`);\n }\n }\n\n // Download font files\n fs.mkdirSync(fontDir, { recursive: true });\n for (const [fontUrl, filename] of urls) {\n const filePath = path.join(fontDir, filename);\n if (!fs.existsSync(filePath)) {\n const fontResponse = await fetch(fontUrl);\n if (fontResponse.ok) {\n const buffer = Buffer.from(await fontResponse.arrayBuffer());\n fs.writeFileSync(filePath, buffer);\n }\n }\n // Rewrite CSS to use relative path (Vite will resolve /@fs/ for dev, or asset for build)\n css = css.split(fontUrl).join(filePath);\n }\n\n // Cache the rewritten CSS\n fs.writeFileSync(cachedCSSPath, css);\n return css;\n}\n\n/**\n * Safely parse a static JS object literal string into a plain object.\n * Uses Vite's parseAst (Rollup/acorn) so no code is ever evaluated.\n * Returns null if the expression contains anything dynamic (function calls,\n * template literals, identifiers, computed properties, etc.).\n *\n * Supports: string literals, numeric literals, boolean literals,\n * arrays of the above, and nested object literals.\n */\nfunction parseStaticObjectLiteral(objectStr: string): Record<string, unknown> | null {\n let ast: ReturnType<typeof parseAst>;\n try {\n // Wrap in parens so the parser treats `{…}` as an expression, not a block\n ast = parseAst(`(${objectStr})`);\n } catch {\n return null;\n }\n\n // The AST should be: Program > ExpressionStatement > ObjectExpression\n const body = ast.body;\n if (body.length !== 1 || body[0].type !== \"ExpressionStatement\") return null;\n\n const expr = body[0].expression;\n if (expr.type !== \"ObjectExpression\") return null;\n\n const result = extractStaticValue(expr);\n return result === undefined ? null : (result as Record<string, unknown>);\n}\n\n/**\n * Recursively extract a static value from an ESTree AST node.\n * Returns undefined (not null) if the node contains any dynamic expression.\n *\n * Uses `any` for the node parameter because Rollup's internal ESTree types\n * (estree.Expression, estree.ObjectExpression, etc.) aren't re-exported by Vite,\n * and the recursive traversal touches many different node shapes.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction extractStaticValue(node: any): unknown {\n switch (node.type) {\n case \"Literal\":\n // String, number, boolean, null\n return node.value;\n\n case \"UnaryExpression\":\n // Handle negative numbers: -1, -3.14\n if (\n node.operator === \"-\" &&\n node.argument?.type === \"Literal\" &&\n typeof node.argument.value === \"number\"\n ) {\n return -node.argument.value;\n }\n return undefined;\n\n case \"ArrayExpression\": {\n const arr: unknown[] = [];\n for (const elem of node.elements) {\n if (!elem) return undefined; // sparse array\n const val = extractStaticValue(elem);\n if (val === undefined) return undefined;\n arr.push(val);\n }\n return arr;\n }\n\n case \"ObjectExpression\": {\n const obj: Record<string, unknown> = {};\n for (const prop of node.properties) {\n if (prop.type !== \"Property\") return undefined; // SpreadElement etc.\n if (prop.computed) return undefined; // [expr]: val\n\n // Key can be Identifier (unquoted) or Literal (quoted)\n let key: string;\n if (prop.key.type === \"Identifier\") {\n key = prop.key.name;\n } else if (prop.key.type === \"Literal\" && typeof prop.key.value === \"string\") {\n key = prop.key.value;\n } else {\n return undefined;\n }\n\n const val = extractStaticValue(prop.value);\n if (val === undefined) return undefined;\n obj[key] = val;\n }\n return obj;\n }\n\n default:\n // TemplateLiteral, CallExpression, Identifier, etc. — reject\n return undefined;\n }\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) return \"/\";\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: any[] } | 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(projectRoot: string): Promise<{ plugins: any[] } | 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: any[] } | 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 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: any) => 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: any) => {\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;\nconst VIRTUAL_GOOGLE_FONTS = \"virtual:vinext-google-fonts\";\nconst RESOLVED_VIRTUAL_GOOGLE_FONTS = \"\\0\" + VIRTUAL_GOOGLE_FONTS;\n\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// IMPORTANT: keep this set in sync with the non-default exports from\n// packages/vinext/src/shims/font-google.ts (and its re-export barrel).\nconst GOOGLE_FONT_UTILITY_EXPORTS = new Set([\n \"buildGoogleFontsUrl\",\n \"getSSRFontLinks\",\n \"getSSRFontStyles\",\n \"getSSRFontPreloads\",\n \"createFontLoader\",\n]);\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\ntype GoogleFontNamedSpecifier = {\n imported: string;\n local: string;\n isType: boolean;\n raw: string;\n};\n\nfunction parseGoogleFontNamedSpecifiers(\n specifiersStr: string,\n forceType = false,\n): GoogleFontNamedSpecifier[] {\n return specifiersStr\n .split(\",\")\n .map((spec) => spec.trim())\n .filter(Boolean)\n .map((raw) => {\n const isType = forceType || raw.startsWith(\"type \");\n const valueSpec = isType ? raw.replace(/^type\\s+/, \"\") : raw;\n const asParts = valueSpec.split(/\\s+as\\s+/);\n const imported = asParts[0]?.trim() ?? \"\";\n const local = (asParts[1] || asParts[0] || \"\").trim();\n return { imported, local, isType, raw };\n })\n .filter((spec) => spec.imported.length > 0 && spec.local.length > 0);\n}\n\nfunction parseGoogleFontImportClause(clause: string): {\n defaultLocal: string | null;\n namespaceLocal: string | null;\n named: GoogleFontNamedSpecifier[];\n} {\n const trimmed = clause.trim();\n\n if (trimmed.startsWith(\"type \")) {\n const braceStart = trimmed.indexOf(\"{\");\n const braceEnd = trimmed.lastIndexOf(\"}\");\n if (braceStart === -1 || braceEnd === -1) {\n return { defaultLocal: null, namespaceLocal: null, named: [] };\n }\n return {\n defaultLocal: null,\n namespaceLocal: null,\n named: parseGoogleFontNamedSpecifiers(trimmed.slice(braceStart + 1, braceEnd), true),\n };\n }\n\n const braceStart = trimmed.indexOf(\"{\");\n const braceEnd = trimmed.lastIndexOf(\"}\");\n if (braceStart !== -1 && braceEnd !== -1) {\n const beforeNamed = trimmed.slice(0, braceStart).trim().replace(/,\\s*$/, \"\").trim();\n return {\n defaultLocal: beforeNamed || null,\n namespaceLocal: null,\n named: parseGoogleFontNamedSpecifiers(trimmed.slice(braceStart + 1, braceEnd)),\n };\n }\n\n const commaIndex = trimmed.indexOf(\",\");\n if (commaIndex !== -1) {\n const defaultLocal = trimmed.slice(0, commaIndex).trim() || null;\n const rest = trimmed.slice(commaIndex + 1).trim();\n if (rest.startsWith(\"* as \")) {\n return {\n defaultLocal,\n namespaceLocal: rest.slice(\"* as \".length).trim() || null,\n named: [],\n };\n }\n }\n\n if (trimmed.startsWith(\"* as \")) {\n return {\n defaultLocal: null,\n namespaceLocal: trimmed.slice(\"* as \".length).trim() || null,\n named: [],\n };\n }\n\n return {\n defaultLocal: trimmed || null,\n namespaceLocal: null,\n named: [],\n };\n}\n\nfunction encodeGoogleFontsVirtualId(payload: {\n hasDefault: boolean;\n fonts: string[];\n utilities: string[];\n}): string {\n const params = new URLSearchParams();\n if (payload.hasDefault) params.set(\"default\", \"1\");\n if (payload.fonts.length > 0) params.set(\"fonts\", payload.fonts.join(\",\"));\n if (payload.utilities.length > 0) params.set(\"utilities\", payload.utilities.join(\",\"));\n return `${VIRTUAL_GOOGLE_FONTS}?${params.toString()}`;\n}\n\nfunction parseGoogleFontsVirtualId(id: string): {\n hasDefault: boolean;\n fonts: string[];\n utilities: string[];\n} | null {\n const cleanId = id.startsWith(\"\\0\") ? id.slice(1) : id;\n if (!cleanId.startsWith(VIRTUAL_GOOGLE_FONTS)) return null;\n const queryIndex = cleanId.indexOf(\"?\");\n const params = new URLSearchParams(queryIndex === -1 ? \"\" : cleanId.slice(queryIndex + 1));\n return {\n hasDefault: params.get(\"default\") === \"1\",\n fonts:\n params\n .get(\"fonts\")\n ?.split(\",\")\n .map((value) => value.trim())\n .filter(Boolean) ?? [],\n utilities:\n params\n .get(\"utilities\")\n ?.split(\",\")\n .map((value) => value.trim())\n .filter(Boolean) ?? [],\n };\n}\n\nfunction generateGoogleFontsVirtualModule(id: string): string | null {\n const payload = parseGoogleFontsVirtualId(id);\n if (!payload) return null;\n\n const utilities = Array.from(new Set(payload.utilities));\n const fonts = Array.from(new Set(payload.fonts));\n const lines: string[] = [];\n\n lines.push(`import { createFontLoader } from ${JSON.stringify(_fontGoogleShimPath)};`);\n\n const reExports: string[] = [];\n if (payload.hasDefault) reExports.push(\"default\");\n reExports.push(...utilities);\n if (reExports.length > 0) {\n lines.push(`export { ${reExports.join(\", \")} } from ${JSON.stringify(_fontGoogleShimPath)};`);\n }\n\n for (const fontName of fonts) {\n const family = fontName.replace(/_/g, \" \");\n lines.push(\n `export const ${fontName} = /*#__PURE__*/ createFontLoader(${JSON.stringify(family)});`,\n );\n }\n\n lines.push(\"\");\n return lines.join(\"\\n\");\n}\n\nfunction propertyNameToGoogleFontFamily(prop: string): string {\n return prop.replace(/_/g, \" \").replace(/([a-z])([A-Z])/g, \"$1 $2\");\n}\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\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 BuildManifestChunk = {\n file: string;\n isEntry?: boolean;\n isDynamicEntry?: boolean;\n imports?: string[];\n dynamicImports?: string[];\n css?: string[];\n assets?: string[];\n};\n\n/**\n * Compute the set of chunk filenames that are ONLY reachable through dynamic\n * imports (i.e. behind React.lazy(), next/dynamic, or manual import()).\n *\n * These chunks should NOT be modulepreloaded in the HTML — they will be\n * fetched on demand when the dynamic import executes.\n *\n * Algorithm: Starting from all entry chunks in the build manifest, walk the\n * static `imports` tree (breadth-first). Any chunk file NOT reached by this\n * walk is only reachable through `dynamicImports` and is therefore \"lazy\".\n *\n * @param buildManifest - Vite's build manifest (manifest.json), which is a\n * Record<string, ManifestChunk> where each chunk has `file`, `imports`,\n * `dynamicImports`, `isEntry`, and `isDynamicEntry` fields.\n * @returns Array of chunk filenames (e.g. \"assets/mermaid-NOHMQCX5.js\") that\n * should be excluded from modulepreload hints.\n */\nfunction computeLazyChunks(buildManifest: Record<string, BuildManifestChunk>): string[] {\n // Collect all chunk files that are statically reachable from entries\n const eagerFiles = new Set<string>();\n const visited = new Set<string>();\n const queue: string[] = [];\n\n // Start BFS from all entry chunks\n for (const key of Object.keys(buildManifest)) {\n const chunk = buildManifest[key];\n if (chunk.isEntry) {\n queue.push(key);\n }\n }\n\n while (queue.length > 0) {\n const key = queue.shift()!;\n if (visited.has(key)) continue;\n visited.add(key);\n\n const chunk = buildManifest[key];\n if (!chunk) continue;\n\n // Mark this chunk's file as eager\n eagerFiles.add(chunk.file);\n\n // Also mark its CSS as eager (CSS should always be preloaded to avoid FOUC)\n if (chunk.css) {\n for (const cssFile of chunk.css) {\n eagerFiles.add(cssFile);\n }\n }\n\n // Follow only static imports — NOT dynamicImports\n if (chunk.imports) {\n for (const imp of chunk.imports) {\n if (!visited.has(imp)) {\n queue.push(imp);\n }\n }\n }\n }\n\n // Any JS file in the manifest that's NOT in eagerFiles is a lazy chunk\n const lazyChunks: string[] = [];\n const allFiles = new Set<string>();\n for (const key of Object.keys(buildManifest)) {\n const chunk = buildManifest[key];\n if (chunk.file && !allFiles.has(chunk.file)) {\n allFiles.add(chunk.file);\n if (!eagerFiles.has(chunk.file) && chunk.file.endsWith(\".js\")) {\n lazyChunks.push(chunk.file);\n }\n }\n }\n\n return lazyChunks;\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 interface 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 * 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 * 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\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 hasCloudflarePlugin = 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 // Build-only cache for og-inline-fetch-assets to avoid repeated file reads\n // during a single production build. Dev mode skips the cache so asset edits\n // are picked up without restarting the Vite server.\n const _ogInlineCache = new Map<string, string>();\n let _ogInlineIsBuild = false;\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. Populated during config() if MDX\n // files are detected and @mdx-js/rollup is installed.\n let mdxDelegate: Plugin | null = null;\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 //\n // @vitejs/plugin-rsc uses `periscopic` to find closure variables for\n // 'use server' inline functions. Due to how periscopic handles block scopes,\n // `const X = ...` declared inside a 'use server' function body is tracked in\n // the BlockStatement scope (not the FunctionDeclaration scope). When periscopic\n // searches for the owner of a reference `X`, it finds the block scope — which\n // is neither the function scope nor the module scope — so it incorrectly\n // classifies `X` as a closure variable from the outer scope.\n //\n // The result: plugin-rsc injects `const [X] = await decryptActionBoundArgs(...)`\n // at the top of the hoisted function, colliding with the existing `const X = ...`\n // declaration in the body. This causes a SyntaxError.\n //\n // Fix: before plugin-rsc sees the file, detect any 'use server' function whose\n // local `const/let/var` declarations shadow an outer-scope variable, and rename\n // the inner declarations (+ usages within that function) to `__local_X`. This\n // eliminates the collision without changing semantics.\n //\n // This is a general fix that works for any library — not just @payloadcms/next.\n {\n name: \"vinext:fix-use-server-closure-collision\",\n enforce: \"pre\" as const,\n transform(code: string, id: string) {\n // Quick bail-out: only files that contain 'use server' inline\n if (!code.includes(\"use server\")) return null;\n // Only JS/TS files\n if (!/\\.(js|jsx|ts|tsx|mjs|cjs)$/.test(id.split(\"?\")[0])) return null;\n\n let ast: any;\n try {\n ast = parseAst(code);\n } catch {\n return null;\n }\n\n function collectPatternNames(pattern: any, names: Set<string>) {\n if (!pattern) return;\n if (pattern.type === \"Identifier\") {\n names.add(pattern.name);\n } else if (pattern.type === \"ObjectPattern\") {\n for (const prop of pattern.properties) {\n collectPatternNames(prop.value ?? prop.argument, names);\n }\n } else if (pattern.type === \"ArrayPattern\") {\n for (const elem of pattern.elements) {\n collectPatternNames(elem, names);\n }\n } else if (pattern.type === \"RestElement\" || pattern.type === \"AssignmentPattern\") {\n collectPatternNames(pattern.left ?? pattern.argument, names);\n }\n }\n\n // Check if a block body has 'use server' as its leading directive prologue.\n // Only the first contiguous run of string-literal expression statements\n // counts — a \"use server\" string mid-function is not a directive.\n function hasUseServerDirective(body: any[]): boolean {\n for (const stmt of body) {\n if (\n stmt.type === \"ExpressionStatement\" &&\n stmt.expression?.type === \"Literal\" &&\n typeof stmt.expression.value === \"string\"\n ) {\n if (stmt.expression.value === \"use server\") return true;\n // Any other string literal in the prologue — keep scanning\n continue;\n }\n // First non-string-literal statement ends the prologue\n break;\n }\n return false;\n }\n\n // Find all 'use server' inline functions and check for collisions.\n //\n // `ancestorNames` accumulates the names that are in scope in all ancestor\n // function/program bodies as we descend — this is the correct set to\n // compare against, not a whole-AST walk (which would pick up siblings).\n const s = new MagicString(code);\n // Track source ranges already rewritten so renamingWalk never calls\n // s.update() twice on the same span (MagicString throws if it does).\n const renamedRanges = new Set<string>();\n let changed = false;\n\n function visitNode(node: any, ancestorNames: Set<string>) {\n if (!node || typeof node !== \"object\") return;\n\n const isFn =\n node.type === \"FunctionDeclaration\" ||\n node.type === \"FunctionExpression\" ||\n node.type === \"ArrowFunctionExpression\";\n\n if (!isFn) {\n // Non-function nodes (Program, BlockStatement, IfStatement, CatchClause,\n // etc.) don't introduce a new function scope, but they may contain\n // variable declarations and catch bindings that are visible to nested\n // functions as ancestor names. Accumulate those into a new set before\n // recursing so we don't mutate the caller's set.\n const namesForChildren = new Set(ancestorNames);\n\n // CatchClause: `catch (e)` — `e` is in scope for the catch body\n if (node.type === \"CatchClause\" && node.param) {\n collectPatternNames(node.param, namesForChildren);\n }\n\n // Collect names visible at function scope from this node:\n // - FunctionDeclaration names (hoisted to enclosing scope)\n // - ClassDeclaration names (block-scoped like let, but treated as\n // function-scoped for our purposes since periscopic sees them)\n // - var declarations (hoisted to function scope, found anywhere)\n // We do NOT collect let/const from nested blocks here — those are\n // block-scoped and not visible to sibling/outer function declarations.\n collectFunctionScopedNames(node, namesForChildren);\n // Also collect let/const/var/class/import declared as immediate children\n // of this node (e.g. top-level Program statements, or the direct body of\n // a BlockStatement) — those ARE in scope for everything in the same block.\n const immediateStmts: any[] =\n node.type === \"Program\" ? node.body : node.type === \"BlockStatement\" ? node.body : [];\n for (const stmt of immediateStmts) {\n if (stmt?.type === \"VariableDeclaration\") {\n for (const decl of stmt.declarations)\n collectPatternNames(decl.id, namesForChildren);\n } else if (stmt?.type === \"ClassDeclaration\" && stmt.id?.name) {\n namesForChildren.add(stmt.id.name);\n } else if (stmt?.type === \"ImportDeclaration\") {\n for (const spec of stmt.specifiers ?? []) {\n // ImportDefaultSpecifier, ImportNamespaceSpecifier, ImportSpecifier\n // all have `local.name` as the binding name in this module.\n if (spec.local?.name) namesForChildren.add(spec.local.name);\n }\n }\n }\n\n for (const key of Object.keys(node)) {\n if (key === \"type\") continue;\n const child = node[key];\n if (Array.isArray(child)) {\n for (const c of child) visitNode(c, namesForChildren);\n } else if (child && typeof child === \"object\" && child.type) {\n visitNode(child, namesForChildren);\n }\n }\n return;\n }\n\n // Build the ancestor name set visible inside this function:\n // everything the parent saw, plus this function's own params.\n const namesForBody = new Set(ancestorNames);\n for (const p of node.params ?? []) collectPatternNames(p, namesForBody);\n\n // Check whether the body has the 'use server' directive.\n const bodyStmts: any[] = node.body?.type === \"BlockStatement\" ? node.body.body : [];\n const isServerFn = hasUseServerDirective(bodyStmts);\n\n if (isServerFn) {\n // Collect ALL variables declared anywhere in this function body.\n // This includes direct bodyStmts, but also for...of/for...in loop\n // variables, declarations inside if/try/while blocks, etc.\n // periscopic puts these in the BlockStatement scope (not the function\n // scope), so they get mis-classified as closure vars from the outer scope.\n // We use collectAllDeclaredNames (recursive, crosses blocks, stops at\n // nested function bodies) to catch every possible declaration site.\n const localDecls = new Set<string>();\n collectAllDeclaredNames(node.body, localDecls);\n\n // Find collisions: local decls that shadow a name from ancestor scopes.\n // collisionRenames maps original name → chosen rename target, taking\n // into account that `__local_${name}` may itself already be declared\n // (e.g. the user wrote `const __local_cookies = ...`). In that case\n // we try `__local_0_${name}`, `__local_1_${name}`, … until we find a\n // free name. This prevents a secondary collision.\n const collisionRenames = new Map<string, string>();\n for (const name of localDecls) {\n if (namesForBody.has(name)) {\n let to = `__local_${name}`;\n let suffix = 0;\n while (localDecls.has(to) || namesForBody.has(to)) {\n to = `__local_${suffix}_${name}`;\n suffix++;\n }\n collisionRenames.set(name, to);\n }\n }\n\n if (collisionRenames.size > 0) {\n for (const [name, to] of collisionRenames) {\n renamingWalk(node.body, name, to);\n }\n changed = true;\n }\n\n // Build the ancestor set for children of this server function.\n // Colliding names have been renamed in this body, e.g. `cookies` →\n // `__local_cookies`. The original name no longer exists as a binding\n // in this scope, so we must remove it from the set and add the renamed\n // version instead. Leaving the original name in would cause nested\n // server functions to see it as an ancestor binding and spuriously flag\n // their own independent `const cookies` as a collision.\n const namesForChildren = new Set(namesForBody);\n for (const name of localDecls) {\n if (collisionRenames.has(name)) {\n namesForChildren.delete(name);\n namesForChildren.add(collisionRenames.get(name)!);\n } else {\n namesForChildren.add(name);\n }\n }\n\n // Recurse into children — nested 'use server' functions must be visited.\n // Skip node.body itself (already handled by renamingWalk above for\n // collisions); we recurse into each statement individually so that\n // nested functions inside the body get their own visitNode pass with\n // the correct ancestorNames.\n for (const stmt of bodyStmts) {\n visitNode(stmt, namesForChildren);\n }\n // Also visit params (they can contain default expressions with closures)\n for (const p of node.params ?? []) visitNode(p, ancestorNames);\n return;\n }\n\n // Not a server function — build the ancestor set for nested functions:\n // - var declarations anywhere in this function body (function-scoped)\n // - FunctionDeclaration names anywhere in this function body\n // - let/const only from the top-level statements of this function body\n // (block-scoped — not visible to nested fns in sibling blocks)\n const namesForChildren = new Set(namesForBody);\n collectFunctionScopedNames(node.body, namesForChildren);\n for (const stmt of bodyStmts) {\n if (stmt?.type === \"VariableDeclaration\" && stmt.kind !== \"var\") {\n for (const decl of stmt.declarations) collectPatternNames(decl.id, namesForChildren);\n }\n }\n\n for (const key of Object.keys(node)) {\n if (key === \"type\") continue;\n const child = node[key];\n if (Array.isArray(child)) {\n for (const c of child) visitNode(c, namesForChildren);\n } else if (child && typeof child === \"object\" && child.type) {\n visitNode(child, namesForChildren);\n }\n }\n }\n\n // Walk an AST subtree renaming all variable-reference Identifier nodes\n // matching `from` to `to`.\n //\n // Correctness rules:\n // - Non-computed MemberExpression.property is NOT a variable reference\n // - Non-computed Property.key is NOT a variable reference\n // - Shorthand Property { x } must be expanded to { x: __local_x }\n // - A nested function that re-declares `from` in its params OR anywhere\n // in its body via var/const/let (including inside control flow) is a\n // new binding — stop descending into it\n // - Never call s.update() on the same source range twice\n //\n // `parent` is the direct parent AST node, used to detect property contexts.\n function renamingWalk(node: any, from: string, to: string, parent?: any) {\n if (!node || typeof node !== \"object\") return;\n\n if (node.type === \"Identifier\" && node.name === from) {\n // Non-computed member expression property: obj.cookies — not a ref\n if (\n parent?.type === \"MemberExpression\" &&\n parent.property === node &&\n !parent.computed\n ) {\n return;\n }\n\n // Non-computed property key in an object literal\n if (parent?.type === \"Property\" && parent.key === node && !parent.computed) {\n if (parent.shorthand) {\n // { cookies } — key and value are the same AST node.\n // Expand to { cookies: __local_cookies } by rewriting at the key\n // visit; skip the value visit via the guard below.\n const rangeKey = `${node.start}:${node.end}`;\n if (!renamedRanges.has(rangeKey)) {\n renamedRanges.add(rangeKey);\n s.update(node.start, node.end, `${from}: ${to}`);\n }\n }\n // Either way, key is not a variable reference — do not rename it.\n return;\n }\n\n // Value side of a shorthand property — same node as key, already handled\n if (parent?.type === \"Property\" && parent.shorthand && parent.value === node) {\n return;\n }\n\n // LabeledStatement label: `cookies: for (...)` — not a variable reference\n if (parent?.type === \"LabeledStatement\" && parent.label === node) {\n return;\n }\n\n // break/continue label: `break cookies` / `continue cookies` — not a variable reference\n if (\n (parent?.type === \"BreakStatement\" || parent?.type === \"ContinueStatement\") &&\n parent.label === node\n ) {\n return;\n }\n\n const rangeKey = `${node.start}:${node.end}`;\n if (!renamedRanges.has(rangeKey)) {\n renamedRanges.add(rangeKey);\n s.update(node.start, node.end, to);\n }\n return;\n }\n\n // For nested function nodes, check whether they re-declare `from`.\n // If they do, stop — the name in that nested scope is a different binding.\n // We must check ALL var declarations anywhere in the body (var hoists),\n // not just top-level statements.\n if (\n node.type === \"FunctionDeclaration\" ||\n node.type === \"FunctionExpression\" ||\n node.type === \"ArrowFunctionExpression\"\n ) {\n const nestedDecls = new Set<string>();\n // Params\n for (const p of node.params ?? []) collectPatternNames(p, nestedDecls);\n // Recursively find all var/const/let declarations in the body,\n // including those nested inside if/for/while/etc.\n collectAllDeclaredNames(node.body, nestedDecls);\n if (nestedDecls.has(from)) return;\n\n // Also stop at nested 'use server' functions — visitNode will handle them\n // independently with the correct collision set, preventing double-rewrites.\n if (node.body?.type === \"BlockStatement\" && hasUseServerDirective(node.body.body)) {\n return;\n }\n }\n\n for (const key of Object.keys(node)) {\n if (key === \"type\" || key === \"start\" || key === \"end\") continue;\n const child = node[key];\n if (Array.isArray(child)) {\n for (const c of child) renamingWalk(c, from, to, node);\n } else if (child && typeof child === \"object\" && child.type) {\n renamingWalk(child, from, to, node);\n }\n }\n }\n\n // Collect names that are visible at function scope from a given subtree.\n //\n // Two separate helpers with different traversal rules:\n //\n // collectFunctionScopedNames(node, names)\n // Collects `var` declarations and `FunctionDeclaration` names anywhere\n // in the subtree, crossing block boundaries (if/for/while/try/catch)\n // but NOT crossing nested function bodies. `let`/`const` in nested\n // blocks are intentionally skipped — they are block-scoped and not\n // visible outside that block.\n // Use this when building ancestorNames for nested functions.\n //\n // collectAllDeclaredNames(node, names)\n // Collects ALL var/let/const declarations anywhere in the subtree,\n // crossing block boundaries but not nested function bodies.\n // Used only by renamingWalk's re-declaration check, where we want to\n // know if ANY declaration of `from` exists in a nested function's scope\n // (params already handled separately).\n\n function collectFunctionScopedNames(node: any, names: Set<string>) {\n if (!node || typeof node !== \"object\") return;\n // FunctionDeclaration: its name is a binding in the enclosing scope.\n // Record it, then stop — don't recurse into the body (different scope).\n if (node.type === \"FunctionDeclaration\") {\n if (node.id?.name) names.add(node.id.name);\n return;\n }\n // ClassDeclaration: like FunctionDeclaration, its name is a binding in\n // the enclosing scope. Don't recurse into the body.\n if (node.type === \"ClassDeclaration\") {\n if (node.id?.name) names.add(node.id.name);\n return;\n }\n // FunctionExpression / ArrowFunctionExpression names are only in scope\n // inside their own body, not the enclosing scope — skip entirely.\n if (node.type === \"FunctionExpression\" || node.type === \"ArrowFunctionExpression\") {\n return;\n }\n // var declarations are function-scoped — collect them wherever they appear.\n // let/const at a nested block level are block-scoped and NOT visible to\n // sibling or outer function declarations, so skip them here.\n if (node.type === \"VariableDeclaration\" && node.kind === \"var\") {\n for (const decl of node.declarations) collectPatternNames(decl.id, names);\n }\n for (const key of Object.keys(node)) {\n if (key === \"type\") continue;\n const child = node[key];\n if (Array.isArray(child)) {\n for (const c of child) collectFunctionScopedNames(c, names);\n } else if (child && typeof child === \"object\" && child.type) {\n collectFunctionScopedNames(child, names);\n }\n }\n }\n\n // Collect ALL declared names (var/let/const/class/function) in a subtree,\n // crossing blocks but not nested function bodies or class bodies.\n // Used by renamingWalk's re-declaration check where any shadowing\n // declaration — regardless of kind — must stop the rename from descending\n // further, and by the server-function local-decl scan to detect all\n // possible collision sites (including class declarations in the body).\n function collectAllDeclaredNames(node: any, names: Set<string>) {\n if (!node || typeof node !== \"object\") return;\n if (node.type === \"VariableDeclaration\") {\n for (const decl of node.declarations) collectPatternNames(decl.id, names);\n }\n // FunctionDeclaration name is a binding in the enclosing scope — record it.\n if (node.type === \"FunctionDeclaration\") {\n if (node.id?.name) names.add(node.id.name);\n return; // don't recurse into its body\n }\n // ClassDeclaration name is a binding in the enclosing scope — record it.\n if (node.type === \"ClassDeclaration\") {\n if (node.id?.name) names.add(node.id.name);\n return; // don't recurse into the class body (separate scope)\n }\n if (node.type === \"FunctionExpression\" || node.type === \"ArrowFunctionExpression\") {\n return; // different scope — stop\n }\n for (const key of Object.keys(node)) {\n if (key === \"type\") continue;\n const child = node[key];\n if (Array.isArray(child)) {\n for (const c of child) collectAllDeclaredNames(c, names);\n } else if (child && typeof child === \"object\" && child.type) {\n collectAllDeclaredNames(child, names);\n }\n }\n }\n\n visitNode(ast, new Set());\n\n if (!changed) return null;\n return { code: s.toString(), map: s.generateMap({ hires: \"boundary\" }) };\n },\n },\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 const phase = env?.command === \"build\" ? PHASE_PRODUCTION_BUILD : PHASE_DEVELOPMENT_SERVER;\n const rawConfig = await loadNextConfig(root, phase);\n nextConfig = await resolveNextConfig(rawConfig, root);\n fileMatcher = createValidFileMatcher(nextConfig.pageExtensions);\n instrumentationPath = findInstrumentationFile(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/instrumentation\": path.resolve(__dirname, \"server\", \"instrumentation\"),\n \"vinext/html\": path.resolve(__dirname, \"server\", \"html\"),\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: any[] = [];\n function flattenPlugins(arr: any[]) {\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 any[]) ?? []);\n hasCloudflarePlugin = pluginsFlat.some(\n (p: any) =>\n p &&\n typeof p === \"object\" &&\n typeof p.name === \"string\" &&\n (p.name === \"vite-plugin-cloudflare\" || p.name.startsWith(\"vite-plugin-cloudflare:\")),\n );\n hasNitroPlugin = pluginsFlat.some(\n (p: any) =>\n p &&\n typeof p === \"object\" &&\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 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 const hasMdxPlugin = pluginsFlat.some(\n (p: any) =>\n p &&\n typeof p === \"object\" &&\n typeof p.name === \"string\" &&\n (p.name === \"@mdx-js/rollup\" || p.name === \"mdx\"),\n );\n if (\n !hasMdxPlugin &&\n hasMdxFiles(root, hasAppDir ? appDir : null, hasPagesDir ? pagesDir : null)\n ) {\n try {\n const mdxRollup = await import(\"@mdx-js/rollup\");\n const mdxFactory = mdxRollup.default ?? mdxRollup;\n const mdxOpts: Record<string, unknown> = {};\n if (nextConfig.mdx) {\n if (nextConfig.mdx.remarkPlugins)\n mdxOpts.remarkPlugins = nextConfig.mdx.remarkPlugins;\n if (nextConfig.mdx.rehypePlugins)\n mdxOpts.rehypePlugins = nextConfig.mdx.rehypePlugins;\n if (nextConfig.mdx.recmaPlugins) mdxOpts.recmaPlugins = nextConfig.mdx.recmaPlugins;\n }\n mdxDelegate = mdxFactory(mdxOpts);\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 } catch {\n // @mdx-js/rollup not installed — warn but don't fail\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 }\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 rollupOptions: {\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 = config.build?.rollupOptions?.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 ? { output: clientOutputConfig } : {}),\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\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\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: appEntries,\n },\n build: {\n outDir: options.rscOutDir ?? \"dist/server\",\n rollupOptions: {\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: appEntries,\n },\n build: {\n outDir: options.ssrOutDir ?? \"dist/server/ssr\",\n rollupOptions: {\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: appEntries,\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 rollupOptions: {\n input: { index: VIRTUAL_APP_BROWSER_ENTRY },\n output: clientOutputConfig,\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 build: {\n manifest: true,\n ssrManifest: true,\n rollupOptions: {\n input: { index: VIRTUAL_CLIENT_ENTRY },\n output: clientOutputConfig,\n treeshake: clientTreeshakeConfig,\n },\n },\n },\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: any) => p && typeof p.name === \"string\" && 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((p: any) => p && p.name === \"rsc\");\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);\n }\n },\n },\n // Stub node:async_hooks in client builds — see src/plugins/async-hooks-stub.ts\n asyncHooksStubPlugin,\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 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 if (!mdxDelegate?.transform) return;\n const hook = mdxDelegate.transform;\n const fn = typeof hook === \"function\" ? hook : hook.handler;\n return fn.call(this, code, id, options);\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: any[] }) {\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: any, res: any, next: any) => {\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 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 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:\n //\n // 1. Rewrites named next/font/google imports/exports to a tiny virtual module\n // that exports only the requested fonts plus any utility exports.\n // This lets us delete the generated ~1,900-line runtime catalog while\n // keeping ESM import semantics intact.\n // 2. During production builds, fetches Google Fonts CSS + font files and\n // injects _selfHostedCSS into statically analyzable font loader calls.\n {\n name: \"vinext:google-fonts\",\n enforce: \"pre\",\n\n _isBuild: false,\n _fontCache: new Map<string, string>(), // url -> local @font-face CSS\n _cacheDir: \"\",\n\n configResolved(config) {\n (this as any)._isBuild = config.command === \"build\";\n (this as any)._cacheDir = path.join(config.root, \".vinext\", \"fonts\");\n },\n\n transform: {\n // Hook filter: only invoke JS when code contains 'next/font/google'.\n // This still eliminates nearly all Rust-to-JS calls since very few files\n // import from next/font/google.\n filter: {\n id: {\n include: /\\.(tsx?|jsx?|mjs)$/,\n },\n code: \"next/font/google\",\n },\n async handler(code, id) {\n // Defensive guard — duplicates filter logic\n if (id.startsWith(\"\\0\")) return null;\n if (!id.match(/\\.(tsx?|jsx?|mjs)$/)) return null;\n if (!code.includes(\"next/font/google\")) return null;\n if (id.startsWith(_shimsDir)) return null;\n\n const s = new MagicString(code);\n let hasChanges = false;\n let proxyImportCounter = 0;\n const overwrittenRanges: Array<[number, number]> = [];\n const fontLocals = new Map<string, string>();\n const proxyObjectLocals = new Set<string>();\n\n const importRe = /^[ \\t]*import\\s+([^;]+?)\\s+from\\s*([\"'])next\\/font\\/google\\2\\s*;?/gm;\n let importMatch;\n while ((importMatch = importRe.exec(code)) !== null) {\n const [fullMatch, clause] = importMatch;\n const matchStart = importMatch.index;\n const matchEnd = matchStart + fullMatch.length;\n const parsed = parseGoogleFontImportClause(clause);\n const utilityImports = parsed.named.filter(\n (spec) => !spec.isType && GOOGLE_FONT_UTILITY_EXPORTS.has(spec.imported),\n );\n const fontImports = parsed.named.filter(\n (spec) => !spec.isType && !GOOGLE_FONT_UTILITY_EXPORTS.has(spec.imported),\n );\n\n if (parsed.defaultLocal) {\n proxyObjectLocals.add(parsed.defaultLocal);\n }\n for (const fontImport of fontImports) {\n fontLocals.set(fontImport.local, fontImport.imported);\n }\n\n if (fontImports.length > 0) {\n const virtualId = encodeGoogleFontsVirtualId({\n hasDefault: Boolean(parsed.defaultLocal),\n fonts: Array.from(new Set(fontImports.map((spec) => spec.imported))),\n utilities: Array.from(new Set(utilityImports.map((spec) => spec.imported))),\n });\n s.overwrite(\n matchStart,\n matchEnd,\n `import ${clause} from ${JSON.stringify(virtualId)};`,\n );\n overwrittenRanges.push([matchStart, matchEnd]);\n hasChanges = true;\n continue;\n }\n\n if (parsed.namespaceLocal) {\n const proxyImportName = `__vinext_google_fonts_proxy_${proxyImportCounter++}`;\n const replacementLines = [\n `import ${proxyImportName} from ${JSON.stringify(_fontGoogleShimPath)};`,\n ];\n if (parsed.defaultLocal) {\n replacementLines.push(`var ${parsed.defaultLocal} = ${proxyImportName};`);\n }\n replacementLines.push(`var ${parsed.namespaceLocal} = ${proxyImportName};`);\n s.overwrite(matchStart, matchEnd, replacementLines.join(\"\\n\"));\n overwrittenRanges.push([matchStart, matchEnd]);\n proxyObjectLocals.add(parsed.namespaceLocal);\n hasChanges = true;\n }\n }\n\n const exportRe = /^[ \\t]*export\\s*\\{([^}]+)\\}\\s*from\\s*([\"'])next\\/font\\/google\\2\\s*;?/gm;\n let exportMatch;\n while ((exportMatch = exportRe.exec(code)) !== null) {\n const [fullMatch, specifiers] = exportMatch;\n const matchStart = exportMatch.index;\n const matchEnd = matchStart + fullMatch.length;\n const namedExports = parseGoogleFontNamedSpecifiers(specifiers);\n const utilityExports = namedExports.filter(\n (spec) => !spec.isType && GOOGLE_FONT_UTILITY_EXPORTS.has(spec.imported),\n );\n const fontExports = namedExports.filter(\n (spec) => !spec.isType && !GOOGLE_FONT_UTILITY_EXPORTS.has(spec.imported),\n );\n if (fontExports.length === 0) continue;\n\n const virtualId = encodeGoogleFontsVirtualId({\n hasDefault: false,\n fonts: Array.from(new Set(fontExports.map((spec) => spec.imported))),\n utilities: Array.from(new Set(utilityExports.map((spec) => spec.imported))),\n });\n s.overwrite(\n matchStart,\n matchEnd,\n `export { ${specifiers.trim()} } from ${JSON.stringify(virtualId)};`,\n );\n overwrittenRanges.push([matchStart, matchEnd]);\n hasChanges = true;\n }\n\n const cacheDir = (this as any)._cacheDir as string;\n const fontCache = (this as any)._fontCache as Map<string, string>;\n\n async function injectSelfHostedCss(\n callStart: number,\n callEnd: number,\n optionsStr: string,\n family: string,\n calleeSource: string,\n ) {\n // Parse options safely via AST — no eval/new Function\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let options: Record<string, any> = {};\n try {\n const parsed = parseStaticObjectLiteral(optionsStr);\n if (!parsed) return; // Contains dynamic expressions, skip\n options = parsed as Record<string, any>;\n } catch {\n return; // Can't parse options statically, skip\n }\n\n // Build the Google Fonts CSS URL\n const weights = options.weight\n ? Array.isArray(options.weight)\n ? options.weight\n : [options.weight]\n : [];\n const styles = options.style\n ? Array.isArray(options.style)\n ? options.style\n : [options.style]\n : [];\n const display = options.display ?? \"swap\";\n\n let spec = family.replace(/\\s+/g, \"+\");\n if (weights.length > 0) {\n const hasItalic = styles.includes(\"italic\");\n if (hasItalic) {\n const pairs: string[] = [];\n for (const w of weights) {\n pairs.push(`0,${w}`);\n pairs.push(`1,${w}`);\n }\n spec += `:ital,wght@${pairs.join(\";\")}`;\n } else {\n spec += `:wght@${weights.join(\";\")}`;\n }\n } else if (styles.length === 0) {\n // Request full variable weight range when no weight specified.\n // Without this, Google Fonts returns only weight 400.\n spec += `:wght@100..900`;\n }\n const params = new URLSearchParams();\n params.set(\"family\", spec);\n params.set(\"display\", display);\n const cssUrl = `https://fonts.googleapis.com/css2?${params.toString()}`;\n\n // Check cache\n let localCSS = fontCache.get(cssUrl);\n if (!localCSS) {\n try {\n localCSS = await fetchAndCacheFont(cssUrl, family, cacheDir);\n fontCache.set(cssUrl, localCSS);\n } catch {\n // Fetch failed (offline?) — fall back to CDN mode\n return;\n }\n }\n\n // Inject _selfHostedCSS into the options object\n const escapedCSS = JSON.stringify(localCSS);\n const closingBrace = optionsStr.lastIndexOf(\"}\");\n const optionsWithCSS =\n optionsStr.slice(0, closingBrace) +\n (optionsStr.slice(0, closingBrace).trim().endsWith(\"{\") ? \"\" : \", \") +\n `_selfHostedCSS: ${escapedCSS}` +\n optionsStr.slice(closingBrace);\n\n const replacement = `${calleeSource}(${optionsWithCSS})`;\n s.overwrite(callStart, callEnd, replacement);\n hasChanges = true;\n }\n\n if ((this as any)._isBuild) {\n const namedCallRe = /\\b([A-Za-z_$][A-Za-z0-9_$]*)\\s*\\(\\s*(\\{[^}]*\\})\\s*\\)/g;\n let namedCallMatch;\n while ((namedCallMatch = namedCallRe.exec(code)) !== null) {\n const [fullMatch, localName, optionsStr] = namedCallMatch;\n const importedName = fontLocals.get(localName);\n if (!importedName) continue;\n\n const callStart = namedCallMatch.index;\n const callEnd = callStart + fullMatch.length;\n if (overwrittenRanges.some(([start, end]) => callStart < end && callEnd > start)) {\n continue;\n }\n\n await injectSelfHostedCss(\n callStart,\n callEnd,\n optionsStr,\n importedName.replace(/_/g, \" \"),\n localName,\n );\n }\n\n const memberCallRe =\n /\\b([A-Za-z_$][A-Za-z0-9_$]*)\\.([A-Za-z_$][A-Za-z0-9_$]*)\\s*\\(\\s*(\\{[^}]*\\})\\s*\\)/g;\n let memberCallMatch;\n while ((memberCallMatch = memberCallRe.exec(code)) !== null) {\n const [fullMatch, objectName, propName, optionsStr] = memberCallMatch;\n if (!proxyObjectLocals.has(objectName)) continue;\n\n const callStart = memberCallMatch.index;\n const callEnd = callStart + fullMatch.length;\n if (overwrittenRanges.some(([start, end]) => callStart < end && callEnd > start)) {\n continue;\n }\n\n await injectSelfHostedCss(\n callStart,\n callEnd,\n optionsStr,\n propertyNameToGoogleFontFamily(propName),\n `${objectName}.${propName}`,\n );\n }\n }\n\n if (!hasChanges) return null;\n return {\n code: s.toString(),\n map: s.generateMap({ hires: \"boundary\" }),\n };\n },\n },\n } as Plugin & { _isBuild: boolean; _fontCache: Map<string, string>; _cacheDir: string },\n // Local font path resolution:\n // When a source file calls localFont({ src: \"./font.woff2\" }) or\n // localFont({ src: [{ path: \"./font.woff2\" }] }), the relative paths\n // won't resolve in the browser because the CSS is injected at runtime.\n // This plugin rewrites those path strings into Vite asset import\n // references so that both dev (/@fs/...) and prod (/assets/font-xxx.woff2)\n // URLs are correct.\n {\n name: \"vinext:local-fonts\",\n enforce: \"pre\",\n\n transform: {\n filter: {\n id: {\n include: /\\.(tsx?|jsx?|mjs)$/,\n exclude: /node_modules/,\n },\n code: \"next/font/local\",\n },\n handler(code, id) {\n // Defensive guards — duplicate 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(\"next/font/local\")) return null;\n // Skip vinext's own font-local shim — it contains example paths\n // in comments that would be incorrectly rewritten.\n if (id.includes(\"font-local\")) return null;\n\n // Verify there's actually an import from next/font/local\n const importRe = /import\\s+\\w+\\s+from\\s*['\"]next\\/font\\/local['\"]/;\n if (!importRe.test(code)) return null;\n\n const s = new MagicString(code);\n let hasChanges = false;\n let fontImportCounter = 0;\n const imports: string[] = [];\n\n // Match font file paths in `path: \"...\"` or `src: \"...\"` properties.\n // Captures: (1) property+colon prefix, (2) quote char, (3) the path.\n const fontPathRe = /((?:path|src)\\s*:\\s*)(['\"])([^'\"]+\\.(?:woff2?|ttf|otf|eot))\\2/g;\n\n let match;\n while ((match = fontPathRe.exec(code)) !== null) {\n const [fullMatch, prefix, _quote, fontPath] = match;\n const varName = `__vinext_local_font_${fontImportCounter++}`;\n\n // Add an import for this font file — Vite resolves it as a static\n // asset and returns the correct URL for both dev and prod.\n imports.push(`import ${varName} from ${JSON.stringify(fontPath)};`);\n\n // Replace: path: \"./font.woff2\" -> path: __vinext_local_font_0\n const matchStart = match.index;\n const matchEnd = matchStart + fullMatch.length;\n s.overwrite(matchStart, matchEnd, `${prefix}${varName}`);\n hasChanges = true;\n }\n\n if (!hasChanges) return null;\n\n // Prepend the asset imports at the top of the file\n s.prepend(imports.join(\"\\n\") + \"\\n\");\n\n return {\n code: s.toString(),\n map: s.generateMap({ hires: \"boundary\" }),\n };\n },\n },\n } as Plugin,\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 as any[]).find(\n (node: any) =>\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: any): 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 = fn?.body?.type === \"BlockStatement\" ? fn.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: any[]): 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];\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 as any[]);\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 const directiveValue: string = cacheDirective.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 as any, {\n runtime: (value: any, name: any) =>\n `(await import(${JSON.stringify(runtimeModuleUrl)})).registerCachedFunction(${value}, ${JSON.stringify(id + \":\" + name)}, ${JSON.stringify(variant)})`,\n rejectNonAsyncFunction: false,\n filter: (name: any, meta: any) => {\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 as any, {\n directive: /^use cache(:\\s*\\w+)?$/,\n runtime: (value: any, name: any, meta: any) => {\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 //\n // Some bundled libraries (notably @vercel/og) load assets at module init time\n // with the pattern:\n //\n // fetch(new URL(\"./some-font.ttf\", import.meta.url)).then(res => res.arrayBuffer())\n //\n // This works in browser and standard Node.js because import.meta.url is a real\n // file:// URL. In Cloudflare Workers (both wrangler dev and production), however,\n // import.meta.url is the string \"worker\" — not a URL — so new URL(...) throws\n // \"TypeError: Invalid URL string\" and the Worker fails to start.\n //\n // Fix: at Vite transform time, find every such pattern, resolve the referenced\n // file relative to the module's actual path on disk (available as `id`), read it,\n // and replace the entire fetch(new URL(...)) expression with an inline base64 IIFE\n // that resolves synchronously. This eliminates the runtime fetch entirely and works\n // in all environments (workerd, Node.js, browser).\n //\n // Note: WASM files imported via `import ... from \"./foo.wasm?module\"` are handled\n // by the bundler/Vite directly and do not need this treatment. Only assets that\n // are runtime-fetched (not statically imported) need to be inlined here.\n {\n name: \"vinext:og-inline-fetch-assets\",\n enforce: \"pre\",\n configResolved(config) {\n _ogInlineIsBuild = config.command === \"build\";\n },\n buildStart() {\n if (_ogInlineIsBuild) {\n _ogInlineCache.clear();\n }\n },\n async transform(code, id) {\n // Quick bail-out: only process modules that use new URL(..., import.meta.url)\n if (!code.includes(\"import.meta.url\")) {\n return null;\n }\n\n const useCache = _ogInlineIsBuild;\n const moduleDir = path.dirname(id);\n let newCode = code;\n let didReplace = false;\n\n // Pattern 1 — edge build: fetch(new URL(\"./file\", import.meta.url)).then((res) => res.arrayBuffer())\n // Replace with an inline IIFE that decodes the asset as base64 and returns Promise<ArrayBuffer>.\n if (code.includes(\"fetch(\")) {\n const fetchPattern =\n /fetch\\(\\s*new URL\\(\\s*([\"'])(\\.\\/[^\"']+)\\1\\s*,\\s*import\\.meta\\.url\\s*\\)\\s*\\)(?:\\.then\\(\\s*(?:function\\s*\\([^)]*\\)|\\([^)]*\\)\\s*=>)\\s*\\{?\\s*return\\s+[^.]+\\.arrayBuffer\\(\\)\\s*\\}?\\s*\\)|\\.then\\(\\s*\\([^)]*\\)\\s*=>\\s*[^.]+\\.arrayBuffer\\(\\)\\s*\\))/g;\n\n for (const match of code.matchAll(fetchPattern)) {\n const fullMatch = match[0];\n const relPath = match[2]; // e.g. \"./noto-sans-v27-latin-regular.ttf\"\n const absPath = path.resolve(moduleDir, relPath);\n\n let fileBase64 = useCache ? _ogInlineCache.get(absPath) : undefined;\n if (fileBase64 === undefined) {\n try {\n const buf = await fs.promises.readFile(absPath);\n fileBase64 = buf.toString(\"base64\");\n if (useCache) {\n _ogInlineCache.set(absPath, fileBase64);\n }\n } catch {\n // File not found on disk — skip (may be a runtime-only asset)\n continue;\n }\n }\n\n // Replace fetch(...).then(...) with an inline IIFE that returns Promise<ArrayBuffer>.\n const inlined = [\n `(function(){`,\n `var b=${JSON.stringify(fileBase64)};`,\n `var r=atob(b);`,\n `var a=new Uint8Array(r.length);`,\n `for(var i=0;i<r.length;i++)a[i]=r.charCodeAt(i);`,\n `return Promise.resolve(a.buffer);`,\n `})()`,\n ].join(\"\");\n\n newCode = newCode.replaceAll(fullMatch, inlined);\n didReplace = true;\n }\n }\n\n // Pattern 2 — node build: readFileSync(fileURLToPath(new URL(\"./file\", import.meta.url)))\n // Replace with Buffer.from(\"<base64>\", \"base64\"), which returns a Buffer (compatible with\n // both font data passed to satori and WASM bytes passed to initWasm).\n if (code.includes(\"readFileSync(\")) {\n const readFilePattern =\n /[a-zA-Z_$][a-zA-Z0-9_$]*\\.readFileSync\\(\\s*(?:[a-zA-Z_$][a-zA-Z0-9_$]*\\.)?fileURLToPath\\(\\s*new URL\\(\\s*([\"'])(\\.\\/[^\"']+)\\1\\s*,\\s*import\\.meta\\.url\\s*\\)\\s*\\)\\s*\\)/g;\n\n for (const match of newCode.matchAll(readFilePattern)) {\n const fullMatch = match[0];\n const relPath = match[2]; // e.g. \"./noto-sans-v27-latin-regular.ttf\"\n const absPath = path.resolve(moduleDir, relPath);\n\n let fileBase64 = useCache ? _ogInlineCache.get(absPath) : undefined;\n if (fileBase64 === undefined) {\n try {\n const buf = await fs.promises.readFile(absPath);\n fileBase64 = buf.toString(\"base64\");\n if (useCache) {\n _ogInlineCache.set(absPath, fileBase64);\n }\n } catch {\n // File not found on disk — skip\n continue;\n }\n }\n\n // Replace readFileSync(...) with Buffer.from(\"<base64>\", \"base64\").\n // Buffer is always available in Node.js and in the vinext SSR/RSC environments.\n const inlined = `Buffer.from(${JSON.stringify(fileBase64)},\"base64\")`;\n\n newCode = newCode.replaceAll(fullMatch, inlined);\n didReplace = true;\n }\n }\n\n if (!didReplace) return null;\n return { code: newCode, map: null };\n },\n },\n // Copy @vercel/og binary assets to the RSC output directory for production builds.\n //\n // The edge build (dist/index.edge.js) uses:\n // - fetch(new URL(\"./noto-sans...\", import.meta.url)) → inlined by og-inline-fetch-assets\n // - import resvg_wasm from \"./resvg.wasm?module\" → static Vite import, emitted by Rollup\n //\n // The node build (dist/index.node.js) uses:\n // - fs.readFileSync(fileURLToPath(new URL(\"./noto-sans...\", import.meta.url))) → inlined\n // - fs.readFileSync(fileURLToPath(new URL(\"./resvg.wasm\", import.meta.url))) → inlined\n //\n // Both builds' font + WASM assets are inlined as base64 by vinext:og-inline-fetch-assets,\n // so no file copy is strictly needed. This plugin is kept as a safety net for any edge-build\n // ?module WASM imports that Rollup/Vite might not emit correctly in the RSC environment.\n {\n name: \"vinext:og-assets\",\n apply: \"build\",\n enforce: \"post\",\n writeBundle: {\n sequential: true,\n order: \"post\",\n async 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 // Check if the bundle references @vercel/og assets\n const indexPath = path.join(outDir, \"index.js\");\n if (!fs.existsSync(indexPath)) return;\n\n const content = fs.readFileSync(indexPath, \"utf-8\");\n // The font is inlined as base64 by vinext:og-inline-fetch-assets, so only\n // the WASM needs to be present as a file alongside the bundle.\n const ogAssets = [\"resvg.wasm\"];\n\n // Only copy if the bundle actually references these files\n const referencedAssets = ogAssets.filter((asset) => content.includes(asset));\n if (referencedAssets.length === 0) return;\n\n // Find @vercel/og in node_modules\n try {\n const require = createRequire(import.meta.url);\n const ogPkgPath = require.resolve(\"@vercel/og/package.json\");\n const ogDistDir = path.join(path.dirname(ogPkgPath), \"dist\");\n\n for (const asset of referencedAssets) {\n const src = path.join(ogDistDir, asset);\n const dest = path.join(outDir, asset);\n if (fs.existsSync(src) && !fs.existsSync(dest)) {\n fs.copyFileSync(src, dest);\n }\n }\n } catch {\n // @vercel/og not installed — nothing to copy\n }\n },\n },\n },\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 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 // 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 // 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 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 patch for workerd (cloudflare-dev + cloudflare-workers)\n //\n // @vercel/og/dist/index.edge.js has one remaining workerd issue after the\n // generic vinext:og-inline-fetch-assets plugin runs (which already handles\n // the font fetch pattern):\n //\n // YOGA WASM: yoga-layout embeds its WASM as a base64 data URL and instantiates\n // it via WebAssembly.instantiate(bytes) at runtime.\n // workerd forbids dynamic WASM compilation from bytes — WASM must be loaded\n // through the module system as a pre-compiled WebAssembly.Module.\n // Fix: extract the yoga WASM bytes at Vite transform time (Node.js), write\n // yoga.wasm to @vercel/og/dist/, import it via `?module` so @cloudflare/vite-plugin\n // can serve it through the module system, and inject h2.instantiateWasm to\n // use the pre-compiled module instead of bytes.\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 // ── Extract yoga WASM and import via ?module ──────────────────────────────────\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 // that we inject to use a pre-compiled WebAssembly.Module loaded via ?module.\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 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 using the ?module import\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 ` WebAssembly.instantiate(yoga_wasm_module, imports).then(function(inst) { callback(inst); });` +\n ` return {}; } })`;\n result = result.replace(YOGA_CALL, YOGA_CALL_PATCHED);\n // Prepend the yoga wasm ?module import so @cloudflare/vite-plugin handles it\n result = `import yoga_wasm_module from \"./yoga.wasm?module\";\\n` + result;\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 as any[]) {\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\" && 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: any[] = [];\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 const exportedName = spec.exported?.name ?? spec.exported?.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 .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 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 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.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 { clientManualChunks, clientOutputConfig, clientTreeshakeConfig, computeLazyChunks };\nexport { augmentSsrManifestFromBundle as _augmentSsrManifestFromBundle };\nexport { resolvePostcssStringPlugins as _resolvePostcssStringPlugins };\nexport { _postcssCache };\nexport { hasMdxFiles as _hasMdxFiles };\nexport { _mdxScanCache };\nexport { parseStaticObjectLiteral as _parseStaticObjectLiteral };\nexport { stripServerExports as _stripServerExports };\nexport { asyncHooksStubPlugin as _asyncHooksStubPlugin };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmEA,MAAM,YAAY,KAAK,QAAQ,cAAc,OAAO,KAAK,IAAI,CAAC;AAG9D,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;;;;;;;;;;AAWhD,eAAe,kBACb,QACA,QACA,UACiB;CAEjB,MAAM,EAAE,eAAe,MAAM,OAAO;CACpC,MAAM,UAAU,WAAW,MAAM,CAAC,OAAO,OAAO,CAAC,OAAO,MAAM,CAAC,MAAM,GAAG,GAAG;CAC3E,MAAM,UAAU,KAAK,KAAK,UAAU,GAAG,OAAO,aAAa,CAAC,QAAQ,QAAQ,IAAI,CAAC,GAAG,UAAU;CAG9F,MAAM,gBAAgB,KAAK,KAAK,SAAS,YAAY;AACrD,KAAI,G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O,MAAM;aAKrC,CAAC,IAAI,UAAU,GAAG,CACpB,KAAI,UAAU,OAAO,KAAK,OAAO,MAAM;;;;;;;AAU/C,SAAS,iBACP,KACA,MACA,SACe;AACf,MAAK,MAAM,OAAO,QAAQ,kBAAkB;EAC1C,MAAM,WAAW,KAAK,KAAK,KAAK,OAAO,IAAI;AAC3C,MAAI,GAAG,WAAW,SAAS,CAAE,QAAO;;AAEtC,QAAO;;;AAIT,MAAM,gCAAgB,IAAI,KAAsB;;;;AAKhD,SAAS,YAAY,MAAc,QAAuB,UAAkC;CAC1F,MAAM,WAAW,GAAG,KAAK,IAAI,UAAU,GAAG,IAAI,YAAY;AAC1D,KAAI,cAAc,IAAI,SAAS,CAAE,QAAO,cAAc,IAAI,SAAS;CACnE,MAAM,OAAO,CAAC,QAAQ,SAAS,CAAC,OAAO,QAAQ;AAC/C,MAAK,MAAM,OAAO,KAChB,KAAI,GAAG,WAAW,IAAI,IAAI,cAAc,IAAI,EAAE;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,SAAS,OAAO,CACtD,QAAO;;SAGL;AAGR,QAAO"}
1
+ {"version":3,"file":"index.js","names":["generateServerEntry","_generateServerEntry","generateClientEntry","_generateClientEntry"],"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 { 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 { findInstrumentationFile, runInstrumentation } from \"./server/instrumentation.js\";\nimport { PHASE_PRODUCTION_BUILD, PHASE_DEVELOPMENT_SERVER } from \"./shims/constants.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 { createOptimizeImportsPlugin } from \"./plugins/optimize-imports.js\";\nimport { hasWranglerConfig, formatMissingCloudflarePluginError } from \"./deploy.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 { fileURLToPath, 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\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\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\n/**\n * Fetch Google Fonts CSS, download .woff2 files, cache locally, and return\n * @font-face CSS with local file references.\n *\n * Cache dir structure: .vinext/fonts/<family-hash>/\n * - style.css (the rewritten @font-face CSS)\n * - *.woff2 (downloaded font files)\n */\nasync function fetchAndCacheFont(\n cssUrl: string,\n family: string,\n cacheDir: string,\n): Promise<string> {\n // Use a hash of the URL for the cache key\n const { createHash } = await import(\"node:crypto\");\n const urlHash = createHash(\"md5\").update(cssUrl).digest(\"hex\").slice(0, 12);\n const fontDir = path.join(cacheDir, `${family.toLowerCase().replace(/\\s+/g, \"-\")}-${urlHash}`);\n\n // Check if already cached\n const cachedCSSPath = path.join(fontDir, \"style.css\");\n if (fs.existsSync(cachedCSSPath)) {\n return fs.readFileSync(cachedCSSPath, \"utf-8\");\n }\n\n // Fetch CSS from Google Fonts (woff2 user-agent gives woff2 URLs)\n const cssResponse = await fetch(cssUrl, {\n headers: {\n \"User-Agent\":\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36\",\n },\n });\n if (!cssResponse.ok) {\n throw new Error(`Failed to fetch Google Fonts CSS: ${cssResponse.status}`);\n }\n let css = await cssResponse.text();\n\n // Extract all font file URLs\n const urlRe = /url\\((https:\\/\\/fonts\\.gstatic\\.com\\/[^)]+)\\)/g;\n const urls = new Map<string, string>(); // original URL -> local filename\n let urlMatch;\n while ((urlMatch = urlRe.exec(css)) !== null) {\n const fontUrl = urlMatch[1];\n if (!urls.has(fontUrl)) {\n const ext = fontUrl.includes(\".woff2\")\n ? \".woff2\"\n : fontUrl.includes(\".woff\")\n ? \".woff\"\n : \".ttf\";\n const fileHash = createHash(\"md5\").update(fontUrl).digest(\"hex\").slice(0, 8);\n urls.set(fontUrl, `${family.toLowerCase().replace(/\\s+/g, \"-\")}-${fileHash}${ext}`);\n }\n }\n\n // Download font files\n fs.mkdirSync(fontDir, { recursive: true });\n for (const [fontUrl, filename] of urls) {\n const filePath = path.join(fontDir, filename);\n if (!fs.existsSync(filePath)) {\n const fontResponse = await fetch(fontUrl);\n if (fontResponse.ok) {\n const buffer = Buffer.from(await fontResponse.arrayBuffer());\n fs.writeFileSync(filePath, buffer);\n }\n }\n // Rewrite CSS to use relative path (Vite will resolve /@fs/ for dev, or asset for build)\n css = css.split(fontUrl).join(filePath);\n }\n\n // Cache the rewritten CSS\n fs.writeFileSync(cachedCSSPath, css);\n return css;\n}\n\n/**\n * Safely parse a static JS object literal string into a plain object.\n * Uses Vite's parseAst (Rollup/acorn) so no code is ever evaluated.\n * Returns null if the expression contains anything dynamic (function calls,\n * template literals, identifiers, computed properties, etc.).\n *\n * Supports: string literals, numeric literals, boolean literals,\n * arrays of the above, and nested object literals.\n */\nfunction parseStaticObjectLiteral(objectStr: string): Record<string, unknown> | null {\n let ast: ReturnType<typeof parseAst>;\n try {\n // Wrap in parens so the parser treats `{…}` as an expression, not a block\n ast = parseAst(`(${objectStr})`);\n } catch {\n return null;\n }\n\n // The AST should be: Program > ExpressionStatement > ObjectExpression\n const body = ast.body;\n if (body.length !== 1 || body[0].type !== \"ExpressionStatement\") return null;\n\n const expr = body[0].expression;\n if (expr.type !== \"ObjectExpression\") return null;\n\n const result = extractStaticValue(expr);\n return result === undefined ? null : (result as Record<string, unknown>);\n}\n\n/**\n * Recursively extract a static value from an ESTree AST node.\n * Returns undefined (not null) if the node contains any dynamic expression.\n *\n * Uses `any` for the node parameter because Rollup's internal ESTree types\n * (estree.Expression, estree.ObjectExpression, etc.) aren't re-exported by Vite,\n * and the recursive traversal touches many different node shapes.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction extractStaticValue(node: any): unknown {\n switch (node.type) {\n case \"Literal\":\n // String, number, boolean, null\n return node.value;\n\n case \"UnaryExpression\":\n // Handle negative numbers: -1, -3.14\n if (\n node.operator === \"-\" &&\n node.argument?.type === \"Literal\" &&\n typeof node.argument.value === \"number\"\n ) {\n return -node.argument.value;\n }\n return undefined;\n\n case \"ArrayExpression\": {\n const arr: unknown[] = [];\n for (const elem of node.elements) {\n if (!elem) return undefined; // sparse array\n const val = extractStaticValue(elem);\n if (val === undefined) return undefined;\n arr.push(val);\n }\n return arr;\n }\n\n case \"ObjectExpression\": {\n const obj: Record<string, unknown> = {};\n for (const prop of node.properties) {\n if (prop.type !== \"Property\") return undefined; // SpreadElement etc.\n if (prop.computed) return undefined; // [expr]: val\n\n // Key can be Identifier (unquoted) or Literal (quoted)\n let key: string;\n if (prop.key.type === \"Identifier\") {\n key = prop.key.name;\n } else if (prop.key.type === \"Literal\" && typeof prop.key.value === \"string\") {\n key = prop.key.value;\n } else {\n return undefined;\n }\n\n const val = extractStaticValue(prop.value);\n if (val === undefined) return undefined;\n obj[key] = val;\n }\n return obj;\n }\n\n default:\n // TemplateLiteral, CallExpression, Identifier, etc. — reject\n return undefined;\n }\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) return \"/\";\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: any[] } | 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(projectRoot: string): Promise<{ plugins: any[] } | 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: any[] } | 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 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: any) => 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: any) => {\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;\nconst VIRTUAL_GOOGLE_FONTS = \"virtual:vinext-google-fonts\";\nconst RESOLVED_VIRTUAL_GOOGLE_FONTS = \"\\0\" + VIRTUAL_GOOGLE_FONTS;\n\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// IMPORTANT: keep this set in sync with the non-default exports from\n// packages/vinext/src/shims/font-google.ts (and its re-export barrel).\nconst GOOGLE_FONT_UTILITY_EXPORTS = new Set([\n \"buildGoogleFontsUrl\",\n \"getSSRFontLinks\",\n \"getSSRFontStyles\",\n \"getSSRFontPreloads\",\n \"createFontLoader\",\n]);\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\ntype GoogleFontNamedSpecifier = {\n imported: string;\n local: string;\n isType: boolean;\n raw: string;\n};\n\nfunction parseGoogleFontNamedSpecifiers(\n specifiersStr: string,\n forceType = false,\n): GoogleFontNamedSpecifier[] {\n return specifiersStr\n .split(\",\")\n .map((spec) => spec.trim())\n .filter(Boolean)\n .map((raw) => {\n const isType = forceType || raw.startsWith(\"type \");\n const valueSpec = isType ? raw.replace(/^type\\s+/, \"\") : raw;\n const asParts = valueSpec.split(/\\s+as\\s+/);\n const imported = asParts[0]?.trim() ?? \"\";\n const local = (asParts[1] || asParts[0] || \"\").trim();\n return { imported, local, isType, raw };\n })\n .filter((spec) => spec.imported.length > 0 && spec.local.length > 0);\n}\n\nfunction parseGoogleFontImportClause(clause: string): {\n defaultLocal: string | null;\n namespaceLocal: string | null;\n named: GoogleFontNamedSpecifier[];\n} {\n const trimmed = clause.trim();\n\n if (trimmed.startsWith(\"type \")) {\n const braceStart = trimmed.indexOf(\"{\");\n const braceEnd = trimmed.lastIndexOf(\"}\");\n if (braceStart === -1 || braceEnd === -1) {\n return { defaultLocal: null, namespaceLocal: null, named: [] };\n }\n return {\n defaultLocal: null,\n namespaceLocal: null,\n named: parseGoogleFontNamedSpecifiers(trimmed.slice(braceStart + 1, braceEnd), true),\n };\n }\n\n const braceStart = trimmed.indexOf(\"{\");\n const braceEnd = trimmed.lastIndexOf(\"}\");\n if (braceStart !== -1 && braceEnd !== -1) {\n const beforeNamed = trimmed.slice(0, braceStart).trim().replace(/,\\s*$/, \"\").trim();\n return {\n defaultLocal: beforeNamed || null,\n namespaceLocal: null,\n named: parseGoogleFontNamedSpecifiers(trimmed.slice(braceStart + 1, braceEnd)),\n };\n }\n\n const commaIndex = trimmed.indexOf(\",\");\n if (commaIndex !== -1) {\n const defaultLocal = trimmed.slice(0, commaIndex).trim() || null;\n const rest = trimmed.slice(commaIndex + 1).trim();\n if (rest.startsWith(\"* as \")) {\n return {\n defaultLocal,\n namespaceLocal: rest.slice(\"* as \".length).trim() || null,\n named: [],\n };\n }\n }\n\n if (trimmed.startsWith(\"* as \")) {\n return {\n defaultLocal: null,\n namespaceLocal: trimmed.slice(\"* as \".length).trim() || null,\n named: [],\n };\n }\n\n return {\n defaultLocal: trimmed || null,\n namespaceLocal: null,\n named: [],\n };\n}\n\nfunction encodeGoogleFontsVirtualId(payload: {\n hasDefault: boolean;\n fonts: string[];\n utilities: string[];\n}): string {\n const params = new URLSearchParams();\n if (payload.hasDefault) params.set(\"default\", \"1\");\n if (payload.fonts.length > 0) params.set(\"fonts\", payload.fonts.join(\",\"));\n if (payload.utilities.length > 0) params.set(\"utilities\", payload.utilities.join(\",\"));\n return `${VIRTUAL_GOOGLE_FONTS}?${params.toString()}`;\n}\n\nfunction parseGoogleFontsVirtualId(id: string): {\n hasDefault: boolean;\n fonts: string[];\n utilities: string[];\n} | null {\n const cleanId = id.startsWith(\"\\0\") ? id.slice(1) : id;\n if (!cleanId.startsWith(VIRTUAL_GOOGLE_FONTS)) return null;\n const queryIndex = cleanId.indexOf(\"?\");\n const params = new URLSearchParams(queryIndex === -1 ? \"\" : cleanId.slice(queryIndex + 1));\n return {\n hasDefault: params.get(\"default\") === \"1\",\n fonts:\n params\n .get(\"fonts\")\n ?.split(\",\")\n .map((value) => value.trim())\n .filter(Boolean) ?? [],\n utilities:\n params\n .get(\"utilities\")\n ?.split(\",\")\n .map((value) => value.trim())\n .filter(Boolean) ?? [],\n };\n}\n\nfunction generateGoogleFontsVirtualModule(id: string): string | null {\n const payload = parseGoogleFontsVirtualId(id);\n if (!payload) return null;\n\n const utilities = Array.from(new Set(payload.utilities));\n const fonts = Array.from(new Set(payload.fonts));\n const lines: string[] = [];\n\n lines.push(`import { createFontLoader } from ${JSON.stringify(_fontGoogleShimPath)};`);\n\n const reExports: string[] = [];\n if (payload.hasDefault) reExports.push(\"default\");\n reExports.push(...utilities);\n if (reExports.length > 0) {\n lines.push(`export { ${reExports.join(\", \")} } from ${JSON.stringify(_fontGoogleShimPath)};`);\n }\n\n for (const fontName of fonts) {\n const family = fontName.replace(/_/g, \" \");\n lines.push(\n `export const ${fontName} = /*#__PURE__*/ createFontLoader(${JSON.stringify(family)});`,\n );\n }\n\n lines.push(\"\");\n return lines.join(\"\\n\");\n}\n\nfunction propertyNameToGoogleFontFamily(prop: string): string {\n return prop.replace(/_/g, \" \").replace(/([a-z])([A-Z])/g, \"$1 $2\");\n}\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\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 BuildManifestChunk = {\n file: string;\n isEntry?: boolean;\n isDynamicEntry?: boolean;\n imports?: string[];\n dynamicImports?: string[];\n css?: string[];\n assets?: string[];\n};\n\n/**\n * Compute the set of chunk filenames that are ONLY reachable through dynamic\n * imports (i.e. behind React.lazy(), next/dynamic, or manual import()).\n *\n * These chunks should NOT be modulepreloaded in the HTML — they will be\n * fetched on demand when the dynamic import executes.\n *\n * Algorithm: Starting from all entry chunks in the build manifest, walk the\n * static `imports` tree (breadth-first). Any chunk file NOT reached by this\n * walk is only reachable through `dynamicImports` and is therefore \"lazy\".\n *\n * @param buildManifest - Vite's build manifest (manifest.json), which is a\n * Record<string, ManifestChunk> where each chunk has `file`, `imports`,\n * `dynamicImports`, `isEntry`, and `isDynamicEntry` fields.\n * @returns Array of chunk filenames (e.g. \"assets/mermaid-NOHMQCX5.js\") that\n * should be excluded from modulepreload hints.\n */\nfunction computeLazyChunks(buildManifest: Record<string, BuildManifestChunk>): string[] {\n // Collect all chunk files that are statically reachable from entries\n const eagerFiles = new Set<string>();\n const visited = new Set<string>();\n const queue: string[] = [];\n\n // Start BFS from all entry chunks\n for (const key of Object.keys(buildManifest)) {\n const chunk = buildManifest[key];\n if (chunk.isEntry) {\n queue.push(key);\n }\n }\n\n while (queue.length > 0) {\n const key = queue.shift()!;\n if (visited.has(key)) continue;\n visited.add(key);\n\n const chunk = buildManifest[key];\n if (!chunk) continue;\n\n // Mark this chunk's file as eager\n eagerFiles.add(chunk.file);\n\n // Also mark its CSS as eager (CSS should always be preloaded to avoid FOUC)\n if (chunk.css) {\n for (const cssFile of chunk.css) {\n eagerFiles.add(cssFile);\n }\n }\n\n // Follow only static imports — NOT dynamicImports\n if (chunk.imports) {\n for (const imp of chunk.imports) {\n if (!visited.has(imp)) {\n queue.push(imp);\n }\n }\n }\n }\n\n // Any JS file in the manifest that's NOT in eagerFiles is a lazy chunk\n const lazyChunks: string[] = [];\n const allFiles = new Set<string>();\n for (const key of Object.keys(buildManifest)) {\n const chunk = buildManifest[key];\n if (chunk.file && !allFiles.has(chunk.file)) {\n allFiles.add(chunk.file);\n if (!eagerFiles.has(chunk.file) && chunk.file.endsWith(\".js\")) {\n lazyChunks.push(chunk.file);\n }\n }\n }\n\n return lazyChunks;\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 interface 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 * 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\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 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 // Build-only cache for og-inline-fetch-assets to avoid repeated file reads\n // during a single production build. Dev mode skips the cache so asset edits\n // are picked up without restarting the Vite server.\n const _ogInlineCache = new Map<string, string>();\n let _ogInlineIsBuild = false;\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. Populated during config() if MDX\n // files are detected and @mdx-js/rollup is installed.\n let mdxDelegate: Plugin | null = null;\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 //\n // @vitejs/plugin-rsc uses `periscopic` to find closure variables for\n // 'use server' inline functions. Due to how periscopic handles block scopes,\n // `const X = ...` declared inside a 'use server' function body is tracked in\n // the BlockStatement scope (not the FunctionDeclaration scope). When periscopic\n // searches for the owner of a reference `X`, it finds the block scope — which\n // is neither the function scope nor the module scope — so it incorrectly\n // classifies `X` as a closure variable from the outer scope.\n //\n // The result: plugin-rsc injects `const [X] = await decryptActionBoundArgs(...)`\n // at the top of the hoisted function, colliding with the existing `const X = ...`\n // declaration in the body. This causes a SyntaxError.\n //\n // Fix: before plugin-rsc sees the file, detect any 'use server' function whose\n // local `const/let/var` declarations shadow an outer-scope variable, and rename\n // the inner declarations (+ usages within that function) to `__local_X`. This\n // eliminates the collision without changing semantics.\n //\n // This is a general fix that works for any library — not just @payloadcms/next.\n {\n name: \"vinext:fix-use-server-closure-collision\",\n enforce: \"pre\" as const,\n transform(code: string, id: string) {\n // Quick bail-out: only files that contain 'use server' inline\n if (!code.includes(\"use server\")) return null;\n // Only JS/TS files\n if (!/\\.(js|jsx|ts|tsx|mjs|cjs)$/.test(id.split(\"?\")[0])) return null;\n\n let ast: any;\n try {\n ast = parseAst(code);\n } catch {\n return null;\n }\n\n function collectPatternNames(pattern: any, names: Set<string>) {\n if (!pattern) return;\n if (pattern.type === \"Identifier\") {\n names.add(pattern.name);\n } else if (pattern.type === \"ObjectPattern\") {\n for (const prop of pattern.properties) {\n collectPatternNames(prop.value ?? prop.argument, names);\n }\n } else if (pattern.type === \"ArrayPattern\") {\n for (const elem of pattern.elements) {\n collectPatternNames(elem, names);\n }\n } else if (pattern.type === \"RestElement\" || pattern.type === \"AssignmentPattern\") {\n collectPatternNames(pattern.left ?? pattern.argument, names);\n }\n }\n\n // Check if a block body has 'use server' as its leading directive prologue.\n // Only the first contiguous run of string-literal expression statements\n // counts — a \"use server\" string mid-function is not a directive.\n function hasUseServerDirective(body: any[]): boolean {\n for (const stmt of body) {\n if (\n stmt.type === \"ExpressionStatement\" &&\n stmt.expression?.type === \"Literal\" &&\n typeof stmt.expression.value === \"string\"\n ) {\n if (stmt.expression.value === \"use server\") return true;\n // Any other string literal in the prologue — keep scanning\n continue;\n }\n // First non-string-literal statement ends the prologue\n break;\n }\n return false;\n }\n\n // Find all 'use server' inline functions and check for collisions.\n //\n // `ancestorNames` accumulates the names that are in scope in all ancestor\n // function/program bodies as we descend — this is the correct set to\n // compare against, not a whole-AST walk (which would pick up siblings).\n const s = new MagicString(code);\n // Track source ranges already rewritten so renamingWalk never calls\n // s.update() twice on the same span (MagicString throws if it does).\n const renamedRanges = new Set<string>();\n let changed = false;\n\n function visitNode(node: any, ancestorNames: Set<string>) {\n if (!node || typeof node !== \"object\") return;\n\n const isFn =\n node.type === \"FunctionDeclaration\" ||\n node.type === \"FunctionExpression\" ||\n node.type === \"ArrowFunctionExpression\";\n\n if (!isFn) {\n // Non-function nodes (Program, BlockStatement, IfStatement, CatchClause,\n // etc.) don't introduce a new function scope, but they may contain\n // variable declarations and catch bindings that are visible to nested\n // functions as ancestor names. Accumulate those into a new set before\n // recursing so we don't mutate the caller's set.\n const namesForChildren = new Set(ancestorNames);\n\n // CatchClause: `catch (e)` — `e` is in scope for the catch body\n if (node.type === \"CatchClause\" && node.param) {\n collectPatternNames(node.param, namesForChildren);\n }\n\n // Collect names visible at function scope from this node:\n // - FunctionDeclaration names (hoisted to enclosing scope)\n // - ClassDeclaration names (block-scoped like let, but treated as\n // function-scoped for our purposes since periscopic sees them)\n // - var declarations (hoisted to function scope, found anywhere)\n // We do NOT collect let/const from nested blocks here — those are\n // block-scoped and not visible to sibling/outer function declarations.\n collectFunctionScopedNames(node, namesForChildren);\n // Also collect let/const/var/class/import declared as immediate children\n // of this node (e.g. top-level Program statements, or the direct body of\n // a BlockStatement) — those ARE in scope for everything in the same block.\n const immediateStmts: any[] =\n node.type === \"Program\" ? node.body : node.type === \"BlockStatement\" ? node.body : [];\n for (const stmt of immediateStmts) {\n if (stmt?.type === \"VariableDeclaration\") {\n for (const decl of stmt.declarations)\n collectPatternNames(decl.id, namesForChildren);\n } else if (stmt?.type === \"ClassDeclaration\" && stmt.id?.name) {\n namesForChildren.add(stmt.id.name);\n } else if (stmt?.type === \"ImportDeclaration\") {\n for (const spec of stmt.specifiers ?? []) {\n // ImportDefaultSpecifier, ImportNamespaceSpecifier, ImportSpecifier\n // all have `local.name` as the binding name in this module.\n if (spec.local?.name) namesForChildren.add(spec.local.name);\n }\n }\n }\n\n for (const key of Object.keys(node)) {\n if (key === \"type\") continue;\n const child = node[key];\n if (Array.isArray(child)) {\n for (const c of child) visitNode(c, namesForChildren);\n } else if (child && typeof child === \"object\" && child.type) {\n visitNode(child, namesForChildren);\n }\n }\n return;\n }\n\n // Build the ancestor name set visible inside this function:\n // everything the parent saw, plus this function's own params.\n const namesForBody = new Set(ancestorNames);\n for (const p of node.params ?? []) collectPatternNames(p, namesForBody);\n\n // Check whether the body has the 'use server' directive.\n const bodyStmts: any[] = node.body?.type === \"BlockStatement\" ? node.body.body : [];\n const isServerFn = hasUseServerDirective(bodyStmts);\n\n if (isServerFn) {\n // Collect ALL variables declared anywhere in this function body.\n // This includes direct bodyStmts, but also for...of/for...in loop\n // variables, declarations inside if/try/while blocks, etc.\n // periscopic puts these in the BlockStatement scope (not the function\n // scope), so they get mis-classified as closure vars from the outer scope.\n // We use collectAllDeclaredNames (recursive, crosses blocks, stops at\n // nested function bodies) to catch every possible declaration site.\n const localDecls = new Set<string>();\n collectAllDeclaredNames(node.body, localDecls);\n\n // Find collisions: local decls that shadow a name from ancestor scopes.\n // collisionRenames maps original name → chosen rename target, taking\n // into account that `__local_${name}` may itself already be declared\n // (e.g. the user wrote `const __local_cookies = ...`). In that case\n // we try `__local_0_${name}`, `__local_1_${name}`, … until we find a\n // free name. This prevents a secondary collision.\n const collisionRenames = new Map<string, string>();\n for (const name of localDecls) {\n if (namesForBody.has(name)) {\n let to = `__local_${name}`;\n let suffix = 0;\n while (localDecls.has(to) || namesForBody.has(to)) {\n to = `__local_${suffix}_${name}`;\n suffix++;\n }\n collisionRenames.set(name, to);\n }\n }\n\n if (collisionRenames.size > 0) {\n for (const [name, to] of collisionRenames) {\n renamingWalk(node.body, name, to);\n }\n changed = true;\n }\n\n // Build the ancestor set for children of this server function.\n // Colliding names have been renamed in this body, e.g. `cookies` →\n // `__local_cookies`. The original name no longer exists as a binding\n // in this scope, so we must remove it from the set and add the renamed\n // version instead. Leaving the original name in would cause nested\n // server functions to see it as an ancestor binding and spuriously flag\n // their own independent `const cookies` as a collision.\n const namesForChildren = new Set(namesForBody);\n for (const name of localDecls) {\n if (collisionRenames.has(name)) {\n namesForChildren.delete(name);\n namesForChildren.add(collisionRenames.get(name)!);\n } else {\n namesForChildren.add(name);\n }\n }\n\n // Recurse into children — nested 'use server' functions must be visited.\n // Skip node.body itself (already handled by renamingWalk above for\n // collisions); we recurse into each statement individually so that\n // nested functions inside the body get their own visitNode pass with\n // the correct ancestorNames.\n for (const stmt of bodyStmts) {\n visitNode(stmt, namesForChildren);\n }\n // Also visit params (they can contain default expressions with closures)\n for (const p of node.params ?? []) visitNode(p, ancestorNames);\n return;\n }\n\n // Not a server function — build the ancestor set for nested functions:\n // - var declarations anywhere in this function body (function-scoped)\n // - FunctionDeclaration names anywhere in this function body\n // - let/const only from the top-level statements of this function body\n // (block-scoped — not visible to nested fns in sibling blocks)\n const namesForChildren = new Set(namesForBody);\n collectFunctionScopedNames(node.body, namesForChildren);\n for (const stmt of bodyStmts) {\n if (stmt?.type === \"VariableDeclaration\" && stmt.kind !== \"var\") {\n for (const decl of stmt.declarations) collectPatternNames(decl.id, namesForChildren);\n }\n }\n\n for (const key of Object.keys(node)) {\n if (key === \"type\") continue;\n const child = node[key];\n if (Array.isArray(child)) {\n for (const c of child) visitNode(c, namesForChildren);\n } else if (child && typeof child === \"object\" && child.type) {\n visitNode(child, namesForChildren);\n }\n }\n }\n\n // Walk an AST subtree renaming all variable-reference Identifier nodes\n // matching `from` to `to`.\n //\n // Correctness rules:\n // - Non-computed MemberExpression.property is NOT a variable reference\n // - Non-computed Property.key is NOT a variable reference\n // - Shorthand Property { x } must be expanded to { x: __local_x }\n // - A nested function that re-declares `from` in its params OR anywhere\n // in its body via var/const/let (including inside control flow) is a\n // new binding — stop descending into it\n // - Never call s.update() on the same source range twice\n //\n // `parent` is the direct parent AST node, used to detect property contexts.\n function renamingWalk(node: any, from: string, to: string, parent?: any) {\n if (!node || typeof node !== \"object\") return;\n\n if (node.type === \"Identifier\" && node.name === from) {\n // Non-computed member expression property: obj.cookies — not a ref\n if (\n parent?.type === \"MemberExpression\" &&\n parent.property === node &&\n !parent.computed\n ) {\n return;\n }\n\n // Non-computed property key in an object literal\n if (parent?.type === \"Property\" && parent.key === node && !parent.computed) {\n if (parent.shorthand) {\n // { cookies } — key and value are the same AST node.\n // Expand to { cookies: __local_cookies } by rewriting at the key\n // visit; skip the value visit via the guard below.\n const rangeKey = `${node.start}:${node.end}`;\n if (!renamedRanges.has(rangeKey)) {\n renamedRanges.add(rangeKey);\n s.update(node.start, node.end, `${from}: ${to}`);\n }\n }\n // Either way, key is not a variable reference — do not rename it.\n return;\n }\n\n // Value side of a shorthand property — same node as key, already handled\n if (parent?.type === \"Property\" && parent.shorthand && parent.value === node) {\n return;\n }\n\n // LabeledStatement label: `cookies: for (...)` — not a variable reference\n if (parent?.type === \"LabeledStatement\" && parent.label === node) {\n return;\n }\n\n // break/continue label: `break cookies` / `continue cookies` — not a variable reference\n if (\n (parent?.type === \"BreakStatement\" || parent?.type === \"ContinueStatement\") &&\n parent.label === node\n ) {\n return;\n }\n\n const rangeKey = `${node.start}:${node.end}`;\n if (!renamedRanges.has(rangeKey)) {\n renamedRanges.add(rangeKey);\n s.update(node.start, node.end, to);\n }\n return;\n }\n\n // For nested function nodes, check whether they re-declare `from`.\n // If they do, stop — the name in that nested scope is a different binding.\n // We must check ALL var declarations anywhere in the body (var hoists),\n // not just top-level statements.\n if (\n node.type === \"FunctionDeclaration\" ||\n node.type === \"FunctionExpression\" ||\n node.type === \"ArrowFunctionExpression\"\n ) {\n const nestedDecls = new Set<string>();\n // Params\n for (const p of node.params ?? []) collectPatternNames(p, nestedDecls);\n // Recursively find all var/const/let declarations in the body,\n // including those nested inside if/for/while/etc.\n collectAllDeclaredNames(node.body, nestedDecls);\n if (nestedDecls.has(from)) return;\n\n // Also stop at nested 'use server' functions — visitNode will handle them\n // independently with the correct collision set, preventing double-rewrites.\n if (node.body?.type === \"BlockStatement\" && hasUseServerDirective(node.body.body)) {\n return;\n }\n }\n\n for (const key of Object.keys(node)) {\n if (key === \"type\" || key === \"start\" || key === \"end\") continue;\n const child = node[key];\n if (Array.isArray(child)) {\n for (const c of child) renamingWalk(c, from, to, node);\n } else if (child && typeof child === \"object\" && child.type) {\n renamingWalk(child, from, to, node);\n }\n }\n }\n\n // Collect names that are visible at function scope from a given subtree.\n //\n // Two separate helpers with different traversal rules:\n //\n // collectFunctionScopedNames(node, names)\n // Collects `var` declarations and `FunctionDeclaration` names anywhere\n // in the subtree, crossing block boundaries (if/for/while/try/catch)\n // but NOT crossing nested function bodies. `let`/`const` in nested\n // blocks are intentionally skipped — they are block-scoped and not\n // visible outside that block.\n // Use this when building ancestorNames for nested functions.\n //\n // collectAllDeclaredNames(node, names)\n // Collects ALL var/let/const declarations anywhere in the subtree,\n // crossing block boundaries but not nested function bodies.\n // Used only by renamingWalk's re-declaration check, where we want to\n // know if ANY declaration of `from` exists in a nested function's scope\n // (params already handled separately).\n\n function collectFunctionScopedNames(node: any, names: Set<string>) {\n if (!node || typeof node !== \"object\") return;\n // FunctionDeclaration: its name is a binding in the enclosing scope.\n // Record it, then stop — don't recurse into the body (different scope).\n if (node.type === \"FunctionDeclaration\") {\n if (node.id?.name) names.add(node.id.name);\n return;\n }\n // ClassDeclaration: like FunctionDeclaration, its name is a binding in\n // the enclosing scope. Don't recurse into the body.\n if (node.type === \"ClassDeclaration\") {\n if (node.id?.name) names.add(node.id.name);\n return;\n }\n // FunctionExpression / ArrowFunctionExpression names are only in scope\n // inside their own body, not the enclosing scope — skip entirely.\n if (node.type === \"FunctionExpression\" || node.type === \"ArrowFunctionExpression\") {\n return;\n }\n // var declarations are function-scoped — collect them wherever they appear.\n // let/const at a nested block level are block-scoped and NOT visible to\n // sibling or outer function declarations, so skip them here.\n if (node.type === \"VariableDeclaration\" && node.kind === \"var\") {\n for (const decl of node.declarations) collectPatternNames(decl.id, names);\n }\n for (const key of Object.keys(node)) {\n if (key === \"type\") continue;\n const child = node[key];\n if (Array.isArray(child)) {\n for (const c of child) collectFunctionScopedNames(c, names);\n } else if (child && typeof child === \"object\" && child.type) {\n collectFunctionScopedNames(child, names);\n }\n }\n }\n\n // Collect ALL declared names (var/let/const/class/function) in a subtree,\n // crossing blocks but not nested function bodies or class bodies.\n // Used by renamingWalk's re-declaration check where any shadowing\n // declaration — regardless of kind — must stop the rename from descending\n // further, and by the server-function local-decl scan to detect all\n // possible collision sites (including class declarations in the body).\n function collectAllDeclaredNames(node: any, names: Set<string>) {\n if (!node || typeof node !== \"object\") return;\n if (node.type === \"VariableDeclaration\") {\n for (const decl of node.declarations) collectPatternNames(decl.id, names);\n }\n // FunctionDeclaration name is a binding in the enclosing scope — record it.\n if (node.type === \"FunctionDeclaration\") {\n if (node.id?.name) names.add(node.id.name);\n return; // don't recurse into its body\n }\n // ClassDeclaration name is a binding in the enclosing scope — record it.\n if (node.type === \"ClassDeclaration\") {\n if (node.id?.name) names.add(node.id.name);\n return; // don't recurse into the class body (separate scope)\n }\n if (node.type === \"FunctionExpression\" || node.type === \"ArrowFunctionExpression\") {\n return; // different scope — stop\n }\n for (const key of Object.keys(node)) {\n if (key === \"type\") continue;\n const child = node[key];\n if (Array.isArray(child)) {\n for (const c of child) collectAllDeclaredNames(c, names);\n } else if (child && typeof child === \"object\" && child.type) {\n collectAllDeclaredNames(child, names);\n }\n }\n }\n\n visitNode(ast, new Set());\n\n if (!changed) return null;\n return { code: s.toString(), map: s.generateMap({ hires: \"boundary\" }) };\n },\n },\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 const phase = 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 fileMatcher = createValidFileMatcher(nextConfig.pageExtensions);\n instrumentationPath = findInstrumentationFile(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/instrumentation\": path.resolve(__dirname, \"server\", \"instrumentation\"),\n \"vinext/html\": path.resolve(__dirname, \"server\", \"html\"),\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: any[] = [];\n function flattenPlugins(arr: any[]) {\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 any[]) ?? []);\n hasCloudflarePlugin = pluginsFlat.some(\n (p: any) =>\n p &&\n typeof p === \"object\" &&\n typeof p.name === \"string\" &&\n (p.name === \"vite-plugin-cloudflare\" || p.name.startsWith(\"vite-plugin-cloudflare:\")),\n );\n hasNitroPlugin = pluginsFlat.some(\n (p: any) =>\n p &&\n typeof p === \"object\" &&\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 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 const hasMdxPlugin = pluginsFlat.some(\n (p: any) =>\n p &&\n typeof p === \"object\" &&\n typeof p.name === \"string\" &&\n (p.name === \"@mdx-js/rollup\" || p.name === \"mdx\"),\n );\n if (\n !hasMdxPlugin &&\n hasMdxFiles(root, hasAppDir ? appDir : null, hasPagesDir ? pagesDir : null)\n ) {\n try {\n const mdxRollup = await import(\"@mdx-js/rollup\");\n const mdxFactory = mdxRollup.default ?? mdxRollup;\n const mdxOpts: Record<string, unknown> = {};\n if (nextConfig.mdx) {\n if (nextConfig.mdx.remarkPlugins)\n mdxOpts.remarkPlugins = nextConfig.mdx.remarkPlugins;\n if (nextConfig.mdx.rehypePlugins)\n mdxOpts.rehypePlugins = nextConfig.mdx.rehypePlugins;\n if (nextConfig.mdx.recmaPlugins) mdxOpts.recmaPlugins = nextConfig.mdx.recmaPlugins;\n }\n mdxDelegate = mdxFactory(mdxOpts);\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 } catch {\n // @mdx-js/rollup not installed — warn but don't fail\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 }\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 rollupOptions: {\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 = config.build?.rollupOptions?.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 ? { output: clientOutputConfig } : {}),\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\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\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: appEntries,\n },\n build: {\n outDir: options.rscOutDir ?? \"dist/server\",\n rollupOptions: {\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: appEntries,\n },\n build: {\n outDir: options.ssrOutDir ?? \"dist/server/ssr\",\n rollupOptions: {\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: appEntries,\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 rollupOptions: {\n input: { index: VIRTUAL_APP_BROWSER_ENTRY },\n output: clientOutputConfig,\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 build: {\n manifest: true,\n ssrManifest: true,\n rollupOptions: {\n input: { index: VIRTUAL_CLIENT_ENTRY },\n output: clientOutputConfig,\n treeshake: clientTreeshakeConfig,\n },\n },\n },\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: any) => p && typeof p.name === \"string\" && 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((p: any) => p && p.name === \"rsc\");\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);\n }\n },\n },\n // Stub node:async_hooks in client builds — see src/plugins/async-hooks-stub.ts\n asyncHooksStubPlugin,\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 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 if (!mdxDelegate?.transform) return;\n const hook = mdxDelegate.transform;\n const fn = typeof hook === \"function\" ? hook : hook.handler;\n return fn.call(this, code, id, options);\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: any[] }) {\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: any, res: any, next: any) => {\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 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 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:\n //\n // 1. Rewrites named next/font/google imports/exports to a tiny virtual module\n // that exports only the requested fonts plus any utility exports.\n // This lets us delete the generated ~1,900-line runtime catalog while\n // keeping ESM import semantics intact.\n // 2. During production builds, fetches Google Fonts CSS + font files and\n // injects _selfHostedCSS into statically analyzable font loader calls.\n {\n name: \"vinext:google-fonts\",\n enforce: \"pre\",\n\n _isBuild: false,\n _fontCache: new Map<string, string>(), // url -> local @font-face CSS\n _cacheDir: \"\",\n\n configResolved(config) {\n (this as any)._isBuild = config.command === \"build\";\n (this as any)._cacheDir = path.join(config.root, \".vinext\", \"fonts\");\n },\n\n transform: {\n // Hook filter: only invoke JS when code contains 'next/font/google'.\n // This still eliminates nearly all Rust-to-JS calls since very few files\n // import from next/font/google.\n filter: {\n id: {\n include: /\\.(tsx?|jsx?|mjs)$/,\n },\n code: \"next/font/google\",\n },\n async handler(code, id) {\n // Defensive guard — duplicates filter logic\n if (id.startsWith(\"\\0\")) return null;\n if (!id.match(/\\.(tsx?|jsx?|mjs)$/)) return null;\n if (!code.includes(\"next/font/google\")) return null;\n if (id.startsWith(_shimsDir)) return null;\n\n const s = new MagicString(code);\n let hasChanges = false;\n let proxyImportCounter = 0;\n const overwrittenRanges: Array<[number, number]> = [];\n const fontLocals = new Map<string, string>();\n const proxyObjectLocals = new Set<string>();\n\n const importRe = /^[ \\t]*import\\s+([^;]+?)\\s+from\\s*([\"'])next\\/font\\/google\\2\\s*;?/gm;\n let importMatch;\n while ((importMatch = importRe.exec(code)) !== null) {\n const [fullMatch, clause] = importMatch;\n const matchStart = importMatch.index;\n const matchEnd = matchStart + fullMatch.length;\n const parsed = parseGoogleFontImportClause(clause);\n const utilityImports = parsed.named.filter(\n (spec) => !spec.isType && GOOGLE_FONT_UTILITY_EXPORTS.has(spec.imported),\n );\n const fontImports = parsed.named.filter(\n (spec) => !spec.isType && !GOOGLE_FONT_UTILITY_EXPORTS.has(spec.imported),\n );\n\n if (parsed.defaultLocal) {\n proxyObjectLocals.add(parsed.defaultLocal);\n }\n for (const fontImport of fontImports) {\n fontLocals.set(fontImport.local, fontImport.imported);\n }\n\n if (fontImports.length > 0) {\n const virtualId = encodeGoogleFontsVirtualId({\n hasDefault: Boolean(parsed.defaultLocal),\n fonts: Array.from(new Set(fontImports.map((spec) => spec.imported))),\n utilities: Array.from(new Set(utilityImports.map((spec) => spec.imported))),\n });\n s.overwrite(\n matchStart,\n matchEnd,\n `import ${clause} from ${JSON.stringify(virtualId)};`,\n );\n overwrittenRanges.push([matchStart, matchEnd]);\n hasChanges = true;\n continue;\n }\n\n if (parsed.namespaceLocal) {\n const proxyImportName = `__vinext_google_fonts_proxy_${proxyImportCounter++}`;\n const replacementLines = [\n `import ${proxyImportName} from ${JSON.stringify(_fontGoogleShimPath)};`,\n ];\n if (parsed.defaultLocal) {\n replacementLines.push(`var ${parsed.defaultLocal} = ${proxyImportName};`);\n }\n replacementLines.push(`var ${parsed.namespaceLocal} = ${proxyImportName};`);\n s.overwrite(matchStart, matchEnd, replacementLines.join(\"\\n\"));\n overwrittenRanges.push([matchStart, matchEnd]);\n proxyObjectLocals.add(parsed.namespaceLocal);\n hasChanges = true;\n }\n }\n\n const exportRe = /^[ \\t]*export\\s*\\{([^}]+)\\}\\s*from\\s*([\"'])next\\/font\\/google\\2\\s*;?/gm;\n let exportMatch;\n while ((exportMatch = exportRe.exec(code)) !== null) {\n const [fullMatch, specifiers] = exportMatch;\n const matchStart = exportMatch.index;\n const matchEnd = matchStart + fullMatch.length;\n const namedExports = parseGoogleFontNamedSpecifiers(specifiers);\n const utilityExports = namedExports.filter(\n (spec) => !spec.isType && GOOGLE_FONT_UTILITY_EXPORTS.has(spec.imported),\n );\n const fontExports = namedExports.filter(\n (spec) => !spec.isType && !GOOGLE_FONT_UTILITY_EXPORTS.has(spec.imported),\n );\n if (fontExports.length === 0) continue;\n\n const virtualId = encodeGoogleFontsVirtualId({\n hasDefault: false,\n fonts: Array.from(new Set(fontExports.map((spec) => spec.imported))),\n utilities: Array.from(new Set(utilityExports.map((spec) => spec.imported))),\n });\n s.overwrite(\n matchStart,\n matchEnd,\n `export { ${specifiers.trim()} } from ${JSON.stringify(virtualId)};`,\n );\n overwrittenRanges.push([matchStart, matchEnd]);\n hasChanges = true;\n }\n\n const cacheDir = (this as any)._cacheDir as string;\n const fontCache = (this as any)._fontCache as Map<string, string>;\n\n async function injectSelfHostedCss(\n callStart: number,\n callEnd: number,\n optionsStr: string,\n family: string,\n calleeSource: string,\n ) {\n // Parse options safely via AST — no eval/new Function\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let options: Record<string, any> = {};\n try {\n const parsed = parseStaticObjectLiteral(optionsStr);\n if (!parsed) return; // Contains dynamic expressions, skip\n options = parsed as Record<string, any>;\n } catch {\n return; // Can't parse options statically, skip\n }\n\n // Build the Google Fonts CSS URL\n const weights = options.weight\n ? Array.isArray(options.weight)\n ? options.weight\n : [options.weight]\n : [];\n const styles = options.style\n ? Array.isArray(options.style)\n ? options.style\n : [options.style]\n : [];\n const display = options.display ?? \"swap\";\n\n let spec = family.replace(/\\s+/g, \"+\");\n if (weights.length > 0) {\n const hasItalic = styles.includes(\"italic\");\n if (hasItalic) {\n const pairs: string[] = [];\n for (const w of weights) {\n pairs.push(`0,${w}`);\n pairs.push(`1,${w}`);\n }\n spec += `:ital,wght@${pairs.join(\";\")}`;\n } else {\n spec += `:wght@${weights.join(\";\")}`;\n }\n } else if (styles.length === 0) {\n // Request full variable weight range when no weight specified.\n // Without this, Google Fonts returns only weight 400.\n spec += `:wght@100..900`;\n }\n const params = new URLSearchParams();\n params.set(\"family\", spec);\n params.set(\"display\", display);\n const cssUrl = `https://fonts.googleapis.com/css2?${params.toString()}`;\n\n // Check cache\n let localCSS = fontCache.get(cssUrl);\n if (!localCSS) {\n try {\n localCSS = await fetchAndCacheFont(cssUrl, family, cacheDir);\n fontCache.set(cssUrl, localCSS);\n } catch {\n // Fetch failed (offline?) — fall back to CDN mode\n return;\n }\n }\n\n // Inject _selfHostedCSS into the options object\n const escapedCSS = JSON.stringify(localCSS);\n const closingBrace = optionsStr.lastIndexOf(\"}\");\n const optionsWithCSS =\n optionsStr.slice(0, closingBrace) +\n (optionsStr.slice(0, closingBrace).trim().endsWith(\"{\") ? \"\" : \", \") +\n `_selfHostedCSS: ${escapedCSS}` +\n optionsStr.slice(closingBrace);\n\n const replacement = `${calleeSource}(${optionsWithCSS})`;\n s.overwrite(callStart, callEnd, replacement);\n hasChanges = true;\n }\n\n if ((this as any)._isBuild) {\n const namedCallRe = /\\b([A-Za-z_$][A-Za-z0-9_$]*)\\s*\\(\\s*(\\{[^}]*\\})\\s*\\)/g;\n let namedCallMatch;\n while ((namedCallMatch = namedCallRe.exec(code)) !== null) {\n const [fullMatch, localName, optionsStr] = namedCallMatch;\n const importedName = fontLocals.get(localName);\n if (!importedName) continue;\n\n const callStart = namedCallMatch.index;\n const callEnd = callStart + fullMatch.length;\n if (overwrittenRanges.some(([start, end]) => callStart < end && callEnd > start)) {\n continue;\n }\n\n await injectSelfHostedCss(\n callStart,\n callEnd,\n optionsStr,\n importedName.replace(/_/g, \" \"),\n localName,\n );\n }\n\n const memberCallRe =\n /\\b([A-Za-z_$][A-Za-z0-9_$]*)\\.([A-Za-z_$][A-Za-z0-9_$]*)\\s*\\(\\s*(\\{[^}]*\\})\\s*\\)/g;\n let memberCallMatch;\n while ((memberCallMatch = memberCallRe.exec(code)) !== null) {\n const [fullMatch, objectName, propName, optionsStr] = memberCallMatch;\n if (!proxyObjectLocals.has(objectName)) continue;\n\n const callStart = memberCallMatch.index;\n const callEnd = callStart + fullMatch.length;\n if (overwrittenRanges.some(([start, end]) => callStart < end && callEnd > start)) {\n continue;\n }\n\n await injectSelfHostedCss(\n callStart,\n callEnd,\n optionsStr,\n propertyNameToGoogleFontFamily(propName),\n `${objectName}.${propName}`,\n );\n }\n }\n\n if (!hasChanges) return null;\n return {\n code: s.toString(),\n map: s.generateMap({ hires: \"boundary\" }),\n };\n },\n },\n } as Plugin & { _isBuild: boolean; _fontCache: Map<string, string>; _cacheDir: string },\n // Local font path resolution:\n // When a source file calls localFont({ src: \"./font.woff2\" }) or\n // localFont({ src: [{ path: \"./font.woff2\" }] }), the relative paths\n // won't resolve in the browser because the CSS is injected at runtime.\n // This plugin rewrites those path strings into Vite asset import\n // references so that both dev (/@fs/...) and prod (/assets/font-xxx.woff2)\n // URLs are correct.\n {\n name: \"vinext:local-fonts\",\n enforce: \"pre\",\n\n transform: {\n filter: {\n id: {\n include: /\\.(tsx?|jsx?|mjs)$/,\n exclude: /node_modules/,\n },\n code: \"next/font/local\",\n },\n handler(code, id) {\n // Defensive guards — duplicate 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(\"next/font/local\")) return null;\n // Skip vinext's own font-local shim — it contains example paths\n // in comments that would be incorrectly rewritten.\n if (id.includes(\"font-local\")) return null;\n\n // Verify there's actually an import from next/font/local\n const importRe = /import\\s+\\w+\\s+from\\s*['\"]next\\/font\\/local['\"]/;\n if (!importRe.test(code)) return null;\n\n const s = new MagicString(code);\n let hasChanges = false;\n let fontImportCounter = 0;\n const imports: string[] = [];\n\n // Match font file paths in `path: \"...\"` or `src: \"...\"` properties.\n // Captures: (1) property+colon prefix, (2) quote char, (3) the path.\n const fontPathRe = /((?:path|src)\\s*:\\s*)(['\"])([^'\"]+\\.(?:woff2?|ttf|otf|eot))\\2/g;\n\n let match;\n while ((match = fontPathRe.exec(code)) !== null) {\n const [fullMatch, prefix, _quote, fontPath] = match;\n const varName = `__vinext_local_font_${fontImportCounter++}`;\n\n // Add an import for this font file — Vite resolves it as a static\n // asset and returns the correct URL for both dev and prod.\n imports.push(`import ${varName} from ${JSON.stringify(fontPath)};`);\n\n // Replace: path: \"./font.woff2\" -> path: __vinext_local_font_0\n const matchStart = match.index;\n const matchEnd = matchStart + fullMatch.length;\n s.overwrite(matchStart, matchEnd, `${prefix}${varName}`);\n hasChanges = true;\n }\n\n if (!hasChanges) return null;\n\n // Prepend the asset imports at the top of the file\n s.prepend(imports.join(\"\\n\") + \"\\n\");\n\n return {\n code: s.toString(),\n map: s.generateMap({ hires: \"boundary\" }),\n };\n },\n },\n } as Plugin,\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 as any[]).find(\n (node: any) =>\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: any): 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 = fn?.body?.type === \"BlockStatement\" ? fn.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: any[]): 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];\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 as any[]);\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 const directiveValue: string = cacheDirective.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 as any, {\n runtime: (value: any, name: any) =>\n `(await import(${JSON.stringify(runtimeModuleUrl)})).registerCachedFunction(${value}, ${JSON.stringify(id + \":\" + name)}, ${JSON.stringify(variant)})`,\n rejectNonAsyncFunction: false,\n filter: (name: any, meta: any) => {\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 as any, {\n directive: /^use cache(:\\s*\\w+)?$/,\n runtime: (value: any, name: any, meta: any) => {\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 //\n // Some bundled libraries (notably @vercel/og) load assets at module init time\n // with the pattern:\n //\n // fetch(new URL(\"./some-font.ttf\", import.meta.url)).then(res => res.arrayBuffer())\n //\n // This works in browser and standard Node.js because import.meta.url is a real\n // file:// URL. In Cloudflare Workers (both wrangler dev and production), however,\n // import.meta.url is the string \"worker\" — not a URL — so new URL(...) throws\n // \"TypeError: Invalid URL string\" and the Worker fails to start.\n //\n // Fix: at Vite transform time, find every such pattern, resolve the referenced\n // file relative to the module's actual path on disk (available as `id`), read it,\n // and replace the entire fetch(new URL(...)) expression with an inline base64 IIFE\n // that resolves synchronously. This eliminates the runtime fetch entirely and works\n // in all environments (workerd, Node.js, browser).\n //\n // Note: WASM files imported via `import ... from \"./foo.wasm?module\"` are handled\n // by the bundler/Vite directly and do not need this treatment. Only assets that\n // are runtime-fetched (not statically imported) need to be inlined here.\n {\n name: \"vinext:og-inline-fetch-assets\",\n enforce: \"pre\",\n configResolved(config) {\n _ogInlineIsBuild = config.command === \"build\";\n },\n buildStart() {\n if (_ogInlineIsBuild) {\n _ogInlineCache.clear();\n }\n },\n async transform(code, id) {\n // Quick bail-out: only process modules that use new URL(..., import.meta.url)\n if (!code.includes(\"import.meta.url\")) {\n return null;\n }\n\n const useCache = _ogInlineIsBuild;\n const moduleDir = path.dirname(id);\n let newCode = code;\n let didReplace = false;\n\n // Pattern 1 — edge build: fetch(new URL(\"./file\", import.meta.url)).then((res) => res.arrayBuffer())\n // Replace with an inline IIFE that decodes the asset as base64 and returns Promise<ArrayBuffer>.\n if (code.includes(\"fetch(\")) {\n const fetchPattern =\n /fetch\\(\\s*new URL\\(\\s*([\"'])(\\.\\/[^\"']+)\\1\\s*,\\s*import\\.meta\\.url\\s*\\)\\s*\\)(?:\\.then\\(\\s*(?:function\\s*\\([^)]*\\)|\\([^)]*\\)\\s*=>)\\s*\\{?\\s*return\\s+[^.]+\\.arrayBuffer\\(\\)\\s*\\}?\\s*\\)|\\.then\\(\\s*\\([^)]*\\)\\s*=>\\s*[^.]+\\.arrayBuffer\\(\\)\\s*\\))/g;\n\n for (const match of code.matchAll(fetchPattern)) {\n const fullMatch = match[0];\n const relPath = match[2]; // e.g. \"./noto-sans-v27-latin-regular.ttf\"\n const absPath = path.resolve(moduleDir, relPath);\n\n let fileBase64 = useCache ? _ogInlineCache.get(absPath) : undefined;\n if (fileBase64 === undefined) {\n try {\n const buf = await fs.promises.readFile(absPath);\n fileBase64 = buf.toString(\"base64\");\n if (useCache) {\n _ogInlineCache.set(absPath, fileBase64);\n }\n } catch {\n // File not found on disk — skip (may be a runtime-only asset)\n continue;\n }\n }\n\n // Replace fetch(...).then(...) with an inline IIFE that returns Promise<ArrayBuffer>.\n const inlined = [\n `(function(){`,\n `var b=${JSON.stringify(fileBase64)};`,\n `var r=atob(b);`,\n `var a=new Uint8Array(r.length);`,\n `for(var i=0;i<r.length;i++)a[i]=r.charCodeAt(i);`,\n `return Promise.resolve(a.buffer);`,\n `})()`,\n ].join(\"\");\n\n newCode = newCode.replaceAll(fullMatch, inlined);\n didReplace = true;\n }\n }\n\n // Pattern 2 — node build: readFileSync(fileURLToPath(new URL(\"./file\", import.meta.url)))\n // Replace with Buffer.from(\"<base64>\", \"base64\"), which returns a Buffer (compatible with\n // both font data passed to satori and WASM bytes passed to initWasm).\n if (code.includes(\"readFileSync(\")) {\n const readFilePattern =\n /[a-zA-Z_$][a-zA-Z0-9_$]*\\.readFileSync\\(\\s*(?:[a-zA-Z_$][a-zA-Z0-9_$]*\\.)?fileURLToPath\\(\\s*new URL\\(\\s*([\"'])(\\.\\/[^\"']+)\\1\\s*,\\s*import\\.meta\\.url\\s*\\)\\s*\\)\\s*\\)/g;\n\n for (const match of newCode.matchAll(readFilePattern)) {\n const fullMatch = match[0];\n const relPath = match[2]; // e.g. \"./noto-sans-v27-latin-regular.ttf\"\n const absPath = path.resolve(moduleDir, relPath);\n\n let fileBase64 = useCache ? _ogInlineCache.get(absPath) : undefined;\n if (fileBase64 === undefined) {\n try {\n const buf = await fs.promises.readFile(absPath);\n fileBase64 = buf.toString(\"base64\");\n if (useCache) {\n _ogInlineCache.set(absPath, fileBase64);\n }\n } catch {\n // File not found on disk — skip\n continue;\n }\n }\n\n // Replace readFileSync(...) with Buffer.from(\"<base64>\", \"base64\").\n // Buffer is always available in Node.js and in the vinext SSR/RSC environments.\n const inlined = `Buffer.from(${JSON.stringify(fileBase64)},\"base64\")`;\n\n newCode = newCode.replaceAll(fullMatch, inlined);\n didReplace = true;\n }\n }\n\n if (!didReplace) return null;\n return { code: newCode, map: null };\n },\n },\n // Copy @vercel/og binary assets to the RSC output directory for production builds.\n //\n // The edge build (dist/index.edge.js) uses:\n // - fetch(new URL(\"./noto-sans...\", import.meta.url)) → inlined by og-inline-fetch-assets\n // - resvg.wasm via dynamic import (og-font-patch rewrites the static import)\n //\n // The node build (dist/index.node.js) uses:\n // - fs.readFileSync(fileURLToPath(new URL(\"./noto-sans...\", import.meta.url))) → inlined\n // - fs.readFileSync(fileURLToPath(new URL(\"./resvg.wasm\", import.meta.url))) → inlined\n //\n // The og-font-patch plugin's resvg fallback uses new URL(\"./resvg.wasm\", import.meta.url)\n // which the bundler should emit as an asset. This plugin is kept as a safety net to ensure\n // the resvg.wasm file exists in the output directory for the Node.js disk-read fallback.\n {\n name: \"vinext:og-assets\",\n apply: \"build\",\n enforce: \"post\",\n writeBundle: {\n sequential: true,\n order: \"post\",\n async 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 // Check if the bundle references @vercel/og assets\n const indexPath = path.join(outDir, \"index.js\");\n if (!fs.existsSync(indexPath)) return;\n\n const content = fs.readFileSync(indexPath, \"utf-8\");\n // The font is inlined as base64 by vinext:og-inline-fetch-assets, so only\n // the WASM needs to be present as a file alongside the bundle.\n const ogAssets = [\"resvg.wasm\"];\n\n // Only copy if the bundle actually references these files\n const referencedAssets = ogAssets.filter((asset) => content.includes(asset));\n if (referencedAssets.length === 0) return;\n\n // Find @vercel/og in node_modules\n try {\n const require = createRequire(import.meta.url);\n const ogPkgPath = require.resolve(\"@vercel/og/package.json\");\n const ogDistDir = path.join(path.dirname(ogPkgPath), \"dist\");\n\n for (const asset of referencedAssets) {\n const src = path.join(ogDistDir, asset);\n const dest = path.join(outDir, asset);\n if (fs.existsSync(src) && !fs.existsSync(dest)) {\n fs.copyFileSync(src, dest);\n }\n }\n } catch {\n // @vercel/og not installed — nothing to copy\n }\n },\n },\n },\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 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 // 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 // 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 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 as any[]) {\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\" && 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: any[] = [];\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 const exportedName = spec.exported?.name ?? spec.exported?.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 .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 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 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.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 { clientManualChunks, clientOutputConfig, clientTreeshakeConfig, computeLazyChunks };\nexport { augmentSsrManifestFromBundle as _augmentSsrManifestFromBundle };\nexport { resolvePostcssStringPlugins as _resolvePostcssStringPlugins };\nexport { _postcssCache };\nexport { hasMdxFiles as _hasMdxFiles };\nexport { _mdxScanCache };\nexport { parseStaticObjectLiteral as _parseStaticObjectLiteral };\nexport { stripServerExports as _stripServerExports };\nexport { asyncHooksStubPlugin as _asyncHooksStubPlugin };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuEA,MAAM,YAAY,KAAK,QAAQ,cAAc,OAAO,KAAK,IAAI,CAAC;AAG9D,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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