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

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 (424) hide show
  1. package/dist/cli/serve.js +4 -4
  2. package/dist/cli/serve.js.map +1 -1
  3. package/dist/conformance/.generated/can-i-use-browser.d.ts.map +1 -1
  4. package/dist/conformance/.generated/can-i-use-browser.js +1 -1
  5. package/dist/conformance/.generated/can-i-use-browser.js.map +1 -1
  6. package/dist/conformance/.generated/can-i-use.d.ts.map +1 -1
  7. package/dist/conformance/.generated/can-i-use.js +2 -2
  8. package/dist/conformance/.generated/can-i-use.js.map +1 -1
  9. package/dist/serve/bundler.d.ts +13 -8
  10. package/dist/serve/bundler.d.ts.map +1 -1
  11. package/dist/serve/bundler.js +31 -36
  12. package/dist/serve/bundler.js.map +1 -1
  13. package/dist/serve/docs-ui/docs/_rhythm/index.html +1 -1
  14. package/dist/serve/docs-ui/docs/agent/set-up-your-agent/index.html +1 -1
  15. package/dist/serve/docs-ui/docs/agent/watch-and-review/index.html +1 -1
  16. package/dist/serve/docs-ui/docs/agent/work-with-an-agent/index.html +1 -1
  17. package/dist/serve/docs-ui/docs/ai-compat/index.html +1 -1
  18. package/dist/serve/docs-ui/docs/api-reference/index.html +2 -2
  19. package/dist/serve/docs-ui/docs/api-reference.md +1 -1
  20. package/dist/serve/docs-ui/docs/app-compat/index.html +1 -1
  21. package/dist/serve/docs-ui/docs/auth-compat/index.html +1 -1
  22. package/dist/serve/docs-ui/docs/build/ai-logic/index.html +44 -22
  23. package/dist/serve/docs-ui/docs/build/ai-logic.md +69 -21
  24. package/dist/serve/docs-ui/docs/build/authentication/index.html +1 -1
  25. package/dist/serve/docs-ui/docs/build/cloud-firestore/index.html +1 -1
  26. package/dist/serve/docs-ui/docs/build/cloud-messaging/index.html +1 -1
  27. package/dist/serve/docs-ui/docs/build/cloud-storage/index.html +1 -1
  28. package/dist/serve/docs-ui/docs/build/realtime-database/index.html +1 -1
  29. package/dist/serve/docs-ui/docs/conformance-scores/index.html +1 -1
  30. package/dist/serve/docs-ui/docs/create-pyric-reference-api/index.html +1 -1
  31. package/dist/serve/docs-ui/docs/database-compat/index.html +1 -1
  32. package/dist/serve/docs-ui/docs/firestore-compat/index.html +1 -1
  33. package/dist/serve/docs-ui/docs/functions-rtdb-compat/index.html +1 -1
  34. package/dist/serve/docs-ui/docs/get-started/how-the-swap-works/index.html +2 -1
  35. package/dist/serve/docs-ui/docs/get-started/how-the-swap-works.md +2 -0
  36. package/dist/serve/docs-ui/docs/get-started/start-building/index.html +3 -2
  37. package/dist/serve/docs-ui/docs/get-started/start-building.md +3 -1
  38. package/dist/serve/docs-ui/docs/index.json +349 -29
  39. package/dist/serve/docs-ui/docs/messaging-compat/index.html +1 -1
  40. package/dist/serve/docs-ui/docs/observe/resolve-runtime-status/index.html +28 -0
  41. package/dist/serve/docs-ui/docs/observe/resolve-runtime-status.md +47 -0
  42. package/dist/serve/docs-ui/docs/observe/see-whats-happening/index.html +1 -1
  43. package/dist/serve/docs-ui/docs/observe/shape-your-data/index.html +1 -1
  44. package/dist/serve/docs-ui/docs/overview/index.html +1 -1
  45. package/dist/serve/docs-ui/docs/pyric-admin-app-reference-api/index.html +1 -1
  46. package/dist/serve/docs-ui/docs/pyric-admin-auth-reference-api/index.html +1 -1
  47. package/dist/serve/docs-ui/docs/pyric-admin-database-reference-api/index.html +1 -1
  48. package/dist/serve/docs-ui/docs/pyric-admin-firestore-reference-api/index.html +1 -1
  49. package/dist/serve/docs-ui/docs/pyric-admin-messaging-reference-api/index.html +916 -0
  50. package/dist/serve/docs-ui/docs/pyric-admin-messaging-reference-api.md +706 -0
  51. package/dist/serve/docs-ui/docs/pyric-admin-storage-reference-api/index.html +1 -1
  52. package/dist/serve/docs-ui/docs/pyric-ai-reference-api/index.html +1 -1
  53. package/dist/serve/docs-ui/docs/pyric-ai-scripting-reference-api/index.html +1 -1
  54. package/dist/serve/docs-ui/docs/pyric-app-reference-api/index.html +1 -1
  55. package/dist/serve/docs-ui/docs/pyric-auth-reference-api/index.html +1 -1
  56. package/dist/serve/docs-ui/docs/pyric-cli-assurance-browser-reference-api/index.html +1 -1
  57. package/dist/serve/docs-ui/docs/pyric-cli-assurance-reference-api/index.html +1 -1
  58. package/dist/serve/docs-ui/docs/pyric-cli-bridge-client-reference-api/index.html +1 -1
  59. package/dist/serve/docs-ui/docs/pyric-cli-bridge-reference-api/index.html +1 -1
  60. package/dist/serve/docs-ui/docs/pyric-cli-conformance-browser-reference-api/index.html +1 -1
  61. package/dist/serve/docs-ui/docs/pyric-cli-conformance-docs-reference-api/index.html +1 -1
  62. package/dist/serve/docs-ui/docs/pyric-cli-conformance-reference-api/index.html +1 -1
  63. package/dist/serve/docs-ui/docs/pyric-cli-credentials-node-reference-api/index.html +1 -1
  64. package/dist/serve/docs-ui/docs/pyric-cli-discover-reference-api/index.html +1 -1
  65. package/dist/serve/docs-ui/docs/pyric-cli-register-reference-api/index.html +1 -1
  66. package/dist/serve/docs-ui/docs/pyric-cli-remote-reference-api/index.html +1 -1
  67. package/dist/serve/docs-ui/docs/pyric-cli-serve-worker-reference-api/index.html +168 -76
  68. package/dist/serve/docs-ui/docs/pyric-cli-serve-worker-reference-api.md +156 -73
  69. package/dist/serve/docs-ui/docs/pyric-cli-verify-reference-api/index.html +1 -1
  70. package/dist/serve/docs-ui/docs/pyric-cli-vite-reference-api/index.html +11 -8
  71. package/dist/serve/docs-ui/docs/pyric-cli-vite-reference-api.md +17 -4
  72. package/dist/serve/docs-ui/docs/pyric-database-reference-api/index.html +1 -1
  73. package/dist/serve/docs-ui/docs/pyric-firestore-reference-api/index.html +1 -1
  74. package/dist/serve/docs-ui/docs/pyric-messaging-reference-api/index.html +1 -1
  75. package/dist/serve/docs-ui/docs/pyric-messaging-sw-reference-api/index.html +1 -1
  76. package/dist/serve/docs-ui/docs/pyric-rules-reference-api/index.html +1 -1
  77. package/dist/serve/docs-ui/docs/pyric-sandbox-database-reference-api/index.html +1 -1
  78. package/dist/serve/docs-ui/docs/pyric-sandbox-firestore-reference-api/index.html +1 -1
  79. package/dist/serve/docs-ui/docs/pyric-sandbox-reference-api/index.html +37 -14
  80. package/dist/serve/docs-ui/docs/pyric-sandbox-reference-api.md +28 -8
  81. package/dist/serve/docs-ui/docs/pyric-storage-reference-api/index.html +1 -1
  82. package/dist/serve/docs-ui/docs/pyric-ui-agents-reference-api/index.html +1 -1
  83. package/dist/serve/docs-ui/docs/pyric-ui-auth-hooks-reference-api/index.html +1 -1
  84. package/dist/serve/docs-ui/docs/pyric-ui-auth-reference-api/index.html +1 -1
  85. package/dist/serve/docs-ui/docs/pyric-ui-events-hooks-reference-api/index.html +1 -1
  86. package/dist/serve/docs-ui/docs/pyric-ui-events-reference-api/index.html +1 -1
  87. package/dist/serve/docs-ui/docs/pyric-ui-firestore-hooks-reference-api/index.html +1 -1
  88. package/dist/serve/docs-ui/docs/pyric-ui-firestore-reference-api/index.html +1 -1
  89. package/dist/serve/docs-ui/docs/pyric-ui-primitives-reference-api/index.html +1 -1
  90. package/dist/serve/docs-ui/docs/pyric-ui-rtdb-reference-api/index.html +1 -1
  91. package/dist/serve/docs-ui/docs/pyric-ui-rules-hooks-reference-api/index.html +1 -1
  92. package/dist/serve/docs-ui/docs/pyric-ui-rules-reference-api/index.html +1 -1
  93. package/dist/serve/docs-ui/docs/pyric-ui-storage-hooks-reference-api/index.html +1 -1
  94. package/dist/serve/docs-ui/docs/pyric-ui-storage-reference-api/index.html +1 -1
  95. package/dist/serve/docs-ui/docs/pyric-ui-traffic-hooks-reference-api/index.html +1 -1
  96. package/dist/serve/docs-ui/docs/pyric-ui-traffic-reference-api/index.html +1 -1
  97. package/dist/serve/docs-ui/docs/rules-compat/index.html +1 -1
  98. package/dist/serve/docs-ui/docs/secure/audit-your-rules/index.html +1 -1
  99. package/dist/serve/docs-ui/docs/secure/firestore-rules-limits/index.html +1 -1
  100. package/dist/serve/docs-ui/docs/secure/read-a-denial/index.html +1 -1
  101. package/dist/serve/docs-ui/docs/secure/rtdb-rules-in-typescript/index.html +1 -1
  102. package/dist/serve/docs-ui/docs/secure/rules-standard-library/index.html +1 -1
  103. package/dist/serve/docs-ui/docs/secure/secure-it-with-rules/index.html +1 -1
  104. package/dist/serve/docs-ui/docs/secure/simulate-and-lint/index.html +1 -1
  105. package/dist/serve/docs-ui/docs/secure/write-a-rules-test-suite/index.html +1 -1
  106. package/dist/serve/docs-ui/docs/ship/ship-to-production/index.html +1 -1
  107. package/dist/serve/docs-ui/docs/ship/test-in-node/index.html +1 -1
  108. package/dist/serve/docs-ui/docs/storage-compat/index.html +1 -1
  109. package/dist/serve/docs-ui/docs/trust/how-we-know-it-matches-firebase/index.html +1 -1
  110. package/dist/serve/docs-ui/docs/trust/versioning-and-compatibility/index.html +1 -1
  111. package/dist/serve/docs-ui/docs/tutorial/index.html +429 -0
  112. package/dist/serve/docs-ui/docs/tutorial.md +701 -0
  113. package/dist/serve/docs-ui/llms.txt +3 -1
  114. package/dist/serve/entries/init.d.ts.map +1 -1
  115. package/dist/serve/entries/init.js +3 -0
  116. package/dist/serve/entries/init.js.map +1 -1
  117. package/dist/serve/entries/runtime.d.ts.map +1 -1
  118. package/dist/serve/entries/runtime.js +20 -5
  119. package/dist/serve/entries/runtime.js.map +1 -1
  120. package/dist/serve/entries/worker-runtime.d.ts +2 -2
  121. package/dist/serve/entries/worker-runtime.d.ts.map +1 -1
  122. package/dist/serve/entries/worker-runtime.js +45 -10
  123. package/dist/serve/entries/worker-runtime.js.map +1 -1
  124. package/dist/serve/runtime/chip-config.d.ts +19 -0
  125. package/dist/serve/runtime/chip-config.d.ts.map +1 -0
  126. package/dist/serve/runtime/chip-config.js +19 -0
  127. package/dist/serve/runtime/chip-config.js.map +1 -0
  128. package/dist/serve/runtime/chip-install.d.ts +10 -0
  129. package/dist/serve/runtime/chip-install.d.ts.map +1 -0
  130. package/dist/serve/runtime/chip-install.js +15 -0
  131. package/dist/serve/runtime/chip-install.js.map +1 -0
  132. package/dist/serve/runtime/chip.d.ts +17 -0
  133. package/dist/serve/runtime/chip.d.ts.map +1 -0
  134. package/dist/serve/runtime/chip.js +257 -0
  135. package/dist/serve/runtime/chip.js.map +1 -0
  136. package/dist/serve/runtime/manifest.d.ts +22 -0
  137. package/dist/serve/runtime/manifest.d.ts.map +1 -0
  138. package/dist/serve/runtime/manifest.js +20 -0
  139. package/dist/serve/runtime/manifest.js.map +1 -0
  140. package/dist/serve/runtime/status.d.ts +49 -0
  141. package/dist/serve/runtime/status.d.ts.map +1 -0
  142. package/dist/serve/runtime/status.js +164 -0
  143. package/dist/serve/runtime/status.js.map +1 -0
  144. package/dist/serve/runtime/worker-connection.d.ts +4 -0
  145. package/dist/serve/runtime/worker-connection.d.ts.map +1 -0
  146. package/dist/serve/runtime/worker-connection.js +11 -0
  147. package/dist/serve/runtime/worker-connection.js.map +1 -0
  148. package/dist/serve/runtime/worker-generation.d.ts +14 -0
  149. package/dist/serve/runtime/worker-generation.d.ts.map +1 -0
  150. package/dist/serve/runtime/worker-generation.js +56 -0
  151. package/dist/serve/runtime/worker-generation.js.map +1 -0
  152. package/dist/serve/runtime/worker-replacement.d.ts +18 -0
  153. package/dist/serve/runtime/worker-replacement.d.ts.map +1 -0
  154. package/dist/serve/runtime/worker-replacement.js +29 -0
  155. package/dist/serve/runtime/worker-replacement.js.map +1 -0
  156. package/dist/serve/standalone-assets.d.ts +2 -2
  157. package/dist/serve/standalone-assets.d.ts.map +1 -1
  158. package/dist/serve/standalone-assets.js +1 -1
  159. package/dist/serve/standalone-assets.js.map +1 -1
  160. package/dist/serve/studio-ui/assets/{RulesCodeEditor-CxVYcZXw.js → RulesCodeEditor-BDlH-5lp.js} +1 -1
  161. package/dist/serve/studio-ui/assets/{index-cpSfgQ7H.js → index-Bf9SSE8L.js} +5 -5
  162. package/dist/serve/studio-ui/assets/{seed-DeuFKi4J.js → seed-D_UjxfOU.js} +1 -1
  163. package/dist/serve/studio-ui/index.html +1 -1
  164. package/dist/serve/vite-ai-config.d.ts +25 -0
  165. package/dist/serve/vite-ai-config.d.ts.map +1 -0
  166. package/dist/serve/vite-ai-config.js +45 -0
  167. package/dist/serve/vite-ai-config.js.map +1 -0
  168. package/dist/serve/vite-plugin.d.ts +17 -36
  169. package/dist/serve/vite-plugin.d.ts.map +1 -1
  170. package/dist/serve/vite-plugin.js +38 -57
  171. package/dist/serve/vite-plugin.js.map +1 -1
  172. package/dist/serve/vite-rules-source.d.ts +8 -0
  173. package/dist/serve/vite-rules-source.d.ts.map +1 -0
  174. package/dist/serve/vite-rules-source.js +23 -0
  175. package/dist/serve/vite-rules-source.js.map +1 -0
  176. package/dist/serve/vite-worker-runtime.d.ts +20 -0
  177. package/dist/serve/vite-worker-runtime.d.ts.map +1 -0
  178. package/dist/serve/vite-worker-runtime.js +25 -0
  179. package/dist/serve/vite-worker-runtime.js.map +1 -0
  180. package/dist/serve/worker/client/connection.d.ts +7 -2
  181. package/dist/serve/worker/client/connection.d.ts.map +1 -1
  182. package/dist/serve/worker/client/connection.js +13 -16
  183. package/dist/serve/worker/client/connection.js.map +1 -1
  184. package/dist/serve/worker/client/core.d.ts +7 -0
  185. package/dist/serve/worker/client/core.d.ts.map +1 -1
  186. package/dist/serve/worker/client/core.js +28 -0
  187. package/dist/serve/worker/client/core.js.map +1 -1
  188. package/dist/serve/worker/client/runtime-control.d.ts +8 -0
  189. package/dist/serve/worker/client/runtime-control.d.ts.map +1 -0
  190. package/dist/serve/worker/client/runtime-control.js +11 -0
  191. package/dist/serve/worker/client/runtime-control.js.map +1 -0
  192. package/dist/serve/worker/entry.js +44 -2
  193. package/dist/serve/worker/entry.js.map +1 -1
  194. package/dist/serve/worker/host/core.js +1 -1
  195. package/dist/serve/worker/host/core.js.map +1 -1
  196. package/dist/serve/worker/host/firestore-writes.d.ts.map +1 -1
  197. package/dist/serve/worker/host/firestore-writes.js +3 -2
  198. package/dist/serve/worker/host/firestore-writes.js.map +1 -1
  199. package/dist/serve/worker/host/studio.js +1 -1
  200. package/dist/serve/worker/host/studio.js.map +1 -1
  201. package/dist/serve/worker/host-context.d.ts +1 -1
  202. package/dist/serve/worker/host-context.d.ts.map +1 -1
  203. package/dist/serve/worker/index.d.ts +2 -1
  204. package/dist/serve/worker/index.d.ts.map +1 -1
  205. package/dist/serve/worker/index.js +2 -1
  206. package/dist/serve/worker/index.js.map +1 -1
  207. package/dist/serve/worker/protocol.d.ts +15 -1
  208. package/dist/serve/worker/protocol.d.ts.map +1 -1
  209. package/dist/serve/worker/protocol.js +2 -2
  210. package/dist/serve/worker/protocol.js.map +1 -1
  211. package/dist/serve/worker/retirement.d.ts +21 -0
  212. package/dist/serve/worker/retirement.d.ts.map +1 -0
  213. package/dist/serve/worker/retirement.js +97 -0
  214. package/dist/serve/worker/retirement.js.map +1 -0
  215. package/dist/serve/worker/serve-init.d.ts.map +1 -1
  216. package/dist/serve/worker/serve-init.js +5 -6
  217. package/dist/serve/worker/serve-init.js.map +1 -1
  218. package/dist/vite.d.ts +1 -0
  219. package/dist/vite.d.ts.map +1 -1
  220. package/dist/vite.js.map +1 -1
  221. package/package.json +6 -4
  222. package/src/assurance/.generated/conformance-verdicts.ts +1090 -0
  223. package/src/assurance/attachment.ts +211 -0
  224. package/src/assurance/browser.ts +80 -0
  225. package/src/assurance/campaign.ts +496 -0
  226. package/src/assurance/capabilities.ts +446 -0
  227. package/src/assurance/cases.ts +43 -0
  228. package/src/assurance/index.ts +75 -0
  229. package/src/assurance/runner.ts +885 -0
  230. package/src/assurance/tool-names.ts +15 -0
  231. package/src/assurance/tools.ts +830 -0
  232. package/src/assurance/types.ts +352 -0
  233. package/src/assurance/validation.ts +434 -0
  234. package/src/bridge/client/bridge.ts +550 -0
  235. package/src/bridge/client/dispatch.ts +137 -0
  236. package/src/bridge/client.ts +45 -0
  237. package/src/bridge/protocol.ts +351 -0
  238. package/src/bridge/server/audit.ts +53 -0
  239. package/src/bridge/server/bridge.ts +597 -0
  240. package/src/bridge/server/headless.ts +160 -0
  241. package/src/bridge/server/json-schema-to-zod.ts +108 -0
  242. package/src/bridge/server/local-bridge.ts +66 -0
  243. package/src/bridge/server/logger.ts +50 -0
  244. package/src/bridge/server/mcp-contract.ts +93 -0
  245. package/src/bridge/server/mcp.ts +129 -0
  246. package/src/bridge/server/peer.ts +232 -0
  247. package/src/bridge/server/standalone.ts +347 -0
  248. package/src/bridge/server/tool-metadata.ts +99 -0
  249. package/src/bridge/server.ts +28 -0
  250. package/src/cli/can-i-use.ts +50 -0
  251. package/src/cli/cli.test.ts +493 -0
  252. package/src/cli/database-rules.ts +329 -0
  253. package/src/cli/dev-runner.ts +282 -0
  254. package/src/cli/firebase-json.ts +100 -0
  255. package/src/cli/firestore-indexes.ts +70 -0
  256. package/src/cli/index.ts +425 -0
  257. package/src/cli/init.ts +260 -0
  258. package/src/cli/mcp-proxy.ts +196 -0
  259. package/src/cli/parse-args.ts +80 -0
  260. package/src/cli/rules.ts +259 -0
  261. package/src/cli/scope.ts +67 -0
  262. package/src/cli/serve.ts +996 -0
  263. package/src/cli/service-commands.ts +73 -0
  264. package/src/cli/snapshot.ts +164 -0
  265. package/src/cli/storage-rules.ts +172 -0
  266. package/src/cli/verify.ts +416 -0
  267. package/src/conformance/.generated/can-i-use-browser.ts +113 -0
  268. package/src/conformance/.generated/can-i-use.ts +117 -0
  269. package/src/conformance/.generated/conformance-docs.ts +14 -0
  270. package/src/conformance/browser.ts +24 -0
  271. package/src/conformance/can-i-use-tool.ts +51 -0
  272. package/src/conformance/can-i-use.ts +18 -0
  273. package/src/conformance/docs.ts +8 -0
  274. package/src/conformance/index.ts +20 -0
  275. package/src/conformance/tools.ts +16 -0
  276. package/src/credentials/core/memoize-ttl.ts +142 -0
  277. package/src/credentials/core/types.ts +10 -0
  278. package/src/credentials/node/from-adc.ts +96 -0
  279. package/src/credentials/node/from-service-account.ts +133 -0
  280. package/src/credentials/node/index.ts +6 -0
  281. package/src/discover/concurrency.ts +127 -0
  282. package/src/discover/crawler-adapter.ts +142 -0
  283. package/src/discover/crawler.ts +1127 -0
  284. package/src/discover/credential-free.ts +27 -0
  285. package/src/discover/findCollectionGroup.ts +131 -0
  286. package/src/discover/firestore-source.ts +59 -0
  287. package/src/discover/index.ts +5 -0
  288. package/src/discover/merge.ts +523 -0
  289. package/src/discover/session.ts +402 -0
  290. package/src/discover/tools.ts +201 -0
  291. package/src/discover/types.ts +187 -0
  292. package/src/discover/wire.ts +324 -0
  293. package/src/functions-rtdb/child.ts +382 -0
  294. package/src/functions-rtdb/delivery.ts +7 -0
  295. package/src/functions-rtdb/discovery.ts +136 -0
  296. package/src/functions-rtdb/event.ts +64 -0
  297. package/src/functions-rtdb/execution.ts +111 -0
  298. package/src/functions-rtdb/in-memory-delivery.ts +40 -0
  299. package/src/functions-rtdb/project.ts +74 -0
  300. package/src/functions-rtdb/projection.ts +104 -0
  301. package/src/functions-rtdb/reference-pattern.ts +20 -0
  302. package/src/functions-rtdb/remote-delivery.ts +23 -0
  303. package/src/pkg-version.ts +49 -0
  304. package/src/register/esm-exports.ts +63 -0
  305. package/src/register/hooks.ts +30 -0
  306. package/src/register/index.ts +150 -0
  307. package/src/register/mapping.ts +33 -0
  308. package/src/remote/index.ts +1050 -0
  309. package/src/rtdb/crawl-snapshot.ts +118 -0
  310. package/src/rtdb/inspection.ts +137 -0
  311. package/src/rtdb/load-rules-document.ts +56 -0
  312. package/src/rtdb/rules-generation-tool.ts +38 -0
  313. package/src/rtdb/rules-json.ts +29 -0
  314. package/src/serve/activity-guard.ts +29 -0
  315. package/src/serve/activity-route.ts +164 -0
  316. package/src/serve/activity-warning.ts +26 -0
  317. package/src/serve/bridge-mount.ts +200 -0
  318. package/src/serve/bundler.ts +519 -0
  319. package/src/serve/capture-store.ts +65 -0
  320. package/src/serve/discovery.ts +199 -0
  321. package/src/serve/entries/ai.ts +292 -0
  322. package/src/serve/entries/app-backend.ts +4 -0
  323. package/src/serve/entries/app-client.ts +26 -0
  324. package/src/serve/entries/app-session-store.ts +47 -0
  325. package/src/serve/entries/app.ts +11 -0
  326. package/src/serve/entries/auth-helper-core.ts +181 -0
  327. package/src/serve/entries/auth-helper-dom.ts +134 -0
  328. package/src/serve/entries/auth-helper-runtime.ts +20 -0
  329. package/src/serve/entries/auth.ts +255 -0
  330. package/src/serve/entries/bridge-url.ts +31 -0
  331. package/src/serve/entries/database.ts +129 -0
  332. package/src/serve/entries/firestore.ts +232 -0
  333. package/src/serve/entries/init.ts +49 -0
  334. package/src/serve/entries/keepalive.ts +46 -0
  335. package/src/serve/entries/messaging-sw.ts +75 -0
  336. package/src/serve/entries/messaging.ts +96 -0
  337. package/src/serve/entries/runtime.ts +556 -0
  338. package/src/serve/entries/session-store.ts +97 -0
  339. package/src/serve/entries/storage.ts +92 -0
  340. package/src/serve/entries/tab-sync-wiring.ts +274 -0
  341. package/src/serve/entries/worker-runtime.ts +135 -0
  342. package/src/serve/init-payload.ts +42 -0
  343. package/src/serve/namespace.ts +675 -0
  344. package/src/serve/open-browser.ts +68 -0
  345. package/src/serve/rules.ts +272 -0
  346. package/src/serve/runtime/chip-config.ts +30 -0
  347. package/src/serve/runtime/chip-install.ts +27 -0
  348. package/src/serve/runtime/chip.ts +282 -0
  349. package/src/serve/runtime/manifest.ts +37 -0
  350. package/src/serve/runtime/status.ts +216 -0
  351. package/src/serve/runtime/worker-connection.ts +14 -0
  352. package/src/serve/runtime/worker-generation.ts +75 -0
  353. package/src/serve/runtime/worker-replacement.ts +42 -0
  354. package/src/serve/sandbox-marker.ts +31 -0
  355. package/src/serve/server.ts +428 -0
  356. package/src/serve/standalone-assets.ts +180 -0
  357. package/src/serve/state-store.ts +166 -0
  358. package/src/serve/studio/disk-project-store.ts +185 -0
  359. package/src/serve/studio/disk-workspace.ts +162 -0
  360. package/src/serve/studio/index.ts +20 -0
  361. package/src/serve/studio/routes.ts +237 -0
  362. package/src/serve/studio/store-types.ts +48 -0
  363. package/src/serve/studio/studio-storage.test.ts +289 -0
  364. package/src/serve/vite-ai-config.ts +77 -0
  365. package/src/serve/vite-plugin.ts +1075 -0
  366. package/src/serve/vite-rules-source.ts +28 -0
  367. package/src/serve/vite-worker-runtime.ts +51 -0
  368. package/src/serve/worker/activity-bootstrap.ts +24 -0
  369. package/src/serve/worker/client/admin-firestore.ts +38 -0
  370. package/src/serve/worker/client/ai.ts +124 -0
  371. package/src/serve/worker/client/auth.ts +489 -0
  372. package/src/serve/worker/client/connection.ts +227 -0
  373. package/src/serve/worker/client/core.ts +384 -0
  374. package/src/serve/worker/client/disconnect.ts +45 -0
  375. package/src/serve/worker/client/firestore-reads.ts +181 -0
  376. package/src/serve/worker/client/firestore-refs.ts +226 -0
  377. package/src/serve/worker/client/firestore-writes.ts +232 -0
  378. package/src/serve/worker/client/handles.ts +91 -0
  379. package/src/serve/worker/client/messaging.ts +119 -0
  380. package/src/serve/worker/client/presence.ts +174 -0
  381. package/src/serve/worker/client/rtdb.ts +311 -0
  382. package/src/serve/worker/client/rules.ts +63 -0
  383. package/src/serve/worker/client/runtime-control.ts +22 -0
  384. package/src/serve/worker/client/service-worker-connection.ts +59 -0
  385. package/src/serve/worker/client/snapshots.ts +86 -0
  386. package/src/serve/worker/client/storage.ts +195 -0
  387. package/src/serve/worker/client/studio.ts +88 -0
  388. package/src/serve/worker/client.ts +57 -0
  389. package/src/serve/worker/durable-persistence.ts +137 -0
  390. package/src/serve/worker/entry.ts +223 -0
  391. package/src/serve/worker/host/admin-firestore.ts +88 -0
  392. package/src/serve/worker/host/connection.ts +179 -0
  393. package/src/serve/worker/host/core.ts +387 -0
  394. package/src/serve/worker/host/dispatch.ts +316 -0
  395. package/src/serve/worker/host/firestore-reads.ts +117 -0
  396. package/src/serve/worker/host/firestore-writes.ts +456 -0
  397. package/src/serve/worker/host/presence.ts +312 -0
  398. package/src/serve/worker/host/rtdb.ts +136 -0
  399. package/src/serve/worker/host/rules.ts +128 -0
  400. package/src/serve/worker/host/storage.ts +312 -0
  401. package/src/serve/worker/host/studio.ts +75 -0
  402. package/src/serve/worker/host/subscriptions.ts +238 -0
  403. package/src/serve/worker/host-ai.ts +165 -0
  404. package/src/serve/worker/host-auth.ts +469 -0
  405. package/src/serve/worker/host-context.ts +273 -0
  406. package/src/serve/worker/host-events.ts +94 -0
  407. package/src/serve/worker/host-messaging.ts +240 -0
  408. package/src/serve/worker/host.ts +47 -0
  409. package/src/serve/worker/index.ts +196 -0
  410. package/src/serve/worker/presence-timing.ts +15 -0
  411. package/src/serve/worker/protocol.ts +1124 -0
  412. package/src/serve/worker/retirement.ts +125 -0
  413. package/src/serve/worker/serve-init.ts +605 -0
  414. package/src/serve/worker/service-worker-channel.ts +33 -0
  415. package/src/serve/worker/service-worker-relay.ts +86 -0
  416. package/src/serve/writer-lock.ts +53 -0
  417. package/src/verify/cases.ts +233 -0
  418. package/src/verify/fixture.ts +258 -0
  419. package/src/verify/index.ts +519 -0
  420. package/src/verify/tools.ts +108 -0
  421. package/src/version/compat-target.ts +17 -0
  422. package/src/vite.ts +18 -0
  423. package/dist/serve/docs-ui/docs/pyric-firestore-values-reference-api/index.html +0 -31
  424. package/dist/serve/docs-ui/docs/pyric-firestore-values-reference-api.md +0 -29
