@agent-native/core 0.7.18 → 0.7.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (269) hide show
  1. package/README.md +1 -1
  2. package/dist/agent/engine/builder-engine.d.ts.map +1 -1
  3. package/dist/agent/engine/builder-engine.js +60 -5
  4. package/dist/agent/engine/builder-engine.js.map +1 -1
  5. package/dist/agent/loop-settings.d.ts +37 -0
  6. package/dist/agent/loop-settings.d.ts.map +1 -0
  7. package/dist/agent/loop-settings.js +127 -0
  8. package/dist/agent/loop-settings.js.map +1 -0
  9. package/dist/agent/production-agent.d.ts +8 -0
  10. package/dist/agent/production-agent.d.ts.map +1 -1
  11. package/dist/agent/production-agent.js +268 -29
  12. package/dist/agent/production-agent.js.map +1 -1
  13. package/dist/agent/run-manager.d.ts.map +1 -1
  14. package/dist/agent/run-manager.js +76 -3
  15. package/dist/agent/run-manager.js.map +1 -1
  16. package/dist/agent/run-store.d.ts +1 -1
  17. package/dist/agent/run-store.d.ts.map +1 -1
  18. package/dist/agent/run-store.js +65 -2
  19. package/dist/agent/run-store.js.map +1 -1
  20. package/dist/agent/thread-data-builder.d.ts +3 -0
  21. package/dist/agent/thread-data-builder.d.ts.map +1 -1
  22. package/dist/agent/thread-data-builder.js +52 -10
  23. package/dist/agent/thread-data-builder.js.map +1 -1
  24. package/dist/agent/tool-search.d.ts +37 -0
  25. package/dist/agent/tool-search.d.ts.map +1 -0
  26. package/dist/agent/tool-search.js +201 -0
  27. package/dist/agent/tool-search.js.map +1 -0
  28. package/dist/agent/types.d.ts +8 -1
  29. package/dist/agent/types.d.ts.map +1 -1
  30. package/dist/agent/types.js.map +1 -1
  31. package/dist/cli/create.d.ts.map +1 -1
  32. package/dist/cli/create.js +57 -11
  33. package/dist/cli/create.js.map +1 -1
  34. package/dist/cli/workspacify.d.ts +2 -0
  35. package/dist/cli/workspacify.d.ts.map +1 -1
  36. package/dist/cli/workspacify.js +34 -1
  37. package/dist/cli/workspacify.js.map +1 -1
  38. package/dist/client/AssistantChat.d.ts.map +1 -1
  39. package/dist/client/AssistantChat.js +303 -14
  40. package/dist/client/AssistantChat.js.map +1 -1
  41. package/dist/client/ConnectBuilderCard.d.ts.map +1 -1
  42. package/dist/client/ConnectBuilderCard.js +1 -1
  43. package/dist/client/ConnectBuilderCard.js.map +1 -1
  44. package/dist/client/MultiTabAssistantChat.d.ts.map +1 -1
  45. package/dist/client/MultiTabAssistantChat.js +16 -24
  46. package/dist/client/MultiTabAssistantChat.js.map +1 -1
  47. package/dist/client/NewWorkspaceAppFlow.d.ts +14 -0
  48. package/dist/client/NewWorkspaceAppFlow.d.ts.map +1 -0
  49. package/dist/client/NewWorkspaceAppFlow.js +200 -0
  50. package/dist/client/NewWorkspaceAppFlow.js.map +1 -0
  51. package/dist/client/PoweredByBadge.d.ts +10 -1
  52. package/dist/client/PoweredByBadge.d.ts.map +1 -1
  53. package/dist/client/PoweredByBadge.js +120 -8
  54. package/dist/client/PoweredByBadge.js.map +1 -1
  55. package/dist/client/agent-chat-adapter.d.ts +8 -0
  56. package/dist/client/agent-chat-adapter.d.ts.map +1 -1
  57. package/dist/client/agent-chat-adapter.js +32 -5
  58. package/dist/client/agent-chat-adapter.js.map +1 -1
  59. package/dist/client/agent-chat.d.ts.map +1 -1
  60. package/dist/client/agent-chat.js +15 -3
  61. package/dist/client/agent-chat.js.map +1 -1
  62. package/dist/client/analytics.d.ts +1 -1
  63. package/dist/client/analytics.d.ts.map +1 -1
  64. package/dist/client/analytics.js +141 -1
  65. package/dist/client/analytics.js.map +1 -1
  66. package/dist/client/builder-frame.d.ts +10 -0
  67. package/dist/client/builder-frame.d.ts.map +1 -0
  68. package/dist/client/builder-frame.js +94 -0
  69. package/dist/client/builder-frame.js.map +1 -0
  70. package/dist/client/composer/MentionPopover.d.ts.map +1 -1
  71. package/dist/client/composer/MentionPopover.js +5 -1
  72. package/dist/client/composer/MentionPopover.js.map +1 -1
  73. package/dist/client/composer/TiptapComposer.d.ts.map +1 -1
  74. package/dist/client/composer/TiptapComposer.js +11 -6
  75. package/dist/client/composer/TiptapComposer.js.map +1 -1
  76. package/dist/client/error-format.d.ts +20 -1
  77. package/dist/client/error-format.d.ts.map +1 -1
  78. package/dist/client/error-format.js +53 -5
  79. package/dist/client/error-format.js.map +1 -1
  80. package/dist/client/index.d.ts +3 -1
  81. package/dist/client/index.d.ts.map +1 -1
  82. package/dist/client/index.js +3 -1
  83. package/dist/client/index.js.map +1 -1
  84. package/dist/client/onboarding/OnboardingPanel.d.ts.map +1 -1
  85. package/dist/client/onboarding/OnboardingPanel.js +88 -6
  86. package/dist/client/onboarding/OnboardingPanel.js.map +1 -1
  87. package/dist/client/org/TeamPage.d.ts.map +1 -1
  88. package/dist/client/org/TeamPage.js +14 -2
  89. package/dist/client/org/TeamPage.js.map +1 -1
  90. package/dist/client/settings/SettingsPanel.d.ts.map +1 -1
  91. package/dist/client/settings/SettingsPanel.js +145 -9
  92. package/dist/client/settings/SettingsPanel.js.map +1 -1
  93. package/dist/client/settings/useBuilderStatus.d.ts +13 -0
  94. package/dist/client/settings/useBuilderStatus.d.ts.map +1 -1
  95. package/dist/client/settings/useBuilderStatus.js +50 -9
  96. package/dist/client/settings/useBuilderStatus.js.map +1 -1
  97. package/dist/client/sse-event-processor.d.ts +9 -1
  98. package/dist/client/sse-event-processor.d.ts.map +1 -1
  99. package/dist/client/sse-event-processor.js +95 -8
  100. package/dist/client/sse-event-processor.js.map +1 -1
  101. package/dist/client/tools/ToolsListPage.d.ts.map +1 -1
  102. package/dist/client/tools/ToolsListPage.js +16 -1
  103. package/dist/client/tools/ToolsListPage.js.map +1 -1
  104. package/dist/client/tools/ToolsSidebarSection.d.ts.map +1 -1
  105. package/dist/client/tools/ToolsSidebarSection.js +63 -8
  106. package/dist/client/tools/ToolsSidebarSection.js.map +1 -1
  107. package/dist/client/tools/tool-order.d.ts +7 -0
  108. package/dist/client/tools/tool-order.d.ts.map +1 -0
  109. package/dist/client/tools/tool-order.js +47 -0
  110. package/dist/client/tools/tool-order.js.map +1 -0
  111. package/dist/client/transcription/BuilderTranscriptionCta.d.ts.map +1 -1
  112. package/dist/client/transcription/BuilderTranscriptionCta.js +71 -6
  113. package/dist/client/transcription/BuilderTranscriptionCta.js.map +1 -1
  114. package/dist/client/use-send-to-agent-chat.d.ts.map +1 -1
  115. package/dist/client/use-send-to-agent-chat.js +11 -3
  116. package/dist/client/use-send-to-agent-chat.js.map +1 -1
  117. package/dist/client/useProductionAgent.d.ts.map +1 -1
  118. package/dist/client/useProductionAgent.js +1 -1
  119. package/dist/client/useProductionAgent.js.map +1 -1
  120. package/dist/db/client.d.ts.map +1 -1
  121. package/dist/db/client.js +5 -1
  122. package/dist/db/client.js.map +1 -1
  123. package/dist/deploy/build.d.ts +1 -0
  124. package/dist/deploy/build.d.ts.map +1 -1
  125. package/dist/deploy/build.js +4 -1
  126. package/dist/deploy/build.js.map +1 -1
  127. package/dist/integrations/pending-tasks-retry-job.d.ts.map +1 -1
  128. package/dist/integrations/pending-tasks-retry-job.js +1 -1
  129. package/dist/integrations/pending-tasks-retry-job.js.map +1 -1
  130. package/dist/oauth-tokens/index.d.ts +1 -1
  131. package/dist/oauth-tokens/index.d.ts.map +1 -1
  132. package/dist/oauth-tokens/index.js +1 -1
  133. package/dist/oauth-tokens/index.js.map +1 -1
  134. package/dist/oauth-tokens/store.d.ts.map +1 -1
  135. package/dist/oauth-tokens/store.js +6 -0
  136. package/dist/oauth-tokens/store.js.map +1 -1
  137. package/dist/observability/store.d.ts.map +1 -1
  138. package/dist/observability/store.js +19 -19
  139. package/dist/observability/store.js.map +1 -1
  140. package/dist/onboarding/default-steps.d.ts.map +1 -1
  141. package/dist/onboarding/default-steps.js +95 -61
  142. package/dist/onboarding/default-steps.js.map +1 -1
  143. package/dist/onboarding/plugin.d.ts.map +1 -1
  144. package/dist/onboarding/plugin.js +17 -8
  145. package/dist/onboarding/plugin.js.map +1 -1
  146. package/dist/org/migrations.js +2 -2
  147. package/dist/org/migrations.js.map +1 -1
  148. package/dist/scripts/agent-engines/list-agent-engines.d.ts.map +1 -1
  149. package/dist/scripts/agent-engines/list-agent-engines.js +2 -3
  150. package/dist/scripts/agent-engines/list-agent-engines.js.map +1 -1
  151. package/dist/scripts/db/exec.d.ts +2 -1
  152. package/dist/scripts/db/exec.d.ts.map +1 -1
  153. package/dist/scripts/db/exec.js +264 -61
  154. package/dist/scripts/db/exec.js.map +1 -1
  155. package/dist/scripts/db/schema.d.ts.map +1 -1
  156. package/dist/scripts/db/schema.js +16 -4
  157. package/dist/scripts/db/schema.js.map +1 -1
  158. package/dist/scripts/dev/index.d.ts.map +1 -1
  159. package/dist/scripts/dev/index.js +36 -11
  160. package/dist/scripts/dev/index.js.map +1 -1
  161. package/dist/scripts/manage-agent-loop-settings.d.ts +7 -0
  162. package/dist/scripts/manage-agent-loop-settings.d.ts.map +1 -0
  163. package/dist/scripts/manage-agent-loop-settings.js +63 -0
  164. package/dist/scripts/manage-agent-loop-settings.js.map +1 -0
  165. package/dist/scripts/runner.d.ts.map +1 -1
  166. package/dist/scripts/runner.js +11 -0
  167. package/dist/scripts/runner.js.map +1 -1
  168. package/dist/server/agent-chat-plugin.d.ts.map +1 -1
  169. package/dist/server/agent-chat-plugin.js +60 -18
  170. package/dist/server/agent-chat-plugin.js.map +1 -1
  171. package/dist/server/app-url.d.ts +5 -4
  172. package/dist/server/app-url.d.ts.map +1 -1
  173. package/dist/server/app-url.js +8 -4
  174. package/dist/server/app-url.js.map +1 -1
  175. package/dist/server/auth.d.ts +37 -0
  176. package/dist/server/auth.d.ts.map +1 -1
  177. package/dist/server/auth.js +114 -35
  178. package/dist/server/auth.js.map +1 -1
  179. package/dist/server/better-auth-instance.d.ts +15 -0
  180. package/dist/server/better-auth-instance.d.ts.map +1 -1
  181. package/dist/server/better-auth-instance.js +131 -5
  182. package/dist/server/better-auth-instance.js.map +1 -1
  183. package/dist/server/builder-browser.d.ts +12 -0
  184. package/dist/server/builder-browser.d.ts.map +1 -1
  185. package/dist/server/builder-browser.js +36 -4
  186. package/dist/server/builder-browser.js.map +1 -1
  187. package/dist/server/core-routes-plugin.d.ts.map +1 -1
  188. package/dist/server/core-routes-plugin.js +350 -53
  189. package/dist/server/core-routes-plugin.js.map +1 -1
  190. package/dist/server/credential-provider.d.ts +21 -3
  191. package/dist/server/credential-provider.d.ts.map +1 -1
  192. package/dist/server/credential-provider.js +51 -21
  193. package/dist/server/credential-provider.js.map +1 -1
  194. package/dist/server/google-oauth.d.ts +3 -0
  195. package/dist/server/google-oauth.d.ts.map +1 -1
  196. package/dist/server/google-oauth.js +35 -18
  197. package/dist/server/google-oauth.js.map +1 -1
  198. package/dist/server/index.d.ts +4 -3
  199. package/dist/server/index.d.ts.map +1 -1
  200. package/dist/server/index.js +4 -3
  201. package/dist/server/index.js.map +1 -1
  202. package/dist/server/schema-prompt.d.ts.map +1 -1
  203. package/dist/server/schema-prompt.js +2 -1
  204. package/dist/server/schema-prompt.js.map +1 -1
  205. package/dist/server/security-headers.d.ts +3 -0
  206. package/dist/server/security-headers.d.ts.map +1 -1
  207. package/dist/server/security-headers.js +7 -1
  208. package/dist/server/security-headers.js.map +1 -1
  209. package/dist/server/ssr-handler.d.ts.map +1 -1
  210. package/dist/server/ssr-handler.js +24 -4
  211. package/dist/server/ssr-handler.js.map +1 -1
  212. package/dist/server/voice-providers-status.d.ts +7 -0
  213. package/dist/server/voice-providers-status.d.ts.map +1 -1
  214. package/dist/server/voice-providers-status.js +1 -0
  215. package/dist/server/voice-providers-status.js.map +1 -1
  216. package/dist/templates/default/_gitignore +5 -1
  217. package/dist/templates/default/app/root.tsx +1 -0
  218. package/dist/templates/default/public/favicon.svg +3 -3
  219. package/dist/templates/default/public/icon-180.svg +3 -3
  220. package/dist/templates/default/public/icon-192.svg +3 -3
  221. package/dist/templates/default/public/icon-512.svg +3 -3
  222. package/dist/templates/workspace-core/AGENTS.md +23 -7
  223. package/dist/templates/workspace-core/package.json +2 -1
  224. package/dist/templates/workspace-core/src/credentials.ts +22 -11
  225. package/dist/templates/workspace-root/.env.example +7 -0
  226. package/dist/templates/workspace-root/README.md +6 -3
  227. package/dist/templates/workspace-root/_gitignore +3 -0
  228. package/dist/templates/workspace-root/package.json +3 -1
  229. package/dist/templates/workspace-root/scripts/workspace-dev.ts +410 -0
  230. package/dist/tools/actions.d.ts.map +1 -1
  231. package/dist/tools/actions.js +2 -0
  232. package/dist/tools/actions.js.map +1 -1
  233. package/dist/tools/html-shell.d.ts.map +1 -1
  234. package/dist/tools/html-shell.js +13 -1
  235. package/dist/tools/html-shell.js.map +1 -1
  236. package/dist/tools/store.d.ts.map +1 -1
  237. package/dist/tools/store.js +16 -11
  238. package/dist/tools/store.js.map +1 -1
  239. package/dist/tracking/providers.d.ts +1 -0
  240. package/dist/tracking/providers.d.ts.map +1 -1
  241. package/dist/tracking/providers.js +72 -0
  242. package/dist/tracking/providers.js.map +1 -1
  243. package/dist/vite/action-types-plugin.d.ts.map +1 -1
  244. package/dist/vite/action-types-plugin.js +106 -9
  245. package/dist/vite/action-types-plugin.js.map +1 -1
  246. package/dist/vite/client.d.ts.map +1 -1
  247. package/dist/vite/client.js +67 -2
  248. package/dist/vite/client.js.map +1 -1
  249. package/docs/content/authentication.md +17 -13
  250. package/docs/content/deployment.md +11 -11
  251. package/docs/content/mcp-clients.md +2 -2
  252. package/docs/content/onboarding.md +32 -30
  253. package/docs/content/security.md +1 -1
  254. package/docs/content/tools.md +4 -0
  255. package/package.json +2 -2
  256. package/src/templates/default/_gitignore +5 -1
  257. package/src/templates/default/app/root.tsx +1 -0
  258. package/src/templates/default/public/favicon.svg +3 -3
  259. package/src/templates/default/public/icon-180.svg +3 -3
  260. package/src/templates/default/public/icon-192.svg +3 -3
  261. package/src/templates/default/public/icon-512.svg +3 -3
  262. package/src/templates/workspace-core/AGENTS.md +23 -7
  263. package/src/templates/workspace-core/package.json +2 -1
  264. package/src/templates/workspace-core/src/credentials.ts +22 -11
  265. package/src/templates/workspace-root/.env.example +7 -0
  266. package/src/templates/workspace-root/README.md +6 -3
  267. package/src/templates/workspace-root/_gitignore +3 -0
  268. package/src/templates/workspace-root/package.json +3 -1
  269. package/src/templates/workspace-root/scripts/workspace-dev.ts +410 -0
