@agent-native/core 0.84.32 → 0.84.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/corpus/README.md +1 -1
  2. package/corpus/core/CHANGELOG.md +20 -0
  3. package/corpus/core/package.json +1 -1
  4. package/corpus/core/src/a2a/response-text.ts +10 -1
  5. package/corpus/core/src/agent/production-agent.ts +23 -20
  6. package/corpus/core/src/agent/run-manager.ts +46 -1
  7. package/corpus/core/src/agent/thread-data-builder.ts +15 -2
  8. package/corpus/core/src/client/code-agent-chat-adapter.ts +8 -1
  9. package/corpus/core/src/client/sse-event-processor.ts +21 -3
  10. package/corpus/core/src/client/use-action.ts +5 -1
  11. package/corpus/core/src/code-agents/transcript-normalizer.ts +31 -0
  12. package/corpus/core/src/server/agent-chat-plugin.ts +8 -2
  13. package/corpus/core/src/server/agent-teams.ts +24 -2
  14. package/corpus/core/src/server/ssr-handler.ts +12 -0
  15. package/corpus/core/src/vite/action-types-plugin.ts +6 -2
  16. package/corpus/core/src/vite/client.ts +152 -17
  17. package/corpus/templates/analytics/changelog/2026-07-01-smoother-chat-streaming.md +6 -0
  18. package/corpus/templates/design/actions/import-design-source.ts +158 -0
  19. package/corpus/templates/design/actions/navigate.ts +3 -2
  20. package/corpus/templates/design/actions/view-screen.ts +1 -1
  21. package/corpus/templates/design/app/components/design/DesignImportPanel.tsx +519 -0
  22. package/corpus/templates/design/app/hooks/use-navigation-state.ts +28 -5
  23. package/corpus/templates/design/app/i18n/zh-TW.ts +40 -0
  24. package/corpus/templates/design/app/i18n-data.ts +508 -0
  25. package/corpus/templates/design/app/pages/DesignEditor.tsx +27 -0
  26. package/corpus/templates/design/changelog/2026-07-01-design-can-import-figma-paste-fig-files-and-standalone-html.md +6 -0
  27. package/corpus/templates/design/package.json +3 -0
  28. package/corpus/templates/design/server/handlers/import-design-file.ts +168 -0
  29. package/corpus/templates/design/server/lib/figma-import/clipboard.ts +122 -0
  30. package/corpus/templates/design/server/lib/figma-import/decode.ts +455 -0
  31. package/corpus/templates/design/server/lib/figma-import/processor.ts +116 -0
  32. package/corpus/templates/design/server/lib/figma-import/render-html.ts +397 -0
  33. package/corpus/templates/design/server/lib/figma-import/types.ts +60 -0
  34. package/corpus/templates/design/server/lib/import-design-files.ts +314 -0
  35. package/corpus/templates/design/server/routes/api/import-design-file.post.ts +1 -0
  36. package/dist/a2a/response-text.d.ts +1 -0
  37. package/dist/a2a/response-text.d.ts.map +1 -1
  38. package/dist/a2a/response-text.js +8 -2
  39. package/dist/a2a/response-text.js.map +1 -1
  40. package/dist/agent/production-agent.d.ts.map +1 -1
  41. package/dist/agent/production-agent.js +31 -27
  42. package/dist/agent/production-agent.js.map +1 -1
  43. package/dist/agent/run-manager.d.ts +12 -0
  44. package/dist/agent/run-manager.d.ts.map +1 -1
  45. package/dist/agent/run-manager.js +32 -1
  46. package/dist/agent/run-manager.js.map +1 -1
  47. package/dist/agent/thread-data-builder.d.ts.map +1 -1
  48. package/dist/agent/thread-data-builder.js +15 -2
  49. package/dist/agent/thread-data-builder.js.map +1 -1
  50. package/dist/client/code-agent-chat-adapter.d.ts.map +1 -1
  51. package/dist/client/code-agent-chat-adapter.js +5 -1
  52. package/dist/client/code-agent-chat-adapter.js.map +1 -1
  53. package/dist/client/sse-event-processor.d.ts.map +1 -1
  54. package/dist/client/sse-event-processor.js +21 -3
  55. package/dist/client/sse-event-processor.js.map +1 -1
  56. package/dist/client/use-action.d.ts +5 -1
  57. package/dist/client/use-action.d.ts.map +1 -1
  58. package/dist/client/use-action.js.map +1 -1
  59. package/dist/code-agents/transcript-normalizer.d.ts.map +1 -1
  60. package/dist/code-agents/transcript-normalizer.js +24 -0
  61. package/dist/code-agents/transcript-normalizer.js.map +1 -1
  62. package/dist/collab/routes.d.ts +1 -1
  63. package/dist/observability/routes.d.ts +3 -3
  64. package/dist/resources/handlers.d.ts +2 -2
  65. package/dist/server/agent-chat-plugin.d.ts.map +1 -1
  66. package/dist/server/agent-chat-plugin.js +2 -3
  67. package/dist/server/agent-chat-plugin.js.map +1 -1
  68. package/dist/server/agent-engine-api-key-route.d.ts +1 -1
  69. package/dist/server/agent-teams.d.ts.map +1 -1
  70. package/dist/server/agent-teams.js +17 -2
  71. package/dist/server/agent-teams.js.map +1 -1
  72. package/dist/server/ssr-handler.d.ts.map +1 -1
  73. package/dist/server/ssr-handler.js +7 -0
  74. package/dist/server/ssr-handler.js.map +1 -1
  75. package/dist/vite/action-types-plugin.d.ts.map +1 -1
  76. package/dist/vite/action-types-plugin.js +6 -2
  77. package/dist/vite/action-types-plugin.js.map +1 -1
  78. package/dist/vite/client.d.ts.map +1 -1
  79. package/dist/vite/client.js +132 -11
  80. package/dist/vite/client.js.map +1 -1
  81. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"ssr-handler.d.ts","sourceRoot":"","sources":["../../src/server/ssr-handler.ts"],"names":[],"mappings":"AA8CA,OAAO,EACL,yBAAyB,EACzB,gCAAgC,EAChC,yBAAyB,GAC1B,MAAM,4BAA4B,CAAC;AA0nBpC;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,MAAM,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,2FAgE5E"}
1
+ {"version":3,"file":"ssr-handler.d.ts","sourceRoot":"","sources":["../../src/server/ssr-handler.ts"],"names":[],"mappings":"AA8CA,OAAO,EACL,yBAAyB,EACzB,gCAAgC,EAChC,yBAAyB,GAC1B,MAAM,4BAA4B,CAAC;AAsoBpC;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,MAAM,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,2FAgE5E"}
@@ -310,6 +310,11 @@ function appendToExistingCspDirective(directives, name, additions) {
310
310
  return;
311
311
  existing.tokens = appendCspTokens(existing.tokens, additions);
312
312
  }
313
+ function ensureCspDirective(directives, name, tokens) {
314
+ if (findCspDirective(directives, name))
315
+ return;
316
+ directives.push({ name, tokens: [...tokens] });
317
+ }
313
318
  function hasStrictNonceScriptPolicy(tokens) {
314
319
  return tokens.some((token) => token === "'strict-dynamic'" || token.startsWith("'nonce-"));
315
320
  }
@@ -358,6 +363,8 @@ function augmentExistingEnforcedCspForFrameworkScripts(policy, options) {
358
363
  appendToExistingOrDefaultCspDirective(directives, "img-src", GA_CSP_IMG_HOSTS);
359
364
  }
360
365
  }
366
+ ensureCspDirective(directives, "object-src", ["'none'"]);
367
+ ensureCspDirective(directives, "base-uri", ["'self'"]);
361
368
  return serializeCsp(directives);
362
369
  }
