@pyric/cli 0.1.0-alpha.18 → 0.1.0-alpha.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (356) hide show
  1. package/README.md +14 -9
  2. package/dist/bridge/server/mcp-contract.d.ts +2 -2
  3. package/dist/bridge/server/mcp-contract.d.ts.map +1 -1
  4. package/dist/bridge/server/mcp-contract.js +3 -0
  5. package/dist/bridge/server/mcp-contract.js.map +1 -1
  6. package/dist/cli/index.d.ts +3 -2
  7. package/dist/cli/index.d.ts.map +1 -1
  8. package/dist/cli/index.js +51 -42
  9. package/dist/cli/index.js.map +1 -1
  10. package/dist/cli/mcp-proxy.d.ts.map +1 -1
  11. package/dist/cli/mcp-proxy.js +3 -3
  12. package/dist/cli/mcp-proxy.js.map +1 -1
  13. package/dist/cli/parse-args.d.ts +1 -1
  14. package/dist/cli/parse-args.d.ts.map +1 -1
  15. package/dist/cli/parse-args.js +51 -15
  16. package/dist/cli/parse-args.js.map +1 -1
  17. package/dist/cli/pyric-config.d.ts +24 -0
  18. package/dist/cli/pyric-config.d.ts.map +1 -0
  19. package/dist/cli/pyric-config.js +28 -0
  20. package/dist/cli/pyric-config.js.map +1 -0
  21. package/dist/cli/rules.d.ts +1 -0
  22. package/dist/cli/rules.d.ts.map +1 -1
  23. package/dist/cli/rules.js +18 -4
  24. package/dist/cli/rules.js.map +1 -1
  25. package/dist/cli/{dev-runner.d.ts → sandbox-runner.d.ts} +33 -36
  26. package/dist/cli/sandbox-runner.d.ts.map +1 -0
  27. package/dist/cli/{dev-runner.js → sandbox-runner.js} +90 -55
  28. package/dist/cli/sandbox-runner.js.map +1 -0
  29. package/dist/cli/serve.d.ts +6 -4
  30. package/dist/cli/serve.d.ts.map +1 -1
  31. package/dist/cli/serve.js +99 -40
  32. package/dist/cli/serve.js.map +1 -1
  33. package/dist/cli/service-command-records/storage-rules-resolve.d.ts +4 -0
  34. package/dist/cli/service-command-records/storage-rules-resolve.d.ts.map +1 -0
  35. package/dist/cli/service-command-records/storage-rules-resolve.js +3 -0
  36. package/dist/cli/service-command-records/storage-rules-resolve.js.map +1 -0
  37. package/dist/cli/service-commands.generated.d.ts +3 -0
  38. package/dist/cli/service-commands.generated.d.ts.map +1 -1
  39. package/dist/cli/service-commands.generated.js +2 -0
  40. package/dist/cli/service-commands.generated.js.map +1 -1
  41. package/dist/cli/snapshot.js +5 -5
  42. package/dist/cli/snapshot.js.map +1 -1
  43. package/dist/cli/verify.js +1 -1
  44. package/dist/cli/verify.js.map +1 -1
  45. package/dist/functions-rtdb/development-runtime.js +1 -1
  46. package/dist/functions-rtdb/development-runtime.js.map +1 -1
  47. package/dist/functions-rtdb/project.js +8 -8
  48. package/dist/functions-rtdb/project.js.map +1 -1
  49. package/dist/next/guard.js +1 -1
  50. package/dist/next/guard.js.map +1 -1
  51. package/dist/remote/index.d.ts +1 -1
  52. package/dist/remote/index.js +9 -9
  53. package/dist/remote/index.js.map +1 -1
  54. package/dist/serve/bundler.js +10 -10
  55. package/dist/serve/bundler.js.map +1 -1
  56. package/dist/serve/entries/ai.d.ts.map +1 -1
  57. package/dist/serve/entries/ai.js +27 -1
  58. package/dist/serve/entries/ai.js.map +1 -1
  59. package/dist/serve/entries/auth-helper-dom.js +1 -1
  60. package/dist/serve/entries/auth-helper-dom.js.map +1 -1
  61. package/dist/serve/entries/auth-helper-runtime.js +1 -1
  62. package/dist/serve/entries/auth-helper-runtime.js.map +1 -1
  63. package/dist/serve/entries/firestore.js +3 -3
  64. package/dist/serve/entries/firestore.js.map +1 -1
  65. package/dist/serve/entries/keepalive.js +1 -1
  66. package/dist/serve/entries/keepalive.js.map +1 -1
  67. package/dist/serve/entries/runtime.js +21 -14
  68. package/dist/serve/entries/runtime.js.map +1 -1
  69. package/dist/serve/entries/storage.js +1 -1
  70. package/dist/serve/entries/storage.js.map +1 -1
  71. package/dist/serve/entries/worker-runtime.js +1 -1
  72. package/dist/serve/entries/worker-runtime.js.map +1 -1
  73. package/dist/serve/init-payload.d.ts +4 -0
  74. package/dist/serve/init-payload.d.ts.map +1 -1
  75. package/dist/serve/namespace.d.ts +6 -0
  76. package/dist/serve/namespace.d.ts.map +1 -1
  77. package/dist/serve/namespace.js +36 -5
  78. package/dist/serve/namespace.js.map +1 -1
  79. package/dist/serve/rules.d.ts +3 -3
  80. package/dist/serve/rules.d.ts.map +1 -1
  81. package/dist/serve/rules.js +56 -25
  82. package/dist/serve/rules.js.map +1 -1
  83. package/dist/serve/runtime/chip.d.ts.map +1 -1
  84. package/dist/serve/runtime/chip.js +32 -1
  85. package/dist/serve/runtime/chip.js.map +1 -1
  86. package/dist/serve/runtime/manifest.d.ts +1 -1
  87. package/dist/serve/runtime/manifest.d.ts.map +1 -1
  88. package/dist/serve/runtime/manifest.js +1 -1
  89. package/dist/serve/runtime/manifest.js.map +1 -1
  90. package/dist/serve/runtime/status.d.ts.map +1 -1
  91. package/dist/serve/runtime/status.js +23 -0
  92. package/dist/serve/runtime/status.js.map +1 -1
  93. package/dist/serve/sandbox-session.d.ts +1 -0
  94. package/dist/serve/sandbox-session.d.ts.map +1 -1
  95. package/dist/serve/sandbox-session.js +10 -4
  96. package/dist/serve/sandbox-session.js.map +1 -1
  97. package/dist/serve/server.d.ts +7 -0
  98. package/dist/serve/server.d.ts.map +1 -1
  99. package/dist/serve/server.js +15 -1
  100. package/dist/serve/server.js.map +1 -1
  101. package/dist/serve/site-ui/404.html +1 -1
  102. package/dist/serve/site-ui/_astro/{RulesCodeEditor.CzwHdCi9.js → RulesCodeEditor.XtDmHOlN.js} +1 -1
  103. package/dist/serve/site-ui/_astro/_example_.B9DG9HLJ.css +1 -0
  104. package/dist/serve/site-ui/_astro/_slug_.Da5VLhW1.css +1 -0
  105. package/dist/serve/site-ui/_astro/_studio_.BnfYCKoI.css +1 -0
  106. package/dist/serve/site-ui/_astro/app.B52xr-DK.js +1 -0
  107. package/dist/serve/site-ui/_astro/app.DWBraPUw.js +12 -0
  108. package/dist/serve/site-ui/_astro/app.pMSnN6Qw.css +1 -0
  109. package/dist/serve/site-ui/_astro/chess-showcase.B72XYeoh.js +354 -0
  110. package/dist/serve/site-ui/_astro/{example-runtime.B0byNQOl.js → example-runtime.C25_lx6Z.js} +2 -26
  111. package/dist/serve/site-ui/_astro/index.Tb-31efc.css +1 -0
  112. package/dist/serve/site-ui/_astro/index.UkCBr-_0.css +1 -0
  113. package/dist/serve/site-ui/_astro/sandbox-controls.DEpnKg-O.js +1169 -0
  114. package/dist/serve/site-ui/_astro/seed.Co0yUJY5.js +20 -0
  115. package/dist/serve/site-ui/_astro/writes.rpjrFzmu.js +102 -0
  116. package/dist/serve/site-ui/auth/index.html +5 -3
  117. package/dist/serve/site-ui/david-east.jpg +0 -0
  118. package/dist/serve/site-ui/docs/_rhythm/index.html +6 -3
  119. package/dist/serve/site-ui/docs/_rhythm.md +1 -1
  120. package/dist/serve/site-ui/docs/agent/set-up-your-agent/index.html +45 -17
  121. package/dist/serve/site-ui/docs/agent/set-up-your-agent.md +20 -17
  122. package/dist/serve/site-ui/docs/agent/watch-and-review/index.html +6 -5
  123. package/dist/serve/site-ui/docs/agent/watch-and-review.md +1 -5
  124. package/dist/serve/site-ui/docs/agent/work-with-an-agent/index.html +8 -5
  125. package/dist/serve/site-ui/docs/agent/work-with-an-agent.md +4 -4
  126. package/dist/serve/site-ui/docs/ai-compat/index.html +5 -2
  127. package/dist/serve/site-ui/docs/api-reference/index.html +6 -2
  128. package/dist/serve/site-ui/docs/api-reference.md +1 -0
  129. package/dist/serve/site-ui/docs/app-compat/index.html +5 -2
  130. package/dist/serve/site-ui/docs/auth-compat/index.html +5 -2
  131. package/dist/serve/site-ui/docs/build/ai-logic/index.html +5 -2
  132. package/dist/serve/site-ui/docs/build/authentication/index.html +7 -4
  133. package/dist/serve/site-ui/docs/build/authentication.md +2 -2
  134. package/dist/serve/site-ui/docs/build/cloud-firestore/index.html +34 -53
  135. package/dist/serve/site-ui/docs/build/cloud-firestore.md +40 -36
  136. package/dist/serve/site-ui/docs/build/cloud-messaging/index.html +5 -2
  137. package/dist/serve/site-ui/docs/build/cloud-storage/index.html +6 -3
  138. package/dist/serve/site-ui/docs/build/cloud-storage.md +1 -1
  139. package/dist/serve/site-ui/docs/build/realtime-database/index.html +9 -6
  140. package/dist/serve/site-ui/docs/build/realtime-database.md +4 -4
  141. package/dist/serve/site-ui/docs/conformance-scores/index.html +5 -2
  142. package/dist/serve/site-ui/docs/create-pyric-reference-api/index.html +6 -3
  143. package/dist/serve/site-ui/docs/create-pyric-reference-api.md +1 -1
  144. package/dist/serve/site-ui/docs/database-compat/index.html +5 -2
  145. package/dist/serve/site-ui/docs/examples/chess/index.html +649 -250
  146. package/dist/serve/site-ui/docs/examples/chess.md +45 -16
  147. package/dist/serve/site-ui/docs/examples/index.html +6 -3
  148. package/dist/serve/site-ui/docs/firestore-compat/index.html +5 -2
  149. package/dist/serve/site-ui/docs/functions-rtdb-compat/index.html +5 -2
  150. package/dist/serve/site-ui/docs/get-started/how-the-swap-works/index.html +9 -6
  151. package/dist/serve/site-ui/docs/get-started/how-the-swap-works.md +5 -5
  152. package/dist/serve/site-ui/docs/get-started/nextjs/index.html +9 -6
  153. package/dist/serve/site-ui/docs/get-started/nextjs.md +4 -4
  154. package/dist/serve/site-ui/docs/get-started/start-building/index.html +41 -10
  155. package/dist/serve/site-ui/docs/get-started/start-building.md +21 -10
  156. package/dist/serve/site-ui/docs/get-started/vite/index.html +6 -3
  157. package/dist/serve/site-ui/docs/get-started/vite.md +1 -1
  158. package/dist/serve/site-ui/docs/index.json +203 -168
  159. package/dist/serve/site-ui/docs/messaging-compat/index.html +5 -2
  160. package/dist/serve/site-ui/docs/observe/resolve-runtime-status/index.html +5 -2
  161. package/dist/serve/site-ui/docs/observe/see-whats-happening/index.html +6 -4
  162. package/dist/serve/site-ui/docs/observe/see-whats-happening.md +2 -4
  163. package/dist/serve/site-ui/docs/observe/shape-your-data/index.html +9 -6
  164. package/dist/serve/site-ui/docs/observe/shape-your-data.md +4 -4
  165. package/dist/serve/site-ui/docs/overview/index.html +16 -10
  166. package/dist/serve/site-ui/docs/overview.md +19 -11
  167. package/dist/serve/site-ui/docs/pyric-admin-app-reference-api/index.html +5 -2
  168. package/dist/serve/site-ui/docs/pyric-admin-auth-reference-api/index.html +5 -2
  169. package/dist/serve/site-ui/docs/pyric-admin-database-reference-api/index.html +5 -2
  170. package/dist/serve/site-ui/docs/pyric-admin-firestore-reference-api/index.html +8 -5
  171. package/dist/serve/site-ui/docs/pyric-admin-firestore-reference-api.md +3 -3
  172. package/dist/serve/site-ui/docs/pyric-admin-messaging-reference-api/index.html +5 -2
  173. package/dist/serve/site-ui/docs/pyric-admin-reference-api/index.html +501 -0
  174. package/dist/serve/site-ui/docs/pyric-admin-reference-api.md +587 -0
  175. package/dist/serve/site-ui/docs/pyric-admin-storage-reference-api/index.html +5 -2
  176. package/dist/serve/site-ui/docs/pyric-ai-reference-api/index.html +5 -2
  177. package/dist/serve/site-ui/docs/pyric-ai-scripting-reference-api/index.html +5 -2
  178. package/dist/serve/site-ui/docs/pyric-app-reference-api/index.html +5 -2
  179. package/dist/serve/site-ui/docs/pyric-auth-reference-api/index.html +5 -2
  180. package/dist/serve/site-ui/docs/pyric-cli-assurance-browser-reference-api/index.html +5 -2
  181. package/dist/serve/site-ui/docs/pyric-cli-assurance-reference-api/index.html +5 -2
  182. package/dist/serve/site-ui/docs/pyric-cli-bridge-client-reference-api/index.html +5 -2
  183. package/dist/serve/site-ui/docs/pyric-cli-bridge-reference-api/index.html +5 -2
  184. package/dist/serve/site-ui/docs/pyric-cli-conformance-browser-reference-api/index.html +5 -2
  185. package/dist/serve/site-ui/docs/pyric-cli-conformance-docs-reference-api/index.html +5 -2
  186. package/dist/serve/site-ui/docs/pyric-cli-conformance-reference-api/index.html +5 -2
  187. package/dist/serve/site-ui/docs/pyric-cli-credentials-node-reference-api/index.html +5 -2
  188. package/dist/serve/site-ui/docs/pyric-cli-discover-reference-api/index.html +5 -2
  189. package/dist/serve/site-ui/docs/pyric-cli-next-reference-api/index.html +5 -2
  190. package/dist/serve/site-ui/docs/pyric-cli-register-app-bridge-reference-api/index.html +5 -2
  191. package/dist/serve/site-ui/docs/pyric-cli-register-reference-api/index.html +5 -2
  192. package/dist/serve/site-ui/docs/pyric-cli-remote-reference-api/index.html +6 -3
  193. package/dist/serve/site-ui/docs/pyric-cli-remote-reference-api.md +1 -1
  194. package/dist/serve/site-ui/docs/pyric-cli-serve-worker-reference-api/index.html +5 -2
  195. package/dist/serve/site-ui/docs/pyric-cli-verify-reference-api/index.html +5 -2
  196. package/dist/serve/site-ui/docs/pyric-cli-vite-reference-api/index.html +5 -2
  197. package/dist/serve/site-ui/docs/pyric-database-reference-api/index.html +166 -95
  198. package/dist/serve/site-ui/docs/pyric-database-reference-api.md +107 -1
  199. package/dist/serve/site-ui/docs/pyric-firestore-reference-api/index.html +5 -2
  200. package/dist/serve/site-ui/docs/pyric-messaging-reference-api/index.html +10 -4
  201. package/dist/serve/site-ui/docs/pyric-messaging-reference-api.md +5 -2
  202. package/dist/serve/site-ui/docs/pyric-messaging-sw-reference-api/index.html +10 -4
  203. package/dist/serve/site-ui/docs/pyric-messaging-sw-reference-api.md +5 -2
  204. package/dist/serve/site-ui/docs/pyric-rules-reference-api/index.html +5 -2
  205. package/dist/serve/site-ui/docs/pyric-sandbox-database-reference-api/index.html +5 -2
  206. package/dist/serve/site-ui/docs/pyric-sandbox-firestore-reference-api/index.html +6 -3
  207. package/dist/serve/site-ui/docs/pyric-sandbox-firestore-reference-api.md +2 -2
  208. package/dist/serve/site-ui/docs/pyric-sandbox-reference-api/index.html +5 -2
  209. package/dist/serve/site-ui/docs/pyric-storage-reference-api/index.html +5 -2
  210. package/dist/serve/site-ui/docs/pyric-ui-agents-reference-api/index.html +5 -2
  211. package/dist/serve/site-ui/docs/pyric-ui-auth-hooks-reference-api/index.html +5 -2
  212. package/dist/serve/site-ui/docs/pyric-ui-auth-reference-api/index.html +5 -2
  213. package/dist/serve/site-ui/docs/pyric-ui-events-hooks-reference-api/index.html +5 -2
  214. package/dist/serve/site-ui/docs/pyric-ui-events-reference-api/index.html +5 -2
  215. package/dist/serve/site-ui/docs/pyric-ui-firestore-hooks-reference-api/index.html +5 -2
  216. package/dist/serve/site-ui/docs/pyric-ui-firestore-reference-api/index.html +5 -2
  217. package/dist/serve/site-ui/docs/pyric-ui-primitives-reference-api/index.html +5 -2
  218. package/dist/serve/site-ui/docs/pyric-ui-rtdb-reference-api/index.html +5 -2
  219. package/dist/serve/site-ui/docs/pyric-ui-rules-hooks-reference-api/index.html +5 -2
  220. package/dist/serve/site-ui/docs/pyric-ui-rules-reference-api/index.html +5 -2
  221. package/dist/serve/site-ui/docs/pyric-ui-storage-hooks-reference-api/index.html +5 -2
  222. package/dist/serve/site-ui/docs/pyric-ui-storage-reference-api/index.html +5 -2
  223. package/dist/serve/site-ui/docs/pyric-ui-traffic-hooks-reference-api/index.html +5 -2
  224. package/dist/serve/site-ui/docs/pyric-ui-traffic-reference-api/index.html +5 -2
  225. package/dist/serve/site-ui/docs/reference/cli/index.html +153 -0
  226. package/dist/serve/site-ui/docs/reference/cli.md +114 -0
  227. package/dist/serve/site-ui/docs/rules-compat/index.html +5 -2
  228. package/dist/serve/site-ui/docs/secure/audit-your-rules/index.html +5 -2
  229. package/dist/serve/site-ui/docs/secure/firestore-rules-limits/index.html +5 -2
  230. package/dist/serve/site-ui/docs/secure/read-a-denial/index.html +6 -3
  231. package/dist/serve/site-ui/docs/secure/read-a-denial.md +1 -1
  232. package/dist/serve/site-ui/docs/secure/rtdb-rules-in-typescript/index.html +5 -2
  233. package/dist/serve/site-ui/docs/secure/rules-standard-library/index.html +5 -2
  234. package/dist/serve/site-ui/docs/secure/secure-it-with-rules/index.html +5 -2
  235. package/dist/serve/site-ui/docs/secure/simulate-and-lint/index.html +5 -2
  236. package/dist/serve/site-ui/docs/secure/write-a-rules-test-suite/index.html +5 -2
  237. package/dist/serve/site-ui/docs/ship/ship-to-production/index.html +7 -4
  238. package/dist/serve/site-ui/docs/ship/ship-to-production.md +2 -2
  239. package/dist/serve/site-ui/docs/ship/test-in-node/index.html +9 -6
  240. package/dist/serve/site-ui/docs/ship/test-in-node.md +4 -4
  241. package/dist/serve/site-ui/docs/storage-compat/index.html +5 -2
  242. package/dist/serve/site-ui/docs/trust/how-we-know-it-matches-firebase/index.html +5 -2
  243. package/dist/serve/site-ui/docs/trust/rules-standard-library/index.html +5 -2
  244. package/dist/serve/site-ui/docs/trust/versioning-and-compatibility/index.html +5 -2
  245. package/dist/serve/site-ui/docs/tutorial/index.html +10 -7
  246. package/dist/serve/site-ui/docs/tutorial.md +4 -4
  247. package/dist/serve/site-ui/examples/chess/index.html +4 -2
  248. package/dist/serve/site-ui/firestore/index.html +5 -3
  249. package/dist/serve/site-ui/hero-charcoal.jpg +0 -0
  250. package/dist/serve/site-ui/index.html +9 -7
  251. package/dist/serve/site-ui/llms.txt +4 -3
  252. package/dist/serve/site-ui/pyric-campfire-full.png +0 -0
  253. package/dist/serve/site-ui/pyric-campfire.png +0 -0
  254. package/dist/serve/site-ui/rtdb/index.html +5 -3
  255. package/dist/serve/site-ui/settings/index.html +5 -3
  256. package/dist/serve/site-ui/storage/index.html +5 -3
  257. package/dist/serve/site-ui/studio/index.html +13 -0
  258. package/dist/serve/site-ui/studio-routes.json +1 -1
  259. package/dist/serve/site-ui/traffic/index.html +5 -3
  260. package/dist/serve/studio/routes.d.ts +9 -0
  261. package/dist/serve/studio/routes.d.ts.map +1 -1
  262. package/dist/serve/studio/routes.js +47 -7
  263. package/dist/serve/studio/routes.js.map +1 -1
  264. package/dist/serve/vite-ai-config.d.ts.map +1 -1
  265. package/dist/serve/vite-ai-config.js +38 -8
  266. package/dist/serve/vite-ai-config.js.map +1 -1
  267. package/dist/serve/vite-module-swap.d.ts.map +1 -1
  268. package/dist/serve/vite-module-swap.js +0 -28
  269. package/dist/serve/vite-module-swap.js.map +1 -1
  270. package/dist/serve/vite-rules-source.d.ts.map +1 -1
  271. package/dist/serve/vite-rules-source.js +28 -7
  272. package/dist/serve/vite-rules-source.js.map +1 -1
  273. package/dist/serve/vite-sandbox-generation.d.ts +1 -1
  274. package/dist/serve/vite-sandbox-generation.d.ts.map +1 -1
  275. package/dist/serve/vite-sandbox-generation.js +1 -1
  276. package/dist/serve/vite-sandbox-generation.js.map +1 -1
  277. package/dist/serve/worker/client/disconnect.js +1 -1
  278. package/dist/serve/worker/client/disconnect.js.map +1 -1
  279. package/dist/serve/worker/client/presence.d.ts.map +1 -1
  280. package/dist/serve/worker/client/presence.js +18 -5
  281. package/dist/serve/worker/client/presence.js.map +1 -1
  282. package/dist/serve/worker/host-ai.d.ts.map +1 -1
  283. package/dist/serve/worker/host-ai.js +15 -0
  284. package/dist/serve/worker/host-ai.js.map +1 -1
  285. package/dist/serve/worker/protocol.d.ts +4 -0
  286. package/dist/serve/worker/protocol.d.ts.map +1 -1
  287. package/dist/serve/worker/protocol.js.map +1 -1
  288. package/dist/serve/worker/serve-init.d.ts.map +1 -1
  289. package/dist/serve/worker/serve-init.js +7 -1
  290. package/dist/serve/worker/serve-init.js.map +1 -1
  291. package/package.json +5 -5
  292. package/src/bridge/server/mcp-contract.ts +3 -0
  293. package/src/cli/cli.test.ts +2 -2
  294. package/src/cli/index.ts +51 -42
  295. package/src/cli/mcp-proxy.ts +10 -11
  296. package/src/cli/parse-args.ts +61 -15
  297. package/src/cli/pyric-config.ts +45 -0
  298. package/src/cli/rules.ts +31 -4
  299. package/src/cli/{dev-runner.ts → sandbox-runner.ts} +117 -72
  300. package/src/cli/serve.ts +115 -47
  301. package/src/cli/service-command-records/storage-rules-resolve.ts +4 -0
  302. package/src/cli/service-commands.generated.ts +2 -0
  303. package/src/cli/snapshot.ts +5 -5
  304. package/src/cli/verify.ts +1 -1
  305. package/src/functions-rtdb/development-runtime.ts +1 -1
  306. package/src/functions-rtdb/project.ts +8 -8
  307. package/src/next/guard.ts +1 -1
  308. package/src/remote/index.ts +9 -9
  309. package/src/serve/bundler.ts +10 -10
  310. package/src/serve/entries/ai.ts +27 -1
  311. package/src/serve/entries/auth-helper-dom.ts +1 -1
  312. package/src/serve/entries/auth-helper-runtime.ts +1 -1
  313. package/src/serve/entries/firestore.ts +3 -3
  314. package/src/serve/entries/keepalive.ts +1 -1
  315. package/src/serve/entries/runtime.ts +19 -14
  316. package/src/serve/entries/storage.ts +1 -1
  317. package/src/serve/entries/worker-runtime.ts +1 -1
  318. package/src/serve/init-payload.ts +4 -0
  319. package/src/serve/namespace.ts +44 -5
  320. package/src/serve/rules.ts +61 -26
  321. package/src/serve/runtime/chip.ts +38 -1
  322. package/src/serve/runtime/manifest.ts +1 -1
  323. package/src/serve/runtime/status.ts +24 -0
  324. package/src/serve/sandbox-session.ts +10 -4
  325. package/src/serve/server.ts +18 -1
  326. package/src/serve/studio/routes.ts +63 -7
  327. package/src/serve/vite-ai-config.ts +37 -7
  328. package/src/serve/vite-module-swap.ts +0 -28
  329. package/src/serve/vite-rules-source.ts +29 -7
  330. package/src/serve/vite-sandbox-generation.ts +1 -1
  331. package/src/serve/worker/client/disconnect.ts +1 -1
  332. package/src/serve/worker/client/presence.ts +25 -5
  333. package/src/serve/worker/host-ai.ts +15 -0
  334. package/src/serve/worker/protocol.ts +2 -1
  335. package/src/serve/worker/serve-init.ts +5 -1
  336. package/README.md.orig +0 -141
  337. package/dist/cli/dev-runner.d.ts.map +0 -1
  338. package/dist/cli/dev-runner.js.map +0 -1
  339. package/dist/serve/site-ui/_astro/_example_.jevZ7OdV.css +0 -1
  340. package/dist/serve/site-ui/_astro/_slug_.C6QfVOxJ.css +0 -1
  341. package/dist/serve/site-ui/_astro/_slug_.CXh9yTP1.css +0 -1
  342. package/dist/serve/site-ui/_astro/_studio_.B6b_G1ev.css +0 -1
  343. package/dist/serve/site-ui/_astro/app.B7pBzz5N.js +0 -11
  344. package/dist/serve/site-ui/_astro/app.BsFsMjn0.css +0 -1
  345. package/dist/serve/site-ui/_astro/app.boex5SnQ.js +0 -1
  346. package/dist/serve/site-ui/_astro/chess-showcase.DDqE-QGe.js +0 -1
  347. package/dist/serve/site-ui/_astro/chess-source-explorer.C5k9c5yK.js +0 -1
  348. package/dist/serve/site-ui/_astro/chess-v2.CFHmd3UL.js +0 -354
  349. package/dist/serve/site-ui/_astro/index.uwPvjH_1.js +0 -1
  350. package/dist/serve/site-ui/_astro/jsx-runtime.D_zvdyIk.js +0 -9
  351. package/dist/serve/site-ui/_astro/reads.Dh3z0fJy.js +0 -1
  352. package/dist/serve/site-ui/_astro/sandbox-controls.C2IqtoSw.js +0 -1252
  353. package/dist/serve/site-ui/_astro/seed.CCmj00su.js +0 -20
  354. package/dist/serve/site-ui/docs/trust/storage-rules-stdlib-research/index.html +0 -582
  355. package/dist/serve/site-ui/docs/trust/storage-rules-stdlib-research.md +0 -448
  356. package/dist/serve/site-ui/examples/firestore-first-write/index.html +0 -2
@@ -0,0 +1,12 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["_astro/seed.Co0yUJY5.js","_astro/sandbox-controls.DEpnKg-O.js","_astro/writes.rpjrFzmu.js","_astro/index.DBy5LfQW.js","_astro/index.DNyk7q8W.js","_astro/RulesCodeEditor.XtDmHOlN.js"])))=>i.map(i=>d[i]);
2
+ import{r as Ca,e as Re,m as wn,d as Na,f as ml,g as yl,h as bl,i as gl,j as o,p as vl,k as wl,l as xl,n as jl,R as ke,o as kl,q as Es,t as Ra,S as _l,Z as Aa,u as Sl,v as El,w as Cl,x as Nl,y as Rl,z as Al,A as Il,B as xn,C as Dl,D as Pl,E as Ia,F as $l,T as ft}from"./sandbox-controls.DEpnKg-O.js";import{r as h}from"./index.DBy5LfQW.js";import{m as Jr,c as Yr,S as Ol,v as Ml,a as Tl,b as Ie,t as Ve,f as Da,e as jn,r as Cs,h as Qr,j as Pa,k as Xr,u as cr,l as Ul,n as kn,o as Bl,p as Ll,q as Fl,w as Ns,x as Vl,y as ql,A as Rs,F as As,z as ht,d as Fe,B as Et,s as tn,C as $a,D as Is,E as lr,G as Wl,g as Oa,H as Ma,I as zl,J as Kl,i as Hl,K as at,L as _n}from"./writes.rpjrFzmu.js";import{r as Gl}from"./index.DNyk7q8W.js";const We={maxExpressionLength:256,maxStringLiteralLength:1024,maxAstDepth:16},Jl=["serverTimestamp","increment","arrayUnion","arrayRemove","deleteField"],Yl={serverTimestamp:{min:0,max:0},increment:{min:1,max:1},arrayUnion:{min:1,max:1/0},arrayRemove:{min:1,max:1/0},deleteField:{min:0,max:0}};function Ql(e){return Jl.includes(e)}class Z extends Error{code="invalid-argument";pos;constructor(t,n){super(t),this.name="ExpressionLexError",this.pos=n}}class ye extends Error{code="invalid-argument";pos;constructor(t,n){super(t),this.name="ExpressionParseError",this.pos=n}}const Xl={"(":"lparen",")":"rparen","[":"lbracket","]":"rbracket",",":"comma",".":"dot","?":"question",":":"colon","+":"plus","-":"minus","*":"star","/":"slash","%":"percent"},Zl={true:"true",false:"false",null:"null"};function eu(e){if(e.length>We.maxExpressionLength)throw new Z(`expression exceeds ${We.maxExpressionLength}-character cap (got ${e.length})`,F(We.maxExpressionLength));const t=[];let n=0;for(;n<e.length;){const r=n,s=e[n];if(s===" "||s===" "||s==="\r"||s===`
3
+ `){n+=1;continue}if(s==='"'||s==="'"){const{token:a,next:c}=ru(e,n,s);if(t.push(a),n=c,n<=r)throw new Z("lexer stalled on string",F(r));continue}if(s>="0"&&s<="9"){const{token:a,next:c}=nu(e,n);if(t.push(a),n=c,n<=r)throw new Z("lexer stalled on number",F(r));continue}if(Sn(s)){const{token:a,next:c}=tu(e,n);t.push(a),n=c;continue}if(s==="$"){const{token:a,next:c}=Ds(e,n,"$","reference");t.push(a),n=c;continue}if(s==="@"){const{token:a,next:c}=Ds(e,n,"@","sentinel");t.push(a),n=c;continue}if(s==="="&&e[n+1]==="="){t.push({kind:"eq",pos:F(n)}),n+=2;continue}if(s==="!"&&e[n+1]==="="){t.push({kind:"neq",pos:F(n)}),n+=2;continue}if(s==="<"){e[n+1]==="="?(t.push({kind:"lte",pos:F(n)}),n+=2):(t.push({kind:"lt",pos:F(n)}),n+=1);continue}if(s===">"){e[n+1]==="="?(t.push({kind:"gte",pos:F(n)}),n+=2):(t.push({kind:"gt",pos:F(n)}),n+=1);continue}if(s==="&"){if(e[n+1]!=="&")throw new Z("unexpected '&' (did you mean '&&'?)",F(n));t.push({kind:"and",pos:F(n)}),n+=2;continue}if(s==="|"){if(e[n+1]!=="|")throw new Z("unexpected '|' (did you mean '||'?)",F(n));t.push({kind:"or",pos:F(n)}),n+=2;continue}if(s==="!"){t.push({kind:"bang",pos:F(n)}),n+=1;continue}if(s==="=")throw new Z("unexpected '=' (did you mean '=='?)",F(n));const i=Xl[s];if(i){t.push({kind:i,pos:F(n)}),n+=1;continue}throw new Z(`unexpected character ${JSON.stringify(s)}`,F(n))}return t.push({kind:"eof",pos:F(e.length)}),t}function F(e){return{offset:e,column:e+1}}function Sn(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"||e==="_"}function Ta(e){return Sn(e)||e>="0"&&e<="9"}function tu(e,t){let n=t+1;for(;n<e.length&&Ta(e[n]);)n+=1;const r=e.slice(t,n),s=Zl[r];return s?{token:{kind:s,pos:F(t)},next:n}:{token:{kind:"identifier",pos:F(t),value:r},next:n}}function Ds(e,t,n,r){const s=t+1;if(s>=e.length||!Sn(e[s]))throw new Z(`expected identifier after '${n}'`,F(t));let i=s+1;for(;i<e.length&&Ta(e[i]);)i+=1;const a=e.slice(s,i);return{token:{kind:r,pos:F(t),value:a},next:i}}function nu(e,t){let n=t;const r=e[n];if(n+=1,r==="0"){if(n<e.length&&e[n]>="0"&&e[n]<="9")throw new Z("leading zeros are not allowed in number literals",F(t))}else for(;n<e.length&&e[n]>="0"&&e[n]<="9";)n+=1;let s=!1;if(n<e.length&&e[n]==="."){const c=e[n+1];if(c!==void 0&&c>="0"&&c<="9")for(s=!0,n+=1;n<e.length&&e[n]>="0"&&e[n]<="9";)n+=1;else if(!(c!==void 0&&Sn(c)))throw new Z("expected digit after '.' in number literal",F(n))}const i=e.slice(t,n),a=Number.parseFloat(i);if(!Number.isFinite(a))throw new Z(`numeric literal '${i}' is not finite`,F(t));if(!s&&!Number.isSafeInteger(a))throw new Z(`integer literal '${i}' exceeds safe integer range`,F(t));return{token:{kind:"number",pos:F(t),value:a},next:n}}function ru(e,t,n){let r=t+1,s="";for(;r<e.length;){const i=e[r];if(i===n)return{token:{kind:"string",pos:F(t),value:s},next:r+1};if(i==="\\"){const a=e[r+1];if(a===void 0)throw new Z("unterminated escape sequence in string literal",F(r));switch(a){case'"':s+='"';break;case"'":s+="'";break;case"\\":s+="\\";break;case"n":s+=`
4
+ `;break;case"t":s+=" ";break;default:throw new Z(`invalid escape sequence '\\${a}' (only \\", \\', \\\\, \\n, \\t are allowed)`,F(r))}r+=2}else{if(i===`
5
+ `||i==="\r")throw new Z("unterminated string literal (newline before closing quote)",F(t));s+=i,r+=1}if(s.length>We.maxStringLiteralLength)throw new Z(`string literal exceeds ${We.maxStringLiteralLength}-character cap`,F(t))}throw new Z("unterminated string literal",F(t))}function su(e){const t=new iu(e),n=t.parseExpression();return t.expect("eof","unexpected trailing tokens"),cu(n),n}class iu{tokens;cursor=0;constructor(t){this.tokens=t}parseExpression(){return this.parseTernary()}parseTernary(){const t=this.parseLogicalOr();if(this.peek().kind!=="question")return t;const n=this.consume(),r=this.parseExpression();this.expect("colon","expected ':' in ternary");const s=this.parseExpression();return{kind:"ternary",cond:t,whenTrue:r,whenFalse:s,pos:n.pos}}parseLogicalOr(){let t=this.parseLogicalAnd();for(;this.peek().kind==="or";){const n=this.consume(),r=this.parseLogicalAnd();t={kind:"logical",op:"||",left:t,right:r,pos:n.pos}}return t}parseLogicalAnd(){let t=this.parseComparison();for(;this.peek().kind==="and";){const n=this.consume(),r=this.parseComparison();t={kind:"logical",op:"&&",left:t,right:r,pos:n.pos}}return t}parseComparison(){let t=this.parseSum();for(;;){const n=au(this.peek().kind);if(!n)break;const r=this.consume(),s=this.parseSum();t={kind:"binary",op:n,left:t,right:s,pos:r.pos}}return t}parseSum(){let t=this.parseProduct();for(;;){const n=this.peek().kind;if(n!=="plus"&&n!=="minus")break;const r=this.consume(),s=this.parseProduct();t={kind:"binary",op:n==="plus"?"+":"-",left:t,right:s,pos:r.pos}}return t}parseProduct(){let t=this.parseUnary();for(;;){const n=this.peek().kind;if(n!=="star"&&n!=="slash"&&n!=="percent")break;const r=this.consume(),s=this.parseUnary();t={kind:"binary",op:n==="star"?"*":n==="slash"?"/":"%",left:t,right:s,pos:r.pos}}return t}parseUnary(){const t=this.peek().kind;if(t==="minus"||t==="bang"){const n=this.consume(),r=this.parseUnary();return{kind:"unary",op:t==="minus"?"-":"!",operand:r,pos:n.pos}}return this.parsePostfix()}parsePostfix(){let t=this.parsePrimary();for(;;){const n=this.peek().kind;if(n==="dot"){const r=this.consume(),s=this.expect("identifier","expected identifier after '.'");t={kind:"fieldAccess",target:t,field:s.value,pos:r.pos}}else if(n==="lbracket"){const r=this.consume(),s=this.parseExpression();this.expect("rbracket","expected ']'"),t={kind:"indexAccess",target:t,index:s,pos:r.pos}}else break}return t}parsePrimary(){const t=this.peek();switch(t.kind){case"number":return this.consume(),{kind:"literal",value:t.value,pos:t.pos};case"string":return this.consume(),{kind:"literal",value:t.value,pos:t.pos};case"true":return this.consume(),{kind:"literal",value:!0,pos:t.pos};case"false":return this.consume(),{kind:"literal",value:!1,pos:t.pos};case"null":return this.consume(),{kind:"literal",value:null,pos:t.pos};case"reference":return this.consume(),{kind:"reference",alias:t.value,pos:t.pos};case"sentinel":return this.parseSentinelCall();case"lparen":{this.consume();const n=this.parseExpression();return this.expect("rparen","expected ')'"),n}case"identifier":throw new ye(`bare identifier '${t.value}' is not a value (did you mean '$${t.value}' or '@${t.value}'?)`,t.pos);case"eof":throw new ye("unexpected end of expression",t.pos);default:throw new ye("unexpected token",t.pos)}}parseSentinelCall(){const t=this.consume(),n=t.value;if(!Ql(n))throw new ye(`unknown sentinel '@${n}' (allowed: serverTimestamp, increment, arrayUnion, arrayRemove, deleteField)`,t.pos);this.expect("lparen",`expected '(' after sentinel '@${n}'`);const r=[];if(this.peek().kind!=="rparen")for(r.push(this.parseExpression());this.peek().kind==="comma";)this.consume(),r.push(this.parseExpression());this.expect("rparen","expected ')' after sentinel arguments");const s=Yl[n];if(r.length<s.min||r.length>s.max){const i=s.max===1/0?`at least ${s.min}`:s.min===s.max?`exactly ${s.min}`:`${s.min}..${s.max}`;throw new ye(`sentinel '@${n}' expects ${i} argument(s), got ${r.length}`,t.pos)}return{kind:"sentinel",name:n,args:r,pos:t.pos}}peek(){return this.tokens[this.cursor]}consume(){const t=this.tokens[this.cursor];return this.cursor+=1,t}expect(t,n){const r=this.peek();if(r.kind!==t)throw new ye(`${n} (got ${ou(r)})`,r.pos);return this.consume()}}function au(e){switch(e){case"eq":return"==";case"neq":return"!=";case"lt":return"<";case"lte":return"<=";case"gt":return">";case"gte":return">=";default:return null}}function ou(e){return e.kind==="eof"?"end of expression":e.value!==void 0?`${e.kind} ${JSON.stringify(e.value)}`:e.kind}function cu(e){t(e);function t(n){let r=0;switch(n.kind){case"literal":case"reference":r=0;break;case"unary":r=t(n.operand);break;case"binary":case"logical":r=Math.max(t(n.left),t(n.right));break;case"ternary":r=Math.max(t(n.cond),t(n.whenTrue),t(n.whenFalse));break;case"fieldAccess":r=t(n.target);break;case"indexAccess":r=Math.max(t(n.target),t(n.index));break;case"sentinel":r=n.args.length===0?0:Math.max(...n.args.map(t));break}const s=r+1;if(s>We.maxAstDepth)throw new ye(`expression AST exceeds depth cap of ${We.maxAstDepth}`,n.pos);return s}}class oe extends Error{code;pos;constructor(t,n,r){super(n),this.name="EvalError",this.code=t,this.pos=r}}function $t(e){if(typeof e!="object"||e===null)return!1;const t=e,n=t.__type,r=Object.keys(t);switch(n){case"serverTimestamp":case"deleteField":return r.length===1;case"increment":return r.length===2&&typeof t.value=="number";case"arrayUnion":case"arrayRemove":return r.length===2&&Array.isArray(t.values);default:return!1}}function ue(e,t){return new oe("type-mismatch",t,e.pos)}function ce(e,t){switch(e.kind){case"literal":return e.value;case"reference":return lu(e,t);case"sentinel":return uu(e,t);case"unary":return du(e,t);case"binary":return fu(e,t);case"logical":return pu(e,t);case"ternary":return mu(e,t);case"fieldAccess":return yu(e,t);case"indexAccess":return bu(e,t)}}function lu(e,t){if(!Object.prototype.hasOwnProperty.call(t.reads,e.alias))throw new oe("unknown-reference",`unknown alias '$${e.alias}' (not in reads). Hint: aliases are case-sensitive; sentinels use '@' not '$'.`,e.pos);return t.reads[e.alias]??null}function uu(e,t){const n=e.args.map(r=>{const s=ce(r,t);if($t(s))throw new oe("sentinel-misuse",`sentinel '@${s.__type}' cannot be a sentinel argument`,r.pos);return s});switch(e.name){case"serverTimestamp":return{__type:"serverTimestamp"};case"deleteField":return{__type:"deleteField"};case"increment":{const r=n[0];if(typeof r!="number")throw ue(e,`'@increment' expects a numeric argument, got ${re(r)}`);return nn(r,e),{__type:"increment",value:r}}case"arrayUnion":return{__type:"arrayUnion",values:n};case"arrayRemove":return{__type:"arrayRemove",values:n}}}function du(e,t){const n=ce(e.operand,t);if(ur(n,e),e.op==="-"){if(typeof n!="number")throw ue(e,`unary '-' expects a number, got ${re(n)}`);const r=-n;return nn(r,e),r}if(typeof n!="boolean")throw ue(e,`unary '!' expects a boolean, got ${re(n)}`);return!n}function fu(e,t){const n=ce(e.left,t),r=ce(e.right,t);switch(ur(n,e),ur(r,e),e.op){case"+":if(typeof n=="number"&&typeof r=="number"){const s=n+r;return nn(s,e),s}if(typeof n=="string"&&typeof r=="string")return n+r;throw ue(e,`'+' expects (number, number) or (string, string); got (${re(n)}, ${re(r)})`);case"-":case"*":case"/":case"%":{if(typeof n!="number"||typeof r!="number")throw ue(e,`'${e.op}' expects (number, number); got (${re(n)}, ${re(r)})`);let s;switch(e.op){case"-":s=n-r;break;case"*":s=n*r;break;case"/":s=n/r;break;case"%":s=n%r;break}return nn(s,e),s}case"==":return Ps(e,n,r);case"!=":return!Ps(e,n,r);case"<":case"<=":case">":case">=":return hu(e,n,r)}}function Ps(e,t,n){if(t===null||n===null)return t===n;const r=typeof t;if(r!==typeof n)return!1;if(r==="number"||r==="string"||r==="boolean")return t===n;throw ue(e,"equality between objects/arrays is not supported (compare specific fields instead)")}function hu(e,t,n){if(!(typeof t=="number"&&typeof n=="number"||typeof t=="string"&&typeof n=="string"))throw ue(e,`'${e.op}' expects matching number/number or string/string operands; got (${re(t)}, ${re(n)})`);switch(e.op){case"<":return t<n;case"<=":return t<=n;case">":return t>n;case">=":return t>=n;default:throw new Error("unreachable")}}function pu(e,t){const n=ce(e.left,t);if(typeof n!="boolean")throw ue(e,`'${e.op}' expects boolean operands; left is ${re(n)}`);if(e.op==="&&"){if(!n)return!1}else if(n)return!0;const r=ce(e.right,t);if(typeof r!="boolean")throw ue(e,`'${e.op}' expects boolean operands; right is ${re(r)}`);return r}function mu(e,t){const n=ce(e.cond,t);if(typeof n!="boolean")throw ue(e,`ternary condition must be boolean, got ${re(n)}`);return ce(n?e.whenTrue:e.whenFalse,t)}function yu(e,t){const n=ce(e.target,t);if(n==null)throw new oe("null-access",`cannot access field '${e.field}' on null`,e.pos);if(typeof n!="object"||Array.isArray(n)||$t(n))throw ue(e,`cannot access field '${e.field}' on ${re(n)}`);const r=n;return Object.prototype.hasOwnProperty.call(r,e.field)?r[e.field]:null}function bu(e,t){const n=ce(e.target,t);if(n==null)throw new oe("null-access","cannot index null target",e.pos);const r=ce(e.index,t);if(Array.isArray(n)){if(typeof r!="number"||!Number.isInteger(r))throw new oe("invalid-index",`array index must be a non-negative integer, got ${re(r)}`,e.pos);if(r<0)throw new oe("invalid-index",`negative array index ${r} not supported (use length-based indexing in eval)`,e.pos);return r>=n.length?null:n[r]}if(typeof n=="object"&&!$t(n)){if(typeof r!="string")throw new oe("invalid-index",`object key must be a string, got ${re(r)}`,e.pos);const s=n;return Object.prototype.hasOwnProperty.call(s,r)?s[r]:null}throw ue(e,`cannot index into ${re(n)}`)}function ur(e,t){if($t(e))throw new oe("sentinel-misuse",`sentinel '@${e.__type}' cannot be used as an operator operand`,t.pos)}function nn(e,t){if(!Number.isFinite(e))throw new oe("division-by-zero",`arithmetic produced a non-finite value (${Number.isNaN(e)?"NaN":"Infinity"})`,t.pos)}function re(e){if(e===null)return"null";if(Array.isArray(e))return`array(${e.length})`;if(typeof e=="object"&&e!==null){if($t(e))return`sentinel '@${e.__type}'`;const t=Object.keys(e);if(t.length===0)return"object {}";const n=t.slice(0,3).join(", "),r=t.length>3?", …":"";return`object {${n}${r}}`}return typeof e}const Ua="$expr";class rn extends Error{code="invalid-argument";path;constructor(t,n){super(t),this.name="ExpressionWalkError",this.path=n}}function gu(e,t){return dr(e,t,"")}function dr(e,t,n){if(e===null)return null;if(typeof e!="object")return e;if(Array.isArray(e)){const i=new Array(e.length);for(let a=0;a<e.length;a+=1)i[a]=dr(e[a],t,n===""?String(a):`${n}.${a}`);return i}const r=e;if(Object.prototype.hasOwnProperty.call(r,Ua))return vu(r,t,n);const s={};for(const i of Object.keys(r))s[i]=dr(r[i],t,n===""?i:`${n}.${i}`);return s}function vu(e,t,n){const r=Object.keys(e);if(r.length!==1)throw new rn(`expression wrapper at '${n||"<root>"}' must have only the '$expr' key, got [${r.map(c=>JSON.stringify(c)).join(", ")}]`,n);const s=e[Ua];if(typeof s!="string")throw new rn(`'$expr' value at '${n||"<root>"}' must be a string, got ${ju(s)}`,n);const i=xu(s,n);return wu(i,t,n)}function wu(e,t,n){try{return ce(e,t)}catch(r){if(r instanceof oe){const s=new oe(r.code,`at '${n||"<root>"}': ${r.message}`,r.pos);throw s.cause=r,s}throw r}}function xu(e,t){try{return su(eu(e))}catch(n){throw n instanceof Z?$s(n,Z,t):n instanceof ye?$s(n,ye,t):n}}function $s(e,t,n){const r=new t(`at '${n||"<root>"}': ${e.message}`,e.pos);return r.cause=e,r}function ju(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function ku(e){const{resolveSandbox:t,resolveModulesFn:n}=e;return[{name:"firestore_simulator_create",description:'Seed the session\'s local Firestore environment with rules and optional initial documents. Resets any prior state. Supports `rules_version = "2+modules"` — modules resolve in-process before seeding. Returns the lint result + document count for verification.',parameters:{type:"object",properties:{rules:{type:"string",description:"Firestore security rules source (version 2 or 2+modules)."},documents:{type:"object",description:'Initial documents keyed by full path, e.g. `{ "users/u1": { name: "alice" } }`.',additionalProperties:!0}},required:["rules"]},async execute(r){const{rules:s,documents:i}=r;let a=s;if(a.includes("'2+modules'")||a.includes('"2+modules"')){if(!n)return{ok:!1,summary:"Module resolve unavailable: this builder was not wired with `resolveModulesFn`. Use a package entry that wires module resolution, such as pyric/rules/internal/node, instead of importing the impl directly.",data:{code:"NO_MODULE_RESOLVER"}};const u=n(a);if(!u.success)return{ok:!1,summary:`Module resolve failed: ${u.error.message}`,data:u};a=u.data.resolved}const l=(await t()).seed({rules:a,documents:i??{}});return{ok:!0,summary:`Seeded sandbox with ${Object.keys(i??{}).length} document(s)`,data:{lint:l,documentCount:Object.keys(i??{}).length}}}},{name:"firestore_simulator_execute",description:"Execute a single write (create / update / delete) against the seeded sandbox. Rules evaluate against the in-memory state; allow → state mutates and the op is logged, deny → state unchanged and `debugMessages` explain the rule decision.",parameters:{type:"object",properties:{method:{type:"string",enum:["create","update","delete"]},path:{type:"string",description:"Document path, e.g. `users/u1`."},auth:{description:"Auth context. `null` for unauthenticated. Otherwise `{ uid, token? }` where `token` is the custom-claims object."},data:{type:"object",description:"Document data. Required for create / update.",additionalProperties:!0}},required:["method","path","auth"]},async execute(r){const{method:s,path:i,auth:a,data:c}=r,u=(await t()).execute({method:s,path:i,auth:a,data:c});return{ok:u.allowed,summary:u.allowed?`${s} on ${i} allowed`:`${s} on ${i} denied`,data:{allowed:u.allowed,debugMessages:u.debugMessages}}}},{name:"firestore_simulator_read",description:"Read a document (`get`) or list a collection (`list`) from the seeded sandbox. Default uses admin access (bypasses rules). Set `evaluateRules: true` with an `auth` context to test read access control through the rules engine.",parameters:{type:"object",properties:{path:{type:"string",description:"Doc path for `get`, collection path for `list`."},method:{type:"string",enum:["get","list"],description:"Default `get`."},auth:{description:"Auth context. Required when `evaluateRules` is true."},evaluateRules:{type:"boolean",description:"Evaluate read rules against `auth`. Default false (admin read)."}},required:["path"]},async execute(r){const{path:s,method:i,auth:a,evaluateRules:c}=r,l=await t();if(c){const u=l.execute({method:i??"get",path:s,auth:a??null});return{ok:u.allowed,summary:u.allowed?`${i??"get"} on ${s} allowed`:`${i??"get"} on ${s} denied`,data:{allowed:u.allowed,document:u.data,debugMessages:u.debugMessages}}}return i==="list"?{ok:!0,summary:`Listed ${s}`,data:{documents:l.listDocuments(s)}}:{ok:!0,summary:`Read ${s}`,data:{document:l.getDocument(s)}}}},{name:"firestore_simulator_batch",description:"Execute multiple writes atomically. All operations must pass rules — if any denies, none apply. Rules evaluate each op against pre-batch state (no cross-visibility within the batch).",parameters:{type:"object",properties:{operations:{type:"array",items:{type:"object",properties:{method:{type:"string",enum:["create","update","delete"]},path:{type:"string"},data:{type:"object",additionalProperties:!0}},required:["method","path"]}},auth:{description:"Auth context for every op. `null` for unauthenticated."}},required:["operations","auth"]},async execute(r){const{operations:s,auth:i}=r,c=(await t()).batch(s,i);return{ok:c.allowed,summary:c.allowed?`Batch of ${s.length} op(s) committed`:`Batch of ${s.length} op(s) rejected by rules. To SEED data, use the admin data tool firestore_batch_write; to test rules, pass an auth the rules permit.`,data:{allowed:c.allowed,results:c.results}}}},{name:"firestore_create_with_auto_id",description:"Create a document at `<collection>/<auto-id>` with a Firestore-compatible 20-char alphanumeric id (mirrors the live SDK `addDoc()` flow). Rules evaluate as for an explicit-id `create`. Returns the minted path so the caller can re-read the doc without a side channel.",parameters:{type:"object",properties:{collection:{type:"string",description:"Collection path under which to mint the new document, e.g. `users` or `users/u1/posts`."},auth:{description:"Auth context. `null` for unauthenticated. Otherwise `{ uid, token? }`."},data:{type:"object",description:"Document data.",additionalProperties:!0}},required:["collection","auth","data"]},async execute(r){const{collection:s,auth:i,data:a}=r,c=await t(),{path:l,result:u}=c.createWithAutoId(s,a,i);return{ok:u.allowed,summary:u.allowed?`Created ${l}`:`Create at ${l} denied by rules (as ${i?i.uid:"unauthenticated"}). To SEED data, use the admin data tool firestore_add_document; to test rules, pass an auth the rules permit.`,data:{path:l,allowed:u.allowed,debugMessages:u.debugMessages}}}},{name:"firestore_simulator_undo",description:"Undo the last allowed write. Restores state to immediately before that op. Returns the undone event, or a `{ undone: false }` outcome when the log is empty.",parameters:{type:"object",properties:{}},async execute(){const s=(await t()).undo();return s?{ok:!0,summary:`Undid ${s.method} on ${s.path}`,data:{undone:!0,event:{method:s.method,path:s.path}}}:{ok:!0,summary:"Nothing to undo",data:{undone:!1}}}},{name:"firestore_simulator_redo",description:"Re-apply the most recently undone write. Pairs with `firestore_simulator_undo`. Returns the re-applied event, or `{ redone: false }` when the undo stack is empty (no recent undo to redo).",parameters:{type:"object",properties:{}},async execute(){const s=(await t()).redo();return s?{ok:s.allowed,summary:s.allowed?`Redid ${s.event?.method??"op"} on ${s.event?.path??"?"}`:"Redo restored a denied event (no state change)",data:{redone:!0,allowed:s.allowed,event:s.event?{method:s.event.method,path:s.event.path}:null,debugMessages:s.debugMessages}}:{ok:!0,summary:"Nothing to redo",data:{redone:!1}}}},{name:"firestore_simulator_events",description:'Return every event the sandbox has seen — allowed and denied — with timestamps, auth, and debug messages. Useful for audit / replay / "why did this rule deny?" investigations.',parameters:{type:"object",properties:{}},async execute(){return{ok:!0,summary:"Event log",data:{events:(await t()).getEvents().map(s=>({id:s.id,method:s.method,path:s.path,allowed:s.allowed,auth:s.auth,debugMessages:s.debugMessages}))}}}},{name:"firestore_simulator_transaction",description:'Run a declarative transaction. Reads are captured server-side and referenced from write data via `{ "$expr": "..." }` wrappers — agents never see the read values, eliminating the "round-trip the doc through context" cost. Expression DSL: arithmetic (+ - * / %), comparison, &&/||/?:, $alias.field references, string literals in either "double" or \'single\' quotes, and @sentinel(...) calls (@increment, @serverTimestamp, @arrayUnion, @arrayRemove, @deleteField). Reads are omitted from the response by default; set `includeReads: true` when debugging a denial.',parameters:{type:"object",properties:{auth:{description:"Auth context for rule eval. `null` for unauthenticated."},readOnly:{type:"boolean",description:"Hint that the transaction is read-only. v1: writes are still committed; `readOnlyViolation: true` surfaces on the response if any was queued."},includeReads:{type:"boolean",description:"Default false. When true, the response includes the captured read data + per-write debugMessages."},reads:{type:"object",description:"Reads keyed by alias. Aliases referenced from write expressions as `$alias` (e.g. `$src.balance`).",additionalProperties:{type:"string"}},writes:{type:"array",minItems:1,items:{type:"object",properties:{method:{type:"string",enum:["create","update","set","delete"]},path:{type:"string"},data:{type:"object",additionalProperties:!0}},required:["method","path"]},description:"Write operations to apply atomically."}},required:["reads","writes","auth"]},async execute(r){const{auth:s,readOnly:i,includeReads:a,reads:c,writes:l}=r;for(let p=0;p<l.length;p+=1){const f=l[p];if(f.method==="delete"&&f.data!==void 0)return{ok:!1,summary:`writes[${p}]: 'delete' must not include 'data'`,data:{code:"INVALID_INPUT"}};if(f.method!=="delete"&&f.data===void 0)return{ok:!1,summary:`writes[${p}]: '${f.method}' requires 'data'`,data:{code:"INVALID_INPUT"}}}const u=await t(),d=a===!0;try{const p=u.transaction(m=>{const y={};for(const[g,v]of Object.entries(c)){const w=m.get(v).data();y[g]=w===void 0?null:w}for(let g=0;g<l.length;g+=1){const v=l[g];if(v.method==="delete"){m.delete(v.path);continue}const b=gu(v.data,{reads:y});if(b===null||typeof b!="object"||Array.isArray(b))throw new rn(`writes[${g}].data resolved to a non-object`,`writes.${g}.data`);const w=b;switch(v.method){case"create":m.create(v.path,w);break;case"update":m.update(v.path,w);break;case"set":m.set(v.path,w);break}}},{auth:s,readOnly:i}),f={allowed:p.allowed,writes:p.writes.map(m=>{const y={path:m.path,method:m.method,allowed:m.allowed};return m.error&&(y.error={code:m.error.code,message:m.error.message}),d&&(y.debugMessages=m.debugMessages),y})};return p.error&&(f.error={code:p.error.code,message:p.error.message}),p.readOnlyViolation&&(f.readOnlyViolation=!0),d&&(f.reads=p.reads.map(m=>({path:m.path,data:m.data}))),{ok:p.allowed,summary:p.allowed?`Transaction committed (${l.length} write(s))`:"Transaction rolled back",data:f}}catch(p){if(p instanceof rn||p instanceof Z||p instanceof ye||p instanceof oe)return{ok:!1,summary:`Transaction failed: ${p.message}`,data:{allowed:!1,writes:[],error:{code:"invalid-argument",message:p.message}}};throw p}}}]}function Ba(e){return ku({resolveSandbox:e.resolveSandbox,resolveModulesFn:Ca})}let Fn;function _u(){if(Fn)return Fn;const e=Yr();return e.addOperation("identifiers",{_nonterminal(...t){return t.flatMap(n=>n.identifiers())},_iter(...t){return t.flatMap(n=>n.identifiers())},_terminal(){return[]},CallExpr_methodCall(t,n,r,s,i,a){return[...t.identifiers(),...i.asIteration().children.flatMap(c=>c.identifiers())]},CallExpr_memberAccess(t,n,r){return t.identifiers()},ident(t,n,r){return[this.sourceString]}}),Fn=e,e}function Su(e){const t=Jr(e);if(t.failed())return{raw:e,valid:!1,errors:[{code:"PARSE_ERROR",message:t.message??"Parse failed"}],warnings:[],referencedIdentifiers:[]};const n=_u()(t).identifiers(),r=[...new Set(n)];return{raw:e,valid:!0,errors:[],warnings:[],referencedIdentifiers:r}}const Eu=new Set(["__proto__","prototype","constructor"]);function L(e){if(e===""||e==="/")return[];const t=e.split("/").filter(n=>n.length>0);for(const n of t)if(Eu.has(n))throw new Error(`Invalid RTDB path segment '${n}': the keys __proto__, prototype, and constructor are reserved and cannot appear in a path.`);return t}function J(e){return e.length===0?"/":"/"+e.join("/")}function Ne(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>Ne(n));const t={};for(const[n,r]of Object.entries(e))t[n]=Ne(r);return t}function Os(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ot(e,t){if(Object.is(e,t))return!0;if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((s,i)=>ot(s,t[i]));if(!Os(e)||!Os(t))return!1;const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(s=>s in t&&ot(e[s],t[s]))}class Cu{root={};snapshot(){return Ne(this.root)}restore(t){this.root=Ne(t)}read(t){const n=L(t);if(n.length>0&&n[0]===".info")return n.length===1?{connected:!0,serverTimeOffset:0}:n[1]==="connected"?!0:n[1]==="serverTimeOffset"?0:null;let s=this.root;for(const i of n){if(s===null||typeof s!="object"||Array.isArray(s))return null;const a=s;if(!Object.hasOwn(a,i))return null;s=a[i]}return Ne(s)}write(t,n){const r=L(t),s=this.read(t);if(r.length===0)return n===null?(this.root={},s):(this.root=Ne(n),s);(this.root===null||typeof this.root!="object"||Array.isArray(this.root))&&(this.root={});let i=this.root;for(let c=0;c<r.length-1;c++){const l=r[c],u=Object.hasOwn(i,l)?i[l]:void 0;if(u==null||typeof u!="object"||Array.isArray(u)){const d={};i[l]=d,i=d}else i=u}const a=r[r.length-1];return n===null?(delete i[a],this.trim(r)):i[a]=Ne(n),s}multiUpdate(t){const r=Object.entries(t).map(([i,a])=>({path:J(L(i)),value:a}));for(let i=0;i<r.length;i++)for(let a=i+1;a<r.length;a++){const c=r[i].path,l=r[a].path;if(c===l)throw new Error(`multi-path update: duplicate path '${c}'.`);const u=c==="/"?"/":c+"/",d=l==="/"?"/":l+"/";if(c!=="/"&&l.startsWith(u))throw new Error(`multi-path update: '${l}' is a descendant of '${c}'.`);if(l!=="/"&&c.startsWith(d))throw new Error(`multi-path update: '${c}' is a descendant of '${l}'.`)}const s=[];for(const{path:i,value:a}of r){const c=this.write(i,a);s.push({path:i,prior:c})}return s}shallowUpdate(t,n){const r=[],s=L(t);for(const[i,a]of Object.entries(n)){const c=[...s,...L(i)],l=J(c),u=this.write(l,a);r.push({path:l,prior:u})}return r}trim(t){if(!(this.root===null||typeof this.root!="object"||Array.isArray(this.root)))for(let n=t.length-1;n>=1;n--){const r=t.slice(0,n),s=t[n-1];let i=this.root;for(let c=0;c<r.length-1;c++){const l=i[r[c]];if(l==null||typeof l!="object"||Array.isArray(l))return;i=l}const a=i[s];if(a!==void 0&&typeof a=="object"&&a!==null&&!Array.isArray(a)&&Object.keys(a).length===0){delete i[s];continue}return}}}function Nu(e,t){return e==="/"||t==="/"?!0:e===t||e.startsWith(`${t}/`)||t.startsWith(`${e}/`)}class Ru{version=0;activeVersions=[];mutations=[];get entries(){return this.mutations}get currentVersion(){return this.version}begin(){const t=this.version;return this.activeVersions.push(t),t}mark(t="/"){this.version+=1,this.activeVersions.length>0&&this.mutations.push({version:this.version,paths:(Array.isArray(t)?t:[t]).map(n=>J(L(n)))})}conflictsSince(t,n){const r=J(L(n));return this.mutations.some(s=>s.version>t&&s.paths.some(i=>Nu(r,i)))}release(t){const n=this.activeVersions.lastIndexOf(t);if(n>=0&&this.activeVersions.splice(n,1),this.activeVersions.length===0){this.mutations.length=0;return}const r=Math.min(...this.activeVersions),s=this.mutations.findIndex(i=>i.version>r);s<0?this.mutations.length=0:s>0&&this.mutations.splice(0,s)}}function he(e){return e==="unsupported"?"unsupported":"deny"}function xe(e){return J(L(e))}class Au{sandbox;nextId=0;constructor(t){this.sandbox=t}nextListenerId(){return this.nextId+=1,`rtdb-listener-${this.nextId.toString(36)}`}nextGroupId(t){return this.nextId+=1,`rtdb-${t}-${this.nextId.toString(36)}`}mutation(t,n,r,s={}){if(this.sandbox)try{Re(this.sandbox,wn({service:"rtdb",op:n,path:r,auth:t,before:s.before,after:s.after,detail:s.detail}),{service:"rtdb"})}catch{}}operation(t,n,r,s,i,a={}){if(this.sandbox)try{let c;i&&(c={engine:"rtdb",matchedPath:i.matchedPath,matchedRule:i.matchedRule,pathVariableBindings:i.pathVariableBindings,reason:i.reason,errorCode:i.errorCode});let l="user";a.origin&&(l=a.origin),Re(this.sandbox,Na({service:"rtdb",method:n,path:xe(r),auth:t,result:s,origin:l,durationMs:a.durationMs,reasons:i?.reasons,rules:c,request:a.request,resourceBefore:a.resourceBefore,resourceAfter:a.resourceAfter,groupId:a.groupId,groupKind:a.groupKind,triggeredBy:a.triggeredBy,detail:a.detail,at:a.at}),{service:"rtdb"})}catch{}}commit(t,n,r,s={}){if(this.sandbox)try{Re(this.sandbox,ml({service:"rtdb",method:n,path:xe(r),auth:t,data:s.data,priorState:s.priorState,nextState:s.nextState,groupId:s.groupId,groupKind:s.groupKind,replay:s.replay,detail:s.detail}),{service:"rtdb"})}catch{}}listener(t,n,r,s={}){if(this.sandbox)try{let i="value";s.event&&(i=s.event),Re(this.sandbox,yl({service:"rtdb",phase:t,listenerId:n.id,target:{kind:i,path:xe(n.path)},auth:r,result:s.result,size:s.size,sample:s.sample,reason:s.reason,error:s.error,triggeredBy:s.triggeredBy,detail:s.detail,reasons:s.reasons,rules:s.rules}),{service:"rtdb"})}catch{}}}class Iu{values=new Map;get(t){return this.values.get(J(L(t)))??null}forChild(t){const n=L(t);return r=>this.get(J([...n,r]))}clear(){this.values.clear()}clearAtOrBelow(t){const n=J(L(t)),r=n==="/"?"/":`${n}/`;for(const s of this.values.keys())(s===n||s.startsWith(r))&&this.values.delete(s)}replace(t,n){this.clearAtOrBelow(t),n!==null&&this.values.set(J(L(t)),n)}set(t,n){const r=J(L(t));n===null?this.values.delete(r):this.values.set(r,n)}stateAtOrBelow(t){const n=J(L(t)),r=n==="/"?"/":`${n}/`;return JSON.stringify([...this.values].filter(([s])=>s===n||s.startsWith(r)).sort(([s],[i])=>s.localeCompare(i)))}applyUpdate(t){for(const n of t){const r=this.get(n.path);this.clearAtOrBelow(n.path),n.value!==null&&r!==null&&this.values.set(J(L(n.path)),r)}}entries(){return this.values.entries()}restore(t){this.values.clear();for(const[n,r]of Object.entries(t))this.values.set(J(L(n)),r)}}function sn(e){if(e!==null&&typeof e!="string"&&(typeof e!="number"||!Number.isFinite(e)))throw new Error("priority must be a valid Firebase priority (string, finite number, or null)")}let qe=[],fr=!1,hr=!1,pr=!1,Vn;function Du(){if(Vn)return Vn;const e=Yr();return e.addOperation("lint",{_nonterminal(...t){t.forEach(n=>n.lint())},_iter(...t){t.forEach(n=>n.lint())},_terminal(){},CallExpr_methodCall(t,n,r,s,i,a){t.lint(),i.asIteration().children.forEach(c=>c.lint()),r.sourceString==="child"&&t.sourceString==="data"&&(pr=!0)},ident(t,n,r){const s=this.sourceString;s==="data"&&(fr=!0),s==="newData"&&(hr=!0)},bool_true(t){qe.push({code:"HARDCODED_TRUE",message:"Rule expression is hardcoded to true"})},bool_false(t){qe.push({code:"HARDCODED_FALSE",message:"Rule expression is hardcoded to false"})},Comparison_looseEq(t,n,r){qe.push({code:"LOOSE_EQUALITY",message:"Use '===' instead of '=='"}),t.lint(),r.lint()},Comparison_looseNeq(t,n,r){qe.push({code:"LOOSE_INEQUALITY",message:"Use '!==' instead of '!='"}),t.lint(),r.lint()}}),Vn=e,e}function Pu(e,t="read"){const n=Jr(e);return n.failed()?[]:(qe=[],fr=!1,hr=!1,pr=!1,Du()(n).lint(),t==="write"&&fr&&!hr&&!pr&&qe.push({code:"DATA_IN_WRITE",message:"Write rule references 'data' but not 'newData'; consider using 'newData' to check incoming data"}),[...qe])}const $u=new Set(["__proto__","prototype","constructor"]);function Ms(e,t){return $u.has(t)?null:typeof e=="string"?t==="length"?e.length:null:e===null||typeof e!="object"||!Object.hasOwn(e,t)?null:e[t]??null}function Ou(e){let t="";for(let n=0;n<e.length;n++){const r=e[n];if(r!=="\\"||n===e.length-1){t+=r;continue}const s=e[++n];switch(s){case"\\":t+="\\";break;case"'":t+="'";break;case'"':t+='"';break;case"n":t+=`
6
+ `;break;case"r":t+="\r";break;case"t":t+=" ";break;case"b":t+="\b";break;case"f":t+="\f";break;case"/":t+="/";break;default:t+="\\"+s;break}}return t}class je{_value;_path;_root;constructor(t,n="/",r){this._value=t??null,this._path=n,this._root=r!==void 0?r:t}val(){return this._value}exists(){return this._value!==null&&this._value!==void 0}hasChild(t){return this.child(t).exists()}hasChildren(t){return Array.isArray(t)?t.every(n=>this.hasChild(String(n))):typeof this._value=="object"&&this._value!==null&&Object.keys(this._value).length>0}isString(){return typeof this._value=="string"}isNumber(){return typeof this._value=="number"}isBoolean(){return typeof this._value=="boolean"}child(t){const n=t.split("/").filter(i=>i.length>0);let r=this._value,s=this._path;for(const i of n){if(r==null||typeof r!="object"){r=null,s=`${s}/${i}`.replace(/\/+/g,"/");break}r=Object.hasOwn(r,i)?r[i]??null:null,s=`${s==="/"?"":s}/${i}`}return new je(r,s,this._root)}parent(){if(this._path==="/")return null;const t=this._path.split("/").filter(s=>s.length>0);t.pop();const n="/"+t.join("/"),r=new je(this._root,"/");return n==="/"?r:r.child(t.join("/"))}getPriority(){return null}}class Mu{value;constructor(t){this.value=t}matches(t){return(t instanceof RegExp?t:new RegExp(t)).test(this.value)}contains(t){return this.value.includes(t)}beginsWith(t){return this.value.startsWith(t)}endsWith(t){return this.value.endsWith(t)}replace(t,n){if(t instanceof RegExp){const r=t.flags.includes("g")?t.flags:`${t.flags}g`;return this.value.replace(new RegExp(t.source,r),n)}return t===""?this.value:this.value.split(t).join(n)}toLowerCase(){return this.value.toLowerCase()}toUpperCase(){return this.value.toUpperCase()}get length(){return this.value.length}}let Ee={auth:null,data:new je(null),newData:new je(null),root:new je(null),now:Date.now(),pathVariableBindings:{}},qn;function Tu(){if(qn)return qn;const e=Yr();return e.addOperation("eval",{Expr(t){return t.eval()},Ternary_ternary(t,n,r,s,i){return t.eval()?r.eval():i.eval()},Ternary(t){return t.eval()},Logical_and(t,n,r){return t.eval()&&r.eval()},Logical_or(t,n,r){return t.eval()||r.eval()},Logical(t){return t.eval()},Comparison_strictEq(t,n,r){return t.eval()===r.eval()},Comparison_strictNeq(t,n,r){return t.eval()!==r.eval()},Comparison_gte(t,n,r){return t.eval()>=r.eval()},Comparison_lte(t,n,r){return t.eval()<=r.eval()},Comparison_gt(t,n,r){return t.eval()>r.eval()},Comparison_lt(t,n,r){return t.eval()<r.eval()},Comparison_looseEq(t,n,r){return t.eval()==r.eval()},Comparison_looseNeq(t,n,r){return t.eval()!=r.eval()},Comparison(t){return t.eval()},Additive_add(t,n,r){return t.eval()+r.eval()},Additive_sub(t,n,r){return t.eval()-r.eval()},Additive(t){return t.eval()},Multiplicative_mul(t,n,r){return t.eval()*r.eval()},Multiplicative_div(t,n,r){return t.eval()/r.eval()},Multiplicative_mod(t,n,r){return t.eval()%r.eval()},Multiplicative(t){return t.eval()},UnaryExpr_not(t,n){return!n.eval()},UnaryExpr_neg(t,n){return-n.eval()},UnaryExpr(t){return t.eval()},CallExpr_methodCall(t,n,r,s,i,a){const c=t.eval(),l=r.sourceString,u=i.asIteration().children.map(d=>d.eval());if(c instanceof je)switch(l){case"val":return c.val();case"exists":return c.exists();case"hasChild":return c.hasChild(String(u[0]));case"hasChildren":return c.hasChildren(u.length>0?u[0]:void 0);case"isString":return c.isString();case"isNumber":return c.isNumber();case"isBoolean":return c.isBoolean();case"child":return c.child(String(u[0]));case"parent":return c.parent();case"getPriority":return c.getPriority();default:throw new Error(`Unknown DataSnapshot method: ${l}`)}if(typeof c=="string"){const d=new Mu(c);switch(l){case"matches":return d.matches(u[0]);case"contains":return d.contains(String(u[0]));case"beginsWith":return d.beginsWith(String(u[0]));case"endsWith":return d.endsWith(String(u[0]));case"replace":return d.replace(u[0],String(u[1]));case"toLowerCase":return d.toLowerCase();case"toUpperCase":return d.toUpperCase();default:throw new Error(`Unknown string method: ${l}`)}}throw new Error(`Unknown method '${l}' for the given value.`)},CallExpr_memberAccess(t,n,r){const s=t.eval();return s==null?null:Ms(s,r.sourceString)},CallExpr_indexAccess(t,n,r,s){const i=t.eval(),a=r.eval();return i==null?null:Ms(i,String(a))},CallExpr(t){return t.eval()},Primary_paren(t,n,r){return n.eval()},Primary(t){return t.eval()},Array(t,n,r){return n.asIteration().children.map(s=>s.eval())},literal(t){return t.eval()},number_float(t,n,r,s){return parseFloat(this.sourceString)},number_exp(t,n){return parseFloat(this.sourceString)},number_int(t){return parseInt(this.sourceString,10)},number(t){return t.eval()},string_double(t,n,r){return JSON.parse(this.sourceString)},string_single(t,n,r){return Ou(n.sourceString)},string(t){return t.eval()},regex(t,n,r,s){return new RegExp(n.sourceString,s.sourceString)},bool_true(t){return!0},bool_false(t){return!1},bool(t){return t.eval()},null(t){return null},ident(t,n,r){const s=this.sourceString;if(s in Ee.pathVariableBindings)return Ee.pathVariableBindings[s];switch(s){case"auth":return Ee.auth;case"data":return Ee.data;case"newData":return Ee.newData;case"root":return Ee.root;case"now":return Ee.now;default:return}}}),qn=e,e}function La(e,t){const n=Jr(e);if(n.failed())throw new Error(n.message??"RTDB expression failed to parse");return Ee=t,Tu()(n).eval()}function Uu(e){const t=e.val();return t===null||typeof t!="object"?[]:Object.keys(t)}function Bu(e,t,n,r,s,i){let a=null;function c(u,d,p,f,m){if(!p.exists())return null;const y=u.validate;if(y){if(!y.parsed.valid)a||(a={node:u,rule:y,bindings:f,unsupported:!0});else if(!La(y.raw,s(d,p,f)))return{node:u,rule:y,bindings:f}}for(const g of u.children){const v=g.path.split("/").filter(Boolean);if(v.length===0)continue;const b=v[v.length-1],w=b.startsWith("$");if(m.length>0){if(!w&&m[0]!==b)continue;return c(g,d.child(m[0]),p.child(m[0]),w?{...f,[b]:m[0]}:f,m.slice(1))}if(w)for(const x of Uu(p)){const k=c(g,d.child(x),p.child(x),{...f,[b]:x},[]);if(k)return k}else{const x=c(g,d.child(b),p.child(b),f,[]);if(x)return x}}return null}return c(e,t,n,r,i)??a}function Fa(e,t,n,r=0){const s=[{node:e,pathVariableBindings:{...n},depth:r}];if(t.length===0)return s;for(const i of e.children){const a=i.path.split("/").filter(Boolean);if(a.length===0)continue;const c=a[a.length-1],l=c.startsWith("$");if(l||t[0]===c){const u=l?{...n,[c]:t[0]}:{...n},d=Fa(i,t.slice(1),u,r+1);return s.push(...d),s}}return s}function mr(e,t,n){if(t.length===0)return n??null;const[r,...s]=t,i=e!==null&&typeof e=="object"&&!Array.isArray(e)?{...e}:{},a=Object.hasOwn(i,r)?i[r]:null,c=mr(a,s,n);return c==null?delete i[r]:i[r]=c,i}function Lu(e,t,n,r){if(!r||r.length===0)return mr(e,t,n??null);let s=e;for(const i of r){const a=i.path.split("/").filter(Boolean);s=mr(s,a,i.value??null)}return s}class Fu{execute(t,n){const r=Ol.safeParse(n);if(!r.success)return{success:!1,error:{code:"INVALID_INPUT",message:r.error.message,recoverable:!0}};const{operation:s,path:i,auth:a,mockData:c,newData:l,updates:u}=r.data;try{const d=i.split("/").filter(Boolean),p=t,f=Fa(p,d,{}),m=new je(c,"/"),y=s==="read"?c:Lu(c,d,l,u),g=new je(y,"/"),v=(k,j,_)=>{const N={};for(const[P,I]of Object.entries(_))N[P]=I,N[P.slice(1)]=I;return{auth:a?{uid:a.uid,token:a.token}:null,data:k,newData:j,root:m,now:Date.now(),pathVariableBindings:N}};let b;for(const k of f){const j=k.node[s];if(!j)continue;if(!j.parsed.valid){b||(b=k);continue}const _=d.slice(0,k.depth).join("/"),N=m.child(_),P=g.child(_);if(La(j.raw,v(N,P,k.pathVariableBindings))){if(s==="write"){const D=Bu(p,m,g,{},v,d);if(D)return{success:!0,data:{allowed:!1,unsupported:D.unsupported===!0,matchedPath:D.node.path,matchedRule:D.rule.raw,reason:D.unsupported?`Validation rule at '${D.node.path}' contains an expression the simulator cannot evaluate: ${D.rule.raw} — not evaluated; production may reject this write.`:"Validation rule evaluated to false",pathVariableBindings:D.bindings}}}return{success:!0,data:{allowed:!0,matchedPath:k.node.path,matchedRule:j.raw,reason:"Rule expression evaluated to true",pathVariableBindings:k.pathVariableBindings}}}}if(b){const k=b.node[s];return{success:!0,data:{allowed:!1,unsupported:!0,matchedPath:b.node.path,matchedRule:k.raw,reason:`'${s}' rule at '${b.node.path}' contains an expression the simulator cannot evaluate: ${k.raw} — not evaluated; production may reject or allow this ${s}.`,pathVariableBindings:b.pathVariableBindings}}}const w=f[f.length-1],x=w.node[s];return x?{success:!0,data:{allowed:!1,matchedPath:w.node.path,matchedRule:x.raw,reason:"Rule expression evaluated to false",pathVariableBindings:w.pathVariableBindings}}:{success:!1,error:{code:"NO_MATCHING_RULE",message:`No '${s}' rule found for path '${i}'`,recoverable:!0}}}catch(d){return{success:!1,error:{code:"EVALUATION_ERROR",message:d instanceof Error?d.message:String(d),recoverable:!1}}}}}const Vu=new Set([".read",".write",".validate",".indexOn"]);function Va(e,t,n=[]){const r=Su(e),s=r.valid?Ml(e,t,n):r.errors,i=r.valid?Pu(e,t):[];return{raw:e,parsed:{...r,errors:s,warnings:i}}}function qa(e,t,n){const r={path:t,pathVariables:[...n],children:[]};for(const[i,a]of[[".read","read"],[".write","write"],[".validate","validate"]]){const c=e[i];c!==void 0&&(r[a]=Va(String(c),a,n))}const s=e[".indexOn"];s!==void 0&&(r.indexOn=Array.isArray(s)?s.map(String):[String(s)]);for(const[i,a]of Object.entries(e)){if(Vu.has(i)||typeof a!="object"||a===null)continue;const c=t==="/"?`/${i}`:`${t}/${i}`,l=i.startsWith("$")?[...n,i]:[...n];r.children.push(qa(a,c,l))}return r}function Wa(e){if(!e||typeof e!="object")throw new Error("Invalid rules JSON: expected an object");const t=e;if(!("rules"in t))throw new Error('Invalid rules JSON: missing top-level "rules" key');if(typeof t.rules!="object"||t.rules===null)throw new Error('Invalid rules JSON: "rules" must be an object');return qa(t.rules,"/",[])}function Wn(e){return e==="true"?!0:e==="false"?!1:e}function za(e){const t={};e.read&&(t[".read"]=Wn(e.read.raw)),e.write&&(t[".write"]=Wn(e.write.raw)),e.validate&&(t[".validate"]=Wn(e.validate.raw)),e.indexOn&&(t[".indexOn"]=e.indexOn);for(const n of e.children){const r=n.path.split("/").filter(Boolean);t[r[r.length-1]]=za(n)}return t}function qu(e){if(!e||typeof e!="object"||!("path"in e))throw new Error("Invalid compiled rules: expected a rules node with a 'path' property");return{rules:za(e)}}function Zr(e,t){return new Fu().execute(e,t)}function ve(){const e=new Error("PERMISSION_DENIED: Permission denied");return e.code="PERMISSION_DENIED",e}class Wu{compiled=null;defaultPolicy="allow";setDefaultPolicy(t){this.defaultPolicy=t}setRules(t){if(t===null){this.compiled=null;return}this.compiled=Wa(t)}hasRules(){return this.compiled!==null}check(t,n,r){return this.evaluate(t,n,r).check}evaluate(t,n,r){if(t==="read"){if(n==="/.info"||n===".info")return{check:"allow",reasons:["/.info/ system metadata paths are always readable regardless of security rules."]};if(n.startsWith("/.info/"))return{check:"allow",reasons:["/.info/ system metadata paths are always readable regardless of security rules."]};if(n.startsWith(".info/"))return{check:"allow",reasons:["/.info/ system metadata paths are always readable regardless of security rules."]}}if(this.compiled===null)return this.defaultPolicy==="deny"?{check:"no-rule",reasons:["No RTDB rules loaded; default deny."],errorCode:"NO_MATCHING_RULE",errorMessage:"No RTDB rules loaded; default deny."}:{check:"allow",reasons:["No RTDB rules loaded; default allow."]};const i=r.auth===null?null:{uid:r.auth.uid,token:r.auth.token??{}},a=Zr(this.compiled,{operation:t,path:n==="/"?"/":n,auth:i,mockData:r.mockData,newData:r.newData,updates:r.updates});return a.success?a.data.unsupported?{check:"unsupported",reasons:[`${a.data.matchedPath} ${t} UNSUPPORTED: ${a.data.reason}`],matchedPath:a.data.matchedPath,matchedRule:a.data.matchedRule,reason:a.data.reason,pathVariableBindings:a.data.pathVariableBindings}:{check:a.data.allowed?"allow":"deny",reasons:[`${a.data.matchedPath} ${t} ${a.data.allowed?"ALLOW":"DENY"}: ${a.data.reason}`],matchedPath:a.data.matchedPath,matchedRule:a.data.matchedRule,reason:a.data.reason,pathVariableBindings:a.data.pathVariableBindings}:a.error.code==="NO_MATCHING_RULE"?{check:"no-rule",reasons:[a.error.message],errorCode:a.error.code,errorMessage:a.error.message}:{check:"no-rule",reasons:[a.error.message],errorCode:a.error.code,errorMessage:a.error.message}}}class zu{tree=new Cu;rules=new Wu;activeRules=null;valueListeners=new Set;childListeners=new Set;priorities=new Iu;mutations=new Ru;events;writeSubscribers=new Set;resetGeneration=0;constructor(t){this.events=new Au(t)}notifyWrite(){for(const t of this.writeSubscribers)try{t()}catch{}}}function es(e,t){if(e===t)return 0;if(e===null)return-1;if(t===null)return 1;const n=Ts(e),r=Ts(t);return n!==r?n-r:typeof e=="number"&&typeof t=="number"?e<t?-1:e>t?1:0:typeof e=="boolean"&&typeof t=="boolean"?e===t?0:e?1:-1:typeof e=="string"&&typeof t=="string"?e<t?-1:e>t?1:0:0}function Ts(e){return e===null?0:typeof e=="boolean"?1:typeof e=="number"?2:typeof e=="string"?3:4}const Ku=/^-?(0*)\d{1,10}$/,Hu=-2147483648,Gu=2147483647;function Us(e){if(Ku.test(e)){const t=Number(e);if(t>=Hu&&t<=Gu)return t}return null}function an(e,t){if(e===t)return 0;const n=Us(e),r=Us(t);return n!==null?r!==null?n-r===0?e.length-t.length:n-r:-1:r!==null?1:e<t?-1:1}function Ct(e,t,n,r=null){const s=e??{kind:"priority"};switch(s.kind){case"key":return t;case"value":return n;case"priority":return r;case"child":{if(n===null||typeof n!="object"||Array.isArray(n))return null;const i=s.path.split("/").filter(c=>c.length>0);let a=n;for(const c of i){if(a===null||typeof a!="object"||Array.isArray(a))return null;a=a[c]??null}return a}}}function ze(e,t,n=()=>null){if(e===null||typeof e!="object"||Array.isArray(e))return[];let s=Object.entries(e).map(([a,c])=>({key:a,value:c,priority:n(a)}));const i=t.orderBy?.kind==="key";s.sort((a,c)=>{if(i)return an(a.key,c.key);const l=Ct(t.orderBy,a.key,a.value,a.priority),u=Ct(t.orderBy,c.key,c.value,c.priority),d=es(l,u);return d!==0?d:an(a.key,c.key)});for(const a of t.bounds)s=s.filter(c=>Ju(a,c,t.orderBy));if(t.limit){const a=t.limit.n;t.limit.kind==="limitToFirst"?s=s.slice(0,a):s=a>=s.length?s:s.slice(s.length-a)}return s}function Ju(e,t,n){const s=n?.kind==="key"?an(t.key,String(e.value)):es(Ct(n,t.key,t.value,t.priority),e.value),i=a=>an(t.key,a);switch(e.kind){case"startAt":return s>0?!0:s<0?!1:e.key===void 0||i(e.key)>=0;case"startAfter":return s>0?!0:s<0||e.key===void 0?!1:i(e.key)>0;case"endAt":return s<0?!0:s>0?!1:e.key===void 0||i(e.key)<=0;case"endBefore":return s<0?!0:s>0||e.key===void 0?!1:i(e.key)<0;case"equalTo":return s!==0?!1:e.key===void 0||i(e.key)===0}}function Bs(e){return e.length===0?null:Object.fromEntries(e.map(({key:t,value:n})=>[t,n]))}function Yu(e,t){return e.length===t.length&&e.every((n,r)=>{const s=t[r];return n.key===s.key&&n.priority===s.priority&&ot(n.value,s.value)})}function ts(e){const t=new Error(`permission_denied at ${J(L(e))}: Client doesn't have permission to access the desired data.`);return t.code="PERMISSION_DENIED",t}class Qu{state;constructor(t){this.state=t}onValue(t,n,r,s,i,a){const c=Date.now(),l=this.state.rules.evaluate("read",n==="/"?"/":n,{auth:t,mockData:this.state.tree.snapshot()});if(l.check!=="allow"){let u;s&&(u={query:s}),this.state.events.operation(t,"listen",n,he(l.check),l,{at:c,durationMs:Date.now()-c,request:u,origin:"listener"});const d={engine:"rtdb",matchedPath:l.matchedPath,matchedRule:l.matchedRule,pathVariableBindings:l.pathVariableBindings,reason:l.reason,errorCode:l.errorCode};if(this.state.events.listener("errored",{id:this.state.events.nextListenerId(),path:n},t,{event:"value",result:"deny",error:{code:"PERMISSION_DENIED",message:"PERMISSION_DENIED: Permission denied",reasons:l.reasons},reasons:l.reasons,rules:d}),i)return queueMicrotask(()=>{a&&a(),i(ts(n))}),()=>{};throw ve()}return this.attach(t,n,r,s,{origin:"listener",result:"allow",evaluation:l,at:c},i,a)}adminOnValue(t,n,r){return this.attach(null,t,n,r,{origin:"admin",result:"not-applicable",evaluation:void 0,at:Date.now()})}attach(t,n,r,s,i,a,c){const l=this.state.events.nextListenerId();this.state.events.operation(t,"listen",n,i.result,i.evaluation,{at:i.at,durationMs:Date.now()-i.at,request:s?{query:s}:void 0,origin:i.origin});const u={id:l,auth:t,cb:r,path:n,query:s,cancelCallback:a,onCanceled:c};if(this.state.valueListeners.add(u),this.state.events.listener("attach",u,t,{event:"value",result:"allow",detail:s?{query:s}:void 0}),s){const d=ze(this.state.tree.read(n),s,this.state.priorities.forChild(n));u.lastWindow=d,this.deliverInitial(u,{val:Bs(d),exists:d.length>0,key:this.key(n),rows:d},{initial:!0,query:!0})}else{const d=this.snapshot(n);u.lastValue=d.val,u.lastPriorityState=this.state.priorities.stateAtOrBelow(n),this.deliverInitial(u,d,{initial:!0})}return()=>{this.state.valueListeners.delete(u),this.state.events.listener("detach",u,t,{event:"value"})}}fanOut(t){if(this.state.valueListeners.size===0)return;const n=t.map(r=>J(L(r)));for(const r of this.state.valueListeners){const s=J(L(r.path));if(!n.some(c=>Xu(s,c)))continue;if(r.query){const c=ze(this.state.tree.read(r.path),r.query,this.state.priorities.forChild(r.path));if(Yu(r.lastWindow??[],c)){this.state.events.listener("suppressed",r,r.auth,{event:"value",reason:"no-op",detail:{query:!0}});continue}r.lastWindow=c,this.deliver(r,{val:Bs(c),exists:c.length>0,key:this.key(r.path),rows:c},{query:!0});continue}const i=this.snapshot(r.path),a=this.state.priorities.stateAtOrBelow(r.path);if(ot(r.lastValue??null,i.val)&&r.lastPriorityState===a){this.state.events.listener("suppressed",r,r.auth,{event:"value",reason:"no-op"});continue}r.lastValue=i.val,r.lastPriorityState=a,this.deliver(r,i,{})}}off(t,n){const r=J(L(t));for(const s of[...this.state.valueListeners])J(L(s.path))===r&&(n!==void 0&&s.cb!==n||(this.state.valueListeners.delete(s),this.state.events.listener("detach",s,s.auth,{event:"value"})))}count(){return this.state.valueListeners.size}snapshot(t){const n=this.state.tree.read(t);return{val:n,exists:n!==null,key:this.key(t)}}key(t){const n=L(t);return n.length===0?null:n[n.length-1]}deliver(t,n,r){this.state.events.listener("delivery",t,t.auth,{event:"value",size:n.rows?.length??(n.exists?1:0),sample:n.val,detail:r});try{t.cb(n)}catch(s){this.state.events.listener("errored",t,t.auth,{event:"value",result:"error",error:{message:s instanceof Error?s.message:String(s)},detail:r})}}deliverInitial(t,n,r){try{t.cb(n),this.state.events.listener("delivery",t,t.auth,{event:"value",size:n.rows?.length??(n.exists?1:0),sample:n.val,detail:r})}catch(s){this.state.events.listener("errored",t,t.auth,{event:"value",result:"error",error:{message:s instanceof Error?s.message:String(s)},detail:r})}}}function Xu(e,t){if(e===t||e==="/")return!0;const n=`${e}/`,r=t==="/"?"/":`${t}/`;return t.startsWith(n)||e.startsWith(r)}function Ye(e,t){const n=e.findIndex(r=>r.key===t);return n>0?e[n-1].key:null}function vt(e,t){const n=e.findIndex(r=>r.key===t);return n>0?e[n-1].key:null}function Ls(e,t){if(t===void 0)return null;const n=L(e),r=L(t);return r.length!==n.length+1||!n.every((s,i)=>r[i]===s)?null:r[r.length-1]??null}class Zu{state;constructor(t){this.state=t}onChild(t,n,r,s,i,a,c){const l=Date.now(),u=this.state.events.nextListenerId(),d=this.state.rules.evaluate("read",r==="/"?"/":r,{auth:t,mockData:this.state.tree.snapshot()});if(d.check!=="allow"){this.state.events.operation(t,"listen",r,he(d.check),d,{at:l,durationMs:Date.now()-l,origin:"listener",detail:{event:n}});const f={engine:"rtdb",matchedPath:d.matchedPath,matchedRule:d.matchedRule,pathVariableBindings:d.pathVariableBindings,reason:d.reason,errorCode:d.errorCode};if(this.state.events.listener("errored",{id:u,path:r},t,{event:n,result:"deny",error:{code:"PERMISSION_DENIED",message:"PERMISSION_DENIED: Permission denied",reasons:d.reasons},reasons:d.reasons,rules:f}),a)return queueMicrotask(()=>{c&&c(),a(ts(r))}),()=>{};throw ve()}this.state.events.operation(t,"listen",r,"allow",d,{at:l,durationMs:Date.now()-l,origin:"listener",detail:{event:n}});const p={id:u,auth:t,event:n,path:r,cb:s,spec:i,cancelCallback:a,onCanceled:c};if(this.state.childListeners.add(p),this.state.events.listener("attach",p,t,{event:n,result:"allow",detail:i?{query:i}:void 0}),i){const f=ze(this.state.tree.read(r),i,this.state.priorities.forChild(r));if(p.lastWindow=f,n==="child_added")for(const{key:m,value:y}of f)this.deliver(p,{key:m,val:y,previousChildName:Ye(f,m)},{initial:!0,query:!0})}else if(n==="child_added")for(const{key:f,val:m}of this.directChildren(r)){const y=this.directChildren(r);this.deliver(p,{key:f,val:m,previousChildName:vt(y,f)},{initial:!0})}return()=>{this.state.childListeners.delete(p),this.state.events.listener("detach",p,t,{event:n})}}off(t,n,r){const s=J(L(t));for(const i of[...this.state.childListeners])n!==void 0&&i.event!==n||J(L(i.path))===s&&(r!==void 0&&i.cb!==r||(this.state.childListeners.delete(i),this.state.events.listener("detach",i,i.auth,{event:i.event})))}snapshotParents(){const t=new Map;for(const n of this.state.childListeners){const r=J(L(n.path));t.has(r)||t.set(r,new Map(this.directChildren(r).map(({key:s,val:i})=>[s,i])))}return t}fanOut(t,n){if(this.state.childListeners.size===0)return;const r=new Map;for(const s of this.state.childListeners){if(s.spec){this.fanOutQuery(s,n);continue}const i=J(L(s.path)),a=r.get(i)??[];a.push(s),r.set(i,a)}for(const[s,i]of r){const a=t.get(s)??new Map,c=new Map(this.directChildren(s).map(({key:f,val:m})=>[f,m])),l=[...c].map(([f,m])=>({key:f,val:m})),u=[...a].map(([f,m])=>({key:f,val:m})),d={child_added:[],child_changed:[],child_removed:[],child_moved:[]};for(const[f,m]of c)a.has(f)?ot(a.get(f),m)||d.child_changed.push({key:f,val:m,previousChildName:vt(l,f)}):d.child_added.push({key:f,val:m,previousChildName:vt(l,f)});for(const[f,m]of a)c.has(f)||d.child_removed.push({key:f,val:m,previousChildName:vt(u,f)});const p=Ls(s,n);p!==null&&a.has(p)&&c.has(p)&&d.child_moved.push({key:p,val:c.get(p),previousChildName:vt(l,p)});for(const f of i)for(const m of d[f.event])this.deliver(f,m,{})}}count(){return this.state.childListeners.size}directChildren(t){const n=this.state.tree.read(t);return n===null||typeof n!="object"||Array.isArray(n)?[]:ze(n,{orderBy:{kind:"priority"},bounds:[],limit:null},this.state.priorities.forChild(t)).map(({key:r,value:s})=>({key:r,val:s}))}fanOutQuery(t,n){const r=t.lastWindow??[],s=ze(this.state.tree.read(t.path),t.spec,this.state.priorities.forChild(t.path));t.lastWindow=s;const i=new Map(r.map(l=>[l.key,l.value])),a=new Map(s.map(l=>[l.key,l.value])),c=[];if(t.event==="child_added")for(const l of s)i.has(l.key)||c.push({key:l.key,val:l.value,previousChildName:Ye(s,l.key)});else if(t.event==="child_changed")for(const l of s)i.has(l.key)&&!ot(i.get(l.key),l.value)&&c.push({key:l.key,val:l.value,previousChildName:Ye(s,l.key)});else if(t.event==="child_removed")for(const l of r)a.has(l.key)||c.push({key:l.key,val:l.value,previousChildName:Ye(r,l.key)});else if(t.spec?.orderBy&&t.spec.orderBy.kind!=="key"){const l=t.spec.orderBy.kind==="priority"?Ls(t.path,n):null;let u=!1;if(l!==null){const d=s.find(p=>p.key===l);d&&i.has(l)&&(c.push({key:d.key,val:d.value,previousChildName:Ye(s,d.key)}),u=!0)}if(!u){const d=new Map(r.map(p=>[p.key,p]));for(const p of s){const f=d.get(p.key);if(!f)continue;const m=Ct(t.spec.orderBy,f.key,f.value,f.priority),y=Ct(t.spec.orderBy,p.key,p.value,p.priority);es(m,y)!==0&&c.push({key:p.key,val:p.value,previousChildName:Ye(s,p.key)})}}}for(const l of c)this.deliver(t,l,{query:!0})}deliver(t,n,r){this.state.events.listener("delivery",t,t.auth,{event:t.event,size:1,sample:r.query?{key:n.key,val:n.val}:n,detail:r});try{t.cb(n)}catch(s){this.state.events.listener("errored",t,t.auth,{event:t.event,result:"error",error:{message:s instanceof Error?s.message:String(s)},detail:r})}}}function ed(e){const t=e!==null;let n=!1;if(t){const r=typeof e=="object",s=Array.isArray(e);r&&(s||(n=!0))}if(n){const r=e,i=r[".pyricRtdbPersistence"]===1,a="data"in r;let c=!1;i&&a&&(c=!0);const l=r.priorities,u=l!==null,d=l!==void 0;let p=!1;if(u&&d){const m=typeof l=="object",y=Array.isArray(l);m&&(y||(p=!0))}let f=!1;if(c&&p&&(f=!0),f){const m={},y=Object.entries(l);for(const[j,_]of y){const N=typeof _=="string",P=typeof _=="number";let I=!1;P&&Number.isFinite(_)&&(I=!0);let D=!1;N&&(D=!0),I&&(D=!0),D&&(m[j]=_)}const g=r.data;let v=null;g!==void 0&&g!==null&&(v=g);const w=r.rules;let x=null;if(w!==void 0&&w!==null){const _=typeof w=="object",N=Array.isArray(w);let P=!1;if(_&&(N||(P=!0)),P){const I=w;if("rules"in I){const C=I.rules;if(C!==null&&C!==void 0){const R=typeof C=="object",V=Array.isArray(C);let G=!1;R&&(V||(G=!0)),G&&(x={rules:C})}}}}return{data:v,priorities:m,rules:x}}}return{data:e,priorities:{},rules:null}}class td{state;values;children;constructor(t,n,r){this.state=t,this.values=n,this.children=r}exportTree(){return this.state.tree.snapshot()}exportState(){const t=this.state.activeRules!==null,n={".pyricRtdbPersistence":1,data:this.state.tree.snapshot(),priorities:Object.fromEntries(this.state.priorities.entries())};return t&&(n.rules=structuredClone(this.state.activeRules)),n}restore(t){const n=this.children.snapshotParents(),r=ed(t);let s={};const i=r.data===null,a=r.data===void 0;let c=!1;i||a||(c=!0),c&&(s=r.data),r.rules!==null?(this.state.rules.setRules(r.rules),this.state.activeRules=structuredClone(r.rules)):(this.state.rules.setRules(null),this.state.activeRules=null),this.state.tree.restore(s),this.state.priorities.restore(r.priorities),this.state.mutations.mark("/"),this.values.fanOut(["/"]),this.children.fanOut(n)}reset(){this.state.resetGeneration+=1,this.restore(null)}subscribe(t){return this.state.writeSubscribers.add(t),()=>{this.state.writeSubscribers.delete(t)}}}const nd=/[\[\].#$/\u0000-\u001F\u007F]/;function rd(e){return e.length!==0&&!nd.test(e)}function sd(e){return typeof e=="number"&&(Number.isNaN(e)||e===1/0||e===-1/0)}function id(e){return e===".priority"||e===".value"||e===".sv"}function ad(e,t){yr(e,t,"set")}function yr(e,t,n){if(e===void 0)throw new Error(`${n} failed: value argument contains undefined in property '${t}'`);if(typeof e=="function")throw new Error(`${n} failed: value argument contains a function in property '${t}'`);if(sd(e))throw new Error(`${n} failed: value argument contains ${String(e)} in property '${t}'`);if(!(e===null||typeof e!="object")){if(Array.isArray(e)){for(let r=0;r<e.length;r++){if(!(r in e))continue;const s=e[r];s!==void 0&&yr(s,`${t}/${r}`,n)}return}for(const[r,s]of Object.entries(e)){if(!id(r)&&!rd(r))throw new Error(`${n} failed: value argument contains an invalid key (${r}) in path ${t}. Keys must be non-empty strings and can't contain ".", "#", "$", "/", "[", or "]"`);yr(s,`${t}/${r}`,n)}}}function Be(e,t){return ad(e,t),br(e)}function br(e){if(e==null)return null;if(typeof e!="object")return e;if(Array.isArray(e)){const n={};for(let r=0;r<e.length;r++){if(!(r in e))continue;const s=br(e[r]);s!==null&&(n[String(r)]=s)}return Object.keys(n).length===0?null:n}const t={};for(const[n,r]of Object.entries(e)){if(n===".sv"){t[n]=r;continue}const s=br(r);s!==null&&(t[n]=s)}return Object.keys(t).length===0?null:t}function Zt(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(a=>Zt(a));const t=e,n=Object.keys(t);let r=n.length>0,s=0;for(const a of n)if(/^(0|[1-9]\d*)$/.test(a))s=Math.max(s,Number(a));else{r=!1;break}if(r&&s<2*n.length){const a=[];for(let c=0;c<=s;c++){const l=t[String(c)];a[c]=l===void 0?null:Zt(l)}return a}const i={};for(const[a,c]of Object.entries(t))i[a]=Zt(c);return i}function od(e){return e===null||typeof e!="object"?!1:e[".sv"]==="timestamp"}function cd(e){if(e===null||typeof e!="object")return!1;const t=e[".sv"];return t!==null&&typeof t=="object"&&typeof t.increment=="number"}function we(e,t,n){if(od(e))return t;if(cd(e)){const i=e[".sv"].increment;return(typeof n=="number"?n:0)+i}if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map((i,a)=>we(i,t,Array.isArray(n)?n[a]:void 0));const r=n!==null&&typeof n=="object"&&!Array.isArray(n)?n:void 0,s={};for(const[i,a]of Object.entries(e))s[i]=we(a,t,r?r[i]:void 0);return s}function Fs(){return new Error("permission_denied")}class ld{state;values;children;constructor(t,n,r){this.state=t,this.values=n,this.children=r}run(t,n,r,s){const i=s?.applyLocally!==!1,a=L(n),c=a.length===0?null:a[a.length-1];let l=null,u,d=0,p=!1;do{d+=1;const x=this.state.mutations.begin();l=this.state.tree.read(n);const k=l===null?null:Zt(Ne(l));let j=!1;try{u=r(k),j=this.state.mutations.conflictsSince(x,n)}finally{this.state.mutations.release(x)}if(!j||u===void 0){p=!0;break}}while(d<25);if(!p)throw new Error("maxretry");const f=this.state.events.nextGroupId("transaction");if(u===void 0)return this.state.events.operation(t,"transaction",n,"not-applicable",void 0,{origin:"transaction",groupId:f,groupKind:"transaction",resourceBefore:{data:l,exists:l!==null},detail:{committed:!1,aborted:!0}}),{committed:!1,val:l,key:c};const m=Date.now(),y=Be(we(u,m,l),n==="/"?"":n);if(i){const x=this.state.tree.snapshot(),k=Object.fromEntries(this.state.priorities.entries()),j=this.state.priorities.get(n),_=this.children.snapshotParents();this.state.tree.write(n,y),this.state.priorities.replace(n,j),this.values.fanOut([n]),this.children.fanOut(_);const N=Date.now(),P=this.state.rules.evaluate("write",n==="/"?"/":n,{auth:t,mockData:x,newData:y});if(P.check!=="allow"){this.state.events.operation(t,"transaction",n,he(P.check),P,{at:N,durationMs:Date.now()-N,origin:"transaction",request:{data:u,resourceData:u},resourceBefore:{data:l,exists:l!==null},resourceAfter:{data:y,exists:y!==null},groupId:f,groupKind:"transaction"});const I=this.children.snapshotParents();throw this.state.tree.restore(x),this.state.priorities.restore(k),this.values.fanOut([n]),this.children.fanOut(I),Fs()}return this.recordCommit(t,n,u,l,y,f,m,N,!0,P),{committed:!0,val:y,key:c}}const g=Date.now(),v=this.state.rules.evaluate("write",n==="/"?"/":n,{auth:t,mockData:this.state.tree.snapshot(),newData:y});if(v.check!=="allow")throw this.state.events.operation(t,"transaction",n,he(v.check),v,{at:g,durationMs:Date.now()-g,origin:"transaction",request:{data:u,resourceData:u},resourceBefore:{data:l,exists:l!==null},resourceAfter:{data:y,exists:y!==null},groupId:f,groupKind:"transaction"}),Fs();this.state.events.operation(t,"transaction",n,"allow",v,{at:g,durationMs:Date.now()-g,origin:"transaction",request:{data:u,resourceData:u},resourceBefore:{data:l,exists:l!==null},resourceAfter:{data:y,exists:y!==null},groupId:f,groupKind:"transaction"});const b=this.state.priorities.get(n),w=this.children.snapshotParents();return this.state.tree.write(n,y),this.state.priorities.replace(n,b),this.state.mutations.mark(n),this.values.fanOut([n]),this.children.fanOut(w),this.finishEvents(t,n,u,l,y,f,m,!1),this.state.notifyWrite(),{committed:!0,val:y,key:c}}recordCommit(t,n,r,s,i,a,c,l,u,d){this.state.events.operation(t,"transaction",n,"allow",d,{at:l,durationMs:Date.now()-l,origin:"transaction",request:{data:r,resourceData:r},resourceBefore:{data:s,exists:s!==null},resourceAfter:{data:i,exists:i!==null},groupId:a,groupKind:"transaction"}),this.finishEvents(t,n,r,s,i,a,c,u),this.state.mutations.mark(n),this.state.notifyWrite()}finishEvents(t,n,r,s,i,a,c,l){this.state.events.commit(t,"transaction",n,{data:r,priorState:s,nextState:i,groupId:a,groupKind:"transaction",replay:{requestTime:c},detail:{committed:!0,applyLocally:l}}),this.state.events.mutation(t,"transaction",xe(n),{before:s,after:i,detail:{committed:!0}})}}class ud{state;values;children;constructor(t,n,r){this.state=t,this.values=n,this.children=r}adminSet(t,n){if(sn(n),this.state.tree.read(t)===null)return;const r=this.children.snapshotParents(),s=this.state.priorities.get(t)!==n;this.state.priorities.set(t,n),this.state.mutations.mark(t),s&&this.values.fanOut([t]),this.children.fanOut(r,s?t:void 0),this.state.notifyWrite()}set(t,n,r){sn(r);const s=this.state.tree.read(n),i=Date.now(),a=this.state.rules.evaluate("write",n==="/"?"/":n,{auth:t,mockData:this.state.tree.snapshot(),newData:s}),c=this.state.priorities.get(n),l={at:i,durationMs:Date.now()-i,request:{data:r},resourceBefore:{data:s,exists:s!==null},resourceAfter:{data:s,exists:s!==null},detail:{priority:r,priorPriority:c}};if(a.check!=="allow")throw this.state.events.operation(t,"setPriority",n,he(a.check),a,l),ve();if(this.state.events.operation(t,"setPriority",n,"allow",a,l),s===null)return;const u=this.children.snapshotParents(),d=c!==r;this.state.priorities.set(n,r),this.state.mutations.mark(n),d&&this.values.fanOut([n]),this.children.fanOut(u,d?n:void 0),d&&(this.state.events.commit(t,"setPriority",n,{data:r,priorState:c,nextState:r,detail:{priority:r,priorPriority:c}}),this.state.events.mutation(t,"setPriority",xe(n),{before:c,after:r,detail:{priorityMetadata:!0}})),this.state.notifyWrite()}}function Vs(e){return e.length===0?null:Object.fromEntries(e.map(({key:t,value:n})=>[t,n]))}class dd{state;values;children;priorityWrites;constructor(t,n,r){this.state=t,this.values=n,this.children=r,this.priorityWrites=new ud(t,n,r)}setData(t){this.state.tree.restore({}),this.state.priorities.clear();for(const[n,r]of Object.entries(t))this.state.tree.write(n,Be(we(r,Date.now()),n==="/"?"":n));this.state.mutations.mark("/"),this.state.notifyWrite()}setRules(t){t===null?this.state.activeRules=null:this.state.activeRules=structuredClone(t),this.state.rules.setRules(t),this.cancelDeniedListeners(),this.state.notifyWrite()}setDefaultPolicy(t){this.state.rules.setDefaultPolicy(t),this.cancelDeniedListeners(),this.state.notifyWrite()}getActiveRules(){const t=this.state.activeRules===null;let n=null;return t||(n=structuredClone(this.state.activeRules)),n}snapshotState(){return this.state.tree.snapshot()}adminGet(t){const n=this.state.tree.read(t);return this.state.events.operation(null,"get",t,"not-applicable",void 0,{origin:"admin",resourceBefore:{data:n,exists:n!==null}}),n}adminGetQuery(t,n){const r=ze(this.state.tree.read(t),n,this.state.priorities.forChild(t));return this.state.events.operation(null,"get",t,"not-applicable",void 0,{origin:"admin",request:{query:n},resourceBefore:{data:Vs(r),exists:r.length>0}}),r}adminSet(t,n){this.adminSetWithPriority(t,n,null,!1)}adminSetWithPriority(t,n,r,s=!0){sn(r);const i=Date.now(),a=this.state.tree.read(t),c=Be(we(n,i,a),t==="/"?"":t),l=c===null?"remove":"set";this.state.events.operation(null,l,t,"not-applicable",void 0,{origin:"admin",request:{data:n,resourceData:n},resourceBefore:{data:a,exists:a!==null},resourceAfter:{data:c,exists:c!==null}});const u=this.children.snapshotParents(),d=this.state.priorities.get(t),p=this.state.priorities.stateAtOrBelow(t);this.state.tree.write(t,c),this.state.priorities.replace(t,c===null?null:r);const f=p!==this.state.priorities.stateAtOrBelow(t);this.changed([t],u,f?t:void 0);const m=this.state.tree.read(t);this.state.events.commit(null,m===null?"remove":"set",t,{data:n,priorState:a,nextState:m,replay:{requestTime:i},detail:s?{admin:!0,priority:r,priorPriority:d}:{admin:!0}}),this.state.notifyWrite()}adminUpdate(t,n){const r=Date.now(),s=this.state.tree.read(t),i=this.resolvePatch(t,n,r),a=Object.keys(n).some(u=>u.includes("/"));this.state.events.operation(null,"update",t,"not-applicable",void 0,{origin:"admin",request:{data:n,resourceData:n},resourceBefore:{data:s,exists:s!==null},detail:a?{admin:!0,multiPath:!0,paths:Object.keys(i)}:{admin:!0,multiPath:!1,keys:Object.keys(n)}});const c=this.children.snapshotParents();a?this.state.tree.multiUpdate(i):this.state.tree.shallowUpdate(t,Object.fromEntries(Object.entries(i).map(([u,d])=>[L(u).at(-1),d]))),this.state.priorities.applyUpdate(Object.entries(i).map(([u,d])=>({path:u,value:d}))),this.changed(Object.keys(i),c);const l=a?{admin:!0,multiPath:!0,paths:Object.keys(i)}:{admin:!0,multiPath:!1,keys:Object.keys(n)};this.state.events.commit(null,"update",t,{data:n,priorState:s,nextState:this.state.tree.read(t),replay:{requestTime:r},detail:l}),this.state.notifyWrite()}adminRemove(t){this.adminSet(t,null)}adminSetPriority(t,n){this.priorityWrites.adminSet(t,n)}get(t,n){const r=Date.now(),s=this.state.tree.read(n),i=this.readEvaluation(t,n);if(i.check!=="allow")throw this.state.events.operation(t,"get",n,he(i.check),i,{at:r,durationMs:Date.now()-r,resourceBefore:{data:s,exists:s!==null}}),ve();return this.state.events.operation(t,"get",n,"allow",i,{at:r,durationMs:Date.now()-r,resourceBefore:{data:s,exists:s!==null}}),this.state.tree.read(n)}getQuery(t,n,r){const s=Date.now(),i=this.readEvaluation(t,n);if(i.check!=="allow")throw this.state.events.operation(t,"get",n,he(i.check),i,{at:s,durationMs:Date.now()-s,request:{query:r}}),ve();const a=ze(this.state.tree.read(n),r,this.state.priorities.forChild(n));return this.state.events.operation(t,"get",n,"allow",i,{at:s,durationMs:Date.now()-s,request:{query:r},resourceBefore:{data:Vs(a),exists:a.length>0}}),a}set(t,n,r){this.setInternal(t,n,r,"set",null,!1)}setWithPriority(t,n,r,s){sn(s),this.setInternal(t,n,r,"set",s,!0)}remove(t,n){this.setInternal(t,n,null,"remove",null,!1)}setPriority(t,n,r){this.priorityWrites.set(t,n,r)}validateSet(t,n,r){const s=Be(we(r,Date.now(),this.state.tree.read(n)),n==="/"?"":n);if(this.writeEvaluation(t,n,s).check!=="allow")throw ve()}validateUpdate(t,n,r){const s=this.state.tree.snapshot(),i=Object.entries(r).map(([a,c])=>{const l=J([...L(n),...L(a)]);return{path:l,value:Be(we(c,Date.now(),this.state.tree.read(l)),l)}});for(const a of i)if(this.state.rules.evaluate("write",a.path,{auth:t,mockData:s,newData:a.value,...i.length>1?{updates:i}:{}}).check!=="allow")throw ve()}update(t,n,r){const s=Date.now(),i=this.resolvePatch(n,r,s),a=Object.keys(r).some(y=>y.includes("/")),c=this.state.tree.snapshot(),l=Object.entries(i).map(([y,g])=>({path:y,value:g})),u=Object.fromEntries(Object.entries(i).map(([y,g])=>[L(y).at(-1),g])),d=this.state.events.nextGroupId("update");for(const y of l){const g=Date.now(),v=this.state.tree.read(y.path),b=this.state.rules.evaluate("write",y.path,{auth:t,mockData:c,newData:y.value,...a?{updates:l}:{}}),w={at:g,durationMs:Date.now()-g,origin:"batch",request:{data:y.value,resourceData:y.value},resourceBefore:{data:v,exists:v!==null},resourceAfter:{data:y.value,exists:y.value!==null},groupId:d,groupKind:"batch",detail:a?{multiPath:!0,rootPath:xe(n)}:{multiPath:!1,rootPath:xe(n),key:L(y.path).at(-1)}};if(b.check!=="allow")throw this.state.events.operation(t,"update",y.path,he(b.check),b,w),ve();this.state.events.operation(t,"update",y.path,"allow",b,w)}const p=this.state.tree.read(n),f=this.children.snapshotParents();a?this.state.tree.multiUpdate(i):this.state.tree.shallowUpdate(n,u),this.state.priorities.applyUpdate(l),this.changed(Object.keys(i),f);const m=this.state.tree.read(n);this.state.events.commit(t,"update",n,{data:r,priorState:p,nextState:m,groupId:d,groupKind:"batch",replay:{requestTime:s},detail:a?{multiPath:!0,paths:Object.keys(i)}:{multiPath:!1,keys:Object.keys(u)}}),this.state.events.mutation(t,"update",xe(n),{after:a?i:u,detail:a?{multiPath:!0,paths:Object.keys(i)}:{multiPath:!1,keys:Object.keys(u)}}),this.state.notifyWrite()}setInternal(t,n,r,s,i,a){const c=Date.now(),l=Be(we(r,c,this.state.tree.read(n)),n==="/"?"":n),u=this.state.tree.read(n),d=this.state.priorities.get(n),p=Date.now(),f=this.writeEvaluation(t,n,l),m={at:p,durationMs:Date.now()-p,request:{data:r,resourceData:r},resourceBefore:{data:u,exists:u!==null},resourceAfter:{data:l,exists:l!==null}};if(f.check!=="allow")throw this.state.events.operation(t,s,n,he(f.check),f,m),ve();this.state.events.operation(t,s,n,"allow",f,m);const y=this.children.snapshotParents(),g=this.state.priorities.stateAtOrBelow(n);this.state.tree.write(n,l),this.state.priorities.replace(n,l===null?null:i);const v=g!==this.state.priorities.stateAtOrBelow(n);this.changed([n],y,v?n:void 0);const b=this.state.tree.read(n),w=b===null?"remove":s;this.state.events.commit(t,w,n,{data:r,priorState:u,nextState:b,replay:{requestTime:c},...a?{detail:{priority:i,priorPriority:d}}:{}}),this.state.events.mutation(t,w,xe(n),{before:u,after:b}),this.state.notifyWrite()}resolvePatch(t,n,r){return Object.fromEntries(Object.entries(n).map(([s,i])=>{const a=J([...L(t),...L(s)]);return[a,Be(we(i,r,this.state.tree.read(a)),a)]}))}changed(t,n,r){this.state.mutations.mark(t),this.values.fanOut(t),this.children.fanOut(n,r)}cancelDeniedListeners(){const t=this.state.tree.snapshot(),n=[];for(const s of[...this.state.valueListeners]){const i=this.state.rules.evaluate("read",s.path,{auth:s.auth,mockData:t});if(i.check==="allow")continue;this.state.valueListeners.delete(s),this.state.events.operation(s.auth,"listen",s.path,he(i.check),i,{origin:"listener"});const a={engine:"rtdb",matchedPath:i.matchedPath,matchedRule:i.matchedRule,pathVariableBindings:i.pathVariableBindings,reason:i.reason,errorCode:i.errorCode};this.state.events.listener("errored",s,s.auth,{event:"value",result:"deny",error:{code:"PERMISSION_DENIED",message:"PERMISSION_DENIED: Permission denied",reasons:i.reasons},reasons:i.reasons,rules:a}),n.push(s)}const r=[];for(const s of[...this.state.childListeners]){const i=this.state.rules.evaluate("read",s.path,{auth:s.auth,mockData:t});if(i.check==="allow")continue;this.state.childListeners.delete(s),this.state.events.operation(s.auth,"listen",s.path,he(i.check),i,{origin:"listener",detail:{event:s.event}});const a={engine:"rtdb",matchedPath:i.matchedPath,matchedRule:i.matchedRule,pathVariableBindings:i.pathVariableBindings,reason:i.reason,errorCode:i.errorCode};this.state.events.listener("errored",s,s.auth,{event:s.event,result:"deny",error:{code:"PERMISSION_DENIED",message:"PERMISSION_DENIED: Permission denied",reasons:i.reasons},reasons:i.reasons,rules:a}),r.push(s)}for(const s of[...n,...r]){try{s.onCanceled&&s.onCanceled()}catch{}try{s.cancelCallback&&s.cancelCallback(ts(s.path))}catch{}}}readEvaluation(t,n){return this.state.rules.evaluate("read",n==="/"?"/":n,{auth:t,mockData:this.state.tree.snapshot()})}writeEvaluation(t,n,r){return this.state.rules.evaluate("write",n==="/"?"/":n,{auth:t,mockData:this.state.tree.snapshot(),newData:r})}}class fd{state;values;children;writes;transactions;persistence;constructor(t){this.state=new zu(t),this.values=new Qu(this.state),this.children=new Zu(this.state),this.writes=new dd(this.state,this.values,this.children),this.transactions=new ld(this.state,this.values,this.children),this.persistence=new td(this.state,this.values,this.children)}get connectionResetGeneration(){return this.state.resetGeneration}get transactionMutationHistory(){return this.state.mutations.entries}invalidateConnectionQueues(){this.state.resetGeneration+=1}getPriority(t){return this.state.priorities.get(t)}setData(t){this.writes.setData(t)}setRules(t){this.writes.setRules(t)}setDefaultPolicy(t){this.writes.setDefaultPolicy(t)}getActiveRules(){return this.writes.getActiveRules()}snapshotState(){return this.writes.snapshotState()}adminGet(t){return this.writes.adminGet(t)}adminGetQuery(t,n){return this.writes.adminGetQuery(t,n)}adminSet(t,n){this.writes.adminSet(t,n)}adminSetWithPriority(t,n,r){this.writes.adminSetWithPriority(t,n,r)}adminUpdate(t,n){this.writes.adminUpdate(t,n)}adminRemove(t){this.writes.adminRemove(t)}adminSetPriority(t,n){this.writes.adminSetPriority(t,n)}get(t,n){return this.writes.get(t,n)}getQuery(t,n,r){return this.writes.getQuery(t,n,r)}set(t,n,r){this.writes.set(t,n,r)}setWithPriority(t,n,r,s){this.writes.setWithPriority(t,n,r,s)}update(t,n,r){this.writes.update(t,n,r)}remove(t,n){this.writes.remove(t,n)}setPriority(t,n,r){this.writes.setPriority(t,n,r)}validateSet(t,n,r){this.writes.validateSet(t,n,r)}validateUpdate(t,n,r){this.writes.validateUpdate(t,n,r)}onValue(t,n,r,s,i,a){return this.values.onValue(t,n,r,s,i,a)}adminOnValue(t,n,r){return this.values.adminOnValue(t,n,r)}runTransaction(t,n,r,s){return this.transactions.run(t,n,r,s)}onChild(t,n,r,s,i,a,c){return this.children.onChild(t,n,r,s,i,a,c)}off(t,n,r){(n===void 0||n==="value")&&this.values.off(t,r),n!=="value"&&this.children.off(t,n,r)}exportTree(){return this.persistence.exportTree()}exportPersistenceState(){return this.persistence.exportState()}restoreTree(t){this.persistence.restore(t)}resetTree(){this.persistence.reset()}subscribeWrites(t){return this.persistence.subscribe(t)}mintKey(){return Tl()}listenerCount(){return this.values.count()}childListenerCount(){return this.children.count()}}const qs=new WeakMap;function Ka(e){let t=qs.get(e);if(t)return t;t=new fd(e),qs.set(e,t);const n=t;return e.onEvent(r=>{r.kind==="session_boundary"&&r.phase==="reset"&&n.invalidateConnectionQueues()}),e.registerPersistableService("rtdb",{snapshot:()=>n.exportPersistenceState(),restore:r=>{n.restoreTree(r)},subscribe:r=>n.subscribeWrites(r),reset:()=>{n.resetTree()}}),t}function Ha(e){return Ka(e).getActiveRules()}function Ws(e){return Ka(e).snapshotState()}const Ga=new WeakMap;function hd(e){return Ga.get(e)?.raw??e}const pd=new WeakMap,zs=new WeakMap;function gr(e,t,n,r,s){Ga.set(e,{target:n,path:t.ref.path,kind:s,converter:r,raw:t})}function md(e,t){const n=cr(e),r=cr(t);return n.isStructurallyEqual?.(r)??n===r}function yd(e,t,n,r){const s=e,i=(zs.get(s)??[]).filter(c=>c.query.deref()!==void 0),a=i.find(c=>{const l=c.query.deref();return l!==void 0&&md(l,t)});if(a!==void 0){const c=bd(a.docs,n)&&a.metadata.fromCache===r.fromCache&&a.metadata.hasPendingWrites===r.hasPendingWrites;return a.docs=n,a.metadata=r,c?"settled":"initial"}return i.push({query:new WeakRef(t),docs:n,metadata:r}),zs.set(s,i),"initial"}function bd(e,t){return e.length===t.length&&e.every((n,r)=>{const s=t[r];return n.path===s.path&&Ul(n.data,s.data)})}function vr(e,t,n,r,s){const i=t,a=d=>({path:d.ref?.path??"",data:Xr(d.data?.(),n)}),c=Object.freeze((i.docs??[]).map(a)),l=Object.freeze((i.docChanges?.()??[]).map(d=>({...a(d.doc??{}),type:d.type??"",oldIndex:d.oldIndex??-1,newIndex:d.newIndex??-1}))),u=Object.freeze({fromCache:i.metadata?.fromCache===!0,hasPendingWrites:i.metadata?.hasPendingWrites===!0});pd.set(e,{target:n,query:r,converter:jn(r)??null,source:s,...s==="read"?{readPhase:yd(n,r,c,u)}:{},metadata:u,docs:c,changes:l})}function on(e,t){const n=e,r=n.data.bind(e);return Object.defineProperty(n,"data",{value:()=>Da(r()),configurable:!0,writable:!0}),t&&n.ref?.path&&Object.defineProperty(n,"metadata",{value:Ie(t).snapshotMetadata(n.ref.path),configurable:!0}),e}function Ja(e,t,n,r){const s={id:e.id,ref:e.ref,exists:e.exists,metadata:Ie(n).snapshotMetadata(e.ref.path),data:()=>{if(!(typeof e.exists=="function"?e.exists():e.exists))return;const a=Da(e.data()),c={id:e.id,ref:e.ref,exists:!0,metadata:Ie(n).snapshotMetadata(e.ref.path),data:()=>a};return t.fromFirestore(c)}};return Ve(s,n),Ve(e.ref,n),wr(e.ref,n),gr(s,e,n,t,r),s}function En(e,t){if(!e||typeof e!="object")return e;Ve(e,t);const n=e;if(n.ref&&(Ve(n.ref,t),wr(n.ref,t)),Ks(n),Array.isArray(n.docs))for(const r of n.docs)r&&(Ve(r,t),gr(r,r,t,null,"query-child")),r?.ref&&(Ve(r.ref,t),wr(r.ref,t)),r&&Ks(r);else n.ref&&gr(e,e,t,null,"document");return e}function wr(e,t){if(typeof e.path!="string"||e.path.length===0)return;const n=e.path;try{const r=Cs.get(e),s=r??Qr(t).doc(n);r===void 0&&Cs.set(e,s),bl(e,n,t,s),t.kind==="sandbox-live"&&Pa.set(s,i=>i.doc(n))}catch{}}function Ks(e){const t=e.exists;if(typeof t=="function")return;const n=t===!0;try{Object.defineProperty(e,"exists",{value:()=>n,writable:!0,configurable:!0,enumerable:!0})}catch{}}async function Ya(e){const t=kn(e),n=Ie(t);n.markStarted();const r=jn(e),s=await Bl(t,e).get();return n.cachePath(e.path),r?Ja(s,r,t,"document"):(En(s,t),on(s,t))}async function cn(e){const t=kn(e),n=Ie(t);n.markStarted();const r=jn(e),s=await Ll(t,e).get();if(n.cacheQuery(e),r){const a=r,c=s.docs.map(u=>Ja(u,a,t,"query-child")),l=Ve({size:c.length,empty:c.length===0,docs:c,metadata:n.querySnapshotMetadata()},t);for(const u of c)n.cachePath(u.ref.path);return vr(l,s,t,e,"read"),l}En(s,t);const i=s.docs;for(const a of i)n.cachePath(a.ref.path),on(a,t);return Object.defineProperty(s,"metadata",{value:n.querySnapshotMetadata(),configurable:!0}),vr(s,s,t,e,"read"),s}function Qa(e){return typeof e=="string"?e:e._internalPath.segments.join(".")}function ln(e,...t){const n=kn(e),r=jn(e),s=Fl(e);let i,a;try{i=t.map(u=>u.prepareSandbox?.(n)??u)}catch(u){throw Ns(u)}const c=u=>{let d=s(u);for(const p of i)d=p.applySandbox(d);return d};try{a=c(Qr(n))}catch(u){throw Ns(u)}const l=Vl(a,n,u=>c(u));return r?ql(l,n,r):l}function gd(e,t,n){return Xa(Qa(e),t,n,!1)}function Xa(e,t,n,r){return{type:"where",applySandbox:i=>i.where(e,t,n),prepareSandbox:r?void 0:i=>{const a=Xr(n,i,t==="in"||t==="not-in");return Xa(e,t,a.executionValue,!0)},_sandboxFilter:{kind:"where",field:e,op:t,value:n}}}function Hs(e,t){const n=Qa(e);return{type:"orderBy",applySandbox:r=>r.orderBy(n,t)}}function un(e){return{type:"limit",applySandbox:t=>t.limit(e)}}function vd(e){if(e.length!==1)return!1;const t=e[0];return t!==null&&typeof t=="object"&&"data"in t&&typeof t.data=="function"}function wd(...e){return vd(e)?Za(e[0],!1,!0):eo(e,!1,!0)}function Za(e,t,n,r=!1){return{type:n?"startAt":"endAt",applySandbox:s=>n?s.startCursorFromSnapshot(e,t):s.endCursorFromSnapshot(e,t),prepareSandbox:r?void 0:()=>{const s=hd(e),i=s.data(),a=Object.freeze({id:s.id,ref:s.ref,exists:i!==void 0,data:()=>i});return Za(a,t,n,!0)}}}function eo(e,t,n,r=!1){return{type:n?"startAt":"endAt",applySandbox:s=>n?s.startCursor([...e],t):s.endCursor([...e],t),prepareSandbox:r?void 0:s=>eo(e.map(i=>Xr(i,s).executionValue),t,n,!0)}}function xd(e,t,n,r){const s=kn(e);Ie(s).markStarted();const i=kd(s,e),a=_d(t,n,r,s,e),c=Sd(a,s),l=c.length===3?i.onSnapshot(c[0],c[1],c[2]):c.length===2?i.onSnapshot(c[0],c[1]):i.onSnapshot(c[0]);if(!s.own)return l;let u=!1;const d=()=>{u||(u=!0,l())},p=()=>{u||(d(),jd(c)?.(new ht("aborted","The operation was aborted.")))},f=s.own(p);return()=>{f(),d()}}function jd(e){const t=e.at(-1);if(typeof t=="function"&&e.length>=3)return t;if(t&&typeof t=="object"){const n=t.error;if(typeof n=="function")return n}}function kd(e,t){const n=cr(t);if(e.kind==="sandbox")return n;const r=Pa.get(n);if(!r)throw new TypeError("pyric/firestore: live ref missing rebuild closure for onSnapshot.");return r(Qr(e))}function to(e){if(typeof e!="object"||e===null)return!1;const t=e;return typeof t.next=="function"||typeof t.error=="function"||typeof t.complete=="function"}function _d(e,t,n,r,s){if(typeof e=="object"&&e!==null&&!to(e)){const a=t;return typeof a=="function"?[e,Gs(a,r,s),n??xr]:a&&typeof a=="object"?[e,Js(a,r,s)]:[e]}return typeof e=="function"?[Gs(e,r,s),t??xr]:e&&typeof e=="object"?[Js(e,r,s)]:[e]}function Sd(e,t){if(t.kind!=="sandbox-live")return e;const n=e[0];return typeof n=="object"&&n!==null&&!to(n)?[{...n,[As]:!0,...t.authScope?{[Rs]:t.authScope}:{}},...e.slice(1)]:[{[As]:!0,...t.authScope?{[Rs]:t.authScope}:{}},...e]}function no(e,t,n){if(!e||typeof e!="object")return e;const r=e;if(typeof r.data=="function"&&on(e,t),Array.isArray(r.docs)){for(const s of r.docs)on(s,t);vr(e,e,t,n,"listener")}return e}function xr(e){console.error("pyric/firestore: Uncaught Error in snapshot listener:",e)}function Gs(e,t,n){return r=>{e(no(En(r,t),t,n)),Ie(t).notifySnapshotDelivered()}}function Js(e,t,n){return{...e,next:e.next?r=>{e.next(no(En(r,t),t,n)),Ie(t).notifySnapshotDelivered()}:void 0,error:e.error??xr}}const Se={description:"Identity to act as. Omit or 'admin' = admin write that BYPASSES rules (sandbox seeding). { uid, claims? } = act as that user with rules ENFORCED.",oneOf:[{type:"string",enum:["admin"]},{type:"object",properties:{uid:{type:"string"},claims:{type:"object",description:"Custom claims forwarded to the rule context (request.auth.token)."}},required:["uid"]}]},Ed=["<","<=","==","!=",">=",">","in","not-in","array-contains","array-contains-any"],Cd={type:"object",properties:{field:{type:"string"},op:{type:"string",enum:[...Ed]},value:{}},required:["field","op","value"]};function ro(e){const{resolveDb:t}=e;return[{name:"firestore_get_document",description:"Get a Firestore document by path. Admin by default; pass `as:{uid}` to read with rules enforced as that user.",parameters:{type:"object",properties:{path:{type:"string",description:'e.g. "users/alice"'},as:Se},required:["path"]},async execute(n){const r=n,s=await t(r.as),i=Fe(s,r.path),a=await Ya(i),c=typeof a.exists=="function"?a.exists():a.exists;return{ok:!0,summary:c?`Got ${r.path}`:`No document at ${r.path}`,data:{exists:c,data:c?a.data():null}}}},{name:"firestore_list_documents",description:"List documents in a collection. Supports orderBy + limit. Admin by default; pass `as:{uid}` to enforce rules.",parameters:{type:"object",properties:{collection:{type:"string"},orderBy:{type:"string"},limit:{type:"number"},as:Se},required:["collection"]},async execute(n){const r=n,s=await t(r.as),i=Et(s,r.collection),a=[];r.orderBy&&a.push(Hs(r.orderBy)),r.limit&&a.push(un(r.limit));const c=await cn(ln(i,...a));return{ok:!0,summary:`${c.size} docs in ${r.collection}`,data:{docs:c.docs.map(l=>({id:l.id,data:l.data()}))}}}},{name:"firestore_create_document",description:"Create or replace a Firestore document at an explicit path. Admin by default (bypasses rules — for seeding); pass `as:{uid}` to write as that user with rules enforced.",parameters:{type:"object",properties:{path:{type:"string"},data:{type:"object"},as:Se},required:["path","data"]},async execute(n){const r=n,s=await t(r.as);return await tn(Fe(s,r.path),r.data),{ok:!0,summary:`Created ${r.path}`}}},{name:"firestore_add_document",description:"Add a document with an auto-generated id under a collection (mirrors the Web SDK addDoc). Admin by default — the right tool for seeding; pass `as:{uid}` to write as a user with rules enforced. Returns the minted path.",parameters:{type:"object",properties:{collection:{type:"string",description:'Collection to add the doc under, e.g. "users" or "users/u1/posts".'},data:{type:"object"},as:Se},required:["collection","data"]},async execute(n){const r=n,s=await t(r.as),i=await $a(Et(s,r.collection),r.data);return{ok:!0,summary:`Created ${i.path}`,data:{path:i.path,id:i.id}}}},{name:"firestore_update_document",description:"Merge fields into an existing Firestore document. Admin by default; pass `as:{uid}` to enforce rules.",parameters:{type:"object",properties:{path:{type:"string"},data:{type:"object"},as:Se},required:["path","data"]},async execute(n){const r=n,s=await t(r.as);return await Is(Fe(s,r.path),r.data),{ok:!0,summary:`Updated ${r.path}`}}},{name:"firestore_delete_document",description:"Delete a Firestore document. Admin by default; pass `as:{uid}` to enforce rules.",parameters:{type:"object",properties:{path:{type:"string"},as:Se},required:["path"]},async execute(n){const r=n,s=await t(r.as);return await lr(Fe(s,r.path)),{ok:!0,summary:`Deleted ${r.path}`}}},{name:"firestore_batch_write",description:"Apply many writes (set / update / delete) in ONE call — the efficient way to seed or bulk-edit (one call, not N). Applied in order; stops on the first failure. Admin by default; pass `as:{uid}` to apply them as a user with rules enforced. Up to 500 ops.",parameters:{type:"object",properties:{operations:{type:"array",description:"Writes applied in order; stops on the first failure (NOT atomic — earlier writes are not rolled back).",minItems:1,maxItems:500,items:{type:"object",properties:{op:{type:"string",enum:["set","update","delete"]},path:{type:"string"},data:{type:"object",description:"Required for set/update; ignored for delete."}},required:["op","path"]}},as:Se},required:["operations"]},async execute(n){const r=n;if(r.operations.length===0||r.operations.length>500)return{ok:!1,summary:`firestore_batch_write: operations must be 1..500 (got ${r.operations.length}).`};const s=await t(r.as);for(const i of r.operations){const a=Fe(s,i.path);i.op==="set"?await tn(a,i.data??{}):i.op==="update"?await Is(a,i.data??{}):await lr(a)}return{ok:!0,summary:`Applied ${r.operations.length} write(s)`,data:{count:r.operations.length}}}},{name:"firestore_query_where",description:"Query a collection with one or more where clauses (AND-semantics) + optional orderBy + limit. For OR semantics use a single where clause with the `in` / `array-contains-any` op. Admin by default; pass `as:{uid}` to enforce rules.",parameters:{type:"object",properties:{collection:{type:"string"},where:{type:"array",description:"One or more where clauses. AND across clauses.",items:Cd,minItems:1},orderBy:{type:"string"},limit:{type:"number"},as:Se},required:["collection","where"]},async execute(n){const r=n,s=await t(r.as),i=Et(s,r.collection),a=r.where.map(l=>gd(l.field,l.op,l.value));r.orderBy&&a.push(Hs(r.orderBy)),r.limit&&a.push(un(r.limit));const c=await cn(ln(i,...a));return{ok:!0,summary:`${c.size} matches in ${r.collection}`,data:{docs:c.docs.map(l=>({id:l.id,data:l.data()}))}}}}]}function so(e){const{resolveSandbox:t}=e;return[{name:"sandbox_inspect",description:"Single-call sandbox diagnostic. Returns current rules source, lint summary, doc count by collection, and recent denials + requests. Use this FIRST when debugging unexpected sandbox behavior — it surfaces the rules / state / event log without forcing per-tool grep.",parameters:{type:"object",properties:{recentEventLimit:{type:"number",description:"Cap on recent denials/requests returned. Default 10.",default:10}}},async execute(n){const r=n,s=await t(),i=gl(s,{recentEventLimit:r.recentEventLimit});return{ok:!0,summary:`rules: ${i.rules.isEmpty?"EMPTY (setRules has not been called)":`${i.rules.sizeBytes}B, ${i.rules.lint.errors} errors / ${i.rules.lint.warnings} warnings`} · docs: ${i.documents.totalCount} across ${Object.keys(i.documents.byCollection).length} collections · events: ${i.events.totalCount} total, ${i.events.recentDenials.length} recent denials`,data:i}}}]}const Nd="modulepreload",Rd=function(e){return"/__pyric/ui/"+e},Ys={},io=function(t,n,r){let s=Promise.resolve();if(n&&n.length>0){let a=function(u){return Promise.all(u.map(d=>Promise.resolve(d).then(p=>({status:"fulfilled",value:p}),p=>({status:"rejected",reason:p}))))};document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),l=c?.nonce||c?.getAttribute("nonce");s=a(n.map(u=>{if(u=Rd(u),u in Ys)return;Ys[u]=!0;const d=u.endsWith(".css"),p=d?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${p}`))return;const f=document.createElement("link");if(f.rel=d?"stylesheet":Nd,d||(f.as="script"),f.crossOrigin="",f.href=u,l&&f.setAttribute("nonce",l),document.head.appendChild(f),d)return new Promise((m,y)=>{f.addEventListener("load",m),f.addEventListener("error",()=>y(new Error(`Unable to preload CSS for ${u}`)))})}))}function i(a){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=a,window.dispatchEvent(c),!c.defaultPrevented)throw a}return s.then(a=>{for(const c of a||[])c.status==="rejected"&&i(c.reason);return t().catch(i)})};function ao(e){return e.kind==="session_boundary"&&e.phase==="reset"}function Ad(e,t){return ao(t)?[t]:[...e,t]}const oo=h.createContext(null),co={status:"disabled",handles:null,events:[]};function Id({children:e}){return o.jsx(oo.Provider,{value:co,children:e})}function $e(){return h.useContext(oo)??co}function Le(e,t){return`${e.replace(/\/$/,"")}${t}`}const zn=new Map;let Kn=null;function Dd(e){return e||(Kn||(Kn=`studio-writer-${Math.random().toString(36).slice(2)}`),Kn)}function lo(e){return{token:e?.token,writerId:e?.writerId}}async function uo(e,t){if(t)return t;const n=e.replace(/\/$/,""),r=zn.get(n);if(r)return r;const s=fetch(Le(n,"/__pyric/init.json")).then(i=>i.ok?i.json():null).then(i=>typeof i?.sessionToken=="string"?i.sessionToken:null).catch(()=>null).then(i=>(i||zn.delete(n),i));return zn.set(n,s),s}async function fo(e,t,n=!1){const r={},{token:s,writerId:i}=lo(t);n&&(r["x-pyric-writer"]=Dd(i));const a=await uo(e,s);return a&&(r["x-pyric-session-token"]=a),r}function Pd(e,t){const n=e,{token:r}=lo(t),s=(i=!1)=>fo(n,t,i);return{async read(i){const a=await s(!1),c=await fetch(Le(n,`/__pyric/workspace?path=${encodeURIComponent(i)}`),{headers:a});if(c.status===404)return null;if(!c.ok)throw new Error(`workspace.read(${i}) → ${c.status}`);return c.text()},async write(i,a){const c=await s(!0),l=await fetch(Le(n,`/__pyric/workspace?path=${encodeURIComponent(i)}`),{method:"PUT",headers:c,body:a});if(!l.ok)throw new Error(`workspace.write(${i}) → ${l.status}`)},async list(i){const a=await s(!1),c=i?`?dir=${encodeURIComponent(i)}`:"",l=await fetch(Le(n,`/__pyric/workspace/list${c}`),{headers:a});if(!l.ok)throw new Error(`workspace.list(${i??""}) → ${l.status}`);return await l.json()},async remove(i){const a=await s(!0),c=await fetch(Le(n,`/__pyric/workspace?path=${encodeURIComponent(i)}`),{method:"DELETE",headers:a});if(!c.ok)throw new Error(`workspace.remove(${i}) → ${c.status}`)},watch(i){let a=null,c=!1;const l=u=>{try{i(JSON.parse(u.data))}catch{}};return uo(n,r).then(u=>{if(c)return;const d=u?Le(n,`/__pyric/workspace/watch?token=${encodeURIComponent(u)}`):Le(n,"/__pyric/workspace/watch");a=new EventSource(d),a.addEventListener("change",l)}),()=>{c=!0,a&&(a.removeEventListener("change",l),a.close())}}}}function wt(e,t){return`${e.replace(/\/$/,"")}${t}`}function $d(e,t){const n=e,r=(s=!1)=>fo(n,t,s);return{async list(){const s=await r(!1),i=await fetch(wt(n,"/__pyric/projects"),{headers:s});if(!i.ok)throw new Error(`projects.list() → ${i.status}`);return await i.json()},async open(s){const i=await r(!1),a=await fetch(wt(n,`/__pyric/projects/${encodeURIComponent(s)}`),{headers:i});if(!a.ok)throw new Error(`projects.open(${s}) → ${a.status}`);return{meta:await a.json(),workspace:Pd(n,t)}},async create(s){const a={...await r(!0),"content-type":"application/json"},c=await fetch(wt(n,"/__pyric/projects"),{method:"POST",headers:a,body:JSON.stringify(s)});if(!c.ok)throw new Error(`projects.create() → ${c.status}`);return await c.json()},async update(s,i){const c={...await r(!0),"content-type":"application/json"},l=await fetch(wt(n,`/__pyric/projects/${encodeURIComponent(s)}`),{method:"PATCH",headers:c,body:JSON.stringify(i)});if(!l.ok)throw new Error(`projects.update(${s}) → ${l.status}`)},async remove(s){const i=await r(!0),a=await fetch(wt(n,`/__pyric/projects/${encodeURIComponent(s)}`),{method:"DELETE",headers:i});if(!a.ok)throw new Error(`projects.remove(${s}) → ${a.status}`)}}}function Od(e,t){return`${e.replace(/\/$/,"")}${t}`}function Hn(e){return/auth/i.test(e)?"auth":"firestore"}function Md(e){const t=e,r={"content-type":"application/json","x-pyric-writer":`studio-${Math.random().toString(36).slice(2)}`},s=new Map,i=l=>Od(t,`/__pyric/state?section=${Hn(l)}`),a=async l=>{const u=Hn(l),d=s.get(u);if(d)return d;const p=await fetch(i(l));let f=new Map;if(p.ok){const m=await p.text();m&&m!=="null"&&(f=vl(m))}else if(p.status!==404)throw new Error(`persistence.read(${l}) → ${p.status}`);return s.set(u,f),f},c=async(l,u)=>{const d=await fetch(i(l),{method:"POST",headers:r,body:wl(u)});if(d.status===423)throw new Error("persistence.write blocked, another tab holds the persist writer lock");if(!d.ok)throw new Error(`persistence.write(${l}) → ${d.status}`)};return{async getRecord(l,u){return(await a(l)).get(u)??null},async listRecords(l){return[...(await a(l)).keys()]},async putRecords(l,u){const d=await a(l);for(const[p,f]of u)d.set(p,f);await c(l,d)},async deleteRecords(l,u){const d=await a(l);for(const p of u)d.delete(p);await c(l,d)},async clear(l){s.set(Hn(l),new Map);const u=await fetch(i(l),{method:"POST",headers:r,body:"null"});if(!u.ok&&u.status!==423)throw new Error(`persistence.clear(${l}) → ${u.status}`)}}}const Td="local";function Ud(){const e=new Map,t=new Set,n=r=>{for(const s of t)s(r)};return{async read(r){return e.has(r)?e.get(r):null},async write(r,s){const i=e.has(r)?"update":"create";e.set(r,s),n({path:r,type:i})},async list(r){const s=r?`${r.replace(/\/+$/,"")}/`:"",i=[];for(const a of e.keys())s&&!a.startsWith(s)||i.push({path:a,kind:"file"});return i},async remove(r){e.delete(r)&&n({path:r,type:"delete"})},watch(r){return t.add(r),()=>t.delete(r)}}}function Bd(){const e=Ud();let t={id:Td,title:"Local Project",createdAt:Date.now(),updatedAt:Date.now()};return{async list(){return[t]},async open(n){if(n!==t.id)throw new Error(`Static Studio runs in single-project mode — no project '${n}'.`);return{meta:t,workspace:e}},async create(){throw new Error("Static Studio runs in single-project mode — creating additional projects is not supported.")},async update(n,r){n===t.id&&(t={...t,...r,updatedAt:Date.now()})},async remove(){}}}const Ld="/__pyric/sdk/worker.js",Ce="pyric-shared-worker",Fd="/__pyric/ui/studio";function ho(e=typeof document>"u"?void 0:document){const t=e?.querySelector('meta[name="pyric-worker-v"]')?.getAttribute("content")?.trim()||null;return{studioUrl:Fd,worker:{url:Ld,name:Ce,servedEpoch:t}}}const dn="pyric:worker-generation",xt="pyric:worker-generation-probe";function Vd(e,t){const n=e&&/^[a-f0-9]{16}$/.test(e)?e:null;if(!t)return n?`${Ce}:${n}`:Ce;try{const r=t.getItem(dn);return r&&/^[a-f0-9]{16}$/.test(r)?`${Ce}:${r}`:n?(t.setItem(dn,n),`${Ce}:${n}`):Ce}catch{return n?`${Ce}:${n}`:Ce}}function qd(e,t){if(!/^[a-f0-9]{16}$/.test(e))throw new Error("Pyric cannot replace the worker: invalid served worker epoch.");if(!t)throw new Error("Pyric cannot replace the worker because origin storage is unavailable. Close all tabs for this origin and reopen the app.");try{if(t.setItem(dn,e),t.getItem(dn)!==e)throw new Error("the worker generation could not be read back")}catch(n){throw new Error("Pyric cannot replace the worker because origin storage is unavailable. Close all tabs for this origin and reopen the app.",{cause:n})}}function Wd(e){if(!e?.removeItem)throw new Error("Pyric cannot replace the worker because origin storage is unavailable. Close all tabs for this origin and reopen the app.");try{const t=e.getItem(xt);if(e.setItem(xt,"ok"),e.getItem(xt)!=="ok")throw new Error("the worker generation probe could not be read back");t===null?e.removeItem(xt):e.setItem(xt,t)}catch(t){throw new Error("Pyric cannot replace the worker because origin storage is unavailable. Close all tabs for this origin and reopen the app.",{cause:t})}}function zd(e){const t=e.schedule??(s=>{setTimeout(s,100)});let n=!1;const r=e.subscribeReload(s=>{if(!n){try{e.commitGeneration(s)}catch(i){e.onPreparationError?.(i);return}n=!0,t(e.reload)}});return{async request(){e.preflight(),await e.retire()},dispose:r}}function Kd(){let e=null;const t=new Set;return{get currentUser(){return e},set currentUser(n){if(e!==n){e=n;for(const r of[...t])r(n)}},onCurrentUserChanged(n){return t.add(n),()=>t.delete(n)}}}const po=new WeakMap;let jr;function Hd(e,t,n=Kd()){const r=e.name,s=n===t?void 0:{},i=new Map,a=new Set,c={app:e,sandbox:t,session:n,services:i,cleanups:a,assertAlive(){if(c.deleted)throw new ht("app/app-deleted",`Firebase: Firebase App named '${r}' already deleted (app/app-deleted).`)},...s?{authScope:s}:{},service(l,u){const d=i.get(l);if(d!==void 0)return d;c.assertAlive();const p=u();return i.set(l,p),p},onDelete(l){return c.deleted?(l(),()=>{}):(a.add(l),()=>a.delete(l))},deleted:!1};return po.set(e,c),c}function Gd(e){jr=e}Wl({resolve(e,t){const n=typeof e=="object"&&e!==null?po.get(e):void 0;if(n)return n},defaultApp(){if(!jr)throw new TypeError("No default sandbox app registry is installed - import and initialize pyric/app before calling a service factory without an app.");return jr()}});const Jd="[DEFAULT]",Yd=new Map;function Qd(e,t){return new ht(`app/${e}`,`Firebase: ${t} (app/${e}).`)}function Xd(e){return Qd("no-app",`No Firebase App '${e}' has been created - call initializeApp() first`)}function Zd(e=Jd){const t=Yd.get(e);if(!t)throw Xd(e);return t.app}Gd(Zd);let ef=0,tf=0;function T(){return`op-${++ef}`}function pt(){return`sub-${++tf}`}const ct=new Map,Nt=new Map,Rt=new Map,mt=new WeakSet,kr=new Set;function nf(e){return kr.add(e),()=>kr.delete(e)}function mo(){return Object.assign(new Error("Firebase App was deleted"),{code:"app/app-deleted"})}function Ot(e,t,n,r){return mt.has(e)?!1:(Nt.set(t,n),e.postMessage(r),!0)}function rf(e,t,n,r){return mt.has(e)?!1:(Rt.set(t,{port:e,next:n}),e.postMessage(r),!0)}function Mt(e,t){Nt.delete(t),Rt.delete(t),mt.has(e)||e.postMessage({t:"unsub",subId:t})}function sf(e){mt.add(e);const t=mo();for(const[n,r]of[...ct])r.port===e&&(ct.delete(n),r.reject(t));for(const[n,r]of[...Nt])r.port===e&&(Nt.delete(n),r.service==="firestore"&&r.error?.(new ht("aborted","The operation was aborted.")));for(const[n,r]of[...Rt])r.port===e&&Rt.delete(n);e.onmessage=null}function Qs(e,t){if(t.denialContext===void 0||typeof fetch!="function")return;const n={kind:e,code:t.code,message:t.message,denialContext:t.denialContext,...typeof t.remediation=="string"?{remediation:t.remediation}:{}};try{fetch("/__pyric/denials",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(n)}).catch(()=>{})}catch{}}function ns(e){e.onmessage=t=>{const n=t.data;if(n.t==="res"){const r=ct.get(n.id);if(!r)return;if(ct.delete(n.id),n.ok)r.resolve(n.value);else{const s=new Error(n.error.message);s.code=n.error.code,n.error.denialContext!==void 0&&(s.denialContext=n.error.denialContext),n.error.aiEnvelope!==void 0&&(s.aiEnvelope=n.error.aiEnvelope),Qs("read",s),r.reject(s)}}else if(n.t==="snap"){const r=Nt.get(n.subId);if(!r)return;const s=n.value??{};if(s.__error){const i=s.__error,a=new Error(i.message);a.code=i.code,i.denialContext!==void 0&&(a.denialContext=i.denialContext),i.aiEnvelope!==void 0&&(a.aiEnvelope=i.aiEnvelope),Qs("listener",a),r.error?r.error(a):console.error("pyric/firestore: Uncaught Error in snapshot listener:",a);return}r.next(n.value)}else if(n.t==="event"){const r=Rt.get(n.subId);r&&r.next(n.events)}else if(n.t==="runtime-reload")for(const r of kr)r(n)}}let lt;function Xs(e){lt=e&&e.mode==="app-session"?void 0:e}function af(){return lt}let _r;function of(e){_r=e}function rs(e){return _r&&(e.t==="op"||e.t==="sub")?{...e,issuer:_r}:e}function ss(e,t){return mt.has(e)?Promise.reject(mo()):new Promise((n,r)=>{const s=t;ct.set(s.id,{port:e,resolve:n,reject:r}),e.postMessage(t)})}function W(e,t){return ss(e,rs(t))}function yo(e,t,n,r){const s=t.id;let i;const a=new Promise((c,l)=>{i=setTimeout(()=>{ct.delete(s)&&l(new Error(r))},n)});return Promise.race([W(e,t),a]).finally(()=>{i&&clearTimeout(i)})}function de(e,t){if(mt.has(e)&&!t.method.startsWith("rtdb."))return Promise.reject(new ht("failed-precondition","The client has already been terminated."));const n=lt?{...t,actAs:lt}:t;return W(e,n)}async function cf(e,t,n={}){const r=n.timeoutMs??12e3;await yo(e.port,{t:"op",id:T(),method:"retireRuntime",targetEpoch:t},r,`Timed out waiting for the Pyric worker to retire after ${r}ms.`)}function lf(e){return nf(t=>e(t.epoch))}function uf(e,t,n={}){if(typeof SharedWorker>"u")throw new Error("SharedWorker is not available. Open this page over http:// (not file://) and use a supported browser (Chrome 4+, Firefox 29+, Safari 16.4+).");const r=new SharedWorker(e,{type:"classic",name:t??"pyric-shared-worker"});n.onError&&r.addEventListener("error",i=>{const a=i.message||`failed to load ${String(e)}`;n.onError?.(new Error(`Pyric SharedWorker error: ${a}`))});const s=r.port;return ns(s),s.start(),{__kind:"client-db",port:s}}async function df(e,t={}){const n=T(),r=t.timeoutMs??2e3;return(await yo(e.port,{t:"op",id:n,method:"getRuntimeEpoch"},r,`Timed out waiting for the Pyric SharedWorker version handshake after ${r}ms.`)).version}async function ff(e){return(await W(e.port,{t:"op",id:T(),method:"getVersion"})).instanceId??""}async function hf(e){return(await W(e.port,{t:"op",id:T(),method:"exportState"})).bundle}async function pf(e,t){await W(e.port,{t:"op",id:T(),method:"importState",bundle:t})}async function mf(e,t){await W(e.port,{t:"op",id:T(),method:"saveBranch",name:t})}async function yf(e){return(await W(e.port,{t:"op",id:T(),method:"listBranches"})).branches??[]}async function bf(e,t){await W(e.port,{t:"op",id:T(),method:"switchBranch",name:t})}async function gf(e,t){await W(e.port,{t:"op",id:T(),method:"deleteBranch",name:t})}async function vf(e,t,n){return await W(e.port,{t:"tool",id:T(),name:t,args:n})}function wf(e,t){return ss(e.port,{...t,issuer:void 0,relaySource:"remote",t:"op",id:T()})}function xf(e,t,n){if(t.target==="events")throw new Error("event-stream subscriptions cannot be relayed over the bridge yet (needs bounded backpressure — slice 2)");const r=pt();return Ot(e.port,r,{port:e.port,next:n,error:i=>n({__error:{code:i.code??"unknown",message:i instanceof Error?i.message:String(i)}})},{...t,issuer:void 0,relaySource:"remote",t:"sub",subId:r})||queueMicrotask(()=>n({__error:{code:"app/app-deleted",message:"Firebase App was deleted"}})),()=>{Mt(e.port,r)}}function jf(e){const t=(e??"/").split("/").filter(Boolean).join("/");return t?`/${t}`:"/"}const kf=[];function _f(e){for(const t of[...kf])t.port===e&&t.close()}const Sf=5e3;function Ef(){return Object.assign(new Error("Timed out waiting for SharedWorker app cleanup acknowledgment. Close all tabs using this pyric sandbox origin so the worker can restart."),{code:"app/delete-timeout"})}async function Cf(e,t={}){let n;try{const r=ss(e.port,{t:"disconnect",id:T()}),s=new Promise((i,a)=>{n=setTimeout(()=>a(Ef()),t.ackTimeoutMs??Sf)});await Promise.race([r,s])}finally{n!==void 0&&clearTimeout(n),_f(e.port),sf(e.port),e.port.close()}}function is(e){return e.split("/").at(-1)??e}function Nf(e,...t){const n=("port"in e,e.port);let r;if(e.__kind==="client-db"){if(t.length===0)throw new TypeError("doc(db, path) requires a path segment.");r=t.join("/")}else{const i=e.descriptor.path;r=t.length>0?`${i}/${t.join("/")}`:i}return{__kind:"doc-ref",descriptor:{__ref:"doc",path:r},port:n,id:is(r),path:r}}function Rf(e,...t){const n=e.port;if(t.length===0)throw new TypeError("collection() requires a path segment.");let r;return e.__kind==="client-db"?r=t.join("/"):r=`${e.descriptor.path}/${t.join("/")}`,{__kind:"coll-ref",descriptor:{__ref:"collection",path:r},port:n,id:is(r),path:r}}function Af(e){return{_descriptor:{kind:"limit",n:e}}}function If(...e){return{_descriptor:{kind:"startAfter",values:e}}}function Df(e,...t){const n=(e.__kind==="coll-ref",e.descriptor),r=e.__kind==="query"?e.descriptor.constraints:[];return{__kind:"query",descriptor:{__ref:"query",source:n.__ref==="query"?n.source:n,constraints:[...r,...t.map(i=>i._descriptor)]},port:e.port}}function Pf(e){return xl(JSON.parse(e.json))}const bo=8*1024*1024;function $f(e,t){const n=new Error(`${t} is ${e} bytes — over the ${bo/1048576} MiB storage op cap (MAX_STORAGE_OP_BYTES). Streaming/resumable transfers are not supported on the sandbox backend; split the object or keep it under the cap.`);return n.code="payload-too-large",n}function Of(e){let t="";for(let r=0;r<e.length;r+=32768){const s=e.subarray(r,r+32768);t+=String.fromCharCode.apply(null,s)}return btoa(t)}function Mf(e){return Pf(e)}function as(e,t){const n=e.exists&&e.data?Mf(e.data):void 0,r=e.path??e.id,s={__kind:"doc-ref",descriptor:{__ref:"doc",path:r},port:t,id:e.id,path:r};return{id:e.id,path:r,ref:s,exists:()=>e.exists,data:()=>n}}function go(e,t){const n=e.docs.map(r=>as(r,t));return{size:n.length,empty:n.length===0,docs:n}}async function Tf(e){const t=await de(e.port,{t:"op",id:T(),method:"getDoc",path:e.descriptor.path});return as(t,e.port)}async function Uf(e){const t=await de(e.port,{t:"op",id:T(),method:"getDocs",source:(e.__kind==="coll-ref",e.descriptor)});return go(t,e.port)}async function Bf(e){return(await de(e.port,{t:"op",id:T(),method:"listRootCollections"})).ids}async function Lf(e,t){return(await de(e.port,{t:"op",id:T(),method:"listSubcollections",docPath:t})).ids}function Ff(e,t,n){const r=pt(),s=e.port,i={port:s,service:"firestore",next:l=>{const u=l;"docs"in u?t(go(u,s)):t(as(u,s))},error:n},a=(e.__kind==="doc-ref"||e.__kind==="coll-ref",e.descriptor);return!Ot(s,r,i,rs(lt?{t:"sub",subId:r,target:a,actAs:lt}:{t:"sub",subId:r,target:a}))&&n&&queueMicrotask(()=>n(new Error("Firebase App was deleted"))),()=>{Mt(s,r)}}async function Vf(e,t,n){await de(e.port,{t:"op",id:T(),method:"setDoc",path:e.descriptor.path,data:t,options:n})}async function qf(e){await de(e.port,{t:"op",id:T(),method:"deleteDoc",path:e.descriptor.path})}async function Wf(e,t){const n=await de(e.port,{t:"op",id:T(),method:"addDoc",collectionPath:e.descriptor.path,data:t});return{__kind:"doc-ref",descriptor:{__ref:"doc",path:n.path},port:e.port,id:n.id,path:n.path}}async function zf(e,t){return await W(e.port,{t:"op",id:T(),method:"admin.listDocuments",path:t})}function Kf(e,t){const n=pt(),r=e.port;return rf(r,n,t,{t:"sub",subId:n,target:"events"}),()=>{Mt(r,n)}}async function Hf(e){return await W(e.port,{t:"op",id:T(),method:"getSnapshot"})}async function Gf(e){return await W(e.port,{t:"op",id:T(),method:"resetAll"})??{errors:[]}}const Jf=15e3;function Yf(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"}function Zs(){return typeof document<"u"&&typeof document.addEventListener=="function"&&typeof document.removeEventListener=="function"}function ei(){return typeof window<"u"&&typeof window.addEventListener=="function"&&typeof window.removeEventListener=="function"}function Qf(){return Yf()?crypto.randomUUID():`page-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function ti(){return typeof location>"u"?"/":`${location.pathname}${location.search}${location.hash}`}function ni(){return typeof document>"u"?"visible":document.visibilityState==="hidden"?"hidden":"visible"}function Xf(e){const{db:t,kind:n}=e,r=e.clientId??Qf(),s=e.heartbeatIntervalMs??Jf;let i=!1,a=null;const c=()=>{W(t.port,{t:"op",id:T(),method:"presence.register",clientId:r,kind:n,route:ti(),visibility:ni()}).catch(()=>{})},l=()=>{W(t.port,{t:"op",id:T(),method:"presence.heartbeat",clientId:r}).catch(()=>{})},u=()=>{W(t.port,{t:"op",id:T(),method:"presence.update",clientId:r,route:ti(),visibility:ni()}).catch(()=>{})},d=()=>{W(t.port,{t:"op",id:T(),method:"presence.disconnect",clientId:r}).catch(()=>{})};c(),Zs()&&document.addEventListener("visibilitychange",u),ei()&&(window.addEventListener("popstate",u),window.addEventListener("hashchange",u),window.addEventListener("pagehide",p),a=setInterval(()=>{i||l()},s));function p(){f()}function f(){i||(i=!0,a!=null&&(clearInterval(a),a=null),Zs()&&document.removeEventListener("visibilitychange",u),ei()&&(window.removeEventListener("popstate",u),window.removeEventListener("hashchange",u),window.removeEventListener("pagehide",p)),d())}return{clientId:r,kind:n,stop:f}}function Zf(e,t){const n=pt();return Ot(e.port,n,{port:e.port,next:r=>{t(r)}},{t:"sub",subId:n,target:"presence"}),()=>{Mt(e.port,n)}}const eh=Symbol("pyric.clientUser.port");function th(e,t){const n={uid:t.uid,email:t.email,emailVerified:t.emailVerified,displayName:t.displayName,photoURL:t.photoURL,phoneNumber:t.phoneNumber,isAnonymous:t.isAnonymous,providerId:t.providerId,providerData:t.providerData,async getIdToken(r){return await W(e,{t:"op",id:T(),method:"auth.getIdToken",forceRefresh:r})},async getIdTokenResult(r){return await W(e,{t:"op",id:T(),method:"auth.getIdTokenResult",forceRefresh:r})}};return Object.defineProperty(n,eh,{value:e,enumerable:!1}),n}function nh(e,t){return t?th(e,t):null}function rh(e,t){let n;if(typeof e=="object"&&"__kind"in e&&e.__kind==="client-db")n=e.port;else{if(typeof SharedWorker>"u")throw new Error("SharedWorker is not available. Open this page over http:// (not file://) and use a supported browser (Chrome 4+, Firefox 29+, Safari 16.4+).");n=new SharedWorker(e,{type:"classic",name:"pyric-shared-worker"}).port,n.start(),ns(n)}const r={__kind:"client-auth",port:n,currentUser:null},s=pt();return Ot(n,s,{port:n,next:i=>{r.currentUser=nh(n,i)}},{t:"sub",subId:s,target:"authState"}),r}async function sh(e){return await W(e.port,{t:"op",id:T(),method:"auth.listUsers"})}async function ih(e,t){return await W(e.port,{t:"op",id:T(),method:"auth.adminCreateUser",request:t})}async function ah(e,t,n){return await W(e.port,{t:"op",id:T(),method:"auth.adminUpdateUser",uid:t,request:n})}async function oh(e,t){await W(e.port,{t:"op",id:T(),method:"auth.adminDeleteUser",uid:t})}async function ch(e){await W(e.port,{t:"op",id:T(),method:"auth.adminClearUsers"})}async function lh(e){return await W(e.port,{t:"op",id:T(),method:"auth.getProviderConfig"})}async function uh(e,t,n){await W(e.port,{t:"op",id:T(),method:"auth.setProviderConfig",providerId:t,enabled:n})}const Sr="pyric-storage";function dh(e){return e?`${Sr}:${e}`:Sr}const fh=1,me="blobs",ie="metadata";async function hh(e=Sr){try{const t=await yh(e);return new mh(t)}catch{return new ph}}class ph{blobs=new Map;metadata=new Map;async put(t,n,r){this.blobs.set(t,n),this.metadata.set(t,r)}async getBlob(t){return this.blobs.get(t)}async getMetadata(t){return this.metadata.get(t)}async putMetadata(t,n){this.metadata.set(t,n)}async delete(t){this.blobs.delete(t),this.metadata.delete(t)}async listByPrefix(t){const n=[],r=Array.from(this.metadata.keys()).sort();for(const s of r)if(s.startsWith(t)){const i=this.metadata.get(s);i&&n.push(i)}return n}async reset(){this.blobs.clear(),this.metadata.clear()}close(){}}class mh{db;constructor(t){this.db=t}async put(t,n,r){const s=this.db.transaction([me,ie],"readwrite");s.objectStore(me).put(n,t),s.objectStore(ie).put(r,t),await Ft(s)}async getBlob(t){const n=this.db.transaction(me,"readonly");return Gn(n.objectStore(me).get(t))}async getMetadata(t){const n=this.db.transaction(ie,"readonly");return Gn(n.objectStore(ie).get(t))}async putMetadata(t,n){const r=this.db.transaction(ie,"readwrite");r.objectStore(ie).put(n,t),await Ft(r)}async delete(t){const n=this.db.transaction([me,ie],"readwrite");n.objectStore(me).delete(t),n.objectStore(ie).delete(t),await Ft(n)}async listByPrefix(t){const n=this.db.transaction(ie,"readonly"),r=IDBKeyRange.bound(t,t+"￿",!1,!1);return Gn(n.objectStore(ie).getAll(r))}async reset(){const t=this.db.transaction([me,ie],"readwrite");t.objectStore(me).clear(),t.objectStore(ie).clear(),await Ft(t)}close(){this.db.close()}}function yh(e){return new Promise((t,n)=>{try{if(typeof indexedDB>"u"||!indexedDB.open)return n(new Error("IndexedDB not available"));const r=indexedDB.open(e,fh);r.addEventListener("upgradeneeded",()=>{const s=r.result;s.objectStoreNames.contains(me)||s.createObjectStore(me),s.objectStoreNames.contains(ie)||s.createObjectStore(ie)}),r.addEventListener("success",()=>t(r.result)),r.addEventListener("error",()=>n(r.error)),r.addEventListener("blocked",()=>n(new Error(`IndexedDB open blocked for db "${e}"`)))}catch(r){n(r)}})}function Gn(e){return new Promise((t,n)=>{e.addEventListener("success",()=>t(e.result)),e.addEventListener("error",()=>n(e.error))})}function Ft(e){return new Promise((t,n)=>{e.addEventListener("complete",()=>t()),e.addEventListener("error",()=>n(e.error)),e.addEventListener("abort",()=>n(e.error??new Error("IndexedDB transaction aborted")))})}function ri(e){switch(e){case"read":return["get","list"];case"write":return["create","update","delete"];default:return[e]}}const bh=new Set(["&&","||","==","!=","<",">","<=",">=","+","-","*","/","%"]);function vo(e){return{segments:e.path.segments.map(gh),children:e.children.map(vo),allows:e.allows.map(t=>({verbs:t.operations,condition:H(t.condition)})),functions:e.functions.map(Er)}}function gh(e){switch(e.type){case"literal":return{kind:"literal",value:e.value};case"wildcard":return{kind:"param",name:e.name};case"recursive":return{kind:"wildcard",name:e.name}}}function Er(e){return{name:e.name,params:e.parameters,lets:e.lets.map(t=>({name:t.name,value:H(t.value)})),body:H(e.body)}}function H(e){switch(e.type){case"literal":return typeof e.value=="number"&&e.raw.includes(".")?{kind:"literal",value:new ke(e.value)}:{kind:"literal",value:e.value};case"identifier":return{kind:"ident",name:e.name};case"memberAccess":return{kind:"member",target:H(e.object),name:e.property};case"methodCall":return{kind:"methodcall",target:H(e.object),method:e.method,args:e.args.map(H)};case"bracketAccess":return{kind:"index",target:H(e.object),index:H(e.index)};case"sliceAccess":return{kind:"slice",target:H(e.object),start:H(e.start),end:H(e.end)};case"binaryOp":if(!bh.has(e.op))throw new SyntaxError(`Unsupported binary operator '${e.op}' in storage rules.`);return{kind:"binary",op:e.op,left:H(e.left),right:H(e.right)};case"unaryOp":if(e.op!=="!"&&e.op!=="-")throw new SyntaxError(`Unsupported unary operator '${e.op}' in storage rules.`);return{kind:"unary",op:e.op,arg:H(e.operand)};case"ternary":return{kind:"ternary",cond:H(e.condition),then:H(e.consequent),else:H(e.alternate)};case"inExpr":return{kind:"in",element:H(e.element),collection:H(e.collection)};case"isExpr":return{kind:"is",value:H(e.value),typeName:e.typeName};case"listLiteral":return{kind:"list",elements:e.elements.map(H)};case"mapLiteral":return{kind:"map",entries:e.entries.map(t=>({key:H(t.key),value:H(t.value)}))};case"pathLiteral":return{kind:"path",segments:e.segments.map(t=>typeof t=="string"?{kind:"literal",value:t}:{kind:"interp",expr:H(t)})};case"functionCall":return{kind:"call",name:e.name,args:e.args.map(H)};default:{const t=e;throw new SyntaxError(`Unsupported expression construct: ${JSON.stringify(t)}`)}}}function Cr(e){const t=jl(e);if(!t.ok)throw new SyntaxError(`Storage rules parse error at line ${t.error.line}, column ${t.error.column}: expected ${t.error.expected}.`);const n=t.ast;if(n.service.name!=="firebase.storage")throw new SyntaxError(`Expected 'service firebase.storage', got 'service ${n.service.name}'.`);const r={segments:[],children:[vo(n.service.match)],allows:[],functions:[...(n.imports??[]).flatMap(s=>s.functions.map(i=>({name:i,params:[],lets:[],body:{kind:"literal",value:null},unresolvedImport:s.module}))),...(n.functions??[]).map(Er),...(n.service.functions??[]).map(Er)]};return wo(r,new Map),{_root:r,_version:n.version}}function wo(e,t){const n=new Map(t);for(const r of e.functions)n.set(r.name,r);e.visibleFuncs=n;for(const r of e.functions)r.declScope=n;for(const r of e.children)wo(r,n)}function X(e,t){if(e.kind==="methodcall"&&e.target.kind==="ident"&&e.target.name==="firestore"&&!t.has("firestore")&&(e.method==="get"||e.method==="exists"))return!0;switch(e.kind){case"member":return X(e.target,t);case"index":return X(e.target,t)||X(e.index,t);case"slice":return[e.target,e.start,e.end].some(n=>X(n,t));case"unary":return X(e.arg,t);case"ternary":return[e.cond,e.then,e.else].some(n=>X(n,t));case"in":return X(e.element,t)||X(e.collection,t);case"is":return X(e.value,t);case"list":return e.elements.some(n=>X(n,t));case"map":return e.entries.some(({key:n,value:r})=>X(n,t)||X(r,t));case"binary":return X(e.left,t)||X(e.right,t);case"call":return e.args.some(n=>X(n,t));case"methodcall":return X(e.target,t)||e.args.some(n=>X(n,t));case"path":return e.segments.some(n=>n.kind==="interp"&&X(n.expr,t));case"ident":case"literal":return!1}}function xo(e,t=new Set){const n=new Set(t);for(const r of e.segments)r.kind!=="literal"&&n.add(r.name);if(e.allows.some(({condition:r})=>r&&X(r,n)))return!0;for(const r of e.functions){const s=new Set([...n,...r.params]);for(const i of r.lets){if(X(i.value,s))return!0;s.add(i.name)}if(X(r.body,s))return!0}return e.children.some(r=>xo(r,n))}function vh(e,t,n,r,s){const i=new Set;for(const a of r)a.startsWith("storage-rules#")&&i.add(a);return xo(s._root)&&i.add("storage-rules#131"),Object.freeze({targetService:"firebase.storage",source:e,modules:Object.freeze([...t]),bundledModules:Object.freeze([...n]),evidenceIds:Object.freeze([...i].sort())})}const wh="pyric-default",Cn=Symbol("pyric/storage/target");function Ke(e){return e.currentAuth?.()??e.context.auth}class xh{backend;rules;constructor(t,n=null){this.backend=t,this.rules=n}}const si=new WeakMap,ii=new WeakMap,jh=new WeakMap;function kh(e,t,n){const r=si.get(e);if(r){const c=ii.get(e)??null;if(t.rules!==void 0&&t.rules!==c)throw new Error(`pyric/storage: ${n} received a rules source, but this sandbox's storage service is already open ${c===null?"without rules":"with a different rules source"} — rules are honored only on the FIRST storage call per Sandbox, so these rules would be silently discarded. Configure rules on the first storage call for this sandbox.`);return r}let s=null,i=null;if(t.rules){let c=t.rules,l=[],u=[],d=[];if(s=Cr(c),s._version==="2+modules"){const p=Ca(c);if(!p.success)throw new SyntaxError(`Storage rules module resolution failed (${p.error.code}): ${p.error.message}`);c=p.data.resolved,l=p.data.modules,u=p.data.bundledModules,d=p.data.evidenceIds,s=Cr(c)}i=vh(c,l,u,d,s)}const a=hh(t.dbName??dh(t.projectId)).then(c=>new xh(c,s));return si.set(e,a),ii.set(e,t.rules??null),jh.set(e,i),e.registerPersistableService("storage",{snapshot:()=>null,restore:()=>{},reset:async()=>{await(await a).backend.reset()}}),a}function Jn(e){return e instanceof _l}const ai=new WeakMap,oi=new WeakMap;function _h(e,t={}){const n=!Jn(e),r=Jn(e)?e.sandbox:e,s=kh(r,t,"getAdminStorageSandbox");if(n){const d=oi.get(r);if(d)return d}const i=Jn(e)?e:r.withAuth(null),a=i.operationContext.authLens.mode==="admin"?i:Ra(i,{source:i.operationContext.source,authLens:{mode:"admin"},...i.operationContext.planId===void 0?{}:{planId:i.operationContext.planId}}),c=ai.get(i);if(c)return c;const l={kind:"sandbox",sandbox:r,context:a,bucket:t.bucket??wh,servicePromise:s,admin:!0},u=Object.freeze({[Cn]:l});return ai.set(i,u),n&&oi.set(r,u),u}function yt(e,t){const n=kl(t,Es(e.context.operationContext));return{...t,...Es(n),service:"storage"}}function _e(e){const t=e[Cn];if(!t)throw new TypeError("pyric/storage: not a FirebaseStorage handle — was it produced by getStorageSandbox?");return t}function Tt(e){return _e(e).servicePromise}class U extends Error{}class ee{message;constructor(t){this.message=t}}function z(e){return e instanceof ee}function De(e){if(typeof e=="number")return e;if(e instanceof ke)return e.value}function Pe(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function it(e,t){if(e===t)return!0;if(e==null||t==null)return e==null&&t==null;const n=De(e),r=De(t);if(n!==void 0&&r!==void 0)return n===r;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((s,i)=>it(s,t[i]));if(Pe(e)&&Pe(t)){const s=Object.keys(e),i=Object.keys(t);return s.length===i.length&&s.every(a=>Object.prototype.hasOwnProperty.call(t,a)&&it(e[a],t[a]))}return!1}function ae(e){return e===null?"null":e===void 0?"undefined":e instanceof ke?"float":typeof e}function Sh(e,t){if(e.target.kind==="ident"&&e.target.name==="timestamp"&&!(e.target.name in t.locals)&&!(e.target.name in t.params))return Rh(e,t);if(e.target.kind==="ident"&&e.target.name==="duration"&&!(e.target.name in t.locals)&&!(e.target.name in t.params))return Nh(e,t);if(e.target.kind==="ident"&&e.target.name==="firestore"&&!(e.target.name in t.locals)&&!(e.target.name in t.params))return Eh(e,t);if(e.method==="matches")return Ah(e,t);if(e.method==="split")return Ih(e,t);if(e.method==="size")return Dh(e,t);if(e.method==="keys")return Ph(e,t);if(e.method==="hasAll")return $h(e,t);if(e.method==="get")return Oh(e,t);throw new U(`unsupported method .${e.method}()`)}function Eh(e,t){if(e.method!=="get"&&e.method!=="exists")throw new U(`unsupported method firestore.${e.method}()`);if(!t.firestoreLookup)throw new U(`firestore.${e.method}() is unsupported here — no Firestore lookup capability is configured`);if(e.args.length!==1)throw new U(`firestore.${e.method}() expects a single path argument`);const n=e.args[0];if(n.kind!=="path")throw new U(`firestore.${e.method}() requires a /databases/.../documents/... path literal`);const r=Ch(n,t);if(!t.firestoreAccesses.has(r)){if(t.firestoreAccesses.size>=2)throw new U("firestore access limit exceeded: at most two distinct documents");t.firestoreAccesses.add(r)}if(e.method==="exists")return t.firestoreLookup.exists(r);const s=t.firestoreLookup.get(r);return s===null?new ee(`firestore.get() targeted a nonexistent document: ${r}`):{data:s}}function Ch(e,t){const n=e.segments.map(s=>{if(s.kind==="literal")return s.value;const i=B(s.expr,t);if(typeof i=="string")return i;if(typeof i=="number")return String(i);throw new U(`Firestore path interpolation resolved to ${ae(i)} (expected a string)`)});if(n.length<4||n[0]!=="databases"||n[2]!=="documents")throw new U(`malformed Firestore path — expected /databases/<db>/documents/... , got /${n.join("/")}`);if(n[1]!=="(default)")throw new U(`Storage rules may access only the default Firestore database, got ${n[1]}`);const r=n.slice(3);if(r.length===0||r.length%2!==0)throw new U(`Firestore path does not point at a document (needs an even segment count): ${r.join("/")}`);return r.join("/")}const ci={w:10080*60*1e3,d:1440*60*1e3,h:3600*1e3,m:60*1e3,s:1e3,ms:1,ns:1e-6};function Nh(e,t){if(e.method!=="value")throw new U(`unsupported duration.${e.method}()`);const n=e.args.map(a=>B(a,t));if(n.length!==2||typeof n[0]!="number"||typeof n[1]!="string")throw new U("duration.value() expects (magnitude: number, unit: string)");const[r,s]=n,i=ci[s];if(i===void 0)throw new U(`duration.value() got unknown unit "${s}" — expected one of ${Object.keys(ci).join(", ")}`);return r*i}function Rh(e,t){const n=e.args.map(r=>B(r,t));if(e.method==="value"){if(n.length!==1||typeof n[0]!="number")throw new U("timestamp.value() expects (epochMillis: number)");return n[0]}if(e.method==="date"){if(n.length!==3||!n.every(a=>typeof a=="number"))throw new U("timestamp.date() expects (year, month, day) numbers");const[r,s,i]=n;return Date.UTC(r,s-1,i)}throw new U(`unsupported timestamp.${e.method}()`)}function Ah(e,t){const n=B(e.target,t);if(z(n))return n;if(typeof n!="string")throw new U(`matches() requires a string target, got ${ae(n)}`);if(e.args.length!==1)throw new U("matches() expects a single pattern argument");const r=B(e.args[0],t);if(typeof r!="string")throw new U("matches() pattern must be a string");const s=/\\[1-9]/.test(r),i=/\(\?<?[=!]/.test(r);if(s||i)throw new U(`matches() pattern uses an RE2-unsupported construct (${s?"backreference":"lookaround"}) that production would reject`);let a;try{a=new RegExp(`^(?:${r})$`)}catch(c){throw new U(`matches() invalid regex pattern: ${c.message}`)}return a.test(n)}function Ih(e,t){const n=B(e.target,t);if(z(n))return n;if(typeof n!="string")throw new U(`split() requires a string target, got ${ae(n)}`);if(e.args.length!==1)throw new U("split() expects a single pattern argument");const r=B(e.args[0],t);if(typeof r!="string")throw new U("split() pattern must be a string");const s=/\\[1-9]/.test(r),i=/\(\?<?[=!]/.test(r);if(s||i)throw new U(`split() pattern uses an RE2-unsupported construct (${s?"backreference":"lookaround"}) that production would reject`);let a;try{a=new RegExp(r)}catch(c){throw new U(`split() invalid regex pattern: ${c.message}`)}return n.split(a)}function Dh(e,t){const n=B(e.target,t);if(z(n))return n;if(e.args.length!==0)throw new U("size() expects no arguments");if(typeof n=="string"||Array.isArray(n))return n.length;if(Pe(n))return Object.keys(n).length;throw new U(`size() requires a string, list, or map target, got ${ae(n)}`)}function Ph(e,t){const n=B(e.target,t);if(z(n))return n;if(e.args.length!==0)throw new U("keys() expects no arguments");if(!Pe(n))throw new U(`keys() requires a map target, got ${ae(n)}`);return Object.keys(n)}function $h(e,t){const n=B(e.target,t);if(z(n))return n;if(!Array.isArray(n))throw new U(`hasAll() requires a list or set target, got ${ae(n)}`);if(e.args.length!==1)throw new U("hasAll() expects one list or set argument");const r=B(e.args[0],t);if(z(r))return r;if(!Array.isArray(r))throw new U("hasAll() argument must be a list or set");return r.every(s=>n.some(i=>it(i,s)))}function Oh(e,t){const n=B(e.target,t);if(z(n))return n;if(!Pe(n))throw new U(`get() requires a map target, got ${ae(n)}`);if(e.args.length!==2)throw new U("get() expects a key and default value");const r=B(e.args[0],t);if(z(r))return r;if(typeof r!="string")throw new U("get() key must be a string");const s=B(e.args[1],t);return z(s)?s:Object.prototype.hasOwnProperty.call(n,r)?n[r]:s}function Mh(e){return e.split("/").filter(t=>t.length>0)}function Yn(e){return"/"+e.map(t=>t.kind==="literal"?t.value:t.kind==="param"?`{${t.name}}`:`{${t.name}=**}`).join("/")}function Th(e,t,n){let r=0;const s={...n};for(let i=0;i<e.length;i++){const a=e[i];if(a.kind==="wildcard")return s[a.name]=t.slice(r),{left:[],params:s};if(r>=t.length)return null;if(a.kind==="literal"){if(t[r]!==a.value)return null;r++}else s[a.name]=t[r],r++}return{left:t.slice(r),params:s}}function jo(e,t,n=new Date,r){const s=n.getTime(),i=Mh(t.request.path),a=[],c=new Set,l=new Set(ri(t.request.method));function u(p,f,m){const y=Th(p.segments,f,m);if(!y)return!1;const g=y.params,v=y.left;if(v.length===0)for(const b of p.allows){const w=new Set(b.verbs.flatMap(ri));if(![...l].some(j=>w.has(j)))continue;let k;try{const j=b.condition?B(b.condition,{input:t,now:s,params:g,locals:{},funcs:p.visibleFuncs??new Map,depth:0,firestoreLookup:r,firestoreAccesses:c}):!0;if(z(j)){a.push(`match ${Yn(p.segments)} ${t.request.method}: ${j.message}`);continue}k=et(j)}catch(j){if(j instanceof U){a.push(`match ${Yn(p.segments)} ${t.request.method}: ${j.message}`);continue}throw j}if(k)return!0;a.push(`match ${Yn(p.segments)} ${t.request.method}: condition false`)}for(const b of p.children)if(u(b,v,g))return!0;return!1}const d=u(e._root,i,{});return!d&&a.length===0&&a.push(`no rule matches ${t.request.method} /${i.join("/")}`),{allowed:d,reasons:a}}function li(e,t){if(!Pe(e)&&!Array.isArray(e))return new ee(`Property ${t} is undefined on ${ae(e)}.`);if(!Object.hasOwn(e,t))return new ee(`Property ${t} is undefined on object.`);const n=e[t];return n===void 0?new ee(`Property ${t} is undefined on object.`):n}function et(e){return z(e)?!1:e!==!1&&e!==null&&e!==void 0&&!(typeof e=="number"&&Number.isNaN(e))}const ui=20;function B(e,t){switch(e.kind){case"literal":return e.value;case"ident":return e.name in t.locals?t.locals[e.name]:e.name==="request"?Fh(t.input,t.now):e.name==="resource"?t.input.resource===null?new ee("Null value error."):Lh(t.input.resource):e.name in t.params?t.params[e.name]:void 0;case"member":{const n=B(e.target,t);return z(n)?n:n==null?new ee("Null value error."):li(n,e.name)}case"index":{const n=B(e.target,t);if(z(n))return n;if(n==null)return new ee("Null value error.");const r=B(e.index,t);return z(r)?r:li(n,String(r))}case"call":return Uh(e,t);case"methodcall":return Sh(e,t);case"path":throw new U("a Firestore path literal is only valid as an argument to firestore.get()/exists()");case"unary":{const n=B(e.arg,t);return z(n)?n:e.op==="-"?n instanceof ke?new ke(-n.value):typeof n!="number"?new ee(`Unary '-' applied to ${ae(n)}.`):-n:!et(n)}case"ternary":{const n=B(e.cond,t);return z(n)?n:et(n)?B(e.then,t):B(e.else,t)}case"in":{const n=B(e.element,t);if(z(n))return n;const r=B(e.collection,t);return z(r)?r:Array.isArray(r)?r.some(s=>it(s,n)):Pe(r)?typeof n=="string"&&Object.prototype.hasOwnProperty.call(r,n):new ee(`'in' applied to ${ae(r)} (expected a list or map).`)}case"is":{const n=B(e.value,t);return z(n)?n:Bh(n,e.typeName)}case"list":{const n=[];for(const r of e.elements){const s=B(r,t);if(z(s))return s;n.push(s)}return n}case"map":{const n={};for(const r of e.entries){const s=B(r.key,t);if(z(s))return s;if(typeof s!="string")return new ee(`Map literal key is ${ae(s)} (expected a string).`);const i=B(r.value,t);if(z(i))return i;n[s]=i}return n}case"slice":{const n=B(e.target,t);if(z(n))return n;const r=B(e.start,t);if(z(r))return r;const s=B(e.end,t);return z(s)?s:typeof r!="number"||typeof s!="number"||!Number.isInteger(r)||!Number.isInteger(s)?new ee("Slice bounds must be integers."):Array.isArray(n)||typeof n=="string"?r<0||s<r||s>n.length?new ee(`Slice bounds [${r}:${s}] out of range for ${ae(n)} of size ${n.length}.`):n.slice(r,s):new ee(`Slice applied to ${ae(n)} (expected a list or string).`)}case"binary":{if(e.op==="&&"){const s=B(e.left,t);return z(s)?s:et(s)?B(e.right,t):s}if(e.op==="||"){const s=B(e.left,t);if(z(s)){const i=B(e.right,t);return et(i)?i:s}return et(s)?s:B(e.right,t)}const n=B(e.left,t);if(z(n))return n;const r=B(e.right,t);if(z(r))return r;switch(e.op){case"==":return it(n,r);case"!=":return!it(n,r);case"<":return Vt(n,r)<0;case">":return Vt(n,r)>0;case"<=":return Vt(n,r)<=0;case">=":return Vt(n,r)>=0;case"+":return Te(n,r,(s,i)=>s+i);case"-":return Te(n,r,(s,i)=>s-i);case"*":return Te(n,r,(s,i)=>s*i);case"/":return tt(n)||tt(r)?Te(n,r,(s,i)=>s/i):De(r)===0?new ee("Division by zero."):Te(n,r,(s,i)=>Math.trunc(s/i));case"%":return tt(n)||tt(r)?Te(n,r,(s,i)=>s%i):De(r)===0?new ee("Modulo by zero."):Te(n,r,(s,i)=>s%i)}}}}function Uh(e,t){const n=t.funcs.get(e.name);if(!n)throw new U(`undefined function ${e.name}()`);if(n.unresolvedImport!==void 0)throw new U(`function ${e.name}() is imported from '${n.unresolvedImport}', but import module resolution is not implemented`);if(n.params.length!==e.args.length)throw new U(`function ${e.name}() expects ${n.params.length} argument(s), got ${e.args.length}`);const r=t.depth+1;if(r>ui)throw new U(`function ${e.name}() exceeded max call depth ${ui}`);const s=e.args.map(c=>B(c,t)),i={};n.params.forEach((c,l)=>{i[c]=s[l]});const a={input:t.input,now:t.now,params:{},locals:i,funcs:n.declScope??new Map,depth:r,firestoreLookup:t.firestoreLookup,firestoreAccesses:t.firestoreAccesses};for(const c of n.lets)i[c.name]=B(c.value,a);return B(n.body,a)}function Bh(e,t){switch(t){case"string":return typeof e=="string";case"bool":return typeof e=="boolean";case"int":return typeof e=="number"&&Number.isInteger(e);case"float":return e instanceof ke||typeof e=="number"&&!Number.isInteger(e);case"number":return e instanceof ke||typeof e=="number";case"list":return Array.isArray(e);case"map":return Pe(e);default:return new ee(`'is ${t}' is not supported by the storage evaluator.`)}}function tt(e){return e instanceof ke}function Vt(e,t){const n=De(e),r=De(t);return n!==void 0&&r!==void 0?n-r:typeof e=="string"&&typeof t=="string"?e<t?-1:e>t?1:0:Number.NaN}function Te(e,t,n){const r=De(e),s=De(t);if(r===void 0||s===void 0)return;const i=n(r,s);return tt(e)||tt(t)?new ke(i):i}function Lh(e){return{size:e.size,contentType:e.contentType,metadata:e.metadata,name:e.name,bucket:e.bucket,generation:e.generation,metageneration:e.metageneration,timeCreated:di(e.timeCreated),updated:di(e.updated)}}function di(e){if(e===void 0)return;const t=Date.parse(e);return Number.isNaN(t)?void 0:t}function Fh(e,t){return{auth:e.request.auth??new ee("Property auth is undefined on object."),resource:e.request.resource??new ee("Property resource is undefined on object."),method:e.request.method,path:e.request.path,time:t}}function Vh(e){return`storage/${e}`}class bt extends Error{code;constructor(t,n){const r=Vh(t);super(`${r}: ${n}`),this.name="StorageError",this.code=r,Object.setPrototypeOf(this,bt.prototype)}}function ko(e){return new bt("object-not-found",`no object at "${e}".`)}function qh(e,t,n){return new bt("unauthorized",`${e} "${t}" denied by rules${n}.`)}function Nn(e){return new bt("invalid-root-operation",`${e} cannot operate on the root reference.`)}function Wh(){return new bt("canceled","User canceled the upload/download.")}function Ut(e,t,n,r){const s=n?.kind==="sandbox"?yt(n,r):r;if(n?.kind==="sandbox"&&n.admin===!0){qt(n,t,"not-applicable",void 0,"admin",!1,s);return}if(!e.rules){qt(n,t,"allow",void 0,"user",!1,s);return}const i=n?zh(t,n.bucket):t,a=jo(e.rules,i,void 0,Kh(n));if(!a.allowed){qt(n,t,"deny",a.reasons,"user",!0,s);const c=a.reasons.length>0?` — ${a.reasons.join("; ")}`:"";throw qh(t.request.method,t.request.path,c)}qt(n,t,"allow",a.reasons,"user",!0,s)}function zh(e,t){const n=e.request.path.replace(/^\/+/,"");return{...e,request:{...e.request,path:n===""?`b/${t}/o`:`b/${t}/o/${n}`}}}function qt(e,t,n,r,s,i,a){if(e)try{Re(e.sandbox,Na({service:"storage",method:t.request.method,path:t.request.path,auth:t.request.auth,result:n,origin:s,reasons:r,rulesDisposition:s==="admin"?{kind:"bypassed",reason:"admin"}:i?{kind:"evaluated",verdict:n==="deny"?"deny":"allow"}:{kind:"not-evaluated",reason:"no-rules"},rules:i?{engine:"storage",reason:r&&r.length>0?r.join("; "):void 0}:void 0}),{...a,service:"storage"})}catch{}}function Kh(e){if(!e)return;const t=e.sandbox.admin;return{get:n=>t.getDocument(n),exists:n=>t.getDocument(n)!==null}}function Rn(e){return e?{size:e.size,contentType:e.contentType,metadata:e.customMetadata,name:Hh(e.fullPath,e.bucket),bucket:e.bucket,timeCreated:e.timeCreated,updated:e.updated,generation:fi(e.generation),metageneration:fi(e.metageneration)}:null}function Hh(e,t){if(e===void 0)return;const n=e.startsWith("/")?e.slice(1):e;if(t!==void 0){const s=`b/${t}/o/`;if(n.startsWith(s))return n.slice(s.length)}const r=/^b\/[^/]+\/o\//.exec(n);return r?n.slice(r[0].length):n}function fi(e){if(e===void 0)return;const t=Number(e);return Number.isFinite(t)?t:void 0}function Gh(e){return{size:e.size,contentType:e.contentType,metadata:e.customMetadata}}function os(e){return{...e}}async function Jh(e){Yh(e,"getMetadata");const t=_e(e.storage),n=yt(t),r=await Tt(e.storage),s=await r.backend.getMetadata(e.fullPath);if(Ut(r,{request:{auth:Ke(t),method:"get",path:e.fullPath},resource:Rn(s)},t,n),!s)throw ko(e.fullPath);return os(s)}function Yh(e,t){if(e.fullPath==="")throw Nn(t)}const Qh="application/octet-stream";async function _o(e,t,n,r){ep(e,"uploadBytes");const s=_e(e.storage),i=yt(s,r),a=Xh(t,n?.contentType),c=So({ref:e,blob:a,settable:n}),l=await Tt(e.storage),u=await l.backend.getMetadata(e.fullPath);Ut(l,{request:{auth:Ke(s),method:u?"update":"create",path:e.fullPath,resource:Gh({size:c.size,contentType:c.contentType,customMetadata:c.customMetadata})},resource:Rn(u)},s,i),await l.backend.put(e.fullPath,a,c);try{Re(s.sandbox,wn({service:"storage",op:"object_put",path:e.fullPath,auth:Ke(s),before:u??void 0,after:c,detail:{bucket:e.bucket,size:c.size,contentType:c.contentType,overwrite:u!=null}}),i)}catch{}return{ref:e,metadata:os(c)}}function So(e){const{ref:t,blob:n,settable:r}=e,s=(e.now??new Date).toISOString(),i=Zh(e.now??new Date),a=t.name;return{fullPath:t.fullPath,name:a,bucket:t.bucket,generation:i,metageneration:"1",timeCreated:s,updated:s,size:n.size,contentType:r?.contentType||n.type||Qh,cacheControl:r?.cacheControl,contentDisposition:r?.contentDisposition,contentEncoding:r?.contentEncoding,contentLanguage:r?.contentLanguage,customMetadata:r?.customMetadata}}function Xh(e,t){return e instanceof Blob?t&&t!==e.type?new Blob([e],{type:t}):e:new Blob([e],{type:t??""})}function Zh(e){return String(e.getTime())}function ep(e,t){if(e.fullPath==="")throw Nn(t)}function tp(e){return e instanceof Blob?e.size:e.byteLength}function np(){const e=new Error("storage/canceled: User canceled the upload/download.");return e.code="storage/canceled",e}function rp(){const e=new Error("storage/invalid-root-operation: uploadBytesResumable cannot operate on root reference.");return e.code="storage/invalid-root-operation",e}class sp{[Symbol.toStringTag]="UploadTask";_snapshot;_promise;_resolve;_reject;_observers=[];_didIntermediateProgress=!1;_error;_ref;_data;_metadata;constructor(t,n,r){this._ref=t,this._data=n,this._metadata=r;const s=tp(n),i=new Date().toISOString();let a="application/octet-stream";if(n instanceof Blob&&n.type!==""&&(a=n.type),r!==void 0&&r.contentType!==void 0){const p=r.contentType;p!==void 0&&(a=p)}const u={fullPath:t.fullPath,name:t.name,bucket:"default",generation:"1",metageneration:"1",timeCreated:i,updated:i,size:s,contentType:a};this._promise=new Promise((d,p)=>{this._resolve=d,this._reject=p}),this._promise.catch(()=>{}),this._snapshot={bytesTransferred:0,totalBytes:s,state:"running",metadata:u,ref:this._ref,task:this},queueMicrotask(()=>{this._runStep()})}get snapshot(){return this._snapshot}then(t,n){return this._promise.then(t,n)}catch(t){return this._promise.catch(t)}finally(t){return this._promise.finally(t)}pause(){return this._snapshot.state==="running"?(this._updateSnapshot("paused",this._snapshot.bytesTransferred),this._notifyObservers("next"),!0):!1}resume(){return this._snapshot.state==="paused"?(this._updateSnapshot("running",this._snapshot.bytesTransferred),this._notifyObservers("next"),queueMicrotask(()=>{this._runStep()}),!0):!1}cancel(){let t=!1;return(this._snapshot.state==="running"||this._snapshot.state==="paused")&&(t=!0),t?(this._error=np(),this._updateSnapshot("canceled",this._snapshot.bytesTransferred),this._notifyObservers("error"),this._reject(this._error),!0):!1}on(t,n,r,s){let i,a,c,l=!1;if(typeof n=="object"&&n!==null&&(l=!0),l){const f=n;f.next!==void 0&&(i=f.next),f.error!==void 0&&(a=f.error),f.complete!==void 0&&(c=f.complete)}else typeof n=="function"&&(i=n),typeof r=="function"&&(a=r),typeof s=="function"&&(c=s);const d={next:i,error:a,complete:c};if(this._observers.push(d),this._snapshot.state==="running"){if(i!==void 0){const m=i;try{m(this._snapshot)}catch{}}}else if(this._snapshot.state==="paused"){if(i!==void 0){const y=i;try{y(this._snapshot)}catch{}}}else if(this._snapshot.state==="success"){if(i!==void 0){const v=i;try{v(this._snapshot)}catch{}}if(c!==void 0){const v=c;try{v()}catch{}}}else if(this._snapshot.state==="error"){if(a!==void 0&&this._error!==void 0){const b=a,w=this._error;try{b(w)}catch{}}}else if(this._snapshot.state==="canceled"&&a!==void 0&&this._error!==void 0){const w=a,x=this._error;try{w(x)}catch{}}return()=>{const f=this._observers.indexOf(d);f!==-1&&this._observers.splice(f,1)}}_updateSnapshot(t,n,r){let s=this._snapshot.metadata;r!==void 0&&(s=r),this._snapshot={bytesTransferred:n,totalBytes:this._snapshot.totalBytes,state:t,metadata:s,ref:this._ref,task:this}}_notifyObservers(t){if(t==="next"){for(const i of this._observers)if(i.next!==void 0){const c=i.next;try{c(this._snapshot)}catch{}}}if(t==="error"){for(const i of this._observers)if(i.error!==void 0&&this._error!==void 0){const l=i.error,u=this._error;try{l(u)}catch{}}}if(t==="complete"){for(const i of this._observers)if(i.complete!==void 0){const c=i.complete;try{c()}catch{}}}}_runStep(){if(this._snapshot.state!=="running")return;if(this._didIntermediateProgress===!1){this._didIntermediateProgress=!0;let r=0;this._snapshot.totalBytes>0&&(r=Math.floor(this._snapshot.totalBytes/2)),this._updateSnapshot("running",r),this._notifyObservers("next"),queueMicrotask(()=>{this._runStep()});return}this._commitUpload()}async _commitUpload(){if(this._snapshot.state==="running")try{const n=await Eo(this._ref,this._data,this._metadata);if(this._snapshot.state==="running")this._updateSnapshot("success",this._snapshot.totalBytes,n.metadata),this._notifyObservers("next"),this._notifyObservers("complete"),this._resolve(this._snapshot);else try{await Co(this._ref)}catch{}}catch(n){if(this._snapshot.state==="running"){let s;n instanceof Error?s=n:s=new Error(String(n)),this._error=s,this._updateSnapshot("error",this._snapshot.bytesTransferred),this._notifyObservers("error"),this._reject(this._error)}}}}function ip(e,t,n){if(e.fullPath==="")throw rp();return new sp(e,t,n)}class At{__kind="storage-ref";port;storage;bucket;fullPath;name;constructor(t,n,r,s){this.port=t,this.bucket=n,this.fullPath=r,this.name=is(r),s&&(this.storage=s)}get parent(){if(this.fullPath==="")return null;const t=this.fullPath.lastIndexOf("/"),n=t===-1?"":this.fullPath.slice(0,t);return new At(this.port,this.bucket,n,this.storage)}get root(){return this.fullPath===""?this:new At(this.port,this.bucket,"",this.storage)}toString(){return`gs://${this.bucket}/${this.fullPath}`}}function ap(e){return e.replace(/^\/+|\/+$/g,"")}function op(e,t,n){let r;if(typeof e=="object"&&"__kind"in e&&e.__kind==="client-db")r=e.port;else{if(typeof SharedWorker>"u")throw new Error("SharedWorker is not available. Open this page over http:// (not file://) and use a supported browser.");r=new SharedWorker(e,{type:"classic",name:"pyric-shared-worker"}).port,r.start(),ns(r)}return{__kind:"client-storage",port:r,bucket:n??"pyric-default"}}function cp(e,t){const n=ap(t??"");let r,s,i="pyric-default",a;if(e.__kind==="client-storage")r=n,s=e.port,i=e.bucket,a=e;else{const c=e.fullPath;r=n?c?`${c}/${n}`:n:c,s=e.port,i=e.bucket,a=e.storage}return new At(s,i,r,a)}async function lp(e){const t=await de(e.port,{t:"op",id:T(),method:"storage.listAll",path:e.fullPath}),n=r=>new At(e.port,e.bucket,r.fullPath,e.storage);return{items:t.items.map(n),prefixes:t.prefixes.map(n)}}async function up(e){return await de(e.port,{t:"op",id:T(),method:"storage.getMetadata",path:e.fullPath})}async function dp(e){return await de(e.port,{t:"op",id:T(),method:"storage.getBlob",path:e.fullPath})}async function Eo(e,t,n){const r=t instanceof Blob?new Uint8Array(await t.arrayBuffer()):t instanceof ArrayBuffer?new Uint8Array(t):t;if(r.byteLength>bo)throw $f(r.byteLength,`uploadBytes payload for '${e.fullPath}'`);const s=n?.contentType??(t instanceof Blob&&t.type?t.type:void 0),i=await de(e.port,{t:"op",id:T(),method:"storage.putBytes",path:e.fullPath,dataB64:Of(r),...s!==void 0?{contentType:s}:{},...n!==void 0?{metadata:n}:{}});return{ref:e,metadata:i}}async function Co(e){await de(e.port,{t:"op",id:T(),method:"storage.deleteObject",path:e.fullPath})}new Array(12).fill(0);async function fp(e){return W(e.port,{t:"op",id:T(),method:"rtdb.adminSnapshot"})}async function hp(e,t,n){await W(e.port,{t:"op",id:T(),method:"rtdb.set",path:t,value:n,actAs:{mode:"admin"}})}async function pp(e,t,n){await W(e.port,{t:"op",id:T(),method:"rtdb.update",path:t,values:n,actAs:{mode:"admin"}})}async function mp(e,t){await W(e.port,{t:"op",id:T(),method:"rtdb.remove",path:t,actAs:{mode:"admin"}})}function yp(e,t,n,r){const s=pt();return!Ot(e.port,s,{port:e.port,next:a=>n(a?.value??null),error:r},rs({t:"sub",subId:s,target:{service:"rtdb",path:jf(t)},actAs:{mode:"admin"}}))&&r&&queueMicrotask(()=>r(new Error("FIREBASE FATAL ERROR: Database has been deleted."))),()=>Mt(e.port,s)}function bp(e){const t=new Set;let n={servedEpoch:e.servedEpoch,runningEpoch:null,updateAvailable:!1,updating:!1,error:null};const r=l=>{n={...n,...l};for(const u of t)u()},s=e.storage,i=e.servedEpoch;let a=null;const c=()=>i?(a??=zd({targetEpoch:i,retire:()=>e.retire?e.retire(i):cf(e.db,i),subscribeReload:e.subscribeReload??lf,preflight:e.preflight??(()=>Wd(s)),commitGeneration:e.remember??(l=>qd(l,s)),onPreparationError:l=>r({updating:!1,error:l instanceof Error?l.message:String(l)}),reload:e.reload??(()=>window.location.reload()),...e.schedule?{schedule:e.schedule}:{}}),a):null;return(e.readVersion??(()=>df(e.db)))().then(l=>r({runningEpoch:l,updateAvailable:!!(i&&l!=="dev"&&l!==i)})).catch(l=>r({error:l instanceof Error?l.message:String(l)})),{getSnapshot:()=>n,subscribe(l){return t.add(l),c(),()=>{t.delete(l),t.size===0&&(a?.dispose(),a=null)}},async update(){const l=c();if(!l||!n.updateAvailable||n.updating)throw new Error("No Pyric worker update is available.");r({updating:!0,error:null});try{await l.request()}catch(u){throw r({updating:!1,error:u instanceof Error?u.message:String(u)}),u}},dispose(){t.clear(),a?.dispose(),a=null}}}function gp(e={}){const t=ho(e.document??(typeof document>"u"?void 0:document));let n=e.storage;if(!n)try{n=typeof localStorage>"u"?void 0:localStorage}catch{n=void 0}return{url:e.workerUrl??t.worker.url,name:Vd(t.worker.servedEpoch,n)}}const vp="/__pyric/sdk/worker.js";function wp(e){let t=[],n=!1;const r=new Set;let s=null;function i(){s||(s=Kf(e,a=>{const c=!n;n=!0;const l=c?[]:[...t];for(const u of a)ao(u)&&(l.length=0),l.push(u);t=l;for(const u of a)for(const d of r)d(u)}))}return{history:()=>t,subscribe:a=>(r.add(a),i(),()=>{r.delete(a),r.size===0&&s&&(s(),s=null,n=!1,t=[])})}}function xp(e=vp){if(typeof SharedWorker>"u")return null;of("studio");let t;try{const l=gp({workerUrl:e});t=uf(l.url,l.name)}catch{return null}let n;try{n=typeof localStorage>"u"?void 0:localStorage}catch{n=void 0}const r=bp({db:t,servedEpoch:ho(typeof document>"u"?void 0:document).worker.servedEpoch,storage:n});Xs({mode:"admin"});const s=Xf({db:t,kind:"studio"}),i=wp(t),a=rh(t);let c=!1;return{db:t,runtime:r,dispose:async()=>{c||(c=!0,s.stop(),r.dispose(),await Cf(t).catch(()=>{}))},presenceClientId:s.clientId,subscribePresence:l=>Zf(t,l),instanceId:()=>ff(t),exportState:()=>hf(t),importState:l=>pf(t,l),saveBranch:l=>mf(t,l),listBranches:()=>yf(t),switchBranch:l=>bf(t,l),deleteBranch:l=>gf(t,l),feed:i,setLens:l=>Xs(l),getLens:()=>af(),listRootCollections:()=>Bf(t),listSubcollections:l=>Lf(t,l),listDocuments:async l=>(await zf(t,l)).map(({path:u,phantom:d})=>({path:u,phantom:d})),readRtdbState:()=>fp(t),setRtdbValue:(l,u)=>hp(t,l,u),updateRtdbValue:(l,u)=>pp(t,l,u),deleteRtdbValue:l=>mp(t,l),subscribeRtdbValue:(l,u,d)=>yp(t,l,u,d),firestoreApi:{collection:Rf,doc:Nf,getDoc:Tf,getDocs:Uf,onSnapshot:Ff,setDoc:Vf,deleteDoc:qf,addDoc:Wf,query:Df,limit:Af,startAfter:If},auth:a,authApi:{listUsers:()=>sh(a),subscribeUsers:(l,u)=>i.subscribe(d=>{d.kind==="service_mutation"&&d.service==="auth"&&u()}),createUser:(l,u)=>ih(a,u),updateUser:(l,u,d)=>ah(a,u,d),deleteUser:(l,u)=>oh(a,u),clearUsers:()=>ch(a),getAuthProviderConfig:()=>lh(a),setAuthProviderConfig:(l,u,d)=>uh(a,u,d),subscribeAuthProviderConfig:(l,u)=>i.subscribe(d=>{d.kind==="service_mutation"&&d.op==="provider_config_update"&&u()})},storage:op(t),storageApi:{ref:cp,listAll:lp,getMetadata:up,getBlob:dp,uploadBytes:Eo,uploadBytesResumable:ip,deleteObject:Co},getSnapshot:()=>Hf(t),resetAll:()=>Gf(t)}}const hi=5174,pi="/sandbox",jp=4001,kp="worker-relay";function _p(e){if(e===null||typeof e!="object")return!1;const t=e.type;return t==="hello"||t==="hello-ack"||t==="attach"||t==="attach-ack"||t==="tool-call"||t==="tool-result"||t==="worker-op"||t==="worker-res"||t==="worker-sub"||t==="worker-unsub"||t==="worker-snap"||t==="ping"||t==="pong"}function Nr(e){if(e===null||typeof e!="object")return null;if(typeof Blob<"u"&&e instanceof Blob)return"Blob";if(e instanceof ArrayBuffer)return"ArrayBuffer";if(ArrayBuffer.isView(e))return e.constructor?.name??"TypedArray";if(Array.isArray(e)){for(const t of e){const n=Nr(t);if(n)return n}return null}for(const t of Object.values(e)){const n=Nr(t);if(n)return n}return null}function mi(e,t){const n=Nr(t);if(!n)return;const r=new Error(`worker ${e} produced a binary payload (${n}) that cannot cross the JSON bridge relay — it would be silently corrupted by JSON.stringify. Use the base64 storage ops instead ('storage.getBytes' / 'storage.putBytes'), which carry bytes as JSON-safe 'dataB64' strings; 'storage.getBlob' is MessagePort-only.`);throw r.code="invalid-argument",r}function yi(e,t){return{code:e.code,severity:t,message:e.message,path:e.path,origin:"validate"}}const ge=e=>e,bi=(...e)=>ge(e.map(t=>`(${t})`).join(" && ")),Sp=(...e)=>ge(e.map(t=>`(${t})`).join(" || ")),No=e=>e,Ep=()=>No("newData.hasChildren()"),Cp=e=>No(`newData.hasChild("${e}")`);function Ro(e,t){const n=e.shape,r=[],s={};for(const[c,l]of Object.entries(n)){const u=l,d=u instanceof Sl,p=d?u.unwrap():u;d||r.push(c);const f=Ao(p,c),m=t?.[c];if(m&&m.length>0?s[c]={validate:bi(f,...m)}:s[c]={validate:f},p instanceof Aa){const y=Ro(p);s[c]={validate:y.validate,children:y.children}}}const i=[Ep()];for(const c of r)i.push(Cp(c));return{validate:bi(...i),children:s}}function Ao(e,t){if(e instanceof El)return ge("newData.isString()");if(e instanceof Cl)return ge("newData.isNumber()");if(e instanceof Nl)return ge("newData.isBoolean()");if(e instanceof Rl){const n=e.options;return ge(n.map(r=>`newData.val() === "${r}"`).join(" || "))}if(e instanceof Al){const n=e.value;return ge(typeof n=="string"?`newData.val() === "${n}"`:`newData.val() === ${n}`)}if(e instanceof Il){const n=e._def.options;return Sp(...n.map(r=>Ao(r,t)))}if(e instanceof Aa)return ge("newData.hasChildren()");throw new Error(`Unsupported Zod type for RTDB rules: ${e.constructor.name} on field "${t}"`)}function Np(e){let t;if(typeof e=="function"){const s=[];e({path:(i,a)=>s.push([i,a])}),t=s}else t=Object.entries(e);const n=Io(t);n.sort((s,i)=>{const a=s[0]==="/"?0:s[0].split("/").filter(Boolean).length,c=i[0]==="/"?0:i[0].split("/").filter(Boolean).length;return a-c||s[0].localeCompare(i[0])});const r={path:"/",pathVariables:[],children:[]};for(const[s]of n)s!=="/"&&Rp(r,s);for(const[s,i]of n){const a=s==="/"?r:cs(r,s);a&&Ap(r,a,i,s)}return r}function Rp(e,t){const n=t.split("/").filter(Boolean);let r=e;for(let s=0;s<n.length;s++){const i="/"+n.slice(0,s+1).join("/"),a=n.slice(0,s+1).filter(l=>l.startsWith("$"));let c=r.children.find(l=>l.path===i);c||(c={path:i,pathVariables:a,children:[]},r.children.push(c)),r=c}}function Ap(e,t,n,r){const s=r.split("/").filter(i=>i.startsWith("$"));if(n.read&&(t.read=Qe(n.read,"read",s)),n.write&&(t.write=Qe(n.write,"write",s)),n.validate&&(t.validate=Qe(n.validate,"validate",s)),n.schema){const i=Ro(n.schema,n.fieldConstraints);t.validate||(t.validate=Qe(i.validate,"validate",s));for(const[a,c]of Object.entries(i.children)){const l=`${r}/${a}`;let u=t.children.find(d=>d.path===l);if(u||(u={path:l,pathVariables:s,children:[]},t.children.push(u)),u.validate=Qe(c.validate,"validate",s),"children"in c&&c.children)for(const[d,p]of Object.entries(c.children)){const f=`${l}/${d}`;let m=u.children.find(y=>y.path===f);m||(m={path:f,pathVariables:s,children:[]},u.children.push(m)),m.validate=Qe(p.validate,"validate",s)}}}if(n.indexOn){const i=r.split("/").filter(Boolean);if(i[i.length-1]?.startsWith("$")){const c="/"+i.slice(0,-1).join("/"),l=cs(e,c);l&&(l.indexOn=n.indexOn)}}}function Io(e){const t=[];for(const[n,r]of e){const{children:s,...i}=r;if(t.push([n,i]),s){const a=Object.entries(s).map(([c,l])=>[n+c,l]);t.push(...Io(a))}}return t}function Qe(e,t,n){return Va(String(e),t,n)}function cs(e,t){if(e.path===t)return e;for(const n of e.children){const r=cs(n,t);if(r)return r}return null}function Ip(e){return e==null?null:typeof e=="string"?{uid:e,token:{}}:{uid:e.uid,token:e.token??{}}}function Dp(e){return{operation:e.operation,path:e.path,auth:Ip(e.auth),mockData:e.mockData??e.data??{},...e.newData!==void 0?{newData:e.newData}:{}}}function Qn(e,t,n,r){return(n?.parsed[r]??[]).map(s=>({path:e,rule:t,code:s.code,message:s.message}))}function Rr(e,t){const n=[...Qn(e.path,".read",e.read,t),...Qn(e.path,".write",e.write,t),...Qn(e.path,".validate",e.validate,t)];for(const r of e.children)n.push(...Rr(r,t));return n}class Pp{definition;constructor(t){this.definition=t}compile(){return Np(this.definition.paths)}toJSON(){return qu(this.compile())}check(){try{const t=this.compile(),n=Rr(t,"errors"),r=Rr(t,"warnings");return{ok:n.length===0,errors:n,warnings:r}}catch(t){return{ok:!1,errors:[{path:"/",rule:"ruleset",code:"COMPILE_ERROR",message:t instanceof Error?t.message:String(t)}],warnings:[]}}}simulate(t){return Zr(this.compile(),Dp(t))}}function $p(e){return new Pp(e)}function Op(e){const t=e;return typeof t.toJSON=="function"&&typeof t.simulate=="function"&&typeof t.check=="function"}function Mp(e){const t=e;return typeof t=="object"&&t!==null&&"rules"in t&&!("paths"in t)&&typeof t.toJSON!="function"}class Xn{doc;constructor(t){this.doc=t}lint(){const t=this.doc.check();return[...t.errors.map(n=>yi(n,"error")),...t.warnings.map(n=>yi(n,"warning"))]}runOne(t){const n=this.doc.simulate({operation:t.operation,path:t.path,auth:t.auth??null,...t.data!==void 0?{data:t.data}:{},...t.newData!==void 0?{newData:t.newData}:{}});if(!n.success)return{case:t,...t.description!==void 0?{description:t.description}:{},expectation:t.expectation,decision:"UNSUPPORTED",passed:!1,unsupported:!0,matchedPath:t.path,matchedRule:t.operation,reason:n.error.message};const r=n.data,s=r.unsupported===!0,i=s?"UNSUPPORTED":r.allowed?"ALLOW":"DENY",a=!s&&i===t.expectation;return{case:t,...t.description!==void 0?{description:t.description}:{},expectation:t.expectation,decision:i,passed:a,unsupported:s,matchedPath:r.matchedPath,matchedRule:r.matchedRule,reason:r.reason}}simulate(t){const n=t.map(a=>this.runOne(a));let r=0,s=0,i=0;for(const a of n)a.unsupported?i++:a.passed?r++:s++;return{passed:r,failed:s,unsupported:i,cases:n}}explain(t){const n=this.runOne(t);return{decision:n.decision,expectation:n.expectation,passed:n.passed,unsupported:n.unsupported,matchedPath:n.matchedPath,matchedRule:n.matchedRule,reason:n.reason}}toJSON(){return this.doc.toJSON()}}function Tp(e){return e==null?null:typeof e=="string"?{uid:e,token:{}}:{uid:e.uid,token:e.token??{}}}class Up{json;compiled;constructor(t){this.json=t,this.compiled=Wa(t)}toJSON(){return this.json}compile(){return this.compiled}check(){return{ok:!0,errors:[],warnings:[]}}simulate(t){return Zr(this.compiled,{operation:t.operation,path:t.path,auth:Tp(t.auth),mockData:t.mockData??t.data??{},...t.newData!==void 0?{newData:t.newData}:{}})}}function Bp(e){return Op(e)?new Xn(e):Mp(e)?new Xn(new Up(e)):new Xn($p(e))}function Lp(e,t){return e==="/"?`/${t}`:`${e}/${t}`}function gi(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function Fp(e){const t=(e??"/").split("/").filter(Boolean);return t.length===0?"/":`/${t.join("/")}`}function Vp(e,t){let n=e;for(const r of t.split("/").filter(Boolean)){if(n===null||typeof n!="object"||Array.isArray(n))return null;n=n[r]}return n??null}function Do(e,t,n,r,s){if(e===null||typeof e!="object"||Array.isArray(e))return{path:t,childCount:0,truncated:!1,children:[],schema:{},valueType:gi(e)};const i=Object.entries(e).sort(([p],[f])=>p.localeCompare(f)),a={},c=[];for(const[p,f]of i)f!==null&&typeof f=="object"&&!Array.isArray(f)?c.push([p,f]):a[p]=gi(f);const l=n>=r&&c.length>0,u=i.length>s,d=n>=r?[]:c.slice(0,s).map(([p,f])=>Do(f,Lp(t,p),n+1,r,s));return{path:t,childCount:i.length,truncated:l||u,children:d,schema:a}}function qp(e,t={}){const n=Fp(t.path),r=t.maxDepth??10,s=t.maxChildren??100;return Do(Vp(e,n),n,0,r,s)}function Po(e){return e.children.reduce((t,n)=>t+1+Po(n),0)}function $o(e){return[{name:"rtdb_simulate_access",description:"Simulate one read, write, or validate operation against the RTDB rules and data currently loaded in the local sandbox. No production database is contacted and no prior rules-loading tool call is required.",parameters:{type:"object",properties:{operation:{type:"string",enum:["read","write","validate"]},path:{type:"string"},auth:{anyOf:[{type:"null"},{type:"object",properties:{uid:{type:"string"},claims:{type:"object"}},required:["uid"]}]},newData:{}},required:["operation","path"]},async execute(t){const n=t,r=await e.resolveSandbox(),s=Ha(r);if(!s)return{ok:!1,summary:"No RTDB rules are loaded in the local sandbox.",data:{code:"NO_ACTIVE_RULES"}};const i=Ws(r),a=i!==null&&typeof i=="object"&&!Array.isArray(i)?i:{},c={expectation:"ALLOW",operation:n.operation,path:n.path,auth:n.auth?{uid:n.auth.uid,token:n.auth.claims??{}}:null,data:a,...n.newData!==void 0?{newData:n.newData}:{}},l=Bp(s).simulate([c]).cases[0];return{ok:!l.unsupported,summary:l.unsupported?`Simulation unsupported: ${l.reason}`:`Simulation: ${l.decision.toLowerCase()}`,data:{decision:l.decision,allowed:l.decision==="ALLOW",unsupported:l.unsupported,matchedPath:l.matchedPath,matchedRule:l.matchedRule,reason:l.reason}}}},{name:"rtdb_crawl_structure",description:"Describe the structure of the RTDB data currently loaded in the local sandbox without returning leaf values or contacting a production database.",parameters:{type:"object",properties:{path:{type:"string",description:"Root-relative path to inspect. Defaults to /."},maxDepth:{type:"number",minimum:0,description:"Maximum object depth to return. Defaults to 10."},maxChildren:{type:"number",minimum:1,description:"Maximum object children to return per node. Defaults to 100."}}},async execute(t){const n=t,r=await e.resolveSandbox(),s=qp(Ws(r),n);return{ok:!0,summary:`Crawled ${Po(s)} object paths from ${s.path}`,data:s}}}]}function Wp(e){const t=xn(e),n=r=>r&&r!=="admin"?Oa(e.withAuth({uid:r.uid,token:r.claims})):Ma(e);return[...Ba({resolveSandbox:()=>t}),...ro({resolveDb:n}),...so({resolveSandbox:()=>e}),...$o({resolveSandbox:()=>e})]}function zp(e){const t=new Map(Wp(e).map(n=>[n.name,n]));return async(n,r)=>{const s=t.get(n);if(!s)throw new Gp(n);const i={signal:new AbortController().signal},a=await s.execute(r,i);return{ok:a.ok,summary:a.summary,data:a.data}}}const vi=new WeakMap;async function Kp(e,t,n){let r=vi.get(e);return r||(r=zp(e),vi.set(e,r)),r(t,n)}const Hp=(()=>{const e=async()=>{throw new Error("SANDBOX_TOOL_NAMES: stub resolver should never be invoked")};return[...Ba({resolveSandbox:e}),...ro({resolveDb:e}),...so({resolveSandbox:e}),...$o({resolveSandbox:e})].map(t=>t.name)})();class Gp extends Error{tool;constructor(t){super(`unknown sandbox tool: ${t}`),this.tool=t,this.name="UnknownToolError"}}const Jp=500,Yp=3e4,Qp=2e3,Xp=.5,Zp=3;function em(e,t={}){const n=tm(t.url),r=t.sandboxId??nm(),s=t.dispatcher??Kp,i=t.toolNames??[...Hp],a=t.initialReconnectDelayMs??Jp,c=t.maxReconnectDelayMs??Yp,l=t.noReconnect??!1,u=t.onStateChange??(()=>{}),d=t.standbyPollMs??Qp,p=t.fetchImpl??(A=>fetch(A)),f=t.workerRelay??null;let m=null,y=!1,g=0,v=null,b=null,w=0,x={kind:"connecting"};const k=new Map;function j(){for(const A of k.values())try{A()}catch{}k.clear()}function _(A){x=A;try{u(A)}catch{}}function N(A){if(m&&m.readyState===WebSocket.OPEN)try{m.send(JSON.stringify(A))}catch{}}function P(){if(y)return;_({kind:"connecting"});let A;try{A=new WebSocket(n)}catch(O){G(`failed to open WebSocket: ${O instanceof Error?O.message:String(O)}`);return}m=A,A.onopen=()=>{g=0;const O={type:"hello",protocol:1,tools:i,sandboxId:r,...f?{capabilities:[kp]}:{}};N(O)},A.onmessage=O=>{let M;try{M=JSON.parse(typeof O.data=="string"?O.data:"")}catch{return}if(_p(M)){if(M.type==="hello-ack"){_({kind:"connected",bridgeVersion:M.bridgeVersion});return}if(M.type==="tool-call"){I(M);return}if(M.type==="worker-op"){D(M);return}if(M.type==="worker-sub"){C(M);return}if(M.type==="worker-unsub"){const $=k.get(M.subId);if($){k.delete(M.subId);try{$()}catch{}}return}if(M.type==="ping"){N({type:"pong",id:M.id});return}}},A.onclose=O=>{const M=O.reason||`closed (code ${O.code})`;if(m=null,j(),O.code===jp){E();return}G(M)},A.onerror=()=>{}}async function I(A){let O;try{const M=await s(e,A.name,A.args??{});O={type:"tool-result",id:A.id,ok:!0,result:M}}catch(M){O={type:"tool-result",id:A.id,ok:!1,error:{code:M instanceof Error?M.name:"Error",message:M instanceof Error?M.message:String(M)}}}N(O)}async function D(A){if(f)try{const O=await f.op(A.op);mi(`op '${A.op.method}'`,O),N({type:"worker-res",id:A.id,ok:!0,value:O})}catch(O){const M=O.denialContext;N({type:"worker-res",id:A.id,ok:!1,error:{code:O.code??"unknown",message:O instanceof Error?O.message:String(O),...M!==void 0?{denialContext:M}:{}}})}}function C(A){if(f&&!k.has(A.subId))try{const O=f.subscribe(A.sub,M=>{try{mi(`subscription '${A.subId}'`,M)}catch($){N({type:"worker-snap",subId:A.subId,value:{__error:{code:$.code??"invalid-argument",message:$ instanceof Error?$.message:String($)}}});return}N({type:"worker-snap",subId:A.subId,value:M})});k.set(A.subId,O)}catch(O){const M=O.denialContext;N({type:"worker-snap",subId:A.subId,value:{__error:{code:O.code??"unknown",message:O instanceof Error?O.message:String(O),...M!==void 0?{denialContext:M}:{}}}})}}function S(){try{const A=new URL(n);A.protocol=A.protocol==="wss:"?"https:":"http:";const O=A.origin;return[`${O}/__pyric/health`,`${O}/health`]}catch{return[]}}function E(){if(!y){if(l){_({kind:"disconnected",reason:"replaced by a newer sandbox peer"});return}g=0,w=0,_({kind:"standby"}),R()}}function R(){if(y)return;const A=d*(1+Math.random()*Xp);b=setTimeout(()=>{b=null,V()},A)}async function V(){if(y)return;let A=null;for(const O of S())try{const M=await p(O);if(!M.ok)continue;const $=await M.json();if(typeof $.sandboxConnected=="boolean"){A=!$.sandboxConnected;break}}catch{}if(!y){if(A===!0){P();return}if(A===!1){w=0,R();return}if(w+=1,w>=Zp){G("standby health poll unreachable");return}R()}}function G(A){if(y)return;if(l){_({kind:"disconnected",reason:A});return}g+=1;const O=Math.min(a*2**(g-1),c);_({kind:"reconnecting",attempt:g,delayMs:O}),v=setTimeout(()=>{v=null,P()},O)}return P(),{disconnect(){if(y=!0,j(),v&&(clearTimeout(v),v=null),b&&(clearTimeout(b),b=null),m){try{m.close()}catch{}m=null}_({kind:"disconnected",reason:"client closed"})},state(){return x}}}function tm(e){if(e)return e;if(typeof window<"u"){const t=window.__PYRIC_BRIDGE_URL__;if(t)return t;const n=window.location.hostname||"localhost";return`${window.location.protocol==="https:"?"wss:":"ws:"}//${n}:${hi}${pi}`}return`ws://localhost:${hi}${pi}`}function nm(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`sb-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function rm(e,t){try{const n=new URL(e,t.href),r=new URL(t.href),s=t.protocol==="https:"?"wss:":"ws:",i=r.port.length>0,a=n.port.length>0,l=i&&a?`${r.hostname}:${n.port}`:r.host;return`${s}//${l}${n.pathname}`}catch{return e}}function sm(e,t){return{url:t,dispatcher:(n,r,s)=>vf(e,r,s),workerRelay:{op:n=>wf(e,n),subscribe:(n,r)=>xf(e,n,r)}}}async function im(e,t={}){const n=t.baseUrl??"",r=t.fetchImpl??(typeof fetch<"u"?fetch:null),s=u=>t.onStateChange?.({kind:"disconnected",reason:u});if(!r)return s("no fetch available"),null;let i;try{const u=await r(`${n}/__pyric/init.json`);if(!u.ok)return s("not served"),null;i=(await u.json()).bridgeUrl??null}catch{return s("not served"),null}if(!i)return s("bridge off"),null;const a=t.locationLike??(typeof window<"u"?window.location:null),c=a?rm(i,a):i,l=em(null,{...sm(e,c),...t.onStateChange?{onStateChange:t.onStateChange}:{},...t.initialReconnectDelayMs!==void 0?{initialReconnectDelayMs:t.initialReconnectDelayMs}:{},...t.maxReconnectDelayMs!==void 0?{maxReconnectDelayMs:t.maxReconnectDelayMs}:{}});return console.info("[pyric studio] registered as the sandbox bridge peer at",c),l}const am={};function om(){return!1}function cm(){let e={kind:"connecting"};const t=new Set;return{get:()=>e,subscribe(n){return t.add(n),()=>t.delete(n)},set(n){e=n;for(const r of t)r()}}}function lm(e,t={}){if(e==="local"){const n=t.baseUrl??"",r=om(),s=t.persistence==="memory"||r?Dl():Md(n),i=t.disableLive?null:xp(t.workerUrl),a=i?cm():null;let c=!1,l=null;return i&&a&&im(i.db,{baseUrl:n,onStateChange:u=>a.set(u)}).then(u=>{c?u?.disconnect():l=u}),{mode:e,projects:r?Bd():$d(n),persistence:s,...i?{live:i}:{},...a?{bridge:a}:{},dispose(){c=!0,l?.disconnect(),i?.dispose()}}}throw new Error(`createStudioEnvironment(${e}): only 'local' is wired in v1 (T3). 'browser'/'hosted' land in A3.`)}const Oo=h.createContext(null),um={status:"pending",env:null,error:null};function dm(e){try{return{status:"ready",env:lm(e),error:null}}catch(t){return{status:"error",env:null,error:t instanceof Error?t:new Error(String(t))}}}function fm({mode:e="local",children:t}){const[n,r]=h.useState(null);h.useEffect(()=>{const i=dm(e);return r({mode:e,state:i}),()=>{i.status==="ready"&&i.env.dispose()}},[e]);const s=n?.mode===e?n.state:um;return o.jsx(Oo.Provider,{value:s,children:t})}function pe(){const e=h.useContext(Oo);if(!e)throw new Error("useEnvironment must be used within an <EnvironmentProvider>");return e}const hm="pyric-studio:theme",en="dark";function pm(){return en}function mm(){typeof document>"u"||document.documentElement.setAttribute("data-theme","dark")}const ym=h.createContext(null);function bm({children:e}){const[t,n]=h.useState(pm);h.useEffect(()=>{mm();try{localStorage.setItem(hm,en)}catch{}},[t]);const r="dark",s=h.useCallback(c=>n(en),[]),i=h.useCallback(()=>n(en),[]),a=h.useMemo(()=>({choice:t,resolvedTheme:r,setChoice:s,cycleChoice:i}),[t,r,s,i]);return o.jsx(ym.Provider,{value:a,children:e})}function An(){const e=typeof import.meta<"u"&&"/__pyric/ui/"||"/";return e.endsWith("/")?e:`${e}/`}function gm(e){const t={};for(const n of e.replace(/^\?/,"").split("&")){if(!n)continue;const r=n.indexOf("="),s=r===-1?n:n.slice(0,r),i=r===-1?"":n.slice(r+1);s&&(t[decodeURIComponent(s)]=decodeURIComponent(i))}return t}function ls(e,t="",n=An()){let r=e;const s=n.replace(/\/$/,"");n!=="/"&&(e===s||e.startsWith(n))&&(r=e.slice(s.length));const i=r.split("/").filter(Boolean).map(l=>decodeURIComponent(l)),[a="",...c]=i;return{tab:a,rest:c,query:gm(t)}}function vm(e,t=An()){const n=[e.tab,...e.rest??[]].filter(s=>s!=null&&s!=="").map(s=>encodeURIComponent(s)).join("/"),r=Object.entries(e.query??{}).filter(([,s])=>s!=null&&s!=="").map(([s,i])=>`${encodeURIComponent(s)}=${encodeURIComponent(String(i))}`).join("&");return`${t}${n}${r?`?${r}`:""}`}const Mo="studio",wm=[{id:"home",label:"Studio",description:"What is happening in the sandbox, and where to go next."},{id:"firestore",label:"Firestore",description:"Browse and edit collections, documents, and references."},{id:"auth",label:"Auth",description:"View and edit users, claims, providers, and account state."},{id:"rtdb",label:"RTDB",description:"Browse and edit RTDB data in the shared sandbox."},{id:"storage",label:"Storage",description:"Browse buckets, inspect objects, upload, and delete files."},{id:"traffic",label:"Traffic",description:"Watch sandbox requests, listener activity, and rule decisions."},{id:"assurance",label:"Assurance",description:"Compare intended access with qualified local sandbox behavior."},{id:"settings",label:"Settings",description:"Configure models, keys, theme, sandbox maintenance, and diagnostics."}];function xm({assuranceEnabled:e=!1}={}){return wm.filter(t=>t.id!=="assurance"||e)}const He=xm({assuranceEnabled:!1}),jm=He.map(e=>e.id);function km(e){return He.find(t=>t.id===e)??He[0]}const Ar="pyric:studio:navigated",_m={tab:"",rest:[],query:{}};function To(){return typeof window<"u"?window.location.pathname+window.location.search:""}function Sm(e){return e===""||e===Mo?"home":e}function be(){if(typeof window>"u")return _m;const e=ls(window.location.pathname,window.location.search);return{...e,tab:Sm(e.tab)}}function Em(e){return e.tab==="home"?{...e,tab:Mo}:e}function ut(e){return vm(Em(e))}function Uo(){typeof window<"u"&&window.dispatchEvent(new Event(Ar))}function le(e){if(typeof window>"u")return;const t=ut(e);To()!==t&&(window.history.pushState(null,"",t),Uo())}function fn(e){typeof window>"u"||(window.history.replaceState(null,"",ut(e)),Uo())}function Bt(e){return typeof window>"u"?()=>{}:(window.addEventListener("popstate",e),window.addEventListener(Ar,e),()=>{window.removeEventListener("popstate",e),window.removeEventListener(Ar,e)})}function Cm(e,t){const n=h.useCallback(i=>e.includes(i)?i:t,[e,t]),r=h.useSyncExternalStore(Bt,()=>n(be().tab),()=>t);h.useEffect(()=>{const i=typeof window<"u"?window.location.hash:"";if(i.length>1){const c=i.slice(1),l=c.indexOf("?"),u=ls(`/${l===-1?c:c.slice(0,l)}`,l===-1?"":c.slice(l),"/");if(e.includes(u.tab)){fn(u);return}}const a=be();e.includes(a.tab)||fn({tab:n(a.tab)})},[n]);const s=h.useCallback(i=>{const a=n(i);a!==r&&le({tab:a})},[n,r]);return[r,s]}let Ir=null;function Nm(e){Ir=e}function Rm(){return Ir?(Ir(),!0):!1}function Am(e){return(e.metaKey||e.ctrlKey)&&!e.altKey&&!e.shiftKey&&(e.key==="k"||e.key==="K")}function Im(e,t){const n=e.toLowerCase(),r=t.toLowerCase();let s=0;for(const i of r)if(i===n[s]&&s++,s===n.length)return!0;return s===n.length}const Dm=7;function Pm(e,t){const n=e.trim();if(!n)return[];const r=t.filter(p=>p.id!=="settings"),s=[],i=[],a=[],[c="",...l]=n.split(/\s+/),u=l.join(" ");for(const p of r){const f={id:`tab:${p.id}`,label:`Go to ${p.label}`,hint:p.description,target:{tab:p.id}},m=p.label.toLowerCase();if(m.startsWith(n.toLowerCase())?s.push(f):Im(n,p.label)&&i.push(f),u&&(m===c.toLowerCase()||m.startsWith(c.toLowerCase()))){const y=u.split("/").filter(Boolean);p.id==="firestore"||p.id==="storage"?a.push({id:`deep:${p.id}:${u}`,label:`Open /${y.join("/")} in ${p.label}`,hint:p.id==="firestore"?"Firestore path":"Storage object path",target:{tab:p.id,rest:y}}):p.id==="auth"?a.push({id:`deep:auth:${u}`,label:`Open user ${u} in Auth`,hint:"Auth uid",target:{tab:"auth",rest:[u]}}):p.id==="traffic"&&a.push({id:`deep:traffic:${u}`,label:`Open ${u} in the rules inspector`,hint:"Traffic event id",target:{tab:"traffic",query:{inspect:u}}})}}const d=n.match(/^gs:\/\/[^/]+\/(.+)$/);if(d){const p=d[1].split("/").filter(Boolean);a.unshift({id:`deep:storage:${d[1]}`,label:`Open ${d[1]} in Storage`,hint:"Storage object path",target:{tab:"storage",rest:p}})}else if(n.includes("/")&&!n.includes(" ")){const p=n.split("/").filter(Boolean);p.length&&a.push({id:`deep:firestore:${n}`,label:`Open /${p.join("/")} in Firestore`,hint:"Firestore path",target:{tab:"firestore",rest:p}})}return[...s,...a,...i].slice(0,Dm)}function Dr(e){return`${e.kind}:${e.target.tab}:${(e.target.rest??[]).join("/")}`}const Pr={docsPerCollection:50,collectionsScanned:20,users:100,objects:200,storageListCalls:20,subcollections:30,subcollectionRpcCalls:40};async function $m(e,t,{maxObjects:n,maxListCalls:r}){const s=[],i=[e];let a=0;for(;i.length&&s.length<n&&a<r;){a++;const c=await t(i.shift());for(const l of c.items){if(s.length>=n)break;s.push(l.fullPath)}i.push(...c.prefixes)}return s}async function Om(e,t,n,{maxSubcollections:r,maxRpcCalls:s,docsPerCollection:i}){const a=[],c=[],l=[...e];let u=0;for(;l.length&&a.length<r&&u<s;){const d=l.shift();u++;let p=[];try{p=await t(d)}catch{continue}for(const f of p){if(a.length>=r)break;const m=`${d}/${f}`;a.push(m);try{const y=await n(m,i);for(const g of y.slice(0,i))c.push(g),l.push(g)}catch{}}}return{subcollections:a,documents:c}}const Mm=5;function hn(e,t){const n=e.toLowerCase(),r=t.toLowerCase();if(!n||!r)return 0;if(r===n)return 1e3;if(r.startsWith(n))return 900-Math.min(r.length-n.length,100);const s=r.indexOf(n);if(s!==-1)return 700-Math.min(s,100);let i=0,a=-1,c=-1;for(let u=0;u<r.length&&i<n.length;u++)r[u]===n[i]&&(a===-1&&(a=u),c=u,i++);if(i!==n.length)return 0;const l=c-a+1;return Math.max(1,400-(l-n.length)*10-Math.min(a,50))}const Tm={collection:"Firestore collections",document:"Firestore documents",subcollection:"Firestore subcollections",user:"Auth users",object:"Storage objects","rtdb-key":"RTDB keys"},Um=["collection","document","subcollection","user","object","rtdb-key"];function Bm(e){switch(e.kind){case"collection":return"Firestore collection";case"document":return"Firestore document";case"subcollection":return e.alt?`Subcollection of /${e.alt}`:"Subcollection";case"user":return e.alt?`Auth user · uid ${e.alt}`:"Auth user";case"object":return"Storage object";case"rtdb-key":return"RTDB top-level key"}}function Bo(e){return e.endsWith("/")?{base:e.slice(0,-1),trailing:!0}:{base:e,trailing:!1}}function Lm(e,t){const{base:n,trailing:r}=Bo(e);if(!n)return 0;const s=n.split("/"),i=t.split("/");if(s.length>i.length)return 0;const a=s.length-1;for(let c=0;c<a;c++)if(s[c].toLowerCase()!==i[c].toLowerCase())return 0;return r?s[a].toLowerCase()===i[a].toLowerCase()?850:0:hn(s[a],i[a])}function Fm(e,t){const{base:n,trailing:r}=Bo(e);if(!n||n.includes("/"))return 0;const s=t.split("/").pop()??t;return r?s.toLowerCase()===n.toLowerCase()?850:0:hn(n,s)}function wi(e,t,n,r=Mm){const s=e.trim();if(!s)return[];const i=[],a=Pm(e,t);a.length&&i.push({kind:"navigate",title:"Go to",results:a});for(const c of Um){const l=c==="document"||c==="subcollection",u=c==="collection"||c==="subcollection",d=new Map;for(const f of n)f.kind===c&&d.set(Dr(f),f);const p=[...d.values()].map(f=>({entry:f,score:Math.max(hn(s,f.label),f.alt?hn(s,f.alt):0,l?Lm(s,f.label):0,u?Fm(s,f.label):0)})).filter(f=>f.score>0).sort((f,m)=>m.score-f.score||f.entry.label.localeCompare(m.entry.label)).slice(0,r);p.length&&i.push({kind:c,title:Tm[c],results:p.map(({entry:f})=>({id:Dr(f),label:f.label,hint:Bm(f),target:f.target}))})}return i}function xi(e){return e.flatMap(t=>t.results)}function Vm(e){return{kind:"collection",label:e,target:{tab:"firestore",rest:[e]}}}function ji(e){return{kind:"document",label:e,target:{tab:"firestore",rest:e.split("/").filter(Boolean)}}}function qm(e){const t=e.split("/").filter(Boolean),n=t.slice(0,-1).join("/");return{kind:"subcollection",label:e,alt:n||void 0,target:{tab:"firestore",rest:t}}}function Wm(e){return e.email?{kind:"user",label:e.email,alt:e.uid,target:{tab:"auth",rest:[e.uid]}}:{kind:"user",label:e.uid,target:{tab:"auth",rest:[e.uid]}}}function zm(e){return{kind:"object",label:e,target:{tab:"storage",rest:e.split("/").filter(Boolean)}}}function Km(e){return{kind:"rtdb-key",label:e,target:{tab:"rtdb",rest:[e]}}}async function Hm(e,t={},n){const r={...Pr,...t},s=[],i=d=>{d.length&&(s.push(...d),n?.(d))},a=(async()=>{let d=[];try{d=await e.listRootCollections?.()??[]}catch{d=[]}d.length&&i(d.map(Vm));const p=[];if(e.listDocumentPaths)for(const f of d.slice(0,r.collectionsScanned))try{const y=(await e.listDocumentPaths(f,r.docsPerCollection)).slice(0,r.docsPerCollection);p.push(...y),i(y.map(ji))}catch{}if(e.listSubcollections&&e.listDocumentPaths)try{const{subcollections:f,documents:m}=await Om(p,e.listSubcollections,e.listDocumentPaths,{maxSubcollections:r.subcollections,maxRpcCalls:r.subcollectionRpcCalls,docsPerCollection:r.docsPerCollection});i(f.map(qm)),i(m.map(ji))}catch{}})(),c=(async()=>{if(e.listUsers)try{const d=await e.listUsers(r.users);i(d.slice(0,r.users).map(Wm))}catch{}})(),l=(async()=>{if(e.listStorageObjectPaths)try{const d=await e.listStorageObjectPaths(r.objects);i(d.slice(0,r.objects).map(zm))}catch{}})(),u=(async()=>{if(e.listRtdbTopLevelKeys)try{i((await e.listRtdbTopLevelKeys()).map(Km))}catch{}})();return await Promise.allSettled([a,c,l,u]),s}const Lo=Symbol("pyric/auth/target"),Gm=Symbol("pyric.user.internal");function q(e,t){return new ht(e,`Firebase: ${t} (${e}).`)}const Fo={PASSWORD:"password"},Zn={EMAIL_LINK:"emailLink",EMAIL_PASSWORD:"password"};class In{providerId;signInMethod;constructor(t,n){this.providerId=t,this.signInMethod=n}toJSON(){return{providerId:this.providerId,signInMethod:this.signInMethod}}static fromJSON(t){const n=typeof t=="string"?Jm(t):t;if(!n)return null;const r=n.providerId,s=n.signInMethod;if(typeof r!="string"||typeof s!="string")return null;if(r===Fo.PASSWORD){const i=typeof n.email=="string"?n.email:"",a=typeof n.password=="string"?n.password:"";return new Ym(i,a,s)}return new In(r,s)}}function Jm(e){try{const t=JSON.parse(e);return typeof t=="object"&&t!==null?t:null}catch{return null}}class Ym extends In{email;secret;constructor(t,n,r=Zn.EMAIL_PASSWORD){super(Fo.PASSWORD,r),this.email=t,Object.defineProperty(this,"secret",{value:n,enumerable:!1,writable:!1})}get password(){return this.signInMethod===Zn.EMAIL_PASSWORD?this.secret:null}get emailLink(){return this.signInMethod===Zn.EMAIL_LINK?this.secret:null}toJSON(){return{providerId:this.providerId,signInMethod:this.signInMethod,email:this.email,password:this.secret}}}class Dn extends In{idToken;accessToken;secret;constructor(t,n,r={}){super(t,n),this.idToken=r.idToken,this.accessToken=r.accessToken,this.secret=r.secret}toJSON(){return{providerId:this.providerId,signInMethod:this.signInMethod,idToken:this.idToken,accessToken:this.accessToken,secret:this.secret}}}function us(e,t){return t?new Dn(e,e):null}class nt{static PROVIDER_ID="google.com";static GOOGLE_SIGN_IN_METHOD="google.com";providerId=nt.PROVIDER_ID;addScope(t){return this}setCustomParameters(t){return this}static credentialFromResult(t){return us(nt.PROVIDER_ID,t)}static credentialFromError(t){return null}static credential(t,n){return new Dn(nt.PROVIDER_ID,nt.GOOGLE_SIGN_IN_METHOD,{idToken:t??void 0,accessToken:n??void 0})}}class rt{static PROVIDER_ID="facebook.com";static FACEBOOK_SIGN_IN_METHOD="facebook.com";providerId=rt.PROVIDER_ID;addScope(t){return this}setCustomParameters(t){return this}static credentialFromResult(t){return us(rt.PROVIDER_ID,t)}static credentialFromError(t){return null}static credential(t){return new Dn(rt.PROVIDER_ID,rt.FACEBOOK_SIGN_IN_METHOD,{accessToken:t})}}class st{static PROVIDER_ID="github.com";static GITHUB_SIGN_IN_METHOD="github.com";providerId=st.PROVIDER_ID;addScope(t){return this}setCustomParameters(t){return this}static credentialFromResult(t){return us(st.PROVIDER_ID,t)}static credentialFromError(t){return null}static credential(t){return new Dn(st.PROVIDER_ID,st.GITHUB_SIGN_IN_METHOD,{accessToken:t})}}const Vo=[nt.PROVIDER_ID,"apple.com",rt.PROVIDER_ID,st.PROVIDER_ID,"twitter.com","microsoft.com","yahoo.com"];function ds(e,t=!1){const n=e[Lo];if(!n)throw new TypeError("pyric/auth: unrecognized Auth handle — was it produced by getAuth(...)?");return t||n.assertAlive?.(),n}class Qm{mockResults=new Map;resolver=null;redirectResult=null;setMockResult(t,n){this.mockResults.set(t,n)}consumeMockResult(t){const n=this.mockResults.get(t);return n&&this.mockResults.delete(t),n}setResolver(t){this.resolver=t}getResolver(){return this.resolver}setRedirectResult(t){this.redirectResult=t}takeRedirectResult(){const t=this.redirectResult;return this.redirectResult=null,t}actionCodes=new Map;nextCodeSerial=1;outbox=[];mailResolver=null;mintActionCode(t){const n=`sandbox-oob-${this.nextCodeSerial++}`;return this.actionCodes.set(n,t),n}stageActionCode(t,n){this.actionCodes.set(t,n)}peekActionCode(t){return this.actionCodes.get(t)}consumeActionCode(t){const n=this.actionCodes.get(t);return n&&this.actionCodes.delete(t),n}setMailResolver(t){this.mailResolver=t}deliverMail(t){if(this.outbox.push(t),this.mailResolver)try{this.mailResolver.deliver(t)}catch{}}takeMail(t){const n=t===void 0?this.outbox.length>0?0:-1:this.outbox.findIndex(r=>r.email.toLowerCase()===t.toLowerCase());return n<0?null:this.outbox.splice(n,1)[0]??null}listMail(){return[...this.outbox]}}function Xm(e,t,n){const r=JSON.stringify(t);return`sandbox-id-token-${e}-${String(n)}:${r}`}function Ue(e){if(typeof e!="string"||e.length===0)throw q("auth/invalid-email","Error");const t=e.indexOf("@");if(t<=0||t===e.length-1)throw q("auth/invalid-email","Error")}function jt(e){if(typeof e!="string"||e.length<6)throw q("auth/weak-password","Password should be at least 6 characters")}function qo(){return{usersByEmail:new Map,usersByUid:new Map,userDbSubscribers:new Set,providerConfig:new Map([["password",!0],["anonymous",!0]]),providerConfigSubscribers:new Set,counters:{nextAdminUserId:1,nextAnonymousId:1}}}const Zm="__pyric_no_password__";class Wo{usersByEmail;usersByUid;authStateSubs=[];idTokenSubs=[];userDbSubs;beforeStateSubs=[];sharedCounters;flow=new Qm;sandbox;session;cachedUser=null;lastNotifiedUid=null;applyingTransition=!1;tokenCache=new Map;nextTokenSerial=1;persistenceMode="LOCAL";signInProviderByUid=new Map;providerConfig;providerConfigSubs;providerEnforcementDelegated=!1;constructor(t,n=t,r=qo(),s){this.sandbox=t,this.session=n,this.usersByEmail=r.usersByEmail,this.usersByUid=r.usersByUid,this.userDbSubs=r.userDbSubscribers,this.providerConfig=r.providerConfig,this.providerConfigSubs=r.providerConfigSubscribers,this.sharedCounters=r.counters,this.cachedUser=this.buildUserFromState(n.currentUser),this.lastNotifiedUid=this.cachedUser?.uid??null;const i=n.onCurrentUserChanged(a=>{if(this.applyingTransition)return;const c=a===null?null:a.uid,l=this.cachedUser?.uid??null;c!==l&&(this.cachedUser=this.buildUserFromState(a)),this.notifyAuthListeners()});s?.(()=>{i(),this.authStateSubs.length=0,this.idTokenSubs.length=0,this.beforeStateSubs.length=0})}getCurrentUser(){return this.cachedUser}subscribe(t,n){const r=t==="auth-state"?this.authStateSubs:this.idTokenSubs,s={observer:n,hasFired:!1,lastValue:null};return r.push(s),queueMicrotask(()=>{r.includes(s)&&(s.hasFired&&s.lastValue===this.cachedUser||this.deliverOne(s,this.cachedUser))}),()=>{const i=r.indexOf(s);i!==-1&&r.splice(i,1)}}fanOut(t="both"){const n=this.cachedUser;if(t==="both"||t==="auth-state")for(const r of[...this.authStateSubs])this.deliverOne(r,n);if(t==="both"||t==="id-token")for(const r of[...this.idTokenSubs])this.deliverOne(r,n)}notifyAuthListeners(){this.fanOut("id-token");const t=this.cachedUser?.uid??null;this.lastNotifiedUid!==t&&(this.lastNotifiedUid=t,this.fanOut("auth-state"))}deliverOne(t,n){t.hasFired=!0,t.lastValue=n;const r=t.observer;try{typeof r=="function"?r(n):r.next&&r.next(n)}catch{}}makeStored(t){return{email:null,password:null,displayName:null,phoneNumber:null,photoUrl:null,customClaims:{},isAnonymous:!1,providerUserInfo:[],disabled:!1,emailVerified:!1,createdAt:new Date().toISOString(),lastLoginAt:null,...t}}notifyUsersChanged(){for(const t of[...this.userDbSubs])try{t()}catch{}}emitAuthEvent(t,n={}){try{Re(this.sandbox,wn({service:"auth",op:t,path:n.path,auth:n.auth??this.session.currentUser,before:n.before,after:n.after,detail:n.detail}),{service:"auth"})}catch{}}subscribeUsers(t){return this.userDbSubs.add(t),()=>{this.userDbSubs.delete(t)}}isProviderEnabled(t){return this.providerConfig.get(t)??!0}listProviderConfig(){return[...this.providerConfig.entries()].map(([t,n])=>({providerId:t,enabled:n}))}setProviderConfig(t,n){const r=this.providerConfig.get(t)??!0;r!==n&&(this.providerConfig.set(t,n),this.notifyProviderConfigChanged(),this.emitAuthEvent("provider_config_update",{path:t,auth:null,before:{providerId:t,enabled:r},after:{providerId:t,enabled:n}}))}notifyProviderConfigChanged(){for(const t of[...this.providerConfigSubs])try{t()}catch{}}subscribeProviderConfig(t){return this.providerConfigSubs.add(t),()=>{this.providerConfigSubs.delete(t)}}setProviderEnforcementDelegated(t){this.providerEnforcementDelegated=t}assertProviderEnabled(t){if(!this.providerEnforcementDelegated&&!this.isProviderEnabled(t))throw q("auth/operation-not-allowed",`${t} sign-in is disabled for this sandbox project. Enable it with sandbox.setAuthProviderConfig(auth, '${t}', true).`)}exportProviderConfig(){return Object.fromEntries(this.providerConfig)}restoreProviderConfig(t){if(this.providerConfig.clear(),t&&typeof t=="object")for(const[n,r]of Object.entries(t))typeof r=="boolean"&&this.providerConfig.set(n,r);else this.providerConfig.set("password",!0),this.providerConfig.set("anonymous",!0);this.notifyProviderConfigChanged()}getPersistenceMode(){return this.persistenceMode}setPersistenceMode(t){this.persistenceMode!==t&&(this.persistenceMode=t,this.notifySessionChanged())}sessionChangeSubs=new Set;notifySessionChanged(){for(const t of[...this.sessionChangeSubs])try{t()}catch{}}subscribeSession(t){return this.sessionChangeSubs.add(t),()=>{this.sessionChangeSubs.delete(t)}}seedUsers(t){for(const n of t){const r=this.usersByUid.get(n.uid);r?.email&&r.email.toLowerCase()!==n.email.toLowerCase()&&this.usersByEmail.delete(r.email.toLowerCase());const s=this.makeStored({uid:n.uid,email:n.email,password:n.password,displayName:n.displayName??null,customClaims:n.customClaims??{},providerUserInfo:[{providerId:n.providerId??"password"}]});this.usersByEmail.set(n.email.toLowerCase(),s),this.usersByUid.set(n.uid,s)}t.length>0&&this.notifyUsersChanged()}exportUsers(){const t=[];for(const n of this.usersByUid.values()){if(n.email===null)continue;const r={uid:n.uid,email:n.email,password:n.password??Zm,providerId:n.providerUserInfo[0]?.providerId??"password"};n.displayName!==null&&(r.displayName=n.displayName),Object.keys(n.customClaims).length>0&&(r.customClaims=n.customClaims),t.push(r)}return t}restoreSession(t){const n=this.usersByUid.get(t);if(!n)throw q("auth/user-not-found",`restoreSession: no identity with uid ${t}.`);if(n.disabled)throw q("auth/user-disabled",`restoreSession: user ${t} is disabled.`);const r=n.isAnonymous?"anonymous":n.providerUserInfo[0]?.providerId??"password",s=this.buildUserFromStored(n);return this.setCurrentUser(s,r),s}findByEmail(t){return this.usersByEmail.get(t.toLowerCase())}findByUid(t){return this.usersByUid.get(t)}mintActionCode(t){return this.flow.mintActionCode(t)}stageActionCode(t,n){this.flow.stageActionCode(t,n)}peekActionCode(t){return this.flow.peekActionCode(t)}consumeActionCode(t){return this.flow.consumeActionCode(t)}deliverMail(t){this.flow.deliverMail(t)}takeMail(t){return this.flow.takeMail(t)}listMail(){return this.flow.listMail()}setMailResolver(t){this.flow.setMailResolver(t)}setEmailVerified(t,n){const r=this.requireByEmail(t);return r.emailVerified!==n&&(r.emailVerified=n,this.notifyUsersChanged(),this.emitAuthEvent("user_update",{path:r.uid,after:this.toRecord(r),detail:{emailVerified:n}})),r}setPasswordByEmail(t,n){jt(n);const r=this.requireByEmail(t);return r.password=n,this.notifyUsersChanged(),this.emitAuthEvent("user_update",{path:r.uid,after:this.toRecord(r),detail:{passwordReset:!0}}),r}changeEmail(t,n){Ue(n);const r=this.requireByEmail(t),s=n.toLowerCase(),i=this.usersByEmail.get(s);if(i&&i.uid!==r.uid)throw q("auth/email-already-in-use",`An account already exists for ${n}.`);return r.email&&this.usersByEmail.delete(r.email.toLowerCase()),r.email=n,r.emailVerified=!0,this.usersByEmail.set(s,r),this.notifyUsersChanged(),this.emitAuthEvent("user_update",{path:r.uid,after:this.toRecord(r),detail:{emailChanged:n}}),r}upsertEmailLinkUser(t){Ue(t);const n=t.toLowerCase(),r=this.usersByEmail.get(n);if(r)return r.providerUserInfo.some(a=>a.providerId==="password")||r.providerUserInfo.push({providerId:"password"}),r.emailVerified=!0,this.notifyUsersChanged(),{stored:r,isNewUser:!1};const s=`email-${n}-${this.usersByEmail.size+1}`,i=this.makeStored({uid:s,email:t,providerUserInfo:[{providerId:"password"}]});return i.emailVerified=!0,this.usersByEmail.set(n,i),this.usersByUid.set(s,i),this.notifyUsersChanged(),this.emitAuthEvent("user_create",{path:s,after:this.toRecord(i),detail:{emailLink:!0}}),{stored:i,isNewUser:!0}}linkProvider(t,n,r){const s=this.usersByUid.get(t);if(!s)throw q("auth/user-not-found",`linkWithCredential: no identity with uid ${t}.`);if(s.providerUserInfo.some(a=>a.providerId===n))throw q("auth/provider-already-linked",`User can only be linked to one identity for the given provider (${n}).`);const i=r?.email;if(i){Ue(i);const a=i.toLowerCase(),c=this.usersByEmail.get(a);if(c&&c.uid!==t)throw q("auth/email-already-in-use",`An account already exists for ${i}.`);r.password!==void 0&&r.password!==null&&(jt(r.password),s.password=r.password),s.email&&s.email.toLowerCase()!==a&&this.usersByEmail.delete(s.email.toLowerCase()),s.email=i,this.usersByEmail.set(a,s),r.emailVerified!==void 0&&(s.emailVerified=r.emailVerified)}return s.providerUserInfo.push({providerId:n}),s.isAnonymous&&(s.isAnonymous=!1),this.notifyUsersChanged(),this.emitAuthEvent("user_update",{path:t,after:this.toRecord(s),detail:{linked:n}}),s}unlinkProvider(t,n){const r=this.usersByUid.get(t);if(!r)throw q("auth/user-not-found",`unlink: no identity with uid ${t}.`);const s=r.providerUserInfo.findIndex(i=>i.providerId===n);if(s<0)throw q("auth/no-such-provider",`User was not linked to an account with the given provider (${n}).`);return r.providerUserInfo.splice(s,1),n==="password"&&(r.password=null),this.notifyUsersChanged(),this.emitAuthEvent("user_update",{path:t,after:this.toRecord(r),detail:{unlinked:n}}),r}requireByEmail(t){const n=this.usersByEmail.get(t.toLowerCase());if(!n)throw q("auth/user-not-found",`No user found for ${t}.`);return n}createEmailPasswordUser(t,n){Ue(t),jt(n);const r=t.toLowerCase();if(this.usersByEmail.has(r))throw q("auth/email-already-in-use",`An account already exists for ${t}.`);const s=`email-${r}-${this.usersByEmail.size+1}`,i=this.makeStored({uid:s,email:t,password:n,providerUserInfo:[{providerId:"password"}]});return this.usersByEmail.set(r,i),this.usersByUid.set(s,i),this.notifyUsersChanged(),this.emitAuthEvent("user_create",{path:s,after:this.toRecord(i)}),i}beforeAuthStateChanged(t,n){const r={callback:t,onAbort:n,active:!0};return this.beforeStateSubs.push(r),()=>{r.active=!1}}async runBeforeStateChange(t){if(t===this.cachedUser)return;const n=[];try{for(const r of this.beforeStateSubs)r.active&&(await r.callback(t),r.onAbort&&n.push(r.onAbort))}catch(r){n.reverse();for(const i of n)try{i()}catch{}const s=r instanceof Error?r.message:String(r);throw q("auth/login-blocked",s)}}transitionCurrentUser(t,n){return!this.beforeStateSubs.some(s=>s.active)||t===this.cachedUser?(this.setCurrentUser(t,n),Promise.resolve()):this.runBeforeStateChange(t).then(()=>{this.setCurrentUser(t,n)})}setCurrentUser(t,n){if(t===null){const a=this.cachedUser;this.cachedUser=null,this.applyingTransition=!0;try{this.session.currentUser=null}finally{this.applyingTransition=!1}a&&(this.tokenCache.delete(a.uid),this.notifyAuthListeners(),this.notifySessionChanged(),this.emitAuthEvent("sign_out",{path:a.uid,auth:{uid:a.uid}}));return}n!==void 0&&this.signInProviderByUid.set(t.uid,n);const r=this.usersByUid.get(t.uid),s=r?.customClaims??{};n!==void 0&&r&&(r.lastLoginAt=new Date().toISOString(),this.notifyUsersChanged()),this.cachedUser=t,this.tokenCache.set(t.uid,this.mintToken(t.uid,s));const i={uid:t.uid,token:s};this.applyingTransition=!0;try{this.session.currentUser=i}finally{this.applyingTransition=!1}this.notifyAuthListeners(),this.notifySessionChanged(),n!==void 0&&this.emitAuthEvent("sign_in",{path:t.uid,auth:i,after:{uid:t.uid,isAnonymous:t.isAnonymous,email:t.email},detail:{providerId:n??"anonymous"}})}setMockResult(t,n){this.flow.setMockResult(t,n)}consumeMockResult(t){return this.flow.consumeMockResult(t)}setResolver(t){this.flow.setResolver(t)}getResolver(){return this.flow.getResolver()}setRedirectResult(t){this.flow.setRedirectResult(t)}takeRedirectResult(){return this.flow.takeRedirectResult()}recordProviderSignIn(t,n){let r=!1,s=this.usersByUid.get(t.uid);s||(s=this.makeStored({uid:t.uid,email:t.email,displayName:t.displayName,isAnonymous:t.isAnonymous}),this.usersByUid.set(t.uid,s),t.email&&this.usersByEmail.set(t.email.toLowerCase(),s),r=!0),s.providerUserInfo.some(i=>i.providerId===n)||(s.providerUserInfo.push({providerId:n}),r=!0),r&&this.notifyUsersChanged()}createSignInCredential(t){const{providerId:n}=t;let r;if("uid"in t){const s=this.usersByUid.get(t.uid);if(!s)throw q("auth/user-not-found",`createSignInCredential: no identity with uid ${t.uid}. Use the {spec} shape to create one.`);r=s}else{const{spec:s}=t,i=this.usersByEmail.get(s.email.toLowerCase());i?r=i:(r=this.makeStored({uid:s.uid??ey(),email:s.email,displayName:s.displayName??null,customClaims:s.customClaims??{}}),this.usersByUid.set(r.uid,r),this.usersByEmail.set(s.email.toLowerCase(),r),this.notifyUsersChanged())}return r.providerUserInfo.some(s=>s.providerId===n)||(r.providerUserInfo.push({providerId:n}),this.notifyUsersChanged()),{user:this.buildUserFromStored(r),providerId:n,operationType:"signIn"}}listIdentities(){return[...this.usersByUid.values()].map(t=>({uid:t.uid,email:t.email,displayName:t.displayName,providerId:t.isAnonymous?"anonymous":t.providerUserInfo[0]?.providerId??"password",providerUserInfo:[...t.providerUserInfo],isAnonymous:t.isAnonymous,customClaims:t.customClaims}))}toRecord(t){return{uid:t.uid,email:t.email,displayName:t.displayName,phoneNumber:t.phoneNumber,photoUrl:t.photoUrl,customClaims:{...t.customClaims},providerUserInfo:t.providerUserInfo.map(n=>({...n})),isAnonymous:t.isAnonymous,disabled:t.disabled,emailVerified:t.emailVerified,createdAt:t.createdAt,lastLoginAt:t.lastLoginAt}}listUsers(){return[...this.usersByUid.values()].map(t=>this.toRecord(t))}sanitizeLinkedProviders(t,n,r){const s=new Set,i=[];for(const a of t){const c=a?.providerId?.trim();if(!c)throw q("auth/argument-error",`${r}: providerUserInfo entries need a non-empty providerId.`);c==="password"||c==="anonymous"||s.has(c)||(s.add(c),i.push({providerId:c}))}return n&&i.unshift({providerId:"password"}),i}createUser(t){const n=t.uid??`user-${this.sharedCounters.nextAdminUserId++}`;if(this.usersByUid.has(n))throw q("auth/uid-already-exists",`createUser: a user with uid ${n} already exists.`);if(t.email!==void 0&&(Ue(t.email),this.usersByEmail.has(t.email.toLowerCase())))throw q("auth/email-already-in-use",`An account already exists for ${t.email}.`);if(t.password!==void 0&&(jt(t.password),t.email===void 0))throw q("auth/invalid-email","createUser: a password requires an email.");const r=this.makeStored({uid:n,email:t.email??null,password:t.password??null,displayName:t.displayName??null,phoneNumber:t.phoneNumber??null,photoUrl:t.photoUrl??null,customClaims:t.customClaims??{},disabled:t.disabled??!1,emailVerified:t.emailVerified??!1,providerUserInfo:this.sanitizeLinkedProviders(t.providerUserInfo??[],t.password!==void 0,"createUser")});this.usersByUid.set(n,r),r.email&&this.usersByEmail.set(r.email.toLowerCase(),r),this.notifyUsersChanged();const s=this.toRecord(r);return this.emitAuthEvent("user_create",{path:n,auth:null,after:s}),s}updateUser(t,n){const r=this.usersByUid.get(t);if(!r)throw q("auth/user-not-found",`No user found for uid ${t}.`);const s=this.toRecord(r);if(n.email!==void 0){Ue(n.email);const a=n.email.toLowerCase(),c=this.usersByEmail.get(a);if(c&&c!==r)throw q("auth/email-already-in-use",`An account already exists for ${n.email}.`);r.email&&this.usersByEmail.delete(r.email.toLowerCase()),r.email=n.email,this.usersByEmail.set(a,r)}n.password!==void 0&&(jt(n.password),r.password=n.password,r.providerUserInfo.some(a=>a.providerId==="password")||r.providerUserInfo.push({providerId:"password"})),n.providerUserInfo!==void 0&&(r.providerUserInfo=this.sanitizeLinkedProviders(n.providerUserInfo,r.password!==null,"updateUser")),n.displayName!==void 0&&(r.displayName=n.displayName),n.customClaims!==void 0&&(r.customClaims={...n.customClaims}),n.disabled!==void 0&&(r.disabled=n.disabled),n.emailVerified!==void 0&&(r.emailVerified=n.emailVerified),this.notifyUsersChanged();const i=this.toRecord(r);return this.emitAuthEvent("user_update",{path:t,auth:null,before:s,after:i}),i}deleteUser(t){const n=this.usersByUid.get(t);if(!n)throw q("auth/user-not-found",`No user found for uid ${t}.`);const r=this.toRecord(n);this.usersByUid.delete(t),n.email&&this.usersByEmail.get(n.email.toLowerCase())===n&&this.usersByEmail.delete(n.email.toLowerCase()),this.tokenCache.delete(t),this.signInProviderByUid.delete(t),this.notifyUsersChanged(),this.emitAuthEvent("user_delete",{path:t,auth:null,before:r})}clearUsers(){if(this.usersByUid.size===0&&this.usersByEmail.size===0)return;const t=this.usersByUid.size;this.usersByUid.clear(),this.usersByEmail.clear(),this.notifyUsersChanged(),this.emitAuthEvent("users_clear",{path:"*",auth:null,detail:{count:t}})}assertSignInAllowed(t){if(this.usersByUid.get(t)?.disabled)throw q("auth/user-disabled","The user account has been disabled by an administrator.")}buildUserFromStored(t){return this.makeUser({uid:t.uid,email:t.email,displayName:t.displayName,isAnonymous:t.isAnonymous,claims:t.customClaims,photoURL:t.photoUrl,emailVerified:t.emailVerified,phoneNumber:t.phoneNumber,providers:t.providerUserInfo})}mintAnonymousUser(){const t=`anonymous-${this.sharedCounters.nextAnonymousId++}`,n=this.makeStored({uid:t,isAnonymous:!0});return this.usersByUid.set(t,n),this.notifyUsersChanged(),this.emitAuthEvent("user_create",{path:t,after:this.toRecord(n),detail:{isAnonymous:!0}}),this.makeUser({uid:t,email:null,displayName:null,isAnonymous:!0,claims:{}})}mintDetachedSession(t){switch(t.kind){case"anonymous":return this.assertProviderEnabled("anonymous"),this.establishDetachedSession(this.mintAnonymousUser(),"anonymous");case"password":return this.assertProviderEnabled("password"),this.establishDetachedSession(this.buildUserFromStored(this.validatePassword(t.email,t.password)),"password");case"createPassword":return this.assertProviderEnabled("password"),this.establishDetachedSession(this.buildUserFromStored(this.createEmailPasswordUser(t.email,t.password)),"password");case"uid":{const n=this.usersByUid.get(t.uid);if(!n)throw q("auth/user-not-found",`mintSession: no identity with uid ${t.uid}.`);if(n.disabled)throw q("auth/user-disabled",`mintSession: user ${t.uid} is disabled.`);const r=n.isAnonymous?"anonymous":n.providerUserInfo[0]?.providerId??"password";return this.establishDetachedSession(this.buildUserFromStored(n),r)}}}establishDetachedSession(t,n){this.signInProviderByUid.set(t.uid,n);const r=this.usersByUid.get(t.uid),s=r?.customClaims??{};r&&(r.lastLoginAt=new Date().toISOString(),this.notifyUsersChanged()),this.tokenCache.set(t.uid,this.mintToken(t.uid,s));const i={uid:t.uid,token:s};return this.emitAuthEvent("sign_in",{path:t.uid,auth:i,after:{uid:t.uid,isAnonymous:t.isAnonymous,email:t.email},detail:{providerId:n,session:"connection"}}),{user:t,state:i}}buildUserFromState(t){if(t===null)return null;const n=this.usersByUid.get(t.uid);return n?this.buildUserFromStored({...n,customClaims:t.token??n.customClaims}):this.makeUser({uid:t.uid,email:null,displayName:null,isAnonymous:t.uid.startsWith("anonymous-"),claims:t.token??{}})}mintToken(t,n){const r=new Date,s=new Date(r.getTime()+100*365*24*60*60*1e3),i=this.nextTokenSerial++,a=Xm(t,n,i),c=this.signInProviderByUid.get(t)??null,l={sub:t,aud:"pyric-sandbox",iss:"https://sandbox.pyric.dev",auth_time:Math.floor(r.getTime()/1e3),iat:Math.floor(r.getTime()/1e3),exp:Math.floor(s.getTime()/1e3),...n,firebase:{sign_in_provider:c}},u={token:a,claims:l,expirationTime:s.toISOString(),issuedAtTime:r.toISOString(),authTime:r.toISOString(),signInProvider:c};return{token:a,result:u}}getIdTokenFor(t,n,r){if(r){const a=this.mintToken(t,n);return this.tokenCache.set(t,a),this.fanOut("id-token"),a.token}const s=this.tokenCache.get(t);if(s)return s.token;const i=this.mintToken(t,n);return this.tokenCache.set(t,i),i.token}getIdTokenResultFor(t,n,r){if(r){const a=this.mintToken(t,n);return this.tokenCache.set(t,a),this.fanOut("id-token"),a.result}const s=this.tokenCache.get(t);if(s)return s.result;const i=this.mintToken(t,n);return this.tokenCache.set(t,i),i.result}makeUser(t){const n=t.photoURL??null,r=t.phoneNumber??null,s=t.emailVerified??!1,i="firebase",a=t.providers??[{providerId:"password"}],c=t.isAnonymous?[]:a.map(u=>({uid:t.uid,displayName:t.displayName,email:t.email,phoneNumber:r,photoURL:n,providerId:u.providerId})),l={uid:t.uid,email:t.email,emailVerified:s,displayName:t.displayName,photoURL:n,phoneNumber:r,isAnonymous:t.isAnonymous,providerId:i,providerData:c,getIdToken:async u=>this.getIdTokenFor(t.uid,this.liveClaims(t.uid,t.claims),u===!0),getIdTokenResult:async u=>this.getIdTokenResultFor(t.uid,this.liveClaims(t.uid,t.claims),u===!0)};return Object.defineProperty(l,Gm,{value:{updateProfile:u=>(this.updateProfileFor(l,u),Promise.resolve()),delete:()=>(this.deleteFor(l),Promise.resolve()),updateEmail:u=>(this.updateEmailFor(l,u),Promise.resolve()),updatePassword:u=>(this.updatePasswordFor(l,u),Promise.resolve()),reload:()=>(this.reloadFor(l),Promise.resolve()),target:this.selfTarget()},enumerable:!1}),l}selfTarget(){return{kind:"sandbox",sandbox:this.sandbox,backend:this}}updateProfileFor(t,n){const r=this.usersByUid.get(t.uid),s=r?this.toRecord(r):void 0;r&&(n.displayName!==void 0&&(r.displayName=n.displayName),n.photoURL!==void 0&&(r.photoUrl=n.photoURL)),this.applyProfileToUser(t,n),this.cachedUser&&this.cachedUser.uid===t.uid&&this.cachedUser!==t&&this.applyProfileToUser(this.cachedUser,n),this.notifyUsersChanged(),this.emitAuthEvent("user_update",{path:t.uid,auth:{uid:t.uid},before:s,after:r?this.toRecord(r):void 0,detail:{displayName:n.displayName,photoURL:n.photoURL}})}applyProfileToUser(t,n){const r=t;n.displayName!==void 0&&(r.displayName=n.displayName),n.photoURL!==void 0&&(r.photoURL=n.photoURL);const s=t.providerData?.[0];s&&(n.displayName!==void 0&&(s.displayName=n.displayName),n.photoURL!==void 0&&(s.photoURL=n.photoURL))}updateProfileByUid(t,n){const r=this.usersByUid.get(t);if(!r)throw q("auth/user-not-found",`updateProfile: no identity with uid ${t}.`);const s=this.toRecord(r);n.displayName!==void 0&&(r.displayName=n.displayName),n.photoURL!==void 0&&(r.photoUrl=n.photoURL),this.cachedUser&&this.cachedUser.uid===t&&this.applyProfileToUser(this.cachedUser,n),this.notifyUsersChanged();const i=this.toRecord(r);return this.emitAuthEvent("user_update",{path:t,auth:{uid:t},before:s,after:i,detail:{displayName:n.displayName,photoURL:n.photoURL}}),i}deleteFor(t){this.usersByUid.has(t.uid)&&this.deleteUser(t.uid),this.cachedUser&&this.cachedUser.uid===t.uid&&this.setCurrentUser(null)}updateEmailFor(t,n){this.updateUser(t.uid,{email:n}),this.applyEmailToUser(t,n),this.cachedUser&&this.cachedUser.uid===t.uid&&this.cachedUser!==t&&this.applyEmailToUser(this.cachedUser,n)}applyEmailToUser(t,n){t.email=n;const r=t.providerData?.[0];r&&(r.email=n)}updatePasswordFor(t,n){this.updateUser(t.uid,{password:n})}reloadFor(t){const n=this.usersByUid.get(t.uid);if(!n)throw q("auth/user-token-expired","The user's credential is no longer valid. The user must sign in again.");this.applyStoredToUser(t,n),this.cachedUser&&this.cachedUser.uid===t.uid&&this.cachedUser!==t&&this.applyStoredToUser(this.cachedUser,n)}applyStoredToUser(t,n){const r=t;r.email=n.email,r.displayName=n.displayName,r.photoURL=n.photoUrl,r.emailVerified=n.emailVerified,r.phoneNumber=n.phoneNumber}liveClaims(t,n){return this.usersByUid.get(t)?.customClaims??n}validatePassword(t,n){if(Ue(t),typeof n!="string"||n.length===0)throw q("auth/missing-password","A non-empty password must be provided");const r=this.findByEmail(t);if(!r)throw q("auth/user-not-found",`No user found for ${t}.`);if(r.disabled)throw q("auth/user-disabled","The user account has been disabled by an administrator.");if(r.password!==n)throw q("auth/wrong-password","Invalid password.");return r}}function ey(){return`provider-${globalThis.crypto.randomUUID()}`}const ki=new WeakSet,Wt=new WeakMap;function zo(e,t,n,r="[DEFAULT]"){return ty(e,t),ny(e,t,n,r)}function ty(e,t){ki.has(e)||(ki.add(e),e.registerPersistableService("auth",{snapshot:()=>({users:t.exportUsers(),providers:t.exportProviderConfig()}),restore:n=>{const r=n;t.clearUsers(),Array.isArray(r?.users)&&r.users.length>0&&t.seedUsers(r.users),t.restoreProviderConfig(r?.providers)},reset:()=>{t.clearUsers(),t.restoreProviderConfig(void 0)},subscribe:n=>{const r=t.subscribeUsers(n),s=t.subscribeProviderConfig(n);return()=>{r(),s()}}}))}function _i(e){return{snapshot:()=>null,restore:()=>{},session:{currentUid:()=>e.session.currentUser?.uid??null,restore:(t,n)=>{e.backend.setPersistenceMode(n),e.backend.restoreSession(t)},mode:()=>e.backend.getPersistenceMode(),subscribe:t=>(e.subscribers.add(t),e.unsubscribeBackend||(e.unsubscribeBackend=e.backend.subscribeSession(()=>{for(const n of e.subscribers)n()})),()=>{e.subscribers.delete(t),e.subscribers.size===0&&(e.unsubscribeBackend?.(),e.unsubscribeBackend=void 0)})}}}function ny(e,t,n,r){let s=Wt.get(e);s||(s=new Map,Wt.set(e,s));const i=`auth-session:${r}`,a=s.get(i);if(a){const u=++a.generation;return a.unregisterService?.(),a.unregisterService=void 0,a.unsubscribeBackend?.(),a.unsubscribeBackend=void 0,a.backend=t,a.session=n,a.unregisterService=e.registerPersistableService(i,_i(a)),()=>{a.generation===u&&(a.unregisterService?.(),a.unregisterService=void 0,a.unsubscribeBackend?.(),a.unsubscribeBackend=void 0,a.subscribers.clear(),s.get(i)===a&&s.delete(i),s.size===0&&Wt.delete(e))}}const c={backend:t,session:n,subscribers:new Set,generation:1};s.set(i,c),c.unregisterService=e.registerPersistableService(i,_i(c));const l=c.generation;return()=>{c.generation===l&&(c.unregisterService?.(),c.unregisterService=void 0,c.unsubscribeBackend?.(),c.unsubscribeBackend=void 0,c.subscribers.clear(),s.get(i)===c&&s.delete(i),s.size===0&&Wt.delete(e))}}async function vk(e){const{backend:t}=ds(e);t.assertProviderEnabled("anonymous");const n=t.getCurrentUser();if(n?.isAnonymous)return{user:n,providerId:null,operationType:"signIn",_additionalUserInfo:{isNewUser:!1,profile:{},providerId:null}};const r=t.mintAnonymousUser();return await t.transitionCurrentUser(r,"anonymous"),{user:r,providerId:null,operationType:"signIn",_additionalUserInfo:{isNewUser:!0,profile:{},providerId:null}}}async function ry(e){const t=ds(e,!0);try{t.assertAlive?.()}catch(n){if(n.code==="app/app-deleted")return;throw n}await t.backend.transitionCurrentUser(null)}const Si=new WeakMap,Ei=new WeakMap,Ci=new WeakMap;function Ko(e){let t=Ei.get(e);return t||(t=qo(),Ei.set(e,t)),t}function sy(e){let t=Si.get(e);return t||(t=new Wo(e,e,Ko(e)),Si.set(e,t),zo(e,t,e)),t}function iy(e,t){return t.service("auth/backend",()=>{const{sandbox:n,session:r}=t,s=new Wo(n,r,Ko(n),i=>{t.onDelete(i)});return t.onDelete(zo(n,s,r,e.name)),s})}function Ho(e){if(e===void 0)return Ho(zl());const t=Kl(e);if(t)return t.service("auth/default",()=>{const n={kind:"sandbox",sandbox:t.sandbox,backend:iy(e,t),own:r=>t.onDelete(r),assertAlive:()=>t.assertAlive()};return Ni(n,e)});if(ay(e)){let n=Ci.get(e);return n||(n=Ni({kind:"sandbox",sandbox:e,backend:sy(e)}),Ci.set(e,n),n)}throw new TypeError("pyric/auth is a sandbox-only mirror. Package resolution must leave firebase/auth unchanged for production; activate pyric sandbox or @pyric/cli/register before importing to select the sandbox.")}function ay(e){return typeof e=="object"&&e!==null&&typeof e.onCurrentUserChanged=="function"&&typeof e.withAuth=="function"}function Ni(e,t){const n={[Lo]:e,...t?{app:t}:{},signOut(){return ry(n)}};return Object.defineProperty(n,"currentUser",{enumerable:!0,get(){return e.backend.getCurrentUser()}})}function K(e){return ds(e)}const fe={setUser(e,t){K(e).backend.setCurrentUser(t)},setAuthFlowResolver(e,t){K(e).backend.setResolver(t)},setAuthMailResolver(e,t){K(e).backend.setMailResolver(t)},takeAuthMail(e,t){return K(e).backend.takeMail(t)},listAuthMail(e){return K(e).backend.listMail()},mockActionCode(e,t,n){K(e).backend.stageActionCode(t,n)},listIdentities(e){return K(e).backend.listIdentities()},createSignInCredential(e,t){return K(e).backend.createSignInCredential(t)},mockSignInResult(e,t){const n=t.providerId;if(!n)throw new Pl("invalid-argument","sandbox.mockSignInResult: result.providerId is required so the next signInWithPopup / signInWithCredential call can match.");K(e).backend.setMockResult(n,t)},seedUsers(e,t){K(e).backend.seedUsers(t)},exportUsers(e){return K(e).backend.exportUsers()},restoreSession(e,t){return K(e).backend.restoreSession(t)},mintSession(e,t){return K(e).backend.mintDetachedSession(t)},listUsers(e){return K(e).backend.listUsers()},createUser(e,t){return K(e).backend.createUser(t)},updateUser(e,t,n){return K(e).backend.updateUser(t,n)},updateProfile(e,t,n){return K(e).backend.updateProfileByUid(t,n)},deleteUser(e,t){K(e).backend.deleteUser(t)},clearUsers(e){K(e).backend.clearUsers()},subscribeUsers(e,t){return K(e).backend.subscribeUsers(t)},getAuthProviderConfig(e){return K(e).backend.listProviderConfig()},setAuthProviderConfig(e,t,n){K(e).backend.setProviderConfig(t,n)},assertAuthProviderEnabled(e,t){K(e).backend.assertProviderEnabled(t)},delegateProviderEnforcement(e,t){K(e).backend.setProviderEnforcementDelegated(t)},subscribeAuthProviderConfig(e,t){return K(e).backend.subscribeProviderConfig(t)}};function It(e,t){return cy(e)?(_e(e.storage),new Dt(e.storage,oy(e.fullPath,t??""))):(_e(e),new Dt(e,Go(t??"")))}class Dt{storage;bucket;fullPath;constructor(t,n){this.storage=t;const r=_e(t);this.bucket=r.bucket,this.fullPath=n}get name(){if(this.fullPath==="")return"";const t=this.fullPath.lastIndexOf("/");return t===-1?this.fullPath:this.fullPath.slice(t+1)}get parent(){if(this.fullPath==="")return null;const t=this.fullPath.lastIndexOf("/"),n=t===-1?"":this.fullPath.slice(0,t);return new Dt(this.storage,n)}get root(){return this.fullPath===""?this:new Dt(this.storage,"")}toString(){return`gs://${this.bucket}/${this.fullPath}`}}function Go(e){return e===""?"":e.split("/").filter(t=>t.length>0).join("/")}function oy(e,t){const n=Go(t);return e===""?n:n===""?e:`${e}/${n}`}function cy(e){if(e===null||typeof e!="object"||Cn in e)return!1;const t=e;return typeof t.fullPath=="string"&&t.storage!==void 0}async function ly(e,t){return Jo(e,"getBlob"),uy(e,t)}async function fs(e,t){Jo(e,"deleteObject");const n=_e(e.storage),r=yt(n,t),s=await Tt(e.storage),i=await s.backend.getMetadata(e.fullPath);Ut(s,{request:{auth:Ke(n),method:"delete",path:e.fullPath},resource:Rn(i)},n,r),await s.backend.delete(e.fullPath);try{Re(n.sandbox,wn({service:"storage",op:"object_delete",path:e.fullPath,auth:Ke(n),before:i??void 0,detail:{bucket:e.bucket}}),r)}catch{}}async function uy(e,t){const n=_e(e.storage),r=yt(n),s=await Tt(e.storage),i=await s.backend.getMetadata(e.fullPath);Ut(s,{request:{auth:Ke(n),method:"get",path:e.fullPath},resource:Rn(i)},n,r);const a=await s.backend.getBlob(e.fullPath);if(!a)throw ko(e.fullPath);return typeof t=="number"&&a.size>t?a.slice(0,t):a}function Jo(e,t){if(e.fullPath==="")throw Nn(t)}function dy(e,t){if(e instanceof Blob)return t!==void 0&&t!==e.type?new Blob([e],{type:t}):e;let r="";return t!==void 0&&(r=t),new Blob([e],{type:r})}class fy{[Symbol.toStringTag]="UploadTask";_snapshot;_promise;_resolve;_reject;_observers=[];_didIntermediateProgress=!1;_error;_ref;_blob;_metadata;_provenance;constructor(t,n,r,s){this._ref=t,this._metadata=r,this._provenance=s;let i;r!==void 0&&(i=r.contentType),this._blob=dy(n,i);const c=So({ref:t,blob:this._blob,settable:r}),l=os(c);this._promise=new Promise((u,d)=>{this._resolve=u,this._reject=d}),this._promise.catch(()=>{}),this._snapshot={bytesTransferred:0,totalBytes:this._blob.size,state:"running",metadata:l,ref:this._ref,task:this},queueMicrotask(()=>{this._runStep()})}get snapshot(){return this._snapshot}then(t,n){return this._promise.then(t,n)}catch(t){return this._promise.catch(t)}finally(t){return this._promise.finally(t)}pause(){return this._snapshot.state==="running"?(this._updateSnapshot("paused",this._snapshot.bytesTransferred),this._notifyObservers("next"),!0):!1}resume(){return this._snapshot.state==="paused"?(this._updateSnapshot("running",this._snapshot.bytesTransferred),this._notifyObservers("next"),queueMicrotask(()=>{this._runStep()}),!0):!1}cancel(){let t=!1;return(this._snapshot.state==="running"||this._snapshot.state==="paused")&&(t=!0),t?(this._error=Wh(),this._updateSnapshot("canceled",this._snapshot.bytesTransferred),this._notifyObservers("error"),this._reject(this._error),!0):!1}on(t,n,r,s){let i,a,c,l=!1;if(typeof n=="object"&&n!==null&&(l=!0),l){const f=n;f.next!==void 0&&(i=f.next),f.error!==void 0&&(a=f.error),f.complete!==void 0&&(c=f.complete)}else typeof n=="function"&&(i=n),typeof r=="function"&&(a=r),typeof s=="function"&&(c=s);const d={next:i,error:a,complete:c};if(this._observers.push(d),this._snapshot.state==="running"){if(i!==void 0){const m=i;try{m(this._snapshot)}catch{}}}else if(this._snapshot.state==="paused"){if(i!==void 0){const y=i;try{y(this._snapshot)}catch{}}}else if(this._snapshot.state==="success"){if(i!==void 0){const v=i;try{v(this._snapshot)}catch{}}if(c!==void 0){const v=c;try{v()}catch{}}}else if(this._snapshot.state==="error"){if(a!==void 0&&this._error!==void 0){const b=a,w=this._error;try{b(w)}catch{}}}else if(this._snapshot.state==="canceled"&&a!==void 0&&this._error!==void 0){const w=a,x=this._error;try{w(x)}catch{}}return()=>{const f=this._observers.indexOf(d);f!==-1&&this._observers.splice(f,1)}}_updateSnapshot(t,n,r){let s=this._snapshot.metadata;r!==void 0&&(s=r),this._snapshot={bytesTransferred:n,totalBytes:this._snapshot.totalBytes,state:t,metadata:s,ref:this._ref,task:this}}_notifyObservers(t){if(t==="next"){for(const i of this._observers)if(i.next!==void 0){const c=i.next;try{c(this._snapshot)}catch{}}}if(t==="error"){for(const i of this._observers)if(i.error!==void 0&&this._error!==void 0){const l=i.error,u=this._error;try{l(u)}catch{}}}if(t==="complete"){for(const i of this._observers)if(i.complete!==void 0){const c=i.complete;try{c()}catch{}}}}_runStep(){if(this._snapshot.state!=="running")return;if(this._didIntermediateProgress===!1){this._didIntermediateProgress=!0;let r=0;this._snapshot.totalBytes>0&&(r=Math.floor(this._snapshot.totalBytes/2)),this._updateSnapshot("running",r),this._notifyObservers("next"),queueMicrotask(()=>{this._runStep()});return}this._commitUpload()}async _commitUpload(){if(this._snapshot.state==="running")try{const n=await _o(this._ref,this._blob,this._metadata,this._provenance);if(this._snapshot.state==="running")this._updateSnapshot("success",this._snapshot.totalBytes,n.metadata),this._notifyObservers("next"),this._notifyObservers("complete"),this._resolve(this._snapshot);else try{await fs(this._ref,this._provenance)}catch{}}catch(n){if(this._snapshot.state==="running"){let s;n instanceof Error?s=n:s=new Error(String(n)),this._error=s,this._updateSnapshot("error",this._snapshot.bytesTransferred),this._notifyObservers("error"),this._reject(this._error)}}}}function hy(e,t,n,r){if(e.fullPath==="")throw Nn("uploadBytesResumable");return new fy(e,t,n,r)}async function hs(e){const t=e.storage,n=_e(t),r=yt(n),s=await Tt(t);Ut(s,{request:{auth:Ke(n),method:"list",path:e.fullPath},resource:null},n,r);const i=e.fullPath===""?"":`${e.fullPath}/`,a=await s.backend.listByPrefix(i),c=[],l=new Set,u=[];for(const d of a){if(!d.fullPath.startsWith(i))continue;const p=d.fullPath.slice(i.length);if(p==="")continue;const f=p.indexOf("/");if(f===-1)c.push(It(t,d.fullPath));else{const m=p.slice(0,f),y=`${i}${m}`;l.has(y)||(l.add(y),u.push(It(t,y)))}}return u.sort((d,p)=>d.fullPath<p.fullPath?-1:d.fullPath>p.fullPath?1:0),{items:c,prefixes:u}}function py(e,t,n){const r={name:n,options:structuredClone(t),automaticDataCollectionEnabled:!0};return Hd(r,e),r}const my=Object.freeze({source:Object.freeze({kind:"studio"}),authLens:Object.freeze({mode:"admin"})});function yy(e){return Ra(e.withAuth(null),my)}const by="pyric-studio";function Yo(e,t){return e.listDocuments(t).map(({path:n,phantom:r})=>({path:n,phantom:r}))}let gy=0;function vy(e){const t=py(e,{projectId:"pyric-studio"},`pyric-studio-${gy++}`),n=xn(e),r=yy(e);return{sandbox:e,app:t,firestore:Oa(e),adminFirestore:Ma(r),auth:Ho(e),storage:_h(r),listRootCollections:()=>n.listRootCollections(),listSubcollections:s=>n.listSubcollections(s),listDocuments:s=>Yo(n,s)}}function wy(e,t){const[n,r]=h.useState(!1),[s,i]=h.useState(null),a=h.useMemo(()=>Hl(),[]),c=h.useMemo(()=>{try{return vy(a)}catch(u){return i(u instanceof Error?u:new Error(String(u))),null}},[a]);return h.useEffect(()=>{let u=!1;if(!e){r(!1);return}return a.enablePersistence({key:by,injectedBackend:e}).then(()=>{u||r(!0)}).catch(d=>{u||i(d instanceof Error?d:new Error(String(d)))}),()=>{u=!0}},[a,e]),s?{status:"error",handles:null,error:s}:c?e!=null&&n||t==="ready"?{status:"ready",handles:c}:{status:"pending",handles:null}:{status:"error",handles:null,error:new Error("Studio: failed to construct the sandbox data handles.")}}function xy(e){if(e.kind==="listener")return e.phase==="errored"&&(e.result==="deny"||e.result==="unsupported"||e.result==="allow"||e.error?.code==="PERMISSION_DENIED");const t=Ia(e);return t?t.rules.kind==="evaluated":!1}function jy(e){return"service"in e&&typeof e.service=="string"?e.service:"firestore"}function ky(e){if(!("request"in e))return;const t=e.request;if(t){if("resourceData"in t&&t.resourceData!==void 0)return t.resourceData;if("data"in t)return t.data}}function _y(e,t){const n=[];for(const r of e){if(r.origin==="listener"&&!r.rules){let s;for(const i of t)if(i.kind==="operation"&&i.method==="listen"&&i.path===r.path&&i.rules){s=i;break}s&&(s.rules&&(r.rules=s.rules),s.reasons&&r.reasons.length===0&&(r.reasons=s.reasons))}n.push(r)}return n}function Sy(e){const t=[];for(const r of e)xy(r)&&t.push(Ey(r));return _y(t,e).sort((r,s)=>s.at-r.at)}function Ey(e){let t="listen",n="(service)",r="listener";e.kind==="request"||e.kind==="operation"?(t=e.method,e.path!==void 0&&(n=e.path),r=e.origin):e.kind==="listener"&&(t="listen",e.target.path!==void 0&&(n=e.target.path),r="listener");let s="deny";e.result==="allow"?s="allow":e.result==="unsupported"&&(s="unsupported");const i={id:e.id,at:e.at,result:s,method:t,service:jy(e),path:n,auth:e.auth,reasons:e.reasons??[],origin:r,unsupported:s==="unsupported"};"matchedRule"in e&&e.matchedRule&&(i.matchedRule=e.matchedRule),"evaluatedRule"in e&&e.evaluatedRule&&(i.evaluatedRule=e.evaluatedRule),"rules"in e&&e.rules&&(i.rules=e.rules);const a=ky(e);return a!==void 0&&(i.resourceData=a),"resourceBefore"in e&&e.resourceBefore&&(i.resourceBefore={data:e.resourceBefore.data,exists:e.resourceBefore.exists}),i}const Ri=/^Rule #(\d+) \(([^)]+)\) → (ALLOW|deny|unsupported)/;function Cy(e){const t=e.rules?.engine??e.service;return t==="rtdb"||t==="storage"?t:"firestore"}function Ny(e){if(e.rules?.reason==="Validation rule evaluated to false")return"validate";const t=e.method;return t==="get"||t==="list"||t==="listen"?"read":"write"}function Ry(e){const t=Cy(e),n=e.reasons.filter(s=>Ri.test(s)),r=e.reasons.filter(s=>!Ri.test(s));if(e.unsupported)return{headline:`The simulator hit an unmodelled rules feature evaluating ${e.method} ${e.path}.`,engine:t,ruleLines:n,otherLines:r,implicitDeny:!1};if(e.result==="allow"){if(t==="firestore"&&e.matchedRule){const i=e.matchedRule,a=`Rule #${i.ruleIndex} (${i.operations.join(", ")})`;return{headline:`${a} allowed ${e.method} on ${e.path}.`,engine:t,ruleNode:a,ruleLines:n,otherLines:r,implicitDeny:!1}}return!e.matchedRule&&!e.rules&&!e.evaluatedRule&&n.length===0?{headline:`This ${e.method} on ${e.path} succeeded, but no rules evaluation was recorded for it — rules likely never ran (an admin/bypass operation from a worker that didn't stamp its lens, or a pre-provenance event).`,engine:t,ruleLines:n,otherLines:r,implicitDeny:!1,noEvaluation:!0}:{headline:`Rules allowed ${e.method} on ${e.path}.`,engine:t,...e.rules?.matchedRule?{ruleExpression:e.rules.matchedRule}:{},ruleLines:n,otherLines:r,implicitDeny:!1}}return t==="rtdb"?Iy(e,n,r):t==="storage"?Dy(e,n,r):Ay(e,n,r)}function Ay(e,t,n){const r=!e.matchedRule;let s,i;if(r)s=`No rule allowed ${e.method} on ${e.path}: implicit deny (no matching \`allow\`).`;else{const a=e.matchedRule;i=`Rule #${a.ruleIndex} (${a.operations.join(", ")})`,s=`${i} denied ${e.method} on ${e.path}.`}return{headline:s,engine:"firestore",ruleNode:i,ruleLines:t,otherLines:n,implicitDeny:r}}function Iy(e,t,n){const r=e.rules,s=Ny(e),i=!r?.matchedPath||r?.errorCode==="NO_MATCHING_RULE",a=r?.pathVariableBindings&&Object.keys(r.pathVariableBindings).length>0?r.pathVariableBindings:void 0;let c,l;return i?c=`No \`.${s}\` rule granted ${e.method} on ${e.path}: RTDB implicit deny (no rule matched).`:s==="validate"?(l=`${r.matchedPath} .validate`,c=`The \`.validate\` rule at \`${r.matchedPath}\` rejected the proposed value for ${e.method} ${e.path}.`):(l=`${r.matchedPath} .${s}`,c=`The \`.${s}\` rule at \`${r.matchedPath}\` evaluated false for ${e.method} ${e.path}.`),{headline:c,engine:"rtdb",ruleNode:l,ruleExpression:r?.matchedRule,phase:s,bindings:a,ruleLines:t,otherLines:n,implicitDeny:i}}function Dy(e,t,n){const r=e.reasons.find(c=>/^match\s/.test(c)),i=e.reasons.some(c=>/^no rule matches/.test(c))||!r;return{headline:i?`No \`match\` block allowed ${e.method} on ${e.path}: Storage implicit deny (no rule matched).`:`A \`match\` block condition evaluated false for ${e.method} on ${e.path}.`,engine:"storage",ruleNode:i?void 0:r,ruleLines:t,otherLines:n,implicitDeny:i}}function Py(e){return e.skipped?"skipped":e.error!==void 0?"error":e.value===!0?"true":e.value===!1?"false":"value"}function $y(e){const t=e.evaluatedRule?.expressionTrace;if(!t||t.length===0)return[];const n=t.map(s=>({source:s.source,outcome:Py(s),...s.value!==void 0?{value:s.value}:{},...s.error!==void 0?{error:s.error}:{},...s.letBinding?{letBinding:s.letBinding.name}:{},...s.inlinedFrom?{inlinedFrom:s.inlinedFrom.name}:{},depth:0,children:[]})),r=[];return t.forEach((s,i)=>{s.parent===null||s.parent===void 0||!n[s.parent]?r.push(n[i]):(n[i].depth=n[s.parent].depth+1,n[s.parent].children.push(n[i]))}),r}function Oy(e){const t=[{name:"request.auth",present:e.auth!==null,value:e.auth,...e.auth===null?{absentNote:"request.auth was null — the request was unauthenticated."}:{}},{name:"request.method",present:!0,value:e.method},{name:"request.path",present:!0,value:e.path}],n=e.method==="get"||e.method==="list"||e.method==="listen";return t.push({name:"request.resource.data",present:e.resourceData!==void 0,value:e.resourceData??null,...e.resourceData===void 0?{absentNote:n?"A read carries no proposed write, so request.resource.data is absent.":"No proposed write payload was captured for this denial."}:{}}),t.push({name:"resource",present:e.resourceBefore!==void 0,value:e.resourceBefore?{data:e.resourceBefore.data,exists:e.resourceBefore.exists}:null,...e.resourceBefore===void 0?{absentNote:"The rule evaluated no existing document (e.g. a list/query, or the doc did not exist)."}:{}}),t}function My(e){const t=xn(e.sandbox);return{sandbox:e.sandbox,app:e.app,firestore:e.firestore,adminFirestore:e.adminFirestore,auth:e.auth,storage:e.storage,listRootCollections:()=>t.listRootCollections(),listSubcollections:n=>t.listSubcollections(n),listDocuments:n=>Yo(t,n)}}function Oe(){const e=$e(),t=pe(),n=t.status==="ready"?t.env.persistence:void 0,r=wy(n,t.status),s=t.status==="ready"?t.env.live:void 0,i=Ty(s);return h.useMemo(()=>{switch(e.status){case"ready":return{status:"ready",handles:My(e.handles)};case"pending":return{status:"pending",handles:null};case"error":return{status:"error",handles:null,error:e.error};case"disabled":{if(s&&r.status==="ready"){const a=s.db;return{status:"ready",firestoreApi:s.firestoreApi,authApi:s.authApi,storageApi:s.storageApi,handles:{...r.handles,firestore:a,adminFirestore:a,auth:s.auth,storage:s.storage,listRootCollections:()=>i,listSubcollections:c=>s.listSubcollections(c),listDocuments:c=>s.listDocuments(c)}}}return r}}},[e,r,s,i])}function Ty(e){const[t,n]=h.useState([]);return h.useEffect(()=>{if(!e){n([]);return}let r=!0;const s=()=>{e.listRootCollections().then(a=>{r&&n(a)}).catch(()=>{})};try{e.setLens({mode:"admin"})}catch{}s();const i=e.feed.subscribe(()=>s());return()=>{r=!1,i()}},[e]),t}const pn=500;function er(e){return e.length>pn?e.slice(-pn):e}function Lt(){const e=$e(),t=pe(),n=t.status==="ready"?t.env.live?.feed:void 0,r=e.status==="ready",[s,i]=h.useState([]);h.useEffect(()=>{if(r||!n){i([]);return}return i(er(n.history())),n.subscribe(l=>i(u=>er(Ad(u,l))))},[r,n]);const a=h.useMemo(()=>r?er(e.events):[],[r,e]);return r?a:s}function Uy(e){return $l(e)}function By(e){if(typeof e!="string")return!1;const t=e.toLowerCase();return t==="permission_denied"||t==="permission-denied"||t==="auth/permission-denied"}function Ly(e){const t=Ia(e);if(!t)throw new Error("Studio traffic adapter received a non-operation event");if(e.kind==="request")return{...e,operationContext:t.context,rulesDisposition:t.rules};if(e.kind==="listener"){let s="error";if(e.result!==void 0)s=e.result;else{const c=e.error;c!==void 0&&By(c.code)&&(s="deny")}let i="(service)";e.target.path!==void 0&&(i=e.target.path);let a=[];if(e.reasons!==void 0)a=e.reasons;else{const c=e.error;c!==void 0&&c.reasons!==void 0&&(a=c.reasons)}return{kind:"operation",service:e.service,id:e.id,at:e.at,method:"listen",path:i,auth:e.auth,result:s,reasons:a,origin:"listener",triggeredBy:e.triggeredBy,operationContext:t.context,rulesDisposition:t.rules}}let n="(service)";e.path!==void 0&&(n=e.path);let r=[];return e.reasons!==void 0&&(r=e.reasons),{kind:"operation",service:e.service,id:e.id,at:e.at,durationMs:e.durationMs,method:e.method,path:n,auth:e.auth,result:e.result,reasons:r,request:e.request,resourceBefore:e.resourceBefore,resourceAfter:e.resourceAfter,origin:e.origin,groupId:e.groupId,groupKind:e.groupKind,triggeredBy:e.triggeredBy,operationContext:t.context,rulesDisposition:t.rules}}function Fy(){const e=Lt();return h.useMemo(()=>e.filter(Uy).map(Ly),[e])}function Vy(){const e=Lt();return h.useMemo(()=>Sy(e),[e])}function qy(){const e=Oe();return h.useCallback(async t=>{if(e.status!=="ready")throw new Error("No sandbox available to seed.");const n=e.handles.adminFirestore,r=e.firestoreApi?.doc??Fe,s=e.firestoreApi?.setDoc??tn;let i=0;const a=[];for(const c of t)try{await s(r(n,c.path),c.data),i++}catch(l){a.push(`${c.path}: ${l instanceof Error?l.message:String(l)}`)}return{written:i,errors:a}},[e])}function Wy(){const e=Oe();return h.useCallback(async t=>{if(e.status!=="ready")throw new Error("No sandbox available to seed auth.");const n=e.handles.auth,r=e.authApi?.createUser??fe.createUser;let s=0;const i=[];for(const a of t)try{await r(n,a.request),s++}catch(c){const l=a.request.uid??a.request.email??"<auto>";i.push(`${l}: ${c instanceof Error?c.message:String(c)}`)}return{created:s,errors:i}},[e])}function zy(){const e=Oe(),t=pe(),n=t.status==="ready"?t.env.live:void 0;return h.useCallback(async()=>{if(e.status!=="ready")throw new Error("No sandbox to clear.");const r=[];try{const s=n?await n.resetAll():await e.handles.sandbox.resetAll();r.push(...s?.errors??[])}catch(s){r.push(`reset: ${s instanceof Error?s.message:String(s)}`)}return{errors:r}},[e,n])}function Ky(){const e=zy(),t=qy(),n=Wy(),r=$e();return h.useCallback(async()=>{const s=await e();if(r.status==="ready"){const{applySeed:i,deploySeedRules:a}=await io(async()=>{const{applySeed:c,deploySeedRules:l}=await import("./seed.Co0yUJY5.js");return{applySeed:c,deploySeedRules:l}},__vite__mapDeps([0,1,2,3,4]));a(r.handles.sandbox),await i(r.handles)}else try{const i=await fetch("/__pyric/init.json").then(l=>l.ok?l.json():null),a=i?.seed;a&&await t(Object.entries(a).map(([l,u])=>({path:l,data:u})));const c=i?.authUsers;Array.isArray(c)&&await n(c.map(l=>({request:l})))}catch(i){s.errors.push(`reseed: ${i instanceof Error?i.message:String(i)}`)}return s},[e,t,n,r])}function ps(){const e=pe(),t=e.status==="ready"?e.env.live:void 0,[n,r]=h.useState("");return h.useEffect(()=>{if(!t){r("");return}let s=!1;return t.instanceId().then(i=>{s||r(i)}),()=>{s=!0}},[t]),n}function Hy(){const e=pe(),t=e.status==="ready"?e.env.live:void 0;return h.useCallback(async()=>t?t.exportState():null,[t])}function Gy(){const e=pe(),t=e.status==="ready"?e.env.live:void 0;return h.useCallback(async n=>t?(await t.importState(n),!0):!1,[t])}function Jy(){const e=pe(),t=e.status==="ready"?e.env.live:void 0,[n,r]=h.useState([]),s=h.useCallback(async()=>{r(t?await t.listBranches():[])},[t]);h.useEffect(()=>{s()},[s]);const i=h.useCallback(async l=>{t&&(await t.saveBranch(l),await s())},[t,s]),a=h.useCallback(async l=>{t&&await t.switchBranch(l)},[t]),c=h.useCallback(async l=>{t&&(await t.deleteBranch(l),await s())},[t,s]);return{branches:n,save:i,switchTo:a,remove:c}}function Yy(e="firestore"){const t=$e(),n=t.status==="ready",[r,s]=h.useState({});return h.useEffect(()=>{if(n)return;let i=!0;return fetch("/__pyric/init.json").then(a=>a.ok?a.json():null).then(a=>{if(!i||!a||typeof a!="object")return;const l={};typeof a.rules=="string"&&(l.firestore=a.rules),a.databaseRules!==void 0&&a.databaseRules!==null&&(typeof a.databaseRules=="string"?l.rtdb=a.databaseRules:l.rtdb=JSON.stringify(a.databaseRules,null,2)),typeof a.storageRules=="string"&&(l.storage=a.storageRules),s(l)}).catch(()=>{}),()=>{i=!1}},[n]),h.useMemo(()=>{const i=t.status==="ready",a=e==="database"?"rtdb":e;if(!i){const c=r[a];return c!==void 0?c:""}try{if(a==="rtdb"){const u=Ha(t.handles.sandbox);return u!=null?JSON.stringify(u,null,2):""}return xn(t.handles.sandbox).getRules()}catch{return""}},[t,r,e])}function Qy(e){let t=!0;return n=>{const r=t;t=!1,e(s=>Zy(s,n,r))}}function Xy(e){const t=new Map;for(const n of e)t.set(Dr(n),n);return[...t.values()]}function Zy(e,t,n){return Xy(n?t:[...e??[],...t])}const eb=3e4;function Qo(){const e=Oe(),t=pe(),[n,r]=h.useState(null),[s,i]=h.useState(!1),a=h.useRef(!1),c=h.useRef(e);c.current=e;const l=t.status==="ready"?t.env.live:void 0,u=h.useRef(l);u.current=l;const d=h.useRef(null),p=h.useRef(0),f=h.useRef(null),m=h.useRef(0),y=h.useCallback(v=>{const b=c.current;if(b.status!=="ready")return;const w=++p.current;a.current=!0,i(!0);const x=b.handles,k=x.adminFirestore,j=b.firestoreApi?.collection??Et,_=b.firestoreApi?.query??ln,N=b.firestoreApi?.getDocs??cn,P=b.firestoreApi?.limit??un,I=b.storageApi?.ref??It,D=b.storageApi?.listAll??hs,C=b.authApi?.listUsers??fe.listUsers,S={listRootCollections:()=>x.listRootCollections(),listDocumentPaths:async(R,V)=>(await N(_(j(k,R),P(V)))).docs.slice(0,V).map(A=>`${R}/${A.id}`),listSubcollections:R=>Promise.resolve(x.listSubcollections(R)),listUsers:async R=>(await Promise.resolve(C(x.auth))).slice(0,R).map(G=>({uid:G.uid,email:G.email??null})),listStorageObjectPaths:R=>$m(I(x.storage,""),D,{maxObjects:R,maxListCalls:Pr.storageListCalls}),listRtdbTopLevelKeys:async()=>{const R=u.current;if(!R)return[];const V=Date.now()-m.current<eb;if(f.current!==null&&V&&!v?.rtdbLikely)return f.current;const G=await R.readRtdbState(),A=G===null||typeof G!="object"||Array.isArray(G)?[]:Object.keys(G);return f.current=A,m.current=Date.now(),A}},E=Qy(R=>r(R));Hm(S,Pr,R=>{w===p.current&&E(R)}).catch(()=>{}).finally(()=>{if(w===p.current&&(a.current=!1,i(!1),r(R=>R??[]),d.current)){const R=d.current;d.current=null,y(R)}})},[]),g=h.useCallback(v=>{if(c.current.status==="ready"){if(a.current){d.current={...d.current,...v};return}y(v)}},[y]);return h.useEffect(()=>{e.status==="ready"&&n===null&&!a.current&&y()},[e,n,y]),{entries:n,building:s,ensure:g}}const tb=150;function nb(e){return e.startsWith("/")||/rtdb/i.test(e)}function Xo({autoFocus:e,onNavigated:t,onEscape:n,exposeFocus:r}){const[s,i]=h.useState(""),[a,c]=h.useState(""),[l,u]=h.useState(0),[d,p]=h.useState(!1),f=h.useRef(null),{entries:m,building:y,ensure:g}=Qo();h.useEffect(()=>{if(r)return r(()=>f.current?.focus()),()=>r(null)},[r]),h.useEffect(()=>{e&&f.current?.focus()},[e]),h.useEffect(()=>{const j=setTimeout(()=>c(s),tb);return()=>clearTimeout(j)},[s]);const v=h.useMemo(()=>wi(a,He,m??[]),[a,m]),b=h.useMemo(()=>xi(v),[v]);h.useEffect(()=>{u(j=>b.length===0?0:Math.min(j,b.length-1))},[b.length]);const w=j=>{j&&(i(""),c(""),p(!1),le(j.target),t?.(j.target))},x=()=>{if(s===a){w(b[l]??b[0]);return}const j=xi(wi(s,He,m??[]));w(j[0])};let k=0;return o.jsxs("div",{className:"studio-home__command",children:[o.jsx("div",{className:"studio-home__command-row",children:o.jsx("input",{ref:f,className:"studio-home__command-input",type:"text",value:s,placeholder:"Jump to a surface, collection, doc, user, or object…","aria-label":"Command input",role:"combobox","aria-expanded":d&&b.length>0,"aria-autocomplete":"list",onFocus:()=>{g(),p(!0)},onBlur:()=>p(!1),onChange:j=>{const _=j.target.value;i(_),p(!0),nb(_)&&g({rtdbLikely:!0})},onKeyDown:j=>{if(j.key==="ArrowDown")j.preventDefault(),u(_=>Math.min(_+1,Math.max(b.length-1,0)));else if(j.key==="ArrowUp")j.preventDefault(),u(_=>Math.max(_-1,0));else if(j.key==="Enter")x();else if(j.key==="Escape"){if(n){n();return}i(""),c(""),p(!1)}}})}),d&&!v.length&&y&&m===null?o.jsx("div",{className:"studio-home__command-results",role:"status","aria-live":"polite",children:o.jsx("span",{className:"studio-home__command-group-title",children:"Indexing sandbox…"})}):null,d&&v.length?o.jsx("div",{className:"studio-home__command-results",role:"listbox","aria-label":"Suggestions",onMouseDown:j=>j.preventDefault(),children:v.map(j=>{const _=k;return k+=j.results.length,o.jsxs("div",{className:"studio-home__command-group",children:[o.jsx("span",{className:"studio-home__command-group-title","aria-hidden":"true",children:j.title}),o.jsx("ul",{className:"studio-home__command-group-list",children:j.results.map((N,P)=>{const I=_+P;return o.jsx("li",{children:o.jsxs("button",{type:"button",role:"option","aria-selected":I===l,className:"studio-home__command-result","data-active":I===l?"true":void 0,onMouseEnter:()=>u(I),onClick:()=>w(N),children:[o.jsx("span",{className:"studio-home__command-label",children:N.label}),o.jsx("span",{className:"studio-home__command-sub",children:N.hint})]})},N.id)})})]},j.kind)})}):null]})}function rb({onClose:e}){const t=h.useRef(null);return h.useEffect(()=>(t.current=document.activeElement,()=>{const n=t.current;n instanceof HTMLElement&&n.focus()}),[]),h.useEffect(()=>{const n=r=>{r.key==="Escape"&&e()};return window.addEventListener("keydown",n),()=>window.removeEventListener("keydown",n)},[e]),o.jsx("div",{className:"studio__cmdk-backdrop",onMouseDown:e,children:o.jsx("div",{className:"studio__cmdk",role:"dialog","aria-modal":"true","aria-label":"Command",onMouseDown:n=>n.stopPropagation(),children:o.jsx(Xo,{autoFocus:!0,onEscape:e,onNavigated:e})})})}const sb={status:"loading",payload:null},zt={status:"absent",payload:null};let mn=sb,Ai=!1;const $r=new Set;function Kt(e){mn=e;for(const t of $r)t()}function ib(){if(!Ai){if(Ai=!0,typeof fetch>"u"){mn=zt;return}fetch("/__pyric/init.json").then(async e=>{if(!e.ok||!(e.headers.get("content-type")??"").includes("json"))return Kt(zt);const n=await e.json();Kt({status:"ready",payload:n})}).catch(()=>Kt(zt))}}function ab(e){return $r.add(e),ib(),()=>$r.delete(e)}function Pn(){return h.useSyncExternalStore(ab,()=>mn,()=>mn)}function ob(e){return e.kind==="absent"?"absent":e.sandboxConnected?"available":"idle"}function cb(e,t){if(e!==200||typeof t!="object"||t===null)return{kind:"absent"};const n=t.sandboxConnected;return typeof n!="boolean"?{kind:"absent"}:{kind:"json",sandboxConnected:n}}async function lb(e){try{const t=await e("/__pyric/health");return t.ok?(t.headers.get("content-type")??"").includes("json")?cb(t.status,await t.json()):{kind:"absent"}:{kind:"absent"}}catch{return{kind:"absent"}}}function ub(e=5e3){const[t,n]=h.useState("checking");return h.useEffect(()=>{if(typeof fetch>"u"){n("absent");return}let r=!0,s=null;const i=async()=>{const u=ob(await lb(fetch));return r&&(n(u),u==="absent"&&s&&(clearInterval(s),s=null)),u},a=()=>typeof document>"u"||document.visibilityState!=="hidden",c=()=>{s||(s=setInterval(()=>{a()&&i()},e))},l=()=>{a()&&i()};return i().then(u=>{r&&u!=="absent"&&c()}),typeof document<"u"&&document.addEventListener("visibilitychange",l),()=>{r=!1,s&&clearInterval(s),typeof document<"u"&&document.removeEventListener("visibilitychange",l)}},[e]),t}const db="Only pages in this browser profile, on this origin, connected to this shared sandbox worker. Other profiles, incognito windows, origins, or worker names are not visible.";function fb(e,t){const n=Math.max(0,t-e);return n<5e3?"just now":n<6e4?`${Math.floor(n/1e3)}s ago`:n<36e5?`${Math.floor(n/6e4)}m ago`:`${Math.floor(n/36e5)}h ago`}function hb(e){return e==="studio"?"Studio":"App"}function pb(e,t,n=Date.now()){const r=e.clients.length,s=e.clients.map(a=>({clientId:a.clientId,kindLabel:hb(a.kind),route:a.route||"/",visibilityLabel:a.visibility==="hidden"?"Hidden":"Visible",isThisPage:a.clientId===t,freshnessLabel:fb(a.lastSeen,n)}));s.sort((a,c)=>a.isThisPage!==c.isThisPage?a.isThisPage?-1:1:a.kindLabel!==c.kindLabel?a.kindLabel==="Studio"?-1:1:a.route.localeCompare(c.route));const i=s.filter(a=>!a.isThisPage).length;return{count:r,chipLabel:r===1?"1 page connected":`${r} pages connected`,prominent:r>1,clients:s,boundaryCopy:db,otherCount:i}}function mb(){const e=pe(),t=e.status==="ready"&&e.env.live?e.env.live:null,[n,r]=h.useState(null);return h.useEffect(()=>{if(!t){r(null);return}const s=t.presenceClientId;return t.subscribePresence(i=>{r(pb(i,s))})},[t]),n}const yb={servedEpoch:null,runningEpoch:null,updateAvailable:!1,updating:!1,error:null},bb=()=>()=>{},Ii=()=>yb;function gb(){const e=pe(),t=Pn(),n=ub(),r=mb(),[s,i]=h.useState(!1),a=h.useRef(null),c=e.status==="ready"?e.env.live?.runtime:void 0,l=h.useSyncExternalStore(c?.subscribe??bb,c?.getSnapshot??Ii,c?.getSnapshot??Ii),d=t.status==="ready"&&e.status==="ready"&&!e.env.live,p=e.status==="error",f=l.error?"worker update failed":p?"backend error":d?"worker unreachable":null,m=l.error??(p?e.error.message:"Served, but the shared sandbox worker is not reachable; data views may be stale. Open Settings diagnostics."),y=n==="available";return h.useEffect(()=>{if(!s)return;const g=v=>{v.key==="Escape"&&(i(!1),a.current?.focus())};return document.addEventListener("keydown",g),()=>document.removeEventListener("keydown",g)},[s]),o.jsxs("div",{className:"studio__status","aria-label":"Studio status",children:[l.updateAvailable?o.jsxs("button",{type:"button",className:"studio-chip studio-chip--warn",disabled:l.updating,title:"The Studio backend is running older code. Update every connected page to the served worker version.",onClick:()=>void c?.update().catch(()=>{}),children:[o.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),l.updating?"updating worker…":"update worker"]}):null,f?o.jsxs("a",{className:"studio-chip studio-chip--warn",href:ut({tab:"settings"}),title:m,onClick:g=>{g.preventDefault(),le({tab:"settings"})},children:[o.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),f]}):null,r&&r.count>0?o.jsxs("span",{className:"studio-presence",children:[o.jsxs("button",{ref:a,type:"button",className:r.prominent?"studio-chip studio-chip--live studio-presence__trigger":"studio-chip studio-presence__trigger","aria-haspopup":"dialog","aria-expanded":s,"aria-controls":"studio-presence-panel",title:r.otherCount>0?`${r.chipLabel}. ${r.otherCount} other page${r.otherCount===1?"":"s"} can keep the worker alive.`:`${r.chipLabel}. Expand for details.`,onClick:()=>i(g=>!g),children:[o.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),r.chipLabel]}),s?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"studio-presence__backdrop",onMouseDown:()=>i(!1)}),o.jsxs("div",{id:"studio-presence-panel",className:"studio-presence__panel",role:"dialog","aria-label":"Connected pages",children:[o.jsx("p",{className:"studio-presence__lead",children:r.count===1?"This page is the only connection to the shared sandbox worker.":`${r.count} pages share this sandbox worker. Closing this page alone will not restart it.`}),o.jsx("ul",{className:"studio-presence__list",children:r.clients.map(g=>o.jsxs("li",{className:"studio-presence__item",children:[o.jsxs("div",{className:"studio-presence__item-head",children:[o.jsx("span",{className:"studio-presence__kind",children:g.kindLabel}),g.isThisPage?o.jsx("span",{className:"studio-presence__this",children:"This page"}):null]}),o.jsx("div",{className:"studio-presence__route",title:g.route,children:g.route}),o.jsxs("div",{className:"studio-presence__meta",children:[g.visibilityLabel," · ",g.freshnessLabel]})]},g.clientId))}),o.jsx("p",{className:"studio-presence__boundary",children:r.boundaryCopy})]})]}):null]}):null,y?o.jsxs("span",{className:"studio-chip studio-chip--live",title:"MCP bridge available — a sandbox peer is connected; external agents can reach this sandbox.",children:[o.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),"MCP bridge"]}):null]})}function vb(e,t){const n=e.triggeredBy,r=t.triggeredBy;return!n&&!r?!0:!n||!r?!1:n.method===r.method&&n.path===r.path}function Di(e,t,n){let r=0;for(const s of n)s.result==="deny"&&r++;return{type:"group",kind:e,key:t,events:n,count:n.length,denies:r}}function wb({events:e,groupBatches:t=!0,groupListenerRuns:n=!0}){return h.useMemo(()=>{const r=[];let s=0;for(;s<e.length;){const i=e[s];if(t&&i.groupId){let a=s+1;for(;a<e.length&&e[a].groupId===i.groupId;)a++;const c=e.slice(s,a),l=i.origin==="transaction"?"transaction":"batch";r.push(Di(l,i.groupId,c)),s=a;continue}if(n&&i.origin==="listener"){let a=s+1;for(;a<e.length&&e[a].origin==="listener"&&!e[a].groupId&&vb(e[a],i);)a++;const c=e.slice(s,a);if(c.length>1){const l=i.triggeredBy?`${i.triggeredBy.method}:${i.triggeredBy.path}`:"unknown";r.push(Di("listener-run",`listener-run:${l}:${s}`,c))}else r.push({type:"single",event:i});s=a;continue}r.push({type:"single",event:i}),s++}return{items:r}},[e,t,n])}const xb={buckets:[],total:0,denies:0,maxCount:0,outOfWindow:0};function jb({events:e,window:t,bucketCount:n=30}){return h.useMemo(()=>kb(e,t,n),[e,t.start,t.end,n])}function kb(e,t,n=30){const r=t.end-t.start;if(n<=0||r<=0)return xb;const s=r/n,i=new Array(n).fill(0),a=new Array(n).fill(0);let c=0,l=0,u=0;for(const f of e){const m=f.at;if(m<t.start||m>=t.end){u++;continue}let y=Math.floor((m-t.start)/s);y>=n&&(y=n-1),i[y]++,c++,f.result==="deny"&&(a[y]++,l++)}let d=0;for(const f of i)f>d&&(d=f);return{buckets:i.map((f,m)=>{const y=a[m];return{index:m,start:t.start+m*s,end:t.start+(m+1)*s,count:f,denies:y,allows:f-y,heightRatio:d===0?0:f/d,denyHeightRatio:d===0?0:y/d}}),total:c,denies:l,maxCount:d,outOfWindow:u}}const _b=new Set(["get","list"]),Sb=new Set(["create","update","set"]),Eb=new Set(["delete","remove"]),Cb=[{key:"reads",label:"Read ops"},{key:"writes",label:"Writes"},{key:"deletes",label:"Deletes"}],Nb=[{key:"allows",label:"Allows"},{key:"denies",label:"Denies"},{key:"errors",label:"Errors"}];function $n(e){return e.origin==="admin"}function Rb(e,t=$n){return e.result==="allow"||t(e)?_b.has(e.method)?"reads":Sb.has(e.method)?"writes":Eb.has(e.method)?"deletes":null:null}function Ab(e,t=$n){return t(e)?null:e.result==="allow"?"allows":e.result==="deny"?"denies":e.result==="error"?"errors":null}const Ib=e=>({points:[],series:e.map(t=>({key:t.key,label:t.label,values:[],total:0})),maxValue:0});function Zo(e,t,n,r,s){const i=t.end-t.start;if(n<=0||i<=0)return Ib(r);const a=i/n,c=new Map(r.map(f=>[f.key,new Array(n).fill(0)])),l=new Map(r.map(f=>[f.key,0]));for(const f of e){const m=f.at;if(m<t.start||m>=t.end)continue;const y=s(f);if(y==null)continue;let g=Math.floor((m-t.start)/a);g>=n&&(g=n-1);const v=c.get(y);v[g]++,l.set(y,(l.get(y)??0)+1)}let u=0;for(const f of c.values())for(const m of f)m>u&&(u=m);const d=new Array(n);for(let f=0;f<n;f++)d[f]={index:f,start:t.start+f*a,end:t.start+(f+1)*a};const p=r.map(f=>({key:f.key,label:f.label,values:c.get(f.key),total:l.get(f.key)??0}));return{points:d,series:p,maxValue:u}}function Db(e,t,n=24,r=$n){return Zo(e,t,n,Cb,s=>Rb(s,r))}function Pb(e,t,n=24,r=$n){return Zo(e,t,n,Nb,s=>Ab(s,r))}function $b({events:e,window:t,bucketCount:n=24,isAdmin:r}){return h.useMemo(()=>Db(e,t,n,r),[e,t.start,t.end,n,r])}function Ob({events:e,window:t,bucketCount:n=24,isAdmin:r}){return h.useMemo(()=>Pb(e,t,n,r),[e,t.start,t.end,n,r])}function Or({children:e,kind:t,className:n,ariaLabel:r}){return o.jsx("span",{"data-pyric-badge":"","data-pyric-badge-kind":t,className:n,"aria-label":r,children:r?o.jsx("span",{"aria-hidden":"true",children:e}):e})}function Pt(e){const t=new Date(e),n=r=>String(r).padStart(2,"0");return`${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`}function ec({event:e,selected:t,onSelect:n,renderClassification:r,formatTime:s=Pt,className:i}){return o.jsxs("button",{type:"button",onClick:()=>n?.(e),className:i,"data-pyric-traffic-row":"","data-pyric-result":e.result,"data-pyric-origin":e.origin,"data-pyric-method":e.method,"data-pyric-selected":t?"":void 0,children:[o.jsx("span",{"data-pyric-traffic-time":"",children:s(e.at)}),o.jsx("span",{"data-pyric-traffic-service":e.service??"",children:e.service??""}),o.jsx(Or,{kind:e.method,children:e.method}),o.jsx("span",{"data-pyric-traffic-path":"",children:e.path||"/"}),r?r(e):null]})}var ms=Gl();function Xe(e,t,n){let r=n.initialDeps??[],s,i=!0;function a(){var c,l,u;let d;n.key&&((c=n.debug)!=null&&c.call(n))&&(d=Date.now());const p=e();if(!(p.length!==r.length||p.some((y,g)=>r[g]!==y)))return s;r=p;let m;if(n.key&&((l=n.debug)!=null&&l.call(n))&&(m=Date.now()),s=t(...p),n.key&&((u=n.debug)!=null&&u.call(n))){const y=Math.round((Date.now()-d)*100)/100,g=Math.round((Date.now()-m)*100)/100,v=g/16,b=(w,x)=>{for(w=String(w);w.length<x;)w=" "+w;return w};console.info(`%c⏱ ${b(g,5)} /${b(y,5)} ms`,`
7
+ font-size: .6rem;
8
+ font-weight: bold;
9
+ color: hsl(${Math.max(0,Math.min(120-120*v,120))}deg 100% 31%);`,n?.key)}return n?.onChange&&!(i&&n.skipInitialOnChange)&&n.onChange(s),i=!1,s}return a.updateDeps=c=>{r=c},a}function Pi(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const Mb=(e,t)=>Math.abs(e-t)<1.01,Tb=(e,t,n)=>{let r;return function(...s){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,s),n)}},$i=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},Ub=e=>e,Bb=e=>{const t=Math.max(e.startIndex-e.overscan,0),n=Math.min(e.endIndex+e.overscan,e.count-1),r=[];for(let s=t;s<=n;s++)r.push(s);return r},Lb=(e,t)=>{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;const s=a=>{const{width:c,height:l}=a;t({width:Math.round(c),height:Math.round(l)})};if(s($i(n)),!r.ResizeObserver)return()=>{};const i=new r.ResizeObserver(a=>{const c=()=>{const l=a[0];if(l?.borderBoxSize){const u=l.borderBoxSize[0];if(u){s({width:u.inlineSize,height:u.blockSize});return}}s($i(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(c):c()});return i.observe(n,{box:"border-box"}),()=>{i.unobserve(n)}},Oi={passive:!0},Mi=typeof window>"u"?!0:"onscrollend"in window,Fb=(e,t)=>{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;let s=0;const i=e.options.useScrollendEvent&&Mi?()=>{}:Tb(r,()=>{t(s,!1)},e.options.isScrollingResetDelay),a=d=>()=>{const{horizontal:p,isRtl:f}=e.options;s=p?n.scrollLeft*(f&&-1||1):n.scrollTop,i(),t(s,d)},c=a(!0),l=a(!1);n.addEventListener("scroll",c,Oi);const u=e.options.useScrollendEvent&&Mi;return u&&n.addEventListener("scrollend",l,Oi),()=>{n.removeEventListener("scroll",c),u&&n.removeEventListener("scrollend",l)}},Vb=(e,t,n)=>{if(t?.borderBoxSize){const r=t.borderBoxSize[0];if(r)return Math.round(r[n.options.horizontal?"inlineSize":"blockSize"])}return e[n.options.horizontal?"offsetWidth":"offsetHeight"]},qb=(e,{adjustments:t=0,behavior:n},r)=>{var s,i;const a=e+t;(i=(s=r.scrollElement)==null?void 0:s.scrollTo)==null||i.call(s,{[r.options.horizontal?"left":"top"]:a,behavior:n})};class Wb{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this.itemSizeCache=new Map,this.laneAssignments=new Map,this.pendingMeasuredCacheIndexes=[],this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this.elementsCache=new Map,this.now=()=>{var n,r,s;return((s=(r=(n=this.targetWindow)==null?void 0:n.performance)==null?void 0:r.now)==null?void 0:s.call(r))??Date.now()},this.observer=(()=>{let n=null;const r=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(s=>{s.forEach(i=>{const a=()=>{const c=i.target,l=this.indexFromElement(c);if(!c.isConnected){this.observer.unobserve(c);return}this.shouldMeasureDuringScroll(l)&&this.resizeItem(l,this.options.measureElement(c,i,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(a):a()})}));return{disconnect:()=>{var s;(s=r())==null||s.disconnect(),n=null},observe:s=>{var i;return(i=r())==null?void 0:i.observe(s,{box:"border-box"})},unobserve:s=>{var i;return(i=r())==null?void 0:i.unobserve(s)}}})(),this.range=null,this.setOptions=n=>{Object.entries(n).forEach(([r,s])=>{typeof s>"u"&&delete n[r]}),this.options={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:Ub,rangeExtractor:Bb,onChange:()=>{},measureElement:Vb,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",...n}},this.notify=n=>{var r,s;(s=(r=this.options).onChange)==null||s.call(r,this,n)},this.maybeNotify=Xe(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),n=>{this.notify(n)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(n=>n()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var n;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((n=this.scrollElement)==null?void 0:n.window)??null,this.elementsCache.forEach(s=>{this.observer.observe(s)}),this.unsubs.push(this.options.observeElementRect(this,s=>{this.scrollRect=s,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(s,i)=>{this.scrollAdjustments=0,this.scrollDirection=i?this.getScrollOffset()<s?"forward":"backward":null,this.scrollOffset=s,this.isScrolling=i,this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getFurthestMeasurement=(n,r)=>{const s=new Map,i=new Map;for(let a=r-1;a>=0;a--){const c=n[a];if(s.has(c.lane))continue;const l=i.get(c.lane);if(l==null||c.end>l.end?i.set(c.lane,c):c.end<l.end&&s.set(c.lane,!0),s.size===this.options.lanes)break}return i.size===this.options.lanes?Array.from(i.values()).sort((a,c)=>a.end===c.end?a.index-c.index:a.end-c.end)[0]:void 0},this.getMeasurementOptions=Xe(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode],(n,r,s,i,a,c,l)=>(this.prevLanes!==void 0&&this.prevLanes!==c&&(this.lanesChangedFlag=!0),this.prevLanes=c,this.pendingMeasuredCacheIndexes=[],{count:n,paddingStart:r,scrollMargin:s,getItemKey:i,enabled:a,lanes:c,laneAssignmentMode:l}),{key:!1}),this.getMeasurements=Xe(()=>[this.getMeasurementOptions(),this.itemSizeCache],({count:n,paddingStart:r,scrollMargin:s,getItemKey:i,enabled:a,lanes:c,laneAssignmentMode:l},u)=>{if(!a)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>n)for(const m of this.laneAssignments.keys())m>=n&&this.laneAssignments.delete(m);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMeasuredCacheIndexes=[]),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(m=>{this.itemSizeCache.set(m.key,m.size)}));const d=this.lanesSettling?0:this.pendingMeasuredCacheIndexes.length>0?Math.min(...this.pendingMeasuredCacheIndexes):0;this.pendingMeasuredCacheIndexes=[],this.lanesSettling&&this.measurementsCache.length===n&&(this.lanesSettling=!1);const p=this.measurementsCache.slice(0,d),f=new Array(c).fill(void 0);for(let m=0;m<d;m++){const y=p[m];y&&(f[y.lane]=m)}for(let m=d;m<n;m++){const y=i(m),g=this.laneAssignments.get(m);let v,b;const w=l==="estimate"||u.has(y);if(g!==void 0&&this.options.lanes>1){v=g;const _=f[v],N=_!==void 0?p[_]:void 0;b=N?N.end+this.options.gap:r+s}else{const _=this.options.lanes===1?p[m-1]:this.getFurthestMeasurement(p,m);b=_?_.end+this.options.gap:r+s,v=_?_.lane:m%this.options.lanes,this.options.lanes>1&&w&&this.laneAssignments.set(m,v)}const x=u.get(y),k=typeof x=="number"?x:this.options.estimateSize(m),j=b+k;p[m]={index:m,start:b,size:k,end:j,key:y,lane:v},f[v]=m}return this.measurementsCache=p,p},{key:!1,debug:()=>this.options.debug}),this.calculateRange=Xe(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,s,i)=>this.range=n.length>0&&r>0?zb({measurements:n,outerSize:r,scrollOffset:s,lanes:i}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=Xe(()=>{let n=null,r=null;const s=this.calculateRange();return s&&(n=s.startIndex,r=s.endIndex),this.maybeNotify.updateDeps([this.isScrolling,n,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,n,r]},(n,r,s,i,a)=>i===null||a===null?[]:n({startIndex:i,endIndex:a,overscan:r,count:s}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=n=>{const r=this.options.indexAttribute,s=n.getAttribute(r);return s?parseInt(s,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=n=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const s=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(s!==void 0&&this.range){const i=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),a=Math.max(0,s-i),c=Math.min(this.options.count-1,s+i);return n>=a&&n<=c}return!0},this.measureElement=n=>{if(!n){this.elementsCache.forEach((a,c)=>{a.isConnected||(this.observer.unobserve(a),this.elementsCache.delete(c))});return}const r=this.indexFromElement(n),s=this.options.getItemKey(r),i=this.elementsCache.get(s);i!==n&&(i&&this.observer.unobserve(i),this.observer.observe(n),this.elementsCache.set(s,n)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(n,void 0,this))},this.resizeItem=(n,r)=>{var s;const i=this.measurementsCache[n];if(!i)return;const a=this.itemSizeCache.get(i.key)??i.size,c=r-a;c!==0&&(((s=this.scrollState)==null?void 0:s.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(i,c,this):i.start<this.getScrollOffset()+this.scrollAdjustments)&&this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=c,behavior:void 0}),this.pendingMeasuredCacheIndexes.push(i.index),this.itemSizeCache=new Map(this.itemSizeCache.set(i.key,r)),this.notify(!1))},this.getVirtualItems=Xe(()=>[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const s=[];for(let i=0,a=n.length;i<a;i++){const c=n[i],l=r[c];s.push(l)}return s},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length!==0)return Pi(r[tc(0,r.length-1,s=>Pi(r[s]).start,n)])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const n=this.scrollElement.document.documentElement;return this.options.horizontal?n.scrollWidth-this.scrollElement.innerWidth:n.scrollHeight-this.scrollElement.innerHeight}},this.getOffsetForAlignment=(n,r,s=0)=>{if(!this.scrollElement)return 0;const i=this.getSize(),a=this.getScrollOffset();r==="auto"&&(r=n>=a+i?"end":"start"),r==="center"?n+=(s-i)/2:r==="end"&&(n-=i);const c=this.getMaxScrollOffset();return Math.max(Math.min(c,n),0)},this.getOffsetForIndex=(n,r="auto")=>{n=Math.max(0,Math.min(n,this.options.count-1));const s=this.getSize(),i=this.getScrollOffset(),a=this.measurementsCache[n];if(!a)return;if(r==="auto")if(a.end>=i+s-this.options.scrollPaddingEnd)r="end";else if(a.start<=i+this.options.scrollPaddingStart)r="start";else return[i,r];if(r==="end"&&n===this.options.count-1)return[this.getMaxScrollOffset(),r];const c=r==="end"?a.end+this.options.scrollPaddingEnd:a.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(c,r,a.size),r]},this.scrollToOffset=(n,{align:r="start",behavior:s="auto"}={})=>{const i=this.getOffsetForAlignment(n,r),a=this.now();this.scrollState={index:null,align:r,behavior:s,startedAt:a,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:s}),this.scheduleScrollReconcile()},this.scrollToIndex=(n,{align:r="auto",behavior:s="auto"}={})=>{n=Math.max(0,Math.min(n,this.options.count-1));const i=this.getOffsetForIndex(n,r);if(!i)return;const[a,c]=i,l=this.now();this.scrollState={index:n,align:c,behavior:s,startedAt:l,lastTargetOffset:a,stableFrames:0},this._scrollToOffset(a,{adjustments:void 0,behavior:s}),this.scheduleScrollReconcile()},this.scrollBy=(n,{behavior:r="auto"}={})=>{const s=this.getScrollOffset()+n,i=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:i,lastTargetOffset:s,stableFrames:0},this._scrollToOffset(s,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.getTotalSize=()=>{var n;const r=this.getMeasurements();let s;if(r.length===0)s=this.options.paddingStart;else if(this.options.lanes===1)s=((n=r[r.length-1])==null?void 0:n.end)??0;else{const i=Array(this.options.lanes).fill(null);let a=r.length-1;for(;a>=0&&i.some(c=>c===null);){const c=r[a];i[c.lane]===null&&(i[c.lane]=c.end),a--}s=Math.max(...i.filter(c=>c!==null))}return Math.max(s-this.options.scrollMargin+this.options.paddingEnd,0)},this._scrollToOffset=(n,{adjustments:r,behavior:s})=>{this.options.scrollToFn(n,{behavior:s,adjustments:r},this)},this.measure=()=>{this.itemSizeCache=new Map,this.laneAssignments=new Map,this.notify(!1)},this.setOptions(t)}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const r=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,s=r?r[0]:this.scrollState.lastTargetOffset,i=1,a=s!==this.scrollState.lastTargetOffset;if(!a&&Mb(s,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=i){this.scrollState=null;return}}else this.scrollState.stableFrames=0,a&&(this.scrollState.lastTargetOffset=s,this.scrollState.behavior="auto",this._scrollToOffset(s,{adjustments:void 0,behavior:"auto"}));this.scheduleScrollReconcile()}}const tc=(e,t,n,r)=>{for(;e<=t;){const s=(e+t)/2|0,i=n(s);if(i<r)e=s+1;else if(i>r)t=s-1;else return s}return e>0?e-1:0};function zb({measurements:e,outerSize:t,scrollOffset:n,lanes:r}){const s=e.length-1,i=l=>e[l].start;if(e.length<=r)return{startIndex:0,endIndex:s};let a=tc(0,s,i,n),c=a;if(r===1)for(;c<s&&e[c].end<n+t;)c++;else if(r>1){const l=Array(r).fill(0);for(;c<s&&l.some(d=>d<n+t);){const d=e[c];l[d.lane]=d.end,c++}const u=Array(r).fill(n+t);for(;a>=0&&u.some(d=>d>=n);){const d=e[a];u[d.lane]=d.start,a--}a=Math.max(0,a-a%r),c=Math.min(s,c+(r-1-c%r))}return{startIndex:a,endIndex:c}}const Ti=typeof document<"u"?h.useLayoutEffect:h.useEffect;function Kb({useFlushSync:e=!0,...t}){const n=h.useReducer(()=>({}),{})[1],r={...t,onChange:(i,a)=>{var c;e&&a?ms.flushSync(n):n(),(c=t.onChange)==null||c.call(t,i,a)}},[s]=h.useState(()=>new Wb(r));return s.setOptions(r),Ti(()=>s._didMount(),[]),Ti(()=>s._willUpdate()),s}function Hb(e){return Kb({observeElementRect:Lb,observeElementOffset:Fb,scrollToFn:qb,...e})}function ys({items:e,estimateSize:t,renderItem:n,overscan:r=5,className:s,height:i="100%",getItemKey:a}){const c=h.useRef(null),l=typeof t=="function"?t:()=>t,u=Hb({count:e.length,getScrollElement:()=>c.current,estimateSize:l,overscan:r});return o.jsx("div",{ref:c,className:s,"data-pyric-ui":"virtual-list",style:{height:i,overflowY:"auto",contain:"strict"},children:o.jsx("div",{"data-pyric-virtual-inner":!0,style:{height:`${u.getTotalSize()}px`,width:"100%",position:"relative"},children:u.getVirtualItems().map(d=>{const p=e[d.index],f=a?a(p,d.index):d.key;return o.jsx("div",{"data-pyric-virtual-row":!0,"data-index":d.index,ref:u.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${d.start}px)`},children:n(p,d.index)},f)})})})}const Gb={batch:"batch write",transaction:"transaction","listener-run":"listener re-evals"};function Jb({group:e,defaultExpanded:t=!1,onSelect:n,selectedId:r,renderClassification:s,formatTime:i,className:a}){const[c,l]=h.useState(t);return o.jsxs("div",{className:a,"data-pyric-traffic-group":"","data-pyric-group-kind":e.kind,"data-pyric-expanded":c?"":void 0,children:[o.jsxs("button",{type:"button",onClick:()=>l(u=>!u),"data-pyric-traffic-group-header":"","data-pyric-group-kind":e.kind,"aria-expanded":c,children:[o.jsx("span",{"data-pyric-group-kind-label":"",children:Gb[e.kind]}),o.jsxs("span",{"data-pyric-group-count":"",children:["×",e.count]}),e.denies>0?o.jsxs("span",{"data-pyric-group-denies":"",children:[e.denies," denied"]}):null]}),c?o.jsx("ul",{"data-pyric-traffic-group-members":"",children:e.events.map(u=>o.jsx("li",{"data-pyric-traffic-entry":"","data-pyric-traffic-id":u.id,children:o.jsx(ec,{event:u,selected:u.id===r,onSelect:n,renderClassification:s,formatTime:i})},u.id))}):null]})}function Yb(e){return e<0?0:e>1?1:e}function tr(e,t){const n=t.end-t.start;return n<=0?0:Yb((e-t.start)/n)}function Qb({events:e,buckets:t,window:n,bucketCount:r=30,brush:s,onBrush:i,renderBucketSummary:a,liveAt:c,header:l,axis:u,emptyState:d,className:p}){const f=h.useId(),[m,y]=h.useState(null),[g,v]=h.useState(null),b=jb({events:e??[],window:n,bucketCount:r}),w=t??b,{buckets:x,total:k}=w,j=m??g,_=j===null?null:x.find(S=>S.index===j)??null,N=_!==null&&s?.start===_.start&&s.end===_.end;if(x.length===0)return o.jsx("div",{className:p,"data-pyric-ui":"traffic-timeline","data-pyric-empty":"",children:d});const P=k===0,I=c===void 0?n.end:c,D=I==null?null:tr(I,n),C=typeof u=="function"?u(n):u;return o.jsxs("div",{className:p,"data-pyric-ui":"traffic-timeline","data-pyric-empty":P?"":void 0,children:[l!==void 0&&o.jsx("div",{"data-pyric-timeline-header":"",children:l}),o.jsxs("div",{"data-pyric-timeline-chart":"",children:[o.jsx("div",{"data-pyric-timeline-bars":"",role:i?"group":"img","aria-label":"request volume over time",children:x.map(S=>o.jsx(Xb,{bucket:S,window:n,onBrush:i,onHover:a?y:void 0,onFocus:a?v:void 0,summaryId:a&&!N&&_?.index===S.index?f:void 0,selected:s?.start===S.start&&s.end===S.end},S.index))}),_&&a&&!N?o.jsx("div",{id:f,role:"tooltip","data-pyric-bucket-summary":"",style:{"--pyric-bucket-summary-x":(_.index+.5)/Math.max(x.length,1)},children:a(_)}):null,s&&o.jsx("div",{"data-pyric-brush":"","aria-hidden":"true",style:{"--pyric-brush-left":tr(s.start,n),"--pyric-brush-right":1-tr(s.end,n)}}),D!=null&&o.jsx("div",{"data-pyric-live":"","aria-hidden":"true",style:{"--pyric-live-x":D}})]}),C!=null&&o.jsx("div",{"data-pyric-timeline-axis":"",children:C})]})}function Xb({bucket:e,window:t,onBrush:n,onHover:r,onFocus:s,summaryId:i,selected:a}){const c=n!==void 0,l=`${e.count} ${e.count===1?"request":"requests"}`,u=`${e.denies} denied`;return o.jsxs("button",{type:"button","data-pyric-bucket":"","data-pyric-bucket-index":e.index,"data-pyric-bucket-count":e.count,"data-pyric-bucket-denies":e.denies,"data-pyric-has-denies":e.denies>0?"":void 0,"data-pyric-bucket-selected":a?"":void 0,disabled:!c,"aria-label":`${l}, ${u}`,"aria-describedby":i,"aria-pressed":c?a:void 0,onPointerEnter:r?()=>r(e.index):void 0,onPointerLeave:r?()=>r(null):void 0,onFocus:s?()=>s(e.index):void 0,onBlur:s?()=>s(null):void 0,onClick:c?()=>n?.({start:e.start,end:e.end}):void 0,style:{"--pyric-bucket-h":e.heightRatio,"--pyric-bucket-deny-h":e.denyHeightRatio},children:[o.jsx("span",{"data-pyric-bucket-allow":"","aria-hidden":"true"}),o.jsx("span",{"data-pyric-bucket-deny":"","aria-hidden":"true"})]})}const Zb=e=>String(e);function eg({series:e,visible:t,onToggle:n,formatValue:r=Zb,className:s}){const i=t!==void 0&&n!==void 0;return o.jsx("div",{className:s,"data-pyric-ui":"traffic-metric-cards",role:i?"group":void 0,children:e.map((a,c)=>{const l=t?t.has(a.key):!0,u=o.jsxs(o.Fragment,{children:[o.jsx("span",{"data-pyric-metric-swatch":"","aria-hidden":"true"}),o.jsx("span",{"data-pyric-metric-label":"",children:a.label}),o.jsx("span",{"data-pyric-metric-value":"",children:r(a.total)})]});return i?o.jsxs("label",{"data-pyric-metric-card":"","data-pyric-metric-key":a.key,"data-pyric-series-index":c,"data-pyric-metric-hidden":l?void 0:"",children:[o.jsx("input",{type:"checkbox",checked:l,onChange:()=>n(a.key),"data-pyric-metric-checkbox":""}),u]},a.key):o.jsx("span",{"data-pyric-metric-card":"","data-pyric-metric-key":a.key,"data-pyric-series-index":c,children:u},a.key)})})}const tg=e=>String(e),ng=e=>new Date(e).toLocaleTimeString();function rg({points:e,series:t,visible:n,omitZeroSeries:r=!1,formatValue:s=tg,formatTime:i=ng,emptyState:a,className:c}){const[l,u]=h.useState(null);if(e.length===0)return o.jsx("div",{className:c,"data-pyric-ui":"traffic-line-chart","data-pyric-empty":"",children:a});const d=t.filter(b=>(!n||n.has(b.key))&&(!r||b.total>0));let p=0;for(const b of d)for(const w of b.values)w>p&&(p=w);const f=p===0?1:p,m=e.length,y=b=>m===1?50:b/(m-1)*100,g=b=>100-b/f*100,v=l!=null?e[l]:null;return o.jsx("div",{className:c,"data-pyric-ui":"traffic-line-chart",children:o.jsxs("div",{"data-pyric-chart-svg":"",children:[o.jsx("svg",{viewBox:"0 0 100 100",preserveAspectRatio:"none",role:"img","aria-label":"metrics over time",children:t.map(b=>{const w=t.indexOf(b);if(!((!n||n.has(b.key))&&(!r||b.total>0)))return null;const k=b.values.map((j,_)=>`${_===0?"M":"L"}${y(_)},${g(j)}`).join(" ");return o.jsx("path",{"data-pyric-chart-line":"","data-pyric-series-key":b.key,"data-pyric-series-index":w,d:k,fill:"none",vectorEffect:"non-scaling-stroke"},b.key)})}),o.jsx("div",{"data-pyric-chart-hits":"",children:e.map((b,w)=>o.jsx("button",{type:"button","data-pyric-chart-hit":"","data-pyric-point-index":w,onMouseEnter:()=>u(w),onFocus:()=>u(w),onMouseLeave:()=>u(x=>x===w?null:x),onBlur:()=>u(x=>x===w?null:x),"aria-label":`${i(b.start)} to ${i(b.end)}`},b.index))}),v&&o.jsxs("div",{"data-pyric-chart-tooltip":"",style:{"--pyric-hover-x":y(v.index)},children:[o.jsxs("div",{"data-pyric-tooltip-time":"",children:[i(v.start)," – ",i(v.end)]}),d.map(b=>o.jsxs("div",{"data-pyric-tooltip-row":"","data-pyric-series-key":b.key,"data-pyric-series-index":t.indexOf(b),children:[o.jsx("span",{"data-pyric-tooltip-label":"",children:b.label}),o.jsx("span",{"data-pyric-tooltip-value":"",children:s(b.values[v.index])})]},b.key))]})]})})}const sg={listUsers:fe.listUsers,subscribeUsers:fe.subscribeUsers,createUser:fe.createUser,updateUser:fe.updateUser,deleteUser:fe.deleteUser,clearUsers:fe.clearUsers,getAuthProviderConfig:fe.getAuthProviderConfig,setAuthProviderConfig:fe.setAuthProviderConfig,subscribeAuthProviderConfig:fe.subscribeAuthProviderConfig},nc=h.createContext(sg);function ig(){return h.useContext(nc)}function rc({value:e,children:t}){return h.createElement(nc.Provider,{value:e},t)}function ag(e,t){return[e.uid,e.email,e.displayName,e.phoneNumber].some(n=>n!=null&&n.toLowerCase().includes(t))}function bs(e){const{listUsers:t,subscribeUsers:n,createUser:r,updateUser:s,deleteUser:i,clearUsers:a}=ig(),[c,l]=h.useState([]),[u,d]=h.useState(!0),[p,f]=h.useState(void 0),[m,y]=h.useState("");h.useEffect(()=>{let j=!1;d(!0),f(void 0);const _=D=>{j||(l(D),d(!1))},N=D=>{j||(l([]),f(D instanceof Error?D:new Error(String(D))),d(!1))},P=()=>{try{const D=t(e);D&&typeof D.then=="function"?D.then(_).catch(N):_(D)}catch(D){N(D)}};let I;try{P(),I=n(e,P)}catch(D){N(D)}return()=>{j=!0,I?.()}},[e,t,n]);const g=h.useMemo(()=>{const j=m.trim().toLowerCase();return j?c.filter(_=>ag(_,j)):c},[c,m]),v=h.useCallback(j=>r(e,j),[e,r]),b=h.useCallback((j,_)=>s(e,j,_),[e,s]),w=h.useCallback(j=>i(e,j),[e,i]),x=h.useCallback(()=>a(e),[e,a]),k=h.useCallback(()=>{const j=t(e);j&&typeof j.then=="function"?j.then(_=>l(_)).catch(()=>{}):l(j)},[e,t]);return{users:g,totalCount:c.length,isLoading:u,error:p,filter:m,setFilter:y,createUser:v,updateUser:b,deleteUser:w,clearUsers:x,refresh:k}}const og=["iss","aud","sub","iat","exp","nbf","jti","nonce","azp","acr","amr","cnf","auth_time","firebase","at_hash","c_hash"],cg=1e3;function sc(e){const t=e.trim();if(!t)return{ok:!0,claims:void 0};if(t.length>cg)return{ok:!1,message:"Custom claims length must not exceed 1000 characters"};let n;try{n=JSON.parse(t)}catch{return{ok:!1,message:"Custom claims must be a valid JSON object"}}if(typeof n!="object"||n===null||Array.isArray(n))return{ok:!1,message:"Custom claims must be a valid JSON object"};for(const r of og)if(r in n)return{ok:!1,message:`Custom claims must not have forbidden key: ${r}`};return{ok:!0,claims:n}}const lg={email:"",password:"",displayName:"",phoneNumber:"",photoUrl:"",emailVerified:!1,disabled:!1,claimsText:"",providerIds:[]},ug=new Set(["password","anonymous","phone"]),dg=/^[^@]+@[^@]+\.[^@]+$/,Ui=6;function fg(e){return e?{email:e.email??"",password:"",displayName:e.displayName??"",phoneNumber:e.phoneNumber??"",photoUrl:e.photoUrl??"",emailVerified:e.emailVerified,disabled:e.disabled,claimsText:Object.keys(e.customClaims).length?JSON.stringify(e.customClaims,null,2):"",providerIds:e.providerUserInfo.map(t=>t.providerId).filter(t=>!ug.has(t))}:{...lg}}function hg(e){const t=fg(e);return{fields:t,initial:{...t}}}function pg(e,t){switch(t.type){case"setField":return{...e,fields:{...e.fields,[t.field]:t.value}};case"reset":return{...e,fields:{...e.initial}}}}function mg(e){const t={},n=e.email.trim(),r=e.password;n&&!dg.test(n)&&(t.email="Invalid email"),r&&r.length<Ui&&(t.password=`Password should be at least ${Ui} characters`),r&&!n&&(t.password="Email is required for password authentication");const s=sc(e.claimsText);return s.ok||(t.claims=s.message),t}function yg(e){const{fields:t,initial:n}=e;return Object.keys(t).some(r=>r==="providerIds"?!ic(t.providerIds,n.providerIds):t[r]!==n[r])}function ic(e,t){if(e.length!==t.length)return!1;const n=[...t].sort();return[...e].sort().every((r,s)=>r===n[s])}function ac(e){const t=sc(e.claimsText);return t.ok?t.claims:void 0}function bg(e){const t=e.fields,n={emailVerified:t.emailVerified,disabled:t.disabled};t.email.trim()&&(n.email=t.email.trim()),t.password&&(n.password=t.password),t.displayName.trim()&&(n.displayName=t.displayName.trim()),t.phoneNumber.trim()&&(n.phoneNumber=t.phoneNumber.trim()),t.photoUrl.trim()&&(n.photoUrl=t.photoUrl.trim());const r=ac(t);return r&&(n.customClaims=r),t.providerIds.length&&(n.providerUserInfo=t.providerIds.map(s=>({providerId:s}))),n}function gg(e){const{fields:t,initial:n}=e,r={};return t.email.trim()!==n.email&&t.email.trim()&&(r.email=t.email.trim()),t.password&&t.password!==n.password&&(r.password=t.password),t.displayName.trim()!==n.displayName&&(r.displayName=t.displayName.trim()||null),t.emailVerified!==n.emailVerified&&(r.emailVerified=t.emailVerified),t.disabled!==n.disabled&&(r.disabled=t.disabled),t.claimsText!==n.claimsText&&(r.customClaims=ac(t)??{}),ic(t.providerIds,n.providerIds)||(r.providerUserInfo=t.providerIds.map(s=>({providerId:s}))),r}function oc(e={}){const[t,n]=h.useReducer(pg,e.initial,hg),r=h.useMemo(()=>mg(t.fields),[t.fields]),s=h.useMemo(()=>yg(t),[t]),i=h.useCallback((c,l)=>n({type:"setField",field:c,value:l}),[]),a=h.useCallback(()=>n({type:"reset"}),[]);return{fields:t.fields,errors:r,isDirty:s,isValid:Object.keys(r).length===0,setField:i,reset:a,toCreateRequest:()=>bg(t),toUpdateRequest:()=>gg(t),dispatch:n}}const vg={"google.com":"Google","apple.com":"Apple","gc.apple.com":"Game Center","facebook.com":"Facebook","github.com":"GitHub","microsoft.com":"Microsoft","playgames.google.com":"Play Games","twitter.com":"Twitter","yahoo.com":"Yahoo",password:"Email/Password",phone:"Phone",anonymous:"Anonymous",oidc:"OIDC",saml:"SAML"};function yn(e){return vg[e]??e}function Bi(e){return e.email??e.phoneNumber??(e.isAnonymous?"anonymous":e.uid)}function wg(e){return e.isAnonymous&&e.providerUserInfo.length===0?o.jsx("span",{"data-pyric-provider-id":"anonymous",children:yn("anonymous")}):e.providerUserInfo.map(t=>o.jsx("span",{"data-pyric-provider-id":t.providerId,children:yn(t.providerId)},t.providerId))}function Li(e){if(!e)return"—";const t=new Date(e);return Number.isNaN(t.getTime())?"—":t.toLocaleDateString()}function cc({users:e,isLoading:t,error:n,filter:r,onSelect:s,renderIdentifier:i,renderProviders:a,renderSelection:c,renderSelectionHeader:l,renderActions:u,renderActionsHeader:d,formatCreatedAt:p=Li,formatLastLoginAt:f=Li,emptyState:m,noResultsState:y,className:g,virtualizeThreshold:v=100,rowHeight:b=44,virtualizedHeight:w="60vh"}){if(n)return o.jsx("div",{className:g,"data-pyric-ui":"auth-user-list","data-pyric-error":"",role:"alert",children:n.message});if(t&&e.length===0)return o.jsx("div",{className:g,"data-pyric-ui":"auth-user-list","data-pyric-loading":""});if(e.length===0){const j=!!r?.trim();return o.jsx("div",{className:g,"data-pyric-ui":"auth-user-list","data-pyric-empty":"","data-pyric-no-results":j?"":void 0,children:j?y??"No results":m??"No users for this project yet"})}const x=e.length>v,k=j=>o.jsxs("div",{role:"row","data-pyric-user-entry":!0,"data-pyric-user-uid":j.uid,"data-pyric-user-disabled":j.disabled?"":void 0,children:[c?o.jsx("span",{role:"cell","data-pyric-user-cell":"selection",children:c(j)}):null,o.jsx("span",{role:"cell","data-pyric-user-cell":"identifier",children:s?o.jsx("button",{type:"button","data-pyric-user-select":!0,onClick:()=>s(j),children:i?i(j):Bi(j)}):(i??Bi)(j)}),o.jsx("span",{role:"cell","data-pyric-user-cell":"providers",children:(a??wg)(j)}),o.jsx("span",{role:"cell","data-pyric-user-cell":"created",children:p(j.createdAt)}),o.jsx("span",{role:"cell","data-pyric-user-cell":"signed-in",children:f(j.lastLoginAt)}),o.jsx("span",{role:"cell","data-pyric-user-cell":"uid",children:j.uid}),u?o.jsx("span",{role:"cell","data-pyric-user-cell":"actions",children:u(j)}):null]},j.uid);return o.jsxs("div",{className:g,role:"table","aria-label":"Authentication users","data-pyric-ui":"auth-user-list","data-pyric-virtualized":x?"":void 0,"data-pyric-selection":c?"":void 0,"data-pyric-actions":u?"":void 0,children:[o.jsxs("div",{role:"row","data-pyric-user-header":!0,children:[c?o.jsx("span",{role:"columnheader","data-pyric-user-cell":"selection","aria-label":"Selection",children:l}):null,o.jsx("span",{role:"columnheader","data-pyric-user-cell":"identifier",children:"Identifier"}),o.jsx("span",{role:"columnheader","data-pyric-user-cell":"providers",children:"Provider"}),o.jsx("span",{role:"columnheader","data-pyric-user-cell":"created",children:"Created"}),o.jsx("span",{role:"columnheader","data-pyric-user-cell":"signed-in",children:"Signed In"}),o.jsx("span",{role:"columnheader","data-pyric-user-cell":"uid",children:"User UID"}),u?o.jsx("span",{role:"columnheader","data-pyric-user-cell":"actions","aria-label":"Actions",children:d}):null]}),x?o.jsx(ys,{items:e,estimateSize:b,height:w,getItemKey:j=>j.uid,renderItem:k}):o.jsx("div",{role:"rowgroup","data-pyric-user-rows":!0,children:e.map(k)})]})}function xg({value:e,onChange:t,error:n,hint:r,placeholder:s='{"role":"admin"}',className:i}){return o.jsxs("div",{className:i,"data-pyric-ui":"claims-field",children:[o.jsx("textarea",{"data-pyric-field":"claims","data-pyric-claims-invalid":n!=null?"":void 0,"aria-label":"Custom claims (optional)","aria-invalid":n!=null||void 0,placeholder:s,value:e,onChange:a=>t(a.target.value)}),n!=null&&o.jsx("p",{role:"alert","data-pyric-claims-error":!0,children:n}),r!=null&&o.jsx("p",{"data-pyric-claims-hint":!0,children:r})]})}function jg({selected:e,onChange:t}){return o.jsx("div",{"data-pyric-provider-checklist":!0,children:Vo.map(n=>o.jsxs("label",{"data-pyric-provider-option":n,children:[o.jsx("input",{type:"checkbox",checked:e.includes(n),onChange:r=>t(r.target.checked?[...e,n]:e.filter(s=>s!==n))}),o.jsx("span",{"data-pyric-provider-option-label":!0,children:yn(n)}),o.jsx("span",{"data-pyric-provider-option-id":!0,children:n})]},n))})}function lc({initial:e,onSubmit:t,onCancel:n,submitLabel:r="Save",cancelLabel:s="Cancel",children:i,className:a,renderField:c}){const l=oc({initial:e}),u=e?"edit":"create",d=l.isValid&&(u==="create"||l.isDirty),p=(y,g,v,b,w=null)=>({name:y,label:g,input:b,error:w,kind:v,defaultRender:()=>v==="checkbox"?o.jsxs("label",{"data-pyric-field-label":y,children:[b,o.jsx("span",{"data-pyric-label-text":!0,children:g})]},y):v==="group"?o.jsxs("fieldset",{"data-pyric-field-label":y,children:[o.jsx("legend",{"data-pyric-label-text":!0,children:g}),b]},y):o.jsxs("label",{"data-pyric-field-label":y,children:[o.jsx("span",{"data-pyric-label-text":!0,children:g}),b,w!=null&&o.jsx("p",{role:"alert","data-pyric-field-error":y,children:w})]},y)}),f=[p("email","Email","text",o.jsx("input",{type:"email","data-pyric-field":"email",placeholder:"email@example.com",value:l.fields.email,onChange:y=>l.setField("email",y.target.value)}),l.errors.email??null),p("password","Password","text",o.jsx("input",{type:"password","data-pyric-field":"password",placeholder:u==="edit"?"New password (unchanged if empty)":"Password",value:l.fields.password,onChange:y=>l.setField("password",y.target.value)}),l.errors.password??null),p("display-name","Display name","text",o.jsx("input",{type:"text","data-pyric-field":"display-name",placeholder:"Display name (optional)",value:l.fields.displayName,onChange:y=>l.setField("displayName",y.target.value)})),p("phone-number","Phone number","text",o.jsx("input",{type:"tel","data-pyric-field":"phone-number",placeholder:"+1 555 555 0100",value:l.fields.phoneNumber,onChange:y=>l.setField("phoneNumber",y.target.value)})),p("photo-url","Photo URL","text",o.jsx("input",{type:"url","data-pyric-field":"photo-url",placeholder:"https://example.com/avatar.png",value:l.fields.photoUrl,onChange:y=>l.setField("photoUrl",y.target.value)})),...u==="create"?[p("providers","Sign-in providers","group",o.jsx(jg,{selected:l.fields.providerIds,onChange:y=>l.setField("providerIds",y)}))]:[],p("email-verified","Verified email","checkbox",o.jsx("input",{type:"checkbox","data-pyric-field":"email-verified",checked:l.fields.emailVerified,onChange:y=>l.setField("emailVerified",y.target.checked)})),p("disabled","Disabled (sign-in attempts are rejected)","checkbox",o.jsx("input",{type:"checkbox","data-pyric-field":"disabled",checked:l.fields.disabled,onChange:y=>l.setField("disabled",y.target.checked)}))],m=y=>{y.preventDefault(),d&&t(u==="edit"?{mode:u,uid:e.uid,request:l.toUpdateRequest()}:{mode:u,request:l.toCreateRequest()})};return o.jsxs("form",{className:a,"data-pyric-ui":"auth-user-form","data-pyric-mode":u,"data-pyric-is-dirty":l.isDirty?"":void 0,"data-pyric-is-valid":l.isValid?"":void 0,onSubmit:m,children:[f.map(y=>c?o.jsx(h.Fragment,{children:c(y)},y.name):y.defaultRender()),o.jsx(xg,{value:l.fields.claimsText,onChange:y=>l.setField("claimsText",y),error:l.errors.claims}),i,o.jsxs("footer",{"data-pyric-form-actions":!0,children:[n?o.jsx("button",{type:"button","data-pyric-cancel":!0,onClick:n,children:s}):null,o.jsx("button",{type:"submit","data-pyric-submit":!0,disabled:!d,children:r})]})]})}function kg({open:e,onOpenChange:t,title:n,body:r,destructive:s,confirmLabel:i="Confirm",cancelLabel:a="Cancel",onConfirm:c,className:l}){const u=h.useRef(null),d=h.useRef(null);return h.useEffect(()=>{if(!e)return;const p=f=>{f.key==="Escape"&&(f.stopPropagation(),t(!1))};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[e,t]),h.useEffect(()=>{if(e)return d.current=document.activeElement,u.current?.focus(),()=>{d.current?.focus?.()}},[e]),!e||typeof document>"u"?null:ms.createPortal(o.jsxs("div",{role:"presentation","data-pyric-ui":"confirm-portal",onClick:p=>{p.target===p.currentTarget&&t(!1)},children:[o.jsx("div",{"data-pyric-ui":"confirm-overlay","aria-hidden":"true"}),o.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"pyric-confirm-title","aria-describedby":r?"pyric-confirm-body":void 0,className:l,"data-pyric-ui":"confirm-dialog","data-pyric-destructive":s?"":void 0,children:[o.jsx("div",{id:"pyric-confirm-title","data-pyric-confirm-title":!0,children:n}),r?o.jsx("div",{id:"pyric-confirm-body","data-pyric-confirm-body":!0,children:r}):null,o.jsxs("div",{"data-pyric-confirm-actions":!0,children:[o.jsx("button",{type:"button","data-pyric-confirm-cancel":!0,onClick:()=>t(!1),children:a}),o.jsx("button",{ref:u,type:"button","data-pyric-confirm-confirm":!0,"data-pyric-destructive":s?"":void 0,onClick:c,children:i})]})]})]}),document.body)}const uc=h.createContext(null);function gt(){const e=h.useContext(uc);if(!e)throw new Error("useConfirm: missing <ConfirmProvider> ancestor");return e}function gs({children:e,dialogClassName:t}){const[n,r]=h.useState(null),s=h.useRef(!1),i=h.useCallback(u=>new Promise(d=>{s.current=!1,r({options:u,resolve:d})}),[]),a=h.useCallback(()=>{n&&(s.current||(s.current=!0,n.resolve(!0),r(null)))},[n]),c=h.useCallback(u=>{u||n&&(s.current||(s.current=!0,n.resolve(!1),r(null)))},[n]),l=h.useMemo(()=>i,[i]);return o.jsxs(uc.Provider,{value:l,children:[e,n?o.jsx(kg,{open:!0,onOpenChange:c,title:n.options.title,body:n.options.body,destructive:n.options.destructive,confirmLabel:n.options.confirmLabel,cancelLabel:n.options.cancelLabel,onConfirm:a,className:t}):null]})}function _g(e){return e.email??e.phoneNumber??e.displayName??e.uid}function Sg({user:e,onDelete:t,title:n="Delete user",body:r,confirmLabel:s="Delete",renderTrigger:i,className:a}){const c=gt(),l=async()=>{await c({title:n,body:r??`This will permanently delete ${_g(e)}.`,destructive:!0,confirmLabel:s})&&t(e.uid)};return i?o.jsx(o.Fragment,{children:i({onClick:l})}):o.jsx("button",{type:"button",className:a,"data-pyric-ui":"delete-user","data-pyric-destructive":!0,onClick:l,children:"Delete user"})}function Eg(e){if(e instanceof Error)return e;if(typeof e=="string")return new Error(e);if(e&&typeof e=="object"){const t=e,n=typeof t.message=="string"?t.message:null,r=typeof t.code=="string"?t.code:null;if(n&&r)return new Error(`[${r}] ${n}`);if(n)return new Error(n);if(r)return new Error(r);try{return new Error(JSON.stringify(e))}catch{return new Error(Object.prototype.toString.call(e))}}return new Error(String(e))}const Cg={addDoc:$a,collection:Et,deleteDoc:lr,doc:Fe,getDoc:Ya,getDocs:cn,limit:un,onSnapshot:xd,query:ln,setDoc:tn,startAfter:wd},dc=h.createContext(Cg);function vs(){return h.useContext(dc)}function Ng({value:e,children:t}){return h.createElement(dc.Provider,{value:e},t)}function Rg(e){const{onSnapshot:t}=vs(),[n,r]=h.useState(()=>({data:void 0,error:void 0,isLoading:e!=null}));return h.useEffect(()=>{if(!e){r({data:void 0,error:void 0,isLoading:!1});return}return r(i=>({data:i.data,error:void 0,isLoading:!0})),t(e,i=>r({data:i,error:void 0,isLoading:!1}),i=>r({data:void 0,error:Eg(i),isLoading:!1}))},[t,e]),n}function On(e){return e==null?"null":typeof e=="string"?"string":typeof e=="number"?"number":typeof e=="boolean"?"boolean":typeof e=="object"&&Je(e)!==null?"vector":Array.isArray(e)?"array":e instanceof ft?"timestamp":e instanceof at?"geopoint":e instanceof _n?"bytes":typeof e=="object"&&fc(e)?"timestamp":typeof e=="object"&&hc(e)?"geopoint":typeof e=="object"&&Ag(e)?"reference":typeof e=="object"?"map":"null"}function fc(e){const t=e;return Object.keys(t).length!==2?!1:typeof t.seconds=="number"&&typeof t.nanoseconds=="number"||typeof t._seconds=="number"&&typeof t._nanoseconds=="number"}function hc(e){const t=e;return Object.keys(t).length===2&&typeof t.latitude=="number"&&typeof t.longitude=="number"}function Ag(e){const t=e;if(typeof t.path!="string"||typeof t.id!="string")return!1;const n=typeof t.firestore=="object"&&t.firestore!==null,r=typeof t.env=="object"&&t.env!==null,s=t.type==="document";return n||r||s}function Je(e){if(e===null||typeof e!="object")return null;const t=e;if(t.typeName==="vector"&&Ht(t.value)||t.__type__==="__vector__"&&Ht(t.value))return Gt(t.value);if(Ht(t._values))return Gt(t._values);if(typeof t.toArray=="function")try{const n=t.toArray();if(Ht(n))return Gt(n)}catch{}return null}function Ht(e){return Array.isArray(e)&&e.every(t=>typeof t=="number")}function Gt(e){const t=e.slice();return{values:t,dimension:t.length}}const Fi=4;function pc(e){const t=e.values.slice(0,Fi).join(", "),n=e.values.length>Fi?", …":"";return`vector · ${e.dimension} [${t}${n}]`}function bn(e){const t=Je(e);if(t)return pc(t);if(Array.isArray(e))return e.map(bn);if(e&&typeof e=="object"){const n=Object.getPrototypeOf(e);if(n===Object.prototype||n===null){const r={};for(const[s,i]of Object.entries(e))r[s]=bn(i);return r}}return e}function mc(){return crypto.randomUUID()}function Ig(e){const t=mc(),n={rootId:t,nodes:{[t]:{id:t,parentId:null,key:null,type:"map",value:void 0}},childIds:{[t]:[]}};for(const[r,s]of Object.entries(e))Mr(n,t,r,s);return n}function Mr(e,t,n,r){const s=On(r),i=mc(),a={id:i,parentId:t,key:n,type:s,value:Dg(s)?void 0:r};if(e.nodes[i]=a,e.childIds[i]=[],e.childIds[t].push(i),s==="map"&&r&&typeof r=="object")for(const[c,l]of Object.entries(r))Mr(e,i,c,l);else if(s==="array"&&Array.isArray(r))for(const c of r)Mr(e,i,null,c);return i}function Dg(e){return e==="map"||e==="array"}function yc(e){const t=e.nodes[e.rootId];if(!t||t.type!=="map")throw new Error("treeToData: tree root must be a map node");return Tr(e,e.rootId)}function Tr(e,t){const n=e.nodes[t];if(!n)throw new Error(`serializeNode: missing node ${t}`);switch(n.type){case"map":{const r={};for(const s of e.childIds[t]??[]){const i=e.nodes[s];i&&i.key!=null&&(r[i.key]=Tr(e,s))}return r}case"array":{const r=[];for(const s of e.childIds[t]??[])r.push(Tr(e,s));return r}default:return n.value}}function Ur(e){const t={};for(const[r,s]of Object.entries(e.nodes))t[r]={...s};const n={};for(const[r,s]of Object.entries(e.childIds))n[r]=[...s];return{rootId:e.rootId,nodes:t,childIds:n}}function bc(e,t){const n=[t],r=[t];for(;r.length;){const s=r.shift();for(const i of e.childIds[s]??[])n.push(i),r.push(i)}return n}function gc(e,t){switch(e){case"string":return typeof t=="string"?void 0:"Expected a string";case"number":return typeof t!="number"?"Expected a number":Number.isFinite(t)?void 0:"Number must be finite";case"boolean":return typeof t=="boolean"?void 0:"Expected a boolean";case"null":return t==null?void 0:"Expected null";case"timestamp":return t instanceof ft?void 0:"Expected a Timestamp";case"geopoint":return t instanceof at?t.latitude<-90||t.latitude>90?"Latitude must be between -90 and 90":t.longitude<-180||t.longitude>180?"Longitude must be between -180 and 180":void 0:"Expected a GeoPoint";case"reference":if(t===null||typeof t!="object")return"Expected a DocumentReference";const n=t;return typeof n.path!="string"?"Reference missing `path`":n.path?n.path.split("/").filter(Boolean).length%2!==0?"Reference path must have an even segment count":void 0:"Reference path is empty";case"bytes":return t instanceof _n?void 0:"Expected a Bytes value";case"vector":return Je(t)!==null?void 0:"Expected a vector value";case"map":case"array":return}}function vc(e){const t={};let n=0;for(const[r,s]of Object.entries(e.nodes))t[r]={...s,error:void 0};for(const r of Object.values(t)){if(r.type==="map"||r.type==="array")continue;const s=gc(r.type,r.value);s&&(t[r.id].error=s,n++)}for(const[r,s]of Object.entries(t)){if(s.type!=="map")continue;const i=e.childIds[r]??[],a=new Map;for(const c of i){const l=t[c];if(!l)continue;const u=l.key??"";u||(l.error||n++,t[c].error=t[c].error??"Field name is required");const d=a.get(u)??[];d.push(c),a.set(u,d)}for(const[c,l]of a)if(c&&l.length>1)for(const u of l)t[u].error||n++,t[u].error=t[u].error??"Field name must be unique"}return{tree:{rootId:e.rootId,nodes:t,childIds:e.childIds},errorCount:n}}function ws(e){switch(e){case"string":return"";case"number":return 0;case"boolean":return!1;case"null":return null;case"timestamp":return ft.now();case"geopoint":return new at(0,0);case"reference":return{path:"",id:"",firestore:{}};case"bytes":return _n.fromUint8Array(new Uint8Array);case"vector":return{__type__:"__vector__",value:[]};case"map":case"array":return}}function Br(e){if(e===null||typeof e!="object"||Je(e)!==null)return e;if(fc(e)){const n=e;return new ft(n.seconds??n._seconds??0,n.nanoseconds??n._nanoseconds??0)}if(hc(e)){const n=e;return new at(n.latitude,n.longitude)}if(Array.isArray(e))return e.map(Br);const t=Object.getPrototypeOf(e);if(t===Object.prototype||t===null){const n={};for(const[r,s]of Object.entries(e))n[r]=Br(s);return n}return e}function wc(e){const t=Ig(Br(e)),{tree:n,errorCount:r}=vc(t);return{tree:n,initial:n,errorCount:r}}function Pg(e,t){switch(t.type){case"setValue":return Ze(e,n=>Og(n,t.nodeId,t.value));case"setType":return Ze(e,n=>Mg(n,t.nodeId,t.newType));case"setKey":return Ze(e,n=>Tg(n,t.nodeId,t.key));case"addMapEntry":return Ze(e,n=>Ug(n,t.parentId,t.key,t.childType));case"addArrayEntry":return Ze(e,n=>Bg(n,t.parentId,t.childType));case"remove":return Ze(e,n=>Lg(n,t.nodeId));case"reset":return{tree:e.initial,initial:e.initial,errorCount:$g(e.initial)};case"replaceData":return wc(t.data);case"touch":{const n=e.tree.nodes[t.nodeId];if(!n||n.touched)return e;const r=Ur(e.tree);return r.nodes[t.nodeId]={...r.nodes[t.nodeId],touched:!0},{...e,tree:r}}case"touchAll":{const n=Ur(e.tree);for(const r of Object.keys(n.nodes))n.nodes[r]={...n.nodes[r],touched:!0};return{...e,tree:n}}}}function Ze(e,t){const n=t(Ur(e.tree)),{tree:r,errorCount:s}=vc(n);return{...e,tree:r,errorCount:s}}function $g(e){let t=0;for(const n of Object.values(e.nodes))n.error&&t++;return t}function Og(e,t,n){const r=e.nodes[t];return!r||r.type==="map"||r.type==="array"||(e.nodes[t]={...r,value:n}),e}function Mg(e,t,n){const r=e.nodes[t];if(!r||r.id===e.rootId&&n!=="map"||r.type===n)return e;if(r.type==="map"||r.type==="array"){const i=(e.childIds[t]??[]).slice();for(const a of i)for(const c of bc(e,a))delete e.nodes[c],delete e.childIds[c];e.childIds[t]=[]}const s=n==="map"||n==="array"?void 0:ws(n);return e.nodes[t]={...r,type:n,value:s},e}function Tg(e,t,n){const r=e.nodes[t];if(!r||r.parentId==null)return e;const s=e.nodes[r.parentId];return!s||s.type!=="map"||(e.nodes[t]={...r,key:n}),e}function Ug(e,t,n,r){const s=e.nodes[t];if(!s||s.type!=="map")return e;const i=crypto.randomUUID(),a=r==="map"||r==="array"?void 0:ws(r);return e.nodes[i]={id:i,parentId:t,key:n,type:r,value:a},e.childIds[i]=[],e.childIds[t]=[...e.childIds[t]??[],i],e}function Bg(e,t,n){const r=e.nodes[t];if(!r||r.type!=="array"||n==="array")return e;const s=crypto.randomUUID(),i=n==="map"?void 0:ws(n);return e.nodes[s]={id:s,parentId:t,key:null,type:n,value:i},e.childIds[s]=[],e.childIds[t]=[...e.childIds[t]??[],s],e}function Lg(e,t){const n=e.nodes[t];if(!n||n.id===e.rootId)return e;const r=bc(e,t);for(const s of r)delete e.nodes[s],delete e.childIds[s];return n.parentId!=null&&(e.childIds[n.parentId]=(e.childIds[n.parentId]??[]).filter(s=>s!==t)),e}function xc(e={}){const t=e.initial??{},n=h.useRef(null);n.current==null&&(n.current=wc(t));const[r,s]=h.useReducer(Pg,n.current),i=h.useCallback((w,x)=>s({type:"setValue",nodeId:w,value:x}),[]),a=h.useCallback((w,x)=>s({type:"setType",nodeId:w,newType:x}),[]),c=h.useCallback((w,x)=>s({type:"setKey",nodeId:w,key:x}),[]),l=h.useCallback((w,x,k)=>s({type:"addMapEntry",parentId:w,key:x,childType:k}),[]),u=h.useCallback((w,x)=>s({type:"addArrayEntry",parentId:w,childType:x}),[]),d=h.useCallback(w=>s({type:"remove",nodeId:w}),[]),p=h.useCallback(()=>s({type:"reset"}),[]),f=h.useCallback(w=>s({type:"replaceData",data:w}),[]),m=h.useCallback(w=>s({type:"touch",nodeId:w}),[]),y=h.useCallback(()=>s({type:"touchAll"}),[]),g=h.useCallback(()=>yc(r.tree),[r.tree]),v=r.tree!==r.initial,b=r.errorCount===0;return h.useMemo(()=>({...r,isDirty:v,isValid:b,dispatch:s,setValue:i,setType:a,setKey:c,addMapEntry:l,addArrayEntry:u,remove:d,reset:p,replaceData:f,touch:m,touchAll:y,toData:g}),[r,v,b,i,a,c,l,u,d,p,f,m,y,g])}function Fg({collection:e,query:t,pageSize:n=50,mode:r="paged"}){const[s,i]=h.useState([]),[a,c]=h.useState(!0),[l,u]=h.useState(void 0),[d,p]=h.useState(!1),[f,m]=h.useState(0),[y,g]=h.useState(n),v=h.useRef(0),[b,w]=h.useState(0),{addDoc:x,deleteDoc:k,doc:j,getDoc:_,getDocs:N,limit:P,onSnapshot:I,query:D,setDoc:C,startAfter:S}=vs();h.useEffect(()=>{g(n)},[e,r,n,t]),h.useEffect(()=>{let A=!1;r==="paged"&&i([]),p(!1),c(!0),u(void 0);const O=t??e,M=r==="live"?y:n,$=D(O,P(M)),Y=ne=>{A||(i([...ne.docs]),p(ne.docs.length===M),c(!1))},se=ne=>{A||(u(ne instanceof Error?ne:new Error(String(ne))),c(!1))};if(r==="live"){const ne=++v.current,hl=I($,pl=>{w(ne),Y(pl)},se);return()=>{A=!0,hl()}}return N($).then(ne=>{Y(ne)}).catch(se),()=>{A=!0}},[e,N,P,r,I,n,t,D,y,f]);const E=h.useCallback(()=>{if(!d||a)return;if(r==="live"){c(!0),g($=>$+n);return}const A=s[s.length-1];if(!A)return;c(!0);const M=D(t??e,S(A),P(n));N(M).then($=>{i(Y=>[...Y,...$.docs]),p($.docs.length===n),c(!1)}).catch($=>{u($ instanceof Error?$:new Error(String($))),c(!1)})},[e,s,N,d,a,P,r,n,t,D,S]),R=h.useCallback(async(A,O,M)=>{if(A==null){const Y=await x(e,O);return r==="paged"&&m(se=>se+1),Y}const $=j(e,A);if(M?.onExisting==="fail"){const Y=await _($);if(typeof Y.exists=="function"?Y.exists():!!Y.exists){const ne=new Error(`Document "${A}" already exists.`);throw ne.code="already-exists",ne}}return await C($,O),r==="paged"&&m(Y=>Y+1),$},[x,e,j,_,r,C]),V=h.useCallback(async A=>{await k(A),r==="paged"&&m(O=>O+1)},[k,r]),G=h.useCallback(()=>m(A=>A+1),[]);return{documents:s,isLoading:a,error:l,subscriptionGeneration:b,hasMore:d,loadMore:E,createDocument:R,deleteDocument:V,refresh:G}}function Vg({firestore:e,documentRef:t,listSubcollections:n}){const[r,s]=h.useState([]),[i,a]=h.useState(!1),[c,l]=h.useState(void 0),u=h.useRef(n);u.current=n;const d=t?.path;return h.useEffect(()=>{if(!t){s([]),a(!1),l(void 0);return}let p=!1;return a(!0),l(void 0),u.current(e,t).then(f=>{p||(s(f),a(!1))}).catch(f=>{p||(l(f instanceof Error?f:new Error(String(f))),a(!1))}),()=>{p=!0}},[e,d]),{subcollections:r,isLoading:i,error:c}}function Vi(e){return typeof e=="object"&&e!==null&&"isEqual"in e&&typeof e.isEqual=="function"}function qi(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function gn(e,t){if(Object.is(e,t))return!0;if(Vi(e))return e.isEqual(t);if(Vi(t))return t.isEqual(e);if(e instanceof Uint8Array||t instanceof Uint8Array)return!(e instanceof Uint8Array)||!(t instanceof Uint8Array)||e.length!==t.length?!1:e.every((s,i)=>s===t[i]);if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((s,i)=>gn(s,t[i]));if(!qi(e)||!qi(t))return!1;const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(s=>s in t&&gn(e[s],t[s]))}function qg({value:e,path:t}){return o.jsx("span",{"data-pyric-field-type":"string","data-pyric-field-path":t,children:e})}function Wg({value:e,onChange:t,error:n,path:r}){return o.jsxs("label",{"data-pyric-field-type":"string","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[o.jsx("input",{type:"text",value:e,onChange:s=>t(s.target.value),"aria-invalid":n?"true":void 0}),n?o.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const zg={type:"string",Display:qg,Edit:Wg};function Kg({value:e,path:t}){return o.jsx("span",{"data-pyric-field-type":"number","data-pyric-field-path":t,children:String(e)})}function Hg({value:e,onChange:t,error:n,path:r}){return o.jsxs("label",{"data-pyric-field-type":"number","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[o.jsx("input",{type:"number",value:Number.isFinite(e)?e:"",onChange:s=>{const i=s.target.value,a=i===""?Number.NaN:parseFloat(i);t(a)},"aria-invalid":n?"true":void 0}),n?o.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const Gg={type:"number",Display:Kg,Edit:Hg};function Jg({value:e,path:t}){return o.jsx("span",{"data-pyric-field-type":"boolean","data-pyric-field-path":t,"data-value":e?"true":"false",children:e?"true":"false"})}function Yg({value:e,onChange:t,path:n}){return o.jsx("span",{"data-pyric-field-type":"boolean","data-pyric-field-path":n,"data-value":e?"true":"false",children:o.jsxs("select",{value:e?"true":"false",onChange:r=>t(r.target.value==="true"),"aria-label":"Boolean value","data-pyric-boolean-select":!0,children:[o.jsx("option",{value:"true",children:"true"}),o.jsx("option",{value:"false",children:"false"})]})})}const Qg={type:"boolean",Display:Jg,Edit:Yg};function Xg({path:e}){return o.jsx("span",{"data-pyric-field-type":"null","data-pyric-field-path":e,children:"null"})}function Zg({path:e}){return o.jsx("span",{"data-pyric-field-type":"null","data-pyric-field-path":e,children:"null"})}const ev={type:"null",Display:Xg,Edit:Zg};function jc(e){if(e instanceof ft)return e.toDate();const t=e,n=t?t.seconds??t._seconds:void 0,r=t?t.nanoseconds??t._nanoseconds??0:0;return typeof n=="number"?new Date(n*1e3+Math.floor(r/1e6)):new Date(NaN)}function tv({value:e,path:t}){const n=jc(e),r=Number.isNaN(n.getTime())?"":n.toISOString();return o.jsx("time",{dateTime:r,"data-pyric-field-type":"timestamp","data-pyric-field-path":t,children:r})}function nv({value:e,onChange:t,error:n,path:r}){const s=jc(e),i=new Date(s.getTime()-s.getTimezoneOffset()*6e4),a=Number.isNaN(i.getTime())?"":i.toISOString().slice(0,16);return o.jsxs("label",{"data-pyric-field-type":"timestamp","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[o.jsx("input",{type:"datetime-local",value:a,onChange:c=>{const l=c.target.value;if(!l)return;const u=new Date(l);t(ft.fromDate(u))},"aria-invalid":n?"true":void 0}),n?o.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const rv={type:"timestamp",Display:tv,Edit:nv};function sv({value:e,path:t}){return o.jsxs("span",{"data-pyric-field-type":"geopoint","data-pyric-field-path":t,"data-lat":String(e.latitude),"data-lng":String(e.longitude),children:[e.latitude,", ",e.longitude]})}function iv({value:e,onChange:t,error:n,path:r}){return o.jsxs("span",{"data-pyric-field-type":"geopoint","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[o.jsx("label",{children:o.jsx("input",{type:"number",step:"any",min:-90,max:90,value:e.latitude,onChange:s=>{const i=parseFloat(s.target.value);try{t(new at(i,e.longitude))}catch{}},"aria-label":"Latitude"})}),o.jsx("label",{children:o.jsx("input",{type:"number",step:"any",min:-180,max:180,value:e.longitude,onChange:s=>{const i=parseFloat(s.target.value);try{t(new at(e.latitude,i))}catch{}},"aria-label":"Longitude"})}),n?o.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const av={type:"geopoint",Display:sv,Edit:iv},kc=h.createContext({});kc.Provider;function ov(){return h.useContext(kc)}function cv({value:e,path:t}){const{onReferenceClick:n}=ov();return n?o.jsx("button",{type:"button",onClick:()=>n(e),"data-pyric-field-type":"reference","data-pyric-field-path":t,"data-target-path":e.path,"data-pyric-clickable":"",children:e.path}):o.jsx("span",{"data-pyric-field-type":"reference","data-pyric-field-path":t,"data-target-path":e.path,children:e.path})}function lv({value:e,onChange:t,error:n,path:r}){return o.jsxs("label",{"data-pyric-field-type":"reference","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[o.jsx("input",{type:"text",value:e.path,placeholder:"users/alice",onChange:s=>{const i=s.target.value,a=i.split("/").filter(Boolean),c=a[a.length-1]??"",l=e.firestore??{};t({path:i,id:c,firestore:l,type:"document"})},"aria-invalid":n?"true":void 0}),n?o.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const uv={type:"reference",Display:cv,Edit:lv};function dv({value:e,path:t}){const n=e.toBase64();return o.jsx("code",{"data-pyric-field-type":"bytes","data-pyric-field-path":t,"data-byte-length":String(e.toUint8Array().byteLength),children:n})}function fv({value:e,onChange:t,error:n,path:r}){return o.jsxs("label",{"data-pyric-field-type":"bytes","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[o.jsx("textarea",{value:e.toBase64(),onChange:s=>{try{t(_n.fromBase64String(s.target.value))}catch{}},"aria-invalid":n?"true":void 0}),n?o.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const hv={type:"bytes",Display:dv,Edit:fv};function Lr({value:e,path:t,fieldEditors:n}){const r=On(e),s=n[r];if(!s)return null;const{Display:i}=s;return o.jsx(i,{value:e,path:t,fieldEditors:n})}function _c({label:e,value:t,path:n,fieldEditors:r,kind:s}){const i=On(t),a=i==="map"||i==="array",[c,l]=h.useState(!0),u=s==="key"?{"data-pyric-tree-key":""}:{"data-pyric-tree-index":""},d=s==="key"?{"data-field-name":e}:{"data-field-index":e};return a?o.jsxs("li",{"data-pyric-tree-entry":!0,"data-pyric-tree-nested":!0,...d,children:[o.jsxs("button",{type:"button","data-pyric-tree-toggle":!0,"aria-expanded":c,onClick:()=>l(p=>!p),children:[o.jsx("span",{"data-pyric-tree-chevron":!0,"aria-hidden":"true",children:"›"}),o.jsx("span",{...u,children:e})]}),c?o.jsx(Lr,{value:t,path:n,fieldEditors:r}):null]}):o.jsxs("li",{"data-pyric-tree-entry":!0,...d,children:[o.jsx("span",{"data-pyric-tree-chevron":!0,"data-pyric-tree-chevron-empty":!0,"aria-hidden":"true"}),o.jsx("span",{...u,children:e}),o.jsx(Lr,{value:t,path:n,fieldEditors:r})]})}function pv({value:e,path:t,fieldEditors:n}){const r=Object.entries(e).sort(([s],[i])=>s.localeCompare(i));return o.jsx("ul",{"data-pyric-field-type":"map","data-pyric-tree":!0,"data-pyric-field-path":t,children:r.map(([s,i])=>o.jsx(_c,{label:s,value:i,path:t?`${t}.${s}`:s,fieldEditors:n??{},kind:"key"},s))})}const mv={type:"map",Display:pv};function yv({value:e,path:t,fieldEditors:n}){return o.jsx("ul",{"data-pyric-field-type":"array","data-pyric-tree":!0,"data-pyric-field-path":t,children:e.map((r,s)=>o.jsx(_c,{label:String(s),value:r,path:t?`${t}[${s}]`:`[${s}]`,fieldEditors:n??{},kind:"index"},s))})}const bv={type:"array",Display:yv},Wi=4;function gv(e){return e.length<=Wi?`[${e.join(", ")}]`:`[${e.slice(0,Wi).join(", ")}, …]`}function vv({value:e,path:t}){const n=Je(e);return n?o.jsxs("span",{"data-pyric-field-type":"vector","data-pyric-field-path":t,"data-dimension":String(n.dimension),children:[o.jsx("span",{"data-pyric-vector-dims":!0,children:`vector · ${n.dimension}`}),o.jsx("span",{"data-pyric-vector-preview":!0,children:gv(n.values)})]}):o.jsx("span",{"data-pyric-field-type":"vector","data-pyric-field-path":t})}function wv(e){let t;try{t=JSON.parse(e)}catch{return{ok:!1,error:"Invalid JSON"}}return!Array.isArray(t)||!t.every(n=>typeof n=="number")?{ok:!1,error:"Expected a JSON array of numbers"}:{ok:!0,value:{__type__:"__vector__",value:t}}}function xv({value:e,onChange:t,error:n,path:r}){const s=Je(e),i=s?JSON.stringify(s.values):"[]",[a,c]=h.useState(i),[l,u]=h.useState(void 0),d=m=>{c(m);const y=wv(m);if(!y.ok){u(y.error);return}u(void 0),t(y.value)},p=s?s.dimension:0,f=l??n;return o.jsxs("label",{"data-pyric-field-type":"vector","data-pyric-field-path":r,"data-dimension":String(p),"data-pyric-error":f?"":void 0,children:[o.jsx("span",{"data-pyric-vector-dims":!0,children:`vector · ${p}`}),o.jsx("span",{"data-pyric-vector-note":!0,children:"Replace whole. Paste a JSON number array."}),o.jsx("textarea",{"data-pyric-vector-raw":!0,value:a,onChange:m=>d(m.target.value),"aria-invalid":f?"true":void 0,"aria-label":"Vector value (JSON number array)"}),f?o.jsx("span",{"data-pyric-error-message":!0,children:f}):null]})}const jv={type:"vector",Display:vv,Edit:xv},zi={string:zg,number:Gg,boolean:Qg,null:ev,timestamp:rv,geopoint:av,reference:uv,bytes:hv,map:mv,array:bv,vector:jv};function Sc(e){return e?{...zi,...e}:zi}function Mn(e={}){const t=h.useRef(null),n=e.narrowBreakpoint??480,r=e.mediumBreakpoint??768,[s,i]=h.useState("wide");return h.useEffect(()=>{const a=t.current;if(!a||typeof ResizeObserver>"u")return;const c=new ResizeObserver(l=>{const u=l[0];if(!u)return;const d=u.contentRect.width;d<n?i("narrow"):d<r?i("medium"):i("wide")});return c.observe(a),()=>c.disconnect()},[n,r]),{ref:t,size:s}}const Ec=h.createContext(null);function Me(){const e=h.useContext(Ec);if(!e)throw new Error("DocumentEditor.* components must render inside <DocumentEditor.Root>");return e}function kv({initial:e,fieldEditors:t,onChange:n,children:r,className:s}){const i=xc({initial:e}),a=Sc(t),c=h.useRef(n);c.current=n,h.useEffect(()=>{c.current?.(i)},[i]);const{ref:l,size:u}=Mn();return o.jsx(Ec.Provider,{value:{editor:i,fieldEditors:a},children:o.jsx("div",{ref:l,className:s,"data-pyric-ui":"document-editor","data-pyric-is-valid":i.isValid?"":void 0,"data-pyric-is-dirty":i.isDirty?"":void 0,"data-size":u,children:r})})}function _v(){const{editor:e}=Me(),t=e.tree.childIds[e.tree.rootId]??[];return o.jsxs("div",{"data-pyric-editor-fields":!0,children:[t.map(n=>o.jsx(xs,{nodeId:n,path:Sv(e,n)},n)),o.jsx(Cc,{parentId:e.tree.rootId})]})}function Sv(e,t){const n=[];let r=e.tree.nodes[t];for(;r&&r.parentId!=null;){const s=e.tree.nodes[r.parentId];if(!s)break;if(s.type==="array"){const i=(e.tree.childIds[s.id]??[]).indexOf(r.id);n.unshift(`[${i}]`)}else n.unshift(r.key??"");r=s}return n.reduce((s,i)=>i.startsWith("[")?`${s}${i}`:s?`${s}.${i}`:i,"")}function xs({nodeId:e,path:t}){const{editor:n,fieldEditors:r}=Me(),s=n.tree.nodes[e];if(!s)return null;if(s.type==="map")return o.jsx(Nv,{node:s,path:t});if(s.type==="array")return o.jsx(Rv,{node:s,path:t});const a=r[s.type]?.Edit;if(!a)return null;const c=s.touched?s.error:void 0;return o.jsxs("div",{"data-pyric-field-entry":!0,"data-field-name":s.key??void 0,"data-pyric-error":c?"":void 0,onBlur:()=>n.touch(s.id),children:[o.jsx(js,{node:s,path:t}),o.jsx(a,{value:s.value,path:t,error:c,onChange:l=>n.setValue(s.id,l)})]})}function js({node:e,path:t}){const{editor:n}=Me(),s=(e.parentId!=null?n.tree.nodes[e.parentId]:null)?.type==="map";return e.id===n.tree.rootId?null:o.jsxs("div",{"data-pyric-field-chrome":!0,"data-pyric-field-path":t,children:[s?o.jsx("input",{type:"text",value:e.key??"",onChange:a=>n.setKey(e.id,a.target.value),"aria-label":"Field name","data-pyric-field-key-input":!0,"aria-invalid":e.touched&&e.error?"true":void 0}):null,o.jsx(Cv,{node:e}),o.jsx("button",{type:"button",onClick:()=>n.remove(e.id),"data-pyric-remove":!0,"aria-label":"Remove field",children:"×"})]})}const Ev=["string","number","boolean","null","timestamp","geopoint","reference","bytes","vector","map","array"];function Cv({node:e}){const{editor:t}=Me(),n=e.parentId!=null?t.tree.nodes[e.parentId]:null,r=Ev.filter(s=>!(n?.type==="array"&&s==="array"));return o.jsx("select",{value:e.type,onChange:s=>t.setType(e.id,s.target.value),"aria-label":"Field type","data-pyric-field-type-select":!0,children:r.map(s=>o.jsx("option",{value:s,children:s},s))})}function Nv({node:e,path:t}){const{editor:n}=Me(),r=n.tree.childIds[e.id]??[];return o.jsxs("div",{"data-pyric-field-entry":!0,"data-pyric-field-type":"map","data-field-name":e.key??void 0,children:[e.id!==n.tree.rootId?o.jsx(js,{node:e,path:t}):null,o.jsx("div",{"data-pyric-map-children":!0,children:r.map(s=>{const i=n.tree.nodes[s];if(!i)return null;const a=t?`${t}.${i.key??""}`:i.key??"";return o.jsx(xs,{nodeId:s,path:a},s)})}),o.jsx(Cc,{parentId:e.id})]})}function Rv({node:e,path:t}){const{editor:n}=Me(),r=n.tree.childIds[e.id]??[];return o.jsxs("div",{"data-pyric-field-entry":!0,"data-pyric-field-type":"array","data-field-name":e.key??void 0,children:[o.jsx(js,{node:e,path:t}),o.jsx("ol",{"data-pyric-array-children":!0,children:r.map((s,i)=>{const a=t?`${t}[${i}]`:`[${i}]`;return o.jsx("li",{"data-field-index":String(i),children:o.jsx(xs,{nodeId:s,path:a})},s)})}),o.jsx(Av,{parentId:e.id})]})}function Cc({parentId:e}){const{editor:t}=Me();return o.jsx("button",{type:"button","data-pyric-add-map-entry":!0,onClick:()=>t.addMapEntry(e,"","string"),children:"+ Add field"})}function Av({parentId:e}){const{editor:t}=Me();return o.jsx("button",{type:"button","data-pyric-add-array-entry":!0,onClick:()=>t.addArrayEntry(e,"string"),children:"+ Add item"})}const Ki={Root:kv,Fields:_v};function Iv({collections:e,isLoading:t,error:n,onSelect:r,emptyState:s,className:i}){return n?o.jsx("div",{className:i,"data-pyric-ui":"collection-list","data-pyric-error":"",role:"alert",children:n.message}):t&&e.length===0?o.jsx("div",{className:i,"data-pyric-ui":"collection-list","data-pyric-loading":""}):e.length===0?o.jsx("div",{className:i,"data-pyric-ui":"collection-list","data-pyric-empty":"",children:s}):o.jsx("ul",{className:i,"data-pyric-ui":"collection-list",children:e.map(a=>o.jsx("li",{"data-pyric-collection-entry":!0,"data-pyric-collection-id":a.id,children:o.jsx("button",{type:"button",onClick:()=>r?.(a),"data-pyric-collection-select":!0,children:a.id})},a.path))})}const kt=new Map;function ks({scope:e,entries:t,equals:n=Object.is,durationMs:r=1200,ready:s=!0}){const i=h.useRef(null),a=h.useRef(new Map),c=h.useRef(new Map),[l,u]=h.useState(kt);return h.useEffect(()=>{const d=i.current;if(!s){if(d&&d.scope!==e){i.current=null;for(const f of c.current.values())clearTimeout(f);c.current.clear(),a.current.clear(),u(kt)}return}if(!d||d.scope!==e){i.current={scope:e,entries:t};for(const f of c.current.values())clearTimeout(f);c.current.clear(),a.current.clear(),u(kt);return}const p=new Map;for(const[f,m]of t){const y=d.entries.has(f),g=d.entries.get(f);if(y&&n(g,m))continue;const v=a.current.get(f)===0?1:0;a.current.set(f,v),p.set(f,{kind:y?"modified":"added",cycle:v})}i.current={scope:e,entries:t},u(f=>{const m=new Map(f);let y=p.size>0;for(const g of f.keys())t.has(g)||(m.delete(g),y=!0);for(const[g,v]of p)m.set(g,v);return y?m.size===0?kt:m:f});for(const[f,m]of p){const y=c.current.get(f);y&&clearTimeout(y);const g=setTimeout(()=>{c.current.delete(f),u(v=>{if(v.get(f)?.cycle!==m.cycle)return v;const b=new Map(v);return b.delete(f),b.size===0?kt:b})},r);c.current.set(f,g)}},[r,t,n,s,e]),h.useEffect(()=>()=>{for(const d of c.current.values())clearTimeout(d);c.current.clear()},[]),l}function _t(e){return e.ref}function Dv({documents:e,isLoading:t,error:n,hasMore:r,onSelect:s,onLoadMore:i,renderLabel:a,renderRowAction:c,emptyState:l,className:u,updateScope:d="document-list",virtualizeThreshold:p=100,rowHeight:f=36,virtualizedHeight:m="60vh"}){const y=h.useMemo(()=>new Map(e.map(b=>[_t(b).path,b.data()])),[e]),g=ks({scope:d,entries:y,equals:gn,ready:!t});if(n)return o.jsx("div",{className:u,"data-pyric-ui":"document-list","data-pyric-error":"",role:"alert",children:n.message});if(t&&e.length===0)return o.jsx("div",{className:u,"data-pyric-ui":"document-list","data-pyric-loading":""});if(e.length===0)return o.jsx("div",{className:u,"data-pyric-ui":"document-list","data-pyric-empty":"",children:l});const v=e.length>p;return o.jsxs("div",{className:u,"data-pyric-ui":"document-list","data-pyric-virtualized":v?"":void 0,children:[v?o.jsx(ys,{items:e,estimateSize:f,height:m,getItemKey:b=>_t(b).path,renderItem:b=>{const w=g.get(_t(b).path);return o.jsxs("div",{"data-pyric-document-entry":!0,"data-pyric-document-id":b.id,"data-pyric-update":w?.kind,"data-pyric-update-cycle":w?.cycle,children:[o.jsx("button",{type:"button",onClick:()=>s?.(_t(b)),"data-pyric-document-select":!0,"data-pyric-update":w?.kind,"data-pyric-update-cycle":w?.cycle,children:a?a(b):b.id}),c?o.jsx("span",{"data-pyric-document-action":!0,children:c(b)}):null]})}}):o.jsx("ul",{"data-pyric-document-list-items":!0,children:e.map(b=>{const w=_t(b),x=g.get(w.path);return o.jsxs("li",{"data-pyric-document-entry":!0,"data-pyric-document-id":b.id,"data-pyric-update":x?.kind,"data-pyric-update-cycle":x?.cycle,children:[o.jsx("button",{type:"button",onClick:()=>s?.(w),"data-pyric-document-select":!0,"data-pyric-update":x?.kind,"data-pyric-update-cycle":x?.cycle,children:a?a(b):b.id}),c?o.jsx("span",{"data-pyric-document-action":!0,children:c(b)}):null]},w.path)})}),r&&i?o.jsx("button",{type:"button",onClick:i,"data-pyric-load-more":!0,disabled:t,children:"Load more"}):null]})}const Pv=/^__.*__$/;function Nc(e){if(e.length===0)return"Cannot be empty";if(e.includes("/"))return'Cannot contain "/"';if(e==="."||e==="..")return'Cannot be "." or ".."';if(Pv.test(e))return"Cannot match __.*__ (reserved)";if(Ov(e)>1500)return"Cannot exceed 1500 bytes"}function $v(e){return Nc(e)}function Ov(e){return new TextEncoder().encode(e).length}function Mv(e){return Nc(e)}const Hi="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Tv(){let e="";for(let t=0;t<20;t++)e+=Hi.charAt(Math.floor(Math.random()*Hi.length));return e}const Uv={ref:It,listAll:hs,getMetadata:Jh,getBlob:ly,uploadBytes:_o,uploadBytesResumable:hy,deleteObject:fs},Rc=h.createContext(Uv);function Tn(){return h.useContext(Rc)}function Bv({value:e,children:t}){return h.createElement(Rc.Provider,{value:e},t)}function nr(e){return e.replace(/^\/+|\/+$/g,"")}function Fr(e,t){return e.fullPath<t.fullPath?-1:e.fullPath>t.fullPath?1:0}function rr(e,t){return e.some(n=>n.fullPath===t.fullPath)?e:[...e,t].sort(Fr)}function Lv(e,t){const{listAll:n,ref:r}=Tn(),s=nr(t),[i,a]=h.useState(()=>({status:e==null?"idle":"loading",items:[],prefixes:[],error:void 0})),[c,l]=h.useState(0),u=h.useRef(new Map);h.useEffect(()=>{if(u.current.clear(),e==null){a({status:"idle",items:[],prefixes:[],error:void 0});return}let y=!1;return a({status:"loading",items:[],prefixes:[],error:void 0}),n(r(e,s)).then(g=>{y||a({status:"success",items:[...g.items].sort(Fr),prefixes:[...g.prefixes].sort(Fr),error:void 0})}).catch(g=>{y||a({status:"error",items:[],prefixes:[],error:g instanceof Error?g:new Error(String(g))})}),()=>{y=!0}},[e,s,c]);const d=h.useCallback(()=>l(y=>y+1),[]),p=h.useCallback(y=>{if(e==null)return;const g=y.endsWith("/"),v=nr(y),b=s===""?"":`${s}/`;if(!v.startsWith(b)||v===s)return;const w=v.slice(b.length),x=w.indexOf("/");a(k=>{if(k.status==="idle")return k;if(x===-1)return g?(u.current.set(v,k.prefixes.some(_=>_.fullPath===v)?null:v),{...k,prefixes:rr(k.prefixes,r(e,v))}):(u.current.set(v,k.items.some(_=>_.fullPath===v)?null:v),{...k,items:rr(k.items,r(e,v))});const j=`${b}${w.slice(0,x)}`;return u.current.set(v,k.prefixes.some(_=>_.fullPath===j)?null:j),{...k,prefixes:rr(k.prefixes,r(e,j))}})},[e,s]),f=h.useCallback(y=>{const g=nr(y),v=u.current.get(g);if(u.current.delete(g),v===null)return;const b=v??g;a(w=>({...w,items:w.items.filter(x=>x.fullPath!==b),prefixes:w.prefixes.filter(x=>x.fullPath!==b)}))},[]),m=h.useMemo(()=>[...i.prefixes.map(y=>({kind:"folder",name:y.name,fullPath:y.fullPath,ref:y})),...i.items.map(y=>({kind:"object",name:y.name,fullPath:y.fullPath,ref:y}))],[i.prefixes,i.items]);return{status:i.status,items:i.items,prefixes:i.prefixes,entries:m,error:i.error,refresh:d,insertItem:p,removeItem:f}}function Q(e){return e.split("/").filter(Boolean).join("/")}function Fv(e={}){const{path:t,onPathChange:n,defaultPath:r=""}=e,s=t!==void 0,[i,a]=h.useState(()=>Q(r)),c=s?Q(t):i,l=h.useCallback(m=>{const y=Q(m);s||a(y),n?.(y)},[s,n]),u=h.useMemo(()=>c===""?[]:c.split("/"),[c]),d=h.useCallback(m=>{const y=Q(m);l(y.includes("/")||c===""?y:`${c}/${y}`)},[c,l]),p=h.useCallback(()=>{u.length!==0&&l(u.slice(0,-1).join("/"))},[u,l]),f=h.useCallback(m=>{l(m<0?"":u.slice(0,m+1).join("/"))},[u,l]);return{path:c,segments:u,setPath:l,enter:d,up:p,navigateToIndex:f}}const Gi={status:"idle",blob:void 0,url:void 0,error:void 0};function Vv(e,t){const{getBlob:n,getMetadata:r,ref:s}=Tn(),i=t==null?null:Q(t),a=e!=null&&i!=null&&i!=="",[c,l]=h.useState(()=>({status:a?"loading":"idle",metadata:void 0,error:void 0})),[u,d]=h.useState(Gi),[p,f]=h.useState(0),m=h.useRef(0);h.useEffect(()=>{if(m.current++,d(Gi),!a){l({status:"idle",metadata:void 0,error:void 0});return}let b=!1;return l({status:"loading",metadata:void 0,error:void 0}),r(s(e,i)).then(w=>{b||l({status:"success",metadata:w,error:void 0})}).catch(w=>{b||l({status:"error",metadata:void 0,error:w instanceof Error?w:new Error(String(w))})}),()=>{b=!0}},[e,i,p]);const y=u.url;h.useEffect(()=>{if(y!==void 0)return()=>{URL.revokeObjectURL(y)}},[y]);const g=h.useCallback(()=>f(b=>b+1),[]),v=h.useCallback(()=>{if(e==null||i==null||i==="")return;const b=++m.current;d({status:"loading",blob:void 0,url:void 0,error:void 0}),n(s(e,i)).then(w=>{b===m.current&&d({status:"success",blob:w,url:URL.createObjectURL(w),error:void 0})}).catch(w=>{b===m.current&&d({status:"error",blob:void 0,url:void 0,error:w instanceof Error?w:new Error(String(w))})})},[e,i]);return{status:c.status,metadata:c.metadata,error:c.error,refresh:g,blobStatus:u.status,blob:u.blob,blobUrl:u.url,blobError:u.error,loadBlob:v}}function qv(){const[e,t]=h.useState(()=>new Map),n=h.useCallback(u=>e.has(u),[e]),r=h.useCallback(u=>{t(d=>{if(d.has(u.fullPath))return d;const p=new Map(d);return p.set(u.fullPath,u),p})},[]),s=h.useCallback(u=>{t(d=>{if(!d.has(u))return d;const p=new Map(d);return p.delete(u),p})},[]),i=h.useCallback(u=>{t(d=>{const p=new Map(d);return p.has(u.fullPath)?p.delete(u.fullPath):p.set(u.fullPath,u),p})},[]),a=h.useCallback(u=>{t(new Map(u.map(d=>[d.fullPath,d])))},[]),c=h.useCallback(()=>t(new Map),[]);return{selected:h.useMemo(()=>[...e.values()],[e]),size:e.size,isSelected:n,toggle:i,select:r,deselect:s,selectAll:a,clear:c}}function Wv(e,t){const n=It(e,t);return{storage:e,bucket:n.bucket,fullPath:`${n.fullPath}/`,name:"",parent:n,root:n.root,toString:()=>`${n.toString()}/`}}function zv(e){return{...e,fullPath:`${e.fullPath}/`,name:""}}function Kv(e){return{async*start(t){const n=e??{listAll:hs,deleteObject:fs};let r=0;const s=[t],i=[];for(;s.length>0;){const a=s.pop();i.push(a);const c=await n.listAll(a);s.push(...c.prefixes);for(const l of c.items)await n.deleteObject(l),r++,yield{deletedCount:r,done:!1}}for(const a of i)try{await n.deleteObject(zv(a))}catch{}yield{deletedCount:r,done:!0}}}}function Hv(e,t={}){const n=Tn(),[r,s]=h.useState(0),[i,a]=h.useState(!1),[c,l]=h.useState(void 0),u=h.useRef(0),d=h.useRef(t);return d.current=t,{deleteEntries:h.useCallback(async f=>{const m=++u.current;s(0),l(void 0);const y={deleted:[],failed:[]};if(e==null||f.length===0)return y;a(!0);const g=d.current.impl??Kv(n);let v=0;try{for(const b of f){d.current.list?.removeItem(b.fullPath);try{if(b.kind==="object")await n.deleteObject(n.ref(e,b.fullPath)),v++;else for await(const w of g.start(n.ref(e,b.fullPath))){if(m!==u.current)return y;if(s(v+w.deletedCount),w.done){v+=w.deletedCount;break}}y.deleted.push(b.fullPath),m===u.current&&s(v)}catch(w){const x=w instanceof Error?w:new Error(String(w));y.failed.push({fullPath:b.fullPath,error:x}),d.current.list?.insertItem(b.kind==="folder"?`${b.fullPath}/`:b.fullPath),m===u.current&&y.failed.length===1&&l(x)}}return y}finally{m===u.current&&a(!1)}},[n,e]),progress:r,isRunning:i,error:c}}const Gv=Object.freeze({read:!0,write:!0,delete:!0,upload:!0,reasons:Object.freeze({read:[],write:[]})});function Jv(e,t={}){const{paths:n,rules:r,identity:s,writeResource:i}=t,a=e==null?null:e[Cn],[c,l]=h.useState(()=>({status:e==null?"idle":"loading",rules:null,source:"none",error:void 0}));h.useEffect(()=>{if(a==null){l({status:"idle",rules:null,source:"none",error:void 0});return}if(r!=null){try{const w=typeof r=="string"?Cr(r):r;l({status:"ready",rules:w,source:"option",error:void 0})}catch(w){l({status:"error",rules:null,source:"none",error:w instanceof Error?w:new Error(String(w))})}return}let b=!1;return l({status:"loading",rules:null,source:"none",error:void 0}),a.servicePromise.then(w=>{b||l({status:"ready",rules:w.rules,source:w.rules?"sandbox":"none",error:void 0})}).catch(w=>{b||l({status:"error",rules:null,source:"none",error:w instanceof Error?w:new Error(String(w))})}),()=>{b=!0}},[a,r]);const u=s!==void 0?s:a?.context.auth??null,{rules:d,status:p}=c,f=i?.size,m=i?.contentType,y=h.useCallback(b=>{if(d==null)return Gv;const w=Q(b),x=a?.bucket??"pyric-default",k=w===""?`b/${x}/o`:`b/${x}/o/${w}`,j=D=>jo(d,{request:{auth:u,method:D,path:k,...D==="create"&&f!==void 0?{resource:{size:f,contentType:m}}:{}},resource:null}),_=j("read"),N=j("create"),P=j("delete"),I=N;return{read:_.allowed,write:I.allowed,delete:P.allowed,upload:N.allowed,reasons:{read:_.allowed?[]:_.reasons,write:I.allowed?[]:I.reasons}}},[d,a?.bucket,u,f,m]),g=typeof n=="string"?n:(n??[]).join(`
10
+ `),v=h.useMemo(()=>{const b=typeof n=="string"?[n]:n??[],w={};for(const x of b)w[Q(x)]=y(x);return w},[g,y]);return{status:p,source:c.source,advisory:!1,identity:u,verdicts:v,verdictFor:y,error:c.error}}function Ji(e,t){return e===""?t:t===""?e:`${e}/${t}`}function Yv(e){return e instanceof Blob?e.size:e.byteLength}function Qv(e){if(e instanceof Blob){const t=e;return{path:t.webkitRelativePath||t.name,data:t}}return e}function Xv(e,t={}){const{ref:n,uploadBytes:r}=Tn(),s=Q(t.path??""),[i,a]=h.useState([]),c=h.useRef(t);c.current=t;const l=h.useCallback(f=>{a(m=>m.map(y=>y.id===f.id?f:y))},[]),u=h.useCallback(async f=>{if(e==null)throw new Error("useObjectUpload: storage handle is null");const y=(Array.isArray(f)?f:[f]).map(g=>{const v=Qv(g);return{task:{id:crypto.randomUUID(),fullPath:Ji(s,Q(v.path)),status:"running",bytesTransferred:0,totalBytes:Yv(v.data)},entry:v}});a(g=>[...g,...y.map(v=>v.task)]);for(const{task:g}of y)c.current.list?.insertItem(g.fullPath),c.current.onProgress?.(g);return Promise.all(y.map(async({task:g,entry:v})=>{try{const b=await r(n(e,g.fullPath),v.data,v.metadata),w={...g,status:"success",bytesTransferred:g.totalBytes,metadata:b.metadata};return l(w),c.current.onProgress?.(w),c.current.onComplete?.(w),w}catch(b){const w={...g,status:"error",error:b instanceof Error?b:new Error(String(b))};return c.current.list?.removeItem(g.fullPath),l(w),c.current.onError?.(w),w}}))},[e,s,l,n,r]),d=h.useCallback(async f=>{if(e==null)throw new Error("useObjectUpload: storage handle is null");const m=Ji(s,Q(f));if(m==="")throw new Error("createFolder: folder name is empty");c.current.list?.insertItem(`${m}/`);try{await r(Wv(e,m),new Blob([]),{contentType:"text/plain"})}catch(y){throw c.current.list?.removeItem(m),y}},[e,s,r]),p=h.useCallback(()=>{a(f=>f.filter(m=>m.status==="running"))},[]);return{tasks:i,isUploading:i.some(f=>f.status==="running"),upload:u,createFolder:d,clearCompleted:p}}function Zv({path:e,onNavigate:t,rootLabel:n="/",separator:r="/",className:s}){const i=Q(e),a=i===""?[]:i.split("/");return o.jsx("nav",{className:s,"data-pyric-ui":"path-breadcrumb","aria-label":"Storage path",children:o.jsxs("ol",{"data-pyric-breadcrumb-list":!0,children:[o.jsx("li",{"data-pyric-breadcrumb-item":!0,children:o.jsx("button",{type:"button",onClick:()=>t?.(""),"data-pyric-breadcrumb-link":!0,"data-pyric-breadcrumb-root":!0,"data-pyric-current":a.length===0?"":void 0,"aria-current":a.length===0?"page":void 0,children:n})}),a.map((c,l)=>{const u=l===a.length-1,d=a.slice(0,l+1).join("/");return o.jsxs("li",{"data-pyric-breadcrumb-item":!0,children:[o.jsx("span",{"aria-hidden":!0,"data-pyric-breadcrumb-separator":!0,children:r}),o.jsx("button",{type:"button",onClick:()=>t?.(d),"data-pyric-breadcrumb-link":!0,"data-pyric-current":u?"":void 0,"aria-current":u?"page":void 0,children:c})]},d)})]})})}function ew({entries:e,status:t="success",error:n,onNavigate:r,onSelect:s,selectedPath:i,gate:a,renderEntry:c,renderRowAction:l,emptyState:u,className:d,virtualizeThreshold:p=100,rowHeight:f=36,virtualizedHeight:m="60vh"}){const{ref:y,size:g}=Mn();if(n)return o.jsx("div",{className:d,"data-pyric-ui":"object-browser","data-pyric-error":"",role:"alert",children:n.message});if((t==="loading"||t==="idle")&&e.length===0)return o.jsx("div",{className:d,"data-pyric-ui":"object-browser","data-pyric-loading":t==="loading"?"":void 0,"data-pyric-idle":t==="idle"?"":void 0});if(e.length===0)return o.jsx("div",{className:d,"data-pyric-ui":"object-browser","data-pyric-empty":"",children:u});const v=x=>{if(!a)return{denied:!1};const k=a.verdictFor(x.fullPath);return k.read?{denied:!1}:{denied:!0,reason:k.reasons.read.join("; ")}},b=x=>{const k=x.kind==="object"&&x.fullPath===i;return o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",onClick:()=>x.kind==="folder"?r?.(x.fullPath):s?.(x.ref),"data-pyric-entry-select":!0,"data-pyric-selected":k?"":void 0,"aria-selected":k||void 0,children:c?c(x):x.name}),l?o.jsx("span",{"data-pyric-storage-action":!0,children:l(x)}):null]})},w=e.length>p;return o.jsx("div",{ref:y,className:d,"data-pyric-ui":"object-browser","data-size":g,"data-pyric-virtualized":w?"":void 0,children:w?o.jsx(ys,{items:e,estimateSize:f,height:m,getItemKey:x=>`${x.kind}:${x.fullPath}`,renderItem:x=>{const k=v(x);return o.jsx("div",{"data-pyric-storage-entry":!0,"data-pyric-entry-kind":x.kind,"data-pyric-entry-path":x.fullPath,"data-pyric-denied":k.denied?"":void 0,"data-pyric-denied-reason":k.reason,children:b(x)})}}):o.jsx("ul",{"data-pyric-object-browser-items":!0,children:e.map(x=>{const k=v(x);return o.jsx("li",{"data-pyric-storage-entry":!0,"data-pyric-entry-kind":x.kind,"data-pyric-entry-path":x.fullPath,"data-pyric-denied":k.denied?"":void 0,"data-pyric-denied-reason":k.reason,children:b(x)},`${x.kind}:${x.fullPath}`)})})})}async function Ac(e,t,n){const r=t===""?e.name:`${t}/${e.name}`;if(e.isFile){const s=await new Promise((i,a)=>e.file(i,a));n.push({file:s,relativePath:r});return}if(e.isDirectory){const s=e.createReader();for(;;){const i=await new Promise((a,c)=>s.readEntries(a,c));if(i.length===0)break;for(const a of i)await Ac(a,r,n)}}}async function tw(e){const t=[],n=e.items?Array.from(e.items):[];for(const r of n){if(r.kind!=="file")continue;const s=r.webkitGetAsEntry,i=typeof s=="function"?s.call(r):null;if(i)await Ac(i,"",t);else{const a=r.getAsFile?.();a&&t.push({file:a,relativePath:a.name})}}if(t.length===0)for(const r of Array.from(e.files??[]))t.push({file:r,relativePath:r.name});return t}function nw({onFiles:e,children:t,disabled:n,disabledReason:r,className:s}){const[i,a]=h.useState(!1),c=h.useRef(0),l=h.useCallback(f=>{f.preventDefault(),!n&&(c.current+=1,a(!0))},[n]),u=h.useCallback(f=>{f.preventDefault()},[]),d=h.useCallback(f=>{f.preventDefault(),!n&&(c.current=Math.max(0,c.current-1),c.current===0&&a(!1))},[n]),p=h.useCallback(f=>{if(f.preventDefault(),c.current=0,a(!1),n)return;const m=f.dataTransfer;m&&tw(m).then(y=>{y.length>0&&e(y)})},[n,e]);return o.jsx("div",{className:s,"data-pyric-ui":"upload-dropzone","data-dragging":i?"":void 0,"data-disabled":n?"":void 0,"data-disabled-reason":n?r:void 0,"aria-disabled":n||void 0,onDragEnter:l,onDragOver:u,onDragLeave:d,onDrop:p,children:t})}function rw(e){const t=e.lastIndexOf(".");return t<=0||t===e.length-1?{stem:e,ext:""}:{stem:e.slice(0,t),ext:e.slice(t)}}function sw(e){const t=/^(.*) \((\d+)\)$/.exec(e);if(!t)return{base:e,counter:null};const n=Number(t[2]);return Number.isSafeInteger(n)?{base:t[1],counter:n}:{base:e,counter:null}}function Yi(e,t){if(!t.has(e))return e;const{stem:n,ext:r}=rw(e),{base:s,counter:i}=sw(n);let a=i===null?1:i+1;for(;;){const c=`${s} (${a})${r}`;if(!t.has(c))return c;a+=1}}function iw(e,t){const n=new Set(t),r=new Map;return e.map(s=>{const i=s.indexOf("/");if(i===-1){const l=Yi(s,n);return n.add(l),l}const a=s.slice(0,i);let c=r.get(a);return c===void 0&&(c=Yi(a,n),n.add(c),r.set(a,c)),`${c}${s.slice(i)}`})}function Qi(e){const t=Q(e);if(t==="")return[];const n=t.split("/");return n.map((r,s)=>n.slice(0,s+1).join("/"))}const Ic=[];function aw(e,t){switch(t.type){case"create":{const n=Qi(t.path).filter(r=>!e.includes(r));return n.length===0?e:[...e,...n].sort()}case"materialize":{const n=new Set(Qi(t.path));if(n.size===0)return e;const r=e.filter(s=>!n.has(s));return r.length===e.length?e:r}case"discard":{const n=Q(t.path);if(n==="")return e;const r=e.filter(s=>s!==n&&!s.startsWith(`${n}/`));return r.length===e.length?e:r}case"clear":return e.length===0?e:Ic}}function ow(e,t){const n=Q(t),r=n===""?"":`${n}/`;return e.filter(s=>s.startsWith(r)&&s!==n&&!s.slice(r.length).includes("/")).map(s=>s.slice(r.length))}function Xi(e,t){return e.includes(Q(t))}function cw(e){const t=Q(e);return t===""?"Enter a folder name.":t.split("/").some(r=>r==="."||r==="..")?'Folder names may not be "." or "..".':null}const lw=256*1024;function Vr(e){return(e.contentType??"").split(";")[0].trim().toLowerCase()}const uw={id:"image",match:e=>Vr(e).startsWith("image/"),needsBlob:!0,render:({metadata:e,blobUrl:t})=>t?o.jsx("img",{"data-pyric-preview-image":!0,src:t,alt:e.name}):null};function dw({blob:e,isJson:t}){const[n,r]=h.useState(void 0);return h.useEffect(()=>{let s=!1;return e.text().then(i=>{if(!s){if(t)try{r(JSON.stringify(JSON.parse(i),null,2));return}catch{}r(i)}}),()=>{s=!0}},[e,t]),n===void 0?null:o.jsx("pre",{"data-pyric-preview-text":!0,children:n})}const fw={id:"text",match:e=>{const t=Vr(e);return t.startsWith("text/")||t==="application/json"},needsBlob:!0,maxBytes:lw,render:({metadata:e,blob:t})=>t?o.jsx(dw,{blob:t,isJson:Vr(e)==="application/json"}):null},hw=[uw,fw];function pw(e,t){for(const n of[...t??[],...hw])if(n.match(e))return n}const mw=[{key:"fullPath",label:"Path",value:e=>e.fullPath},{key:"size",label:"Size",value:e=>`${e.size}`},{key:"contentType",label:"Content type",value:e=>e.contentType},{key:"cacheControl",label:"Cache control",value:e=>e.cacheControl},{key:"timeCreated",label:"Created",value:e=>e.timeCreated},{key:"updated",label:"Updated",value:e=>e.updated}];function yw({metadata:e}){return o.jsxs("dl",{"data-pyric-object-metadata":!0,children:[mw.map(({key:t,label:n,value:r})=>{const s=r(e);return s===void 0?null:o.jsxs("div",{"data-pyric-metadata-field":t,children:[o.jsx("dt",{children:n}),o.jsx("dd",{children:s})]},t)}),Object.entries(e.customMetadata??{}).map(([t,n])=>o.jsxs("div",{"data-pyric-metadata-field":"customMetadata","data-pyric-metadata-key":t,children:[o.jsx("dt",{children:t}),o.jsx("dd",{children:n})]},`custom:${t}`))]})}function bw({storage:e,path:t,previews:n,renderMetadata:r,children:s,className:i}){const{ref:a,size:c}=Mn(),l=Vv(e,t),{metadata:u,blobStatus:d,loadBlob:p}=l,f=u?pw(u,n):void 0,m=f?.maxBytes!==void 0&&u!==void 0&&u.size>f.maxBytes,y=f?.needsBlob===!0&&!m;if(h.useEffect(()=>{y&&d==="idle"&&p()},[y,d,p]),l.status==="idle")return o.jsx("div",{className:i,"data-pyric-ui":"object-inspector","data-pyric-idle":""});if(l.status==="loading")return o.jsx("div",{className:i,"data-pyric-ui":"object-inspector","data-pyric-loading":""});if(l.status==="error"||u===void 0)return o.jsx("div",{className:i,"data-pyric-ui":"object-inspector","data-pyric-error":"",role:"alert",children:l.error?.message});let g,v={};return f===void 0?v={"data-pyric-preview-none":""}:m?v={"data-pyric-preview-too-large":""}:y&&d==="loading"?v={"data-pyric-preview-loading":""}:y&&d==="error"?(v={"data-pyric-preview-error":""},g=l.blobError?.message):(!y||d==="success")&&(g=f.render({metadata:u,blob:l.blob,blobUrl:l.blobUrl})),o.jsxs("div",{ref:a,className:i,"data-pyric-ui":"object-inspector","data-size":c,children:[o.jsx("div",{"data-pyric-object-name":!0,children:u.name}),r?r(u):o.jsx(yw,{metadata:u}),o.jsx("div",{"data-pyric-object-preview":!0,"data-pyric-preview":f?.id,...v,children:g}),s]})}const Dc=h.createContext(null);function gw(){const e=h.useContext(Dc);if(!e)throw new Error("useToast: missing <ToastProvider> ancestor");return e}function vw({children:e,defaultDuration:t=5e3,className:n,regionLabel:r="Notifications"}){const[s,i]=h.useState([]),a=h.useCallback(u=>{i(d=>d.filter(p=>p.id!==u))},[]),c=h.useCallback(u=>{const d=crypto.randomUUID(),p=u.duration??t;return i(f=>[...f,{id:d,...u}]),p>0&&window.setTimeout(()=>{i(f=>f.filter(m=>m.id!==d))},p),d},[t]),l=h.useMemo(()=>({toast:c,dismiss:a,toasts:s}),[c,a,s]);return o.jsxs(Dc.Provider,{value:l,children:[e,o.jsx(ww,{toasts:s,dismiss:a,className:n,regionLabel:r})]})}function ww({toasts:e,dismiss:t,className:n,regionLabel:r}){const[s,i]=h.useState(!1);return h.useEffect(()=>i(!0),[]),!s||typeof document>"u"?null:ms.createPortal(o.jsx("ol",{"aria-label":r,"aria-live":"polite","data-pyric-ui":"toast-region",className:n,children:e.map(a=>o.jsxs("li",{"data-pyric-toast":!0,"data-pyric-toast-kind":a.kind??"info",role:a.kind==="error"?"alert":"status",children:[o.jsx("div",{"data-pyric-toast-title":!0,children:a.title}),a.body?o.jsx("div",{"data-pyric-toast-body":!0,children:a.body}):null,o.jsx("button",{type:"button","data-pyric-toast-dismiss":!0,"aria-label":"Dismiss",onClick:()=>t(a.id),children:"×"})]},a.id))}),document.body)}function xw({storage:e,entries:t,impl:n,list:r,gate:s,title:i,body:a,confirmLabel:c="Delete",onDeleted:l,onFailed:u,renderTrigger:d,className:p}){const f=gt(),{toast:m}=gw(),{deleteEntries:y,isRunning:g,progress:v}=Hv(e,{impl:n,list:r}),b=s?t.map(j=>({entry:j,verdict:s.verdictFor(j.fullPath)})).filter(j=>!j.verdict.delete):[],w=b.length===0?void 0:`Delete denied for ${b[0].entry.fullPath}${b.length>1?` (+${b.length-1} more)`:""}: ${b[0].verdict.reasons.write.join("; ")}`,x=g||t.length===0||e==null||b.length>0,k=async()=>{if(x||!await f({title:i??(t.length===1?`Delete ${t[0].fullPath}?`:`Delete ${t.length} items?`),body:a??o.jsx("ul",{"data-pyric-delete-selection-paths":!0,children:t.map(N=>o.jsxs("li",{"data-pyric-entry-kind":N.kind,children:[N.fullPath,N.kind==="folder"?"/":""]},N.fullPath))}),destructive:!0,confirmLabel:c}))return;const _=await y(t);_.failed.length===0?(m({title:`Deleted ${_.deleted.length} ${_.deleted.length===1?"item":"items"}`,kind:"success"}),l?.(_)):(m({title:`Delete failed for ${_.failed.length} of ${t.length}`,kind:"error",body:o.jsx("ul",{"data-pyric-delete-selection-failures":!0,children:_.failed.map(N=>o.jsxs("li",{children:[N.fullPath,":"," ",N.error.code??N.error.message]},N.fullPath))})}),u?.(_))};return d?o.jsx(o.Fragment,{children:d({onClick:k,isRunning:g,progress:v,disabled:x,deniedReason:w})}):o.jsx("button",{type:"button",onClick:k,className:p,disabled:x,title:w,"data-pyric-ui":"delete-selection","data-pyric-destructive":"","data-pyric-running":g?"":void 0,"data-pyric-denied":w?"":void 0,"data-pyric-denied-reason":w,children:g?`Deleting… (${v})`:c})}function vn(e){const t=e.split("/").filter(Boolean),n=[];let r="";return t.forEach((s,i)=>{r=r?`${r}/${s}`:s,n.push({kind:i%2===0?"collection":"document",id:s,path:r})}),n}function Pc(e){const t=e.indexOf("?");return ls(t===-1?e:e.slice(0,t),t===-1?"":e.slice(t))}function jw(e){const{tab:t,rest:n,query:r}=Pc(e),s=n.join("/");return t==="firestore"?{view:"firestore",path:vn(s)}:t==="auth"?{view:"auth",uid:n[0]??null}:t==="storage"?s?{view:"storage",kind:r.kind==="prefix"?"prefix":"object",path:s}:{view:"storage",kind:"root"}:null}function kw(e){switch(e.view){case"firestore":{const t=e.path[e.path.length-1];return{tab:"firestore",rest:t?t.path.split("/").filter(Boolean):[]}}case"auth":return{tab:"auth",rest:e.uid?[e.uid]:[]};case"storage":return e.kind==="root"?{tab:"storage"}:{tab:"storage",rest:e.path.split("/").filter(Boolean),...e.kind==="prefix"?{query:{kind:"prefix"}}:{}}}}function $c(e){const{tab:t,query:n}=Pc(e),r=jw(e),s=t==="traffic"?n.inspect??null:null;return{target:r,selectedInspectId:s}}let Zi=null,qr=$c("");function _w(){const e=To();return e!==Zi&&(Zi=e,qr=$c(e)),qr}function Sw(){return qr}function Jt(e){le(kw(e))}function Ew(e){le({tab:"traffic",query:{inspect:e}})}function Un(){const e=h.useSyncExternalStore(Bt,_w,Sw),t=h.useCallback(s=>Jt(s),[]),n=h.useCallback(s=>{switch(s.kind){case"user":Jt({view:"auth",uid:s.uid});break;case"storage":Jt({view:"storage",kind:"object",path:s.objectPath});break;case"document":Jt({view:"firestore",path:vn(s.path)});break}},[]),r=h.useCallback(s=>Ew(s),[]);return h.useMemo(()=>({target:e.target,navigate:t,navigateRef:n,selectedInspectId:e.selectedInspectId,navigateInspect:r}),[e,t,n,r])}const Cw={narrowBreakpoint:640,mediumBreakpoint:920};function Nw(e){switch(e){case"narrow":return 1;case"medium":return 2;case"wide":return 3}}function Rw(e,t){const n=Nw(t),r=Math.min(Math.max(e,1),n),s=Math.max(e-r,0),i=t==="narrow"?0:n-r;return{startIndex:s,visibleCount:r,emptySlots:i}}function sr({label:e,error:t,hint:n,children:r}){return o.jsxs("div",{className:"fs-modal__group",children:[o.jsx("span",{className:"fs-modal__label",children:e}),r,t?o.jsx("span",{className:"fs-modal__err",role:"alert",children:t}):n?o.jsx("span",{className:"fs-modal__hint",children:n}):null]})}function Oc({mode:e,parentPath:t,onCreate:n,onClose:r}){const[s,i]=h.useState(""),[a,c]=h.useState(()=>Tv()),[l,u]=h.useState(null),[d,p]=h.useState(null),[f,m]=h.useState(!1),y=h.useRef(null),g=e==="collection"&&s?$v(s):void 0,v=a?Mv(a):void 0,w=!(e==="collection"&&(!s||g))&&!!a&&!v&&!f;h.useEffect(()=>{const j=_=>{_.key==="Escape"&&!f&&r()};return document.addEventListener("keydown",j),()=>document.removeEventListener("keydown",j)},[f,r]);const x=async()=>{if(!(!w||!l)){if(!l.isValid){l.touchAll();return}m(!0),p(null);try{await n({collectionId:e==="collection"?s:null,docId:a,data:yc(l.tree)}),r()}catch(j){p(j instanceof Error?j:new Error(String(j))),m(!1)}}},k=e==="collection"?"Start a collection":"Add a document";return o.jsx("div",{className:"fs-modal-backdrop",onMouseDown:j=>{j.target===j.currentTarget&&!f&&r()},children:o.jsxs("div",{ref:y,className:"fs-modal",role:"dialog","aria-modal":"true","aria-label":k,"data-pyric-ui":"fs-create-modal","data-fs-create-mode":e,children:[o.jsx("h2",{className:"fs-modal__title",children:k}),o.jsx(sr,{label:"Parent path",children:o.jsx("span",{className:"fs-modal__path",children:t})}),e==="collection"?o.jsx(sr,{label:"Collection ID",error:g,children:o.jsx("input",{autoFocus:!0,type:"text",value:s,placeholder:"e.g. users",onChange:j=>i(j.target.value),"data-pyric-field":"collection-id","aria-invalid":g?"true":void 0})}):null,o.jsx(sr,{label:"Document ID",error:a?v:"Cannot be empty",hint:"Auto-generated — edit to set your own.",children:o.jsx("input",{autoFocus:e==="document",type:"text",value:a,onChange:j=>c(j.target.value),"data-pyric-field":"doc-id","aria-invalid":v||!a?"true":void 0})}),o.jsxs("div",{className:"fs-modal__group",children:[o.jsx("span",{className:"fs-modal__label",children:"Fields"}),o.jsx("div",{className:"fs-modal__fields",children:o.jsx(Ki.Root,{initial:{},onChange:u,children:o.jsx(Ki.Fields,{})})})]}),d?o.jsx("p",{className:"fs-modal__err",role:"alert",children:d.message}):null,o.jsxs("div",{className:"fs-modal__actions",children:[o.jsx("button",{type:"button",className:"fs-editor__cancel",disabled:f,onClick:r,children:"Cancel"}),o.jsx("button",{type:"button",className:"fs-editor__save",disabled:!w,onClick:()=>void x(),children:f?"Saving…":"Save"})]})]})})}function Mc({items:e,label:t="More actions"}){const[n,r]=h.useState(!1),[s,i]=h.useState(null),a=h.useRef(null),c=()=>{if(!n){const l=a.current?.getBoundingClientRect();l&&i({top:l.bottom+4,right:window.innerWidth-l.right})}r(l=>!l)};return h.useEffect(()=>{if(!n)return;const l=u=>{u.key==="Escape"&&(r(!1),a.current?.focus())};return document.addEventListener("keydown",l),()=>document.removeEventListener("keydown",l)},[n]),o.jsxs("span",{className:"fs-overflow","data-pyric-ui":"fs-overflow-menu",children:[o.jsx("button",{ref:a,type:"button",className:"fs-overflow__trigger","aria-haspopup":"menu","aria-expanded":n,"aria-label":t,onClick:c,children:o.jsx("span",{"aria-hidden":"true",children:"⋮"})}),n?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"fs-overflow__backdrop",onMouseDown:()=>r(!1)}),o.jsx("div",{className:"fs-overflow__menu",role:"menu",style:s?{top:s.top,right:s.right}:void 0,children:e.map(l=>o.jsx("button",{type:"button",role:"menuitem",className:"fs-overflow__item","data-destructive":l.destructive?"":void 0,disabled:l.disabled,onClick:()=>{r(!1),l.onSelect()},children:l.label},l.label))})]}):null]})}function Tc(e){return JSON.stringify(e)}function Aw(e,t){const n=new Map,r=(s,i)=>{const a=t(s),c=Tc(i);if(a==="map"){const l=s,u=Object.keys(l).sort();n.set(c,[a,u]);for(const d of u)r(l[d],[...i,["field",d]]);return}if(a==="array"){const l=s;n.set(c,[a,l.map((u,d)=>String(d))]),l.forEach((u,d)=>r(u,[...i,["index",d]]));return}n.set(c,[a,s])};for(const[s,i]of Object.entries(e))r(i,[["field",s]]);return n}function Uc(e,t){const n=[];let r=e.nodes[t];for(;r&&r.parentId!=null;){const s=e.nodes[r.parentId];if(!s)break;s.type==="array"?n.unshift(["index",(e.childIds[s.id]??[]).indexOf(r.id)]):n.unshift(["field",r.key??""]),r=s}return Tc(n)}function Iw(e,t){const n=[];let r=e.nodes[t];for(;r&&r.parentId!=null;){const s=e.nodes[r.parentId];if(!s)break;if(s.type==="array"){const i=(e.childIds[s.id]??[]).indexOf(r.id);n.unshift(`[${i}]`)}else n.unshift(r.key??"");r=s}return n.reduce((s,i)=>i.startsWith("[")?`${s}${i}`:s?`${s}.${i}`:i,"")}function Dw(e,t){const n=e.nodes[t],r=n?.parentId!=null?e.nodes[n.parentId]:null;if(r?.type==="array"){const s=(e.childIds[r.id]??[]).indexOf(t);return{label:String(s),isArrayChild:!0}}return{label:n?.key??"",isArrayChild:!1}}function ea(e,t,n){switch(e.type){case"map":return"{…}";case"array":return"[…]";case"string":return JSON.stringify(e.value);case"null":return"null";case"vector":{const r=t(e.value);return r?n(r):"vector"}default:return String(e.value)}}const Pw=42;function $w(e,t,n,r=Pw){const s=e.nodes[t],i=e.childIds[t]??[];let a;return s.type==="array"?a=`[${i.slice(0,3).map(l=>ea(e.nodes[l],n.asVectorView,n.vectorPreview)).join(", ")}${i.length>3?", …":""}]`:a=`{${i.slice(0,2).map(l=>`"${e.nodes[l].key}": ${ea(e.nodes[l],n.asVectorView,n.vectorPreview)}`).join(", ")}${i.length>2?", …":""}}`,a.length>r?`${a.slice(0,r-1)}…`:a}function Ow(e,t,n){return t.parentId==null?!1:(e.childIds[t.parentId]??[]).some(s=>s!==t.id&&e.nodes[s]?.key===n)}function Mw(e){return e.shiftKey===!0}const Bc=["string","number","boolean","null","timestamp","geopoint","reference","bytes","vector"],Tw=[...Bc,"map","array"];function Uw({snapshot:e,documentRef:t,onCommit:n,onDeleteDocument:r,onDeleteDocumentFields:s,fieldEditors:i,onReferenceClick:a,onStartCollection:c,firestore:l,listSubcollections:u,onSubcollectionClick:d}){const p=h.useMemo(()=>e?.data()??{},[e]),f=h.useMemo(()=>p,[]),m=xc({initial:f}),y=m.replaceData,g=h.useMemo(()=>Sc(i),[i]),v=gt(),[b,w]=h.useState(()=>new Set),[x,k]=h.useState(null),j=h.useRef(e),_=h.useRef(new Set),N=h.useRef(!1),[P,I]=h.useState(null),D=h.useMemo(()=>Aw(p,On),[p]),C=ks({scope:t.path,entries:D,equals:gn,ready:x===null});h.useEffect(()=>{N.current&&(N.current=!1,I(null),n(m.toData()).catch($=>{I($ instanceof Error?$:new Error(String($)))}))},[m.tree]),h.useEffect(()=>{!e||e===j.current||x!==null||(j.current=e,_.current.clear(),y(e.data()??{}))},[x,y,e]);const S=h.useCallback($=>{w(Y=>{const se=new Set(Y);return se.has($)?se.delete($):se.add($),se})},[]),[E,R]=h.useState(null),V=h.useCallback(($,Y)=>{if(Y==="map"?m.addMapEntry($,"","string"):m.addArrayEntry($,"string"),$!==m.tree.rootId){const se=Uc(m.tree,$);w(ne=>new Set(ne).add(se))}R($)},[m]);h.useEffect(()=>{if(!E)return;const $=m.tree.childIds[E]??[],Y=$[$.length-1];Y&&!x&&(_.current.add(Y),k(Y),R(null))},[m.tree,E]);const G=h.useCallback($=>{m.remove($),_.current.delete($),N.current=!0,x===$&&k(null)},[m,x]),A=h.useCallback(async($,Y,se)=>{if(Mw(se)){G($.id);return}await v({title:`Delete field "${Y}"?`,destructive:!0,confirmLabel:"Delete"})&&G($.id)},[v,G]),O=t.id,M=m.tree.childIds[m.tree.rootId]??[];return o.jsxs("div",{"data-pyric-ui":"fs-doctree",className:"fs-doctree",children:[o.jsxs("div",{className:"fs-doctree__head",children:[o.jsx("span",{className:"fs-doctree__docid",children:O}),o.jsx(Mc,{items:[{label:"Delete document fields",onSelect:()=>{(async()=>await v({title:"Delete all fields?",body:"The document itself is kept, empty.",destructive:!0,confirmLabel:"Delete fields"})&&s())()},destructive:!0},{label:"Delete document",onSelect:r,destructive:!0}]})]}),P?o.jsx("p",{className:"fs-doctree__err",children:P.message}):null,o.jsxs("ul",{className:"fs-doctree__rows",children:[c?o.jsx("li",{className:"fs-doctree__action-row",children:o.jsxs("button",{type:"button",className:"fs-doctree__action",onClick:c,children:[o.jsx("span",{"aria-hidden":"true",children:"+"})," Start collection"]})}):null,o.jsx("li",{className:"fs-doctree__action-row",children:o.jsxs("button",{type:"button",className:"fs-doctree__action",onClick:()=>V(m.tree.rootId,"map"),children:[o.jsx("span",{"aria-hidden":"true",children:"+"})," Add field"]})}),M.map($=>o.jsx(Lc,{nodeId:$,depth:0,editor:m,registry:g,expanded:b,onToggle:S,editingId:x,setEditingId:k,newIdsRef:_,onAdd:V,onDelete:A,onCommitNeeded:()=>{N.current=!0},onReferenceClick:a,updates:C},$))]}),l&&u?o.jsx(Fc,{firestore:l,documentRef:t,listSubcollections:u,onSubcollectionClick:d}):null]})}function Lc({nodeId:e,depth:t,editor:n,registry:r,expanded:s,onToggle:i,editingId:a,setEditingId:c,newIdsRef:l,onAdd:u,onDelete:d,onCommitNeeded:p,onReferenceClick:f,updates:m}){const{tree:y}=n,g=y.nodes[e];if(!g)return null;const{label:v,isArrayChild:b}=Dw(y,e),w=g.type==="map"||g.type==="array",x=Iw(y,e),k=Uc(y,e),j=m.get(k),_=s.has(k),N=a===e,P=l.current.has(e);return N?o.jsx("li",{className:"fs-doctree__row fs-doctree__row--editing","data-pyric-doctree-depth":t,style:{"--fs-depth":t},children:o.jsx(Bw,{node:g,isNew:P,isArrayChild:b,tree:y,editor:n,registry:r,path:x,onCommitNeeded:p,onDone:()=>{l.current.delete(e),c(null)},onCancelNew:()=>{n.remove(e),l.current.delete(e),c(null)}})}):o.jsxs("li",{className:"fs-doctree__row","data-pyric-doctree-depth":t,"data-pyric-doctree-nested":w?"":void 0,style:{"--fs-depth":t},children:[o.jsxs("div",{className:"fs-doctree__line","data-pyric-update":j?.kind,"data-pyric-update-cycle":j?.cycle,children:[w?o.jsx("button",{type:"button",className:"fs-doctree__caret","aria-expanded":_,onClick:()=>i(k),children:o.jsx("span",{"aria-hidden":"true",children:_?"▼":"▶"})}):o.jsx("span",{className:"fs-doctree__caret fs-doctree__caret--empty","aria-hidden":"true"}),b?o.jsx("span",{className:"fs-doctree__chip",children:v}):o.jsx("span",{className:"fs-doctree__key",children:v}),w?_?null:o.jsx("span",{className:"fs-doctree__preview",children:$w(y,e,{asVectorView:Je,vectorPreview:pc})}):o.jsx("span",{className:"fs-doctree__value",children:o.jsx(Lr,{value:g.value,path:x,fieldEditors:r})}),o.jsxs("span",{className:"fs-doctree__hover",children:[o.jsxs("span",{className:"fs-doctree__typenote",children:["(",g.type,")"]}),w?o.jsx("button",{type:"button",className:"fs-doctree__icon",title:"Add field","aria-label":`Add field to ${v||"document"}`,onClick:()=>u(e,g.type==="array"?"array":"map"),children:"+"}):o.jsx("button",{type:"button",className:"fs-doctree__icon",title:"Edit","aria-label":`Edit ${v}`,onClick:()=>c(e),children:"✎"}),o.jsx("button",{type:"button",className:"fs-doctree__icon fs-doctree__icon--danger",title:"Delete (shift-click to skip confirmation)","aria-label":`Delete ${v||"field"} (shift-click to skip confirmation)`,onClick:I=>void d(g,v,{shiftKey:I.shiftKey}),children:"🗑"})]})]}),w&&_?o.jsxs("ul",{className:"fs-doctree__children",children:[(y.childIds[e]??[]).map(I=>o.jsx(Lc,{nodeId:I,depth:t+1,editor:n,registry:r,expanded:s,onToggle:i,editingId:a,setEditingId:c,newIdsRef:l,onAdd:u,onDelete:d,onCommitNeeded:p,onReferenceClick:f,updates:m},I)),o.jsx("li",{className:"fs-doctree__action-row fs-doctree__action-row--nested",children:o.jsxs("button",{type:"button",className:"fs-doctree__action",onClick:()=>u(e,g.type==="array"?"array":"map"),children:[o.jsx("span",{"aria-hidden":"true",children:"+"})," ",g.type==="array"?"Add item":"Add field"]})})]}):null]})}function Bw({node:e,isNew:t,isArrayChild:n,tree:r,editor:s,registry:i,path:a,onCommitNeeded:c,onDone:l,onCancelNew:u}){const[d,p]=h.useState(e.key??""),[f,m]=h.useState(e.type),[y,g]=h.useState(e.value),[v,b]=h.useState(!1),w=n?void 0:d===""?"Field name is required":Ow(r,e,d)?"Field name must be unique":void 0,x=f==="map"||f==="array"?void 0:gc(f,y),k=!w&&!x,j=()=>{if(!k){b(!0);return}n||s.setKey(e.id,d),f!==e.type&&s.setType(e.id,f),f!=="map"&&f!=="array"&&s.setValue(e.id,y),c(),l()},_=()=>{t?u():l()},P=i[f]?.Edit,I=f!=="map"&&f!=="array"&&P?o.jsx(P,{value:y,path:a,error:v?x:void 0,onChange:S=>g(S)}):f==="map"||f==="array"?o.jsxs("span",{className:"fs-doctree__editnote",children:["Saves as an empty ",f," — add its children afterward."]}):null,D=o.jsxs("span",{className:"fs-doctree__editactions",children:[o.jsx("button",{type:"button",className:"fs-doctree__editsave",onClick:j,"aria-label":"Save field",children:"✓"}),o.jsx("button",{type:"button",className:"fs-doctree__editcancel",onClick:_,"aria-label":"Cancel edit",children:"✕"})]}),C=o.jsx("select",{className:"fs-doctree__edittype",value:f,onChange:S=>{const E=S.target.value;m(E),E!=="map"&&E!=="array"&&E!==f&&g(Lw(E))},"aria-label":"Field type",children:(t?Tw:Bc).map(S=>o.jsx("option",{value:S,children:S},S))});return o.jsxs("div",{className:"fs-doctree__editrow",onKeyDown:S=>{S.key==="Enter"&&!S.target.matches("textarea")?(S.preventDefault(),j()):S.key==="Escape"&&(S.preventDefault(),_())},children:[n?null:o.jsxs("div",{className:"fs-doctree__editline",children:[o.jsx("input",{type:"text",className:"fs-doctree__editkey",value:d,placeholder:"Field name",autoFocus:t,onChange:S=>p(S.target.value),onBlur:()=>b(!0),"aria-label":"Field name","aria-invalid":v&&w?"true":void 0}),C]}),o.jsxs("div",{className:"fs-doctree__editline",children:[n?C:null,I,D]}),v&&w?o.jsx("span",{className:"fs-doctree__editerr",children:w}):null]})}function Lw(e){switch(e){case"string":return"";case"number":return 0;case"boolean":return!1;default:return null}}function Fc({firestore:e,documentRef:t,listSubcollections:n,onSubcollectionClick:r}){const{subcollections:s,isLoading:i}=Vg({firestore:e,documentRef:t,listSubcollections:n});return!i&&s.length===0?null:o.jsxs("section",{"data-pyric-ui":"fs-doctree-subcollections","data-pyric-loading":i?"":void 0,children:[o.jsx("div",{className:"fs-doctree__subhead",children:"Subcollections"}),o.jsx("ul",{className:"fs-doctree__sublist",children:s.map(a=>o.jsx("li",{children:r?o.jsxs("button",{type:"button",className:"fs-doctree__subrow",onClick:()=>r(a),"aria-label":`Open subcollection ${a.id}`,children:[o.jsx("span",{children:a.id}),o.jsx("span",{className:"fs-doctree__subtype",children:"subcollection"}),o.jsx("span",{"aria-hidden":"true",children:"›"})]}):o.jsxs("div",{className:"fs-doctree__subrow",children:[o.jsx("span",{children:a.id}),o.jsx("span",{className:"fs-doctree__subtype",children:"subcollection"})]})},a.path))})]})}function Fw(e){return e.split("/").filter(Boolean).length%2===0}function Vc(e,t){async function*n(s,i,a=!1){const c=await t.listSubcollections(s.path);for(const l of c)yield*r(e.collection(s,l),i);a||(await e.deleteDoc(s),i.n++,yield{deletedCount:i.n,done:!1})}async function*r(s,i){const a=await t.listDocuments(s.path);for(const c of a){const l=c.path.split("/").pop();l&&(yield*n(e.doc(s,l),i,c.phantom===!0))}}return{async*start(s){const i={n:0};Fw(s.path)?yield*n(s,i):yield*r(s,i),yield{deletedCount:i.n,done:!0}}}}async function qc(e,t){for await(const n of e.start(t))if(n.done)return}async function Wc({confirm:e,ref:t,api:n,recursiveImpl:r}){let s=!1;return await e({title:`Delete document "${t.id}"?`,body:o.jsxs("label",{className:"fs-delete-recursive",children:[o.jsx("input",{type:"checkbox",onChange:a=>{s=a.currentTarget.checked}}),o.jsx("span",{children:"Also delete subcollections recursively. Leave this off to keep nested data."})]}),destructive:!0,confirmLabel:"Delete document"})?(s?await qc(r,t):await n.deleteDoc(t),!0):!1}function Vw(e){const t=e.exists;return typeof t=="function"?t.call(e):t}async function qw(e,t,n,r){const s=e.doc(t,n),i=await e.getDoc(s);if(typeof i.exists=="function"?i.exists():!!i.exists)throw new Error(`Document "${n}" already exists here — choose a different ID.`);await e.setDoc(s,r)}function Ww(e){return{id:e.id,ref:e,data:()=>{},__pyricPhantom:!0}}function ta(e){return e.__pyricPhantom===!0}function zw(e,t,n){const r=n.split("/");if(r.length===1)return e.collection(t,n);const s=r[r.length-1],i=r.slice(0,-1).join("/");return e.collection(e.doc(t,i),s)}function Kw({handles:e}){const{target:t,navigate:n}=Un(),r=e.adminFirestore,s=vs(),i=h.useMemo(()=>t?.view==="firestore"?t.path:[],[t]),a=h.useCallback(k=>{const j=typeof k=="function"?k(i):k;n({view:"firestore",path:j})},[n,i]),c=(k,j)=>a(_=>[..._.slice(0,k+1),j]),[l,u]=h.useState(null),d=h.useCallback(async({collectionId:k,docId:j,data:_})=>{if(!l||!k)return;const N=l.parentDocPath,P=N?s.collection(s.doc(r,N),k):s.collection(r,k);await qw(s,P,j,_);const I=N?`${N}/${k}`:k;n({view:"firestore",path:vn(`${I}/${j}`)})},[s,r,l,n]),p=[o.jsx(Jw,{api:s,firestore:r,collectionIds:e.listRootCollections(),onSelect:k=>a([{kind:"collection",id:k,path:k}]),onStartCollection:()=>u({parentDocPath:null})},"__root__"),...i.map((k,j)=>k.kind==="collection"?o.jsx(Yw,{api:s,firestore:r,handles:e,collectionPath:k.path,selectedId:i[j+1]?.id??null,onSelect:_=>c(j,{kind:"document",id:_.id,path:_.path}),onCollectionDeleted:()=>a(_=>_.slice(0,j))},k.path):o.jsx(Qw,{api:s,firestore:r,handles:e,docPath:k.path,onOpenSubcollection:_=>c(j,{kind:"collection",id:_.id,path:_.path}),onReferenceClick:_=>n({view:"firestore",path:vn(_.path)}),onStartCollection:()=>u({parentDocPath:k.path}),onDeleted:()=>a(_=>_.slice(0,j))},k.path))],{ref:f,size:m}=Mn(Cw),{startIndex:y,visibleCount:g,emptySlots:v}=Rw(p.length,m),b=p.slice(y,y+g),w=i.length===0?"Select a collection":i[i.length-1]?.kind==="collection"?"Select a document":null,x=[...b,...Array.from({length:v},(k,j)=>o.jsx(Gw,{hint:j===0?w:null},`__empty_${j}__`))];return h.useEffect(()=>{if(m==="wide")return;const k=f.current;if(!k)return;const j=document.activeElement;if(j&&j!==document.body&&k.contains(j))return;const _=k.querySelector(".fs-columns > .fs-col:last-child");_&&(_.tabIndex=-1,_.focus({preventScroll:!0}))},[i.length,m]),o.jsx(gs,{children:o.jsxs("div",{ref:f,"data-pyric-ui":"fs-browser","data-fs-depth":i.length,"data-size":m,children:[o.jsx(Hw,{path:i,onHome:()=>a([]),onJump:k=>a(j=>j.slice(0,k+1))}),o.jsx("div",{className:"fs-columns",children:x}),l?o.jsx(Oc,{mode:"collection",parentPath:l.parentDocPath?`/${l.parentDocPath}`:"/",onCreate:d,onClose:()=>u(null)}):null]})})}function Hw({path:e,onHome:t,onJump:n}){return o.jsxs("nav",{"data-pyric-ui":"fs-breadcrumb","aria-label":"Firestore path",children:[o.jsx("button",{type:"button",className:"fs-crumb",onClick:t,children:"home"}),e.map((r,s)=>o.jsxs(h.Fragment,{children:[o.jsx("span",{className:"fs-crumb-sep","aria-hidden":!0,children:"›"}),s===e.length-1?o.jsx("span",{className:"fs-crumb fs-crumb--current",children:r.id}):o.jsx("button",{type:"button",className:"fs-crumb",onClick:()=>n(s),children:r.id})]},r.path))]})}function Gw({hint:e}){return o.jsx("section",{"data-pyric-ui":"fs-empty-col",className:"fs-pane fs-col fs-col--empty","aria-hidden":e?void 0:!0,children:e?o.jsx("p",{className:"fs-empty",children:e}):null})}function Jw({api:e,firestore:t,collectionIds:n,onSelect:r,onStartCollection:s}){const i=h.useMemo(()=>n.map(a=>e.collection(t,a)),[e,t,n]);return o.jsxs("section",{"data-pyric-ui":"fs-collections",className:"fs-pane fs-col",children:[o.jsxs("div",{className:"fs-phead",children:[o.jsx("span",{className:"fs-phead-title",children:"Collections"}),o.jsx("button",{type:"button",className:"fs-add",onClick:s,children:"+ New"})]}),o.jsx(Iv,{collections:i,onSelect:a=>r(a.id),emptyState:o.jsx("p",{className:"fs-empty",children:"No collections yet. App or agent writes show up here."})})]})}function Yw({api:e,firestore:t,handles:n,collectionPath:r,selectedId:s,onSelect:i,onCollectionDeleted:a}){const c=h.useMemo(()=>zw(e,t,r),[e,t,r]),{documents:l,isLoading:u,error:d,subscriptionGeneration:p,hasMore:f,loadMore:m,createDocument:y}=Fg({collection:c,mode:"live"}),[g,v]=h.useState([]);h.useEffect(()=>{let C=!1;return Promise.resolve(n.listDocuments(r)).then(S=>{C||v(S.filter(E=>E.phantom).map(E=>E.path.split("/").pop()??""))}).catch(()=>{C||v([])}),()=>{C=!0}},[n,r,l]);const b=h.useMemo(()=>{const C=new Set(l.map(S=>S.id));return[...l,...g.filter(S=>S.length>0&&!C.has(S)).map(S=>Ww(e.doc(t,`${r}/${S}`)))]},[l,g,e,t,r]),w=r.split("/").pop()??r,[x,k]=h.useState(null),[j,_]=h.useState(!1),N=gt(),P=h.useMemo(()=>Vc(e,n),[e,n]),I=h.useCallback(async C=>{k(null);try{await Wc({confirm:N,ref:C,api:e,recursiveImpl:P})}catch(S){k(S instanceof Error?S:new Error(String(S)))}},[e,N,P]),D=h.useCallback(async()=>{if(await N({title:`Delete collection "${w}"?`,body:"This deletes every document in it (and their subcollections).",destructive:!0,confirmLabel:"Delete collection"})){k(null);try{await qc(P,c),a()}catch(S){k(S instanceof Error?S:new Error(String(S)))}}},[N,P,c,w,a]);return o.jsxs("section",{"data-pyric-ui":"fs-documents",className:"fs-pane fs-col",children:[o.jsxs("div",{className:"fs-phead",children:[o.jsx("span",{className:"fs-phead-title",children:w}),o.jsx("span",{className:"fs-phead-actions",children:o.jsx("button",{type:"button",className:"fs-add",onClick:()=>_(!0),children:"+ New"})}),o.jsx(Mc,{items:[{label:"Delete collection",onSelect:()=>void D(),destructive:!0}]})]}),j?o.jsx(Oc,{mode:"document",parentPath:`/${r}`,onCreate:async({docId:C,data:S})=>{const E=await y(C,S,{onExisting:"fail"});i(E)},onClose:()=>_(!1)}):null,o.jsx(Dv,{documents:b,isLoading:u,error:d,updateScope:`${r}:${p}`,hasMore:f,onLoadMore:m,onSelect:i,renderLabel:C=>{const S=C.ref;return o.jsx("span",{"data-pyric-selected":s===S.id?"":void 0,style:{display:"contents"},children:ta(C)?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"fs-doc-phantom",children:C.id}),o.jsx("span",{className:"fs-sub fs-doc-phantom-hint",children:"missing"})]}):C.id})},renderRowAction:C=>{if(ta(C))return null;const S=C.ref;return o.jsx("button",{type:"button",className:"fs-doc-del",title:"Delete document","aria-label":`Delete ${S.id}`,onClick:E=>{E.stopPropagation(),I(S)},children:"×"})},emptyState:o.jsx("p",{className:"fs-empty",children:"No documents."})}),x?o.jsx("p",{className:"fs-empty fs-doc-del-err",children:x.message}):null]})}function Qw({api:e,firestore:t,handles:n,docPath:r,onOpenSubcollection:s,onReferenceClick:i,onStartCollection:a,onDeleted:c}){const l=h.useMemo(()=>e.doc(t,r),[e,t,r]),{data:u,error:d,isLoading:p}=Rg(l),f=h.useCallback(async(k,j)=>(await n.listSubcollections(j.path)).map(N=>e.collection(j,N)),[n,e]),m=gt(),y=h.useMemo(()=>Vc(e,n),[e,n]),[g,v]=h.useState(null),b=h.useCallback(async()=>{v(null);try{await Wc({confirm:m,ref:l,api:e,recursiveImpl:y})&&c()}catch(k){v(k instanceof Error?k:new Error(String(k)))}},[e,m,y,l,c]),w=h.useCallback(async()=>{await e.setDoc(l,{})},[e,l]),x=u!=null&&Vw(u);return o.jsxs("section",{"data-pyric-ui":"fs-document",className:"fs-pane fs-col doc",children:[x?null:o.jsxs("div",{className:"fs-phead",children:[o.jsx("span",{className:"fs-phead-title",children:l.id}),o.jsx("span",{className:"fs-phead-actions",children:o.jsx("button",{type:"button",className:"fs-add",onClick:a,children:"+ Collection"})})]}),u&&x?o.jsx(Uw,{snapshot:u,documentRef:l,firestore:t,listSubcollections:f,onReferenceClick:i,onSubcollectionClick:s,onStartCollection:a,onDeleteDocument:()=>void b(),onDeleteDocumentFields:w,onCommit:async k=>{await e.setDoc(l,k)}},r):d?o.jsx("p",{className:"fs-empty fs-doc-del-err",children:d.message}):p?o.jsx("p",{className:"fs-empty",children:"Loading document…"}):o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"fs-empty",children:"This document does not exist."}),o.jsx(Fc,{firestore:t,documentRef:l,listSubcollections:f,onSubcollectionClick:s})]}),g?o.jsx("p",{className:"fs-empty fs-doc-del-err",children:g.message}):null]})}const Xw="block w-full text-sm text-soft-white";function Zw({auth:e,focusUid:t}){const{users:n,totalCount:r,isLoading:s,error:i,filter:a,setFilter:c,updateUser:l}=bs(e),[u,d]=h.useState(null);h.useEffect(()=>{t&&(d(t),c(t))},[t,c]);const p=n.find(f=>f.uid===u)??null;return o.jsxs("div",{className:"grid grid-cols-[1fr_320px] gap-4",children:[o.jsxs("section",{className:"min-w-0",children:[o.jsx("input",{value:a,onChange:f=>c(f.target.value),placeholder:"Filter users…",className:"mb-3 w-full rounded border border-border bg-content-bg px-3 py-1.5 text-sm text-soft-white placeholder:text-slate-gray"}),o.jsx(cc,{users:n,isLoading:s,error:i,filter:a,onSelect:f=>d(f.uid),className:Xw,emptyState:o.jsx("p",{className:"py-6 text-sm text-slate-gray",children:"No users yet. Sign in from the app, or the agent seeds them, and they appear here."}),noResultsState:o.jsx("p",{className:"py-6 text-sm text-slate-gray",children:"No users match the filter."})}),o.jsxs("p",{className:"mt-2 text-xs text-slate-gray",children:[r," user(s) total"]})]}),o.jsx("section",{className:"min-w-0 border-l border-border pl-4",children:p?o.jsx(ex,{user:p,onSave:f=>l(p.uid,f)},p.uid):o.jsx("p",{className:"py-6 text-sm text-slate-gray",children:"Select a user to view and edit."})})]})}function ex({user:e,onSave:t}){const n=oc({initial:e}),[r,s]=h.useState(null),[i,a]=h.useState(!1),c=()=>{s(null),a(!1);try{t(n.toUpdateRequest()),a(!0)}catch(l){s(l instanceof Error?l:new Error(String(l)))}};return o.jsxs("div",{"data-pyric-ui":"auth-editor",children:[o.jsx("h3",{className:"mb-3 truncate font-mono text-xs text-slate-gray",title:e.uid,children:e.uid}),o.jsxs("label",{className:"mb-3 block text-xs text-slate-gray",children:["Display name",o.jsx("input",{value:n.fields.displayName,onChange:l=>n.setField("displayName",l.target.value),className:"mt-1 w-full rounded border border-border bg-content-bg px-2 py-1 text-sm text-soft-white"})]}),o.jsxs("label",{className:"mb-3 block text-xs text-slate-gray",children:["Custom claims (JSON)",o.jsx("textarea",{value:n.fields.claimsText,onChange:l=>n.setField("claimsText",l.target.value),rows:6,spellCheck:!1,className:"mt-1 w-full rounded border border-border bg-content-bg p-2 font-mono text-xs text-soft-white"}),n.errors.claims?o.jsx("span",{className:"text-danger",children:n.errors.claims}):null]}),o.jsxs("label",{className:"mb-3 flex items-center gap-2 text-xs text-slate-gray",children:[o.jsx("input",{type:"checkbox",checked:n.fields.disabled,onChange:l=>n.setField("disabled",l.target.checked)}),"Disabled"]}),r?o.jsx("p",{className:"mb-2 text-xs text-danger",children:r.message}):null,i?o.jsx("p",{className:"mb-2 text-xs text-primary",children:"Saved."}):null,o.jsxs("div",{className:"flex gap-2",children:[o.jsx("button",{type:"button",onClick:c,disabled:!n.isValid||!n.isDirty,className:"rounded bg-primary/15 px-3 py-1 text-xs font-medium text-primary hover:bg-primary/25 disabled:opacity-40",children:"Save"}),o.jsx("button",{type:"button",onClick:n.reset,disabled:!n.isDirty,className:"rounded border border-border px-3 py-1 text-xs text-slate-gray hover:text-soft-white disabled:opacity-40",children:"Reset"})]})]})}function na(e){const t=Q(e),n=t.lastIndexOf("/");return n===-1?"":t.slice(0,n)}function ra(e,t){return e===""?t:t===""?e:`${e}/${t}`}function sa(e){const t=e.lastIndexOf("/");return t===-1?e:e.slice(t+1)}const tx=[{key:"size",label:"size",value:e=>`${e.size} bytes`},{key:"contentType",label:"content type",value:e=>e.contentType},{key:"timeCreated",label:"created",value:e=>e.timeCreated},{key:"updated",label:"updated",value:e=>e.updated},{key:"md5Hash",label:"md5",value:e=>e.md5Hash},{key:"cacheControl",label:"cache control",value:e=>e.cacheControl},{key:"fullPath",label:"path",value:e=>`gs://${e.bucket}/${e.fullPath}`}];function nx(e){const t=Object.entries(e.customMetadata??{});return o.jsxs("dl",{"data-pyric-object-metadata":!0,children:[o.jsx("div",{"data-storage-meta-group":!0,children:"Metadata"}),tx.map(({key:n,label:r,value:s})=>{const i=s(e);return i===void 0?null:o.jsxs("div",{"data-pyric-metadata-field":n,children:[o.jsx("dt",{children:r}),o.jsx("dd",{children:i})]},n)}),t.length>0?o.jsx("div",{"data-storage-meta-group":!0,children:"Custom metadata"}):null,t.map(([n,r])=>o.jsxs("div",{"data-pyric-metadata-field":"customMetadata","data-pyric-metadata-key":n,children:[o.jsx("dt",{children:n}),o.jsx("dd",{children:r})]},`custom:${n}`))]})}function rx(){return o.jsx("svg",{"aria-hidden":!0,viewBox:"0 0 16 16",width:"13",height:"13",fill:"none",stroke:"currentColor",strokeWidth:"1.25",strokeLinejoin:"round",children:o.jsx("path",{d:"M1.75 4.25c0-.55.45-1 1-1h3.4l1.5 1.7h5.6c.55 0 1 .45 1 1v6.05c0 .55-.45 1-1 1H2.75c-.55 0-1-.45-1-1z"})})}function sx(){return o.jsxs("svg",{"aria-hidden":!0,viewBox:"0 0 16 16",width:"13",height:"13",fill:"none",stroke:"currentColor",strokeWidth:"1.25",strokeLinejoin:"round",children:[o.jsx("path",{d:"M4.25 1.75h5l3 3v9.5h-8z"}),o.jsx("path",{d:"M9.25 1.75v3h3"})]})}function ix(e){const t=e.kind==="folder";return o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"storage__cell-name",children:[o.jsx("span",{className:"storage__ic","aria-hidden":!0,children:t?o.jsx(rx,{}):o.jsx(sx,{})}),o.jsx("span",{className:"storage__nm",children:e.name}),t?o.jsx("span",{"aria-hidden":!0,className:"storage__chev",children:"›"}):null]}),o.jsx("span",{className:"storage__cell-type",children:t?"folder":"file"}),o.jsx("span",{className:"storage__cell-size"}),o.jsx("span",{className:"storage__cell-updated"})]})}function ax({storage:e,focusTarget:t}){const n=Un(),r=t.kind==="object"?Q(t.path):null,s=t.kind==="prefix"?Q(t.path):r?na(r):"",i=h.useCallback(C=>{const S=Q(C);n.navigate(S?{view:"storage",kind:"prefix",path:S}:{view:"storage",kind:"root"})},[n.navigate]),a=Fv({path:s,onPathChange:i}),c=C=>{n.navigate({view:"storage",kind:"object",path:Q(C)})},l=Lv(e,a.path),u=qv(),d=Jv(e),[p,f]=h.useReducer(aw,Ic),m=Xv(e,{path:a.path,list:l,onComplete:C=>f({type:"materialize",path:na(C.fullPath)})});h.useEffect(()=>{if(l.status==="success")for(const C of l.entries)C.kind==="folder"&&Xi(p,C.fullPath)&&f({type:"materialize",path:C.fullPath})},[l.status,l.entries,p]);const[y,g]=h.useState(!1),[v,b]=h.useState(""),[w,x]=h.useState(null),k=h.useRef(null),j=h.useMemo(()=>{const C=ow(p,a.path).filter(R=>!l.entries.some(V=>V.kind==="folder"&&V.name===R));if(C.length===0)return l.entries;const S=C.map(R=>{const V=ra(a.path,R);return{kind:"folder",name:R,fullPath:V,ref:{fullPath:V,name:R}}});return[...[...l.entries.filter(R=>R.kind==="folder"),...S].sort((R,V)=>R.name<V.name?-1:R.name>V.name?1:0),...l.entries.filter(R=>R.kind==="object")]},[l.entries,p,a.path]),_=j.length>0&&j.every(C=>u.isSelected(C.fullPath)),N=C=>{const S=new Set(j.map(R=>R.name)),E=iw(C.map(R=>R.relativePath),S);m.upload(C.map((R,V)=>({path:E[V],data:R.file})))},P=C=>{C.preventDefault();const S=cw(v);if(S){x(S);return}const E=ra(a.path,Q(v));f({type:"create",path:E}),a.setPath(E),b(""),x(null),g(!1)};h.useEffect(()=>u.clear(),[a.path,u.clear]);const I=m.tasks.filter(C=>C.status==="error"),D=d.verdictFor(a.path);return o.jsx(vw,{children:o.jsx(gs,{children:o.jsxs("div",{className:"storage",children:[o.jsxs("div",{className:"storage__sub",children:[o.jsx(Zv,{path:a.path,rootLabel:"files",onNavigate:a.setPath}),o.jsx("div",{className:"storage__actions",children:u.size>0?o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"studio-selection-count",children:[u.size," selected"]}),o.jsx(xw,{storage:e,entries:u.selected,list:l,gate:d,className:"studio-selection-delete",onDeleted:C=>{for(const S of u.selected)S.kind==="folder"&&C.deleted.includes(S.fullPath)&&f({type:"discard",path:S.fullPath});r&&u.selected.some(S=>S.kind==="object"?S.fullPath===r:r.startsWith(`${S.fullPath}/`))&&a.setPath(a.path),u.clear(),l.refresh()},onFailed:C=>{const S=new Set(C.failed.map(E=>E.fullPath));u.selectAll(u.selected.filter(E=>S.has(E.fullPath))),l.refresh()}}),o.jsx("button",{type:"button",className:"storage__action",onClick:u.clear,children:"Clear selection"})]}):o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:"storage__action","aria-expanded":y,onClick:()=>{g(C=>!C),x(null)},children:"New folder"}),o.jsx("button",{type:"button",className:"storage__action storage__action--upload",onClick:()=>k.current?.click(),children:"Upload files"}),o.jsx("input",{ref:k,type:"file",multiple:!0,hidden:!0,onChange:C=>{const S=Array.from(C.currentTarget.files??[]);S.length>0&&N(S.map(E=>({file:E,relativePath:E.name}))),C.currentTarget.value=""}})]})})]}),y?o.jsxs("form",{className:"storage__newfolder",onSubmit:P,children:[o.jsx("input",{autoFocus:!0,className:"storage__newfolder-input",placeholder:"folder or nested/path/of/folders","aria-label":"New folder name",value:v,onChange:C=>{b(C.currentTarget.value),x(null)},onKeyDown:C=>{C.key==="Escape"&&g(!1)}}),o.jsx("button",{type:"submit",className:"storage__newfolder-btn",children:"Create"}),w?o.jsx("span",{className:"storage__newfolder-err",role:"alert",children:w}):o.jsx("span",{className:"storage__newfolder-note",children:"Nested paths create the whole chain. Empty folders last this session only — upload a file to keep one."})]}):null,I.length>0?o.jsxs("p",{className:"storage__upload-err",role:"alert",children:[I.length===1?`Upload failed: ${sa(I[0].fullPath)} — ${I[0].error?.message??"error"}`:`${I.length} uploads failed: ${I.map(C=>sa(C.fullPath)).join(", ")}`,o.jsx("button",{type:"button",className:"storage__upload-err-dismiss",onClick:m.clearCompleted,children:"Dismiss"})]}):null,o.jsxs("div",{className:"storage__body","data-storage-level":r?"inspector":"browser",children:[o.jsxs(nw,{className:"storage__browser",onFiles:N,disabled:!D.upload,disabledReason:D.reasons.write.join("; "),children:[o.jsxs("div",{className:"storage__lhead",children:[o.jsx("label",{className:"storage__select-all",title:"Select all in this folder",children:o.jsx("input",{type:"checkbox","aria-label":"Select all in this folder",checked:_,onChange:C=>C.currentTarget.checked?u.selectAll(j):u.clear()})}),o.jsx("span",{children:"name"}),o.jsx("span",{children:"type"}),o.jsx("span",{children:"size"}),o.jsx("span",{children:"updated"})]}),o.jsx(ew,{entries:j,status:l.status,error:l.error,gate:d,selectedPath:r??void 0,renderEntry:ix,renderRowAction:C=>o.jsx("label",{className:"storage__select-row",title:`Select ${C.name}`,children:o.jsx("input",{type:"checkbox","aria-label":`Select ${C.name}`,checked:u.isSelected(C.fullPath),onChange:()=>u.toggle(C)})}),onNavigate:a.enter,onSelect:C=>c(C.fullPath),emptyState:o.jsx("p",{className:"storage__empty",children:Xi(p,a.path)?"Empty folder — session-only until a file is uploaded here. Drop files anywhere in this pane, or use Upload files.":"No files yet. Drop files here or use Upload files; files your app uploads to Storage also appear here."})}),o.jsxs("div",{className:"storage__dropcue","aria-hidden":!0,children:["Drop to upload to /",a.path||""]})]}),o.jsx("div",{className:"storage__inspector",children:r?o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:"storage__back",onClick:()=>a.setPath(a.path),"aria-label":"Back to files",children:"‹ Files"}),o.jsx(bw,{storage:e,path:r,renderMetadata:nx})]}):o.jsx("p",{className:"storage__inspector-hint",children:"Select an object to inspect its preview and metadata."})})]})]})})})}function ox({view:e}){const t=e==="firestore"?"Firestore":e==="auth"?"Auth":"Storage";return o.jsxs("div",{"data-pyric-ui":"data-pending",className:"flex flex-col items-center justify-center gap-2 py-16 text-center",children:[o.jsx("span",{className:"rounded-full border border-border px-3 py-1 text-xs uppercase tracking-wide text-slate-gray",children:"Local backend pending"}),o.jsxs("p",{className:"max-w-md text-sm leading-relaxed text-slate-gray",children:["The ",t," viewer mounts here. It goes live once the local sandbox backend is reachable (the served `pyric dev --ui` workspace)."]})]})}function zc({view:e}){const{target:t}=Un(),n=Oe(),r=n.status==="ready"?n.handles.auth:null;return o.jsx("div",{"data-pyric-ui":"data-feature",children:n.status!=="ready"||!r?o.jsx(ox,{view:e}):n.authApi?o.jsx(rc,{value:n.authApi,children:o.jsx(ia,{view:e,handles:n.handles,auth:r,target:t,firestoreApi:n.firestoreApi,storageApi:n.storageApi})}):o.jsx(ia,{view:e,handles:n.handles,auth:r,target:t,firestoreApi:n.firestoreApi,storageApi:n.storageApi})})}function ia({view:e,handles:t,auth:n,target:r,firestoreApi:s,storageApi:i}){const{users:a}=bs(n),c=h.useMemo(()=>new Set(a.map(l=>l.uid)),[a]);switch(e){case"firestore":{const l=o.jsx(Kw,{handles:t,knownUids:c});return s?o.jsx(Ng,{value:s,children:l}):l}case"auth":return o.jsx(Zw,{auth:n,focusUid:r?.view==="auth"?r.uid:null});case"storage":{const l=o.jsx(ax,{storage:t.storage,focusTarget:r?.view==="storage"?r:{kind:"root"}});return i?o.jsx(Bv,{value:i,children:l}):l}}}function cx(){return o.jsx(zc,{view:"firestore"})}function lx(){return o.jsx(zc,{view:"storage"})}function ux(e,t){const n=new Set(t.map(r=>r.uid));return new Set([...e].filter(r=>n.has(r)))}async function dx(e,t){const n=[];for(const r of e)try{await t(r.uid)}catch{n.push(r.uid)}return n}function fx(e){const[t,n]=h.useState(()=>new Set);h.useEffect(()=>{n(s=>{const i=ux(s,e);return i.size===s.size&&[...i].every(a=>s.has(a))?s:i})},[e]);const r=h.useMemo(()=>e.filter(s=>t.has(s.uid)),[t,e]);return{selectedUsers:r,allVisibleSelected:e.length>0&&r.length===e.length,isSelected:s=>t.has(s),toggle(s){n(i=>{const a=new Set(i);return a.has(s)?a.delete(s):a.add(s),a})},selectAll(s){n(s?new Set(e.map(i=>i.uid)):new Set)},replace(s){n(new Set(s))},clear(){n(new Set)}}}function hx({users:e,filter:t,onDelete:n,onComplete:r}){const s=gt(),[i,a]=h.useState(!1),[c,l]=h.useState(null),u=async()=>{const d=t.trim().length>0;if(!await s({title:`Delete ${e.length} ${e.length===1?"user":"users"}?`,body:d?`Only the ${e.length} users shown by the current filter will be deleted.`:`This will permanently delete the ${e.length} selected users.`,destructive:!0,confirmLabel:"Delete users"}))return;a(!0),l(null);const f=await dx(e,n);a(!1),l(f.length>0?`Could not delete ${f.length} selected user(s).`:null),r(f)};return o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:"studio-selection-delete",disabled:i,onClick:()=>void u(),children:i?"Deleting…":"Delete"}),c?o.jsx("span",{className:"auth-sub__error",children:c}):null]})}function Kc(e){if(!e)return"never";const t=new Date(e).getTime();if(Number.isNaN(t))return"never";const n=Math.max(0,Math.round((Date.now()-t)/1e3));if(n<45)return"just now";const r=Math.round(n/60);if(r<60)return`${r}m ago`;const s=Math.round(r/60);return s<24?`${s}h ago`:`${Math.round(s/24)}d ago`}function Hc(e){if(!e)return"unknown";const t=new Date(e);return Number.isNaN(t.getTime())?"unknown":t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}function px(e){const t=e.isAnonymous&&!e.email,n=e.email??e.phoneNumber??(t?"anonymous":e.uid);return o.jsxs("span",{className:t?"auth-ident auth-ident--anon":"auth-ident",children:[o.jsx("span",{className:"auth-ident__primary",title:n,children:n}),o.jsx("span",{className:"auth-ident__uid",title:e.uid,children:e.uid})]})}function mx({auth:e}={}){const t=$e(),n=Oe(),r=e??(n.status==="ready"?n.handles.auth:null),s=n.status==="ready"?n.authApi:void 0;if(!r)return o.jsx("div",{className:"auth-surface","data-pyric-ui":"auth-surface",children:o.jsx(wx,{status:t.status})});const i=o.jsx(gs,{children:o.jsx(yx,{auth:r})});return s?o.jsx(rc,{value:s,children:i}):i}function yx({auth:e}){const{users:t,totalCount:n,isLoading:r,error:s,filter:i,setFilter:a,createUser:c,updateUser:l,deleteUser:u}=bs(e),d=Un(),p=d.target?.view==="auth"?d.target.uid:null,f=b=>d.navigate({view:"auth",uid:b}),m=h.useMemo(()=>t.find(b=>b.uid===p)??null,[t,p]),[y,g]=h.useState(!1),v=fx(t);return o.jsxs("div",{className:"auth-surface","data-pyric-ui":"auth-surface",children:[o.jsxs("div",{className:"auth-sub",children:[o.jsxs("span",{className:"auth-sub__h",children:["users ",o.jsxs("span",{className:"auth-sub__n",children:["· ",n]})]}),o.jsx("input",{className:"auth-sub__filter",value:i,onChange:b=>a(b.target.value),placeholder:"filter users…","aria-label":"Filter users"}),o.jsx("div",{className:"auth-sub__right",children:v.selectedUsers.length>0?o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"studio-selection-count",children:[v.selectedUsers.length," selected"]}),o.jsx(hx,{users:v.selectedUsers,filter:i,onDelete:b=>Promise.resolve(u(b)),onComplete:b=>{v.replace(b),p&&!b.includes(p)&&f(null)}}),o.jsx("button",{type:"button",className:"auth-sub__clear",onClick:v.clear,children:"Clear selection"})]}):o.jsx("button",{type:"button",className:"auth-sub__add",onClick:()=>{g(!0),f(null)},children:"Add user"})})]}),o.jsxs("div",{className:"auth-body","data-auth-level":m||y?"detail":"list",children:[o.jsx("div",{className:"auth-list",children:o.jsx(cc,{users:t,isLoading:r,error:s,filter:i,onSelect:b=>{g(!1),f(b.uid)},renderIdentifier:px,formatCreatedAt:Hc,formatLastLoginAt:Kc,renderSelectionHeader:o.jsx("label",{className:"auth-select",title:"Select all shown users",children:o.jsx("input",{type:"checkbox","aria-label":"Select all shown users",checked:v.allVisibleSelected,onChange:b=>v.selectAll(b.currentTarget.checked)})}),renderSelection:b=>o.jsx("label",{className:"auth-select",title:`Select ${b.uid}`,children:o.jsx("input",{type:"checkbox","aria-label":`Select ${b.uid}`,checked:v.isSelected(b.uid),onChange:()=>v.toggle(b.uid)})}),emptyState:o.jsx("p",{className:"auth-zero",children:"No users yet. Sign-ins from the app, agent-seeded users, and “Add user” all land here."}),noResultsState:o.jsxs("p",{className:"auth-zero",children:["No users match “",i,"”."]})})}),o.jsx("div",{className:"auth-detail",children:y?o.jsx(bx,{onCancel:()=>g(!1),onCreate:async b=>{const w=await Promise.resolve(c(b));g(!1),f(w.uid)}}):m?o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:"auth-back",onClick:()=>f(null),"aria-label":"Back to users",children:"‹ Users"}),o.jsx(vx,{user:m,onSave:b=>{b.mode==="edit"&&l(b.uid,b.request)},onProvidersChange:async b=>{await Promise.resolve(l(m.uid,{providerUserInfo:b}))},onDelete:()=>{u(m.uid),f(null)}},m.uid)]}):o.jsx("div",{className:"auth-detail__empty",children:o.jsx("p",{className:"auth-zero",children:"Select a user to view and edit."})})})]})]})}function bx({onCreate:e,onCancel:t}){const[n,r]=h.useState(null),s=i=>{i.mode==="create"&&(r(null),e(i.request).catch(a=>{r(a instanceof Error?a:new Error(String(a)))}))};return o.jsxs("div",{className:"auth-editor","data-pyric-ui":"auth-create-user",children:[o.jsxs("div",{className:"auth-editor__head",children:[o.jsx("div",{className:"auth-editor__who",children:"New user"}),o.jsx("div",{className:"auth-editor__meta",children:"Created without signing in — admin semantics, like the emulator’s add-user flow."})]}),o.jsx(lc,{onSubmit:s,onCancel:t,submitLabel:"Create user",children:n?o.jsx("p",{className:"auth-save auth-save--error",role:"alert",children:n.message}):null})]})}const aa=[...Vo];function gx({user:e,onChange:t}){const[n,r]=h.useState(null),[s,i]=h.useState(""),a=e.providerUserInfo.map(m=>m.providerId),c=a.includes("password"),l=a.filter(m=>m!=="password"),u=l.filter(m=>!aa.includes(m)),d=m=>{r(null),t(m.map(y=>({providerId:y}))).catch(y=>{r(y instanceof Error?y:new Error(String(y)))})},p=(m,y)=>{d(y?[...l,m]:l.filter(g=>g!==m))},f=()=>{const m=s.trim();m&&(i(""),!l.includes(m)&&d([...l,m]))};return o.jsxs("section",{className:"auth-providers-editor","aria-label":"Sign-in providers",children:[o.jsx("div",{className:"auth-group",children:"Sign-in providers"}),o.jsx("div",{className:"auth-providers-editor__list",children:[...aa,...u].map(m=>o.jsxs("label",{className:"auth-provider-row","data-pyric-provider-id":m,children:[o.jsx("input",{type:"checkbox",checked:l.includes(m),onChange:y=>p(m,y.target.checked)}),o.jsx("span",{className:"auth-provider-row__label",children:yn(m)}),o.jsx("span",{className:"auth-provider-row__id",children:m})]},m))}),c||e.isAnonymous?o.jsx("p",{className:"auth-providers-editor__derived",children:c?"Password is linked by the password credential above.":"Anonymous — the provider lives on the token, not the record."}):null,o.jsx("div",{className:"auth-provider-custom",children:o.jsxs("label",{className:"auth-provider-custom__field",children:[o.jsx("span",{className:"auth-provider-custom__label",children:"Custom provider ID"}),o.jsxs("span",{className:"auth-provider-custom__row",children:[o.jsx("input",{type:"text",value:s,placeholder:"oidc.my-provider",onChange:m=>i(m.target.value),onKeyDown:m=>{m.key==="Enter"&&(m.preventDefault(),f())}}),o.jsx("button",{type:"button",onClick:f,disabled:!s.trim(),children:"Link"})]})]})}),n?o.jsx("p",{className:"auth-save auth-save--error",role:"alert",children:n.message}):null]})}function vx({user:e,onSave:t,onProvidersChange:n,onDelete:r}){const[s,i]=h.useState(null),[a,c]=h.useState(!1),l=p=>{i(null),c(!1);try{t(p),c(!0)}catch(f){i(f instanceof Error?f:new Error(String(f)))}},u=Hc(e.createdAt),d=Kc(e.lastLoginAt);return o.jsxs("div",{className:"auth-editor","data-pyric-user-disabled":e.disabled?"":void 0,children:[o.jsxs("div",{className:"auth-editor__head",children:[o.jsxs("div",{className:"auth-editor__who",children:[e.email??(e.isAnonymous?"anonymous":e.uid),e.disabled?o.jsx("span",{className:"auth-tag-off",children:"disabled"}):null]}),o.jsxs("div",{className:"auth-editor__uid",children:["uid · ",e.uid]}),o.jsxs("div",{className:"auth-editor__meta",children:["created ",u," · signed in ",d]})]}),o.jsx(gx,{user:e,onChange:n}),o.jsxs(lc,{initial:e,onSubmit:l,submitLabel:"Save",children:[s?o.jsx("p",{className:"auth-save auth-save--error",role:"alert",children:s.message}):null,a?o.jsx("p",{className:"auth-save auth-save--ok",children:"Saved."}):null]},e.uid),o.jsx("div",{className:"auth-editor__foot",children:o.jsx(Sg,{user:e,onDelete:r,className:"auth-del"})})]})}function wx({status:e}){const t=e==="pending"?"Seeding the sandbox…":e==="error"?"The dev-seed failed. Check the console.":"No sandbox Auth handle. Run with the dev-seed (DEV) or a live env.";return o.jsx("div",{className:"auth-detail__empty","data-pyric-ui":"auth-surface-empty",children:o.jsx("p",{className:"auth-zero",children:t})})}function xx(e){return e.operationContext.source.kind==="studio"}function jx(e,t){return t?e.filter(n=>!xx(n)):[...e]}const kx=["all","allow","deny","bypassed"];function Bn(e){return e.rulesDisposition.kind==="bypassed"?"bypassed":e.rulesDisposition.kind==="evaluated"?e.rulesDisposition.verdict:null}function _x(e,t){return t==="all"?[...e]:e.filter(n=>Bn(n)===t)}function ir(e){return e.rulesDisposition.kind==="evaluated"}function oa(e){const t=e.path;if(e.service==="storage"&&e.method==="list"&&(t===""||t==="/"))return{tab:"storage"};if(!t||t==="(service)")return null;const n=t.split("/").filter(Boolean);switch(e.service??"firestore"){case"firestore":return n.length?{tab:"firestore",rest:n}:null;case"rtdb":return{tab:"rtdb"};case"storage":return n.length?{tab:"storage",rest:n,...e.method==="list"?{query:{kind:"prefix"}}:{}}:null;case"auth":return t!=="*"?{tab:"auth",rest:[t]}:null;default:return null}}const Wr="inspect";function Gc(e){const t=e[Wr];return t||null}function Jc(e,t){const{[Wr]:n,...r}=e;return t?{...r,[Wr]:t}:r}function Sx(e,t){return Jc(e,Gc(e)===t?null:t)}const Ex=h.lazy(()=>io(()=>import("./RulesCodeEditor.XtDmHOlN.js"),__vite__mapDeps([5,1,3])));function Yc(e){return o.jsx(h.Suspense,{fallback:o.jsx(Cx,{value:e.value,minHeightRem:e.minHeightRem}),children:o.jsx(Ex,{...e})})}function Cx({value:e,minHeightRem:t=14}){return o.jsx("pre",{"data-pyric-ui":"rules-code-editor-loading",className:"overflow-auto rounded-md border border-border bg-content-bg p-3 font-mono text-xs text-slate-gray",style:{minHeight:`${t}rem`},children:e||"Loading editor…"})}function Qc({denial:e,rulesSource:t}){const n=Ry(e);return o.jsxs("div",{"data-pyric-ui":"denial-detail",className:"flex min-h-0 flex-col gap-4 overflow-auto rounded-lg border border-border bg-sidebar-bg p-5",children:[o.jsxs("section",{children:[o.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.result==="allow"?o.jsx(Or,{kind:"allow",className:"rounded bg-primary/15 px-2 py-0.5 text-xs font-semibold uppercase text-primary",children:"allowed"}):o.jsx(Or,{kind:"deny",className:"rounded bg-danger/15 px-2 py-0.5 text-xs font-semibold uppercase text-danger",children:e.unsupported?"unsupported":"denied"}),o.jsxs("span",{className:"font-mono text-sm text-soft-white",children:[e.service!=="firestore"?`${e.service} · `:"",e.method," ",e.path]})]}),o.jsx("p",{className:"text-sm leading-relaxed text-soft-white",children:n.headline})]}),n.noEvaluation?o.jsx("p",{"data-pyric-ui":"rules-debug-no-evaluation",className:"rounded-md border border-border bg-content-bg px-3 py-2 text-xs text-slate-gray",children:"No matched rule, evaluation trace, or re-run is shown because this event carries no rules verdict to ground them in."}):o.jsxs(o.Fragment,{children:[o.jsx(Nx,{denial:e,exp:n,rulesSource:t}),o.jsx(Px,{denial:e})]}),o.jsx(Ox,{denial:e})]})}function Nx({denial:e,exp:t,rulesSource:n}){const r=t.engine==="rtdb",s=t.engine==="storage";return r?o.jsx(Ux,{denial:e,exp:t,rulesSource:n}):s?o.jsx(Bx,{exp:t}):o.jsx(Dx,{denial:e,exp:t,rulesSource:n})}function Rx(e){const t="// @pyric-source-map:",n=e.indexOf(t);if(!(n!==-1))return null;const s=n+t.length,i=e.slice(s).trim();try{const a=JSON.parse(i);return Array.isArray(a)?a:null}catch{return null}}function Ax(e){const n=e.indexOf("// @pyric-source-map:");return n!==-1?e.slice(0,n).trimEnd():e}function Ix(e,t){if(e===void 0||t===void 0)return t;const s=Rx(e);if(s!==null){const a=s.find(l=>l.authoredLine===t);if(a!==void 0)return a.generatedLine}return t}function Dx({denial:e,exp:t,rulesSource:n}){const r=e.evaluatedRule?.line,s=Ix(n,r),i=n!==void 0?Ax(n):void 0,a=e.result==="allow",c=!!(i&&i.trim().length>0);return o.jsx(Ae,{label:t.implicitDeny||!t.ruleNode?"matched rule":`matched rule — ${t.ruleNode}${r?` · line ${r}`:""}`,children:c?o.jsx(Yc,{value:i,readOnly:!0,markLine:s,markKind:a?"allow":"deny",minHeightRem:12,ariaLabel:`Deployed firestore.rules — the ${a?"allowing":"denying"} rule is marked`}):o.jsx("pre",{className:"overflow-auto rounded-md border border-border bg-content-bg p-3 font-mono text-xs leading-relaxed text-slate-gray",children:[...t.ruleLines,...t.otherLines].join(`
11
+ `)||"(no trace)"})})}function Px({denial:e}){const t=$y(e);return t.length===0?null:o.jsx(Ae,{label:"show the work — how the condition evaluated",children:o.jsx("div",{"data-pyric-ui":"rules-debug-trace",className:"flex flex-col gap-0.5 overflow-auto rounded-md border border-border bg-content-bg p-3",children:t.map((n,r)=>o.jsx(Xc,{step:n},r))})})}const $x={true:"✓",false:"✗",skipped:"⊘",error:"!",value:"·"};function Xc({step:e}){const t=e.outcome==="true"?"text-diff-add":e.outcome==="false"||e.outcome==="error"?"text-danger":"text-slate-gray",n=e.outcome==="skipped"?"not evaluated (short-circuit)":e.outcome==="error"?e.error:`→ ${Zc(e.value)}`;return o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"flex items-baseline gap-2 font-mono text-xs",style:{paddingLeft:`${e.depth*.9}rem`},children:[o.jsx("span",{"aria-hidden":!0,className:`w-3 shrink-0 text-center font-bold ${t}`,children:$x[e.outcome]}),o.jsxs("span",{className:e.outcome==="skipped"?"text-slate-gray line-through":"text-soft-white",children:[e.letBinding?`let ${e.letBinding} = `:"",e.source]}),o.jsx("span",{className:"text-slate-gray",children:n}),e.inlinedFrom?o.jsxs("span",{className:"text-[0.6rem] uppercase tracking-wide text-slate-gray",children:[e.inlinedFrom,"()"]}):null]}),e.children.map((r,s)=>o.jsx(Xc,{step:r},s))]})}function Zc(e){if(e===void 0)return"undefined";try{return JSON.stringify(bn(e))}catch{return String(e)}}function Ox({denial:e}){const t=Oy(e);return o.jsx(Ae,{label:"what the rule saw (request / resource)",children:o.jsx("div",{"data-pyric-ui":"rules-debug-variables",className:"flex flex-col gap-2 rounded-md border border-border bg-content-bg p-3",children:t.map(n=>o.jsx(Mx,{variable:n},n.name))})})}function Mx({variable:e}){return o.jsxs("div",{className:"flex flex-col gap-0.5",children:[o.jsx("span",{className:"font-mono text-[0.7rem] text-primary",children:e.name}),e.present?o.jsx(el,{value:e.value}):o.jsxs("span",{className:"font-mono text-xs italic text-slate-gray",children:["absent",e.absentNote?` — ${e.absentNote}`:""]})]})}function el({value:e,depth:t=0}){const[n,r]=h.useState(t<2),s=bn(e);if(s===null||typeof s!="object")return o.jsx("span",{className:"font-mono text-xs text-soft-white",children:Zc(s)});const i=Array.isArray(s)?s.map((a,c)=>[String(c),a]):Object.entries(s);return i.length===0?o.jsx("span",{className:"font-mono text-xs text-slate-gray",children:Array.isArray(s)?"[]":"{}"}):o.jsxs("div",{className:"flex flex-col",children:[o.jsxs("button",{type:"button",onClick:()=>r(a=>!a),"aria-expanded":n,className:"flex w-fit items-center gap-1 font-mono text-xs text-slate-gray hover:text-soft-white",children:[o.jsx("span",{"aria-hidden":!0,children:n?"▾":"▸"}),o.jsx("span",{children:Array.isArray(s)?`[${i.length}]`:`{${i.length}}`})]}),n?o.jsx("div",{className:"flex flex-col gap-0.5 border-l border-border pl-3",children:i.map(([a,c])=>o.jsxs("div",{className:"flex flex-wrap items-baseline gap-2",children:[o.jsxs("span",{className:"font-mono text-xs text-slate-gray",children:[a,":"]}),o.jsx(el,{value:c,depth:t+1})]},a))}):null]})}function Tx(e,t,n,r){if(!e||!n)return;const i=e.split(/\r?\n/),a=t!==void 0&&t.length>0;let c;a?c=`".${t}"`:c=null;const l=[];for(let m=0;m<i.length;m++){const y=i[m];!y.includes(n)||!(c===null||y.includes(c))||l.push(m+1)}if(l.length===1)return l[0];if(l.length===0)return;const d=(r??"").split("/").filter(Boolean);if(d.length===0)return l[0];let p=l[0],f=-1;for(const m of l){let y=0;const g=m-2,v=Math.max(0,g-30);for(let b=g;b>=v;b--){const w=i[b];for(const x of d)w.includes(`"${x}"`)&&y++}y>f&&(f=y,p=m)}return p}function Ux({denial:e,exp:t,rulesSource:n}){const r=Tx(n,t.phase,t.ruleExpression,e.rules?.matchedPath),s=e.result==="allow",i=n!==void 0&&n.trim().length>0;let a;t.implicitDeny||!t.ruleNode?a="rule node":r!==void 0?a=`rule node — ${t.ruleNode} · line ${r}`:a=`rule node — ${t.ruleNode}`;let c;return s?c="Deployed database.rules.json — the allowing rule is marked":c="Deployed database.rules.json — the denying rule is marked",o.jsxs(o.Fragment,{children:[o.jsx(Ae,{label:a,children:i?o.jsx(Yc,{value:n,readOnly:!0,markLine:r,markKind:s?"allow":"deny",minHeightRem:12,ariaLabel:c}):o.jsxs("code",{className:"font-mono text-xs text-soft-white",children:[t.phase?`.${t.phase}`:"(no matching rule)",e.rules?.matchedPath?` at ${e.rules.matchedPath}`:""]})}),!i&&t.ruleExpression?o.jsx(Ae,{label:"rule expression",children:o.jsx("pre",{className:"overflow-auto rounded-md border border-border bg-content-bg p-3 font-mono text-xs text-slate-gray",children:t.ruleExpression})}):null,t.bindings?o.jsx(Ae,{label:"$variable bindings",children:o.jsx("code",{className:"font-mono text-xs text-soft-white",children:Object.entries(t.bindings).map(([l,u])=>`${l.startsWith("$")?l:`$${l}`} → ${u}`).join(", ")})}):null,e.rules?.reason?o.jsx(Ae,{label:"simulator reason",children:o.jsx("code",{className:"font-mono text-xs text-slate-gray",children:e.rules.reason})}):null]})}function Bx({exp:e}){return o.jsxs(Ae,{label:e.implicitDeny?"matched rule":"matched rule (match block)",children:[e.ruleNode?o.jsx("code",{className:"mb-2 block font-mono text-xs text-soft-white",children:e.ruleNode}):null,o.jsx("pre",{className:"overflow-auto rounded-md border border-border bg-content-bg p-3 font-mono text-xs leading-relaxed text-slate-gray",children:[...e.ruleLines,...e.otherLines].join(`
12
+ `)||"(no trace)"})]})}function Ae({label:e,children:t}){return o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx("span",{className:"text-[0.65rem] font-semibold uppercase tracking-wider text-slate-gray",children:e}),t]})}function ca({eventId:e,onClose:t}){const r=Vy().find(a=>a.id===e),s=r?.service??"firestore",i=Yy(s);return r?o.jsxs("div",{"data-pyric-ui":"traffic-rules-inspector",className:"traffic__inspector",children:[o.jsxs("div",{className:"traffic__inspector-bar",children:[o.jsx("span",{className:"traffic__inspector-title",children:"rules inspector"}),o.jsx("button",{type:"button",className:"traffic__inspector-close",onClick:t,"aria-label":"Close rules inspector (Esc)",children:"close (esc)"})]}),o.jsx(Qc,{denial:r,rulesSource:i})]}):o.jsxs("div",{"data-pyric-ui":"traffic-inspect-missing",className:"traffic__inspector",children:[o.jsx("p",{className:"traffic__inspector-missing",children:"This operation isn't in this session's traffic. It may be from an earlier session, or the event has aged out of the buffer."}),o.jsx("button",{type:"button",className:"traffic__inspector-close",onClick:t,children:"Back to the log"})]})}const Lx=new Intl.NumberFormat,Fx={reads:"read operations",writes:"writes",deletes:"deletes"},Vx={allows:"allowed requests",denies:"denied requests"};function la(e){return e.length<=1?e[0]??"":e.length===2?`${e[0]} and ${e[1]}`:`${e.slice(0,-1).join(", ")}, and ${e.at(-1)}`}function ua(e){return e&&`${e[0].toUpperCase()}${e.slice(1)}`}function tl(e,t){const n=e.reduce((u,d)=>u+d.total,0);if(n===0)return{total:n,headline:t.emptyHeadline,finding:t.emptyFinding};const r=Math.max(...e.map(u=>u.total)),s=e.filter(u=>u.total===r),i=`${Lx.format(n)} observed ${n===1?t.singular:t.plural}`,a=u=>t.labels[u.key]??u.label.toLowerCase();if(s.length>1){const u=s.map(a);return{total:n,headline:i,finding:s.length===e.length?`${t.evenSplitPrefix} ${la(u)}.`:`${ua(la(u))} tied for the largest share of ${t.subject} in this window.`}}const c=s[0],l=Math.round(c.total/n*100);return{total:n,headline:i,finding:`${ua(a(c))} accounted for ${l}% of ${t.subject} in this window.`}}function qx(e){return tl(e,{labels:Fx,singular:"billable operation",plural:"billable operations",subject:"activity",evenSplitPrefix:"Activity was split evenly across",emptyHeadline:"No billable activity observed",emptyFinding:"Successful reads, writes, and deletes will appear here as they happen."})}function Wx(e){return tl(e,{labels:Vx,singular:"Rules evaluation",plural:"Rules evaluations",subject:"evaluations",evenSplitPrefix:"Evaluations were split evenly between",emptyHeadline:"No Rules evaluations observed",emptyFinding:"Allow and deny decisions will appear here as Rules evaluate requests."})}const zx=new Intl.NumberFormat,Kx=new Intl.DateTimeFormat(void 0,{hour:"numeric",minute:"2-digit"});function da(e){return zx.format(e)}function St(e){return Kx.format(e)}function Hx(e){return Bn(e)==="bypassed"}function Gx(e){return e.every(t=>t.total===0)}function nl({eyebrow:e,story:t,series:n,points:r,window:s,emptyLabel:i,evidenceTitle:a,source:c,methodology:l}){const[u,d]=h.useState(()=>new Set(n.map(f=>f.key))),p=h.useCallback(f=>{d(m=>{const y=new Set(m);return y.has(f)?y.delete(f):y.add(f),y})},[]);return o.jsxs("section",{className:"traffic__metric-panel traffic__metric-panel--journal","data-pyric-ui":"traffic-metric-panel",children:[o.jsxs("header",{className:"traffic__metric-story",children:[o.jsx("p",{className:"traffic__metric-eyebrow",children:e}),o.jsx("h3",{className:"traffic__metric-headline",children:t.headline}),o.jsx("p",{className:"traffic__metric-finding",children:t.finding})]}),o.jsx(eg,{series:n,visible:u,onToggle:p,formatValue:da,className:`traffic__metric-cards traffic__metric-cards--journal traffic__metric-cards--${n.length}`}),Gx(n)?o.jsx("p",{className:"traffic__empty",children:i}):o.jsxs("div",{className:"traffic__metric-evidence",children:[o.jsxs("div",{className:"traffic__metric-evidence-header",children:[o.jsx("h4",{children:a}),o.jsxs("span",{children:[St(s.start),"–",St(s.end)]})]}),o.jsx(rg,{points:r,series:n,visible:u,omitZeroSeries:!0,formatValue:da,formatTime:St,className:"traffic__chart traffic__chart--journal"}),o.jsxs("div",{className:"traffic__metric-axis","aria-hidden":"true",children:[o.jsx("span",{children:St(s.start)}),o.jsx("span",{children:St(s.end)})]})]}),o.jsxs("footer",{className:"traffic__metric-footer",children:[o.jsx("p",{className:"traffic__metric-source",children:c}),o.jsxs("details",{className:"traffic__metric-methodology",children:[o.jsx("summary",{children:"How this is counted"}),o.jsx("div",{children:l})]})]})]})}function Jx({events:e,window:t}){const n=h.useMemo(()=>e.filter(i=>(i.service??"firestore")==="firestore"),[e]),r=$b({events:n,window:t,isAdmin:Hx}),s=h.useMemo(()=>qx(r.series),[r.series]);return o.jsx("div",{className:"traffic__metrics","data-pyric-ui":"traffic-billable-view",children:o.jsx(nl,{eyebrow:"Billable activity",story:s,series:r.series,points:r.points,window:t,emptyLabel:"No reads, writes, or deletes in this session yet.",evidenceTitle:"When the activity happened",source:"Source: Pyric Firestore sandbox events · Operation counts, not a Firebase invoice",methodology:o.jsxs(o.Fragment,{children:[o.jsxs("p",{children:["Counts successful Firestore sandbox ",o.jsx("code",{children:"get"}),"/",o.jsx("code",{children:"list"}),","," ",o.jsx("code",{children:"create"}),"/",o.jsx("code",{children:"update"}),"/",o.jsx("code",{children:"set"}),", and"," ",o.jsx("code",{children:"delete"}),"/",o.jsx("code",{children:"remove"})," operations in the displayed window. Rules-bypassed admin operations are included because they still execute."]}),o.jsxs("p",{children:[o.jsx("strong",{children:"Read ops are a proxy, not billed document reads."})," Each"," ",o.jsx("code",{children:"list"})," is counted once because the event does not report how many documents the query returned. This is observed sandbox activity, not a Firebase invoice."]})]})})})}function Yx({events:e,window:t}){const n=h.useMemo(()=>e.filter(a=>a.rulesDisposition.kind==="evaluated"),[e]),r=Ob({events:n,window:t}),s=h.useMemo(()=>r.series.filter(a=>a.key==="allows"||a.key==="denies"),[r.series]),i=h.useMemo(()=>Wx(s),[s]);return o.jsx("div",{className:"traffic__metrics","data-pyric-ui":"traffic-rules-view",children:o.jsx(nl,{eyebrow:"Rules decisions",story:i,series:s,points:r.points,window:t,emptyLabel:"No allow or deny decisions in this session yet.",evidenceTitle:"When Rules evaluated requests",source:"Source: Pyric sandbox events · Evaluated Rules dispositions only",methodology:o.jsxs(o.Fragment,{children:[o.jsxs("p",{children:["Counts only operations whose canonical Rules disposition is"," ",o.jsx("code",{children:"evaluated"}),", grouped by its ",o.jsx("code",{children:"allow"})," or ",o.jsx("code",{children:"deny"})," ","verdict."]}),o.jsxs("p",{children:[o.jsx("strong",{children:"Bypasses and runtime failures are not Rules decisions."})," Admin bypasses, services without Rules, unsupported operations, and runtime errors are excluded because Rules did not produce a verdict."]})]})})})}const Qx=[{id:"timeline",label:"Timeline"},{id:"billable",label:"Billable metrics"},{id:"rules",label:"Rules"}];function Xx(e){return e==="billable"?"billable":e==="rules"||e==="subscriptions"?"rules":"timeline"}function Zx(e,t){return e===0?"No requests occurred in this interval.":e===1?t===1?"The request in this interval was denied.":"One request occurred in this interval; it was not denied.":t===0?`${e} requests occurred in this interval; none were denied.`:t===e?`All ${e} requests in this interval were denied.`:`${e} requests occurred in this interval; ${t} ${t===1?"was":"were"} denied.`}function ej(e,t){const n=e.filter(s=>s.at>=t.start&&s.at<t.end),r=n.reduce((s,i)=>s+(i.result==="deny"?1:0),0);return{window:t,events:n,total:n.length,denies:r,finding:Zx(n.length,r)}}function tj(e,t){return e?.start===t.start&&e.end===t.end?null:t}function nj(){const{tab:e,query:t}=be();return e!=="traffic"?"timeline":Xx(t.view)}function rj(){const e=h.useSyncExternalStore(Bt,nj,()=>"timeline"),t=h.useCallback(n=>{const r={...be().query,view:n==="timeline"?void 0:n};r.view===void 0&&delete r.view,le({tab:"traffic",query:r})},[]);return[e,t]}function sj(){const e=h.useSyncExternalStore(Bt,()=>be().query.hide==="studio",()=>!1),t=h.useCallback(()=>{const n={...be().query};n.hide==="studio"?delete n.hide:n.hide="studio",le({tab:"traffic",query:n})},[]);return[e,t]}function ij(e,t){const n=Math.max(0,Math.round((t-e)/1e3));if(n<60)return`${n}s ago`;const r=Math.round(n/60);return r<60?`${r}m ago`:`${Math.round(r/60)}h ago`}function fa(e){return`${Pt(e.start)}–${Pt(e.end)}`}function aj({event:e}){const t=Bn(e);return t?o.jsx("span",{className:"traffic__verdict","data-verdict":t,children:t}):null}function oj(){return h.useSyncExternalStore(Bt,()=>Gc(be().query),()=>null)}const ar=100;function cj(){const e=Fy(),[t,n]=rj(),[r,s]=sj(),i=h.useMemo(()=>jx(e,r),[e,r]),a=e.length-i.length,[c,l]=h.useState("all"),[u,d]=h.useState(null),p=oj(),[f,m]=h.useState(ar),y=E=>{le({tab:"traffic",query:Sx(be().query,E)})},g=()=>{le({tab:"traffic",query:Jc(be().query,null)})};h.useEffect(()=>{if(!p)return;const E=R=>{R.key==="Escape"&&g()};return globalThis.addEventListener("keydown",E),()=>globalThis.removeEventListener("keydown",E)},[p]);const v=h.useMemo(()=>{const E=Date.now();if(i.length===0)return{start:E-15*6e4,end:E};let R=1/0;for(const V of i)V.at<R&&(R=V.at);return{start:Math.min(R,E-6e4),end:E+1e3}},[i]),b=v.end,w=h.useMemo(()=>u?ej(i,u):null,[i,u]),x=w?.events??i,k=h.useMemo(()=>_x(x,c).sort((E,R)=>R.at-E.at),[x,c]),{items:j}=wb({events:k}),_=j.slice(0,f),N=j.length-_.length,P=i.length>=pn,I=i.filter(E=>E.result==="deny").length,D=E=>o.jsx(aj,{event:E}),C=E=>{if(ir(E)){y(E.id);return}const R=oa(E);R&&le(R)},S=p!=null&&_.some(E=>E.type!=="group"&&E.event.id===p);return o.jsxs("section",{"data-pyric-ui":"traffic-surface",className:"traffic",children:[o.jsxs("div",{className:"traffic__tabs",role:"tablist","aria-label":"Traffic views",children:[Qx.map(E=>o.jsx("button",{type:"button",role:"tab",className:"traffic__tab","aria-selected":t===E.id,onClick:()=>n(E.id),children:E.label},E.id)),o.jsxs("button",{type:"button",className:"traffic__hide-studio","aria-pressed":r,onClick:s,title:"Hide ops issued by Pyric Studio's own viewers and editors",children:["Hide Studio traffic",r&&a>0?` (${a} hidden)`:""]})]}),t==="billable"?o.jsx(Jx,{events:i,window:v}):t==="rules"?o.jsx(Yx,{events:i,window:v}):o.jsxs(o.Fragment,{children:[o.jsx(Qb,{events:i,window:v,brush:u??void 0,onBrush:E=>{d(R=>tj(R,E)),p&&g()},liveAt:v.end,bucketCount:36,className:"traffic__timeline",header:o.jsxs("div",{className:"traffic__tl-header",children:[o.jsxs("span",{className:"traffic__tl-count",children:[i.length," requests",P?` (showing latest ${pn})`:""]}),I>0?o.jsxs("button",{type:"button",className:"traffic__tl-deny","aria-pressed":c==="deny",onClick:()=>l(E=>E==="deny"?"all":"deny"),title:"Filter the stream to denied requests",children:[I," denied"]}):null,o.jsx("span",{className:"traffic__tl-live",children:"live"})]}),axis:E=>o.jsxs("div",{className:"traffic__tl-axis",children:[o.jsx("span",{children:ij(E.start,b)}),o.jsx("span",{children:"now"})]}),renderBucketSummary:E=>o.jsxs("div",{className:"traffic__bucket-summary",children:[o.jsx("span",{children:fa(E)}),o.jsxs("strong",{children:[E.count," ",E.count===1?"request":"requests"]}),o.jsxs("span",{children:[E.denies," denied"]})]}),emptyState:o.jsx("p",{className:"traffic__empty",children:"No requests in this window yet."})}),w?o.jsxs("section",{className:"traffic__time-focus","aria-label":"Selected traffic interval","aria-live":"polite",children:[o.jsxs("div",{className:"traffic__time-focus-story",children:[o.jsx("p",{className:"traffic__time-focus-eyebrow",children:"Selected interval"}),o.jsx("h3",{children:fa(w.window)}),o.jsx("p",{children:w.finding})]}),o.jsx("button",{type:"button",onClick:()=>d(null),children:"Show all traffic"})]}):null,o.jsxs("div",{className:"traffic__filters",role:"group","aria-label":"Traffic filters",children:[o.jsx("span",{className:"traffic__filters-label","aria-hidden":"true",children:"verdict"}),kx.map(E=>o.jsx("button",{type:"button",className:"traffic__filter","aria-pressed":c===E,onClick:()=>l(E),children:E},E))]}),p&&!S?o.jsx(ca,{eventId:p,onClose:g},p):null,j.length===0?o.jsx("p",{className:"traffic__empty",children:w?c==="all"?"No requests occurred in the selected interval.":`No ${c} traffic occurred in the selected interval.`:c==="all"?"No requests yet. Reads, writes, and listeners against the sandbox stream in live.":`No ${c} traffic in this session.`}):o.jsxs("div",{className:"traffic__log","data-pyric-ui":"traffic-log","data-pyric-grouped":"","data-pyric-time-focused":w?"":void 0,children:[o.jsx("ul",{"data-pyric-traffic-log-items":"",children:_.map(E=>E.type==="group"?o.jsx("li",{"data-pyric-traffic-group-entry":"",children:o.jsx(Jb,{group:E,onSelect:R=>{const V=R;if(ir(V)){y(V.id);return}const G=oa(V);G&&le(G)},renderClassification:R=>D(R),formatTime:Pt})},E.key):o.jsxs("li",{"data-pyric-traffic-entry":"","data-pyric-traffic-id":E.event.id,"data-verdict":Bn(E.event)??void 0,children:[o.jsx(ec,{event:E.event,selected:E.event.id===p,onSelect:R=>C(R),renderClassification:R=>D(R),formatTime:Pt}),E.event.id===p&&ir(E.event)?o.jsx(ca,{eventId:p,onClose:g},p):null]},E.event.id))}),N>0?o.jsxs("button",{type:"button",className:"traffic__show-more",onClick:()=>m(E=>E+ar),children:["Show ",Math.min(N,ar)," more (",N," hidden)"]}):null]})]})]})}const ha=["amber","teal","coral","slate","olive","plum","rust","indigo","mint","sand","ash","jade"],pa=["fox","owl","lynx","crane","otter","wren","ibex","hare","newt","moth","seal","vole"];function _s(e){if(!e)return"";let t=0;for(let n=0;n<e.length;n++)t=Math.imul(t,31)+e.charCodeAt(n)>>>0;return`${ha[t%ha.length]}-${pa[(t>>>4)%pa.length]}`}function lj(e){const t=e.operationContext?.source??e.actor;if(t?.kind==="agent")return{provenance:"agent",identity:`agent:${t.name}`};if(t?.kind==="studio")return{provenance:"studio",identity:"studio"};if(t?.kind==="app-builder")return{provenance:"app-builder",identity:"builder"};const n="auth"in e&&e.auth&&typeof e.auth=="object"?e.auth.uid:void 0;return!t||t.kind==="unattributed"?{provenance:"unattributed",identity:n??"unattributed"}:{provenance:"app",identity:n??"app"}}function uj(e){return e?{tab:"firestore",rest:e.split("/").filter(Boolean)}:null}function dj(e){const{provenance:t,identity:n}=lj(e),r={id:e.id,at:e.at,provenance:t,identity:n};switch(e.kind){case"write":return{...r,denied:!1,summary:`${e.method} /${e.path}`,target:uj(e.path)};case"request":return e.result!=="deny"?null:{...r,denied:!0,summary:`denied ${e.method} /${e.path}`,target:{tab:"traffic",query:{inspect:e.id}}};case"operation":return e.result==="deny"?{...r,denied:!0,summary:`denied ${e.service} ${e.method}${e.path?` ${e.path}`:""}`,target:{tab:"traffic",query:{inspect:e.id}}}:null;case"service_mutation":{const s=e.path?` ${e.path}`:"",i=e.service==="auth"&&e.path&&e.path!=="*"?{tab:"auth",rest:[e.path]}:e.service==="storage"&&e.path?{tab:"storage",rest:e.path.split("/").filter(Boolean)}:e.service==="rtdb"?{tab:"rtdb"}:null;return{...r,denied:!1,summary:`${e.service} ${e.op}${s}`,target:i}}case"commit":return e.service!=="rtdb"||e.detail?.admin!==!0?null:{...r,denied:!1,summary:`rtdb ${e.method}${e.path?` ${e.path}`:""}`,target:{tab:"rtdb"}};case"session_boundary":return{...r,provenance:"system",identity:"sandbox",denied:!1,summary:`session ${e.phase}`,target:null};default:return null}}function fj(e,t=20){const n=[];for(let r=e.length-1;r>=0&&n.length<t;r--){const s=dj(e[r]);s&&n.push(s)}return n}const hj=20;function pj(e){le(e)}function dt({target:e,className:t,children:n,title:r}){return o.jsx("a",{className:t,href:ut(e),title:r,onClick:s=>{s.metaKey||s.ctrlKey||s.shiftKey||s.altKey||(s.preventDefault(),pj(e))},children:n})}function mj(){const e=$e(),t=Pn(),n=ps();if(t.status==="loading"||e.status==="pending")return o.jsxs("div",{className:"studio-home__status","aria-label":"Sandbox status",children:[o.jsx("span",{className:"studio-chip studio-home__skeleton-chip","aria-hidden":"true"}),o.jsx("span",{className:"studio-chip studio-home__skeleton-chip","aria-hidden":"true"})]});const s=[];if(e.status==="ready"&&t.status!=="ready"&&s.push(o.jsxs("span",{className:"studio-chip",title:"In-page seeded sandbox — no server. Data resets on reload.",children:[o.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),"dev seed · in-page"]},"seed")),t.status==="ready"){const i=t.payload;s.push(o.jsxs(dt,{className:"studio-chip",target:{tab:"settings"},title:"Persistence mode — manage in Settings.",children:[o.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),i.persist?"persisted to disk":"ephemeral"]},"persist")),i.rulesHash&&s.push(o.jsxs("span",{className:"studio-chip",title:"Hash of the rules this serve deployed to the sandbox.",children:[o.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),"rules ",i.rulesHash.slice(0,8)]},"rules"))}return n&&s.push(o.jsxs(dt,{className:"studio-chip",target:{tab:"settings"},title:`Sandbox instance ${n} — maintenance lives in Settings.`,children:[o.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),_s(n)]},"instance")),o.jsx("div",{className:"studio-home__status","aria-label":"Sandbox status",children:s})}function yj(e){return new Date(e).toLocaleTimeString(void 0,{hour12:!1})}function bj(){const e=Lt(),t=h.useMemo(()=>fj(e,hj),[e]);return o.jsxs("section",{className:"studio-panel studio-home__feed","aria-label":"Live activity",children:[o.jsxs("header",{className:"studio-home__feed-head",children:[o.jsx("h2",{className:"studio-panel__title studio-home__feed-title",children:"Activity"}),o.jsx(dt,{className:"studio-home__feed-all",target:{tab:"traffic"},children:"view all in Traffic →"})]}),t.length===0?o.jsx("p",{className:"studio-home__feed-empty",children:"No activity yet — writes, denials, and seeds show up here live."}):o.jsx("div",{className:"studio-home__feed-scroll",children:o.jsx("ol",{className:"studio-home__feed-list",children:t.map(n=>{const r=o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"studio-home__feed-ident","data-provenance":n.provenance,children:[o.jsx("span",{className:"studio-home__feed-dot","aria-hidden":"true"}),n.identity]}),o.jsx("span",{className:"studio-home__feed-summary","data-denied":n.denied?"true":void 0,children:n.summary}),o.jsx("time",{className:"studio-home__feed-time",dateTime:new Date(n.at).toISOString(),children:yj(n.at)})]});return o.jsx("li",{children:n.target?o.jsx(dt,{className:"studio-home__feed-row",target:n.target,children:r}):o.jsx("span",{className:"studio-home__feed-row",children:r})},n.id)})})})]})}const gj=["firestore","auth","rtdb","storage","traffic"];function vj(){const e=Oe(),t=Lt(),n=h.useMemo(()=>{const r={};if(e.status==="ready"){const s=e.handles.listRootCollections().length;r.firestore=`${s} collection${s===1?"":"s"}`}return t.length&&(r.traffic=`${t.length} events`),r},[e,t]);return o.jsx("div",{className:"studio-home__tiles",children:gj.map(r=>{const s=He.find(i=>i.id===r);return s?o.jsxs(dt,{className:"studio-card studio-home__tile",target:{tab:r},children:[o.jsxs("span",{className:"studio-home__tile-top",children:[o.jsx("span",{className:"studio-home__tile-label",children:s.label}),n[r]?o.jsx("span",{className:"studio-badge",children:n[r]}):null]}),o.jsx("span",{className:"studio-home__tile-desc",children:s.description})]},r):null})})}function wj(){const e=Pn(),t=e.status==="ready",n=t&&!!e.payload.bridgeUrl,r=typeof window<"u"?window.location.origin:"",s=t?e.payload.rulesHash:null;return o.jsxs(o.Fragment,{children:[o.jsxs("section",{className:"studio-card studio-home__onboard","aria-label":"Connect your agent",children:[o.jsx("span",{className:"studio-home__tile-label",children:"Connect your agent"}),o.jsx("span",{className:"studio-home__tile-desc",children:"Point Claude Code, Cursor, or any MCP client at this sandbox and its writes show up in the feed, attributed."}),o.jsx("code",{className:"studio-home__snippet",children:n?`${r}/__pyric/mcp`:"pyric sandbox --bridge # then <url>/__pyric/mcp"})]}),o.jsxs("section",{className:"studio-card studio-home__onboard","aria-label":"Seed data",children:[o.jsx("span",{className:"studio-home__tile-label",children:"Seed data"}),o.jsx("span",{className:"studio-home__tile-desc",children:"Start from a fixture, or create documents by hand in the Firestore browser."}),o.jsx("code",{className:"studio-home__snippet",children:"pyric sandbox --seed seed.json"}),o.jsx(dt,{className:"studio-home__onboard-link",target:{tab:"firestore"},children:"open Firestore →"})]}),o.jsxs("section",{className:"studio-card studio-home__onboard","aria-label":"Bring your rules",children:[o.jsx("span",{className:"studio-home__tile-label",children:"Bring your rules"}),s?o.jsxs("span",{className:"studio-home__tile-desc",children:["Your repo rules are deployed to this sandbox (",s.slice(0,8),"). Denials will appear in the feed and in Traffic."]}):o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"studio-home__tile-desc",children:"Serve your repo's rules file and every denial becomes a debuggable event."}),o.jsxs("code",{className:"studio-home__snippet",children:["pyric.json: ",'{"rules":"firestore.rules"}']})]})]})]})}function xj(){const e=Oe(),t=Lt(),n=$e(),r=e.status==="pending"||n.status==="pending",s=!r&&t.length===0&&(e.status!=="ready"||e.handles.listRootCollections().length===0);return o.jsxs("section",{className:"studio-surface studio-home","aria-label":"Home",children:[o.jsxs("div",{className:"studio-home__hero",children:[o.jsx("img",{className:"studio-home__hero-logo",src:"/__pyric/ui/pyric-logo.svg",alt:"","aria-hidden":"true"}),o.jsx("h1",{className:"studio-home__hero-title",children:"Firebase tooling for the agent era"})]}),o.jsx(Xo,{exposeFocus:Nm}),o.jsx(mj,{}),o.jsx("div",{className:"studio-home__body",children:r?o.jsxs("section",{className:"studio-panel studio-home__feed studio-home__skeleton","aria-hidden":"true",children:[o.jsx("div",{className:"studio-home__skeleton-row"}),o.jsx("div",{className:"studio-home__skeleton-row"}),o.jsx("div",{className:"studio-home__skeleton-row"})]}):s?o.jsx(wj,{}):o.jsxs(o.Fragment,{children:[o.jsx(bj,{}),o.jsx(vj,{})]})})]})}function te(e){const t=e.split("/").filter(Boolean);return t.length===0?"/":`/${t.join("/")}`}function Ge(e){return te(e).split("/").filter(Boolean)}function zr(e,t){return te([...Ge(e),...t.split("/").filter(Boolean)].join("/"))}function rl(e,t){const n=Ge(e),r=Ge(t);if(r.length<n.length)return null;for(let i=0;i<n.length;i++)if(r[i]!==n[i])return null;const s=r.slice(n.length);return s.length===0?"/":`/${s.join("/")}`}function sl(e){if(e==null)return null;if(typeof e!="object")return e;const t=e;let n=!1;const r={};for(const[s,i]of Object.entries(t)){const a=sl(i);if(a===null){n=!0;continue}a!==i&&(n=!0),r[s]=a}return Object.keys(r).length===0?null:n?r:e}function jj(e){if(typeof e=="string")return JSON.stringify(e);if(e==null)return"null";if(typeof e=="object")try{return JSON.stringify(e)??"null"}catch{return"null"}return String(e)}function Ss(e){return e===null||typeof e!="object"?!1:Object.keys(e).length>0}function il(e){return e===null||typeof e!="object"?[]:Object.entries(e).sort(([t],[n])=>t.localeCompare(n,void 0,{numeric:!0}))}function al(e,t){let n=e??null;for(const r of Ge(t)){if(n===null||typeof n!="object")return null;n=n[r]??null}return n}function kj(e){return e==null?"null":Array.isArray(e)?"array":typeof e}function Kr(e,t){if(Object.is(e,t))return!0;if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((a,c)=>Kr(a,t[c]));if(e===null||t===null||typeof e!="object"||typeof t!="object")return!1;const n=e,r=t,s=Object.keys(n),i=Object.keys(r);return s.length!==i.length?!1:s.every(a=>a in r&&Kr(n[a],r[a]))}function _j(e,t){const n=new Map,r=(s,i)=>{if(!Ss(s)){n.set(i,["leaf",s??null]);return}const a=il(s);n.set(i,["parent",a.map(([c])=>c)]);for(const[c,l]of a)r(l,zr(i,c))};return r(e,te(t)),n}function Sj(e){let t=e.trim();if(t.length===0)return"/";const n=/^[a-z][a-z0-9+.-]*:\/\/[^/?#]+/i.exec(t);return n&&(t=t.slice(n[0].length)),t=t.replace(/[?#].*$/,""),te(t)}function Ej(e){const t=Ge(e);return t.map((n,r)=>({label:n,path:`/${t.slice(0,r+1).join("/")}`}))}const Cj=["string","number","boolean","json"];function ma(e){switch(typeof e){case"string":return"string";case"number":return"number";case"boolean":return"boolean";default:return"json"}}function Nj(e,t){return t==="json"?JSON.stringify(e??null):e==null?"":String(e)}function Rj(e){if(e.trim().length===0)return"Enter a key.";const t=e.match(/[.$#[\]/]/);return t?`Keys can't contain "${t[0]}".`:null}function Aj(e,t){switch(e){case"string":return{ok:!0,value:t};case"number":{const n=t.trim();if(n.length===0)return{ok:!1,error:"Enter a number."};const r=Number(n);return Number.isNaN(r)?{ok:!1,error:`"${t}" is not a number.`}:{ok:!0,value:r}}case"boolean":{const n=t.trim().toLowerCase();return n==="true"?{ok:!0,value:!0}:n==="false"?{ok:!0,value:!1}:{ok:!1,error:"Enter true or false."}}case"json":{const n=t.trim();if(n.length===0)return{ok:!0,value:null};try{return{ok:!0,value:JSON.parse(n)}}catch(r){return{ok:!1,error:r instanceof Error?r.message:"Invalid JSON."}}}}}function ol(e){return{path:te(e),status:"loading",value:null,error:null,expanded:{},pages:{}}}function cl(e,t){const n=rl(e.path,t);return n===null?null:al(e.value,n)}function Ij(e,t){const n=te(t);return n===e.path||e.expanded[n]===!0}function Dj(e,t,n){const r=il(cl(e,t)),s=Math.min(r.length,e.pages[te(t)]??n);return{entries:r.slice(0,s),total:r.length,hiddenCount:r.length-s}}function ya(e,t){const n={};let r=!1;for(const[s,i]of Object.entries(e)){const a=rl(t.path,s);a!==null&&Ss(al(t.value,a))?n[s]=i:r=!0}return r?n:e}function ll(e,t){switch(t.type){case"navigate":{const n=te(t.path);return n===e.path?e:ol(n)}case"value":{if(te(t.path)!==e.path)return e;const n={...e,status:"live",value:sl(t.value),error:null};return n.expanded=ya(e.expanded,n),n.pages=ya(e.pages,n),n}case"error":return te(t.path)!==e.path?e:{...e,status:"error",error:t.message};case"expand":{const n=te(t.path);return n===e.path||e.expanded[n]?e:{...e,expanded:{...e.expanded,[n]:!0}}}case"collapse":{const n=te(t.path);if(!e.expanded[n])return e;const r={...e.expanded};return delete r[n],{...e,expanded:r}}case"toggle":{const n=te(t.path);return ll(e,{type:e.expanded[n]?"collapse":"expand",path:n})}case"show-more":{const n=te(t.path),r=e.pages[n]??t.pageSize;return{...e,pages:{...e.pages,[n]:r+t.pageSize}}}}}const Pj=50;function $j(e,t,n={}){const r=n.pageSize??Pj,s=te(t),[i,a]=h.useReducer(ll,s,ol),c=h.useMemo(()=>_j(i.value,i.path),[i.path,i.value]),l=ks({scope:i.path,entries:c,equals:Kr,ready:i.status==="live"});i.path!==s&&a({type:"navigate",path:s}),h.useEffect(()=>{let g=!1;const v=e.subscribeValue(s,b=>{g||a({type:"value",path:s,value:b})},b=>{g||a({type:"error",path:s,message:b instanceof Error?b.message:String(b)})});return()=>{g=!0,v()}},[e,s]);const u=h.useCallback(g=>cl(i,g),[i]),d=h.useCallback(g=>Ij(i,g),[i]),p=h.useCallback(g=>Dj(i,g,r),[i,r]),f=h.useCallback(g=>a({type:"toggle",path:g}),[]),m=h.useCallback(g=>a({type:"show-more",path:g,pageSize:r}),[r]),y=h.useCallback(g=>l.get(te(g)),[l]);return h.useMemo(()=>({state:i,pageSize:r,valueAt:u,isExpanded:d,childrenAt:p,toggle:f,showMore:m,updateAt:y}),[i,r,u,d,p,f,m,y])}function Oj({path:e,onNavigate:t,rootLabel:n="/",inputPrefix:r,className:s}){const i=te(e),[a,c]=h.useState(!1),l=h.useRef(null);h.useEffect(()=>{a&&l.current?.select()},[a]);const u=f=>{f.preventDefault(),t(Sj(l.current?.value??"")),c(!1)},d=()=>c(!1),p=Ej(i);return o.jsx("nav",{className:s,"data-pyric-ui":"rtdb-path-bar","data-rtdb-editing":a?"":void 0,"aria-label":"Database path",children:a?o.jsxs("form",{"data-rtdb-path-form":!0,onSubmit:u,children:[r?o.jsx("span",{"data-rtdb-path-prefix":!0,children:r}):null,o.jsx("input",{ref:l,"data-rtdb-path-input":!0,"aria-label":"Database path",autoFocus:!0,defaultValue:i,onBlur:d,onKeyDown:f=>{f.key==="Escape"&&d()},spellCheck:!1})]}):o.jsxs(o.Fragment,{children:[o.jsxs("ol",{"data-rtdb-crumb-list":!0,children:[o.jsx("li",{"data-rtdb-crumb-item":!0,children:o.jsx("button",{type:"button","data-rtdb-crumb":!0,"data-rtdb-crumb-root":!0,"data-pyric-current":p.length===0?"":void 0,"aria-current":p.length===0?"page":void 0,onClick:()=>t("/"),children:n})}),p.map((f,m)=>{const y=m===p.length-1;return o.jsxs("li",{"data-rtdb-crumb-item":!0,children:[o.jsx("span",{"aria-hidden":!0,"data-rtdb-crumb-separator":!0,children:"/"}),o.jsx("button",{type:"button","data-rtdb-crumb":!0,"data-pyric-current":y?"":void 0,"aria-current":y?"page":void 0,onClick:()=>t(f.path),children:f.label})]},f.path)})]}),o.jsx("button",{type:"button","data-rtdb-path-edit":!0,"aria-label":"Edit path",title:"Edit path",onClick:()=>c(!0),children:o.jsx("svg",{"aria-hidden":!0,viewBox:"0 0 16 16",width:"12",height:"12",fill:"currentColor",children:o.jsx("path",{d:"M11.7 1.3a1 1 0 0 1 1.4 0l1.6 1.6a1 1 0 0 1 0 1.4l-8.5 8.5-3.4 1.1a.5.5 0 0 1-.63-.63l1.1-3.4 8.43-8.57ZM10.9 3.5l1.6 1.6 1.2-1.2-1.6-1.6-1.2 1.2Z"})})})]})})}function Mj({tree:e,api:t,onNavigate:n,rootLabel:r="/",className:s}){const{state:i}=e,a=Ge(i.path),c=a.length===0?r:a[a.length-1];return o.jsx("div",{className:s,"data-pyric-ui":"rtdb-tree",children:i.status==="loading"?o.jsx("p",{"data-rtdb-loading":!0,children:"Loading…"}):i.status==="error"?o.jsx("p",{role:"alert","data-rtdb-error":!0,children:i.error}):o.jsx(ul,{tree:e,api:t,onNavigate:n,path:i.path,label:c,isViewRoot:!0})})}function ul({tree:e,api:t,onNavigate:n,path:r,label:s,isViewRoot:i}){const a=e.valueAt(r),c=Ss(a),l=e.isExpanded(r),u=e.updateAt(r),[d,p]=h.useState(!1),[f,m]=h.useState(!1),[y,g]=h.useState(!1),[v,b]=h.useState(null),w=async(j,_)=>{try{await j(),b(null),_()}catch(N){b(N instanceof Error?N.message:String(N))}},x=()=>{p(!0),g(!1),c&&!l&&e.toggle(r)},k=c&&l?e.childrenAt(r):null;return o.jsxs("div",{"data-rtdb-node":!0,"data-rtdb-kind":c?"parent":"leaf","data-rtdb-view-root":i?"":void 0,"data-rtdb-expanded":c&&l?"":void 0,children:[o.jsxs("div",{"data-rtdb-row":!0,"data-pyric-update":u?.kind,"data-pyric-update-cycle":u?.cycle,children:[c&&!i?o.jsx("button",{type:"button","data-rtdb-caret":!0,"aria-expanded":l,"aria-label":l?"Collapse":"Expand",onClick:()=>e.toggle(r),children:o.jsx("svg",{"aria-hidden":!0,viewBox:"0 0 8 8",width:"8",height:"8",fill:"currentColor",children:o.jsx("path",{d:"M1 0l6 4-6 4z"})})}):o.jsx("span",{"aria-hidden":!0,"data-rtdb-caret-spacer":!0}),o.jsx("button",{type:"button","data-rtdb-key":!0,"aria-label":"Key name",onClick:()=>n?.(r),children:s}),c?null:o.jsxs(o.Fragment,{children:[o.jsx("span",{"aria-hidden":!0,"data-rtdb-sep":!0,children:":"}),o.jsx("button",{type:"button","data-rtdb-value":!0,"data-rtdb-type":kj(a),title:"Edit value",onClick:()=>{m(!0),g(!1)},children:jj(a)})]}),o.jsx("span",{"data-rtdb-actions":!0,children:y?o.jsxs("span",{"data-rtdb-confirm":!0,children:[o.jsxs("span",{"data-rtdb-confirm-label":!0,children:["Delete",c?" subtree":"","?"]}),o.jsx("button",{type:"button","data-rtdb-confirm-yes":!0,onClick:()=>void w(()=>t.remove(r),()=>g(!1)),children:"Delete"}),o.jsx("button",{type:"button","data-rtdb-confirm-no":!0,onClick:()=>g(!1),children:"Cancel"})]}):o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button","data-rtdb-action-add":!0,"aria-label":`Add child to ${ba(r)}`,title:"Add child",onClick:x,children:"+"}),o.jsx("button",{type:"button","data-rtdb-action-delete":!0,"aria-label":`Delete ${ba(r)}`,title:"Delete",onClick:()=>g(!0),children:"×"})]})})]}),v?o.jsx("p",{role:"alert","data-rtdb-error":!0,children:v}):null,f?o.jsx(ga,{initialType:ma(a),initialText:Nj(a,ma(a)),submitLabel:"Save",onCancel:()=>m(!1),onSubmit:j=>w(()=>t.set(r,j),()=>m(!1))}):null,d?o.jsx(ga,{withKey:!0,initialType:"string",initialText:"",submitLabel:"Add",onCancel:()=>p(!1),onSubmit:(j,_)=>w(()=>t.set(zr(r,_),j),()=>p(!1))}):null,k?o.jsxs("ul",{"data-rtdb-children":!0,children:[k.entries.map(([j])=>o.jsx("li",{children:o.jsx(ul,{tree:e,api:t,onNavigate:n,path:zr(r,j),label:j})},j)),k.hiddenCount>0?o.jsx("li",{"data-rtdb-show-more-item":!0,children:o.jsxs("button",{type:"button","data-rtdb-show-more":!0,onClick:()=>e.showMore(r),children:["Show more (",k.hiddenCount," hidden)"]})}):null]}):null]})}function ba(e){const t=Ge(e);return t.length===0?"root":t[t.length-1]}function ga({withKey:e,initialType:t,initialText:n,submitLabel:r,onSubmit:s,onCancel:i}){const a=h.useRef(null),c=h.useRef(null),[l,u]=h.useState(t),[d,p]=h.useState(null),f=y=>{y.preventDefault();const g=a.current?.value??"";if(e){const b=Rj(g);if(b){p(b);return}}const v=Aj(l,c.current?.value??"");if(!v.ok){p(v.error);return}p(null),s(v.value,e?g.trim():void 0)},m=y=>{y.key==="Escape"&&i()};return o.jsxs("form",{"data-rtdb-editor":!0,onSubmit:f,children:[e?o.jsx("input",{ref:a,"data-rtdb-editor-key":!0,"aria-label":"Child key",placeholder:"key",autoFocus:!0,onKeyDown:m,spellCheck:!1}):null,o.jsx("select",{"data-rtdb-editor-type":!0,"aria-label":"Value type",value:l,onChange:y=>u(y.currentTarget.value),onKeyDown:m,children:Cj.map(y=>o.jsx("option",{value:y,children:y},y))}),l==="boolean"?o.jsxs("select",{ref:c,"data-rtdb-editor-value":!0,"aria-label":"Value",defaultValue:n.trim().toLowerCase()==="true"?"true":"false",onKeyDown:m,children:[o.jsx("option",{value:"true",children:"true"}),o.jsx("option",{value:"false",children:"false"})]}):o.jsx("input",{ref:c,"data-rtdb-editor-value":!0,"aria-label":"Value",placeholder:l==="json"?'{ "key": "value" }':"value",autoFocus:!e,defaultValue:n,onKeyDown:m,spellCheck:!1}),o.jsx("button",{type:"submit","data-rtdb-editor-save":!0,children:r}),o.jsx("button",{type:"button","data-rtdb-editor-cancel":!0,onClick:i,children:"Cancel"}),d?o.jsx("span",{role:"alert","data-rtdb-editor-error":!0,children:d}):null]})}function Tj(){const e=pe(),t=e.status==="ready"?e.env.live:void 0;return o.jsxs("section",{className:"studio-surface grid gap-4","aria-labelledby":"rtdb-title",children:[o.jsxs("div",{className:"studio-surface__intro",children:[o.jsx("p",{className:"studio-surface__eyebrow",children:"RTDB"}),o.jsx("h1",{id:"rtdb-title",className:"studio-surface__title",children:"RTDB"}),o.jsx("p",{className:"studio-surface__copy",children:"Browse and edit RTDB data in the shared sandbox."})]}),t?o.jsx(Bj,{live:t}):o.jsx(Uj,{})]})}function Uj(){return o.jsxs("div",{className:"rounded-md border border-dashed border-line bg-panel p-8 text-center",children:[o.jsx("span",{className:"rounded-full border border-line px-3 py-1 text-xs uppercase tracking-wide text-muted",children:"Shared worker pending"}),o.jsx("p",{className:"mx-auto mt-3 max-w-md text-sm leading-relaxed text-muted",children:"The RTDB viewer goes live once Studio connects to the shared sandbox worker."})]})}function Bj({live:e}){const[t,n]=h.useState("/"),r=_s(ps()),s=r?`${r}-sandbox`:"sandbox",i=h.useMemo(()=>({set:(c,l)=>e.setRtdbValue(c,l),remove:c=>e.deleteRtdbValue(c),subscribeValue:(c,l,u)=>e.subscribeRtdbValue(c,l,u)}),[e]),a=$j(i,t);return o.jsxs("div",{className:"rtdb",children:[o.jsx(Oj,{className:"rtdb__pathbar",path:t,onNavigate:n,rootLabel:s,inputPrefix:s}),o.jsx(Mj,{className:"rtdb__tree",tree:a,api:i,onNavigate:n,rootLabel:s})]})}function Lj(e){if(e===null)return null;const t={collections:0,users:0,objects:0,rtdbKeys:0};for(const n of e)n.kind==="collection"?t.collections++:n.kind==="user"?t.users++:n.kind==="object"?t.objects++:n.kind==="rtdb-key"&&t.rtdbKeys++;return t}function Yt(e,t,n=`${t}s`){return`${e} ${e===1?t:n}`}function Fj(e){if(e===null)return"measuring…";const t=[];return e.collections&&t.push(Yt(e.collections,"collection")),e.users&&t.push(Yt(e.users,"user")),e.objects&&t.push(Yt(e.objects,"file")),e.rtdbKeys&&t.push(Yt(e.rtdbKeys,"RTDB key")),t.length?t.join(" · "):"empty — no data yet"}function Ln(){return{width:15,height:15,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.7,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0}}function Vj(){return o.jsxs("svg",{...Ln(),children:[o.jsx("path",{d:"M12 4v10"}),o.jsx("path",{d:"M8 10l4 4 4-4"}),o.jsx("path",{d:"M4 19h16"})]})}function qj(){return o.jsxs("svg",{...Ln(),children:[o.jsx("path",{d:"M12 14V4"}),o.jsx("path",{d:"M8 8l4-4 4 4"}),o.jsx("path",{d:"M4 19h16"})]})}function Wj(){return o.jsxs("svg",{...Ln(),children:[o.jsx("circle",{cx:"7",cy:"6",r:"2.4"}),o.jsx("circle",{cx:"7",cy:"18",r:"2.4"}),o.jsx("circle",{cx:"17",cy:"8",r:"2.4"}),o.jsx("path",{d:"M7 8.4v7.2"}),o.jsx("path",{d:"M17 10.4c0 3-4 3.6-7 4.4"})]})}function zj(){return o.jsxs("svg",{...Ln(),children:[o.jsx("path",{d:"M4 5v5h5"}),o.jsx("path",{d:"M4.6 10a8 8 0 1 0 1.7-5.3"})]})}function Qt({glyph:e,name:t,caption:n,disabled:r,danger:s,onClick:i}){return o.jsxs("button",{type:"button",className:"studio-sandbox__action","data-danger":s?"true":void 0,disabled:r,onClick:i,children:[o.jsxs("span",{className:"studio-sandbox__action-top",children:[e,o.jsx("span",{className:"studio-sandbox__action-name",children:t})]}),o.jsx("span",{className:"studio-sandbox__action-caption",children:n})]})}function Kj(){const e=Ky(),t=Hy(),n=Gy(),r=Jy(),s=Pn(),i=h.useRef(null),a=_s(ps()),[c,l]=h.useState(!1),[u,d]=h.useState(!1),[p,f]=h.useState(!1),[m,y]=h.useState(!1),[g,v]=h.useState(""),b=Qo(),{ensure:w}=b;h.useEffect(()=>w(),[w]);const x=Lj(b.entries),k=Fj(x),j=s.status==="ready"?s.payload.persist?"persisted to disk":"ephemeral":"in-page · resets on reload",_=async()=>{const S=await t();if(!S||typeof document>"u")return;const E=URL.createObjectURL(new Blob([S],{type:"application/json"})),R=document.createElement("a");R.href=E,R.download=`pyric-sandbox-${a||"export"}.json`,R.click(),URL.revokeObjectURL(E)},N=async S=>{const E=S.target.files?.[0];if(S.target.value="",!!E&&!(typeof window<"u"&&!window.confirm("Import replaces all data in this sandbox. This cannot be undone. Continue?"))){d(!0);try{await n(await E.text())}finally{d(!1)}}},P=async()=>{f(!1),l(!0);try{await e()}finally{l(!1)}},I=async()=>{const S=g.trim();S&&(await r.save(S),v(""),y(!1))},D=async S=>{typeof window<"u"&&!window.confirm(`Switch to branch "${S}"? This replaces the current sandbox state.`)||await r.switchTo(S)},C=async S=>{typeof window<"u"&&!window.confirm(`Delete branch "${S}"?`)||await r.remove(S)};return o.jsxs("section",{className:"studio-surface studio-settings","aria-labelledby":"settings-title",children:[o.jsxs("div",{className:"studio-surface__intro",children:[o.jsx("p",{className:"studio-surface__eyebrow",children:"Settings"}),o.jsx("h1",{id:"settings-title",className:"studio-surface__title",children:"Configuration and maintenance."}),o.jsx("p",{className:"studio-surface__copy",children:"Global controls live here so service surfaces can stay focused on their primary work."})]}),o.jsx("div",{className:"studio-settings__grid",children:o.jsxs("section",{className:"studio-panel studio-settings__panel","aria-labelledby":"settings-sandbox-title",children:[o.jsx("h2",{id:"settings-sandbox-title",className:"studio-panel__title",children:"Sandbox"}),o.jsxs("div",{className:"studio-sandbox__live","aria-label":"Sandbox contents",children:[o.jsx("span",{className:"studio-sandbox__instance mono",children:a||"local"}),o.jsx("span",{className:"studio-sandbox__inventory",children:k}),o.jsx("span",{className:"studio-sandbox__persist",children:j})]}),o.jsxs("div",{className:"studio-sandbox__actions",children:[o.jsx(Qt,{glyph:o.jsx(Vj,{}),name:"Export",caption:"Downloads all of this as one file.",onClick:()=>void _()}),o.jsx(Qt,{glyph:o.jsx(qj,{}),name:u?"Importing…":"Import",caption:"A chosen file replaces everything here.",disabled:u,onClick:()=>i.current?.click()}),o.jsx(Qt,{glyph:o.jsx(Wj,{}),name:"Save branch",caption:"Keeps a copy you can return to.",onClick:()=>y(S=>!S)}),o.jsx(Qt,{glyph:o.jsx(zj,{}),name:c?"Resetting…":"Reset session",caption:"Everything returns to the seeded start.",disabled:c,danger:!0,onClick:()=>f(!0)})]}),o.jsx("input",{ref:i,type:"file",accept:"application/json,.json",className:"studio-settings__file",onChange:N}),m?o.jsxs("form",{className:"studio-sandbox__name-row",onSubmit:S=>{S.preventDefault(),I()},children:[o.jsx("input",{className:"studio-sandbox__name-input",type:"text",value:g,placeholder:"branch name","aria-label":"Branch name",autoFocus:!0,onChange:S=>v(S.target.value),onKeyDown:S=>{S.key==="Escape"&&(y(!1),v(""))}}),o.jsx("button",{type:"submit",className:"studio-button",disabled:!g.trim(),children:"Save"}),o.jsx("button",{type:"button",className:"studio-button",onClick:()=>{y(!1),v("")},children:"Cancel"})]}):null,p?o.jsxs("div",{className:"studio-sandbox__confirm",role:"alert",children:[o.jsx("span",{className:"studio-sandbox__confirm-copy",children:x&&k!=="empty — no data yet"?`This erases ${k}.`:"This erases everything in this sandbox."}),o.jsxs("span",{className:"studio-sandbox__confirm-actions",children:[o.jsx("button",{type:"button",className:"studio-button studio-button--danger",onClick:()=>void P(),children:"Erase and reseed"}),o.jsx("button",{type:"button",className:"studio-button",onClick:()=>f(!1),children:"Keep"})]})]}):null,r.branches.length>0?o.jsx("div",{className:"studio-settings__branches",children:r.branches.map(S=>o.jsxs("div",{className:"studio-settings__branch",children:[o.jsx("span",{className:"mono",children:S}),o.jsxs("span",{className:"studio-settings__branch-actions",children:[o.jsx("button",{type:"button",className:"studio-button",onClick:()=>void D(S),children:"Switch"}),o.jsx("button",{type:"button",className:"studio-button",onClick:()=>void C(S),children:"Delete"})]})]},S))}):o.jsx("p",{className:"studio-sandbox__branches-empty",children:"No branches yet — Save branch keeps this exact state to come back to."})]})})]})}function Xt(e){return e===null?"absent":e===void 0?"unknown":typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):JSON.stringify(e)}function Hj(e){const t=e.stateDiff;if(!t)return"No state evidence";if(!t.changed)return e.mutation.output!==void 0?"Read result captured":"No state change";if(t.before&&t.after&&typeof t.before=="object"&&typeof t.after=="object"&&!Array.isArray(t.before)&&!Array.isArray(t.after)){const n=t.before,r=t.after,i=[...new Set([...Object.keys(n),...Object.keys(r)])].filter(a=>JSON.stringify(n[a])!==JSON.stringify(r[a]));if(i.length>0&&i.length<=3)return i.map(a=>`${a}: ${Xt(n[a])} -> ${Xt(r[a])}`).join(", ")}return`${Xt(t.before)} -> ${Xt(t.after)}`}function Gj(e){return e.results.map(t=>({id:t.probeId,service:t.control.operation.service,operation:`${t.mutation.operation.method} ${t.mutation.operation.path}`,actor:t.actorEvidence.uid??(t.actorEvidence.acquisition==="anonymous-request"?"anonymous":t.actorEvidence.actorId),expected:t.invariant.expected,observed:t.mutation.decision,classification:t.classification,impact:Hj(t),supported:t.qualification.supported}))}function Jj(e){const t=e.mutation.events.find(a=>a.result==="allow"||a.result==="deny"||a.result==="unsupported");if(!t)return null;const n=t.result,r={id:t.id??`${e.probeId}-decision`,at:t.at??0,result:n,method:t.method??t.op??e.mutation.operation.method,service:t.service??e.mutation.operation.service,path:t.path??e.mutation.operation.path,auth:t.auth??null,reasons:t.reasons??[],origin:t.origin??"user",unsupported:n==="unsupported"};t.matchedRule&&(r.matchedRule=t.matchedRule),t.evaluatedRule&&(r.evaluatedRule=t.evaluatedRule),t.rules&&(r.rules=t.rules),t.resourceBefore&&(r.resourceBefore=t.resourceBefore);const s=t.request,i=s?.resourceData??s?.data;return i!==void 0&&(r.resourceData=i),r}const Yj="pyric:assurance-campaign",Qj="pyric-assurance-v1",Hr=new Set;let va=!1,wa;function xa(e){for(const t of Hr)t(e)}function ja(e){return!!e&&typeof e=="object"&&e.schema==="pyric.assurance.visualization.v1"&&typeof e.campaignId=="string"}function Xj(){if(!(va||typeof document>"u")){va=!0,globalThis.addEventListener(Yj,e=>{const t=e.detail;ja(t)&&xa(t)});try{wa=new BroadcastChannel(Qj),wa.onmessage=e=>{ja(e.data)&&xa(e.data)}}catch{}}}function Zj(e){return Xj(),Hr.add(e),()=>Hr.delete(e)}function or(e){return{campaignId:"collaboration-local-v1",probeId:e.id,targetHash:"fnv1a32-7f4c911a",actorEvidence:{actorId:"member-b",acquisition:"password",reachability:"reachable",uid:"mallory"},invariant:{id:`${e.id}-invariant`,service:e.service,statement:e.statement,expected:"DENY",source:"declared",confidence:"authoritative"},mutationSpec:{dimension:e.service==="firestore"?"payload":"path",description:e.description,operation:e.mutation},control:{operation:e.control,decision:"ALLOW",events:[]},mutation:{operation:e.mutation,decision:"ALLOW",events:e.service==="firestore"?[{id:"req-firestore-owner-transfer",at:100,kind:"request",service:"firestore",method:"update",path:"rooms/r1",result:"allow",auth:{uid:"mallory",token:{}},reasons:["Rule #1 (update) -> ALLOW"],origin:"user",request:{resourceData:{ownerId:"mallory"}},resourceBefore:{exists:!0,data:e.before},matchedRule:{ruleIndex:0,operations:["update"]}}]:[]},stateDiff:{changed:!0,before:e.before,after:e.after},qualification:{engine:"pyric-local-sandboxes",supported:!0,requirements:[{id:`${e.service}.local-supported-subset`,supported:!0,reason:"This probe stays within the supported local evaluator subset."}]},classification:"local-counterexample"}}const ek=[or({id:"firestore-owner-transfer",service:"firestore",control:{service:"firestore",method:"update",path:"rooms/r1",data:{title:"Edited"}},mutation:{service:"firestore",method:"update",path:"rooms/r1",data:{ownerId:"mallory"}},statement:"A non-owner room member must not change ownerId.",description:"Changed only the updated field from title to ownerId.",before:{ownerId:"alice",title:"Original title"},after:{ownerId:"mallory",title:"Original title"}}),or({id:"rtdb-other-role",service:"rtdb",control:{service:"rtdb",method:"set",path:"/rooms/r1/members/mallory/status",data:"online"},mutation:{service:"rtdb",method:"set",path:"/rooms/r1/members/alice/role",data:"online"},statement:"A member must not change another member's role.",description:"Changed only the target path from own status to another member role.",before:"owner",after:"online"}),or({id:"storage-overwrite-owner",service:"storage",control:{service:"storage",method:"upload",path:"b/pyric-default/o/rooms/r1/mallory/note.json",dataBase64:"bWFsbG9yeQ==",customMetadata:{owner:"mallory"}},mutation:{service:"storage",method:"upload",path:"b/pyric-default/o/rooms/r1/alice/private.json",dataBase64:"bWFsbG9yeQ==",customMetadata:{owner:"mallory"}},statement:"A member must not overwrite an object owned by another actor.",description:"Changed only the target from a new own object to an existing other-owned object.",before:{text:"alice-secret",customMetadata:{owner:"alice"}},after:{text:"mallory",customMetadata:{owner:"mallory"}}})],wk=ek.map(e=>({...e,campaignId:"collaboration-local-v1-fixed",targetHash:"fnv1a32-a9f18f23",mutation:{...e.mutation,decision:"DENY",events:[]},stateDiff:void 0,classification:"no-counterexample"}));const Gr="pyric:assurance:campaigns",dl="pyric:assurance:campaign:";function tk(e){return!!e&&typeof e=="object"&&e.schema==="pyric.assurance.visualization.v1"&&typeof e.campaignId=="string"}function nk(){if(typeof sessionStorage>"u")return[];try{const e=JSON.parse(sessionStorage.getItem(Gr)??"[]");if(!Array.isArray(e))return[];const t=e.map(n=>sessionStorage.getItem(`${dl}${String(n)}`)).filter(n=>!!n).map(n=>JSON.parse(n)).filter(tk);return t.length,t}catch{return[]}}function rk(e){if(!(typeof sessionStorage>"u"))try{const t=JSON.parse(sessionStorage.getItem(Gr)??"[]"),n=Array.isArray(t)?t.map(String):[];n.includes(e.campaignId)||n.push(e.campaignId),sessionStorage.setItem(Gr,JSON.stringify(n)),sessionStorage.setItem(`${dl}${e.campaignId}`,JSON.stringify(e))}catch{}}function sk(e,t){const n=e.findIndex(s=>s.campaignId===t.campaignId);if(n===-1)return[...e,t];const r=[...e];return r[n]=t,r}function ik(){const[e,t]=h.useState(nk);return h.useEffect(()=>{const r=Zj(s=>{rk(s),t(i=>sk(i,s))});return()=>{r()}},[]),e}function ak(e,t){return e!==t?"assurance-verdict--mismatch":t==="ALLOW"?"assurance-verdict--allow":"assurance-verdict--deny"}function ok(e){return e.replaceAll("-"," ")}function ka({value:e}){return o.jsx("pre",{className:"assurance-evidence__json",children:JSON.stringify(e,null,2)})}function ck(){return o.jsxs("section",{className:"assurance-empty","aria-labelledby":"assurance-empty-title",children:[o.jsx("p",{className:"assurance-surface__eyebrow",children:"Local authorization assurance"}),o.jsx("h1",{id:"assurance-empty-title",children:"No campaign in this Studio session"}),o.jsx("p",{children:"Campaigns appear here as the local assurance tools map actors, run controls, and test explicit security invariants."}),o.jsx("span",{className:"assurance-local-state",children:"Pyric sandboxes only | network off"})]})}function _a({attachment:e}){return e?o.jsxs("div",{className:"assurance-attachment","aria-label":"Attached sandbox inventory",children:[o.jsxs("span",{children:[o.jsx("strong",{children:e.source.origin}),"read-only clone"]}),o.jsxs("span",{children:[o.jsx("strong",{children:e.inventory.firestoreDocuments}),"Firestore docs"]}),o.jsxs("span",{children:[o.jsx("strong",{children:e.inventory.authUsers}),"Auth users"]}),o.jsxs("span",{children:[o.jsx("strong",{children:e.inventory.rtdbPresent?"present":"empty"}),"RTDB"]})]}):null}function lk({campaigns:e}){const t=ik(),n=e??t,r=be().query,[s,i]=h.useState(r.campaign??n.find(x=>x.report)?.campaignId??n[0]?.campaignId??""),a=n.find(x=>x.campaignId===s)??n[0],c=h.useMemo(()=>a?.report?Gj(a.report):[],[a]),[l,u]=h.useState(r.probe??c[0]?.id??"");if(h.useEffect(()=>{!s&&n[0]&&i(n[0].campaignId)},[s,n]),h.useEffect(()=>{c.some(x=>x.id===l)||u(c[0]?.id??"")},[c,l]),!a)return o.jsx(ck,{});const d=a.context?.attachment,p=a.report;if(!p)return o.jsxs("section",{className:"assurance-empty","aria-labelledby":"assurance-mapped-title",children:[o.jsx("p",{className:"assurance-surface__eyebrow",children:a.campaignId}),o.jsx("h1",{id:"assurance-mapped-title",children:"Campaign mapped, awaiting its first run"}),o.jsxs("p",{children:[a.observations.length," known-good operation(s) and"," ",a.probes.length," probe(s) are available."]}),o.jsx(_a,{attachment:d}),d?.coverageGaps.length?o.jsx("ul",{className:"assurance-coverage-gaps","aria-label":"Attachment coverage gaps",children:d.coverageGaps.map(x=>o.jsxs("li",{children:[o.jsx("code",{children:x.service}),x.reason]},x.code))}):null,o.jsx("span",{className:"assurance-local-state",children:"Pyric sandboxes only | network off"})]});const f=c.find(x=>x.id===l)??c[0],m=p.results.find(x=>x.probeId===f?.id),y=m?Jj(m):null,g=a.verifications?.at(-1),v=g!==void 0&&g.summary.controlsPassed===g.summary.probes&&g.summary.noCounterexamples===g.summary.probes&&g.summary.localCounterexamples===0&&g.summary.engineGaps===0&&g.summary.invalidProbes===0;function b(x){i(x);const j=n.find(_=>_.campaignId===x)?.report?.results[0]?.probeId??"";u(j),fn({tab:"assurance",query:{campaign:x,probe:j||void 0}})}function w(x){u(x.id),fn({tab:"assurance",query:{campaign:a.campaignId,probe:x.id}})}return o.jsxs("section",{className:"assurance-surface","aria-labelledby":"assurance-title",children:[o.jsxs("header",{className:"assurance-surface__header",children:[o.jsxs("div",{children:[o.jsx("p",{className:"assurance-surface__eyebrow",children:"Local authorization assurance"}),o.jsx("h1",{id:"assurance-title",children:a.campaignId})]}),o.jsxs("div",{className:"assurance-surface__controls",children:[n.length>1?o.jsxs("label",{children:[o.jsx("span",{children:"Campaign"}),o.jsx("select",{value:a.campaignId,onChange:x=>b(x.target.value),children:n.map(x=>o.jsx("option",{value:x.campaignId,children:x.campaignId},x.campaignId))})]}):null,o.jsx("span",{className:"assurance-local-state",children:"Pyric sandboxes only | network off"})]})]}),o.jsx(_a,{attachment:d}),o.jsxs("div",{className:"assurance-summary","aria-label":"Campaign summary",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Controls"}),o.jsxs("strong",{children:[p.summary.controlsPassed,"/",p.summary.probes]})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Counterexamples"}),o.jsx("strong",{children:p.summary.localCounterexamples})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Candidate signals"}),o.jsx("strong",{children:p.summary.candidateSignals})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Engine gaps"}),o.jsx("strong",{children:p.summary.engineGaps})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Coverage gaps"}),o.jsx("strong",{children:d?.coverageGaps.length??0})]})]}),g?o.jsxs("div",{className:`assurance-verification-band assurance-verification-band--${v?"passed":"failed"}`,role:"status",children:[o.jsx("strong",{children:v?"Candidate rules verified":"Candidate rules need review"}),o.jsxs("span",{children:[g.summary.controlsPassed,"/",g.summary.probes," ","controls preserved"," | ",g.summary.noCounterexamples,"/",g.summary.probes," negative cases denied"]}),o.jsx("code",{children:g.campaignId})]}):null,d?.coverageGaps.length?o.jsxs("div",{className:"assurance-coverage-band",children:[o.jsxs("strong",{children:[d.coverageGaps.length," attachment gap(s)"]}),o.jsx("span",{children:d.coverageGaps.map(x=>`${x.service}: ${x.reason}`).join(" ")})]}):null,o.jsxs("div",{className:"assurance-workspace",children:[o.jsxs("section",{className:"assurance-matrix","aria-labelledby":"assurance-matrix-title",children:[o.jsxs("div",{className:"assurance-section-heading",children:[o.jsx("h2",{id:"assurance-matrix-title",children:"Expected and observed access"}),o.jsx("span",{children:p.targetHash})]}),o.jsxs("div",{className:"assurance-table",role:"table",children:[o.jsxs("div",{className:"assurance-table__header",role:"row",children:[o.jsx("span",{role:"columnheader",children:"Operation"}),o.jsx("span",{role:"columnheader",children:"Actor"}),o.jsx("span",{role:"columnheader",children:"Expected"}),o.jsx("span",{role:"columnheader",children:"Observed"}),o.jsx("span",{role:"columnheader",children:"Impact"})]}),c.map(x=>o.jsxs("button",{type:"button",className:"assurance-table__row","aria-pressed":x.id===f?.id,onClick:()=>w(x),role:"row",children:[o.jsxs("span",{role:"cell",children:[o.jsx("small",{children:x.service}),x.operation]}),o.jsx("span",{role:"cell",children:x.actor}),o.jsx("span",{role:"cell",className:`assurance-verdict ${x.expected==="ALLOW"?"assurance-verdict--allow":"assurance-verdict--deny"}`,children:x.expected}),o.jsx("span",{role:"cell",className:`assurance-verdict ${ak(x.expected,x.observed)}`,children:x.observed}),o.jsx("span",{role:"cell",children:x.impact})]},x.id))]})]}),m?o.jsxs("aside",{className:"assurance-inspector","aria-labelledby":"assurance-inspector-title",children:[o.jsxs("div",{className:"assurance-section-heading",children:[o.jsxs("div",{children:[o.jsx("span",{className:`assurance-classification assurance-classification--${m.classification}`,children:ok(m.classification)}),o.jsx("h2",{id:"assurance-inspector-title",children:m.probeId})]}),o.jsx("span",{children:m.actorEvidence.reachability})]}),o.jsxs("dl",{className:"assurance-facts",children:[o.jsxs("div",{children:[o.jsx("dt",{children:"Invariant"}),o.jsx("dd",{children:m.invariant.statement})]}),o.jsxs("div",{children:[o.jsx("dt",{children:"Mutation"}),o.jsx("dd",{children:m.mutationSpec.description})]}),o.jsxs("div",{children:[o.jsx("dt",{children:"Actor"}),o.jsxs("dd",{children:[m.actorEvidence.uid??m.actorEvidence.actorId," ","via ",m.actorEvidence.acquisition]})]}),o.jsxs("div",{children:[o.jsx("dt",{children:"Fidelity"}),o.jsx("dd",{children:m.qualification.supported?"Supported for this probe":"Engine gap"})]})]}),m.qualification.requirements.some(x=>!x.supported)?o.jsx("ul",{className:"assurance-gaps",children:m.qualification.requirements.filter(x=>!x.supported).map(x=>o.jsxs("li",{children:[o.jsx("code",{children:x.id}),x.reason]},x.id))}):null,m.stateDiff?o.jsxs("section",{className:"assurance-evidence","aria-labelledby":"assurance-state-title",children:[o.jsx("h3",{id:"assurance-state-title",children:"State evidence"}),o.jsxs("div",{className:"assurance-evidence__diff",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Before"}),o.jsx(ka,{value:m.stateDiff.before})]}),o.jsxs("div",{children:[o.jsx("span",{children:"After"}),o.jsx(ka,{value:m.stateDiff.after})]})]})]}):null,y?o.jsxs("section",{className:"assurance-rule-decision","aria-labelledby":"assurance-rule-title",children:[o.jsx("h3",{id:"assurance-rule-title",children:"Rule decision"}),o.jsx(Qc,{denial:y})]}):o.jsx("p",{className:"assurance-no-decision",children:"This service recorded operation and state evidence but no canonical rule-decision event."})]}):null]})]})}function Sa(){return An()}function fl(){return`${An()}docs`}function Ea(e){return t=>{t.metaKey||t.ctrlKey||t.shiftKey||t.altKey||(t.preventDefault(),e())}}function uk(){const[e,t]=h.useState(!1);return h.useEffect(()=>{let n=!0;return fetch(`${fl()}/index.json`,{method:"HEAD"}).then(r=>{const s=r.headers.get("content-type")??"";n&&r.ok&&s.includes("json")&&t(!0)}).catch(()=>{}),()=>{n=!1}},[]),e}function dk({id:e}){const t=km(e),n=$e(),r=[`route #${t.id}`];return n.status==="ready"?(r.push(`events: ${n.events.length}`),r.push("dev-seed: ready")):n.status==="pending"?r.push("dev-seed: seeding…"):n.status==="error"?r.push("dev-seed: error"):r.push("dev-seed: off"),o.jsxs("section",{className:"studio__placeholder","aria-labelledby":`route-${t.id}`,children:[o.jsx("p",{className:"studio__placeholder-eyebrow",children:"Surface"}),o.jsx("h2",{id:`route-${t.id}`,className:"studio__placeholder-title",children:t.label}),o.jsx("p",{className:"studio__placeholder-blurb",children:t.description}),o.jsx("div",{className:"studio__placeholder-meta",children:r.map(s=>o.jsx("span",{children:s},s))})]})}function fk({id:e}){switch(e){case"home":return o.jsx(xj,{});case"firestore":return o.jsx(cx,{});case"auth":return o.jsx(mx,{});case"storage":return o.jsx(lx,{});case"rtdb":return o.jsx(Tj,{});case"traffic":return o.jsx(cj,{});case"assurance":return o.jsx(lk,{});case"settings":return o.jsx(Kj,{});default:return o.jsx(dk,{id:e})}}function hk(){const[e,t]=Cm(jm,"home"),n=l=>t(l),[r,s]=h.useState(!1),i=uk(),a=e==="home";h.useEffect(()=>{const l=u=>{if(Am(u)){if(r){u.preventDefault(),s(!1);return}if(a){Rm()&&u.preventDefault();return}u.preventDefault(),s(!0)}};return window.addEventListener("keydown",l),()=>window.removeEventListener("keydown",l)},[a,r]),h.useEffect(()=>{a&&s(!1)},[a]),h.useEffect(()=>{document.querySelector('.studio__rail [aria-current="page"]')?.scrollIntoView({block:"nearest",inline:"center"})},[e]);const c=He.filter(l=>l.id!=="home");return o.jsxs("div",{className:"studio","data-surface":e,children:[o.jsxs("header",{className:"studio__chrome",children:[o.jsx("div",{className:"studio__bar",children:o.jsxs("div",{className:"studio__chrome-inner",children:[o.jsxs("nav",{className:"studio__nav","aria-label":"Site",children:[o.jsx("a",{className:"studio__brand",href:Sa(),"aria-label":"Pyric",children:"pyric"}),o.jsx("a",{className:"studio__nav-tab",href:Sa(),children:"Home"}),i?o.jsx("a",{className:"studio__nav-tab",href:fl(),children:"Docs"}):null,o.jsx("a",{className:"studio__nav-tab",href:ut({tab:"home"}),"aria-current":e==="home"?"page":!0,onClick:Ea(()=>n("home")),children:"Studio"})]}),o.jsx(gb,{})]})}),o.jsx("nav",{className:"studio__rail","aria-label":"Studio",children:o.jsx("div",{className:"studio__chrome-inner",children:o.jsx("div",{className:"studio__nav",children:c.map(l=>o.jsx("a",{className:"studio__nav-tab",href:ut({tab:l.id}),"aria-current":l.id===e?"page":void 0,onClick:Ea(()=>n(l.id)),children:l.label},l.id))})})})]}),o.jsx("main",{className:"studio__content","data-surface":e,children:o.jsx("div",{className:"studio__surface-slot","data-active":"true",children:o.jsx(fk,{id:e})})}),r?o.jsx(rb,{onClose:()=>s(!1)}):null]})}function pk(){return o.jsx(bm,{children:o.jsx(Id,{children:o.jsx(fm,{mode:"local",children:o.jsx(hk,{})})})})}function xk(){return o.jsx(h.StrictMode,{children:o.jsx(pk,{})})}export{xk as S,vk as a,ry as b,It as r,fe as s,_o as u};