@@ -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;AAE7B,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,CAAC,CAAC;IACnE,OAAO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,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\";\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]);\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\nasync function rewriteMountedResponse(response, basePath) {\n if (!basePath) 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(prefixMountedHtml(html, basePath), {\n status: response.status,\n statusText: response.statusText,\n headers,\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 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 const builtinsPattern = [\n \"fs\",\n \"fs/promises\",\n \"path\",\n \"os\",\n \"crypto\",\n \"http\",\n \"https\",\n \"stream\",\n \"stream/web\",\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 \"async_hooks\",\n \"process\",\n \"worker_threads\",\n \"sqlite\",\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 \"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\nfunction 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 // Only shim the commonly-used builtins to keep it small\n const shimmed = [\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 ];\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 // 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 \"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 \"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;AAE7B,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,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B,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\";\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]);\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\nasync function rewriteMountedResponse(response, basePath) {\n if (!basePath) 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(prefixMountedHtml(html, basePath), {\n status: response.status,\n statusText: response.statusText,\n headers,\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 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 const builtinsPattern = [\n \"fs\",\n \"fs/promises\",\n \"path\",\n \"os\",\n \"crypto\",\n \"http\",\n \"https\",\n \"stream\",\n \"stream/web\",\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 \"async_hooks\",\n \"process\",\n \"worker_threads\",\n \"sqlite\",\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 // Only shim the commonly-used builtins to keep it small\n const shimmed = [\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 ];\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 // 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 +1 @@
1
- {"version":3,"file":"pending-tasks-retry-job.d.ts","sourceRoot":"","sources":["../../src/integrations/pending-tasks-retry-job.ts"],"names":[],"mappings":"AAqDA;;;GAGG;AACH,wBAAsB,sBAAsB,CAC1C,cAAc,CAAC,EAAE,MAAM,GACtB,OAAO,CAAC,IAAI,CAAC,CA4Ff;AAkED;;;GAGG;AACH,wBAAgB,yBAAyB,CAAC,OAAO,CAAC,EAAE;IAClD,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB,GAAG,IAAI,CAwBP;AAED,2BAA2B;AAC3B,wBAAgB,wBAAwB,IAAI,IAAI,CAM/C"}
1
+ {"version":3,"file":"pending-tasks-retry-job.d.ts","sourceRoot":"","sources":["../../src/integrations/pending-tasks-retry-job.ts"],"names":[],"mappings":"AAqDA;;;GAGG;AACH,wBAAsB,sBAAsB,CAC1C,cAAc,CAAC,EAAE,MAAM,GACtB,OAAO,CAAC,IAAI,CAAC,CA2Ff;AAkED;;;GAGG;AACH,wBAAgB,yBAAyB,CAAC,OAAO,CAAC,EAAE;IAClD,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB,GAAG,IAAI,CAwBP;AAED,2BAA2B;AAC3B,wBAAgB,wBAAwB,IAAI,IAAI,CAM/C"}
@@ -75,7 +75,7 @@ export async function retryStuckPendingTasks(webhookBaseUrl) {
75
75
  if (tableExists !== false) {
76
76
  tableExists = false;
77
77
  if (process.env.DEBUG) {
78
- console.log("[integrations] pending-tasks retry job: table not present yet, skipping", err);
78
+ console.log("[integrations] pending-tasks retry job: table not present yet, skipping");
79
79
  }
80
80
  }
81
81
  return;
@@ -1 +1 @@
1
- {"version":3,"file":"pending-tasks-retry-job.js","sourceRoot":"","sources":["../../src/integrations/pending-tasks-retry-job.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EAAE,sBAAsB,EAAE,MAAM,iCAAiC,CAAC;AACzE,OAAO,EAAE,yBAAyB,EAAE,MAAM,4BAA4B,CAAC;AACvE,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAExD;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,MAAM,iBAAiB,GAAG,MAAM,CAAC;AACjC,8EAA8E;AAC9E,MAAM,sBAAsB,GAAG,MAAM,CAAC;AACtC,2EAA2E;AAC3E,MAAM,yBAAyB,GAAG,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC;AAChD,mEAAmE;AACnE,MAAM,YAAY,GAAG,CAAC,CAAC;AAEvB,MAAM,cAAc,GAAG,GAAG,sBAAsB,4BAA4B,CAAC;AAE7E,IAAI,aAAa,GAA0C,IAAI,CAAC;AAChE,IAAI,oBAAwC,CAAC;AAC7C;;;GAGG;AACH,IAAI,WAAW,GAAmB,IAAI,C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M;SAC1B,CAAC,CAAC;IACL,CAAC;YAAS,CAAC;QACT,YAAY,CAAC,KAAK,CAAC,CAAC;IACtB,CAAC;AACH,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,yBAAyB,CAAC,OAEzC;IACC,IAAI,aAAa;QAAE,OAAO;IAC1B,oBAAoB,GAAG,OAAO,EAAE,cAAc,CAAC;IAE/C,6EAA6E;IAC7E,UAAU,CAAC,GAAG,EAAE;QACd,KAAK,sBAAsB,EAAE,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE;YAC1C,OAAO,CAAC,KAAK,CAAC,+CAA+C,EAAE,GAAG,CAAC,CAAC;QACtE,CAAC,CAAC,CAAC;IACL,CAAC,EAAE,MAAM,CAAC,CAAC;IAEX,aAAa,GAAG,WAAW,CAAC,GAAG,EAAE;QAC/B,KAAK,sBAAsB,EAAE,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE;YAC1C,OAAO,CAAC,KAAK,CAAC,+CAA+C,EAAE,GAAG,CAAC,CAAC;QACtE,CAAC,CAAC,CAAC;IACL,CAAC,EAAE,iBAAiB,CAAC,CAAC;IAEtB,IAAI,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC;QACtB,OAAO,CAAC,GAAG,CACT,yDACE,iBAAiB,GAAG,IACtB,IAAI,CACL,CAAC;IACJ,CAAC;AACH,CAAC;AAED,2BAA2B;AAC3B,MAAM,UAAU,wBAAwB;IACtC,IAAI,aAAa,EAAE,CAAC;QAClB,aAAa,CAAC,aAAa,CAAC,CAAC;QAC7B,aAAa,GAAG,IAAI,CAAC;IACvB,CAAC;IACD,oBAAoB,GAAG,SAAS,CAAC;AACnC,CAAC","sourcesContent":["import { getDbExec } from \"../db/client.js\";\nimport { FRAMEWORK_ROUTE_PREFIX } from \"../server/core-routes-plugin.js\";\nimport { withConfiguredAppBasePath } from \"../server/app-base-path.js\";\nimport { signInternalToken } from \"./internal-token.js\";\n\n/**\n * Retries stuck integration webhook tasks.\n *\n * The integration webhook flow enqueues work into `integration_pending_tasks`\n * (see `pending-tasks-store.ts`) and then fires a self-webhook to the\n * `/_agent-native/integrations/process-task` endpoint to drain the queue.\n * If that fire-and-forget dispatch fails (e.g. transient network blip), the\n * row stays in `pending` forever. Likewise, if the processor is killed mid-\n * processing (function timeout, container shutdown), a row can remain in\n * `processing` forever.\n *\n * This job runs every 60s and re-fires the processor endpoint for tasks that\n * look stuck:\n * - status='pending' AND created_at older than 90s (initial dispatch lost)\n * - status='processing' AND updated_at older than 5min (killed mid-flight)\n *\n * Retries are capped at MAX_ATTEMPTS attempts; after that the row is marked\n * `failed` permanently so it stops being retried.\n *\n * If the `integration_pending_tasks` table does not yet exist (e.g. older\n * deploy that hasn't run the new webhook flow), this job no-ops silently\n * rather than spamming logs.\n */\n\nconst RETRY_INTERVAL_MS = 60_000;\n/** Tasks pending longer than this are considered stuck on initial dispatch */\nconst PENDING_STUCK_AFTER_MS = 90_000;\n/** Tasks \"processing\" longer than this are considered killed mid-flight */\nconst PROCESSING_STUCK_AFTER_MS = 5 * 60 * 1000;\n/** After this many attempts we give up and mark the task failed */\nconst MAX_ATTEMPTS = 3;\n\nconst PROCESSOR_PATH = `${FRAMEWORK_ROUTE_PREFIX}/integrations/process-task`;\n\nlet retryInterval: ReturnType<typeof setInterval> | null = null;\nlet activeWebhookBaseUrl: string | undefined;\n/**\n * Whether the table exists. Cached after first probe so we don't log every\n * minute when the queue isn't in use yet on a given deployment.\n */\nlet tableExists: boolean | null = null;\n\ninterface StuckTaskRow {\n id: string;\n status: string;\n attempts: number;\n}\n\n/**\n * One pass: find stuck tasks and re-fire the processor for each.\n * Exported for tests and for manual triggers.\n */\nexport async function retryStuckPendingTasks(\n webhookBaseUrl?: string,\n): Promise<void> {\n const baseUrl = webhookBaseUrl ?? activeWebhookBaseUrl;\n const client = getDbExec();\n const now = Date.now();\n const pendingCutoff = now - PENDING_STUCK_AFTER_MS;\n const processingCutoff = now - PROCESSING_STUCK_AFTER_MS;\n\n let stuckRows: StuckTaskRow[];\n try {\n const { rows } = await client.execute({\n sql: `\n SELECT id, status, attempts\n FROM integration_pending_tasks\n WHERE (status = 'pending' AND created_at <= ?)\n OR (status = 'processing' AND updated_at <= ?)\n `,\n args: [pendingCutoff, processingCutoff],\n });\n stuckRows = rows.map((r) => ({\n id: r.id as string,\n status: r.status as string,\n attempts: Number(r.attempts ?? 0),\n }));\n tableExists = true;\n } catch (err) {\n // Most common case: the table hasn't been created yet because no inbound\n // integration webhook has been processed on this deployment. Silently\n // no-op until the table appears.\n if (tableExists !== false) {\n tableExists = false;\n if (process.env.DEBUG) {\n console.log(\n \"[integrations] pending-tasks retry job: table not present yet, skipping\",\n err,\n );\n }\n }\n return;\n }\n\n if (stuckRows.length === 0) return;\n\n for (const row of stuckRows) {\n try {\n // Cap retries — mark failed and move on so the row stops bouncing\n // between pending and processing forever.\n if (row.attempts >= MAX_ATTEMPTS) {\n await client.execute({\n sql: `\n UPDATE integration_pending_tasks\n SET status = 'failed',\n updated_at = ?,\n error_message = COALESCE(error_message, ?)\n WHERE id = ?\n AND status = ?\n `,\n args: [\n Date.now(),\n `Retry job: exceeded ${MAX_ATTEMPTS} attempts`,\n row.id,\n row.status,\n ],\n });\n console.warn(\n `[integrations] Pending task ${row.id} exceeded ${MAX_ATTEMPTS} attempts — marking failed`,\n );\n continue;\n }\n\n // Reset stuck `processing` rows back to `pending` so the processor's\n // atomic claim (which only matches pending) can re-acquire it.\n // Without this, processing rows stay stuck forever.\n // For pending rows, just touch updated_at to avoid re-firing every tick.\n const newStatus = row.status === \"processing\" ? \"pending\" : row.status;\n await client.execute({\n sql: `\n UPDATE integration_pending_tasks\n SET status = ?, updated_at = ?\n WHERE id = ?\n AND status = ?\n `,\n args: [newStatus, Date.now(), row.id, row.status],\n });\n\n await refireProcessor(row.id, baseUrl);\n } catch (err) {\n console.error(\n `[integrations] Failed to retry pending task ${row.id}:`,\n err,\n );\n }\n }\n}\n\n/**\n * Fire-and-forget POST to the processor endpoint for a single task id.\n * Mirrors the original dispatch from the webhook handler, including the\n * short-lived HMAC bearer token bound to this taskId.\n */\nasync function refireProcessor(\n taskId: string,\n webhookBaseUrl: string | undefined,\n): Promise<void> {\n const baseUrl =\n webhookBaseUrl ||\n process.env.WEBHOOK_BASE_URL ||\n process.env.APP_URL ||\n process.env.URL ||\n process.env.DEPLOY_URL ||\n `http://localhost:${process.env.PORT || 3000}`;\n\n const url = `${withConfiguredAppBasePath(baseUrl)}${PROCESSOR_PATH}`;\n\n // Sign with HMAC if A2A_SECRET is configured. In production we MUST sign —\n // an unsigned dispatch in production lets attackers re-trigger any queued\n // task with a guessable id (C3 in the webhook security audit). In dev we\n // fall back to unsigned so contributors can iterate without configuring\n // A2A_SECRET locally.\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n try {\n headers[\"Authorization\"] = `Bearer ${signInternalToken(taskId)}`;\n } catch (err) {\n if (process.env.NODE_ENV === \"production\") {\n console.error(\n `[integrations] Refusing to dispatch task ${taskId} — A2A_SECRET not configured. ` +\n \"Set A2A_SECRET to enable signed retry dispatches.\",\n );\n return;\n }\n // Dev: proceed unsigned. Log the underlying error path so a malformed\n // secret (different from \"not set\") doesn't fail silently (L5 in the audit).\n if (err instanceof Error && !/A2A_SECRET/i.test(err.message)) {\n console.error(\n `[integrations] signInternalToken failed unexpectedly for ${taskId}:`,\n err,\n );\n }\n }\n\n // Don't await the body — we just want the request to leave the box.\n // A short timeout avoids tying up the retry loop on a hung processor.\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), 5_000);\n\n try {\n await fetch(url, {\n method: \"POST\",\n headers,\n body: JSON.stringify({ taskId }),\n signal: controller.signal,\n });\n } finally {\n clearTimeout(timer);\n }\n}\n\n/**\n * Start the periodic retry loop. Safe to call multiple times — second call\n * is a no-op.\n */\nexport function startPendingTasksRetryJob(options?: {\n webhookBaseUrl?: string;\n}): void {\n if (retryInterval) return;\n activeWebhookBaseUrl = options?.webhookBaseUrl;\n\n // Stagger the first run a bit so we don't hammer the DB immediately on boot.\n setTimeout(() => {\n void retryStuckPendingTasks().catch((err) => {\n console.error(\"[integrations] Pending-tasks retry job error:\", err);\n });\n }, 10_000);\n\n retryInterval = setInterval(() => {\n void retryStuckPendingTasks().catch((err) => {\n console.error(\"[integrations] Pending-tasks retry job error:\", err);\n });\n }, RETRY_INTERVAL_MS);\n\n if (process.env.DEBUG) {\n console.log(\n `[integrations] Pending-tasks retry job started (every ${\n RETRY_INTERVAL_MS / 1000\n }s)`,\n );\n }\n}\n\n/** Stop the retry loop. */\nexport function stopPendingTasksRetryJob(): void {\n if (retryInterval) {\n clearInterval(retryInterval);\n retryInterval = null;\n }\n activeWebhookBaseUrl = undefined;\n}\n"]}
1
+ {"version":3,"file":"pending-tasks-retry-job.js","sourceRoot":"","sources":["../../src/integrations/pending-tasks-retry-job.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EAAE,sBAAsB,EAAE,MAAM,iCAAiC,CAAC;AACzE,OAAO,EAAE,yBAAyB,EAAE,MAAM,4BAA4B,CAAC;AACvE,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAExD;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,MAAM,iBAAiB,GAAG,MAAM,CAAC;AACjC,8EAA8E;AAC9E,MAAM,sBAAsB,GAAG,MAAM,CAAC;AACtC,2EAA2E;AAC3E,MAAM,yBAAyB,GAAG,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC;AAChD,mEAAmE;AACnE,MAAM,YAAY,GAAG,CAAC,CAAC;AAEvB,MAAM,cAAc,GAAG,GAAG,sBAAsB,4BAA4B,CAAC;AAE7E,IAAI,aAAa,GAA0C,IAAI,CAAC;AAChE,IAAI,oBAAwC,CAAC;AAC7C;;;GAGG;AACH,IAAI,WAAW,GAAmB,IAAI,CAAC;AAQvC;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,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,KAAK,CAAC,CAAC;IACtB,CAAC;AACH,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,yBAAyB,CAAC,OAEzC;IACC,IAAI,aAAa;QAAE,OAAO;IAC1B,oBAAoB,GAAG,OAAO,EAAE,cAAc,CAAC;IAE/C,6EAA6E;IAC7E,UAAU,CAAC,GAAG,EAAE;QACd,KAAK,sBAAsB,EAAE,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE;YAC1C,OAAO,CAAC,KAAK,CAAC,+CAA+C,EAAE,GAAG,CAAC,CAAC;QACtE,CAAC,CAAC,CAAC;IACL,CAAC,EAAE,MAAM,CAAC,CAAC;IAEX,aAAa,GAAG,WAAW,CAAC,GAAG,EAAE;QAC/B,KAAK,sBAAsB,EAAE,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE;YAC1C,OAAO,CAAC,KAAK,CAAC,+CAA+C,EAAE,GAAG,CAAC,CAAC;QACtE,CAAC,CAAC,CAAC;IACL,CAAC,EAAE,iBAAiB,CAAC,CAAC;IAEtB,IAAI,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC;QACtB,OAAO,CAAC,GAAG,CACT,yDACE,iBAAiB,GAAG,IACtB,IAAI,CACL,CAAC;IACJ,CAAC;AACH,CAAC;AAED,2BAA2B;AAC3B,MAAM,UAAU,wBAAwB;IACtC,IAAI,aAAa,EAAE,CAAC;QAClB,aAAa,CAAC,aAAa,CAAC,CAAC;QAC7B,aAAa,GAAG,IAAI,CAAC;IACvB,CAAC;IACD,oBAAoB,GAAG,SAAS,CAAC;AACnC,CAAC","sourcesContent":["import { getDbExec } from \"../db/client.js\";\nimport { FRAMEWORK_ROUTE_PREFIX } from \"../server/core-routes-plugin.js\";\nimport { withConfiguredAppBasePath } from \"../server/app-base-path.js\";\nimport { signInternalToken } from \"./internal-token.js\";\n\n/**\n * Retries stuck integration webhook tasks.\n *\n * The integration webhook flow enqueues work into `integration_pending_tasks`\n * (see `pending-tasks-store.ts`) and then fires a self-webhook to the\n * `/_agent-native/integrations/process-task` endpoint to drain the queue.\n * If that fire-and-forget dispatch fails (e.g. transient network blip), the\n * row stays in `pending` forever. Likewise, if the processor is killed mid-\n * processing (function timeout, container shutdown), a row can remain in\n * `processing` forever.\n *\n * This job runs every 60s and re-fires the processor endpoint for tasks that\n * look stuck:\n * - status='pending' AND created_at older than 90s (initial dispatch lost)\n * - status='processing' AND updated_at older than 5min (killed mid-flight)\n *\n * Retries are capped at MAX_ATTEMPTS attempts; after that the row is marked\n * `failed` permanently so it stops being retried.\n *\n * If the `integration_pending_tasks` table does not yet exist (e.g. older\n * deploy that hasn't run the new webhook flow), this job no-ops silently\n * rather than spamming logs.\n */\n\nconst RETRY_INTERVAL_MS = 60_000;\n/** Tasks pending longer than this are considered stuck on initial dispatch */\nconst PENDING_STUCK_AFTER_MS = 90_000;\n/** Tasks \"processing\" longer than this are considered killed mid-flight */\nconst PROCESSING_STUCK_AFTER_MS = 5 * 60 * 1000;\n/** After this many attempts we give up and mark the task failed */\nconst MAX_ATTEMPTS = 3;\n\nconst PROCESSOR_PATH = `${FRAMEWORK_ROUTE_PREFIX}/integrations/process-task`;\n\nlet retryInterval: ReturnType<typeof setInterval> | null = null;\nlet activeWebhookBaseUrl: string | undefined;\n/**\n * Whether the table exists. Cached after first probe so we don't log every\n * minute when the queue isn't in use yet on a given deployment.\n */\nlet tableExists: boolean | null = null;\n\ninterface StuckTaskRow {\n id: string;\n status: string;\n attempts: number;\n}\n\n/**\n * One pass: find stuck tasks and re-fire the processor for each.\n * Exported for tests and for manual triggers.\n */\nexport async function retryStuckPendingTasks(\n webhookBaseUrl?: string,\n): Promise<void> {\n const baseUrl = webhookBaseUrl ?? activeWebhookBaseUrl;\n const client = getDbExec();\n const now = Date.now();\n const pendingCutoff = now - PENDING_STUCK_AFTER_MS;\n const processingCutoff = now - PROCESSING_STUCK_AFTER_MS;\n\n let stuckRows: StuckTaskRow[];\n try {\n const { rows } = await client.execute({\n sql: `\n SELECT id, status, attempts\n FROM integration_pending_tasks\n WHERE (status = 'pending' AND created_at <= ?)\n OR (status = 'processing' AND updated_at <= ?)\n `,\n args: [pendingCutoff, processingCutoff],\n });\n stuckRows = rows.map((r) => ({\n id: r.id as string,\n status: r.status as string,\n attempts: Number(r.attempts ?? 0),\n }));\n tableExists = true;\n } catch (err) {\n // Most common case: the table hasn't been created yet because no inbound\n // integration webhook has been processed on this deployment. Silently\n // no-op until the table appears.\n if (tableExists !== false) {\n tableExists = false;\n if (process.env.DEBUG) {\n console.log(\n \"[integrations] pending-tasks retry job: table not present yet, skipping\",\n );\n }\n }\n return;\n }\n\n if (stuckRows.length === 0) return;\n\n for (const row of stuckRows) {\n try {\n // Cap retries — mark failed and move on so the row stops bouncing\n // between pending and processing forever.\n if (row.attempts >= MAX_ATTEMPTS) {\n await client.execute({\n sql: `\n UPDATE integration_pending_tasks\n SET status = 'failed',\n updated_at = ?,\n error_message = COALESCE(error_message, ?)\n WHERE id = ?\n AND status = ?\n `,\n args: [\n Date.now(),\n `Retry job: exceeded ${MAX_ATTEMPTS} attempts`,\n row.id,\n row.status,\n ],\n });\n console.warn(\n `[integrations] Pending task ${row.id} exceeded ${MAX_ATTEMPTS} attempts — marking failed`,\n );\n continue;\n }\n\n // Reset stuck `processing` rows back to `pending` so the processor's\n // atomic claim (which only matches pending) can re-acquire it.\n // Without this, processing rows stay stuck forever.\n // For pending rows, just touch updated_at to avoid re-firing every tick.\n const newStatus = row.status === \"processing\" ? \"pending\" : row.status;\n await client.execute({\n sql: `\n UPDATE integration_pending_tasks\n SET status = ?, updated_at = ?\n WHERE id = ?\n AND status = ?\n `,\n args: [newStatus, Date.now(), row.id, row.status],\n });\n\n await refireProcessor(row.id, baseUrl);\n } catch (err) {\n console.error(\n `[integrations] Failed to retry pending task ${row.id}:`,\n err,\n );\n }\n }\n}\n\n/**\n * Fire-and-forget POST to the processor endpoint for a single task id.\n * Mirrors the original dispatch from the webhook handler, including the\n * short-lived HMAC bearer token bound to this taskId.\n */\nasync function refireProcessor(\n taskId: string,\n webhookBaseUrl: string | undefined,\n): Promise<void> {\n const baseUrl =\n webhookBaseUrl ||\n process.env.WEBHOOK_BASE_URL ||\n process.env.APP_URL ||\n process.env.URL ||\n process.env.DEPLOY_URL ||\n `http://localhost:${process.env.PORT || 3000}`;\n\n const url = `${withConfiguredAppBasePath(baseUrl)}${PROCESSOR_PATH}`;\n\n // Sign with HMAC if A2A_SECRET is configured. In production we MUST sign —\n // an unsigned dispatch in production lets attackers re-trigger any queued\n // task with a guessable id (C3 in the webhook security audit). In dev we\n // fall back to unsigned so contributors can iterate without configuring\n // A2A_SECRET locally.\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n try {\n headers[\"Authorization\"] = `Bearer ${signInternalToken(taskId)}`;\n } catch (err) {\n if (process.env.NODE_ENV === \"production\") {\n console.error(\n `[integrations] Refusing to dispatch task ${taskId} — A2A_SECRET not configured. ` +\n \"Set A2A_SECRET to enable signed retry dispatches.\",\n );\n return;\n }\n // Dev: proceed unsigned. Log the underlying error path so a malformed\n // secret (different from \"not set\") doesn't fail silently (L5 in the audit).\n if (err instanceof Error && !/A2A_SECRET/i.test(err.message)) {\n console.error(\n `[integrations] signInternalToken failed unexpectedly for ${taskId}:`,\n err,\n );\n }\n }\n\n // Don't await the body — we just want the request to leave the box.\n // A short timeout avoids tying up the retry loop on a hung processor.\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), 5_000);\n\n try {\n await fetch(url, {\n method: \"POST\",\n headers,\n body: JSON.stringify({ taskId }),\n signal: controller.signal,\n });\n } finally {\n clearTimeout(timer);\n }\n}\n\n/**\n * Start the periodic retry loop. Safe to call multiple times — second call\n * is a no-op.\n */\nexport function startPendingTasksRetryJob(options?: {\n webhookBaseUrl?: string;\n}): void {\n if (retryInterval) return;\n activeWebhookBaseUrl = options?.webhookBaseUrl;\n\n // Stagger the first run a bit so we don't hammer the DB immediately on boot.\n setTimeout(() => {\n void retryStuckPendingTasks().catch((err) => {\n console.error(\"[integrations] Pending-tasks retry job error:\", err);\n });\n }, 10_000);\n\n retryInterval = setInterval(() => {\n void retryStuckPendingTasks().catch((err) => {\n console.error(\"[integrations] Pending-tasks retry job error:\", err);\n });\n }, RETRY_INTERVAL_MS);\n\n if (process.env.DEBUG) {\n console.log(\n `[integrations] Pending-tasks retry job started (every ${\n RETRY_INTERVAL_MS / 1000\n }s)`,\n );\n }\n}\n\n/** Stop the retry loop. */\nexport function stopPendingTasksRetryJob(): void {\n if (retryInterval) {\n clearInterval(retryInterval);\n retryInterval = null;\n }\n activeWebhookBaseUrl = undefined;\n}\n"]}
@@ -1,3 +1,3 @@
1
- export { getOAuthTokens, saveOAuthTokens, deleteOAuthTokens, listOAuthAccounts, listOAuthAccountsByOwner, hasOAuthTokens, setOAuthDisplayName, } from "./store.js";
1
+ export { getOAuthTokens, OAuthAccountOwnedByOtherUserError, saveOAuthTokens, deleteOAuthTokens, listOAuthAccounts, listOAuthAccountsByOwner, hasOAuthTokens, setOAuthDisplayName, } from "./store.js";
2
2
  export { refreshExpiringGoogleTokens, startGoogleTokenRefreshLoop, } from "./google-refresh.js";
3
3
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/oauth-tokens/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,EACd,eAAe,EACf,iBAAiB,EACjB,iBAAiB,EACjB,wBAAwB,EACxB,cAAc,EACd,mBAAmB,GACpB,MAAM,YAAY,CAAC;AAEpB,OAAO,EACL,2BAA2B,EAC3B,2BAA2B,GAC5B,MAAM,qBAAqB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/oauth-tokens/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,EACd,iCAAiC,EACjC,eAAe,EACf,iBAAiB,EACjB,iBAAiB,EACjB,wBAAwB,EACxB,cAAc,EACd,mBAAmB,GACpB,MAAM,YAAY,CAAC;AAEpB,OAAO,EACL,2BAA2B,EAC3B,2BAA2B,GAC5B,MAAM,qBAAqB,CAAC"}
@@ -1,3 +1,3 @@
1
- export { getOAuthTokens, saveOAuthTokens, deleteOAuthTokens, listOAuthAccounts, listOAuthAccountsByOwner, hasOAuthTokens, setOAuthDisplayName, } from "./store.js";
1
+ export { getOAuthTokens, OAuthAccountOwnedByOtherUserError, saveOAuthTokens, deleteOAuthTokens, listOAuthAccounts, listOAuthAccountsByOwner, hasOAuthTokens, setOAuthDisplayName, } from "./store.js";
2
2
  export { refreshExpiringGoogleTokens, startGoogleTokenRefreshLoop, } from "./google-refresh.js";
3
3
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/oauth-tokens/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,EACd,eAAe,EACf,iBAAiB,EACjB,iBAAiB,EACjB,wBAAwB,EACxB,cAAc,EACd,mBAAmB,GACpB,MAAM,YAAY,CAAC;AAEpB,OAAO,EACL,2BAA2B,EAC3B,2BAA2B,GAC5B,MAAM,qBAAqB,CAAC","sourcesContent":["export {\n getOAuthTokens,\n saveOAuthTokens,\n deleteOAuthTokens,\n listOAuthAccounts,\n listOAuthAccountsByOwner,\n hasOAuthTokens,\n setOAuthDisplayName,\n} from \"./store.js\";\n\nexport {\n refreshExpiringGoogleTokens,\n startGoogleTokenRefreshLoop,\n} from \"./google-refresh.js\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/oauth-tokens/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,EACd,iCAAiC,EACjC,eAAe,EACf,iBAAiB,EACjB,iBAAiB,EACjB,wBAAwB,EACxB,cAAc,EACd,mBAAmB,GACpB,MAAM,YAAY,CAAC;AAEpB,OAAO,EACL,2BAA2B,EAC3B,2BAA2B,GAC5B,MAAM,qBAAqB,CAAC","sourcesContent":["export {\n getOAuthTokens,\n OAuthAccountOwnedByOtherUserError,\n saveOAuthTokens,\n deleteOAuthTokens,\n listOAuthAccounts,\n listOAuthAccountsByOwner,\n hasOAuthTokens,\n setOAuthDisplayName,\n} from \"./store.js\";\n\nexport {\n refreshExpiringGoogleTokens,\n startGoogleTokenRefreshLoop,\n} from \"./google-refresh.js\";\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../src/oauth-tokens/store.ts"],"names":[],"mappings":"AAyCA,wBAAsB,cAAc,CAClC,QAAQ,EAAE,MAAM,EAChB,SAAS,EAAE,MAAM,GAChB,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC,CASzC;AAED;;;;;;;;GAQG;AACH,qBAAa,iCAAkC,SAAQ,KAAK;IAC1D,QAAQ,CAAC,UAAU,OAAO;IAC1B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAC/B,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;gBACpB,IAAI,EAAE;QAChB,QAAQ,EAAE,MAAM,CAAC;QACjB,SAAS,EAAE,MAAM,CAAC;QAClB,aAAa,EAAE,MAAM,CAAC;QACtB,cAAc,EAAE,MAAM,CAAC;KACxB;CAUF;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,eAAe,CACnC,QAAQ,EAAE,MAAM,EAChB,SAAS,EAAE,MAAM,EACjB,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC/B,KAAK,CAAC,EAAE,MAAM,GACb,OAAO,CAAC,IAAI,CAAC,CAwDf;AAED,wBAAsB,iBAAiB,CACrC,QAAQ,EAAE,MAAM,EAChB,SAAS,CAAC,EAAE,MAAM,GACjB,OAAO,CAAC,MAAM,CAAC,CAejB;AAED,wBAAsB,iBAAiB,CAAC,QAAQ,EAAE,MAA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