@pyric/cli 0.1.0-alpha.11 → 0.1.0-alpha.12

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 (301) hide show
  1. package/dist/conformance/.generated/can-i-use-browser.d.ts.map +1 -1
  2. package/dist/conformance/.generated/can-i-use-browser.js +1 -1
  3. package/dist/conformance/.generated/can-i-use-browser.js.map +1 -1
  4. package/dist/conformance/.generated/can-i-use.d.ts.map +1 -1
  5. package/dist/conformance/.generated/can-i-use.js +2 -2
  6. package/dist/conformance/.generated/can-i-use.js.map +1 -1
  7. package/dist/serve/docs-ui/docs/_rhythm/index.html +1 -1
  8. package/dist/serve/docs-ui/docs/agent/set-up-your-agent/index.html +1 -1
  9. package/dist/serve/docs-ui/docs/agent/watch-and-review/index.html +1 -1
  10. package/dist/serve/docs-ui/docs/agent/work-with-an-agent/index.html +1 -1
  11. package/dist/serve/docs-ui/docs/ai-compat/index.html +1 -1
  12. package/dist/serve/docs-ui/docs/api-reference/index.html +2 -2
  13. package/dist/serve/docs-ui/docs/api-reference.md +1 -1
  14. package/dist/serve/docs-ui/docs/app-compat/index.html +1 -1
  15. package/dist/serve/docs-ui/docs/auth-compat/index.html +1 -1
  16. package/dist/serve/docs-ui/docs/build/ai-logic/index.html +1 -1
  17. package/dist/serve/docs-ui/docs/build/authentication/index.html +1 -1
  18. package/dist/serve/docs-ui/docs/build/cloud-firestore/index.html +1 -1
  19. package/dist/serve/docs-ui/docs/build/cloud-messaging/index.html +1 -1
  20. package/dist/serve/docs-ui/docs/build/cloud-storage/index.html +1 -1
  21. package/dist/serve/docs-ui/docs/build/realtime-database/index.html +1 -1
  22. package/dist/serve/docs-ui/docs/conformance-scores/index.html +1 -1
  23. package/dist/serve/docs-ui/docs/create-pyric-reference-api/index.html +1 -1
  24. package/dist/serve/docs-ui/docs/database-compat/index.html +1 -1
  25. package/dist/serve/docs-ui/docs/firestore-compat/index.html +1 -1
  26. package/dist/serve/docs-ui/docs/functions-rtdb-compat/index.html +1 -1
  27. package/dist/serve/docs-ui/docs/get-started/how-the-swap-works/index.html +1 -1
  28. package/dist/serve/docs-ui/docs/get-started/start-building/index.html +1 -1
  29. package/dist/serve/docs-ui/docs/index.json +200 -25
  30. package/dist/serve/docs-ui/docs/messaging-compat/index.html +1 -1
  31. package/dist/serve/docs-ui/docs/observe/see-whats-happening/index.html +1 -1
  32. package/dist/serve/docs-ui/docs/observe/shape-your-data/index.html +1 -1
  33. package/dist/serve/docs-ui/docs/overview/index.html +1 -1
  34. package/dist/serve/docs-ui/docs/pyric-admin-app-reference-api/index.html +1 -1
  35. package/dist/serve/docs-ui/docs/pyric-admin-auth-reference-api/index.html +1 -1
  36. package/dist/serve/docs-ui/docs/pyric-admin-database-reference-api/index.html +1 -1
  37. package/dist/serve/docs-ui/docs/pyric-admin-firestore-reference-api/index.html +1 -1
  38. package/dist/serve/docs-ui/docs/pyric-admin-messaging-reference-api/index.html +916 -0
  39. package/dist/serve/docs-ui/docs/pyric-admin-messaging-reference-api.md +706 -0
  40. package/dist/serve/docs-ui/docs/pyric-admin-storage-reference-api/index.html +1 -1
  41. package/dist/serve/docs-ui/docs/pyric-ai-reference-api/index.html +1 -1
  42. package/dist/serve/docs-ui/docs/pyric-ai-scripting-reference-api/index.html +1 -1
  43. package/dist/serve/docs-ui/docs/pyric-app-reference-api/index.html +1 -1
  44. package/dist/serve/docs-ui/docs/pyric-auth-reference-api/index.html +1 -1
  45. package/dist/serve/docs-ui/docs/pyric-cli-assurance-browser-reference-api/index.html +1 -1
  46. package/dist/serve/docs-ui/docs/pyric-cli-assurance-reference-api/index.html +1 -1
  47. package/dist/serve/docs-ui/docs/pyric-cli-bridge-client-reference-api/index.html +1 -1
  48. package/dist/serve/docs-ui/docs/pyric-cli-bridge-reference-api/index.html +1 -1
  49. package/dist/serve/docs-ui/docs/pyric-cli-conformance-browser-reference-api/index.html +1 -1
  50. package/dist/serve/docs-ui/docs/pyric-cli-conformance-docs-reference-api/index.html +1 -1
  51. package/dist/serve/docs-ui/docs/pyric-cli-conformance-reference-api/index.html +1 -1
  52. package/dist/serve/docs-ui/docs/pyric-cli-credentials-node-reference-api/index.html +1 -1
  53. package/dist/serve/docs-ui/docs/pyric-cli-discover-reference-api/index.html +1 -1
  54. package/dist/serve/docs-ui/docs/pyric-cli-register-reference-api/index.html +1 -1
  55. package/dist/serve/docs-ui/docs/pyric-cli-remote-reference-api/index.html +1 -1
  56. package/dist/serve/docs-ui/docs/pyric-cli-serve-worker-reference-api/index.html +131 -66
  57. package/dist/serve/docs-ui/docs/pyric-cli-serve-worker-reference-api.md +130 -65
  58. package/dist/serve/docs-ui/docs/pyric-cli-verify-reference-api/index.html +1 -1
  59. package/dist/serve/docs-ui/docs/pyric-cli-vite-reference-api/index.html +1 -1
  60. package/dist/serve/docs-ui/docs/pyric-database-reference-api/index.html +1 -1
  61. package/dist/serve/docs-ui/docs/pyric-firestore-reference-api/index.html +1 -1
  62. package/dist/serve/docs-ui/docs/pyric-messaging-reference-api/index.html +1 -1
  63. package/dist/serve/docs-ui/docs/pyric-messaging-sw-reference-api/index.html +1 -1
  64. package/dist/serve/docs-ui/docs/pyric-rules-reference-api/index.html +1 -1
  65. package/dist/serve/docs-ui/docs/pyric-sandbox-database-reference-api/index.html +1 -1
  66. package/dist/serve/docs-ui/docs/pyric-sandbox-firestore-reference-api/index.html +1 -1
  67. package/dist/serve/docs-ui/docs/pyric-sandbox-reference-api/index.html +37 -14
  68. package/dist/serve/docs-ui/docs/pyric-sandbox-reference-api.md +28 -8
  69. package/dist/serve/docs-ui/docs/pyric-storage-reference-api/index.html +1 -1
  70. package/dist/serve/docs-ui/docs/pyric-ui-agents-reference-api/index.html +1 -1
  71. package/dist/serve/docs-ui/docs/pyric-ui-auth-hooks-reference-api/index.html +1 -1
  72. package/dist/serve/docs-ui/docs/pyric-ui-auth-reference-api/index.html +1 -1
  73. package/dist/serve/docs-ui/docs/pyric-ui-events-hooks-reference-api/index.html +1 -1
  74. package/dist/serve/docs-ui/docs/pyric-ui-events-reference-api/index.html +1 -1
  75. package/dist/serve/docs-ui/docs/pyric-ui-firestore-hooks-reference-api/index.html +1 -1
  76. package/dist/serve/docs-ui/docs/pyric-ui-firestore-reference-api/index.html +1 -1
  77. package/dist/serve/docs-ui/docs/pyric-ui-primitives-reference-api/index.html +1 -1
  78. package/dist/serve/docs-ui/docs/pyric-ui-rtdb-reference-api/index.html +1 -1
  79. package/dist/serve/docs-ui/docs/pyric-ui-rules-hooks-reference-api/index.html +1 -1
  80. package/dist/serve/docs-ui/docs/pyric-ui-rules-reference-api/index.html +1 -1
  81. package/dist/serve/docs-ui/docs/pyric-ui-storage-hooks-reference-api/index.html +1 -1
  82. package/dist/serve/docs-ui/docs/pyric-ui-storage-reference-api/index.html +1 -1
  83. package/dist/serve/docs-ui/docs/pyric-ui-traffic-hooks-reference-api/index.html +1 -1
  84. package/dist/serve/docs-ui/docs/pyric-ui-traffic-reference-api/index.html +1 -1
  85. package/dist/serve/docs-ui/docs/rules-compat/index.html +1 -1
  86. package/dist/serve/docs-ui/docs/secure/audit-your-rules/index.html +1 -1
  87. package/dist/serve/docs-ui/docs/secure/firestore-rules-limits/index.html +1 -1
  88. package/dist/serve/docs-ui/docs/secure/read-a-denial/index.html +1 -1
  89. package/dist/serve/docs-ui/docs/secure/rtdb-rules-in-typescript/index.html +1 -1
  90. package/dist/serve/docs-ui/docs/secure/rules-standard-library/index.html +1 -1
  91. package/dist/serve/docs-ui/docs/secure/secure-it-with-rules/index.html +1 -1
  92. package/dist/serve/docs-ui/docs/secure/simulate-and-lint/index.html +1 -1
  93. package/dist/serve/docs-ui/docs/secure/write-a-rules-test-suite/index.html +1 -1
  94. package/dist/serve/docs-ui/docs/ship/ship-to-production/index.html +1 -1
  95. package/dist/serve/docs-ui/docs/ship/test-in-node/index.html +1 -1
  96. package/dist/serve/docs-ui/docs/storage-compat/index.html +1 -1
  97. package/dist/serve/docs-ui/docs/trust/how-we-know-it-matches-firebase/index.html +1 -1
  98. package/dist/serve/docs-ui/docs/trust/versioning-and-compatibility/index.html +1 -1
  99. package/dist/serve/docs-ui/llms.txt +1 -1
  100. package/dist/serve/worker/host/core.js +1 -1
  101. package/dist/serve/worker/host/core.js.map +1 -1
  102. package/dist/serve/worker/host/firestore-writes.d.ts.map +1 -1
  103. package/dist/serve/worker/host/firestore-writes.js +3 -2
  104. package/dist/serve/worker/host/firestore-writes.js.map +1 -1
  105. package/dist/serve/worker/index.d.ts +2 -1
  106. package/dist/serve/worker/index.d.ts.map +1 -1
  107. package/dist/serve/worker/index.js +2 -1
  108. package/dist/serve/worker/index.js.map +1 -1
  109. package/dist/serve/worker/protocol.js +2 -2
  110. package/dist/serve/worker/protocol.js.map +1 -1
  111. package/package.json +5 -4
  112. package/src/assurance/.generated/conformance-verdicts.ts +1090 -0
  113. package/src/assurance/attachment.ts +211 -0
  114. package/src/assurance/browser.ts +80 -0
  115. package/src/assurance/campaign.ts +496 -0
  116. package/src/assurance/capabilities.ts +446 -0
  117. package/src/assurance/cases.ts +43 -0
  118. package/src/assurance/index.ts +75 -0
  119. package/src/assurance/runner.ts +885 -0
  120. package/src/assurance/tool-names.ts +15 -0
  121. package/src/assurance/tools.ts +830 -0
  122. package/src/assurance/types.ts +352 -0
  123. package/src/assurance/validation.ts +434 -0
  124. package/src/bridge/client/bridge.ts +550 -0
  125. package/src/bridge/client/dispatch.ts +137 -0
  126. package/src/bridge/client.ts +45 -0
  127. package/src/bridge/protocol.ts +351 -0
  128. package/src/bridge/server/audit.ts +53 -0
  129. package/src/bridge/server/bridge.ts +597 -0
  130. package/src/bridge/server/headless.ts +160 -0
  131. package/src/bridge/server/json-schema-to-zod.ts +108 -0
  132. package/src/bridge/server/local-bridge.ts +66 -0
  133. package/src/bridge/server/logger.ts +50 -0
  134. package/src/bridge/server/mcp-contract.ts +93 -0
  135. package/src/bridge/server/mcp.ts +129 -0
  136. package/src/bridge/server/peer.ts +232 -0
  137. package/src/bridge/server/standalone.ts +347 -0
  138. package/src/bridge/server/tool-metadata.ts +99 -0
  139. package/src/bridge/server.ts +28 -0
  140. package/src/cli/can-i-use.ts +50 -0
  141. package/src/cli/cli.test.ts +493 -0
  142. package/src/cli/database-rules.ts +329 -0
  143. package/src/cli/dev-runner.ts +282 -0
  144. package/src/cli/firebase-json.ts +100 -0
  145. package/src/cli/firestore-indexes.ts +70 -0
  146. package/src/cli/index.ts +425 -0
  147. package/src/cli/init.ts +260 -0
  148. package/src/cli/mcp-proxy.ts +196 -0
  149. package/src/cli/parse-args.ts +80 -0
  150. package/src/cli/rules.ts +259 -0
  151. package/src/cli/scope.ts +67 -0
  152. package/src/cli/serve.ts +996 -0
  153. package/src/cli/service-commands.ts +73 -0
  154. package/src/cli/snapshot.ts +164 -0
  155. package/src/cli/storage-rules.ts +172 -0
  156. package/src/cli/verify.ts +416 -0
  157. package/src/conformance/.generated/can-i-use-browser.ts +113 -0
  158. package/src/conformance/.generated/can-i-use.ts +117 -0
  159. package/src/conformance/.generated/conformance-docs.ts +14 -0
  160. package/src/conformance/browser.ts +24 -0
  161. package/src/conformance/can-i-use-tool.ts +51 -0
  162. package/src/conformance/can-i-use.ts +18 -0
  163. package/src/conformance/docs.ts +8 -0
  164. package/src/conformance/index.ts +20 -0
  165. package/src/conformance/tools.ts +16 -0
  166. package/src/credentials/core/memoize-ttl.ts +142 -0
  167. package/src/credentials/core/types.ts +10 -0
  168. package/src/credentials/node/from-adc.ts +96 -0
  169. package/src/credentials/node/from-service-account.ts +133 -0
  170. package/src/credentials/node/index.ts +6 -0
  171. package/src/discover/concurrency.ts +127 -0
  172. package/src/discover/crawler-adapter.ts +142 -0
  173. package/src/discover/crawler.ts +1127 -0
  174. package/src/discover/credential-free.ts +27 -0
  175. package/src/discover/findCollectionGroup.ts +131 -0
  176. package/src/discover/firestore-source.ts +59 -0
  177. package/src/discover/index.ts +5 -0
  178. package/src/discover/merge.ts +523 -0
  179. package/src/discover/session.ts +402 -0
  180. package/src/discover/tools.ts +201 -0
  181. package/src/discover/types.ts +187 -0
  182. package/src/discover/wire.ts +324 -0
  183. package/src/functions-rtdb/child.ts +382 -0
  184. package/src/functions-rtdb/delivery.ts +7 -0
  185. package/src/functions-rtdb/discovery.ts +136 -0
  186. package/src/functions-rtdb/event.ts +64 -0
  187. package/src/functions-rtdb/execution.ts +111 -0
  188. package/src/functions-rtdb/in-memory-delivery.ts +40 -0
  189. package/src/functions-rtdb/project.ts +74 -0
  190. package/src/functions-rtdb/projection.ts +104 -0
  191. package/src/functions-rtdb/reference-pattern.ts +20 -0
  192. package/src/functions-rtdb/remote-delivery.ts +23 -0
  193. package/src/pkg-version.ts +49 -0
  194. package/src/register/esm-exports.ts +63 -0
  195. package/src/register/hooks.ts +30 -0
  196. package/src/register/index.ts +150 -0
  197. package/src/register/mapping.ts +33 -0
  198. package/src/remote/index.ts +1050 -0
  199. package/src/rtdb/crawl-snapshot.ts +118 -0
  200. package/src/rtdb/inspection.ts +137 -0
  201. package/src/rtdb/load-rules-document.ts +56 -0
  202. package/src/rtdb/rules-generation-tool.ts +38 -0
  203. package/src/rtdb/rules-json.ts +29 -0
  204. package/src/serve/activity-guard.ts +29 -0
  205. package/src/serve/activity-route.ts +164 -0
  206. package/src/serve/activity-warning.ts +26 -0
  207. package/src/serve/bridge-mount.ts +200 -0
  208. package/src/serve/bundler.ts +493 -0
  209. package/src/serve/capture-store.ts +65 -0
  210. package/src/serve/discovery.ts +199 -0
  211. package/src/serve/entries/ai.ts +292 -0
  212. package/src/serve/entries/app-backend.ts +4 -0
  213. package/src/serve/entries/app-client.ts +26 -0
  214. package/src/serve/entries/app-session-store.ts +47 -0
  215. package/src/serve/entries/app.ts +11 -0
  216. package/src/serve/entries/auth-helper-core.ts +181 -0
  217. package/src/serve/entries/auth-helper-dom.ts +134 -0
  218. package/src/serve/entries/auth-helper-runtime.ts +20 -0
  219. package/src/serve/entries/auth.ts +255 -0
  220. package/src/serve/entries/bridge-url.ts +31 -0
  221. package/src/serve/entries/database.ts +129 -0
  222. package/src/serve/entries/firestore.ts +232 -0
  223. package/src/serve/entries/init.ts +46 -0
  224. package/src/serve/entries/keepalive.ts +46 -0
  225. package/src/serve/entries/messaging-sw.ts +75 -0
  226. package/src/serve/entries/messaging.ts +96 -0
  227. package/src/serve/entries/runtime.ts +540 -0
  228. package/src/serve/entries/session-store.ts +97 -0
  229. package/src/serve/entries/storage.ts +92 -0
  230. package/src/serve/entries/tab-sync-wiring.ts +274 -0
  231. package/src/serve/entries/worker-runtime.ts +75 -0
  232. package/src/serve/init-payload.ts +42 -0
  233. package/src/serve/namespace.ts +675 -0
  234. package/src/serve/open-browser.ts +68 -0
  235. package/src/serve/rules.ts +272 -0
  236. package/src/serve/sandbox-marker.ts +31 -0
  237. package/src/serve/server.ts +428 -0
  238. package/src/serve/standalone-assets.ts +180 -0
  239. package/src/serve/state-store.ts +166 -0
  240. package/src/serve/studio/disk-project-store.ts +185 -0
  241. package/src/serve/studio/disk-workspace.ts +162 -0
  242. package/src/serve/studio/index.ts +20 -0
  243. package/src/serve/studio/routes.ts +237 -0
  244. package/src/serve/studio/store-types.ts +48 -0
  245. package/src/serve/studio/studio-storage.test.ts +289 -0
  246. package/src/serve/vite-plugin.ts +1102 -0
  247. package/src/serve/worker/activity-bootstrap.ts +24 -0
  248. package/src/serve/worker/client/admin-firestore.ts +38 -0
  249. package/src/serve/worker/client/ai.ts +124 -0
  250. package/src/serve/worker/client/auth.ts +489 -0
  251. package/src/serve/worker/client/connection.ts +202 -0
  252. package/src/serve/worker/client/core.ts +350 -0
  253. package/src/serve/worker/client/disconnect.ts +45 -0
  254. package/src/serve/worker/client/firestore-reads.ts +181 -0
  255. package/src/serve/worker/client/firestore-refs.ts +226 -0
  256. package/src/serve/worker/client/firestore-writes.ts +232 -0
  257. package/src/serve/worker/client/handles.ts +91 -0
  258. package/src/serve/worker/client/messaging.ts +119 -0
  259. package/src/serve/worker/client/presence.ts +174 -0
  260. package/src/serve/worker/client/rtdb.ts +311 -0
  261. package/src/serve/worker/client/rules.ts +63 -0
  262. package/src/serve/worker/client/service-worker-connection.ts +59 -0
  263. package/src/serve/worker/client/snapshots.ts +86 -0
  264. package/src/serve/worker/client/storage.ts +195 -0
  265. package/src/serve/worker/client/studio.ts +88 -0
  266. package/src/serve/worker/client.ts +57 -0
  267. package/src/serve/worker/durable-persistence.ts +137 -0
  268. package/src/serve/worker/entry.ts +179 -0
  269. package/src/serve/worker/host/admin-firestore.ts +88 -0
  270. package/src/serve/worker/host/connection.ts +179 -0
  271. package/src/serve/worker/host/core.ts +387 -0
  272. package/src/serve/worker/host/dispatch.ts +316 -0
  273. package/src/serve/worker/host/firestore-reads.ts +117 -0
  274. package/src/serve/worker/host/firestore-writes.ts +456 -0
  275. package/src/serve/worker/host/presence.ts +312 -0
  276. package/src/serve/worker/host/rtdb.ts +136 -0
  277. package/src/serve/worker/host/rules.ts +128 -0
  278. package/src/serve/worker/host/storage.ts +312 -0
  279. package/src/serve/worker/host/studio.ts +75 -0
  280. package/src/serve/worker/host/subscriptions.ts +238 -0
  281. package/src/serve/worker/host-ai.ts +165 -0
  282. package/src/serve/worker/host-auth.ts +469 -0
  283. package/src/serve/worker/host-context.ts +273 -0
  284. package/src/serve/worker/host-events.ts +94 -0
  285. package/src/serve/worker/host-messaging.ts +240 -0
  286. package/src/serve/worker/host.ts +47 -0
  287. package/src/serve/worker/index.ts +196 -0
  288. package/src/serve/worker/presence-timing.ts +15 -0
  289. package/src/serve/worker/protocol.ts +1112 -0
  290. package/src/serve/worker/serve-init.ts +606 -0
  291. package/src/serve/worker/service-worker-channel.ts +33 -0
  292. package/src/serve/worker/service-worker-relay.ts +86 -0
  293. package/src/serve/writer-lock.ts +53 -0
  294. package/src/verify/cases.ts +233 -0
  295. package/src/verify/fixture.ts +258 -0
  296. package/src/verify/index.ts +519 -0
  297. package/src/verify/tools.ts +108 -0
  298. package/src/version/compat-target.ts +17 -0
  299. package/src/vite.ts +17 -0
  300. package/dist/serve/docs-ui/docs/pyric-firestore-values-reference-api/index.html +0 -31
  301. package/dist/serve/docs-ui/docs/pyric-firestore-values-reference-api.md +0 -29