363
370
  function augmentExistingReportOnlyCspForFrameworkScripts(policy, options) {
@@ -1 +1 @@
1
- {"version":3,"file":"ssr-handler.js","sourceRoot":"","sources":["../../src/server/ssr-handler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,IAAI,CAAC;AACxC;;;;;;;;;;;;;;;;GAgBG;AACH,OAAO,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AAEpD,OAAO,EACL,yBAAyB,EACzB,8BAA8B,GAC/B,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,6BAA6B,EAC7B,gCAAgC,EAChC,8BAA8B,EAC9B,8BAA8B,EAC9B,+BAA+B,EAC/B,qCAAqC,GACtC,MAAM,0BAA0B,CAAC;AAClC,OAAO,EACL,oBAAoB,EACpB,gBAAgB,EAChB,mBAAmB,EACnB,2BAA2B,GAC5B,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACL,yBAAyB,EACzB,gBAAgB,IAAI,yBAAyB,GAC9C,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,qBAAqB,EAAE,MAAM,sBAAsB,CAAC;AAC7D,OAAO,EAAE,uBAAuB,EAAE,MAAM,uBAAuB,CAAC;AAChE,OAAO,EAAE,2BAA2B,EAAE,MAAM,oBAAoB,CAAC;AAEjE,OAAO,EACL,yBAAyB,EACzB,gCAAgC,EAChC,yBAAyB,GAC1B,MAAM,4BAA4B,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AAC,GAAG,CAAC,QAAQ,KAAK,YAAY,CAAC;YACrD,MAAM,IAAI,GAAG,MAAM;gBACjB,CAAC,CAAC,uBAAuB;gBACzB,CAAC,CAAC,0BAA2B,GAAa,EAAE,OAAO,IAAI,GAAG,EAAE,CAAC;YAC/D,OAAO,IAAI,QAAQ,CAAC,IAAI,EAAE;gBACxB,MAAM,EAAE,GAAG;gBACX,OAAO,EAAE,EAAE,cAAc,EAAE,YAAY,EAAE;aAC1C,CAAC,CAAC;QACL,CAAC;IACH,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { defineEventHandler } from \"h3\";\n/**\n * Shared SSR catch-all handler for React Router framework mode.\n *\n * Templates wire this up via:\n *\n * // server/routes/[...page].get.ts\n * import { createH3SSRHandler } from \"@agent-native/core/server/ssr-handler\";\n * export default createH3SSRHandler(\n * () => import(\"virtual:react-router/server-build\"),\n * );\n *\n * The `getBuild` callback MUST live in the template's own source so Vite's\n * @react-router/dev plugin can resolve the `virtual:` module. Pulling the\n * import into core (e.g. via a re-export) puts it in node_modules where\n * Vite's SSR externalizer leaves it untouched and Node's ESM loader rejects\n * the unknown scheme — silently 302'ing every request to \"/\".\n */\nimport { createRequestHandler } from \"react-router\";\n\nimport {\n DEFAULT_SSR_CACHE_HEADERS,\n DEFAULT_SPECULATION_RULES_PATH,\n} from \"../shared/cache-control.js\";\nimport {\n AGENT_NATIVE_SOCIAL_IMAGE_ALT,\n AGENT_NATIVE_SOCIAL_IMAGE_HEIGHT,\n AGENT_NATIVE_SOCIAL_IMAGE_PATH,\n AGENT_NATIVE_SOCIAL_IMAGE_TYPE,\n AGENT_NATIVE_SOCIAL_IMAGE_WIDTH,\n withAgentNativeSocialImageCacheBuster,\n} from \"../shared/social-meta.js\";\nimport {\n GA_CSP_CONNECT_HOSTS,\n GA_CSP_IMG_HOSTS,\n GA_CSP_SCRIPT_HOSTS,\n getGaInlineConfigScriptBody,\n} from \"./analytics.js\";\nimport {\n getAppBasePathFromViteEnv,\n stripAppBasePath as canonicalStripAppBasePath,\n} from \"./app-base-path.js\";\nimport { runWithRequestContext } from \"./request-context.js\";\nimport { computeInlineScriptHash } from \"./security-headers.js\";\nimport { getSentryClientConfigScript } from \"./sentry-config.js\";\n\nexport {\n DEFAULT_SSR_CACHE_HEADERS,\n DEFAULT_SPECULATION_RULES_HEADER,\n DEFAULT_SSR_CACHE_CONTROL,\n} from \"../shared/cache-control.js\";\n\nfunction getAppBasePath(): string {\n return getAppBasePathFromViteEnv();\n}\n\nfunction stripAppBasePath(pathname: string): string {\n return canonicalStripAppBasePath(pathname, getAppBasePath());\n}\n\nfunction stripBasePath(pathname: string, basePath: string): string {\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 requestWithPathname(\n request: Request,\n pathname: string,\n basePath: string,\n): Request {\n const url = new URL(request.url);\n let changed = false;\n if (basePath && pathname === \"/__manifest\") {\n const paths = url.searchParams.get(\"paths\");\n if (paths) {\n const strippedPaths = paths\n .split(\",\")\n .map((path) => stripBasePath(path, basePath))\n .join(\",\");\n if (strippedPaths !== paths) {\n url.searchParams.set(\"paths\", strippedPaths);\n changed = true;\n }\n }\n }\n if (url.pathname !== pathname) {\n url.pathname = pathname;\n changed = true;\n }\n if (!changed) return request;\n const init: RequestInit & { duplex?: \"half\" } = {\n method: request.method,\n headers: request.headers,\n signal: request.signal,\n };\n if (request.body && ![\"GET\", \"HEAD\"].includes(request.method.toUpperCase())) {\n init.body = request.body;\n init.duplex = \"half\";\n }\n return new Request(url, init);\n}\n\nfunction prefixMountedPath(path: string, basePath: string): string {\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: string, basePath: string): string {\n if (!basePath) return html;\n return html\n .replace(\n /\\b(href|src|action|formaction|poster)=([\"'])(\\/(?!\\/)[^\"']*)\\2/g,\n (_match, attr: string, quote: string, path: string) =>\n `${attr}=${quote}${prefixMountedPath(path, basePath)}${quote}`,\n )\n .replace(/url\\(([\"']?)(\\/(?!\\/)[^)'\" ]+)\\1\\)/g, (_match, quote, path) => {\n const q = quote || \"\";\n return `url(${q}${prefixMountedPath(path, basePath)}${q})`;\n });\n}\n\nfunction injectHeadScript(html: string, script: string | null): string {\n if (!script) return html;\n const headCloseIdx = html.indexOf(\"</head>\");\n if (headCloseIdx === -1) return html;\n return html.slice(0, headCloseIdx) + script + html.slice(headCloseIdx);\n}\n\nconst OG_IMAGE_META_RE = /<meta\\b(?=[^>]*\\bproperty=([\"'])og:image\\1)[^>]*>/i;\nconst TWITTER_CARD_META_RE =\n /<meta\\b(?=[^>]*\\bname=([\"'])twitter:card\\1)[^>]*>/i;\nconst TWITTER_IMAGE_META_RE =\n /<meta\\b(?=[^>]*\\bname=([\"'])twitter:image\\1)[^>]*>/i;\n\nfunction defaultSocialImageUrl(requestUrl: string, basePath: string): string {\n return withAgentNativeSocialImageCacheBuster(\n new URL(\n prefixMountedPath(AGENT_NATIVE_SOCIAL_IMAGE_PATH, basePath),\n requestUrl,\n ).toString(),\n );\n}\n\nfunction injectDefaultSocialImageMeta(html: string, imageUrl: string): string {\n const headCloseIdx = html.indexOf(\"</head>\");\n if (headCloseIdx === -1) return html;\n\n const hasAnySocialImage =\n OG_IMAGE_META_RE.test(html) || TWITTER_IMAGE_META_RE.test(html);\n const tags: string[] = [];\n\n if (!hasAnySocialImage) {\n tags.push(`<meta property=\"og:image\" content=\"${imageUrl}\">`);\n tags.push(`<meta property=\"og:image:secure_url\" content=\"${imageUrl}\">`);\n tags.push(\n `<meta property=\"og:image:type\" content=\"${AGENT_NATIVE_SOCIAL_IMAGE_TYPE}\">`,\n );\n tags.push(\n `<meta property=\"og:image:width\" content=\"${AGENT_NATIVE_SOCIAL_IMAGE_WIDTH}\">`,\n );\n tags.push(\n `<meta property=\"og:image:height\" content=\"${AGENT_NATIVE_SOCIAL_IMAGE_HEIGHT}\">`,\n );\n tags.push(\n `<meta property=\"og:image:alt\" content=\"${AGENT_NATIVE_SOCIAL_IMAGE_ALT}\">`,\n );\n }\n if (!TWITTER_CARD_META_RE.test(html)) {\n tags.push(`<meta name=\"twitter:card\" content=\"summary_large_image\">`);\n }\n if (!hasAnySocialImage) {\n tags.push(`<meta name=\"twitter:image\" content=\"${imageUrl}\">`);\n tags.push(\n `<meta name=\"twitter:image:alt\" content=\"${AGENT_NATIVE_SOCIAL_IMAGE_ALT}\">`,\n );\n }\n\n if (tags.length === 0) return html;\n return html.slice(0, headCloseIdx) + tags.join(\"\") + html.slice(headCloseIdx);\n}\n\nfunction isSsrHtmlOrDataResponse(\n headers: Headers,\n status: number,\n pathname: string,\n): boolean {\n if (status < 200 || status >= 400) return false;\n const contentType = headers.get(\"content-type\")?.toLowerCase() ?? \"\";\n if (contentType.includes(\"text/html\")) return true;\n return pathname.endsWith(\".data\") && contentType.includes(\"text/x-script\");\n}\n\n/**\n * Apply the SSR cache policy to the response headers.\n *\n * ┌──────────────────────────────────────────────────────────────────────────┐\n * │ SSR IS A PUBLIC, HARD-CDN-CACHED SHELL — SERVED IDENTICALLY TO EVERYONE. │\n * │ │\n * │ Every SSR HTML / React Router `.data` response gets the same public │\n * │ stale-while-revalidate policy for ALL visitors, authenticated or not, so │\n * │ the edge serves one shared copy and never stampedes origin. │\n * │ │\n * │ DO NOT reintroduce per-user / cookie-based cache variation here (no │\n * │ `private`, no `no-store`, no `Vary: Cookie`, no \"authenticated → don't │\n * │ cache\" branch). That makes pages uncacheable for every logged-in visitor, │\n * │ which is slow and expensive — exactly the regression this guardrail │\n * │ prevents. The reason it is SAFE to hard-cache is that the SSR response is │\n * │ impersonal: `createH3SSRHandler` renders without reading the request's │\n * │ session/cookies, so there is no per-user data baked into the HTML. ALL │\n * │ per-user state (who's logged in, private records, access checks) is │\n * │ resolved CLIENT-SIDE after load. Keep it that way: if you need the SSR │\n * │ output to differ per user, the fix is to move that work client-side, not │\n * │ to disable caching here. │\n * └──────────────────────────────────────────────────────────────────────────┘\n */\nfunction applyDefaultSsrCacheHeader(\n headers: Headers,\n status: number,\n pathname: string,\n) {\n if (!isSsrHtmlOrDataResponse(headers, status, pathname)) return;\n\n // Netlify Functions/proxies are not cached by default. Set all three cache\n // headers: Cache-Control for browsers, CDN-Cache-Control for generic CDNs,\n // and Netlify-CDN-Cache-Control (with durable) so Netlify's shared cache\n // actually serves SSR HTML/.data from the edge instead of forwarding every\n // request to origin — for every visitor, authenticated or not.\n for (const [name, value] of Object.entries(DEFAULT_SSR_CACHE_HEADERS)) {\n headers.set(name, value);\n }\n}\n\nfunction applyDefaultSpeculationRulesHeader(\n headers: Headers,\n status: number,\n basePath: string,\n) {\n if (status < 200 || status >= 400) return;\n if (headers.has(\"speculation-rules\")) return;\n\n const contentType = headers.get(\"content-type\")?.toLowerCase() ?? \"\";\n if (!contentType.includes(\"text/html\")) return;\n\n // Cloudflare Speed Brain injects its own Speculation-Rules header when the\n // origin omits one. Those browser prefetches carry `Sec-Purpose: prefetch`,\n // and Cloudflare refuses cache-ineligible dynamic pages with a 503 before\n // the request can reach Netlify/origin. We publish an explicit no-op ruleset\n // by default so Cloudflare does not inject its edge prefetch rules. Preserve\n // an app-provided Speculation-Rules header above if a template deliberately\n // owns this behavior.\n const rulesPath = prefixMountedPath(DEFAULT_SPECULATION_RULES_PATH, basePath);\n headers.set(\"speculation-rules\", `\"${rulesPath}\"`);\n}\n\n/**\n * Extract the plain JS body from a `<script ...>body</script>` string.\n * Returns `null` if the input is falsy or has no recognisable `</script>` end.\n * Used to compute the sha256 hash of framework-injected inline scripts so the\n * hash can be listed in the `script-src` CSP directive without relying on\n * `'unsafe-inline'`.\n */\nfunction extractScriptBody(scriptTag: string | null): string | null {\n if (!scriptTag) return null;\n const start = scriptTag.indexOf(\">\") + 1;\n const end = scriptTag.lastIndexOf(\"</script>\");\n if (start <= 0 || end < start) return null;\n return scriptTag.slice(start, end);\n}\n\ntype CspDirective = {\n name: string;\n tokens: string[];\n};\n\nconst CSP_DIRECTIVES_WITH_VALUE_TOKENS = new Set([\n \"base-uri\",\n \"block-all-mixed-content\",\n \"child-src\",\n \"connect-src\",\n \"default-src\",\n \"fenced-frame-src\",\n \"font-src\",\n \"form-action\",\n \"frame-ancestors\",\n \"frame-src\",\n \"img-src\",\n \"manifest-src\",\n \"media-src\",\n \"navigate-to\",\n \"object-src\",\n \"plugin-types\",\n \"prefetch-src\",\n \"referrer\",\n \"reflected-xss\",\n \"require-sri-for\",\n \"require-trusted-types-for\",\n \"report-to\",\n \"report-uri\",\n \"sandbox\",\n \"script-src\",\n \"script-src-attr\",\n \"script-src-elem\",\n \"style-src\",\n \"style-src-attr\",\n \"style-src-elem\",\n \"trusted-types\",\n \"upgrade-insecure-requests\",\n \"webrtc\",\n \"worker-src\",\n]);\n\nfunction hasCommaJoinedCspPolicies(policy: string): boolean {\n let commaIndex = policy.indexOf(\",\");\n while (commaIndex !== -1) {\n const afterComma = policy.slice(commaIndex + 1);\n const directive = /^\\s+([a-z][a-z0-9-]*)(?=\\s|;|$)/i.exec(afterComma)?.[1];\n if (\n directive &&\n CSP_DIRECTIVES_WITH_VALUE_TOKENS.has(directive.toLowerCase())\n ) {\n return true;\n }\n commaIndex = policy.indexOf(\",\", commaIndex + 1);\n }\n return false;\n}\n\nfunction parseCsp(policy: string): CspDirective[] {\n return policy\n .split(\";\")\n .map((part) => part.trim())\n .filter(Boolean)\n .map((part) => {\n const [name = \"\", ...tokens] = part.split(/\\s+/);\n return { name: name.toLowerCase(), tokens };\n })\n .filter((directive) => directive.name);\n}\n\nfunction serializeCsp(directives: CspDirective[]): string {\n return directives\n .map((directive) =>\n [directive.name, ...directive.tokens].filter(Boolean).join(\" \"),\n )\n .join(\"; \");\n}\n\nfunction appendCspTokens(\n tokens: string[],\n additions: readonly string[],\n): string[] {\n if (!additions.length) return tokens;\n const next = tokens.filter((token) => token !== \"'none'\");\n const seen = new Set(next);\n for (const token of additions) {\n if (!token || seen.has(token)) continue;\n next.push(token);\n seen.add(token);\n }\n return next;\n}\n\nfunction findCspDirective(\n directives: CspDirective[],\n name: string,\n): CspDirective | undefined {\n return directives.find((directive) => directive.name === name);\n}\n\nfunction appendToExistingOrDefaultCspDirective(\n directives: CspDirective[],\n name: string,\n additions: readonly string[],\n): void {\n if (!additions.length) return;\n const existing = findCspDirective(directives, name);\n if (existing) {\n existing.tokens = appendCspTokens(existing.tokens, additions);\n return;\n }\n\n const defaultSrc = findCspDirective(directives, \"default-src\");\n if (!defaultSrc) return;\n directives.push({\n name,\n tokens: appendCspTokens([...defaultSrc.tokens], additions),\n });\n}\n\nfunction appendToExistingCspDirective(\n directives: CspDirective[],\n name: string,\n additions: readonly string[],\n): void {\n const existing = findCspDirective(directives, name);\n if (!existing) return;\n existing.tokens = appendCspTokens(existing.tokens, additions);\n}\n\nfunction hasStrictNonceScriptPolicy(tokens: readonly string[]): boolean {\n return tokens.some(\n (token) => token === \"'strict-dynamic'\" || token.startsWith(\"'nonce-\"),\n );\n}\n\nfunction appendToScriptCspDirective(\n directives: CspDirective[],\n name: string,\n additions: readonly string[],\n): boolean {\n const existing = findCspDirective(directives, name);\n if (existing) {\n if (hasStrictNonceScriptPolicy(existing.tokens)) return false;\n existing.tokens = appendCspTokens(existing.tokens, additions);\n return true;\n }\n\n const defaultSrc = findCspDirective(directives, \"default-src\");\n if (!defaultSrc || hasStrictNonceScriptPolicy(defaultSrc.tokens)) {\n return false;\n }\n directives.push({\n name,\n tokens: appendCspTokens([...defaultSrc.tokens], additions),\n });\n return true;\n}\n\nfunction appendToEffectiveScriptElementCspDirective(\n directives: CspDirective[],\n additions: readonly string[],\n): boolean {\n const scriptSrcElem = findCspDirective(directives, \"script-src-elem\");\n if (scriptSrcElem) {\n if (hasStrictNonceScriptPolicy(scriptSrcElem.tokens)) return false;\n scriptSrcElem.tokens = appendCspTokens(scriptSrcElem.tokens, additions);\n return true;\n }\n\n return appendToScriptCspDirective(directives, \"script-src\", additions);\n}\n\nfunction augmentExistingEnforcedCspForFrameworkScripts(\n policy: string,\n options: {\n gaScriptSrcTokens: readonly string[];\n gaEnabled: boolean;\n },\n): string {\n // Multiple CSP headers are surfaced by Headers.get() as one comma-joined\n // string. CSP is not a comma-list header, so serializing a parsed combined\n // value would turn two policies into one invalid policy. Leave those headers\n // app-owned; a comma inside a source/report URL is still safe to parse.\n if (hasCommaJoinedCspPolicies(policy)) return policy;\n\n const directives = parseCsp(policy);\n if (!directives.length) return policy;\n\n if (options.gaEnabled) {\n const addedScriptElement = appendToEffectiveScriptElementCspDirective(\n directives,\n options.gaScriptSrcTokens,\n );\n if (addedScriptElement) {\n appendToExistingOrDefaultCspDirective(\n directives,\n \"connect-src\",\n GA_CSP_CONNECT_HOSTS,\n );\n appendToExistingOrDefaultCspDirective(\n directives,\n \"img-src\",\n GA_CSP_IMG_HOSTS,\n );\n }\n }\n\n return serializeCsp(directives);\n}\n\nfunction augmentExistingReportOnlyCspForFrameworkScripts(\n policy: string,\n options: {\n scriptSrcTokens: readonly string[];\n gaEnabled: boolean;\n },\n): string {\n if (hasCommaJoinedCspPolicies(policy)) return policy;\n\n const directives = parseCsp(policy);\n if (!directives.length) return policy;\n\n appendToExistingOrDefaultCspDirective(\n directives,\n \"script-src\",\n options.scriptSrcTokens,\n );\n appendToExistingCspDirective(\n directives,\n \"script-src-elem\",\n options.scriptSrcTokens,\n );\n\n if (options.gaEnabled) {\n appendToExistingOrDefaultCspDirective(\n directives,\n \"connect-src\",\n GA_CSP_CONNECT_HOSTS,\n );\n appendToExistingOrDefaultCspDirective(\n directives,\n \"img-src\",\n GA_CSP_IMG_HOSTS,\n );\n }\n\n return serializeCsp(directives);\n}\n\n/**\n * Apply a Content-Security-Policy header to HTML document responses.\n *\n * Two directives are always enforced in production:\n *\n * - `object-src 'none'` — disables Flash / Java / PDF plugin execution,\n * which are a reliable code-execution vector even in modern browsers.\n * - `base-uri 'self'` — prevents a `<base href=\"...\">` injection from\n * hijacking all relative URLs in the document (a common attack target when\n * user-controlled content reaches the HTML).\n *\n * A third directive, `script-src`, is emitted via `Content-Security-Policy-\n * Report-Only` rather than enforced when the app has no existing document CSP.\n * The framework injects deterministic inline scripts (the Sentry config block,\n * whose hash is computed once at process startup from the resolved env vars,\n * and — when `GA_MEASUREMENT_ID` is set — the gtag config block, whose hash is\n * derived from the same string `wrapWithAnalytics` embeds). It also loads\n * Google Tag Manager / GA4 from `GA_CSP_SCRIPT_HOSTS`. All of those are listed\n * here so the report-only policy reflects the code the framework itself injects\n * instead of reporting a violation on every page load.\n *\n * If an app or host already sends an enforced CSP with `script-src`,\n * `script-src-elem`, `connect-src`, `img-src`, or `default-src`, we merge only\n * GA-specific allowances into existing host/hash policies. Strict nonce or\n * `strict-dynamic` script policies stay app-owned because blindly appending\n * hashes or hosts would widen the policy without reliably loading our injected\n * scripts.\n *\n * Templates additionally render a theme-init inline script whose exact content\n * varies by template (default theme param, custom docs variant, etc.) and which\n * is rendered by React Router, not this handler, so its hash is not available\n * here. Shipping script-src as Report-Only surfaces the remaining violations\n * without breaking template customisations; teams can graduate to enforcement\n * once their hashes are enumerated.\n *\n * Skipped in development (`NODE_ENV !== 'production'`) so HMR eval and Vite\n * dev-server injects are never blocked. Set `AGENT_NATIVE_DISABLE_DOC_CSP=1`\n * to opt out in production for a template with exotic needs.\n */\nfunction applyDocumentCsp(headers: Headers, sentryScript: string | null): void {\n if (process.env.NODE_ENV !== \"production\") return;\n if (process.env.AGENT_NATIVE_DISABLE_DOC_CSP === \"1\") return;\n\n // script-src as Report-Only: list 'self', the framework-injected inline\n // script hashes (Sentry config + gtag config), and the Google Analytics /\n // Tag Manager loader hosts. These are exactly the scripts the framework\n // itself injects, so listing them keeps the report-only policy from flagging\n // GA on every page load (and keeps it safe to graduate to enforcement).\n // Template theme-init hashes are NOT included here — see function comment.\n const sentryBody = extractScriptBody(sentryScript);\n const sentryHash = sentryBody ? computeInlineScriptHash(sentryBody) : null;\n const gaInlineBody = getGaInlineConfigScriptBody();\n const gaHash = gaInlineBody ? computeInlineScriptHash(gaInlineBody) : null;\n const gaHosts = gaInlineBody ? [...GA_CSP_SCRIPT_HOSTS] : [];\n const gaScriptSrcTokens = [...(gaHash ? [gaHash] : []), ...gaHosts];\n const scriptSrcTokens = [\n \"'self'\",\n ...(sentryHash ? [sentryHash] : []),\n ...(gaHash ? [gaHash] : []),\n ...gaHosts,\n ];\n\n const cspAugmentOptions = {\n scriptSrcTokens,\n gaScriptSrcTokens,\n gaEnabled: Boolean(gaInlineBody),\n };\n const existing = headers.get(\"content-security-policy\") ?? \"\";\n if (!existing) {\n headers.set(\n \"content-security-policy\",\n \"object-src 'none'; base-uri 'self'\",\n );\n } else {\n headers.set(\n \"content-security-policy\",\n augmentExistingEnforcedCspForFrameworkScripts(\n existing,\n cspAugmentOptions,\n ),\n );\n }\n\n const scriptSrc = `script-src ${scriptSrcTokens.join(\" \")}`;\n const existingRo = headers.get(\"content-security-policy-report-only\") ?? \"\";\n if (!existingRo) {\n headers.set(\"content-security-policy-report-only\", scriptSrc);\n } else {\n headers.set(\n \"content-security-policy-report-only\",\n augmentExistingReportOnlyCspForFrameworkScripts(\n existingRo,\n cspAugmentOptions,\n ),\n );\n }\n}\n\nfunction isFrameworkOrAssetPath(pathname: string): boolean {\n return (\n pathname.startsWith(\"/.well-known/\") ||\n pathname.startsWith(\"/_agent_native/\") ||\n pathname.startsWith(\"/_agent-native/\") ||\n pathname.startsWith(\"/api/\") ||\n pathname.startsWith(\"/@vite/\") ||\n pathname.startsWith(\"/@id/\") ||\n pathname.startsWith(\"/@fs/\") ||\n pathname === \"/@react-refresh\" ||\n pathname === \"/__vite_ping\" ||\n pathname === \"/__open-in-editor\" ||\n pathname === \"/favicon.ico\" ||\n pathname === \"/favicon.png\" ||\n (/\\.\\w+$/.test(pathname) && !pathname.endsWith(\".data\"))\n );\n}\n\nasync function rewriteMountedResponse(\n response: Response,\n basePath: string,\n pathname: string,\n requestUrl: string,\n): Promise<Response> {\n const sentryClientConfigScript = getSentryClientConfigScript();\n const headers = new Headers(response.headers);\n applyDefaultSsrCacheHeader(headers, response.status, pathname);\n applyDefaultSpeculationRulesHeader(headers, response.status, basePath);\n\n const location = headers.get(\"location\");\n if (location?.startsWith(\"/\") && !location.startsWith(\"//\")) {\n headers.set(\"location\", prefixMountedPath(location, basePath));\n }\n\n const contentType = headers.get(\"content-type\") ?? \"\";\n if (!contentType.toLowerCase().includes(\"text/html\") || !response.body) {\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n }\n\n const html = await response.text();\n headers.delete(\"content-length\");\n applyDocumentCsp(headers, sentryClientConfigScript);\n return new Response(\n injectHeadScript(\n injectDefaultSocialImageMeta(\n prefixMountedHtml(html, basePath),\n defaultSocialImageUrl(requestUrl, basePath),\n ),\n sentryClientConfigScript,\n ),\n {\n status: response.status,\n statusText: response.statusText,\n headers,\n },\n );\n}\n\n/**\n * Create an h3 catch-all that hands page routes to React Router and\n * returns 404 for framework / asset paths that React Router doesn't own.\n */\nexport function createH3SSRHandler(getBuild: () => Promise<unknown> | unknown) {\n const handler = createRequestHandler(getBuild as any);\n return defineEventHandler(async (event) => {\n const basePath = getAppBasePath();\n const p = stripAppBasePath(event.url.pathname);\n if (isFrameworkOrAssetPath(p)) {\n return new Response(null, { status: 404 });\n }\n try {\n const request = requestWithPathname(event.req as Request, p, basePath);\n // SSR renders an IMPERSONAL public shell — we deliberately do NOT read the\n // request's session/cookies here, and pin an explicitly anonymous request\n // context. That keeps the SSR HTML/.data identical for every visitor so it\n // can be hard-cached at the CDN for everyone (see applyDefaultSsrCacheHeader).\n //\n // Consequence: SSR loaders that call `getRequestUserEmail()` / `accessFilter()`\n // always see the unauthenticated branch and render public content only. Any\n // per-user view (private records, share-grant access, who's logged in) MUST\n // be resolved CLIENT-SIDE after load, never baked into SSR. Do not re-pin the\n // session here to \"fix\" a per-user page — that silently makes the page\n // uncacheable and/or leaks one user's data into another's cached copy.\n const ctx = { userEmail: undefined, orgId: undefined };\n if (request.method === \"HEAD\") {\n const getRequest = new Request(request.url, {\n method: \"GET\",\n headers: request.headers,\n signal: request.signal,\n });\n const response = await runWithRequestContext(ctx, () =>\n handler(getRequest),\n );\n return await rewriteMountedResponse(\n new Response(null, {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n }),\n basePath,\n p,\n request.url,\n );\n }\n return await rewriteMountedResponse(\n await runWithRequestContext(ctx, () => handler(request)),\n basePath,\n p,\n request.url,\n );\n } catch (err) {\n // Log the full stack server-side, but never leak it to the client.\n // Stack traces expose file paths, library versions, and code structure\n // that aid reconnaissance attacks. In dev we surface the message text\n // so devtools shows something useful; in prod we return a bare 500.\n console.error(\"[ssr-handler] SSR error:\", err);\n const isProd = process.env.NODE_ENV === \"production\";\n const body = isProd\n ? \"Internal Server Error\"\n : `Internal Server Error: ${(err as Error)?.message ?? err}`;\n return new Response(body, {\n status: 500,\n headers: { \"content-type\": \"text/plain\" },\n });\n }\n });\n}\n"]}
1
+ {"version":3,"file":"ssr-handler.js","sourceRoot":"","sources":["../../src/server/ssr-handler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,IAAI,CAAC;AACxC;;;;;;;;;;;;;;;;GAgBG;AACH,OAAO,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AAEpD,OAAO,EACL,yBAAyB,EACzB,8BAA8B,GAC/B,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,6BAA6B,EAC7B,gCAAgC,EAChC,8BAA8B,EAC9B,8BAA8B,EAC9B,+BAA+B,EAC/B,qCAAqC,GACtC,MAAM,0BAA0B,CAAC;AAClC,OAAO,EACL,oBAAoB,EACpB,gBAAgB,EAChB,mBAAmB,EACnB,2BAA2B,GAC5B,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACL,yBAAyB,EACzB,gBAAgB,IAAI,yBAAyB,GAC9C,MAAM,oBAAoB,CAAC;AA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ACF,OAAO,MAAM,sBAAsB,CACjC,IAAI,QAAQ,CAAC,IAAI,EAAE;oBACjB,MAAM,EAAE,QAAQ,CAAC,MAAM;oBACvB,UAAU,EAAE,QAAQ,CAAC,UAAU;oBAC/B,OAAO,EAAE,QAAQ,CAAC,OAAO;iBAC1B,CAAC,EACF,QAAQ,EACR,CAAC,EACD,OAAO,CAAC,GAAG,CACZ,CAAC;YACJ,CAAC;YACD,OAAO,MAAM,sBAAsB,CACjC,MAAM,qBAAqB,CAAC,GAAG,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,EACxD,QAAQ,EACR,CAAC,EACD,OAAO,CAAC,GAAG,CACZ,CAAC;QACJ,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,mEAAmE;YACnE,uEAAuE;YACvE,sEAAsE;YACtE,oEAAoE;YACpE,OAAO,CAAC,KAAK,CAAC,0BAA0B,EAAE,GAAG,CAAC,CAAC;YAC/C,MAAM,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY,CAAC;YACrD,MAAM,IAAI,GAAG,MAAM;gBACjB,CAAC,CAAC,uBAAuB;gBACzB,CAAC,CAAC,0BAA2B,GAAa,EAAE,OAAO,IAAI,GAAG,EAAE,CAAC;YAC/D,OAAO,IAAI,QAAQ,CAAC,IAAI,EAAE;gBACxB,MAAM,EAAE,GAAG;gBACX,OAAO,EAAE,EAAE,cAAc,EAAE,YAAY,EAAE;aAC1C,CAAC,CAAC;QACL,CAAC;IACH,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { defineEventHandler } from \"h3\";\n/**\n * Shared SSR catch-all handler for React Router framework mode.\n *\n * Templates wire this up via:\n *\n * // server/routes/[...page].get.ts\n * import { createH3SSRHandler } from \"@agent-native/core/server/ssr-handler\";\n * export default createH3SSRHandler(\n * () => import(\"virtual:react-router/server-build\"),\n * );\n *\n * The `getBuild` callback MUST live in the template's own source so Vite's\n * @react-router/dev plugin can resolve the `virtual:` module. Pulling the\n * import into core (e.g. via a re-export) puts it in node_modules where\n * Vite's SSR externalizer leaves it untouched and Node's ESM loader rejects\n * the unknown scheme — silently 302'ing every request to \"/\".\n */\nimport { createRequestHandler } from \"react-router\";\n\nimport {\n DEFAULT_SSR_CACHE_HEADERS,\n DEFAULT_SPECULATION_RULES_PATH,\n} from \"../shared/cache-control.js\";\nimport {\n AGENT_NATIVE_SOCIAL_IMAGE_ALT,\n AGENT_NATIVE_SOCIAL_IMAGE_HEIGHT,\n AGENT_NATIVE_SOCIAL_IMAGE_PATH,\n AGENT_NATIVE_SOCIAL_IMAGE_TYPE,\n AGENT_NATIVE_SOCIAL_IMAGE_WIDTH,\n withAgentNativeSocialImageCacheBuster,\n} from \"../shared/social-meta.js\";\nimport {\n GA_CSP_CONNECT_HOSTS,\n GA_CSP_IMG_HOSTS,\n GA_CSP_SCRIPT_HOSTS,\n getGaInlineConfigScriptBody,\n} from \"./analytics.js\";\nimport {\n getAppBasePathFromViteEnv,\n stripAppBasePath as canonicalStripAppBasePath,\n} from \"./app-base-path.js\";\nimport { runWithRequestContext } from \"./request-context.js\";\nimport { computeInlineScriptHash } from \"./security-headers.js\";\nimport { getSentryClientConfigScript } from \"./sentry-config.js\";\n\nexport {\n DEFAULT_SSR_CACHE_HEADERS,\n DEFAULT_SPECULATION_RULES_HEADER,\n DEFAULT_SSR_CACHE_CONTROL,\n} from \"../shared/cache-control.js\";\n\nfunction getAppBasePath(): string {\n return getAppBasePathFromViteEnv();\n}\n\nfunction stripAppBasePath(pathname: string): string {\n return canonicalStripAppBasePath(pathname, getAppBasePath());\n}\n\nfunction stripBasePath(pathname: string, basePath: string): string {\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 requestWithPathname(\n request: Request,\n pathname: string,\n basePath: string,\n): Request {\n const url = new URL(request.url);\n let changed = false;\n if (basePath && pathname === \"/__manifest\") {\n const paths = url.searchParams.get(\"paths\");\n if (paths) {\n const strippedPaths = paths\n .split(\",\")\n .map((path) => stripBasePath(path, basePath))\n .join(\",\");\n if (strippedPaths !== paths) {\n url.searchParams.set(\"paths\", strippedPaths);\n changed = true;\n }\n }\n }\n if (url.pathname !== pathname) {\n url.pathname = pathname;\n changed = true;\n }\n if (!changed) return request;\n const init: RequestInit & { duplex?: \"half\" } = {\n method: request.method,\n headers: request.headers,\n signal: request.signal,\n };\n if (request.body && ![\"GET\", \"HEAD\"].includes(request.method.toUpperCase())) {\n init.body = request.body;\n init.duplex = \"half\";\n }\n return new Request(url, init);\n}\n\nfunction prefixMountedPath(path: string, basePath: string): string {\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: string, basePath: string): string {\n if (!basePath) return html;\n return html\n .replace(\n /\\b(href|src|action|formaction|poster)=([\"'])(\\/(?!\\/)[^\"']*)\\2/g,\n (_match, attr: string, quote: string, path: string) =>\n `${attr}=${quote}${prefixMountedPath(path, basePath)}${quote}`,\n )\n .replace(/url\\(([\"']?)(\\/(?!\\/)[^)'\" ]+)\\1\\)/g, (_match, quote, path) => {\n const q = quote || \"\";\n return `url(${q}${prefixMountedPath(path, basePath)}${q})`;\n });\n}\n\nfunction injectHeadScript(html: string, script: string | null): string {\n if (!script) return html;\n const headCloseIdx = html.indexOf(\"</head>\");\n if (headCloseIdx === -1) return html;\n return html.slice(0, headCloseIdx) + script + html.slice(headCloseIdx);\n}\n\nconst OG_IMAGE_META_RE = /<meta\\b(?=[^>]*\\bproperty=([\"'])og:image\\1)[^>]*>/i;\nconst TWITTER_CARD_META_RE =\n /<meta\\b(?=[^>]*\\bname=([\"'])twitter:card\\1)[^>]*>/i;\nconst TWITTER_IMAGE_META_RE =\n /<meta\\b(?=[^>]*\\bname=([\"'])twitter:image\\1)[^>]*>/i;\n\nfunction defaultSocialImageUrl(requestUrl: string, basePath: string): string {\n return withAgentNativeSocialImageCacheBuster(\n new URL(\n prefixMountedPath(AGENT_NATIVE_SOCIAL_IMAGE_PATH, basePath),\n requestUrl,\n ).toString(),\n );\n}\n\nfunction injectDefaultSocialImageMeta(html: string, imageUrl: string): string {\n const headCloseIdx = html.indexOf(\"</head>\");\n if (headCloseIdx === -1) return html;\n\n const hasAnySocialImage =\n OG_IMAGE_META_RE.test(html) || TWITTER_IMAGE_META_RE.test(html);\n const tags: string[] = [];\n\n if (!hasAnySocialImage) {\n tags.push(`<meta property=\"og:image\" content=\"${imageUrl}\">`);\n tags.push(`<meta property=\"og:image:secure_url\" content=\"${imageUrl}\">`);\n tags.push(\n `<meta property=\"og:image:type\" content=\"${AGENT_NATIVE_SOCIAL_IMAGE_TYPE}\">`,\n );\n tags.push(\n `<meta property=\"og:image:width\" content=\"${AGENT_NATIVE_SOCIAL_IMAGE_WIDTH}\">`,\n );\n tags.push(\n `<meta property=\"og:image:height\" content=\"${AGENT_NATIVE_SOCIAL_IMAGE_HEIGHT}\">`,\n );\n tags.push(\n `<meta property=\"og:image:alt\" content=\"${AGENT_NATIVE_SOCIAL_IMAGE_ALT}\">`,\n );\n }\n if (!TWITTER_CARD_META_RE.test(html)) {\n tags.push(`<meta name=\"twitter:card\" content=\"summary_large_image\">`);\n }\n if (!hasAnySocialImage) {\n tags.push(`<meta name=\"twitter:image\" content=\"${imageUrl}\">`);\n tags.push(\n `<meta name=\"twitter:image:alt\" content=\"${AGENT_NATIVE_SOCIAL_IMAGE_ALT}\">`,\n );\n }\n\n if (tags.length === 0) return html;\n return html.slice(0, headCloseIdx) + tags.join(\"\") + html.slice(headCloseIdx);\n}\n\nfunction isSsrHtmlOrDataResponse(\n headers: Headers,\n status: number,\n pathname: string,\n): boolean {\n if (status < 200 || status >= 400) return false;\n const contentType = headers.get(\"content-type\")?.toLowerCase() ?? \"\";\n if (contentType.includes(\"text/html\")) return true;\n return pathname.endsWith(\".data\") && contentType.includes(\"text/x-script\");\n}\n\n/**\n * Apply the SSR cache policy to the response headers.\n *\n * ┌──────────────────────────────────────────────────────────────────────────┐\n * │ SSR IS A PUBLIC, HARD-CDN-CACHED SHELL — SERVED IDENTICALLY TO EVERYONE. │\n * │ │\n * │ Every SSR HTML / React Router `.data` response gets the same public │\n * │ stale-while-revalidate policy for ALL visitors, authenticated or not, so │\n * │ the edge serves one shared copy and never stampedes origin. │\n * │ │\n * │ DO NOT reintroduce per-user / cookie-based cache variation here (no │\n * │ `private`, no `no-store`, no `Vary: Cookie`, no \"authenticated → don't │\n * │ cache\" branch). That makes pages uncacheable for every logged-in visitor, │\n * │ which is slow and expensive — exactly the regression this guardrail │\n * │ prevents. The reason it is SAFE to hard-cache is that the SSR response is │\n * │ impersonal: `createH3SSRHandler` renders without reading the request's │\n * │ session/cookies, so there is no per-user data baked into the HTML. ALL │\n * │ per-user state (who's logged in, private records, access checks) is │\n * │ resolved CLIENT-SIDE after load. Keep it that way: if you need the SSR │\n * │ output to differ per user, the fix is to move that work client-side, not │\n * │ to disable caching here. │\n * └──────────────────────────────────────────────────────────────────────────┘\n */\nfunction applyDefaultSsrCacheHeader(\n headers: Headers,\n status: number,\n pathname: string,\n) {\n if (!isSsrHtmlOrDataResponse(headers, status, pathname)) return;\n\n // Netlify Functions/proxies are not cached by default. Set all three cache\n // headers: Cache-Control for browsers, CDN-Cache-Control for generic CDNs,\n // and Netlify-CDN-Cache-Control (with durable) so Netlify's shared cache\n // actually serves SSR HTML/.data from the edge instead of forwarding every\n // request to origin — for every visitor, authenticated or not.\n for (const [name, value] of Object.entries(DEFAULT_SSR_CACHE_HEADERS)) {\n headers.set(name, value);\n }\n}\n\nfunction applyDefaultSpeculationRulesHeader(\n headers: Headers,\n status: number,\n basePath: string,\n) {\n if (status < 200 || status >= 400) return;\n if (headers.has(\"speculation-rules\")) return;\n\n const contentType = headers.get(\"content-type\")?.toLowerCase() ?? \"\";\n if (!contentType.includes(\"text/html\")) return;\n\n // Cloudflare Speed Brain injects its own Speculation-Rules header when the\n // origin omits one. Those browser prefetches carry `Sec-Purpose: prefetch`,\n // and Cloudflare refuses cache-ineligible dynamic pages with a 503 before\n // the request can reach Netlify/origin. We publish an explicit no-op ruleset\n // by default so Cloudflare does not inject its edge prefetch rules. Preserve\n // an app-provided Speculation-Rules header above if a template deliberately\n // owns this behavior.\n const rulesPath = prefixMountedPath(DEFAULT_SPECULATION_RULES_PATH, basePath);\n headers.set(\"speculation-rules\", `\"${rulesPath}\"`);\n}\n\n/**\n * Extract the plain JS body from a `<script ...>body</script>` string.\n * Returns `null` if the input is falsy or has no recognisable `</script>` end.\n * Used to compute the sha256 hash of framework-injected inline scripts so the\n * hash can be listed in the `script-src` CSP directive without relying on\n * `'unsafe-inline'`.\n */\nfunction extractScriptBody(scriptTag: string | null): string | null {\n if (!scriptTag) return null;\n const start = scriptTag.indexOf(\">\") + 1;\n const end = scriptTag.lastIndexOf(\"</script>\");\n if (start <= 0 || end < start) return null;\n return scriptTag.slice(start, end);\n}\n\ntype CspDirective = {\n name: string;\n tokens: string[];\n};\n\nconst CSP_DIRECTIVES_WITH_VALUE_TOKENS = new Set([\n \"base-uri\",\n \"block-all-mixed-content\",\n \"child-src\",\n \"connect-src\",\n \"default-src\",\n \"fenced-frame-src\",\n \"font-src\",\n \"form-action\",\n \"frame-ancestors\",\n \"frame-src\",\n \"img-src\",\n \"manifest-src\",\n \"media-src\",\n \"navigate-to\",\n \"object-src\",\n \"plugin-types\",\n \"prefetch-src\",\n \"referrer\",\n \"reflected-xss\",\n \"require-sri-for\",\n \"require-trusted-types-for\",\n \"report-to\",\n \"report-uri\",\n \"sandbox\",\n \"script-src\",\n \"script-src-attr\",\n \"script-src-elem\",\n \"style-src\",\n \"style-src-attr\",\n \"style-src-elem\",\n \"trusted-types\",\n \"upgrade-insecure-requests\",\n \"webrtc\",\n \"worker-src\",\n]);\n\nfunction hasCommaJoinedCspPolicies(policy: string): boolean {\n let commaIndex = policy.indexOf(\",\");\n while (commaIndex !== -1) {\n const afterComma = policy.slice(commaIndex + 1);\n const directive = /^\\s+([a-z][a-z0-9-]*)(?=\\s|;|$)/i.exec(afterComma)?.[1];\n if (\n directive &&\n CSP_DIRECTIVES_WITH_VALUE_TOKENS.has(directive.toLowerCase())\n ) {\n return true;\n }\n commaIndex = policy.indexOf(\",\", commaIndex + 1);\n }\n return false;\n}\n\nfunction parseCsp(policy: string): CspDirective[] {\n return policy\n .split(\";\")\n .map((part) => part.trim())\n .filter(Boolean)\n .map((part) => {\n const [name = \"\", ...tokens] = part.split(/\\s+/);\n return { name: name.toLowerCase(), tokens };\n })\n .filter((directive) => directive.name);\n}\n\nfunction serializeCsp(directives: CspDirective[]): string {\n return directives\n .map((directive) =>\n [directive.name, ...directive.tokens].filter(Boolean).join(\" \"),\n )\n .join(\"; \");\n}\n\nfunction appendCspTokens(\n tokens: string[],\n additions: readonly string[],\n): string[] {\n if (!additions.length) return tokens;\n const next = tokens.filter((token) => token !== \"'none'\");\n const seen = new Set(next);\n for (const token of additions) {\n if (!token || seen.has(token)) continue;\n next.push(token);\n seen.add(token);\n }\n return next;\n}\n\nfunction findCspDirective(\n directives: CspDirective[],\n name: string,\n): CspDirective | undefined {\n return directives.find((directive) => directive.name === name);\n}\n\nfunction appendToExistingOrDefaultCspDirective(\n directives: CspDirective[],\n name: string,\n additions: readonly string[],\n): void {\n if (!additions.length) return;\n const existing = findCspDirective(directives, name);\n if (existing) {\n existing.tokens = appendCspTokens(existing.tokens, additions);\n return;\n }\n\n const defaultSrc = findCspDirective(directives, \"default-src\");\n if (!defaultSrc) return;\n directives.push({\n name,\n tokens: appendCspTokens([...defaultSrc.tokens], additions),\n });\n}\n\nfunction appendToExistingCspDirective(\n directives: CspDirective[],\n name: string,\n additions: readonly string[],\n): void {\n const existing = findCspDirective(directives, name);\n if (!existing) return;\n existing.tokens = appendCspTokens(existing.tokens, additions);\n}\n\nfunction ensureCspDirective(\n directives: CspDirective[],\n name: string,\n tokens: readonly string[],\n): void {\n if (findCspDirective(directives, name)) return;\n directives.push({ name, tokens: [...tokens] });\n}\n\nfunction hasStrictNonceScriptPolicy(tokens: readonly string[]): boolean {\n return tokens.some(\n (token) => token === \"'strict-dynamic'\" || token.startsWith(\"'nonce-\"),\n );\n}\n\nfunction appendToScriptCspDirective(\n directives: CspDirective[],\n name: string,\n additions: readonly string[],\n): boolean {\n const existing = findCspDirective(directives, name);\n if (existing) {\n if (hasStrictNonceScriptPolicy(existing.tokens)) return false;\n existing.tokens = appendCspTokens(existing.tokens, additions);\n return true;\n }\n\n const defaultSrc = findCspDirective(directives, \"default-src\");\n if (!defaultSrc || hasStrictNonceScriptPolicy(defaultSrc.tokens)) {\n return false;\n }\n directives.push({\n name,\n tokens: appendCspTokens([...defaultSrc.tokens], additions),\n });\n return true;\n}\n\nfunction appendToEffectiveScriptElementCspDirective(\n directives: CspDirective[],\n additions: readonly string[],\n): boolean {\n const scriptSrcElem = findCspDirective(directives, \"script-src-elem\");\n if (scriptSrcElem) {\n if (hasStrictNonceScriptPolicy(scriptSrcElem.tokens)) return false;\n scriptSrcElem.tokens = appendCspTokens(scriptSrcElem.tokens, additions);\n return true;\n }\n\n return appendToScriptCspDirective(directives, \"script-src\", additions);\n}\n\nfunction augmentExistingEnforcedCspForFrameworkScripts(\n policy: string,\n options: {\n gaScriptSrcTokens: readonly string[];\n gaEnabled: boolean;\n },\n): string {\n // Multiple CSP headers are surfaced by Headers.get() as one comma-joined\n // string. CSP is not a comma-list header, so serializing a parsed combined\n // value would turn two policies into one invalid policy. Leave those headers\n // app-owned; a comma inside a source/report URL is still safe to parse.\n if (hasCommaJoinedCspPolicies(policy)) return policy;\n\n const directives = parseCsp(policy);\n if (!directives.length) return policy;\n\n if (options.gaEnabled) {\n const addedScriptElement = appendToEffectiveScriptElementCspDirective(\n directives,\n options.gaScriptSrcTokens,\n );\n if (addedScriptElement) {\n appendToExistingOrDefaultCspDirective(\n directives,\n \"connect-src\",\n GA_CSP_CONNECT_HOSTS,\n );\n appendToExistingOrDefaultCspDirective(\n directives,\n \"img-src\",\n GA_CSP_IMG_HOSTS,\n );\n }\n }\n\n ensureCspDirective(directives, \"object-src\", [\"'none'\"]);\n ensureCspDirective(directives, \"base-uri\", [\"'self'\"]);\n\n return serializeCsp(directives);\n}\n\nfunction augmentExistingReportOnlyCspForFrameworkScripts(\n policy: string,\n options: {\n scriptSrcTokens: readonly string[];\n gaEnabled: boolean;\n },\n): string {\n if (hasCommaJoinedCspPolicies(policy)) return policy;\n\n const directives = parseCsp(policy);\n if (!directives.length) return policy;\n\n appendToExistingOrDefaultCspDirective(\n directives,\n \"script-src\",\n options.scriptSrcTokens,\n );\n appendToExistingCspDirective(\n directives,\n \"script-src-elem\",\n options.scriptSrcTokens,\n );\n\n if (options.gaEnabled) {\n appendToExistingOrDefaultCspDirective(\n directives,\n \"connect-src\",\n GA_CSP_CONNECT_HOSTS,\n );\n appendToExistingOrDefaultCspDirective(\n directives,\n \"img-src\",\n GA_CSP_IMG_HOSTS,\n );\n }\n\n return serializeCsp(directives);\n}\n\n/**\n * Apply a Content-Security-Policy header to HTML document responses.\n *\n * Two directives are always enforced in production:\n *\n * - `object-src 'none'` — disables Flash / Java / PDF plugin execution,\n * which are a reliable code-execution vector even in modern browsers.\n * - `base-uri 'self'` — prevents a `<base href=\"...\">` injection from\n * hijacking all relative URLs in the document (a common attack target when\n * user-controlled content reaches the HTML).\n *\n * A third directive, `script-src`, is emitted via `Content-Security-Policy-\n * Report-Only` rather than enforced when the app has no existing document CSP.\n * The framework injects deterministic inline scripts (the Sentry config block,\n * whose hash is computed once at process startup from the resolved env vars,\n * and — when `GA_MEASUREMENT_ID` is set — the gtag config block, whose hash is\n * derived from the same string `wrapWithAnalytics` embeds). It also loads\n * Google Tag Manager / GA4 from `GA_CSP_SCRIPT_HOSTS`. All of those are listed\n * here so the report-only policy reflects the code the framework itself injects\n * instead of reporting a violation on every page load.\n *\n * If an app or host already sends an enforced CSP with `script-src`,\n * `script-src-elem`, `connect-src`, `img-src`, or `default-src`, we merge only\n * GA-specific allowances into existing host/hash policies. Strict nonce or\n * `strict-dynamic` script policies stay app-owned because blindly appending\n * hashes or hosts would widen the policy without reliably loading our injected\n * scripts.\n *\n * Templates additionally render a theme-init inline script whose exact content\n * varies by template (default theme param, custom docs variant, etc.) and which\n * is rendered by React Router, not this handler, so its hash is not available\n * here. Shipping script-src as Report-Only surfaces the remaining violations\n * without breaking template customisations; teams can graduate to enforcement\n * once their hashes are enumerated.\n *\n * Skipped in development (`NODE_ENV !== 'production'`) so HMR eval and Vite\n * dev-server injects are never blocked. Set `AGENT_NATIVE_DISABLE_DOC_CSP=1`\n * to opt out in production for a template with exotic needs.\n */\nfunction applyDocumentCsp(headers: Headers, sentryScript: string | null): void {\n if (process.env.NODE_ENV !== \"production\") return;\n if (process.env.AGENT_NATIVE_DISABLE_DOC_CSP === \"1\") return;\n\n // script-src as Report-Only: list 'self', the framework-injected inline\n // script hashes (Sentry config + gtag config), and the Google Analytics /\n // Tag Manager loader hosts. These are exactly the scripts the framework\n // itself injects, so listing them keeps the report-only policy from flagging\n // GA on every page load (and keeps it safe to graduate to enforcement).\n // Template theme-init hashes are NOT included here — see function comment.\n const sentryBody = extractScriptBody(sentryScript);\n const sentryHash = sentryBody ? computeInlineScriptHash(sentryBody) : null;\n const gaInlineBody = getGaInlineConfigScriptBody();\n const gaHash = gaInlineBody ? computeInlineScriptHash(gaInlineBody) : null;\n const gaHosts = gaInlineBody ? [...GA_CSP_SCRIPT_HOSTS] : [];\n const gaScriptSrcTokens = [...(gaHash ? [gaHash] : []), ...gaHosts];\n const scriptSrcTokens = [\n \"'self'\",\n ...(sentryHash ? [sentryHash] : []),\n ...(gaHash ? [gaHash] : []),\n ...gaHosts,\n ];\n\n const cspAugmentOptions = {\n scriptSrcTokens,\n gaScriptSrcTokens,\n gaEnabled: Boolean(gaInlineBody),\n };\n const existing = headers.get(\"content-security-policy\") ?? \"\";\n if (!existing) {\n headers.set(\n \"content-security-policy\",\n \"object-src 'none'; base-uri 'self'\",\n );\n } else {\n headers.set(\n \"content-security-policy\",\n augmentExistingEnforcedCspForFrameworkScripts(\n existing,\n cspAugmentOptions,\n ),\n );\n }\n\n const scriptSrc = `script-src ${scriptSrcTokens.join(\" \")}`;\n const existingRo = headers.get(\"content-security-policy-report-only\") ?? \"\";\n if (!existingRo) {\n headers.set(\"content-security-policy-report-only\", scriptSrc);\n } else {\n headers.set(\n \"content-security-policy-report-only\",\n augmentExistingReportOnlyCspForFrameworkScripts(\n existingRo,\n cspAugmentOptions,\n ),\n );\n }\n}\n\nfunction isFrameworkOrAssetPath(pathname: string): boolean {\n return (\n pathname.startsWith(\"/.well-known/\") ||\n pathname.startsWith(\"/_agent_native/\") ||\n pathname.startsWith(\"/_agent-native/\") ||\n pathname.startsWith(\"/api/\") ||\n pathname.startsWith(\"/@vite/\") ||\n pathname.startsWith(\"/@id/\") ||\n pathname.startsWith(\"/@fs/\") ||\n pathname === \"/@react-refresh\" ||\n pathname === \"/__vite_ping\" ||\n pathname === \"/__open-in-editor\" ||\n pathname === \"/favicon.ico\" ||\n pathname === \"/favicon.png\" ||\n (/\\.\\w+$/.test(pathname) && !pathname.endsWith(\".data\"))\n );\n}\n\nasync function rewriteMountedResponse(\n response: Response,\n basePath: string,\n pathname: string,\n requestUrl: string,\n): Promise<Response> {\n const sentryClientConfigScript = getSentryClientConfigScript();\n const headers = new Headers(response.headers);\n applyDefaultSsrCacheHeader(headers, response.status, pathname);\n applyDefaultSpeculationRulesHeader(headers, response.status, basePath);\n\n const location = headers.get(\"location\");\n if (location?.startsWith(\"/\") && !location.startsWith(\"//\")) {\n headers.set(\"location\", prefixMountedPath(location, basePath));\n }\n\n const contentType = headers.get(\"content-type\") ?? \"\";\n if (!contentType.toLowerCase().includes(\"text/html\") || !response.body) {\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n }\n\n const html = await response.text();\n headers.delete(\"content-length\");\n applyDocumentCsp(headers, sentryClientConfigScript);\n return new Response(\n injectHeadScript(\n injectDefaultSocialImageMeta(\n prefixMountedHtml(html, basePath),\n defaultSocialImageUrl(requestUrl, basePath),\n ),\n sentryClientConfigScript,\n ),\n {\n status: response.status,\n statusText: response.statusText,\n headers,\n },\n );\n}\n\n/**\n * Create an h3 catch-all that hands page routes to React Router and\n * returns 404 for framework / asset paths that React Router doesn't own.\n */\nexport function createH3SSRHandler(getBuild: () => Promise<unknown> | unknown) {\n const handler = createRequestHandler(getBuild as any);\n return defineEventHandler(async (event) => {\n const basePath = getAppBasePath();\n const p = stripAppBasePath(event.url.pathname);\n if (isFrameworkOrAssetPath(p)) {\n return new Response(null, { status: 404 });\n }\n try {\n const request = requestWithPathname(event.req as Request, p, basePath);\n // SSR renders an IMPERSONAL public shell — we deliberately do NOT read the\n // request's session/cookies here, and pin an explicitly anonymous request\n // context. That keeps the SSR HTML/.data identical for every visitor so it\n // can be hard-cached at the CDN for everyone (see applyDefaultSsrCacheHeader).\n //\n // Consequence: SSR loaders that call `getRequestUserEmail()` / `accessFilter()`\n // always see the unauthenticated branch and render public content only. Any\n // per-user view (private records, share-grant access, who's logged in) MUST\n // be resolved CLIENT-SIDE after load, never baked into SSR. Do not re-pin the\n // session here to \"fix\" a per-user page — that silently makes the page\n // uncacheable and/or leaks one user's data into another's cached copy.\n const ctx = { userEmail: undefined, orgId: undefined };\n if (request.method === \"HEAD\") {\n const getRequest = new Request(request.url, {\n method: \"GET\",\n headers: request.headers,\n signal: request.signal,\n });\n const response = await runWithRequestContext(ctx, () =>\n handler(getRequest),\n );\n return await rewriteMountedResponse(\n new Response(null, {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n }),\n basePath,\n p,\n request.url,\n );\n }\n return await rewriteMountedResponse(\n await runWithRequestContext(ctx, () => handler(request)),\n basePath,\n p,\n request.url,\n );\n } catch (err) {\n // Log the full stack server-side, but never leak it to the client.\n // Stack traces expose file paths, library versions, and code structure\n // that aid reconnaissance attacks. In dev we surface the message text\n // so devtools shows something useful; in prod we return a bare 500.\n console.error(\"[ssr-handler] SSR error:\", err);\n const isProd = process.env.NODE_ENV === \"production\";\n const body = isProd\n ? \"Internal Server Error\"\n : `Internal Server Error: ${(err as Error)?.message ?? err}`;\n return new Response(body, {\n status: 500,\n headers: { \"content-type\": \"text/plain\" },\n });\n }\n });\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"action-types-plugin.d.ts","sourceRoot":"","sources":["../../src/vite/action-types-plugin.ts"],"names":[],"mappings":"AAmBA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,MAAM,CAAC;AAuUnC;;;;;;;;;GASG;AACH,wBAAgB,iBAAiB,IAAI,MAAM,CAuC1C;AAED;;;GAGG;AACH,wBAAgB,gCAAgC,CAAC,WAAW,EAAE,MAAM,GAAG,IAAI,CAG1E"}
1
+ {"version":3,"file":"action-types-plugin.d.ts","sourceRoot":"","sources":["../../src/vite/action-types-plugin.ts"],"names":[],"mappings":"AAmBA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,MAAM,CAAC;AA2UnC;;;;;;;;;GASG;AACH,wBAAgB,iBAAiB,IAAI,MAAM,CAuC1C;AAED;;;GAGG;AACH,wBAAgB,gCAAgC,CAAC,WAAW,EAAE,MAAM,GAAG,IAAI,CAG1E"}
@@ -263,12 +263,16 @@ type ActionEntry<T> = T extends { default: { run: (...args: infer A) => infer R
263
263
  }
264
264
  : { result: any; params: Record<string, any> };
265
265
 
266
- declare module "@agent-native/core/client" {
267
- interface ActionRegistry {
266
+ declare global {
267
+ interface AgentNativeActionRegistry {
268
268
  ${typeEntries.join("\n")}
269
269
  }
270
270
  }
271
271
 
272
+ declare module "@agent-native/core/client" {
273
+ interface ActionRegistry extends AgentNativeActionRegistry {}
274
+ }
275
+
272
276
  export {};
273
277
  `;
274
278
  writeIfChanged(path.join(outDir, "action-types.d.ts"), typesContent);
@@ -1 +1 @@
1
- {"version":3,"file":"action-types-plugin.js","sourceRoot":"","s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AC,CAAC;gBACnD,CAAC;YACH,CAAC,CAAC;YACF,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;YACxB,IAAI,mBAAmB;gBAAE,OAAO,CAAC,GAAG,CAAC,mBAAmB,CAAC,CAAC;YAC1D,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,YAAY,CAAC,CAAC;YAChC,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,YAAY,CAAC,CAAC;YACnC,qEAAqE;YACrE,uEAAuE;YACvE,6CAA6C;QAC/C,CAAC;KACF,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,gCAAgC,CAAC,WAAmB;IAClE,MAAM,UAAU,GAAG,IAAI,CAAC,OAAO,CAAC,WAAW,EAAE,SAAS,CAAC,CAAC;IACxD,uBAAuB,CAAC,UAAU,EAAE,WAAW,CAAC,CAAC;AACnD,CAAC","sourcesContent":["import fs from \"fs\";\n/**\n * Vite plugin that generates end-to-end type-safe action types AND a runtime\n * registry of static imports so bundlers (Nitro on Netlify/Vercel/AWS-Lambda,\n * Rolldown, etc.) include every action file in the server bundle.\n *\n * Watches the `actions/` directory and emits:\n * - `.generated/action-types.d.ts` — type-only module that augments the\n * `ActionRegistry` interface in `@agent-native/core/client`, giving\n * `useActionQuery`/`useActionMutation` full inference.\n * - `.generated/actions-registry.ts` — runtime registry keyed by action\n * name, with static `import` statements for every action. Templates\n * import this file from their `server/plugins/agent-chat.ts` so Nitro\n * bundles the actions into the server function; without it the runtime\n * `fs.readdirSync` inside `autoDiscoverActions` finds nothing in a\n * bundled serverless function and every action route 404s.\n */\nimport path from \"path\";\n\nimport type { Plugin } from \"vite\";\n\n/** Files to skip during discovery (matches action-discovery.ts). */\nconst SKIP_FILES = new Set([\n \"helpers\",\n \"run\",\n \"db-connect\",\n \"db-status\",\n \"registry\",\n]);\n\n/**\n * Framework-level sharing actions that must ALWAYS be in the generated\n * registry, even when the template's `actions/` directory doesn't contain\n * them. Each entry maps the action name to the bare-specifier import path so\n * bundlers see a static import and pull the module into the server bundle.\n *\n * Order matters: templates can override by defining a same-named file in\n * their own `actions/` directory — the merge below is skip-existing.\n */\nconst CORE_SHARING_ACTIONS: Array<{ name: string; specifier: string }> = [\n {\n name: \"share-resource\",\n specifier: \"@agent-native/core/sharing/actions/share-resource\",\n },\n {\n name: \"unshare-resource\",\n specifier: \"@agent-native/core/sharing/actions/unshare-resource\",\n },\n {\n name: \"list-resource-shares\",\n specifier: \"@agent-native/core/sharing/actions/list-resource-shares\",\n },\n {\n name: \"set-resource-visibility\",\n specifier: \"@agent-native/core/sharing/actions/set-resource-visibility\",\n },\n {\n name: \"upload-image\",\n specifier: \"@agent-native/core/file-upload/actions/upload-image\",\n },\n {\n name: \"context-manifest-get\",\n specifier:\n \"@agent-native/core/agent/context-xray/actions/context-manifest-get\",\n },\n {\n name: \"context-pin\",\n specifier: \"@agent-native/core/agent/context-xray/actions/context-pin\",\n },\n {\n name: \"context-evict\",\n specifier: \"@agent-native/core/agent/context-xray/actions/context-evict\",\n },\n {\n name: \"context-restore\",\n specifier: \"@agent-native/core/agent/context-xray/actions/context-restore\",\n },\n {\n name: \"context-report\",\n specifier: \"@agent-native/core/agent/context-xray/actions/context-report\",\n },\n {\n name: \"get-localization-preference\",\n specifier:\n \"@agent-native/core/localization/actions/get-localization-preference\",\n },\n {\n name: \"set-localization-preference\",\n specifier:\n \"@agent-native/core/localization/actions/set-localization-preference\",\n },\n];\n\nfunction isRuntimeSourceFile(filename: string): boolean {\n if (!/\\.(ts|js)$/.test(filename)) return false;\n if (/\\.d\\.ts$/.test(filename)) return false;\n if (/\\.(test|spec)\\.(ts|js)$/.test(filename)) return false;\n return true;\n}\n\nfunction scanActionFiles(actionsDir: string): string[] {\n let files: string[];\n try {\n files = fs.readdirSync(actionsDir);\n } catch {\n return [];\n }\n return files.filter((f) => {\n if (!isRuntimeSourceFile(f)) return false;\n const name = f.replace(/\\.(ts|js)$/, \"\");\n if (name.startsWith(\"_\")) return false;\n if (SKIP_FILES.has(name)) return false;\n // Only include files that actually call defineAction or explicitly\n // re-export a package action. CLI scripts or example templates that live\n // in actions/ but don't export an action would otherwise drag their own\n // (often app/, browser-only, or fs-only) imports into the serverless\n // bundle and fail to resolve.\n try {\n const content = fs.readFileSync(path.join(actionsDir, f), \"utf-8\");\n const reexportsDefaultAction =\n /export\\s*\\{\\s*default\\s*\\}\\s*from\\s*[\"'][^\"']+[\"']/.test(content);\n if (!content.includes(\"defineAction\") && !reexportsDefaultAction) {\n return false;\n }\n } catch {\n return false;\n }\n return true;\n });\n}\n\nfunction toIdent(name: string): string {\n return \"a_\" + name.replace(/[^a-zA-Z0-9_]/g, \"_\");\n}\n\nfunction writeIfChanged(outFile: string, content: string): void {\n const existing = fs.existsSync(outFile)\n ? fs.readFileSync(outFile, \"utf-8\")\n : \"\";\n if (existing !== content) {\n fs.mkdirSync(path.dirname(outFile), { recursive: true });\n fs.writeFileSync(outFile, content);\n }\n}\n\nfunction findWorkspaceCoreActionsDir(projectRoot: string): string | null {\n let dir = path.resolve(projectRoot);\n let workspaceRoot: string | null = null;\n let packageName: string | null = null;\n\n for (let i = 0; i < 20; i++) {\n const pkgPath = path.join(dir, \"package.json\");\n if (fs.existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(fs.readFileSync(pkgPath, \"utf-8\"));\n const declared = pkg?.[\"agent-native\"]?.workspaceCore;\n if (typeof declared === \"string\" && declared.length > 0) {\n workspaceRoot = dir;\n packageName = declared;\n break;\n }\n } catch {\n // Keep walking on malformed package.json.\n }\n }\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n\n if (!workspaceRoot || !packageName) return null;\n\n const nm = path.join(workspaceRoot, \"node_modules\", packageName);\n if (fs.existsSync(path.join(nm, \"package.json\"))) {\n const actionsDir = path.join(fs.realpathSync(nm), \"actions\");\n return fs.existsSync(actionsDir) ? actionsDir : null;\n }\n\n const packagesDir = path.join(workspaceRoot, \"packages\");\n const candidates: string[] = [];\n if (fs.existsSync(packagesDir)) {\n for (const entry of fs.readdirSync(packagesDir, { withFileTypes: true })) {\n if (!entry.isDirectory()) continue;\n candidates.push(path.join(packagesDir, entry.name));\n if (entry.name.startsWith(\"@\")) {\n const scopeDir = path.join(packagesDir, entry.name);\n for (const sub of fs.readdirSync(scopeDir, { withFileTypes: true })) {\n if (sub.isDirectory()) candidates.push(path.join(scopeDir, sub.name));\n }\n }\n }\n }\n\n for (const candidate of candidates) {\n const pkgPath = path.join(candidate, \"package.json\");\n if (!fs.existsSync(pkgPath)) continue;\n try {\n const pkg = JSON.parse(fs.readFileSync(pkgPath, \"utf-8\"));\n if (pkg?.name === packageName) {\n const actionsDir = path.join(candidate, \"actions\");\n return fs.existsSync(actionsDir) ? actionsDir : null;\n }\n } catch {\n // Ignore malformed package.json.\n }\n }\n\n return null;\n}\n\n/**\n * Scan the actions directory and emit the types + runtime registry files.\n * Only writes files whose content has changed, to avoid triggering rebuilds.\n */\nfunction generateActionArtifacts(\n actionsDir: string,\n projectRoot: string,\n): void {\n const outDir = path.resolve(projectRoot, \".generated\");\n const relActionsDir = path.relative(outDir, actionsDir).replace(/\\\\/g, \"/\");\n\n const actionFiles = scanActionFiles(actionsDir);\n const workspaceActionsDir = findWorkspaceCoreActionsDir(projectRoot);\n const workspaceActionFiles = workspaceActionsDir\n ? scanActionFiles(workspaceActionsDir)\n : [];\n\n // Pre-compute template action names — used for skip-existing logic in both\n // the type declarations and the runtime registry below.\n const templateActionNames = new Set<string>(\n actionFiles.map((f) => f.replace(/\\.(ts|js)$/, \"\")),\n );\n const registeredActionNames = new Set(templateActionNames);\n\n const actionSources = actionFiles.map((f) => {\n const name = f.replace(/\\.(ts|js)$/, \"\");\n return {\n name,\n relPath: `${relActionsDir}/${name}`,\n };\n });\n\n if (workspaceActionsDir) {\n for (const f of workspaceActionFiles) {\n const name = f.replace(/\\.(ts|js)$/, \"\");\n if (registeredActionNames.has(name)) continue;\n const relPath = path\n .relative(outDir, path.join(workspaceActionsDir, name))\n .replace(/\\\\/g, \"/\");\n actionSources.push({ name, relPath });\n registeredActionNames.add(name);\n }\n }\n\n // --- types file ---------------------------------------------------------\n const typeEntries = actionSources.map(({ name, relPath }) => {\n return ` \"${name}\": ActionEntry<typeof import(\"${relPath}\")>;`;\n });\n\n // Also declare types for framework-level sharing actions so callers don't\n // need `as any` casts (same skip-existing logic as the runtime registry).\n for (const entry of CORE_SHARING_ACTIONS) {\n if (registeredActionNames.has(entry.name)) continue;\n typeEntries.push(\n ` \"${entry.name}\": ActionEntry<typeof import(\"${entry.specifier}\")>;`,\n );\n registeredActionNames.add(entry.name);\n }\n\n const typesContent = `// AUTO-GENERATED by @agent-native/core — do not edit manually.\n// Regenerated when files in actions/ change.\n// This file augments the ActionRegistry interface so that useActionQuery and\n// useActionMutation infer the correct types from your action definitions.\n\n/** Extract the return type and parameter type from a defineAction module. */\ntype ActionEntry<T> = T extends { default: { run: (...args: infer A) => infer R } }\n ? {\n result: Awaited<R>;\n params: A extends [infer P, ...any[]] ? P : Record<string, any>;\n }\n : { result: any; params: Record<string, any> };\n\ndeclare module \"@agent-native/core/client\" {\n interface ActionRegistry {\n${typeEntries.join(\"\\n\")}\n }\n}\n\nexport {};\n`;\n\n writeIfChanged(path.join(outDir, \"action-types.d.ts\"), typesContent);\n\n // --- runtime registry ---------------------------------------------------\n // Static imports of each action's default export so bundlers see every\n // action and include it in the server bundle. Normalization matches\n // `loadActionsIntoRegistry` in server/action-discovery.ts.\n const imports: string[] = [];\n const entries: string[] = [];\n const runtimeActionNames = new Set<string>();\n for (const { name, relPath } of actionSources) {\n const ident = toIdent(name);\n imports.push(`import * as ${ident} from \"${relPath}\";`);\n entries.push(` ${JSON.stringify(name)}: ${ident},`);\n runtimeActionNames.add(name);\n }\n // Framework-level sharing actions — only added when the template hasn't\n // provided a same-named file (skip-existing merge). Static imports ensure\n // bundlers pull these modules into the server bundle so\n // `/_agent-native/actions/share-resource` (etc.) always resolve.\n for (const entry of CORE_SHARING_ACTIONS) {\n if (runtimeActionNames.has(entry.name)) continue;\n const ident = toIdent(entry.name);\n imports.push(`import * as ${ident} from \"${entry.specifier}\";`);\n entries.push(` ${JSON.stringify(entry.name)}: ${ident},`);\n runtimeActionNames.add(entry.name);\n }\n\n const registryContent = `// AUTO-GENERATED by @agent-native/core — do not edit manually.\n// Static-import registry of every action file. Bundlers (Nitro, Rolldown)\n// see these imports and include the action modules in the server bundle.\n// The agent-chat plugin normalizes each module into an ActionEntry shape.\n${imports.join(\"\\n\")}\n\nconst modules: Record<string, unknown> = {\n${entries.join(\"\\n\")}\n};\n\nexport default modules;\n`;\n\n // Always write the registry — even when the template has no actions/ files\n // we still emit imports for the framework-level sharing actions so they get\n // mounted on every template that consumes the registry.\n writeIfChanged(path.join(outDir, \"actions-registry.ts\"), registryContent);\n\n // Ensure .generated/ is in .gitignore\n const gitignorePath = path.join(projectRoot, \".gitignore\");\n if (fs.existsSync(gitignorePath)) {\n const gitignore = fs.readFileSync(gitignorePath, \"utf-8\");\n if (!gitignore.includes(\".generated\")) {\n fs.appendFileSync(gitignorePath, \"\\n.generated/\\n\");\n }\n }\n}\n\n/**\n * Vite plugin that watches `actions/` and generates type-safe action types.\n *\n * Add to your Vite config (auto-included by `defineConfig` from `@agent-native/core`):\n *\n * ```ts\n * import { actionTypesPlugin } from \"@agent-native/core/vite/action-types-plugin\";\n * plugins: [actionTypesPlugin()]\n * ```\n */\nexport function actionTypesPlugin(): Plugin {\n let projectRoot = \"\";\n let actionsDir = \"\";\n let workspaceActionsDir: string | null = null;\n\n return {\n name: \"agent-native-action-types\",\n configResolved(config) {\n projectRoot = config.root;\n actionsDir = path.resolve(projectRoot, \"actions\");\n workspaceActionsDir = findWorkspaceCoreActionsDir(projectRoot);\n },\n buildStart() {\n generateActionArtifacts(actionsDir, projectRoot);\n },\n configureServer(server) {\n // Generate on startup\n generateActionArtifacts(actionsDir, projectRoot);\n\n // Watch for changes in actions/\n const watcher = server.watcher;\n const handleChange = (file: string) => {\n const inAppActions = file.startsWith(actionsDir);\n const inWorkspaceActions = workspaceActionsDir\n ? file.startsWith(workspaceActionsDir)\n : false;\n if ((inAppActions || inWorkspaceActions) && /\\.(ts|js)$/.test(file)) {\n generateActionArtifacts(actionsDir, projectRoot);\n }\n };\n watcher.add(actionsDir);\n if (workspaceActionsDir) watcher.add(workspaceActionsDir);\n watcher.on(\"add\", handleChange);\n watcher.on(\"unlink\", handleChange);\n // Don't regenerate on content changes — only file additions/removals\n // affect the registry. Return type changes are picked up by TypeScript\n // from the source files via typeof import().\n },\n };\n}\n\n/**\n * Public helper to regenerate the types + registry from a non-Vite context\n * (e.g. the Nitro deploy build, where Vite plugins don't run).\n */\nexport function generateActionRegistryForProject(projectRoot: string): void {\n const actionsDir = path.resolve(projectRoot, \"actions\");\n generateActionArtifacts(actionsDir, projectRoot);\n}\n"]}
1
+ {"version":3,"file":"action-types-plugin.js","sourceRoot":"","sources":["../../src/vite/action-types-plugin.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB;;;;;;;;;;;;;;;GAeG;AACH,OAAO,IAAI,MAAM,MAAM,CAAC;AAIxB,oEAAoE;AACpE,MAAM,UAAU,GAAG,IAAI,GAAG,CAAC;IACzB,SAAS;IACT,KAAK;IACL,YAAY;IACZ,WAAW;IACX,UAAU;CACX,CAAC,CAAC;AAEH;;;;;;;;GAQG;AACH,MAAM,oBAAoB,GAA+C;IACvE;QACE,IAAI,EAAE,gBAAgB;QACtB,SAAS,EAAE,mDAAmD;KAC/D;IACD;QACE,IAAI,EAAE,kBAAkB;QACxB,SAAS,EAAE,qDAAqD;KACjE;IACD;QACE,IAAI,EAAE,sBAAsB;QAC5B,SAAS,EAAE,yDAAyD;KACrE;IACD;QACE,IAAI,EAAE,yBAAyB;QAC/B,SAAS,EAAE,4DAA4D;KACxE;IACD;QACE,IAAI,EAAE,cAAc;QACpB,SAAS,EAAE,qDAAqD;KACjE;IACD;QACE,IAAI,EAAE,sBAAsB;QAC5B,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WAAW,CAAC,CAAC;QACnD,CAAC;QACD,eAAe,CAAC,MAAM;YACpB,sBAAsB;YACtB,uBAAuB,CAAC,UAAU,EAAE,WAAW,CAAC,CAAC;YAEjD,gCAAgC;YAChC,MAAM,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC;YAC/B,MAAM,YAAY,GAAG,CAAC,IAAY,EAAE,EAAE;gBACpC,MAAM,YAAY,GAAG,IAAI,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC;gBACjD,MAAM,kBAAkB,GAAG,mBAAmB;oBAC5C,CAAC,CAAC,IAAI,CAAC,UAAU,CAAC,mBAAmB,CAAC;oBACtC,CAAC,CAAC,KAAK,CAAC;gBACV,IAAI,CAAC,YAAY,IAAI,kBAAkB,CAAC,IAAI,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;oBACpE,uBAAuB,CAAC,UAAU,EAAE,WAAW,CAAC,CAAC;gBACnD,CAAC;YACH,CAAC,CAAC;YACF,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;YACxB,IAAI,mBAAmB;gBAAE,OAAO,CAAC,GAAG,CAAC,mBAAmB,CAAC,CAAC;YAC1D,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,YAAY,CAAC,CAAC;YAChC,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,YAAY,CAAC,CAAC;YACnC,qEAAqE;YACrE,uEAAuE;YACvE,6CAA6C;QAC/C,CAAC;KACF,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,gCAAgC,CAAC,WAAmB;IAClE,MAAM,UAAU,GAAG,IAAI,CAAC,OAAO,CAAC,WAAW,EAAE,SAAS,CAAC,CAAC;IACxD,uBAAuB,CAAC,UAAU,EAAE,WAAW,CAAC,CAAC;AACnD,CAAC","sourcesContent":["import fs from \"fs\";\n/**\n * Vite plugin that generates end-to-end type-safe action types AND a runtime\n * registry of static imports so bundlers (Nitro on Netlify/Vercel/AWS-Lambda,\n * Rolldown, etc.) include every action file in the server bundle.\n *\n * Watches the `actions/` directory and emits:\n * - `.generated/action-types.d.ts` — type-only module that augments the\n * `ActionRegistry` interface in `@agent-native/core/client`, giving\n * `useActionQuery`/`useActionMutation` full inference.\n * - `.generated/actions-registry.ts` — runtime registry keyed by action\n * name, with static `import` statements for every action. Templates\n * import this file from their `server/plugins/agent-chat.ts` so Nitro\n * bundles the actions into the server function; without it the runtime\n * `fs.readdirSync` inside `autoDiscoverActions` finds nothing in a\n * bundled serverless function and every action route 404s.\n */\nimport path from \"path\";\n\nimport type { Plugin } from \"vite\";\n\n/** Files to skip during discovery (matches action-discovery.ts). */\nconst SKIP_FILES = new Set([\n \"helpers\",\n \"run\",\n \"db-connect\",\n \"db-status\",\n \"registry\",\n]);\n\n/**\n * Framework-level sharing actions that must ALWAYS be in the generated\n * registry, even when the template's `actions/` directory doesn't contain\n * them. Each entry maps the action name to the bare-specifier import path so\n * bundlers see a static import and pull the module into the server bundle.\n *\n * Order matters: templates can override by defining a same-named file in\n * their own `actions/` directory — the merge below is skip-existing.\n */\nconst CORE_SHARING_ACTIONS: Array<{ name: string; specifier: string }> = [\n {\n name: \"share-resource\",\n specifier: \"@agent-native/core/sharing/actions/share-resource\",\n },\n {\n name: \"unshare-resource\",\n specifier: \"@agent-native/core/sharing/actions/unshare-resource\",\n },\n {\n name: \"list-resource-shares\",\n specifier: \"@agent-native/core/sharing/actions/list-resource-shares\",\n },\n {\n name: \"set-resource-visibility\",\n specifier: \"@agent-native/core/sharing/actions/set-resource-visibility\",\n },\n {\n name: \"upload-image\",\n specifier: \"@agent-native/core/file-upload/actions/upload-image\",\n },\n {\n name: \"context-manifest-get\",\n specifier:\n \"@agent-native/core/agent/context-xray/actions/context-manifest-get\",\n },\n {\n name: \"context-pin\",\n specifier: \"@agent-native/core/agent/context-xray/actions/context-pin\",\n },\n {\n name: \"context-evict\",\n specifier: \"@agent-native/core/agent/context-xray/actions/context-evict\",\n },\n {\n name: \"context-restore\",\n specifier: \"@agent-native/core/agent/context-xray/actions/context-restore\",\n },\n {\n name: \"context-report\",\n specifier: \"@agent-native/core/agent/context-xray/actions/context-report\",\n },\n {\n name: \"get-localization-preference\",\n specifier:\n \"@agent-native/core/localization/actions/get-localization-preference\",\n },\n {\n name: \"set-localization-preference\",\n specifier:\n \"@agent-native/core/localization/actions/set-localization-preference\",\n },\n];\n\nfunction isRuntimeSourceFile(filename: string): boolean {\n if (!/\\.(ts|js)$/.test(filename)) return false;\n if (/\\.d\\.ts$/.test(filename)) return false;\n if (/\\.(test|spec)\\.(ts|js)$/.test(filename)) return false;\n return true;\n}\n\nfunction scanActionFiles(actionsDir: string): string[] {\n let files: string[];\n try {\n files = fs.readdirSync(actionsDir);\n } catch {\n return [];\n }\n return files.filter((f) => {\n if (!isRuntimeSourceFile(f)) return false;\n const name = f.replace(/\\.(ts|js)$/, \"\");\n if (name.startsWith(\"_\")) return false;\n if (SKIP_FILES.has(name)) return false;\n // Only include files that actually call defineAction or explicitly\n // re-export a package action. CLI scripts or example templates that live\n // in actions/ but don't export an action would otherwise drag their own\n // (often app/, browser-only, or fs-only) imports into the serverless\n // bundle and fail to resolve.\n try {\n const content = fs.readFileSync(path.join(actionsDir, f), \"utf-8\");\n const reexportsDefaultAction =\n /export\\s*\\{\\s*default\\s*\\}\\s*from\\s*[\"'][^\"']+[\"']/.test(content);\n if (!content.includes(\"defineAction\") && !reexportsDefaultAction) {\n return false;\n }\n } catch {\n return false;\n }\n return true;\n });\n}\n\nfunction toIdent(name: string): string {\n return \"a_\" + name.replace(/[^a-zA-Z0-9_]/g, \"_\");\n}\n\nfunction writeIfChanged(outFile: string, content: string): void {\n const existing = fs.existsSync(outFile)\n ? fs.readFileSync(outFile, \"utf-8\")\n : \"\";\n if (existing !== content) {\n fs.mkdirSync(path.dirname(outFile), { recursive: true });\n fs.writeFileSync(outFile, content);\n }\n}\n\nfunction findWorkspaceCoreActionsDir(projectRoot: string): string | null {\n let dir = path.resolve(projectRoot);\n let workspaceRoot: string | null = null;\n let packageName: string | null = null;\n\n for (let i = 0; i < 20; i++) {\n const pkgPath = path.join(dir, \"package.json\");\n if (fs.existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(fs.readFileSync(pkgPath, \"utf-8\"));\n const declared = pkg?.[\"agent-native\"]?.workspaceCore;\n if (typeof declared === \"string\" && declared.length > 0) {\n workspaceRoot = dir;\n packageName = declared;\n break;\n }\n } catch {\n // Keep walking on malformed package.json.\n }\n }\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n\n if (!workspaceRoot || !packageName) return null;\n\n const nm = path.join(workspaceRoot, \"node_modules\", packageName);\n if (fs.existsSync(path.join(nm, \"package.json\"))) {\n const actionsDir = path.join(fs.realpathSync(nm), \"actions\");\n return fs.existsSync(actionsDir) ? actionsDir : null;\n }\n\n const packagesDir = path.join(workspaceRoot, \"packages\");\n const candidates: string[] = [];\n if (fs.existsSync(packagesDir)) {\n for (const entry of fs.readdirSync(packagesDir, { withFileTypes: true })) {\n if (!entry.isDirectory()) continue;\n candidates.push(path.join(packagesDir, entry.name));\n if (entry.name.startsWith(\"@\")) {\n const scopeDir = path.join(packagesDir, entry.name);\n for (const sub of fs.readdirSync(scopeDir, { withFileTypes: true })) {\n if (sub.isDirectory()) candidates.push(path.join(scopeDir, sub.name));\n }\n }\n }\n }\n\n for (const candidate of candidates) {\n const pkgPath = path.join(candidate, \"package.json\");\n if (!fs.existsSync(pkgPath)) continue;\n try {\n const pkg = JSON.parse(fs.readFileSync(pkgPath, \"utf-8\"));\n if (pkg?.name === packageName) {\n const actionsDir = path.join(candidate, \"actions\");\n return fs.existsSync(actionsDir) ? actionsDir : null;\n }\n } catch {\n // Ignore malformed package.json.\n }\n }\n\n return null;\n}\n\n/**\n * Scan the actions directory and emit the types + runtime registry files.\n * Only writes files whose content has changed, to avoid triggering rebuilds.\n */\nfunction generateActionArtifacts(\n actionsDir: string,\n projectRoot: string,\n): void {\n const outDir = path.resolve(projectRoot, \".generated\");\n const relActionsDir = path.relative(outDir, actionsDir).replace(/\\\\/g, \"/\");\n\n const actionFiles = scanActionFiles(actionsDir);\n const workspaceActionsDir = findWorkspaceCoreActionsDir(projectRoot);\n const workspaceActionFiles = workspaceActionsDir\n ? scanActionFiles(workspaceActionsDir)\n : [];\n\n // Pre-compute template action names — used for skip-existing logic in both\n // the type declarations and the runtime registry below.\n const templateActionNames = new Set<string>(\n actionFiles.map((f) => f.replace(/\\.(ts|js)$/, \"\")),\n );\n const registeredActionNames = new Set(templateActionNames);\n\n const actionSources = actionFiles.map((f) => {\n const name = f.replace(/\\.(ts|js)$/, \"\");\n return {\n name,\n relPath: `${relActionsDir}/${name}`,\n };\n });\n\n if (workspaceActionsDir) {\n for (const f of workspaceActionFiles) {\n const name = f.replace(/\\.(ts|js)$/, \"\");\n if (registeredActionNames.has(name)) continue;\n const relPath = path\n .relative(outDir, path.join(workspaceActionsDir, name))\n .replace(/\\\\/g, \"/\");\n actionSources.push({ name, relPath });\n registeredActionNames.add(name);\n }\n }\n\n // --- types file ---------------------------------------------------------\n const typeEntries = actionSources.map(({ name, relPath }) => {\n return ` \"${name}\": ActionEntry<typeof import(\"${relPath}\")>;`;\n });\n\n // Also declare types for framework-level sharing actions so callers don't\n // need `as any` casts (same skip-existing logic as the runtime registry).\n for (const entry of CORE_SHARING_ACTIONS) {\n if (registeredActionNames.has(entry.name)) continue;\n typeEntries.push(\n ` \"${entry.name}\": ActionEntry<typeof import(\"${entry.specifier}\")>;`,\n );\n registeredActionNames.add(entry.name);\n }\n\n const typesContent = `// AUTO-GENERATED by @agent-native/core — do not edit manually.\n// Regenerated when files in actions/ change.\n// This file augments the ActionRegistry interface so that useActionQuery and\n// useActionMutation infer the correct types from your action definitions.\n\n/** Extract the return type and parameter type from a defineAction module. */\ntype ActionEntry<T> = T extends { default: { run: (...args: infer A) => infer R } }\n ? {\n result: Awaited<R>;\n params: A extends [infer P, ...any[]] ? P : Record<string, any>;\n }\n : { result: any; params: Record<string, any> };\n\ndeclare global {\n interface AgentNativeActionRegistry {\n${typeEntries.join(\"\\n\")}\n }\n}\n\ndeclare module \"@agent-native/core/client\" {\n interface ActionRegistry extends AgentNativeActionRegistry {}\n}\n\nexport {};\n`;\n\n writeIfChanged(path.join(outDir, \"action-types.d.ts\"), typesContent);\n\n // --- runtime registry ---------------------------------------------------\n // Static imports of each action's default export so bundlers see every\n // action and include it in the server bundle. Normalization matches\n // `loadActionsIntoRegistry` in server/action-discovery.ts.\n const imports: string[] = [];\n const entries: string[] = [];\n const runtimeActionNames = new Set<string>();\n for (const { name, relPath } of actionSources) {\n const ident = toIdent(name);\n imports.push(`import * as ${ident} from \"${relPath}\";`);\n entries.push(` ${JSON.stringify(name)}: ${ident},`);\n runtimeActionNames.add(name);\n }\n // Framework-level sharing actions — only added when the template hasn't\n // provided a same-named file (skip-existing merge). Static imports ensure\n // bundlers pull these modules into the server bundle so\n // `/_agent-native/actions/share-resource` (etc.) always resolve.\n for (const entry of CORE_SHARING_ACTIONS) {\n if (runtimeActionNames.has(entry.name)) continue;\n const ident = toIdent(entry.name);\n imports.push(`import * as ${ident} from \"${entry.specifier}\";`);\n entries.push(` ${JSON.stringify(entry.name)}: ${ident},`);\n runtimeActionNames.add(entry.name);\n }\n\n const registryContent = `// AUTO-GENERATED by @agent-native/core — do not edit manually.\n// Static-import registry of every action file. Bundlers (Nitro, Rolldown)\n// see these imports and include the action modules in the server bundle.\n// The agent-chat plugin normalizes each module into an ActionEntry shape.\n${imports.join(\"\\n\")}\n\nconst modules: Record<string, unknown> = {\n${entries.join(\"\\n\")}\n};\n\nexport default modules;\n`;\n\n // Always write the registry — even when the template has no actions/ files\n // we still emit imports for the framework-level sharing actions so they get\n // mounted on every template that consumes the registry.\n writeIfChanged(path.join(outDir, \"actions-registry.ts\"), registryContent);\n\n // Ensure .generated/ is in .gitignore\n const gitignorePath = path.join(projectRoot, \".gitignore\");\n if (fs.existsSync(gitignorePath)) {\n const gitignore = fs.readFileSync(gitignorePath, \"utf-8\");\n if (!gitignore.includes(\".generated\")) {\n fs.appendFileSync(gitignorePath, \"\\n.generated/\\n\");\n }\n }\n}\n\n/**\n * Vite plugin that watches `actions/` and generates type-safe action types.\n *\n * Add to your Vite config (auto-included by `defineConfig` from `@agent-native/core`):\n *\n * ```ts\n * import { actionTypesPlugin } from \"@agent-native/core/vite/action-types-plugin\";\n * plugins: [actionTypesPlugin()]\n * ```\n */\nexport function actionTypesPlugin(): Plugin {\n let projectRoot = \"\";\n let actionsDir = \"\";\n let workspaceActionsDir: string | null = null;\n\n return {\n name: \"agent-native-action-types\",\n configResolved(config) {\n projectRoot = config.root;\n actionsDir = path.resolve(projectRoot, \"actions\");\n workspaceActionsDir = findWorkspaceCoreActionsDir(projectRoot);\n },\n buildStart() {\n generateActionArtifacts(actionsDir, projectRoot);\n },\n configureServer(server) {\n // Generate on startup\n generateActionArtifacts(actionsDir, projectRoot);\n\n // Watch for changes in actions/\n const watcher = server.watcher;\n const handleChange = (file: string) => {\n const inAppActions = file.startsWith(actionsDir);\n const inWorkspaceActions = workspaceActionsDir\n ? file.startsWith(workspaceActionsDir)\n : false;\n if ((inAppActions || inWorkspaceActions) && /\\.(ts|js)$/.test(file)) {\n generateActionArtifacts(actionsDir, projectRoot);\n }\n };\n watcher.add(actionsDir);\n if (workspaceActionsDir) watcher.add(workspaceActionsDir);\n watcher.on(\"add\", handleChange);\n watcher.on(\"unlink\", handleChange);\n // Don't regenerate on content changes — only file additions/removals\n // affect the registry. Return type changes are picked up by TypeScript\n // from the source files via typeof import().\n },\n };\n}\n\n/**\n * Public helper to regenerate the types + registry from a non-Vite context\n * (e.g. the Nitro deploy build, where Vite plugins don't run).\n */\nexport function generateActionRegistryForProject(projectRoot: string): void {\n const actionsDir = path.resolve(projectRoot, \"actions\");\n generateActionArtifacts(actionsDir, projectRoot);\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/vite/client.ts"],"names":[],"mappings":"AAMA,OA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GAAG,SAAS,GACvB,MAAM,GAAG,SAAS,CAMpB;AAED,wBAAgB,kBAAkB,CAChC,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM,GAAG,SAAS,GACvB,OAAO,CAWT;AA4vBD;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,WAAW,CACzB,OAAO,GAAE,4BAAiC,GACzC,MAAM,EAAE,CAcV;AAED;;;;;GAKG;AACH,wBAAgB,YAAY,CAAC,OAAO,GAAE,mBAAwB,GAAG,UAAU,CAU1E;AAED,OAAO,EACL,eAAe,IAAI,gBAAgB,EACnC,sBAAsB,IAAI,uBAAuB,EACjD,mBAAmB,IAAI,oBAAoB,EAC3C,qBAAqB,IAAI,sBAAsB,GAChD,CAAC"}
@@ -1,3 +1,4 @@
1
+ import { EventEmitter } from "events";
1
2
  import fs from "fs";
2
3
  import { createRequire, syncBuiltinESMExports } from "module";
3
4
  import path from "path";
@@ -14,6 +15,119 @@ import { agentsBundlePlugin } from "./agents-bundle-plugin.js";
14
15
  const require = createRequire(import.meta.url);
15
16
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
16
17
  let nitroFsWatchGuardInstalled = false;
18
+ function isFileWatchLimitError(error) {
19
+ return error?.code === "EMFILE" || error?.code === "ENOSPC";
20
+ }
21
+ function watchPollingIntervalMs() {
22
+ const raw = Number(process.env.CHOKIDAR_INTERVAL ?? 1000);
23
+ return Number.isFinite(raw) && raw > 0 ? raw : 1000;
24
+ }
25
+ function fsWatchListener(args) {
26
+ const maybeOptionsOrListener = args[1];
27
+ const maybeListener = args[2];
28
+ if (typeof maybeOptionsOrListener === "function")
29
+ return maybeOptionsOrListener;
30
+ if (typeof maybeListener === "function")
31
+ return maybeListener;
32
+ return null;
33
+ }
34
+ function fsWatchPersistent(args) {
35
+ const options = args[1];
36
+ if (!options || typeof options === "function")
37
+ return true;
38
+ if (typeof options === "string" || Buffer.isBuffer(options))
39
+ return true;
40
+ return options.persistent !== false;
41
+ }
42
+ function directEntrySnapshot(target) {
43
+ const snapshot = new Map();
44
+ const stat = fs.statSync(target);
45
+ if (!stat.isDirectory()) {
46
+ snapshot.set(path.basename(target), {
47
+ mtimeMs: stat.mtimeMs,
48
+ size: stat.size,
49
+ directory: false,
50
+ });
51
+ return snapshot;
52
+ }
53
+ for (const entry of fs.readdirSync(target, { withFileTypes: true })) {
54
+ const entryPath = path.join(target, entry.name);
55
+ try {
56
+ const entryStat = fs.statSync(entryPath);
57
+ snapshot.set(entry.name, {
58
+ mtimeMs: entryStat.mtimeMs,
59
+ size: entryStat.size,
60
+ directory: entryStat.isDirectory(),
61
+ });
62
+ }
63
+ catch {
64
+ // The entry may have disappeared between readdir and stat.
65
+ }
66
+ }
67
+ return snapshot;
68
+ }
69
+ function createPollingFsWatcher(args) {
70
+ const target = String(args[0]);
71
+ const listener = fsWatchListener(args);
72
+ const emitter = new EventEmitter();
73
+ let closed = false;
74
+ let previous = directEntrySnapshot(target);
75
+ if (listener)
76
+ emitter.on("change", listener);
77
+ const emitChange = (eventName, filename) => {
78
+ emitter.emit("change", eventName, filename);
79
+ };
80
+ const timer = setInterval(() => {
81
+ if (closed)
82
+ return;
83
+ let next;
84
+ try {
85
+ next = directEntrySnapshot(target);
86
+ }
87
+ catch (error) {
88
+ emitter.emit("error", error);
89
+ return;
90
+ }
91
+ for (const [filename, current] of next) {
92
+ const old = previous.get(filename);
93
+ if (!old) {
94
+ emitChange("rename", filename);
95
+ continue;
96
+ }
97
+ if (old.mtimeMs !== current.mtimeMs ||
98
+ old.size !== current.size ||
99
+ old.directory !== current.directory) {
100
+ emitChange("change", filename);
101
+ }
102
+ }
103
+ for (const filename of previous.keys()) {
104
+ if (!next.has(filename))
105
+ emitChange("rename", filename);
106
+ }
107
+ previous = next;
108
+ }, watchPollingIntervalMs());
109
+ if (!fsWatchPersistent(args))
110
+ timer.unref();
111
+ emitter.close = () => {
112
+ if (closed)
113
+ return;
114
+ closed = true;
115
+ clearInterval(timer);
116
+ emitter.removeAllListeners();
117
+ };
118
+ emitter.ref = () => {
119
+ timer.ref();
120
+ return emitter;
121
+ };
122
+ emitter.unref = () => {
123
+ timer.unref();
124
+ return emitter;
125
+ };
126
+ return emitter;
127
+ }
128
+ function warnNitroFsWatchFallback(target, err) {
129
+ console.warn(`[agent-native] Falling back to polling Nitro fs.watch for ${String(target)}: ${err.message}`);
130
+ }
17
131
  function installNitroFsWatchGuard() {
18
132
  if (nitroFsWatchGuardInstalled)
19
133
  return;
@@ -26,23 +140,30 @@ function installNitroFsWatchGuard() {
26
140
  }
27
141
  catch (error) {
28
142
  const err = error;
29
- if (err.code !== "EMFILE" && err.code !== "ENOSPC")
143
+ if (!isFileWatchLimitError(err))
30
144
  throw error;
31
- console.warn(`[agent-native] Disabled Nitro fs.watch for ${String(args[0])}: ${err.message}`);
32
- return {
33
- close() { },
34
- on() {
35
- return this;
36
- },
37
- };
145
+ warnNitroFsWatchFallback(args[0], err);
146
+ return createPollingFsWatcher(args);
38
147
  }
39
148
  const originalEmit = watcher.emit.bind(watcher);
149
+ const originalClose = watcher.close.bind(watcher);
150
+ let pollingFallback;
151
+ watcher.close = (() => {
152
+ pollingFallback?.close();
153
+ return originalClose();
154
+ });
40
155
  watcher.emit = ((eventName, ...eventArgs) => {
41
156
  const err = eventArgs[0];
42
- if (eventName === "error" &&
43
- (err?.code === "EMFILE" || err?.code === "ENOSPC")) {
44
- console.warn(`[agent-native] Disabled Nitro fs.watch for ${String(args[0])}: ${err.message}`);
157
+ if (eventName === "error" && isFileWatchLimitError(err) && err) {
158
+ warnNitroFsWatchFallback(args[0], err);
45
159
  watcher.close();
160
+ pollingFallback = createPollingFsWatcher(args);
161
+ pollingFallback.on("change", (changeEvent, filename) => {
162
+ originalEmit("change", changeEvent, filename);
163
+ });
164
+ pollingFallback.on("error", (pollingError) => {
165
+ originalEmit("error", pollingError);
166
+ });
46
167
  return false;
47
168
  }
48
169
  return originalEmit(eventName, ...eventArgs);