@@ -0,0 +1,556 @@
1
+ /**
2
+ * `pyric dev` in-page runtime — the shared chunk every served SDK bundle
3
+ * closes over. One sandbox per page; init payload (rules, future bridge URL)
4
+ * fetched from `/__pyric/init.json` at module init.
5
+ *
6
+ * TOP-LEVEL AWAIT IS LOAD-BEARING: every importer (the auth/firestore bundles,
7
+ * and therefore the user's app module) is deferred until this module resolves,
8
+ * so by the time app code runs the rules are deployed — no
9
+ * "first write raced the ruleset" class of bugs.
10
+ *
11
+ * This file is BUNDLED FOR THE BROWSER by `../bundler.ts` (esbuild) — it is
12
+ * never imported by node-side @pyric/cli code. Bundle splitting must keep it
13
+ * a single shared chunk: two copies would mean two sandboxes (P0 validation
14
+ * constraint, design rationale section 9).
15
+ */
16
+ import {
17
+ recordBackendOverBlob,
18
+ serializeToBuckets,
19
+ bundleRecords,
20
+ } from 'pyric/sandbox';
21
+ import { getFirestore } from 'pyric/firestore';
22
+ import { seedDocuments, setRules, snapshotDocuments } from 'pyric/sandbox/firestore';
23
+ import { getDatabase, sandbox as rtdbSandbox } from 'pyric/database';
24
+ import { getStorageSandbox } from 'pyric/storage';
25
+ import { getAuth, onAuthStateChanged, signOut, sandbox as authOps, type SeedUser } from 'pyric/auth';
26
+ import {
27
+ callTool as workerCallTool,
28
+ relayWorkerOp,
29
+ relayWorkerSub,
30
+ } from '../worker/client.js';
31
+ import { useWorker, workerDb } from './worker-runtime.js';
32
+ import { keepaliveSafe } from './keepalive.js';
33
+ import { toPageOriginWsUrl } from './bridge-url.js';
34
+ import { buildVerifyFixture } from '../../verify/fixture.js';
35
+ import type { InitPayload } from '../init-payload.js';
36
+ import { setupFirebaseActivityGuard } from '../activity-guard.js';
37
+ import { getPyricRuntimeStatus } from '../runtime/status.js';
38
+ export { sandbox } from './app-backend.js';
39
+ import { sandbox } from './app-backend.js';
40
+
41
+ /**
42
+ * The DEFAULT-ON worker path (Phase 3c): when SharedWorker is available the
43
+ * `firebase/*` entry adapters route to the worker-hosted sandbox instead of
44
+ * the in-page one. The worker owns rules/seed/persist/capture/session (it
45
+ * fetches the SAME `/__pyric/init.json`), so on this path the page MUST NOT
46
+ * re-run that backend init below — doing so would double-POST captures and
47
+ * fight the worker over `/__pyric/state`. Unsupported browsers fall back to
48
+ * the in-page sandbox + the shipped BroadcastChannel sync (strict enhancement).
49
+ *
50
+ * `globalThis.__PYRIC_FORCE_INPAGE__` is an explicit opt-out: a host that does
51
+ * NOT serve the worker bundle (`/__pyric/sdk/worker.js`) sets it before this
52
+ * module evaluates so the page takes the in-page path instead of trying to load
53
+ * a worker that 404s. `pyric dev` always serves the worker and never sets it;
54
+ * the `@pyric/cli/vite` plugin sets it until it serves the worker (M2).
55
+ */
56
+ /**
57
+ * The in-page sandbox. On the worker path it is NOT the data backend — it
58
+ * stays mounted as the FALLBACK primitive. Worker-mode provider UI reads the
59
+ * worker user directory directly and never constructs a page-local Auth
60
+ * backend.
61
+ */
62
+
63
+ interface ServeDiagnostics {
64
+ sandboxReady: boolean;
65
+ rulesDeployed: boolean;
66
+ databaseRulesDeployed: boolean;
67
+ storageRulesDeployed: boolean;
68
+ rulesHash: string | null;
69
+ databaseRulesHash: string | null;
70
+ storageRulesHash: string | null;
71
+ initError: string | null;
72
+ bridgeConnected: boolean;
73
+ seededDocs: number;
74
+ persistEnabled: boolean;
75
+ /** Epoch ms of the last successful state flush to the server. */
76
+ lastFlushAt: number | null;
77
+ /** True when another tab holds the writer lock — this tab won't persist. */
78
+ persistReadOnly: boolean;
79
+ /** True when a `--seed` fixture was withheld because the sandbox already
80
+ * held restored/lived data (see the seed-docs block below). */
81
+ seedSkipped: boolean;
82
+ }
83
+
84
+ declare global {
85
+ // eslint-disable-next-line no-var
86
+ var __pyricServe: ServeDiagnostics;
87
+ }
88
+
89
+ const diagnostics: ServeDiagnostics = {
90
+ sandboxReady: true,
91
+ rulesDeployed: false,
92
+ databaseRulesDeployed: false,
93
+ storageRulesDeployed: false,
94
+ rulesHash: null,
95
+ databaseRulesHash: null,
96
+ storageRulesHash: null,
97
+ initError: null,
98
+ bridgeConnected: false,
99
+ seededDocs: 0,
100
+ persistEnabled: false,
101
+ lastFlushAt: null,
102
+ persistReadOnly: false,
103
+ seedSkipped: false,
104
+ };
105
+ globalThis.__pyricServe = diagnostics;
106
+ const runtimeStatus = getPyricRuntimeStatus();
107
+
108
+ if (!useWorker) {
109
+ sandbox.onEvent((event) => runtimeStatus.recordSandboxEvents([event]));
110
+ }
111
+
112
+ let bridgeUrlFromPayload: string | null = null;
113
+ let activityTokenFromPayload: string | null = null;
114
+
115
+ // ── init payload: fetch + apply (top-level await — see header) ────────
116
+ // WORKER PATH: skipped — the worker fetches the same init.json and owns
117
+ // rules/seed/persist/capture/session. Running it here too would double-POST
118
+ // captures and fight the worker over the /__pyric/state writer lock.
119
+ if (!useWorker) try {
120
+ const res = await fetch('/__pyric/init.json');
121
+ if (!res.ok) throw new Error(`/__pyric/init.json → ${res.status}`);
122
+ const payload = (await res.json()) as InitPayload;
123
+ bridgeUrlFromPayload = payload.bridgeUrl;
124
+ activityTokenFromPayload = payload.activityToken ?? null;
125
+ // Register RTDB with the persistence registry BEFORE enablePersistence
126
+ // (below) so the restored tree rides the controller blob and is applied
127
+ // during restore-on-attach — same eager-registration reasoning as the
128
+ // worker path (serve-init.ts). `getDatabase(sandbox)` is idempotent
129
+ // (one backend per sandbox) so a later rules/op call reuses it.
130
+ getDatabase(sandbox);
131
+ if (payload.rules) {
132
+ const lint = setRules(sandbox, payload.rules);
133
+ if (lint.parseError) {
134
+ // The server lints before serving, so this is a defensive surface —
135
+ // loud, but don't brick the page: the sandbox keeps its default rules.
136
+ throw new Error(
137
+ `firestore.rules failed to parse in the sandbox: ${JSON.stringify(lint.parseError)}`,
138
+ );
139
+ }
140
+ diagnostics.rulesDeployed = true;
141
+ diagnostics.rulesHash = payload.rulesHash;
142
+ }
143
+ if (payload.databaseRules) {
144
+ rtdbSandbox.setRules(getDatabase(sandbox), payload.databaseRules);
145
+ diagnostics.databaseRulesDeployed = true;
146
+ diagnostics.databaseRulesHash = payload.databaseRulesHash ?? null;
147
+ }
148
+ // Open the ONE per-sandbox storage service eagerly: the FIRST open wins the
149
+ // rules AND the project-scoped IDB name (`pyric-storage:<projectKey>`,
150
+ // issue #359) — a lazy first open from app code would land on the legacy
151
+ // shared database. `projectKey` is absent on older servers → legacy name.
152
+ getStorageSandbox(sandbox, {
153
+ ...(payload.storageRules ? { rules: payload.storageRules } : {}),
154
+ ...(payload.projectKey ? { projectId: payload.projectKey } : {}),
155
+ });
156
+ if (payload.storageRules) {
157
+ diagnostics.storageRulesDeployed = true;
158
+ diagnostics.storageRulesHash = payload.storageRulesHash;
159
+ }
160
+ // Auth users land first in either mode (persist restore or state-file
161
+ // fixture) so restored docs' owner uids resolve in rules and the session
162
+ // restore below has a DB to restore into.
163
+ if (payload.authUsers && payload.authUsers.length > 0) {
164
+ authOps.seedUsers(getAuth(sandbox), payload.authUsers as unknown as SeedUser[]);
165
+ }
166
+ if (!payload.persist && payload.seedState) {
167
+ // ── ephemeral fixture (`--seed <state-file>`): restore the blob through
168
+ // the persistence controller's OWN deserializer (wrapper re-hydration —
169
+ // seedDocuments on raw marker JSON would break instanceof in rules) via
170
+ // a read-only backend. Writes go nowhere: ephemeral stays ephemeral.
171
+ const seedSnap = payload.seedState as {
172
+ firestore?: Record<string, Record<string, unknown>>;
173
+ services?: Record<string, unknown>;
174
+ };
175
+ const fixtureBundle = bundleRecords(
176
+ serializeToBuckets(seedSnap.firestore ?? {}, seedSnap.services ?? {}, 0),
177
+ );
178
+ // NOTE (pre-mortem #6b): this attaches a PERMANENT controller whose
179
+ // write() is a no-op — so every later mutation in this page pays the
180
+ // whole-state serialize cost to feed a sink. pyric exposes no
181
+ // `disablePersistence`/dispose, so a one-shot restore isn't possible from
182
+ // here without a pyric change (tracked as a pyric follow-up). Accepted:
183
+ // fixture pages are demo-sized; the cost is bounded and invisible to
184
+ // correctness.
185
+ await sandbox.enablePersistence({
186
+ key: 'pyric-serve-fixture',
187
+ injectedBackend: recordBackendOverBlob({
188
+ read: async () => fixtureBundle,
189
+ write: async () => {},
190
+ clear: async () => {},
191
+ }),
192
+ });
193
+ const docs = (payload.seedState as { firestore?: Record<string, unknown> }).firestore;
194
+ diagnostics.seededDocs = docs ? Object.keys(docs).length : 0;
195
+ }
196
+ if (payload.persist) {
197
+ // ── persist mode (flow doc section 3c): the substrate is durable. The
198
+ // sandbox's OWN persistence controller with an HTTP backend over
199
+ // /__pyric/state — it owns restore-on-attach (wrapper re-hydration),
200
+ // debounced auto-flush, and the beforeunload safety flush.
201
+ const section = (name: string): string => `/__pyric/state?section=${name}`;
202
+ // Single-writer lock (pre-mortem #3): a per-page id claims the writer
203
+ // role on first flush; a second tab gets 423 and drops to read-only so
204
+ // it can't erase this tab's world. The server frees a stale lock, so a
205
+ // reload after the writer closed can reclaim it.
206
+ const writerId =
207
+ typeof crypto !== 'undefined' && crypto.randomUUID ? crypto.randomUUID() : `w-${Date.now()}`;
208
+ const writerHeaders = { 'content-type': 'application/json', 'x-pyric-writer': writerId };
209
+ let readOnly = false;
210
+ const lostWriterLock = (): void => {
211
+ if (readOnly) return;
212
+ readOnly = true;
213
+ diagnostics.persistReadOnly = true;
214
+ console.warn(
215
+ '[pyric dev] another tab is the persist writer — THIS tab is read-only ' +
216
+ '(your changes here will NOT be saved). Close the other tab and reload to take over.',
217
+ );
218
+ };
219
+ await sandbox.enablePersistence({
220
+ key: 'pyric-serve',
221
+ injectedBackend: recordBackendOverBlob({
222
+ async read() {
223
+ const res = await fetch(section('firestore'));
224
+ return res.status === 200 ? await res.text() : null;
225
+ },
226
+ async write(value) {
227
+ if (readOnly) return; // a non-writer tab silently no-ops its flushes
228
+ const res = await fetch(section('firestore'), {
229
+ method: 'POST',
230
+ headers: writerHeaders,
231
+ body: value,
232
+ // The controller's beforeunload flush fires THIS write as the
233
+ // page is leaving; a plain fetch is aborted on unload (pre-mortem
234
+ // #1 — the "crash-only" claim was wrong). `keepalive` lets a
235
+ // small final flush survive unload. It's capped (~64KB across
236
+ // all keepalive requests), so large states skip it and warn
237
+ // once — those lose the final unsaved delta on tab close
238
+ // (reload-based flushes are unaffected).
239
+ keepalive: keepaliveSafe(value),
240
+ });
241
+ if (res.status === 423) return lostWriterLock();
242
+ if (!res.ok) throw new Error(`state flush → ${res.status}`);
243
+ diagnostics.lastFlushAt = Date.now();
244
+ },
245
+ async clear() {
246
+ if (readOnly) return;
247
+ await fetch(section('firestore'), { method: 'POST', headers: writerHeaders, body: 'null' });
248
+ },
249
+ }),
250
+ });
251
+ diagnostics.persistEnabled = true;
252
+
253
+ // Heartbeat: keep an alive-but-idle writer's lock fresh. PUT refreshes
254
+ // the lock WITHOUT writing state (a POST would clobber). Release on
255
+ // pagehide so another tab can take over promptly.
256
+ const heartbeat = setInterval(() => {
257
+ if (readOnly) return;
258
+ void fetch('/__pyric/state', { method: 'PUT', headers: writerHeaders }).then((res) => {
259
+ if (res.status === 423) {
260
+ lostWriterLock();
261
+ clearInterval(heartbeat);
262
+ }
263
+ }, () => {});
264
+ }, 20_000);
265
+ if (typeof window !== 'undefined') {
266
+ window.addEventListener('pagehide', () => {
267
+ clearInterval(heartbeat);
268
+ if (!readOnly) {
269
+ fetch('/__pyric/state', { method: 'DELETE', headers: writerHeaders, keepalive: true }).catch(() => {});
270
+ }
271
+ });
272
+ }
273
+
274
+ // Auth user-DB changes flush separately (the controller's blob is
275
+ // firestore-only). Debounced; exportUsers→seedUsers round-trips.
276
+ const auth = getAuth(sandbox);
277
+ let authFlushTimer: ReturnType<typeof setTimeout> | null = null;
278
+ authOps.subscribeUsers(auth, () => {
279
+ if (readOnly) return;
280
+ if (authFlushTimer) clearTimeout(authFlushTimer);
281
+ authFlushTimer = setTimeout(() => {
282
+ void fetch(section('auth'), {
283
+ method: 'POST',
284
+ headers: writerHeaders,
285
+ body: JSON.stringify({ users: authOps.exportUsers(auth) }),
286
+ }).then(
287
+ (res) => {
288
+ if (res.status === 423) lostWriterLock();
289
+ else if (res.ok) diagnostics.lastFlushAt = Date.now();
290
+ },
291
+ (e) => console.warn('[pyric dev] auth state flush failed:', e),
292
+ );
293
+ }, 500);
294
+ });
295
+ }
296
+ if (payload.capture) {
297
+ // ── capture mode (the write-side of the pyric verify loop): whenever
298
+ // the sandbox changes, push a snapshot of the full session fixture
299
+ // (rules + history + firestore state) to /__pyric/capture. The server
300
+ // writes it verbatim to `.pyric/last-session.json` so `pyric verify`
301
+ // can replay without any extra arguments. This is independent of
302
+ // --persist — capture is about the verify loop, persist is about
303
+ // cross-reload durability.
304
+ const flushCapture = (): void => {
305
+ const rtdbState =
306
+ payload.databaseRules || sandbox.history().some((event) => event.service === 'rtdb')
307
+ ? rtdbSandbox.snapshotState(getDatabase(sandbox))
308
+ : undefined;
309
+ const auth = getAuth(sandbox);
310
+ const body = JSON.stringify(buildVerifyFixture({
311
+ sandbox,
312
+ firestoreRules: payload.rules,
313
+ rtdbRules: payload.databaseRules ?? null,
314
+ rtdbState,
315
+ rtdbDatabaseUrl: payload.databaseUrl ?? null,
316
+ authState: {
317
+ users: authOps.exportUsers(auth),
318
+ currentUser: auth.currentUser,
319
+ },
320
+ }));
321
+ fetch('/__pyric/capture', {
322
+ method: 'POST',
323
+ headers: { 'content-type': 'application/json' },
324
+ body,
325
+ keepalive: keepaliveSafe(body),
326
+ }).catch(() => {});
327
+ };
328
+
329
+ // Debounced flush on every sandbox event — coalesces rapid writes (e.g.
330
+ // seeding multiple docs) into a single push. 400ms matches the cadence
331
+ // of the persist auth flush; small enough to feel live, large enough to
332
+ // avoid one-POST-per-write on bulk ops.
333
+ let captureTimer: ReturnType<typeof setTimeout> | null = null;
334
+ sandbox.onEvent(() => {
335
+ if (captureTimer) clearTimeout(captureTimer);
336
+ captureTimer = setTimeout(flushCapture, 400);
337
+ });
338
+
339
+ // Unload flush — best-effort, keepalive. Separate from any persist
340
+ // pagehide listener so they don't interfere.
341
+ if (typeof window !== 'undefined') {
342
+ window.addEventListener('pagehide', () => {
343
+ flushCapture();
344
+ });
345
+ }
346
+ }
347
+ if (payload.seed && Object.keys(payload.seed).length > 0) {
348
+ // A seed fixture applies only into an empty home — mirrors the worker's
349
+ // guard (serve/worker/serve-init.ts): by this point any --persist restore
350
+ // above has already run, so an existing document means lived/restored
351
+ // data, not a blank slate. Never stomp it with a fixture.
352
+ const existing = Object.keys(snapshotDocuments(sandbox)).length > 0;
353
+ if (existing) {
354
+ diagnostics.seedSkipped = true;
355
+ console.info(
356
+ '[pyric dev] --seed skipped: the sandbox already has restored data — the fixture would ' +
357
+ 'have overwritten it. Use `--persist --fresh` to discard existing state and re-seed.',
358
+ );
359
+ } else {
360
+ // Admin-style fixture load (bypasses rules) — runs before app code
361
+ // (top-level await), so the app's first render sees the seeded state.
362
+ seedDocuments(sandbox, payload.seed);
363
+ diagnostics.seededDocs = Object.keys(payload.seed).length;
364
+ }
365
+ }
366
+ } catch (e) {
367
+ diagnostics.initError = e instanceof Error ? e.message : String(e);
368
+ runtimeStatus.reportError(e, 'runtime');
369
+ console.error(
370
+ '[pyric dev] init failed — the sandbox is running WITHOUT your project rules:',
371
+ diagnostics.initError,
372
+ );
373
+ }
374
+
375
+ // Unsupported/forced-in-page browsers own a real page-local sandbox rather
376
+ // than the SharedWorker backend, so they install the same default-on guard at
377
+ // this feed seam. Top-level await keeps this in place before application code.
378
+ if (!useWorker && activityTokenFromPayload) {
379
+ setupFirebaseActivityGuard(
380
+ {
381
+ history: () => sandbox.history(),
382
+ subscribe: (listener) => sandbox.onEvent(listener),
383
+ },
384
+ fetch,
385
+ activityTokenFromPayload,
386
+ );
387
+ }
388
+
389
+ // ── provenance (flow doc section 3a): make the shim's presence unmistakable.
390
+ // Source says `firebase/*`; what runs is the pyric sandbox — say so loudly
391
+ // once, and explain any stack frame that points into /__pyric/sdk/. ────────
392
+ console.info(
393
+ `[pyric dev] firebase/* on this page is served by the pyric sandbox` +
394
+ (useWorker
395
+ ? ' in a SharedWorker (one backend for all tabs; rules/seed/persist owned by the worker)'
396
+ : diagnostics.rulesHash || diagnostics.databaseRulesHash || diagnostics.storageRulesHash
397
+ ? ' (project rules loaded)'
398
+ : ' (no project rules)') +
399
+ ` — diagnostics: globalThis.__pyricServe`,
400
+ );
401
+
402
+ let provenanceHintShown = false;
403
+ function explainSandboxFrame(stackOrUrl: string | undefined): boolean {
404
+ if (!stackOrUrl || !stackOrUrl.includes('/__pyric/sdk/')) return false;
405
+ if (!provenanceHintShown) {
406
+ provenanceHintShown = true;
407
+ console.info(
408
+ '[pyric dev] the error above originates in the pyric sandbox shim serving firebase/*, ' +
409
+ 'not the real Firebase SDK — behavior can differ where COMPAT coverage is incomplete.',
410
+ );
411
+ }
412
+ return true;
413
+ }
414
+ if (typeof window !== 'undefined') {
415
+ // Stack containment is useful provenance context, but it is NOT an ownership
416
+ // boundary: an app callback thrown from an SDK caller also contains an SDK
417
+ // frame. Explicit sandbox events and runtime catches feed the status model.
418
+ window.addEventListener('error', (e) =>
419
+ explainSandboxFrame(e.error instanceof Error ? (e.error.stack ?? e.filename) : e.filename),
420
+ );
421
+ window.addEventListener('unhandledrejection', (e) =>
422
+ explainSandboxFrame(e.reason instanceof Error ? e.reason.stack : undefined),
423
+ );
424
+ }
425
+
426
+ // ── bridge peer (only when `pyric dev --bridge` put a URL in the payload;
427
+ // dynamic import so bridge-less pages never load the client chunk) ─────
428
+ async function connectBridgePeer(rawUrl: string): Promise<void> {
429
+ // Re-anchor the bridge WS to THIS page's origin so it reaches the server the
430
+ // page was actually served from over Tailscale / a LAN IP / https, not the
431
+ // server's baked-in localhost. See bridge-url.ts.
432
+ const url = toPageOriginWsUrl(rawUrl, window.location);
433
+ const { connectBridge } = await import('../../bridge/client/bridge.js');
434
+ // On the worker path, route agent tool-calls THROUGH the SharedWorker so the
435
+ // agent shares the one sandbox the app + Studio use (no separate in-page
436
+ // backend). Off the worker path (in-page fallback), dispatch in-page as before.
437
+ if (useWorker && workerDb) {
438
+ const wdb = workerDb;
439
+ connectBridge(sandbox, {
440
+ url,
441
+ dispatcher: (_sandbox, name, args) => workerCallTool(wdb, name, args),
442
+ // Generic worker relay (remote sandbox, slice 1): server-side Node code
443
+ // (`connectRemoteSandbox`) reaches THIS page's SharedWorker through the
444
+ // bridge — ops and snap-delivering subscriptions pass straight through
445
+ // to the one sandbox the app + Studio + agent share.
446
+ workerRelay: {
447
+ op: (op) => relayWorkerOp(wdb, op),
448
+ subscribe: (sub, onValue) => relayWorkerSub(wdb, sub, onValue),
449
+ },
450
+ });
451
+ } else {
452
+ connectBridge(sandbox, { url });
453
+ }
454
+ diagnostics.bridgeConnected = true;
455
+ console.info('[pyric dev] sandbox registered with the MCP bridge at', url);
456
+ }
457
+ if (bridgeUrlFromPayload) {
458
+ // In-page path: bridgeUrlFromPayload came from the (already-blocking) init
459
+ // block above, so connect inline.
460
+ try {
461
+ await connectBridgePeer(bridgeUrlFromPayload);
462
+ } catch (e) {
463
+ runtimeStatus.reportError(e, 'runtime');
464
+ console.error('[pyric dev] bridge connect failed:', e instanceof Error ? e.message : String(e));
465
+ }
466
+ } else if (useWorker) {
467
+ // Worker path: the worker owns serve-init, so the page skipped the init.json
468
+ // fetch. Discover the bridge URL (the agent routes its tool-calls THROUGH the
469
+ // worker) in a FIRE-AND-FORGET task so app boot is NEVER blocked — runtime.ts
470
+ // is on the load-bearing top-level-await path, and the agent connecting a beat
471
+ // later is fine. Bridge-less pages just read a null bridgeUrl and stop.
472
+ void (async () => {
473
+ try {
474
+ const res = await fetch('/__pyric/init.json');
475
+ const url = res.ok ? ((await res.json()) as InitPayload).bridgeUrl : null;
476
+ if (url) await connectBridgePeer(url);
477
+ } catch (e) {
478
+ runtimeStatus.reportError(e, 'runtime');
479
+ console.error('[pyric dev] bridge connect failed:', e instanceof Error ? e.message : String(e));
480
+ }
481
+ })();
482
+ }
483
+
484
+ // ── cross-tab realtime sync — wire AFTER sandbox + auth are fully set up ──────
485
+ //
486
+ // Two independent channels, two independent kinds of state:
487
+ //
488
+ // Channel 1 — Firestore writes (`pyric:serve:tabsync`):
489
+ // `sandbox.enableTabSync` owns the channel entirely. It broadcasts every
490
+ // committed Firestore write event to peer tabs and runs the hello/state
491
+ // late-join handshake so a freshly-opened tab inherits the current
492
+ // Firestore documents. A write in Tab A fires `onSnapshot` listeners in Tab B
493
+ // — restoring production's cross-client realtime without a server.
494
+ //
495
+ // Channel 2 — Auth state (`pyric:serve:auth-sync`):
496
+ // Auth lives outside the Firestore environment so `enableTabSync` can't
497
+ // carry it. `wireAuthTabSync` bridges sign-in/sign-out/user-DB changes
498
+ // over its own BroadcastChannel using a full-state protocol (see
499
+ // `tab-sync-wiring.ts` for the detailed protocol + echo-guard rationale).
500
+ //
501
+ // Both are no-ops in non-browser environments (`BroadcastChannel` absent).
502
+ //
503
+ // WORKER PATH: retired. The SharedWorker IS the single backend for all tabs, so
504
+ // cross-tab Firestore + auth are automatic — the in-page sandbox these channels
505
+ // would sync isn't the data backend here. Kept ONLY for the in-page fallback
506
+ // (the tier the plan designates for browsers without SharedWorker).
507
+ if (!useWorker && typeof BroadcastChannel !== 'undefined') {
508
+ // 1. Firestore cross-tab — library primitive does the heavy lifting.
509
+ sandbox.enableTabSync({
510
+ channel: new BroadcastChannel('pyric:serve:tabsync'),
511
+ });
512
+
513
+ // 2. Auth cross-tab — our own bridge (see tab-sync-wiring.ts).
514
+ // Dynamic import keeps the module out of the critical path; the channel
515
+ // is opened synchronously above so `hello` is posted as soon as the
516
+ // listener is wired (wireAuthTabSync handles ordering internally).
517
+ void import('./tab-sync-wiring.js').then(({ wireAuthTabSync }) => {
518
+ wireAuthTabSync(
519
+ getAuth(sandbox),
520
+ // Cast: authOps's generics are narrowed to `Auth` which is exactly what
521
+ // wireAuthTabSync expects; `as` here avoids a deep generic unification
522
+ // that TypeScript can't resolve across module boundaries.
523
+ authOps as import('./tab-sync-wiring.js').AuthOps,
524
+ onAuthStateChanged,
525
+ signOut,
526
+ );
527
+ });
528
+ }
529
+
530
+ // ── rules hot-reload (SSE) — `pyric dev` watches firestore.rules and
531
+ // broadcasts; we re-deploy in place, no page refresh. EventSource is
532
+ // browser-only; guarded so the bundle stays inert under other runtimes. ──
533
+ // IN-PAGE PATH ONLY: open a per-tab SSE to re-deploy rules to the in-page
534
+ // sandbox. On the WORKER path the SharedWorker owns ONE hot-reload stream for
535
+ // the whole origin (see entry.ts), so tabs open NO SSE connection — multi-tab
536
+ // pages would otherwise exhaust Chrome's ~6-connections-per-origin cap and a
537
+ // later tab's navigation would hang until an earlier tab closed.
538
+ if (!useWorker && typeof EventSource !== 'undefined') {
539
+ const events = new EventSource('/__pyric/events');
540
+ events.addEventListener('rules-changed', (e) => {
541
+ try {
542
+ const { rules, rulesHash } = JSON.parse((e as MessageEvent).data as string) as {
543
+ rules: string;
544
+ rulesHash: string;
545
+ };
546
+ const lint = setRules(sandbox, rules);
547
+ if (lint.parseError) throw new Error(JSON.stringify(lint.parseError));
548
+ diagnostics.rulesDeployed = true;
549
+ diagnostics.rulesHash = rulesHash;
550
+ console.info(`[pyric dev] firestore.rules hot-reloaded (hash ${rulesHash})`);
551
+ } catch (err) {
552
+ runtimeStatus.reportError(err, 'runtime');
553
+ console.error('[pyric dev] rules hot-reload failed:', err instanceof Error ? err.message : String(err));
554
+ }
555
+ });
556
+ }
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Auth session persistence for `pyric dev` — the one genuine
3
+ * client-fidelity item in the persistence model (flow doc section 3c): real
4
+ * Firebase keeps you signed in across reloads by DEFAULT
5
+ * (`browserLocalPersistence`), so the served sandbox does too.
6
+ *
7
+ * The user *database* persists with the substrate (`--persist`); the
8
+ * *session* persists like the real client — independent of data mode, in
9
+ * web storage, honoring `setPersistence` semantics:
10
+ *
11
+ * LOCAL (default) → localStorage (survives reload + browser restart)
12
+ * SESSION → sessionStorage (survives reload, not the tab)
13
+ * NONE → nothing stored
14
+ *
15
+ * A restored session only resolves when the referenced uid still exists in
16
+ * the sandbox user DB — so ephemeral mode drops helper-created sessions on
17
+ * reload, consistently (`sandbox.restoreSession` throws, we clear).
18
+ *
19
+ * Pure over injected Storage objects so the logic is bun-testable; the
20
+ * browser wiring (real storages, `onAuthStateChanged` recording, restore at
21
+ * init) lives in the entries that import this.
22
+ */
23
+
24
+ export type SessionMode = 'LOCAL' | 'SESSION' | 'NONE';
25
+
26
+ const DEFAULT_KEY = 'pyric:serve:auth-session';
27
+
28
+ export interface SessionStores {
29
+ local: Pick<Storage, 'getItem' | 'setItem' | 'removeItem'>;
30
+ session: Pick<Storage, 'getItem' | 'setItem' | 'removeItem'>;
31
+ }
32
+
33
+ export interface StoredSession {
34
+ uid: string;
35
+ }
36
+
37
+ export class SessionStore {
38
+ private mode: SessionMode = 'LOCAL'; // firebase's default persistence
39
+ private readonly key: string;
40
+
41
+ constructor(
42
+ private readonly stores: SessionStores,
43
+ appName = '[DEFAULT]',
44
+ ) {
45
+ this.key = appName === '[DEFAULT]'
46
+ ? DEFAULT_KEY
47
+ : `${DEFAULT_KEY}:${encodeURIComponent(appName)}`;
48
+ }
49
+
50
+ /** `setPersistence` parity: switch the backing store and MIGRATE any
51
+ * current session into it (the real SDK carries the session over). */
52
+ setMode(mode: SessionMode): void {
53
+ const current = this.load();
54
+ this.clear();
55
+ this.mode = mode;
56
+ if (current) this.save(current.uid);
57
+ }
58
+
59
+ save(uid: string): void {
60
+ this.clear(); // a session lives in exactly one store
61
+ if (this.mode === 'NONE') return;
62
+ this.backing().setItem(this.key, JSON.stringify({ uid } satisfies StoredSession));
63
+ }
64
+
65
+ /** Reads BOTH storages (localStorage first — matches lookup order when a
66
+ * prior page used a different mode). Restoring also restores the mode:
67
+ * the initial Auth observer resaves the user, and must not migrate a
68
+ * SESSION record into the default LOCAL slot. */
69
+ load(): StoredSession | null {
70
+ for (const [mode, store] of [
71
+ ['LOCAL', this.stores.local],
72
+ ['SESSION', this.stores.session],
73
+ ] as const) {
74
+ const raw = store.getItem(this.key);
75
+ if (!raw) continue;
76
+ try {
77
+ const parsed = JSON.parse(raw) as StoredSession;
78
+ if (parsed && typeof parsed.uid === 'string') {
79
+ this.mode = mode;
80
+ return parsed;
81
+ }
82
+ } catch {
83
+ store.removeItem(this.key); // corrupt → drop, never throw at page init
84
+ }
85
+ }
86
+ return null;
87
+ }
88
+
89
+ clear(): void {
90
+ this.stores.local.removeItem(this.key);
91
+ this.stores.session.removeItem(this.key);
92
+ }
93
+
94
+ private backing(): SessionStores['local'] {
95
+ return this.mode === 'SESSION' ? this.stores.session : this.stores.local;
96
+ }
97
+ }