@agent-native/core 0.49.10 → 0.49.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/skills.d.ts +5 -5
- package/dist/cli/skills.d.ts.map +1 -1
- package/dist/cli/skills.js +195 -15
- package/dist/cli/skills.js.map +1 -1
- package/dist/deploy/build.d.ts.map +1 -1
- package/dist/deploy/build.js +10 -2
- package/dist/deploy/build.js.map +1 -1
- package/dist/extensions/actions.js +1 -1
- package/dist/extensions/actions.js.map +1 -1
- package/dist/local-artifacts/index.d.ts +101 -0
- package/dist/local-artifacts/index.d.ts.map +1 -0
- package/dist/local-artifacts/index.js +507 -0
- package/dist/local-artifacts/index.js.map +1 -0
- package/dist/secrets/substitution.js +2 -2
- package/dist/secrets/substitution.js.map +1 -1
- package/dist/server/auth-marketing.d.ts +1 -0
- package/dist/server/auth-marketing.d.ts.map +1 -1
- package/dist/server/auth-marketing.js +5 -0
- package/dist/server/auth-marketing.js.map +1 -1
- package/dist/server/auth.d.ts.map +1 -1
- package/dist/server/auth.js +2 -2
- package/dist/server/auth.js.map +1 -1
- package/dist/server/entry-server.d.ts +27 -4
- package/dist/server/entry-server.d.ts.map +1 -1
- package/dist/server/entry-server.js +63 -43
- package/dist/server/entry-server.js.map +1 -1
- package/dist/server/onboarding-html.d.ts.map +1 -1
- package/dist/server/onboarding-html.js +3 -3
- package/dist/server/onboarding-html.js.map +1 -1
- package/dist/server/social-og-image.d.ts +2 -0
- package/dist/server/social-og-image.d.ts.map +1 -1
- package/dist/server/social-og-image.js +20 -7
- package/dist/server/social-og-image.js.map +1 -1
- package/dist/server/ssr-handler.d.ts.map +1 -1
- package/dist/server/ssr-handler.js +2 -2
- package/dist/server/ssr-handler.js.map +1 -1
- package/dist/shared/index.d.ts +1 -1
- package/dist/shared/index.d.ts.map +1 -1
- package/dist/shared/index.js +1 -1
- package/dist/shared/index.js.map +1 -1
- package/dist/shared/social-meta.d.ts +2 -0
- package/dist/shared/social-meta.d.ts.map +1 -1
- package/dist/shared/social-meta.js +5 -0
- package/dist/shared/social-meta.js.map +1 -1
- package/dist/templates/default/.agents/skills/storing-data/SKILL.md +3 -1
- package/dist/templates/default/app/entry.server.tsx +8 -2
- package/dist/templates/starter-shell-sync.spec.ts +4 -3
- package/dist/templates/workspace-core/.agents/skills/extensions/SKILL.md +3 -2
- package/dist/templates/workspace-core/.agents/skills/storing-data/SKILL.md +3 -1
- package/docs/content/template-content.md +9 -0
- package/package.json +5 -1
- package/src/templates/default/.agents/skills/storing-data/SKILL.md +3 -1
- package/src/templates/default/app/entry.server.tsx +8 -2
- package/src/templates/starter-shell-sync.spec.ts +4 -3
- package/src/templates/workspace-core/.agents/skills/extensions/SKILL.md +3 -2
- package/src/templates/workspace-core/.agents/skills/storing-data/SKILL.md +3 -1
package/dist/deploy/build.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build.js","sourceRoot":"","sources":["../../src/deploy/build.ts"],"names":[],"mappings":";AAEA;;;;;;;;;;;;GAYG;AAEH,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAC7C,OAAO,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAC;AACvC,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AACpC,OAAO,EACL,iBAAiB,EACjB,eAAe,EACf,mBAAmB,EACnB,wBAAwB,EACxB,uBAAuB,GAGxB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACL,uBAAuB,GAExB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,gCAAgC,EAAE,MAAM,gCAAgC,CAAC;AAClF,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,EACL,6BAA6B,EAC7B,gCAAgC,EAChC,8BAA8B,EAC9B,8BAA8B,EAC9B,+BAA+B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\n/**\n * Post-build step for deploying agent-native apps to edge/serverless targets.\n *\n * When NITRO_PRESET is set, this script:\n * 1. Takes the React Router build output (build/client/ + build/server/)\n * 2. Generates a platform-specific server entry point\n * 3. Bundles everything with esbuild into the target format\n *\n * Supported presets:\n * - cloudflare_pages: Outputs dist/ with _worker.js for Cloudflare Pages\n *\n * Usage: node deploy/build.js (called automatically by `agent-native build`)\n */\n\nimport path from \"path\";\nimport fs from \"fs\";\nimport { execFileSync } from \"child_process\";\nimport { createRequire } from \"module\";\nimport { fileURLToPath } from \"url\";\nimport {\n discoverApiRoutes,\n discoverPlugins,\n discoverActionFiles,\n getMissingDefaultPlugins,\n DEFAULT_PLUGIN_REGISTRY,\n type DiscoveredRoute,\n type DiscoveredAction,\n} from \"./route-discovery.js\";\nimport {\n getWorkspaceCoreExports,\n type WorkspaceCoreExports,\n} from \"./workspace-core.js\";\nimport { generateActionRegistryForProject } from \"../vite/action-types-plugin.js\";\nimport { mcpEmbedStaticAssetRouteRules } from \"../shared/mcp-embed-headers.js\";\nimport {\n AGENT_NATIVE_SOCIAL_IMAGE_ALT,\n AGENT_NATIVE_SOCIAL_IMAGE_HEIGHT,\n AGENT_NATIVE_SOCIAL_IMAGE_PATH,\n AGENT_NATIVE_SOCIAL_IMAGE_TYPE,\n AGENT_NATIVE_SOCIAL_IMAGE_WIDTH,\n} from \"../shared/social-meta.js\";\nimport {\n DEFAULT_SSR_CDN_CACHE_CONTROL,\n DEFAULT_SSR_NETLIFY_CDN_CACHE_CONTROL,\n DEFAULT_SPECULATION_RULES_PATH,\n DEFAULT_SSR_CACHE_CONTROL,\n} from \"../shared/cache-control.js\";\nimport {\n collectImmutableAssetPaths,\n IMMUTABLE_ASSET_CACHE_CONTROL,\n IMMUTABLE_ASSET_CACHE_HEADERS,\n prefixAssetPath,\n} from \"./immutable-assets.js\";\nimport { normalizeAppBasePath } from \"../server/app-base-path.js\";\n\nconst cwd = process.cwd();\nconst preset = process.env.NITRO_PRESET || \"node\";\nexport const NITRO_RUNTIME_IGNORE_PATTERNS = [\n \"**/*.spec.ts\",\n \"**/*.spec.tsx\",\n \"**/*.spec.mts\",\n \"**/*.spec.cts\",\n \"**/*.spec.js\",\n \"**/*.spec.jsx\",\n \"**/*.spec.mjs\",\n \"**/*.spec.cjs\",\n \"**/*.test.ts\",\n \"**/*.test.tsx\",\n \"**/*.test.mts\",\n \"**/*.test.cts\",\n \"**/*.test.js\",\n \"**/*.test.jsx\",\n \"**/*.test.mjs\",\n \"**/*.test.cjs\",\n];\n\nfunction normalizeConfiguredAppBasePath(): string {\n return normalizeAppBasePath(\n process.env.VITE_APP_BASE_PATH || process.env.APP_BASE_PATH,\n );\n}\n\n/** Plugins that require Node.js runtime and cannot run on edge/serverless */\nconst NODE_ONLY_PLUGINS = new Set([\n \"terminal\", // PTY requires child_process\n // @sentry/node ships node:fs / node:async_hooks bindings that don't load\n // on workerd / Cloudflare Workers. Templates running on edge presets can\n // mount their own edge-compatible Sentry wrapper if they want server\n // observability there; the framework default is the Node SDK.\n \"sentry\",\n]);\n\nfunction isNodeOnlyPlugin(filePath: string): boolean {\n const basename = path.basename(filePath, path.extname(filePath));\n return NODE_ONLY_PLUGINS.has(basename);\n}\n\nexport function generateProvidedPluginsNitroPluginSource(\n pluginStems: string[],\n): string {\n const stems = [...new Set(pluginStems.filter(Boolean))].sort();\n return `// AUTO-GENERATED by @agent-native/core deploy build\nimport { markDefaultPluginProvided } from \"@agent-native/core/server\";\n\nconst pluginStems = ${JSON.stringify(stems)};\n\nexport default function markBuildDiscoveredPlugins(nitroApp) {\n for (const stem of pluginStems) {\n markDefaultPluginProvided(nitroApp, stem);\n }\n}\n`;\n}\n\nasync function writeProvidedPluginsNitroPlugin(): Promise<string | null> {\n const plugins = await discoverPlugins(cwd);\n const stems = plugins.map((plugin) =>\n path.basename(plugin, path.extname(plugin)),\n );\n if (stems.length === 0) return null;\n\n const tmpDir = path.join(cwd, \".deploy-tmp\");\n fs.mkdirSync(tmpDir, { recursive: true });\n const pluginPath = path.join(tmpDir, \"agent-native-provided-plugins.mjs\");\n fs.writeFileSync(pluginPath, generateProvidedPluginsNitroPluginSource(stems));\n return pluginPath;\n}\n\ntype RouteRules = Record<string, { headers?: Record<string, string> }>;\n\nfunction addImmutableAssetRouteRule(\n routeRules: RouteRules,\n pathname: string,\n): void {\n const existing = routeRules[pathname] ?? {};\n routeRules[pathname] = {\n ...existing,\n headers: {\n ...(existing.headers ?? {}),\n ...IMMUTABLE_ASSET_CACHE_HEADERS,\n },\n };\n}\n\nexport function addImmutableAssetRouteRulesForClientBuild(\n routeRules: RouteRules,\n clientDir: string,\n appBasePath = \"\",\n): void {\n for (const assetPath of collectImmutableAssetPaths(clientDir)) {\n addImmutableAssetRouteRule(routeRules, assetPath);\n const mountedPath = prefixAssetPath(assetPath, appBasePath);\n if (mountedPath !== assetPath) {\n addImmutableAssetRouteRule(routeRules, mountedPath);\n }\n }\n}\n\n/**\n * Generate the worker entry source code that wires up H3 + React Router SSR.\n *\n * If a workspace core is present (monorepo with `agent-native.workspaceCore`\n * configured and the named package resolves), any plugin slot that the\n * workspace core exports is imported from there instead of from\n * `@agent-native/core/server`. This is the middle layer of the three-layer\n * inheritance model: app local > workspace core > framework default.\n */\nexport function generateWorkerEntry(\n routes: DiscoveredRoute[],\n pluginPaths: string[],\n defaultPluginStems: string[] = [],\n actions: DiscoveredAction[] = [],\n workspaceCore: WorkspaceCoreExports | null = null,\n immutableAssetPaths: string[] = [],\n builtAppBasePath = normalizeConfiguredAppBasePath(),\n): string {\n const routeImports: string[] = [];\n const routeRegistrations: string[] = [];\n\n for (let i = 0; i < routes.length; i++) {\n const r = routes[i];\n const varName = `route_${i}`;\n routeImports.push(`import ${varName} from ${JSON.stringify(r.absPath)};`);\n routeRegistrations.push(\n ` app.on(${JSON.stringify(r.method.toUpperCase())}, ${JSON.stringify(r.route)}, ${varName});`,\n );\n if (r.method.toLowerCase() === \"get\") {\n routeRegistrations.push(\n ` app.on(\"HEAD\", ${JSON.stringify(r.route)}, defineEventHandler(async (event) => {\n const originalReq = event.req;\n event.req = requestWithMethod(event.req, \"GET\");\n try {\n const result = await ${varName}(event);\n const response = result instanceof Response ? result : toResponse(result, event);\n return new Response(null, {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n } finally {\n event.req = originalReq;\n }\n }));`,\n );\n }\n }\n\n // Action route imports and registrations\n const actionImports: string[] = [];\n const actionRegistrations: string[] = [];\n for (let i = 0; i < actions.length; i++) {\n const a = actions[i];\n const varName = `action_${i}`;\n actionImports.push(`import ${varName} from ${JSON.stringify(a.absPath)};`);\n // Mirror the runtime mount (action-routes.ts): `path = http?.path ?? name`.\n const routePath = `/_agent-native/actions/${a.path ?? a.name}`;\n actionRegistrations.push(\n ` app.on(${JSON.stringify(a.method.toUpperCase())}, ${JSON.stringify(routePath)}, defineEventHandler(async (event) => {\n const params = ${a.method === \"get\" ? \"parseActionSearchParams(event.url.searchParams)\" : \"(await readBody(event)) ?? {}\"};\n try {\n const result = await ${varName}.run(params, { caller: \"http\" });\n if (typeof result === \"string\") { try { return JSON.parse(result); } catch { return result; } }\n return result;\n } catch (err) {\n return new Response(JSON.stringify({ error: err?.message || \"Action failed\" }), { status: err?.message?.startsWith(\"Invalid action parameters\") ? 400 : 500, headers: { \"Content-Type\": \"application/json\" } });\n }\n }));`,\n );\n }\n\n // Filter out Node-only plugins\n const edgePlugins = pluginPaths.filter((p) => !isNodeOnlyPlugin(p));\n const pluginImports: string[] = [];\n const pluginCalls: string[] = [];\n const providedPluginStems = new Set<string>();\n\n for (let i = 0; i < edgePlugins.length; i++) {\n const varName = `plugin_${i}`;\n providedPluginStems.add(\n path.basename(edgePlugins[i], path.extname(edgePlugins[i])),\n );\n pluginImports.push(\n `import ${varName} from ${JSON.stringify(edgePlugins[i])};`,\n );\n pluginCalls.push(` if (typeof ${varName} === \"function\") {\n await ${varName}(nitroApp);\n }`);\n }\n // Auto-mounted default plugins (for slots the template doesn't override\n // locally). For each slot, prefer a workspace-core export over the\n // @agent-native/core default, if the workspace core provides one.\n const edgeDefaultStems = defaultPluginStems.filter(\n (stem) => !NODE_ONLY_PLUGINS.has(stem),\n );\n for (let i = 0; i < edgeDefaultStems.length; i++) {\n const stem = edgeDefaultStems[i];\n providedPluginStems.add(stem);\n const varName = `defaultPlugin_${i}`;\n\n const workspaceExportName = workspaceCore?.plugins?.[stem as never];\n if (workspaceCore && workspaceExportName) {\n // Workspace-core layer wins over the framework default.\n pluginImports.push(\n `import { ${workspaceExportName} as ${varName} } from ${JSON.stringify(\n `${workspaceCore.packageName}/server`,\n )};`,\n );\n } else {\n // Fall back to the framework default from @agent-native/core.\n const defaultExportName = DEFAULT_PLUGIN_REGISTRY[stem];\n if (!defaultExportName) continue;\n pluginImports.push(\n `import { ${defaultExportName} as ${varName} } from \"@agent-native/core/server\";`,\n );\n }\n pluginCalls.push(` if (typeof ${varName} === \"function\") {\n await ${varName}(nitroApp);\n }`);\n }\n const generatedPluginMarks =\n providedPluginStems.size > 0\n ? [\n ...new Set([\n ...Object.keys(DEFAULT_PLUGIN_REGISTRY),\n ...providedPluginStems,\n ]),\n ]\n : [];\n if (generatedPluginMarks.length > 0) {\n pluginImports.unshift(\n `import { markDefaultPluginProvided as markGeneratedPluginProvided } from \"@agent-native/core/server\";`,\n );\n }\n\n return `\n// Auto-generated worker entry point for ${preset}\nimport { H3, defineEventHandler, readBody, toResponse } from \"h3\";\nimport { createRequestHandler } from \"react-router\";\nimport * as serverBuild from \"./server-build.js\";\n\nfunction normalizeAppBasePath(value) {\n if (!value || value === \"/\") return \"\";\n const trimmed = String(value).trim();\n if (!trimmed || trimmed === \"/\") return \"\";\n return \"/\" + trimmed.replace(/^\\\\/+/, \"\").replace(/\\\\/+$/, \"\");\n}\n\nfunction getAppBasePath() {\n const builtAppBasePath = ${JSON.stringify(builtAppBasePath)};\n return normalizeAppBasePath(\n globalThis.process?.env?.VITE_APP_BASE_PATH ||\n globalThis.process?.env?.APP_BASE_PATH ||\n builtAppBasePath,\n );\n}\n\nfunction stripAppBasePath(pathname) {\n const basePath = getAppBasePath();\n if (!basePath) return pathname;\n if (pathname === basePath) return \"/\";\n if (pathname.startsWith(basePath + \"/\")) {\n return pathname.slice(basePath.length) || \"/\";\n }\n return pathname;\n}\n\nfunction parseActionSearchParams(searchParams) {\n const params = {};\n for (const [rawKey, value] of searchParams.entries()) {\n const isArrayKey = rawKey.endsWith(\"[]\");\n // The core client serializes arrays as key[]=value so one-item arrays\n // survive GET action parsing in generated worker deployments.\n const key = isArrayKey ? rawKey.slice(0, -2) : rawKey;\n const current = params[key];\n if (current === undefined) {\n params[key] = isArrayKey ? [value] : value;\n } else if (Array.isArray(current)) {\n current.push(value);\n } else {\n params[key] = [current, value];\n }\n }\n return params;\n}\n\nfunction isApiPath(pathname) {\n return pathname === \"/api\" || pathname.startsWith(\"/api/\");\n}\n\nfunction isFrameworkPath(pathname) {\n return (\n pathname === \"/_agent-native\" || pathname.startsWith(\"/_agent-native/\")\n );\n}\n\nfunction requestWithMountedApiPrefixStripped(request) {\n const basePath = getAppBasePath();\n if (!basePath) return request;\n const url = new URL(request.url);\n const strippedPathname = stripAppBasePath(url.pathname);\n if (strippedPathname === url.pathname) {\n return request;\n }\n if (!isApiPath(strippedPathname) && !isFrameworkPath(strippedPathname)) {\n return request;\n }\n url.pathname = strippedPathname;\n return new Request(url, request);\n}\n\nfunction prefixMountedPath(path, basePath) {\n if (!basePath || !path.startsWith(\"/\") || path.startsWith(\"//\")) return path;\n if (path === basePath || path.startsWith(basePath + \"/\")) return path;\n return basePath + path;\n}\n\nfunction prefixMountedHtml(html, basePath) {\n if (!basePath) return html;\n return html\n .replace(\n /\\\\b(href|src|action|formaction|poster)=([\"'])(\\\\/(?!\\\\/)[^\"']*)\\\\2/g,\n (_match, attr, quote, path) =>\n attr + \"=\" + quote + prefixMountedPath(path, basePath) + quote,\n )\n .replace(/url\\\\(([\"']?)(\\\\/(?!\\\\/)[^)'\" ]+)\\\\1\\\\)/g, (_match, quote, path) => {\n const q = quote || \"\";\n return \"url(\" + q + prefixMountedPath(path, basePath) + q + \")\";\n });\n}\n\nfunction firstNonEmpty() {\n for (const value of arguments) {\n const trimmed = typeof value === \"string\" ? value.trim() : \"\";\n if (trimmed) return trimmed;\n }\n}\n\nfunction getSentryClientConfigScript() {\n const env = globalThis.process?.env || {};\n const key = firstNonEmpty(env.SENTRY_CLIENT_KEY, env.VITE_SENTRY_CLIENT_KEY);\n const projectId = firstNonEmpty(\n env.SENTRY_PROJECT_ID,\n env.VITE_SENTRY_PROJECT_ID,\n );\n const host = firstNonEmpty(\n env.SENTRY_INGEST_HOST,\n env.VITE_SENTRY_INGEST_HOST,\n );\n const dsn =\n firstNonEmpty(\n env.SENTRY_CLIENT_DSN,\n env.VITE_SENTRY_CLIENT_DSN,\n env.VITE_SENTRY_DSN,\n env.SENTRY_DSN,\n ) || (key && projectId && host ? \"https://\" + key + \"@\" + host + \"/\" + projectId : undefined);\n if (!dsn) return null;\n const config = {\n sentryDsn: dsn,\n sentryEnvironment:\n firstNonEmpty(\n env.SENTRY_ENVIRONMENT,\n env.NETLIFY_CONTEXT,\n env.VERCEL_ENV,\n env.NODE_ENV,\n ) || \"production\",\n };\n return (\n '<script data-agent-native-sentry-config>' +\n 'window.__AGENT_NATIVE_CONFIG__=Object.assign({},window.__AGENT_NATIVE_CONFIG__,' +\n JSON.stringify(config) +\n \");</script>\"\n );\n}\n\nfunction injectHeadScript(html, script) {\n if (!script) return html;\n const headCloseIdx = html.indexOf(\"</head>\");\n if (headCloseIdx === -1) return html;\n return html.slice(0, headCloseIdx) + script + html.slice(headCloseIdx);\n}\n\nconst DEFAULT_SSR_CACHE_CONTROL = ${JSON.stringify(DEFAULT_SSR_CACHE_CONTROL)};\nconst DEFAULT_SSR_CDN_CACHE_CONTROL = ${JSON.stringify(DEFAULT_SSR_CDN_CACHE_CONTROL)};\nconst DEFAULT_SSR_NETLIFY_CDN_CACHE_CONTROL = ${JSON.stringify(DEFAULT_SSR_NETLIFY_CDN_CACHE_CONTROL)};\nconst DEFAULT_SPECULATION_RULES_PATH = ${JSON.stringify(DEFAULT_SPECULATION_RULES_PATH)};\nconst IMMUTABLE_ASSET_CACHE_CONTROL = ${JSON.stringify(IMMUTABLE_ASSET_CACHE_CONTROL)};\nconst IMMUTABLE_ASSET_PATHS = new Set(${JSON.stringify(\n [...new Set(immutableAssetPaths)].sort(),\n )});\nconst AGENT_NATIVE_SOCIAL_IMAGE_PATH = ${JSON.stringify(\n AGENT_NATIVE_SOCIAL_IMAGE_PATH,\n )};\nconst AGENT_NATIVE_SOCIAL_IMAGE_ALT = ${JSON.stringify(\n AGENT_NATIVE_SOCIAL_IMAGE_ALT,\n )};\nconst AGENT_NATIVE_SOCIAL_IMAGE_TYPE = ${JSON.stringify(\n AGENT_NATIVE_SOCIAL_IMAGE_TYPE,\n )};\nconst AGENT_NATIVE_SOCIAL_IMAGE_WIDTH = ${JSON.stringify(\n AGENT_NATIVE_SOCIAL_IMAGE_WIDTH,\n )};\nconst AGENT_NATIVE_SOCIAL_IMAGE_HEIGHT = ${JSON.stringify(\n AGENT_NATIVE_SOCIAL_IMAGE_HEIGHT,\n )};\nconst OG_IMAGE_META_RE = /<meta\\\\b(?=[^>]*\\\\bproperty=([\"'])og:image\\\\1)[^>]*>/i;\nconst TWITTER_CARD_META_RE = /<meta\\\\b(?=[^>]*\\\\bname=([\"'])twitter:card\\\\1)[^>]*>/i;\nconst TWITTER_IMAGE_META_RE = /<meta\\\\b(?=[^>]*\\\\bname=([\"'])twitter:image\\\\1)[^>]*>/i;\n\nfunction defaultSocialImageUrl(request, basePath) {\n return new URL(prefixMountedPath(AGENT_NATIVE_SOCIAL_IMAGE_PATH, basePath), request.url).toString();\n}\n\nfunction injectDefaultSocialImageMeta(html, imageUrl) {\n const headCloseIdx = html.indexOf(\"</head>\");\n if (headCloseIdx === -1) return html;\n\n const hasAnySocialImage =\n OG_IMAGE_META_RE.test(html) || TWITTER_IMAGE_META_RE.test(html);\n const tags = [];\n\n if (!hasAnySocialImage) {\n tags.push('<meta property=\"og:image\" content=\"' + imageUrl + '\">');\n tags.push('<meta property=\"og:image:secure_url\" content=\"' + imageUrl + '\">');\n tags.push('<meta property=\"og:image:type\" content=\"' + AGENT_NATIVE_SOCIAL_IMAGE_TYPE + '\">');\n tags.push('<meta property=\"og:image:width\" content=\"' + AGENT_NATIVE_SOCIAL_IMAGE_WIDTH + '\">');\n tags.push('<meta property=\"og:image:height\" content=\"' + AGENT_NATIVE_SOCIAL_IMAGE_HEIGHT + '\">');\n tags.push('<meta property=\"og:image:alt\" content=\"' + AGENT_NATIVE_SOCIAL_IMAGE_ALT + '\">');\n }\n if (!TWITTER_CARD_META_RE.test(html)) {\n tags.push('<meta name=\"twitter:card\" content=\"summary_large_image\">');\n }\n if (!hasAnySocialImage) {\n tags.push('<meta name=\"twitter:image\" content=\"' + imageUrl + '\">');\n tags.push('<meta name=\"twitter:image:alt\" content=\"' + AGENT_NATIVE_SOCIAL_IMAGE_ALT + '\">');\n }\n\n if (tags.length === 0) return html;\n return html.slice(0, headCloseIdx) + tags.join(\"\") + html.slice(headCloseIdx);\n}\n\nfunction isSsrHtmlOrDataResponse(headers, status, pathname) {\n if (status < 200 || status >= 400) return false;\n const contentType = (headers.get(\"content-type\") || \"\").toLowerCase();\n if (contentType.includes(\"text/html\")) return true;\n return pathname.endsWith(\".data\") && contentType.includes(\"text/x-script\");\n}\n\n/**\n * Apply the SSR cache policy to the response headers.\n *\n * SSR IS A PUBLIC, HARD-CDN-CACHED SHELL — SERVED IDENTICALLY TO EVERYONE.\n * Every SSR HTML / React Router .data response gets the same public\n * stale-while-revalidate policy for ALL visitors, authenticated or not. The SSR\n * output is impersonal (the handler never reads the request's session/cookies),\n * so it is safe to hard-cache one shared copy at the edge. Do NOT reintroduce\n * per-user / cookie-based cache variation here (no private, no no-store, no\n * \"authenticated then don't cache\" branch) — that makes every logged-in\n * visitor's pages uncacheable. Per-user state is resolved client-side instead.\n */\nfunction applyDefaultSsrCacheHeader(headers, status, pathname) {\n if (!isSsrHtmlOrDataResponse(headers, status, pathname)) return;\n\n headers.set(\"cache-control\", DEFAULT_SSR_CACHE_CONTROL);\n headers.set(\"cdn-cache-control\", DEFAULT_SSR_CDN_CACHE_CONTROL);\n // Netlify function responses are dynamic by default and can otherwise show\n // Cache-Status fwd=bypass even with Cache-Control: public. Keep this\n // Netlify-specific header so SSR HTML/.data are served from the shared\n // durable CDN cache instead of stampeding origin — for every visitor.\n headers.set(\"netlify-cdn-cache-control\", DEFAULT_SSR_NETLIFY_CDN_CACHE_CONTROL);\n}\n\nfunction applyDefaultSpeculationRulesHeader(headers, status, basePath) {\n if (status < 200 || status >= 400) return;\n if (headers.has(\"speculation-rules\")) return;\n\n const contentType = (headers.get(\"content-type\") || \"\").toLowerCase();\n if (!contentType.includes(\"text/html\")) return;\n\n // Cloudflare Speed Brain injects Speculation-Rules when origin omits this\n // header. Those browser prefetches carry Sec-Purpose: prefetch and\n // Cloudflare can return 503 before the request reaches origin. Publish an\n // explicit no-op ruleset by default; apps can still provide their own header.\n headers.set(\"speculation-rules\", '\"' + prefixMountedPath(DEFAULT_SPECULATION_RULES_PATH, basePath) + '\"');\n}\nfunction isImmutableAssetRequest(request) {\n const pathname = stripAppBasePath(new URL(request.url).pathname);\n return IMMUTABLE_ASSET_PATHS.has(pathname);\n}\n\nfunction applyImmutableAssetCacheHeaders(response, request) {\n if (!isImmutableAssetRequest(request)) return response;\n if (!((response.status >= 200 && response.status < 300) || response.status === 304)) {\n return response;\n }\n const headers = new Headers(response.headers);\n headers.set(\"Cache-Control\", IMMUTABLE_ASSET_CACHE_CONTROL);\n headers.set(\"CDN-Cache-Control\", IMMUTABLE_ASSET_CACHE_CONTROL);\n headers.set(\"Netlify-CDN-Cache-Control\", IMMUTABLE_ASSET_CACHE_CONTROL);\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n}\n\nasync function rewriteMountedResponse(response, basePath, pathname, request) {\n const sentryClientConfigScript = getSentryClientConfigScript();\n const headers = new Headers(response.headers);\n applyDefaultSsrCacheHeader(headers, response.status, pathname);\n applyDefaultSpeculationRulesHeader(headers, response.status, basePath);\n\n const location = headers.get(\"location\");\n if (location?.startsWith(\"/\") && !location.startsWith(\"//\")) {\n headers.set(\"location\", prefixMountedPath(location, basePath));\n }\n\n const contentType = headers.get(\"content-type\") || \"\";\n if (!contentType.toLowerCase().includes(\"text/html\") || !response.body) {\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n }\n\n const html = await response.text();\n headers.delete(\"content-length\");\n return new Response(\n injectHeadScript(\n injectDefaultSocialImageMeta(\n prefixMountedHtml(html, basePath),\n defaultSocialImageUrl(request, basePath),\n ),\n sentryClientConfigScript,\n ),\n {\n status: response.status,\n statusText: response.statusText,\n headers,\n },\n );\n}\n\nfunction requestWithMethod(request, method) {\n return new Request(request.url, {\n method,\n headers: request.headers,\n signal: request.signal,\n });\n}\n\nfunction requestWithPathname(request, pathname) {\n const url = new URL(request.url);\n if (url.pathname === pathname) return request;\n url.pathname = pathname;\n return new Request(url, request);\n}\n\n// API route handlers\n${routeImports.join(\"\\n\")}\n\n// Action handlers (auto-discovered from actions/)\n${actionImports.join(\"\\n\")}\n\n// Server plugins\n${pluginImports.join(\"\\n\")}\n\nlet _handler;\n\nasync function getHandler() {\n if (_handler) return _handler;\n\n const app = new H3();\n\n // Build a fake nitroApp surface so framework plugins (which expect\n // \\`nitroApp.h3[\"~middleware\"]\\`) can register routes via getH3App().\n const noop = () => {};\n const nitroApp = {\n h3: app,\n hooks: { hook: noop, callHook: noop, hookOnce: noop },\n captureError: noop,\n };\n\n // CORS — applied as global middleware via .use(handler)\n app.use(defineEventHandler((event) => {\n if (event.req.method === \"OPTIONS\") {\n return new Response(null, {\n status: 204,\n headers: {\n \"Access-Control-Allow-Origin\": \"*\",\n \"Access-Control-Allow-Methods\": \"GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS\",\n \"Access-Control-Allow-Headers\": \"Content-Type,Authorization,X-Requested-With,X-Request-Source,X-Agent-Native-CSRF,X-Agent-Native-Embed-Target\",\n },\n });\n }\n }));\n\n // Run plugins — they call getH3App(nitroApp).use(path, handler) which\n // pushes path-prefix middleware onto app[\"~middleware\"].\n // Pre-mark every build-time plugin slot before any plugin awaits the runtime\n // default bootstrap. Bundled serverless workers often lack server/plugins/\n // on disk, so runtime discovery would otherwise auto-mount duplicate\n // framework defaults before later custom plugins get a chance to mark\n // themselves as provided.\n${generatedPluginMarks.map((stem) => ` markGeneratedPluginProvided(nitroApp, ${JSON.stringify(stem)});`).join(\"\\n\")}\n${pluginCalls.join(\"\\n\")}\n\n // Register API routes\n${routeRegistrations.join(\"\\n\")}\n\n // Register action routes (/_agent-native/actions/*)\n${actionRegistrations.join(\"\\n\")}\n\n // SSR catch-all for React Router\n const rrHandler = createRequestHandler(() => serverBuild);\n app.all(\"/**\", defineEventHandler(async (event) => {\n const basePath = getAppBasePath();\n const p = stripAppBasePath(new URL(event.req.url).pathname);\n if (\n p.startsWith(\"/.well-known/\") ||\n p.startsWith(\"/_agent-native/\") ||\n isApiPath(p) ||\n p === \"/favicon.ico\" ||\n p === \"/favicon.png\" ||\n (/\\\\.\\\\w+$/.test(p) && !p.endsWith(\".data\"))\n ) {\n return new Response(null, { status: 404 });\n }\n const request = requestWithPathname(event.req, p);\n if (event.req.method === \"HEAD\") {\n const getRequest = requestWithMethod(request, \"GET\");\n const response = await rrHandler(getRequest);\n return rewriteMountedResponse(\n new Response(null, {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n }),\n basePath,\n p,\n getRequest\n );\n }\n return rewriteMountedResponse(await rrHandler(request), basePath, p, request);\n }));\n\n _handler = app.fetch.bind(app);\n return _handler;\n}\n\nexport default {\n async fetch(request, env, ctx) {\n // Expose env and ctx bindings globally for compatibility\n if (ctx) globalThis.__cf_ctx = ctx;\n if (env) {\n globalThis.process = globalThis.process || { env: {} };\n globalThis.process.env = globalThis.process.env || {};\n // Expose D1/KV/R2 bindings on globalThis.__cf_env for the db layer\n globalThis.__cf_env = env;\n for (const [key, value] of Object.entries(env)) {\n if (typeof value === \"string\") {\n globalThis.process.env[key] = value;\n }\n }\n }\n\n // Try serving static assets first (CF Pages advanced mode).\n // Only attempt this for GET/HEAD — the ASSETS binding is a static file\n // server and returns 405 for any other method, which would short-circuit\n // API calls (PUT/POST/DELETE to /_agent-native/*) before they reach our\n // h3 middleware.\n if (env?.ASSETS && (request.method === \"GET\" || request.method === \"HEAD\")) {\n try {\n const assetResponse = await env.ASSETS.fetch(request);\n if (assetResponse.status !== 404) {\n return applyImmutableAssetCacheHeaders(assetResponse, request);\n }\n } catch {\n // Asset fetch failed — fall through to SSR\n }\n }\n\n const handler = await getHandler();\n return handler(requestWithMountedApiPrefixStripped(request));\n }\n};\n`;\n}\n\n/**\n * Build for Cloudflare Pages.\n * Output structure:\n * dist/\n * _worker.js (bundled worker entry)\n * assets/ (static client assets)\n */\nasync function buildCloudflarePages() {\n generateActionRegistryForProject(cwd);\n\n const buildDir = path.join(cwd, \"build\");\n const clientDir = path.join(buildDir, \"client\");\n const serverDir = path.join(buildDir, \"server\");\n const distDir = path.join(cwd, \"dist\");\n\n // Verify build output exists\n if (!fs.existsSync(clientDir) || !fs.existsSync(serverDir)) {\n console.error(\n \"Build output not found at build/client/ and build/server/. Run react-router build first.\",\n );\n process.exit(1);\n }\n\n // Clean dist\n if (fs.existsSync(distDir)) {\n fs.rmSync(distDir, { recursive: true });\n }\n fs.mkdirSync(distDir, { recursive: true });\n\n // Copy client assets to dist/\n copyDir(clientDir, distDir);\n\n // Exclude _worker.js from being served as a public asset\n fs.writeFileSync(path.join(distDir, \".assetsignore\"), \"_worker.js\\n\");\n\n // Write a package.json inside _worker.js/ to tell wrangler this is a\n // pre-bundled ES module worker — skip re-bundling our esbuild output.\n fs.mkdirSync(path.join(distDir, \"_worker.js\"), { recursive: true });\n fs.writeFileSync(\n path.join(distDir, \"_worker.js\", \"package.json\"),\n JSON.stringify({ main: \"index.js\", type: \"module\" }),\n );\n\n // Create empty stub for native modules that wrangler's bundler needs to resolve\n const stubsDir = path.join(distDir, \"_worker.js\", \"stubs\");\n fs.mkdirSync(stubsDir, { recursive: true });\n fs.writeFileSync(\n path.join(stubsDir, \"empty.js\"),\n \"export default {}; export const watch = () => ({ close() {} }); export const Database = class {};\\n\",\n );\n\n // Discover routes, plugins, actions, and the workspace core (if any).\n const routes = await discoverApiRoutes(cwd);\n const plugins = await discoverPlugins(cwd);\n const actions = await discoverActionFiles(cwd);\n const missingDefaults = await getMissingDefaultPlugins(cwd);\n const workspaceCore = await getWorkspaceCoreExports(cwd);\n\n const workspaceSlotCount = workspaceCore\n ? Object.keys(workspaceCore.plugins).length\n : 0;\n console.log(\n `[deploy] ${routes.length} API routes, ${actions.length} actions, ${plugins.length} plugins (${plugins.filter((p) => isNodeOnlyPlugin(p)).length} skipped as Node-only), ${missingDefaults.length} auto-mounted defaults${workspaceCore ? `, workspace-core ${workspaceCore.packageName} (${workspaceSlotCount} plugin slots)` : \"\"}`,\n );\n\n // Generate the worker entry\n const immutableAssetPaths = collectImmutableAssetPaths(clientDir);\n const entrySource = generateWorkerEntry(\n routes,\n plugins,\n missingDefaults,\n actions,\n workspaceCore,\n immutableAssetPaths,\n );\n\n // Create _worker.js output directory\n const workerOutDir = path.join(distDir, \"_worker.js\");\n fs.mkdirSync(workerOutDir, { recursive: true });\n\n // Write the worker entry\n const entryFile = path.join(workerOutDir, \"index.js\");\n\n // Rewrite the server-build import to point at the copied files\n const adjustedEntry = entrySource.replace(\n `import * as serverBuild from \"./server-build.js\";`,\n `import * as serverBuild from \"./server/index.js\";`,\n );\n\n // Write a temp file for esbuild to bundle everything into a single worker entry.\n // The server build (React Router SSR) is copied to tmp so esbuild can resolve it.\n const tmpDir = path.join(cwd, \".deploy-tmp\");\n fs.mkdirSync(tmpDir, { recursive: true });\n // Name the entry \"index.js\" so esbuild outputs index.js in the outdir,\n // matching the _worker.js/index.js entry point that Cloudflare Pages expects.\n const tmpEntry = path.join(tmpDir, \"index.js\");\n fs.writeFileSync(tmpEntry, adjustedEntry);\n\n // Copy server build files so esbuild can resolve the import\n copyDir(serverDir, path.join(tmpDir, \"server\"));\n\n // Create a require shim so CJS require(\"fs\") calls resolve via ESM imports.\n // This is injected via esbuild --inject to replace its broken __require shim.\n fs.writeFileSync(\n path.join(tmpDir, \"_require-shim.js\"),\n generateRequireShim(),\n );\n\n // Create stub modules for native/Node-only deps that can't run on Workers.\n // These get resolved by esbuild instead of the real modules, avoiding bundling\n // native code that would fail on the Workers runtime.\n const stubModules = [\n \"better-sqlite3\",\n \"node-pty\",\n \"chokidar\",\n \"fsevents\",\n \"dotenv\",\n \"@anthropic-ai/sdk\",\n ];\n const stubDir = path.join(tmpDir, \"node_modules\");\n for (const mod of stubModules) {\n const modDir = path.join(stubDir, mod);\n fs.mkdirSync(modDir, { recursive: true });\n fs.writeFileSync(\n path.join(modDir, \"index.js\"),\n `export default {}; export const watch = () => ({ close() {} });`,\n );\n fs.writeFileSync(\n path.join(modDir, \"package.json\"),\n JSON.stringify({ name: mod, main: \"index.js\", type: \"module\" }),\n );\n }\n\n const esbuildBin = findEsbuild();\n\n // Externalize node builtins (both bare and node: prefixed) — the require\n // shim handles bare ones. Also alias every `node:*` specifier to its bare\n // name so esbuild emits `import from \"fs\"` everywhere, never\n // `import from \"node:fs\"`. CF Pages Functions (wrangler 3.x, nodejs_compat\n // v1) rejects the `node:` prefix in chunks with:\n // No such module \"node:fs\" imported from chunks/...\n // The alias is the authoritative fix; the post-build strip stays as belt\n // & suspenders in case esbuild emits a node: string via some other path.\n const builtinNames = getNodeBuiltinNames();\n // Only externalize bare names. node:* externals would otherwise pin\n // the prefix in output; instead we alias node:* → bare so anything that\n // resolves past alias land as bare externals.\n const nodeExternals = builtinNames.map((n) => `--external:${n}`);\n const nodeAliases = builtinNames.map((n) => `--alias:node:${n}=${n}`);\n\n // Hard externalize large client-only / node-only libraries so they don't\n // bloat the edge worker. These are never executed in the CF Pages runtime\n // — mermaid/excalidraw render in the browser, pdf-parse and @google/genai\n // run from node-only action scripts. Without this, slides' bundle hits\n // the 25 MiB Pages Functions limit.\n //\n // @anthropic-ai/tokenizer (tiktoken .wasm) and @resvg/resvg-js (native\n // .node binding) can't be bundled by esbuild at all — no loader for those\n // files. Both import sites degrade gracefully when the runtime import\n // fails: context-xray token counts fall back to char/4 estimates and the\n // OG image route falls back to SVG.\n const heavyClientExternals = [\n \"mermaid\",\n \"@excalidraw/excalidraw\",\n \"@excalidraw/mermaid-to-excalidraw\",\n \"pdf-parse\",\n \"pdfjs-dist\",\n \"@google/genai\",\n \"chartjs-node-canvas\",\n \"@napi-rs/canvas\",\n \"@anthropic-ai/tokenizer\",\n \"@resvg/resvg-js\",\n ].map((p) => `--external:${p}`);\n\n execFileSync(\n esbuildBin,\n [\n tmpEntry,\n \"--bundle\",\n \"--format=esm\",\n \"--target=es2022\",\n // browser platform for npm resolution; node builtins externalized separately\n \"--platform=browser\",\n \"--minify\",\n // Single-file bundle (no --splitting). CF Pages Functions' deploy\n // validator fails to load chunked _worker.js/ bundles even when the\n // chunks contain only bare node-builtin imports (wrangler 3.101.0\n // + nodejs_compat v2). Matches main's working config.\n `--outdir=${workerOutDir}`,\n \"--conditions=workerd,worker,import\",\n // The ssr-handler imports a virtual module that only exists at dev time\n \"--external:virtual:react-router/server-build\",\n // Banner: override the __require shim that esbuild generates for CJS modules.\n // This provides a real require() backed by ESM imports of node builtins.\n // Without this, CF Workers rejects the bundle because esbuild's default\n // __require shim throws \"Dynamic require of X is not supported\".\n `--banner:js=${generateRequireShim()}`,\n // Externalize node: builtins — CF Workers runtime provides them\n ...nodeExternals,\n ...heavyClientExternals,\n // Rewrite node:* -> bare names so chunks never contain node: imports\n ...nodeAliases,\n ],\n { stdio: \"inherit\", cwd },\n );\n\n // Clean up tmp\n fs.rmSync(tmpDir, { recursive: true });\n\n // Rewrite the external virtual import to a local stub.\n // esbuild externalizes \"virtual:react-router/server-build\" (used by ssr-handler),\n // but wrangler re-bundles and chokes on it. Replace the import with a no-op stub.\n const virtualStub = path.join(workerOutDir, \"chunks\", \"_virtual-stub.js\");\n fs.mkdirSync(path.dirname(virtualStub), { recursive: true });\n fs.writeFileSync(virtualStub, \"export default {};\\n\");\n\n // Post-build patches — apply to ALL .js files in the worker output directory\n // (entry + chunks) since code can land in any chunk after splitting.\n const allJsFiles = getAllJsFiles(workerOutDir);\n for (const jsFile of allJsFiles) {\n let code = fs.readFileSync(jsFile, \"utf-8\");\n const isEntry = path.basename(jsFile) === \"index.js\";\n\n // Strip \"node:\" prefix from all imports/requires. Cloudflare Pages\n // Functions runs under nodejs_compat v1, which exposes builtins as\n // bare names (\"fs\") and rejects \"node:fs\" at worker init:\n // No such module \"node:fs\" imported from chunks/...\n // (Workers-on-the-edge use v2 and require the prefix; Pages lags.)\n // Preserve the original quote char (single vs double) when rewriting —\n // esbuild's minifier sometimes places `import('node:buffer')` inside a\n // double-quoted string literal; swapping to double quotes breaks the\n // outer literal and produces `Unexpected identifier 'buffer'`.\n code = code.replace(\n /\\bfrom(\\s*)([\"'])node:([^\"']+)\\2/g,\n (_, ws, q, mod) => `from${ws}${q}${mod}${q}`,\n );\n code = code.replace(\n /\\bimport(\\s*)([\"'])node:([^\"']+)\\2/g,\n (_, ws, q, mod) => `import${ws}${q}${mod}${q}`,\n );\n // Strip `node:` prefix from any string literal that names a node\n // builtin. Covers dynamic imports, require(), getBuiltinModule(),\n // and minified wrappers like `Ut(\"node:fs\")` that Nitro/h3 emit.\n // Pages' loader scans chunks for `\"node:*\"` literals and fails with\n // 'No such module \"node:fs\"' whether or not the string is reached\n // at runtime. Scoping to known builtins avoids touching user data.\n // Sorted longest-first so `fs/promises` matches before `fs`.\n const builtinsPattern = [...NODE_BUILTINS]\n .sort((a, b) => b.length - a.length)\n .join(\"|\");\n const builtinRe = new RegExp(`([\"'])node:(${builtinsPattern})\\\\1`, \"g\");\n code = code.replace(\n builtinRe,\n (_, q: string, mod: string) => `${q}${mod}${q}`,\n );\n\n // Rewrite virtual:react-router/server-build imports to the local stub.\n // The generated entry handles SSR directly; this import is dead code from ssr-handler.\n const relStub = path\n .relative(path.dirname(jsFile), virtualStub)\n .replace(/\\\\/g, \"/\");\n code = code.replace(\n /[\"']virtual:react-router\\/server-build[\"']/g,\n `\"./${relStub}\"`,\n );\n\n // Patch createRequire(import.meta.url) — import.meta.url is undefined in CF Workers.\n // Matches both `from \"module\"` and `from \"node:module\"` — with the node:\n // prefix preserved (for nodejs_compat_v2), the latter is what esbuild now emits.\n code = code.replace(\n /\\bimport\\s*\\{\\s*createRequire\\s+as\\s+([\\w$]+)\\s*\\}\\s*from\\s*[\"'](?:node:)?module[\"']\\s*;/g,\n \"var $1 = function() { return typeof require !== 'undefined' ? require : function(m) { throw new Error('require not supported: ' + m); }; };\",\n );\n\n // Patch setInterval/setTimeout at module scope — CF Workers disallows timers in global scope.\n // Some dependencies (e.g. Anthropic SDK rate limiter) call setInterval at module init.\n // With code splitting, chunks evaluate before the entry, so the shim must be in every file.\n // The restore only happens in the entry's fetch() handler.\n if (!code.includes(\"__origSetInterval\")) {\n const timerShim = [\n \"var __origSetInterval=globalThis.setInterval;\",\n \"globalThis.setInterval=function(){return{unref(){},ref(){},close(){}}};\",\n ].join(\"\");\n code = timerShim + code;\n }\n if (isEntry) {\n const timerRestore =\n \"if(__origSetInterval)globalThis.setInterval=__origSetInterval;\";\n code = code.replace(\n /async fetch\\(request,\\s*env,\\s*ctx\\)\\s*\\{/,\n (match) => match + timerRestore,\n );\n }\n\n fs.writeFileSync(jsFile, code);\n }\n\n // Report size\n const entrySize = fs.statSync(entryFile).size;\n const totalSize = getDirSize(workerOutDir);\n const chunkCount = allJsFiles.length - 1; // exclude entry\n console.log(\n `[deploy] Cloudflare Pages output written to dist/ (entry: ${(entrySize / 1024).toFixed(0)}KB, ${chunkCount} chunks, total: ${(totalSize / 1024 / 1024).toFixed(1)}MB)`,\n );\n}\n\nconst NODE_BUILTINS = [\n \"assert\",\n \"async_hooks\",\n \"buffer\",\n \"child_process\",\n \"cluster\",\n \"console\",\n \"constants\",\n \"crypto\",\n \"dgram\",\n \"diagnostics_channel\",\n \"dns\",\n \"domain\",\n \"events\",\n \"fs\",\n \"fs/promises\",\n \"http\",\n \"http2\",\n \"https\",\n \"inspector\",\n \"module\",\n \"net\",\n \"os\",\n \"path\",\n \"perf_hooks\",\n \"process\",\n \"punycode\",\n \"querystring\",\n \"readline\",\n \"repl\",\n \"sqlite\",\n \"stream\",\n \"stream/web\",\n \"string_decoder\",\n \"sys\",\n \"timers\",\n \"tls\",\n \"trace_events\",\n \"tty\",\n \"url\",\n \"util\",\n \"v8\",\n \"vm\",\n \"wasi\",\n \"worker_threads\",\n \"zlib\",\n];\n\nexport function getNodeBuiltinNames(): string[] {\n return NODE_BUILTINS;\n}\n\n/**\n * Generate a require() shim that bridges CJS require(\"fs\") calls to ESM imports.\n * Injected via esbuild --inject so CJS deps work on Workers runtime.\n */\nfunction generateRequireShim(): string {\n // Shim the full set of node builtins so any CJS `require(\"X\")` from a\n // transitive dep resolves to the imported ESM module. Anything less is\n // whack-a-mole: terminal helpers pull in `tty`, transformer libs pull in\n // `worker_threads`, etc. — every miss fails deploy with a generic\n // \"Cannot require: <name>\" thrown by this shim itself.\n //\n // Some builtins exist only as runtime polyfills under nodejs_compat\n // (some are no-op stubs). That's fine — the `import` returns whatever\n // the runtime provides; failures only surface when callers actually USE\n // the unsupported APIs at request time, which is the same as if the\n // shim wasn't there.\n //\n // `sqlite` is excluded because it's Node 22+ only and Workers'\n // nodejs_compat doesn't expose it yet — importing it makes the whole\n // bundle fail to load.\n const shimmed = NODE_BUILTINS.filter((name) => name !== \"sqlite\");\n\n // Bare module names — CF Pages Functions runs under nodejs_compat v1,\n // which rejects \"node:fs\" and only accepts \"fs\". The post-build pass in\n // buildCloudflarePages() also strips any `node:` prefix that esbuild or\n // dependencies emit elsewhere.\n const imports = shimmed\n .map((m) => `import __${m.replace(\"/\", \"_\")} from \"${m}\";`)\n .join(\"\");\n // Only bare-name keys. Pages' Functions loader appears to scan chunks\n // for \"node:*\" string literals and pre-resolves them as module specs —\n // so keeping \"node:fs\" as an object key caused deploy to fail with\n // 'No such module \"node:fs\"' even though nothing imported it. The\n // post-build strip turns every runtime `require(\"node:fs\")` into\n // `require(\"fs\")` so bare keys are sufficient.\n const entries = shimmed\n .map((m) => `\"${m}\":__${m.replace(\"/\", \"_\")}`)\n .join(\",\");\n\n const messageChannelPolyfill = `if(typeof MessageChannel===\"undefined\"){globalThis.MessageChannel=class{constructor(){const a={onmessage:null},b={onmessage:null};a.postMessage=d=>{if(b.onmessage)setTimeout(()=>b.onmessage({data:d}),0)};b.postMessage=d=>{if(a.onmessage)setTimeout(()=>a.onmessage({data:d}),0)};this.port1=a;this.port2=b}}}`;\n return `${imports}\\n${messageChannelPolyfill}\\nconst __mods={${entries}};export var require=globalThis.require||function(m){const r=__mods[m];if(r!==undefined)return r;throw new Error(\"Cannot require: \"+m)};\\n`;\n}\n\nfunction findEsbuild(): string {\n // Try to resolve esbuild's binary via Node module resolution\n // This works regardless of hoisting or .bin symlink creation\n try {\n const _require = createRequire(cwd + \"/\");\n const esbuildPkg = path.dirname(_require.resolve(\"esbuild/package.json\"));\n const bin = path.join(esbuildPkg, \"bin\", \"esbuild\");\n if (fs.existsSync(bin)) return bin;\n } catch {}\n\n // Fallback: check local and workspace .bin\n const localBin = path.resolve(cwd, \"node_modules/.bin/esbuild\");\n if (fs.existsSync(localBin)) return localBin;\n\n const workspaceRoot = findWorkspaceRoot(cwd);\n if (workspaceRoot) {\n const workspaceBin = path.resolve(\n workspaceRoot,\n \"node_modules/.bin/esbuild\",\n );\n if (fs.existsSync(workspaceBin)) return workspaceBin;\n }\n\n return \"esbuild\";\n}\n\nfunction findWorkspaceRoot(dir: string): string | null {\n let current = dir;\n while (current !== path.dirname(current)) {\n if (\n fs.existsSync(path.join(current, \"pnpm-workspace.yaml\")) ||\n fs.existsSync(path.join(current, \"pnpm-lock.yaml\"))\n ) {\n return current;\n }\n current = path.dirname(current);\n }\n return null;\n}\n\n/** Recursively collect all .js files in a directory. */\nfunction getAllJsFiles(dir: string): string[] {\n const results: string[] = [];\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n results.push(...getAllJsFiles(fullPath));\n } else if (entry.name.endsWith(\".js\")) {\n results.push(fullPath);\n }\n }\n return results;\n}\n\nfunction getDirSize(dir: string): number {\n let size = 0;\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n size += getDirSize(fullPath);\n } else {\n size += fs.statSync(fullPath).size;\n }\n }\n return size;\n}\n\nexport function copyDir(\n src: string,\n dest: string,\n ancestorRealPaths = new Set<string>(),\n) {\n const realSrc = fs.realpathSync(src);\n if (ancestorRealPaths.has(realSrc)) return;\n const nextAncestorRealPaths = new Set(ancestorRealPaths);\n nextAncestorRealPaths.add(realSrc);\n\n fs.mkdirSync(dest, { recursive: true });\n const entries = fs.readdirSync(src, { withFileTypes: true });\n for (const entry of entries) {\n const srcPath = path.join(src, entry.name);\n const destPath = path.join(dest, entry.name);\n if (entry.isSymbolicLink()) {\n let stat: fs.Stats;\n try {\n stat = fs.statSync(srcPath);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n console.warn(\n `[deploy] Skipping broken symlink while copying ${srcPath}`,\n );\n continue;\n }\n throw error;\n }\n if (stat.isDirectory()) {\n copyDir(srcPath, destPath, nextAncestorRealPaths);\n } else {\n fs.copyFileSync(srcPath, destPath);\n }\n } else if (entry.isDirectory()) {\n copyDir(srcPath, destPath, nextAncestorRealPaths);\n } else {\n fs.copyFileSync(srcPath, destPath);\n }\n }\n}\n\nconst LIBSQL_NATIVE_PACKAGE_NAMES = [\n \"darwin-arm64\",\n \"darwin-x64\",\n \"linux-arm-gnueabihf\",\n \"linux-arm-musleabihf\",\n \"linux-arm64-gnu\",\n \"linux-arm64-musl\",\n \"linux-x64-gnu\",\n \"linux-x64-musl\",\n \"win32-x64-msvc\",\n];\nconst FFMPEG_STATIC_PACKAGE_NAME = \"ffmpeg-static\";\nconst RESVG_SCOPE = \"@resvg\";\nconst RESVG_PACKAGE_PREFIX = \"resvg-js\";\nconst FFMPEG_STATIC_BINARY_NAMES =\n process.platform === \"win32\" ? [\"ffmpeg.exe\", \"ffmpeg\"] : [\"ffmpeg\"];\nconst SERVERLESS_FFMPEG_STATIC_PLATFORM = \"linux\";\nconst SERVERLESS_FFMPEG_STATIC_ARCHES = new Set<NodeJS.Architecture>([\n \"arm64\",\n \"x64\",\n]);\ntype ServerlessFfmpegStaticArch = \"arm64\" | \"x64\";\n\nfunction serverlessFfmpegStaticTargetArchFromEnv(): ServerlessFfmpegStaticArch | null {\n const value = process.env.AGENT_NATIVE_SERVERLESS_FFMPEG_ARCH;\n if (value === \"arm64\" || value === \"x64\") return value;\n return null;\n}\n\nexport function shouldBundleFfmpegStaticForServerless(\n hostPlatform: NodeJS.Platform = process.platform,\n hostArch: NodeJS.Architecture = process.arch,\n targetArch: ServerlessFfmpegStaticArch | null = serverlessFfmpegStaticTargetArchFromEnv(),\n): boolean {\n return (\n hostPlatform === SERVERLESS_FFMPEG_STATIC_PLATFORM &&\n targetArch !== null &&\n hostArch === targetArch &&\n SERVERLESS_FFMPEG_STATIC_ARCHES.has(targetArch)\n );\n}\n\nfunction nodeModulesAncestors(startDir: string): string[] {\n const dirs: string[] = [];\n let current = path.resolve(startDir);\n while (true) {\n const candidate = path.join(current, \"node_modules\");\n if (fs.existsSync(candidate)) dirs.push(candidate);\n const parent = path.dirname(current);\n if (parent === current) break;\n current = parent;\n }\n return dirs;\n}\n\nfunction findInstalledLibsqlNativePackage(\n nodeModulesRoots: string[],\n packageName: string,\n): string | null {\n for (const root of nodeModulesRoots) {\n const direct = path.join(root, \"@libsql\", packageName);\n if (fs.existsSync(path.join(direct, \"index.node\"))) return direct;\n\n const pnpmRoot = path.join(root, \".pnpm\");\n if (!fs.existsSync(pnpmRoot)) continue;\n const pnpmPrefix = `@libsql+${packageName}@`;\n for (const entry of fs.readdirSync(pnpmRoot)) {\n if (!entry.startsWith(pnpmPrefix)) continue;\n const nested = path.join(\n pnpmRoot,\n entry,\n \"node_modules\",\n \"@libsql\",\n packageName,\n );\n if (fs.existsSync(path.join(nested, \"index.node\"))) return nested;\n }\n }\n return null;\n}\n\nfunction hasFfmpegStaticBinary(packageDir: string): boolean {\n return FFMPEG_STATIC_BINARY_NAMES.some((binaryName) =>\n fs.existsSync(path.join(packageDir, binaryName)),\n );\n}\n\nfunction hasInstalledFfmpegStaticPackage(nodeModulesRoots: string[]): boolean {\n for (const root of nodeModulesRoots) {\n const direct = path.join(root, FFMPEG_STATIC_PACKAGE_NAME);\n if (fs.existsSync(path.join(direct, \"package.json\"))) return true;\n\n const pnpmRoot = path.join(root, \".pnpm\");\n if (!fs.existsSync(pnpmRoot)) continue;\n const pnpmPrefix = `${FFMPEG_STATIC_PACKAGE_NAME}@`;\n for (const entry of fs.readdirSync(pnpmRoot)) {\n if (!entry.startsWith(pnpmPrefix)) continue;\n const nested = path.join(\n pnpmRoot,\n entry,\n \"node_modules\",\n FFMPEG_STATIC_PACKAGE_NAME,\n );\n if (fs.existsSync(path.join(nested, \"package.json\"))) return true;\n }\n }\n return false;\n}\n\nexport function findInstalledFfmpegStaticPackage(\n nodeModulesRoots: string[],\n): string | null {\n for (const root of nodeModulesRoots) {\n const direct = path.join(root, FFMPEG_STATIC_PACKAGE_NAME);\n if (\n fs.existsSync(path.join(direct, \"package.json\")) &&\n hasFfmpegStaticBinary(direct)\n ) {\n return direct;\n }\n\n const pnpmRoot = path.join(root, \".pnpm\");\n if (!fs.existsSync(pnpmRoot)) continue;\n const pnpmPrefix = `${FFMPEG_STATIC_PACKAGE_NAME}@`;\n for (const entry of fs.readdirSync(pnpmRoot)) {\n if (!entry.startsWith(pnpmPrefix)) continue;\n const nested = path.join(\n pnpmRoot,\n entry,\n \"node_modules\",\n FFMPEG_STATIC_PACKAGE_NAME,\n );\n if (\n fs.existsSync(path.join(nested, \"package.json\")) &&\n hasFfmpegStaticBinary(nested)\n ) {\n return nested;\n }\n }\n }\n return null;\n}\n\nexport function findInstalledResvgPackages(\n nodeModulesRoots: string[],\n): Array<{ packageName: string; packageDir: string }> {\n const found = new Map<string, string>();\n\n for (const root of nodeModulesRoots) {\n const directScope = path.join(root, RESVG_SCOPE);\n if (fs.existsSync(directScope)) {\n for (const entry of fs.readdirSync(directScope)) {\n if (!entry.startsWith(RESVG_PACKAGE_PREFIX)) continue;\n const packageDir = path.join(directScope, entry);\n if (fs.existsSync(path.join(packageDir, \"package.json\"))) {\n found.set(entry, packageDir);\n }\n }\n }\n\n const pnpmRoot = path.join(root, \".pnpm\");\n if (!fs.existsSync(pnpmRoot)) continue;\n for (const entry of fs.readdirSync(pnpmRoot)) {\n const match = entry.match(/^@resvg\\+(resvg-js[^@]*)@/);\n if (!match) continue;\n const packageName = match[1];\n const packageDir = path.join(\n pnpmRoot,\n entry,\n \"node_modules\",\n RESVG_SCOPE,\n packageName,\n );\n if (fs.existsSync(path.join(packageDir, \"package.json\"))) {\n found.set(packageName, packageDir);\n }\n }\n }\n\n return [...found.entries()]\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([packageName, packageDir]) => ({ packageName, packageDir }));\n}\n\nfunction copyInstalledLibsqlNativePackages(serverDir: string | undefined) {\n if (!serverDir || !fs.existsSync(serverDir)) return;\n const nodeModulesRoots = nodeModulesAncestors(cwd);\n const destScopeDir = path.join(serverDir, \"node_modules\", \"@libsql\");\n let copied = 0;\n\n for (const packageName of LIBSQL_NATIVE_PACKAGE_NAMES) {\n const src = findInstalledLibsqlNativePackage(nodeModulesRoots, packageName);\n if (!src) continue;\n\n copyDir(src, path.join(destScopeDir, packageName));\n copied += 1;\n }\n\n if (copied > 0) {\n console.log(\n `[deploy] Copied ${copied} installed libsql native package(s) into the server bundle.`,\n );\n }\n}\n\nfunction copyInstalledResvgPackages(serverDir: string | undefined) {\n if (!serverDir || !fs.existsSync(serverDir)) return;\n const packages = findInstalledResvgPackages(nodeModulesAncestors(cwd));\n if (packages.length === 0) return;\n\n const destScopeDir = path.join(serverDir, \"node_modules\", RESVG_SCOPE);\n for (const { packageName, packageDir } of packages) {\n copyDir(packageDir, path.join(destScopeDir, packageName));\n }\n\n console.log(\n `[deploy] Copied ${packages.length} resvg package(s) into the server bundle for OG image rendering.`,\n );\n}\n\nfunction copyInstalledFfmpegStaticPackage(serverDir: string | undefined) {\n if (!serverDir || !fs.existsSync(serverDir)) return;\n const nodeModulesRoots = nodeModulesAncestors(cwd);\n if (!shouldBundleFfmpegStaticForServerless()) {\n if (hasInstalledFfmpegStaticPackage(nodeModulesRoots)) {\n console.warn(\n `[deploy] ffmpeg-static installs a ${process.platform}-${process.arch} binary, but the serverless runtime architecture is not known to match it; ` +\n \"set AGENT_NATIVE_SERVERLESS_FFMPEG_ARCH=x64 or arm64 to bundle a matching binary, otherwise server-side media transcription fallback will require FFMPEG_PATH or a system ffmpeg.\",\n );\n }\n return;\n }\n\n const src = findInstalledFfmpegStaticPackage(nodeModulesRoots);\n if (!src) {\n if (hasInstalledFfmpegStaticPackage(nodeModulesRoots)) {\n console.warn(\n \"[deploy] ffmpeg-static is installed without a downloaded ffmpeg binary; \" +\n \"server-side media transcription fallback will require FFMPEG_PATH or a system ffmpeg.\",\n );\n }\n return;\n }\n\n copyDir(\n src,\n path.join(serverDir, \"node_modules\", FFMPEG_STATIC_PACKAGE_NAME),\n );\n console.log(\n \"[deploy] Copied ffmpeg-static into the server bundle for media transcription fallback.\",\n );\n}\n\n/**\n * Create stub directories for dangling platform-specific optional dependency\n * symlinks in the pnpm store.\n *\n * pnpm's store at `node_modules/.pnpm/<pkg>@<ver>/node_modules/<pkg>/<dep>`\n * contains symlinks for ALL optional deps declared by a package, but only\n * installs the ones matching the current OS/CPU as real packages. The other\n * symlinks dangle — their targets at `.pnpm/<scope>+<pkg>@<ver>/node_modules/...`\n * don't exist.\n *\n * Nitro's `nitro:externals` plugin (via nf3 / @vercel/nft) walks\n * optionalDependencies when tracing files and calls `realpath` on them, which\n * throws ENOENT on dangling targets. This blocks builds with presets like\n * netlify / vercel / aws-lambda on macOS when packages like `libsql` declare\n * Linux-only platform variants as optional deps.\n *\n * Fix: walk `node_modules/.pnpm/` and for every dangling symlink under\n * `<pkg>/node_modules/<scope>/<dep>`, create the symlink's target as a tiny\n * stub directory containing just a valid `package.json`. The tracer can now\n * `realpath` and read the package.json without throwing — the stub is empty\n * so no binary is bundled (which is what we want: we're building from macOS,\n * the target deploy platform will install its own native binary).\n */\nfunction createDanglingOptionalDepStubs() {\n // In pnpm monorepos, the store may live at the workspace root rather than\n // in the template dir. Walk up from `cwd` to find every `.pnpm` directory.\n const pnpmRoots: string[] = [];\n let dir = cwd;\n while (true) {\n const candidate = path.join(dir, \"node_modules\", \".pnpm\");\n if (fs.existsSync(candidate)) pnpmRoots.push(candidate);\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n if (pnpmRoots.length === 0) return;\n\n let stubsCreated = 0;\n\n for (const pnpmRoot of pnpmRoots) {\n let pkgDirs: string[];\n try {\n pkgDirs = fs.readdirSync(pnpmRoot);\n } catch {\n continue;\n }\n\n for (const pkgDir of pkgDirs) {\n // e.g. `libsql@0.5.29`, `@libsql+client@0.15.15`\n const innerNm = path.join(pnpmRoot, pkgDir, \"node_modules\");\n if (!fs.existsSync(innerNm)) continue;\n\n let innerEntries: fs.Dirent[];\n try {\n innerEntries = fs.readdirSync(innerNm, { withFileTypes: true });\n } catch {\n continue;\n }\n\n for (const entry of innerEntries) {\n // Top-level entry: either `foo` (unscoped) or `@scope` (scoped)\n const entryPath = path.join(innerNm, entry.name);\n const candidates: { symlinkPath: string; pkgName: string }[] = [];\n if (entry.name.startsWith(\"@\")) {\n // Scoped — iterate children\n let scopedChildren: fs.Dirent[];\n try {\n scopedChildren = fs.readdirSync(entryPath, {\n withFileTypes: true,\n });\n } catch {\n continue;\n }\n for (const child of scopedChildren) {\n candidates.push({\n symlinkPath: path.join(entryPath, child.name),\n pkgName: `${entry.name}/${child.name}`,\n });\n }\n } else {\n candidates.push({ symlinkPath: entryPath, pkgName: entry.name });\n }\n\n for (const { symlinkPath, pkgName } of candidates) {\n let isSymlink = false;\n try {\n isSymlink = fs.lstatSync(symlinkPath).isSymbolicLink();\n } catch {\n continue;\n }\n if (!isSymlink) continue;\n\n // Check if the symlink target exists\n try {\n fs.statSync(symlinkPath);\n continue; // Target exists — nothing to do\n } catch {\n // Dangling symlink — create a stub at the target\n }\n\n let linkTarget: string;\n try {\n linkTarget = fs.readlinkSync(symlinkPath);\n } catch {\n continue;\n }\n const resolvedTarget = path.resolve(\n path.dirname(symlinkPath),\n linkTarget,\n );\n\n try {\n fs.mkdirSync(resolvedTarget, { recursive: true });\n const stubPkgJson = {\n name: pkgName,\n version: \"0.0.0-stub\",\n description:\n \"Empty stub created by @agent-native/core deploy build to satisfy nitro's file tracer on platforms where this optional dep is not installed.\",\n };\n fs.writeFileSync(\n path.join(resolvedTarget, \"package.json\"),\n JSON.stringify(stubPkgJson, null, 2),\n );\n stubsCreated++;\n } catch {\n // Best-effort — ignore failures\n }\n }\n }\n }\n }\n\n if (stubsCreated > 0) {\n console.log(\n `[deploy] Created ${stubsCreated} stub package dir(s) for dangling optional deps (platform-specific binaries not installed on this host).`,\n );\n }\n}\n\n/**\n * Build for any non-Cloudflare preset using Nitro's programmatic build API.\n * Handles netlify, vercel, deno_deploy, aws-lambda, and all other targets.\n */\nexport interface NitroBuildHooks {\n prepare: (nitro: any) => Promise<void>;\n copyPublicAssets: (nitro: any) => Promise<void>;\n nitroBuild: (nitro: any) => Promise<void>;\n}\n\nexport interface NitroBuildPipelineOptions {\n nitro: any;\n hooks: NitroBuildHooks;\n clientDir: string;\n publicOutputDir: string | undefined;\n appBasePath: string;\n cwd: string;\n}\n\n/**\n * Run Nitro's lifecycle in the order required to ship a working React Router\n * framework-mode build.\n *\n * The critical ordering constraint is that the React Router client build must\n * be copied into `publicOutputDir` *before* `nitroBuild` runs. Nitro generates\n * the static-asset manifest baked into the server bundle by globbing\n * `publicDir` during the server build; files copied in after that point exist\n * on disk but are invisible to the runtime `serveStatic` handler. Every\n * /assets/* request then falls through to the SSR catch-all, which 404s\n * anything with a file extension.\n */\nexport async function runNitroBuildPipeline(\n opts: NitroBuildPipelineOptions,\n): Promise<void> {\n const { nitro, hooks, clientDir, publicOutputDir, appBasePath, cwd } = opts;\n const hasClientBuild = fs.existsSync(clientDir) && Boolean(publicOutputDir);\n\n if (hasClientBuild) {\n // Install hashed-asset route rules before Nitro prepares platform output.\n // Some presets materialize headers during prepare/copy phases, not only in\n // nitroBuild; adding these later leaves Netlify/Vercel static assets without\n // the one-year immutable CDN policy even though the runtime manifest works.\n nitro.options.routeRules ??= {};\n addImmutableAssetRouteRulesForClientBuild(\n nitro.options.routeRules,\n clientDir,\n appBasePath,\n );\n }\n\n await hooks.prepare(nitro);\n await hooks.copyPublicAssets(nitro);\n\n if (hasClientBuild && publicOutputDir) {\n copyDir(clientDir, publicOutputDir);\n if (appBasePath) {\n copyDir(clientDir, path.join(publicOutputDir, appBasePath.slice(1)));\n }\n console.log(\n `[deploy] Copied client assets to ${path.relative(cwd, publicOutputDir)}`,\n );\n }\n\n await hooks.nitroBuild(nitro);\n}\n\n/**\n * Browser-only diagram/drawing renderers that execute `window`-touching code at\n * module-evaluation time. They are rendered exclusively client-side — core's\n * `MermaidBlock` and templates' Excalidraw slides mount them inside `useEffect` /\n * `React.lazy`, never during SSR — so the server never needs the real module.\n *\n * Keep this list to libraries that are *provably never* invoked on the server.\n * Node-only deps that DO run server-side (pdf-parse, @google/genai, canvas, …)\n * must NOT go here — see `heavyClientExternals` for the edge-worker externals.\n */\nconst BROWSER_ONLY_SERVER_LIBS = [\n \"@excalidraw/excalidraw\",\n \"@excalidraw/mermaid-to-excalidraw\",\n \"mermaid\",\n];\n\n/**\n * Rolldown plugin for the Nitro server bundle that replaces the browser-only\n * renderers above with an inert proxy module.\n *\n * Why this is needed: Nitro re-bundles the server from node_modules with its own\n * Rolldown pipeline, and Rolldown merges Excalidraw into a SHARED vendor chunk\n * that the SSR render path (tiptap / radix-ui / recharts) imports *statically*.\n * That evaluates Excalidraw's top-level `window` access at function cold-start\n * and crashes every request with `ReferenceError: window is not defined` (HTTP\n * 502). The Vite SSR build already stubs these via `ssrStubPlugin` for\n * `build/server`, but that Vite plugin doesn't run during Nitro's separate\n * bundle — so mirror the same stub here.\n */\nfunction createBrowserOnlyServerStubPlugin() {\n const stubbed = new Set(BROWSER_ONLY_SERVER_LIBS);\n const STUB_ID = \"\\0agent-native-browser-only-server-stub\";\n return {\n name: \"agent-native-browser-only-server-stub\",\n // enforce: \"pre\" so we intercept before Nitro's node resolver bundles the\n // real package. defu concatenates rollupConfig.plugins ahead of Nitro's own.\n resolveId(id: string) {\n // Match the bare package name or any subpath (incl. `/index.css`).\n const pkg = id\n .split(\"/\")\n .slice(0, id.startsWith(\"@\") ? 2 : 1)\n .join(\"/\");\n return stubbed.has(pkg) ? STUB_ID : null;\n },\n load(id: string) {\n if (id !== STUB_ID) return null;\n // A Proxy answers any property access (default or named) with another\n // proxy, so every import shape resolves without evaluating real browser\n // code. It is never actually invoked on the server, so it never throws.\n return (\n \"const handler = { get(_t, p) {\" +\n \" if (p === Symbol.toPrimitive) return () => '';\" +\n \" if (p === 'then') return undefined;\" +\n \" if (p === '__esModule') return true;\" +\n \" return new Proxy(function () {}, handler); } };\" +\n \"const stub = new Proxy(function () {}, handler);\" +\n \"export default stub;\"\n );\n },\n };\n}\n\nasync function buildWithNitro() {\n console.log(`[deploy] Building for preset \"${preset}\" via Nitro...`);\n const appBasePath = normalizeConfiguredAppBasePath();\n\n // Nitro runs its own server build after the React Router/Vite build. The\n // template's agent-chat plugin imports .generated/actions-registry.ts so the\n // serverless bundle has static imports for every domain action. Regenerate\n // here as well so deploy builds are not coupled to a previous Vite run or to\n // ignored local .generated files being present.\n generateActionRegistryForProject(cwd);\n\n // Work around pnpm + nitro:externals (nf3) bug where dangling symlinks for\n // platform-specific optional deps cause realpath ENOENT during file tracing.\n createDanglingOptionalDepStubs();\n\n const {\n createNitro,\n prepare,\n copyPublicAssets,\n build: nitroBuild,\n } = await import(\"nitro/builder\");\n\n // Resolve the React Router server build so the SSR catch-all route\n // can import \"virtual:react-router/server-build\" in production.\n const rrServerBuild = path.join(cwd, \"build\", \"server\", \"index.js\");\n\n // Inline the template's AGENTS.md + .agents/skills/ content into the Nitro\n // bundle via the `virtual` config option. Nitro's internal `nitro:virtual`\n // Rollup plugin picks this up and resolves `virtual:agents-bundle` to the\n // generated ES module source. Without this, Nitro's Rolldown build (used for\n // netlify, vercel, aws-lambda, node presets) can't resolve the virtual\n // module that `server/agents-bundle.ts` imports — it silently falls through\n // to an empty bundle and the agent gets no instructions/skills at runtime.\n //\n // The Vite plugin at `vite/agents-bundle-plugin.ts` handles this for the\n // React Router client/server build (and cloudflare via esbuild rebundle),\n // but Nitro runs its OWN build from ./server/ without Vite, so it needs its\n // own virtual module registration. Both paths reuse `readAgentsBundleFromFs`\n // from `server/agents-bundle.ts` to guarantee identical content.\n const { readAgentsBundleFromFs } = await import(\"../server/agents-bundle.js\");\n // Resolve the workspace core (if present) up front so the bundle embeds\n // enterprise-wide AGENTS.md + skills alongside the template's.\n const nitroWorkspaceCore = await getWorkspaceCoreExports(cwd);\n const nitroWorkspaceSource = nitroWorkspaceCore\n ? {\n skillsDir: nitroWorkspaceCore.skillsDir,\n agentsMdPath: nitroWorkspaceCore.agentsMdPath,\n rootDir: nitroWorkspaceCore.packageDir,\n }\n : null;\n const agentsBundleModuleSource = () => {\n const bundle = readAgentsBundleFromFs(cwd, nitroWorkspaceSource);\n return `// AUTO-GENERATED by @agent-native/core deploy build (Nitro virtual)\n// Contains the inlined AGENTS.md + .agents/skills/ content from the template,\n// merged with the workspace core's AGENTS.md + skills/ when present.\nconst bundle = ${JSON.stringify(bundle)};\nexport default bundle;\n`;\n };\n\n // Path aliases used by templates (mirrors tsconfig + Vite config). Nitro\n // bundles server/ and actions/ with its own Rolldown pipeline that doesn't\n // see Vite's resolve.alias — so without this, action files that import\n // `@/foo` (= `app/foo`) end up with the literal `@/foo` specifier in the\n // serverless function output and crash at runtime with\n // \"Cannot find package '@/foo' imported from /var/task/main.mjs\".\n const appDir = path.join(cwd, \"app\");\n const sharedDir = path.join(cwd, \"shared\");\n const pathAliases: Record<string, string> = {};\n if (fs.existsSync(appDir)) pathAliases[\"@\"] = appDir;\n if (fs.existsSync(sharedDir)) pathAliases[\"@shared\"] = sharedDir;\n\n const providedPluginsNitroPlugin = await writeProvidedPluginsNitroPlugin();\n\n const nitro = await createNitro({\n rootDir: cwd,\n dev: false,\n preset,\n baseURL: appBasePath || \"/\",\n minify: true,\n serverDir: \"./server\",\n ignore: NITRO_RUNTIME_IGNORE_PATTERNS,\n alias: {\n ...pathAliases,\n ...(fs.existsSync(rrServerBuild)\n ? { \"virtual:react-router/server-build\": rrServerBuild }\n : {}),\n },\n virtual: {\n \"virtual:agents-bundle\": agentsBundleModuleSource,\n },\n // Replace browser-only renderers (Excalidraw/Mermaid) with an inert proxy in\n // the server bundle. Without this, Nitro's Rolldown build pulls the real\n // Excalidraw into a shared vendor chunk imported statically by the SSR render\n // path, and its top-level `window` access crashes the function at cold-start\n // (ReferenceError: window is not defined → every request 502s). Mirrors the\n // Vite `ssrStubPlugin`, which only covers the `build/server` step.\n rollupConfig: {\n plugins: [createBrowserOnlyServerStubPlugin()],\n },\n ...(providedPluginsNitroPlugin\n ? { plugins: [providedPluginsNitroPlugin] }\n : {}),\n routeRules: mcpEmbedStaticAssetRouteRules(appBasePath),\n // For edge presets (cloudflare, deno), bundle all deps — node_modules\n // aren't available at runtime. Netlify/Vercel/Node have node_modules.\n ...(preset.startsWith(\"cloudflare\") || preset.startsWith(\"deno\")\n ? { noExternals: true }\n : {}),\n } as any);\n\n await runNitroBuildPipeline({\n nitro,\n hooks: { prepare, copyPublicAssets, nitroBuild },\n clientDir: path.join(cwd, \"build\", \"client\"),\n publicOutputDir: nitro.options.output.publicDir,\n appBasePath,\n cwd,\n });\n\n if (preset === \"netlify\" || preset === \"vercel\" || preset === \"aws-lambda\") {\n copyInstalledLibsqlNativePackages(nitro.options.output.serverDir);\n copyInstalledResvgPackages(nitro.options.output.serverDir);\n copyInstalledFfmpegStaticPackage(nitro.options.output.serverDir);\n }\n\n // Resolve remaining bare npm imports by bundling them into _libs/.\n // Nitro sometimes leaves small packages as externals even with noExternals.\n if (preset.startsWith(\"cloudflare\") || preset.startsWith(\"deno\")) {\n const { execFileSync } = await import(\"child_process\");\n const { createRequire } = await import(\"module\");\n const esbuildBin = (() => {\n try {\n const _req = createRequire(cwd + \"/\");\n const pkg = path.dirname(_req.resolve(\"esbuild/package.json\"));\n const bin = path.join(pkg, \"bin\", \"esbuild\");\n if (fs.existsSync(bin)) return bin;\n } catch {}\n return \"esbuild\";\n })();\n\n // Scan all output files for bare npm imports\n const outputDir =\n nitro.options.output.serverDir || path.join(cwd, \"dist\", \"_worker.js\");\n const bareImports = new Set<string>();\n function scanForBareImports(dir: string) {\n if (!fs.existsSync(dir)) return;\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n const p = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n scanForBareImports(p);\n continue;\n }\n if (!entry.name.endsWith(\".mjs\") && !entry.name.endsWith(\".js\"))\n continue;\n const code = fs.readFileSync(p, \"utf-8\");\n const matches = code.matchAll(/from\\s*[\"']([a-z@][a-z0-9._\\-/]*)[\"']/g);\n for (const m of matches) {\n const mod = m[1];\n if (mod.startsWith(\"node:\")) continue;\n // Skip Node builtins that are available via nodejs_compat\n const builtins = new Set([\n \"fs\",\n \"path\",\n \"os\",\n \"crypto\",\n \"http\",\n \"https\",\n \"stream\",\n \"url\",\n \"util\",\n \"events\",\n \"buffer\",\n \"net\",\n \"tls\",\n \"assert\",\n \"timers\",\n \"child_process\",\n \"module\",\n \"process\",\n \"sqlite\",\n \"worker_threads\",\n \"querystring\",\n \"zlib\",\n \"vm\",\n \"string_decoder\",\n \"diagnostics_channel\",\n \"async_hooks\",\n \"perf_hooks\",\n \"inspector\",\n ]);\n if (builtins.has(mod)) continue;\n bareImports.add(mod);\n }\n }\n }\n scanForBareImports(outputDir);\n\n // For each bare import, try to bundle it as a standalone module\n if (bareImports.size > 0) {\n const libsDir = path.join(outputDir, \"_libs\");\n fs.mkdirSync(libsDir, { recursive: true });\n for (const mod of bareImports) {\n const outFile = path.join(libsDir, `${mod.replace(/[/@]/g, \"_\")}.mjs`);\n try {\n // Resolve the module — check workspace node_modules and pnpm store\n let resolvedMod = mod;\n const _require = createRequire(cwd + \"/\");\n try {\n const resolved = _require.resolve(mod);\n resolvedMod = resolved;\n } catch {\n // Try from workspace root\n try {\n const wsRequire = createRequire(\n path.resolve(cwd, \"../../package.json\"),\n );\n resolvedMod = wsRequire.resolve(mod);\n } catch {\n // Will fail at esbuild\n }\n }\n // Scan what named imports the consumer expects, then generate\n // explicit re-exports to handle CJS modules properly.\n const neededExports = new Set<string>();\n function findNeededExports(dir: string) {\n if (!fs.existsSync(dir)) return;\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n const p = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n findNeededExports(p);\n continue;\n }\n if (!entry.name.endsWith(\".mjs\") && !entry.name.endsWith(\".js\"))\n continue;\n const code = fs.readFileSync(p, \"utf-8\");\n // Match: import{foo as bar,baz}from\"<mod>\"\n const escaped = mod.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const re = new RegExp(\n `import\\\\{([^}]+)\\\\}from[\"']${escaped}[\"']`,\n \"g\",\n );\n for (const m2 of code.matchAll(re)) {\n for (const part of m2[1].split(\",\")) {\n const name = part\n .trim()\n .split(/\\s+as\\s+/)[0]\n .trim();\n if (name && /^[a-zA-Z_$]/.test(name)) neededExports.add(name);\n }\n }\n }\n }\n findNeededExports(outputDir);\n\n const entryCode =\n neededExports.size > 0\n ? [\n `import _mod from \"${resolvedMod}\";`,\n `export default _mod;`,\n ...Array.from(neededExports).map(\n (n) =>\n `export const ${n} = _mod.${n} ?? _mod?.default?.${n};`,\n ),\n ].join(\"\\n\")\n : `export * from \"${resolvedMod}\"; export { default } from \"${resolvedMod}\";`;\n\n execFileSync(\n esbuildBin,\n [\n \"--bundle\",\n `--outfile=${outFile}`,\n \"--format=esm\",\n \"--platform=neutral\",\n \"--target=es2022\",\n \"--external:node:*\",\n ],\n {\n input: entryCode,\n cwd,\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n },\n );\n // Rewrite imports in all files to point to the bundled module\n function rewriteImports(dir: string) {\n if (!fs.existsSync(dir)) return;\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n const p = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n rewriteImports(p);\n continue;\n }\n if (!entry.name.endsWith(\".mjs\") && !entry.name.endsWith(\".js\"))\n continue;\n let code = fs.readFileSync(p, \"utf-8\");\n const relPath = path\n .relative(path.dirname(p), outFile)\n .replace(/\\\\/g, \"/\");\n const importPath = relPath.startsWith(\".\")\n ? relPath\n : \"./\" + relPath;\n const re = new RegExp(\n `from[\"']${mod.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")}[\"']`,\n \"g\",\n );\n if (re.test(code)) {\n code = code.replace(re, `from\"${importPath}\"`);\n fs.writeFileSync(p, code);\n }\n }\n }\n rewriteImports(outputDir);\n console.log(`[deploy] Bundled external: ${mod}`);\n } catch {\n console.warn(\n `[deploy] Could not bundle: ${mod} (may not be needed at runtime)`,\n );\n }\n }\n }\n }\n\n // Cloudflare-specific post-build patches\n if (preset.startsWith(\"cloudflare\")) {\n const serverDir2 = nitro.options.output.serverDir;\n const scanDirs = [serverDir2];\n if (serverDir2) {\n const chunksDir = path.join(serverDir2, \"_chunks\");\n const libsDir = path.join(serverDir2, \"_libs\");\n if (fs.existsSync(chunksDir)) scanDirs.push(chunksDir);\n if (fs.existsSync(libsDir)) scanDirs.push(libsDir);\n }\n\n for (const scanDir of scanDirs) {\n if (!scanDir || !fs.existsSync(scanDir)) continue;\n for (const file of fs.readdirSync(scanDir)) {\n if (!file.endsWith(\".mjs\") && !file.endsWith(\".js\")) continue;\n const filePath = path.join(scanDir, file);\n let code = fs.readFileSync(filePath, \"utf-8\");\n let changed = false;\n\n // 1. Rewrite bare Node.js imports to node: prefixed.\n // CF Workers requires the node: prefix for built-in modules.\n const NODE_BUILTINS = [\n \"fs\",\n \"path\",\n \"os\",\n \"crypto\",\n \"http\",\n \"https\",\n \"stream\",\n \"url\",\n \"util\",\n \"events\",\n \"buffer\",\n \"querystring\",\n \"zlib\",\n \"net\",\n \"tls\",\n \"assert\",\n \"timers\",\n \"child_process\",\n \"module\",\n \"process\",\n \"sqlite\",\n \"worker_threads\",\n \"string_decoder\",\n \"diagnostics_channel\",\n \"async_hooks\",\n \"perf_hooks\",\n \"inspector\",\n \"vm\",\n ];\n for (const mod of NODE_BUILTINS) {\n // Match: from\"fs\" or from \"fs\" (but not from\"node:fs\")\n const re = new RegExp(`from\\\\s*[\"']${mod}[\"']`, \"g\");\n if (re.test(code)) {\n code = code.replace(re, `from\"node:${mod}\"`);\n changed = true;\n }\n }\n\n // 2. Patch import.meta.url for createRequire().\n // React Router's server build uses createRequire(import.meta.url)\n // but import.meta.url is undefined on CF Workers.\n if (code.includes(\"import.meta.url\")) {\n code = code.replace(/import\\.meta\\.url/g, '\"file:///worker.mjs\"');\n changed = true;\n }\n\n // 3. Patch setInterval/setTimeout at global scope.\n // CF Workers disallows timers in global scope.\n if (code.includes(\"setInterval\") && !code.includes(\"__timer_shim__\")) {\n const shim =\n \"/* __timer_shim__ */\" +\n \"var __origSetInterval=globalThis.setInterval;\" +\n \"globalThis.setInterval=function(){return{unref(){},ref(){},close(){}}};\";\n const restore =\n \";(function(){if(typeof __origSetInterval!=='undefined')globalThis.setInterval=__origSetInterval})();\";\n code = shim + code + \"\\n\" + restore;\n changed = true;\n }\n\n if (changed) fs.writeFileSync(filePath, code);\n }\n }\n // 3. Create stub modules in _libs/ for native deps that Nitro's rolldown\n // bundler references but can't resolve on CF Workers, and rewrite\n // bare imports to point to the stub files.\n const libsDir2 = path.join(\n serverDir2 || path.join(cwd, \"dist\", \"_worker.js\"),\n \"_libs\",\n );\n if (fs.existsSync(libsDir2)) {\n const NATIVE_STUBS = [\"better-sqlite3\", \"node-pty\", \"cron-parser\"];\n for (const mod of NATIVE_STUBS) {\n const libFiles = fs\n .readdirSync(libsDir2)\n .filter((f) => f.endsWith(\".mjs\"));\n const referencingFiles: string[] = [];\n for (const f of libFiles) {\n const filePath = path.join(libsDir2, f);\n const content = fs.readFileSync(filePath, \"utf-8\");\n if (content.includes(`\"${mod}\"`) || content.includes(`'${mod}'`)) {\n referencingFiles.push(filePath);\n }\n }\n if (referencingFiles.length === 0) continue;\n\n // Create a stub _libs/<mod>.mjs that exports empty defaults\n const stubName = mod.replace(/[/@]/g, \"__\") + \".mjs\";\n const stubPath = path.join(libsDir2, stubName);\n if (!fs.existsSync(stubPath)) {\n fs.writeFileSync(\n stubPath,\n `export default {}; export const watch = () => ({ close() {} });\\n`,\n );\n console.log(`[deploy] Created stub for _libs/${stubName}`);\n }\n\n // Rewrite bare imports in _libs/ and _chunks/ to use the stub\n const escaped = mod.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const importRe = new RegExp(`(from\\\\s*[\"'])${escaped}([\"'])`, \"g\");\n // Scan _libs/ files\n for (const filePath of referencingFiles) {\n let code = fs.readFileSync(filePath, \"utf-8\");\n if (importRe.test(code)) {\n code = code.replace(importRe, `$1./${stubName}$2`);\n fs.writeFileSync(filePath, code);\n console.log(\n `[deploy] Rewrote ${mod} imports in _libs/${path.basename(filePath)}`,\n );\n }\n }\n // Also scan _chunks/ files (they import native deps too)\n const chunksDir2 = path.join(\n serverDir2 || path.join(cwd, \"dist\", \"_worker.js\"),\n \"_chunks\",\n );\n if (fs.existsSync(chunksDir2)) {\n for (const f of fs\n .readdirSync(chunksDir2)\n .filter((f) => f.endsWith(\".mjs\") || f.endsWith(\".js\"))) {\n const filePath = path.join(chunksDir2, f);\n let code = fs.readFileSync(filePath, \"utf-8\");\n if (importRe.test(code)) {\n // From _chunks/, the stub is at ../_libs/<stubName>\n code = code.replace(importRe, `$1../_libs/${stubName}$2`);\n fs.writeFileSync(filePath, code);\n console.log(`[deploy] Rewrote ${mod} imports in _chunks/${f}`);\n }\n }\n }\n }\n }\n\n console.log(\n \"[deploy] Patched bare Node imports, timer calls, and route finder for CF Workers\",\n );\n }\n\n await nitro.close();\n console.log(`[deploy] Nitro build complete for preset \"${preset}\".`);\n}\n\nasync function main() {\n console.log(`[deploy] Building for ${preset}...`);\n\n switch (preset) {\n case \"cloudflare_pages\":\n case \"cloudflare-pages\":\n // Cloudflare Workers require a single-file bundle that wrangler can deploy.\n // Nitro's native presets produce split chunks that wrangler can't upload\n // as multi-module Workers. Use the custom esbuild-based bundler.\n await buildCloudflarePages();\n break;\n default:\n // All other presets (netlify, vercel, deno_deploy, aws-lambda, etc.)\n // are handled natively by Nitro's build API.\n await buildWithNitro();\n break;\n }\n}\n\nif (\n process.argv[1] &&\n path.resolve(process.argv[1]) === path.resolve(fileURLToPath(import.meta.url))\n) {\n await main();\n}\n"]}
|
|
1
|
+
{"version":3,"file":"build.js","sourceRoot":"","sources":["../../src/deploy/build.ts"],"names":[],"mappings":";AAEA;;;;;;;;;;;;GAYG;AAEH,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAC7C,OAAO,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAC;AACvC,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AACpC,OAAO,EACL,iBAAiB,EACjB,eAA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YAC7B,MAAM;QACR;YACE,qEAAqE;YACrE,6CAA6C;YAC7C,MAAM,cAAc,EAAE,CAAC;YACvB,MAAM;IACV,CAAC;AACH,CAAC;AAED,IACE,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC;IACf,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,OAAO,CAAC,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAC9E,CAAC;IACD,MAAM,IAAI,EAAE,CAAC;AACf,CAAC","sourcesContent":["#!/usr/bin/env node\n\n/**\n * Post-build step for deploying agent-native apps to edge/serverless targets.\n *\n * When NITRO_PRESET is set, this script:\n * 1. Takes the React Router build output (build/client/ + build/server/)\n * 2. Generates a platform-specific server entry point\n * 3. Bundles everything with esbuild into the target format\n *\n * Supported presets:\n * - cloudflare_pages: Outputs dist/ with _worker.js for Cloudflare Pages\n *\n * Usage: node deploy/build.js (called automatically by `agent-native build`)\n */\n\nimport path from \"path\";\nimport fs from \"fs\";\nimport { execFileSync } from \"child_process\";\nimport { createRequire } from \"module\";\nimport { fileURLToPath } from \"url\";\nimport {\n discoverApiRoutes,\n discoverPlugins,\n discoverActionFiles,\n getMissingDefaultPlugins,\n DEFAULT_PLUGIN_REGISTRY,\n type DiscoveredRoute,\n type DiscoveredAction,\n} from \"./route-discovery.js\";\nimport {\n getWorkspaceCoreExports,\n type WorkspaceCoreExports,\n} from \"./workspace-core.js\";\nimport { generateActionRegistryForProject } from \"../vite/action-types-plugin.js\";\nimport { mcpEmbedStaticAssetRouteRules } from \"../shared/mcp-embed-headers.js\";\nimport {\n AGENT_NATIVE_SOCIAL_IMAGE_ALT,\n AGENT_NATIVE_SOCIAL_IMAGE_CACHE_BUSTER,\n AGENT_NATIVE_SOCIAL_IMAGE_HEIGHT,\n AGENT_NATIVE_SOCIAL_IMAGE_PATH,\n AGENT_NATIVE_SOCIAL_IMAGE_TYPE,\n AGENT_NATIVE_SOCIAL_IMAGE_WIDTH,\n} from \"../shared/social-meta.js\";\nimport {\n DEFAULT_SSR_CDN_CACHE_CONTROL,\n DEFAULT_SSR_NETLIFY_CDN_CACHE_CONTROL,\n DEFAULT_SPECULATION_RULES_PATH,\n DEFAULT_SSR_CACHE_CONTROL,\n} from \"../shared/cache-control.js\";\nimport {\n collectImmutableAssetPaths,\n IMMUTABLE_ASSET_CACHE_CONTROL,\n IMMUTABLE_ASSET_CACHE_HEADERS,\n prefixAssetPath,\n} from \"./immutable-assets.js\";\nimport { normalizeAppBasePath } from \"../server/app-base-path.js\";\n\nconst cwd = process.cwd();\nconst preset = process.env.NITRO_PRESET || \"node\";\nexport const NITRO_RUNTIME_IGNORE_PATTERNS = [\n \"**/*.spec.ts\",\n \"**/*.spec.tsx\",\n \"**/*.spec.mts\",\n \"**/*.spec.cts\",\n \"**/*.spec.js\",\n \"**/*.spec.jsx\",\n \"**/*.spec.mjs\",\n \"**/*.spec.cjs\",\n \"**/*.test.ts\",\n \"**/*.test.tsx\",\n \"**/*.test.mts\",\n \"**/*.test.cts\",\n \"**/*.test.js\",\n \"**/*.test.jsx\",\n \"**/*.test.mjs\",\n \"**/*.test.cjs\",\n];\n\nfunction normalizeConfiguredAppBasePath(): string {\n return normalizeAppBasePath(\n process.env.VITE_APP_BASE_PATH || process.env.APP_BASE_PATH,\n );\n}\n\n/** Plugins that require Node.js runtime and cannot run on edge/serverless */\nconst NODE_ONLY_PLUGINS = new Set([\n \"terminal\", // PTY requires child_process\n // @sentry/node ships node:fs / node:async_hooks bindings that don't load\n // on workerd / Cloudflare Workers. Templates running on edge presets can\n // mount their own edge-compatible Sentry wrapper if they want server\n // observability there; the framework default is the Node SDK.\n \"sentry\",\n]);\n\nfunction isNodeOnlyPlugin(filePath: string): boolean {\n const basename = path.basename(filePath, path.extname(filePath));\n return NODE_ONLY_PLUGINS.has(basename);\n}\n\nexport function generateProvidedPluginsNitroPluginSource(\n pluginStems: string[],\n): string {\n const stems = [...new Set(pluginStems.filter(Boolean))].sort();\n return `// AUTO-GENERATED by @agent-native/core deploy build\nimport { markDefaultPluginProvided } from \"@agent-native/core/server\";\n\nconst pluginStems = ${JSON.stringify(stems)};\n\nexport default function markBuildDiscoveredPlugins(nitroApp) {\n for (const stem of pluginStems) {\n markDefaultPluginProvided(nitroApp, stem);\n }\n}\n`;\n}\n\nasync function writeProvidedPluginsNitroPlugin(): Promise<string | null> {\n const plugins = await discoverPlugins(cwd);\n const stems = plugins.map((plugin) =>\n path.basename(plugin, path.extname(plugin)),\n );\n if (stems.length === 0) return null;\n\n const tmpDir = path.join(cwd, \".deploy-tmp\");\n fs.mkdirSync(tmpDir, { recursive: true });\n const pluginPath = path.join(tmpDir, \"agent-native-provided-plugins.mjs\");\n fs.writeFileSync(pluginPath, generateProvidedPluginsNitroPluginSource(stems));\n return pluginPath;\n}\n\ntype RouteRules = Record<string, { headers?: Record<string, string> }>;\n\nfunction addImmutableAssetRouteRule(\n routeRules: RouteRules,\n pathname: string,\n): void {\n const existing = routeRules[pathname] ?? {};\n routeRules[pathname] = {\n ...existing,\n headers: {\n ...(existing.headers ?? {}),\n ...IMMUTABLE_ASSET_CACHE_HEADERS,\n },\n };\n}\n\nexport function addImmutableAssetRouteRulesForClientBuild(\n routeRules: RouteRules,\n clientDir: string,\n appBasePath = \"\",\n): void {\n for (const assetPath of collectImmutableAssetPaths(clientDir)) {\n addImmutableAssetRouteRule(routeRules, assetPath);\n const mountedPath = prefixAssetPath(assetPath, appBasePath);\n if (mountedPath !== assetPath) {\n addImmutableAssetRouteRule(routeRules, mountedPath);\n }\n }\n}\n\n/**\n * Generate the worker entry source code that wires up H3 + React Router SSR.\n *\n * If a workspace core is present (monorepo with `agent-native.workspaceCore`\n * configured and the named package resolves), any plugin slot that the\n * workspace core exports is imported from there instead of from\n * `@agent-native/core/server`. This is the middle layer of the three-layer\n * inheritance model: app local > workspace core > framework default.\n */\nexport function generateWorkerEntry(\n routes: DiscoveredRoute[],\n pluginPaths: string[],\n defaultPluginStems: string[] = [],\n actions: DiscoveredAction[] = [],\n workspaceCore: WorkspaceCoreExports | null = null,\n immutableAssetPaths: string[] = [],\n builtAppBasePath = normalizeConfiguredAppBasePath(),\n): string {\n const routeImports: string[] = [];\n const routeRegistrations: string[] = [];\n\n for (let i = 0; i < routes.length; i++) {\n const r = routes[i];\n const varName = `route_${i}`;\n routeImports.push(`import ${varName} from ${JSON.stringify(r.absPath)};`);\n routeRegistrations.push(\n ` app.on(${JSON.stringify(r.method.toUpperCase())}, ${JSON.stringify(r.route)}, ${varName});`,\n );\n if (r.method.toLowerCase() === \"get\") {\n routeRegistrations.push(\n ` app.on(\"HEAD\", ${JSON.stringify(r.route)}, defineEventHandler(async (event) => {\n const originalReq = event.req;\n event.req = requestWithMethod(event.req, \"GET\");\n try {\n const result = await ${varName}(event);\n const response = result instanceof Response ? result : toResponse(result, event);\n return new Response(null, {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n } finally {\n event.req = originalReq;\n }\n }));`,\n );\n }\n }\n\n // Action route imports and registrations\n const actionImports: string[] = [];\n const actionRegistrations: string[] = [];\n for (let i = 0; i < actions.length; i++) {\n const a = actions[i];\n const varName = `action_${i}`;\n actionImports.push(`import ${varName} from ${JSON.stringify(a.absPath)};`);\n // Mirror the runtime mount (action-routes.ts): `path = http?.path ?? name`.\n const routePath = `/_agent-native/actions/${a.path ?? a.name}`;\n actionRegistrations.push(\n ` app.on(${JSON.stringify(a.method.toUpperCase())}, ${JSON.stringify(routePath)}, defineEventHandler(async (event) => {\n const params = ${a.method === \"get\" ? \"parseActionSearchParams(event.url.searchParams)\" : \"(await readBody(event)) ?? {}\"};\n try {\n const result = await ${varName}.run(params, { caller: \"http\" });\n if (typeof result === \"string\") { try { return JSON.parse(result); } catch { return result; } }\n return result;\n } catch (err) {\n return new Response(JSON.stringify({ error: err?.message || \"Action failed\" }), { status: err?.message?.startsWith(\"Invalid action parameters\") ? 400 : 500, headers: { \"Content-Type\": \"application/json\" } });\n }\n }));`,\n );\n }\n\n // Filter out Node-only plugins\n const edgePlugins = pluginPaths.filter((p) => !isNodeOnlyPlugin(p));\n const pluginImports: string[] = [];\n const pluginCalls: string[] = [];\n const providedPluginStems = new Set<string>();\n\n for (let i = 0; i < edgePlugins.length; i++) {\n const varName = `plugin_${i}`;\n providedPluginStems.add(\n path.basename(edgePlugins[i], path.extname(edgePlugins[i])),\n );\n pluginImports.push(\n `import ${varName} from ${JSON.stringify(edgePlugins[i])};`,\n );\n pluginCalls.push(` if (typeof ${varName} === \"function\") {\n await ${varName}(nitroApp);\n }`);\n }\n // Auto-mounted default plugins (for slots the template doesn't override\n // locally). For each slot, prefer a workspace-core export over the\n // @agent-native/core default, if the workspace core provides one.\n const edgeDefaultStems = defaultPluginStems.filter(\n (stem) => !NODE_ONLY_PLUGINS.has(stem),\n );\n for (let i = 0; i < edgeDefaultStems.length; i++) {\n const stem = edgeDefaultStems[i];\n providedPluginStems.add(stem);\n const varName = `defaultPlugin_${i}`;\n\n const workspaceExportName = workspaceCore?.plugins?.[stem as never];\n if (workspaceCore && workspaceExportName) {\n // Workspace-core layer wins over the framework default.\n pluginImports.push(\n `import { ${workspaceExportName} as ${varName} } from ${JSON.stringify(\n `${workspaceCore.packageName}/server`,\n )};`,\n );\n } else {\n // Fall back to the framework default from @agent-native/core.\n const defaultExportName = DEFAULT_PLUGIN_REGISTRY[stem];\n if (!defaultExportName) continue;\n pluginImports.push(\n `import { ${defaultExportName} as ${varName} } from \"@agent-native/core/server\";`,\n );\n }\n pluginCalls.push(` if (typeof ${varName} === \"function\") {\n await ${varName}(nitroApp);\n }`);\n }\n const generatedPluginMarks =\n providedPluginStems.size > 0\n ? [\n ...new Set([\n ...Object.keys(DEFAULT_PLUGIN_REGISTRY),\n ...providedPluginStems,\n ]),\n ]\n : [];\n if (generatedPluginMarks.length > 0) {\n pluginImports.unshift(\n `import { markDefaultPluginProvided as markGeneratedPluginProvided } from \"@agent-native/core/server\";`,\n );\n }\n\n return `\n// Auto-generated worker entry point for ${preset}\nimport { H3, defineEventHandler, readBody, toResponse } from \"h3\";\nimport { createRequestHandler } from \"react-router\";\nimport * as serverBuild from \"./server-build.js\";\n\nfunction normalizeAppBasePath(value) {\n if (!value || value === \"/\") return \"\";\n const trimmed = String(value).trim();\n if (!trimmed || trimmed === \"/\") return \"\";\n return \"/\" + trimmed.replace(/^\\\\/+/, \"\").replace(/\\\\/+$/, \"\");\n}\n\nfunction getAppBasePath() {\n const builtAppBasePath = ${JSON.stringify(builtAppBasePath)};\n return normalizeAppBasePath(\n globalThis.process?.env?.VITE_APP_BASE_PATH ||\n globalThis.process?.env?.APP_BASE_PATH ||\n builtAppBasePath,\n );\n}\n\nfunction stripAppBasePath(pathname) {\n const basePath = getAppBasePath();\n if (!basePath) return pathname;\n if (pathname === basePath) return \"/\";\n if (pathname.startsWith(basePath + \"/\")) {\n return pathname.slice(basePath.length) || \"/\";\n }\n return pathname;\n}\n\nfunction parseActionSearchParams(searchParams) {\n const params = {};\n for (const [rawKey, value] of searchParams.entries()) {\n const isArrayKey = rawKey.endsWith(\"[]\");\n // The core client serializes arrays as key[]=value so one-item arrays\n // survive GET action parsing in generated worker deployments.\n const key = isArrayKey ? rawKey.slice(0, -2) : rawKey;\n const current = params[key];\n if (current === undefined) {\n params[key] = isArrayKey ? [value] : value;\n } else if (Array.isArray(current)) {\n current.push(value);\n } else {\n params[key] = [current, value];\n }\n }\n return params;\n}\n\nfunction isApiPath(pathname) {\n return pathname === \"/api\" || pathname.startsWith(\"/api/\");\n}\n\nfunction isFrameworkPath(pathname) {\n return (\n pathname === \"/_agent-native\" || pathname.startsWith(\"/_agent-native/\")\n );\n}\n\nfunction requestWithMountedApiPrefixStripped(request) {\n const basePath = getAppBasePath();\n if (!basePath) return request;\n const url = new URL(request.url);\n const strippedPathname = stripAppBasePath(url.pathname);\n if (strippedPathname === url.pathname) {\n return request;\n }\n if (!isApiPath(strippedPathname) && !isFrameworkPath(strippedPathname)) {\n return request;\n }\n url.pathname = strippedPathname;\n return new Request(url, request);\n}\n\nfunction prefixMountedPath(path, basePath) {\n if (!basePath || !path.startsWith(\"/\") || path.startsWith(\"//\")) return path;\n if (path === basePath || path.startsWith(basePath + \"/\")) return path;\n return basePath + path;\n}\n\nfunction prefixMountedHtml(html, basePath) {\n if (!basePath) return html;\n return html\n .replace(\n /\\\\b(href|src|action|formaction|poster)=([\"'])(\\\\/(?!\\\\/)[^\"']*)\\\\2/g,\n (_match, attr, quote, path) =>\n attr + \"=\" + quote + prefixMountedPath(path, basePath) + quote,\n )\n .replace(/url\\\\(([\"']?)(\\\\/(?!\\\\/)[^)'\" ]+)\\\\1\\\\)/g, (_match, quote, path) => {\n const q = quote || \"\";\n return \"url(\" + q + prefixMountedPath(path, basePath) + q + \")\";\n });\n}\n\nfunction firstNonEmpty() {\n for (const value of arguments) {\n const trimmed = typeof value === \"string\" ? value.trim() : \"\";\n if (trimmed) return trimmed;\n }\n}\n\nfunction getSentryClientConfigScript() {\n const env = globalThis.process?.env || {};\n const key = firstNonEmpty(env.SENTRY_CLIENT_KEY, env.VITE_SENTRY_CLIENT_KEY);\n const projectId = firstNonEmpty(\n env.SENTRY_PROJECT_ID,\n env.VITE_SENTRY_PROJECT_ID,\n );\n const host = firstNonEmpty(\n env.SENTRY_INGEST_HOST,\n env.VITE_SENTRY_INGEST_HOST,\n );\n const dsn =\n firstNonEmpty(\n env.SENTRY_CLIENT_DSN,\n env.VITE_SENTRY_CLIENT_DSN,\n env.VITE_SENTRY_DSN,\n env.SENTRY_DSN,\n ) || (key && projectId && host ? \"https://\" + key + \"@\" + host + \"/\" + projectId : undefined);\n if (!dsn) return null;\n const config = {\n sentryDsn: dsn,\n sentryEnvironment:\n firstNonEmpty(\n env.SENTRY_ENVIRONMENT,\n env.NETLIFY_CONTEXT,\n env.VERCEL_ENV,\n env.NODE_ENV,\n ) || \"production\",\n };\n return (\n '<script data-agent-native-sentry-config>' +\n 'window.__AGENT_NATIVE_CONFIG__=Object.assign({},window.__AGENT_NATIVE_CONFIG__,' +\n JSON.stringify(config) +\n \");</script>\"\n );\n}\n\nfunction injectHeadScript(html, script) {\n if (!script) return html;\n const headCloseIdx = html.indexOf(\"</head>\");\n if (headCloseIdx === -1) return html;\n return html.slice(0, headCloseIdx) + script + html.slice(headCloseIdx);\n}\n\nconst DEFAULT_SSR_CACHE_CONTROL = ${JSON.stringify(DEFAULT_SSR_CACHE_CONTROL)};\nconst DEFAULT_SSR_CDN_CACHE_CONTROL = ${JSON.stringify(DEFAULT_SSR_CDN_CACHE_CONTROL)};\nconst DEFAULT_SSR_NETLIFY_CDN_CACHE_CONTROL = ${JSON.stringify(DEFAULT_SSR_NETLIFY_CDN_CACHE_CONTROL)};\nconst DEFAULT_SPECULATION_RULES_PATH = ${JSON.stringify(DEFAULT_SPECULATION_RULES_PATH)};\nconst IMMUTABLE_ASSET_CACHE_CONTROL = ${JSON.stringify(IMMUTABLE_ASSET_CACHE_CONTROL)};\nconst IMMUTABLE_ASSET_PATHS = new Set(${JSON.stringify(\n [...new Set(immutableAssetPaths)].sort(),\n )});\nconst AGENT_NATIVE_SOCIAL_IMAGE_PATH = ${JSON.stringify(\n AGENT_NATIVE_SOCIAL_IMAGE_PATH,\n )};\nconst AGENT_NATIVE_SOCIAL_IMAGE_CACHE_BUSTER = ${JSON.stringify(\n AGENT_NATIVE_SOCIAL_IMAGE_CACHE_BUSTER,\n )};\nconst AGENT_NATIVE_SOCIAL_IMAGE_ALT = ${JSON.stringify(\n AGENT_NATIVE_SOCIAL_IMAGE_ALT,\n )};\nconst AGENT_NATIVE_SOCIAL_IMAGE_TYPE = ${JSON.stringify(\n AGENT_NATIVE_SOCIAL_IMAGE_TYPE,\n )};\nconst AGENT_NATIVE_SOCIAL_IMAGE_WIDTH = ${JSON.stringify(\n AGENT_NATIVE_SOCIAL_IMAGE_WIDTH,\n )};\nconst AGENT_NATIVE_SOCIAL_IMAGE_HEIGHT = ${JSON.stringify(\n AGENT_NATIVE_SOCIAL_IMAGE_HEIGHT,\n )};\nconst OG_IMAGE_META_RE = /<meta\\\\b(?=[^>]*\\\\bproperty=([\"'])og:image\\\\1)[^>]*>/i;\nconst TWITTER_CARD_META_RE = /<meta\\\\b(?=[^>]*\\\\bname=([\"'])twitter:card\\\\1)[^>]*>/i;\nconst TWITTER_IMAGE_META_RE = /<meta\\\\b(?=[^>]*\\\\bname=([\"'])twitter:image\\\\1)[^>]*>/i;\n\nfunction withAgentNativeSocialImageCacheBuster(image) {\n const separator = image.includes(\"?\") ? \"&\" : \"?\";\n return image + separator + \"v=\" + encodeURIComponent(AGENT_NATIVE_SOCIAL_IMAGE_CACHE_BUSTER);\n}\n\nfunction defaultSocialImageUrl(request, basePath) {\n return withAgentNativeSocialImageCacheBuster(\n new URL(prefixMountedPath(AGENT_NATIVE_SOCIAL_IMAGE_PATH, basePath), request.url).toString()\n );\n}\n\nfunction injectDefaultSocialImageMeta(html, imageUrl) {\n const headCloseIdx = html.indexOf(\"</head>\");\n if (headCloseIdx === -1) return html;\n\n const hasAnySocialImage =\n OG_IMAGE_META_RE.test(html) || TWITTER_IMAGE_META_RE.test(html);\n const tags = [];\n\n if (!hasAnySocialImage) {\n tags.push('<meta property=\"og:image\" content=\"' + imageUrl + '\">');\n tags.push('<meta property=\"og:image:secure_url\" content=\"' + imageUrl + '\">');\n tags.push('<meta property=\"og:image:type\" content=\"' + AGENT_NATIVE_SOCIAL_IMAGE_TYPE + '\">');\n tags.push('<meta property=\"og:image:width\" content=\"' + AGENT_NATIVE_SOCIAL_IMAGE_WIDTH + '\">');\n tags.push('<meta property=\"og:image:height\" content=\"' + AGENT_NATIVE_SOCIAL_IMAGE_HEIGHT + '\">');\n tags.push('<meta property=\"og:image:alt\" content=\"' + AGENT_NATIVE_SOCIAL_IMAGE_ALT + '\">');\n }\n if (!TWITTER_CARD_META_RE.test(html)) {\n tags.push('<meta name=\"twitter:card\" content=\"summary_large_image\">');\n }\n if (!hasAnySocialImage) {\n tags.push('<meta name=\"twitter:image\" content=\"' + imageUrl + '\">');\n tags.push('<meta name=\"twitter:image:alt\" content=\"' + AGENT_NATIVE_SOCIAL_IMAGE_ALT + '\">');\n }\n\n if (tags.length === 0) return html;\n return html.slice(0, headCloseIdx) + tags.join(\"\") + html.slice(headCloseIdx);\n}\n\nfunction isSsrHtmlOrDataResponse(headers, status, pathname) {\n if (status < 200 || status >= 400) return false;\n const contentType = (headers.get(\"content-type\") || \"\").toLowerCase();\n if (contentType.includes(\"text/html\")) return true;\n return pathname.endsWith(\".data\") && contentType.includes(\"text/x-script\");\n}\n\n/**\n * Apply the SSR cache policy to the response headers.\n *\n * SSR IS A PUBLIC, HARD-CDN-CACHED SHELL — SERVED IDENTICALLY TO EVERYONE.\n * Every SSR HTML / React Router .data response gets the same public\n * stale-while-revalidate policy for ALL visitors, authenticated or not. The SSR\n * output is impersonal (the handler never reads the request's session/cookies),\n * so it is safe to hard-cache one shared copy at the edge. Do NOT reintroduce\n * per-user / cookie-based cache variation here (no private, no no-store, no\n * \"authenticated then don't cache\" branch) — that makes every logged-in\n * visitor's pages uncacheable. Per-user state is resolved client-side instead.\n */\nfunction applyDefaultSsrCacheHeader(headers, status, pathname) {\n if (!isSsrHtmlOrDataResponse(headers, status, pathname)) return;\n\n headers.set(\"cache-control\", DEFAULT_SSR_CACHE_CONTROL);\n headers.set(\"cdn-cache-control\", DEFAULT_SSR_CDN_CACHE_CONTROL);\n // Netlify function responses are dynamic by default and can otherwise show\n // Cache-Status fwd=bypass even with Cache-Control: public. Keep this\n // Netlify-specific header so SSR HTML/.data are served from the shared\n // durable CDN cache instead of stampeding origin — for every visitor.\n headers.set(\"netlify-cdn-cache-control\", DEFAULT_SSR_NETLIFY_CDN_CACHE_CONTROL);\n}\n\nfunction applyDefaultSpeculationRulesHeader(headers, status, basePath) {\n if (status < 200 || status >= 400) return;\n if (headers.has(\"speculation-rules\")) return;\n\n const contentType = (headers.get(\"content-type\") || \"\").toLowerCase();\n if (!contentType.includes(\"text/html\")) return;\n\n // Cloudflare Speed Brain injects Speculation-Rules when origin omits this\n // header. Those browser prefetches carry Sec-Purpose: prefetch and\n // Cloudflare can return 503 before the request reaches origin. Publish an\n // explicit no-op ruleset by default; apps can still provide their own header.\n headers.set(\"speculation-rules\", '\"' + prefixMountedPath(DEFAULT_SPECULATION_RULES_PATH, basePath) + '\"');\n}\nfunction isImmutableAssetRequest(request) {\n const pathname = stripAppBasePath(new URL(request.url).pathname);\n return IMMUTABLE_ASSET_PATHS.has(pathname);\n}\n\nfunction applyImmutableAssetCacheHeaders(response, request) {\n if (!isImmutableAssetRequest(request)) return response;\n if (!((response.status >= 200 && response.status < 300) || response.status === 304)) {\n return response;\n }\n const headers = new Headers(response.headers);\n headers.set(\"Cache-Control\", IMMUTABLE_ASSET_CACHE_CONTROL);\n headers.set(\"CDN-Cache-Control\", IMMUTABLE_ASSET_CACHE_CONTROL);\n headers.set(\"Netlify-CDN-Cache-Control\", IMMUTABLE_ASSET_CACHE_CONTROL);\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n}\n\nasync function rewriteMountedResponse(response, basePath, pathname, request) {\n const sentryClientConfigScript = getSentryClientConfigScript();\n const headers = new Headers(response.headers);\n applyDefaultSsrCacheHeader(headers, response.status, pathname);\n applyDefaultSpeculationRulesHeader(headers, response.status, basePath);\n\n const location = headers.get(\"location\");\n if (location?.startsWith(\"/\") && !location.startsWith(\"//\")) {\n headers.set(\"location\", prefixMountedPath(location, basePath));\n }\n\n const contentType = headers.get(\"content-type\") || \"\";\n if (!contentType.toLowerCase().includes(\"text/html\") || !response.body) {\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n }\n\n const html = await response.text();\n headers.delete(\"content-length\");\n return new Response(\n injectHeadScript(\n injectDefaultSocialImageMeta(\n prefixMountedHtml(html, basePath),\n defaultSocialImageUrl(request, basePath),\n ),\n sentryClientConfigScript,\n ),\n {\n status: response.status,\n statusText: response.statusText,\n headers,\n },\n );\n}\n\nfunction requestWithMethod(request, method) {\n return new Request(request.url, {\n method,\n headers: request.headers,\n signal: request.signal,\n });\n}\n\nfunction requestWithPathname(request, pathname) {\n const url = new URL(request.url);\n if (url.pathname === pathname) return request;\n url.pathname = pathname;\n return new Request(url, request);\n}\n\n// API route handlers\n${routeImports.join(\"\\n\")}\n\n// Action handlers (auto-discovered from actions/)\n${actionImports.join(\"\\n\")}\n\n// Server plugins\n${pluginImports.join(\"\\n\")}\n\nlet _handler;\n\nasync function getHandler() {\n if (_handler) return _handler;\n\n const app = new H3();\n\n // Build a fake nitroApp surface so framework plugins (which expect\n // \\`nitroApp.h3[\"~middleware\"]\\`) can register routes via getH3App().\n const noop = () => {};\n const nitroApp = {\n h3: app,\n hooks: { hook: noop, callHook: noop, hookOnce: noop },\n captureError: noop,\n };\n\n // CORS — applied as global middleware via .use(handler)\n app.use(defineEventHandler((event) => {\n if (event.req.method === \"OPTIONS\") {\n return new Response(null, {\n status: 204,\n headers: {\n \"Access-Control-Allow-Origin\": \"*\",\n \"Access-Control-Allow-Methods\": \"GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS\",\n \"Access-Control-Allow-Headers\": \"Content-Type,Authorization,X-Requested-With,X-Request-Source,X-Agent-Native-CSRF,X-Agent-Native-Embed-Target\",\n },\n });\n }\n }));\n\n // Run plugins — they call getH3App(nitroApp).use(path, handler) which\n // pushes path-prefix middleware onto app[\"~middleware\"].\n // Pre-mark every build-time plugin slot before any plugin awaits the runtime\n // default bootstrap. Bundled serverless workers often lack server/plugins/\n // on disk, so runtime discovery would otherwise auto-mount duplicate\n // framework defaults before later custom plugins get a chance to mark\n // themselves as provided.\n${generatedPluginMarks.map((stem) => ` markGeneratedPluginProvided(nitroApp, ${JSON.stringify(stem)});`).join(\"\\n\")}\n${pluginCalls.join(\"\\n\")}\n\n // Register API routes\n${routeRegistrations.join(\"\\n\")}\n\n // Register action routes (/_agent-native/actions/*)\n${actionRegistrations.join(\"\\n\")}\n\n // SSR catch-all for React Router\n const rrHandler = createRequestHandler(() => serverBuild);\n app.all(\"/**\", defineEventHandler(async (event) => {\n const basePath = getAppBasePath();\n const p = stripAppBasePath(new URL(event.req.url).pathname);\n if (\n p.startsWith(\"/.well-known/\") ||\n p.startsWith(\"/_agent-native/\") ||\n isApiPath(p) ||\n p === \"/favicon.ico\" ||\n p === \"/favicon.png\" ||\n (/\\\\.\\\\w+$/.test(p) && !p.endsWith(\".data\"))\n ) {\n return new Response(null, { status: 404 });\n }\n const request = requestWithPathname(event.req, p);\n if (event.req.method === \"HEAD\") {\n const getRequest = requestWithMethod(request, \"GET\");\n const response = await rrHandler(getRequest);\n return rewriteMountedResponse(\n new Response(null, {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n }),\n basePath,\n p,\n getRequest\n );\n }\n return rewriteMountedResponse(await rrHandler(request), basePath, p, request);\n }));\n\n _handler = app.fetch.bind(app);\n return _handler;\n}\n\nexport default {\n async fetch(request, env, ctx) {\n // Expose env and ctx bindings globally for compatibility\n if (ctx) globalThis.__cf_ctx = ctx;\n if (env) {\n globalThis.process = globalThis.process || { env: {} };\n globalThis.process.env = globalThis.process.env || {};\n // Expose D1/KV/R2 bindings on globalThis.__cf_env for the db layer\n globalThis.__cf_env = env;\n for (const [key, value] of Object.entries(env)) {\n if (typeof value === \"string\") {\n globalThis.process.env[key] = value;\n }\n }\n }\n\n // Try serving static assets first (CF Pages advanced mode).\n // Only attempt this for GET/HEAD — the ASSETS binding is a static file\n // server and returns 405 for any other method, which would short-circuit\n // API calls (PUT/POST/DELETE to /_agent-native/*) before they reach our\n // h3 middleware.\n if (env?.ASSETS && (request.method === \"GET\" || request.method === \"HEAD\")) {\n try {\n const assetResponse = await env.ASSETS.fetch(request);\n if (assetResponse.status !== 404) {\n return applyImmutableAssetCacheHeaders(assetResponse, request);\n }\n } catch {\n // Asset fetch failed — fall through to SSR\n }\n }\n\n const handler = await getHandler();\n return handler(requestWithMountedApiPrefixStripped(request));\n }\n};\n`;\n}\n\n/**\n * Build for Cloudflare Pages.\n * Output structure:\n * dist/\n * _worker.js (bundled worker entry)\n * assets/ (static client assets)\n */\nasync function buildCloudflarePages() {\n generateActionRegistryForProject(cwd);\n\n const buildDir = path.join(cwd, \"build\");\n const clientDir = path.join(buildDir, \"client\");\n const serverDir = path.join(buildDir, \"server\");\n const distDir = path.join(cwd, \"dist\");\n\n // Verify build output exists\n if (!fs.existsSync(clientDir) || !fs.existsSync(serverDir)) {\n console.error(\n \"Build output not found at build/client/ and build/server/. Run react-router build first.\",\n );\n process.exit(1);\n }\n\n // Clean dist\n if (fs.existsSync(distDir)) {\n fs.rmSync(distDir, { recursive: true });\n }\n fs.mkdirSync(distDir, { recursive: true });\n\n // Copy client assets to dist/\n copyDir(clientDir, distDir);\n\n // Exclude _worker.js from being served as a public asset\n fs.writeFileSync(path.join(distDir, \".assetsignore\"), \"_worker.js\\n\");\n\n // Write a package.json inside _worker.js/ to tell wrangler this is a\n // pre-bundled ES module worker — skip re-bundling our esbuild output.\n fs.mkdirSync(path.join(distDir, \"_worker.js\"), { recursive: true });\n fs.writeFileSync(\n path.join(distDir, \"_worker.js\", \"package.json\"),\n JSON.stringify({ main: \"index.js\", type: \"module\" }),\n );\n\n // Create empty stub for native modules that wrangler's bundler needs to resolve\n const stubsDir = path.join(distDir, \"_worker.js\", \"stubs\");\n fs.mkdirSync(stubsDir, { recursive: true });\n fs.writeFileSync(\n path.join(stubsDir, \"empty.js\"),\n \"export default {}; export const watch = () => ({ close() {} }); export const Database = class {};\\n\",\n );\n\n // Discover routes, plugins, actions, and the workspace core (if any).\n const routes = await discoverApiRoutes(cwd);\n const plugins = await discoverPlugins(cwd);\n const actions = await discoverActionFiles(cwd);\n const missingDefaults = await getMissingDefaultPlugins(cwd);\n const workspaceCore = await getWorkspaceCoreExports(cwd);\n\n const workspaceSlotCount = workspaceCore\n ? Object.keys(workspaceCore.plugins).length\n : 0;\n console.log(\n `[deploy] ${routes.length} API routes, ${actions.length} actions, ${plugins.length} plugins (${plugins.filter((p) => isNodeOnlyPlugin(p)).length} skipped as Node-only), ${missingDefaults.length} auto-mounted defaults${workspaceCore ? `, workspace-core ${workspaceCore.packageName} (${workspaceSlotCount} plugin slots)` : \"\"}`,\n );\n\n // Generate the worker entry\n const immutableAssetPaths = collectImmutableAssetPaths(clientDir);\n const entrySource = generateWorkerEntry(\n routes,\n plugins,\n missingDefaults,\n actions,\n workspaceCore,\n immutableAssetPaths,\n );\n\n // Create _worker.js output directory\n const workerOutDir = path.join(distDir, \"_worker.js\");\n fs.mkdirSync(workerOutDir, { recursive: true });\n\n // Write the worker entry\n const entryFile = path.join(workerOutDir, \"index.js\");\n\n // Rewrite the server-build import to point at the copied files\n const adjustedEntry = entrySource.replace(\n `import * as serverBuild from \"./server-build.js\";`,\n `import * as serverBuild from \"./server/index.js\";`,\n );\n\n // Write a temp file for esbuild to bundle everything into a single worker entry.\n // The server build (React Router SSR) is copied to tmp so esbuild can resolve it.\n const tmpDir = path.join(cwd, \".deploy-tmp\");\n fs.mkdirSync(tmpDir, { recursive: true });\n // Name the entry \"index.js\" so esbuild outputs index.js in the outdir,\n // matching the _worker.js/index.js entry point that Cloudflare Pages expects.\n const tmpEntry = path.join(tmpDir, \"index.js\");\n fs.writeFileSync(tmpEntry, adjustedEntry);\n\n // Copy server build files so esbuild can resolve the import\n copyDir(serverDir, path.join(tmpDir, \"server\"));\n\n // Create a require shim so CJS require(\"fs\") calls resolve via ESM imports.\n // This is injected via esbuild --inject to replace its broken __require shim.\n fs.writeFileSync(\n path.join(tmpDir, \"_require-shim.js\"),\n generateRequireShim(),\n );\n\n // Create stub modules for native/Node-only deps that can't run on Workers.\n // These get resolved by esbuild instead of the real modules, avoiding bundling\n // native code that would fail on the Workers runtime.\n const stubModules = [\n \"better-sqlite3\",\n \"node-pty\",\n \"chokidar\",\n \"fsevents\",\n \"dotenv\",\n \"@anthropic-ai/sdk\",\n ];\n const stubDir = path.join(tmpDir, \"node_modules\");\n for (const mod of stubModules) {\n const modDir = path.join(stubDir, mod);\n fs.mkdirSync(modDir, { recursive: true });\n fs.writeFileSync(\n path.join(modDir, \"index.js\"),\n `export default {}; export const watch = () => ({ close() {} });`,\n );\n fs.writeFileSync(\n path.join(modDir, \"package.json\"),\n JSON.stringify({ name: mod, main: \"index.js\", type: \"module\" }),\n );\n }\n\n const esbuildBin = findEsbuild();\n\n // Externalize node builtins (both bare and node: prefixed) — the require\n // shim handles bare ones. Also alias every `node:*` specifier to its bare\n // name so esbuild emits `import from \"fs\"` everywhere, never\n // `import from \"node:fs\"`. CF Pages Functions (wrangler 3.x, nodejs_compat\n // v1) rejects the `node:` prefix in chunks with:\n // No such module \"node:fs\" imported from chunks/...\n // The alias is the authoritative fix; the post-build strip stays as belt\n // & suspenders in case esbuild emits a node: string via some other path.\n const builtinNames = getNodeBuiltinNames();\n // Only externalize bare names. node:* externals would otherwise pin\n // the prefix in output; instead we alias node:* → bare so anything that\n // resolves past alias land as bare externals.\n const nodeExternals = builtinNames.map((n) => `--external:${n}`);\n const nodeAliases = builtinNames.map((n) => `--alias:node:${n}=${n}`);\n\n // Hard externalize large client-only / node-only libraries so they don't\n // bloat the edge worker. These are never executed in the CF Pages runtime\n // — mermaid/excalidraw render in the browser, pdf-parse and @google/genai\n // run from node-only action scripts. Without this, slides' bundle hits\n // the 25 MiB Pages Functions limit.\n //\n // @anthropic-ai/tokenizer (tiktoken .wasm) and @resvg/resvg-js (native\n // .node binding) can't be bundled by esbuild at all — no loader for those\n // files. Both import sites degrade gracefully when the runtime import\n // fails: context-xray token counts fall back to char/4 estimates and the\n // OG image route falls back to SVG.\n const heavyClientExternals = [\n \"mermaid\",\n \"@excalidraw/excalidraw\",\n \"@excalidraw/mermaid-to-excalidraw\",\n \"pdf-parse\",\n \"pdfjs-dist\",\n \"@google/genai\",\n \"chartjs-node-canvas\",\n \"@napi-rs/canvas\",\n \"@anthropic-ai/tokenizer\",\n \"@resvg/resvg-js\",\n ].map((p) => `--external:${p}`);\n\n execFileSync(\n esbuildBin,\n [\n tmpEntry,\n \"--bundle\",\n \"--format=esm\",\n \"--target=es2022\",\n // browser platform for npm resolution; node builtins externalized separately\n \"--platform=browser\",\n \"--minify\",\n // Single-file bundle (no --splitting). CF Pages Functions' deploy\n // validator fails to load chunked _worker.js/ bundles even when the\n // chunks contain only bare node-builtin imports (wrangler 3.101.0\n // + nodejs_compat v2). Matches main's working config.\n `--outdir=${workerOutDir}`,\n \"--conditions=workerd,worker,import\",\n // The ssr-handler imports a virtual module that only exists at dev time\n \"--external:virtual:react-router/server-build\",\n // Banner: override the __require shim that esbuild generates for CJS modules.\n // This provides a real require() backed by ESM imports of node builtins.\n // Without this, CF Workers rejects the bundle because esbuild's default\n // __require shim throws \"Dynamic require of X is not supported\".\n `--banner:js=${generateRequireShim()}`,\n // Externalize node: builtins — CF Workers runtime provides them\n ...nodeExternals,\n ...heavyClientExternals,\n // Rewrite node:* -> bare names so chunks never contain node: imports\n ...nodeAliases,\n ],\n { stdio: \"inherit\", cwd },\n );\n\n // Clean up tmp\n fs.rmSync(tmpDir, { recursive: true });\n\n // Rewrite the external virtual import to a local stub.\n // esbuild externalizes \"virtual:react-router/server-build\" (used by ssr-handler),\n // but wrangler re-bundles and chokes on it. Replace the import with a no-op stub.\n const virtualStub = path.join(workerOutDir, \"chunks\", \"_virtual-stub.js\");\n fs.mkdirSync(path.dirname(virtualStub), { recursive: true });\n fs.writeFileSync(virtualStub, \"export default {};\\n\");\n\n // Post-build patches — apply to ALL .js files in the worker output directory\n // (entry + chunks) since code can land in any chunk after splitting.\n const allJsFiles = getAllJsFiles(workerOutDir);\n for (const jsFile of allJsFiles) {\n let code = fs.readFileSync(jsFile, \"utf-8\");\n const isEntry = path.basename(jsFile) === \"index.js\";\n\n // Strip \"node:\" prefix from all imports/requires. Cloudflare Pages\n // Functions runs under nodejs_compat v1, which exposes builtins as\n // bare names (\"fs\") and rejects \"node:fs\" at worker init:\n // No such module \"node:fs\" imported from chunks/...\n // (Workers-on-the-edge use v2 and require the prefix; Pages lags.)\n // Preserve the original quote char (single vs double) when rewriting —\n // esbuild's minifier sometimes places `import('node:buffer')` inside a\n // double-quoted string literal; swapping to double quotes breaks the\n // outer literal and produces `Unexpected identifier 'buffer'`.\n code = code.replace(\n /\\bfrom(\\s*)([\"'])node:([^\"']+)\\2/g,\n (_, ws, q, mod) => `from${ws}${q}${mod}${q}`,\n );\n code = code.replace(\n /\\bimport(\\s*)([\"'])node:([^\"']+)\\2/g,\n (_, ws, q, mod) => `import${ws}${q}${mod}${q}`,\n );\n // Strip `node:` prefix from any string literal that names a node\n // builtin. Covers dynamic imports, require(), getBuiltinModule(),\n // and minified wrappers like `Ut(\"node:fs\")` that Nitro/h3 emit.\n // Pages' loader scans chunks for `\"node:*\"` literals and fails with\n // 'No such module \"node:fs\"' whether or not the string is reached\n // at runtime. Scoping to known builtins avoids touching user data.\n // Sorted longest-first so `fs/promises` matches before `fs`.\n const builtinsPattern = [...NODE_BUILTINS]\n .sort((a, b) => b.length - a.length)\n .join(\"|\");\n const builtinRe = new RegExp(`([\"'])node:(${builtinsPattern})\\\\1`, \"g\");\n code = code.replace(\n builtinRe,\n (_, q: string, mod: string) => `${q}${mod}${q}`,\n );\n\n // Rewrite virtual:react-router/server-build imports to the local stub.\n // The generated entry handles SSR directly; this import is dead code from ssr-handler.\n const relStub = path\n .relative(path.dirname(jsFile), virtualStub)\n .replace(/\\\\/g, \"/\");\n code = code.replace(\n /[\"']virtual:react-router\\/server-build[\"']/g,\n `\"./${relStub}\"`,\n );\n\n // Patch createRequire(import.meta.url) — import.meta.url is undefined in CF Workers.\n // Matches both `from \"module\"` and `from \"node:module\"` — with the node:\n // prefix preserved (for nodejs_compat_v2), the latter is what esbuild now emits.\n code = code.replace(\n /\\bimport\\s*\\{\\s*createRequire\\s+as\\s+([\\w$]+)\\s*\\}\\s*from\\s*[\"'](?:node:)?module[\"']\\s*;/g,\n \"var $1 = function() { return typeof require !== 'undefined' ? require : function(m) { throw new Error('require not supported: ' + m); }; };\",\n );\n\n // Patch setInterval/setTimeout at module scope — CF Workers disallows timers in global scope.\n // Some dependencies (e.g. Anthropic SDK rate limiter) call setInterval at module init.\n // With code splitting, chunks evaluate before the entry, so the shim must be in every file.\n // The restore only happens in the entry's fetch() handler.\n if (!code.includes(\"__origSetInterval\")) {\n const timerShim = [\n \"var __origSetInterval=globalThis.setInterval;\",\n \"globalThis.setInterval=function(){return{unref(){},ref(){},close(){}}};\",\n ].join(\"\");\n code = timerShim + code;\n }\n if (isEntry) {\n const timerRestore =\n \"if(__origSetInterval)globalThis.setInterval=__origSetInterval;\";\n code = code.replace(\n /async fetch\\(request,\\s*env,\\s*ctx\\)\\s*\\{/,\n (match) => match + timerRestore,\n );\n }\n\n fs.writeFileSync(jsFile, code);\n }\n\n // Report size\n const entrySize = fs.statSync(entryFile).size;\n const totalSize = getDirSize(workerOutDir);\n const chunkCount = allJsFiles.length - 1; // exclude entry\n console.log(\n `[deploy] Cloudflare Pages output written to dist/ (entry: ${(entrySize / 1024).toFixed(0)}KB, ${chunkCount} chunks, total: ${(totalSize / 1024 / 1024).toFixed(1)}MB)`,\n );\n}\n\nconst NODE_BUILTINS = [\n \"assert\",\n \"async_hooks\",\n \"buffer\",\n \"child_process\",\n \"cluster\",\n \"console\",\n \"constants\",\n \"crypto\",\n \"dgram\",\n \"diagnostics_channel\",\n \"dns\",\n \"domain\",\n \"events\",\n \"fs\",\n \"fs/promises\",\n \"http\",\n \"http2\",\n \"https\",\n \"inspector\",\n \"module\",\n \"net\",\n \"os\",\n \"path\",\n \"perf_hooks\",\n \"process\",\n \"punycode\",\n \"querystring\",\n \"readline\",\n \"repl\",\n \"sqlite\",\n \"stream\",\n \"stream/web\",\n \"string_decoder\",\n \"sys\",\n \"timers\",\n \"tls\",\n \"trace_events\",\n \"tty\",\n \"url\",\n \"util\",\n \"v8\",\n \"vm\",\n \"wasi\",\n \"worker_threads\",\n \"zlib\",\n];\n\nexport function getNodeBuiltinNames(): string[] {\n return NODE_BUILTINS;\n}\n\n/**\n * Generate a require() shim that bridges CJS require(\"fs\") calls to ESM imports.\n * Injected via esbuild --inject so CJS deps work on Workers runtime.\n */\nfunction generateRequireShim(): string {\n // Shim the full set of node builtins so any CJS `require(\"X\")` from a\n // transitive dep resolves to the imported ESM module. Anything less is\n // whack-a-mole: terminal helpers pull in `tty`, transformer libs pull in\n // `worker_threads`, etc. — every miss fails deploy with a generic\n // \"Cannot require: <name>\" thrown by this shim itself.\n //\n // Some builtins exist only as runtime polyfills under nodejs_compat\n // (some are no-op stubs). That's fine — the `import` returns whatever\n // the runtime provides; failures only surface when callers actually USE\n // the unsupported APIs at request time, which is the same as if the\n // shim wasn't there.\n //\n // `sqlite` is excluded because it's Node 22+ only and Workers'\n // nodejs_compat doesn't expose it yet — importing it makes the whole\n // bundle fail to load.\n const shimmed = NODE_BUILTINS.filter((name) => name !== \"sqlite\");\n\n // Bare module names — CF Pages Functions runs under nodejs_compat v1,\n // which rejects \"node:fs\" and only accepts \"fs\". The post-build pass in\n // buildCloudflarePages() also strips any `node:` prefix that esbuild or\n // dependencies emit elsewhere.\n const imports = shimmed\n .map((m) => `import __${m.replace(\"/\", \"_\")} from \"${m}\";`)\n .join(\"\");\n // Only bare-name keys. Pages' Functions loader appears to scan chunks\n // for \"node:*\" string literals and pre-resolves them as module specs —\n // so keeping \"node:fs\" as an object key caused deploy to fail with\n // 'No such module \"node:fs\"' even though nothing imported it. The\n // post-build strip turns every runtime `require(\"node:fs\")` into\n // `require(\"fs\")` so bare keys are sufficient.\n const entries = shimmed\n .map((m) => `\"${m}\":__${m.replace(\"/\", \"_\")}`)\n .join(\",\");\n\n const messageChannelPolyfill = `if(typeof MessageChannel===\"undefined\"){globalThis.MessageChannel=class{constructor(){const a={onmessage:null},b={onmessage:null};a.postMessage=d=>{if(b.onmessage)setTimeout(()=>b.onmessage({data:d}),0)};b.postMessage=d=>{if(a.onmessage)setTimeout(()=>a.onmessage({data:d}),0)};this.port1=a;this.port2=b}}}`;\n return `${imports}\\n${messageChannelPolyfill}\\nconst __mods={${entries}};export var require=globalThis.require||function(m){const r=__mods[m];if(r!==undefined)return r;throw new Error(\"Cannot require: \"+m)};\\n`;\n}\n\nfunction findEsbuild(): string {\n // Try to resolve esbuild's binary via Node module resolution\n // This works regardless of hoisting or .bin symlink creation\n try {\n const _require = createRequire(cwd + \"/\");\n const esbuildPkg = path.dirname(_require.resolve(\"esbuild/package.json\"));\n const bin = path.join(esbuildPkg, \"bin\", \"esbuild\");\n if (fs.existsSync(bin)) return bin;\n } catch {}\n\n // Fallback: check local and workspace .bin\n const localBin = path.resolve(cwd, \"node_modules/.bin/esbuild\");\n if (fs.existsSync(localBin)) return localBin;\n\n const workspaceRoot = findWorkspaceRoot(cwd);\n if (workspaceRoot) {\n const workspaceBin = path.resolve(\n workspaceRoot,\n \"node_modules/.bin/esbuild\",\n );\n if (fs.existsSync(workspaceBin)) return workspaceBin;\n }\n\n return \"esbuild\";\n}\n\nfunction findWorkspaceRoot(dir: string): string | null {\n let current = dir;\n while (current !== path.dirname(current)) {\n if (\n fs.existsSync(path.join(current, \"pnpm-workspace.yaml\")) ||\n fs.existsSync(path.join(current, \"pnpm-lock.yaml\"))\n ) {\n return current;\n }\n current = path.dirname(current);\n }\n return null;\n}\n\n/** Recursively collect all .js files in a directory. */\nfunction getAllJsFiles(dir: string): string[] {\n const results: string[] = [];\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n results.push(...getAllJsFiles(fullPath));\n } else if (entry.name.endsWith(\".js\")) {\n results.push(fullPath);\n }\n }\n return results;\n}\n\nfunction getDirSize(dir: string): number {\n let size = 0;\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n size += getDirSize(fullPath);\n } else {\n size += fs.statSync(fullPath).size;\n }\n }\n return size;\n}\n\nexport function copyDir(\n src: string,\n dest: string,\n ancestorRealPaths = new Set<string>(),\n) {\n const realSrc = fs.realpathSync(src);\n if (ancestorRealPaths.has(realSrc)) return;\n const nextAncestorRealPaths = new Set(ancestorRealPaths);\n nextAncestorRealPaths.add(realSrc);\n\n fs.mkdirSync(dest, { recursive: true });\n const entries = fs.readdirSync(src, { withFileTypes: true });\n for (const entry of entries) {\n const srcPath = path.join(src, entry.name);\n const destPath = path.join(dest, entry.name);\n if (entry.isSymbolicLink()) {\n let stat: fs.Stats;\n try {\n stat = fs.statSync(srcPath);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n console.warn(\n `[deploy] Skipping broken symlink while copying ${srcPath}`,\n );\n continue;\n }\n throw error;\n }\n if (stat.isDirectory()) {\n copyDir(srcPath, destPath, nextAncestorRealPaths);\n } else {\n fs.copyFileSync(srcPath, destPath);\n }\n } else if (entry.isDirectory()) {\n copyDir(srcPath, destPath, nextAncestorRealPaths);\n } else {\n fs.copyFileSync(srcPath, destPath);\n }\n }\n}\n\nconst LIBSQL_NATIVE_PACKAGE_NAMES = [\n \"darwin-arm64\",\n \"darwin-x64\",\n \"linux-arm-gnueabihf\",\n \"linux-arm-musleabihf\",\n \"linux-arm64-gnu\",\n \"linux-arm64-musl\",\n \"linux-x64-gnu\",\n \"linux-x64-musl\",\n \"win32-x64-msvc\",\n];\nconst FFMPEG_STATIC_PACKAGE_NAME = \"ffmpeg-static\";\nconst RESVG_SCOPE = \"@resvg\";\nconst RESVG_PACKAGE_PREFIX = \"resvg-js\";\nconst FFMPEG_STATIC_BINARY_NAMES =\n process.platform === \"win32\" ? [\"ffmpeg.exe\", \"ffmpeg\"] : [\"ffmpeg\"];\nconst SERVERLESS_FFMPEG_STATIC_PLATFORM = \"linux\";\nconst SERVERLESS_FFMPEG_STATIC_ARCHES = new Set<NodeJS.Architecture>([\n \"arm64\",\n \"x64\",\n]);\ntype ServerlessFfmpegStaticArch = \"arm64\" | \"x64\";\n\nfunction serverlessFfmpegStaticTargetArchFromEnv(): ServerlessFfmpegStaticArch | null {\n const value = process.env.AGENT_NATIVE_SERVERLESS_FFMPEG_ARCH;\n if (value === \"arm64\" || value === \"x64\") return value;\n return null;\n}\n\nexport function shouldBundleFfmpegStaticForServerless(\n hostPlatform: NodeJS.Platform = process.platform,\n hostArch: NodeJS.Architecture = process.arch,\n targetArch: ServerlessFfmpegStaticArch | null = serverlessFfmpegStaticTargetArchFromEnv(),\n): boolean {\n return (\n hostPlatform === SERVERLESS_FFMPEG_STATIC_PLATFORM &&\n targetArch !== null &&\n hostArch === targetArch &&\n SERVERLESS_FFMPEG_STATIC_ARCHES.has(targetArch)\n );\n}\n\nfunction nodeModulesAncestors(startDir: string): string[] {\n const dirs: string[] = [];\n let current = path.resolve(startDir);\n while (true) {\n const candidate = path.join(current, \"node_modules\");\n if (fs.existsSync(candidate)) dirs.push(candidate);\n const parent = path.dirname(current);\n if (parent === current) break;\n current = parent;\n }\n return dirs;\n}\n\nfunction findInstalledLibsqlNativePackage(\n nodeModulesRoots: string[],\n packageName: string,\n): string | null {\n for (const root of nodeModulesRoots) {\n const direct = path.join(root, \"@libsql\", packageName);\n if (fs.existsSync(path.join(direct, \"index.node\"))) return direct;\n\n const pnpmRoot = path.join(root, \".pnpm\");\n if (!fs.existsSync(pnpmRoot)) continue;\n const pnpmPrefix = `@libsql+${packageName}@`;\n for (const entry of fs.readdirSync(pnpmRoot)) {\n if (!entry.startsWith(pnpmPrefix)) continue;\n const nested = path.join(\n pnpmRoot,\n entry,\n \"node_modules\",\n \"@libsql\",\n packageName,\n );\n if (fs.existsSync(path.join(nested, \"index.node\"))) return nested;\n }\n }\n return null;\n}\n\nfunction hasFfmpegStaticBinary(packageDir: string): boolean {\n return FFMPEG_STATIC_BINARY_NAMES.some((binaryName) =>\n fs.existsSync(path.join(packageDir, binaryName)),\n );\n}\n\nfunction hasInstalledFfmpegStaticPackage(nodeModulesRoots: string[]): boolean {\n for (const root of nodeModulesRoots) {\n const direct = path.join(root, FFMPEG_STATIC_PACKAGE_NAME);\n if (fs.existsSync(path.join(direct, \"package.json\"))) return true;\n\n const pnpmRoot = path.join(root, \".pnpm\");\n if (!fs.existsSync(pnpmRoot)) continue;\n const pnpmPrefix = `${FFMPEG_STATIC_PACKAGE_NAME}@`;\n for (const entry of fs.readdirSync(pnpmRoot)) {\n if (!entry.startsWith(pnpmPrefix)) continue;\n const nested = path.join(\n pnpmRoot,\n entry,\n \"node_modules\",\n FFMPEG_STATIC_PACKAGE_NAME,\n );\n if (fs.existsSync(path.join(nested, \"package.json\"))) return true;\n }\n }\n return false;\n}\n\nexport function findInstalledFfmpegStaticPackage(\n nodeModulesRoots: string[],\n): string | null {\n for (const root of nodeModulesRoots) {\n const direct = path.join(root, FFMPEG_STATIC_PACKAGE_NAME);\n if (\n fs.existsSync(path.join(direct, \"package.json\")) &&\n hasFfmpegStaticBinary(direct)\n ) {\n return direct;\n }\n\n const pnpmRoot = path.join(root, \".pnpm\");\n if (!fs.existsSync(pnpmRoot)) continue;\n const pnpmPrefix = `${FFMPEG_STATIC_PACKAGE_NAME}@`;\n for (const entry of fs.readdirSync(pnpmRoot)) {\n if (!entry.startsWith(pnpmPrefix)) continue;\n const nested = path.join(\n pnpmRoot,\n entry,\n \"node_modules\",\n FFMPEG_STATIC_PACKAGE_NAME,\n );\n if (\n fs.existsSync(path.join(nested, \"package.json\")) &&\n hasFfmpegStaticBinary(nested)\n ) {\n return nested;\n }\n }\n }\n return null;\n}\n\nexport function findInstalledResvgPackages(\n nodeModulesRoots: string[],\n): Array<{ packageName: string; packageDir: string }> {\n const found = new Map<string, string>();\n\n for (const root of nodeModulesRoots) {\n const directScope = path.join(root, RESVG_SCOPE);\n if (fs.existsSync(directScope)) {\n for (const entry of fs.readdirSync(directScope)) {\n if (!entry.startsWith(RESVG_PACKAGE_PREFIX)) continue;\n const packageDir = path.join(directScope, entry);\n if (fs.existsSync(path.join(packageDir, \"package.json\"))) {\n found.set(entry, packageDir);\n }\n }\n }\n\n const pnpmRoot = path.join(root, \".pnpm\");\n if (!fs.existsSync(pnpmRoot)) continue;\n for (const entry of fs.readdirSync(pnpmRoot)) {\n const match = entry.match(/^@resvg\\+(resvg-js[^@]*)@/);\n if (!match) continue;\n const packageName = match[1];\n const packageDir = path.join(\n pnpmRoot,\n entry,\n \"node_modules\",\n RESVG_SCOPE,\n packageName,\n );\n if (fs.existsSync(path.join(packageDir, \"package.json\"))) {\n found.set(packageName, packageDir);\n }\n }\n }\n\n return [...found.entries()]\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([packageName, packageDir]) => ({ packageName, packageDir }));\n}\n\nfunction copyInstalledLibsqlNativePackages(serverDir: string | undefined) {\n if (!serverDir || !fs.existsSync(serverDir)) return;\n const nodeModulesRoots = nodeModulesAncestors(cwd);\n const destScopeDir = path.join(serverDir, \"node_modules\", \"@libsql\");\n let copied = 0;\n\n for (const packageName of LIBSQL_NATIVE_PACKAGE_NAMES) {\n const src = findInstalledLibsqlNativePackage(nodeModulesRoots, packageName);\n if (!src) continue;\n\n copyDir(src, path.join(destScopeDir, packageName));\n copied += 1;\n }\n\n if (copied > 0) {\n console.log(\n `[deploy] Copied ${copied} installed libsql native package(s) into the server bundle.`,\n );\n }\n}\n\nfunction copyInstalledResvgPackages(serverDir: string | undefined) {\n if (!serverDir || !fs.existsSync(serverDir)) return;\n const packages = findInstalledResvgPackages(nodeModulesAncestors(cwd));\n if (packages.length === 0) return;\n\n const destScopeDir = path.join(serverDir, \"node_modules\", RESVG_SCOPE);\n for (const { packageName, packageDir } of packages) {\n copyDir(packageDir, path.join(destScopeDir, packageName));\n }\n\n console.log(\n `[deploy] Copied ${packages.length} resvg package(s) into the server bundle for OG image rendering.`,\n );\n}\n\nfunction copyInstalledFfmpegStaticPackage(serverDir: string | undefined) {\n if (!serverDir || !fs.existsSync(serverDir)) return;\n const nodeModulesRoots = nodeModulesAncestors(cwd);\n if (!shouldBundleFfmpegStaticForServerless()) {\n if (hasInstalledFfmpegStaticPackage(nodeModulesRoots)) {\n console.warn(\n `[deploy] ffmpeg-static installs a ${process.platform}-${process.arch} binary, but the serverless runtime architecture is not known to match it; ` +\n \"set AGENT_NATIVE_SERVERLESS_FFMPEG_ARCH=x64 or arm64 to bundle a matching binary, otherwise server-side media transcription fallback will require FFMPEG_PATH or a system ffmpeg.\",\n );\n }\n return;\n }\n\n const src = findInstalledFfmpegStaticPackage(nodeModulesRoots);\n if (!src) {\n if (hasInstalledFfmpegStaticPackage(nodeModulesRoots)) {\n console.warn(\n \"[deploy] ffmpeg-static is installed without a downloaded ffmpeg binary; \" +\n \"server-side media transcription fallback will require FFMPEG_PATH or a system ffmpeg.\",\n );\n }\n return;\n }\n\n copyDir(\n src,\n path.join(serverDir, \"node_modules\", FFMPEG_STATIC_PACKAGE_NAME),\n );\n console.log(\n \"[deploy] Copied ffmpeg-static into the server bundle for media transcription fallback.\",\n );\n}\n\n/**\n * Create stub directories for dangling platform-specific optional dependency\n * symlinks in the pnpm store.\n *\n * pnpm's store at `node_modules/.pnpm/<pkg>@<ver>/node_modules/<pkg>/<dep>`\n * contains symlinks for ALL optional deps declared by a package, but only\n * installs the ones matching the current OS/CPU as real packages. The other\n * symlinks dangle — their targets at `.pnpm/<scope>+<pkg>@<ver>/node_modules/...`\n * don't exist.\n *\n * Nitro's `nitro:externals` plugin (via nf3 / @vercel/nft) walks\n * optionalDependencies when tracing files and calls `realpath` on them, which\n * throws ENOENT on dangling targets. This blocks builds with presets like\n * netlify / vercel / aws-lambda on macOS when packages like `libsql` declare\n * Linux-only platform variants as optional deps.\n *\n * Fix: walk `node_modules/.pnpm/` and for every dangling symlink under\n * `<pkg>/node_modules/<scope>/<dep>`, create the symlink's target as a tiny\n * stub directory containing just a valid `package.json`. The tracer can now\n * `realpath` and read the package.json without throwing — the stub is empty\n * so no binary is bundled (which is what we want: we're building from macOS,\n * the target deploy platform will install its own native binary).\n */\nfunction createDanglingOptionalDepStubs() {\n // In pnpm monorepos, the store may live at the workspace root rather than\n // in the template dir. Walk up from `cwd` to find every `.pnpm` directory.\n const pnpmRoots: string[] = [];\n let dir = cwd;\n while (true) {\n const candidate = path.join(dir, \"node_modules\", \".pnpm\");\n if (fs.existsSync(candidate)) pnpmRoots.push(candidate);\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n if (pnpmRoots.length === 0) return;\n\n let stubsCreated = 0;\n\n for (const pnpmRoot of pnpmRoots) {\n let pkgDirs: string[];\n try {\n pkgDirs = fs.readdirSync(pnpmRoot);\n } catch {\n continue;\n }\n\n for (const pkgDir of pkgDirs) {\n // e.g. `libsql@0.5.29`, `@libsql+client@0.15.15`\n const innerNm = path.join(pnpmRoot, pkgDir, \"node_modules\");\n if (!fs.existsSync(innerNm)) continue;\n\n let innerEntries: fs.Dirent[];\n try {\n innerEntries = fs.readdirSync(innerNm, { withFileTypes: true });\n } catch {\n continue;\n }\n\n for (const entry of innerEntries) {\n // Top-level entry: either `foo` (unscoped) or `@scope` (scoped)\n const entryPath = path.join(innerNm, entry.name);\n const candidates: { symlinkPath: string; pkgName: string }[] = [];\n if (entry.name.startsWith(\"@\")) {\n // Scoped — iterate children\n let scopedChildren: fs.Dirent[];\n try {\n scopedChildren = fs.readdirSync(entryPath, {\n withFileTypes: true,\n });\n } catch {\n continue;\n }\n for (const child of scopedChildren) {\n candidates.push({\n symlinkPath: path.join(entryPath, child.name),\n pkgName: `${entry.name}/${child.name}`,\n });\n }\n } else {\n candidates.push({ symlinkPath: entryPath, pkgName: entry.name });\n }\n\n for (const { symlinkPath, pkgName } of candidates) {\n let isSymlink = false;\n try {\n isSymlink = fs.lstatSync(symlinkPath).isSymbolicLink();\n } catch {\n continue;\n }\n if (!isSymlink) continue;\n\n // Check if the symlink target exists\n try {\n fs.statSync(symlinkPath);\n continue; // Target exists — nothing to do\n } catch {\n // Dangling symlink — create a stub at the target\n }\n\n let linkTarget: string;\n try {\n linkTarget = fs.readlinkSync(symlinkPath);\n } catch {\n continue;\n }\n const resolvedTarget = path.resolve(\n path.dirname(symlinkPath),\n linkTarget,\n );\n\n try {\n fs.mkdirSync(resolvedTarget, { recursive: true });\n const stubPkgJson = {\n name: pkgName,\n version: \"0.0.0-stub\",\n description:\n \"Empty stub created by @agent-native/core deploy build to satisfy nitro's file tracer on platforms where this optional dep is not installed.\",\n };\n fs.writeFileSync(\n path.join(resolvedTarget, \"package.json\"),\n JSON.stringify(stubPkgJson, null, 2),\n );\n stubsCreated++;\n } catch {\n // Best-effort — ignore failures\n }\n }\n }\n }\n }\n\n if (stubsCreated > 0) {\n console.log(\n `[deploy] Created ${stubsCreated} stub package dir(s) for dangling optional deps (platform-specific binaries not installed on this host).`,\n );\n }\n}\n\n/**\n * Build for any non-Cloudflare preset using Nitro's programmatic build API.\n * Handles netlify, vercel, deno_deploy, aws-lambda, and all other targets.\n */\nexport interface NitroBuildHooks {\n prepare: (nitro: any) => Promise<void>;\n copyPublicAssets: (nitro: any) => Promise<void>;\n nitroBuild: (nitro: any) => Promise<void>;\n}\n\nexport interface NitroBuildPipelineOptions {\n nitro: any;\n hooks: NitroBuildHooks;\n clientDir: string;\n publicOutputDir: string | undefined;\n appBasePath: string;\n cwd: string;\n}\n\n/**\n * Run Nitro's lifecycle in the order required to ship a working React Router\n * framework-mode build.\n *\n * The critical ordering constraint is that the React Router client build must\n * be copied into `publicOutputDir` *before* `nitroBuild` runs. Nitro generates\n * the static-asset manifest baked into the server bundle by globbing\n * `publicDir` during the server build; files copied in after that point exist\n * on disk but are invisible to the runtime `serveStatic` handler. Every\n * /assets/* request then falls through to the SSR catch-all, which 404s\n * anything with a file extension.\n */\nexport async function runNitroBuildPipeline(\n opts: NitroBuildPipelineOptions,\n): Promise<void> {\n const { nitro, hooks, clientDir, publicOutputDir, appBasePath, cwd } = opts;\n const hasClientBuild = fs.existsSync(clientDir) && Boolean(publicOutputDir);\n\n if (hasClientBuild) {\n // Install hashed-asset route rules before Nitro prepares platform output.\n // Some presets materialize headers during prepare/copy phases, not only in\n // nitroBuild; adding these later leaves Netlify/Vercel static assets without\n // the one-year immutable CDN policy even though the runtime manifest works.\n nitro.options.routeRules ??= {};\n addImmutableAssetRouteRulesForClientBuild(\n nitro.options.routeRules,\n clientDir,\n appBasePath,\n );\n }\n\n await hooks.prepare(nitro);\n await hooks.copyPublicAssets(nitro);\n\n if (hasClientBuild && publicOutputDir) {\n copyDir(clientDir, publicOutputDir);\n if (appBasePath) {\n copyDir(clientDir, path.join(publicOutputDir, appBasePath.slice(1)));\n }\n console.log(\n `[deploy] Copied client assets to ${path.relative(cwd, publicOutputDir)}`,\n );\n }\n\n await hooks.nitroBuild(nitro);\n}\n\n/**\n * Browser-only diagram/drawing renderers that execute `window`-touching code at\n * module-evaluation time. They are rendered exclusively client-side — core's\n * `MermaidBlock` and templates' Excalidraw slides mount them inside `useEffect` /\n * `React.lazy`, never during SSR — so the server never needs the real module.\n *\n * Keep this list to libraries that are *provably never* invoked on the server.\n * Node-only deps that DO run server-side (pdf-parse, @google/genai, canvas, …)\n * must NOT go here — see `heavyClientExternals` for the edge-worker externals.\n */\nconst BROWSER_ONLY_SERVER_LIBS = [\n \"@excalidraw/excalidraw\",\n \"@excalidraw/mermaid-to-excalidraw\",\n \"mermaid\",\n];\n\n/**\n * Rolldown plugin for the Nitro server bundle that replaces the browser-only\n * renderers above with an inert proxy module.\n *\n * Why this is needed: Nitro re-bundles the server from node_modules with its own\n * Rolldown pipeline, and Rolldown merges Excalidraw into a SHARED vendor chunk\n * that the SSR render path (tiptap / radix-ui / recharts) imports *statically*.\n * That evaluates Excalidraw's top-level `window` access at function cold-start\n * and crashes every request with `ReferenceError: window is not defined` (HTTP\n * 502). The Vite SSR build already stubs these via `ssrStubPlugin` for\n * `build/server`, but that Vite plugin doesn't run during Nitro's separate\n * bundle — so mirror the same stub here.\n */\nfunction createBrowserOnlyServerStubPlugin() {\n const stubbed = new Set(BROWSER_ONLY_SERVER_LIBS);\n const STUB_ID = \"\\0agent-native-browser-only-server-stub\";\n return {\n name: \"agent-native-browser-only-server-stub\",\n // enforce: \"pre\" so we intercept before Nitro's node resolver bundles the\n // real package. defu concatenates rollupConfig.plugins ahead of Nitro's own.\n resolveId(id: string) {\n // Match the bare package name or any subpath (incl. `/index.css`).\n const pkg = id\n .split(\"/\")\n .slice(0, id.startsWith(\"@\") ? 2 : 1)\n .join(\"/\");\n return stubbed.has(pkg) ? STUB_ID : null;\n },\n load(id: string) {\n if (id !== STUB_ID) return null;\n // A Proxy answers any property access (default or named) with another\n // proxy, so every import shape resolves without evaluating real browser\n // code. It is never actually invoked on the server, so it never throws.\n return (\n \"const handler = { get(_t, p) {\" +\n \" if (p === Symbol.toPrimitive) return () => '';\" +\n \" if (p === 'then') return undefined;\" +\n \" if (p === '__esModule') return true;\" +\n \" return new Proxy(function () {}, handler); } };\" +\n \"const stub = new Proxy(function () {}, handler);\" +\n \"export default stub;\"\n );\n },\n };\n}\n\nasync function buildWithNitro() {\n console.log(`[deploy] Building for preset \"${preset}\" via Nitro...`);\n const appBasePath = normalizeConfiguredAppBasePath();\n\n // Nitro runs its own server build after the React Router/Vite build. The\n // template's agent-chat plugin imports .generated/actions-registry.ts so the\n // serverless bundle has static imports for every domain action. Regenerate\n // here as well so deploy builds are not coupled to a previous Vite run or to\n // ignored local .generated files being present.\n generateActionRegistryForProject(cwd);\n\n // Work around pnpm + nitro:externals (nf3) bug where dangling symlinks for\n // platform-specific optional deps cause realpath ENOENT during file tracing.\n createDanglingOptionalDepStubs();\n\n const {\n createNitro,\n prepare,\n copyPublicAssets,\n build: nitroBuild,\n } = await import(\"nitro/builder\");\n\n // Resolve the React Router server build so the SSR catch-all route\n // can import \"virtual:react-router/server-build\" in production.\n const rrServerBuild = path.join(cwd, \"build\", \"server\", \"index.js\");\n\n // Inline the template's AGENTS.md + .agents/skills/ content into the Nitro\n // bundle via the `virtual` config option. Nitro's internal `nitro:virtual`\n // Rollup plugin picks this up and resolves `virtual:agents-bundle` to the\n // generated ES module source. Without this, Nitro's Rolldown build (used for\n // netlify, vercel, aws-lambda, node presets) can't resolve the virtual\n // module that `server/agents-bundle.ts` imports — it silently falls through\n // to an empty bundle and the agent gets no instructions/skills at runtime.\n //\n // The Vite plugin at `vite/agents-bundle-plugin.ts` handles this for the\n // React Router client/server build (and cloudflare via esbuild rebundle),\n // but Nitro runs its OWN build from ./server/ without Vite, so it needs its\n // own virtual module registration. Both paths reuse `readAgentsBundleFromFs`\n // from `server/agents-bundle.ts` to guarantee identical content.\n const { readAgentsBundleFromFs } = await import(\"../server/agents-bundle.js\");\n // Resolve the workspace core (if present) up front so the bundle embeds\n // enterprise-wide AGENTS.md + skills alongside the template's.\n const nitroWorkspaceCore = await getWorkspaceCoreExports(cwd);\n const nitroWorkspaceSource = nitroWorkspaceCore\n ? {\n skillsDir: nitroWorkspaceCore.skillsDir,\n agentsMdPath: nitroWorkspaceCore.agentsMdPath,\n rootDir: nitroWorkspaceCore.packageDir,\n }\n : null;\n const agentsBundleModuleSource = () => {\n const bundle = readAgentsBundleFromFs(cwd, nitroWorkspaceSource);\n return `// AUTO-GENERATED by @agent-native/core deploy build (Nitro virtual)\n// Contains the inlined AGENTS.md + .agents/skills/ content from the template,\n// merged with the workspace core's AGENTS.md + skills/ when present.\nconst bundle = ${JSON.stringify(bundle)};\nexport default bundle;\n`;\n };\n\n // Path aliases used by templates (mirrors tsconfig + Vite config). Nitro\n // bundles server/ and actions/ with its own Rolldown pipeline that doesn't\n // see Vite's resolve.alias — so without this, action files that import\n // `@/foo` (= `app/foo`) end up with the literal `@/foo` specifier in the\n // serverless function output and crash at runtime with\n // \"Cannot find package '@/foo' imported from /var/task/main.mjs\".\n const appDir = path.join(cwd, \"app\");\n const sharedDir = path.join(cwd, \"shared\");\n const pathAliases: Record<string, string> = {};\n if (fs.existsSync(appDir)) pathAliases[\"@\"] = appDir;\n if (fs.existsSync(sharedDir)) pathAliases[\"@shared\"] = sharedDir;\n\n const providedPluginsNitroPlugin = await writeProvidedPluginsNitroPlugin();\n\n const nitro = await createNitro({\n rootDir: cwd,\n dev: false,\n preset,\n baseURL: appBasePath || \"/\",\n minify: true,\n serverDir: \"./server\",\n ignore: NITRO_RUNTIME_IGNORE_PATTERNS,\n alias: {\n ...pathAliases,\n ...(fs.existsSync(rrServerBuild)\n ? { \"virtual:react-router/server-build\": rrServerBuild }\n : {}),\n },\n virtual: {\n \"virtual:agents-bundle\": agentsBundleModuleSource,\n },\n // Replace browser-only renderers (Excalidraw/Mermaid) with an inert proxy in\n // the server bundle. Without this, Nitro's Rolldown build pulls the real\n // Excalidraw into a shared vendor chunk imported statically by the SSR render\n // path, and its top-level `window` access crashes the function at cold-start\n // (ReferenceError: window is not defined → every request 502s). Mirrors the\n // Vite `ssrStubPlugin`, which only covers the `build/server` step.\n rollupConfig: {\n plugins: [createBrowserOnlyServerStubPlugin()],\n },\n ...(providedPluginsNitroPlugin\n ? { plugins: [providedPluginsNitroPlugin] }\n : {}),\n routeRules: mcpEmbedStaticAssetRouteRules(appBasePath),\n // For edge presets (cloudflare, deno), bundle all deps — node_modules\n // aren't available at runtime. Netlify/Vercel/Node have node_modules.\n ...(preset.startsWith(\"cloudflare\") || preset.startsWith(\"deno\")\n ? { noExternals: true }\n : {}),\n } as any);\n\n await runNitroBuildPipeline({\n nitro,\n hooks: { prepare, copyPublicAssets, nitroBuild },\n clientDir: path.join(cwd, \"build\", \"client\"),\n publicOutputDir: nitro.options.output.publicDir,\n appBasePath,\n cwd,\n });\n\n if (preset === \"netlify\" || preset === \"vercel\" || preset === \"aws-lambda\") {\n copyInstalledLibsqlNativePackages(nitro.options.output.serverDir);\n copyInstalledResvgPackages(nitro.options.output.serverDir);\n copyInstalledFfmpegStaticPackage(nitro.options.output.serverDir);\n }\n\n // Resolve remaining bare npm imports by bundling them into _libs/.\n // Nitro sometimes leaves small packages as externals even with noExternals.\n if (preset.startsWith(\"cloudflare\") || preset.startsWith(\"deno\")) {\n const { execFileSync } = await import(\"child_process\");\n const { createRequire } = await import(\"module\");\n const esbuildBin = (() => {\n try {\n const _req = createRequire(cwd + \"/\");\n const pkg = path.dirname(_req.resolve(\"esbuild/package.json\"));\n const bin = path.join(pkg, \"bin\", \"esbuild\");\n if (fs.existsSync(bin)) return bin;\n } catch {}\n return \"esbuild\";\n })();\n\n // Scan all output files for bare npm imports\n const outputDir =\n nitro.options.output.serverDir || path.join(cwd, \"dist\", \"_worker.js\");\n const bareImports = new Set<string>();\n function scanForBareImports(dir: string) {\n if (!fs.existsSync(dir)) return;\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n const p = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n scanForBareImports(p);\n continue;\n }\n if (!entry.name.endsWith(\".mjs\") && !entry.name.endsWith(\".js\"))\n continue;\n const code = fs.readFileSync(p, \"utf-8\");\n const matches = code.matchAll(/from\\s*[\"']([a-z@][a-z0-9._\\-/]*)[\"']/g);\n for (const m of matches) {\n const mod = m[1];\n if (mod.startsWith(\"node:\")) continue;\n // Skip Node builtins that are available via nodejs_compat\n const builtins = new Set([\n \"fs\",\n \"path\",\n \"os\",\n \"crypto\",\n \"http\",\n \"https\",\n \"stream\",\n \"url\",\n \"util\",\n \"events\",\n \"buffer\",\n \"net\",\n \"tls\",\n \"assert\",\n \"timers\",\n \"child_process\",\n \"module\",\n \"process\",\n \"sqlite\",\n \"worker_threads\",\n \"querystring\",\n \"zlib\",\n \"vm\",\n \"string_decoder\",\n \"diagnostics_channel\",\n \"async_hooks\",\n \"perf_hooks\",\n \"inspector\",\n ]);\n if (builtins.has(mod)) continue;\n bareImports.add(mod);\n }\n }\n }\n scanForBareImports(outputDir);\n\n // For each bare import, try to bundle it as a standalone module\n if (bareImports.size > 0) {\n const libsDir = path.join(outputDir, \"_libs\");\n fs.mkdirSync(libsDir, { recursive: true });\n for (const mod of bareImports) {\n const outFile = path.join(libsDir, `${mod.replace(/[/@]/g, \"_\")}.mjs`);\n try {\n // Resolve the module — check workspace node_modules and pnpm store\n let resolvedMod = mod;\n const _require = createRequire(cwd + \"/\");\n try {\n const resolved = _require.resolve(mod);\n resolvedMod = resolved;\n } catch {\n // Try from workspace root\n try {\n const wsRequire = createRequire(\n path.resolve(cwd, \"../../package.json\"),\n );\n resolvedMod = wsRequire.resolve(mod);\n } catch {\n // Will fail at esbuild\n }\n }\n // Scan what named imports the consumer expects, then generate\n // explicit re-exports to handle CJS modules properly.\n const neededExports = new Set<string>();\n function findNeededExports(dir: string) {\n if (!fs.existsSync(dir)) return;\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n const p = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n findNeededExports(p);\n continue;\n }\n if (!entry.name.endsWith(\".mjs\") && !entry.name.endsWith(\".js\"))\n continue;\n const code = fs.readFileSync(p, \"utf-8\");\n // Match: import{foo as bar,baz}from\"<mod>\"\n const escaped = mod.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const re = new RegExp(\n `import\\\\{([^}]+)\\\\}from[\"']${escaped}[\"']`,\n \"g\",\n );\n for (const m2 of code.matchAll(re)) {\n for (const part of m2[1].split(\",\")) {\n const name = part\n .trim()\n .split(/\\s+as\\s+/)[0]\n .trim();\n if (name && /^[a-zA-Z_$]/.test(name)) neededExports.add(name);\n }\n }\n }\n }\n findNeededExports(outputDir);\n\n const entryCode =\n neededExports.size > 0\n ? [\n `import _mod from \"${resolvedMod}\";`,\n `export default _mod;`,\n ...Array.from(neededExports).map(\n (n) =>\n `export const ${n} = _mod.${n} ?? _mod?.default?.${n};`,\n ),\n ].join(\"\\n\")\n : `export * from \"${resolvedMod}\"; export { default } from \"${resolvedMod}\";`;\n\n execFileSync(\n esbuildBin,\n [\n \"--bundle\",\n `--outfile=${outFile}`,\n \"--format=esm\",\n \"--platform=neutral\",\n \"--target=es2022\",\n \"--external:node:*\",\n ],\n {\n input: entryCode,\n cwd,\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n },\n );\n // Rewrite imports in all files to point to the bundled module\n function rewriteImports(dir: string) {\n if (!fs.existsSync(dir)) return;\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n const p = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n rewriteImports(p);\n continue;\n }\n if (!entry.name.endsWith(\".mjs\") && !entry.name.endsWith(\".js\"))\n continue;\n let code = fs.readFileSync(p, \"utf-8\");\n const relPath = path\n .relative(path.dirname(p), outFile)\n .replace(/\\\\/g, \"/\");\n const importPath = relPath.startsWith(\".\")\n ? relPath\n : \"./\" + relPath;\n const re = new RegExp(\n `from[\"']${mod.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")}[\"']`,\n \"g\",\n );\n if (re.test(code)) {\n code = code.replace(re, `from\"${importPath}\"`);\n fs.writeFileSync(p, code);\n }\n }\n }\n rewriteImports(outputDir);\n console.log(`[deploy] Bundled external: ${mod}`);\n } catch {\n console.warn(\n `[deploy] Could not bundle: ${mod} (may not be needed at runtime)`,\n );\n }\n }\n }\n }\n\n // Cloudflare-specific post-build patches\n if (preset.startsWith(\"cloudflare\")) {\n const serverDir2 = nitro.options.output.serverDir;\n const scanDirs = [serverDir2];\n if (serverDir2) {\n const chunksDir = path.join(serverDir2, \"_chunks\");\n const libsDir = path.join(serverDir2, \"_libs\");\n if (fs.existsSync(chunksDir)) scanDirs.push(chunksDir);\n if (fs.existsSync(libsDir)) scanDirs.push(libsDir);\n }\n\n for (const scanDir of scanDirs) {\n if (!scanDir || !fs.existsSync(scanDir)) continue;\n for (const file of fs.readdirSync(scanDir)) {\n if (!file.endsWith(\".mjs\") && !file.endsWith(\".js\")) continue;\n const filePath = path.join(scanDir, file);\n let code = fs.readFileSync(filePath, \"utf-8\");\n let changed = false;\n\n // 1. Rewrite bare Node.js imports to node: prefixed.\n // CF Workers requires the node: prefix for built-in modules.\n const NODE_BUILTINS = [\n \"fs\",\n \"path\",\n \"os\",\n \"crypto\",\n \"http\",\n \"https\",\n \"stream\",\n \"url\",\n \"util\",\n \"events\",\n \"buffer\",\n \"querystring\",\n \"zlib\",\n \"net\",\n \"tls\",\n \"assert\",\n \"timers\",\n \"child_process\",\n \"module\",\n \"process\",\n \"sqlite\",\n \"worker_threads\",\n \"string_decoder\",\n \"diagnostics_channel\",\n \"async_hooks\",\n \"perf_hooks\",\n \"inspector\",\n \"vm\",\n ];\n for (const mod of NODE_BUILTINS) {\n // Match: from\"fs\" or from \"fs\" (but not from\"node:fs\")\n const re = new RegExp(`from\\\\s*[\"']${mod}[\"']`, \"g\");\n if (re.test(code)) {\n code = code.replace(re, `from\"node:${mod}\"`);\n changed = true;\n }\n }\n\n // 2. Patch import.meta.url for createRequire().\n // React Router's server build uses createRequire(import.meta.url)\n // but import.meta.url is undefined on CF Workers.\n if (code.includes(\"import.meta.url\")) {\n code = code.replace(/import\\.meta\\.url/g, '\"file:///worker.mjs\"');\n changed = true;\n }\n\n // 3. Patch setInterval/setTimeout at global scope.\n // CF Workers disallows timers in global scope.\n if (code.includes(\"setInterval\") && !code.includes(\"__timer_shim__\")) {\n const shim =\n \"/* __timer_shim__ */\" +\n \"var __origSetInterval=globalThis.setInterval;\" +\n \"globalThis.setInterval=function(){return{unref(){},ref(){},close(){}}};\";\n const restore =\n \";(function(){if(typeof __origSetInterval!=='undefined')globalThis.setInterval=__origSetInterval})();\";\n code = shim + code + \"\\n\" + restore;\n changed = true;\n }\n\n if (changed) fs.writeFileSync(filePath, code);\n }\n }\n // 3. Create stub modules in _libs/ for native deps that Nitro's rolldown\n // bundler references but can't resolve on CF Workers, and rewrite\n // bare imports to point to the stub files.\n const libsDir2 = path.join(\n serverDir2 || path.join(cwd, \"dist\", \"_worker.js\"),\n \"_libs\",\n );\n if (fs.existsSync(libsDir2)) {\n const NATIVE_STUBS = [\"better-sqlite3\", \"node-pty\", \"cron-parser\"];\n for (const mod of NATIVE_STUBS) {\n const libFiles = fs\n .readdirSync(libsDir2)\n .filter((f) => f.endsWith(\".mjs\"));\n const referencingFiles: string[] = [];\n for (const f of libFiles) {\n const filePath = path.join(libsDir2, f);\n const content = fs.readFileSync(filePath, \"utf-8\");\n if (content.includes(`\"${mod}\"`) || content.includes(`'${mod}'`)) {\n referencingFiles.push(filePath);\n }\n }\n if (referencingFiles.length === 0) continue;\n\n // Create a stub _libs/<mod>.mjs that exports empty defaults\n const stubName = mod.replace(/[/@]/g, \"__\") + \".mjs\";\n const stubPath = path.join(libsDir2, stubName);\n if (!fs.existsSync(stubPath)) {\n fs.writeFileSync(\n stubPath,\n `export default {}; export const watch = () => ({ close() {} });\\n`,\n );\n console.log(`[deploy] Created stub for _libs/${stubName}`);\n }\n\n // Rewrite bare imports in _libs/ and _chunks/ to use the stub\n const escaped = mod.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const importRe = new RegExp(`(from\\\\s*[\"'])${escaped}([\"'])`, \"g\");\n // Scan _libs/ files\n for (const filePath of referencingFiles) {\n let code = fs.readFileSync(filePath, \"utf-8\");\n if (importRe.test(code)) {\n code = code.replace(importRe, `$1./${stubName}$2`);\n fs.writeFileSync(filePath, code);\n console.log(\n `[deploy] Rewrote ${mod} imports in _libs/${path.basename(filePath)}`,\n );\n }\n }\n // Also scan _chunks/ files (they import native deps too)\n const chunksDir2 = path.join(\n serverDir2 || path.join(cwd, \"dist\", \"_worker.js\"),\n \"_chunks\",\n );\n if (fs.existsSync(chunksDir2)) {\n for (const f of fs\n .readdirSync(chunksDir2)\n .filter((f) => f.endsWith(\".mjs\") || f.endsWith(\".js\"))) {\n const filePath = path.join(chunksDir2, f);\n let code = fs.readFileSync(filePath, \"utf-8\");\n if (importRe.test(code)) {\n // From _chunks/, the stub is at ../_libs/<stubName>\n code = code.replace(importRe, `$1../_libs/${stubName}$2`);\n fs.writeFileSync(filePath, code);\n console.log(`[deploy] Rewrote ${mod} imports in _chunks/${f}`);\n }\n }\n }\n }\n }\n\n console.log(\n \"[deploy] Patched bare Node imports, timer calls, and route finder for CF Workers\",\n );\n }\n\n await nitro.close();\n console.log(`[deploy] Nitro build complete for preset \"${preset}\".`);\n}\n\nasync function main() {\n console.log(`[deploy] Building for ${preset}...`);\n\n switch (preset) {\n case \"cloudflare_pages\":\n case \"cloudflare-pages\":\n // Cloudflare Workers require a single-file bundle that wrangler can deploy.\n // Nitro's native presets produce split chunks that wrangler can't upload\n // as multi-module Workers. Use the custom esbuild-based bundler.\n await buildCloudflarePages();\n break;\n default:\n // All other presets (netlify, vercel, deno_deploy, aws-lambda, etc.)\n // are handled natively by Nitro's build API.\n await buildWithNitro();\n break;\n }\n}\n\nif (\n process.argv[1] &&\n path.resolve(process.argv[1]) === path.resolve(fileURLToPath(import.meta.url))\n) {\n await main();\n}\n"]}
|