@@ -0,0 +1,1102 @@
1
+ /**
2
+ * `@pyric/cli/vite` — the firebase→pyric-sandbox swap as a Vite plugin.
3
+ *
4
+ * The serve analog for SOURCE-driven apps: instead of `vite build && pyric dev
5
+ * dist`, a team keeps `vite dev` (HMR, source maps) with the in-process sandbox
6
+ * standing in for Firebase. The app's `firebase/*` imports are UNCHANGED — the
7
+ * plugin swaps them at the module-resolution layer (`resolveId`), the same way
8
+ * `pyric dev` swaps via a runtime import map. (Design: `plans/pyric-vite-plugin.md`.)
9
+ *
10
+ * Two flavors, one `apply` function. Under `vite dev` the swap is ALWAYS on.
11
+ * For `vite build` the swap is MODE-gated: a plain `vite build` (mode
12
+ * `production`) ships the real `firebase` package — the swap never reaches the
13
+ * prod artifact — while `vite build --mode development` (any NON-production
14
+ * mode) produces a SANDBOX build that bundles pyric's in-page adapters instead
15
+ * of the real SDK: self-contained, meant to be previewed under `pyric dev`, and
16
+ * stamped with the sandbox-build marker so it can never be deployed (`pyric
17
+ * deploy hosting` refuses it). `pyric({ swapInBuild })` forces the build
18
+ * behavior on/off regardless of mode. See `sandbox-marker.ts`.
19
+ *
20
+ * This is a thin adapter over serve's proven machinery. It REUSES, not reimplements:
21
+ * - the node-builtin shims — `NODE_BUILTIN_SHIMS`;
22
+ * - the swap targets — `defaultSdkEntries()` (the `serve/entries/*` wrappers,
23
+ * compiled-dist preferred, src fallback);
24
+ * - the `/__pyric/*` namespace — `createPyricNamespace` mounted verbatim behind
25
+ * a connect-middleware adapter;
26
+ * - rules load + prepare — `loadProjectRules` / `prepareRulesSource`;
27
+ * - the SharedWorker host — `bundleWorker` served at `/__pyric/sdk/worker.js`;
28
+ * - durable stores — `createStateStore` (persist) / `createCaptureStore`.
29
+ *
30
+ * Scope = M1 (swap + rules) + M2 (SharedWorker multi-tab + persist/capture/seed)
31
+ * + M3 (the MCP bridge fold — `{ bridge }`). M3 reuses `createBridgeMount` (the
32
+ * proven serve-flavored bridge behind `pyric dev --bridge`), composing it into
33
+ * the same `/__pyric` middleware; on the worker path the bridge peer routes
34
+ * agent tool-calls THROUGH the SharedWorker (`connectBridgePeer`), so the agent
35
+ * and the app share one backend without forcing the page in-page.
36
+ *
37
+ * Serving `worker.js` flips `runtime.ts` to the worker path (one backend across
38
+ * tabs, IndexedDB-durable); on that path the WORKER owns persist/capture/seed via
39
+ * the same `/__pyric/*` routes. If the worker bundle fails, the plugin falls back
40
+ * to the in-page sandbox (single-tab, ephemeral).
41
+ */
42
+ import { readFile } from 'node:fs/promises';
43
+ import { existsSync, readFileSync, rmSync, writeFileSync, mkdirSync } from 'node:fs';
44
+ import { homedir } from 'node:os';
45
+ import path from 'node:path';
46
+ import type { IncomingMessage, ServerResponse, Server as HttpServer } from 'node:http';
47
+ import type { Plugin, UserConfig, ConfigEnv } from 'vite';
48
+ import type { Plugin as EsbuildPlugin } from 'esbuild';
49
+ import {
50
+ SDK_MODULES,
51
+ defaultSdkEntries,
52
+ resolveStudioUiDir,
53
+ pyricPackageRoot,
54
+ bundleWorker,
55
+ workerSourceHash,
56
+ NODE_BUILTIN_RE,
57
+ NODE_BUILTIN_SHIMS,
58
+ } from './bundler.js';
59
+ import {
60
+ createEventHub,
61
+ createPyricNamespace,
62
+ type InitPayload,
63
+ } from './namespace.js';
64
+ import { formatActivityWarning } from './activity-warning.js';
65
+ import type { AiEngineConfigWire } from './worker/protocol.js';
66
+ import type { AIOptions } from 'pyric/ai';
67
+ import { diskWorkspace, diskProjectStore } from './studio/index.js';
68
+ import { createBridgeMount } from './bridge-mount.js';
69
+ import {
70
+ loadProjectDatabaseRules,
71
+ loadProjectRules,
72
+ loadProjectStorageRules,
73
+ prepareRulesSource,
74
+ rulesHashOf,
75
+ } from './rules.js';
76
+ import { createStateStore, STATE_FILE_VERSION, type PyricStateFile } from './state-store.js';
77
+ import { createCaptureStore } from './capture-store.js';
78
+ import { isAllowedHost } from './server.js';
79
+ import { SANDBOX_BUILD_META } from './sandbox-marker.js';
80
+ import { readFirebaseJson, readFirebaseRc, type FirebaseJson } from '../cli/firebase-json.js';
81
+ import {
82
+ discoverFunctionsRtdbProject,
83
+ type FunctionsRtdbProject,
84
+ } from '../functions-rtdb/project.js';
85
+ import {
86
+ spawnFunctionsRtdbChild,
87
+ type FunctionsRtdbChildHandle,
88
+ } from '../functions-rtdb/child.js';
89
+ import {
90
+ buildChildEnv,
91
+ createLinePrefixer,
92
+ registerModuleUrl,
93
+ } from '../cli/dev-runner.js';
94
+
95
+ /**
96
+ * Whether a `vite build` should run the firebase→pyric swap (produce a SANDBOX
97
+ * build). MODE-based with a plugin-config override:
98
+ * - `options.swapInBuild` wins outright when set (force on/off);
99
+ * - otherwise swap for any NON-production mode. A plain `vite build` (mode
100
+ * `production`) ships real firebase; `vite build --mode development` (or any
101
+ * custom non-prod mode) is a sandbox build.
102
+ * `vite dev` is handled separately in `apply` (always on).
103
+ */
104
+ function swapsInBuild(env: ConfigEnv, swapInBuild: boolean | undefined): boolean {
105
+ if (swapInBuild !== undefined) return swapInBuild;
106
+ return env.mode !== 'production';
107
+ }
108
+
109
+ /** Any `firebase/<sub>` specifier. */
110
+ const FB_ANY = /^firebase\/([a-z-]+(?:\/[a-z-]+)*)$/;
111
+
112
+ /** The serve proxy route the browser openai engine defaults to (#98.2). */
113
+ const AI_PROXY_PATH = '/__pyric/ai-proxy';
114
+
115
+ /**
116
+ * The plugin-level engine config surface = `pyric/ai`'s `EngineConfig` (what an
117
+ * app passes to `getAI`), minus the custom `AnswerEngine` object variant — a
118
+ * live object cannot cross to the SharedWorker host or serialize into the page,
119
+ * so the plugin's declarative surface is the JSON-able `scripted` / `openai`
120
+ * configs only (the same restriction the worker path already enforces).
121
+ */
122
+ export type PyricAiEngineConfig = Extract<NonNullable<AIOptions['engine']>, { kind: string }>;
123
+
124
+ /**
125
+ * Node-side `EngineConfig` → JSON-safe {@link AiEngineConfigWire}. Mirrors the
126
+ * browser `toEngineWire` (entries/ai.ts): an openai config with no `baseUrl`
127
+ * targets the same-origin proxy; scripted `script` entries pass through (plain
128
+ * authoring shapes — function/RegExp matchers can't survive JSON and are not a
129
+ * plugin-config use case).
130
+ */
131
+ export function engineConfigToWire(engine: PyricAiEngineConfig): AiEngineConfigWire {
132
+ if (engine.kind === 'openai') {
133
+ return {
134
+ kind: 'openai',
135
+ baseUrl: engine.baseUrl ?? AI_PROXY_PATH,
136
+ ...(engine.model !== undefined ? { model: engine.model } : {}),
137
+ ...(engine.modelMap !== undefined ? { modelMap: engine.modelMap } : {}),
138
+ };
139
+ }
140
+ return {
141
+ kind: 'scripted',
142
+ ...(engine.script !== undefined
143
+ ? { script: engine.script as unknown as Array<Record<string, unknown>> }
144
+ : {}),
145
+ };
146
+ }
147
+ /** The firebase subpaths with swap entries. */
148
+ const SERVED = new Set(SDK_MODULES.map((specifier) => specifier.slice('firebase/'.length)));
149
+ const entryKey = (subpath: string): string => subpath.replaceAll('/', '-');
150
+ const NODE_SHIM_PREFIX = '\0pyric:node-shim:';
151
+
152
+ /** Walk up from a file to the nearest directory containing a package.json. */
153
+ function packageRootOf(file: string): string {
154
+ let dir = path.dirname(file);
155
+ while (dir !== path.dirname(dir) && !existsSync(path.join(dir, 'package.json'))) {
156
+ dir = path.dirname(dir);
157
+ }
158
+ return dir;
159
+ }
160
+
161
+ export interface PyricOptions {
162
+ /** firestore.rules path (relative to `root`). Default: `firebase.json`'s
163
+ * `firestore.rules`, else `firestore.rules` in the project root. */
164
+ rules?: string;
165
+ /** Project dir for `firebase.json` / rules discovery. Default: Vite's `root`. */
166
+ root?: string;
167
+ /** Persist sandbox state to `.pyric/state/state.json` so data + test users
168
+ * survive reloads/restarts. Off by default (ephemeral). */
169
+ persist?: boolean;
170
+ /** With `persist`: discard any existing state file and re-seed from scratch. */
171
+ fresh?: boolean;
172
+ /** Write the live session fixture to `.pyric/last-session.json` (for
173
+ * `pyric verify`). Default `true`; pass `false` to suppress. */
174
+ capture?: boolean;
175
+ /** Seed file: a `"collection/doc" → fields` JSON map, or a `pyric snapshot`
176
+ * state-file envelope. Applied at page init (state wins once it exists). */
177
+ seed?: string;
178
+ /** Mount the MCP **bridge** on Vite's dev origin so an external agent
179
+ * (Claude Code, Cursor) can drive this sandbox over MCP — `POST /__pyric/mcp`
180
+ * + `GET /__pyric/health` + `WS /__pyric/sandbox`, all on Vite's port.
181
+ * `true` is shorthand for `{}`. The agent and the page share ONE sandbox.
182
+ *
183
+ * Does NOT change the sandbox topology: on the default SharedWorker path the
184
+ * page dials the bridge WS and relays agent tool-calls THROUGH the worker
185
+ * (`connectBridgePeer`), so multi-tab stays on. The in-page fallback engages
186
+ * only when the worker bundle itself fails, bridge or not. */
187
+ bridge?: boolean | { project?: string; disableAuditLog?: boolean };
188
+ /** Serve the **Pyric Studio** app at `/__pyric/ui/` on Vite's dev origin (the
189
+ * `pyric dev --ui` equivalent). Mounts the disk-backed workspace/project
190
+ * routes Studio's `local` mode talks to AND serves the built Studio assets
191
+ * (vendored in this package at `dist/serve/studio-ui`). **On by default**,
192
+ * including under `bridge` (the bridge peer routes through the SharedWorker,
193
+ * so app, Studio, and agent all observe the one sandbox); pass `ui: false`
194
+ * to disable. */
195
+ ui?: boolean;
196
+ /** RTDB-triggered Cloud Functions under this dev server (the `pyric dev`
197
+ * parity fold). By default a `functions` block in `firebase.json` is
198
+ * discovered automatically: its `onValueCreated` triggers run in an isolated
199
+ * node child against the shared sandbox (other trigger kinds warn and are
200
+ * skipped), and the discovered codebase turns the MCP bridge mount on (the
201
+ * child dials the sandbox over the bridge WS — the page's sandbox topology
202
+ * is unchanged, see `bridge`). `functions: false` is the off switch: no
203
+ * discovery, no child, no functions-forced bridge mount.
204
+ *
205
+ * Field precedence: explicit option > env var > firebase files > default.
206
+ * - `region`: the trigger location. Beats `PYRIC_FUNCTIONS_RTDB_REGION`;
207
+ * default `us-central1`.
208
+ * - `instance`: the RTDB instance name. Default `<projectId>-default-rtdb`,
209
+ * where projectId is `PYRIC_PROJECT`, else `.firebaserc`'s default
210
+ * project, else `demo-project`.
211
+ * - `watch`: hot-reload the functions source (default `true`, matching
212
+ * rules). A save under the functions source dir stops the child and
213
+ * respawns it — redeploy semantics: in-flight executions in the old child
214
+ * may drop, and writes landing during the swap gap are consumed as the new
215
+ * child's baseline (they do not fire). Unlike rules, a broken save cannot
216
+ * keep last-good live — the old child is already gone — so functions stay
217
+ * down until the next good save. */
218
+ functions?: false | { region?: string; instance?: string; watch?: boolean };
219
+ /** Force whether `vite build` runs the firebase→pyric swap, overriding the
220
+ * mode default. Unset (default): swap for any NON-production mode, keep real
221
+ * firebase for mode `production`. `true` = always produce a sandbox build;
222
+ * `false` = never swap in build (real firebase regardless of mode). `vite
223
+ * dev` is unaffected — the swap is always on there. */
224
+ swapInBuild?: boolean;
225
+ /**
226
+ * Dev-server-level AI configuration for `pyric/ai` (the sanctioned
227
+ * replacement for threading `engine` through every app `getAI(...)` call,
228
+ * which is first-call-wins and easy to get wrong).
229
+ *
230
+ * pyric({
231
+ * ai: {
232
+ * engine: { kind: 'openai', model: 'llama3.2', baseUrl: '/__pyric/ai-proxy' },
233
+ * proxyUpstream: 'http://localhost:11434/v1', // your Ollama
234
+ * },
235
+ * })
236
+ *
237
+ * - `engine` is `pyric/ai`'s `EngineConfig` (scripted | openai), applied on
238
+ * both the SharedWorker and in-page paths. An openai `baseUrl` of
239
+ * `/__pyric/ai-proxy` (or omitted) routes through the same-origin proxy so a
240
+ * localhost upstream needs zero CORS setup.
241
+ * - `proxyUpstream` sets what `/__pyric/ai-proxy` forwards to (beats the
242
+ * `PYRIC_AI_PROXY_UPSTREAM` env var; default `http://localhost:11434/v1`).
243
+ *
244
+ * Precedence: a plugin-level `engine`, when set, always wins over an engine an
245
+ * app's own `getAI()` passes (host-side via `ctx.aiEngine` on the worker path,
246
+ * page-side via an injected global on the in-page fallback); with no plugin
247
+ * engine the first `getAI()` call's engine is honored (first-call-wins), and
248
+ * with neither the zero-config scripted default applies.
249
+ */
250
+ ai?: {
251
+ /** Engine config (scripted | openai). Custom `AnswerEngine` objects are not
252
+ * supported at the plugin level — they can't cross to the worker/page. */
253
+ engine?: PyricAiEngineConfig;
254
+ /** OpenAI-compatible upstream `/__pyric/ai-proxy` forwards to. Beats
255
+ * `PYRIC_AI_PROXY_UPSTREAM`; default `http://localhost:11434/v1`. */
256
+ proxyUpstream?: string;
257
+ };
258
+ }
259
+
260
+ /**
261
+ * The dev-only Vite plugin. Add to `vite.config`:
262
+ *
263
+ * import { pyric } from '@pyric/cli/vite';
264
+ * export default defineConfig({ plugins: [pyric()] });
265
+ */
266
+ export function pyric(options: PyricOptions = {}): Plugin {
267
+ // Resolved once. `defaultSdkEntries()` prefers compiled dist `.js` and falls
268
+ // back to source `.ts` in the workspace.
269
+ const entries = defaultSdkEntries(); // { app, auth, firestore, init } → abs paths
270
+ const pyricRoot = pyricPackageRoot();
271
+ // The @pyric/cli package root — covers the served entries AND their siblings
272
+ // (`worker/client.js`, the bridge client) that the entries statically import.
273
+ const cliRoot = packageRootOf(entries.init);
274
+
275
+ // section 8 refinement: a firebase import is "pyric-internal" iff its importer lives
276
+ // under the resolved pyric package root — keyed on the root, not a `/pyric/`
277
+ // substring (which a user project path could false-positive).
278
+ const isPyricImporter = (importer: string | undefined): boolean => {
279
+ if (!importer) return false;
280
+ const f = importer.split('?')[0];
281
+ return f === pyricRoot || f.startsWith(pyricRoot + path.sep);
282
+ };
283
+ // Node builtins are reached only from OUR code (pyric internals + the served
284
+ // entries) — shim those, but NEVER hijack a user app or third-party library's
285
+ // own `fs`/`path`/`url` (which Vite, or the user's polyfill plugin, should
286
+ // resolve). The firebase branch stays scoped to pyric; this is the wider "ours".
287
+ const isOurCode = (importer: string | undefined): boolean => {
288
+ if (!importer) return false;
289
+ if (isPyricImporter(importer)) return true;
290
+ const f = importer.split('?')[0];
291
+ return f === cliRoot || f.startsWith(cliRoot + path.sep);
292
+ };
293
+ const shimFor = (spec: string): string => NODE_BUILTIN_SHIMS[spec.replace(/^node:/, '')]!;
294
+
295
+ // The esbuild mirror for Vite's dep optimizer — REQUIRED so a node_modules
296
+ // library's `firebase/*` swaps too (the optimizer's esbuild pass bypasses the
297
+ // Rollup-pipeline resolveId below and would otherwise pre-bake real firebase).
298
+ const esbuildMirror: EsbuildPlugin = {
299
+ name: 'pyric-sandbox-optimizer',
300
+ setup(build) {
301
+ build.onResolve({ filter: FB_ANY }, (args) => {
302
+ const sub = FB_ANY.exec(args.path)![1]!;
303
+ if (SERVED.has(sub)) return { path: entries[entryKey(sub)]! };
304
+ return null; // non-served firebase from a lib → real firebase
305
+ });
306
+ build.onResolve({ filter: NODE_BUILTIN_RE }, (args) => {
307
+ if (!isOurCode(args.importer)) return null; // user/lib node builtins → Vite/their polyfill
308
+ return { path: args.path.replace(/^node:/, ''), namespace: 'pyric-node-shim' };
309
+ });
310
+ build.onLoad({ filter: /.*/, namespace: 'pyric-node-shim' }, (args) => ({
311
+ contents: NODE_BUILTIN_SHIMS[args.path]!,
312
+ loader: 'js',
313
+ }));
314
+ },
315
+ };
316
+
317
+ // Live rules box — the watcher swaps it; the init payload always serves the
318
+ // current version.
319
+ const live: {
320
+ rules: string | null;
321
+ rulesHash: string | null;
322
+ databaseRules: { rules: Record<string, unknown> } | null;
323
+ databaseRulesHash: string | null;
324
+ databaseUrl: string | null;
325
+ storageRules: string | null;
326
+ storageRulesHash: string | null;
327
+ } = {
328
+ rules: null,
329
+ rulesHash: null,
330
+ databaseRules: null,
331
+ databaseRulesHash: null,
332
+ databaseUrl: null,
333
+ storageRules: null,
334
+ storageRulesHash: null,
335
+ };
336
+
337
+ // M2: the SharedWorker bundle's content hash (sync) — stamped into the page so
338
+ // a still-running OLD worker is detected as stale. `workerReady` flips true once
339
+ // `bundleWorker` succeeds in configureServer; until then (or on bundle failure)
340
+ // the page is forced onto the in-page sandbox path. transformIndexHtml reads it.
341
+ const workerVersion = workerSourceHash();
342
+ let workerReady = false;
343
+
344
+ // Set by the `config` hook. When the plugin runs under `vite build` at all it
345
+ // is a SANDBOX build (the `apply` gate below only lets build through under the
346
+ // sandbox trigger), so `command === 'build'` is sufficient to know we are
347
+ // producing marker-stamped, non-production output.
348
+ let sandboxBuild = false;
349
+ // Sandbox build: the serve init entry (runtime bootstrap + the ServeAuthHelper
350
+ // popup picker) is emitted as its OWN chunk and script-tagged into index.html.
351
+ // Rollup dedupes the shared runtime module between this chunk and the app
352
+ // chunk (both import the same absolute file), so the page runs exactly ONE
353
+ // sandbox runtime — unlike serve-time injection of /__pyric/sdk/init.js,
354
+ // which is a separately-bundled second runtime copy (the double-init bug:
355
+ // two banners, two bridge registrations). `pyric dev` sees the marker and
356
+ // skips its injection for these pages (see injectServeTags).
357
+ let initChunkRef: string | undefined;
358
+ let initChunkFile: string | undefined;
359
+
360
+ // M3 bridge fold: normalize `bridge` once (true ⇒ `{}`, falsy ⇒ null). When
361
+ // on, the MCP mount is composed into the /__pyric middleware (createBridgeMount,
362
+ // shared with `pyric dev --bridge`) AND the page is forced onto the in-page
363
+ // sandbox path — the bridge peer is the in-page sandbox, never the SharedWorker,
364
+ // so multi-tab is disabled under bridge to keep agent + app on one backend.
365
+ const bridgeOpts = options.bridge === true ? {} : options.bridge || null;
366
+
367
+ // Plugin-level AI engine, normalized once to the JSON-safe wire shape. Travels
368
+ // to the worker host via the init payload (→ ctx.aiEngine) AND to the in-page
369
+ // fallback via an injected synchronous global (see transformIndexHtml). Undefined
370
+ // when the `ai.engine` option is unset.
371
+ const aiEngineWire = options.ai?.engine ? engineConfigToWire(options.ai.engine) : undefined;
372
+
373
+ return {
374
+ name: 'pyric:sandbox',
375
+ // Active for `vite dev` ALWAYS, and for `vite build` only when it is a
376
+ // SANDBOX build (any non-`production` mode, or `swapInBuild: true`). A plain
377
+ // `vite build` keeps the real firebase package — the swap never reaches
378
+ // production output. A sandbox build applies the same swap so the output
379
+ // bundles pyric's in-page adapters (self-contained; preview it under
380
+ // `pyric dev`, never deploy it).
381
+ apply(_config, env) {
382
+ if (env.command === 'serve') return true;
383
+ return swapsInBuild(env, options.swapInBuild);
384
+ },
385
+ enforce: 'pre',
386
+
387
+ config(_config, env) {
388
+ sandboxBuild = env.command === 'build';
389
+ // Cast: the `esbuild` package's `Plugin` type skews slightly from Vite's
390
+ // bundled esbuild types (benign — the Plugin shape is stable across the
391
+ // versions in range).
392
+ return {
393
+ optimizeDeps: {
394
+ // Keep firebase out of the optimizer's pre-bake; the resolver swaps it
395
+ // per-importer at request time.
396
+ exclude: [...SDK_MODULES],
397
+ // The excluded SDK is served as ESM straight from dist, so Vite never
398
+ // scans it for dependencies. js-md5 / js-sha256 are CJS-only (no ESM
399
+ // named exports); without a forced pre-bundle the browser gets the raw
400
+ // UMD source and `import { md5 }` throws a SyntaxError. Force-including
401
+ // them gives the dist imports the interop-wrapped optimized copies.
402
+ include: ['js-md5', 'js-sha256'],
403
+ esbuildOptions: { plugins: [esbuildMirror] },
404
+ },
405
+ // Sandbox build only: the swapped-in runtime chunk uses TOP-LEVEL AWAIT
406
+ // (it deploys rules before app code runs — load-bearing, see
407
+ // entries/runtime.ts). Vite's default build target predates TLA and the
408
+ // esbuild transpile would fail. A sandbox build is a throwaway preview
409
+ // served under `pyric dev` (modern browser), so pin an ESNext target
410
+ // that keeps TLA. A plain production `vite build` never runs this plugin,
411
+ // so the user's own target is untouched there.
412
+ ...(sandboxBuild ? { build: { target: 'esnext' } } : {}),
413
+ } as unknown as UserConfig;
414
+ },
415
+
416
+ configResolved(resolved) {
417
+ // AUGMENT (don't replace) the fs allow-list: pyric dist + the @pyric/cli
418
+ // tree live outside the app root, but setting `server.fs.allow` in config()
419
+ // would clobber Vite's auto-added root/workspace entries and 403 the app's
420
+ // own source. Push the two PACKAGE ROOTS — @pyric/cli' root (not just the
421
+ // entries dir) is needed because the served init entry statically imports
422
+ // siblings (`worker/client.js`, the bridge client) outside entries/.
423
+ const allow = resolved.server?.fs?.allow;
424
+ if (allow) {
425
+ for (const dir of [pyricRoot, cliRoot]) {
426
+ if (!allow.includes(dir)) allow.push(dir);
427
+ }
428
+ }
429
+ },
430
+
431
+ resolveId(source, importer) {
432
+ const fb = FB_ANY.exec(source);
433
+ if (fb) {
434
+ const sub = fb[1]!;
435
+ if (SERVED.has(sub)) return entries[entryKey(sub)]!; // swap served set for user/lib
436
+ return null; // non-served firebase from user → real firebase
437
+ }
438
+ const node = NODE_BUILTIN_RE.exec(source);
439
+ // Shim node builtins ONLY when reached from our own code — never hijack a
440
+ // user app or library's own fs/path/url (Vite/their polyfill handles those).
441
+ if (node && isOurCode(importer)) return NODE_SHIM_PREFIX + node[2]!;
442
+ return null;
443
+ },
444
+
445
+ load(id) {
446
+ if (id.startsWith(NODE_SHIM_PREFIX)) return shimFor(id.slice(NODE_SHIM_PREFIX.length));
447
+ return null;
448
+ },
449
+
450
+ async configureServer(server) {
451
+ const cwd = options.root ?? server.config.root;
452
+
453
+ // Reproduce serve's rules prelude: firebase.json (optional) → loadProjectRules.
454
+ let fbJson: FirebaseJson | null = null;
455
+ try {
456
+ fbJson = await readFirebaseJson(cwd);
457
+ } catch {
458
+ /* optional — serve without a firebase.json */
459
+ }
460
+ // Honor an explicit `rules` option by overriding the resolved config.
461
+ const config: FirebaseJson | null = options.rules
462
+ ? { ...(fbJson ?? {}), firestore: { ...(fbJson?.firestore ?? {}), rules: options.rules } }
463
+ : fbJson;
464
+ const loaded = await loadProjectRules(cwd, config);
465
+ const loadedDatabase = await loadProjectDatabaseRules(cwd, config);
466
+ const loadedStorage = await loadProjectStorageRules(cwd, config);
467
+ live.rules = loaded.rules;
468
+ live.rulesHash = loaded.rulesHash;
469
+ live.databaseRules = loadedDatabase.rules;
470
+ live.databaseRulesHash = loadedDatabase.rulesHash;
471
+ live.databaseUrl = loadedDatabase.databaseUrl;
472
+ live.storageRules = loadedStorage.rules;
473
+ live.storageRulesHash = loadedStorage.rulesHash;
474
+
475
+ // ── M2 durable stores (mirrors serve's startServe orchestration) ──────
476
+ // Capture (default-on): the worker/page pushes its session fixture to
477
+ // /__pyric/capture; the store writes .pyric/last-session.json for `pyric verify`.
478
+ const capture = (options.capture ?? true) ? createCaptureStore(cwd) : undefined;
479
+ // Persist: createStateStore IS the durable sandbox. Load eagerly so a
480
+ // corrupt/mismatched file fails the start (not silently ephemeral).
481
+ const state = options.persist ? createStateStore(cwd) : undefined;
482
+ if (state && options.fresh) {
483
+ for (const p of [state.path, state.backupPath]) if (existsSync(p)) rmSync(p);
484
+ server.config.logger.info(' ⓘ [pyric] fresh: discarded the existing state file; re-seeding');
485
+ }
486
+ // Eager load (mirrors serve.ts:158) — parse the file NOW so a corrupt or
487
+ // version-mismatched state file throws StateFileError and FAILS THE START
488
+ // with the actionable inspect-or-delete message. Without this the first
489
+ // parse is deferred into initPayload() at request time, where it throws
490
+ // synchronously AFTER namespace.ts has committed `writeHead(200)`: the
491
+ // client gets a 200 with an empty body, the page/worker swallow the JSON
492
+ // error, and the sandbox silently runs WITHOUT the persisted data + rules.
493
+ // (No-op on first run: load() returns null for a missing file.)
494
+ // configureServer is async, so an uncaught throw aborts the dev start.
495
+ if (state) state.load();
496
+
497
+ // Seed: a "collection/doc" → fields map, OR a `pyric snapshot` state-file
498
+ // envelope (detected by its `version` key). Ported from serve.ts.
499
+ let seed: Record<string, Record<string, unknown>> | null = null;
500
+ let seedState: unknown | null = null;
501
+ let seedUsers: Record<string, unknown>[] | null = null;
502
+ if (options.seed) {
503
+ const seedPath = path.resolve(cwd, options.seed);
504
+ let parsed: unknown;
505
+ try {
506
+ parsed = JSON.parse(readFileSync(seedPath, 'utf8'));
507
+ } catch (e) {
508
+ throw new Error(`@pyric/cli/vite: failed to read seed ${seedPath}: ${e instanceof Error ? e.message : String(e)}`);
509
+ }
510
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
511
+ throw new Error('@pyric/cli/vite: seed must be a JSON object of "collection/doc" → fields');
512
+ }
513
+ const obj = parsed as Record<string, unknown>;
514
+ if (obj.version === STATE_FILE_VERSION && ('firestore' in obj || 'auth' in obj)) {
515
+ const fixture = obj as unknown as PyricStateFile;
516
+ if (state && !state.exists()) {
517
+ // persist first run from a fixture: prime the store, then the normal
518
+ // persist path restores it like any lived state.
519
+ if (fixture.firestore != null) state.writeSection('firestore', fixture.firestore);
520
+ if (fixture.auth != null) state.writeSection('auth', fixture.auth);
521
+ } else if (!state) {
522
+ seedState = fixture.firestore ?? null;
523
+ seedUsers = (fixture.auth?.users as Record<string, unknown>[] | undefined) ?? null;
524
+ }
525
+ // persist + existing state: lived state wins; the fixture is inert.
526
+ } else {
527
+ seed = parsed as Record<string, Record<string, unknown>>;
528
+ }
529
+ }
530
+
531
+ // ── M2 SharedWorker host: bundle it (cached per version) and serve it at
532
+ // /__pyric/sdk/worker.js. This is what flips runtime.ts to the worker path.
533
+ // On bundle failure, fall back to the in-page sandbox (workerReady stays
534
+ // false → transformIndexHtml forces in-page).
535
+ const sdkDir = path.join(homedir(), '.pyric', 'vite-worker', workerVersion);
536
+ try {
537
+ await bundleWorker({ outDir: sdkDir });
538
+ workerReady = true;
539
+ } catch (e) {
540
+ server.config.logger.warn(
541
+ ` ⚠ [pyric] SharedWorker bundle failed — using the in-page sandbox (single-tab, ephemeral): ${e instanceof Error ? e.message : String(e)}`,
542
+ );
543
+ }
544
+
545
+ // ── Functions (RTDB triggers) — the `pyric dev` parity fold ───────────
546
+ // Discover the one supported Functions codebase from the same resolved
547
+ // firebase.json the rules used (project.ts reads it itself). Reuses the
548
+ // exact serve module, so absent `functions` → null (silently off) and a
549
+ // malformed config throws serve's own error text — which, thrown from an
550
+ // async configureServer, fails the dev start the same way serve's
551
+ // `return 2` aborts. The Functions child connects to the sandbox over the
552
+ // bridge WS, so a discovered codebase forces the bridge mount on (mirrors
553
+ // serve's `bridgeEnabledFor(..., functionsProject)`). `functions: false`
554
+ // is the off switch: discovery never runs, so neither does the mount.
555
+ const functionsOpts = typeof options.functions === 'object' ? options.functions : {};
556
+ let functionsProject: FunctionsRtdbProject | null = null;
557
+ if (options.functions !== false) {
558
+ try {
559
+ functionsProject = discoverFunctionsRtdbProject(cwd);
560
+ } catch (error) {
561
+ // Malformed functions config: fail the start with serve's exact message.
562
+ throw error instanceof Error ? error : new Error(String(error));
563
+ }
564
+ }
565
+ const functionsProjectId = functionsProject
566
+ ? (process.env.PYRIC_PROJECT ?? (await readFirebaseRc(cwd))?.projects?.default ?? 'demo-project')
567
+ : null;
568
+
569
+ // ── M3 MCP bridge (mirrors serve.ts:221–274) ─────────────────────────
570
+ // The mount is long-lived (one bridge per dev session); its MCP transport
571
+ // is rebuilt per request (stateless). Composed into the /__pyric middleware
572
+ // below (handler tier) + the server's WS upgrade. middlewareMode has no
573
+ // httpServer → HTTP routes still work, no WS peer.
574
+ // Guard the WS upgrade with the SAME allow rule Vite's own host check
575
+ // uses (host + allowedHosts, where `true` = opted into all hosts). Vite's
576
+ // upgrade path bypasses connect middleware, so this is the only guard on it.
577
+ const mount = bridgeOpts || functionsProject
578
+ ? createBridgeMount({
579
+ ...(bridgeOpts ?? {}),
580
+ // A functions-only session still needs a labeled bridge; prefer an
581
+ // explicit bridge project, else the resolved functions project id.
582
+ project: bridgeOpts?.project ?? functionsProjectId ?? undefined,
583
+ upgradeGuard: {
584
+ boundHost: typeof server.config.server.host === 'string' ? server.config.server.host : 'localhost',
585
+ allowedHosts:
586
+ server.config.server.allowedHosts === true
587
+ ? true
588
+ : Array.isArray(server.config.server.allowedHosts)
589
+ ? server.config.server.allowedHosts
590
+ : [],
591
+ },
592
+ })
593
+ : null;
594
+
595
+ // The /__pyric/* namespace, reused VERBATIM (now with the sdk dir + state +
596
+ // capture routes live).
597
+ const events = createEventHub();
598
+ const initPayload = (): InitPayload => ({
599
+ rules: live.rules,
600
+ rulesHash: live.rulesHash,
601
+ databaseRules: live.databaseRules,
602
+ databaseRulesHash: live.databaseRulesHash,
603
+ databaseUrl: live.databaseUrl,
604
+ storageRules: live.storageRules,
605
+ storageRulesHash: live.storageRulesHash,
606
+ // Project identity: scopes the storage IDB name per served project
607
+ // (issue #359). Local-only — a dev path never leaves the machine.
608
+ projectKey: cwd,
609
+ // The bound port is known only after `listen`; initPayload runs per
610
+ // request (after listen), so resolve it lazily here. Absolute ws://host:port
611
+ // mirrors serve (the browser reads this as the bridge peer URL).
612
+ bridgeUrl: (() => {
613
+ if (!mount) return null;
614
+ const addr = server.httpServer?.address();
615
+ const port = addr && typeof addr === 'object' ? addr.port : 0;
616
+ const host = (typeof server.config.server.host === 'string' && server.config.server.host) || 'localhost';
617
+ return port > 0 ? mount.wsUrl({ host, port }) : null;
618
+ })(),
619
+ // Precedence: once a state file exists, lived state is the truth — seed
620
+ // applies only on the first (state-less) run.
621
+ seed: state?.exists() ? null : seed,
622
+ seedState,
623
+ persist: Boolean(state),
624
+ capture: Boolean(capture),
625
+ authUsers: state
626
+ ? ((state.readSection('auth') as { users?: Record<string, unknown>[] } | null)?.users ?? null)
627
+ : seedUsers,
628
+ // Messaging is part of the canonical firebase/* sandbox swap.
629
+ messaging: true,
630
+ // Plugin-level engine → the worker host's ctx.aiEngine (host-ai.ts),
631
+ // which wins over any op-carried engine. Null when unset.
632
+ ai: aiEngineWire ? { engine: aiEngineWire } : null,
633
+ });
634
+ // Pyric Studio: mount the disk-backed workspace/project routes that
635
+ // Studio's `local` mode talks to + serve the built Studio app at
636
+ // /__pyric/ui/. Mirrors `pyric dev --ui`; the studio-ui assets are
637
+ // vendored in this package's dist (resolveStudioUiDir).
638
+ //
639
+ // ON BY DEFAULT, including under `bridge`: the bridge now routes agent
640
+ // tool-calls THROUGH the SharedWorker (see `connectBridgePeer`), so the
641
+ // app, Studio, and agent all observe the ONE sandbox. Explicit `ui: false`
642
+ // still wins.
643
+ const uiEnabled = options.ui ?? true;
644
+ const studio = uiEnabled
645
+ ? {
646
+ workspace: diskWorkspace(cwd),
647
+ projects: diskProjectStore(path.join(cwd, '.pyric', 'projects')),
648
+ }
649
+ : undefined;
650
+ let studioUiDir: string | undefined;
651
+ if (uiEnabled) {
652
+ studioUiDir = resolveStudioUiDir() ?? undefined;
653
+ if (!studioUiDir) {
654
+ server.config.logger.warn(
655
+ '[pyric] ui: built Studio app not found; /__pyric/ui/ will 404 ' +
656
+ '(run the full build, or reinstall @pyric/cli).',
657
+ );
658
+ }
659
+ }
660
+ const namespace = createPyricNamespace({
661
+ sdkDir,
662
+ initPayload,
663
+ events,
664
+ activity: (incident) => server.config.logger.warn(formatActivityWarning(incident)),
665
+ state,
666
+ capture,
667
+ studio,
668
+ studioUiDir,
669
+ // `ai.proxyUpstream`: what `/__pyric/ai-proxy` forwards to (beats the
670
+ // PYRIC_AI_PROXY_UPSTREAM env var; falls back to the default when unset).
671
+ aiProxyUpstream: options.ai?.proxyUpstream,
672
+ // Adapt Vite's logger to the plain info/note shape the namespace's
673
+ // diagnostics (denial relay, future hot-reload lines) expect —
674
+ // matches the `↻`/`⚠ [pyric]` lines already logged elsewhere in this
675
+ // plugin via `server.config.logger` directly.
676
+ logger: {
677
+ info: (m) => server.config.logger.info(m),
678
+ note: (m) => server.config.logger.warn(m),
679
+ },
680
+ });
681
+
682
+ // DNS-rebinding guard for the /__pyric/* surface. Vite has its own host
683
+ // check, but a `configureServer` hook that doesn't return a function mounts
684
+ // BEFORE it (and the ordering differs across Vite 5/6/7), so guard here too
685
+ // — independent of Vite's internals. Reuses serve's `isAllowedHost`.
686
+ const srvOpts = server.config.server;
687
+ const hostAllowed = (req: IncomingMessage): boolean => {
688
+ if (srvOpts.allowedHosts === true) return true; // user opted into all hosts
689
+ const boundHost = typeof srvOpts.host === 'string' ? srvOpts.host : 'localhost';
690
+ const extra = Array.isArray(srvOpts.allowedHosts) ? srvOpts.allowedHosts : [];
691
+ return isAllowedHost(req.headers.host, boundHost, extra);
692
+ };
693
+
694
+ // Connect-middleware adapter (build `url` from originalUrl; next() when the
695
+ // namespace closure returns false; never rewrite route bodies).
696
+ server.middlewares.use('/__pyric', (req: IncomingMessage & { originalUrl?: string }, res: ServerResponse, next: () => void) => {
697
+ if (!hostAllowed(req)) {
698
+ res.statusCode = 403;
699
+ res.end(`pyric: refused request for Host '${req.headers.host ?? ''}' (DNS-rebinding guard).`);
700
+ return;
701
+ }
702
+ const url = new URL(req.originalUrl ?? req.url ?? '/', `http://${req.headers.host ?? 'localhost'}`);
703
+ // Bridge first (mirrors serve.ts): /__pyric/mcp + /__pyric/health must be
704
+ // handled by the mount, not 404 through the namespace. Falls through to the
705
+ // namespace when the mount returns false (every non-bridge route).
706
+ Promise.resolve(mount ? mount.handler(req, res, url) : false)
707
+ .then((bridged) => (bridged ? true : Promise.resolve(namespace(req, res, url))))
708
+ .then((handled) => {
709
+ if (!handled) next();
710
+ })
711
+ .catch((err: unknown) => {
712
+ if (!res.headersSent) res.statusCode = 500;
713
+ res.end(err instanceof Error ? err.message : String(err));
714
+ });
715
+ });
716
+
717
+ // WS upgrade for the in-page sandbox peer (ws://…/__pyric/sandbox). The
718
+ // listener only fires once upgrades arrive (after listen), so adding it in
719
+ // configureServer is safe. middlewareMode has no httpServer → HTTP bridge
720
+ // routes still work, just no WS peer.
721
+ // Cast: Vite types `httpServer` as http.Server | http2.Http2SecureServer;
722
+ // attachUpgrade only needs `.on('upgrade')`, present on both. (serve passes
723
+ // a plain http.Server, so this widening is plugin-specific.)
724
+ if (mount && server.httpServer) mount.attachUpgrade(server.httpServer as unknown as HttpServer);
725
+
726
+ // A2 discovery pointer: the stdio `mcp-proxy` (the sanctioned Claude Code
727
+ // entrypoint) reads `.pyric/serve.json` to find the bridge without a fixed
728
+ // URL -- it takes the PORT and probes BOTH loopback families, defeating the
729
+ // IPv6/IPv4 trap that broke the hand-written `.mcp.json`. serve writes this
730
+ // pointer; the Vite plugin must too. Written after listen (port known),
731
+ // removed on close.
732
+ if (mount && server.httpServer) {
733
+ const httpServer = server.httpServer;
734
+ const pointer = path.join(cwd, '.pyric', 'serve.json');
735
+ const host =
736
+ (typeof server.config.server.host === 'string' && server.config.server.host) || 'localhost';
737
+ const writePointer = (): void => {
738
+ const addr = httpServer.address();
739
+ const port = addr && typeof addr === 'object' ? addr.port : 0;
740
+ if (!port) return;
741
+ try {
742
+ mkdirSync(path.dirname(pointer), { recursive: true });
743
+ writeFileSync(
744
+ pointer,
745
+ JSON.stringify(
746
+ {
747
+ url: `http://${host}:${port}`,
748
+ mcpUrl: mount.mcpUrl({ host, port }),
749
+ port,
750
+ pid: process.pid,
751
+ instanceId: mount.instanceId,
752
+ project: bridgeOpts?.project ?? 'sandbox',
753
+ },
754
+ null,
755
+ 2,
756
+ ) + '\n',
757
+ );
758
+ } catch {
759
+ /* best-effort: the proxy falls back to a port scan */
760
+ }
761
+ };
762
+ // Cross-family collision guard: once listening, probe BOTH loopback
763
+ // families on our port. If a DIFFERENT sandbox answers on the other
764
+ // family, two dev servers are colliding (IPv4 `*:P` + IPv6 `[::1]:P`)
765
+ // and the agent/browser can split across them (writes seem to vanish).
766
+ // #697's dual-bind can't apply here — Vite owns the single listen — so
767
+ // we can only warn, loudly. (Our own family answers with our instanceId
768
+ // and is skipped; a dual-stack bind owns both and never trips this.)
769
+ const warnOnCollision = async (): Promise<void> => {
770
+ const a = httpServer.address();
771
+ const p = a && typeof a === 'object' ? a.port : 0;
772
+ if (!p) return;
773
+ for (const probe of [`http://127.0.0.1:${p}`, `http://[::1]:${p}`]) {
774
+ try {
775
+ const res = await fetch(`${probe}/__pyric/health`, { signal: AbortSignal.timeout(1000) });
776
+ if (res.status !== 200) continue;
777
+ const body = (await res.json()) as { mode?: string; instanceId?: string };
778
+ if (body.mode === 'sandbox' && body.instanceId && body.instanceId !== mount.instanceId) {
779
+ server.config.logger.warn(
780
+ `\n⚠ pyric: another sandbox already serves port ${p} on a different loopback ` +
781
+ `family (${probe}). Two dev servers are colliding across IPv4/IPv6 — your MCP ` +
782
+ `agent and browser can land on DIFFERENT sandboxes (writes seem to vanish). ` +
783
+ `Stop the other server, or give this app a unique \`server.port\` so the two ` +
784
+ `don't share one (pinning server.host to a family the squatter holds would ` +
785
+ `just EADDRINUSE).\n`,
786
+ { timestamp: true },
787
+ );
788
+ return; // one warning is enough
789
+ }
790
+ } catch {
791
+ /* other family silent — no collision */
792
+ }
793
+ }
794
+ };
795
+ const announce = (): void => {
796
+ writePointer();
797
+ void warnOnCollision();
798
+ };
799
+ if ((httpServer as unknown as { listening?: boolean }).listening) announce();
800
+ else httpServer.once('listening', announce);
801
+ httpServer.once('close', () => {
802
+ try {
803
+ rmSync(pointer);
804
+ } catch {
805
+ /* gone already */
806
+ }
807
+ });
808
+ }
809
+
810
+ // ── Functions child lifecycle (mirrors serve's runServe) ─────────────
811
+ // The Functions runtime executes in an isolated node child (child.ts),
812
+ // exactly as `pyric dev` runs it: the child loads the user's unchanged
813
+ // functions module, and `--import @pyric/cli/register` + `PYRIC_SANDBOX=
814
+ // remote:<serveUrl>` route its `firebase-admin/app` to a RemoteSandbox that
815
+ // dials the bridge WS (`/__pyric/sandbox`). onValueCreated triggers observe
816
+ // RTDB writes and write their effects back through that one shared sandbox.
817
+ // Started once a sandbox peer (a browser tab / SharedWorker relay) has
818
+ // connected — the trigger's baseline needs a live backend — and stopped on
819
+ // server close. Vite restarts re-run configureServer, so the child respawns
820
+ // with the new server. Unlike `pyric dev` (which does not watch functions
821
+ // source), the plugin hot-reloads it via Vite's own watcher — see the
822
+ // watch block below; `functions: { watch: false }` restores dev's
823
+ // restart-to-reload behavior.
824
+ if (functionsProject && functionsProjectId && mount && server.httpServer) {
825
+ const httpServer = server.httpServer;
826
+ const project = functionsProject;
827
+ const projectId = functionsProjectId;
828
+ const bridgeMount = mount;
829
+ const host =
830
+ (typeof server.config.server.host === 'string' && server.config.server.host) || 'localhost';
831
+ // Prefer the compiled child (node cannot execute the .ts source when the
832
+ // plugin runs from source in tests); fall back to spawnFunctionsRtdbChild's
833
+ // own default (correct when the plugin runs from dist in production).
834
+ const builtChild = path.join(cliRoot, 'dist/functions-rtdb/child.js');
835
+ const childModuleUrl = existsSync(builtChild) ? builtChild : undefined;
836
+ let functionsChild: FunctionsRtdbChildHandle | null = null;
837
+ let disposed = false;
838
+
839
+ const start = async (mode: 'initial' | 'reload' = 'initial'): Promise<void> => {
840
+ const addr = httpServer.address();
841
+ const port = addr && typeof addr === 'object' ? addr.port : 0;
842
+ if (!port || disposed) return;
843
+ const serveUrl = `http://${host}:${port}`;
844
+
845
+ // Wait (bounded) for a sandbox peer — the SharedWorker relay / browser
846
+ // tab that holds the backend. Poll the mount directly (no self-fetch).
847
+ // On a hot reload the peer is usually still connected (the loop exits
848
+ // immediately); when it dropped mid-session, wait briefly rather than
849
+ // the full initial 30s.
850
+ const deadline = Date.now() + (mode === 'reload' ? 5_000 : 30_000);
851
+ while (!disposed && !bridgeMount.sandboxConnected()) {
852
+ if (Date.now() >= deadline) break;
853
+ await new Promise((r) => setTimeout(r, 250));
854
+ }
855
+ if (disposed) return;
856
+ if (!bridgeMount.sandboxConnected()) {
857
+ server.config.logger.warn(
858
+ mode === 'reload'
859
+ ? ` ✖ [pyric] functions not restarted — no sandbox peer connected. ` +
860
+ `Functions stay down until the next save with ${serveUrl} open.`
861
+ : ` ⚠ [pyric] functions not started — no browser tab connected after 30s. ` +
862
+ `Open ${serveUrl} and restart the dev server.`,
863
+ );
864
+ return;
865
+ }
866
+
867
+ functionsChild = spawnFunctionsRtdbChild({
868
+ cwd: project.sourceDir,
869
+ entry: project.entry,
870
+ env: buildChildEnv(process.env, { serveUrl, registerUrl: registerModuleUrl() }),
871
+ // Precedence (per field): plugin option > env var > firebase files
872
+ // > default. projectId already folds PYRIC_PROJECT > .firebaserc >
873
+ // demo-project.
874
+ instance: functionsOpts.instance ?? `${projectId}-default-rtdb`,
875
+ location: functionsOpts.region ?? process.env.PYRIC_FUNCTIONS_RTDB_REGION ?? 'us-central1',
876
+ ...(childModuleUrl ? { childModuleUrl } : {}),
877
+ onEvent(event) {
878
+ if (event.type === 'execution') {
879
+ const params = Object.entries(event.params)
880
+ .map(([name, value]) => `${name}=${value}`)
881
+ .join(', ');
882
+ const suffix = params ? ` (${params})` : '';
883
+ if (event.status === 'fulfilled') {
884
+ server.config.logger.info(` ✔ [pyric] function ${event.exportName} ← /${event.ref}${suffix}`);
885
+ } else {
886
+ server.config.logger.error(
887
+ ` ✖ [pyric] function ${event.exportName} ← /${event.ref}${suffix}: ${event.error.message}`,
888
+ );
889
+ }
890
+ } else {
891
+ server.config.logger.error(
892
+ ` ✖ [pyric] functions delivery for ${event.exportName}: ${event.error.message}`,
893
+ );
894
+ }
895
+ },
896
+ });
897
+
898
+ const out = createLinePrefixer('[functions] ', (line) => server.config.logger.info(line.replace(/\n$/, '')));
899
+ const err = createLinePrefixer('[functions] ', (line) => server.config.logger.warn(line.replace(/\n$/, '')));
900
+ functionsChild.child.stdout?.setEncoding('utf8');
901
+ functionsChild.child.stderr?.setEncoding('utf8');
902
+ functionsChild.child.stdout?.on('data', (chunk: string) => out.push(chunk));
903
+ functionsChild.child.stderr?.on('data', (chunk: string) => err.push(chunk));
904
+ functionsChild.child.stdout?.once('end', () => out.flush());
905
+ functionsChild.child.stderr?.once('end', () => err.flush());
906
+
907
+ try {
908
+ const ready = await functionsChild.ready;
909
+ server.config.logger.info(
910
+ mode === 'reload'
911
+ ? ` ↻ [pyric] functions reloaded (${ready.triggerCount} trigger${ready.triggerCount === 1 ? '' : 's'})`
912
+ : ` ✔ [pyric] functions ${ready.triggerCount} onValueCreated ` +
913
+ `trigger${ready.triggerCount === 1 ? '' : 's'} from ${path.relative(cwd, project.entry)}`,
914
+ );
915
+ for (const unsupported of ready.unsupportedTriggers) {
916
+ server.config.logger.warn(
917
+ ` ⚠ [pyric] functions export ${unsupported.exportName} uses unsupported trigger ` +
918
+ `${unsupported.eventType}; it will not run.`,
919
+ );
920
+ }
921
+ } catch (error) {
922
+ const message = error instanceof Error ? error.message : String(error);
923
+ server.config.logger.error(
924
+ mode === 'reload'
925
+ ? // Unlike rules, last-good cannot stay live — the old child is
926
+ // already stopped — so a broken save takes functions down.
927
+ ` ✖ [pyric] functions failed to reload: ${message}\n` +
928
+ ` ✖ [pyric] functions are down until the next good save.`
929
+ : ` ✖ [pyric] functions failed to start: ${message}`,
930
+ );
931
+ await functionsChild.stop().catch(() => undefined);
932
+ functionsChild = null;
933
+ }
934
+ };
935
+
936
+ let reloadDebounce: ReturnType<typeof setTimeout> | null = null;
937
+ httpServer.once('close', () => {
938
+ disposed = true;
939
+ if (reloadDebounce) clearTimeout(reloadDebounce);
940
+ void functionsChild?.stop().catch(() => undefined);
941
+ });
942
+ if ((httpServer as unknown as { listening?: boolean }).listening) void start();
943
+ else httpServer.once('listening', () => void start());
944
+
945
+ // Functions hot-reload from Vite's OWN watcher (mirrors the rules block
946
+ // below). Restart = redeploy: stop the old child, respawn via the same
947
+ // start path — there is no in-place swap, so in-flight executions in the
948
+ // old child may drop and writes landing in the swap gap become the new
949
+ // child's baseline (execution.ts consumes each trigger's first observed
950
+ // value as baseline; they do not fire). Debounced 300ms — a save fans
951
+ // out several fs events and a child respawn is far heavier than a rules
952
+ // re-parse. Restarts are serialized: a save landing mid-restart queues
953
+ // exactly one follow-up run.
954
+ if (functionsOpts.watch !== false) {
955
+ const sourceDir = project.sourceDir;
956
+ // Usually redundant (Vite watches its root, which contains the
957
+ // functions dir in the common layout) but load-bearing when the
958
+ // functions source lives outside Vite's root. node_modules stays
959
+ // ignored: Vite's watcher ignores `**/node_modules/**` globally, and
960
+ // the handler below filters it again for explicitly-added trees.
961
+ server.watcher.add(sourceDir);
962
+ let restarting = false;
963
+ let queued = false;
964
+ const restart = async (): Promise<void> => {
965
+ if (restarting) {
966
+ queued = true;
967
+ return;
968
+ }
969
+ restarting = true;
970
+ try {
971
+ do {
972
+ queued = false;
973
+ if (disposed) return;
974
+ const old = functionsChild;
975
+ functionsChild = null;
976
+ if (old) await old.stop().catch(() => undefined);
977
+ await start('reload');
978
+ } while (queued && !disposed);
979
+ } finally {
980
+ restarting = false;
981
+ }
982
+ };
983
+ const onFunctionsFsEvent = (file: string): void => {
984
+ const resolved = path.resolve(file);
985
+ const rel = path.relative(sourceDir, resolved);
986
+ if (rel === '' || rel.startsWith('..') || path.isAbsolute(rel)) return;
987
+ if (rel.split(path.sep).includes('node_modules')) return;
988
+ if (reloadDebounce) clearTimeout(reloadDebounce);
989
+ reloadDebounce = setTimeout(() => void restart(), 300);
990
+ };
991
+ server.watcher.on('change', onFunctionsFsEvent);
992
+ server.watcher.on('add', onFunctionsFsEvent);
993
+ server.watcher.on('unlink', onFunctionsFsEvent);
994
+ }
995
+ }
996
+
997
+ // Rules hot-reload from Vite's OWN watcher (no second fs watcher). Reuse
998
+ // prepareRulesSource (resolve + lint); last-good stays live on a broken save.
999
+ // Debounced (editors emit several change events per save) — matches
1000
+ // watchProjectRules' 150ms cadence, which we can't reuse here (it opens its
1001
+ // own fs watcher).
1002
+ if (loaded.sourcePath) {
1003
+ const rulesFile = loaded.sourcePath;
1004
+ let debounce: ReturnType<typeof setTimeout> | null = null;
1005
+ server.watcher.add(rulesFile);
1006
+ server.watcher.on('change', (file) => {
1007
+ if (path.resolve(file) !== path.resolve(rulesFile)) return;
1008
+ if (debounce) clearTimeout(debounce);
1009
+ debounce = setTimeout(() => {
1010
+ void readFile(rulesFile, 'utf8').then(
1011
+ (raw) => {
1012
+ try {
1013
+ const rules = prepareRulesSource(raw, rulesFile);
1014
+ live.rules = rules;
1015
+ live.rulesHash = rulesHashOf(rules);
1016
+ events.broadcast('rules-changed', { rules, rulesHash: live.rulesHash });
1017
+ server.config.logger.info(` ↻ [pyric] rules reloaded (${live.rulesHash})`);
1018
+ } catch (e) {
1019
+ server.config.logger.warn(
1020
+ ` ⚠ [pyric] rules NOT reloaded (last-good stays live): ${e instanceof Error ? e.message : String(e)}`,
1021
+ );
1022
+ }
1023
+ },
1024
+ () => {},
1025
+ );
1026
+ }, 150);
1027
+ });
1028
+ }
1029
+ },
1030
+
1031
+ // Sandbox build only: emit the serve init entry as its own chunk. Emitted in
1032
+ // buildStart (module graph time); its final filename is resolved in
1033
+ // generateBundle. Our plugin is `enforce: 'pre'`, so our generateBundle runs
1034
+ // BEFORE Vite's build-html plugin applies transformIndexHtml — the filename
1035
+ // is always available when the script tag is injected below.
1036
+ buildStart() {
1037
+ if (sandboxBuild) {
1038
+ initChunkRef = this.emitFile({
1039
+ type: 'chunk',
1040
+ id: entries.init,
1041
+ name: 'pyric-sandbox-init',
1042
+ });
1043
+ }
1044
+ },
1045
+ generateBundle() {
1046
+ if (initChunkRef) initChunkFile = this.getFileName(initChunkRef);
1047
+ },
1048
+
1049
+ transformIndexHtml(html) {
1050
+ // Sandbox BUILD: the app's own `firebase/*` imports were already swapped
1051
+ // (resolveId, above) to pyric's in-page adapters and BUNDLED into the app
1052
+ // chunk, and the emitted init chunk (script-tagged here) carries the
1053
+ // runtime bootstrap + the ServeAuthHelper popup picker — rollup shares
1054
+ // ONE runtime module between the two, so the output is fully
1055
+ // self-contained. `pyric dev` sees the marker below and skips its own
1056
+ // serve-time injection for this page (a second injected runtime would
1057
+ // double-init: two banners, two bridge peers). The marker is also the
1058
+ // signal that makes `pyric dev` trust this dist (skip the inlined-SDK
1059
+ // scan). transformIndexHtml runs BEFORE Vite writes index.html, so both
1060
+ // land in the emitted asset.
1061
+ if (sandboxBuild) {
1062
+ if (html.includes(SANDBOX_BUILD_META)) return html;
1063
+ const initTag = initChunkFile
1064
+ ? `<script type="module" crossorigin src="/${initChunkFile}" data-pyric-sandbox-init></script>`
1065
+ : '';
1066
+ const tags = SANDBOX_BUILD_META + initTag;
1067
+ return html.includes('</head>')
1068
+ ? html.replace('</head>', `${tags}</head>`)
1069
+ : tags + html;
1070
+ }
1071
+ const MARKER = 'data-pyric-sandbox';
1072
+ if (html.includes(MARKER)) return html;
1073
+ // Worker path (default): stamp the served worker's content hash so the page
1074
+ // can WARN when a still-running OLD worker is stale (a SharedWorker can't
1075
+ // hot-update). In-page path: force it via the explicit flag before the init
1076
+ // module evaluates — a classic inline script runs before the deferred module.
1077
+ // The flag (not nulling `window.SharedWorker`) leaves the user's own
1078
+ // SharedWorker usage intact. We force in-page ONLY when the worker bundle
1079
+ // failed (workerReady false) — the ephemeral fallback. `bridge` no longer
1080
+ // forces in-page: the bridge peer routes agent tool-calls THROUGH the
1081
+ // worker (see `connectBridgePeer`), so the agent shares the one sandbox the
1082
+ // app + Studio use.
1083
+ const head = workerReady
1084
+ ? `<meta name="pyric-worker-v" content="${workerVersion}" ${MARKER}>`
1085
+ : `<script ${MARKER}>globalThis.__PYRIC_FORCE_INPAGE__=true;</script>`;
1086
+ // Plugin-level engine for the IN-PAGE path: a classic inline script runs
1087
+ // before the deferred init module AND before app code's `getAI`, so the
1088
+ // served `getAI` (entries/ai.ts) reads it synchronously — init.json can't
1089
+ // be awaited there. Harmless on the worker path (that branch ignores the
1090
+ // global; the worker reads ctx.aiEngine from init.json). `<` is escaped so
1091
+ // an engine value can never break out of the script tag.
1092
+ const aiEngineTag = aiEngineWire
1093
+ ? `<script ${MARKER}>globalThis.__PYRIC_AI_ENGINE__=${JSON.stringify(aiEngineWire).replace(/</g, '\\u003c')};</script>`
1094
+ : '';
1095
+ // Boot the sandbox by loading the real init entry as a module (Vite
1096
+ // serves + transforms it). The init module's top-level await deploys rules
1097
+ // before app code runs. Mirrors serve's injectServeTags.
1098
+ const tag = head + aiEngineTag + `<script type="module" src="/@fs/${entries.init}" ${MARKER}></script>`;
1099
+ return html.includes('</head>') ? html.replace('</head>', `${tag}</head>`) : tag + html;
1100
+ },
1101
+ };
1102
+ }