@agent-native/core 0.12.25 → 0.12.27
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/agent/production-agent.d.ts.map +1 -1
- package/dist/agent/production-agent.js +20 -2
- package/dist/agent/production-agent.js.map +1 -1
- package/dist/client/AgentTaskCard.d.ts.map +1 -1
- package/dist/client/AgentTaskCard.js +16 -3
- package/dist/client/AgentTaskCard.js.map +1 -1
- package/dist/client/AssistantChat.d.ts.map +1 -1
- package/dist/client/AssistantChat.js +22 -12
- package/dist/client/AssistantChat.js.map +1 -1
- package/dist/client/IframeEmbed.d.ts.map +1 -1
- package/dist/client/IframeEmbed.js +2 -2
- package/dist/client/IframeEmbed.js.map +1 -1
- package/dist/client/agent-chat-adapter.d.ts.map +1 -1
- package/dist/client/agent-chat-adapter.js +62 -9
- package/dist/client/agent-chat-adapter.js.map +1 -1
- package/dist/client/composer/ComposerPlusMenu.d.ts.map +1 -1
- package/dist/client/composer/ComposerPlusMenu.js +1 -1
- package/dist/client/composer/ComposerPlusMenu.js.map +1 -1
- package/dist/client/composer/PromptComposer.d.ts.map +1 -1
- package/dist/client/composer/PromptComposer.js +8 -7
- package/dist/client/composer/PromptComposer.js.map +1 -1
- package/dist/client/composer/attachment-accept.d.ts +7 -0
- package/dist/client/composer/attachment-accept.d.ts.map +1 -0
- package/dist/client/composer/attachment-accept.js +36 -0
- package/dist/client/composer/attachment-accept.js.map +1 -0
- package/dist/client/sse-event-processor.d.ts.map +1 -1
- package/dist/client/sse-event-processor.js +8 -0
- package/dist/client/sse-event-processor.js.map +1 -1
- package/dist/db/client.d.ts +3 -0
- package/dist/db/client.d.ts.map +1 -1
- package/dist/db/client.js +70 -34
- package/dist/db/client.js.map +1 -1
- package/dist/db/create-get-db.d.ts.map +1 -1
- package/dist/db/create-get-db.js +30 -7
- package/dist/db/create-get-db.js.map +1 -1
- package/dist/deploy/build.js +64 -0
- package/dist/deploy/build.js.map +1 -1
- package/dist/scripts/db/exec.d.ts.map +1 -1
- package/dist/scripts/db/exec.js +3 -6
- package/dist/scripts/db/exec.js.map +1 -1
- package/dist/scripts/db/patch.d.ts.map +1 -1
- package/dist/scripts/db/patch.js +3 -6
- package/dist/scripts/db/patch.js.map +1 -1
- package/dist/scripts/db/query.d.ts.map +1 -1
- package/dist/scripts/db/query.js +3 -6
- package/dist/scripts/db/query.js.map +1 -1
- package/dist/scripts/db/schema.d.ts.map +1 -1
- package/dist/scripts/db/schema.js +3 -6
- package/dist/scripts/db/schema.js.map +1 -1
- package/dist/scripts/db/sqlite-client.d.ts +15 -0
- package/dist/scripts/db/sqlite-client.d.ts.map +1 -0
- package/dist/scripts/db/sqlite-client.js +51 -0
- package/dist/scripts/db/sqlite-client.js.map +1 -0
- package/dist/server/better-auth-instance.js +4 -3
- package/dist/server/better-auth-instance.js.map +1 -1
- package/package.json +1 -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;AAElF,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,EAAE,CAAC;AAC1B,MAAM,MAAM,GAAG,OAAO,CAAC,GAAG,CAA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CAAC;4BACjC,OAAO,CAAC,GAAG,CAAC,oBAAoB,GAAG,uBAAuB,CAAC,EAAE,CAAC,CAAC;wBACjE,CAAC;oBACH,CAAC;gBACH,CAAC;YACH,CAAC;QACH,CAAC;QAED,OAAO,CAAC,GAAG,CACT,kFAAkF,CACnF,CAAC;IACJ,CAAC;IAED,MAAM,KAAK,CAAC,KAAK,EAAE,CAAC;IACpB,OAAO,CAAC,GAAG,CAAC,6CAA6C,MAAM,IAAI,CAAC,CAAC;AACvE,CAAC;AAED,KAAK,UAAU,IAAI;IACjB,OAAO,CAAC,GAAG,CAAC,yBAAyB,MAAM,KAAK,CAAC,CAAC;IAElD,QAAQ,MAAM,EAAE,CAAC;QACf,KAAK,kBAAkB,CAAC;QACxB,KAAK,kBAAkB;YACrB,4EAA4E;YAC5E,yEAAyE;YACzE,iEAAiE;YACjE,MAAM,oBAAoB,EAAE,CAAC;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\";\n\nconst cwd = process.cwd();\nconst preset = process.env.NITRO_PRESET || \"node\";\n\nfunction normalizeConfiguredAppBasePath(): string {\n const raw = process.env.VITE_APP_BASE_PATH || process.env.APP_BASE_PATH;\n if (!raw || raw === \"/\") return \"\";\n const trimmed = String(raw).trim();\n if (!trimmed || trimmed === \"/\") return \"\";\n const normalized = trimmed.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\");\n return normalized ? `/${normalized}` : \"\";\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\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): 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 const routePath = `/_agent-native/actions/${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\" ? \"Object.fromEntries(event.url.searchParams)\" : \"(await readBody(event)) ?? {}\"};\n try {\n const result = await ${varName}.run(params);\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\n for (let i = 0; i < edgePlugins.length; i++) {\n const varName = `plugin_${i}`;\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\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 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\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 return normalizeAppBasePath(\n globalThis.process?.env?.VITE_APP_BASE_PATH ||\n globalThis.process?.env?.APP_BASE_PATH,\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 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\nasync function rewriteMountedResponse(response, basePath) {\n const sentryClientConfigScript = getSentryClientConfigScript();\n if (!basePath && !sentryClientConfigScript) return response;\n\n const headers = new Headers(response.headers);\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(prefixMountedHtml(html, basePath), sentryClientConfigScript),\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\",\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${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 );\n }\n return rewriteMountedResponse(await rrHandler(request), basePath);\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 assetResponse;\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 entrySource = generateWorkerEntry(\n routes,\n plugins,\n missingDefaults,\n actions,\n workspaceCore,\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 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 ].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\nfunction copyDir(src: string, dest: string) {\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.isDirectory()) {\n copyDir(srcPath, destPath);\n } else {\n fs.copyFileSync(srcPath, destPath);\n }\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 */\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 nitro = await createNitro({\n rootDir: cwd,\n dev: false,\n preset,\n baseURL: appBasePath || \"/\",\n minify: true,\n serverDir: \"./server\",\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 // 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 prepare(nitro);\n await copyPublicAssets(nitro);\n await nitroBuild(nitro);\n\n // Copy React Router's client build into Nitro's public output dir\n const clientDir = path.join(cwd, \"build\", \"client\");\n const publicOutputDir = nitro.options.output.publicDir;\n if (fs.existsSync(clientDir) && publicOutputDir) {\n copyDir(clientDir, publicOutputDir);\n const basePath = appBasePath;\n if (basePath) {\n copyDir(clientDir, path.join(publicOutputDir, basePath.slice(1)));\n }\n console.log(\n `[deploy] Copied client assets to ${path.relative(cwd, publicOutputDir)}`,\n );\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 // Try resolving from both template dir and workspace root\n const nodePaths = [\n path.join(cwd, \"node_modules\"),\n path.resolve(cwd, \"../../node_modules\"),\n ].filter((p) => fs.existsSync(p));\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,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;AAElF,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,EAAE,CAAC;AAC1B,MAAM,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,YAAY,IAAI,MAAM,CAAC;AAElD,SAAS,8BAA8B;IACrC,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,kBAAkB,IAAI,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC;IACxE,IAAI,CAAC,GAAG,IAAI,GAAG,KAAK,GAAG;QAAE,OAAO,EAAE,CAAC;IACnC,MAAM,OAAO,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC;IACnC,IAAI,CAAC,OAAO,IAAI,OAAO,KAAK,GAAG;QAAE,OAAO,EAAE,CAAC;IAC3C,MAAM,UAAU,GAAG,OAAO,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CA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M,EAAE,CAAC;QACf,KAAK,kBAAkB,CAAC;QACxB,KAAK,kBAAkB;YACrB,4EAA4E;YAC5E,yEAAyE;YACzE,iEAAiE;YACjE,MAAM,oBAAoB,EAAE,CAAC;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\";\n\nconst cwd = process.cwd();\nconst preset = process.env.NITRO_PRESET || \"node\";\n\nfunction normalizeConfiguredAppBasePath(): string {\n const raw = process.env.VITE_APP_BASE_PATH || process.env.APP_BASE_PATH;\n if (!raw || raw === \"/\") return \"\";\n const trimmed = String(raw).trim();\n if (!trimmed || trimmed === \"/\") return \"\";\n const normalized = trimmed.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\");\n return normalized ? `/${normalized}` : \"\";\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\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): 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 const routePath = `/_agent-native/actions/${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\" ? \"Object.fromEntries(event.url.searchParams)\" : \"(await readBody(event)) ?? {}\"};\n try {\n const result = await ${varName}.run(params);\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\n for (let i = 0; i < edgePlugins.length; i++) {\n const varName = `plugin_${i}`;\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\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 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\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 return normalizeAppBasePath(\n globalThis.process?.env?.VITE_APP_BASE_PATH ||\n globalThis.process?.env?.APP_BASE_PATH,\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 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\nasync function rewriteMountedResponse(response, basePath) {\n const sentryClientConfigScript = getSentryClientConfigScript();\n if (!basePath && !sentryClientConfigScript) return response;\n\n const headers = new Headers(response.headers);\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(prefixMountedHtml(html, basePath), sentryClientConfigScript),\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\",\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${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 );\n }\n return rewriteMountedResponse(await rrHandler(request), basePath);\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 assetResponse;\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 entrySource = generateWorkerEntry(\n routes,\n plugins,\n missingDefaults,\n actions,\n workspaceCore,\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 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 ].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\nfunction copyDir(src: string, dest: string) {\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.isDirectory()) {\n copyDir(srcPath, destPath);\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];\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 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\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 */\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 nitro = await createNitro({\n rootDir: cwd,\n dev: false,\n preset,\n baseURL: appBasePath || \"/\",\n minify: true,\n serverDir: \"./server\",\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 // 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 prepare(nitro);\n await copyPublicAssets(nitro);\n await nitroBuild(nitro);\n\n // Copy React Router's client build into Nitro's public output dir\n const clientDir = path.join(cwd, \"build\", \"client\");\n const publicOutputDir = nitro.options.output.publicDir;\n if (fs.existsSync(clientDir) && publicOutputDir) {\n copyDir(clientDir, publicOutputDir);\n const basePath = appBasePath;\n if (basePath) {\n copyDir(clientDir, path.join(publicOutputDir, basePath.slice(1)));\n }\n console.log(\n `[deploy] Copied client assets to ${path.relative(cwd, publicOutputDir)}`,\n );\n }\n\n if (preset === \"netlify\" || preset === \"vercel\" || preset === \"aws-lambda\") {\n copyInstalledLibsqlNativePackages(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 // Try resolving from both template dir and workspace root\n const nodePaths = [\n path.join(cwd, \"node_modules\"),\n path.resolve(cwd, \"../../node_modules\"),\n ].filter((p) => fs.existsSync(p));\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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"exec.d.ts","sourceRoot":"","sources":["../../../src/scripts/db/exec.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AA6kBH,wBAA8B,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,
|
|
1
|
+
{"version":3,"file":"exec.d.ts","sourceRoot":"","sources":["../../../src/scripts/db/exec.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AA6kBH,wBAA8B,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAyJlE"}
|
package/dist/scripts/db/exec.js
CHANGED
|
@@ -14,11 +14,11 @@
|
|
|
14
14
|
* pnpm action db-exec --statements '[{"sql":"INSERT INTO notes (id,title) VALUES (?,?)","args":["n1","One"]},{"sql":"UPDATE counters SET value=value+1 WHERE key=?","args":["notes"]}]'
|
|
15
15
|
*/
|
|
16
16
|
import path from "path";
|
|
17
|
-
import {
|
|
18
|
-
import { getDatabaseUrl, getDatabaseAuthToken } from "../../db/client.js";
|
|
17
|
+
import { getDatabaseUrl } from "../../db/client.js";
|
|
19
18
|
import { parseArgs, fail } from "../utils.js";
|
|
20
19
|
import { buildScopingPostgres, buildScopingSqlite, } from "./scoping.js";
|
|
21
20
|
import { assertNoSensitiveFrameworkTables } from "./safety.js";
|
|
21
|
+
import { createSqliteScriptClient } from "./sqlite-client.js";
|
|
22
22
|
function isPostgresUrl(url) {
|
|
23
23
|
return url.startsWith("postgres://") || url.startsWith("postgresql://");
|
|
24
24
|
}
|
|
@@ -558,10 +558,7 @@ Options:
|
|
|
558
558
|
return;
|
|
559
559
|
}
|
|
560
560
|
// libsql / SQLite path
|
|
561
|
-
const client =
|
|
562
|
-
url,
|
|
563
|
-
authToken: getDatabaseAuthToken(),
|
|
564
|
-
});
|
|
561
|
+
const client = await createSqliteScriptClient(url);
|
|
565
562
|
try {
|
|
566
563
|
// Set up user-scoped temp views in production
|
|
567
564
|
const scoping = await buildScopingSqlite(client);
|