@pyric/cli 0.1.0-alpha.27 → 0.1.0-alpha.28
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.
- package/dist/bridge/surface/arguments/assurance.d.ts +6 -6
- package/dist/bridge/surface/arguments/messaging.d.ts +2 -2
- package/dist/bridge/surface/methods/assurance/map.d.ts +6 -6
- package/dist/bridge/surface/methods/messaging/send.d.ts +4 -4
- package/dist/bridge/surface/render/discriminator-schemas.d.ts +4 -4
- package/dist/cli/index.d.ts +1 -0
- package/dist/cli/index.d.ts.map +1 -1
- package/dist/cli/index.js +15 -1
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/run.d.ts +42 -0
- package/dist/cli/run.d.ts.map +1 -0
- package/dist/cli/run.js +115 -0
- package/dist/cli/run.js.map +1 -0
- package/dist/conformance/.generated/can-i-use.d.ts.map +1 -1
- package/dist/conformance/.generated/can-i-use.js +1 -1
- package/dist/conformance/.generated/can-i-use.js.map +1 -1
- package/dist/conformance/.generated/conformance-docs.d.ts.map +1 -1
- package/dist/conformance/.generated/conformance-docs.js +1 -1
- package/dist/conformance/.generated/conformance-docs.js.map +1 -1
- package/dist/remote/local-storage-url.d.ts +2 -15
- package/dist/remote/local-storage-url.d.ts.map +1 -1
- package/dist/remote/local-storage-url.js +1 -60
- package/dist/remote/local-storage-url.js.map +1 -1
- package/dist/serve/assets/avatar-route.d.ts.map +1 -1
- package/dist/serve/assets/avatar-route.js +6 -6
- package/dist/serve/assets/avatar-route.js.map +1 -1
- package/dist/serve/assets/resolver.d.ts +3 -0
- package/dist/serve/assets/resolver.d.ts.map +1 -1
- package/dist/serve/assets/resolver.js +1 -1
- package/dist/serve/assets/resolver.js.map +1 -1
- package/dist/serve/entries/app-client.d.ts.map +1 -1
- package/dist/serve/entries/app-client.js +6 -0
- package/dist/serve/entries/app-client.js.map +1 -1
- package/dist/serve/site-ui/_astro/{app.DpzsBfos.js → app.BCNb6gMq.js} +1 -1
- package/dist/serve/site-ui/_astro/{app.CiMHEvEW.js → app.DhoRPDdN.js} +20 -20
- package/dist/serve/site-ui/_astro/{seed.BpXSRzLo.js → seed.BO5CXcqE.js} +1 -1
- package/dist/serve/site-ui/auth/index.html +1 -1
- package/dist/serve/site-ui/docs/_rhythm/index.html +1 -1
- package/dist/serve/site-ui/docs/agent/set-up-your-agent/index.html +1 -1
- package/dist/serve/site-ui/docs/agent/watch-and-review/index.html +1 -1
- package/dist/serve/site-ui/docs/agent/work-with-an-agent/index.html +1 -1
- package/dist/serve/site-ui/docs/ai-compat/index.html +1 -1
- package/dist/serve/site-ui/docs/api-reference/index.html +2 -1
- package/dist/serve/site-ui/docs/api-reference.md +1 -0
- package/dist/serve/site-ui/docs/app-compat/index.html +1 -1
- package/dist/serve/site-ui/docs/auth-compat/index.html +2 -2
- package/dist/serve/site-ui/docs/auth-compat.md +1 -1
- package/dist/serve/site-ui/docs/auth-flutter-compat/index.html +1 -1
- package/dist/serve/site-ui/docs/auth-kotlin-compat/index.html +1 -1
- package/dist/serve/site-ui/docs/auth-swift-compat/index.html +1 -1
- package/dist/serve/site-ui/docs/build/ai-logic/index.html +1 -1
- package/dist/serve/site-ui/docs/build/authentication/index.html +1 -1
- package/dist/serve/site-ui/docs/build/cloud-firestore/index.html +1 -1
- package/dist/serve/site-ui/docs/build/cloud-messaging/index.html +1 -1
- package/dist/serve/site-ui/docs/build/cloud-storage/index.html +13 -2
- package/dist/serve/site-ui/docs/build/cloud-storage.md +23 -0
- package/dist/serve/site-ui/docs/build/default-avatars/index.html +1 -1
- package/dist/serve/site-ui/docs/build/inspect-activity/index.html +1 -1
- package/dist/serve/site-ui/docs/build/realtime-database/index.html +1 -1
- package/dist/serve/site-ui/docs/conformance-scores/index.html +1 -1
- package/dist/serve/site-ui/docs/create-pyric-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/database-compat/index.html +1 -1
- package/dist/serve/site-ui/docs/examples/chess/index.html +1 -1
- package/dist/serve/site-ui/docs/examples/index.html +1 -1
- package/dist/serve/site-ui/docs/firestore-compat/index.html +1 -1
- package/dist/serve/site-ui/docs/firestore-flutter-compat/index.html +1 -1
- package/dist/serve/site-ui/docs/firestore-kotlin-compat/index.html +1 -1
- package/dist/serve/site-ui/docs/firestore-swift-compat/index.html +1 -1
- package/dist/serve/site-ui/docs/functions-rtdb-compat/index.html +1 -1
- package/dist/serve/site-ui/docs/get-started/backend-bundlers/index.html +1 -1
- package/dist/serve/site-ui/docs/get-started/flutter/index.html +1 -1
- package/dist/serve/site-ui/docs/get-started/how-the-swap-works/index.html +1 -1
- package/dist/serve/site-ui/docs/get-started/nextjs/index.html +1 -1
- package/dist/serve/site-ui/docs/get-started/node-host/index.html +1 -1
- package/dist/serve/site-ui/docs/get-started/start-building/index.html +1 -1
- package/dist/serve/site-ui/docs/get-started/vite/index.html +4 -2
- package/dist/serve/site-ui/docs/get-started/vite.md +4 -0
- package/dist/serve/site-ui/docs/index.json +50 -0
- package/dist/serve/site-ui/docs/messaging-compat/index.html +1 -1
- package/dist/serve/site-ui/docs/observe/resolve-runtime-status/index.html +1 -1
- package/dist/serve/site-ui/docs/observe/see-whats-happening/index.html +1 -1
- package/dist/serve/site-ui/docs/observe/shape-your-data/index.html +1 -1
- package/dist/serve/site-ui/docs/observe/switch-and-impersonate-identities/index.html +1 -1
- package/dist/serve/site-ui/docs/overview/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-admin-app-check-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-admin-app-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-admin-auth-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-admin-data-connect-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-admin-database-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-admin-eventarc-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-admin-extensions-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-admin-firestore-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-admin-functions-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-admin-installations-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-admin-instance-id-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-admin-machine-learning-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-admin-messaging-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-admin-phone-number-verification-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-admin-project-management-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-admin-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-admin-remote-config-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-admin-security-rules-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-admin-storage-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-ai-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-ai-scripting-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-analytics-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-app-check-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-app-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-auth-reference-api/index.html +2 -2
- package/dist/serve/site-ui/docs/pyric-auth-reference-api.md +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-assurance-browser-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-assurance-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-bridge-client-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-bridge-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-bundler-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-conformance-browser-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-conformance-docs-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-conformance-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-credentials-node-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-discover-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-flow-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-next-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-register-app-bridge-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-register-client-app-bridge-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-register-client-app-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-register-client-auth-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-register-client-database-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-register-client-firestore-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-register-client-storage-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-register-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-remote-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-repro-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-serve-worker-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-verify-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-vite-reference-api/index.html +17 -3
- package/dist/serve/site-ui/docs/pyric-cli-vite-reference-api.md +7 -5
- package/dist/serve/site-ui/docs/pyric-cli-vite-ssr-loader-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-database-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-firestore-lite-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-firestore-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-functions-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-messaging-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-messaging-sw-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-performance-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-remote-config-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-rules-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-sandbox-branches-store-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-sandbox-checkpoints-directory-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-sandbox-checkpoints-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-sandbox-database-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-sandbox-firestore-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-sandbox-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-storage-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-storage-sw-reference-api/index.html +102 -0
- package/dist/serve/site-ui/docs/pyric-storage-sw-reference-api.md +76 -0
- package/dist/serve/site-ui/docs/pyric-ui-agents-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-ui-auth-hooks-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-ui-auth-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-ui-events-hooks-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-ui-events-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-ui-firestore-hooks-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-ui-firestore-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-ui-listener-owner-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-ui-primitives-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-ui-rtdb-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-ui-rules-hooks-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-ui-rules-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-ui-storage-hooks-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-ui-storage-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-ui-traffic-hooks-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-ui-traffic-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/reference/cli/index.html +12 -2
- package/dist/serve/site-ui/docs/reference/cli.md +24 -0
- package/dist/serve/site-ui/docs/rtdb-flutter-compat/index.html +1 -1
- package/dist/serve/site-ui/docs/rtdb-kotlin-compat/index.html +1 -1
- package/dist/serve/site-ui/docs/rtdb-swift-compat/index.html +1 -1
- package/dist/serve/site-ui/docs/rules-compat/index.html +1 -1
- package/dist/serve/site-ui/docs/secure/audit-your-rules/index.html +1 -1
- package/dist/serve/site-ui/docs/secure/firestore-rules-limits/index.html +1 -1
- package/dist/serve/site-ui/docs/secure/read-a-denial/index.html +1 -1
- package/dist/serve/site-ui/docs/secure/rtdb-rules-in-typescript/index.html +1 -1
- package/dist/serve/site-ui/docs/secure/rtdb-rules-standard-library/index.html +1 -1
- package/dist/serve/site-ui/docs/secure/rules-standard-library/index.html +1 -1
- package/dist/serve/site-ui/docs/secure/secure-it-with-rules/index.html +1 -1
- package/dist/serve/site-ui/docs/secure/simulate-and-lint/index.html +1 -1
- package/dist/serve/site-ui/docs/secure/write-a-rules-test-suite/index.html +1 -1
- package/dist/serve/site-ui/docs/ship/ship-to-production/index.html +1 -1
- package/dist/serve/site-ui/docs/ship/test-in-node/index.html +1 -1
- package/dist/serve/site-ui/docs/storage-compat/index.html +1 -1
- package/dist/serve/site-ui/docs/trust/how-we-know-it-matches-firebase/index.html +1 -1
- package/dist/serve/site-ui/docs/trust/rules-standard-library/index.html +1 -1
- package/dist/serve/site-ui/docs/trust/versioning-and-compatibility/index.html +1 -1
- package/dist/serve/site-ui/docs/tutorial/index.html +1 -1
- package/dist/serve/site-ui/examples/chess/index.html +1 -1
- package/dist/serve/site-ui/firestore/index.html +1 -1
- package/dist/serve/site-ui/llms.txt +1 -0
- package/dist/serve/site-ui/rtdb/index.html +1 -1
- package/dist/serve/site-ui/settings/index.html +1 -1
- package/dist/serve/site-ui/storage/index.html +1 -1
- package/dist/serve/site-ui/studio/index.html +1 -1
- package/dist/serve/site-ui/traffic/index.html +1 -1
- package/dist/serve/vite-plugin.d.ts +6 -0
- package/dist/serve/vite-plugin.d.ts.map +1 -1
- package/dist/serve/vite-plugin.js +11 -1
- package/dist/serve/vite-plugin.js.map +1 -1
- package/dist/serve/vite-service-worker.d.ts +12 -0
- package/dist/serve/vite-service-worker.d.ts.map +1 -0
- package/dist/serve/vite-service-worker.js +33 -0
- package/dist/serve/vite-service-worker.js.map +1 -0
- package/dist/serve/worker/client/auth.d.ts.map +1 -1
- package/dist/serve/worker/client/auth.js +4 -3
- package/dist/serve/worker/client/auth.js.map +1 -1
- package/dist/serve/worker/host/auth-action-codes.js +2 -2
- package/dist/serve/worker/host/auth-action-codes.js.map +1 -1
- package/dist/serve/worker/host/auth-custom-token.d.ts.map +1 -1
- package/dist/serve/worker/host/auth-custom-token.js +4 -2
- package/dist/serve/worker/host/auth-custom-token.js.map +1 -1
- package/dist/serve/worker/host/dispatch.d.ts.map +1 -1
- package/dist/serve/worker/host/dispatch.js +3 -1
- package/dist/serve/worker/host/dispatch.js.map +1 -1
- package/dist/serve/worker/host-auth.d.ts +6 -0
- package/dist/serve/worker/host-auth.d.ts.map +1 -1
- package/dist/serve/worker/host-auth.js +16 -5
- package/dist/serve/worker/host-auth.js.map +1 -1
- package/dist/serve/worker/inbound-validation.d.ts.map +1 -1
- package/dist/serve/worker/inbound-validation.js +1 -0
- package/dist/serve/worker/inbound-validation.js.map +1 -1
- package/dist/serve/worker/protocol/storage.d.ts +1 -8
- package/dist/serve/worker/protocol/storage.d.ts.map +1 -1
- package/dist/serve/worker/protocol/storage.js +2 -14
- package/dist/serve/worker/protocol/storage.js.map +1 -1
- package/dist/serve/worker/protocol.d.ts +2 -0
- package/dist/serve/worker/protocol.d.ts.map +1 -1
- package/dist/serve/worker/protocol.js.map +1 -1
- package/package.json +12 -8
- package/src/cli/index.ts +15 -1
- package/src/cli/run.ts +139 -0
- package/src/conformance/.generated/can-i-use.ts +1 -1
- package/src/conformance/.generated/conformance-docs.ts +1 -1
- package/src/remote/local-storage-url.ts +1 -58
- package/src/serve/assets/avatar-route.ts +6 -7
- package/src/serve/assets/resolver.ts +4 -1
- package/src/serve/entries/app-client.ts +7 -0
- package/src/serve/vite-plugin.ts +15 -1
- package/src/serve/vite-service-worker.ts +44 -0
- package/src/serve/worker/client/auth.ts +4 -3
- package/src/serve/worker/host/auth-action-codes.ts +2 -2
- package/src/serve/worker/host/auth-custom-token.ts +4 -2
- package/src/serve/worker/host/dispatch.ts +2 -0
- package/src/serve/worker/host-auth.ts +18 -5
- package/src/serve/worker/inbound-validation.ts +1 -0
- package/src/serve/worker/protocol/storage.ts +2 -14
- package/src/serve/worker/protocol.ts +2 -0
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["_astro/RulesCodeEditor.kBYcclwV.js","_astro/sandbox-controls.Bp5PoonS.js","_astro/index.DBy5LfQW.js","_astro/seed.
|
|
2
|
-
import{r as
|
|
3
|
-
`){n+=1;continue}if(s==='"'||s==="'"){const{token:o,next:a}=
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["_astro/RulesCodeEditor.kBYcclwV.js","_astro/sandbox-controls.Bp5PoonS.js","_astro/index.DBy5LfQW.js","_astro/seed.BO5CXcqE.js","_astro/writes.DHSW22XD.js","_astro/index.DNyk7q8W.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{r as Hf,d as Sb,M as Yi,g as kb,e as jb,o as Xa,F as H,f as pt,m as Un,h as Te,k as Kf,l as Eb,n as Cb,p as In,q as xn,t as Gf,u as ds,v as Ee,w as Vs,x as Ps,y as Ds,z as qs,A as Dt,B as vi,S as Jf,C as Kr,D as Yf,E as Ws,G as Qf,H as Nb,I as Rb,J as Ib,K as Ab,L as Xf,R as Me,N as xi,O as Zf,P as eh,Q as Ob,T as $b,U as Uo,V as ct,W as Bo,X as Pb,Y as Ft,Z as jr,_ as Db,$ as Tb,a0 as Mb,a1 as Gr,a2 as th,a3 as Lb,a4 as De,a5 as nh,a6 as Ub,a7 as Bb,a8 as Fb,a9 as Vb,aa as qb,ab as rh,ac as Wb,ad as zb,ae as Hb,af as Kb,ag as Gb,ah as fs,ai as il,aj as Jb,ak as Yb,al as Qb,am as ol,an as Xb,ao as Zb,ap as ew,aq as tw,ar as nw,as as sh,at as rw,au as sw,av as iw,aw as ow,ax as ih,ay as oh,az as $n,aA as Jr,aB as aw,aC as cw,i as lw,j as c,aD as uw,aE as dw,aF as fw,aG as hw,aH as pw,aI as mw,aJ as ah,aK as yw,aL as Za,aM as gw,aN as bw,aO as ww,aP as vw,aQ as un,aR as Er,aS as xw,aT as ch,aU as lh,aV as al,aW as _w,aX as Sw,aY as kw,aZ as jw,a_ as Ew,a$ as Cw,b0 as Nw,b1 as Rw,b2 as Iw,b3 as Aw,b4 as uh,b5 as Ow,b6 as on,b7 as Vt,b8 as Pn}from"./sandbox-controls.Bp5PoonS.js";import{r as y}from"./index.DBy5LfQW.js";import{a as $w,r as Pw,b as Cr,d as st,T as zs,c as Et,t as rn,e as Yr,f as dh,h as cl,j as ec,k as fh,l as tc,u as Fo,m as Dw,n as nc,o as Bn,w as hh,p as Tw,q as Mw,v as Lw,x as Uw,y as Bw,B as Fw,C as Vw,z as qw,A as Ww,D as Vo,E as zw,F as Hw,G as Kw,Q as Gw,H as pr,s as Hs,I as ph,J as ll,K as qo,L as Jw,M as Yw,N as rc,O as sc,g as Ks,i as Qw}from"./writes.DHSW22XD.js";import{r as Xw}from"./index.DNyk7q8W.js";const an={maxExpressionLength:256,maxStringLiteralLength:1024,maxAstDepth:16},Zw=["serverTimestamp","increment","arrayUnion","arrayRemove","deleteField"],ev={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 tv(e){return Zw.includes(e)}class be extends Error{code="invalid-argument";pos;constructor(t,n){super(t),this.name="ExpressionLexError",this.pos=n}}class ft extends Error{code="invalid-argument";pos;constructor(t,n){super(t),this.name="ExpressionParseError",this.pos=n}}const nv={"(":"lparen",")":"rparen","[":"lbracket","]":"rbracket",",":"comma",".":"dot","?":"question",":":"colon","+":"plus","-":"minus","*":"star","/":"slash","%":"percent"},rv={true:"true",false:"false",null:"null"};function sv(e){if(e.length>an.maxExpressionLength)throw new be(`expression exceeds ${an.maxExpressionLength}-character cap (got ${e.length})`,J(an.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:o,next:a}=av(e,n,s);if(t.push(o),n=a,n<=r)throw new be("lexer stalled on string",J(r));continue}if(s>="0"&&s<="9"){const{token:o,next:a}=ov(e,n);if(t.push(o),n=a,n<=r)throw new be("lexer stalled on number",J(r));continue}if(_i(s)){const{token:o,next:a}=iv(e,n);t.push(o),n=a;continue}if(s==="$"){const{token:o,next:a}=ul(e,n,"$","reference");t.push(o),n=a;continue}if(s==="@"){const{token:o,next:a}=ul(e,n,"@","sentinel");t.push(o),n=a;continue}if(s==="="&&e[n+1]==="="){t.push({kind:"eq",pos:J(n)}),n+=2;continue}if(s==="!"&&e[n+1]==="="){t.push({kind:"neq",pos:J(n)}),n+=2;continue}if(s==="<"){e[n+1]==="="?(t.push({kind:"lte",pos:J(n)}),n+=2):(t.push({kind:"lt",pos:J(n)}),n+=1);continue}if(s===">"){e[n+1]==="="?(t.push({kind:"gte",pos:J(n)}),n+=2):(t.push({kind:"gt",pos:J(n)}),n+=1);continue}if(s==="&"){if(e[n+1]!=="&")throw new be("unexpected '&' (did you mean '&&'?)",J(n));t.push({kind:"and",pos:J(n)}),n+=2;continue}if(s==="|"){if(e[n+1]!=="|")throw new be("unexpected '|' (did you mean '||'?)",J(n));t.push({kind:"or",pos:J(n)}),n+=2;continue}if(s==="!"){t.push({kind:"bang",pos:J(n)}),n+=1;continue}if(s==="=")throw new be("unexpected '=' (did you mean '=='?)",J(n));const i=nv[s];if(i){t.push({kind:i,pos:J(n)}),n+=1;continue}throw new be(`unexpected character ${JSON.stringify(s)}`,J(n))}return t.push({kind:"eof",pos:J(e.length)}),t}function J(e){return{offset:e,column:e+1}}function _i(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"||e==="_"}function mh(e){return _i(e)||e>="0"&&e<="9"}function iv(e,t){let n=t+1;for(;n<e.length&&mh(e[n]);)n+=1;const r=e.slice(t,n),s=rv[r];return s?{token:{kind:s,pos:J(t)},next:n}:{token:{kind:"identifier",pos:J(t),value:r},next:n}}function ul(e,t,n,r){const s=t+1;if(s>=e.length||!_i(e[s]))throw new be(`expected identifier after '${n}'`,J(t));let i=s+1;for(;i<e.length&&mh(e[i]);)i+=1;const o=e.slice(s,i);return{token:{kind:r,pos:J(t),value:o},next:i}}function ov(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 be("leading zeros are not allowed in number literals",J(t))}else for(;n<e.length&&e[n]>="0"&&e[n]<="9";)n+=1;let s=!1;if(n<e.length&&e[n]==="."){const a=e[n+1];if(a!==void 0&&a>="0"&&a<="9")for(s=!0,n+=1;n<e.length&&e[n]>="0"&&e[n]<="9";)n+=1;else if(!(a!==void 0&&_i(a)))throw new be("expected digit after '.' in number literal",J(n))}const i=e.slice(t,n),o=Number.parseFloat(i);if(!Number.isFinite(o))throw new be(`numeric literal '${i}' is not finite`,J(t));if(!s&&!Number.isSafeInteger(o))throw new be(`integer literal '${i}' exceeds safe integer range`,J(t));return{token:{kind:"number",pos:J(t),value:o},next:n}}function av(e,t,n){let r=t+1,s="";for(;r<e.length;){const i=e[r];if(i===n)return{token:{kind:"string",pos:J(t),value:s},next:r+1};if(i==="\\"){const o=e[r+1];if(o===void 0)throw new be("unterminated escape sequence in string literal",J(r));switch(o){case'"':s+='"';break;case"'":s+="'";break;case"\\":s+="\\";break;case"n":s+=`
|
|
4
4
|
`;break;case"t":s+=" ";break;default:throw new be(`invalid escape sequence '\\${o}' (only \\", \\', \\\\, \\n, \\t are allowed)`,J(r))}r+=2}else{if(i===`
|
|
5
|
-
`||i==="\r")throw new be("unterminated string literal (newline before closing quote)",J(t));s+=i,r+=1}if(s.length>on.maxStringLiteralLength)throw new be(`string literal exceeds ${on.maxStringLiteralLength}-character cap`,J(t))}throw new be("unterminated string literal",J(t))}function iv(e){const t=new ov(e),n=t.parseExpression();return t.expect("eof","unexpected trailing tokens"),lv(n),n}class ov{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=av(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 ft(`bare identifier '${t.value}' is not a value (did you mean '$${t.value}' or '@${t.value}'?)`,t.pos);case"eof":throw new ft("unexpected end of expression",t.pos);default:throw new ft("unexpected token",t.pos)}}parseSentinelCall(){const t=this.consume(),n=t.value;if(!Xw(n))throw new ft(`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=Qw[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 ft(`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 ft(`${n} (got ${cv(r)})`,r.pos);return this.consume()}}function av(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 cv(e){return e.kind==="eof"?"end of expression":e.value!==void 0?`${e.kind} ${JSON.stringify(e.value)}`:e.kind}function lv(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>on.maxAstDepth)throw new ft(`expression AST exceeds depth cap of ${on.maxAstDepth}`,n.pos);return s}}class qe extends Error{code;pos;constructor(t,n,r){super(n),this.name="EvalError",this.code=t,this.pos=r}}function Yr(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 Xe(e,t){return new qe("type-mismatch",t,e.pos)}function We(e,t){switch(e.kind){case"literal":return e.value;case"reference":return uv(e,t);case"sentinel":return dv(e,t);case"unary":return fv(e,t);case"binary":return hv(e,t);case"logical":return mv(e,t);case"ternary":return yv(e,t);case"fieldAccess":return gv(e,t);case"indexAccess":return bv(e,t)}}function uv(e,t){if(!Object.prototype.hasOwnProperty.call(t.reads,e.alias))throw new qe("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 dv(e,t){const n=e.args.map(r=>{const s=We(r,t);if(Yr(s))throw new qe("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 Xe(e,`'@increment' expects a numeric argument, got ${Ie(r)}`);return Ks(r,e),{__type:"increment",value:r}}case"arrayUnion":return{__type:"arrayUnion",values:n};case"arrayRemove":return{__type:"arrayRemove",values:n}}}function fv(e,t){const n=We(e.operand,t);if(Vo(n,e),e.op==="-"){if(typeof n!="number")throw Xe(e,`unary '-' expects a number, got ${Ie(n)}`);const r=-n;return Ks(r,e),r}if(typeof n!="boolean")throw Xe(e,`unary '!' expects a boolean, got ${Ie(n)}`);return!n}function hv(e,t){const n=We(e.left,t),r=We(e.right,t);switch(Vo(n,e),Vo(r,e),e.op){case"+":if(typeof n=="number"&&typeof r=="number"){const s=n+r;return Ks(s,e),s}if(typeof n=="string"&&typeof r=="string")return n+r;throw Xe(e,`'+' expects (number, number) or (string, string); got (${Ie(n)}, ${Ie(r)})`);case"-":case"*":case"/":case"%":{if(typeof n!="number"||typeof r!="number")throw Xe(e,`'${e.op}' expects (number, number); got (${Ie(n)}, ${Ie(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 Ks(s,e),s}case"==":return ul(e,n,r);case"!=":return!ul(e,n,r);case"<":case"<=":case">":case">=":return pv(e,n,r)}}function ul(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 Xe(e,"equality between objects/arrays is not supported (compare specific fields instead)")}function pv(e,t,n){if(!(typeof t=="number"&&typeof n=="number"||typeof t=="string"&&typeof n=="string"))throw Xe(e,`'${e.op}' expects matching number/number or string/string operands; got (${Ie(t)}, ${Ie(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 mv(e,t){const n=We(e.left,t);if(typeof n!="boolean")throw Xe(e,`'${e.op}' expects boolean operands; left is ${Ie(n)}`);if(e.op==="&&"){if(!n)return!1}else if(n)return!0;const r=We(e.right,t);if(typeof r!="boolean")throw Xe(e,`'${e.op}' expects boolean operands; right is ${Ie(r)}`);return r}function yv(e,t){const n=We(e.cond,t);if(typeof n!="boolean")throw Xe(e,`ternary condition must be boolean, got ${Ie(n)}`);return We(n?e.whenTrue:e.whenFalse,t)}function gv(e,t){const n=We(e.target,t);if(n==null)throw new qe("null-access",`cannot access field '${e.field}' on null`,e.pos);if(typeof n!="object"||Array.isArray(n)||Yr(n))throw Xe(e,`cannot access field '${e.field}' on ${Ie(n)}`);const r=n;return Object.prototype.hasOwnProperty.call(r,e.field)?r[e.field]:null}function bv(e,t){const n=We(e.target,t);if(n==null)throw new qe("null-access","cannot index null target",e.pos);const r=We(e.index,t);if(Array.isArray(n)){if(typeof r!="number"||!Number.isInteger(r))throw new qe("invalid-index",`array index must be a non-negative integer, got ${Ie(r)}`,e.pos);if(r<0)throw new qe("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"&&!Yr(n)){if(typeof r!="string")throw new qe("invalid-index",`object key must be a string, got ${Ie(r)}`,e.pos);const s=n;return Object.prototype.hasOwnProperty.call(s,r)?s[r]:null}throw Xe(e,`cannot index into ${Ie(n)}`)}function Vo(e,t){if(Yr(e))throw new qe("sentinel-misuse",`sentinel '@${e.__type}' cannot be used as an operator operand`,t.pos)}function Ks(e,t){if(!Number.isFinite(e))throw new qe("division-by-zero",`arithmetic produced a non-finite value (${Number.isNaN(e)?"NaN":"Infinity"})`,t.pos)}function Ie(e){if(e===null)return"null";if(Array.isArray(e))return`array(${e.length})`;if(typeof e=="object"&&e!==null){if(Yr(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 mh="$expr";class Gs extends Error{code="invalid-argument";path;constructor(t,n){super(t),this.name="ExpressionWalkError",this.path=n}}function wv(e,t){return Wo(e,t,"")}function Wo(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 o=0;o<e.length;o+=1)i[o]=Wo(e[o],t,n===""?String(o):`${n}.${o}`);return i}const r=e;if(Object.prototype.hasOwnProperty.call(r,mh))return vv(r,t,n);const s={};for(const i of Object.keys(r))s[i]=Wo(r[i],t,n===""?i:`${n}.${i}`);return s}function vv(e,t,n){const r=Object.keys(e);if(r.length!==1)throw new Gs(`expression wrapper at '${n||"<root>"}' must have only the '$expr' key, got [${r.map(a=>JSON.stringify(a)).join(", ")}]`,n);const s=e[mh];if(typeof s!="string")throw new Gs(`'$expr' value at '${n||"<root>"}' must be a string, got ${Sv(s)}`,n);const i=_v(s,n);return xv(i,t,n)}function xv(e,t,n){try{return We(e,t)}catch(r){if(r instanceof qe){const s=new qe(r.code,`at '${n||"<root>"}': ${r.message}`,r.pos);throw s.cause=r,s}throw r}}function _v(e,t){try{return iv(tv(e))}catch(n){throw n instanceof be?dl(n,be,t):n instanceof ft?dl(n,ft,t):n}}function dl(e,t,n){const r=new t(`at '${n||"<root>"}': ${e.message}`,e.pos);return r.cause=e,r}function Sv(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function kv(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 o=s;if(o.includes("'2+modules'")||o.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(o);if(!u.success)return{ok:!1,summary:`Module resolve failed: ${u.error.message}`,data:u};o=u.data.resolved}const l=(await t()).seed({rules:o,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:o,data:a}=r,u=(await t()).execute({method:s,path:i,auth:o,data:a});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:o,evaluateRules:a}=r,l=await t();if(a){const u=l.execute({method:i??"get",path:s,auth:o??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,a=(await t()).batch(s,i);return{ok:a.allowed,summary:a.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:a.allowed,results:a.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:o}=r,a=await t(),{path:l,result:u}=a.createWithAutoId(s,o,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 no retained write remains.",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 retained events — allowed and denied — with timestamps, auth, debug messages, and an omitted count when the bounded log was trimmed. Useful for audit / replay / "why did this rule deny?" investigations.',parameters:{type:"object",properties:{}},async execute(){const r=await t(),{omittedCount:s}=r.getEventRetention();return{ok:!0,summary:s>0?`Event log (${s} omitted)`:"Event log",data:{omittedCount:s,events:r.getEvents().map(o=>({id:o.id,method:o.method,path:o.path,allowed:o.allowed,auth:o.auth,debugMessages:o.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:o,reads:a,writes:l}=r;for(let h=0;h<l.length;h+=1){const f=l[h];if(f.method==="delete"&&f.data!==void 0)return{ok:!1,summary:`writes[${h}]: 'delete' must not include 'data'`,data:{code:"INVALID_INPUT"}};if(f.method!=="delete"&&f.data===void 0)return{ok:!1,summary:`writes[${h}]: '${f.method}' requires 'data'`,data:{code:"INVALID_INPUT"}}}const u=await t(),d=o===!0;try{const h=u.transaction(p=>{const m={};for(const[g,b]of Object.entries(a)){const x=p.get(b).data();m[g]=x===void 0?null:x}for(let g=0;g<l.length;g+=1){const b=l[g];if(b.method==="delete"){p.delete(b.path);continue}const w=wv(b.data,{reads:m});if(w===null||typeof w!="object"||Array.isArray(w))throw new Gs(`writes[${g}].data resolved to a non-object`,`writes.${g}.data`);const x=w;switch(b.method){case"create":p.create(b.path,x);break;case"update":p.update(b.path,x);break;case"set":p.set(b.path,x);break}}},{auth:s,readOnly:i}),f={allowed:h.allowed,writes:h.writes.map(p=>{const m={path:p.path,method:p.method,allowed:p.allowed};return p.error&&(m.error={code:p.error.code,message:p.error.message}),d&&(m.debugMessages=p.debugMessages),m})};return h.error&&(f.error={code:h.error.code,message:h.error.message}),h.readOnlyViolation&&(f.readOnlyViolation=!0),d&&(f.reads=h.reads.map(p=>({path:p.path,data:p.data}))),{ok:h.allowed,summary:h.allowed?`Transaction committed (${l.length} write(s))`:"Transaction rolled back",data:f}}catch(h){if(h instanceof Gs||h instanceof be||h instanceof ft||h instanceof qe)return{ok:!1,summary:`Transaction failed: ${h.message}`,data:{allowed:!1,writes:[],error:{code:"invalid-argument",message:h.message}}};throw h}}}]}function jv(e){return kv({resolveSandbox:e.resolveSandbox,resolveModulesFn:zf})}const Ev=new Set([".read",".write",".validate",".indexOn"]),Cv=new Set([".read",".write",".validate"]),yh=/[.#$/[\]]/,Nv="Invalid rule expression. Expected 'true', 'false', or an expression string.",Rv="Invalid indexOn expression. Must be either a string or an array of strings",fl=`String can't contain ".", "#", "$", "/", "[", or "]"`,hl="Expected '{'.";function gh(e,t){const n=[],r=(i,o,a="error")=>{n.push({path:e,code:i,message:o,severity:a})},s=[];for(const[i,o]of Object.entries(t)){if(Cv.has(i)){typeof o!="string"&&typeof o!="boolean"&&r("RULE_NOT_EXPRESSION",Nv,typeof o=="number"||typeof o=="object"&&o!==null?"error":"warning");continue}if(i===".indexOn"){const u=h=>typeof h=="string";u(o)||Array.isArray(o)&&o.every(u)||r("INDEX_ON_SHAPE",Rv,typeof o=="number"?"error":"warning");continue}const a=typeof o=="object"&&o!==null&&!Array.isArray(o);if(i.startsWith(".")){a?r("INVALID_KEY",fl):r("EXPECTED_OBJECT",hl);continue}i.startsWith("$")&&s.push(i);const l=i.startsWith("$")?i.slice(1):i;yh.test(l)?r("INVALID_KEY",fl,l.includes("#")?"error":"warning"):a||r("EXPECTED_OBJECT",hl)}return s.length>1&&r("MULTIPLE_WILDCARDS",`Cannot have multiple default rules ('${s[0]}' and '${s[1]}').`),n}const ae=e=>e;function Ye(e){if(e===null)return"null";if(typeof e=="string"){if(/[\u0000-\u001f\u007f]/.test(e))throw new Error(`lit: ${JSON.stringify(e)} holds a newline or another control character, which RTDB rules literals here cannot carry.`);return`'${e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}'`}if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`RTDB rules have no literal for ${e}.`);return String(e)}if(typeof e=="boolean")return e?"true":"false";let t=typeof e;throw e===void 0?t="undefined":Array.isArray(e)&&(t="array"),new Error(`RTDB rules have no literal for ${t}.`)}function Iv(e,t){if(typeof t!="string"||t.length===0||yh.test(t))throw new Error(`${e}: '${String(t)}' is not a field name; RTDB keys cannot be empty or contain . # $ / [ ].`);return t}function Av(e,t){let n=0,r=null,s=!1,i=!1;for(let o=0;o<e.length;o++){const a=e[o];if(r){a==="\\"?o++:a===r&&(r=null);continue}if(s){a==="\\"?o++:i?a==="]"&&(i=!1):a==="["?i=!0:a==="/"&&(s=!1);continue}if(a==="'"||a==='"')r=a;else if(a==="/"&&/\(\s*$/.test(e.slice(0,o)))s=!0;else if(a==="("||a==="[")n++;else if(a===")"||a==="]")n--;else if(n===0&&t.some(l=>e.startsWith(l,o)))return!0}return!1}const bh=(e,t)=>Av(e,t)?`(${e})`:e;function In(...e){const t=e.filter(n=>n.length>0);if(t.length===0)throw new Error("all: pass at least one condition; an empty all() would allow everything.");return t.length===1?t[0]:ae(t.map(n=>bh(n,["||","?"])).join(" && "))}function pl(...e){const t=e.filter(n=>n.length>0);if(t.length===0)throw new Error("any: pass at least one condition; an empty any() would deny everything.");return t.length===1?t[0]:ae(t.map(n=>bh(n,["&&","?"])).join(" || "))}const Ov=`RtdbExpr {
|
|
5
|
+
`||i==="\r")throw new be("unterminated string literal (newline before closing quote)",J(t));s+=i,r+=1}if(s.length>an.maxStringLiteralLength)throw new be(`string literal exceeds ${an.maxStringLiteralLength}-character cap`,J(t))}throw new be("unterminated string literal",J(t))}function cv(e){const t=new lv(e),n=t.parseExpression();return t.expect("eof","unexpected trailing tokens"),fv(n),n}class lv{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=uv(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 ft(`bare identifier '${t.value}' is not a value (did you mean '$${t.value}' or '@${t.value}'?)`,t.pos);case"eof":throw new ft("unexpected end of expression",t.pos);default:throw new ft("unexpected token",t.pos)}}parseSentinelCall(){const t=this.consume(),n=t.value;if(!tv(n))throw new ft(`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=ev[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 ft(`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 ft(`${n} (got ${dv(r)})`,r.pos);return this.consume()}}function uv(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 dv(e){return e.kind==="eof"?"end of expression":e.value!==void 0?`${e.kind} ${JSON.stringify(e.value)}`:e.kind}function fv(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>an.maxAstDepth)throw new ft(`expression AST exceeds depth cap of ${an.maxAstDepth}`,n.pos);return s}}class Ve extends Error{code;pos;constructor(t,n,r){super(n),this.name="EvalError",this.code=t,this.pos=r}}function Qr(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 Xe(e,t){return new Ve("type-mismatch",t,e.pos)}function We(e,t){switch(e.kind){case"literal":return e.value;case"reference":return hv(e,t);case"sentinel":return pv(e,t);case"unary":return mv(e,t);case"binary":return yv(e,t);case"logical":return bv(e,t);case"ternary":return wv(e,t);case"fieldAccess":return vv(e,t);case"indexAccess":return xv(e,t)}}function hv(e,t){if(!Object.prototype.hasOwnProperty.call(t.reads,e.alias))throw new Ve("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 pv(e,t){const n=e.args.map(r=>{const s=We(r,t);if(Qr(s))throw new Ve("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 Xe(e,`'@increment' expects a numeric argument, got ${Ie(r)}`);return Gs(r,e),{__type:"increment",value:r}}case"arrayUnion":return{__type:"arrayUnion",values:n};case"arrayRemove":return{__type:"arrayRemove",values:n}}}function mv(e,t){const n=We(e.operand,t);if(Wo(n,e),e.op==="-"){if(typeof n!="number")throw Xe(e,`unary '-' expects a number, got ${Ie(n)}`);const r=-n;return Gs(r,e),r}if(typeof n!="boolean")throw Xe(e,`unary '!' expects a boolean, got ${Ie(n)}`);return!n}function yv(e,t){const n=We(e.left,t),r=We(e.right,t);switch(Wo(n,e),Wo(r,e),e.op){case"+":if(typeof n=="number"&&typeof r=="number"){const s=n+r;return Gs(s,e),s}if(typeof n=="string"&&typeof r=="string")return n+r;throw Xe(e,`'+' expects (number, number) or (string, string); got (${Ie(n)}, ${Ie(r)})`);case"-":case"*":case"/":case"%":{if(typeof n!="number"||typeof r!="number")throw Xe(e,`'${e.op}' expects (number, number); got (${Ie(n)}, ${Ie(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 Gs(s,e),s}case"==":return dl(e,n,r);case"!=":return!dl(e,n,r);case"<":case"<=":case">":case">=":return gv(e,n,r)}}function dl(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 Xe(e,"equality between objects/arrays is not supported (compare specific fields instead)")}function gv(e,t,n){if(!(typeof t=="number"&&typeof n=="number"||typeof t=="string"&&typeof n=="string"))throw Xe(e,`'${e.op}' expects matching number/number or string/string operands; got (${Ie(t)}, ${Ie(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 bv(e,t){const n=We(e.left,t);if(typeof n!="boolean")throw Xe(e,`'${e.op}' expects boolean operands; left is ${Ie(n)}`);if(e.op==="&&"){if(!n)return!1}else if(n)return!0;const r=We(e.right,t);if(typeof r!="boolean")throw Xe(e,`'${e.op}' expects boolean operands; right is ${Ie(r)}`);return r}function wv(e,t){const n=We(e.cond,t);if(typeof n!="boolean")throw Xe(e,`ternary condition must be boolean, got ${Ie(n)}`);return We(n?e.whenTrue:e.whenFalse,t)}function vv(e,t){const n=We(e.target,t);if(n==null)throw new Ve("null-access",`cannot access field '${e.field}' on null`,e.pos);if(typeof n!="object"||Array.isArray(n)||Qr(n))throw Xe(e,`cannot access field '${e.field}' on ${Ie(n)}`);const r=n;return Object.prototype.hasOwnProperty.call(r,e.field)?r[e.field]:null}function xv(e,t){const n=We(e.target,t);if(n==null)throw new Ve("null-access","cannot index null target",e.pos);const r=We(e.index,t);if(Array.isArray(n)){if(typeof r!="number"||!Number.isInteger(r))throw new Ve("invalid-index",`array index must be a non-negative integer, got ${Ie(r)}`,e.pos);if(r<0)throw new Ve("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"&&!Qr(n)){if(typeof r!="string")throw new Ve("invalid-index",`object key must be a string, got ${Ie(r)}`,e.pos);const s=n;return Object.prototype.hasOwnProperty.call(s,r)?s[r]:null}throw Xe(e,`cannot index into ${Ie(n)}`)}function Wo(e,t){if(Qr(e))throw new Ve("sentinel-misuse",`sentinel '@${e.__type}' cannot be used as an operator operand`,t.pos)}function Gs(e,t){if(!Number.isFinite(e))throw new Ve("division-by-zero",`arithmetic produced a non-finite value (${Number.isNaN(e)?"NaN":"Infinity"})`,t.pos)}function Ie(e){if(e===null)return"null";if(Array.isArray(e))return`array(${e.length})`;if(typeof e=="object"&&e!==null){if(Qr(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 yh="$expr";class Js extends Error{code="invalid-argument";path;constructor(t,n){super(t),this.name="ExpressionWalkError",this.path=n}}function _v(e,t){return zo(e,t,"")}function zo(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 o=0;o<e.length;o+=1)i[o]=zo(e[o],t,n===""?String(o):`${n}.${o}`);return i}const r=e;if(Object.prototype.hasOwnProperty.call(r,yh))return Sv(r,t,n);const s={};for(const i of Object.keys(r))s[i]=zo(r[i],t,n===""?i:`${n}.${i}`);return s}function Sv(e,t,n){const r=Object.keys(e);if(r.length!==1)throw new Js(`expression wrapper at '${n||"<root>"}' must have only the '$expr' key, got [${r.map(a=>JSON.stringify(a)).join(", ")}]`,n);const s=e[yh];if(typeof s!="string")throw new Js(`'$expr' value at '${n||"<root>"}' must be a string, got ${Ev(s)}`,n);const i=jv(s,n);return kv(i,t,n)}function kv(e,t,n){try{return We(e,t)}catch(r){if(r instanceof Ve){const s=new Ve(r.code,`at '${n||"<root>"}': ${r.message}`,r.pos);throw s.cause=r,s}throw r}}function jv(e,t){try{return cv(sv(e))}catch(n){throw n instanceof be?fl(n,be,t):n instanceof ft?fl(n,ft,t):n}}function fl(e,t,n){const r=new t(`at '${n||"<root>"}': ${e.message}`,e.pos);return r.cause=e,r}function Ev(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function Cv(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 o=s;if(o.includes("'2+modules'")||o.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(o);if(!u.success)return{ok:!1,summary:`Module resolve failed: ${u.error.message}`,data:u};o=u.data.resolved}const l=(await t()).seed({rules:o,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:o,data:a}=r,u=(await t()).execute({method:s,path:i,auth:o,data:a});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:o,evaluateRules:a}=r,l=await t();if(a){const u=l.execute({method:i??"get",path:s,auth:o??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,a=(await t()).batch(s,i);return{ok:a.allowed,summary:a.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:a.allowed,results:a.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:o}=r,a=await t(),{path:l,result:u}=a.createWithAutoId(s,o,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 no retained write remains.",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 retained events — allowed and denied — with timestamps, auth, debug messages, and an omitted count when the bounded log was trimmed. Useful for audit / replay / "why did this rule deny?" investigations.',parameters:{type:"object",properties:{}},async execute(){const r=await t(),{omittedCount:s}=r.getEventRetention();return{ok:!0,summary:s>0?`Event log (${s} omitted)`:"Event log",data:{omittedCount:s,events:r.getEvents().map(o=>({id:o.id,method:o.method,path:o.path,allowed:o.allowed,auth:o.auth,debugMessages:o.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:o,reads:a,writes:l}=r;for(let h=0;h<l.length;h+=1){const f=l[h];if(f.method==="delete"&&f.data!==void 0)return{ok:!1,summary:`writes[${h}]: 'delete' must not include 'data'`,data:{code:"INVALID_INPUT"}};if(f.method!=="delete"&&f.data===void 0)return{ok:!1,summary:`writes[${h}]: '${f.method}' requires 'data'`,data:{code:"INVALID_INPUT"}}}const u=await t(),d=o===!0;try{const h=u.transaction(p=>{const m={};for(const[g,b]of Object.entries(a)){const x=p.get(b).data();m[g]=x===void 0?null:x}for(let g=0;g<l.length;g+=1){const b=l[g];if(b.method==="delete"){p.delete(b.path);continue}const w=_v(b.data,{reads:m});if(w===null||typeof w!="object"||Array.isArray(w))throw new Js(`writes[${g}].data resolved to a non-object`,`writes.${g}.data`);const x=w;switch(b.method){case"create":p.create(b.path,x);break;case"update":p.update(b.path,x);break;case"set":p.set(b.path,x);break}}},{auth:s,readOnly:i}),f={allowed:h.allowed,writes:h.writes.map(p=>{const m={path:p.path,method:p.method,allowed:p.allowed};return p.error&&(m.error={code:p.error.code,message:p.error.message}),d&&(m.debugMessages=p.debugMessages),m})};return h.error&&(f.error={code:h.error.code,message:h.error.message}),h.readOnlyViolation&&(f.readOnlyViolation=!0),d&&(f.reads=h.reads.map(p=>({path:p.path,data:p.data}))),{ok:h.allowed,summary:h.allowed?`Transaction committed (${l.length} write(s))`:"Transaction rolled back",data:f}}catch(h){if(h instanceof Js||h instanceof be||h instanceof ft||h instanceof Ve)return{ok:!1,summary:`Transaction failed: ${h.message}`,data:{allowed:!1,writes:[],error:{code:"invalid-argument",message:h.message}}};throw h}}}]}function Nv(e){return Cv({resolveSandbox:e.resolveSandbox,resolveModulesFn:Hf})}const Rv=new Set([".read",".write",".validate",".indexOn"]),Iv=new Set([".read",".write",".validate"]),gh=/[.#$/[\]]/,Av="Invalid rule expression. Expected 'true', 'false', or an expression string.",Ov="Invalid indexOn expression. Must be either a string or an array of strings",hl=`String can't contain ".", "#", "$", "/", "[", or "]"`,pl="Expected '{'.";function bh(e,t){const n=[],r=(i,o,a="error")=>{n.push({path:e,code:i,message:o,severity:a})},s=[];for(const[i,o]of Object.entries(t)){if(Iv.has(i)){typeof o!="string"&&typeof o!="boolean"&&r("RULE_NOT_EXPRESSION",Av,typeof o=="number"||typeof o=="object"&&o!==null?"error":"warning");continue}if(i===".indexOn"){const u=h=>typeof h=="string";u(o)||Array.isArray(o)&&o.every(u)||r("INDEX_ON_SHAPE",Ov,typeof o=="number"?"error":"warning");continue}const a=typeof o=="object"&&o!==null&&!Array.isArray(o);if(i.startsWith(".")){a?r("INVALID_KEY",hl):r("EXPECTED_OBJECT",pl);continue}i.startsWith("$")&&s.push(i);const l=i.startsWith("$")?i.slice(1):i;gh.test(l)?r("INVALID_KEY",hl,l.includes("#")?"error":"warning"):a||r("EXPECTED_OBJECT",pl)}return s.length>1&&r("MULTIPLE_WILDCARDS",`Cannot have multiple default rules ('${s[0]}' and '${s[1]}').`),n}const ae=e=>e;function Ye(e){if(e===null)return"null";if(typeof e=="string"){if(/[\u0000-\u001f\u007f]/.test(e))throw new Error(`lit: ${JSON.stringify(e)} holds a newline or another control character, which RTDB rules literals here cannot carry.`);return`'${e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}'`}if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`RTDB rules have no literal for ${e}.`);return String(e)}if(typeof e=="boolean")return e?"true":"false";let t=typeof e;throw e===void 0?t="undefined":Array.isArray(e)&&(t="array"),new Error(`RTDB rules have no literal for ${t}.`)}function $v(e,t){if(typeof t!="string"||t.length===0||gh.test(t))throw new Error(`${e}: '${String(t)}' is not a field name; RTDB keys cannot be empty or contain . # $ / [ ].`);return t}function Pv(e,t){let n=0,r=null,s=!1,i=!1;for(let o=0;o<e.length;o++){const a=e[o];if(r){a==="\\"?o++:a===r&&(r=null);continue}if(s){a==="\\"?o++:i?a==="]"&&(i=!1):a==="["?i=!0:a==="/"&&(s=!1);continue}if(a==="'"||a==='"')r=a;else if(a==="/"&&/\(\s*$/.test(e.slice(0,o)))s=!0;else if(a==="("||a==="[")n++;else if(a===")"||a==="]")n--;else if(n===0&&t.some(l=>e.startsWith(l,o)))return!0}return!1}const wh=(e,t)=>Pv(e,t)?`(${e})`:e;function An(...e){const t=e.filter(n=>n.length>0);if(t.length===0)throw new Error("all: pass at least one condition; an empty all() would allow everything.");return t.length===1?t[0]:ae(t.map(n=>wh(n,["||","?"])).join(" && "))}function ml(...e){const t=e.filter(n=>n.length>0);if(t.length===0)throw new Error("any: pass at least one condition; an empty any() would deny everything.");return t.length===1?t[0]:ae(t.map(n=>wh(n,["&&","?"])).join(" || "))}const Dv=`RtdbExpr {
|
|
6
6
|
Expr = Ternary
|
|
7
7
|
|
|
8
8
|
Ternary
|
|
@@ -116,32 +116,32 @@ import{r as zf,d as vb,M as Ji,g as xb,e as _b,o as Qa,F as H,f as pt,m as Ln,h
|
|
|
116
116
|
|
|
117
117
|
identChar = alnum | "_" | "$"
|
|
118
118
|
}
|
|
119
|
-
`;let
|
|
120
|
-
`,r:"\r",t:" ",v:"\v",0:"\0","\\":"\\","'":"'",'"':'"',"/":"/"};function
|
|
121
|
-
`)||t.includes("\r")}function
|
|
119
|
+
`;let yl;function vh(){return yl??=kb(Dv),yl}const Xr="The expression chains more terms than the rules parser reads.";function Zr(e){const t=e.trim(),n=Sb(t,{comments:!1,regexLiterals:!0,multilineStrings:!0}).find(r=>r.depth>Yi);if(n!==void 0)return{ok:!1,message:`Brackets nest more than ${Yi} levels deep at offset ${n.open}: the rules parser reads at most ${Yi}, a limit of this parser, not of production.`};try{const r=vh().match(t);return r.failed()?{ok:!1,message:r.message??"Parse failed"}:{ok:!0,match:r}}catch(r){if(r instanceof RangeError)return{ok:!1,message:Xr};throw r}}function es(){return vh().createSemantics()}const Ys="unterminated string literal",Tv=/^[0-9a-fA-F]{2}$/,Mv=/^[0-9a-fA-F]{4}$/,Lv={b:"\b",f:"\f",n:`
|
|
120
|
+
`,r:"\r",t:" ",v:"\v",0:"\0","\\":"\\","'":"'",'"':'"',"/":"/"};function Nr(e){const t=xh(e);return t.includes(`
|
|
121
|
+
`)||t.includes("\r")}function Uv(e){let t=0;const n=e.length;let r=!0;for(;t<n;){const s=e[t];if(s===" "||s===" "||s===`
|
|
122
122
|
`||s==="\r"){t++;continue}if(s==='"'||s==="'"){const i=s;for(t++;t<n;){const o=e[t];if(o===`
|
|
123
|
-
`||o==="\r")return!0;if(o==="\\"){t+=2;continue}if(o===i){t++;break}t++}r=!1;continue}if(s==="/"&&r){t=_b(e,t),r=!1;continue}r=Mv(s),t++}return!1}function Nr(e){const t=vh(e);let n="",r=0;const s=t.length;for(;r<s;){const i=t[r];if(i!=="\\"){n+=i,r++;continue}if(r+1>=s){n+="\\";break}const o=t[r+1],a=Pv[o];if(a!==void 0){n+=a,r+=2;continue}if(o==="x"&&r+3<s){const l=t.slice(r+2,r+4);if($v.test(l)){n+=String.fromCharCode(Number.parseInt(l,16)),r+=4;continue}}if(o==="u"&&r+5<s){const l=t.slice(r+2,r+6);if(Dv.test(l)){n+=String.fromCharCode(Number.parseInt(l,16)),r+=6;continue}}n+=o,r+=2}return n}function vh(e){if(e.length>=2){const t=e[0],n=e[e.length-1];if(t==='"'&&n==='"'||t==="'"&&n==="'")return e.slice(1,-1)}return e}function Mv(e){return"(!,&|?:;=[<>+-*%".includes(e)}function fn(e,t){return e==="matches"?"matches() expects 1 regular expression literal argument.":t===0?`${e}() expects no arguments.`:t===1?`${e}() expects 1 argument.`:`${e}() expects two arguments.`}function xh(e){return`${e}() expects a string argument.`}function zo(e){return`Argument ${e} of replace() must be a string.`}const _h="hasChildren() expects only a single argument (containing an array of child names).",Sh="hasChildren() expects an array of child names.",kh="hasChildren() expects an array of strings.";function Ys(e,t){switch(e){case"==":case"===":return t==="left"?"Invalid == expression: left operand is not a number, boolean, string, null.":"Invalid == expression: right operand is not a number, boolean, string, or null.";case"!=":case"!==":return`Invalid != expression: ${t} operand is not a number, boolean, string, or null.`;case"+":return`Invalid + expression: ${t} operand is not a number or string.`;case"-":case"*":case"/":case"%":return`Invalid ${e} expression: ${t} operand is not a number.`;default:return`Invalid ${e} expression: ${t} operand must be a number or string.`}}function yl(e){return`Unknown variable '${e}'.`}const jh="matches() expects a regular expression literal argument.",Eh="regular expressions do not support flags other than i";function sc(e){return e===""||e==="i"}const Lv=new Set(["__proto__","prototype","constructor"]);function gl(e,t){return Lv.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 ic(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function pr(e){if(Array.isArray(e)){const n={};for(let r=0;r<e.length;r++){if(!(r in e))continue;const s=pr(e[r]);s!==null&&(n[String(r)]=s)}return Object.keys(n).length===0?null:n}if(!ic(e))return e??null;if(Object.hasOwn(e,".value"))return pr(e[".value"]);const t={};for(const[n,r]of Object.entries(e)){if(n===".priority")continue;const s=pr(r);s!==null&&(t[n]=s)}return Object.keys(t).length===0?null:t}function Uv(e){if(!ic(e)||pr(e)===null)return null;const t=e[".priority"];return typeof t=="number"||typeof t=="string"?t:null}class Bt{_value;_path;_root;constructor(t,n="/",r){this._value=t??null,this._path=n,this._root=r!==void 0?r:t}val(){return pr(this._value)}exists(){return this.val()!==null}hasChild(t){return this.child(t).exists()}hasChildren(t){return t!==void 0?t.every(n=>this.hasChild(n)):ic(this.val())}isString(){return typeof this.val()=="string"}isNumber(){return typeof this.val()=="number"}isBoolean(){return typeof this.val()=="boolean"}child(t){const n=t.split("/").filter(o=>o.length>0);if(n.length===0)return this;let r=this._value;for(const o of n)r!=null&&typeof r=="object"?r=Object.hasOwn(r,o)?r[o]??null:null:r=null;const i=`${this._path==="/"?"":this._path}/${n.join("/")}`;return new Bt(r,i,this._root)}parent(){if(this._path==="/")throw new ee("Cannot call parent() on root.");const t=this._path.split("/").filter(r=>r.length>0);return t.pop(),t.length===0?new Bt(this._root,"/"):new Bt(this._root,"/").child(t.join("/"))}getPriority(){return Uv(this._value)}}class Bv{value;constructor(t){this.value=t}matches(t){return 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){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}}class ee extends Error{constructor(t){super(t),this.name="RtdbRuleRuntimeError"}}const bl=new Set(["val","exists","hasChild","hasChildren","isString","isNumber","isBoolean","child","parent","getPriority"]),Fv=new Set(["matches","contains","beginsWith","endsWith","replace","toLowerCase","toUpperCase"]);function Jn(e,t){if(t.length!==1)throw new ee(fn(e,1));const[n]=t;if(typeof n!="string")throw new ee(xh(e));return n}function qv(e){if(e.length===0)return;if(e.length>1)throw new ee(_h);const[t]=e;if(!Array.isArray(t))throw new ee(Sh);if(!t.every(n=>typeof n=="string"))throw new ee(kh);return t}function Vv(e){if(e.length!==1)throw new ee(fn("matches",1));const[t]=e;if(!(t instanceof RegExp))throw new ee(jh);return t}function Wv(e){if(e.length!==2)throw new ee(fn("replace",2));const[t,n]=e;if(typeof t!="string")throw new ee(zo(1));if(typeof n!="string")throw new ee(zo(2));return[t,n]}const zv=new Set(["==","===","!=","!=="]),Hv=new Set(["-","*","/","%"]),Kv=new Set(["<","<=",">",">="]);function wl(e,t){return t instanceof Bt||typeof t=="function"?!0:zv.has(e)?!1:Hv.has(e)?typeof t!="number":typeof t!="number"&&typeof t!="string"}function Be(e,t,n,r){const s=t.eval(r);if(wl(e,s))throw new ee(Ys(e,"left"));const i=n.eval(r);if(wl(e,i)||Kv.has(e)&&typeof s!=typeof i)throw new ee(Ys(e,"right"));return[s,i]}function Gv(e){return e===null?"null":Array.isArray(e)?"array":typeof e}let Yi;function Jv(){if(Yi)return Yi;const e=Zr();return e.addOperation("eval(ctx)",{Expr(t){return t.eval(this.args.ctx)},Ternary_ternary(t,n,r,s,i){const o=t.eval(this.args.ctx);if(typeof o!="boolean")throw new ee("condition of ? must be boolean.");return o?r.eval(this.args.ctx):i.eval(this.args.ctx)},Ternary(t){return t.eval(this.args.ctx)},LogicalOr_or(t,n,r){const s=t.eval(this.args.ctx);if(typeof s!="boolean")throw new ee("Left operand of || must be boolean.");if(s)return!0;const i=r.eval(this.args.ctx);if(typeof i!="boolean")throw new ee("Right operand of || must be boolean.");return i},LogicalOr(t){return t.eval(this.args.ctx)},LogicalAnd_and(t,n,r){const s=t.eval(this.args.ctx);if(typeof s!="boolean")throw new ee("Left operand of && must be boolean.");if(!s)return!1;const i=r.eval(this.args.ctx);if(typeof i!="boolean")throw new ee("Right operand of && must be boolean.");return i},LogicalAnd(t){return t.eval(this.args.ctx)},Equality_strictEq(t,n,r){const[s,i]=Be("===",t,r,this.args.ctx);return s===i},Equality_strictNeq(t,n,r){const[s,i]=Be("!==",t,r,this.args.ctx);return s!==i},Equality_looseEq(t,n,r){const[s,i]=Be("==",t,r,this.args.ctx);return s===i},Equality_looseNeq(t,n,r){const[s,i]=Be("!=",t,r,this.args.ctx);return s!==i},Equality(t){return t.eval(this.args.ctx)},Comparison_gte(t,n,r){const[s,i]=Be(">=",t,r,this.args.ctx);return s>=i},Comparison_lte(t,n,r){const[s,i]=Be("<=",t,r,this.args.ctx);return s<=i},Comparison_gt(t,n,r){const[s,i]=Be(">",t,r,this.args.ctx);return s>i},Comparison_lt(t,n,r){const[s,i]=Be("<",t,r,this.args.ctx);return s<i},Comparison(t){return t.eval(this.args.ctx)},Additive_add(t,n,r){const[s,i]=Be("+",t,r,this.args.ctx);return s+i},Additive_sub(t,n,r){const[s,i]=Be("-",t,r,this.args.ctx);return s-i},Additive(t){return t.eval(this.args.ctx)},Multiplicative_mul(t,n,r){const[s,i]=Be("*",t,r,this.args.ctx);return s*i},Multiplicative_div(t,n,r){const[s,i]=Be("/",t,r,this.args.ctx);return i===0?Number.NaN:s/i},Multiplicative_mod(t,n,r){const[s,i]=Be("%",t,r,this.args.ctx);return s%i},Multiplicative(t){return t.eval(this.args.ctx)},UnaryExpr_not(t,n){const r=n.eval(this.args.ctx);return typeof r=="boolean"?!r:!1},UnaryExpr_neg(t,n){const r=n.eval(this.args.ctx);if(typeof r!="number")throw new ee("Invalid unary - expression: operand is not a number.");return-r},UnaryExpr(t){return t.eval(this.args.ctx)},CallExpr_methodCall(t,n,r,s,i,o){const a=t.eval(this.args.ctx),l=r.sourceString,u=i.asIteration().children.map(h=>h.eval(this.args.ctx));if(a instanceof Bt)switch(l){case"val":return a.val();case"exists":return a.exists();case"hasChild":return a.hasChild(Jn(l,u));case"hasChildren":return a.hasChildren(qv(u));case"isString":return a.isString();case"isNumber":return a.isNumber();case"isBoolean":return a.isBoolean();case"child":return a.child(Jn(l,u));case"parent":return a.parent();case"getPriority":return a.getPriority();default:throw new Error(`Unknown DataSnapshot method: ${l}`)}if(typeof a=="string"){const h=new Bv(a);switch(l){case"matches":return h.matches(Vv(u));case"contains":return h.contains(Jn(l,u));case"beginsWith":return h.beginsWith(Jn(l,u));case"endsWith":return h.endsWith(Jn(l,u));case"replace":return h.replace(...Wv(u));case"toLowerCase":return h.toLowerCase();case"toUpperCase":return h.toUpperCase();default:throw bl.has(l)?new ee(`Method '${l}' is not defined on a string.`):new Error(`Unknown string method: ${l}`)}}throw(bl.has(l)||Fv.has(l))&&a!==void 0?new ee(`Method '${l}' is not defined on ${Gv(a)}.`):new Error(`Unknown method '${l}' for the given value.`)},CallExpr_memberAccess(t,n,r){const s=t.eval(this.args.ctx),i=r.sourceString;if(i==="length"){if(typeof s=="string")return s.length;throw new ee("No such method/property 'length'.")}return s==null?null:gl(s,i)},CallExpr_indexAccess(t,n,r,s){const i=t.eval(this.args.ctx),o=r.eval(this.args.ctx);if(typeof o!="string"&&typeof o!="number")throw new ee("Invalid property access.");return i==null?null:gl(i,String(o))},CallExpr(t){return t.eval(this.args.ctx)},Primary_paren(t,n,r){return n.eval(this.args.ctx)},Primary(t){return t.eval(this.args.ctx)},Array(t,n,r){return n.asIteration().children.map(s=>s.eval(this.args.ctx))},literal(t){return t.eval(this.args.ctx)},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(this.args.ctx)},string_double(t,n,r){if(Cr(this.sourceString))throw new SyntaxError(Js);return Nr(this.sourceString)},string_single(t,n,r){if(Cr(this.sourceString))throw new SyntaxError(Js);return Nr(this.sourceString)},string(t){return t.eval(this.args.ctx)},regex(t,n,r,s){if(!sc(s.sourceString))throw new ee(Eh);return new RegExp(n.sourceString,s.sourceString)},bool_true(t){return!0},bool_false(t){return!1},bool(t){return t.eval(this.args.ctx)},null(t){return null},ident(t,n,r){const s=this.args.ctx,i=this.sourceString;if(t.sourceString==="$"){const o=s?.pathVariableBindings;if(o!==void 0){if(i in o)return o[i];if(i.slice(1)in o)return o[i.slice(1)]}return}switch(i){case"auth":return s?.auth??null;case"data":return s?.data;case"newData":return s?.newData;case"root":return s?.root;case"now":return s?.now;case"query":return s?.query??null;default:return}}}),Yi=e,e}function Ch(e){const t=Xr(e);if(!t.ok)throw new Error(t.message);return Jv()(t.match)}function Ps(e,t){return Ch(e).eval(t)}const vl=new WeakMap;function Yv(e,t){let n=vl.get(e);return n===void 0&&(n=Ch(e.raw),vl.set(e,n)),n.eval(t)}let Qi;const Qv=/^\$[A-Za-z_]\w*$/,Xv=/^(?:auth|data|newData|root|query)(?:\.|\[)/;function Zv(e){return e==="now"||Qv.test(e)||Xv.test(e)}function ex(e){if(e.isLiteral())try{const t=Ps(e.sourceString,{});return typeof t=="string"?t:void 0}catch(t){if(t instanceof ee)return;throw t}}function xt(e){const[t,,n]=e.children;if(!(!t.isLiteral()||!n.isLiteral()))try{const r=Ps(t.sourceString,{}),s=Ps(n.sourceString,{});return typeof r=="number"&&!Number.isFinite(r)||typeof s=="number"&&!Number.isFinite(s)?void 0:Ps(e.sourceString,{})===!0}catch(r){if(r instanceof ee)return;throw r}}function It(e,t,n){const r=e.args.ctx;t.lint(r),n.lint(r);const s=xt(e);if(s!==void 0){r.constantComparisons.push({source:e.sourceString,value:s});return}const i=t.isLiteral(),o=n.isLiteral();if(i===o)return;let a=n;i&&(a=t);const l=ex(a);l!==void 0&&Zv(l)&&r.warnings.push({code:"QUOTED_REFERENCE",message:`Comparison ${e.sourceString} quotes '${l}' as a string literal; it compares against the literal text '${l}' rather than evaluating ${l}.`})}function tx(){if(Qi)return Qi;const e=Zr();return e.addOperation("lint(ctx)",{_nonterminal(...t){t.forEach(n=>n.lint(this.args.ctx))},_iter(...t){t.forEach(n=>n.lint(this.args.ctx))},_terminal(){},CallExpr_methodCall(t,n,r,s,i,o){const a=this.args.ctx;t.lint(a),i.asIteration().children.forEach(l=>l.lint(a)),r.sourceString==="child"&&t.isDataSnapshot()&&(a.hasDataChildAccess=!0)},CallExpr_memberAccess(t,n,r){t.lint(this.args.ctx)},ident(t,n,r){const s=this.args.ctx,i=this.sourceString;i==="data"&&(s.hasData=!0),i==="newData"&&(s.hasNewData=!0)},Equality_strictEq(t,n,r){It(this,t,r)},Equality_strictNeq(t,n,r){It(this,t,r)},Comparison_gte(t,n,r){It(this,t,r)},Comparison_lte(t,n,r){It(this,t,r)},Comparison_gt(t,n,r){It(this,t,r)},Comparison_lt(t,n,r){It(this,t,r)},Equality_looseEq(t,n,r){It(this,t,r)},Equality_looseNeq(t,n,r){It(this,t,r)}}),e.addOperation("isDataSnapshot",{_nonterminal(...t){return t.length===1?t[0].isDataSnapshot():!1},_iter(){return!1},_terminal(){return!1},Primary_paren(t,n,r){return n.isDataSnapshot()},ident(t,n,r){return this.sourceString==="data"},CallExpr_methodCall(t,n,r,s,i,o){const a=r.sourceString;return a==="parent"||a==="child"?t.isDataSnapshot():!1}}),e.addOperation("isNumberLiteral",{_nonterminal(...t){return t.length===1?t[0].isNumberLiteral():!1},_iter(){return!1},_terminal(){return!1},Primary_paren(t,n,r){return n.isNumberLiteral()},UnaryExpr_neg(t,n){return n.isNumberLiteral()},Additive_add(t,n,r){return t.isNumberLiteral()&&r.isNumberLiteral()},Additive_sub(t,n,r){return t.isNumberLiteral()&&r.isNumberLiteral()},Multiplicative_mul(t,n,r){return t.isNumberLiteral()&&r.isNumberLiteral()},Multiplicative_div(t,n,r){return t.isNumberLiteral()&&r.isNumberLiteral()},Multiplicative_mod(t,n,r){return t.isNumberLiteral()&&r.isNumberLiteral()},number(t){return Number.isFinite(Number(this.sourceString))}}),e.addOperation("isLiteral",{_nonterminal(...t){return t.length===1?t[0].isLiteral():!1},_iter(){return!1},_terminal(){return!1},Primary_paren(t,n,r){return n.isLiteral()},UnaryExpr_neg(t,n){return n.isNumberLiteral()},Additive_add(t,n,r){return t.isNumberLiteral()&&r.isNumberLiteral()},Additive_sub(t,n,r){return t.isNumberLiteral()&&r.isNumberLiteral()},Multiplicative_mul(t,n,r){return t.isNumberLiteral()&&r.isNumberLiteral()},Multiplicative_div(t,n,r){return t.isNumberLiteral()&&r.isNumberLiteral()},Multiplicative_mod(t,n,r){return t.isNumberLiteral()&&r.isNumberLiteral()},literal(t){return t.ctorName==="regex"?!1:t.ctorName==="number"?Number.isFinite(Number(t.sourceString)):!0}}),e.addOperation("literalBoolean",{_nonterminal(...t){return t.length===1?t[0].literalBoolean():void 0},_iter(){},_terminal(){},Primary_paren(t,n,r){return n.literalBoolean()},bool_true(t){return!0},bool_false(t){return!1},Equality_strictEq(t,n,r){return xt(this)},Equality_strictNeq(t,n,r){return xt(this)},Comparison_gte(t,n,r){return xt(this)},Comparison_lte(t,n,r){return xt(this)},Comparison_gt(t,n,r){return xt(this)},Comparison_lt(t,n,r){return xt(this)},Equality_looseEq(t,n,r){return xt(this)},Equality_looseNeq(t,n,r){return xt(this)}}),Qi=e,e}function nx(e,t="read"){const n=Xr(e);if(!n.ok)return[];const{match:r}=n,s={warnings:[],hasData:!1,hasNewData:!1,hasDataChildAccess:!1,constantComparisons:[]};try{const i=tx()(r);i.lint(s);const o=t==="validate"?void 0:i.literalBoolean();if(o===!0)s.warnings.push({code:"HARDCODED_TRUE",message:"Rule expression is hardcoded to true"});else if(o===!1)s.warnings.push({code:"HARDCODED_FALSE",message:"Rule expression is hardcoded to false"});else for(const{source:a,value:l}of s.constantComparisons)s.warnings.push({code:"CONSTANT_COMPARISON",message:`Comparison ${a} is always ${l}.`})}catch(i){if(i instanceof RangeError)return[{code:"PARSE_ERROR",message:Qr}];if(i instanceof SyntaxError)return[{code:"PARSE_ERROR",message:i.message}];throw i}return t==="write"&&s.hasData&&!s.hasNewData&&!s.hasDataChildAccess&&s.warnings.push({code:"DATA_IN_WRITE",message:"Write rule references 'data' but not 'newData'; consider using 'newData' to check incoming data"}),s.warnings}const rx=()=>ae("newData.hasChildren()"),sx=e=>ae(`newData.hasChild(${Ye(e)})`);let Xi;function ix(){if(Xi)return Xi;const e=Zr();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,o){return[...t.identifiers(),...i.asIteration().children.flatMap(a=>a.identifiers())]},CallExpr_memberAccess(t,n,r){return t.identifiers()},ident(t,n,r){return[this.sourceString]}}),Xi=e,e}const ox="Rule expressions may not contain assignments.";function ax(e){const t=e.replace(/'(?:\\.|[^'\\])*'?|"(?:\\.|[^"\\])*"?|\/(?:\\.|\[(?:\\.|[^\]\\\n])*\]|[^/\\\n[])+\/[a-zA-Z]*/g,'""');return/(^|[^=!<>])=(?!=)/.test(t)}function cx(e){if(Tv(e))return{raw:e,valid:!1,errors:[{code:"PARSE_ERROR",message:Js}],warnings:[],referencedIdentifiers:[]};const t=Xr(e);if(!t.ok)return{raw:e,valid:!1,errors:[{code:"PARSE_ERROR",message:ax(e)?ox:t.message}],warnings:[],referencedIdentifiers:[]};let n;try{n=ix()(t.match).identifiers()}catch(s){if(s instanceof RangeError)return{raw:e,valid:!1,errors:[{code:"PARSE_ERROR",message:Qr}],warnings:[],referencedIdentifiers:[]};throw s}const r=[...new Set(n)];return{raw:e,valid:!0,errors:[],warnings:[],referencedIdentifiers:r}}function lx(e){return e==="rtdb"?"database":"firestore"}function Yn(e){return e.kind==="doc"?e.path:{collection:e.collection,query:e.query}}function ux(e){return e.path!==void 0?e.path:{collection:"",query:e.query}}function xl(e){const t=e.query;return t===void 0?{}:{query:t}}function dx(e){const t=Qa(e),n="owners"in e&&Array.isArray(e.owners)?e.owners:void 0,r={actor:t.source,authLens:t.authLens,owners:n};return e.kind==="listener_attach"?{phase:"attach",listenerId:e.listenerId,service:"firestore",target:Yn(e.target),...r,...xl(e.target)}:e.kind==="listener_detach"?{phase:"detach",listenerId:e.listenerId,service:"firestore",target:Yn(e.target),...r}:e.kind==="listener_errored"?{phase:"errored",listenerId:e.listenerId,service:"firestore",target:Yn(e.target),...r}:e.kind==="snapshot_delivery"?{phase:"delivery",listenerId:e.listenerId,service:"firestore",target:Yn(e.target),...r}:e.kind==="snapshot_suppressed"?{phase:"suppressed",listenerId:e.listenerId,service:"firestore",target:Yn(e.target),...r}:e.kind==="listener"?{phase:e.phase,listenerId:e.listenerId,service:lx(e.service),target:ux(e.target),...r,...xl(e.target)}:null}function oc(e){const t=fx();for(const n of e)t.append(n);return t.snapshot()}function fx(){const e=new Map;return{append:n=>{const r=dx(n);if(r===null)return;if(r.phase==="attach"){const d={id:r.listenerId,service:r.service,target:r.target,actor:r.actor,authLens:r.authLens,attachedAt:n.at,deliveryCount:0,suppressedCount:0};r.owners!==void 0&&(d.owners=[...r.owners]),r.query!==void 0&&(d.query=r.query);const p=n.activity?.listenerId;typeof p=="string"&&(d.clientListenerId=p),e.set(r.listenerId,d);return}const o=e.get(r.listenerId);if(o===void 0)return;if(r.phase==="delivery"){o.deliveryCount+=1,o.lastDeliveryAt=n.at,r.owners!==void 0&&(o.owners=hx(o.owners,r.owners));return}if(r.phase==="suppressed"){o.suppressedCount+=1;return}e.delete(r.listenerId)},snapshot:()=>Object.freeze([...e.values()].map(n=>Object.freeze({...n}))),clear:()=>e.clear()}}function hx(e,t){const n=t.filter(s=>s.kind==="regions");return n.length===0?[...e??[]]:[...(e??[]).filter(s=>s.kind!=="regions"),...n]}function px(e,t){return typeof e=="string"?e.startsWith(t):e.collection.startsWith(t)}const Nh=Symbol("pyric/auth/target"),mx=Symbol("pyric.user.internal");function Y(e,t){return new H(e,`Firebase: ${t} (${e}).`)}const Rh={PASSWORD:"password"},Zi={EMAIL_LINK:"emailLink",EMAIL_PASSWORD:"password"};class _i{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"?yx(t):t;if(!n)return null;const r=n.providerId,s=n.signInMethod;if(typeof r!="string"||typeof s!="string")return null;if(r===Rh.PASSWORD){const i=typeof n.email=="string"?n.email:"",o=typeof n.password=="string"?n.password:"";return new gx(i,o,s)}return new _i(r,s)}}function yx(e){try{const t=JSON.parse(e);return typeof t=="object"&&t!==null?t:null}catch{return null}}class gx extends _i{email;secret;constructor(t,n,r=Zi.EMAIL_PASSWORD){super(Rh.PASSWORD,r),this.email=t,Object.defineProperty(this,"secret",{value:n,enumerable:!1,writable:!1})}get password(){return this.signInMethod===Zi.EMAIL_PASSWORD?this.secret:null}get emailLink(){return this.signInMethod===Zi.EMAIL_LINK?this.secret:null}toJSON(){return{providerId:this.providerId,signInMethod:this.signInMethod,email:this.email,password:this.secret}}}class Si extends _i{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 ac(e,t){return t?new Si(e,e):null}class _n{static PROVIDER_ID="google.com";static GOOGLE_SIGN_IN_METHOD="google.com";providerId=_n.PROVIDER_ID;addScope(t){return this}setCustomParameters(t){return this}static credentialFromResult(t){return ac(_n.PROVIDER_ID,t)}static credentialFromError(t){return null}static credential(t,n){return new Si(_n.PROVIDER_ID,_n.GOOGLE_SIGN_IN_METHOD,{idToken:t??void 0,accessToken:n??void 0})}}class Sn{static PROVIDER_ID="facebook.com";static FACEBOOK_SIGN_IN_METHOD="facebook.com";providerId=Sn.PROVIDER_ID;addScope(t){return this}setCustomParameters(t){return this}static credentialFromResult(t){return ac(Sn.PROVIDER_ID,t)}static credentialFromError(t){return null}static credential(t){return new Si(Sn.PROVIDER_ID,Sn.FACEBOOK_SIGN_IN_METHOD,{accessToken:t})}}class kn{static PROVIDER_ID="github.com";static GITHUB_SIGN_IN_METHOD="github.com";providerId=kn.PROVIDER_ID;addScope(t){return this}setCustomParameters(t){return this}static credentialFromResult(t){return ac(kn.PROVIDER_ID,t)}static credentialFromError(t){return null}static credential(t){return new Si(kn.PROVIDER_ID,kn.GITHUB_SIGN_IN_METHOD,{accessToken:t})}}const Ih=[_n.PROVIDER_ID,"apple.com",Sn.PROVIDER_ID,kn.PROVIDER_ID,"twitter.com","microsoft.com","yahoo.com"];function cc(e,t=!1){const n=e[Nh];if(!n)throw new TypeError("pyric/auth: unrecognized Auth handle — was it produced by getAuth(...)?");return t||n.assertAlive?.(),n}class bx{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 wx(e,t,n){const r=JSON.stringify(t);return`sandbox-id-token-${e}-${String(n)}:${r}`}function Qt(e){if(typeof e!="string"||e.length===0)throw Y("auth/invalid-email","Error");const t=e.indexOf("@");if(t<=0||t===e.length-1)throw Y("auth/invalid-email","Error")}function Qn(e){if(typeof e!="string"||e.length<6)throw Y("auth/weak-password","Password should be at least 6 characters")}function Ah(){return{usersByEmail:new Map,usersByUid:new Map,userDbSubscribers:new Set,providerConfig:new Map([["password",!0],["anonymous",!0]]),providerConfigSubscribers:new Set,counters:{nextAdminUserId:1}}}const vx=2166136261,xx=2654435769,_x=16777619;function _l(e,t){let n=t;for(let r=0;r<e.length;r++)n^=e[r],n=Math.imul(n,_x);return n>>>0}function Sl(e){return e.toString(16).padStart(8,"0")}function Sx(e){const t=new TextEncoder().encode(e),n=new TextEncoder().encode([...e].reverse().join("")),r=_l(t,vx),s=_l(n,xx);return Sl(r)+Sl(s)}function kx(e){const t=Number.parseInt(e.slice(0,8),16),n=Number.parseInt(e.slice(8,16),16),r=t%360,s=40+n%80,i=(r+s)%360,o=60+t%16,a=45+n%16;return{hueStart:r,hueEnd:i,saturation:o,lightness:a}}function kl(e){const n=new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(e)[Symbol.iterator]().next();if(!n.done)return n.value.segment}function jx(e){const t=e.displayName?.trim();if(t){const r=kl(t);if(r)return r.toUpperCase()}const n=e.email?.split("@")[0]?.trim();if(n){const r=kl(n);if(r)return r.toUpperCase()}}function Ex(e){return encodeURIComponent(e).replace(/'/g,"%27").replace(/\(/g,"%28").replace(/\)/g,"%29")}function Cx(e){const t=Sx(e.uid),{hueStart:n,hueEnd:r,saturation:s,lightness:i}=kx(t),o=`g${t}`,a=jx(e),l=e.pending===!0,u=a===void 0?"":`<text x="64" y="64" font-family="system-ui, -apple-system, sans-serif" font-size="56" fill="#fff" fill-opacity="${l?"0.55":"0.9"}" text-anchor="middle" dominant-baseline="central">${a}</text>`;return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128"><defs><linearGradient id="${o}" x1="0" y1="0" x2="1" y2="1"><stop offset="0%" stop-color="hsl(${n},${s}%,${i}%)"/><stop offset="100%" stop-color="hsl(${r},${s}%,${i}%)"/></linearGradient></defs><rect width="128" height="128" fill="url(#${o})"/>${u}${l?'<circle cx="64" cy="64" r="56" fill="none" stroke="#fff" stroke-opacity="0.25" stroke-width="6"/><circle cx="64" cy="64" r="56" fill="none" stroke="#fff" stroke-opacity="0.95" stroke-width="6" stroke-linecap="round" stroke-dasharray="44 308"><animateTransform attributeName="transform" type="rotate" from="0 64 64" to="360 64 64" dur="1s" repeatCount="indefinite"/></circle>':""}</svg>`}function Nx(e){return`data:image/svg+xml,${Ex(Cx(e))}`}const Rx=e=>Nx(e),Oh="(default)";function $h(e){return`${e}-default-rtdb`}function Dh(e,t){return t!==void 0&&t.length>0&&(e===t||e===$h(t))}function Ph(e){const t=Ix(e,"Invalid Firebase Database URL");if(t.path!=="/")throw Qs("Database URL must point to the root of a Firebase Database (not including a child path).");return t.instance}function Ix(e,t){const n=$x(e);if(n.domain==="firebase.com")throw Qs(`${n.host} is no longer supported. Please use <YOUR FIREBASE>.firebaseio.com instead`);const r=n.namespace;if((!r||r==="undefined")&&n.domain!=="localhost")throw Qs("Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com");const s=n.host.toLowerCase(),i=n.pathSegments.length===0?"/":`/${n.pathSegments.join("/")}`;if(s.length===0||!Ux(r)&&s.split(":")[0]!=="localhost"||!Bx(i))throw new Error(`${t} failed: url argument must be a valid firebase URL and the path can't contain ".", "#", "$", "[", or "]".`);const o=r!==n.subdomain?`?ns=${r}`:"";return{instance:{name:r,url:`${n.secure?"https://":"http://"}${s}/${o}`},host:s,path:i}}function lc(e){if(!Tx.test(e))throw Qs("Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com");return Ph(`${e}.firebaseio.com`)}function Ax(e){if(e===void 0)return;const t=e.trim();if(!(t===""||t.toLowerCase()==="default"))return/^[^./:?#]+$/.test(t)?lc(t):Ph(e)}function Ho(e,t){return e===void 0?t??Oh:e.name}function Ox(e){const t=new Map;return{defaultKey:Ho(void 0,e.defaultName),keyOf:r=>Ho(r,e.defaultName),getOrCreate(r){let s=t.get(r);return s===void 0&&(s=e.create(r),t.set(r,s)),s},get:r=>t.get(r),delete:r=>t.delete(r),entries:()=>t.entries()}}function $x(e){let t=e,n="",r="",s="",i="",o=[],a=!0,l="https",u=t.indexOf("//");u>=0&&(l=t.substring(0,u-1),t=t.substring(u+2));let d=t.indexOf("/");d===-1&&(d=t.length);let h=t.indexOf("?");h===-1&&(h=t.length),n=t.substring(0,Math.min(d,h)),d<h&&(o=Dx(t.substring(d,h)));const f=Px(t.substring(Math.min(t.length,h)));u=n.indexOf(":"),u>=0?a=l==="https"||l==="wss":u=n.length;const p=n.slice(0,u);if(p.toLowerCase()==="localhost")r="localhost";else if(p.split(".").length<=2)r=p;else{const m=n.indexOf(".");s=n.substring(0,m).toLowerCase(),r=n.substring(m+1),i=s}return Object.prototype.hasOwnProperty.call(f,"ns")&&(i=f.ns),{host:n,domain:r,subdomain:s,secure:a,pathSegments:o,namespace:i}}function Dx(e){const t=[];for(const n of e.split("/")){if(n.length===0)continue;let r=n;try{r=decodeURIComponent(n.replace(/\+/g," "))}catch{}t.push(r)}return t}function Px(e){const t={};e.charAt(0)==="?"&&(e=e.substring(1));for(const n of e.split("&")){if(n.length===0)continue;const r=n.split("=");r.length===2&&(t[decodeURIComponent(r[0])]=decodeURIComponent(r[1]))}return t}const Tx=/^[A-Za-z0-9][A-Za-z0-9-]*$/,Mx=/[[\].#$/\u0000-\u001F\u007F]/,Lx=/[[\].#$\u0000-\u001F\u007F]/;function Ux(e){return e.length!==0&&!Mx.test(e)}function Bx(e){const t=e.replace(/^\/*\.info(\/|$)/,"/");return t.length!==0&&!Lx.test(t)}function Qs(e){return new Error(`FIREBASE FATAL ERROR: ${e} `)}const Fx=new Set(["__proto__","prototype","constructor"]);function q(e){if(e===""||e==="/")return[];const t=e.split("/").filter(n=>n.length>0);for(const n of t)if(Fx.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 G(e){return e.length===0?"/":"/"+e.join("/")}function Mt(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>Mt(n));const t={};for(const[n,r]of Object.entries(e))t[n]=Mt(r);return t}function Ko(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function an(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)=>an(s,t[i]));if(!Ko(e)||!Ko(t))return!1;const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(s=>s in t&&an(e[s],t[s]))}class qx{root={};snapshot(){return Mt(this.root)}restore(t){this.root=Mt(t)}read(t){const n=q(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 o=s;if(!Object.hasOwn(o,i))return null;s=o[i]}return Ko(s)&&Object.keys(s).length===0?null:Mt(s)}write(t,n){const r=q(t),s=this.read(t);if(r.length===0)return n===null?(this.root={},s):(this.root=Mt(n),s);(this.root===null||typeof this.root!="object"||Array.isArray(this.root))&&(this.root={});let i=this.root;for(let a=0;a<r.length-1;a++){const l=r[a],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 o=r[r.length-1];return n===null?(delete i[o],this.trim(r)):i[o]=Mt(n),s}multiUpdate(t){const r=Object.entries(t).map(([i,o])=>({path:G(q(i)),value:o}));for(let i=0;i<r.length;i++)for(let o=i+1;o<r.length;o++){const a=r[i].path,l=r[o].path;if(a===l)throw new Error(`multi-path update: duplicate path '${a}'.`);const u=a==="/"?"/":a+"/",d=l==="/"?"/":l+"/";if(a!=="/"&&l.startsWith(u))throw new Error(`multi-path update: '${l}' is a descendant of '${a}'.`);if(l!=="/"&&a.startsWith(d))throw new Error(`multi-path update: '${a}' is a descendant of '${l}'.`)}const s=[];for(const{path:i,value:o}of r){const a=this.write(i,o);s.push({path:i,prior:a})}return s}shallowUpdate(t,n){const r=[],s=q(t);for(const[i,o]of Object.entries(n)){const a=[...s,...q(i)],l=G(a),u=this.write(l,o);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 a=0;a<r.length-1;a++){const l=i[r[a]];if(l==null||typeof l!="object"||Array.isArray(l))return;i=l}const o=i[s];if(o!==void 0&&typeof o=="object"&&o!==null&&!Array.isArray(o)&&Object.keys(o).length===0){delete i[s];continue}return}}}const Vx="12.13.0",Wx=/[\[\].#$/\u0000-\u001F\u007F]/;function zx(e){return e.length!==0&&!Wx.test(e)}function Hx(e){return typeof e=="number"&&(Number.isNaN(e)||e===1/0||e===-1/0)}function Kx(e){return e===".priority"||e===".value"||e===".sv"}function Gx(e,t){Go(e,t,"set")}function Go(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(Hx(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&&Go(s,`${t}/${r}`,n)}return}for(const[r,s]of Object.entries(e)){if(!Kx(r)&&!zx(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 "]"`);Go(s,`${t}/${r}`,n)}}}function Zt(e,t){return Gx(e,t),mr(e)}function mr(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=mr(e[r]);s!==null&&(n[String(r)]=s)}return Object.keys(n).length===0?null:n}if(Object.hasOwn(e,".value"))return mr(e[".value"]);const t={};for(const[n,r]of Object.entries(e)){if(n===".priority")continue;if(n===".sv"){t[n]=r;continue}const s=mr(r);s!==null&&(t[n]=s)}return Object.keys(t).length===0?null:t}function Jx(e){const t=[],n=(r,s)=>{if(r===null||typeof r!="object")return;const i=!Array.isArray(r);if(i&&Object.hasOwn(r,".priority")){const o=r[".priority"],a=typeof o=="object"&&o!==null&&".sv"in o;if(o!==null&&typeof o!="string"&&typeof o!="number"&&!a)throw new Error(`Firebase Database (${Vx}) INTERNAL ASSERT FAILED: Invalid priority type found: ${typeof o}`);a||t.push({segments:s,priority:o})}if(i&&Object.hasOwn(r,".value")){n(r[".value"],s);return}for(const[o,a]of Object.entries(r))o.startsWith(".")||n(a,[...s,o])};return n(e,[]),t}function en(e,t){const n=Jx(e),r=n.find(s=>s.segments.length===0);return{priority:r?r.priority:t,inline:r!==void 0,nested:n.filter(s=>s.segments.length>0)}}function jl(e,t){return typeof e=="object"&&e!==null&&!Array.isArray(e)?{...e,".priority":t}:{".value":e,".priority":t}}function mt(e,t){const n=t.filter(s=>s.priority!==null);if(n.length===0||e===null)return e;let r=structuredClone(e);for(const{segments:s,priority:i}of n){if(s.length===0){r=jl(r,i);continue}let o=r;for(const u of s.slice(0,-1))o=typeof o=="object"&&o!==null&&!Object.hasOwn(o,".value")?o[u]:void 0;const a=s[s.length-1];if(typeof o!="object"||o===null||!Object.hasOwn(o,a))continue;const l=o;l[a]!==null&&(l[a]=jl(l[a],i))}return r}function Yx(e,t=null){const n=en(e,t),r=mr(e);return mt(r,[{segments:[],priority:n.priority},...n.nested])}function Ts(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(o=>Ts(o));const t=e,n=Object.keys(t);let r=n.length>0,s=0;for(const o of n)if(/^(0|[1-9]\d*)$/.test(o))s=Math.max(s,Number(o));else{r=!1;break}if(r&&s<2*n.length){const o=[];for(let a=0;a<=s;a++){const l=t[String(a)];o[a]=l===void 0?null:Ts(l)}return o}const i={};for(const[o,a]of Object.entries(t))i[o]=Ts(a);return i}function Th(e){return"/"+e.split("/").filter(Boolean).join("/")}function El(e,t){return new Error(`Index not defined, add ".indexOn": "${t}", for path "${Th(e)}", to the rules`)}function Qx(e){return e.limit===null&&e.bounds.length===0}function Xx(e,t){return`Using an unspecified index. Your data will be downloaded and filtered on the client. Consider adding ".indexOn": "${t}" at ${Th(e)} to your security rules for better performance.`}function Zx(e){console.warn(`[${new Date().toISOString()}] @firebase/database:`,`FIREBASE WARNING: ${e} `)}function e_(e,t){return e==="/"||t==="/"?!0:e===t||e.startsWith(`${t}/`)||t.startsWith(`${e}/`)}class t_{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=>G(q(n)))})}conflictsSince(t,n){const r=G(q(n));return this.mutations.some(s=>s.version>t&&s.paths.some(i=>e_(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 nt(e){return e==="unsupported"?"unsupported":"deny"}function Dn(e){const t={engine:"rtdb",matchedPath:e.matchedPath,matchedRule:e.matchedRule,pathVariableBindings:e.pathVariableBindings,reason:e.reason,errorCode:e.errorCode};return e.trace!==void 0&&(t.rtdbTrace=e.trace),t}function De(e,t,n,r,s={}){const i={method:n,path:yt(r)};return s.data!==void 0&&(i.data=structuredClone(s.data)),s.query!==void 0&&(i.query=structuredClone(s.query)),{...Object.fromEntries(Object.entries(Dn(e)).filter(([,a])=>a!==void 0)),engine:"rtdb",auth:t===null?null:structuredClone(t),reasons:[...e.reasons],request:i}}function yt(e){return G(q(e))}class n_{sandbox;nextId=0;instanceField;constructor(t,n){this.sandbox=t,this.instanceField=n===void 0?{}:{instance:n}}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{pt(this.sandbox,Ln({at:Te(this.sandbox).now(),service:"rtdb",...this.instanceField,op:n,path:r,auth:t,before:s.before,after:s.after,detail:s.detail}),{service:"rtdb"})}catch{}}operation(t,n,r,s,i,o={}){if(this.sandbox)try{let a;i&&(a=Dn(i));let l="user";o.origin&&(l=o.origin);let u=o.at;u===void 0&&(u=Te(this.sandbox).now()),pt(this.sandbox,Hf({service:"rtdb",...this.instanceField,method:n,path:yt(r),auth:t,result:s,origin:l,durationMs:o.durationMs,reasons:i?.reasons,rules:a,request:o.request,resourceBefore:o.resourceBefore,resourceAfter:o.resourceAfter,groupId:o.groupId,groupKind:o.groupKind,triggeredBy:o.triggeredBy,detail:o.detail,at:u}),{service:"rtdb"})}catch{}}commit(t,n,r,s={}){if(this.sandbox)try{pt(this.sandbox,Sb({at:Te(this.sandbox).now(),service:"rtdb",...this.instanceField,method:n,path:yt(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),pt(this.sandbox,kb({at:Te(this.sandbox).now(),service:"rtdb",...this.instanceField,phase:t,listenerId:n.id,target:{kind:i,path:yt(n.path),...s.query===void 0?{}:{query:s.query}},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,owners:s.owners}),{service:"rtdb"})}catch{}}}class r_{values=new Map;get(t){return this.values.get(G(q(t)))??null}forChild(t){const n=q(t);return r=>this.get(G([...n,r]))}atOrBelow(t){const n=G(q(t)),r=n==="/"?"/":`${n}/`,s={};for(const[i,o]of this.values)(i===n||i.startsWith(r))&&(s[i]=o);return s}clear(){this.values.clear()}clearAtOrBelow(t){const n=G(q(t)),r=n==="/"?"/":`${n}/`;for(const s of this.values.keys())(s===n||s.startsWith(r))&&this.values.delete(s)}replace(t,n,r){if(this.clearAtOrBelow(t),n!==null){this.values.set(G(q(t)),n);return}r&&this.pruneMissingAncestors(t,r)}set(t,n){const r=G(q(t));n===null?this.values.delete(r):this.values.set(r,n)}stateAtOrBelow(t){const n=G(q(t)),r=n==="/"?"/":`${n}/`;return JSON.stringify([...this.values].filter(([s])=>s===n||s.startsWith(r)).sort(([s],[i])=>s.localeCompare(i)))}applyUpdate(t,n){for(const r of t)this.clearAtOrBelow(r.path),r.value===null&&n&&this.pruneMissingAncestors(r.path,n)}pruneMissingAncestors(t,n){const r=q(t);for(let s=r.length-1;s>=0;s-=1){const i=G(r.slice(0,s));if(n(i))break;this.values.delete(i)}}entries(){return this.values.entries()}restore(t){this.values.clear();for(const[n,r]of Object.entries(t))this.values.set(G(q(n)),r)}}function Lt(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)")}const Bn=(...e)=>new Set(["Error",...e]),Rr=Bn("Boolean"),s_=Bn("Boolean","Number","String","Null","NullableSnapshot","Value","Auth","QueryValue","Mixed"),i_=Bn("Number","String","Value","Auth","QueryValue","Mixed"),o_=Bn("Number","String","Value","Auth","QueryValue","Mixed"),Mh=Bn("Number","Value","Auth","QueryValue","Mixed"),uc=Bn("String","Value","Auth","Mixed"),Cl=new Set(["String","Value","Auth"]),Nl=new Set(["Snapshot","NullableSnapshot","Null"]);function a_(e,t){return e===t?e:Nl.has(e)&&Nl.has(t)?"NullableSnapshot":Cl.has(e)||Cl.has(t)?"Value":"Mixed"}function ue(e,t){return{code:e,message:t}}function c_(e){switch(e){case"==":case"===":case"!=":case"!==":return s_;case"<":case"<=":case">":case">=":case"+":return i_;default:return Mh}}function l_(e,t,n){return e!=="+"&&e!=="-"&&e!=="*"&&e!=="/"&&e!=="%"?"Boolean":t==="Error"||n==="Error"?"Error":e!=="+"?"Number":t==="String"||n==="String"?"String":t==="Number"&&n==="Number"?"Number":"Value"}const gt=e=>ue("INVALID_ARGUMENT",e);function _t(e){return{returns:e,check:(t,n)=>n.length===0?null:gt(fn(t,0))}}function yr(e){return{returns:e,check(t,n){return n.length!==1?gt(fn(t,1)):uc.has(n[0].type)?null:gt(xh(t))}}}const u_={returns:"Boolean",check(e,t){if(t.length===0)return null;if(t.length>1)return gt(_h);const n=t[0];return n.type==="Error"?null:n.type!=="Array"?gt(Sh):(n.elements??[]).every(r=>uc.has(r))?null:gt(kh)}},d_={returns:"String",check(e,t){if(t.length!==2)return gt(fn(e,2));const n=t.findIndex(r=>!uc.has(r.type));return n===-1?null:gt(zo(n===0?1:2))}},f_={returns:"Boolean",check(e,t){if(t.length!==1)return gt(fn(e,1));const n=t[0].type;return n==="Regex"||n==="Error"?null:gt(jh)}},h_=new Map([["val",_t("Value")],["exists",_t("Boolean")],["isString",_t("Boolean")],["isNumber",_t("Boolean")],["isBoolean",_t("Boolean")],["parent",_t("Snapshot")],["getPriority",_t("Value")],["child",yr("Snapshot")],["hasChild",yr("Boolean")],["hasChildren",u_]]),Rl=new Map([["contains",yr("Boolean")],["beginsWith",yr("Boolean")],["endsWith",yr("Boolean")],["replace",d_],["toLowerCase",_t("String")],["toUpperCase",_t("String")],["matches",f_]]),p_=new Map([["orderByKey","Boolean"],["orderByValue","Boolean"],["orderByPriority","Boolean"],["orderByChild","QueryValue"],["startAt","QueryValue"],["endAt","QueryValue"],["equalTo","QueryValue"],["limitToFirst","QueryValue"],["limitToLast","QueryValue"]]),m_="Invalid property access: target is not an object.";function Lh(e,t){const n=()=>({kind:"error",error:ue("NO_SUCH_MEMBER",`No such method/property '${t}'.`)});switch(e){case"Error":return{kind:"error",error:null};case"Snapshot":case"NullableSnapshot":{const r=h_.get(t);return r?{kind:"method",method:r}:n()}case"String":case"Value":{const r=Rl.get(t);return r?{kind:"method",method:r}:t==="length"?{kind:"property",type:"Number"}:n()}case"Auth":{const r=Rl.get(t);return r?{kind:"method",method:r}:{kind:"property",type:"Auth"}}case"Query":{const r=p_.get(t);return r?{kind:"property",type:r}:n()}default:return{kind:"error",error:ue("NOT_AN_OBJECT",m_)}}}const y_=new Map([["auth","Auth"],["data","Snapshot"],["newData","Snapshot"],["root","Snapshot"],["now","Number"],["query","Query"]]),St={type:"Error"},Ne=e=>({type:e});function me(e,t){return e.errors.push(t),St}function Re(e,t){return t.type!=="Array"?t.type:(me(e,ue("UNEXPECTED_ARRAY","Unexpected array literal.")),"Error")}function je(e,t){return e.typeOf(t)}function Fe(e,t,n){const r=this.args.ctx,s=t.sourceString,i=Re(r,je(e,r)),o=Re(r,je(n,r)),a=c_(s);return a.has(i)?a.has(o)?Ne(l_(s,i,o)):me(r,ue("INVALID_OPERAND",Ys(s,"right"))):me(r,ue("INVALID_OPERAND",Ys(s,"left")))}function Il(e,t,n){const r=this.args.ctx,s=t.sourceString,i=Re(r,je(e,r)),o=Re(r,je(n,r));return Rr.has(i)?Rr.has(o)?Ne(i==="Error"||o==="Error"?"Error":"Boolean"):me(r,ue("INVALID_OPERAND",`Right operand of ${s} must be boolean.`)):me(r,ue("INVALID_OPERAND",`Left operand of ${s} must be boolean.`))}function Al(e,t,n){const r=Lh(Re(e,t),n);return r.kind==="error"?r.error?me(e,r.error):St:Ne(r.kind==="method"?"SnapshotMethod":r.type)}function g_(e){let t=0,n=!1;for(let r=0;r<e.length;r++){const s=e[r];if(s==="\\"){r++;continue}if(n){s==="]"&&(n=!1);continue}if(s==="["){n=!0;continue}if(s==="(")t++;else if(s===")"&&(t--,t<0))return`Illegal regular expression, unexpected ')' at position ${r+2}`}return t>0?`Illegal regular expression, expected ')' at position ${e.length+4}`:null}let eo;function b_(){if(eo)return eo;const e=Zr();return e.addOperation("literalString",{_nonterminal(...t){return t.length===1?t[0].literalString():void 0},_iter(){},_terminal(){},Primary_paren(t,n,r){return n.literalString()},string(t){return Nr(this.sourceString)}}),e.addOperation("typeOf(ctx)",{_nonterminal(...t){return t.length===1?je(t[0],this.args.ctx):St},_iter(){return St},_terminal(){return St},Ternary_ternary(t,n,r,s,i){const o=this.args.ctx,a=Re(o,je(t,o)),l=Re(o,je(r,o)),u=Re(o,je(i,o));return Rr.has(a)?l==="Error"||u==="Error"?St:Ne(a_(l,u)):me(o,ue("INVALID_OPERAND","condition of ? must be boolean."))},LogicalAnd_and:Il,LogicalOr_or:Il,Equality_strictEq:Fe,Equality_strictNeq:Fe,Comparison_gte:Fe,Comparison_lte:Fe,Comparison_gt:Fe,Comparison_lt:Fe,Equality_looseEq:Fe,Equality_looseNeq:Fe,Additive_add:Fe,Additive_sub:Fe,Multiplicative_mul:Fe,Multiplicative_div:Fe,Multiplicative_mod:Fe,UnaryExpr_not(t,n){const r=this.args.ctx,s=Re(r,je(n,r));return Rr.has(s)?Ne(s==="Error"?"Error":"Boolean"):me(r,ue("INVALID_OPERAND","! only operates on booleans."))},UnaryExpr_neg(t,n){const r=this.args.ctx,s=Re(r,je(n,r));return Mh.has(s)?Ne(s==="Error"?"Error":"Number"):me(r,ue("INVALID_OPERAND","- only operates on numbers."))},CallExpr_methodCall(t,n,r,s,i,o){const a=this.args.ctx,l=Re(a,je(t,a)),u=i.asIteration().children.map(m=>je(m,a)),d=r.sourceString,h=Lh(l,d);if(h.kind==="error")return h.error?me(a,h.error):St;if(h.kind==="property")return me(a,ue("NOT_A_FUNCTION","Type error: Function call on target that is not a function."));const f=u.map(m=>d==="hasChildren"?m:Ne(Re(a,m)));if(f.some(m=>m.type==="Error"))return St;const p=h.method.check(d,f);return p?me(a,p):Ne(h.method.returns)},CallExpr_memberAccess(t,n,r){const s=this.args.ctx;return Al(s,je(t,s),r.sourceString)},CallExpr_indexAccess(t,n,r,s){const i=this.args.ctx,o=je(t,i),a=r.literalString();if(a!==void 0)return Al(i,o,a);const l=Re(i,o),u=Re(i,je(r,i));return l==="Error"||u==="Error"?St:l==="Auth"?o_.has(u)?Ne("Auth"):me(i,ue("INVALID_PROPERTY_ACCESS","Invalid property access on 'auth' object.")):me(i,ue("INVALID_PROPERTY_ACCESS","Invalid property access."))},Primary_paren(t,n,r){return je(n,this.args.ctx)},Array(t,n,r){const s=this.args.ctx;return{type:"Array",elements:n.asIteration().children.map(a=>Re(s,je(a,s)))}},number(t){return Ne("Number")},string(t){return Cr(this.sourceString)?me(this.args.ctx,ue("PARSE_ERROR",Js)):Ne("String")},regex(t,n,r,s){const i=g_(n.sourceString);return i!==null?me(this.args.ctx,ue("INVALID_REGEX",i)):sc(s.sourceString)?Ne("Regex"):me(this.args.ctx,ue("INVALID_REGEX",Eh))},bool(t){return Ne("Boolean")},null(t){return Ne("Null")},ident(t,n,r){const s=this.args.ctx,i=this.sourceString;if(t.sourceString==="$")return s.pathVars.has(i.slice(1))?Ne("String"):me(s,ue("UNKNOWN_IDENTIFIER",yl(i)));if(i==="newData"&&s.context==="read")return me(s,ue("NEWDATA_IN_READ","newData is invalid in .read expressions."));const o=y_.get(i);return o?Ne(o):me(s,ue("UNKNOWN_IDENTIFIER",yl(i)))}}),eo=e,e}function w_(e,t,n=[]){const r=Xr(e);if(!r.ok)return[];const{match:s}=r,i={errors:[],context:t,pathVars:new Set(n.map(a=>a.startsWith("$")?a.slice(1):a))};let o;try{o=Re(i,b_()(s).typeOf(i))}catch(a){if(a instanceof RangeError)return[ue("PARSE_ERROR",Qr)];throw a}return Rr.has(o)||me(i,ue("NOT_BOOLEAN","Expression must evaluate to a boolean.")),i.errors}const Uh=Rn({orderByChild:Ee().nullable().optional(),orderByKey:Pt().nullable().optional(),orderByValue:Pt().nullable().optional(),orderByPriority:Pt().nullable().optional(),equalTo:$s([Ee(),vn(),Pt(),Ds()]).optional(),limitToFirst:vn().nullable().optional(),limitToLast:vn().nullable().optional(),startAt:$s([Ee(),vn(),Pt(),Ds()]).optional(),endAt:$s([Ee(),vn(),Pt(),Ds()]).optional()});function Bh(e){const t=Uh.strict().safeParse(e);if(!t.success)return`query is not a Realtime Database query: ${t.error.issues.map(s=>s.message).join("; ")}`;const n=t.data;if(n.orderByChild==="")return"query.orderByChild must name a child path.";if(n.orderByChild!=null&&n.orderByChild.split("/").filter(Boolean).length===0)return"orderByChild: cannot pass in empty path. Use orderByValue() instead.";if([n.orderByChild!=null&&n.orderByChild!=="",n.orderByKey===!0,n.orderByValue===!0,n.orderByPriority===!0].filter(Boolean).length>1)return"query names more than one of orderByChild, orderByKey and orderByValue.";if(n.equalTo!==void 0&&n.startAt!==void 0)return"equalTo: Starting point was already set (by another call to startAt, startAfter, or equalTo).";if(n.equalTo!==void 0&&n.endAt!==void 0)return"equalTo: Ending point was already set (by another call to endAt, endBefore, or equalTo).";if(n.limitToFirst!=null&&n.limitToLast!=null)return"query names both limitToFirst and limitToLast.";for(const[s,i]of[["limitToFirst",n.limitToFirst],["limitToLast",n.limitToLast]])if(i!=null&&(!Number.isInteger(i)||i<=0))return`query.${s} must be a positive integer.`;return null}const v_=Rn({operation:qs(["read","write","validate"]),path:Ee().min(1).startsWith("/"),auth:$s([Rn({uid:Ee(),tenant:Ee().optional(),token:Fs(us()).optional()}),Ds()]),mockData:Fs(us()),newData:us().optional(),updates:Kf(Rn({path:Ee().min(1).startsWith("/"),value:us()})).optional(),query:Uh.optional(),now:vn().optional()});qs(["INVALID_INPUT","NO_MATCHING_RULE","EVALUATION_ERROR"]);const x_=Rn({path:Ee(),kind:qs(["read","write","validate"]),conditionText:Ee(),verdict:qs(["ALLOW","DENY","ERROR","UNSUPPORTED"]),message:Ee().optional(),pathVariableBindings:Fs(Ee()),instance:Ee().optional()});Rn({allowed:Pt(),unsupported:Pt().optional(),matchedPath:Ee(),matchedRule:Ee(),reason:Ee(),pathVariableBindings:Fs(Ee()),trace:Kf(x_)});const __=["sub","aud","iss","auth_time","iat","exp"],S_=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce","sub","firebase"];function Ol(e){const t=S_.filter(r=>Object.prototype.hasOwnProperty.call(e,r));if(t.length===0)return;const n=t.length>1?`Developer claims "${t.join('", "')}" are reserved and cannot be specified.`:`Developer claim "${t[0]}" is reserved and cannot be specified.`;throw new H("auth/reserved-claim",n)}function Fh(e){const t={...e};for(const n of __)delete t[n];return t}function k_(e){return{uid:e.uid,email:e.email,emailVerified:e.emailVerified,displayName:e.displayName,photoUrl:e.photoUrl,phoneNumber:e.phoneNumber,isAnonymous:e.isAnonymous,providerIds:e.providerUserInfo.map(t=>t.providerId)}}const j_=new Set(["password","phone","anonymous"]);function qh(e,t,n,r){const s={},i={user_id:e},o={};if(t!==null){t.displayName!==null&&(s.name=t.displayName),t.photoUrl!==null&&(s.picture=t.photoUrl),t.isAnonymous&&(i.provider_id="anonymous"),t.email!==null&&(i.email=t.email,i.email_verified=t.emailVerified,o.email=[t.email]),t.phoneNumber!==null&&(i.phone_number=t.phoneNumber,o.phone=[t.phoneNumber]);for(const a of t.providerIds)j_.has(a)||(o[a]=[t.uid])}return{...s,...n,...i,firebase:{identities:o,sign_in_provider:r}}}function $l(e){if(typeof e=="object"&&e!==null&&!Array.isArray(e))return e}function E_(e,t,n=Date.now()){const r=Math.floor(n/1e3),s=qh(e,null,t,null),i=$l(t.firebase)??{},o=s.firebase,a=$l(i.identities)??o.identities,l={...i,identities:a};return{sub:e,aud:"pyric-sandbox",iss:"https://sandbox.pyric.dev",auth_time:r,iat:r,exp:r+3600,...s,...t,user_id:t.user_id??s.user_id,firebase:l}}function C_(e){return e===null||typeof e!="object"?!1:e[".sv"]==="timestamp"}function N_(e){if(e===null||typeof e!="object")return!1;const t=e[".sv"];return t!==null&&typeof t=="object"&&typeof t.increment=="number"}function R_(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&Object.hasOwn(e,".value")?e[".value"]:e}function ht(e,t,n){const r=R_(n);if(C_(e))return t;if(N_(e)){const o=e[".sv"].increment;return(typeof r=="number"?r:0)+o}if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map((o,a)=>ht(o,t,Array.isArray(r)?r[a]:void 0));let s;r!==null&&typeof r=="object"&&!Array.isArray(r)&&(s=r);const i={};for(const[o,a]of Object.entries(e)){const l=o===".value"?r:s?.[o];i[o]=ht(a,t,l)}return i}function Dl(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function I_(e,t){let n=e;for(const r of t.split("/").filter(Boolean)){if(n===null||typeof n!="object")return;n=n[r]}return n}function Pl(e,t,n,r){if(n===void 0)return null;const s=ht(n,r,I_(e,t));return Yx(s)}function A_(e,t,n,r,s,i){if(!s||s.length===0)return Jo(e,n,Pl(e,t,r,i));let o=e;for(const a of s){const l=a.path.split("/").filter(Boolean);o=Jo(o,l,Pl(e,a.path,a.value,i))}return o}function Jo(e,t,n){if(t.length===0)return n??null;const[r,...s]=t;if(!r)return e??null;const i=Dl(e)&&Object.hasOwn(e,".value"),o=i?e[".value"]:e,a=Dl(o);let l=null;a&&Object.hasOwn(o,r)&&(l=o[r]);const u=Jo(l,s,n);if(u==null){if(!a)return e??null;const h={...o};return delete h[r],Object.keys(h).some(p=>p!==".priority")?(i&&Object.hasOwn(e,".priority")&&(h[".priority"]=e[".priority"]),h):null}const d=a?{...o}:{};return d[r]=u,i&&a&&Object.hasOwn(e,".priority")&&(d[".priority"]=e[".priority"]),d}function Vh(e,t){try{const n=Yv(e,t);return typeof n!="boolean"?{holds:!1,runtimeError:"Expression must evaluate to a boolean."}:{holds:n}}catch(n){if(n instanceof ee)return{holds:!1,runtimeError:n.message};throw n}}function Xs(e,t,n,r,s){const i={path:e.path,kind:t,conditionText:n.raw,verdict:"UNSUPPORTED",pathVariableBindings:{...r}};if(s===void 0){const o=n.parsed.errors.map(a=>a.message).join("; ");i.message=o===""?"The simulator cannot evaluate this expression":`The simulator cannot evaluate this expression: ${o}`}else s.runtimeError!==void 0?(i.verdict="ERROR",i.message=s.runtimeError):i.verdict=s.holds?"ALLOW":"DENY";return i}function O_(e){const t=e.val();return t===null||typeof t!="object"?[]:Object.keys(t)}function $_(e,t){const n=wi(e),r=E_(e.uid,n?.token??{},t),s={uid:e.uid,token:r},i=r.firebase,a=(typeof i=="object"&&i!==null?i:{}).sign_in_provider;return typeof a=="string"&&(s.provider=a),s}function Tl(e,t,n,r,s,i,o,a){let l=null;const u=new Set;if(a&&a.length>0)for(const m of a)u.add(m.path.split("/").filter(Boolean).join("/"));else u.add(o.filter(Boolean).join("/"));const d=Array.from(u).map(m=>m.split("/").filter(Boolean));function h(m,g,b,w,x){if(b.exists()){const S=m.validate;if(S)if(!S.parsed.valid)i.push(Xs(m,"validate",S,w,void 0)),l||(l={node:m,rule:S,bindings:w,unsupported:!0});else{const k=Vh(S,s(g,b,w));if(i.push(Xs(m,"validate",S,w,k)),!k.holds)return{node:m,rule:S,bindings:w,runtimeError:k.runtimeError}}}const _=d.some(S=>S.length<=x.length&&S.every((k,N)=>k===x[N]))?O_(b):f(x);for(const S of _){const k=zh(m,S);if(k===void 0)continue;const N=k.variable===void 0?w:{...w,[k.variable]:S},O=h(k.child,g.child(S),b.child(S),N,[...x,S]);if(O)return O}return null}function f(m){const g=new Set;for(const b of d)b.length>m.length&&m.every((x,v)=>x===b[v])&&g.add(b[m.length]);return g}return h(e,t,n,r,[])??l}function Wh(e,t,n,r=0){const s=[{node:e,pathVariableBindings:{...n},depth:r}];if(t.length===0)return s;const i=zh(e,t[0]);if(i===void 0)return s;const o=i.variable===void 0?{...n}:{...n,[i.variable]:t[0]};return s.push(...Wh(i.child,t.slice(1),o,r+1)),s}function D_(e){const t=e.path.split("/").filter(Boolean);return t[t.length-1]}function zh(e,t){let n;for(const r of e.children){const s=D_(r);if(s===void 0)continue;if(s===t)return{child:r};s.startsWith("$")&&n===void 0&&(n={child:r,variable:s})}return n}function Ml(e,t){let n="Validation rule evaluated to false";return e.unsupported?n=`Validation rule at '${e.node.path}' contains an expression the simulator cannot evaluate: ${e.rule.raw}. It was not evaluated; production may reject this write.`:e.runtimeError!==void 0&&(n=`Validation rule at '${e.node.path}' failed at evaluation: ${e.runtimeError}`),{success:!0,data:{allowed:!1,unsupported:e.unsupported===!0,matchedPath:e.node.path,matchedRule:e.rule.raw,reason:n,pathVariableBindings:e.bindings,trace:t}}}function P_(e,t){if(e!=="read")return null;const n=t?.equalTo??null;return{orderByChild:t?.orderByChild??null,orderByKey:t?.orderByKey===!0,orderByValue:t?.orderByValue===!0,orderByPriority:t?.orderByPriority===!0,equalTo:n,limitToFirst:t?.limitToFirst??null,limitToLast:t?.limitToLast??null,startAt:t?.startAt??n,endAt:t?.endAt??n}}class T_{execute(t,n){const r=v_.safeParse(n);if(!r.success)return{success:!1,error:{code:"INVALID_INPUT",message:r.error.message,recoverable:!0}};const s=r.data.query===void 0?null:Bh(r.data.query);if(s!==null)return{success:!1,error:{code:"INVALID_INPUT",message:s,recoverable:!0}};const{operation:i,path:o,auth:a,mockData:l,newData:u,updates:d,query:h}=r.data,f=r.data.now??Date.now(),p=[];try{const m=o.split("/").filter(Boolean),g=t,b=Wh(g,m,{}),w=new Bt(l,"/");let x=l;i!=="read"&&(x=A_(l,o,m,u,d,f));const v=new Bt(x,"/");let _=null;a&&(_=$_(a,f));const S=P_(i,h),k=($,C,I)=>{const A={...I};return{auth:_,data:$,newData:C,root:w,now:f,pathVariableBindings:A,query:S}};if(i==="validate"){const $=Tl(g,w,v,{},k,p,m,d);if($)return Ml($,p);const C=p[p.length-1],I=[...b].reverse().find(A=>A.node.validate!==void 0);return!C&&!I?{success:!1,error:{code:"NO_MATCHING_RULE",message:`No 'validate' rule found for path '${o}'`,recoverable:!0}}:{success:!0,data:{allowed:!0,matchedPath:C?.path??I.node.path,matchedRule:C?.conditionText??I.node.validate.raw,reason:"Validation rules evaluated to true",pathVariableBindings:C?.pathVariableBindings??I.pathVariableBindings,trace:p}}}let N;const O=new Map;for(const $ of b){const C=$.node[i];if(!C)continue;if(!C.parsed.valid){p.push(Xs($.node,i,C,$.pathVariableBindings,void 0)),N||(N=$);continue}const I=m.slice(0,$.depth).join("/"),A=w.child(I),P=v.child(I),T=Vh(C,k(A,P,$.pathVariableBindings));if(p.push(Xs($.node,i,C,$.pathVariableBindings,T)),T.runtimeError!==void 0&&O.set($,T.runtimeError),T.holds){if(i==="write"){const W=Tl(g,w,v,{},k,p,m,d);if(W)return Ml(W,p)}return{success:!0,data:{allowed:!0,matchedPath:$.node.path,matchedRule:C.raw,reason:"Rule expression evaluated to true",pathVariableBindings:$.pathVariableBindings,trace:p}}}}if(N){const $=N.node[i];return{success:!0,data:{allowed:!1,unsupported:!0,matchedPath:N.node.path,matchedRule:$.raw,reason:`'${i}' rule at '${N.node.path}' contains an expression the simulator cannot evaluate: ${$.raw} — not evaluated; production may reject or allow this ${i}.`,pathVariableBindings:N.pathVariableBindings,trace:p}}}const D=[...b].reverse().find($=>$.node[i]!==void 0);if(D===void 0)return{success:!0,data:{allowed:!1,matchedPath:"",matchedRule:"",reason:`No '${i}' rule on '${o}' or its ancestors grants access; denied by default`,pathVariableBindings:b[b.length-1].pathVariableBindings,trace:p}};const R=D.node[i],j=O.get(D),E=j===void 0?"evaluated to false":`failed at evaluation: ${j}`;return{success:!0,data:{allowed:!1,matchedPath:D.node.path,matchedRule:R.raw,reason:`No '${i}' rule grants access; the deepest, at '${D.node.path}', ${E}`,pathVariableBindings:D.pathVariableBindings,trace:p}}}catch(m){return{success:!1,error:{code:"EVALUATION_ERROR",message:m instanceof Error?m.message:String(m),recoverable:!1}}}}}function Hh(e,t,n=[]){try{const r=cx(e),s=r.valid?w_(e,t,n):r.errors,i=r.valid?nx(e,t):[];return{raw:e,parsed:{...r,valid:r.valid&&s.length===0,errors:s,warnings:i}}}catch(r){if(!(r instanceof RangeError))throw r;return{raw:e,parsed:{raw:e,valid:!1,errors:[{code:"PARSE_ERROR",message:Qr}],warnings:[],referencedIdentifiers:[]}}}}function Kh(e,t,n){const r={path:t,pathVariables:[...n],children:[]};for(const[o,a]of[[".read","read"],[".write","write"],[".validate","validate"]]){const l=e[o];if(l!==void 0)if(typeof l=="boolean"||typeof l=="string"||l===null)r[a]=Hh(String(l),a,n);else{const u=JSON.stringify(l)??String(l);r[a]={raw:u,parsed:{raw:u,valid:!1,errors:[],warnings:[],referencedIdentifiers:[]}}}}const s=e[".indexOn"];s!==void 0&&(r.indexOn=Array.isArray(s)?s.map(String):[String(s)]);const i=gh(t,e);i.length>0&&(r.structure=i);for(const[o,a]of Object.entries(e)){if(o.startsWith(".")||Ev.has(o)||typeof a!="object"||a===null||Array.isArray(a))continue;const l=t==="/"?`/${o}`:`${t}/${o}`,u=o.startsWith("$")?[...n,o]:[...n];r.children.push(Kh(a,l,u))}return r}function Gh(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 Kh(t.rules,"/",[])}function to(e){return e==="true"?!0:e==="false"?!1:e}function Jh(e){const t={};e.read&&(t[".read"]=to(e.read.raw)),e.write&&(t[".write"]=to(e.write.raw)),e.validate&&(t[".validate"]=to(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]]=Jh(n)}return t}function M_(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:Jh(e)}}function dc(e,t){return new T_().execute(e,t)}function L_(e,t){let n=[e];for(const r of t){const s=[];for(const i of n)for(const o of i.children){const a=o.path.split("/").filter(Boolean),l=a[a.length-1];l&&(l===r||l.startsWith("$"))&&s.push(o)}if(n=s,n.length===0)break}return n}function Yh(e,t,n){return L_(e,t).filter(r=>r.indexOn?.some(s=>s===n||s.split("/").filter(Boolean).join("/")===n))}function U_(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"?e:null}function B_(e){return e.kind==="value"?".value":e.path.split("/").filter(Boolean).join("/")}function F_(e){const t={orderByKey:e.orderBy?.kind==="key",orderByValue:e.orderBy?.kind==="value",orderByPriority:e.orderBy?.kind==="priority"};e.orderBy?.kind==="child"&&(t.orderByChild=e.orderBy.path);for(const n of e.bounds){const r=U_(n.value);n.kind==="equalTo"?t.equalTo=r:n.kind==="startAt"||n.kind==="startAfter"?t.startAt=r:(n.kind==="endAt"||n.kind==="endBefore")&&(t.endAt=r)}return e.limit?.kind==="limitToFirst"?t.limitToFirst=e.limit.n:e.limit?.kind==="limitToLast"&&(t.limitToLast=e.limit.n),t}function Je(e){const t=new Error("PERMISSION_DENIED: Permission denied");return t.code="PERMISSION_DENIED",fc(t,e)}function fc(e,t){return Object.assign(e,{denialContext:t})}class q_{clock;compiled=null;defaultPolicy="deny";constructor(t=new Gf){this.clock=t}setDefaultPolicy(t){this.defaultPolicy=t}setRules(t){if(t===null){this.compiled=null;return}this.compiled=Gh(t)}hasRules(){return this.compiled!==null}missingQueryIndex(t,n){if(this.compiled===null||n.orderBy===null||n.orderBy.kind==="key"||n.orderBy.kind==="priority")return null;const r=B_(n.orderBy);return Yh(this.compiled,t.split("/").filter(Boolean),r).length>0?null:r}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."]};let i=null;r.auth!==null&&(i={uid:r.auth.uid,token:r.auth.token??{}},r.auth.tenant!==void 0&&(i.tenant=r.auth.tenant));let o=r.query;o===void 0&&r.querySpec!==void 0&&(o=F_(r.querySpec));const a=dc(this.compiled,{operation:t,path:n==="/"?"/":n,auth:i,mockData:r.mockData,newData:r.newData,updates:r.updates,query:o,now:r.now??this.clock.now()});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,trace:a.data.trace}:{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,trace:a.data.trace}:{check:"no-rule",reasons:[a.error.message],errorCode:a.error.code,errorMessage:a.error.message}}}class V_{tree=new qx;rules;activeRules=null;valueListeners=new Set;childListeners=new Set;priorities=new r_;mutations=new t_;events;writeSubscribers=new Set;resetGeneration=0;clock;constructor(t,n){this.events=new n_(t,n),this.clock=t?Te(t):new Gf,this.rules=new q_(this.clock)}rulesSnapshot(){const t=[...this.priorities.entries()].map(([n,r])=>({segments:q(n),priority:r}));return mt(this.tree.snapshot(),t)}prioritiesBelow(t){const n=q(t),r=[];for(const[s,i]of this.priorities.entries()){const o=q(s);o.length>n.length&&n.every((l,u)=>o[u]===l)&&r.push({segments:o.slice(n.length),priority:i})}return r}unspecifiedIndexWarning(t,n){if(Qx(n))return null;const r=this.rules.missingQueryIndex(t,n);return r===null?null:Xx(t,r)}warnOnUnspecifiedIndex(t,n){if(n===void 0||Hr.isSilenced())return;const r=this.unspecifiedIndexWarning(t,n);r!==null&&Zx(r)}notifyWrite(){for(const t of this.writeSubscribers)try{t()}catch{}}}function Qh(e,t){if(e===t)return 0;if(e===null)return-1;if(t===null)return 1;const i=Ll(e),o=Ll(t);return i!==o?i-o:typeof e=="number"&&typeof t=="number"?e<t?-1:e>t?1:0:typeof e=="boolean"&&typeof t=="boolean"?e===!0?1:-1:typeof e=="string"&&typeof t=="string"?e<t?-1:e>t?1:0:0}function Ll(e){return e===null?0:typeof e=="boolean"?1:typeof e=="number"?2:typeof e=="string"?3:4}const W_=/^-?(0*)\d{1,10}$/,z_=-2147483648,H_=2147483647;function Ul(e){if(W_.test(e)){const n=Number(e);if(n>=z_&&n<=H_)return n}return null}function Zs(e,t){if(e===t)return 0;const r=Ul(e),s=Ul(t),i=r!==null,o=s!==null;if(i){if(o){const l=r-s;return l===0?e.length-t.length:l}return-1}else if(o)return 1;return e<t?-1:1}function Ir(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 o=s.path.split("/").filter(l=>l.length>0);let a=n;for(const l of o){if(a===null||typeof a!="object"||Array.isArray(a))return null;a=a[l]??null}return a}}}function cn(e,t,n=()=>null){if(e===null||typeof e!="object"||Array.isArray(e))return[];let i=Object.entries(e).map(([u,d])=>({key:u,value:d,priority:n(u)}));const o=t.orderBy?.kind==="key";i.sort((u,d)=>{if(o)return Zs(u.key,d.key);const h=Ir(t.orderBy,u.key,u.value,u.priority),f=Ir(t.orderBy,d.key,d.value,d.priority),p=Qh(h,f);return p!==0?p:Zs(u.key,d.key)});for(const u of t.bounds)i=i.filter(d=>K_(u,d,t.orderBy));const a=t.limit;if(a!==null){const u=a.n;if(a.kind==="limitToFirst")i=i.slice(0,u);else{if(u>=i.length)return i;i=i.slice(i.length-u)}}return i}function K_(e,t,n){const r=n?.kind==="key";let s;if(r)s=Zs(t.key,String(e.value));else{const u=Ir(n,t.key,t.value,t.priority);s=Qh(u,e.value)}const i=u=>Zs(t.key,u),o=s>0,a=s<0,l=s!==0;switch(e.kind){case"startAt":{if(o)return!0;if(a)return!1;const u=e.key;return u===void 0||i(u)>=0}case"startAfter":{if(o)return!0;if(a)return!1;const u=e.key;return u===void 0?!1:i(u)>0}case"endAt":{if(a)return!0;if(o)return!1;const u=e.key;return u===void 0||i(u)<=0}case"endBefore":{if(a)return!0;if(o)return!1;const u=e.key;return u===void 0?!1:i(u)<0}case"equalTo":{if(l)return!1;const u=e.key;return u===void 0||i(u)===0}}}function Bl(e){return e.length===0?null:Object.fromEntries(e.map(({key:t,value:n})=>[t,n]))}function G_(e,t){return e.length===t.length&&e.every((n,r)=>{const s=t[r];return n.key===s.key&&n.priority===s.priority&&an(n.value,s.value)})}function hc(e,t){const n=new Error(`permission_denied at ${G(q(e))}: Client doesn't have permission to access the desired data.`);return n.code="PERMISSION_DENIED",fc(n,t)}class J_{state;constructor(t){this.state=t}onValue(t,n,r,s,i,o,a){const l=this.state.clock.now(),u=this.state.rules.evaluate("read",n==="/"?"/":n,{auth:t,mockData:this.state.rulesSnapshot(),querySpec:s});if(u.check!=="allow"){let d;s&&(d={query:s}),this.state.events.operation(t,"listen",n,nt(u.check),u,{at:l,durationMs:this.state.clock.now()-l,request:d,origin:"listener"});const h=Dn(u),f=De(u,t,"listen",n,d);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:u.reasons},reasons:u.reasons,rules:h}),i)return o&&o(),queueMicrotask(()=>{i(hc(n,f))}),()=>{};throw Je(f)}return this.state.warnOnUnspecifiedIndex(n,s),this.attach(t,n,r,s,{origin:"listener",result:"allow",evaluation:u,at:l},i,o,a)}adminOnValue(t,n,r){return this.state.warnOnUnspecifiedIndex(t,r),this.attach(null,t,n,r,{origin:"admin",result:"not-applicable",evaluation:void 0,at:this.state.clock.now()})}attach(t,n,r,s,i,o,a,l){const u=this.state.events.nextListenerId(),d=Jf(l?.owner,l?.owners);this.state.events.operation(t,"listen",n,i.result,i.evaluation,{at:i.at,durationMs:this.state.clock.now()-i.at,request:s?{query:s}:void 0,origin:i.origin});const h={id:u,auth:t,cb:r,path:n,query:s,cancelCallback:o,onCanceled:a,admin:i.origin==="admin",owners:d};if(this.state.valueListeners.add(h),this.state.events.listener("attach",h,t,{event:"value",result:"allow",detail:s?{query:s}:void 0,...s?{query:s}:{},owners:d}),s){const f=cn(this.state.tree.read(n),s,this.state.priorities.forChild(n));h.lastWindow=f,this.deliverInitial(h,{val:Bl(f),exists:f.length>0,key:this.key(n),rows:f},{initial:!0,query:!0})}else{const f=this.snapshot(n);h.lastValue=f.val,h.lastPriorityState=this.state.priorities.stateAtOrBelow(n),this.deliverInitial(h,f,{initial:!0})}return()=>{this.state.valueListeners.delete(h),this.state.events.listener("detach",h,t,{event:"value"})}}fanOut(t){if(this.state.valueListeners.size===0)return;const n=t.map(r=>G(q(r)));for(const r of this.state.valueListeners){const s=G(q(r.path));if(!n.some(a=>Y_(s,a)))continue;if(r.query){const a=cn(this.state.tree.read(r.path),r.query,this.state.priorities.forChild(r.path));if(G_(r.lastWindow??[],a)){this.state.events.listener("suppressed",r,r.auth,{event:"value",reason:"no-op",detail:{query:!0}});continue}r.lastWindow=a,this.deliver(r,{val:Bl(a),exists:a.length>0,key:this.key(r.path),rows:a},{query:!0});continue}const i=this.snapshot(r.path),o=this.state.priorities.stateAtOrBelow(r.path);if(an(r.lastValue??null,i.val)&&r.lastPriorityState===o){this.state.events.listener("suppressed",r,r.auth,{event:"value",reason:"no-op"});continue}r.lastValue=i.val,r.lastPriorityState=o,this.deliver(r,i,{})}}off(t,n){const r=G(q(t));for(const s of[...this.state.valueListeners])G(q(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=q(t);return n.length===0?null:n[n.length-1]}deliver(t,n,r){let s,i=!1;const o=Vs(()=>{try{t.cb(n)}catch(a){s=a,i=!0}});this.state.events.listener("delivery",t,t.auth,{event:"value",size:n.rows?.length??(n.exists?1:0),sample:n.val,detail:r,owners:Yo(o)}),i&&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){let s,i=!1;const o=Vs(()=>{try{t.cb(n)}catch(a){s=a,i=!0}});if(!i){this.state.events.listener("delivery",t,t.auth,{event:"value",size:n.rows?.length??(n.exists?1:0),sample:n.val,detail:r,owners:Yo(o)});return}this.state.events.listener("errored",t,t.auth,{event:"value",result:"error",error:{message:s instanceof Error?s.message:String(s)},detail:r})}}function Yo(e){if(e!==void 0)return[e]}function Y_(e,t){if(e===t||e==="/")return!0;const n=`${e}/`,r=t==="/"?"/":`${t}/`;return t.startsWith(n)||e.startsWith(r)}function Fl(e,t){const n=G(q(t)),r=n==="/"?"/":`${n}/`,s={};for(const[i,o]of Object.entries(e))(i===n||i.startsWith(r))&&(s[i]=o);return s}function Xn(e,t){const n=e.findIndex(r=>r.key===t);return n>0?e[n-1].key:null}function fs(e,t){const n=e.findIndex(r=>r.key===t);return n>0?e[n-1].key:null}class Q_{state;constructor(t){this.state=t}onChild(t,n,r,s,i,o,a){const l=this.state.clock.now(),u=this.state.events.nextListenerId(),d=this.state.rules.evaluate("read",r==="/"?"/":r,{auth:t,mockData:this.state.rulesSnapshot(),querySpec:i});if(d.check!=="allow"){this.state.events.operation(t,"listen",r,nt(d.check),d,{at:l,durationMs:this.state.clock.now()-l,origin:"listener",detail:{event:n},request:i?{query:i}:void 0});const h=Dn(d),f=De(d,t,"listen",r);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:h}),o)return a&&a(),queueMicrotask(()=>{o(hc(r,f))}),()=>{};throw Je(f)}return this.state.warnOnUnspecifiedIndex(r,i),this.attach(u,t,n,r,s,i,{origin:"listener",result:"allow",evaluation:d,at:l},o,a)}adminOnChild(t,n,r,s){return this.state.warnOnUnspecifiedIndex(n,s),this.attach(this.state.events.nextListenerId(),null,t,n,r,s,{origin:"admin",result:"not-applicable",evaluation:void 0,at:this.state.clock.now()})}attach(t,n,r,s,i,o,a,l,u){const d=Jf();this.state.events.operation(n,"listen",s,a.result,a.evaluation,{at:a.at,durationMs:this.state.clock.now()-a.at,request:o?{query:o}:void 0,origin:a.origin,detail:{event:r}});const h={id:t,auth:n,event:r,path:s,cb:i,spec:o,cancelCallback:l,onCanceled:u,admin:a.origin==="admin"};if(this.state.childListeners.add(h),this.state.events.listener("attach",h,n,{event:r,result:"allow",detail:o?{query:o}:void 0,...o?{query:o}:{},owners:d}),o){const f=cn(this.state.tree.read(s),o,this.state.priorities.forChild(s));if(h.lastWindow=f,h.lastPriorities=this.state.priorities.atOrBelow(s),r==="child_added")for(const{key:p,value:m}of f)this.deliver(h,{key:p,val:m,previousChildName:Xn(f,p)},{initial:!0,query:!0})}else if(r==="child_added")for(const{key:f,val:p}of this.directChildren(s)){const m=this.directChildren(s);this.deliver(h,{key:f,val:p,previousChildName:fs(m,f)},{initial:!0})}return()=>{this.state.childListeners.delete(h),this.state.events.listener("detach",h,n,{event:r})}}off(t,n,r){const s=G(q(t));for(const i of[...this.state.childListeners])n!==void 0&&i.event!==n||G(q(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=G(q(n.path));t.has(r)||t.set(r,{children:this.childStates(r),priorities:this.state.priorities.atOrBelow(r)})}return t}fanOut(t){if(this.state.childListeners.size===0)return;const n=new Map;for(const r of this.state.childListeners){if(r.spec){this.fanOutQuery(r);continue}const s=G(q(r.path)),i=n.get(s)??[];i.push(r),n.set(s,i)}for(const[r,s]of n){const i=t.get(r),o=i?.children??new Map,a=i?.priorities??{},l=this.childStates(r),u=[...l].map(([f,{val:p}])=>({key:f,val:p})),d=[...o].map(([f,{val:p}])=>({key:f,val:p})),h={child_added:[],child_changed:[],child_removed:[],child_moved:[]};for(const[f,{val:p,priority:m}]of l){const g=o.get(f);if(g===void 0){h.child_added.push({key:f,val:p,previousChildName:fs(u,f)});continue}const b=fs(u,f);an(g.val,p)||h.child_changed.push({key:f,val:p,previousChildName:b}),g.priority!==m&&h.child_moved.push({key:f,val:p,previousChildName:b})}for(const[f,{val:p}]of o)l.has(f)||h.child_removed.push({key:f,val:p,previousChildName:fs(d,f),priorities:Fl(a,G([...q(r),f]))});for(const f of s)for(const p of h[f.event])this.deliver(f,p,{})}}count(){return this.state.childListeners.size}directChildren(t){const n=this.state.tree.read(t);return n===null||typeof n!="object"||Array.isArray(n)?[]:cn(n,{orderBy:{kind:"priority"},bounds:[],limit:null},this.state.priorities.forChild(t)).map(({key:r,value:s})=>({key:r,val:s}))}childStates(t){const n=this.state.priorities.forChild(t);return new Map(this.directChildren(t).map(({key:r,val:s})=>[r,{val:s,priority:n(r)}]))}fanOutQuery(t){const n=t.lastWindow??[],r=cn(this.state.tree.read(t.path),t.spec,this.state.priorities.forChild(t.path));t.lastWindow=r;const s=t.lastPriorities??{};t.lastPriorities=this.state.priorities.atOrBelow(t.path);const i=new Map(n.map(l=>[l.key,l.value])),o=new Map(r.map(l=>[l.key,l.value])),a=[];if(t.event==="child_added")for(const l of r)i.has(l.key)||a.push({key:l.key,val:l.value,previousChildName:Xn(r,l.key)});else if(t.event==="child_changed")for(const l of r)i.has(l.key)&&!an(i.get(l.key),l.value)&&a.push({key:l.key,val:l.value,previousChildName:Xn(r,l.key)});else if(t.event==="child_removed")for(const l of n)o.has(l.key)||a.push({key:l.key,val:l.value,previousChildName:Xn(n,l.key),priorities:Fl(s,G([...q(t.path),l.key]))});else if(t.spec?.orderBy&&t.spec.orderBy.kind!=="key"){const l=new Map(n.map(u=>[u.key,u]));for(const u of r){const d=l.get(u.key);if(!d)continue;const h=Ir(t.spec.orderBy,d.key,d.value,d.priority),f=Ir(t.spec.orderBy,u.key,u.value,u.priority);an(h,f)||a.push({key:u.key,val:u.value,previousChildName:Xn(r,u.key)})}}for(const l of a)this.deliver(t,l,{query:!0})}deliver(t,n,r){let s,i=!1;const o=Vs(()=>{try{t.cb(n)}catch(a){s=a,i=!0}});this.state.events.listener("delivery",t,t.auth,{event:t.event,size:1,sample:r.query?{key:n.key,val:n.val}:{key:n.key,val:n.val,previousChildName:n.previousChildName},detail:r,owners:Yo(o)}),i&&this.state.events.listener("errored",t,t.auth,{event:t.event,result:"error",error:{message:s instanceof Error?s.message:String(s)},detail:r})}}class X_{state;values;children;constructor(t,n,r){this.state=t,this.values=n,this.children=r}adminSet(t,n){Lt(n);const r=this.state.tree.read(t);if(r===null)return;const s=this.state.clock.now(),i=this.state.priorities.get(t);this.state.events.operation(null,"setPriority",t,"not-applicable",void 0,{at:s,origin:"admin",request:{data:n},resourceBefore:{data:r,exists:!0},resourceAfter:{data:r,exists:!0},detail:{admin:!0,priority:n,priorPriority:i}});const o=this.children.snapshotParents(),a=i!==n;this.state.priorities.set(t,n),this.state.mutations.mark(t),a&&this.values.fanOut([t]),this.children.fanOut(o),this.state.events.commit(null,"setPriority",t,{data:n,priorState:i,nextState:n,replay:{requestTime:s},detail:{admin:!0,priority:n,priorPriority:i}}),this.state.notifyWrite()}validate(t,n,r){Lt(r);const s=this.evaluation(t,n,r);if(s.check!=="allow")throw Je(De(s,t,"setPriority",n,{data:r}))}evaluation(t,n,r){const s=this.state.tree.read(n);return this.state.rules.evaluate("write",n==="/"?"/":n,{auth:t,mockData:this.state.rulesSnapshot(),newData:mt(s,[{segments:[],priority:r},...this.state.prioritiesBelow(n)])})}set(t,n,r){Lt(r);const s=this.state.tree.read(n),i=this.state.clock.now(),o=this.evaluation(t,n,r),a=this.state.priorities.get(n),l={at:i,durationMs:this.state.clock.now()-i,request:{data:r},resourceBefore:{data:s,exists:s!==null},resourceAfter:{data:s,exists:s!==null},detail:{priority:r,priorPriority:a}};if(o.check!=="allow")throw this.state.events.operation(t,"setPriority",n,nt(o.check),o,l),Je(De(o,t,"setPriority",n,{data:r}));if(this.state.events.operation(t,"setPriority",n,"allow",o,l),this.state.events.commit(t,"setPriority",n,{data:r,priorState:a,nextState:s===null?null:r,replay:{requestTime:i},detail:{priority:r,priorPriority:a}}),s===null)return;const u=this.children.snapshotParents(),d=a!==r;this.state.priorities.set(n,r),this.state.mutations.mark(n),d&&this.values.fanOut([n]),this.children.fanOut(u),d&&this.state.events.mutation(t,"setPriority",yt(n),{before:a,after:r,detail:{priorityMetadata:!0}}),this.state.notifyWrite()}}function ql(e){return e.length===0?null:Object.fromEntries(e.map(({key:t,value:n})=>[t,n]))}function lr(e,t,n,r,s=!1){const i=q(t);for(let a=0;a<i.length;a++){const l=G(i.slice(0,a)),u=e.tree.read(l);if(u!==null&&typeof u!="object"){const d=e.priorities.get(l);return{overwrittenAncestor:{path:l,state:mt(u,[{segments:[],priority:d}])}}}}const o=e.prioritiesBelow(t);return o.length>0?{priorExport:mt(n,[{segments:[],priority:r},...o])}:s&&r!==null?{priorPriority:r}:{}}const Z_=/\broot\b/,eS=/\bdata\b/,tS=/\bparent\b/;function nS(e,t){return e===t||e==="/"||t==="/"?!0:t.startsWith(`${e}/`)||e.startsWith(`${t}/`)}function Vl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function rS(e,t){if(!t.startsWith(".")&&Object.hasOwn(e,t)&&Vl(e[t]))return e[t];for(const[n,r]of Object.entries(e))if(n.startsWith("$")&&Vl(r))return r}function sS(e,t,n){return typeof e!="string"?!1:Z_.test(e)?!0:eS.test(e)?tS.test(e)||e.includes("[")?!0:n.some(r=>nS(t,r)):!1}function Wl(e,t,n){const r=q(t);let s=e;for(let i=0;i<=r.length&&s!==void 0;i++){const o=G(r.slice(0,i));if(sS(s[".read"],o,n))return!0;i<r.length&&(s=rS(s,r[i]))}return!1}class Xh{state;values;children;priorityWrites;constructor(t,n,r){this.state=t,this.values=n,this.children=r,this.priorityWrites=new X_(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,Zt(ht(r,this.state.clock.now()),n==="/"?"":n));const{priority:s,nested:i}=en(r,null);this.state.priorities.replace(n,this.state.tree.read(n)===null?null:s),this.storeNestedPriorities(n,i)}this.state.mutations.mark("/"),this.cancelDeniedListeners(["/"]),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,{at:this.state.clock.now(),origin:"admin",resourceBefore:{data:n,exists:n!==null}}),n}adminGetQuery(t,n){const r=this.state.rules.missingQueryIndex(t,n);if(r!==null)throw this.state.events.operation(null,"get",t,"error",void 0,{at:this.state.clock.now(),origin:"admin",request:{query:n},detail:{failure:"missing-index"}}),El(t,r);const s=cn(this.state.tree.read(t),n,this.state.priorities.forChild(t));return this.state.events.operation(null,"get",t,"not-applicable",void 0,{at:this.state.clock.now(),origin:"admin",request:{query:n},resourceBefore:{data:ql(s),exists:s.length>0}}),s}adminSet(t,n){this.adminSetWithPriority(t,n,null,!1)}adminSetWithPriority(t,n,r,s=!0){const i=this.state.clock.now(),o=this.state.tree.read(t),a=Zt(ht(n,i,o),t==="/"?"":t),l=en(n,r);r=l.priority,s||=l.inline,Lt(r);const u=a===null?"remove":"set";this.state.events.operation(null,u,t,"not-applicable",void 0,{at:i,origin:"admin",request:{data:n,resourceData:n},resourceBefore:{data:o,exists:o!==null},resourceAfter:{data:a,exists:a!==null}});const d=this.children.snapshotParents(),h=this.state.priorities.get(t),f=lr(this.state,t,o,h);this.state.tree.write(t,a),this.state.priorities.replace(t,a===null?null:r,g=>this.state.tree.read(g)!==null),this.storeNestedPriorities(t,l.nested),this.changed([t],d);const p=this.state.tree.read(t),m=s||h!==null;this.state.events.commit(null,p===null?"remove":"set",t,{data:n,priorState:o,nextState:p,replay:{requestTime:i},detail:{admin:!0,...m?{priority:r,priorPriority:h}:{},...f}}),this.state.notifyWrite()}adminUpdate(t,n){const r=this.state.clock.now(),s=this.state.tree.read(t),i=this.state.priorities.get(t),o=lr(this.state,t,s,i,!0),a=this.resolvePatch(t,n,r),l=this.patchPriorities(t,n),u=Object.keys(n).some(p=>p.includes("/"));this.state.events.operation(null,"update",t,"not-applicable",void 0,{at:r,origin:"admin",request:{data:n,resourceData:n},resourceBefore:{data:s,exists:s!==null},detail:u?{admin:!0,multiPath:!0,paths:Object.keys(a)}:{admin:!0,multiPath:!1,keys:Object.keys(n)}});const d=this.children.snapshotParents();u?this.state.tree.multiUpdate(a):this.state.tree.shallowUpdate(t,Object.fromEntries(Object.entries(a).map(([p,m])=>[q(p).at(-1),m])));const h=p=>this.state.tree.read(p)!==null;this.state.priorities.applyUpdate(Object.entries(a).map(([p,m])=>({path:p,value:m})),h),this.storePatchPriorities(l),this.changed(Object.keys(a),d);const f=u?{admin:!0,multiPath:!0,paths:Object.keys(a),...o}:{admin:!0,multiPath:!1,keys:Object.keys(n),...o};this.state.events.commit(null,"update",t,{data:n,priorState:s,nextState:this.state.tree.read(t),replay:{requestTime:r},detail:f}),this.state.notifyWrite()}adminRemove(t){this.adminSet(t,null)}adminSetPriority(t,n){this.priorityWrites.adminSet(t,n),this.cancelDeniedListeners([t])}get(t,n){const r=this.state.clock.now(),s=this.state.tree.read(n),i=this.readEvaluation(t,n);if(i.check!=="allow")throw this.state.events.operation(t,"get",n,nt(i.check),i,{at:r,durationMs:this.state.clock.now()-r,resourceBefore:{data:s,exists:s!==null}}),Je(De(i,t,"get",n));return this.state.events.operation(t,"get",n,"allow",i,{at:r,durationMs:this.state.clock.now()-r,resourceBefore:{data:s,exists:s!==null}}),this.state.tree.read(n)}getQuery(t,n,r){const s=this.state.clock.now(),i=this.readEvaluation(t,n,r);if(i.check!=="allow")throw this.state.events.operation(t,"get",n,nt(i.check),i,{at:s,durationMs:this.state.clock.now()-s,request:{query:r}}),Je(De(i,t,"get",n,{query:r}));const o=this.state.rules.missingQueryIndex(n,r);if(o!==null)throw this.state.events.operation(t,"get",n,"error",void 0,{at:s,durationMs:this.state.clock.now()-s,request:{query:r},detail:{failure:"missing-index"}}),El(n,o);const a=cn(this.state.tree.read(n),r,this.state.priorities.forChild(n));return this.state.events.operation(t,"get",n,"allow",i,{at:s,durationMs:this.state.clock.now()-s,request:{query:r},resourceBefore:{data:ql(a),exists:a.length>0}}),a}set(t,n,r){this.setInternal(t,n,r,"set",null,!1)}setWithPriority(t,n,r,s){Lt(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),this.cancelDeniedListeners([n])}validatePriority(t,n,r){this.priorityWrites.validate(t,n,r)}validateRead(t,n,r){const s=this.readEvaluation(t,n,r);if(s.check!=="allow")throw Je(De(s,t,"get",n,r?{query:r}:{}))}validateSet(t,n,r,s=null){const{evaluation:i,resolved:o}=this.setCheck(t,n,r,s);if(i.check!=="allow")throw Je(De(i,t,"onDisconnect",n,{data:o}))}validateUpdate(t,n,r){const s=this.updateCheck(t,n,r);if(s!==null)throw Je(De(s.evaluation,t,"onDisconnect",s.path,{data:s.value}))}registerDisconnect(t,n){const r=this.state.clock.now(),s=`onDisconnect.${n.kind}`,i=n.kind==="set"?n.value:n.kind==="update"?n.values:null,o=n.kind==="set"&&n.priority!==null?{priority:n.priority}:void 0;let a,l=null;if(n.kind==="update"){if(Object.keys(n.values).length===0)return;const d=this.updateEvaluations(t,n.path,n.values),h=d.find(f=>f.evaluation.check!=="allow");a=(h??d.at(-1)).evaluation,h!==void 0&&(l={path:h.update.path,data:h.update.value})}else{const d=n.kind==="set"?n.value:null,h=this.setCheck(t,n.path,d,n.kind==="set"?n.priority:null);a=h.evaluation,a.check!=="allow"&&(l={path:n.path,data:h.resolved})}const u={at:r,durationMs:this.state.clock.now()-r,request:{data:i,resourceData:i},detail:o};if(l!==null)throw this.state.events.operation(t,s,n.path,nt(a.check),a,u),Je(De(a,t,"onDisconnect",l.path,{data:l.data}));this.state.events.operation(t,s,n.path,"allow",a,u)}setCheck(t,n,r,s){const i=this.state.clock.now(),o=Zt(ht(r,i,this.state.tree.read(n)),n==="/"?"":n),a=en(r,s);Lt(a.priority);const l=mt(o,[{segments:[],priority:a.priority},...a.nested]);return{evaluation:this.writeEvaluation(t,n,l,i),resolved:o}}updateCheck(t,n,r){if(Object.keys(r).length===0)return null;for(const{update:s,evaluation:i}of this.updateEvaluations(t,n,r))if(i.check!=="allow")return{evaluation:i,path:s.path,value:s.value};return null}updateEvaluations(t,n,r){const s=this.state.clock.now(),i=this.state.rulesSnapshot(),o=this.patchPriorities(n,r),a=Object.entries(r).map(([l,u])=>{const d=G([...q(n),...q(l)]),h=Zt(ht(u,s,this.state.tree.read(d)),d);return{path:d,value:mt(h,o.get(d)??[])}});return a.map(l=>({update:l,evaluation:this.state.rules.evaluate("write",l.path,{auth:t,mockData:i,newData:l.value,updates:a,now:s})}))}update(t,n,r){if(Object.keys(r).length===0)return;const s=this.state.clock.now(),i=this.resolvePatch(n,r,s),o=this.patchPriorities(n,r),a=Object.keys(r).some(v=>v.includes("/")),l=this.state.rulesSnapshot(),u=Object.entries(i).map(([v,_])=>({path:v,value:_})),d=u.map(v=>({path:v.path,value:mt(v.value,o.get(v.path)??[])})),h=Object.fromEntries(Object.entries(i).map(([v,_])=>[q(v).at(-1),_])),f=this.state.events.nextGroupId("update"),p=[];for(const[v,_]of u.entries()){const S=this.state.clock.now(),k=this.state.tree.read(_.path),N=this.state.rules.evaluate("write",_.path,{auth:t,mockData:l,newData:d[v].value,updates:d,now:s}),O={at:S,durationMs:this.state.clock.now()-S,origin:"batch",request:{data:_.value,resourceData:_.value},resourceBefore:{data:k,exists:k!==null},resourceAfter:{data:_.value,exists:_.value!==null},groupId:f,groupKind:"batch",detail:a?{multiPath:!0,rootPath:yt(n)}:{multiPath:!1,rootPath:yt(n),key:q(_.path).at(-1)}};if(N.check!=="allow"){const D={...O,detail:{...O.detail,patch:r}};throw this.state.events.operation(t,"update",_.path,nt(N.check),N,D),Je(De(N,t,"update",_.path,{data:_.value}))}p.push(()=>this.state.events.operation(t,"update",_.path,"allow",N,O))}for(const v of p)v();const m=this.state.tree.read(n),g=this.state.priorities.get(n),b=lr(this.state,n,m,g,!0),w=this.children.snapshotParents();a?this.state.tree.multiUpdate(i):this.state.tree.shallowUpdate(n,h),this.state.priorities.applyUpdate(u,v=>this.state.tree.read(v)!==null),this.storePatchPriorities(o),this.changed(Object.keys(i),w);const x=this.state.tree.read(n);this.state.events.commit(t,"update",n,{data:r,priorState:m,nextState:x,groupId:f,groupKind:"batch",replay:{requestTime:s},detail:a?{multiPath:!0,paths:Object.keys(i),...b}:{multiPath:!1,keys:Object.keys(h),...b}}),this.state.events.mutation(t,"update",yt(n),{after:a?i:h,detail:a?{multiPath:!0,paths:Object.keys(i)}:{multiPath:!1,keys:Object.keys(h)}}),this.state.notifyWrite()}setInternal(t,n,r,s,i,o){const a=this.state.clock.now(),l=Zt(ht(r,a,this.state.tree.read(n)),n==="/"?"":n),u=en(r,i);i=u.priority,o||=u.inline,Lt(i);const d=this.state.tree.read(n),h=this.state.priorities.get(n),f=this.state.clock.now(),p=mt(l,[{segments:[],priority:i},...u.nested]),m=this.writeEvaluation(t,n,p,a),g={at:f,durationMs:this.state.clock.now()-f,request:{data:r,resourceData:r},resourceBefore:{data:d,exists:d!==null},resourceAfter:{data:l,exists:l!==null}};if(m.check!=="allow"){const k=o?{...g,detail:{priority:i}}:g;throw this.state.events.operation(t,s,n,nt(m.check),m,k),Je(De(m,t,s,n,{data:r}))}this.state.events.operation(t,s,n,"allow",m,g);const b=this.children.snapshotParents(),w=lr(this.state,n,d,h);this.state.tree.write(n,l),this.state.priorities.replace(n,l===null?null:i,k=>this.state.tree.read(k)!==null),this.storeNestedPriorities(n,u.nested),this.changed([n],b);const x=this.state.tree.read(n),v=x===null?"remove":s,S={...o||h!==null?{priority:i,priorPriority:h}:{},...w};this.state.events.commit(t,v,n,{data:r,priorState:d,nextState:x,replay:{requestTime:a},detail:Object.keys(S).length>0?S:void 0}),this.state.events.mutation(t,v,yt(n),{before:d,after:x}),this.state.notifyWrite()}resolvePatch(t,n,r){return Object.fromEntries(Object.entries(n).map(([s,i])=>{const o=G([...q(t),...q(s)]);return[o,Zt(ht(i,r,this.state.tree.read(o)),o)]}))}changed(t,n){this.state.mutations.mark(t),this.cancelDeniedListeners(t),this.values.fanOut(t),this.children.fanOut(n)}cancelDeniedListeners(t){if(this.state.valueListeners.size===0&&this.state.childListeners.size===0)return;let n,r;if(t!==void 0){if(this.state.activeRules===null)return;const l=t.map(d=>G(q(d)));if(l.length===0)return;const u=this.state.activeRules.rules;n=[...this.state.valueListeners].filter(d=>!d.admin&&Wl(u,d.path,l)),r=[...this.state.childListeners].filter(d=>!d.admin&&Wl(u,d.path,l))}else n=[...this.state.valueListeners].filter(l=>!l.admin),r=[...this.state.childListeners].filter(l=>!l.admin);if(n.length===0&&r.length===0)return;const s=this.state.rulesSnapshot(),i=[],o=new Map;for(const l of n){const u=this.state.rules.evaluate("read",l.path,{auth:l.auth,mockData:s,querySpec:l.query});if(u.check==="allow")continue;this.state.valueListeners.delete(l),this.state.events.operation(l.auth,"listen",l.path,nt(u.check),u,{origin:"listener",request:l.query?{query:l.query}:void 0,detail:{revoked:!0}});const d=Dn(u);this.state.events.listener("errored",l,l.auth,{event:"value",result:"deny",error:{code:"PERMISSION_DENIED",message:"PERMISSION_DENIED: Permission denied",reasons:u.reasons},reasons:u.reasons,rules:d}),o.set(l,De(u,l.auth,"listen",l.path)),i.push(l)}const a=[];for(const l of r){const u=this.state.rules.evaluate("read",l.path,{auth:l.auth,mockData:s,querySpec:l.spec});if(u.check==="allow")continue;this.state.childListeners.delete(l),this.state.events.operation(l.auth,"listen",l.path,nt(u.check),u,{origin:"listener",request:l.spec?{query:l.spec}:void 0,detail:{event:l.event,revoked:!0}});const d=Dn(u);this.state.events.listener("errored",l,l.auth,{event:l.event,result:"deny",error:{code:"PERMISSION_DENIED",message:"PERMISSION_DENIED: Permission denied",reasons:u.reasons},reasons:u.reasons,rules:d}),o.set(l,De(u,l.auth,"listen",l.path)),a.push(l)}for(const l of[...i,...a]){try{l.onCanceled&&l.onCanceled()}catch{}try{l.cancelCallback&&l.cancelCallback(hc(l.path,o.get(l)))}catch{}}}readEvaluation(t,n,r){return this.state.rules.evaluate("read",n==="/"?"/":n,{auth:t,mockData:this.state.rulesSnapshot(),querySpec:r})}writeEvaluation(t,n,r,s){return this.state.rules.evaluate("write",n==="/"?"/":n,{auth:t,mockData:this.state.rulesSnapshot(),newData:r,now:s})}storeNestedPriorities(t,n){for(const{segments:r,priority:s}of n){const i=G([...q(t),...r]);this.state.priorities.set(i,this.state.tree.read(i)===null?null:s)}}patchPriorities(t,n){const r=new Map;for(const[s,i]of Object.entries(n)){const{priority:o,inline:a,nested:l}=en(i,null),u=G([...q(t),...q(s)]);r.set(u,a?[{segments:[],priority:o},...l]:l)}return r}storePatchPriorities(t){for(const[n,r]of t){const s=r.find(i=>i.segments.length===0);s&&this.state.priorities.set(n,this.state.tree.read(n)===null?null:s.priority),this.storeNestedPriorities(n,r.filter(i=>i.segments.length>0))}}}function iS(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,o="data"in r;let a=!1;i&&o&&(a=!0);const l=r.priorities,u=l!==null,d=l!==void 0;let h=!1;if(u&&d){const p=typeof l=="object",m=Array.isArray(l);p&&(m||(h=!0))}let f=!1;if(a&&h&&(f=!0),f){const p={},m=Object.entries(l);for(const[S,k]of m){const N=typeof k=="string",O=typeof k=="number";let D=!1;O&&Number.isFinite(k)&&(D=!0);let R=!1;N&&(R=!0),D&&(R=!0),R&&(p[S]=k)}const g=r.data;let b=null;g!==void 0&&g!==null&&(b=g);const x=r.rules;let v=null;if(x!==void 0&&x!==null){const k=typeof x=="object",N=Array.isArray(x);let O=!1;if(k&&(N||(O=!0)),O){const D=x;if("rules"in D){const j=D.rules;if(j!==null&&j!==void 0){const C=typeof j=="object",I=Array.isArray(j);let A=!1;C&&(I||(A=!0)),A&&(v={rules:j})}}}}return{data:b,priorities:p,rules:v}}}return{data:e,priorities:{},rules:null}}class oS{state;values;children;writes;constructor(t,n,r){this.state=t,this.values=n,this.children=r,this.writes=new Xh(t,n,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=iS(t);let s={};r.data!==null&&r.data!==void 0&&(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.writes.cancelDeniedListeners(),this.values.fanOut(["/"]),this.children.fanOut(n)}reset(t=!1){this.state.resetGeneration+=1;const n=this.children.snapshotParents();this.state.tree.restore({}),this.state.priorities.restore({}),this.state.mutations.mark("/"),t||(this.state.rules.setRules(null),this.state.activeRules=null),this.writes.cancelDeniedListeners(),this.values.fanOut(["/"]),this.children.fanOut(n)}subscribe(t){return this.state.writeSubscribers.add(t),()=>{this.state.writeSubscribers.delete(t)}}}const zl="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz";let Hl=0;const Xt=new Array(12).fill(0);function aS(e=Date.now()){const t=e===Hl;Hl=e;const n=new Array(8);let r=e;for(let i=7;i>=0;i--)n[i]=zl.charAt(r%64),r=Math.floor(r/64);if(r!==0)throw new Error("RTDB push-id: timestamp overflow.");let s=n.join("");if(t){let i;for(i=11;i>=0&&Xt[i]===63;i--)Xt[i]=0;if(i<0)for(let o=0;o<12;o++)Xt[o]=Math.floor(Math.random()*64);else Xt[i]=(Xt[i]??0)+1}else for(let i=0;i<12;i++)Xt[i]=Math.floor(Math.random()*64);for(let i=0;i<12;i++)s+=zl.charAt(Xt[i]);if(s.length!==20)throw new Error(`RTDB push-id: bad length ${s.length}.`);return s}function cS(e){return fc(new Error("permission_denied"),e)}class lS{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,o=s?.admin===!0,a=q(n),l=a.length===0?null:a[a.length-1];let u=null,d=null,h,f=0,p=!1;do{f+=1;const j=this.state.mutations.begin();u=this.state.tree.read(n),d=o||this.canRead(t,n)?u:null;const E=d===null?null:Ts(Mt(d));let $=!1;try{h=r(E),$=this.state.mutations.conflictsSince(j,n)}finally{this.state.mutations.release(j)}if(!$||h===void 0){p=!0;break}}while(f<25);if(!p)throw new Error("maxretry");const m=this.state.events.nextGroupId("transaction");if(h===void 0)return this.state.events.operation(t,"transaction",n,"not-applicable",void 0,{origin:o?"admin":"transaction",groupId:m,groupKind:"transaction",resourceBefore:{data:d,exists:d!==null},detail:{committed:!1,aborted:!0}}),{committed:!1,val:d,key:l};const g=this.state.clock.now(),b=Zt(ht(h,g,u),n==="/"?"":n),w=this.state.priorities.get(n),x=en(h,w);Lt(x.priority);const v=b===null?null:x.priority,_=this.state.clock.now();let S;if(!o){const j=mt(b,[{segments:[],priority:v},...x.nested]);if(S=this.state.rules.evaluate("write",n,{auth:t,mockData:this.state.rulesSnapshot(),newData:j,now:g}),S.check!=="allow")throw this.state.events.operation(t,"transaction",n,nt(S.check),S,{at:_,durationMs:this.state.clock.now()-_,origin:"transaction",request:{data:h,resourceData:h},resourceBefore:{data:u,exists:u!==null},resourceAfter:{data:b,exists:b!==null},groupId:m,groupKind:"transaction"}),cS(De(S,t,"transaction",n,{data:h}))}const k=j=>this.state.tree.read(j)!==null,N=lr(this.state,n,u,w,!0);if(i){const j=this.children.snapshotParents();return this.state.tree.write(n,b),this.state.priorities.replace(n,v,k),this.storeNestedPriorities(a,x.nested,k),this.values.fanOut([n]),this.children.fanOut(j),this.recordCommit(t,n,h,u,b,m,g,_,!0,S,o,N),{committed:!0,val:b,key:l}}const O=o?"not-applicable":"allow",D=o?"admin":"transaction";this.state.events.operation(t,"transaction",n,O,S,{at:_,durationMs:this.state.clock.now()-_,origin:D,request:{data:h,resourceData:h},resourceBefore:{data:u,exists:u!==null},resourceAfter:{data:b,exists:b!==null},groupId:m,groupKind:"transaction"});const R=this.children.snapshotParents();return this.state.tree.write(n,b),this.state.priorities.replace(n,v,k),this.storeNestedPriorities(a,x.nested,k),this.state.mutations.mark(n),this.values.fanOut([n]),this.children.fanOut(R),this.finishEvents(t,n,h,u,b,m,g,!1,o,N),this.state.notifyWrite(),{committed:!0,val:b,key:l}}storeNestedPriorities(t,n,r){for(const{segments:s,priority:i}of n){const o=G([...t,...s]);this.state.priorities.set(o,r(o)?i:null)}}canRead(t,n){return this.state.rules.evaluate("read",n,{auth:t,mockData:this.state.rulesSnapshot(),now:this.state.clock.now()}).check==="allow"}recordCommit(t,n,r,s,i,o,a,l,u,d,h,f){const p=h?"not-applicable":"allow",m=h?"admin":"transaction";this.state.events.operation(t,"transaction",n,p,d,{at:l,durationMs:this.state.clock.now()-l,origin:m,request:{data:r,resourceData:r},resourceBefore:{data:s,exists:s!==null},resourceAfter:{data:i,exists:i!==null},groupId:o,groupKind:"transaction"}),this.finishEvents(t,n,r,s,i,o,a,u,h,f),this.state.mutations.mark(n),this.state.notifyWrite()}finishEvents(t,n,r,s,i,o,a,l,u,d){this.state.events.commit(t,"transaction",n,{data:r,priorState:s,nextState:i,groupId:o,groupKind:"transaction",replay:{requestTime:a},detail:{...u?{admin:!0}:{},committed:!0,applyLocally:l,...d}}),this.state.events.mutation(t,"transaction",yt(n),{before:s,after:i,detail:{committed:!0}})}}function Kl(e){return e.split("/").find(t=>t.length>0)===".info"}function uS(){const e=new Error("INVALID_PARAMETERS: Invalid token in path");return e.code="INVALID_PARAMETERS",e}function Ce(e,t){const n=t===void 0?[e]:Object.keys(t).map(r=>`${e}/${r}`);if(Kl(e)||n.some(Kl))throw uS()}class dS{state;values;children;writes;transactions;persistence;constructor(t,n){this.state=new V_(t,n),this.values=new J_(this.state),this.children=new Q_(this.state),this.writes=new Xh(this.state,this.values,this.children),this.transactions=new lS(this.state,this.values,this.children),this.persistence=new oS(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){Ce(t),this.writes.adminSet(t,n)}adminSetWithPriority(t,n,r){Ce(t),this.writes.adminSetWithPriority(t,n,r)}adminUpdate(t,n){Ce(t,n),this.writes.adminUpdate(t,n)}adminRemove(t){Ce(t),this.writes.adminRemove(t)}adminSetPriority(t,n){Ce(t),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)}unspecifiedIndexWarning(t,n){return this.state.unspecifiedIndexWarning(t,n)}set(t,n,r){Ce(n),this.writes.set(t,n,r)}setWithPriority(t,n,r,s){Ce(n),this.writes.setWithPriority(t,n,r,s)}update(t,n,r){Ce(n,r),this.writes.update(t,n,r)}remove(t,n){Ce(n),this.writes.remove(t,n)}setPriority(t,n,r){Ce(n),this.writes.setPriority(t,n,r)}validateRead(t,n,r){this.writes.validateRead(t,n,r)}validatePriority(t,n,r){Ce(n),this.writes.validatePriority(t,n,r)}registerDisconnect(t,n){n.kind==="update"?Ce(n.path,n.values):Ce(n.path),this.writes.registerDisconnect(t,n)}validateSet(t,n,r,s=null){Ce(n),this.writes.validateSet(t,n,r,s)}validateUpdate(t,n,r){Ce(n,r),this.writes.validateUpdate(t,n,r)}onValue(t,n,r,s,i,o,a){return this.values.onValue(t,n,r,s,i,o,a)}adminOnValue(t,n,r){return this.values.adminOnValue(t,n,r)}runTransaction(t,n,r,s){return Ce(n),this.transactions.run(t,n,r,s)}onChild(t,n,r,s,i,o,a){return this.children.onChild(t,n,r,s,i,o,a)}adminOnChild(t,n,r,s){return this.children.adminOnChild(t,n,r,s)}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(t=!1){this.persistence.reset(t)}subscribeWrites(t){return this.persistence.subscribe(t)}mintKey(){return aS(this.state.clock.now())}listenerCount(){return this.values.count()}childListenerCount(){return this.children.count()}}const Gl=new WeakMap,Jl=new WeakMap;function fS(e,t){const n=hS(e);return n.getOrCreate(n.keyOf(t))}function hS(e){const t=Gl.get(e);if(t)return t;const n=new Set,r=()=>{for(const i of n)try{i()}catch{}},s=Ox({create:i=>{const o=i===s.defaultKey?void 0:i,a=new dS(e,o);return a.subscribeWrites(r),a}});return Gl.set(e,s),e.onEvent(i=>{if(i.kind==="session_boundary"&&i.phase==="reset")for(const[,o]of s.entries())o.invalidateConnectionQueues(),Jl.has(e)||o.setRules(null)}),e.registerPersistableService("rtdb",{snapshot:()=>{const i=s.getOrCreate(s.defaultKey).exportPersistenceState(),o={};for(const[a,l]of s.entries())a!==s.defaultKey&&(o[a]=l.exportPersistenceState());return Object.keys(o).length>0&&i!==null&&typeof i=="object"&&!Array.isArray(i)?{...i,instances:o}:i},restore:i=>{if(!i||typeof i!="object")return;s.getOrCreate(s.defaultKey).restoreTree(i);const o=i;if(o.instances&&typeof o.instances=="object")for(const[a,l]of Object.entries(o.instances))s.getOrCreate(a).restoreTree(l)},subscribe:i=>(n.add(i),()=>{n.delete(i)}),reset:()=>{for(const[,i]of s.entries())i.resetTree(Jl.has(e))}}),s}const Zh="type.googleapis.com/google.rpc.BadRequest",ep="type.googleapis.com/google.firebase.fcm.v1.FcmError";function es(e,t){return{"@type":Zh,fieldViolations:[{field:e,description:t}]}}function hn(e){return{"@type":ep,errorCode:e}}function Fn(e,t){return{status:400,error:{code:400,message:e,status:"INVALID_ARGUMENT",details:t}}}function Yl(){const e="Recipient of the message is not set.";return Fn(e,[es("message",e),hn("INVALID_ARGUMENT")])}function pS(){const e="Exactly one of token, topic or condition is required.";return Fn(e,[es("message",e),hn("INVALID_ARGUMENT")])}function mS(){const e="The registration token is not a valid FCM registration token";return Fn(e,[hn("INVALID_ARGUMENT"),es("message.token",e)])}function tp(){const e="Topic name contains invalid characters.";return Fn(e,[es("message",e),hn("INVALID_ARGUMENT")])}function yS(){return{status:400,error:{code:400,message:"Request contains an invalid argument.",status:"INVALID_ARGUMENT"}}}function gS(){return Fn("Message is too large. The maximum is 4K (4096 bytes).",[{"@type":Zh},hn("INVALID_ARGUMENT")])}function bS(){const e="TTL must be a non-negative integer.";return Fn(e,[es("message.webpush.headers.TTL",e),hn("INVALID_ARGUMENT")])}function wS(){return{status:404,error:{code:404,message:"Requested entity was not found.",status:"NOT_FOUND",details:[hn("UNREGISTERED")]}}}function vS(e){return e.error.details?.find(n=>n["@type"]===ep)?.errorCode}class tt extends Error{envelope;errorCode;constructor(t){super(t.error.message),this.name="BrokerSendError",this.envelope=t,this.errorCode=vS(t)}}const xS=/^[a-zA-Z0-9-_.~%]+$/,ki=/^[A-Za-z0-9_-]+:[A-Za-z0-9_-]+$/,_S=4506,Ql=new TextEncoder;function SS(e){if(e===void 0)return 0;let t=0;for(const[n,r]of Object.entries(e))t+=Ql.encode(n).length+Ql.encode(String(r)).length;return t}function pc(e){return e.startsWith("/topics/")?e.slice(8):e}function ji(e){const t=pc(e);return t.length>0&&xS.test(t)}function kS(e){const t=e;let n=0;const r=[];function s(){for(;n<t.length&&/\s/.test(t[n]);)n++}function i(l){return s(),t.startsWith(l,n)?(n+=l.length,!0):!1}function o(){if(s(),i("!"))return o();if(i("("))return a()?i(")"):!1;if(s(),t[n]!=="'")return!1;n++;const l=n;for(;n<t.length&&t[n]!=="'";)n++;if(n>=t.length)return!1;const u=t.slice(l,n);return n++,!i("in")||!i("topics")||!ji(u)?!1:(r.push(u),!0)}function a(){if(!o())return!1;for(;;){if(s(),i("&&")||i("||")){if(!o())return!1;continue}return!0}}return!a()||(s(),n!==t.length)?null:{topics:r}}function jS(e){if(typeof e!="object"||e===null)throw new tt(Yl());const t=[];if(typeof e.token=="string"&&t.push({kind:"token",token:e.token}),typeof e.topic=="string"&&t.push({kind:"topic",topic:pc(e.topic)}),typeof e.condition=="string"&&t.push({kind:"condition",condition:e.condition,topics:[]}),t.length===0)throw new tt(Yl());if(t.length>1)throw new tt(pS());const n=t[0];if(n.kind==="token"&&!ki.test(n.token))throw new tt(mS());if(n.kind==="topic"&&!ji(n.topic))throw new tt(tp());if(n.kind==="condition"){const s=kS(n.condition);if(s===null)throw new tt(yS());n.topics=s.topics}const r=e.webpush?.headers?.TTL;if(r!==void 0&&!/^\d+$/.test(String(r)))throw new tt(bS());if(SS(e.data)>_S)throw new tt(gS());return n}function np(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ES(e){if(!(Array.isArray(e)&&e.length===2))return!1;const[n,r]=e,s=typeof n=="string"&&ki.test(n),i=np(r);if(!(s&&i))return!1;const a=typeof r.registrationId=="string"&&r.registrationId.length>0,l=typeof r.recipientId=="string"&&r.recipientId.length>0,u=r.state==="active"||r.state==="unregistered";return a&&l&&u}function CS(e){return typeof e=="string"&&ki.test(e)}function NS(e){if(!(Array.isArray(e)&&e.length===2))return!1;const[n,r]=e,s=typeof n=="string"&&ji(n),i=Array.isArray(r)&&r.every(CS);return s&&i}function RS(e){if(!np(e))return!1;const t=e.version===1,n=Array.isArray(e.tokens)&&e.tokens.every(ES),r=Array.isArray(e.topics)&&e.topics.every(NS);return t&&n&&r}function IS(e){return/[.!?]$/.test(e)?e:`${e}.`}const AS="database.rules.json";function Xl(e,t){const n=e.lastIndexOf("."),r=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\")),s=n>r+1?e.slice(n):"";if(s===".json")return;const i=s===".bolt"?"As of firebase-tools@15.0.0, .bolt rules are no longer supported.":`Unexpected rules format ${s}`;throw new Error(`${t}: ${i}`)}function OS(e){if(e===void 0)return Ho(void 0);const t=$h(e);try{return lc(t).name}catch{return t}}function $S(e,t={}){const n=t.resolveFile??(o=>o),r=OS(t.projectId);if(e==null){const o=AS;return{defaultInstance:r,targets:[{instance:r,file:n(o),configuredFile:o,label:"firebase.json",configured:!1}],unresolved:[]}}if(!Array.isArray(e)){const o=typeof e=="object"?e.rules:void 0;if(typeof o!="string"||o==="")return{defaultInstance:r,targets:[],unresolved:[]};const a="firebase.json database.rules";return Xl(o,a),{defaultInstance:r,targets:[{instance:r,file:n(o),configuredFile:o,label:a,configured:!0}],unresolved:[]}}const s=[],i=[];return e.forEach((o,a)=>{const l=`firebase.json database[${a}]`,u=o!==null&&typeof o=="object"?o:{};let d;if(typeof u.target=="string"&&u.target!==""){const f=t.targetInstances?.(u.target);d=Array.isArray(f)?f.filter(p=>typeof p=="string"&&p!==""):[]}else if(typeof u.instance=="string"&&u.instance!=="")d=[u.instance];else throw new Error(`${l}: Must supply either "target" or "instance" in database config`);if(typeof u.rules!="string"||u.rules==="")return;Xl(u.rules,l);const h=n(u.rules);if(d.length===0&&typeof u.target=="string"){i.push({target:u.target,label:l,file:h});return}for(const f of d){let p;try{p=lc(f).name}catch(g){const b=g instanceof Error?g.message.trim():String(g);throw new Error(`${l}: instance "${f}" is not a database instance name: ${b}`)}Dh(p,t.projectId)&&(p=r);const m=s.find(g=>g.instance===p);if(m===void 0){s.push({instance:p,file:h,configuredFile:u.rules,label:l,configured:!0});continue}if(m.file!==h)throw new Error(`firebase.json deploys two rules files to database instance "${p}": ${m.file} from ${m.label} and ${h} from ${l}. The Firebase CLI deploys both at once, so the configuration does not determine which one production keeps. Deploy one rules file to each instance.`)}}),{defaultInstance:r,targets:s,unresolved:i}}const DS="__pyric_no_password__",PS=300*1e3;function no(e){return Fh(e.claims)}class rp{usersByEmail;usersByUid;authStateSubs=[];idTokenSubs=[];userDbSubs;beforeStateSubs=[];sharedCounters;flow=new bx;sandbox;session;cachedUser=null;lastNotifiedUid=null;applyingTransition=!1;tokenCache=new Map;nextTokenSerial=1;persistenceMode="LOCAL";signInProviderByUid=new Map;authenticatedAtByUid=new Map;providerConfig;providerConfigSubs;providerEnforcementDelegated=!1;avatarMint=Rx;tenantId=null;getTenantId(){return this.tenantId}setTenantId(t){this.tenantId=t}constructor(t,n=t,r=Ah(),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(o=>{if(this.applyingTransition)return;const a=o===null?null:o.uid,l=this.cachedUser?.uid??null;a!==l&&(this.cachedUser=this.buildUserFromState(o)),this.notifyAuthListeners()});s?.(()=>{i(),this.authStateSubs.length=0,this.idTokenSubs.length=0,this.beforeStateSubs.length=0})}getCurrentUser(){return this.cachedUser}getCurrentSignInProvider(){const t=this.cachedUser;return t===null?null:this.signInProviderByUid.get(t.uid)??null}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,n=null){const r={email:null,password:null,displayName:null,phoneNumber:null,photoUrl:null,customClaims:{},isAnonymous:!1,providerUserInfo:[],disabled:!1,emailVerified:!1,createdAt:this.now().toISOString(),lastLoginAt:null,tenantId:null,...t},s=TS(r,n);return MS(r,s)&&(r.photoUrl=this.avatarMint({uid:r.uid,displayName:r.displayName,email:r.email,providerId:s})),r}notifyUsersChanged(){for(const t of[...this.userDbSubs])try{t()}catch{}}now(){return Te(this.sandbox).date()}emitAuthEvent(t,n={}){try{pt(this.sandbox,Ln({at:this.now().getTime(),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}setAvatarMint(t){this.avatarMint=t}assertProviderEnabled(t){if(!this.providerEnforcementDelegated&&!this.isProviderEnabled(t))throw Y("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 r of t){const i=this.usersByUid.get(r.uid)?.email;typeof i=="string"&&i.length>0&&i.toLowerCase()!==r.email?.toLowerCase()&&this.usersByEmail.delete(i.toLowerCase());const l=r.providerId==="anonymous",u=r.providerUserInfo??[{providerId:r.providerId??"password"}],d=l?[]:u.map(k=>({...k})),h=d.some(k=>k.providerId==="password"),p=(r.password===DS||r.password==="__pyric_popup_no_password__")&&!h,m=l||p,g=this.makeStored({uid:r.uid,email:l?null:r.email??null,password:m?null:r.password??null,displayName:r.displayName??null,phoneNumber:r.phoneNumber??null,photoUrl:r.photoUrl??null,customClaims:r.customClaims??{},emailVerified:r.emailVerified??!1,disabled:r.disabled??!1,isAnonymous:l,providerUserInfo:d,tenantId:r.tenantId??null}),{createdAt:b,lastLoginAt:w,email:x}=r;b!==void 0&&(g.createdAt=b),w!==void 0&&(g.lastLoginAt=w),!l&&x!==void 0&&this.usersByEmail.set(x.toLowerCase(),g),this.usersByUid.set(r.uid,g)}t.length>0&&this.notifyUsersChanged()}exportUsers(){const t=[];for(const n of this.usersByUid.values()){const{email:r,displayName:s,photoUrl:i,tenantId:o,phoneNumber:a,isAnonymous:l,disabled:u,emailVerified:d}=n,h=s!==null,f=i!==null,p=Object.keys(n.customClaims).length>0,m=o!==null;if(l){const _={uid:n.uid,providerId:"anonymous",createdAt:n.createdAt,lastLoginAt:n.lastLoginAt};h&&(_.displayName=s),f&&(_.photoUrl=i),p&&(_.customClaims=n.customClaims),u&&(_.disabled=!0),m&&(_.tenantId=o),t.push(_);continue}if(r===null)continue;const b={uid:n.uid,createdAt:n.createdAt,lastLoginAt:n.lastLoginAt,email:r,providerId:n.providerUserInfo[0]?.providerId??"password",providerUserInfo:n.providerUserInfo.map(_=>({..._}))},{password:w}=n;w!==null&&(b.password=w),h&&(b.displayName=s),f&&(b.photoUrl=i),a!==null&&(b.phoneNumber=a),p&&(b.customClaims=n.customClaims),d&&(b.emailVerified=!0),u&&(b.disabled=!0),m&&(b.tenantId=o),t.push(b)}return t}restoreSession(t){const n=this.usersByUid.get(t);if(!n)throw Y("auth/user-not-found",`restoreSession: no identity with uid ${t}.`);if(n.disabled)throw Y("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){Qn(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){Qt(n);const r=this.requireByEmail(t),s=n.toLowerCase(),i=this.usersByEmail.get(s);if(i&&i.uid!==r.uid)throw Y("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){Qt(t);const n=t.toLowerCase(),r=this.usersByEmail.get(n);if(r!==void 0)return!r.providerUserInfo.some(l=>l.providerId==="password")&&r.providerUserInfo.push({providerId:"password"}),r.emailVerified=!0,this.notifyUsersChanged(),{stored:r,isNewUser:!1};const i=`email-${globalThis.crypto.randomUUID()}`,o=this.makeStored({uid:i,email:t,providerUserInfo:[{providerId:"password"}]});return o.emailVerified=!0,this.usersByEmail.set(n,o),this.usersByUid.set(i,o),this.notifyUsersChanged(),this.emitAuthEvent("user_create",{path:i,after:this.toRecord(o),detail:{emailLink:!0}}),{stored:o,isNewUser:!0}}linkProvider(t,n,r){const s=this.usersByUid.get(t);if(!s)throw Y("auth/user-not-found",`linkWithCredential: no identity with uid ${t}.`);if(s.providerUserInfo.some(o=>o.providerId===n))throw Y("auth/provider-already-linked",`User can only be linked to one identity for the given provider (${n}).`);const i=r?.email;if(i){Qt(i);const o=i.toLowerCase(),a=this.usersByEmail.get(o);if(a&&a.uid!==t)throw Y("auth/email-already-in-use",`An account already exists for ${i}.`);r.password!==void 0&&r.password!==null&&(Qn(r.password),s.password=r.password),s.email&&s.email.toLowerCase()!==o&&this.usersByEmail.delete(s.email.toLowerCase()),s.email=i,this.usersByEmail.set(o,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 Y("auth/user-not-found",`unlink: no identity with uid ${t}.`);const s=r.providerUserInfo.findIndex(i=>i.providerId===n);if(s<0)throw Y("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 Y("auth/user-not-found",`No user found for ${t}.`);return n}createEmailPasswordUser(t,n){Qt(t),Qn(n);const r=t.toLowerCase();if(this.usersByEmail.has(r))throw Y("auth/email-already-in-use",`An account already exists for ${t}.`);const i=`email-${globalThis.crypto.randomUUID()}`,o=this.makeStored({uid:i,email:t,password:n,providerUserInfo:[{providerId:"password"}]});return this.usersByEmail.set(r,o),this.usersByUid.set(i,o),this.notifyUsersChanged(),this.emitAuthEvent("user_create",{path:i,after:this.toRecord(o)}),o}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 Y("auth/login-blocked",s)}}transitionCurrentUser(t,n){return t!==null&&n!==void 0&&this.scopeSignInToTenant(t),!this.beforeStateSubs.some(s=>s.active)||t===this.cachedUser?(this.setCurrentUser(t,n),Promise.resolve()):this.runBeforeStateChange(t).then(()=>{this.setCurrentUser(t,n)})}scopeSignInToTenant(t){const n=this.tenantId;t.tenantId=n;const r=this.usersByUid.get(t.uid);r&&(r.tenantId=n)}setCurrentUser(t,n){if(t===null){const p=this.cachedUser;this.cachedUser=null,this.applyingTransition=!0;try{this.session.currentUser=null}finally{this.applyingTransition=!1}p!==null&&(this.tokenCache.delete(p.uid),this.notifyAuthListeners(),this.notifySessionChanged(),this.emitAuthEvent("sign_out",{path:p.uid,auth:{uid:p.uid}}));return}const s=n!==void 0;s&&this.signInProviderByUid.set(t.uid,n),(s||!this.authenticatedAtByUid.has(t.uid))&&this.recordAuthentication(t.uid);const o=this.usersByUid.get(t.uid),a=o?.customClaims??{};s&&o!==void 0&&(o.lastLoginAt=this.now().toISOString(),this.notifyUsersChanged()),this.cachedUser=t;const u=this.mintToken(t.uid,a,t.tenantId??null),d={uid:t.uid,token:no(u.result)};typeof t.tenantId=="string"&&(d.tenant=t.tenantId);const f=d;this.applyingTransition=!0;try{this.session.currentUser=f}finally{this.applyingTransition=!1}this.notifyAuthListeners(),this.notifySessionChanged(),s&&this.emitAuthEvent("sign_in",{path:t.uid,auth:f,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;const s=t.photoURL??null;let i=this.usersByUid.get(t.uid);i?Zl(i,s)&&(r=!0):(i=this.makeStored({uid:t.uid,email:t.email,displayName:t.displayName,photoUrl:s,isAnonymous:t.isAnonymous},n),this.usersByUid.set(t.uid,i),t.email&&this.usersByEmail.set(t.email.toLowerCase(),i),r=!0),i.providerUserInfo.some(o=>o.providerId===n)||(i.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 Y("auth/user-not-found",`createSignInCredential: no identity with uid ${t.uid}. Use the {spec} shape to create one.`);this.assertUserEnabled(s),r=s}else{const{spec:s}=t,i=s.photoUrl??null,o=this.usersByEmail.get(s.email.toLowerCase());o?(this.assertUserEnabled(o),r=o,Zl(r,i)&&this.notifyUsersChanged()):(r=this.makeStored({uid:s.uid??LS(),email:s.email,displayName:s.displayName??null,photoUrl:i,customClaims:s.customClaims??{}},n),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,tenantId:t.tenantId,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 o of t){const a=o?.providerId?.trim();if(!a)throw Y("auth/argument-error",`${r}: providerUserInfo entries need a non-empty providerId.`);a==="password"||a==="anonymous"||s.has(a)||(s.add(a),i.push({providerId:a}))}return n&&i.unshift({providerId:"password"}),i}nextAvailableAdminUid(){for(;;){const t=`user-${this.sharedCounters.nextAdminUserId++}`;if(!this.usersByUid.has(t))return t}}createUser(t){t.customClaims!==void 0&&Ol(t.customClaims);const n=t.uid??this.nextAvailableAdminUid();if(this.usersByUid.has(n))throw Y("auth/uid-already-exists",`createUser: a user with uid ${n} already exists.`);if(t.email!==void 0&&(Qt(t.email),this.usersByEmail.has(t.email.toLowerCase())))throw Y("auth/email-already-in-use",`An account already exists for ${t.email}.`);if(t.password!==void 0&&(Qn(t.password),t.email===void 0))throw Y("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 Y("auth/user-not-found",`No user found for uid ${t}.`);n.customClaims!==void 0&&Ol(n.customClaims);const s=this.toRecord(r);if(n.email!==void 0){Qt(n.email);const o=n.email.toLowerCase(),a=this.usersByEmail.get(o);if(a&&a!==r)throw Y("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(o,r)}n.password!==void 0&&(Qn(n.password),r.password=n.password,r.providerUserInfo.some(o=>o.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 Y("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.authenticatedAtByUid.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 Y("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,tenantId:t.tenantId})}mintAnonymousUser(){const t=`anonymous-${globalThis.crypto.randomUUID()}`,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){const n=t.tenantId??null;switch(t.kind){case"anonymous":return this.assertProviderEnabled("anonymous"),this.establishDetachedSession(this.mintAnonymousUser(),"anonymous",n);case"password":return this.assertProviderEnabled("password"),this.establishDetachedSession(this.buildUserFromStored(this.validatePassword(t.email,t.password)),"password",n);case"createPassword":return this.assertProviderEnabled("password"),this.establishDetachedSession(this.buildUserFromStored(this.createEmailPasswordUser(t.email,t.password)),"password",n);case"provider":case"custom":case"uid":{const r=t.kind==="provider";r&&this.assertProviderEnabled(t.providerId);const s=this.usersByUid.get(t.uid);if(s===void 0)throw Y("auth/user-not-found",`mintSession: no identity with uid ${t.uid}.`);this.assertUserEnabled(s);const a=s.isAnonymous?"anonymous":s.providerUserInfo[0]?.providerId??"password";let l=r?t.providerId:a;t.kind==="custom"&&(l="custom");const d=t.kind!=="uid"||!this.authenticatedAtByUid.has(t.uid);return this.establishDetachedSession(this.buildUserFromStored(s),l,n,d)}}}establishDetachedSession(t,n,r,s=!0){this.signInProviderByUid.set(t.uid,n),s&&this.recordAuthentication(t.uid);const i=this.usersByUid.get(t.uid),o=i?.customClaims??{};i!==void 0&&s&&(i.lastLoginAt=this.now().toISOString(),this.notifyUsersChanged()),t.tenantId=r;const l=this.mintToken(t.uid,o,r),u={uid:t.uid,token:no(l.result)};return r!==null&&(u.tenant=r),this.emitAuthEvent("sign_in",{path:t.uid,auth:u,after:{uid:t.uid,isAnonymous:t.isAnonymous,email:t.email},detail:{providerId:n,session:"connection"}}),{user:t,state:u}}buildUserFromState(t){if(t===null)return null;const n=this.usersByUid.get(t.uid);return n?this.buildUserFromStored({...n,customClaims:t.token??n.customClaims,tenantId:t.tenant??n.tenantId}):this.makeUser({uid:t.uid,email:null,displayName:null,isAnonymous:t.uid.startsWith("anonymous-"),claims:t.token??{},tenantId:t.tenant??null})}mintToken(t,n,r){const s=this.now(),i=new Date(s.getTime()+100*365*24*60*60*1e3),o=this.nextTokenSerial++,a=this.signInProviderByUid.get(t)??null,l=new Date(this.authenticatedAtByUid.get(t)??s.getTime()),u=this.usersByUid.get(t),d={sub:t,aud:"pyric-sandbox",iss:"https://sandbox.pyric.dev",auth_time:Math.floor(l.getTime()/1e3),iat:Math.floor(s.getTime()/1e3),exp:Math.floor(i.getTime()/1e3),...qh(t,u?k_(u):null,n,a)},f=wi({uid:t,tenant:r??void 0,token:d})?.token??d,p=wx(t,Fh(f),o),m={token:p,claims:f,expirationTime:i.toISOString(),issuedAtTime:s.toISOString(),authTime:l.toISOString(),signInProvider:a},g={token:p,result:m},b=this.tokenCache.get(t)??new Map;return b.set(r,g),this.tokenCache.set(t,b),g}getIdTokenFor(t,n,r,s=null){return this.getIdTokenResultFor(t,n,r,s).token}getIdTokenResultFor(t,n,r,s=null){if(r){const l=this.mintToken(t,n,s),u=this.session.currentUser;if(u!==null&&u.uid===t&&(u.tenant??null)===s){this.applyingTransition=!0;try{this.session.currentUser={...u,token:no(l.result)}}finally{this.applyingTransition=!1}}return this.fanOut("id-token"),l.result}const i=this.tokenCache.get(t)?.get(s);return i!==void 0?i.result:this.mintToken(t,n,s).result}makeUser(t){const n=t.photoURL??null,r=t.phoneNumber??null,s=t.emailVerified??!1,i="firebase",o=t.providers??[{providerId:"password"}],l=t.isAnonymous===!0?[]:o.map(d=>({uid:t.uid,displayName:t.displayName,email:t.email,phoneNumber:r,photoURL:n,providerId:d.providerId})),u={uid:t.uid,email:t.email,emailVerified:s,displayName:t.displayName,photoURL:n,phoneNumber:r,isAnonymous:t.isAnonymous,tenantId:t.tenantId??null,providerId:i,providerData:l,getIdToken:async d=>this.getIdTokenFor(t.uid,this.liveClaims(t.uid,t.claims),d===!0,u.tenantId),getIdTokenResult:async d=>this.getIdTokenResultFor(t.uid,this.liveClaims(t.uid,t.claims),d===!0,u.tenantId)};return Object.defineProperty(u,mx,{value:{updateProfile:d=>(this.updateProfileFor(u,d),Promise.resolve()),delete:()=>(this.deleteFor(u),Promise.resolve()),updateEmail:d=>(this.updateEmailFor(u,d),Promise.resolve()),updatePassword:d=>(this.updatePasswordFor(u,d),Promise.resolve()),reload:()=>(this.reloadFor(u),Promise.resolve()),target:this.selfTarget()},enumerable:!1}),u}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 Y("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}recordAuthentication(t){this.authenticatedAtByUid.set(t,this.now().getTime())}assertRecentLogin(t){if(this.usersByUid.get(t)?.isAnonymous===!0)return;const r=this.authenticatedAtByUid.get(t);if(r===void 0)return;if(this.now().getTime()-r>PS)throw Y("auth/requires-recent-login","Error")}deleteFor(t){this.assertRecentLogin(t.uid),this.usersByUid.has(t.uid)&&this.deleteUser(t.uid),this.cachedUser&&this.cachedUser.uid===t.uid&&this.setCurrentUser(null)}updateEmailFor(t,n){this.assertRecentLogin(t.uid),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.assertRecentLogin(t.uid),this.updateUser(t.uid,{password:n})}reloadFor(t){const n=this.usersByUid.get(t.uid);if(!n)throw Y("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}assertUserEnabled(t){if(t.disabled)throw Y("auth/user-disabled","The user account has been disabled by an administrator.")}validatePassword(t,n){if(Qt(t),typeof n!="string"||n.length===0)throw Y("auth/missing-password","A non-empty password must be provided");const r=this.findByEmail(t);if(!r)throw Y("auth/user-not-found",`No user found for ${t}.`);if(this.assertUserEnabled(r),r.password!==n)throw Y("auth/wrong-password","Invalid password.");return r}}function TS(e,t){if(t!==null)return t;const n=e.providerUserInfo[0];return n===void 0?null:n.providerId}function MS(e,t){return e.photoUrl!==null||e.isAnonymous||t===null?!1:t.includes(".")}function Zl(e,t){return t===null||e.photoUrl===t?!1:(e.photoUrl=t,!0)}function LS(){return`provider-${globalThis.crypto.randomUUID()}`}const eu=new WeakSet,hs=new WeakMap;function sp(e,t,n,r="[DEFAULT]"){return US(e,t),BS(e,t,n,r)}function US(e,t){eu.has(e)||(eu.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 tu(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 BS(e,t,n,r){let s=hs.get(e);s||(s=new Map,hs.set(e,s));const i=`auth-session:${r}`,o=s.get(i);if(o){const u=++o.generation;return o.unregisterService?.(),o.unregisterService=void 0,o.unsubscribeBackend?.(),o.unsubscribeBackend=void 0,o.backend=t,o.session=n,o.unregisterService=e.registerPersistableService(i,tu(o)),()=>{o.generation===u&&(o.unregisterService?.(),o.unregisterService=void 0,o.unsubscribeBackend?.(),o.unsubscribeBackend=void 0,o.subscribers.clear(),s.get(i)===o&&s.delete(i),s.size===0&&hs.delete(e))}}const a={backend:t,session:n,subscribers:new Set,generation:1};s.set(i,a),a.unregisterService=e.registerPersistableService(i,tu(a));const l=a.generation;return()=>{a.generation===l&&(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&&hs.delete(e))}}async function m1(e){const{backend:t}=cc(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 FS(e){const t=cc(e,!0);try{t.assertAlive?.()}catch(n){if(n.code==="app/app-deleted")return;throw n}await t.backend.transitionCurrentUser(null)}const nu=new WeakMap,ru=new WeakMap,su=new WeakMap;function ip(e){let t=ru.get(e);return t||(t=Ah(),ru.set(e,t)),t}function qS(e){let t=nu.get(e);return t||(t=new rp(e,e,ip(e)),nu.set(e,t),sp(e,t,e)),t}function VS(e,t){return t.service("auth/backend",()=>{const{sandbox:n,session:r}=t,s=new rp(n,r,ip(n),i=>{t.onDelete(i)});return t.onDelete(sp(n,s,r,e.name)),s})}function mc(e){if(e===void 0)return mc(Iw());const t=Aw(e);if(t)return t.service("auth/default",()=>{const n={kind:"sandbox",sandbox:t.sandbox,backend:VS(e,t),own:r=>t.onDelete(r),assertAlive:()=>t.assertAlive()};return iu(n,e)});if(WS(e)){let n=su.get(e);return n||(n=iu({kind:"sandbox",sandbox:e,backend:qS(e)}),su.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 WS(e){return typeof e=="object"&&e!==null&&typeof e.onCurrentUserChanged=="function"&&typeof e.withAuth=="function"}function iu(e,t){const n={[Nh]:e,...t?{app:t}:{},signOut(){return FS(n)}};return Object.defineProperty(n,"currentUser",{enumerable:!0,get(){return e.backend.getCurrentUser()}}),Object.defineProperty(n,"tenantId",{enumerable:!0,get(){return e.backend.getTenantId()},set(r){e.backend.setTenantId(r)}})}function X(e){return cc(e)}const xe={setUser(e,t){X(e).backend.setCurrentUser(t)},setAuthFlowResolver(e,t){X(e).backend.setResolver(t)},setAuthMailResolver(e,t){X(e).backend.setMailResolver(t)},takeAuthMail(e,t){return X(e).backend.takeMail(t)},listAuthMail(e){return X(e).backend.listMail()},mockActionCode(e,t,n){X(e).backend.stageActionCode(t,n)},listIdentities(e){return X(e).backend.listIdentities()},createSignInCredential(e,t){return X(e).backend.createSignInCredential(t)},mockSignInResult(e,t){const n=t.providerId;if(!n)throw new Yf("invalid-argument","sandbox.mockSignInResult: result.providerId is required so the next signInWithPopup / signInWithCredential call can match.");X(e).backend.setMockResult(n,t)},seedUsers(e,t){X(e).backend.seedUsers(t)},exportUsers(e){return X(e).backend.exportUsers()},restoreSession(e,t){return X(e).backend.restoreSession(t)},getTenantId(e){return X(e).backend.getTenantId()},setTenantId(e,t){X(e).backend.setTenantId(t)},mintSession(e,t){return X(e).backend.mintDetachedSession(t)},signInProvider(e){return X(e).backend.getCurrentSignInProvider()},listUsers(e){return X(e).backend.listUsers()},createUser(e,t){return X(e).backend.createUser(t)},updateUser(e,t,n){return X(e).backend.updateUser(t,n)},updateProfile(e,t,n){return X(e).backend.updateProfileByUid(t,n)},deleteUser(e,t){X(e).backend.deleteUser(t)},clearUsers(e){X(e).backend.clearUsers()},subscribeUsers(e,t){return X(e).backend.subscribeUsers(t)},exportProviderConfig(e){return X(e).backend.exportProviderConfig()},restoreProviderConfig(e,t){X(e).backend.restoreProviderConfig(t)},getAuthProviderConfig(e){return X(e).backend.listProviderConfig()},setAuthProviderConfig(e,t,n){X(e).backend.setProviderConfig(t,n)},assertAuthProviderEnabled(e,t){X(e).backend.assertProviderEnabled(t)},delegateProviderEnforcement(e,t){X(e).backend.setProviderEnforcementDelegated(t)},setAvatarMint(e,t){X(e).backend.setAvatarMint(t)},subscribeAuthProviderConfig(e,t){return X(e).backend.subscribeProviderConfig(t)}};function Qo(e){return e!==void 0&&/^[0-9]+$/.test(e)?BigInt(e):0n}function zS(e,t){return e>t?e:t}function yc(e,t){return e===void 0?t:t===void 0||Qo(e)>=Qo(t)?e:t}function op(e,t){return yc(e,t)??t}function ap(e){return BigInt(Math.floor(e*1e3))}function HS(e){return t=>String(zS(ap(e),Qo(t)+1n))}const Xo="pyric-storage",te="pyric-default";function oe(e,t){return`${e}/${t}`}function ei(e){const t=e.indexOf("/");return t===-1?null:{bucket:e.slice(0,t),path:e.slice(t+1)}}function KS(e){return e?`${Xo}:${e}`:Xo}const GS=2,ke="blobs",le="metadata",gr="generations";function cp(e,t,n){if(e.metadata.bucket!==t||e.metadata.fullPath!==n)throw new Error("A prior Storage object can only be put back at its own bucket and path.");gc(e.blob,e.metadata)}function gc(e,t){if(t.size!==e.size)throw new Error("Storage metadata does not match its object.")}async function JS(e=Xo,t){try{const n=await ek(e);return new ZS(n,t)}catch(n){return typeof indexedDB<"u"&&lp(e,QS(n),"other tabs reload"),new XS(t)}}class YS extends Error{name="OpenBlockedError"}function QS(e){return e instanceof Error||typeof DOMException<"u"&&e instanceof DOMException?`${e.name}: ${e.message}`:String(e)}function lp(e,t,n){console.warn(`[pyric] Storage could not use the IndexedDB store "${e}" (${t}). Storage will not persist until ${n}.`)}class up{uploads=new Map;beginUpload(t,n,r,s,i){const o=typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`upl-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;return this.uploads.set(o,{uploadId:o,bucket:t,path:n,size:r,contentType:s,customMetadata:i,parts:new Map,createdAt:Date.now()}),o}putPart(t,n,r){const s=this.uploads.get(t);if(!s){const o=new Error(`storage/object-not-found: Upload '${t}' not found.`);throw o.code="storage/object-not-found",o}s.parts.set(n,r);let i=0;for(const o of s.parts.values())i+=o.byteLength;return{bytesReceived:i}}readUpload(t){const n=this.uploads.get(t);if(!n){const i=new Error(`storage/object-not-found: Upload '${t}' not found.`);throw i.code="storage/object-not-found",i}let r=0;const s=Array.from(n.parts.keys()).sort((i,o)=>i-o);for(const i of s)r+=n.parts.get(i).byteLength;if(r!==n.size){const i=new Error(`storage/invalid-argument: Uploaded bytes (${r}) did not match declared size (${n.size}).`);throw i.code="storage/invalid-argument",i}return new Blob(s.map(i=>n.parts.get(i)),{type:n.contentType})}abortUpload(t){this.uploads.delete(t)}}class XS{blobs=new Map;metadata=new Map;highWater=new Map;staging=new up;_defaultBucket;constructor(t){this._defaultBucket=t}async put(t,n,r,s){const i=r.bucket||this._defaultBucket||te;this._defaultBucket||(this._defaultBucket=i),gc(n,r),r.bucket||(r.bucket=i);const o=oe(i,t),a=this.objectAt(o),l=this.highWater.get(o);return s!==void 0&&(r.generation=s(yc(a?.metadata.generation,l))),this.blobs.set(o,n),this.metadata.set(o,r),this.highWater.set(o,op(l,r.generation)),a}objectAt(t){const n=this.blobs.get(t),r=this.metadata.get(t);if(!(n===void 0||r===void 0))return{blob:n,metadata:r}}async deleteIfGeneration(t,n,r){return this.replaceIfGeneration(t,n,void 0,r)}async replaceIfGeneration(t,n,r,s){const i=s??this._defaultBucket??te;r!==void 0&&cp(r,i,t);const o=oe(i,t);return this.metadata.get(o)?.generation!==n?!1:(this.blobs.delete(o),this.metadata.delete(o),r===void 0||(this.blobs.set(o,r.blob),this.metadata.set(o,r.metadata)),!0)}async getBlob(t,n){if(n)return this.blobs.get(oe(n,t));const r=this._defaultBucket??te,s=this.blobs.get(oe(r,t));if(s!==void 0)return s;if(r!==te){const i=this.blobs.get(oe(te,t));if(i!==void 0)return i}for(const[i,o]of this.blobs.entries()){const a=ei(i);if(a&&a.path===t)return o}}async getMetadata(t,n){if(n)return this.metadata.get(oe(n,t));const r=this._defaultBucket??te,s=this.metadata.get(oe(r,t));if(s!==void 0)return s;if(r!==te){const i=this.metadata.get(oe(te,t));if(i!==void 0)return i}for(const[i,o]of this.metadata.entries()){const a=ei(i);if(a&&a.path===t)return o}}async getObject(t,n){return this.objectAt(oe(n??this._defaultBucket??te,t))}async putMetadata(t,n,r){const s=r??n.bucket??this._defaultBucket??te;n.bucket||(n.bucket=s),this.metadata.set(oe(s,t),n)}async delete(t,n){const r=n??this._defaultBucket??te;this.blobs.delete(oe(r,t)),this.metadata.delete(oe(r,t))}async listByPrefix(t,n){const s=`${n??this._defaultBucket??te}/${t}`,i=[],o=Array.from(this.metadata.keys()).sort();for(const a of o)if(a.startsWith(s)){const l=this.metadata.get(a);l&&i.push(l)}return i}async reset(t){if(!t){this.blobs.clear(),this.metadata.clear(),this._defaultBucket=void 0;return}const n=`${t}/`;for(const r of Array.from(this.blobs.keys()))r.startsWith(n)&&this.blobs.delete(r);for(const r of Array.from(this.metadata.keys()))r.startsWith(n)&&this.metadata.delete(r)}async beginUpload(t,n,r,s,i){const o=t||this._defaultBucket||te;return this.staging.beginUpload(o,n,r,s,i)}async putPart(t,n,r){return this.staging.putPart(t,n,r)}async readUpload(t){return this.staging.readUpload(t)}async abortUpload(t){this.staging.abortUpload(t)}close(){}scoped(t){return new Ei(this,t)}}class ZS{db;staging=new up;_defaultBucket;closedReason;constructor(t,n){this.db=t,this._defaultBucket=n,t.addEventListener("versionchange",()=>{t.close(),this.closedReason="a newer pyric build opened it in another tab",lp(t.name,this.closedReason,"this tab reloads")})}transaction(t,n){if(this.closedReason!==void 0)throw new Error(`The IndexedDB store "${this.db.name}" closed because ${this.closedReason}. Reload this tab to use Storage.`);return this.db.transaction(t,n)}async put(t,n,r,s){const i=r.bucket||this._defaultBucket||te;this._defaultBucket||(this._defaultBucket=i),gc(n,r),r.bucket||(r.bucket=i);const o=oe(i,t),a=this.transaction([ke,le,gr],"readwrite"),l=tk(a,o),u=a.objectStore(gr).get(o);let d;u.addEventListener("success",()=>{const h=u.result;try{s!==void 0&&(r.generation=s(yc(l.object()?.metadata.generation,h))),a.objectStore(ke).put(n,o),a.objectStore(le).put(r,o),a.objectStore(gr).put(op(h,r.generation),o)}catch(f){d={error:f},a.abort()}});try{await Zn(a)}catch(h){throw d!==void 0?d.error:h}return l.object()}async deleteIfGeneration(t,n,r){return this.replaceIfGeneration(t,n,void 0,r)}async replaceIfGeneration(t,n,r,s){const i=s??this._defaultBucket??te;r!==void 0&&cp(r,i,t);const o=oe(i,t),a=this.transaction([ke,le],"readwrite");let l=!1;const u=a.objectStore(le).get(o);return u.addEventListener("success",()=>{if(u.result?.generation===n){if(l=!0,r===void 0){a.objectStore(ke).delete(o),a.objectStore(le).delete(o);return}a.objectStore(ke).put(r.blob,o),a.objectStore(le).put(r.metadata,o)}}),await Zn(a),l}async getBlob(t,n){const s=this.transaction(ke,"readonly").objectStore(ke);if(n)return vt(s.get(oe(n,t)));const i=this._defaultBucket??te,o=await vt(s.get(oe(i,t)));if(o!==void 0)return o;if(i!==te){const a=await vt(s.get(oe(te,t)));if(a!==void 0)return a}return new Promise((a,l)=>{const u=s.openCursor();u.addEventListener("success",()=>{const d=u.result;if(!d){a(void 0);return}const h=String(d.key),f=ei(h);if(f&&f.path===t){a(d.value);return}d.continue()}),u.addEventListener("error",()=>l(u.error))})}async getMetadata(t,n){const s=this.transaction(le,"readonly").objectStore(le);if(n)return vt(s.get(oe(n,t)));const i=this._defaultBucket??te,o=await vt(s.get(oe(i,t)));if(o!==void 0)return o;if(i!==te){const a=await vt(s.get(oe(te,t)));if(a!==void 0)return a}return new Promise((a,l)=>{const u=s.openCursor();u.addEventListener("success",()=>{const d=u.result;if(!d){a(void 0);return}const h=String(d.key),f=ei(h);if(f&&f.path===t){a(d.value);return}d.continue()}),u.addEventListener("error",()=>l(u.error))})}async getObject(t,n){const r=oe(n??this._defaultBucket??te,t),s=this.transaction([ke,le],"readonly"),[i,o]=await Promise.all([vt(s.objectStore(ke).get(r)),vt(s.objectStore(le).get(r))]);if(!(i===void 0||o===void 0))return{blob:i,metadata:o}}async putMetadata(t,n,r){const s=r??n.bucket??this._defaultBucket??te;n.bucket||(n.bucket=s);const i=oe(s,t),o=this.transaction(le,"readwrite");o.objectStore(le).put(n,i),await Zn(o)}async delete(t,n){const r=n??this._defaultBucket??te,s=oe(r,t),i=this.transaction([ke,le],"readwrite");i.objectStore(ke).delete(s),i.objectStore(le).delete(s),await Zn(i)}async listByPrefix(t,n){const r=n??this._defaultBucket??te,s=this.transaction(le,"readonly"),i=`${r}/${t}`,o=IDBKeyRange.bound(i,i+"�",!1,!1);return vt(s.objectStore(le).getAll(o))}async reset(t){const n=this.transaction([ke,le],"readwrite");if(!t)n.objectStore(ke).clear(),n.objectStore(le).clear(),this._defaultBucket=void 0;else{const r=`${t}/`,s=IDBKeyRange.bound(r,r+"�",!1,!1);n.objectStore(ke).delete(s),n.objectStore(le).delete(s)}await Zn(n)}async beginUpload(t,n,r,s,i){const o=t||this._defaultBucket||te;return this.staging.beginUpload(o,n,r,s,i)}async putPart(t,n,r){return this.staging.putPart(t,n,r)}async readUpload(t){return this.staging.readUpload(t)}async abortUpload(t){this.staging.abortUpload(t)}close(){this.db.close()}scoped(t){return new Ei(this,t)}}class Ei{underlying;bucket;constructor(t,n){this.underlying=t,this.bucket=n}get replacedObjectsOnDisk(){return this.underlying.replacedObjectsOnDisk}async put(t,n,r,s){const i=r.bucket?r:{...r,bucket:this.bucket},o=await this.underlying.put(t,n,i,s);return r.generation=i.generation,o}deleteIfGeneration(t,n,r){return this.underlying.deleteIfGeneration(t,n,r??this.bucket)}replaceIfGeneration(t,n,r,s){return this.underlying.replaceIfGeneration(t,n,r,s??this.bucket)}references(t){if(this.underlying.references)return this.underlying.references(t??this.bucket);throw new Error("The underlying storage backend keeps no object files to refer to.")}putReference(t,n,r,s){const i=s.bucket?s:{...s,bucket:this.bucket};if(this.underlying.putReference)return this.underlying.putReference(t,n,r,i);throw new Error("The underlying storage backend keeps no object files to refer to.")}getBlob(t,n){return this.underlying.getBlob(t,n??this.bucket)}getMetadata(t,n){return this.underlying.getMetadata(t,n??this.bucket)}getObject(t,n){return this.underlying.getObject(t,n??this.bucket)}putMetadata(t,n,r){const s=n.bucket?n:{...n,bucket:this.bucket};return this.underlying.putMetadata(t,s,r??this.bucket)}delete(t,n){return this.underlying.delete(t,n??this.bucket)}listByPrefix(t,n){return this.underlying.listByPrefix(t,n??this.bucket)}reset(t){return this.underlying.reset(t??this.bucket)}beginUpload(t,n,r,s,i){const o=t??this.bucket;if(this.underlying.beginUpload)return this.underlying.beginUpload(o,n,r,s,i);throw new Error("Chunked upload not supported by underlying storage backend")}putPart(t,n,r){if(this.underlying.putPart)return this.underlying.putPart(t,n,r);throw new Error("Chunked upload not supported by underlying storage backend")}readUpload(t){if(this.underlying.readUpload)return this.underlying.readUpload(t);throw new Error("Chunked upload not supported by underlying storage backend")}abortUpload(t){return this.underlying.abortUpload?this.underlying.abortUpload(t):Promise.resolve()}close(){this.underlying.close()}scoped(t){return t===this.bucket?this:this.underlying.scoped?this.underlying.scoped(t):new Ei(this.underlying,t)}}function ek(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,GS);r.addEventListener("upgradeneeded",()=>{const i=r.result;i.objectStoreNames.contains(ke)||i.createObjectStore(ke),i.objectStoreNames.contains(le)||i.createObjectStore(le),i.objectStoreNames.contains(gr)||i.createObjectStore(gr)});let s=!1;r.addEventListener("success",()=>{if(s){r.result.close();return}t(r.result)}),r.addEventListener("error",()=>n(r.error)),r.addEventListener("blocked",()=>{s=!0,n(new YS("another tab holds it open on an older pyric build"))})}catch(r){n(r)}})}function tk(e,t){const n=e.objectStore(ke).get(t),r=e.objectStore(le).get(t);return{object(){const s=n.result,i=r.result;if(!(s===void 0||i===void 0))return{blob:s,metadata:i}}}}function vt(e){return new Promise((t,n)=>{e.addEventListener("success",()=>t(e.result)),e.addEventListener("error",()=>n(e.error))})}function Zn(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")))})}class dp{backend;rules;crossServiceIam;constructor(t,n=null,r="granted"){this.backend=t,this.rules=n,this.crossServiceIam=r}}function ou(e){switch(e){case"read":return["get","list"];case"write":return["create","update","delete"];default:return[e]}}const nk=new Set(["&&","||","==","!=","<",">","<=",">=","+","-","*","/","%"]);function fp(e){return{segments:e.path.segments.map(rk),children:e.children.map(fp),allows:e.allows.map(t=>({verbs:t.operations,condition:re(t.condition)})),functions:e.functions.map(Zo)}}function rk(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 Zo(e){return{name:e.name,params:e.parameters,lets:e.lets.map(t=>{const n={name:t.name,value:re(t.value)};return Qf(t,n),n}),body:re(e.body)}}function re(e){const t=sk(e);return Qf(e,t),t}function sk(e){switch(e.type){case"literal":return typeof e.value=="number"&&e.raw.includes(".")?{kind:"literal",value:new Me(e.value)}:e.value instanceof Uint8Array?{kind:"literal",value:new vi(e.value)}:{kind:"literal",value:e.value};case"identifier":return{kind:"ident",name:e.name};case"memberAccess":return{kind:"member",target:re(e.object),name:e.property};case"methodCall":return{kind:"methodcall",target:re(e.object),method:e.method,args:e.args.map(re)};case"bracketAccess":return{kind:"index",target:re(e.object),index:re(e.index)};case"sliceAccess":return{kind:"slice",target:re(e.object),start:re(e.start),end:re(e.end)};case"binaryOp":if(!nk.has(e.op))throw new SyntaxError(`Unsupported binary operator '${e.op}' in storage rules.`);return{kind:"binary",op:e.op,left:re(e.left),right:re(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:re(e.operand)};case"ternary":return{kind:"ternary",cond:re(e.condition),then:re(e.consequent),else:re(e.alternate)};case"inExpr":return{kind:"in",element:re(e.element),collection:re(e.collection)};case"isExpr":return{kind:"is",value:re(e.value),typeName:e.typeName};case"listLiteral":return{kind:"list",elements:e.elements.map(re)};case"mapLiteral":return{kind:"map",entries:e.entries.map(t=>({key:re(t.key),value:re(t.value)}))};case"pathLiteral":return{kind:"path",segments:e.segments.map(t=>typeof t=="string"?{kind:"literal",value:t}:{kind:"interp",expr:re(t)})};case"functionCall":return{kind:"call",name:e.name,args:e.args.map(re)};default:{const t=e;throw new SyntaxError(`Unsupported expression construct: ${JSON.stringify(t)}`)}}}function ea(e){const t=jb(e);if(!t.ok)throw new SyntaxError(`Storage rules parse error at line ${t.error.line}, column ${t.error.column}: ${Eb(t.error,e)}.`);const n=t.ast;if(n.service.name!=="firebase.storage")throw new SyntaxError(`Expected 'service firebase.storage', got 'service ${n.service.name}'.`);const r=Cb(n);if(r.length>0)throw new SyntaxError(`Storage rules do not compile: ${Nb(r)}`);const s=(n.imports??[]).flatMap(d=>d.functions.map(h=>({name:h,params:[],lets:[],body:{kind:"literal",value:null},unresolvedImport:d.module,scopeKind:"global",declCaptures:new Set}))),i=(n.functions??[]).map(d=>{const h=Zo(d);return h.scopeKind="global",h.declCaptures=new Set,h}),o=new Map;for(const d of s)o.set(d.name,d);for(const d of i)o.set(d.name,d);for(const d of o.values())d.declScope=o;const a=(n.service.functions??[]).map(d=>{const h=Zo(d);return h.scopeKind="service",h.declCaptures=new Set,h}),l=new Map(o);for(const d of a)l.set(d.name,d);for(const d of a)d.declScope=l;const u={segments:[],children:[fp(n.service.match)],allows:[],functions:[...s,...i,...a],visibleFuncs:l};for(const d of u.children)hp(d,l,new Set);return{_root:u,_version:n.version}}function hp(e,t,n){const r=new Set(n);for(const i of e.segments)(i.kind==="param"||i.kind==="wildcard")&&r.add(i.name);const s=new Map(t);for(const i of e.functions)s.set(i.name,i);e.visibleFuncs=s;for(const i of e.functions)i.declScope=s,i.scopeKind="match",i.declCaptures=r;for(const i of e.children)hp(i,s,r)}function pe(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 pe(e.target,t);case"index":return pe(e.target,t)||pe(e.index,t);case"slice":return[e.target,e.start,e.end].some(n=>pe(n,t));case"unary":return pe(e.arg,t);case"ternary":return[e.cond,e.then,e.else].some(n=>pe(n,t));case"in":return pe(e.element,t)||pe(e.collection,t);case"is":return pe(e.value,t);case"list":return e.elements.some(n=>pe(n,t));case"map":return e.entries.some(({key:n,value:r})=>pe(n,t)||pe(r,t));case"binary":return pe(e.left,t)||pe(e.right,t);case"call":return e.args.some(n=>pe(n,t));case"methodcall":return pe(e.target,t)||e.args.some(n=>pe(n,t));case"path":return e.segments.some(n=>n.kind==="interp"&&pe(n.expr,t));case"ident":case"literal":return!1}}function pp(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&&pe(r,n)))return!0;for(const r of e.functions){const s=new Set([...n,...r.params]);for(const i of r.lets){if(pe(i.value,s))return!0;s.add(i.name)}if(pe(r.body,s))return!0}return e.children.some(r=>pp(r,n))}function ik(e){if(/\\[1-9]/.test(e)||/\(\?<?[=!]/.test(e))return!1;try{return new RegExp(`^(?:${Xf(e)})$`),!0}catch{return!1}}function se(e){if(e.kind==="methodcall"&&e.method==="matches"&&e.args.length===1){const t=e.args[0];if(t?.kind==="literal"&&typeof t.value=="string"&&!ik(t.value))throw new SyntaxError(`Storage rules do not compile: Invalid regular expression pattern. Pattern: ${t.value}.`)}switch(e.kind){case"member":se(e.target);return;case"index":se(e.target),se(e.index);return;case"slice":se(e.target),se(e.start),se(e.end);return;case"unary":se(e.arg);return;case"ternary":se(e.cond),se(e.then),se(e.else);return;case"in":se(e.element),se(e.collection);return;case"is":se(e.value);return;case"list":for(const t of e.elements)se(t);return;case"map":for(const{key:t,value:n}of e.entries)se(t),se(n);return;case"binary":se(e.left),se(e.right);return;case"call":for(const t of e.args)se(t);return;case"methodcall":se(e.target);for(const t of e.args)se(t);return;case"path":for(const t of e.segments)t.kind==="interp"&&se(t.expr);return;case"ident":case"literal":return}}function mp(e){for(const{condition:t}of e.allows)t&&se(t);for(const t of e.functions){for(const n of t.lets)se(n.value);se(t.body)}for(const t of e.children)mp(t)}function ok(e){let t=e,n=[],r=[],s=[],i=ea(t);if(i._version!=="2+modules"){if(i._root.functions.some(a=>a.unresolvedImport!==void 0))throw new SyntaxError("Import statements require rules_version = '2+modules'.")}else{const a=zf(t);if(!a.success)throw new SyntaxError(`Storage rules module resolution failed (${a.error.code}): ${a.error.message}`);t=a.data.resolved,n=a.data.modules,r=a.data.bundledModules,s=a.data.evidenceIds,i=ea(t)}mp(i._root);const o=ak(t,n,r,s,i);return{rules:i,resolution:o}}function ak(e,t,n,r,s){const i=new Set;for(const o of r)o.startsWith("storage-rules#")&&i.add(o);return pp(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 yp="pyric-default",Ci=Symbol.for("pyric/storage/target");function Vt(e){return e.currentAuth?.()??e.context.auth}const ck=Symbol.for("pyric.storage.service-caches"),lk=globalThis,pn=lk[ck]??={openServices:new WeakMap,hostBackends:new WeakMap,scopedServices:new WeakMap,sandboxHandles:new WeakMap,bareSandboxHandles:new WeakMap,adminContextHandles:new WeakMap,bareAdminHandles:new WeakMap},au=pn.openServices,uk=pn.hostBackends,cu=pn.scopedServices;function dk(e,t,n){let r=cu.get(e);r||(r=new Map,cu.set(e,r));let s=r.get(t);return s||(s=n.then(i=>{const o=i.backend.scoped?i.backend.scoped(t):i.backend;return new dp(o,i.rules,i.crossServiceIam)}),r.set(t,s)),s}pn.sandboxHandles;pn.bareSandboxHandles;function lu(e,t,n,r,s){if(n===void 0||n===r)return;const i=r===null?`without ${e}`:`with a different ${t}`;throw new Error(`pyric/storage: ${s} received a ${t}, but this sandbox's storage service is already open ${i}. ${e} is honored only on the FIRST storage call per Sandbox, so this value would be silently discarded. Configure it on the first storage call for this sandbox.`)}function fk(e,t,n){const r=au.get(e);if(r!==void 0)return lu("rules","rules source",t.rules,r.rulesSource,n),lu("crossServiceIam","crossServiceIam mode",t.crossServiceIam,r.crossServiceIam,n),r.service;let i=null,o=null;const a=t.rules;if(typeof a=="string"&&a.length>0){const m=ok(a);i=m.rules,o=m.resolution}const u=t.crossServiceIam??"granted",d=uk.get(e);let h;d!==void 0?h=Promise.resolve(d):h=JS(t.dbName??KS(t.projectId),t.bucket??yp);const p=h.then(m=>new dp(m,i,u));return au.set(e,{service:p,rulesSource:t.rules??null,rulesResolution:o,crossServiceIam:u}),e.registerPersistableService("storage",{snapshot:()=>null,restore:()=>{},reset:async()=>{await(await p).backend.reset()}}),p}function ro(e){return e instanceof Rb||"sandbox"in e&&e.sandbox!==void 0}const so=pn.adminContextHandles,io=pn.bareAdminHandles;function hk(e,t={}){const n=!ro(e),r=ro(e)?e.sandbox:e,s=fk(r,t,"getAdminStorageSandbox"),i=t.bucket??yp;if(n){const p=io.get(r)?.get(i);if(p)return p}const o=ro(e)?e:r.withAuth(null),a=o.operationContext.authLens.mode==="admin"?o:Zf(o,{source:o.operationContext.source,authLens:{mode:"admin"},...o.operationContext.planId===void 0?{}:{planId:o.operationContext.planId}}),l=so.get(o)?.get(i);if(l)return l;const u=dk(r,i,s),d={kind:"sandbox",sandbox:r,context:a,bucket:i,servicePromise:u,admin:!0},h=Object.freeze({[Ci]:d});let f=so.get(o);if(f||(f=new Map,so.set(o,f)),f.set(i,h),n){let p=io.get(r);p||(p=new Map,io.set(r,p)),p.set(i,h)}return h}function zt(e,t){const n=Ib(t,Lo(e.context.operationContext));return{...t,...Lo(n),service:"storage"}}function Le(e){const t=e[Ci];if(!t)throw new TypeError("pyric/storage: not a FirebaseStorage handle — was it produced by getStorageSandbox?");return t}function Ht(e){return Le(e).servicePromise}function pk(e){return`storage/${e}`}class Nt extends Error{code;constructor(t,n){const r=pk(t);super(`${r}: ${n}`),this.name="StorageError",this.code=r,Object.setPrototypeOf(this,Nt.prototype)}}function gp(e){return new Nt("object-not-found",`no object at "${e}".`)}function uu(e,t,n){return new Nt("unauthorized",IS(`${e} "${t}" denied by rules${n}`))}function Ni(e){return new Nt("invalid-root-operation",`${e} cannot operate on the root reference.`)}function du(){return new Nt("canceled","User canceled the upload/download.")}const ps="([A-Za-z0-9.\\-_]+)",mk=/^[A-Za-z]+:\/\//,bc=/^data:[^,]*,/i,yk=e=>e,gk=[{pattern:new RegExp(`^gs://${ps}(?:/(.*))?$`,"i"),path:yk},{pattern:new RegExp(`^https?://firebasestorage\\.googleapis\\.com/v[A-Za-z0-9_]+/b/${ps}/o(?:/([^?#]*).*)?$`,"i"),path:decodeURIComponent},{pattern:new RegExp(`^https?://(?:storage\\.googleapis\\.com|storage\\.cloud\\.google\\.com)/${ps}/([^?#]*)`,"i"),path:decodeURIComponent},{pattern:new RegExp(`^https?://[^/?#]+/__pyric/storage/v0/b/${ps}/o/([^?#]+)`),path:decodeURIComponent}];function fu(e,t){return new Nt("invalid-url",`Invalid URL '${e}'. ${t}`)}function bk(e){return mk.test(e)||bc.test(e)}function wk(e){if(bc.test(e))throw fu(e.length>64?`${e.slice(0,64)}...`:e,"A data: URI carries an object's bytes, not its location. Reference the object by its path or its gs:// URL.");for(const n of gk){const r=n.pattern.exec(e);if(r!==null)return{bucket:r[1],path:n.path(r[2]??"")}}throw fu(e,"Expected a gs:// URL or a Storage download URL.")}function ta(e,t){const n=e??"";if(!bk(n))return n;const s=bc.test(n);if(!t&&!s)throw new Nt("invalid-argument","To use ref(service, url), the first argument must be a Storage instance.");return wk(n).path}function Ar(e,t){return xk(e)?(Le(e.storage),new Or(e.storage,vk(e.fullPath,ta(t,!1)))):(Le(e),new Or(e,bp(ta(t,!0))))}class Or{storage;bucket;fullPath;constructor(t,n){this.storage=t;const r=Le(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 Or(this.storage,n)}get root(){return this.fullPath===""?this:new Or(this.storage,"")}toString(){return`gs://${this.bucket}/${this.fullPath}`}}function bp(e){return e===""?"":e.split("/").filter(t=>t.length>0).join("/")}function vk(e,t){const n=bp(t);return e===""?n:n===""?e:`${e}/${n}`}function xk(e){if(e===null||typeof e!="object"||Ci in e)return!1;const t=e;return typeof t.fullPath=="string"&&t.storage!==void 0}const ti=new WeakMap;function Ut(e){ti.get(e)?.progress()}function ni(e){const t=ti.get(e);t?.delivered(void 0,{}),t?.progress()}function qn(e,t){return(n,...r)=>{const s=Hr.begin({app:n.storage??n.port??n,method:e,kind:"operation",source:{service:"storage",target:`${n.bucket}/${n.fullPath}`,key:`storage:${n.bucket}/${n.fullPath}`}});try{const i=t(n,...r);return e==="uploadBytesResumable"&&ti.set(i,s),i.then(o=>{const a=_k(e,o);s.delivered(void 0,e.startsWith("get")||e==="listAll"?a:{}),e==="uploadBytesResumable"&&s.progress(),s.complete(e.startsWith("get")||e==="listAll"?void 0:a)},()=>{s.fail(),ti.delete(i)}),i}catch(i){throw s.fail(),i}}}function _k(e,t){if(e==="getBytes"&&t instanceof ArrayBuffer)return{downloadedBytes:t.byteLength};if(e==="getBlob"&&t&&typeof t=="object"&&"size"in t&&typeof t.size=="number")return{downloadedBytes:t.size};if(e.startsWith("upload")&&t&&typeof t=="object"&&"metadata"in t){const n=t.metadata;if(typeof n.size=="number")return{uploadedBytes:n.size}}return{}}class z{message;constructor(t){this.message=t}}function K(e){return e instanceof z}function ri(e){if(typeof e=="number")return e;if(e instanceof Me)return e.value}class B extends Error{}class ts extends B{}class ns extends B{}class hu extends ns{position;constructor(t,n){super(t),this.position=n}}function Sk(e){return e instanceof B&&!(e instanceof ts)&&!(e instanceof ns)}function Ue(e){return new B(Ab(e))}function mn(e){if(e.args.length!==0)throw new B(`${e.method}() expects no arguments`)}function Ze(e,t){return dt(e.args,t)}function rs(e,t){const n=Ze(e,t);return K(n)||t.expressionBudget?.node(e),n}function Oe(e,t){if(mn(t),e instanceof ct){const n=e.callMethod(t.method,[]);if(n!==Uo)return n}throw Ue(t.method)}const kk=/^(?:\{([A-Za-z_][A-Za-z0-9_]*)\}|\$\(([A-Za-z_][A-Za-z0-9_]*)\))$/;class He extends ct{path;typeName="path";bindings;constructor(t,n={}){super(),this.path=t,this.bindings=n}get segments(){return this.path.split("/").filter(Boolean)}bind(t){const n=[],r={...this.bindings};for(const s of this.segments){const i=kk.exec(s);if(!i){n.push(s);continue}const o=i[1]??i[2];if(Object.hasOwn(t,o)){const a=t[o];if(a==null||typeof a!="string"&&typeof a!="number")throw new TypeError(`Path.bind(): binding '${o}' must not be null`);const l=String(a);n.push(l),r[o]=l}else n.push(s)}return new He("/"+n.join("/"),r)}valueOf(){return NaN}toJSON(){return{__type:"path",path:this.toString()}}equals(t){return(t instanceof He||t instanceof ct&&t.typeName==="path")&&String(t)===this.toString()}toString(){return this.path.startsWith("/")?this.path:`/${this.path}`}}function jk(e,t,n){if(!(e instanceof He))throw Ue("bind");const r=Ze(t,n);if(K(r))return r;if(r.length!==1)throw new B(`Incorrect number of arguments. Received: ${r.length}. Expected: path.bind(map).`);const[s]=r;if(!Ft(s))return new z("path.bind() requires a map argument");try{return e.bind(s)}catch(i){return new z(i.message)}}const Ek={bind:jk};function wp(e){const t={};for(const[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}function Ck(e){return wp({size:e.size,contentType:e.contentType,metadata:e.metadata,name:e.name,bucket:e.bucket,generation:e.generation,metageneration:e.metageneration,timeCreated:pu(e.timeCreated),updated:pu(e.updated)})}function pu(e){if(e===void 0)return;const t=Date.parse(e);if(!Number.isNaN(t))return kr.fromMillis(t)}function Nk(e,t){const n=e.request.auth;let r;return n==null?r=new z("Property auth is undefined on object."):r=wi(n),{auth:r,resource:e.request.resource!==void 0?wp(e.request.resource):new z("Property resource is undefined on object."),method:e.request.method,path:new He(e.request.path),time:kr.fromMillis(t)}}const Rk=["addedKeys","affectedKeys","changedKeys","removedKeys","unchangedKeys"];function Ik(e,t,n){return e instanceof Kr?wc(e,t,n):(mn(t),typeof e=="string"||Array.isArray(e)?e.length:Ft(e)?Object.keys(e).length:Oe(e,t))}function mu(e,t,n){if(!Ft(e))throw Ue(t.method);const r=Ze(t,n);if(K(r))return r;const s=$b(t.method,e,r);if(s instanceof Db)throw new B(s.message);return s}function wc(e,t,n){const r=Ze(t,n);if(K(r))return r;const s=Tb(e,t.method,r);if(s instanceof Mb)throw new B(s.message);return s}const Ak={concat:(e,t)=>Bb(e,t),join:(e,t)=>Ub(e,t),removeAll:(e,t)=>Lb(e,t)};function oo(e,t,n){if(!Array.isArray(e))throw Ue(t.method);const r=Ze(t,n);if(K(r))return r;const s=Ak[t.method](e,r);if(s instanceof eh)throw new B(s.message);return s}function Ok(e,t,n){if(!Ft(e))throw Ue(t.method);if(t.args.length!==2)throw new B("get() expects a key and default value");const r=Ze(t,n);if(K(r))return r;const[s,i]=r;if(typeof s=="string")return Object.hasOwn(e,s)&&e[s]!==void 0?e[s]:i;if(Array.isArray(s)){for(const a of s)if(typeof a!="string")throw new B("get() key list elements must be strings");let o=e;for(const a of s){if(!Ft(o)||!Object.hasOwn(o,a)||o[a]===void 0)return i;o=o[a]}return o}throw new B("get() key must be a string or list of strings")}function ao(e,t,n){if(e instanceof Kr)return wc(e,t,n);if(!Array.isArray(e))throw Ue(t.method);const r=Ze(t,n);if(K(r))return r;const s=Pb(t.method,e,r);if(s instanceof eh)throw new B(s.message);return s}function $k(e,t){if(!Array.isArray(e))throw Ue(t.method);if(t.args.length!==0)throw new B(`Incorrect number of arguments. Received: ${t.args.length}. Expected: list.toSet().`);return new Kr(e)}function Dk(e,t,n){if(!(e instanceof Kr))throw Ue(t.method);return wc(e,t,n)}function Pk(e,t,n){if(!Ft(e))throw Ue(t.method);if(t.args.length!==1)throw new B("diff() expects one map argument");const r=Ze(t,n);if(K(r))return r;const[s]=r;if(!Ft(s))throw new B(`diff() argument must be a map, got ${Pe(s)}`);return new th(s,e)}function Tk(e,t){if(mn(t),!(e instanceof th))throw Ue(t.method);return e[t.method]()}function yu(e,t){return Object.fromEntries(e.map(n=>[n,t]))}const Mk={concat:oo,diff:Pk,get:Ok,hasAll:ao,hasAny:ao,hasOnly:ao,join:oo,keys:mu,removeAll:oo,size:Ik,toSet:$k,values:mu,...yu([...Ob],Dk),...yu(Rk,Tk)};function Lk(e){if(typeof e=="number")return e;if(e instanceof Me)return e.value}function Uk(e,t,n,r){const i=f=>f*Math.PI/180,o=i(e),a=i(n),l=i(n-e),u=i(r-t),d=Math.sin(l/2)**2+Math.cos(o)*Math.cos(a)*Math.sin(u/2)**2;return 6371e3*(2*Math.atan2(Math.sqrt(d),Math.sqrt(1-d)))}function $r(e){return e instanceof si?{latitude:e.latitude,longitude:e.longitude}:e instanceof nh?{latitude:e.lat,longitude:e.lng}:null}function Bk(e,t){const n=rs(e,t);if(K(n))return n;if(e.method!=="value")return new z(`unsupported latlng.${e.method}()`);const[r,s]=n.map(Lk);return n.length!==2||r===void 0||s===void 0||!Number.isFinite(r)||!Number.isFinite(s)?new z("latlng.value() expects (latitude: number, longitude: number)"):r<-90||r>90?new z(`Latitude must be in the range [-90, 90], got ${r}.`):s<-180||s>180?new z(`Longitude must be in the range [-180, 180], got ${s}.`):new si(r,s)}class si extends ct{latitude;longitude;typeName="latlng";constructor(t,n){super(),this.latitude=t,this.longitude=n}valueOf(){return NaN}toJSON(){return{__type:"latlng",latitude:this.latitude,longitude:this.longitude}}equals(t){const n=$r(t);return n!==null?n.latitude===this.latitude&&n.longitude===this.longitude:t instanceof ct&&t.typeName==="latlng"&&t.latitude===this.latitude&&t.longitude===this.longitude}toString(){return`[${this.latitude}, ${this.longitude}]`}}function Fk(e,t){const n=$r(e);if(n===null)throw Ue("latitude");return mn(t),new Me(n.latitude)}function qk(e,t){const n=$r(e);if(n===null)throw Ue("longitude");return mn(t),new Me(n.longitude)}function Vk(e,t,n){const r=$r(e);if(r===null)throw Ue("distance");const s=Ze(t,n);if(K(s))return s;if(s.length!==1)throw new B(`Incorrect number of arguments. Received: ${s.length}. Expected: latlng.distance(latlng).`);const i=$r(s[0]);return i===null?new z("latlng.distance() requires a latlng argument"):new Me(Uk(r.latitude,r.longitude,i.latitude,i.longitude))}const Wk={distance:Vk,latitude:Fk,longitude:qk};function na(e){if(e==null)return e;if(typeof e=="number")return Number.isInteger(e)?e:new Me(e);if(e instanceof Date)return kr.fromMillis(e.getTime());if(e instanceof Uint8Array)return new vi(e);if(e instanceof nh)return new si(e.lat,e.lng);if(e instanceof Fb)return new He(e.toString());if(e instanceof ct)return e;if(typeof e=="object"){if(Array.isArray(e))return e.map(na);const t=e,n=Object.keys(t),r=t.latitude??t._latitude,s=t.longitude??t._longitude;if(t.__type==="latlng"||n.length===2&&typeof r=="number"&&typeof s=="number")return new si(r,s);if(t.__type==="path"||n.length===1&&typeof t.path=="string"&&t.path.startsWith("/databases/"))return new He(t.path);const i={};for(const[o,a]of Object.entries(t))i[o]=na(a);return i}return e}function zk(e,t){if(t.expressionBudget?.node(e),e.method!=="get"&&e.method!=="exists")throw new ts(`unsupported method firestore.${e.method}()`);if(!t.firestoreLookup)throw new B(`firestore.${e.method}() is unsupported here — no Firestore lookup capability is configured`);if(e.args.length!==1)throw new B(`firestore.${e.method}() expects a single path argument`);const n=e.args[0];let r;if(n.kind==="path"){t.expressionBudget?.node(n);for(const i of n.segments)i.kind==="literal"&&t.expressionBudget?.pathSegment(n);r=gu(n,t)}else{const i=rt(n,t);if(K(i))return i;if(i instanceof He||i instanceof ct&&i.typeName==="path"){const a=(i instanceof He?i.path:String(i)).split("/").filter(Boolean).map(l=>({kind:"literal",value:l}));r=gu({segments:a},t)}else return new z(`Function not found error: Name: [${e.method}].`)}if(!t.firestoreAccesses.has(r)){if(t.firestoreAccesses.size>=2)throw new ns("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 z(`firestore.get() targeted a nonexistent document: ${r}`):{data:na(s)}}function gu(e,t){const n=dt(e.segments.flatMap(o=>o.kind==="literal"?[]:[o.expr]),t);if(K(n))throw new B(n.message);let r=0;const s=e.segments.map(o=>{if(o.kind==="literal")return o.value;const a=n[r++];if(typeof a=="string")return a;if(typeof a=="number")return String(a);throw new B(`Firestore path interpolation resolved to ${Pe(a)} (expected a string)`)});if(s.length<4||s[0]!=="databases"||s[2]!=="documents")throw new B(`malformed Firestore path — expected /databases/<db>/documents/... , got /${s.join("/")}`);if(s[1]!=="(default)")throw new B(`Storage rules may access only the default Firestore database, got ${s[1]}`);const i=s.slice(3);if(i.length===0||i.length%2!==0)throw new B(`Firestore path does not point at a document (needs an even segment count): ${i.join("/")}`);return i.join("/")}const Hk=new Set(["crc32","crc32c","md5","sha256"]);function Kk(e,t){if(!Hk.has(e.method))throw new ts(`unsupported method hashing.${e.method}()`);const n=rs(e,t);if(K(n))return n;if(n.length!==1)throw new B(`hashing.${e.method}() expects a single string or bytes argument`);const[r]=n;if(typeof r!="string"&&!(r instanceof vi))throw new B(`Unsupported operation error. Received: hashing.${e.method}(${Pe(r)}). Expected: hashing.${e.method}(bytes), hashing.${e.method}(string).`);return qb(e.method,[r])}const Gk={toBase64:Oe,toHexString:Oe};function Jk(e,t){const n=rs(e,t);if(K(n))return n;const r=Vb(e.method,n);return r instanceof Wb?new z(r.message):r}function ss(e,t){if(typeof e!="string")throw Ue(t.method);return e}function vp(e,t){if(e.args.length!==1)throw new B(`${e.method}() expects a single pattern argument`);const n=Ze(e,t);if(K(n))return n;const[r]=n;if(typeof r!="string")throw new B(`${e.method}() pattern must be a string`);return r}function Yk(e,t,n){const r=ss(e,t),s=vp(t,n);if(typeof s!="string")return s;try{return zb(s,r)}catch(i){throw new B(i.message)}}function Qk(e,t,n){const r=ss(e,t),s=vp(t,n);return typeof s!="string"?s:r.split(xp("split",s,s))}function Xk(e,t,n){const r=ss(e,t),s=Ze(t,n);if(K(s))return s;const[i,o]=s;if(s.length!==2||typeof i!="string"||typeof o!="string")throw new B("replace() expects (pattern: string, replacement: string)");const a=xp("replace",i,i,"g"),l=ej(a);return r.replace(a,(...u)=>{const d=u.slice(0,l+1);return tj(o,d,Zk(u[u.length-1]))})}function Zk(e){return typeof e=="object"&&e!==null?e:{}}function ej(e){const t=new RegExp(`${e.source}|`).exec("");return t===null?0:t.length-1}function tj(e,t,n){const r=t.length-1;let s="",i=0;for(;i<e.length;){const o=e[i];if(o==="\\"){if(i+1>=e.length)throw new B("replace() replacement ends with an escape character");s+=e[i+1],i+=2;continue}if(o!=="$"){s+=o,i+=1;continue}const a=e[i+1];if(a==="{"){const d=e.indexOf("}",i+2);if(d===-1)throw new B(`replace() replacement has an unclosed group name: ${e.slice(i)}`);const h=e.slice(i+2,d);if(!Object.hasOwn(n,h))throw new B(`replace() replacement names no group: ${e.slice(i,d+1)}`);s+=n[h]??"",i=d+1;continue}if(a===void 0||a<"0"||a>"9")throw new B(`replace() replacement has an illegal group reference: ${e.slice(i)}`);let l=Number(a),u=i+2;for(;u<e.length&&e[u]>="0"&&e[u]<="9";){const d=l*10+Number(e[u]);if(d>r)break;l=d,u+=1}if(l>r)throw new B(`replace() replacement names group ${l}, but the pattern has ${r}`);s+=t[l]??"",i=u}return s}function co(e,t){const n=ss(e,t);return mn(t),t.method==="lower"?n.toLowerCase():t.method==="upper"?n.toUpperCase():n.trim()}function nj(e,t){const n=ss(e,t);return mn(t),vi.fromUtf8(n)}function rj(e){let t=!1,n=!1,r=!1,s=!1,i=!1,o=0;for(;o<e.length;){const l=e[o];if(l==="\\"){const u=e[o+1];if(!t&&u!==void 0&&u>="1"&&u<="9")return{unsupported:"backreference",inlineFlags:""};o+=2,n=!1;continue}if(t){l==="]"&&!n&&(t=!1),n=!1,o++;continue}if(l==="["){t=!0,o++,e[o]==="^"&&o++,n=!0;continue}if(l==="("&&e[o+1]==="?"){const u=e.slice(o+2);if(u.startsWith("=")||u.startsWith("!")||u.startsWith("<=")||u.startsWith("<!"))return{unsupported:"lookaround",inlineFlags:""};const d=/^([imsU-]+)[):]/.exec(u);if(d){let h=!1;for(const f of d[1])f==="-"?h=!0:f==="i"?r=!h:f==="m"?s=!h:f==="s"&&(i=!h)}}o++}return{unsupported:null,inlineFlags:`${r?"i":""}${s?"m":""}${i?"s":""}`}}function xp(e,t,n,r=""){const{unsupported:s,inlineFlags:i}=rj(t);if(s!==null)throw new B(`${e}() pattern uses an RE2-unsupported construct (${s}) that production would reject`);const o=Array.from(new Set((r+i).split(""))).join("");try{return new RegExp(Xf(n),o)}catch(a){throw new B(`${e}() invalid regex pattern: ${a.message}`)}}const sj={lower:co,matches:Yk,replace:Xk,split:Qk,toUtf8:nj,trim:co,upper:co},bu=["w","d","h","m","s","ms","ns"],ij=-621355968e5,oj=0xe677d21fdbff,wu=315576e6;function aj(e,t){const n=rs(e,t);if(K(n))return n;if(e.method==="value"){if(n.length!==1||typeof n[0]!="number"||!Number.isInteger(n[0]))throw new B("timestamp.value() expects (epochMillis: number)");const r=n[0];if(r<ij||r>oj)throw new B("timestamp.value() out of range [0001-01-01T00:00:00Z, 9999-12-31T23:59:59.999Z]");return kr.fromMillis(r)}if(e.method==="date"){if(n.length!==3||!n.every(o=>typeof o=="number"&&Number.isInteger(o)))throw new B("timestamp.date() expects (year, month, day) numbers");const[r,s,i]=n;try{return kr.fromYMD(r,s,i)}catch(o){throw new B(o.message)}}throw new B(`unsupported timestamp.${e.method}()`)}function cj(e,t){const n=rs(e,t);if(K(n))return n;if(e.method==="value"){if(n.length!==2||typeof n[0]!="number"||!Number.isInteger(n[0])||typeof n[1]!="string")throw new B("duration.value() expects (magnitude: number, unit: string)");const[r,s]=n;if(!bu.includes(s))throw new B(`duration.value() got unknown unit "${s}", expected one of ${bu.join(", ")}`);const i=ds.fromValue(r,s);if(!Number.isFinite(i.seconds)||Math.abs(i.seconds)>wu)throw new B("duration.value() exceeds maximum range of +/-10000 years");return i}if(e.method==="time"){if(n.length!==4||!n.every(l=>typeof l=="number"&&Number.isInteger(l)))throw new B("duration.time() expects (hours, minutes, seconds, nanos) numbers");const[r,s,i,o]=n,a=ds.fromTime(r,s,i,o);if(!Number.isFinite(a.seconds)||Math.abs(a.seconds)>wu)throw new B("duration.time() exceeds maximum range of +/-10000 years");return a}if(e.method==="abs"){if(n.length!==1||!(n[0]instanceof ds))throw new B("duration.abs() expects a single duration");return ds.abs(n[0])}throw new B(`unsupported duration.${e.method}()`)}const lj={date:Oe,day:Oe,dayOfWeek:Oe,dayOfYear:Oe,hours:Oe,minutes:Oe,month:Oe,nanos:Oe,seconds:Oe,time:Oe,toMillis:Oe,year:Oe},uj=new Map([["duration",cj],["firestore",zk],["hashing",Kk],["latlng",Bk],["math",Jk],["timestamp",aj]]),dj=pj([Gk,Mk,Wk,Ek,sj,lj]);function fj(e,t){const n=hj(e,t);if(n!==void 0)return n(e,t);const r=dj.get(e.method);if(r===void 0)throw new ts(`unsupported method .${e.method}()`);const s=Dr(e.target,t);return K(s)?(Ze(e,t),s):r(s,e,t)}function hj(e,t){if(e.target.kind!=="ident")return;const n=e.target.name;if(!(Object.hasOwn(t.locals,n)||Object.hasOwn(t.params,n)))return uj.get(n)}function pj(e){const t=new Map;for(const n of e)for(const[r,s]of Object.entries(n)){if(t.has(r))throw new Error(`storage rules method .${r}() has two evaluators`);t.set(r,s)}return t}const mj=new Set(["timestamp","duration","bytes","latlng","path"]);function yj(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 Me||typeof e=="number"&&!Number.isInteger(e);case"number":return e instanceof Me||typeof e=="number";case"list":return Array.isArray(e);case"set":return e instanceof Kr;case"map":return Ft(e);case"null":return e===null}return mj.has(t)?e instanceof ct&&e.typeName===t:new z(`'is ${t}' is not supported by the storage evaluator.`)}function vu(e){return e instanceof ct&&!(e instanceof Me)}function gj(e,t,n){if(t instanceof ct){const r=t.binaryOp(e,n);if(r!==Uo)return r}if(e==="+"&&n instanceof ct){const r=n.binaryOp(e,t);if(r!==Uo)return r}return vc(e,t,n)}function vc(e,t,n){return new z(`Unsupported operation error. Received: ${Pe(t)} ${e} ${Pe(n)}.`)}function xu(e){return e instanceof Me}function bj(e,t,n){if(e==="+"&&typeof t=="string"&&typeof n=="string")return t+n;const r=ri(t),s=ri(n);if(r===void 0||s===void 0)return vc(e,t,n);const i=xu(t)||xu(n);let o;switch(e){case"+":o=r+s;break;case"-":o=r-s;break;case"*":o=r*s;break;case"/":if(!i&&s===0)return new z(sl);o=i?r/s:Math.trunc(r/s);break;case"%":if(!i&&s===0)return new z(sl);o=r%s;break}return i?new Me(o):o}function wj(e,t,n){const r=ri(t),s=ri(n);return r!==void 0&&s!==void 0?_u(e,r,s):typeof t=="string"&&typeof n=="string"?_u(e,t,n):vc(e,t,n)}function _u(e,t,n){switch(e){case"<":return t<n;case">":return t>n;case"<=":return t<=n;case">=":return t>=n}}function vj(e){return e.split("/").filter(t=>t.length>0)}function gn(e){return"/"+e.map(t=>t.kind==="literal"?t.value:t.kind==="param"?`{${t.name}}`:`{${t.name}=**}`).join("/")}function Su(e,t,n){let r=0;const s={...n};for(let i=0;i<e.length;i++){const o=e[i];if(o.kind==="wildcard"){const a=e.length-1-i,l=t.length-r-a;if(l<0)return null;const u=t.slice(r,r+l);s[o.name]=new He("/"+u.join("/")),r+=l;continue}if(r>=t.length)return null;if(o.kind==="literal"){if(t[r]!==o.value)return null;r++}else s[o.name]=t[r],r++}return{left:t.slice(r),params:s}}function _p(e,t,n=new Date,r){const s=n.getTime(),i=vj(t.request.path),o=[],a=new Set,l=new Hb((g,b)=>new hu(g,b));let u,d=!1,h;const f=new Set(ou(t.request.method));function p(g,b,w){if(d)return!1;const x=Su(g.segments,b,w);if(!x)return!1;const v=x.params,_=x.left;if(_.length===0)for(const k of g.allows){const N=new Set(k.verbs.flatMap(ou));if(![...f].some(R=>N.has(R)))continue;let D;try{let R=!0;if(k.condition&&(R=rt(k.condition,{input:t,now:s,params:v,matchParams:v,scopeKind:"match",locals:{},funcs:g.visibleFuncs??new Map,firestoreLookup:r,firestoreAccesses:a,expressionBudget:l})),typeof R=="boolean")D=R;else{let j;K(R)?j=R:j=new z(`Allow condition expected bool, got ${Pe(R)}.`),h??=j.message,o.push(`match ${gn(g.segments)} ${t.request.method}: ${j.message}`);continue}}catch(R){if(R instanceof hu)return d=!0,h===void 0?(u={message:R.message,position:R.position},o.push(`match ${gn(g.segments)} ${t.request.method}: ${Gb(R.message,R.position)}`)):o.push(`match ${gn(g.segments)} ${t.request.method}: ${R.message} Reached after an earlier allow rule raised an error; production reports that earlier error: ${h}`),!1;if(R instanceof ns)return d=!0,o.push(`match ${gn(g.segments)} ${t.request.method}: ${R.message}`),!1;if(R instanceof B){h??=R.message,o.push(`match ${gn(g.segments)} ${t.request.method}: ${R.message}`);continue}throw R}if(D)return!0;o.push(`match ${gn(g.segments)} ${t.request.method}: condition false`)}const S=g.segments[g.segments.length-1];if(g.children.length>0&&S!==void 0&&S.kind==="wildcard"){const k=g.segments.slice(0,-1),N=Su(k,b,w);if(N){const O=N.left;for(let D=O.length;D>=0;D--){const R=O.slice(0,D),j=O.slice(D),E={...N.params,[S.name]:new He("/"+R.join("/"))};for(const $ of g.children)if(p($,j,E))return!0}return!1}}for(const k of g.children)if(p(k,_,v))return!0;return!1}const m=p(e._root,i,{});return!m&&o.length===0&&o.push(`no rule matches ${t.request.method} /${i.join("/")}`),{allowed:m,reasons:o,evaluatedExpressions:l.evaluated,...u!==void 0?{resourceLimit:{kind:"expressions",limit:Kb,message:u.message,...u.position===void 0?{}:{line:u.position.line,column:u.position.column}}}:{}}}function xj(e,t){const n=ew(e,t);return n instanceof rh?new z(n.message):n}function rt(e,t){const n=t.expressionBudget;if(!n)return lo(e,t);if(e.kind==="call")return n.call(e),lo(e,t);let r;try{r=lo(e,t)}catch(s){throw s instanceof ns||n.node(e),s}return n.node(e),r}function lo(e,t){switch(e.kind){case"literal":return e.value;case"ident":{if(Object.hasOwn(t.locals,e.name))return t.locals[e.name];if(t.scopeKind!=="global"){if(e.name==="request")return Nk(t.input,t.now);if(e.name==="resource")return t.input.resource===null?new z("Null value error."):Ck(t.input.resource)}return Object.hasOwn(t.params,e.name)?t.params[e.name]:new z(`Identifier ${e.name} is undefined.`)}case"member":{const n=rt(e.target,t);return K(n)?n:n==null?new z("Null value error."):xj(n,e.name)}case"index":{const n=dt([e.index,e.target],t);if(K(n))return n;const[r,s]=n;if(s==null)return new z("Null value error.");const i=Zb(s,r);return i instanceof rh?new z(i.message):i}case"call":return _j(e,t);case"methodcall":return fj(e,t);case"path":{t.expressionBudget?.node(e);for(const i of e.segments)i.kind==="literal"&&t.expressionBudget?.pathSegment(e);const n=dt(e.segments.flatMap(i=>i.kind==="literal"?[]:[i.expr]),t);if(K(n))return n;let r=0;const s=[];for(const i of e.segments){if(i.kind==="literal"){s.push(i.value);continue}const o=n[r++];if(typeof o!="string"&&typeof o!="number")return new z(`Path interpolation resolved to ${Pe(o)} (expected a string)`);s.push(String(o))}return new He(`/${s.join("/")}`)}case"unary":{const n=rt(e.arg,t);if(e.op==="!"){if(K(n))throw new B(n.message);if(typeof n!="boolean")throw new B(`Unary '!' expects a boolean, got ${Pe(n)}.`);return!n}return K(n)?n:e.op==="-"?n instanceof Me?new Me(-n.value):typeof n!="number"?new z(`Unary '-' applied to ${Pe(n)}.`):-n:void 0}case"ternary":{t.expressionBudget?.ternary(e);const n=rt(e.cond,t);return K(n)?n:typeof n!="boolean"?new z(`Ternary condition expected bool, got ${Pe(n)}.`):n?rt(e.then,t):(t.expressionBudget?.ternaryElse(e),rt(e.else,t))}case"in":{const n=dt([e.collection,e.element],t);if(K(n))return n;const[r,s]=n,i=Qb(s,r);return i instanceof Xb?new z(i.message):i}case"is":{const n=rt(e.value,t);return K(n)?n:yj(n,e.typeName)}case"list":return dt(e.elements,t);case"map":{const n=dt(e.entries.flatMap(s=>[s.key,s.value]),t);if(K(n))return n;const r=[];for(let s=0;s<n.length;s+=2){const i=n[s];if(typeof i!="string")return new z(`Map literal key is ${Pe(i)} (expected a string).`);r.push([i,n[s+1]])}return Yb(r)}case"slice":{const n=dt([e.target,e.start,e.end],t);if(K(n))return n;const[r,s,i]=n;if(typeof s!="number"||typeof i!="number"||!Number.isInteger(s)||!Number.isInteger(i))return new z("Slice bounds must be integers.");if(Array.isArray(r)||typeof r=="string"){const o=Jb(s,i,r.length);return o?new z(o):r.slice(s,i)}return new z(`Slice applied to ${Pe(r)} (expected a list or string).`)}case"binary":{if(e.op==="&&")return ku(e,!1,t);if(e.op==="||")return ku(e,!0,t);const n=dt([e.left,e.right],t);if(K(n))return n;const[r,s]=n;if(e.op!=="=="&&e.op!=="!="&&(vu(r)||vu(s)))return gj(e.op,r,s);switch(e.op){case"==":return il(r,s);case"!=":return!il(r,s);case"<":case">":case"<=":case">=":return wj(e.op,r,s);case"+":case"-":case"*":case"/":case"%":return bj(e.op,r,s)}}}}function ku(e,t,n){const{left:r,right:s}=e,i=ju(r,n);if(i===t)return t;n.expressionBudget?.logicalRight(e);const o=ju(s,n);return o===t?t:K(i)?i:o}function ju(e,t){const n=Dr(e,t);return K(n)?n:typeof n!="boolean"?new z(`Expected a boolean '&&'/'||' operand, got ${Pe(n)}.`):n}function Dr(e,t){try{return rt(e,t)}catch(n){if(Sk(n))return new z(n.message);throw n}}function dt(e,t){const n=[];let r;for(const s of e){const i=Dr(s,t);K(i)&&(r??=i),n.push(i)}return r??n}function _j(e,t){const n=t.funcs.get(e.name);if(!n)return Sj(e,t);if(n.unresolvedImport!==void 0)throw new ts(`function ${e.name}() is imported from '${n.unresolvedImport}', but import module resolution is not implemented`);if(n.params.length!==e.args.length)return new z(`Incorrect number of arguments. Received: ${e.args.length}. Expected: ${e.name}(${n.params.join(", ")}).`);const r=e.args.map(l=>Dr(l,t)),s={};n.params.forEach((l,u)=>{s[l]=r[u]});const i=t.matchParams??t.params,o={};if(n.declCaptures)for(const l of n.declCaptures)Object.hasOwn(i,l)&&(o[l]=i[l]);const a={input:t.input,now:t.now,params:o,matchParams:i,scopeKind:n.scopeKind??"match",locals:s,funcs:n.declScope??new Map,firestoreLookup:t.firestoreLookup,firestoreAccesses:t.firestoreAccesses,expressionBudget:t.expressionBudget};for(const l of n.lets)s[l.name]=Dr(l.value,a),a.expressionBudget?.letBinding(l);return rt(n.body,a)}function Sj(e,t){if(e.name==="path"&&e.args.length===1){const i=rt(e.args[0],t);return K(i)?i:typeof i=="string"?i.includes("//")?new z("Invalid argument error in path(): empty path segment."):new He(i):new z(`path() expects a string, got ${Pe(i)}.`)}const n=tw(e.name);if(!n)return new z(`Function not found error: Name: [${e.name}].`);const r=dt(e.args,t);if(K(r))return r;const s=nw(n,r);return s instanceof rw?new z(s.message):s}function is(e,t,n,r){const s=n?.kind==="sandbox"?zt(n,r):r;if(n?.kind==="sandbox"&&n.admin===!0){ms(n,t,"not-applicable",void 0,"admin",!1,s);return}if(!e.rules)throw ms(n,t,"deny",["No Storage rules configured; default deny."],"user",!1,s),uu(t.request.method,t.request.path," — No Storage rules configured; default deny.");const i=n?kj(t,n.bucket):t,o=n?Te(n.sandbox).date():void 0,a=_p(e.rules,i,o,jj(n,e.crossServiceIam));if(!a.allowed){ms(n,t,"deny",a.reasons,"user",!0,s);const l=a.reasons.length>0?` — ${a.reasons.join("; ")}`:"";throw uu(t.request.method,t.request.path,l)}ms(n,t,"allow",a.reasons,"user",!0,s)}function kj(e,t){const n=e.request.path.replace(/^\/+/,"");return{...e,request:{...e.request,path:n===""?`b/${t}/o`:`b/${t}/o/${n}`}}}function ms(e,t,n,r,s,i,o){if(e)try{pt(e.sandbox,Hf({at:Te(e.sandbox).now(),service:"storage",method:t.request.method,path:t.request.path,auth:t.request.auth,result:n,origin:s,reasons:r,detail:{bucket:e.bucket},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}),{...o,service:"storage"})}catch{}}function jj(e,t){if(e)return Ej(e.sandbox,t)}function Ej(e,t){if(t==="denied")return Cj();const n=e.admin;return{get:r=>n.getDocument(r),exists:r=>n.getDocument(r)!==null}}function Cj(){const e=t=>{throw new B(`firestore.${t}() failed: cross-service Firestore access is not authorized: the Storage service agent lacks roles/firebaserules.firestoreServiceAgent (crossServiceIam: 'denied')`)};return{get:()=>e("get"),exists:()=>e("exists")}}function Pr(e){return e.admin===!0?"admin":"client"}const Nj="identity";function Sp(e,t){return e??`inline; filename*=utf-8''${Ij(t.split("/").pop()??"")}`}function kp(e){return e??Nj}const Rj=/[A-Za-z0-9!#$&+\-.^_`|~]/;function Ij(e){let t="";for(const n of e){if(Rj.test(n)){t+=n;continue}for(const r of new TextEncoder().encode(n))t+=`%${r.toString(16).toUpperCase().padStart(2,"0")}`}return t}function jp(e){const t={};for(const[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}function Ri(e){return e?jp({size:e.size,contentType:e.contentType,metadata:e.customMetadata,name:Ep(e.fullPath,e.bucket),bucket:e.bucket,timeCreated:e.timeCreated,updated:e.updated,generation:Eu(e.generation),metageneration:Eu(e.metageneration)}):null}function Ep(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 Eu(e){if(e===void 0)return;const t=Number(e);return Number.isFinite(t)?t:void 0}function Aj(e,t){const n=Ep(e.fullPath,e.bucket),r={name:n,bucket:e.bucket,size:e.size,contentType:e.contentType,contentDisposition:Sp(e.contentDisposition,n??""),contentEncoding:kp(e.contentEncoding),contentLanguage:e.contentLanguage??null,cacheControl:e.cacheControl??null,metadata:e.customMetadata??null};return r.generation=null,r.metageneration=null,r.etag=null,jp(r)}function xc(e,t){return t==="admin"?{...e}:{...e,contentEncoding:kp(e.contentEncoding)}}async function Oj(e){$j(e,"getMetadata");const t=Le(e.storage),n=zt(t),r=await Ht(e.storage),s=await r.backend.getMetadata(e.fullPath);if(is(r,{request:{auth:Vt(t),method:"get",path:e.fullPath},resource:Ri(s)},t,n),!s)throw gp(e.fullPath);return xc(s,Pr(t))}function $j(e,t){if(e.fullPath==="")throw Ni(t)}const Dj="application/octet-stream";async function Pj(e,t,n,r){return Tj(e,t,n,{provenance:r})}async function Tj(e,t,n,r={}){const{result:s}=await Cp(e,t,n,r);return s}async function Cp(e,t,n,{provenance:r,downloadTokens:s}={}){Lj(e,"uploadBytes");const i=Le(e.storage),o=s!==void 0;if(o&&Pr(i)!=="admin")throw new Nt("unauthorized","Only the admin plane sets download tokens on upload.");const a=zt(i,r),l=Mj(t,n?.contentType),u=Te(i.sandbox).date(),d=Np({ref:e,blob:l,settable:n,now:u});o&&(d.downloadTokens=s);const h=await Ht(e.storage),f=await h.backend.getMetadata(e.fullPath);is(h,{request:{auth:Vt(i),method:"create",path:e.fullPath,resource:Aj(d)},resource:Ri(f)},i,a);const p=await h.backend.put(e.fullPath,l,d,HS(u.getTime()));try{pt(i.sandbox,Ln({at:Te(i.sandbox).now(),service:"storage",op:"object_put",path:e.fullPath,auth:Vt(i),before:p?.metadata,after:d,detail:{bucket:e.bucket,size:d.size,contentType:d.contentType,overwrite:p!==void 0}}),a)}catch{}return{result:{ref:e,metadata:xc(d,Pr(i))},replaced:p}}function Np(e){const{ref:t,blob:n,settable:r}=e,s=(e.now??new Date).toISOString(),i=String(ap((e.now??new Date).getTime())),o=t.name,a=Pr(Le(t.storage))==="client";return{fullPath:t.fullPath,name:o,bucket:t.bucket,generation:i,metageneration:"1",timeCreated:s,updated:s,size:n.size,contentType:r?.contentType||n.type||Dj,cacheControl:r?.cacheControl,contentDisposition:a?Sp(r?.contentDisposition,t.fullPath):r?.contentDisposition,contentEncoding:r?.contentEncoding,contentLanguage:r?.contentLanguage,customMetadata:r?.customMetadata}}function Mj(e,t){return e instanceof Blob?t&&t!==e.type?new Blob([e],{type:t}):e:new Blob([e],{type:t??""})}function Lj(e,t){if(e.fullPath==="")throw Ni(t)}async function Uj(e,t){return _c(e,"getBlob"),qj(e,t)}async function Bj(e,t){_c(e,"deleteObject");const n=Le(e.storage),r=zt(n,t),s=await Ht(e.storage),i=await s.backend.getMetadata(e.fullPath);is(s,{request:{auth:Vt(n),method:"delete",path:e.fullPath},resource:Ri(i)},n,r),await s.backend.delete(e.fullPath),Rp(e,i,r)}async function Fj(e,t,n){_c(e,"deleteObject");const r=Le(e.storage),s=await Ht(e.storage),i=await s.backend.getMetadata(e.fullPath),o=await s.backend.deleteIfGeneration(e.fullPath,t);return o&&Rp(e,i,zt(r,n)),o}function Rp(e,t,n){const r=Le(e.storage);try{pt(r.sandbox,Ln({at:Te(r.sandbox).now(),service:"storage",op:"object_delete",path:e.fullPath,auth:Vt(r),before:t??void 0,detail:{bucket:e.bucket}}),n)}catch{}}async function qj(e,t){const n=Le(e.storage),r=zt(n),s=await Ht(e.storage),i=await s.backend.getMetadata(e.fullPath);is(s,{request:{auth:Vt(n),method:"get",path:e.fullPath},resource:Ri(i)},n,r);const o=await s.backend.getBlob(e.fullPath);if(!o)throw gp(e.fullPath);return typeof t=="number"&&o.size>t?o.slice(0,t):o}function _c(e,t){if(e.fullPath==="")throw Ni(t)}async function Vj(e,t,n,r){const s=(await Ht(e.storage)).backend,i=await s.getMetadata(e.fullPath),o=await s.replaceIfGeneration(e.fullPath,t,n);return o&&Wj(e,i,n.metadata,r),o}function Wj(e,t,n,r){const s=Le(e.storage);try{pt(s.sandbox,Ln({at:Te(s.sandbox).now(),service:"storage",op:"object_put",path:e.fullPath,auth:Vt(s),before:t,after:n,detail:{bucket:e.bucket,size:n.size,contentType:n.contentType,overwrite:!0}}),zt(s,r))}catch{}}async function zj(e,t,n){const r=t.prior;return r!==void 0?Vj(e,t.generation,r,n).then(s=>({deleted:!1,restored:s}),s=>({deleted:!1,restored:!1,error:ra(e.fullPath,s,"restore")})):Fj(e,t.generation,n).then(s=>({deleted:s,restored:!1}),s=>({deleted:!1,restored:!1,error:ra(e.fullPath,s,"remove")}))}async function Hj(e,t,n){return(await zj(e,t,n)).error}const Kj={remove:"removing it failed",restore:"restoring the object it replaced failed"};function Gj(e){const t=e?.code;if(typeof t=="string")return t}function ra(e,t,n="remove"){const r=Gj(t)??"storage/unknown",s=t instanceof Error?t.message:String(t),i=Kj[n],o=`${r}: The upload to '${e}' was canceled after it was stored, and ${i}: ${s}`,a=new Error(o,{cause:t});return a.code=r,a}function Jj(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 Yj{[Symbol.toStringTag]="UploadTask";_snapshot;_promise;_resolve;_reject;_observers=[];_didIntermediateProgress=!1;_committing=!1;_sentCommit;_heldOutcome;_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=Jj(n,i);const a=Np({ref:t,blob:this._blob,settable:r}),l=xc(a,Pr(Le(t.storage)));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(()=>{if(!(this._snapshot.state==="running"))return;this._releaseHeldOutcome()||this._runStep()}),!0):!1}cancel(){let t=!1;return(this._snapshot.state==="running"||this._snapshot.state==="paused")&&(t=!0),t?(this._updateSnapshot("canceled",this._snapshot.bytesTransferred),this._rollBackCanceled().then(r=>this._settleCanceled(r)),!0):!1}on(t,n,r,s){let i,o,a,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&&(o=f.error),f.complete!==void 0&&(a=f.complete)}else typeof n=="function"&&(i=n),typeof r=="function"&&(o=r),typeof s=="function"&&(a=s);const d={next:i,error:o,complete:a};if(this._observers.push(d),this._snapshot.state==="running"){if(i!==void 0){const p=i;try{Ut(this),p(this._snapshot)}catch{}}}else if(this._snapshot.state==="paused"){if(i!==void 0){const m=i;try{Ut(this),m(this._snapshot)}catch{}}}else if(this._snapshot.state==="success"){if(i!==void 0){const b=i;try{Ut(this),b(this._snapshot)}catch{}}if(a!==void 0){const b=a;try{ni(this),b()}catch{}}}else if(this._snapshot.state==="error"){if(o!==void 0&&this._error!==void 0){const w=o,x=this._error;try{w(x)}catch{}}}else if(this._snapshot.state==="canceled"&&o!==void 0&&this._error!==void 0){const x=o,v=this._error;try{x(v)}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 a=i.next;try{Ut(this),a(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 a=i.complete;try{ni(this),a()}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(){const t=this._snapshot.state!=="running",n=this._committing||this._heldOutcome!==void 0;if(t||n)return;this._committing=!0;const r=this._storeUpload();this._sentCommit=r;const s=await r;this._committing=!1,this._settleCommit(s)}async _storeUpload(){try{if(await Ht(this._ref.storage),this._snapshot.state!=="running")return;const{result:n,replaced:r}=await Cp(this._ref,this._blob,this._metadata,{provenance:this._provenance});return{stored:{result:n,prior:r}}}catch(t){return{error:t}}}_settleCommit(t){const n=this._snapshot.state;if(n==="running"){this._report(t);return}n==="paused"&&(this._heldOutcome=t)}_releaseHeldOutcome(){const t=this._heldOutcome;return t===void 0?!1:(this._heldOutcome=void 0,this._report(t),!0)}_report(t){if(t===void 0){queueMicrotask(()=>this._runStep());return}if("stored"in t){this._updateSnapshot("success",this._snapshot.totalBytes,t.stored.result.metadata),this._notifyObservers("next"),this._notifyObservers("complete"),this._resolve(this._snapshot);return}this._fail(t.error)}_settleCanceled(t){this._error=t,this._notifyObservers("error"),this._reject(t)}_fail(t){let n;t instanceof Error?n=t:n=new Error(String(t)),this._error=n,this._updateSnapshot("error",this._snapshot.bytesTransferred),this._notifyObservers("error"),this._reject(this._error)}async _rollBackCanceled(){const t=this._heldOutcome;this._heldOutcome=void 0;const n=t??await this._sentCommit;if(!(n!==void 0&&"stored"in n))return du();const s={generation:n.stored.result.metadata.generation,prior:n.stored.prior};return await Hj(this._ref,s,this._provenance)??du()}}function Qj(e,t,n,r){if(e.fullPath==="")throw Ni("uploadBytesResumable");return new Yj(e,t,n,r)}async function Xj(e){const t=e.storage,n=Le(t),r=zt(n),s=await Ht(t);is(s,{request:{auth:Vt(n),method:"list",path:e.fullPath},resource:null},n,r);const i=e.fullPath===""?"":`${e.fullPath}/`,o=await s.backend.listByPrefix(i),a=[],l=new Set,u=[];for(const d of o){if(!d.fullPath.startsWith(i))continue;const h=d.fullPath.slice(i.length);if(h==="")continue;const f=h.indexOf("/");if(f===-1)a.push(Ar(t,d.fullPath));else{const p=h.slice(0,f),m=`${i}${p}`;l.has(m)||(l.add(m),u.push(Ar(t,m)))}}return u.sort((d,h)=>d.fullPath<h.fullPath?-1:d.fullPath>h.fullPath?1:0),{items:a,prefixes:u}}const Zj=qn("uploadBytes",Pj),eE=qn("uploadBytesResumable",Qj),tE=qn("getBlob",Uj),Ip=qn("deleteObject",Bj),nE=qn("getMetadata",Oj),Sc=qn("listAll",Xj);function rE(e){let t="",n=!1,r=!1,s=!1,i=0;for(;i<e.length;){const o=e[i],a=i+1<e.length?e[i+1]:"";if(r){(o===`
|
|
123
|
+
`||o==="\r")return!0;if(o==="\\"){t+=2;continue}if(o===i){t++;break}t++}r=!1;continue}if(s==="/"&&r){t=jb(e,t),r=!1;continue}r=Bv(s),t++}return!1}function Rr(e){const t=xh(e);let n="",r=0;const s=t.length;for(;r<s;){const i=t[r];if(i!=="\\"){n+=i,r++;continue}if(r+1>=s){n+="\\";break}const o=t[r+1],a=Lv[o];if(a!==void 0){n+=a,r+=2;continue}if(o==="x"&&r+3<s){const l=t.slice(r+2,r+4);if(Tv.test(l)){n+=String.fromCharCode(Number.parseInt(l,16)),r+=4;continue}}if(o==="u"&&r+5<s){const l=t.slice(r+2,r+6);if(Mv.test(l)){n+=String.fromCharCode(Number.parseInt(l,16)),r+=6;continue}}n+=o,r+=2}return n}function xh(e){if(e.length>=2){const t=e[0],n=e[e.length-1];if(t==='"'&&n==='"'||t==="'"&&n==="'")return e.slice(1,-1)}return e}function Bv(e){return"(!,&|?:;=[<>+-*%".includes(e)}function hn(e,t){return e==="matches"?"matches() expects 1 regular expression literal argument.":t===0?`${e}() expects no arguments.`:t===1?`${e}() expects 1 argument.`:`${e}() expects two arguments.`}function _h(e){return`${e}() expects a string argument.`}function Ho(e){return`Argument ${e} of replace() must be a string.`}const Sh="hasChildren() expects only a single argument (containing an array of child names).",kh="hasChildren() expects an array of child names.",jh="hasChildren() expects an array of strings.";function Qs(e,t){switch(e){case"==":case"===":return t==="left"?"Invalid == expression: left operand is not a number, boolean, string, null.":"Invalid == expression: right operand is not a number, boolean, string, or null.";case"!=":case"!==":return`Invalid != expression: ${t} operand is not a number, boolean, string, or null.`;case"+":return`Invalid + expression: ${t} operand is not a number or string.`;case"-":case"*":case"/":case"%":return`Invalid ${e} expression: ${t} operand is not a number.`;default:return`Invalid ${e} expression: ${t} operand must be a number or string.`}}function gl(e){return`Unknown variable '${e}'.`}const Eh="matches() expects a regular expression literal argument.",Ch="regular expressions do not support flags other than i";function ic(e){return e===""||e==="i"}const Fv=new Set(["__proto__","prototype","constructor"]);function bl(e,t){return Fv.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 oc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function mr(e){if(Array.isArray(e)){const n={};for(let r=0;r<e.length;r++){if(!(r in e))continue;const s=mr(e[r]);s!==null&&(n[String(r)]=s)}return Object.keys(n).length===0?null:n}if(!oc(e))return e??null;if(Object.hasOwn(e,".value"))return mr(e[".value"]);const t={};for(const[n,r]of Object.entries(e)){if(n===".priority")continue;const s=mr(r);s!==null&&(t[n]=s)}return Object.keys(t).length===0?null:t}function Vv(e){if(!oc(e)||mr(e)===null)return null;const t=e[".priority"];return typeof t=="number"||typeof t=="string"?t:null}class Bt{_value;_path;_root;constructor(t,n="/",r){this._value=t??null,this._path=n,this._root=r!==void 0?r:t}val(){return mr(this._value)}exists(){return this.val()!==null}hasChild(t){return this.child(t).exists()}hasChildren(t){return t!==void 0?t.every(n=>this.hasChild(n)):oc(this.val())}isString(){return typeof this.val()=="string"}isNumber(){return typeof this.val()=="number"}isBoolean(){return typeof this.val()=="boolean"}child(t){const n=t.split("/").filter(o=>o.length>0);if(n.length===0)return this;let r=this._value;for(const o of n)r!=null&&typeof r=="object"?r=Object.hasOwn(r,o)?r[o]??null:null:r=null;const i=`${this._path==="/"?"":this._path}/${n.join("/")}`;return new Bt(r,i,this._root)}parent(){if(this._path==="/")throw new ee("Cannot call parent() on root.");const t=this._path.split("/").filter(r=>r.length>0);return t.pop(),t.length===0?new Bt(this._root,"/"):new Bt(this._root,"/").child(t.join("/"))}getPriority(){return Vv(this._value)}}class qv{value;constructor(t){this.value=t}matches(t){return 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){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}}class ee extends Error{constructor(t){super(t),this.name="RtdbRuleRuntimeError"}}const wl=new Set(["val","exists","hasChild","hasChildren","isString","isNumber","isBoolean","child","parent","getPriority"]),Wv=new Set(["matches","contains","beginsWith","endsWith","replace","toLowerCase","toUpperCase"]);function Yn(e,t){if(t.length!==1)throw new ee(hn(e,1));const[n]=t;if(typeof n!="string")throw new ee(_h(e));return n}function zv(e){if(e.length===0)return;if(e.length>1)throw new ee(Sh);const[t]=e;if(!Array.isArray(t))throw new ee(kh);if(!t.every(n=>typeof n=="string"))throw new ee(jh);return t}function Hv(e){if(e.length!==1)throw new ee(hn("matches",1));const[t]=e;if(!(t instanceof RegExp))throw new ee(Eh);return t}function Kv(e){if(e.length!==2)throw new ee(hn("replace",2));const[t,n]=e;if(typeof t!="string")throw new ee(Ho(1));if(typeof n!="string")throw new ee(Ho(2));return[t,n]}const Gv=new Set(["==","===","!=","!=="]),Jv=new Set(["-","*","/","%"]),Yv=new Set(["<","<=",">",">="]);function vl(e,t){return t instanceof Bt||typeof t=="function"?!0:Gv.has(e)?!1:Jv.has(e)?typeof t!="number":typeof t!="number"&&typeof t!="string"}function Be(e,t,n,r){const s=t.eval(r);if(vl(e,s))throw new ee(Qs(e,"left"));const i=n.eval(r);if(vl(e,i)||Yv.has(e)&&typeof s!=typeof i)throw new ee(Qs(e,"right"));return[s,i]}function Qv(e){return e===null?"null":Array.isArray(e)?"array":typeof e}let Qi;function Xv(){if(Qi)return Qi;const e=es();return e.addOperation("eval(ctx)",{Expr(t){return t.eval(this.args.ctx)},Ternary_ternary(t,n,r,s,i){const o=t.eval(this.args.ctx);if(typeof o!="boolean")throw new ee("condition of ? must be boolean.");return o?r.eval(this.args.ctx):i.eval(this.args.ctx)},Ternary(t){return t.eval(this.args.ctx)},LogicalOr_or(t,n,r){const s=t.eval(this.args.ctx);if(typeof s!="boolean")throw new ee("Left operand of || must be boolean.");if(s)return!0;const i=r.eval(this.args.ctx);if(typeof i!="boolean")throw new ee("Right operand of || must be boolean.");return i},LogicalOr(t){return t.eval(this.args.ctx)},LogicalAnd_and(t,n,r){const s=t.eval(this.args.ctx);if(typeof s!="boolean")throw new ee("Left operand of && must be boolean.");if(!s)return!1;const i=r.eval(this.args.ctx);if(typeof i!="boolean")throw new ee("Right operand of && must be boolean.");return i},LogicalAnd(t){return t.eval(this.args.ctx)},Equality_strictEq(t,n,r){const[s,i]=Be("===",t,r,this.args.ctx);return s===i},Equality_strictNeq(t,n,r){const[s,i]=Be("!==",t,r,this.args.ctx);return s!==i},Equality_looseEq(t,n,r){const[s,i]=Be("==",t,r,this.args.ctx);return s===i},Equality_looseNeq(t,n,r){const[s,i]=Be("!=",t,r,this.args.ctx);return s!==i},Equality(t){return t.eval(this.args.ctx)},Comparison_gte(t,n,r){const[s,i]=Be(">=",t,r,this.args.ctx);return s>=i},Comparison_lte(t,n,r){const[s,i]=Be("<=",t,r,this.args.ctx);return s<=i},Comparison_gt(t,n,r){const[s,i]=Be(">",t,r,this.args.ctx);return s>i},Comparison_lt(t,n,r){const[s,i]=Be("<",t,r,this.args.ctx);return s<i},Comparison(t){return t.eval(this.args.ctx)},Additive_add(t,n,r){const[s,i]=Be("+",t,r,this.args.ctx);return s+i},Additive_sub(t,n,r){const[s,i]=Be("-",t,r,this.args.ctx);return s-i},Additive(t){return t.eval(this.args.ctx)},Multiplicative_mul(t,n,r){const[s,i]=Be("*",t,r,this.args.ctx);return s*i},Multiplicative_div(t,n,r){const[s,i]=Be("/",t,r,this.args.ctx);return i===0?Number.NaN:s/i},Multiplicative_mod(t,n,r){const[s,i]=Be("%",t,r,this.args.ctx);return s%i},Multiplicative(t){return t.eval(this.args.ctx)},UnaryExpr_not(t,n){const r=n.eval(this.args.ctx);return typeof r=="boolean"?!r:!1},UnaryExpr_neg(t,n){const r=n.eval(this.args.ctx);if(typeof r!="number")throw new ee("Invalid unary - expression: operand is not a number.");return-r},UnaryExpr(t){return t.eval(this.args.ctx)},CallExpr_methodCall(t,n,r,s,i,o){const a=t.eval(this.args.ctx),l=r.sourceString,u=i.asIteration().children.map(h=>h.eval(this.args.ctx));if(a instanceof Bt)switch(l){case"val":return a.val();case"exists":return a.exists();case"hasChild":return a.hasChild(Yn(l,u));case"hasChildren":return a.hasChildren(zv(u));case"isString":return a.isString();case"isNumber":return a.isNumber();case"isBoolean":return a.isBoolean();case"child":return a.child(Yn(l,u));case"parent":return a.parent();case"getPriority":return a.getPriority();default:throw new Error(`Unknown DataSnapshot method: ${l}`)}if(typeof a=="string"){const h=new qv(a);switch(l){case"matches":return h.matches(Hv(u));case"contains":return h.contains(Yn(l,u));case"beginsWith":return h.beginsWith(Yn(l,u));case"endsWith":return h.endsWith(Yn(l,u));case"replace":return h.replace(...Kv(u));case"toLowerCase":return h.toLowerCase();case"toUpperCase":return h.toUpperCase();default:throw wl.has(l)?new ee(`Method '${l}' is not defined on a string.`):new Error(`Unknown string method: ${l}`)}}throw(wl.has(l)||Wv.has(l))&&a!==void 0?new ee(`Method '${l}' is not defined on ${Qv(a)}.`):new Error(`Unknown method '${l}' for the given value.`)},CallExpr_memberAccess(t,n,r){const s=t.eval(this.args.ctx),i=r.sourceString;if(i==="length"){if(typeof s=="string")return s.length;throw new ee("No such method/property 'length'.")}return s==null?null:bl(s,i)},CallExpr_indexAccess(t,n,r,s){const i=t.eval(this.args.ctx),o=r.eval(this.args.ctx);if(typeof o!="string"&&typeof o!="number")throw new ee("Invalid property access.");return i==null?null:bl(i,String(o))},CallExpr(t){return t.eval(this.args.ctx)},Primary_paren(t,n,r){return n.eval(this.args.ctx)},Primary(t){return t.eval(this.args.ctx)},Array(t,n,r){return n.asIteration().children.map(s=>s.eval(this.args.ctx))},literal(t){return t.eval(this.args.ctx)},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(this.args.ctx)},string_double(t,n,r){if(Nr(this.sourceString))throw new SyntaxError(Ys);return Rr(this.sourceString)},string_single(t,n,r){if(Nr(this.sourceString))throw new SyntaxError(Ys);return Rr(this.sourceString)},string(t){return t.eval(this.args.ctx)},regex(t,n,r,s){if(!ic(s.sourceString))throw new ee(Ch);return new RegExp(n.sourceString,s.sourceString)},bool_true(t){return!0},bool_false(t){return!1},bool(t){return t.eval(this.args.ctx)},null(t){return null},ident(t,n,r){const s=this.args.ctx,i=this.sourceString;if(t.sourceString==="$"){const o=s?.pathVariableBindings;if(o!==void 0){if(i in o)return o[i];if(i.slice(1)in o)return o[i.slice(1)]}return}switch(i){case"auth":return s?.auth??null;case"data":return s?.data;case"newData":return s?.newData;case"root":return s?.root;case"now":return s?.now;case"query":return s?.query??null;default:return}}}),Qi=e,e}function Nh(e){const t=Zr(e);if(!t.ok)throw new Error(t.message);return Xv()(t.match)}function Ts(e,t){return Nh(e).eval(t)}const xl=new WeakMap;function Zv(e,t){let n=xl.get(e);return n===void 0&&(n=Nh(e.raw),xl.set(e,n)),n.eval(t)}let Xi;const ex=/^\$[A-Za-z_]\w*$/,tx=/^(?:auth|data|newData|root|query)(?:\.|\[)/;function nx(e){return e==="now"||ex.test(e)||tx.test(e)}function rx(e){if(e.isLiteral())try{const t=Ts(e.sourceString,{});return typeof t=="string"?t:void 0}catch(t){if(t instanceof ee)return;throw t}}function xt(e){const[t,,n]=e.children;if(!(!t.isLiteral()||!n.isLiteral()))try{const r=Ts(t.sourceString,{}),s=Ts(n.sourceString,{});return typeof r=="number"&&!Number.isFinite(r)||typeof s=="number"&&!Number.isFinite(s)?void 0:Ts(e.sourceString,{})===!0}catch(r){if(r instanceof ee)return;throw r}}function It(e,t,n){const r=e.args.ctx;t.lint(r),n.lint(r);const s=xt(e);if(s!==void 0){r.constantComparisons.push({source:e.sourceString,value:s});return}const i=t.isLiteral(),o=n.isLiteral();if(i===o)return;let a=n;i&&(a=t);const l=rx(a);l!==void 0&&nx(l)&&r.warnings.push({code:"QUOTED_REFERENCE",message:`Comparison ${e.sourceString} quotes '${l}' as a string literal; it compares against the literal text '${l}' rather than evaluating ${l}.`})}function sx(){if(Xi)return Xi;const e=es();return e.addOperation("lint(ctx)",{_nonterminal(...t){t.forEach(n=>n.lint(this.args.ctx))},_iter(...t){t.forEach(n=>n.lint(this.args.ctx))},_terminal(){},CallExpr_methodCall(t,n,r,s,i,o){const a=this.args.ctx;t.lint(a),i.asIteration().children.forEach(l=>l.lint(a)),r.sourceString==="child"&&t.isDataSnapshot()&&(a.hasDataChildAccess=!0)},CallExpr_memberAccess(t,n,r){t.lint(this.args.ctx)},ident(t,n,r){const s=this.args.ctx,i=this.sourceString;i==="data"&&(s.hasData=!0),i==="newData"&&(s.hasNewData=!0)},Equality_strictEq(t,n,r){It(this,t,r)},Equality_strictNeq(t,n,r){It(this,t,r)},Comparison_gte(t,n,r){It(this,t,r)},Comparison_lte(t,n,r){It(this,t,r)},Comparison_gt(t,n,r){It(this,t,r)},Comparison_lt(t,n,r){It(this,t,r)},Equality_looseEq(t,n,r){It(this,t,r)},Equality_looseNeq(t,n,r){It(this,t,r)}}),e.addOperation("isDataSnapshot",{_nonterminal(...t){return t.length===1?t[0].isDataSnapshot():!1},_iter(){return!1},_terminal(){return!1},Primary_paren(t,n,r){return n.isDataSnapshot()},ident(t,n,r){return this.sourceString==="data"},CallExpr_methodCall(t,n,r,s,i,o){const a=r.sourceString;return a==="parent"||a==="child"?t.isDataSnapshot():!1}}),e.addOperation("isNumberLiteral",{_nonterminal(...t){return t.length===1?t[0].isNumberLiteral():!1},_iter(){return!1},_terminal(){return!1},Primary_paren(t,n,r){return n.isNumberLiteral()},UnaryExpr_neg(t,n){return n.isNumberLiteral()},Additive_add(t,n,r){return t.isNumberLiteral()&&r.isNumberLiteral()},Additive_sub(t,n,r){return t.isNumberLiteral()&&r.isNumberLiteral()},Multiplicative_mul(t,n,r){return t.isNumberLiteral()&&r.isNumberLiteral()},Multiplicative_div(t,n,r){return t.isNumberLiteral()&&r.isNumberLiteral()},Multiplicative_mod(t,n,r){return t.isNumberLiteral()&&r.isNumberLiteral()},number(t){return Number.isFinite(Number(this.sourceString))}}),e.addOperation("isLiteral",{_nonterminal(...t){return t.length===1?t[0].isLiteral():!1},_iter(){return!1},_terminal(){return!1},Primary_paren(t,n,r){return n.isLiteral()},UnaryExpr_neg(t,n){return n.isNumberLiteral()},Additive_add(t,n,r){return t.isNumberLiteral()&&r.isNumberLiteral()},Additive_sub(t,n,r){return t.isNumberLiteral()&&r.isNumberLiteral()},Multiplicative_mul(t,n,r){return t.isNumberLiteral()&&r.isNumberLiteral()},Multiplicative_div(t,n,r){return t.isNumberLiteral()&&r.isNumberLiteral()},Multiplicative_mod(t,n,r){return t.isNumberLiteral()&&r.isNumberLiteral()},literal(t){return t.ctorName==="regex"?!1:t.ctorName==="number"?Number.isFinite(Number(t.sourceString)):!0}}),e.addOperation("literalBoolean",{_nonterminal(...t){return t.length===1?t[0].literalBoolean():void 0},_iter(){},_terminal(){},Primary_paren(t,n,r){return n.literalBoolean()},bool_true(t){return!0},bool_false(t){return!1},Equality_strictEq(t,n,r){return xt(this)},Equality_strictNeq(t,n,r){return xt(this)},Comparison_gte(t,n,r){return xt(this)},Comparison_lte(t,n,r){return xt(this)},Comparison_gt(t,n,r){return xt(this)},Comparison_lt(t,n,r){return xt(this)},Equality_looseEq(t,n,r){return xt(this)},Equality_looseNeq(t,n,r){return xt(this)}}),Xi=e,e}function ix(e,t="read"){const n=Zr(e);if(!n.ok)return[];const{match:r}=n,s={warnings:[],hasData:!1,hasNewData:!1,hasDataChildAccess:!1,constantComparisons:[]};try{const i=sx()(r);i.lint(s);const o=t==="validate"?void 0:i.literalBoolean();if(o===!0)s.warnings.push({code:"HARDCODED_TRUE",message:"Rule expression is hardcoded to true"});else if(o===!1)s.warnings.push({code:"HARDCODED_FALSE",message:"Rule expression is hardcoded to false"});else for(const{source:a,value:l}of s.constantComparisons)s.warnings.push({code:"CONSTANT_COMPARISON",message:`Comparison ${a} is always ${l}.`})}catch(i){if(i instanceof RangeError)return[{code:"PARSE_ERROR",message:Xr}];if(i instanceof SyntaxError)return[{code:"PARSE_ERROR",message:i.message}];throw i}return t==="write"&&s.hasData&&!s.hasNewData&&!s.hasDataChildAccess&&s.warnings.push({code:"DATA_IN_WRITE",message:"Write rule references 'data' but not 'newData'; consider using 'newData' to check incoming data"}),s.warnings}const ox=()=>ae("newData.hasChildren()"),ax=e=>ae(`newData.hasChild(${Ye(e)})`);let Zi;function cx(){if(Zi)return Zi;const e=es();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,o){return[...t.identifiers(),...i.asIteration().children.flatMap(a=>a.identifiers())]},CallExpr_memberAccess(t,n,r){return t.identifiers()},ident(t,n,r){return[this.sourceString]}}),Zi=e,e}const lx="Rule expressions may not contain assignments.";function ux(e){const t=e.replace(/'(?:\\.|[^'\\])*'?|"(?:\\.|[^"\\])*"?|\/(?:\\.|\[(?:\\.|[^\]\\\n])*\]|[^/\\\n[])+\/[a-zA-Z]*/g,'""');return/(^|[^=!<>])=(?!=)/.test(t)}function dx(e){if(Uv(e))return{raw:e,valid:!1,errors:[{code:"PARSE_ERROR",message:Ys}],warnings:[],referencedIdentifiers:[]};const t=Zr(e);if(!t.ok)return{raw:e,valid:!1,errors:[{code:"PARSE_ERROR",message:ux(e)?lx:t.message}],warnings:[],referencedIdentifiers:[]};let n;try{n=cx()(t.match).identifiers()}catch(s){if(s instanceof RangeError)return{raw:e,valid:!1,errors:[{code:"PARSE_ERROR",message:Xr}],warnings:[],referencedIdentifiers:[]};throw s}const r=[...new Set(n)];return{raw:e,valid:!0,errors:[],warnings:[],referencedIdentifiers:r}}function fx(e){return e==="rtdb"?"database":"firestore"}function Qn(e){return e.kind==="doc"?e.path:{collection:e.collection,query:e.query}}function hx(e){return e.path!==void 0?e.path:{collection:"",query:e.query}}function _l(e){const t=e.query;return t===void 0?{}:{query:t}}function px(e){const t=Xa(e),n="owners"in e&&Array.isArray(e.owners)?e.owners:void 0,r={actor:t.source,authLens:t.authLens,owners:n};return e.kind==="listener_attach"?{phase:"attach",listenerId:e.listenerId,service:"firestore",target:Qn(e.target),...r,..._l(e.target)}:e.kind==="listener_detach"?{phase:"detach",listenerId:e.listenerId,service:"firestore",target:Qn(e.target),...r}:e.kind==="listener_errored"?{phase:"errored",listenerId:e.listenerId,service:"firestore",target:Qn(e.target),...r}:e.kind==="snapshot_delivery"?{phase:"delivery",listenerId:e.listenerId,service:"firestore",target:Qn(e.target),...r}:e.kind==="snapshot_suppressed"?{phase:"suppressed",listenerId:e.listenerId,service:"firestore",target:Qn(e.target),...r}:e.kind==="listener"?{phase:e.phase,listenerId:e.listenerId,service:fx(e.service),target:hx(e.target),...r,..._l(e.target)}:null}function ac(e){const t=mx();for(const n of e)t.append(n);return t.snapshot()}function mx(){const e=new Map;return{append:n=>{const r=px(n);if(r===null)return;if(r.phase==="attach"){const d={id:r.listenerId,service:r.service,target:r.target,actor:r.actor,authLens:r.authLens,attachedAt:n.at,deliveryCount:0,suppressedCount:0};r.owners!==void 0&&(d.owners=[...r.owners]),r.query!==void 0&&(d.query=r.query);const p=n.activity?.listenerId;typeof p=="string"&&(d.clientListenerId=p),e.set(r.listenerId,d);return}const o=e.get(r.listenerId);if(o===void 0)return;if(r.phase==="delivery"){o.deliveryCount+=1,o.lastDeliveryAt=n.at,r.owners!==void 0&&(o.owners=yx(o.owners,r.owners));return}if(r.phase==="suppressed"){o.suppressedCount+=1;return}e.delete(r.listenerId)},snapshot:()=>Object.freeze([...e.values()].map(n=>Object.freeze({...n}))),clear:()=>e.clear()}}function yx(e,t){const n=t.filter(s=>s.kind==="regions");return n.length===0?[...e??[]]:[...(e??[]).filter(s=>s.kind!=="regions"),...n]}function gx(e,t){return typeof e=="string"?e.startsWith(t):e.collection.startsWith(t)}const Rh=Symbol("pyric/auth/target"),bx=Symbol("pyric.user.internal");function Y(e,t){return new H(e,`Firebase: ${t} (${e}).`)}const Ih={PASSWORD:"password"},eo={EMAIL_LINK:"emailLink",EMAIL_PASSWORD:"password"};class Si{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"?wx(t):t;if(!n)return null;const r=n.providerId,s=n.signInMethod;if(typeof r!="string"||typeof s!="string")return null;if(r===Ih.PASSWORD){const i=typeof n.email=="string"?n.email:"",o=typeof n.password=="string"?n.password:"";return new vx(i,o,s)}return new Si(r,s)}}function wx(e){try{const t=JSON.parse(e);return typeof t=="object"&&t!==null?t:null}catch{return null}}class vx extends Si{email;secret;constructor(t,n,r=eo.EMAIL_PASSWORD){super(Ih.PASSWORD,r),this.email=t,Object.defineProperty(this,"secret",{value:n,enumerable:!1,writable:!1})}get password(){return this.signInMethod===eo.EMAIL_PASSWORD?this.secret:null}get emailLink(){return this.signInMethod===eo.EMAIL_LINK?this.secret:null}toJSON(){return{providerId:this.providerId,signInMethod:this.signInMethod,email:this.email,password:this.secret}}}class ki extends Si{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 cc(e,t){return t?new ki(e,e):null}class Sn{static PROVIDER_ID="google.com";static GOOGLE_SIGN_IN_METHOD="google.com";providerId=Sn.PROVIDER_ID;addScope(t){return this}setCustomParameters(t){return this}static credentialFromResult(t){return cc(Sn.PROVIDER_ID,t)}static credentialFromError(t){return null}static credential(t,n){return new ki(Sn.PROVIDER_ID,Sn.GOOGLE_SIGN_IN_METHOD,{idToken:t??void 0,accessToken:n??void 0})}}class kn{static PROVIDER_ID="facebook.com";static FACEBOOK_SIGN_IN_METHOD="facebook.com";providerId=kn.PROVIDER_ID;addScope(t){return this}setCustomParameters(t){return this}static credentialFromResult(t){return cc(kn.PROVIDER_ID,t)}static credentialFromError(t){return null}static credential(t){return new ki(kn.PROVIDER_ID,kn.FACEBOOK_SIGN_IN_METHOD,{accessToken:t})}}class jn{static PROVIDER_ID="github.com";static GITHUB_SIGN_IN_METHOD="github.com";providerId=jn.PROVIDER_ID;addScope(t){return this}setCustomParameters(t){return this}static credentialFromResult(t){return cc(jn.PROVIDER_ID,t)}static credentialFromError(t){return null}static credential(t){return new ki(jn.PROVIDER_ID,jn.GITHUB_SIGN_IN_METHOD,{accessToken:t})}}const Ah=[Sn.PROVIDER_ID,"apple.com",kn.PROVIDER_ID,jn.PROVIDER_ID,"twitter.com","microsoft.com","yahoo.com"];function lc(e,t=!1){const n=e[Rh];if(!n)throw new TypeError("pyric/auth: unrecognized Auth handle — was it produced by getAuth(...)?");return t||n.assertAlive?.(),n}class xx{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 _x(e,t,n){const r=JSON.stringify(t);return`sandbox-id-token-${e}-${String(n)}:${r}`}function Qt(e){if(typeof e!="string"||e.length===0)throw Y("auth/invalid-email","Error");const t=e.indexOf("@");if(t<=0||t===e.length-1)throw Y("auth/invalid-email","Error")}function Xn(e){if(typeof e!="string"||e.length<6)throw Y("auth/weak-password","Password should be at least 6 characters")}function Oh(){return{usersByEmail:new Map,usersByUid:new Map,userDbSubscribers:new Set,providerConfig:new Map([["password",!0],["anonymous",!0]]),providerConfigSubscribers:new Set,counters:{nextAdminUserId:1}}}const Sx=2166136261,kx=2654435769,jx=16777619;function Sl(e,t){let n=t;for(let r=0;r<e.length;r++)n^=e[r],n=Math.imul(n,jx);return n>>>0}function kl(e){return e.toString(16).padStart(8,"0")}function Ex(e){const t=new TextEncoder().encode(e),n=new TextEncoder().encode([...e].reverse().join("")),r=Sl(t,Sx),s=Sl(n,kx);return kl(r)+kl(s)}function Cx(e){const t=Number.parseInt(e.slice(0,8),16),n=Number.parseInt(e.slice(8,16),16),r=t%360,s=40+n%80,i=(r+s)%360,o=60+t%16,a=45+n%16;return{hueStart:r,hueEnd:i,saturation:o,lightness:a}}function jl(e){const n=new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(e)[Symbol.iterator]().next();if(!n.done)return n.value.segment}function Nx(e){const t=e.displayName?.trim();if(t){const r=jl(t);if(r)return r.toUpperCase()}const n=e.email?.split("@")[0]?.trim();if(n){const r=jl(n);if(r)return r.toUpperCase()}}function Rx(e){return encodeURIComponent(e).replace(/'/g,"%27").replace(/\(/g,"%28").replace(/\)/g,"%29")}function Ix(e){const t=Ex(e.uid),{hueStart:n,hueEnd:r,saturation:s,lightness:i}=Cx(t),o=`g${t}`,a=Nx(e),l=e.pending===!0,u=a===void 0?"":`<text x="64" y="64" font-family="system-ui, -apple-system, sans-serif" font-size="56" fill="#fff" fill-opacity="${l?"0.55":"0.9"}" text-anchor="middle" dominant-baseline="central">${a}</text>`;return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128"><defs><linearGradient id="${o}" x1="0" y1="0" x2="1" y2="1"><stop offset="0%" stop-color="hsl(${n},${s}%,${i}%)"/><stop offset="100%" stop-color="hsl(${r},${s}%,${i}%)"/></linearGradient></defs><rect width="128" height="128" fill="url(#${o})"/>${u}${l?'<circle cx="64" cy="64" r="56" fill="none" stroke="#fff" stroke-opacity="0.25" stroke-width="6"/><circle cx="64" cy="64" r="56" fill="none" stroke="#fff" stroke-opacity="0.95" stroke-width="6" stroke-linecap="round" stroke-dasharray="44 308"><animateTransform attributeName="transform" type="rotate" from="0 64 64" to="360 64 64" dur="1s" repeatCount="indefinite"/></circle>':""}</svg>`}function Ax(e){return`data:image/svg+xml,${Rx(Ix(e))}`}const Ox=e=>Ax(e),$h="(default)";function Ph(e){return`${e}-default-rtdb`}function Dh(e,t){return t!==void 0&&t.length>0&&(e===t||e===Ph(t))}function Th(e){const t=$x(e,"Invalid Firebase Database URL");if(t.path!=="/")throw Xs("Database URL must point to the root of a Firebase Database (not including a child path).");return t.instance}function $x(e,t){const n=Tx(e);if(n.domain==="firebase.com")throw Xs(`${n.host} is no longer supported. Please use <YOUR FIREBASE>.firebaseio.com instead`);const r=n.namespace;if((!r||r==="undefined")&&n.domain!=="localhost")throw Xs("Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com");const s=n.host.toLowerCase(),i=n.pathSegments.length===0?"/":`/${n.pathSegments.join("/")}`;if(s.length===0||!Vx(r)&&s.split(":")[0]!=="localhost"||!qx(i))throw new Error(`${t} failed: url argument must be a valid firebase URL and the path can't contain ".", "#", "$", "[", or "]".`);const o=r!==n.subdomain?`?ns=${r}`:"";return{instance:{name:r,url:`${n.secure?"https://":"http://"}${s}/${o}`},host:s,path:i}}function uc(e){if(!Ux.test(e))throw Xs("Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com");return Th(`${e}.firebaseio.com`)}function Px(e){if(e===void 0)return;const t=e.trim();if(!(t===""||t.toLowerCase()==="default"))return/^[^./:?#]+$/.test(t)?uc(t):Th(e)}function Ko(e,t){return e===void 0?t??$h:e.name}function Dx(e){const t=new Map;return{defaultKey:Ko(void 0,e.defaultName),keyOf:r=>Ko(r,e.defaultName),getOrCreate(r){let s=t.get(r);return s===void 0&&(s=e.create(r),t.set(r,s)),s},get:r=>t.get(r),delete:r=>t.delete(r),entries:()=>t.entries()}}function Tx(e){let t=e,n="",r="",s="",i="",o=[],a=!0,l="https",u=t.indexOf("//");u>=0&&(l=t.substring(0,u-1),t=t.substring(u+2));let d=t.indexOf("/");d===-1&&(d=t.length);let h=t.indexOf("?");h===-1&&(h=t.length),n=t.substring(0,Math.min(d,h)),d<h&&(o=Mx(t.substring(d,h)));const f=Lx(t.substring(Math.min(t.length,h)));u=n.indexOf(":"),u>=0?a=l==="https"||l==="wss":u=n.length;const p=n.slice(0,u);if(p.toLowerCase()==="localhost")r="localhost";else if(p.split(".").length<=2)r=p;else{const m=n.indexOf(".");s=n.substring(0,m).toLowerCase(),r=n.substring(m+1),i=s}return Object.prototype.hasOwnProperty.call(f,"ns")&&(i=f.ns),{host:n,domain:r,subdomain:s,secure:a,pathSegments:o,namespace:i}}function Mx(e){const t=[];for(const n of e.split("/")){if(n.length===0)continue;let r=n;try{r=decodeURIComponent(n.replace(/\+/g," "))}catch{}t.push(r)}return t}function Lx(e){const t={};e.charAt(0)==="?"&&(e=e.substring(1));for(const n of e.split("&")){if(n.length===0)continue;const r=n.split("=");r.length===2&&(t[decodeURIComponent(r[0])]=decodeURIComponent(r[1]))}return t}const Ux=/^[A-Za-z0-9][A-Za-z0-9-]*$/,Bx=/[[\].#$/\u0000-\u001F\u007F]/,Fx=/[[\].#$\u0000-\u001F\u007F]/;function Vx(e){return e.length!==0&&!Bx.test(e)}function qx(e){const t=e.replace(/^\/*\.info(\/|$)/,"/");return t.length!==0&&!Fx.test(t)}function Xs(e){return new Error(`FIREBASE FATAL ERROR: ${e} `)}const Wx=new Set(["__proto__","prototype","constructor"]);function V(e){if(e===""||e==="/")return[];const t=e.split("/").filter(n=>n.length>0);for(const n of t)if(Wx.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 G(e){return e.length===0?"/":"/"+e.join("/")}function Mt(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>Mt(n));const t={};for(const[n,r]of Object.entries(e))t[n]=Mt(r);return t}function Go(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function cn(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)=>cn(s,t[i]));if(!Go(e)||!Go(t))return!1;const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(s=>s in t&&cn(e[s],t[s]))}class zx{root={};snapshot(){return Mt(this.root)}restore(t){this.root=Mt(t)}read(t){const n=V(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 o=s;if(!Object.hasOwn(o,i))return null;s=o[i]}return Go(s)&&Object.keys(s).length===0?null:Mt(s)}write(t,n){const r=V(t),s=this.read(t);if(r.length===0)return n===null?(this.root={},s):(this.root=Mt(n),s);(this.root===null||typeof this.root!="object"||Array.isArray(this.root))&&(this.root={});let i=this.root;for(let a=0;a<r.length-1;a++){const l=r[a],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 o=r[r.length-1];return n===null?(delete i[o],this.trim(r)):i[o]=Mt(n),s}multiUpdate(t){const r=Object.entries(t).map(([i,o])=>({path:G(V(i)),value:o}));for(let i=0;i<r.length;i++)for(let o=i+1;o<r.length;o++){const a=r[i].path,l=r[o].path;if(a===l)throw new Error(`multi-path update: duplicate path '${a}'.`);const u=a==="/"?"/":a+"/",d=l==="/"?"/":l+"/";if(a!=="/"&&l.startsWith(u))throw new Error(`multi-path update: '${l}' is a descendant of '${a}'.`);if(l!=="/"&&a.startsWith(d))throw new Error(`multi-path update: '${a}' is a descendant of '${l}'.`)}const s=[];for(const{path:i,value:o}of r){const a=this.write(i,o);s.push({path:i,prior:a})}return s}shallowUpdate(t,n){const r=[],s=V(t);for(const[i,o]of Object.entries(n)){const a=[...s,...V(i)],l=G(a),u=this.write(l,o);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 a=0;a<r.length-1;a++){const l=i[r[a]];if(l==null||typeof l!="object"||Array.isArray(l))return;i=l}const o=i[s];if(o!==void 0&&typeof o=="object"&&o!==null&&!Array.isArray(o)&&Object.keys(o).length===0){delete i[s];continue}return}}}const Hx="12.13.0",Kx=/[\[\].#$/\u0000-\u001F\u007F]/;function Gx(e){return e.length!==0&&!Kx.test(e)}function Jx(e){return typeof e=="number"&&(Number.isNaN(e)||e===1/0||e===-1/0)}function Yx(e){return e===".priority"||e===".value"||e===".sv"}function Qx(e,t){Jo(e,t,"set")}function Jo(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(Jx(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&&Jo(s,`${t}/${r}`,n)}return}for(const[r,s]of Object.entries(e)){if(!Yx(r)&&!Gx(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 "]"`);Jo(s,`${t}/${r}`,n)}}}function en(e,t){return Qx(e,t),yr(e)}function yr(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=yr(e[r]);s!==null&&(n[String(r)]=s)}return Object.keys(n).length===0?null:n}if(Object.hasOwn(e,".value"))return yr(e[".value"]);const t={};for(const[n,r]of Object.entries(e)){if(n===".priority")continue;if(n===".sv"){t[n]=r;continue}const s=yr(r);s!==null&&(t[n]=s)}return Object.keys(t).length===0?null:t}function Xx(e){const t=[],n=(r,s)=>{if(r===null||typeof r!="object")return;const i=!Array.isArray(r);if(i&&Object.hasOwn(r,".priority")){const o=r[".priority"],a=typeof o=="object"&&o!==null&&".sv"in o;if(o!==null&&typeof o!="string"&&typeof o!="number"&&!a)throw new Error(`Firebase Database (${Hx}) INTERNAL ASSERT FAILED: Invalid priority type found: ${typeof o}`);a||t.push({segments:s,priority:o})}if(i&&Object.hasOwn(r,".value")){n(r[".value"],s);return}for(const[o,a]of Object.entries(r))o.startsWith(".")||n(a,[...s,o])};return n(e,[]),t}function tn(e,t){const n=Xx(e),r=n.find(s=>s.segments.length===0);return{priority:r?r.priority:t,inline:r!==void 0,nested:n.filter(s=>s.segments.length>0)}}function El(e,t){return typeof e=="object"&&e!==null&&!Array.isArray(e)?{...e,".priority":t}:{".value":e,".priority":t}}function mt(e,t){const n=t.filter(s=>s.priority!==null);if(n.length===0||e===null)return e;let r=structuredClone(e);for(const{segments:s,priority:i}of n){if(s.length===0){r=El(r,i);continue}let o=r;for(const u of s.slice(0,-1))o=typeof o=="object"&&o!==null&&!Object.hasOwn(o,".value")?o[u]:void 0;const a=s[s.length-1];if(typeof o!="object"||o===null||!Object.hasOwn(o,a))continue;const l=o;l[a]!==null&&(l[a]=El(l[a],i))}return r}function Zx(e,t=null){const n=tn(e,t),r=yr(e);return mt(r,[{segments:[],priority:n.priority},...n.nested])}function Ms(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(o=>Ms(o));const t=e,n=Object.keys(t);let r=n.length>0,s=0;for(const o of n)if(/^(0|[1-9]\d*)$/.test(o))s=Math.max(s,Number(o));else{r=!1;break}if(r&&s<2*n.length){const o=[];for(let a=0;a<=s;a++){const l=t[String(a)];o[a]=l===void 0?null:Ms(l)}return o}const i={};for(const[o,a]of Object.entries(t))i[o]=Ms(a);return i}function Mh(e){return"/"+e.split("/").filter(Boolean).join("/")}function Cl(e,t){return new Error(`Index not defined, add ".indexOn": "${t}", for path "${Mh(e)}", to the rules`)}function e_(e){return e.limit===null&&e.bounds.length===0}function t_(e,t){return`Using an unspecified index. Your data will be downloaded and filtered on the client. Consider adding ".indexOn": "${t}" at ${Mh(e)} to your security rules for better performance.`}function n_(e){console.warn(`[${new Date().toISOString()}] @firebase/database:`,`FIREBASE WARNING: ${e} `)}function r_(e,t){return e==="/"||t==="/"?!0:e===t||e.startsWith(`${t}/`)||t.startsWith(`${e}/`)}class s_{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=>G(V(n)))})}conflictsSince(t,n){const r=G(V(n));return this.mutations.some(s=>s.version>t&&s.paths.some(i=>r_(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 nt(e){return e==="unsupported"?"unsupported":"deny"}function Dn(e){const t={engine:"rtdb",matchedPath:e.matchedPath,matchedRule:e.matchedRule,pathVariableBindings:e.pathVariableBindings,reason:e.reason,errorCode:e.errorCode};return e.trace!==void 0&&(t.rtdbTrace=e.trace),t}function Pe(e,t,n,r,s={}){const i={method:n,path:yt(r)};return s.data!==void 0&&(i.data=structuredClone(s.data)),s.query!==void 0&&(i.query=structuredClone(s.query)),{...Object.fromEntries(Object.entries(Dn(e)).filter(([,a])=>a!==void 0)),engine:"rtdb",auth:t===null?null:structuredClone(t),reasons:[...e.reasons],request:i}}function yt(e){return G(V(e))}class i_{sandbox;nextId=0;instanceField;constructor(t,n){this.sandbox=t,this.instanceField=n===void 0?{}:{instance:n}}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{pt(this.sandbox,Un({at:Te(this.sandbox).now(),service:"rtdb",...this.instanceField,op:n,path:r,auth:t,before:s.before,after:s.after,detail:s.detail}),{service:"rtdb"})}catch{}}operation(t,n,r,s,i,o={}){if(this.sandbox)try{let a;i&&(a=Dn(i));let l="user";o.origin&&(l=o.origin);let u=o.at;u===void 0&&(u=Te(this.sandbox).now()),pt(this.sandbox,Kf({service:"rtdb",...this.instanceField,method:n,path:yt(r),auth:t,result:s,origin:l,durationMs:o.durationMs,reasons:i?.reasons,rules:a,request:o.request,resourceBefore:o.resourceBefore,resourceAfter:o.resourceAfter,groupId:o.groupId,groupKind:o.groupKind,triggeredBy:o.triggeredBy,detail:o.detail,at:u}),{service:"rtdb"})}catch{}}commit(t,n,r,s={}){if(this.sandbox)try{pt(this.sandbox,Eb({at:Te(this.sandbox).now(),service:"rtdb",...this.instanceField,method:n,path:yt(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),pt(this.sandbox,Cb({at:Te(this.sandbox).now(),service:"rtdb",...this.instanceField,phase:t,listenerId:n.id,target:{kind:i,path:yt(n.path),...s.query===void 0?{}:{query:s.query}},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,owners:s.owners}),{service:"rtdb"})}catch{}}}class o_{values=new Map;get(t){return this.values.get(G(V(t)))??null}forChild(t){const n=V(t);return r=>this.get(G([...n,r]))}atOrBelow(t){const n=G(V(t)),r=n==="/"?"/":`${n}/`,s={};for(const[i,o]of this.values)(i===n||i.startsWith(r))&&(s[i]=o);return s}clear(){this.values.clear()}clearAtOrBelow(t){const n=G(V(t)),r=n==="/"?"/":`${n}/`;for(const s of this.values.keys())(s===n||s.startsWith(r))&&this.values.delete(s)}replace(t,n,r){if(this.clearAtOrBelow(t),n!==null){this.values.set(G(V(t)),n);return}r&&this.pruneMissingAncestors(t,r)}set(t,n){const r=G(V(t));n===null?this.values.delete(r):this.values.set(r,n)}stateAtOrBelow(t){const n=G(V(t)),r=n==="/"?"/":`${n}/`;return JSON.stringify([...this.values].filter(([s])=>s===n||s.startsWith(r)).sort(([s],[i])=>s.localeCompare(i)))}applyUpdate(t,n){for(const r of t)this.clearAtOrBelow(r.path),r.value===null&&n&&this.pruneMissingAncestors(r.path,n)}pruneMissingAncestors(t,n){const r=V(t);for(let s=r.length-1;s>=0;s-=1){const i=G(r.slice(0,s));if(n(i))break;this.values.delete(i)}}entries(){return this.values.entries()}restore(t){this.values.clear();for(const[n,r]of Object.entries(t))this.values.set(G(V(n)),r)}}function Lt(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)")}const Fn=(...e)=>new Set(["Error",...e]),Ir=Fn("Boolean"),a_=Fn("Boolean","Number","String","Null","NullableSnapshot","Value","Auth","QueryValue","Mixed"),c_=Fn("Number","String","Value","Auth","QueryValue","Mixed"),l_=Fn("Number","String","Value","Auth","QueryValue","Mixed"),Lh=Fn("Number","Value","Auth","QueryValue","Mixed"),dc=Fn("String","Value","Auth","Mixed"),Nl=new Set(["String","Value","Auth"]),Rl=new Set(["Snapshot","NullableSnapshot","Null"]);function u_(e,t){return e===t?e:Rl.has(e)&&Rl.has(t)?"NullableSnapshot":Nl.has(e)||Nl.has(t)?"Value":"Mixed"}function ue(e,t){return{code:e,message:t}}function d_(e){switch(e){case"==":case"===":case"!=":case"!==":return a_;case"<":case"<=":case">":case">=":case"+":return c_;default:return Lh}}function f_(e,t,n){return e!=="+"&&e!=="-"&&e!=="*"&&e!=="/"&&e!=="%"?"Boolean":t==="Error"||n==="Error"?"Error":e!=="+"?"Number":t==="String"||n==="String"?"String":t==="Number"&&n==="Number"?"Number":"Value"}const gt=e=>ue("INVALID_ARGUMENT",e);function _t(e){return{returns:e,check:(t,n)=>n.length===0?null:gt(hn(t,0))}}function gr(e){return{returns:e,check(t,n){return n.length!==1?gt(hn(t,1)):dc.has(n[0].type)?null:gt(_h(t))}}}const h_={returns:"Boolean",check(e,t){if(t.length===0)return null;if(t.length>1)return gt(Sh);const n=t[0];return n.type==="Error"?null:n.type!=="Array"?gt(kh):(n.elements??[]).every(r=>dc.has(r))?null:gt(jh)}},p_={returns:"String",check(e,t){if(t.length!==2)return gt(hn(e,2));const n=t.findIndex(r=>!dc.has(r.type));return n===-1?null:gt(Ho(n===0?1:2))}},m_={returns:"Boolean",check(e,t){if(t.length!==1)return gt(hn(e,1));const n=t[0].type;return n==="Regex"||n==="Error"?null:gt(Eh)}},y_=new Map([["val",_t("Value")],["exists",_t("Boolean")],["isString",_t("Boolean")],["isNumber",_t("Boolean")],["isBoolean",_t("Boolean")],["parent",_t("Snapshot")],["getPriority",_t("Value")],["child",gr("Snapshot")],["hasChild",gr("Boolean")],["hasChildren",h_]]),Il=new Map([["contains",gr("Boolean")],["beginsWith",gr("Boolean")],["endsWith",gr("Boolean")],["replace",p_],["toLowerCase",_t("String")],["toUpperCase",_t("String")],["matches",m_]]),g_=new Map([["orderByKey","Boolean"],["orderByValue","Boolean"],["orderByPriority","Boolean"],["orderByChild","QueryValue"],["startAt","QueryValue"],["endAt","QueryValue"],["equalTo","QueryValue"],["limitToFirst","QueryValue"],["limitToLast","QueryValue"]]),b_="Invalid property access: target is not an object.";function Uh(e,t){const n=()=>({kind:"error",error:ue("NO_SUCH_MEMBER",`No such method/property '${t}'.`)});switch(e){case"Error":return{kind:"error",error:null};case"Snapshot":case"NullableSnapshot":{const r=y_.get(t);return r?{kind:"method",method:r}:n()}case"String":case"Value":{const r=Il.get(t);return r?{kind:"method",method:r}:t==="length"?{kind:"property",type:"Number"}:n()}case"Auth":{const r=Il.get(t);return r?{kind:"method",method:r}:{kind:"property",type:"Auth"}}case"Query":{const r=g_.get(t);return r?{kind:"property",type:r}:n()}default:return{kind:"error",error:ue("NOT_AN_OBJECT",b_)}}}const w_=new Map([["auth","Auth"],["data","Snapshot"],["newData","Snapshot"],["root","Snapshot"],["now","Number"],["query","Query"]]),St={type:"Error"},Ne=e=>({type:e});function me(e,t){return e.errors.push(t),St}function Re(e,t){return t.type!=="Array"?t.type:(me(e,ue("UNEXPECTED_ARRAY","Unexpected array literal.")),"Error")}function je(e,t){return e.typeOf(t)}function Fe(e,t,n){const r=this.args.ctx,s=t.sourceString,i=Re(r,je(e,r)),o=Re(r,je(n,r)),a=d_(s);return a.has(i)?a.has(o)?Ne(f_(s,i,o)):me(r,ue("INVALID_OPERAND",Qs(s,"right"))):me(r,ue("INVALID_OPERAND",Qs(s,"left")))}function Al(e,t,n){const r=this.args.ctx,s=t.sourceString,i=Re(r,je(e,r)),o=Re(r,je(n,r));return Ir.has(i)?Ir.has(o)?Ne(i==="Error"||o==="Error"?"Error":"Boolean"):me(r,ue("INVALID_OPERAND",`Right operand of ${s} must be boolean.`)):me(r,ue("INVALID_OPERAND",`Left operand of ${s} must be boolean.`))}function Ol(e,t,n){const r=Uh(Re(e,t),n);return r.kind==="error"?r.error?me(e,r.error):St:Ne(r.kind==="method"?"SnapshotMethod":r.type)}function v_(e){let t=0,n=!1;for(let r=0;r<e.length;r++){const s=e[r];if(s==="\\"){r++;continue}if(n){s==="]"&&(n=!1);continue}if(s==="["){n=!0;continue}if(s==="(")t++;else if(s===")"&&(t--,t<0))return`Illegal regular expression, unexpected ')' at position ${r+2}`}return t>0?`Illegal regular expression, expected ')' at position ${e.length+4}`:null}let to;function x_(){if(to)return to;const e=es();return e.addOperation("literalString",{_nonterminal(...t){return t.length===1?t[0].literalString():void 0},_iter(){},_terminal(){},Primary_paren(t,n,r){return n.literalString()},string(t){return Rr(this.sourceString)}}),e.addOperation("typeOf(ctx)",{_nonterminal(...t){return t.length===1?je(t[0],this.args.ctx):St},_iter(){return St},_terminal(){return St},Ternary_ternary(t,n,r,s,i){const o=this.args.ctx,a=Re(o,je(t,o)),l=Re(o,je(r,o)),u=Re(o,je(i,o));return Ir.has(a)?l==="Error"||u==="Error"?St:Ne(u_(l,u)):me(o,ue("INVALID_OPERAND","condition of ? must be boolean."))},LogicalAnd_and:Al,LogicalOr_or:Al,Equality_strictEq:Fe,Equality_strictNeq:Fe,Comparison_gte:Fe,Comparison_lte:Fe,Comparison_gt:Fe,Comparison_lt:Fe,Equality_looseEq:Fe,Equality_looseNeq:Fe,Additive_add:Fe,Additive_sub:Fe,Multiplicative_mul:Fe,Multiplicative_div:Fe,Multiplicative_mod:Fe,UnaryExpr_not(t,n){const r=this.args.ctx,s=Re(r,je(n,r));return Ir.has(s)?Ne(s==="Error"?"Error":"Boolean"):me(r,ue("INVALID_OPERAND","! only operates on booleans."))},UnaryExpr_neg(t,n){const r=this.args.ctx,s=Re(r,je(n,r));return Lh.has(s)?Ne(s==="Error"?"Error":"Number"):me(r,ue("INVALID_OPERAND","- only operates on numbers."))},CallExpr_methodCall(t,n,r,s,i,o){const a=this.args.ctx,l=Re(a,je(t,a)),u=i.asIteration().children.map(m=>je(m,a)),d=r.sourceString,h=Uh(l,d);if(h.kind==="error")return h.error?me(a,h.error):St;if(h.kind==="property")return me(a,ue("NOT_A_FUNCTION","Type error: Function call on target that is not a function."));const f=u.map(m=>d==="hasChildren"?m:Ne(Re(a,m)));if(f.some(m=>m.type==="Error"))return St;const p=h.method.check(d,f);return p?me(a,p):Ne(h.method.returns)},CallExpr_memberAccess(t,n,r){const s=this.args.ctx;return Ol(s,je(t,s),r.sourceString)},CallExpr_indexAccess(t,n,r,s){const i=this.args.ctx,o=je(t,i),a=r.literalString();if(a!==void 0)return Ol(i,o,a);const l=Re(i,o),u=Re(i,je(r,i));return l==="Error"||u==="Error"?St:l==="Auth"?l_.has(u)?Ne("Auth"):me(i,ue("INVALID_PROPERTY_ACCESS","Invalid property access on 'auth' object.")):me(i,ue("INVALID_PROPERTY_ACCESS","Invalid property access."))},Primary_paren(t,n,r){return je(n,this.args.ctx)},Array(t,n,r){const s=this.args.ctx;return{type:"Array",elements:n.asIteration().children.map(a=>Re(s,je(a,s)))}},number(t){return Ne("Number")},string(t){return Nr(this.sourceString)?me(this.args.ctx,ue("PARSE_ERROR",Ys)):Ne("String")},regex(t,n,r,s){const i=v_(n.sourceString);return i!==null?me(this.args.ctx,ue("INVALID_REGEX",i)):ic(s.sourceString)?Ne("Regex"):me(this.args.ctx,ue("INVALID_REGEX",Ch))},bool(t){return Ne("Boolean")},null(t){return Ne("Null")},ident(t,n,r){const s=this.args.ctx,i=this.sourceString;if(t.sourceString==="$")return s.pathVars.has(i.slice(1))?Ne("String"):me(s,ue("UNKNOWN_IDENTIFIER",gl(i)));if(i==="newData"&&s.context==="read")return me(s,ue("NEWDATA_IN_READ","newData is invalid in .read expressions."));const o=w_.get(i);return o?Ne(o):me(s,ue("UNKNOWN_IDENTIFIER",gl(i)))}}),to=e,e}function __(e,t,n=[]){const r=Zr(e);if(!r.ok)return[];const{match:s}=r,i={errors:[],context:t,pathVars:new Set(n.map(a=>a.startsWith("$")?a.slice(1):a))};let o;try{o=Re(i,x_()(s).typeOf(i))}catch(a){if(a instanceof RangeError)return[ue("PARSE_ERROR",Xr)];throw a}return Ir.has(o)||me(i,ue("NOT_BOOLEAN","Expression must evaluate to a boolean.")),i.errors}const Bh=In({orderByChild:Ee().nullable().optional(),orderByKey:Dt().nullable().optional(),orderByValue:Dt().nullable().optional(),orderByPriority:Dt().nullable().optional(),equalTo:Ps([Ee(),xn(),Dt(),Ds()]).optional(),limitToFirst:xn().nullable().optional(),limitToLast:xn().nullable().optional(),startAt:Ps([Ee(),xn(),Dt(),Ds()]).optional(),endAt:Ps([Ee(),xn(),Dt(),Ds()]).optional()});function Fh(e){const t=Bh.strict().safeParse(e);if(!t.success)return`query is not a Realtime Database query: ${t.error.issues.map(s=>s.message).join("; ")}`;const n=t.data;if(n.orderByChild==="")return"query.orderByChild must name a child path.";if(n.orderByChild!=null&&n.orderByChild.split("/").filter(Boolean).length===0)return"orderByChild: cannot pass in empty path. Use orderByValue() instead.";if([n.orderByChild!=null&&n.orderByChild!=="",n.orderByKey===!0,n.orderByValue===!0,n.orderByPriority===!0].filter(Boolean).length>1)return"query names more than one of orderByChild, orderByKey and orderByValue.";if(n.equalTo!==void 0&&n.startAt!==void 0)return"equalTo: Starting point was already set (by another call to startAt, startAfter, or equalTo).";if(n.equalTo!==void 0&&n.endAt!==void 0)return"equalTo: Ending point was already set (by another call to endAt, endBefore, or equalTo).";if(n.limitToFirst!=null&&n.limitToLast!=null)return"query names both limitToFirst and limitToLast.";for(const[s,i]of[["limitToFirst",n.limitToFirst],["limitToLast",n.limitToLast]])if(i!=null&&(!Number.isInteger(i)||i<=0))return`query.${s} must be a positive integer.`;return null}const S_=In({operation:qs(["read","write","validate"]),path:Ee().min(1).startsWith("/"),auth:Ps([In({uid:Ee(),tenant:Ee().optional(),token:Vs(ds()).optional()}),Ds()]),mockData:Vs(ds()),newData:ds().optional(),updates:Gf(In({path:Ee().min(1).startsWith("/"),value:ds()})).optional(),query:Bh.optional(),now:xn().optional()});qs(["INVALID_INPUT","NO_MATCHING_RULE","EVALUATION_ERROR"]);const k_=In({path:Ee(),kind:qs(["read","write","validate"]),conditionText:Ee(),verdict:qs(["ALLOW","DENY","ERROR","UNSUPPORTED"]),message:Ee().optional(),pathVariableBindings:Vs(Ee()),instance:Ee().optional()});In({allowed:Dt(),unsupported:Dt().optional(),matchedPath:Ee(),matchedRule:Ee(),reason:Ee(),pathVariableBindings:Vs(Ee()),trace:Gf(k_)});const j_=["sub","aud","iss","auth_time","iat","exp"],E_=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce","sub","firebase"];function $l(e){const t=E_.filter(r=>Object.prototype.hasOwnProperty.call(e,r));if(t.length===0)return;const n=t.length>1?`Developer claims "${t.join('", "')}" are reserved and cannot be specified.`:`Developer claim "${t[0]}" is reserved and cannot be specified.`;throw new H("auth/reserved-claim",n)}function Vh(e){const t={...e};for(const n of j_)delete t[n];return t}function C_(e){return{uid:e.uid,email:e.email,emailVerified:e.emailVerified,displayName:e.displayName,photoUrl:e.photoUrl,phoneNumber:e.phoneNumber,isAnonymous:e.isAnonymous,providerIds:e.providerUserInfo.map(t=>t.providerId)}}const N_=new Set(["password","phone","anonymous"]);function qh(e,t,n,r){const s={},i={user_id:e},o={};if(t!==null){t.displayName!==null&&(s.name=t.displayName),t.photoUrl!==null&&(s.picture=t.photoUrl),t.isAnonymous&&(i.provider_id="anonymous"),t.email!==null&&(i.email=t.email,i.email_verified=t.emailVerified,o.email=[t.email]),t.phoneNumber!==null&&(i.phone_number=t.phoneNumber,o.phone=[t.phoneNumber]);for(const a of t.providerIds)N_.has(a)||(o[a]=[t.uid])}return{...s,...n,...i,firebase:{identities:o,sign_in_provider:r}}}function Pl(e){if(typeof e=="object"&&e!==null&&!Array.isArray(e))return e}function R_(e,t,n=Date.now()){const r=Math.floor(n/1e3),s=qh(e,null,t,null),i=Pl(t.firebase)??{},o=s.firebase,a=Pl(i.identities)??o.identities,l={...i,identities:a};return{sub:e,aud:"pyric-sandbox",iss:"https://sandbox.pyric.dev",auth_time:r,iat:r,exp:r+3600,...s,...t,user_id:t.user_id??s.user_id,firebase:l}}function I_(e){return e===null||typeof e!="object"?!1:e[".sv"]==="timestamp"}function A_(e){if(e===null||typeof e!="object")return!1;const t=e[".sv"];return t!==null&&typeof t=="object"&&typeof t.increment=="number"}function O_(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&Object.hasOwn(e,".value")?e[".value"]:e}function ht(e,t,n){const r=O_(n);if(I_(e))return t;if(A_(e)){const o=e[".sv"].increment;return(typeof r=="number"?r:0)+o}if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map((o,a)=>ht(o,t,Array.isArray(r)?r[a]:void 0));let s;r!==null&&typeof r=="object"&&!Array.isArray(r)&&(s=r);const i={};for(const[o,a]of Object.entries(e)){const l=o===".value"?r:s?.[o];i[o]=ht(a,t,l)}return i}function Dl(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function $_(e,t){let n=e;for(const r of t.split("/").filter(Boolean)){if(n===null||typeof n!="object")return;n=n[r]}return n}function Tl(e,t,n,r){if(n===void 0)return null;const s=ht(n,r,$_(e,t));return Zx(s)}function P_(e,t,n,r,s,i){if(!s||s.length===0)return Yo(e,n,Tl(e,t,r,i));let o=e;for(const a of s){const l=a.path.split("/").filter(Boolean);o=Yo(o,l,Tl(e,a.path,a.value,i))}return o}function Yo(e,t,n){if(t.length===0)return n??null;const[r,...s]=t;if(!r)return e??null;const i=Dl(e)&&Object.hasOwn(e,".value"),o=i?e[".value"]:e,a=Dl(o);let l=null;a&&Object.hasOwn(o,r)&&(l=o[r]);const u=Yo(l,s,n);if(u==null){if(!a)return e??null;const h={...o};return delete h[r],Object.keys(h).some(p=>p!==".priority")?(i&&Object.hasOwn(e,".priority")&&(h[".priority"]=e[".priority"]),h):null}const d=a?{...o}:{};return d[r]=u,i&&a&&Object.hasOwn(e,".priority")&&(d[".priority"]=e[".priority"]),d}function Wh(e,t){try{const n=Zv(e,t);return typeof n!="boolean"?{holds:!1,runtimeError:"Expression must evaluate to a boolean."}:{holds:n}}catch(n){if(n instanceof ee)return{holds:!1,runtimeError:n.message};throw n}}function Zs(e,t,n,r,s){const i={path:e.path,kind:t,conditionText:n.raw,verdict:"UNSUPPORTED",pathVariableBindings:{...r}};if(s===void 0){const o=n.parsed.errors.map(a=>a.message).join("; ");i.message=o===""?"The simulator cannot evaluate this expression":`The simulator cannot evaluate this expression: ${o}`}else s.runtimeError!==void 0?(i.verdict="ERROR",i.message=s.runtimeError):i.verdict=s.holds?"ALLOW":"DENY";return i}function D_(e){const t=e.val();return t===null||typeof t!="object"?[]:Object.keys(t)}function T_(e,t){const n=vi(e),r=R_(e.uid,n?.token??{},t),s={uid:e.uid,token:r},i=r.firebase,a=(typeof i=="object"&&i!==null?i:{}).sign_in_provider;return typeof a=="string"&&(s.provider=a),s}function Ml(e,t,n,r,s,i,o,a){let l=null;const u=new Set;if(a&&a.length>0)for(const m of a)u.add(m.path.split("/").filter(Boolean).join("/"));else u.add(o.filter(Boolean).join("/"));const d=Array.from(u).map(m=>m.split("/").filter(Boolean));function h(m,g,b,w,x){if(b.exists()){const S=m.validate;if(S)if(!S.parsed.valid)i.push(Zs(m,"validate",S,w,void 0)),l||(l={node:m,rule:S,bindings:w,unsupported:!0});else{const k=Wh(S,s(g,b,w));if(i.push(Zs(m,"validate",S,w,k)),!k.holds)return{node:m,rule:S,bindings:w,runtimeError:k.runtimeError}}}const _=d.some(S=>S.length<=x.length&&S.every((k,N)=>k===x[N]))?D_(b):f(x);for(const S of _){const k=Hh(m,S);if(k===void 0)continue;const N=k.variable===void 0?w:{...w,[k.variable]:S},O=h(k.child,g.child(S),b.child(S),N,[...x,S]);if(O)return O}return null}function f(m){const g=new Set;for(const b of d)b.length>m.length&&m.every((x,v)=>x===b[v])&&g.add(b[m.length]);return g}return h(e,t,n,r,[])??l}function zh(e,t,n,r=0){const s=[{node:e,pathVariableBindings:{...n},depth:r}];if(t.length===0)return s;const i=Hh(e,t[0]);if(i===void 0)return s;const o=i.variable===void 0?{...n}:{...n,[i.variable]:t[0]};return s.push(...zh(i.child,t.slice(1),o,r+1)),s}function M_(e){const t=e.path.split("/").filter(Boolean);return t[t.length-1]}function Hh(e,t){let n;for(const r of e.children){const s=M_(r);if(s===void 0)continue;if(s===t)return{child:r};s.startsWith("$")&&n===void 0&&(n={child:r,variable:s})}return n}function Ll(e,t){let n="Validation rule evaluated to false";return e.unsupported?n=`Validation rule at '${e.node.path}' contains an expression the simulator cannot evaluate: ${e.rule.raw}. It was not evaluated; production may reject this write.`:e.runtimeError!==void 0&&(n=`Validation rule at '${e.node.path}' failed at evaluation: ${e.runtimeError}`),{success:!0,data:{allowed:!1,unsupported:e.unsupported===!0,matchedPath:e.node.path,matchedRule:e.rule.raw,reason:n,pathVariableBindings:e.bindings,trace:t}}}function L_(e,t){if(e!=="read")return null;const n=t?.equalTo??null;return{orderByChild:t?.orderByChild??null,orderByKey:t?.orderByKey===!0,orderByValue:t?.orderByValue===!0,orderByPriority:t?.orderByPriority===!0,equalTo:n,limitToFirst:t?.limitToFirst??null,limitToLast:t?.limitToLast??null,startAt:t?.startAt??n,endAt:t?.endAt??n}}class U_{execute(t,n){const r=S_.safeParse(n);if(!r.success)return{success:!1,error:{code:"INVALID_INPUT",message:r.error.message,recoverable:!0}};const s=r.data.query===void 0?null:Fh(r.data.query);if(s!==null)return{success:!1,error:{code:"INVALID_INPUT",message:s,recoverable:!0}};const{operation:i,path:o,auth:a,mockData:l,newData:u,updates:d,query:h}=r.data,f=r.data.now??Date.now(),p=[];try{const m=o.split("/").filter(Boolean),g=t,b=zh(g,m,{}),w=new Bt(l,"/");let x=l;i!=="read"&&(x=P_(l,o,m,u,d,f));const v=new Bt(x,"/");let _=null;a&&(_=T_(a,f));const S=L_(i,h),k=($,C,I)=>{const A={...I};return{auth:_,data:$,newData:C,root:w,now:f,pathVariableBindings:A,query:S}};if(i==="validate"){const $=Ml(g,w,v,{},k,p,m,d);if($)return Ll($,p);const C=p[p.length-1],I=[...b].reverse().find(A=>A.node.validate!==void 0);return!C&&!I?{success:!1,error:{code:"NO_MATCHING_RULE",message:`No 'validate' rule found for path '${o}'`,recoverable:!0}}:{success:!0,data:{allowed:!0,matchedPath:C?.path??I.node.path,matchedRule:C?.conditionText??I.node.validate.raw,reason:"Validation rules evaluated to true",pathVariableBindings:C?.pathVariableBindings??I.pathVariableBindings,trace:p}}}let N;const O=new Map;for(const $ of b){const C=$.node[i];if(!C)continue;if(!C.parsed.valid){p.push(Zs($.node,i,C,$.pathVariableBindings,void 0)),N||(N=$);continue}const I=m.slice(0,$.depth).join("/"),A=w.child(I),D=v.child(I),T=Wh(C,k(A,D,$.pathVariableBindings));if(p.push(Zs($.node,i,C,$.pathVariableBindings,T)),T.runtimeError!==void 0&&O.set($,T.runtimeError),T.holds){if(i==="write"){const W=Ml(g,w,v,{},k,p,m,d);if(W)return Ll(W,p)}return{success:!0,data:{allowed:!0,matchedPath:$.node.path,matchedRule:C.raw,reason:"Rule expression evaluated to true",pathVariableBindings:$.pathVariableBindings,trace:p}}}}if(N){const $=N.node[i];return{success:!0,data:{allowed:!1,unsupported:!0,matchedPath:N.node.path,matchedRule:$.raw,reason:`'${i}' rule at '${N.node.path}' contains an expression the simulator cannot evaluate: ${$.raw} — not evaluated; production may reject or allow this ${i}.`,pathVariableBindings:N.pathVariableBindings,trace:p}}}const P=[...b].reverse().find($=>$.node[i]!==void 0);if(P===void 0)return{success:!0,data:{allowed:!1,matchedPath:"",matchedRule:"",reason:`No '${i}' rule on '${o}' or its ancestors grants access; denied by default`,pathVariableBindings:b[b.length-1].pathVariableBindings,trace:p}};const R=P.node[i],j=O.get(P),E=j===void 0?"evaluated to false":`failed at evaluation: ${j}`;return{success:!0,data:{allowed:!1,matchedPath:P.node.path,matchedRule:R.raw,reason:`No '${i}' rule grants access; the deepest, at '${P.node.path}', ${E}`,pathVariableBindings:P.pathVariableBindings,trace:p}}}catch(m){return{success:!1,error:{code:"EVALUATION_ERROR",message:m instanceof Error?m.message:String(m),recoverable:!1}}}}}function Kh(e,t,n=[]){try{const r=dx(e),s=r.valid?__(e,t,n):r.errors,i=r.valid?ix(e,t):[];return{raw:e,parsed:{...r,valid:r.valid&&s.length===0,errors:s,warnings:i}}}catch(r){if(!(r instanceof RangeError))throw r;return{raw:e,parsed:{raw:e,valid:!1,errors:[{code:"PARSE_ERROR",message:Xr}],warnings:[],referencedIdentifiers:[]}}}}function Gh(e,t,n){const r={path:t,pathVariables:[...n],children:[]};for(const[o,a]of[[".read","read"],[".write","write"],[".validate","validate"]]){const l=e[o];if(l!==void 0)if(typeof l=="boolean"||typeof l=="string"||l===null)r[a]=Kh(String(l),a,n);else{const u=JSON.stringify(l)??String(l);r[a]={raw:u,parsed:{raw:u,valid:!1,errors:[],warnings:[],referencedIdentifiers:[]}}}}const s=e[".indexOn"];s!==void 0&&(r.indexOn=Array.isArray(s)?s.map(String):[String(s)]);const i=bh(t,e);i.length>0&&(r.structure=i);for(const[o,a]of Object.entries(e)){if(o.startsWith(".")||Rv.has(o)||typeof a!="object"||a===null||Array.isArray(a))continue;const l=t==="/"?`/${o}`:`${t}/${o}`,u=o.startsWith("$")?[...n,o]:[...n];r.children.push(Gh(a,l,u))}return r}function Jh(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 Gh(t.rules,"/",[])}function no(e){return e==="true"?!0:e==="false"?!1:e}function Yh(e){const t={};e.read&&(t[".read"]=no(e.read.raw)),e.write&&(t[".write"]=no(e.write.raw)),e.validate&&(t[".validate"]=no(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]]=Yh(n)}return t}function B_(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:Yh(e)}}function fc(e,t){return new U_().execute(e,t)}function F_(e,t){let n=[e];for(const r of t){const s=[];for(const i of n)for(const o of i.children){const a=o.path.split("/").filter(Boolean),l=a[a.length-1];l&&(l===r||l.startsWith("$"))&&s.push(o)}if(n=s,n.length===0)break}return n}function Qh(e,t,n){return F_(e,t).filter(r=>r.indexOn?.some(s=>s===n||s.split("/").filter(Boolean).join("/")===n))}function V_(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"?e:null}function q_(e){return e.kind==="value"?".value":e.path.split("/").filter(Boolean).join("/")}function W_(e){const t={orderByKey:e.orderBy?.kind==="key",orderByValue:e.orderBy?.kind==="value",orderByPriority:e.orderBy?.kind==="priority"};e.orderBy?.kind==="child"&&(t.orderByChild=e.orderBy.path);for(const n of e.bounds){const r=V_(n.value);n.kind==="equalTo"?t.equalTo=r:n.kind==="startAt"||n.kind==="startAfter"?t.startAt=r:(n.kind==="endAt"||n.kind==="endBefore")&&(t.endAt=r)}return e.limit?.kind==="limitToFirst"?t.limitToFirst=e.limit.n:e.limit?.kind==="limitToLast"&&(t.limitToLast=e.limit.n),t}function Je(e){const t=new Error("PERMISSION_DENIED: Permission denied");return t.code="PERMISSION_DENIED",hc(t,e)}function hc(e,t){return Object.assign(e,{denialContext:t})}class z_{clock;compiled=null;defaultPolicy="deny";constructor(t=new Jf){this.clock=t}setDefaultPolicy(t){this.defaultPolicy=t}setRules(t){if(t===null){this.compiled=null;return}this.compiled=Jh(t)}hasRules(){return this.compiled!==null}missingQueryIndex(t,n){if(this.compiled===null||n.orderBy===null||n.orderBy.kind==="key"||n.orderBy.kind==="priority")return null;const r=q_(n.orderBy);return Qh(this.compiled,t.split("/").filter(Boolean),r).length>0?null:r}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."]};let i=null;r.auth!==null&&(i={uid:r.auth.uid,token:r.auth.token??{}},r.auth.tenant!==void 0&&(i.tenant=r.auth.tenant));let o=r.query;o===void 0&&r.querySpec!==void 0&&(o=W_(r.querySpec));const a=fc(this.compiled,{operation:t,path:n==="/"?"/":n,auth:i,mockData:r.mockData,newData:r.newData,updates:r.updates,query:o,now:r.now??this.clock.now()});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,trace:a.data.trace}:{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,trace:a.data.trace}:{check:"no-rule",reasons:[a.error.message],errorCode:a.error.code,errorMessage:a.error.message}}}class H_{tree=new zx;rules;activeRules=null;valueListeners=new Set;childListeners=new Set;priorities=new o_;mutations=new s_;events;writeSubscribers=new Set;resetGeneration=0;clock;constructor(t,n){this.events=new i_(t,n),this.clock=t?Te(t):new Jf,this.rules=new z_(this.clock)}rulesSnapshot(){const t=[...this.priorities.entries()].map(([n,r])=>({segments:V(n),priority:r}));return mt(this.tree.snapshot(),t)}prioritiesBelow(t){const n=V(t),r=[];for(const[s,i]of this.priorities.entries()){const o=V(s);o.length>n.length&&n.every((l,u)=>o[u]===l)&&r.push({segments:o.slice(n.length),priority:i})}return r}unspecifiedIndexWarning(t,n){if(e_(n))return null;const r=this.rules.missingQueryIndex(t,n);return r===null?null:t_(t,r)}warnOnUnspecifiedIndex(t,n){if(n===void 0||Kr.isSilenced())return;const r=this.unspecifiedIndexWarning(t,n);r!==null&&n_(r)}notifyWrite(){for(const t of this.writeSubscribers)try{t()}catch{}}}function Xh(e,t){if(e===t)return 0;if(e===null)return-1;if(t===null)return 1;const i=Ul(e),o=Ul(t);return i!==o?i-o:typeof e=="number"&&typeof t=="number"?e<t?-1:e>t?1:0:typeof e=="boolean"&&typeof t=="boolean"?e===!0?1:-1:typeof e=="string"&&typeof t=="string"?e<t?-1:e>t?1:0:0}function Ul(e){return e===null?0:typeof e=="boolean"?1:typeof e=="number"?2:typeof e=="string"?3:4}const K_=/^-?(0*)\d{1,10}$/,G_=-2147483648,J_=2147483647;function Bl(e){if(K_.test(e)){const n=Number(e);if(n>=G_&&n<=J_)return n}return null}function ei(e,t){if(e===t)return 0;const r=Bl(e),s=Bl(t),i=r!==null,o=s!==null;if(i){if(o){const l=r-s;return l===0?e.length-t.length:l}return-1}else if(o)return 1;return e<t?-1:1}function Ar(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 o=s.path.split("/").filter(l=>l.length>0);let a=n;for(const l of o){if(a===null||typeof a!="object"||Array.isArray(a))return null;a=a[l]??null}return a}}}function ln(e,t,n=()=>null){if(e===null||typeof e!="object"||Array.isArray(e))return[];let i=Object.entries(e).map(([u,d])=>({key:u,value:d,priority:n(u)}));const o=t.orderBy?.kind==="key";i.sort((u,d)=>{if(o)return ei(u.key,d.key);const h=Ar(t.orderBy,u.key,u.value,u.priority),f=Ar(t.orderBy,d.key,d.value,d.priority),p=Xh(h,f);return p!==0?p:ei(u.key,d.key)});for(const u of t.bounds)i=i.filter(d=>Y_(u,d,t.orderBy));const a=t.limit;if(a!==null){const u=a.n;if(a.kind==="limitToFirst")i=i.slice(0,u);else{if(u>=i.length)return i;i=i.slice(i.length-u)}}return i}function Y_(e,t,n){const r=n?.kind==="key";let s;if(r)s=ei(t.key,String(e.value));else{const u=Ar(n,t.key,t.value,t.priority);s=Xh(u,e.value)}const i=u=>ei(t.key,u),o=s>0,a=s<0,l=s!==0;switch(e.kind){case"startAt":{if(o)return!0;if(a)return!1;const u=e.key;return u===void 0||i(u)>=0}case"startAfter":{if(o)return!0;if(a)return!1;const u=e.key;return u===void 0?!1:i(u)>0}case"endAt":{if(a)return!0;if(o)return!1;const u=e.key;return u===void 0||i(u)<=0}case"endBefore":{if(a)return!0;if(o)return!1;const u=e.key;return u===void 0?!1:i(u)<0}case"equalTo":{if(l)return!1;const u=e.key;return u===void 0||i(u)===0}}}function Fl(e){return e.length===0?null:Object.fromEntries(e.map(({key:t,value:n})=>[t,n]))}function Q_(e,t){return e.length===t.length&&e.every((n,r)=>{const s=t[r];return n.key===s.key&&n.priority===s.priority&&cn(n.value,s.value)})}function pc(e,t){const n=new Error(`permission_denied at ${G(V(e))}: Client doesn't have permission to access the desired data.`);return n.code="PERMISSION_DENIED",hc(n,t)}class X_{state;constructor(t){this.state=t}onValue(t,n,r,s,i,o,a){const l=this.state.clock.now(),u=this.state.rules.evaluate("read",n==="/"?"/":n,{auth:t,mockData:this.state.rulesSnapshot(),querySpec:s});if(u.check!=="allow"){let d;s&&(d={query:s}),this.state.events.operation(t,"listen",n,nt(u.check),u,{at:l,durationMs:this.state.clock.now()-l,request:d,origin:"listener"});const h=Dn(u),f=Pe(u,t,"listen",n,d);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:u.reasons},reasons:u.reasons,rules:h}),i)return o&&o(),queueMicrotask(()=>{i(pc(n,f))}),()=>{};throw Je(f)}return this.state.warnOnUnspecifiedIndex(n,s),this.attach(t,n,r,s,{origin:"listener",result:"allow",evaluation:u,at:l},i,o,a)}adminOnValue(t,n,r){return this.state.warnOnUnspecifiedIndex(t,r),this.attach(null,t,n,r,{origin:"admin",result:"not-applicable",evaluation:void 0,at:this.state.clock.now()})}attach(t,n,r,s,i,o,a,l){const u=this.state.events.nextListenerId(),d=Yf(l?.owner,l?.owners);this.state.events.operation(t,"listen",n,i.result,i.evaluation,{at:i.at,durationMs:this.state.clock.now()-i.at,request:s?{query:s}:void 0,origin:i.origin});const h={id:u,auth:t,cb:r,path:n,query:s,cancelCallback:o,onCanceled:a,admin:i.origin==="admin",owners:d};if(this.state.valueListeners.add(h),this.state.events.listener("attach",h,t,{event:"value",result:"allow",detail:s?{query:s}:void 0,...s?{query:s}:{},owners:d}),s){const f=ln(this.state.tree.read(n),s,this.state.priorities.forChild(n));h.lastWindow=f,this.deliverInitial(h,{val:Fl(f),exists:f.length>0,key:this.key(n),rows:f},{initial:!0,query:!0})}else{const f=this.snapshot(n);h.lastValue=f.val,h.lastPriorityState=this.state.priorities.stateAtOrBelow(n),this.deliverInitial(h,f,{initial:!0})}return()=>{this.state.valueListeners.delete(h),this.state.events.listener("detach",h,t,{event:"value"})}}fanOut(t){if(this.state.valueListeners.size===0)return;const n=t.map(r=>G(V(r)));for(const r of this.state.valueListeners){const s=G(V(r.path));if(!n.some(a=>Z_(s,a)))continue;if(r.query){const a=ln(this.state.tree.read(r.path),r.query,this.state.priorities.forChild(r.path));if(Q_(r.lastWindow??[],a)){this.state.events.listener("suppressed",r,r.auth,{event:"value",reason:"no-op",detail:{query:!0}});continue}r.lastWindow=a,this.deliver(r,{val:Fl(a),exists:a.length>0,key:this.key(r.path),rows:a},{query:!0});continue}const i=this.snapshot(r.path),o=this.state.priorities.stateAtOrBelow(r.path);if(cn(r.lastValue??null,i.val)&&r.lastPriorityState===o){this.state.events.listener("suppressed",r,r.auth,{event:"value",reason:"no-op"});continue}r.lastValue=i.val,r.lastPriorityState=o,this.deliver(r,i,{})}}off(t,n){const r=G(V(t));for(const s of[...this.state.valueListeners])G(V(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=V(t);return n.length===0?null:n[n.length-1]}deliver(t,n,r){let s,i=!1;const o=Ws(()=>{try{t.cb(n)}catch(a){s=a,i=!0}});this.state.events.listener("delivery",t,t.auth,{event:"value",size:n.rows?.length??(n.exists?1:0),sample:n.val,detail:r,owners:Qo(o)}),i&&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){let s,i=!1;const o=Ws(()=>{try{t.cb(n)}catch(a){s=a,i=!0}});if(!i){this.state.events.listener("delivery",t,t.auth,{event:"value",size:n.rows?.length??(n.exists?1:0),sample:n.val,detail:r,owners:Qo(o)});return}this.state.events.listener("errored",t,t.auth,{event:"value",result:"error",error:{message:s instanceof Error?s.message:String(s)},detail:r})}}function Qo(e){if(e!==void 0)return[e]}function Z_(e,t){if(e===t||e==="/")return!0;const n=`${e}/`,r=t==="/"?"/":`${t}/`;return t.startsWith(n)||e.startsWith(r)}function Vl(e,t){const n=G(V(t)),r=n==="/"?"/":`${n}/`,s={};for(const[i,o]of Object.entries(e))(i===n||i.startsWith(r))&&(s[i]=o);return s}function Zn(e,t){const n=e.findIndex(r=>r.key===t);return n>0?e[n-1].key:null}function hs(e,t){const n=e.findIndex(r=>r.key===t);return n>0?e[n-1].key:null}class eS{state;constructor(t){this.state=t}onChild(t,n,r,s,i,o,a){const l=this.state.clock.now(),u=this.state.events.nextListenerId(),d=this.state.rules.evaluate("read",r==="/"?"/":r,{auth:t,mockData:this.state.rulesSnapshot(),querySpec:i});if(d.check!=="allow"){this.state.events.operation(t,"listen",r,nt(d.check),d,{at:l,durationMs:this.state.clock.now()-l,origin:"listener",detail:{event:n},request:i?{query:i}:void 0});const h=Dn(d),f=Pe(d,t,"listen",r);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:h}),o)return a&&a(),queueMicrotask(()=>{o(pc(r,f))}),()=>{};throw Je(f)}return this.state.warnOnUnspecifiedIndex(r,i),this.attach(u,t,n,r,s,i,{origin:"listener",result:"allow",evaluation:d,at:l},o,a)}adminOnChild(t,n,r,s){return this.state.warnOnUnspecifiedIndex(n,s),this.attach(this.state.events.nextListenerId(),null,t,n,r,s,{origin:"admin",result:"not-applicable",evaluation:void 0,at:this.state.clock.now()})}attach(t,n,r,s,i,o,a,l,u){const d=Yf();this.state.events.operation(n,"listen",s,a.result,a.evaluation,{at:a.at,durationMs:this.state.clock.now()-a.at,request:o?{query:o}:void 0,origin:a.origin,detail:{event:r}});const h={id:t,auth:n,event:r,path:s,cb:i,spec:o,cancelCallback:l,onCanceled:u,admin:a.origin==="admin"};if(this.state.childListeners.add(h),this.state.events.listener("attach",h,n,{event:r,result:"allow",detail:o?{query:o}:void 0,...o?{query:o}:{},owners:d}),o){const f=ln(this.state.tree.read(s),o,this.state.priorities.forChild(s));if(h.lastWindow=f,h.lastPriorities=this.state.priorities.atOrBelow(s),r==="child_added")for(const{key:p,value:m}of f)this.deliver(h,{key:p,val:m,previousChildName:Zn(f,p)},{initial:!0,query:!0})}else if(r==="child_added")for(const{key:f,val:p}of this.directChildren(s)){const m=this.directChildren(s);this.deliver(h,{key:f,val:p,previousChildName:hs(m,f)},{initial:!0})}return()=>{this.state.childListeners.delete(h),this.state.events.listener("detach",h,n,{event:r})}}off(t,n,r){const s=G(V(t));for(const i of[...this.state.childListeners])n!==void 0&&i.event!==n||G(V(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=G(V(n.path));t.has(r)||t.set(r,{children:this.childStates(r),priorities:this.state.priorities.atOrBelow(r)})}return t}fanOut(t){if(this.state.childListeners.size===0)return;const n=new Map;for(const r of this.state.childListeners){if(r.spec){this.fanOutQuery(r);continue}const s=G(V(r.path)),i=n.get(s)??[];i.push(r),n.set(s,i)}for(const[r,s]of n){const i=t.get(r),o=i?.children??new Map,a=i?.priorities??{},l=this.childStates(r),u=[...l].map(([f,{val:p}])=>({key:f,val:p})),d=[...o].map(([f,{val:p}])=>({key:f,val:p})),h={child_added:[],child_changed:[],child_removed:[],child_moved:[]};for(const[f,{val:p,priority:m}]of l){const g=o.get(f);if(g===void 0){h.child_added.push({key:f,val:p,previousChildName:hs(u,f)});continue}const b=hs(u,f);cn(g.val,p)||h.child_changed.push({key:f,val:p,previousChildName:b}),g.priority!==m&&h.child_moved.push({key:f,val:p,previousChildName:b})}for(const[f,{val:p}]of o)l.has(f)||h.child_removed.push({key:f,val:p,previousChildName:hs(d,f),priorities:Vl(a,G([...V(r),f]))});for(const f of s)for(const p of h[f.event])this.deliver(f,p,{})}}count(){return this.state.childListeners.size}directChildren(t){const n=this.state.tree.read(t);return n===null||typeof n!="object"||Array.isArray(n)?[]:ln(n,{orderBy:{kind:"priority"},bounds:[],limit:null},this.state.priorities.forChild(t)).map(({key:r,value:s})=>({key:r,val:s}))}childStates(t){const n=this.state.priorities.forChild(t);return new Map(this.directChildren(t).map(({key:r,val:s})=>[r,{val:s,priority:n(r)}]))}fanOutQuery(t){const n=t.lastWindow??[],r=ln(this.state.tree.read(t.path),t.spec,this.state.priorities.forChild(t.path));t.lastWindow=r;const s=t.lastPriorities??{};t.lastPriorities=this.state.priorities.atOrBelow(t.path);const i=new Map(n.map(l=>[l.key,l.value])),o=new Map(r.map(l=>[l.key,l.value])),a=[];if(t.event==="child_added")for(const l of r)i.has(l.key)||a.push({key:l.key,val:l.value,previousChildName:Zn(r,l.key)});else if(t.event==="child_changed")for(const l of r)i.has(l.key)&&!cn(i.get(l.key),l.value)&&a.push({key:l.key,val:l.value,previousChildName:Zn(r,l.key)});else if(t.event==="child_removed")for(const l of n)o.has(l.key)||a.push({key:l.key,val:l.value,previousChildName:Zn(n,l.key),priorities:Vl(s,G([...V(t.path),l.key]))});else if(t.spec?.orderBy&&t.spec.orderBy.kind!=="key"){const l=new Map(n.map(u=>[u.key,u]));for(const u of r){const d=l.get(u.key);if(!d)continue;const h=Ar(t.spec.orderBy,d.key,d.value,d.priority),f=Ar(t.spec.orderBy,u.key,u.value,u.priority);cn(h,f)||a.push({key:u.key,val:u.value,previousChildName:Zn(r,u.key)})}}for(const l of a)this.deliver(t,l,{query:!0})}deliver(t,n,r){let s,i=!1;const o=Ws(()=>{try{t.cb(n)}catch(a){s=a,i=!0}});this.state.events.listener("delivery",t,t.auth,{event:t.event,size:1,sample:r.query?{key:n.key,val:n.val}:{key:n.key,val:n.val,previousChildName:n.previousChildName},detail:r,owners:Qo(o)}),i&&this.state.events.listener("errored",t,t.auth,{event:t.event,result:"error",error:{message:s instanceof Error?s.message:String(s)},detail:r})}}class tS{state;values;children;constructor(t,n,r){this.state=t,this.values=n,this.children=r}adminSet(t,n){Lt(n);const r=this.state.tree.read(t);if(r===null)return;const s=this.state.clock.now(),i=this.state.priorities.get(t);this.state.events.operation(null,"setPriority",t,"not-applicable",void 0,{at:s,origin:"admin",request:{data:n},resourceBefore:{data:r,exists:!0},resourceAfter:{data:r,exists:!0},detail:{admin:!0,priority:n,priorPriority:i}});const o=this.children.snapshotParents(),a=i!==n;this.state.priorities.set(t,n),this.state.mutations.mark(t),a&&this.values.fanOut([t]),this.children.fanOut(o),this.state.events.commit(null,"setPriority",t,{data:n,priorState:i,nextState:n,replay:{requestTime:s},detail:{admin:!0,priority:n,priorPriority:i}}),this.state.notifyWrite()}validate(t,n,r){Lt(r);const s=this.evaluation(t,n,r);if(s.check!=="allow")throw Je(Pe(s,t,"setPriority",n,{data:r}))}evaluation(t,n,r){const s=this.state.tree.read(n);return this.state.rules.evaluate("write",n==="/"?"/":n,{auth:t,mockData:this.state.rulesSnapshot(),newData:mt(s,[{segments:[],priority:r},...this.state.prioritiesBelow(n)])})}set(t,n,r){Lt(r);const s=this.state.tree.read(n),i=this.state.clock.now(),o=this.evaluation(t,n,r),a=this.state.priorities.get(n),l={at:i,durationMs:this.state.clock.now()-i,request:{data:r},resourceBefore:{data:s,exists:s!==null},resourceAfter:{data:s,exists:s!==null},detail:{priority:r,priorPriority:a}};if(o.check!=="allow")throw this.state.events.operation(t,"setPriority",n,nt(o.check),o,l),Je(Pe(o,t,"setPriority",n,{data:r}));if(this.state.events.operation(t,"setPriority",n,"allow",o,l),this.state.events.commit(t,"setPriority",n,{data:r,priorState:a,nextState:s===null?null:r,replay:{requestTime:i},detail:{priority:r,priorPriority:a}}),s===null)return;const u=this.children.snapshotParents(),d=a!==r;this.state.priorities.set(n,r),this.state.mutations.mark(n),d&&this.values.fanOut([n]),this.children.fanOut(u),d&&this.state.events.mutation(t,"setPriority",yt(n),{before:a,after:r,detail:{priorityMetadata:!0}}),this.state.notifyWrite()}}function ql(e){return e.length===0?null:Object.fromEntries(e.map(({key:t,value:n})=>[t,n]))}function ur(e,t,n,r,s=!1){const i=V(t);for(let a=0;a<i.length;a++){const l=G(i.slice(0,a)),u=e.tree.read(l);if(u!==null&&typeof u!="object"){const d=e.priorities.get(l);return{overwrittenAncestor:{path:l,state:mt(u,[{segments:[],priority:d}])}}}}const o=e.prioritiesBelow(t);return o.length>0?{priorExport:mt(n,[{segments:[],priority:r},...o])}:s&&r!==null?{priorPriority:r}:{}}const nS=/\broot\b/,rS=/\bdata\b/,sS=/\bparent\b/;function iS(e,t){return e===t||e==="/"||t==="/"?!0:t.startsWith(`${e}/`)||e.startsWith(`${t}/`)}function Wl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function oS(e,t){if(!t.startsWith(".")&&Object.hasOwn(e,t)&&Wl(e[t]))return e[t];for(const[n,r]of Object.entries(e))if(n.startsWith("$")&&Wl(r))return r}function aS(e,t,n){return typeof e!="string"?!1:nS.test(e)?!0:rS.test(e)?sS.test(e)||e.includes("[")?!0:n.some(r=>iS(t,r)):!1}function zl(e,t,n){const r=V(t);let s=e;for(let i=0;i<=r.length&&s!==void 0;i++){const o=G(r.slice(0,i));if(aS(s[".read"],o,n))return!0;i<r.length&&(s=oS(s,r[i]))}return!1}class Zh{state;values;children;priorityWrites;constructor(t,n,r){this.state=t,this.values=n,this.children=r,this.priorityWrites=new tS(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,en(ht(r,this.state.clock.now()),n==="/"?"":n));const{priority:s,nested:i}=tn(r,null);this.state.priorities.replace(n,this.state.tree.read(n)===null?null:s),this.storeNestedPriorities(n,i)}this.state.mutations.mark("/"),this.cancelDeniedListeners(["/"]),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,{at:this.state.clock.now(),origin:"admin",resourceBefore:{data:n,exists:n!==null}}),n}adminGetQuery(t,n){const r=this.state.rules.missingQueryIndex(t,n);if(r!==null)throw this.state.events.operation(null,"get",t,"error",void 0,{at:this.state.clock.now(),origin:"admin",request:{query:n},detail:{failure:"missing-index"}}),Cl(t,r);const s=ln(this.state.tree.read(t),n,this.state.priorities.forChild(t));return this.state.events.operation(null,"get",t,"not-applicable",void 0,{at:this.state.clock.now(),origin:"admin",request:{query:n},resourceBefore:{data:ql(s),exists:s.length>0}}),s}adminSet(t,n){this.adminSetWithPriority(t,n,null,!1)}adminSetWithPriority(t,n,r,s=!0){const i=this.state.clock.now(),o=this.state.tree.read(t),a=en(ht(n,i,o),t==="/"?"":t),l=tn(n,r);r=l.priority,s||=l.inline,Lt(r);const u=a===null?"remove":"set";this.state.events.operation(null,u,t,"not-applicable",void 0,{at:i,origin:"admin",request:{data:n,resourceData:n},resourceBefore:{data:o,exists:o!==null},resourceAfter:{data:a,exists:a!==null}});const d=this.children.snapshotParents(),h=this.state.priorities.get(t),f=ur(this.state,t,o,h);this.state.tree.write(t,a),this.state.priorities.replace(t,a===null?null:r,g=>this.state.tree.read(g)!==null),this.storeNestedPriorities(t,l.nested),this.changed([t],d);const p=this.state.tree.read(t),m=s||h!==null;this.state.events.commit(null,p===null?"remove":"set",t,{data:n,priorState:o,nextState:p,replay:{requestTime:i},detail:{admin:!0,...m?{priority:r,priorPriority:h}:{},...f}}),this.state.notifyWrite()}adminUpdate(t,n){const r=this.state.clock.now(),s=this.state.tree.read(t),i=this.state.priorities.get(t),o=ur(this.state,t,s,i,!0),a=this.resolvePatch(t,n,r),l=this.patchPriorities(t,n),u=Object.keys(n).some(p=>p.includes("/"));this.state.events.operation(null,"update",t,"not-applicable",void 0,{at:r,origin:"admin",request:{data:n,resourceData:n},resourceBefore:{data:s,exists:s!==null},detail:u?{admin:!0,multiPath:!0,paths:Object.keys(a)}:{admin:!0,multiPath:!1,keys:Object.keys(n)}});const d=this.children.snapshotParents();u?this.state.tree.multiUpdate(a):this.state.tree.shallowUpdate(t,Object.fromEntries(Object.entries(a).map(([p,m])=>[V(p).at(-1),m])));const h=p=>this.state.tree.read(p)!==null;this.state.priorities.applyUpdate(Object.entries(a).map(([p,m])=>({path:p,value:m})),h),this.storePatchPriorities(l),this.changed(Object.keys(a),d);const f=u?{admin:!0,multiPath:!0,paths:Object.keys(a),...o}:{admin:!0,multiPath:!1,keys:Object.keys(n),...o};this.state.events.commit(null,"update",t,{data:n,priorState:s,nextState:this.state.tree.read(t),replay:{requestTime:r},detail:f}),this.state.notifyWrite()}adminRemove(t){this.adminSet(t,null)}adminSetPriority(t,n){this.priorityWrites.adminSet(t,n),this.cancelDeniedListeners([t])}get(t,n){const r=this.state.clock.now(),s=this.state.tree.read(n),i=this.readEvaluation(t,n);if(i.check!=="allow")throw this.state.events.operation(t,"get",n,nt(i.check),i,{at:r,durationMs:this.state.clock.now()-r,resourceBefore:{data:s,exists:s!==null}}),Je(Pe(i,t,"get",n));return this.state.events.operation(t,"get",n,"allow",i,{at:r,durationMs:this.state.clock.now()-r,resourceBefore:{data:s,exists:s!==null}}),this.state.tree.read(n)}getQuery(t,n,r){const s=this.state.clock.now(),i=this.readEvaluation(t,n,r);if(i.check!=="allow")throw this.state.events.operation(t,"get",n,nt(i.check),i,{at:s,durationMs:this.state.clock.now()-s,request:{query:r}}),Je(Pe(i,t,"get",n,{query:r}));const o=this.state.rules.missingQueryIndex(n,r);if(o!==null)throw this.state.events.operation(t,"get",n,"error",void 0,{at:s,durationMs:this.state.clock.now()-s,request:{query:r},detail:{failure:"missing-index"}}),Cl(n,o);const a=ln(this.state.tree.read(n),r,this.state.priorities.forChild(n));return this.state.events.operation(t,"get",n,"allow",i,{at:s,durationMs:this.state.clock.now()-s,request:{query:r},resourceBefore:{data:ql(a),exists:a.length>0}}),a}set(t,n,r){this.setInternal(t,n,r,"set",null,!1)}setWithPriority(t,n,r,s){Lt(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),this.cancelDeniedListeners([n])}validatePriority(t,n,r){this.priorityWrites.validate(t,n,r)}validateRead(t,n,r){const s=this.readEvaluation(t,n,r);if(s.check!=="allow")throw Je(Pe(s,t,"get",n,r?{query:r}:{}))}validateSet(t,n,r,s=null){const{evaluation:i,resolved:o}=this.setCheck(t,n,r,s);if(i.check!=="allow")throw Je(Pe(i,t,"onDisconnect",n,{data:o}))}validateUpdate(t,n,r){const s=this.updateCheck(t,n,r);if(s!==null)throw Je(Pe(s.evaluation,t,"onDisconnect",s.path,{data:s.value}))}registerDisconnect(t,n){const r=this.state.clock.now(),s=`onDisconnect.${n.kind}`,i=n.kind==="set"?n.value:n.kind==="update"?n.values:null,o=n.kind==="set"&&n.priority!==null?{priority:n.priority}:void 0;let a,l=null;if(n.kind==="update"){if(Object.keys(n.values).length===0)return;const d=this.updateEvaluations(t,n.path,n.values),h=d.find(f=>f.evaluation.check!=="allow");a=(h??d.at(-1)).evaluation,h!==void 0&&(l={path:h.update.path,data:h.update.value})}else{const d=n.kind==="set"?n.value:null,h=this.setCheck(t,n.path,d,n.kind==="set"?n.priority:null);a=h.evaluation,a.check!=="allow"&&(l={path:n.path,data:h.resolved})}const u={at:r,durationMs:this.state.clock.now()-r,request:{data:i,resourceData:i},detail:o};if(l!==null)throw this.state.events.operation(t,s,n.path,nt(a.check),a,u),Je(Pe(a,t,"onDisconnect",l.path,{data:l.data}));this.state.events.operation(t,s,n.path,"allow",a,u)}setCheck(t,n,r,s){const i=this.state.clock.now(),o=en(ht(r,i,this.state.tree.read(n)),n==="/"?"":n),a=tn(r,s);Lt(a.priority);const l=mt(o,[{segments:[],priority:a.priority},...a.nested]);return{evaluation:this.writeEvaluation(t,n,l,i),resolved:o}}updateCheck(t,n,r){if(Object.keys(r).length===0)return null;for(const{update:s,evaluation:i}of this.updateEvaluations(t,n,r))if(i.check!=="allow")return{evaluation:i,path:s.path,value:s.value};return null}updateEvaluations(t,n,r){const s=this.state.clock.now(),i=this.state.rulesSnapshot(),o=this.patchPriorities(n,r),a=Object.entries(r).map(([l,u])=>{const d=G([...V(n),...V(l)]),h=en(ht(u,s,this.state.tree.read(d)),d);return{path:d,value:mt(h,o.get(d)??[])}});return a.map(l=>({update:l,evaluation:this.state.rules.evaluate("write",l.path,{auth:t,mockData:i,newData:l.value,updates:a,now:s})}))}update(t,n,r){if(Object.keys(r).length===0)return;const s=this.state.clock.now(),i=this.resolvePatch(n,r,s),o=this.patchPriorities(n,r),a=Object.keys(r).some(v=>v.includes("/")),l=this.state.rulesSnapshot(),u=Object.entries(i).map(([v,_])=>({path:v,value:_})),d=u.map(v=>({path:v.path,value:mt(v.value,o.get(v.path)??[])})),h=Object.fromEntries(Object.entries(i).map(([v,_])=>[V(v).at(-1),_])),f=this.state.events.nextGroupId("update"),p=[];for(const[v,_]of u.entries()){const S=this.state.clock.now(),k=this.state.tree.read(_.path),N=this.state.rules.evaluate("write",_.path,{auth:t,mockData:l,newData:d[v].value,updates:d,now:s}),O={at:S,durationMs:this.state.clock.now()-S,origin:"batch",request:{data:_.value,resourceData:_.value},resourceBefore:{data:k,exists:k!==null},resourceAfter:{data:_.value,exists:_.value!==null},groupId:f,groupKind:"batch",detail:a?{multiPath:!0,rootPath:yt(n)}:{multiPath:!1,rootPath:yt(n),key:V(_.path).at(-1)}};if(N.check!=="allow"){const P={...O,detail:{...O.detail,patch:r}};throw this.state.events.operation(t,"update",_.path,nt(N.check),N,P),Je(Pe(N,t,"update",_.path,{data:_.value}))}p.push(()=>this.state.events.operation(t,"update",_.path,"allow",N,O))}for(const v of p)v();const m=this.state.tree.read(n),g=this.state.priorities.get(n),b=ur(this.state,n,m,g,!0),w=this.children.snapshotParents();a?this.state.tree.multiUpdate(i):this.state.tree.shallowUpdate(n,h),this.state.priorities.applyUpdate(u,v=>this.state.tree.read(v)!==null),this.storePatchPriorities(o),this.changed(Object.keys(i),w);const x=this.state.tree.read(n);this.state.events.commit(t,"update",n,{data:r,priorState:m,nextState:x,groupId:f,groupKind:"batch",replay:{requestTime:s},detail:a?{multiPath:!0,paths:Object.keys(i),...b}:{multiPath:!1,keys:Object.keys(h),...b}}),this.state.events.mutation(t,"update",yt(n),{after:a?i:h,detail:a?{multiPath:!0,paths:Object.keys(i)}:{multiPath:!1,keys:Object.keys(h)}}),this.state.notifyWrite()}setInternal(t,n,r,s,i,o){const a=this.state.clock.now(),l=en(ht(r,a,this.state.tree.read(n)),n==="/"?"":n),u=tn(r,i);i=u.priority,o||=u.inline,Lt(i);const d=this.state.tree.read(n),h=this.state.priorities.get(n),f=this.state.clock.now(),p=mt(l,[{segments:[],priority:i},...u.nested]),m=this.writeEvaluation(t,n,p,a),g={at:f,durationMs:this.state.clock.now()-f,request:{data:r,resourceData:r},resourceBefore:{data:d,exists:d!==null},resourceAfter:{data:l,exists:l!==null}};if(m.check!=="allow"){const k=o?{...g,detail:{priority:i}}:g;throw this.state.events.operation(t,s,n,nt(m.check),m,k),Je(Pe(m,t,s,n,{data:r}))}this.state.events.operation(t,s,n,"allow",m,g);const b=this.children.snapshotParents(),w=ur(this.state,n,d,h);this.state.tree.write(n,l),this.state.priorities.replace(n,l===null?null:i,k=>this.state.tree.read(k)!==null),this.storeNestedPriorities(n,u.nested),this.changed([n],b);const x=this.state.tree.read(n),v=x===null?"remove":s,S={...o||h!==null?{priority:i,priorPriority:h}:{},...w};this.state.events.commit(t,v,n,{data:r,priorState:d,nextState:x,replay:{requestTime:a},detail:Object.keys(S).length>0?S:void 0}),this.state.events.mutation(t,v,yt(n),{before:d,after:x}),this.state.notifyWrite()}resolvePatch(t,n,r){return Object.fromEntries(Object.entries(n).map(([s,i])=>{const o=G([...V(t),...V(s)]);return[o,en(ht(i,r,this.state.tree.read(o)),o)]}))}changed(t,n){this.state.mutations.mark(t),this.cancelDeniedListeners(t),this.values.fanOut(t),this.children.fanOut(n)}cancelDeniedListeners(t){if(this.state.valueListeners.size===0&&this.state.childListeners.size===0)return;let n,r;if(t!==void 0){if(this.state.activeRules===null)return;const l=t.map(d=>G(V(d)));if(l.length===0)return;const u=this.state.activeRules.rules;n=[...this.state.valueListeners].filter(d=>!d.admin&&zl(u,d.path,l)),r=[...this.state.childListeners].filter(d=>!d.admin&&zl(u,d.path,l))}else n=[...this.state.valueListeners].filter(l=>!l.admin),r=[...this.state.childListeners].filter(l=>!l.admin);if(n.length===0&&r.length===0)return;const s=this.state.rulesSnapshot(),i=[],o=new Map;for(const l of n){const u=this.state.rules.evaluate("read",l.path,{auth:l.auth,mockData:s,querySpec:l.query});if(u.check==="allow")continue;this.state.valueListeners.delete(l),this.state.events.operation(l.auth,"listen",l.path,nt(u.check),u,{origin:"listener",request:l.query?{query:l.query}:void 0,detail:{revoked:!0}});const d=Dn(u);this.state.events.listener("errored",l,l.auth,{event:"value",result:"deny",error:{code:"PERMISSION_DENIED",message:"PERMISSION_DENIED: Permission denied",reasons:u.reasons},reasons:u.reasons,rules:d}),o.set(l,Pe(u,l.auth,"listen",l.path)),i.push(l)}const a=[];for(const l of r){const u=this.state.rules.evaluate("read",l.path,{auth:l.auth,mockData:s,querySpec:l.spec});if(u.check==="allow")continue;this.state.childListeners.delete(l),this.state.events.operation(l.auth,"listen",l.path,nt(u.check),u,{origin:"listener",request:l.spec?{query:l.spec}:void 0,detail:{event:l.event,revoked:!0}});const d=Dn(u);this.state.events.listener("errored",l,l.auth,{event:l.event,result:"deny",error:{code:"PERMISSION_DENIED",message:"PERMISSION_DENIED: Permission denied",reasons:u.reasons},reasons:u.reasons,rules:d}),o.set(l,Pe(u,l.auth,"listen",l.path)),a.push(l)}for(const l of[...i,...a]){try{l.onCanceled&&l.onCanceled()}catch{}try{l.cancelCallback&&l.cancelCallback(pc(l.path,o.get(l)))}catch{}}}readEvaluation(t,n,r){return this.state.rules.evaluate("read",n==="/"?"/":n,{auth:t,mockData:this.state.rulesSnapshot(),querySpec:r})}writeEvaluation(t,n,r,s){return this.state.rules.evaluate("write",n==="/"?"/":n,{auth:t,mockData:this.state.rulesSnapshot(),newData:r,now:s})}storeNestedPriorities(t,n){for(const{segments:r,priority:s}of n){const i=G([...V(t),...r]);this.state.priorities.set(i,this.state.tree.read(i)===null?null:s)}}patchPriorities(t,n){const r=new Map;for(const[s,i]of Object.entries(n)){const{priority:o,inline:a,nested:l}=tn(i,null),u=G([...V(t),...V(s)]);r.set(u,a?[{segments:[],priority:o},...l]:l)}return r}storePatchPriorities(t){for(const[n,r]of t){const s=r.find(i=>i.segments.length===0);s&&this.state.priorities.set(n,this.state.tree.read(n)===null?null:s.priority),this.storeNestedPriorities(n,r.filter(i=>i.segments.length>0))}}}function cS(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,o="data"in r;let a=!1;i&&o&&(a=!0);const l=r.priorities,u=l!==null,d=l!==void 0;let h=!1;if(u&&d){const p=typeof l=="object",m=Array.isArray(l);p&&(m||(h=!0))}let f=!1;if(a&&h&&(f=!0),f){const p={},m=Object.entries(l);for(const[S,k]of m){const N=typeof k=="string",O=typeof k=="number";let P=!1;O&&Number.isFinite(k)&&(P=!0);let R=!1;N&&(R=!0),P&&(R=!0),R&&(p[S]=k)}const g=r.data;let b=null;g!==void 0&&g!==null&&(b=g);const x=r.rules;let v=null;if(x!==void 0&&x!==null){const k=typeof x=="object",N=Array.isArray(x);let O=!1;if(k&&(N||(O=!0)),O){const P=x;if("rules"in P){const j=P.rules;if(j!==null&&j!==void 0){const C=typeof j=="object",I=Array.isArray(j);let A=!1;C&&(I||(A=!0)),A&&(v={rules:j})}}}}return{data:b,priorities:p,rules:v}}}return{data:e,priorities:{},rules:null}}class lS{state;values;children;writes;constructor(t,n,r){this.state=t,this.values=n,this.children=r,this.writes=new Zh(t,n,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=cS(t);let s={};r.data!==null&&r.data!==void 0&&(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.writes.cancelDeniedListeners(),this.values.fanOut(["/"]),this.children.fanOut(n)}reset(t=!1){this.state.resetGeneration+=1;const n=this.children.snapshotParents();this.state.tree.restore({}),this.state.priorities.restore({}),this.state.mutations.mark("/"),t||(this.state.rules.setRules(null),this.state.activeRules=null),this.writes.cancelDeniedListeners(),this.values.fanOut(["/"]),this.children.fanOut(n)}subscribe(t){return this.state.writeSubscribers.add(t),()=>{this.state.writeSubscribers.delete(t)}}}const Hl="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz";let Kl=0;const Xt=new Array(12).fill(0);function uS(e=Date.now()){const t=e===Kl;Kl=e;const n=new Array(8);let r=e;for(let i=7;i>=0;i--)n[i]=Hl.charAt(r%64),r=Math.floor(r/64);if(r!==0)throw new Error("RTDB push-id: timestamp overflow.");let s=n.join("");if(t){let i;for(i=11;i>=0&&Xt[i]===63;i--)Xt[i]=0;if(i<0)for(let o=0;o<12;o++)Xt[o]=Math.floor(Math.random()*64);else Xt[i]=(Xt[i]??0)+1}else for(let i=0;i<12;i++)Xt[i]=Math.floor(Math.random()*64);for(let i=0;i<12;i++)s+=Hl.charAt(Xt[i]);if(s.length!==20)throw new Error(`RTDB push-id: bad length ${s.length}.`);return s}function dS(e){return hc(new Error("permission_denied"),e)}class fS{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,o=s?.admin===!0,a=V(n),l=a.length===0?null:a[a.length-1];let u=null,d=null,h,f=0,p=!1;do{f+=1;const j=this.state.mutations.begin();u=this.state.tree.read(n),d=o||this.canRead(t,n)?u:null;const E=d===null?null:Ms(Mt(d));let $=!1;try{h=r(E),$=this.state.mutations.conflictsSince(j,n)}finally{this.state.mutations.release(j)}if(!$||h===void 0){p=!0;break}}while(f<25);if(!p)throw new Error("maxretry");const m=this.state.events.nextGroupId("transaction");if(h===void 0)return this.state.events.operation(t,"transaction",n,"not-applicable",void 0,{origin:o?"admin":"transaction",groupId:m,groupKind:"transaction",resourceBefore:{data:d,exists:d!==null},detail:{committed:!1,aborted:!0}}),{committed:!1,val:d,key:l};const g=this.state.clock.now(),b=en(ht(h,g,u),n==="/"?"":n),w=this.state.priorities.get(n),x=tn(h,w);Lt(x.priority);const v=b===null?null:x.priority,_=this.state.clock.now();let S;if(!o){const j=mt(b,[{segments:[],priority:v},...x.nested]);if(S=this.state.rules.evaluate("write",n,{auth:t,mockData:this.state.rulesSnapshot(),newData:j,now:g}),S.check!=="allow")throw this.state.events.operation(t,"transaction",n,nt(S.check),S,{at:_,durationMs:this.state.clock.now()-_,origin:"transaction",request:{data:h,resourceData:h},resourceBefore:{data:u,exists:u!==null},resourceAfter:{data:b,exists:b!==null},groupId:m,groupKind:"transaction"}),dS(Pe(S,t,"transaction",n,{data:h}))}const k=j=>this.state.tree.read(j)!==null,N=ur(this.state,n,u,w,!0);if(i){const j=this.children.snapshotParents();return this.state.tree.write(n,b),this.state.priorities.replace(n,v,k),this.storeNestedPriorities(a,x.nested,k),this.values.fanOut([n]),this.children.fanOut(j),this.recordCommit(t,n,h,u,b,m,g,_,!0,S,o,N),{committed:!0,val:b,key:l}}const O=o?"not-applicable":"allow",P=o?"admin":"transaction";this.state.events.operation(t,"transaction",n,O,S,{at:_,durationMs:this.state.clock.now()-_,origin:P,request:{data:h,resourceData:h},resourceBefore:{data:u,exists:u!==null},resourceAfter:{data:b,exists:b!==null},groupId:m,groupKind:"transaction"});const R=this.children.snapshotParents();return this.state.tree.write(n,b),this.state.priorities.replace(n,v,k),this.storeNestedPriorities(a,x.nested,k),this.state.mutations.mark(n),this.values.fanOut([n]),this.children.fanOut(R),this.finishEvents(t,n,h,u,b,m,g,!1,o,N),this.state.notifyWrite(),{committed:!0,val:b,key:l}}storeNestedPriorities(t,n,r){for(const{segments:s,priority:i}of n){const o=G([...t,...s]);this.state.priorities.set(o,r(o)?i:null)}}canRead(t,n){return this.state.rules.evaluate("read",n,{auth:t,mockData:this.state.rulesSnapshot(),now:this.state.clock.now()}).check==="allow"}recordCommit(t,n,r,s,i,o,a,l,u,d,h,f){const p=h?"not-applicable":"allow",m=h?"admin":"transaction";this.state.events.operation(t,"transaction",n,p,d,{at:l,durationMs:this.state.clock.now()-l,origin:m,request:{data:r,resourceData:r},resourceBefore:{data:s,exists:s!==null},resourceAfter:{data:i,exists:i!==null},groupId:o,groupKind:"transaction"}),this.finishEvents(t,n,r,s,i,o,a,u,h,f),this.state.mutations.mark(n),this.state.notifyWrite()}finishEvents(t,n,r,s,i,o,a,l,u,d){this.state.events.commit(t,"transaction",n,{data:r,priorState:s,nextState:i,groupId:o,groupKind:"transaction",replay:{requestTime:a},detail:{...u?{admin:!0}:{},committed:!0,applyLocally:l,...d}}),this.state.events.mutation(t,"transaction",yt(n),{before:s,after:i,detail:{committed:!0}})}}function Gl(e){return e.split("/").find(t=>t.length>0)===".info"}function hS(){const e=new Error("INVALID_PARAMETERS: Invalid token in path");return e.code="INVALID_PARAMETERS",e}function Ce(e,t){const n=t===void 0?[e]:Object.keys(t).map(r=>`${e}/${r}`);if(Gl(e)||n.some(Gl))throw hS()}class pS{state;values;children;writes;transactions;persistence;constructor(t,n){this.state=new H_(t,n),this.values=new X_(this.state),this.children=new eS(this.state),this.writes=new Zh(this.state,this.values,this.children),this.transactions=new fS(this.state,this.values,this.children),this.persistence=new lS(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){Ce(t),this.writes.adminSet(t,n)}adminSetWithPriority(t,n,r){Ce(t),this.writes.adminSetWithPriority(t,n,r)}adminUpdate(t,n){Ce(t,n),this.writes.adminUpdate(t,n)}adminRemove(t){Ce(t),this.writes.adminRemove(t)}adminSetPriority(t,n){Ce(t),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)}unspecifiedIndexWarning(t,n){return this.state.unspecifiedIndexWarning(t,n)}set(t,n,r){Ce(n),this.writes.set(t,n,r)}setWithPriority(t,n,r,s){Ce(n),this.writes.setWithPriority(t,n,r,s)}update(t,n,r){Ce(n,r),this.writes.update(t,n,r)}remove(t,n){Ce(n),this.writes.remove(t,n)}setPriority(t,n,r){Ce(n),this.writes.setPriority(t,n,r)}validateRead(t,n,r){this.writes.validateRead(t,n,r)}validatePriority(t,n,r){Ce(n),this.writes.validatePriority(t,n,r)}registerDisconnect(t,n){n.kind==="update"?Ce(n.path,n.values):Ce(n.path),this.writes.registerDisconnect(t,n)}validateSet(t,n,r,s=null){Ce(n),this.writes.validateSet(t,n,r,s)}validateUpdate(t,n,r){Ce(n,r),this.writes.validateUpdate(t,n,r)}onValue(t,n,r,s,i,o,a){return this.values.onValue(t,n,r,s,i,o,a)}adminOnValue(t,n,r){return this.values.adminOnValue(t,n,r)}runTransaction(t,n,r,s){return Ce(n),this.transactions.run(t,n,r,s)}onChild(t,n,r,s,i,o,a){return this.children.onChild(t,n,r,s,i,o,a)}adminOnChild(t,n,r,s){return this.children.adminOnChild(t,n,r,s)}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(t=!1){this.persistence.reset(t)}subscribeWrites(t){return this.persistence.subscribe(t)}mintKey(){return uS(this.state.clock.now())}listenerCount(){return this.values.count()}childListenerCount(){return this.children.count()}}const Jl=new WeakMap,Yl=new WeakMap;function mS(e,t){const n=yS(e);return n.getOrCreate(n.keyOf(t))}function yS(e){const t=Jl.get(e);if(t)return t;const n=new Set,r=()=>{for(const i of n)try{i()}catch{}},s=Dx({create:i=>{const o=i===s.defaultKey?void 0:i,a=new pS(e,o);return a.subscribeWrites(r),a}});return Jl.set(e,s),e.onEvent(i=>{if(i.kind==="session_boundary"&&i.phase==="reset")for(const[,o]of s.entries())o.invalidateConnectionQueues(),Yl.has(e)||o.setRules(null)}),e.registerPersistableService("rtdb",{snapshot:()=>{const i=s.getOrCreate(s.defaultKey).exportPersistenceState(),o={};for(const[a,l]of s.entries())a!==s.defaultKey&&(o[a]=l.exportPersistenceState());return Object.keys(o).length>0&&i!==null&&typeof i=="object"&&!Array.isArray(i)?{...i,instances:o}:i},restore:i=>{if(!i||typeof i!="object")return;s.getOrCreate(s.defaultKey).restoreTree(i);const o=i;if(o.instances&&typeof o.instances=="object")for(const[a,l]of Object.entries(o.instances))s.getOrCreate(a).restoreTree(l)},subscribe:i=>(n.add(i),()=>{n.delete(i)}),reset:()=>{for(const[,i]of s.entries())i.resetTree(Yl.has(e))}}),s}const ep="type.googleapis.com/google.rpc.BadRequest",tp="type.googleapis.com/google.firebase.fcm.v1.FcmError";function ts(e,t){return{"@type":ep,fieldViolations:[{field:e,description:t}]}}function pn(e){return{"@type":tp,errorCode:e}}function Vn(e,t){return{status:400,error:{code:400,message:e,status:"INVALID_ARGUMENT",details:t}}}function Ql(){const e="Recipient of the message is not set.";return Vn(e,[ts("message",e),pn("INVALID_ARGUMENT")])}function gS(){const e="Exactly one of token, topic or condition is required.";return Vn(e,[ts("message",e),pn("INVALID_ARGUMENT")])}function bS(){const e="The registration token is not a valid FCM registration token";return Vn(e,[pn("INVALID_ARGUMENT"),ts("message.token",e)])}function np(){const e="Topic name contains invalid characters.";return Vn(e,[ts("message",e),pn("INVALID_ARGUMENT")])}function wS(){return{status:400,error:{code:400,message:"Request contains an invalid argument.",status:"INVALID_ARGUMENT"}}}function vS(){return Vn("Message is too large. The maximum is 4K (4096 bytes).",[{"@type":ep},pn("INVALID_ARGUMENT")])}function xS(){const e="TTL must be a non-negative integer.";return Vn(e,[ts("message.webpush.headers.TTL",e),pn("INVALID_ARGUMENT")])}function _S(){return{status:404,error:{code:404,message:"Requested entity was not found.",status:"NOT_FOUND",details:[pn("UNREGISTERED")]}}}function SS(e){return e.error.details?.find(n=>n["@type"]===tp)?.errorCode}class tt extends Error{envelope;errorCode;constructor(t){super(t.error.message),this.name="BrokerSendError",this.envelope=t,this.errorCode=SS(t)}}const kS=/^[a-zA-Z0-9-_.~%]+$/,ji=/^[A-Za-z0-9_-]+:[A-Za-z0-9_-]+$/,jS=4506,Xl=new TextEncoder;function ES(e){if(e===void 0)return 0;let t=0;for(const[n,r]of Object.entries(e))t+=Xl.encode(n).length+Xl.encode(String(r)).length;return t}function mc(e){return e.startsWith("/topics/")?e.slice(8):e}function Ei(e){const t=mc(e);return t.length>0&&kS.test(t)}function CS(e){const t=e;let n=0;const r=[];function s(){for(;n<t.length&&/\s/.test(t[n]);)n++}function i(l){return s(),t.startsWith(l,n)?(n+=l.length,!0):!1}function o(){if(s(),i("!"))return o();if(i("("))return a()?i(")"):!1;if(s(),t[n]!=="'")return!1;n++;const l=n;for(;n<t.length&&t[n]!=="'";)n++;if(n>=t.length)return!1;const u=t.slice(l,n);return n++,!i("in")||!i("topics")||!Ei(u)?!1:(r.push(u),!0)}function a(){if(!o())return!1;for(;;){if(s(),i("&&")||i("||")){if(!o())return!1;continue}return!0}}return!a()||(s(),n!==t.length)?null:{topics:r}}function NS(e){if(typeof e!="object"||e===null)throw new tt(Ql());const t=[];if(typeof e.token=="string"&&t.push({kind:"token",token:e.token}),typeof e.topic=="string"&&t.push({kind:"topic",topic:mc(e.topic)}),typeof e.condition=="string"&&t.push({kind:"condition",condition:e.condition,topics:[]}),t.length===0)throw new tt(Ql());if(t.length>1)throw new tt(gS());const n=t[0];if(n.kind==="token"&&!ji.test(n.token))throw new tt(bS());if(n.kind==="topic"&&!Ei(n.topic))throw new tt(np());if(n.kind==="condition"){const s=CS(n.condition);if(s===null)throw new tt(wS());n.topics=s.topics}const r=e.webpush?.headers?.TTL;if(r!==void 0&&!/^\d+$/.test(String(r)))throw new tt(xS());if(ES(e.data)>jS)throw new tt(vS());return n}function rp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function RS(e){if(!(Array.isArray(e)&&e.length===2))return!1;const[n,r]=e,s=typeof n=="string"&&ji.test(n),i=rp(r);if(!(s&&i))return!1;const a=typeof r.registrationId=="string"&&r.registrationId.length>0,l=typeof r.recipientId=="string"&&r.recipientId.length>0,u=r.state==="active"||r.state==="unregistered";return a&&l&&u}function IS(e){return typeof e=="string"&&ji.test(e)}function AS(e){if(!(Array.isArray(e)&&e.length===2))return!1;const[n,r]=e,s=typeof n=="string"&&Ei(n),i=Array.isArray(r)&&r.every(IS);return s&&i}function OS(e){if(!rp(e))return!1;const t=e.version===1,n=Array.isArray(e.tokens)&&e.tokens.every(RS),r=Array.isArray(e.topics)&&e.topics.every(AS);return t&&n&&r}function $S(e){return/[.!?]$/.test(e)?e:`${e}.`}function sp(e,t){return e===null||!e.startsWith("/")||e.startsWith("//")||t==null||!/^https?:\/\//.test(t)?e:new URL(e,t).href}function ip(){const e=globalThis.location?.origin;return typeof e=="string"&&/^https?:\/\//.test(e)?e:null}const PS="database.rules.json";function Zl(e,t){const n=e.lastIndexOf("."),r=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\")),s=n>r+1?e.slice(n):"";if(s===".json")return;const i=s===".bolt"?"As of firebase-tools@15.0.0, .bolt rules are no longer supported.":`Unexpected rules format ${s}`;throw new Error(`${t}: ${i}`)}function DS(e){if(e===void 0)return Ko(void 0);const t=Ph(e);try{return uc(t).name}catch{return t}}function TS(e,t={}){const n=t.resolveFile??(o=>o),r=DS(t.projectId);if(e==null){const o=PS;return{defaultInstance:r,targets:[{instance:r,file:n(o),configuredFile:o,label:"firebase.json",configured:!1}],unresolved:[]}}if(!Array.isArray(e)){const o=typeof e=="object"?e.rules:void 0;if(typeof o!="string"||o==="")return{defaultInstance:r,targets:[],unresolved:[]};const a="firebase.json database.rules";return Zl(o,a),{defaultInstance:r,targets:[{instance:r,file:n(o),configuredFile:o,label:a,configured:!0}],unresolved:[]}}const s=[],i=[];return e.forEach((o,a)=>{const l=`firebase.json database[${a}]`,u=o!==null&&typeof o=="object"?o:{};let d;if(typeof u.target=="string"&&u.target!==""){const f=t.targetInstances?.(u.target);d=Array.isArray(f)?f.filter(p=>typeof p=="string"&&p!==""):[]}else if(typeof u.instance=="string"&&u.instance!=="")d=[u.instance];else throw new Error(`${l}: Must supply either "target" or "instance" in database config`);if(typeof u.rules!="string"||u.rules==="")return;Zl(u.rules,l);const h=n(u.rules);if(d.length===0&&typeof u.target=="string"){i.push({target:u.target,label:l,file:h});return}for(const f of d){let p;try{p=uc(f).name}catch(g){const b=g instanceof Error?g.message.trim():String(g);throw new Error(`${l}: instance "${f}" is not a database instance name: ${b}`)}Dh(p,t.projectId)&&(p=r);const m=s.find(g=>g.instance===p);if(m===void 0){s.push({instance:p,file:h,configuredFile:u.rules,label:l,configured:!0});continue}if(m.file!==h)throw new Error(`firebase.json deploys two rules files to database instance "${p}": ${m.file} from ${m.label} and ${h} from ${l}. The Firebase CLI deploys both at once, so the configuration does not determine which one production keeps. Deploy one rules file to each instance.`)}}),{defaultInstance:r,targets:s,unresolved:i}}const MS="__pyric_no_password__",LS=300*1e3;function ro(e){return Vh(e.claims)}class op{usersByEmail;usersByUid;authStateSubs=[];idTokenSubs=[];userDbSubs;beforeStateSubs=[];sharedCounters;flow=new xx;sandbox;session;cachedUser=null;lastNotifiedUid=null;applyingTransition=!1;tokenCache=new Map;nextTokenSerial=1;persistenceMode="LOCAL";signInProviderByUid=new Map;photoOriginByUid=new Map;authenticatedAtByUid=new Map;providerConfig;providerConfigSubs;providerEnforcementDelegated=!1;avatarMint=Ox;tenantId=null;getTenantId(){return this.tenantId}setTenantId(t){this.tenantId=t}constructor(t,n=t,r=Oh(),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(o=>{if(this.applyingTransition)return;const a=o===null?null:o.uid,l=this.cachedUser?.uid??null;a!==l&&(this.cachedUser=this.buildUserFromState(o)),this.notifyAuthListeners()});s?.(()=>{i(),this.authStateSubs.length=0,this.idTokenSubs.length=0,this.beforeStateSubs.length=0})}getCurrentUser(){return this.cachedUser}getCurrentSignInProvider(){const t=this.cachedUser;return t===null?null:this.signInProviderByUid.get(t.uid)??null}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,n=null){const r={email:null,password:null,displayName:null,phoneNumber:null,photoUrl:null,customClaims:{},isAnonymous:!1,providerUserInfo:[],disabled:!1,emailVerified:!1,createdAt:this.now().toISOString(),lastLoginAt:null,tenantId:null,...t},s=US(r,n);return BS(r,s)&&(r.photoUrl=this.avatarMint({uid:r.uid,displayName:r.displayName,email:r.email,providerId:s})),r}notifyUsersChanged(){for(const t of[...this.userDbSubs])try{t()}catch{}}now(){return Te(this.sandbox).date()}emitAuthEvent(t,n={}){try{pt(this.sandbox,Un({at:this.now().getTime(),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}setAvatarMint(t){this.avatarMint=t}assertProviderEnabled(t){if(!this.providerEnforcementDelegated&&!this.isProviderEnabled(t))throw Y("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 r of t){const i=this.usersByUid.get(r.uid)?.email;typeof i=="string"&&i.length>0&&i.toLowerCase()!==r.email?.toLowerCase()&&this.usersByEmail.delete(i.toLowerCase());const l=r.providerId==="anonymous",u=r.providerUserInfo??[{providerId:r.providerId??"password"}],d=l?[]:u.map(k=>({...k})),h=d.some(k=>k.providerId==="password"),p=(r.password===MS||r.password==="__pyric_popup_no_password__")&&!h,m=l||p,g=this.makeStored({uid:r.uid,email:l?null:r.email??null,password:m?null:r.password??null,displayName:r.displayName??null,phoneNumber:r.phoneNumber??null,photoUrl:r.photoUrl??null,customClaims:r.customClaims??{},emailVerified:r.emailVerified??!1,disabled:r.disabled??!1,isAnonymous:l,providerUserInfo:d,tenantId:r.tenantId??null}),{createdAt:b,lastLoginAt:w,email:x}=r;b!==void 0&&(g.createdAt=b),w!==void 0&&(g.lastLoginAt=w),!l&&x!==void 0&&this.usersByEmail.set(x.toLowerCase(),g),this.usersByUid.set(r.uid,g)}t.length>0&&this.notifyUsersChanged()}exportUsers(){const t=[];for(const n of this.usersByUid.values()){const{email:r,displayName:s,photoUrl:i,tenantId:o,phoneNumber:a,isAnonymous:l,disabled:u,emailVerified:d}=n,h=s!==null,f=i!==null,p=Object.keys(n.customClaims).length>0,m=o!==null;if(l){const _={uid:n.uid,providerId:"anonymous",createdAt:n.createdAt,lastLoginAt:n.lastLoginAt};h&&(_.displayName=s),f&&(_.photoUrl=i),p&&(_.customClaims=n.customClaims),u&&(_.disabled=!0),m&&(_.tenantId=o),t.push(_);continue}if(r===null)continue;const b={uid:n.uid,createdAt:n.createdAt,lastLoginAt:n.lastLoginAt,email:r,providerId:n.providerUserInfo[0]?.providerId??"password",providerUserInfo:n.providerUserInfo.map(_=>({..._}))},{password:w}=n;w!==null&&(b.password=w),h&&(b.displayName=s),f&&(b.photoUrl=i),a!==null&&(b.phoneNumber=a),p&&(b.customClaims=n.customClaims),d&&(b.emailVerified=!0),u&&(b.disabled=!0),m&&(b.tenantId=o),t.push(b)}return t}restoreSession(t){const n=this.usersByUid.get(t);if(!n)throw Y("auth/user-not-found",`restoreSession: no identity with uid ${t}.`);if(n.disabled)throw Y("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){Xn(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){Qt(n);const r=this.requireByEmail(t),s=n.toLowerCase(),i=this.usersByEmail.get(s);if(i&&i.uid!==r.uid)throw Y("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){Qt(t);const n=t.toLowerCase(),r=this.usersByEmail.get(n);if(r!==void 0)return!r.providerUserInfo.some(l=>l.providerId==="password")&&r.providerUserInfo.push({providerId:"password"}),r.emailVerified=!0,this.notifyUsersChanged(),{stored:r,isNewUser:!1};const i=`email-${globalThis.crypto.randomUUID()}`,o=this.makeStored({uid:i,email:t,providerUserInfo:[{providerId:"password"}]});return o.emailVerified=!0,this.usersByEmail.set(n,o),this.usersByUid.set(i,o),this.notifyUsersChanged(),this.emitAuthEvent("user_create",{path:i,after:this.toRecord(o),detail:{emailLink:!0}}),{stored:o,isNewUser:!0}}linkProvider(t,n,r){const s=this.usersByUid.get(t);if(!s)throw Y("auth/user-not-found",`linkWithCredential: no identity with uid ${t}.`);if(s.providerUserInfo.some(o=>o.providerId===n))throw Y("auth/provider-already-linked",`User can only be linked to one identity for the given provider (${n}).`);const i=r?.email;if(i){Qt(i);const o=i.toLowerCase(),a=this.usersByEmail.get(o);if(a&&a.uid!==t)throw Y("auth/email-already-in-use",`An account already exists for ${i}.`);r.password!==void 0&&r.password!==null&&(Xn(r.password),s.password=r.password),s.email&&s.email.toLowerCase()!==o&&this.usersByEmail.delete(s.email.toLowerCase()),s.email=i,this.usersByEmail.set(o,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 Y("auth/user-not-found",`unlink: no identity with uid ${t}.`);const s=r.providerUserInfo.findIndex(i=>i.providerId===n);if(s<0)throw Y("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 Y("auth/user-not-found",`No user found for ${t}.`);return n}createEmailPasswordUser(t,n){Qt(t),Xn(n);const r=t.toLowerCase();if(this.usersByEmail.has(r))throw Y("auth/email-already-in-use",`An account already exists for ${t}.`);const i=`email-${globalThis.crypto.randomUUID()}`,o=this.makeStored({uid:i,email:t,password:n,providerUserInfo:[{providerId:"password"}]});return this.usersByEmail.set(r,o),this.usersByUid.set(i,o),this.notifyUsersChanged(),this.emitAuthEvent("user_create",{path:i,after:this.toRecord(o)}),o}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 Y("auth/login-blocked",s)}}transitionCurrentUser(t,n){return t!==null&&n!==void 0&&this.scopeSignInToTenant(t),!this.beforeStateSubs.some(s=>s.active)||t===this.cachedUser?(this.setCurrentUser(t,n),Promise.resolve()):this.runBeforeStateChange(t).then(()=>{this.setCurrentUser(t,n)})}scopeSignInToTenant(t){const n=this.tenantId;t.tenantId=n;const r=this.usersByUid.get(t.uid);r&&(r.tenantId=n)}setCurrentUser(t,n){if(t===null){const p=this.cachedUser;this.cachedUser=null,this.applyingTransition=!0;try{this.session.currentUser=null}finally{this.applyingTransition=!1}p!==null&&(this.tokenCache.delete(p.uid),this.notifyAuthListeners(),this.notifySessionChanged(),this.emitAuthEvent("sign_out",{path:p.uid,auth:{uid:p.uid}}));return}const s=n!==void 0;s&&this.signInProviderByUid.set(t.uid,n),(s||!this.authenticatedAtByUid.has(t.uid))&&this.recordAuthentication(t.uid);const o=this.usersByUid.get(t.uid),a=o?.customClaims??{};s&&o!==void 0&&(o.lastLoginAt=this.now().toISOString(),this.notifyUsersChanged()),this.cachedUser=t;const u=this.mintToken(t.uid,a,t.tenantId??null),d={uid:t.uid,token:ro(u.result)};typeof t.tenantId=="string"&&(d.tenant=t.tenantId);const f=d;this.applyingTransition=!0;try{this.session.currentUser=f}finally{this.applyingTransition=!1}this.notifyAuthListeners(),this.notifySessionChanged(),s&&this.emitAuthEvent("sign_in",{path:t.uid,auth:f,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;const s=t.photoURL??null;let i=this.usersByUid.get(t.uid);i?eu(i,s)&&(r=!0):(i=this.makeStored({uid:t.uid,email:t.email,displayName:t.displayName,photoUrl:s,isAnonymous:t.isAnonymous},n),this.usersByUid.set(t.uid,i),t.email&&this.usersByEmail.set(t.email.toLowerCase(),i),r=!0),i.providerUserInfo.some(o=>o.providerId===n)||(i.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 Y("auth/user-not-found",`createSignInCredential: no identity with uid ${t.uid}. Use the {spec} shape to create one.`);this.assertUserEnabled(s),r=s}else{const{spec:s}=t,i=s.photoUrl??null,o=this.usersByEmail.get(s.email.toLowerCase());o?(this.assertUserEnabled(o),r=o,eu(r,i)&&this.notifyUsersChanged()):(r=this.makeStored({uid:s.uid??FS(),email:s.email,displayName:s.displayName??null,photoUrl:i,customClaims:s.customClaims??{}},n),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,tenantId:t.tenantId,createdAt:t.createdAt,lastLoginAt:t.lastLoginAt}}listUsers(){return[...this.usersByUid.values()].map(t=>({...this.toRecord(t),photoUrl:Zt(t,this.photoOriginByUid)}))}sanitizeLinkedProviders(t,n,r){const s=new Set,i=[];for(const o of t){const a=o?.providerId?.trim();if(!a)throw Y("auth/argument-error",`${r}: providerUserInfo entries need a non-empty providerId.`);a==="password"||a==="anonymous"||s.has(a)||(s.add(a),i.push({providerId:a}))}return n&&i.unshift({providerId:"password"}),i}nextAvailableAdminUid(){for(;;){const t=`user-${this.sharedCounters.nextAdminUserId++}`;if(!this.usersByUid.has(t))return t}}createUser(t){t.customClaims!==void 0&&$l(t.customClaims);const n=t.uid??this.nextAvailableAdminUid();if(this.usersByUid.has(n))throw Y("auth/uid-already-exists",`createUser: a user with uid ${n} already exists.`);if(t.email!==void 0&&(Qt(t.email),this.usersByEmail.has(t.email.toLowerCase())))throw Y("auth/email-already-in-use",`An account already exists for ${t.email}.`);if(t.password!==void 0&&(Xn(t.password),t.email===void 0))throw Y("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}),{...this.toRecord(r),photoUrl:Zt(r,this.photoOriginByUid)}}updateUser(t,n){const r=this.usersByUid.get(t);if(!r)throw Y("auth/user-not-found",`No user found for uid ${t}.`);n.customClaims!==void 0&&$l(n.customClaims);const s=this.toRecord(r);if(n.email!==void 0){Qt(n.email);const o=n.email.toLowerCase(),a=this.usersByEmail.get(o);if(a&&a!==r)throw Y("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(o,r)}n.password!==void 0&&(Xn(n.password),r.password=n.password,r.providerUserInfo.some(o=>o.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}),{...this.toRecord(r),photoUrl:Zt(r,this.photoOriginByUid)}}deleteUser(t){const n=this.usersByUid.get(t);if(!n)throw Y("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.photoOriginByUid.delete(t),this.authenticatedAtByUid.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 Y("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:Zt(t,this.photoOriginByUid),emailVerified:t.emailVerified,phoneNumber:t.phoneNumber,providers:t.providerUserInfo,tenantId:t.tenantId})}mintAnonymousUser(){const t=`anonymous-${globalThis.crypto.randomUUID()}`,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){const n=t.tenantId??null;switch(t.kind){case"anonymous":return this.assertProviderEnabled("anonymous"),this.establishDetachedSession(this.mintAnonymousUser(),"anonymous",n,!0,t.origin);case"password":return this.assertProviderEnabled("password"),this.establishDetachedSession(this.buildUserFromStored(this.validatePassword(t.email,t.password)),"password",n,!0,t.origin);case"createPassword":return this.assertProviderEnabled("password"),this.establishDetachedSession(this.buildUserFromStored(this.createEmailPasswordUser(t.email,t.password)),"password",n,!0,t.origin);case"provider":case"custom":case"uid":{const r=t.kind==="provider";r&&this.assertProviderEnabled(t.providerId);const s=this.usersByUid.get(t.uid);if(s===void 0)throw Y("auth/user-not-found",`mintSession: no identity with uid ${t.uid}.`);this.assertUserEnabled(s);const a=s.isAnonymous?"anonymous":s.providerUserInfo[0]?.providerId??"password";let l=r?t.providerId:a;t.kind==="custom"&&(l="custom");const d=t.kind!=="uid"||!this.authenticatedAtByUid.has(t.uid);return this.establishDetachedSession(this.buildUserFromStored(s),l,n,d,t.origin)}}}establishDetachedSession(t,n,r,s=!0,i){this.signInProviderByUid.set(t.uid,n),i!==void 0&&this.photoOriginByUid.set(t.uid,i),s&&this.recordAuthentication(t.uid);const o=this.usersByUid.get(t.uid),a=o?.customClaims??{},l=o!==void 0;l&&(t.photoURL=Zt(o,this.photoOriginByUid)),l&&s&&(o.lastLoginAt=this.now().toISOString(),this.notifyUsersChanged()),t.tenantId=r;const u=this.mintToken(t.uid,a,r),d={uid:t.uid,token:ro(u.result)};return r!==null&&(d.tenant=r),this.emitAuthEvent("sign_in",{path:t.uid,auth:d,after:{uid:t.uid,isAnonymous:t.isAnonymous,email:t.email},detail:{providerId:n,session:"connection"}}),{user:t,state:d}}buildUserFromState(t){if(t===null)return null;const n=this.usersByUid.get(t.uid);return n?this.buildUserFromStored({...n,customClaims:t.token??n.customClaims,tenantId:t.tenant??n.tenantId}):this.makeUser({uid:t.uid,email:null,displayName:null,isAnonymous:t.uid.startsWith("anonymous-"),claims:t.token??{},tenantId:t.tenant??null})}mintToken(t,n,r){const s=this.now(),i=new Date(s.getTime()+100*365*24*60*60*1e3),o=this.nextTokenSerial++,a=this.signInProviderByUid.get(t)??null,l=new Date(this.authenticatedAtByUid.get(t)??s.getTime()),u=this.usersByUid.get(t),d={sub:t,aud:"pyric-sandbox",iss:"https://sandbox.pyric.dev",auth_time:Math.floor(l.getTime()/1e3),iat:Math.floor(s.getTime()/1e3),exp:Math.floor(i.getTime()/1e3),...qh(t,u?{...C_(u),photoUrl:Zt(u,this.photoOriginByUid)}:null,n,a)},f=vi({uid:t,tenant:r??void 0,token:d})?.token??d,p=_x(t,Vh(f),o),m={token:p,claims:f,expirationTime:i.toISOString(),issuedAtTime:s.toISOString(),authTime:l.toISOString(),signInProvider:a},g={token:p,result:m},b=this.tokenCache.get(t)??new Map;return b.set(r,g),this.tokenCache.set(t,b),g}getIdTokenFor(t,n,r,s=null){return this.getIdTokenResultFor(t,n,r,s).token}getIdTokenResultFor(t,n,r,s=null){if(r){const l=this.mintToken(t,n,s),u=this.session.currentUser;if(u!==null&&u.uid===t&&(u.tenant??null)===s){this.applyingTransition=!0;try{this.session.currentUser={...u,token:ro(l.result)}}finally{this.applyingTransition=!1}}return this.fanOut("id-token"),l.result}const i=this.tokenCache.get(t)?.get(s);return i!==void 0?i.result:this.mintToken(t,n,s).result}makeUser(t){const n=t.photoURL??null,r=t.phoneNumber??null,s=t.emailVerified??!1,i="firebase",o=t.providers??[{providerId:"password"}],l=t.isAnonymous===!0?[]:o.map(d=>({uid:t.uid,displayName:t.displayName,email:t.email,phoneNumber:r,photoURL:n,providerId:d.providerId})),u={uid:t.uid,email:t.email,emailVerified:s,displayName:t.displayName,photoURL:n,phoneNumber:r,isAnonymous:t.isAnonymous,tenantId:t.tenantId??null,providerId:i,providerData:l,getIdToken:async d=>this.getIdTokenFor(t.uid,this.liveClaims(t.uid,t.claims),d===!0,u.tenantId),getIdTokenResult:async d=>this.getIdTokenResultFor(t.uid,this.liveClaims(t.uid,t.claims),d===!0,u.tenantId)};return Object.defineProperty(u,bx,{value:{updateProfile:d=>(this.updateProfileFor(u,d),Promise.resolve()),delete:()=>(this.deleteFor(u),Promise.resolve()),updateEmail:d=>(this.updateEmailFor(u,d),Promise.resolve()),updatePassword:d=>(this.updatePasswordFor(u,d),Promise.resolve()),reload:()=>(this.reloadFor(u),Promise.resolve()),target:this.selfTarget()},enumerable:!1}),u}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 Y("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}recordAuthentication(t){this.authenticatedAtByUid.set(t,this.now().getTime())}assertRecentLogin(t){if(this.usersByUid.get(t)?.isAnonymous===!0)return;const r=this.authenticatedAtByUid.get(t);if(r===void 0)return;if(this.now().getTime()-r>LS)throw Y("auth/requires-recent-login","Error")}deleteFor(t){this.assertRecentLogin(t.uid),this.usersByUid.has(t.uid)&&this.deleteUser(t.uid),this.cachedUser&&this.cachedUser.uid===t.uid&&this.setCurrentUser(null)}updateEmailFor(t,n){this.assertRecentLogin(t.uid),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.assertRecentLogin(t.uid),this.updateUser(t.uid,{password:n})}reloadFor(t){const n=this.usersByUid.get(t.uid);if(!n)throw Y("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=Zt(n,this.photoOriginByUid),r.emailVerified=n.emailVerified,r.phoneNumber=n.phoneNumber}liveClaims(t,n){return this.usersByUid.get(t)?.customClaims??n}assertUserEnabled(t){if(t.disabled)throw Y("auth/user-disabled","The user account has been disabled by an administrator.")}validatePassword(t,n){if(Qt(t),typeof n!="string"||n.length===0)throw Y("auth/missing-password","A non-empty password must be provided");const r=this.findByEmail(t);if(!r)throw Y("auth/user-not-found",`No user found for ${t}.`);if(this.assertUserEnabled(r),r.password!==n)throw Y("auth/wrong-password","Invalid password.");return r}}function US(e,t){if(t!==null)return t;const n=e.providerUserInfo[0];return n===void 0?null:n.providerId}function BS(e,t){return e.photoUrl!==null||e.isAnonymous||t===null?!1:t.includes(".")}function Zt(e,t){return sp(e.photoUrl,t.get(e.uid)??ip())}function eu(e,t){return t===null||e.photoUrl===t?!1:(e.photoUrl=t,!0)}function FS(){return`provider-${globalThis.crypto.randomUUID()}`}const tu=new WeakSet,ps=new WeakMap;function ap(e,t,n,r="[DEFAULT]"){return VS(e,t),qS(e,t,n,r)}function VS(e,t){tu.has(e)||(tu.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 nu(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 qS(e,t,n,r){let s=ps.get(e);s||(s=new Map,ps.set(e,s));const i=`auth-session:${r}`,o=s.get(i);if(o){const u=++o.generation;return o.unregisterService?.(),o.unregisterService=void 0,o.unsubscribeBackend?.(),o.unsubscribeBackend=void 0,o.backend=t,o.session=n,o.unregisterService=e.registerPersistableService(i,nu(o)),()=>{o.generation===u&&(o.unregisterService?.(),o.unregisterService=void 0,o.unsubscribeBackend?.(),o.unsubscribeBackend=void 0,o.subscribers.clear(),s.get(i)===o&&s.delete(i),s.size===0&&ps.delete(e))}}const a={backend:t,session:n,subscribers:new Set,generation:1};s.set(i,a),a.unregisterService=e.registerPersistableService(i,nu(a));const l=a.generation;return()=>{a.generation===l&&(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&&ps.delete(e))}}async function w1(e){const{backend:t}=lc(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 WS(e){const t=lc(e,!0);try{t.assertAlive?.()}catch(n){if(n.code==="app/app-deleted")return;throw n}await t.backend.transitionCurrentUser(null)}const ru=new WeakMap,su=new WeakMap,iu=new WeakMap;function cp(e){let t=su.get(e);return t||(t=Oh(),su.set(e,t)),t}function zS(e){let t=ru.get(e);return t||(t=new op(e,e,cp(e)),ru.set(e,t),ap(e,t,e)),t}function HS(e,t){return t.service("auth/backend",()=>{const{sandbox:n,session:r}=t,s=new op(n,r,cp(n),i=>{t.onDelete(i)});return t.onDelete(ap(n,s,r,e.name)),s})}function yc(e){if(e===void 0)return yc($w());const t=Pw(e);if(t)return t.service("auth/default",()=>{const n={kind:"sandbox",sandbox:t.sandbox,backend:HS(e,t),own:r=>t.onDelete(r),assertAlive:()=>t.assertAlive()};return ou(n,e)});if(KS(e)){let n=iu.get(e);return n||(n=ou({kind:"sandbox",sandbox:e,backend:zS(e)}),iu.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 KS(e){return typeof e=="object"&&e!==null&&typeof e.onCurrentUserChanged=="function"&&typeof e.withAuth=="function"}function ou(e,t){const n={[Rh]:e,...t?{app:t}:{},signOut(){return WS(n)}};return Object.defineProperty(n,"currentUser",{enumerable:!0,get(){return e.backend.getCurrentUser()}}),Object.defineProperty(n,"tenantId",{enumerable:!0,get(){return e.backend.getTenantId()},set(r){e.backend.setTenantId(r)}})}function X(e){return lc(e)}const xe={setUser(e,t){X(e).backend.setCurrentUser(t)},setAuthFlowResolver(e,t){X(e).backend.setResolver(t)},setAuthMailResolver(e,t){X(e).backend.setMailResolver(t)},takeAuthMail(e,t){return X(e).backend.takeMail(t)},listAuthMail(e){return X(e).backend.listMail()},mockActionCode(e,t,n){X(e).backend.stageActionCode(t,n)},listIdentities(e){return X(e).backend.listIdentities()},createSignInCredential(e,t){return X(e).backend.createSignInCredential(t)},mockSignInResult(e,t){const n=t.providerId;if(!n)throw new Qf("invalid-argument","sandbox.mockSignInResult: result.providerId is required so the next signInWithPopup / signInWithCredential call can match.");X(e).backend.setMockResult(n,t)},seedUsers(e,t){X(e).backend.seedUsers(t)},exportUsers(e){return X(e).backend.exportUsers()},restoreSession(e,t){return X(e).backend.restoreSession(t)},getTenantId(e){return X(e).backend.getTenantId()},setTenantId(e,t){X(e).backend.setTenantId(t)},mintSession(e,t){return X(e).backend.mintDetachedSession(t)},signInProvider(e){return X(e).backend.getCurrentSignInProvider()},listUsers(e){return X(e).backend.listUsers()},createUser(e,t){return X(e).backend.createUser(t)},updateUser(e,t,n){return X(e).backend.updateUser(t,n)},updateProfile(e,t,n){return X(e).backend.updateProfileByUid(t,n)},deleteUser(e,t){X(e).backend.deleteUser(t)},clearUsers(e){X(e).backend.clearUsers()},subscribeUsers(e,t){return X(e).backend.subscribeUsers(t)},exportProviderConfig(e){return X(e).backend.exportProviderConfig()},restoreProviderConfig(e,t){X(e).backend.restoreProviderConfig(t)},getAuthProviderConfig(e){return X(e).backend.listProviderConfig()},setAuthProviderConfig(e,t,n){X(e).backend.setProviderConfig(t,n)},assertAuthProviderEnabled(e,t){X(e).backend.assertProviderEnabled(t)},delegateProviderEnforcement(e,t){X(e).backend.setProviderEnforcementDelegated(t)},setAvatarMint(e,t){X(e).backend.setAvatarMint(t)},subscribeAuthProviderConfig(e,t){return X(e).backend.subscribeProviderConfig(t)}};function Xo(e){return e!==void 0&&/^[0-9]+$/.test(e)?BigInt(e):0n}function GS(e,t){return e>t?e:t}function gc(e,t){return e===void 0?t:t===void 0||Xo(e)>=Xo(t)?e:t}function lp(e,t){return gc(e,t)??t}function up(e){return BigInt(Math.floor(e*1e3))}function JS(e){return t=>String(GS(up(e),Xo(t)+1n))}const Zo="pyric-storage",te="pyric-default";function oe(e,t){return`${e}/${t}`}function ti(e){const t=e.indexOf("/");return t===-1?null:{bucket:e.slice(0,t),path:e.slice(t+1)}}function YS(e){return e?`${Zo}:${e}`:Zo}const QS=2,ke="blobs",le="metadata",br="generations";function dp(e,t,n){if(e.metadata.bucket!==t||e.metadata.fullPath!==n)throw new Error("A prior Storage object can only be put back at its own bucket and path.");bc(e.blob,e.metadata)}function bc(e,t){if(t.size!==e.size)throw new Error("Storage metadata does not match its object.")}async function XS(e=Zo,t){try{const n=await rk(e);return new nk(n,t)}catch(n){return typeof indexedDB<"u"&&fp(e,ek(n),"other tabs reload"),new tk(t)}}class ZS extends Error{name="OpenBlockedError"}function ek(e){return e instanceof Error||typeof DOMException<"u"&&e instanceof DOMException?`${e.name}: ${e.message}`:String(e)}function fp(e,t,n){console.warn(`[pyric] Storage could not use the IndexedDB store "${e}" (${t}). Storage will not persist until ${n}.`)}class hp{uploads=new Map;beginUpload(t,n,r,s,i){const o=typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`upl-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;return this.uploads.set(o,{uploadId:o,bucket:t,path:n,size:r,contentType:s,customMetadata:i,parts:new Map,createdAt:Date.now()}),o}putPart(t,n,r){const s=this.uploads.get(t);if(!s){const o=new Error(`storage/object-not-found: Upload '${t}' not found.`);throw o.code="storage/object-not-found",o}s.parts.set(n,r);let i=0;for(const o of s.parts.values())i+=o.byteLength;return{bytesReceived:i}}readUpload(t){const n=this.uploads.get(t);if(!n){const i=new Error(`storage/object-not-found: Upload '${t}' not found.`);throw i.code="storage/object-not-found",i}let r=0;const s=Array.from(n.parts.keys()).sort((i,o)=>i-o);for(const i of s)r+=n.parts.get(i).byteLength;if(r!==n.size){const i=new Error(`storage/invalid-argument: Uploaded bytes (${r}) did not match declared size (${n.size}).`);throw i.code="storage/invalid-argument",i}return new Blob(s.map(i=>n.parts.get(i)),{type:n.contentType})}abortUpload(t){this.uploads.delete(t)}}class tk{blobs=new Map;metadata=new Map;highWater=new Map;staging=new hp;_defaultBucket;constructor(t){this._defaultBucket=t}async put(t,n,r,s){const i=r.bucket||this._defaultBucket||te;this._defaultBucket||(this._defaultBucket=i),bc(n,r),r.bucket||(r.bucket=i);const o=oe(i,t),a=this.objectAt(o),l=this.highWater.get(o);return s!==void 0&&(r.generation=s(gc(a?.metadata.generation,l))),this.blobs.set(o,n),this.metadata.set(o,r),this.highWater.set(o,lp(l,r.generation)),a}objectAt(t){const n=this.blobs.get(t),r=this.metadata.get(t);if(!(n===void 0||r===void 0))return{blob:n,metadata:r}}async deleteIfGeneration(t,n,r){return this.replaceIfGeneration(t,n,void 0,r)}async replaceIfGeneration(t,n,r,s){const i=s??this._defaultBucket??te;r!==void 0&&dp(r,i,t);const o=oe(i,t);return this.metadata.get(o)?.generation!==n?!1:(this.blobs.delete(o),this.metadata.delete(o),r===void 0||(this.blobs.set(o,r.blob),this.metadata.set(o,r.metadata)),!0)}async getBlob(t,n){if(n)return this.blobs.get(oe(n,t));const r=this._defaultBucket??te,s=this.blobs.get(oe(r,t));if(s!==void 0)return s;if(r!==te){const i=this.blobs.get(oe(te,t));if(i!==void 0)return i}for(const[i,o]of this.blobs.entries()){const a=ti(i);if(a&&a.path===t)return o}}async getMetadata(t,n){if(n)return this.metadata.get(oe(n,t));const r=this._defaultBucket??te,s=this.metadata.get(oe(r,t));if(s!==void 0)return s;if(r!==te){const i=this.metadata.get(oe(te,t));if(i!==void 0)return i}for(const[i,o]of this.metadata.entries()){const a=ti(i);if(a&&a.path===t)return o}}async getObject(t,n){return this.objectAt(oe(n??this._defaultBucket??te,t))}async putMetadata(t,n,r){const s=r??n.bucket??this._defaultBucket??te;n.bucket||(n.bucket=s),this.metadata.set(oe(s,t),n)}async delete(t,n){const r=n??this._defaultBucket??te;this.blobs.delete(oe(r,t)),this.metadata.delete(oe(r,t))}async listByPrefix(t,n){const s=`${n??this._defaultBucket??te}/${t}`,i=[],o=Array.from(this.metadata.keys()).sort();for(const a of o)if(a.startsWith(s)){const l=this.metadata.get(a);l&&i.push(l)}return i}async reset(t){if(!t){this.blobs.clear(),this.metadata.clear(),this._defaultBucket=void 0;return}const n=`${t}/`;for(const r of Array.from(this.blobs.keys()))r.startsWith(n)&&this.blobs.delete(r);for(const r of Array.from(this.metadata.keys()))r.startsWith(n)&&this.metadata.delete(r)}async beginUpload(t,n,r,s,i){const o=t||this._defaultBucket||te;return this.staging.beginUpload(o,n,r,s,i)}async putPart(t,n,r){return this.staging.putPart(t,n,r)}async readUpload(t){return this.staging.readUpload(t)}async abortUpload(t){this.staging.abortUpload(t)}close(){}scoped(t){return new Ci(this,t)}}class nk{db;staging=new hp;_defaultBucket;closedReason;constructor(t,n){this.db=t,this._defaultBucket=n,t.addEventListener("versionchange",()=>{t.close(),this.closedReason="a newer pyric build opened it in another tab",fp(t.name,this.closedReason,"this tab reloads")})}transaction(t,n){if(this.closedReason!==void 0)throw new Error(`The IndexedDB store "${this.db.name}" closed because ${this.closedReason}. Reload this tab to use Storage.`);return this.db.transaction(t,n)}async put(t,n,r,s){const i=r.bucket||this._defaultBucket||te;this._defaultBucket||(this._defaultBucket=i),bc(n,r),r.bucket||(r.bucket=i);const o=oe(i,t),a=this.transaction([ke,le,br],"readwrite"),l=sk(a,o),u=a.objectStore(br).get(o);let d;u.addEventListener("success",()=>{const h=u.result;try{s!==void 0&&(r.generation=s(gc(l.object()?.metadata.generation,h))),a.objectStore(ke).put(n,o),a.objectStore(le).put(r,o),a.objectStore(br).put(lp(h,r.generation),o)}catch(f){d={error:f},a.abort()}});try{await er(a)}catch(h){throw d!==void 0?d.error:h}return l.object()}async deleteIfGeneration(t,n,r){return this.replaceIfGeneration(t,n,void 0,r)}async replaceIfGeneration(t,n,r,s){const i=s??this._defaultBucket??te;r!==void 0&&dp(r,i,t);const o=oe(i,t),a=this.transaction([ke,le],"readwrite");let l=!1;const u=a.objectStore(le).get(o);return u.addEventListener("success",()=>{if(u.result?.generation===n){if(l=!0,r===void 0){a.objectStore(ke).delete(o),a.objectStore(le).delete(o);return}a.objectStore(ke).put(r.blob,o),a.objectStore(le).put(r.metadata,o)}}),await er(a),l}async getBlob(t,n){const s=this.transaction(ke,"readonly").objectStore(ke);if(n)return vt(s.get(oe(n,t)));const i=this._defaultBucket??te,o=await vt(s.get(oe(i,t)));if(o!==void 0)return o;if(i!==te){const a=await vt(s.get(oe(te,t)));if(a!==void 0)return a}return new Promise((a,l)=>{const u=s.openCursor();u.addEventListener("success",()=>{const d=u.result;if(!d){a(void 0);return}const h=String(d.key),f=ti(h);if(f&&f.path===t){a(d.value);return}d.continue()}),u.addEventListener("error",()=>l(u.error))})}async getMetadata(t,n){const s=this.transaction(le,"readonly").objectStore(le);if(n)return vt(s.get(oe(n,t)));const i=this._defaultBucket??te,o=await vt(s.get(oe(i,t)));if(o!==void 0)return o;if(i!==te){const a=await vt(s.get(oe(te,t)));if(a!==void 0)return a}return new Promise((a,l)=>{const u=s.openCursor();u.addEventListener("success",()=>{const d=u.result;if(!d){a(void 0);return}const h=String(d.key),f=ti(h);if(f&&f.path===t){a(d.value);return}d.continue()}),u.addEventListener("error",()=>l(u.error))})}async getObject(t,n){const r=oe(n??this._defaultBucket??te,t),s=this.transaction([ke,le],"readonly"),[i,o]=await Promise.all([vt(s.objectStore(ke).get(r)),vt(s.objectStore(le).get(r))]);if(!(i===void 0||o===void 0))return{blob:i,metadata:o}}async putMetadata(t,n,r){const s=r??n.bucket??this._defaultBucket??te;n.bucket||(n.bucket=s);const i=oe(s,t),o=this.transaction(le,"readwrite");o.objectStore(le).put(n,i),await er(o)}async delete(t,n){const r=n??this._defaultBucket??te,s=oe(r,t),i=this.transaction([ke,le],"readwrite");i.objectStore(ke).delete(s),i.objectStore(le).delete(s),await er(i)}async listByPrefix(t,n){const r=n??this._defaultBucket??te,s=this.transaction(le,"readonly"),i=`${r}/${t}`,o=IDBKeyRange.bound(i,i+"�",!1,!1);return vt(s.objectStore(le).getAll(o))}async reset(t){const n=this.transaction([ke,le],"readwrite");if(!t)n.objectStore(ke).clear(),n.objectStore(le).clear(),this._defaultBucket=void 0;else{const r=`${t}/`,s=IDBKeyRange.bound(r,r+"�",!1,!1);n.objectStore(ke).delete(s),n.objectStore(le).delete(s)}await er(n)}async beginUpload(t,n,r,s,i){const o=t||this._defaultBucket||te;return this.staging.beginUpload(o,n,r,s,i)}async putPart(t,n,r){return this.staging.putPart(t,n,r)}async readUpload(t){return this.staging.readUpload(t)}async abortUpload(t){this.staging.abortUpload(t)}close(){this.db.close()}scoped(t){return new Ci(this,t)}}class Ci{underlying;bucket;constructor(t,n){this.underlying=t,this.bucket=n}get replacedObjectsOnDisk(){return this.underlying.replacedObjectsOnDisk}async put(t,n,r,s){const i=r.bucket?r:{...r,bucket:this.bucket},o=await this.underlying.put(t,n,i,s);return r.generation=i.generation,o}deleteIfGeneration(t,n,r){return this.underlying.deleteIfGeneration(t,n,r??this.bucket)}replaceIfGeneration(t,n,r,s){return this.underlying.replaceIfGeneration(t,n,r,s??this.bucket)}references(t){if(this.underlying.references)return this.underlying.references(t??this.bucket);throw new Error("The underlying storage backend keeps no object files to refer to.")}putReference(t,n,r,s){const i=s.bucket?s:{...s,bucket:this.bucket};if(this.underlying.putReference)return this.underlying.putReference(t,n,r,i);throw new Error("The underlying storage backend keeps no object files to refer to.")}getBlob(t,n){return this.underlying.getBlob(t,n??this.bucket)}getMetadata(t,n){return this.underlying.getMetadata(t,n??this.bucket)}getObject(t,n){return this.underlying.getObject(t,n??this.bucket)}putMetadata(t,n,r){const s=n.bucket?n:{...n,bucket:this.bucket};return this.underlying.putMetadata(t,s,r??this.bucket)}delete(t,n){return this.underlying.delete(t,n??this.bucket)}listByPrefix(t,n){return this.underlying.listByPrefix(t,n??this.bucket)}reset(t){return this.underlying.reset(t??this.bucket)}beginUpload(t,n,r,s,i){const o=t??this.bucket;if(this.underlying.beginUpload)return this.underlying.beginUpload(o,n,r,s,i);throw new Error("Chunked upload not supported by underlying storage backend")}putPart(t,n,r){if(this.underlying.putPart)return this.underlying.putPart(t,n,r);throw new Error("Chunked upload not supported by underlying storage backend")}readUpload(t){if(this.underlying.readUpload)return this.underlying.readUpload(t);throw new Error("Chunked upload not supported by underlying storage backend")}abortUpload(t){return this.underlying.abortUpload?this.underlying.abortUpload(t):Promise.resolve()}close(){this.underlying.close()}scoped(t){return t===this.bucket?this:this.underlying.scoped?this.underlying.scoped(t):new Ci(this.underlying,t)}}function rk(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,QS);r.addEventListener("upgradeneeded",()=>{const i=r.result;i.objectStoreNames.contains(ke)||i.createObjectStore(ke),i.objectStoreNames.contains(le)||i.createObjectStore(le),i.objectStoreNames.contains(br)||i.createObjectStore(br)});let s=!1;r.addEventListener("success",()=>{if(s){r.result.close();return}t(r.result)}),r.addEventListener("error",()=>n(r.error)),r.addEventListener("blocked",()=>{s=!0,n(new ZS("another tab holds it open on an older pyric build"))})}catch(r){n(r)}})}function sk(e,t){const n=e.objectStore(ke).get(t),r=e.objectStore(le).get(t);return{object(){const s=n.result,i=r.result;if(!(s===void 0||i===void 0))return{blob:s,metadata:i}}}}function vt(e){return new Promise((t,n)=>{e.addEventListener("success",()=>t(e.result)),e.addEventListener("error",()=>n(e.error))})}function er(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")))})}class pp{backend;rules;crossServiceIam;constructor(t,n=null,r="granted"){this.backend=t,this.rules=n,this.crossServiceIam=r}}function au(e){switch(e){case"read":return["get","list"];case"write":return["create","update","delete"];default:return[e]}}const ik=new Set(["&&","||","==","!=","<",">","<=",">=","+","-","*","/","%"]);function mp(e){return{segments:e.path.segments.map(ok),children:e.children.map(mp),allows:e.allows.map(t=>({verbs:t.operations,condition:re(t.condition)})),functions:e.functions.map(ea)}}function ok(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 ea(e){return{name:e.name,params:e.parameters,lets:e.lets.map(t=>{const n={name:t.name,value:re(t.value)};return Xf(t,n),n}),body:re(e.body)}}function re(e){const t=ak(e);return Xf(e,t),t}function ak(e){switch(e.type){case"literal":return typeof e.value=="number"&&e.raw.includes(".")?{kind:"literal",value:new Me(e.value)}:e.value instanceof Uint8Array?{kind:"literal",value:new xi(e.value)}:{kind:"literal",value:e.value};case"identifier":return{kind:"ident",name:e.name};case"memberAccess":return{kind:"member",target:re(e.object),name:e.property};case"methodCall":return{kind:"methodcall",target:re(e.object),method:e.method,args:e.args.map(re)};case"bracketAccess":return{kind:"index",target:re(e.object),index:re(e.index)};case"sliceAccess":return{kind:"slice",target:re(e.object),start:re(e.start),end:re(e.end)};case"binaryOp":if(!ik.has(e.op))throw new SyntaxError(`Unsupported binary operator '${e.op}' in storage rules.`);return{kind:"binary",op:e.op,left:re(e.left),right:re(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:re(e.operand)};case"ternary":return{kind:"ternary",cond:re(e.condition),then:re(e.consequent),else:re(e.alternate)};case"inExpr":return{kind:"in",element:re(e.element),collection:re(e.collection)};case"isExpr":return{kind:"is",value:re(e.value),typeName:e.typeName};case"listLiteral":return{kind:"list",elements:e.elements.map(re)};case"mapLiteral":return{kind:"map",entries:e.entries.map(t=>({key:re(t.key),value:re(t.value)}))};case"pathLiteral":return{kind:"path",segments:e.segments.map(t=>typeof t=="string"?{kind:"literal",value:t}:{kind:"interp",expr:re(t)})};case"functionCall":return{kind:"call",name:e.name,args:e.args.map(re)};default:{const t=e;throw new SyntaxError(`Unsupported expression construct: ${JSON.stringify(t)}`)}}}function ta(e){const t=Nb(e);if(!t.ok)throw new SyntaxError(`Storage rules parse error at line ${t.error.line}, column ${t.error.column}: ${Rb(t.error,e)}.`);const n=t.ast;if(n.service.name!=="firebase.storage")throw new SyntaxError(`Expected 'service firebase.storage', got 'service ${n.service.name}'.`);const r=Ib(n);if(r.length>0)throw new SyntaxError(`Storage rules do not compile: ${Ab(r)}`);const s=(n.imports??[]).flatMap(d=>d.functions.map(h=>({name:h,params:[],lets:[],body:{kind:"literal",value:null},unresolvedImport:d.module,scopeKind:"global",declCaptures:new Set}))),i=(n.functions??[]).map(d=>{const h=ea(d);return h.scopeKind="global",h.declCaptures=new Set,h}),o=new Map;for(const d of s)o.set(d.name,d);for(const d of i)o.set(d.name,d);for(const d of o.values())d.declScope=o;const a=(n.service.functions??[]).map(d=>{const h=ea(d);return h.scopeKind="service",h.declCaptures=new Set,h}),l=new Map(o);for(const d of a)l.set(d.name,d);for(const d of a)d.declScope=l;const u={segments:[],children:[mp(n.service.match)],allows:[],functions:[...s,...i,...a],visibleFuncs:l};for(const d of u.children)yp(d,l,new Set);return{_root:u,_version:n.version}}function yp(e,t,n){const r=new Set(n);for(const i of e.segments)(i.kind==="param"||i.kind==="wildcard")&&r.add(i.name);const s=new Map(t);for(const i of e.functions)s.set(i.name,i);e.visibleFuncs=s;for(const i of e.functions)i.declScope=s,i.scopeKind="match",i.declCaptures=r;for(const i of e.children)yp(i,s,r)}function pe(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 pe(e.target,t);case"index":return pe(e.target,t)||pe(e.index,t);case"slice":return[e.target,e.start,e.end].some(n=>pe(n,t));case"unary":return pe(e.arg,t);case"ternary":return[e.cond,e.then,e.else].some(n=>pe(n,t));case"in":return pe(e.element,t)||pe(e.collection,t);case"is":return pe(e.value,t);case"list":return e.elements.some(n=>pe(n,t));case"map":return e.entries.some(({key:n,value:r})=>pe(n,t)||pe(r,t));case"binary":return pe(e.left,t)||pe(e.right,t);case"call":return e.args.some(n=>pe(n,t));case"methodcall":return pe(e.target,t)||e.args.some(n=>pe(n,t));case"path":return e.segments.some(n=>n.kind==="interp"&&pe(n.expr,t));case"ident":case"literal":return!1}}function gp(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&&pe(r,n)))return!0;for(const r of e.functions){const s=new Set([...n,...r.params]);for(const i of r.lets){if(pe(i.value,s))return!0;s.add(i.name)}if(pe(r.body,s))return!0}return e.children.some(r=>gp(r,n))}function ck(e){if(/\\[1-9]/.test(e)||/\(\?<?[=!]/.test(e))return!1;try{return new RegExp(`^(?:${Zf(e)})$`),!0}catch{return!1}}function se(e){if(e.kind==="methodcall"&&e.method==="matches"&&e.args.length===1){const t=e.args[0];if(t?.kind==="literal"&&typeof t.value=="string"&&!ck(t.value))throw new SyntaxError(`Storage rules do not compile: Invalid regular expression pattern. Pattern: ${t.value}.`)}switch(e.kind){case"member":se(e.target);return;case"index":se(e.target),se(e.index);return;case"slice":se(e.target),se(e.start),se(e.end);return;case"unary":se(e.arg);return;case"ternary":se(e.cond),se(e.then),se(e.else);return;case"in":se(e.element),se(e.collection);return;case"is":se(e.value);return;case"list":for(const t of e.elements)se(t);return;case"map":for(const{key:t,value:n}of e.entries)se(t),se(n);return;case"binary":se(e.left),se(e.right);return;case"call":for(const t of e.args)se(t);return;case"methodcall":se(e.target);for(const t of e.args)se(t);return;case"path":for(const t of e.segments)t.kind==="interp"&&se(t.expr);return;case"ident":case"literal":return}}function bp(e){for(const{condition:t}of e.allows)t&&se(t);for(const t of e.functions){for(const n of t.lets)se(n.value);se(t.body)}for(const t of e.children)bp(t)}function lk(e){let t=e,n=[],r=[],s=[],i=ta(t);if(i._version!=="2+modules"){if(i._root.functions.some(a=>a.unresolvedImport!==void 0))throw new SyntaxError("Import statements require rules_version = '2+modules'.")}else{const a=Hf(t);if(!a.success)throw new SyntaxError(`Storage rules module resolution failed (${a.error.code}): ${a.error.message}`);t=a.data.resolved,n=a.data.modules,r=a.data.bundledModules,s=a.data.evidenceIds,i=ta(t)}bp(i._root);const o=uk(t,n,r,s,i);return{rules:i,resolution:o}}function uk(e,t,n,r,s){const i=new Set;for(const o of r)o.startsWith("storage-rules#")&&i.add(o);return gp(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 wp="pyric-default",Ni=Symbol.for("pyric/storage/target");function qt(e){return e.currentAuth?.()??e.context.auth}const dk=Symbol.for("pyric.storage.service-caches"),fk=globalThis,mn=fk[dk]??={openServices:new WeakMap,hostBackends:new WeakMap,scopedServices:new WeakMap,sandboxHandles:new WeakMap,bareSandboxHandles:new WeakMap,adminContextHandles:new WeakMap,bareAdminHandles:new WeakMap},cu=mn.openServices,hk=mn.hostBackends,lu=mn.scopedServices;function pk(e,t,n){let r=lu.get(e);r||(r=new Map,lu.set(e,r));let s=r.get(t);return s||(s=n.then(i=>{const o=i.backend.scoped?i.backend.scoped(t):i.backend;return new pp(o,i.rules,i.crossServiceIam)}),r.set(t,s)),s}mn.sandboxHandles;mn.bareSandboxHandles;function uu(e,t,n,r,s){if(n===void 0||n===r)return;const i=r===null?`without ${e}`:`with a different ${t}`;throw new Error(`pyric/storage: ${s} received a ${t}, but this sandbox's storage service is already open ${i}. ${e} is honored only on the FIRST storage call per Sandbox, so this value would be silently discarded. Configure it on the first storage call for this sandbox.`)}function mk(e,t,n){const r=cu.get(e);if(r!==void 0)return uu("rules","rules source",t.rules,r.rulesSource,n),uu("crossServiceIam","crossServiceIam mode",t.crossServiceIam,r.crossServiceIam,n),r.service;let i=null,o=null;const a=t.rules;if(typeof a=="string"&&a.length>0){const m=lk(a);i=m.rules,o=m.resolution}const u=t.crossServiceIam??"granted",d=hk.get(e);let h;d!==void 0?h=Promise.resolve(d):h=XS(t.dbName??YS(t.projectId),t.bucket??wp);const p=h.then(m=>new pp(m,i,u));return cu.set(e,{service:p,rulesSource:t.rules??null,rulesResolution:o,crossServiceIam:u}),e.registerPersistableService("storage",{snapshot:()=>null,restore:()=>{},reset:async()=>{await(await p).backend.reset()}}),p}function so(e){return e instanceof Ob||"sandbox"in e&&e.sandbox!==void 0}const io=mn.adminContextHandles,oo=mn.bareAdminHandles;function yk(e,t={}){const n=!so(e),r=so(e)?e.sandbox:e,s=mk(r,t,"getAdminStorageSandbox"),i=t.bucket??wp;if(n){const p=oo.get(r)?.get(i);if(p)return p}const o=so(e)?e:r.withAuth(null),a=o.operationContext.authLens.mode==="admin"?o:eh(o,{source:o.operationContext.source,authLens:{mode:"admin"},...o.operationContext.planId===void 0?{}:{planId:o.operationContext.planId}}),l=io.get(o)?.get(i);if(l)return l;const u=pk(r,i,s),d={kind:"sandbox",sandbox:r,context:a,bucket:i,servicePromise:u,admin:!0},h=Object.freeze({[Ni]:d});let f=io.get(o);if(f||(f=new Map,io.set(o,f)),f.set(i,h),n){let p=oo.get(r);p||(p=new Map,oo.set(r,p)),p.set(i,h)}return h}function zt(e,t){const n=$b(t,Uo(e.context.operationContext));return{...t,...Uo(n),service:"storage"}}function Le(e){const t=e[Ni];if(!t)throw new TypeError("pyric/storage: not a FirebaseStorage handle — was it produced by getStorageSandbox?");return t}function Ht(e){return Le(e).servicePromise}function gk(e){return`storage/${e}`}class Nt extends Error{code;constructor(t,n){const r=gk(t);super(`${r}: ${n}`),this.name="StorageError",this.code=r,Object.setPrototypeOf(this,Nt.prototype)}}function vp(e){return new Nt("object-not-found",`no object at "${e}".`)}function du(e,t,n){return new Nt("unauthorized",$S(`${e} "${t}" denied by rules${n}`))}function Ri(e){return new Nt("invalid-root-operation",`${e} cannot operate on the root reference.`)}function fu(){return new Nt("canceled","User canceled the upload/download.")}const ms="([A-Za-z0-9.\\-_]+)",bk=e=>e,wk=[{pattern:new RegExp(`^gs://${ms}(?:/(.*))?$`,"i"),path:bk},{pattern:new RegExp(`^https?://firebasestorage\\.googleapis\\.com/v[A-Za-z0-9_]+/b/${ms}/o(?:/([^?#]*).*)?$`,"i"),path:decodeURIComponent},{pattern:new RegExp(`^https?://(?:storage\\.googleapis\\.com|storage\\.cloud\\.google\\.com)/${ms}/([^?#]*)`,"i"),path:decodeURIComponent},{pattern:new RegExp(`^https?://[^/?#]+/__pyric/storage/v0/b/${ms}/o/([^?#]+)`),path:decodeURIComponent}];function vk(e){for(const t of wk){const n=t.pattern.exec(e);if(n!==null)return{bucket:n[1],path:t.path(n[2]??"")}}}const xk=/^[A-Za-z]+:\/\//,wc=/^data:[^,]*,/i;function hu(e,t){return new Nt("invalid-url",`Invalid URL '${e}'. ${t}`)}function _k(e){return xk.test(e)||wc.test(e)}function Sk(e){if(wc.test(e))throw hu(e.length>64?`${e.slice(0,64)}...`:e,"A data: URI carries an object's bytes, not its location. Reference the object by its path or its gs:// URL.");const n=vk(e);if(n!==void 0)return n;throw hu(e,"Expected a gs:// URL or a Storage download URL.")}function na(e,t){const n=e??"";if(!_k(n))return n;const s=wc.test(n);if(!t&&!s)throw new Nt("invalid-argument","To use ref(service, url), the first argument must be a Storage instance.");return Sk(n).path}function Or(e,t){return jk(e)?(Le(e.storage),new $r(e.storage,kk(e.fullPath,na(t,!1)))):(Le(e),new $r(e,xp(na(t,!0))))}class $r{storage;bucket;fullPath;constructor(t,n){this.storage=t;const r=Le(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 $r(this.storage,n)}get root(){return this.fullPath===""?this:new $r(this.storage,"")}toString(){return`gs://${this.bucket}/${this.fullPath}`}}function xp(e){return e===""?"":e.split("/").filter(t=>t.length>0).join("/")}function kk(e,t){const n=xp(t);return e===""?n:n===""?e:`${e}/${n}`}function jk(e){if(e===null||typeof e!="object"||Ni in e)return!1;const t=e;return typeof t.fullPath=="string"&&t.storage!==void 0}const ni=new WeakMap;function Ut(e){ni.get(e)?.progress()}function ri(e){const t=ni.get(e);t?.delivered(void 0,{}),t?.progress()}function qn(e,t){return(n,...r)=>{const s=Kr.begin({app:n.storage??n.port??n,method:e,kind:"operation",source:{service:"storage",target:`${n.bucket}/${n.fullPath}`,key:`storage:${n.bucket}/${n.fullPath}`}});try{const i=t(n,...r);return e==="uploadBytesResumable"&&ni.set(i,s),i.then(o=>{const a=Ek(e,o);s.delivered(void 0,e.startsWith("get")||e==="listAll"?a:{}),e==="uploadBytesResumable"&&s.progress(),s.complete(e.startsWith("get")||e==="listAll"?void 0:a)},()=>{s.fail(),ni.delete(i)}),i}catch(i){throw s.fail(),i}}}function Ek(e,t){if(e==="getBytes"&&t instanceof ArrayBuffer)return{downloadedBytes:t.byteLength};if(e==="getBlob"&&t&&typeof t=="object"&&"size"in t&&typeof t.size=="number")return{downloadedBytes:t.size};if(e.startsWith("upload")&&t&&typeof t=="object"&&"metadata"in t){const n=t.metadata;if(typeof n.size=="number")return{uploadedBytes:n.size}}return{}}class z{message;constructor(t){this.message=t}}function K(e){return e instanceof z}function si(e){if(typeof e=="number")return e;if(e instanceof Me)return e.value}class B extends Error{}class ns extends B{}class rs extends B{}class pu extends rs{position;constructor(t,n){super(t),this.position=n}}function Ck(e){return e instanceof B&&!(e instanceof ns)&&!(e instanceof rs)}function Ue(e){return new B(Pb(e))}function yn(e){if(e.args.length!==0)throw new B(`${e.method}() expects no arguments`)}function Ze(e,t){return dt(e.args,t)}function ss(e,t){const n=Ze(e,t);return K(n)||t.expressionBudget?.node(e),n}function Oe(e,t){if(yn(t),e instanceof ct){const n=e.callMethod(t.method,[]);if(n!==Bo)return n}throw Ue(t.method)}const Nk=/^(?:\{([A-Za-z_][A-Za-z0-9_]*)\}|\$\(([A-Za-z_][A-Za-z0-9_]*)\))$/;class He extends ct{path;typeName="path";bindings;constructor(t,n={}){super(),this.path=t,this.bindings=n}get segments(){return this.path.split("/").filter(Boolean)}bind(t){const n=[],r={...this.bindings};for(const s of this.segments){const i=Nk.exec(s);if(!i){n.push(s);continue}const o=i[1]??i[2];if(Object.hasOwn(t,o)){const a=t[o];if(a==null||typeof a!="string"&&typeof a!="number")throw new TypeError(`Path.bind(): binding '${o}' must not be null`);const l=String(a);n.push(l),r[o]=l}else n.push(s)}return new He("/"+n.join("/"),r)}valueOf(){return NaN}toJSON(){return{__type:"path",path:this.toString()}}equals(t){return(t instanceof He||t instanceof ct&&t.typeName==="path")&&String(t)===this.toString()}toString(){return this.path.startsWith("/")?this.path:`/${this.path}`}}function Rk(e,t,n){if(!(e instanceof He))throw Ue("bind");const r=Ze(t,n);if(K(r))return r;if(r.length!==1)throw new B(`Incorrect number of arguments. Received: ${r.length}. Expected: path.bind(map).`);const[s]=r;if(!Ft(s))return new z("path.bind() requires a map argument");try{return e.bind(s)}catch(i){return new z(i.message)}}const Ik={bind:Rk};function _p(e){const t={};for(const[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}function Ak(e){return _p({size:e.size,contentType:e.contentType,metadata:e.metadata,name:e.name,bucket:e.bucket,generation:e.generation,metageneration:e.metageneration,timeCreated:mu(e.timeCreated),updated:mu(e.updated)})}function mu(e){if(e===void 0)return;const t=Date.parse(e);if(!Number.isNaN(t))return jr.fromMillis(t)}function Ok(e,t){const n=e.request.auth;let r;return n==null?r=new z("Property auth is undefined on object."):r=vi(n),{auth:r,resource:e.request.resource!==void 0?_p(e.request.resource):new z("Property resource is undefined on object."),method:e.request.method,path:new He(e.request.path),time:jr.fromMillis(t)}}const $k=["addedKeys","affectedKeys","changedKeys","removedKeys","unchangedKeys"];function Pk(e,t,n){return e instanceof Gr?vc(e,t,n):(yn(t),typeof e=="string"||Array.isArray(e)?e.length:Ft(e)?Object.keys(e).length:Oe(e,t))}function yu(e,t,n){if(!Ft(e))throw Ue(t.method);const r=Ze(t,n);if(K(r))return r;const s=Tb(t.method,e,r);if(s instanceof Mb)throw new B(s.message);return s}function vc(e,t,n){const r=Ze(t,n);if(K(r))return r;const s=Ub(e,t.method,r);if(s instanceof Bb)throw new B(s.message);return s}const Dk={concat:(e,t)=>qb(e,t),join:(e,t)=>Vb(e,t),removeAll:(e,t)=>Fb(e,t)};function ao(e,t,n){if(!Array.isArray(e))throw Ue(t.method);const r=Ze(t,n);if(K(r))return r;const s=Dk[t.method](e,r);if(s instanceof th)throw new B(s.message);return s}function Tk(e,t,n){if(!Ft(e))throw Ue(t.method);if(t.args.length!==2)throw new B("get() expects a key and default value");const r=Ze(t,n);if(K(r))return r;const[s,i]=r;if(typeof s=="string")return Object.hasOwn(e,s)&&e[s]!==void 0?e[s]:i;if(Array.isArray(s)){for(const a of s)if(typeof a!="string")throw new B("get() key list elements must be strings");let o=e;for(const a of s){if(!Ft(o)||!Object.hasOwn(o,a)||o[a]===void 0)return i;o=o[a]}return o}throw new B("get() key must be a string or list of strings")}function co(e,t,n){if(e instanceof Gr)return vc(e,t,n);if(!Array.isArray(e))throw Ue(t.method);const r=Ze(t,n);if(K(r))return r;const s=Lb(t.method,e,r);if(s instanceof th)throw new B(s.message);return s}function Mk(e,t){if(!Array.isArray(e))throw Ue(t.method);if(t.args.length!==0)throw new B(`Incorrect number of arguments. Received: ${t.args.length}. Expected: list.toSet().`);return new Gr(e)}function Lk(e,t,n){if(!(e instanceof Gr))throw Ue(t.method);return vc(e,t,n)}function Uk(e,t,n){if(!Ft(e))throw Ue(t.method);if(t.args.length!==1)throw new B("diff() expects one map argument");const r=Ze(t,n);if(K(r))return r;const[s]=r;if(!Ft(s))throw new B(`diff() argument must be a map, got ${De(s)}`);return new nh(s,e)}function Bk(e,t){if(yn(t),!(e instanceof nh))throw Ue(t.method);return e[t.method]()}function gu(e,t){return Object.fromEntries(e.map(n=>[n,t]))}const Fk={concat:ao,diff:Uk,get:Tk,hasAll:co,hasAny:co,hasOnly:co,join:ao,keys:yu,removeAll:ao,size:Pk,toSet:Mk,values:yu,...gu([...Db],Lk),...gu($k,Bk)};function Vk(e){if(typeof e=="number")return e;if(e instanceof Me)return e.value}function qk(e,t,n,r){const i=f=>f*Math.PI/180,o=i(e),a=i(n),l=i(n-e),u=i(r-t),d=Math.sin(l/2)**2+Math.cos(o)*Math.cos(a)*Math.sin(u/2)**2;return 6371e3*(2*Math.atan2(Math.sqrt(d),Math.sqrt(1-d)))}function Pr(e){return e instanceof ii?{latitude:e.latitude,longitude:e.longitude}:e instanceof rh?{latitude:e.lat,longitude:e.lng}:null}function Wk(e,t){const n=ss(e,t);if(K(n))return n;if(e.method!=="value")return new z(`unsupported latlng.${e.method}()`);const[r,s]=n.map(Vk);return n.length!==2||r===void 0||s===void 0||!Number.isFinite(r)||!Number.isFinite(s)?new z("latlng.value() expects (latitude: number, longitude: number)"):r<-90||r>90?new z(`Latitude must be in the range [-90, 90], got ${r}.`):s<-180||s>180?new z(`Longitude must be in the range [-180, 180], got ${s}.`):new ii(r,s)}class ii extends ct{latitude;longitude;typeName="latlng";constructor(t,n){super(),this.latitude=t,this.longitude=n}valueOf(){return NaN}toJSON(){return{__type:"latlng",latitude:this.latitude,longitude:this.longitude}}equals(t){const n=Pr(t);return n!==null?n.latitude===this.latitude&&n.longitude===this.longitude:t instanceof ct&&t.typeName==="latlng"&&t.latitude===this.latitude&&t.longitude===this.longitude}toString(){return`[${this.latitude}, ${this.longitude}]`}}function zk(e,t){const n=Pr(e);if(n===null)throw Ue("latitude");return yn(t),new Me(n.latitude)}function Hk(e,t){const n=Pr(e);if(n===null)throw Ue("longitude");return yn(t),new Me(n.longitude)}function Kk(e,t,n){const r=Pr(e);if(r===null)throw Ue("distance");const s=Ze(t,n);if(K(s))return s;if(s.length!==1)throw new B(`Incorrect number of arguments. Received: ${s.length}. Expected: latlng.distance(latlng).`);const i=Pr(s[0]);return i===null?new z("latlng.distance() requires a latlng argument"):new Me(qk(r.latitude,r.longitude,i.latitude,i.longitude))}const Gk={distance:Kk,latitude:zk,longitude:Hk};function ra(e){if(e==null)return e;if(typeof e=="number")return Number.isInteger(e)?e:new Me(e);if(e instanceof Date)return jr.fromMillis(e.getTime());if(e instanceof Uint8Array)return new xi(e);if(e instanceof rh)return new ii(e.lat,e.lng);if(e instanceof Wb)return new He(e.toString());if(e instanceof ct)return e;if(typeof e=="object"){if(Array.isArray(e))return e.map(ra);const t=e,n=Object.keys(t),r=t.latitude??t._latitude,s=t.longitude??t._longitude;if(t.__type==="latlng"||n.length===2&&typeof r=="number"&&typeof s=="number")return new ii(r,s);if(t.__type==="path"||n.length===1&&typeof t.path=="string"&&t.path.startsWith("/databases/"))return new He(t.path);const i={};for(const[o,a]of Object.entries(t))i[o]=ra(a);return i}return e}function Jk(e,t){if(t.expressionBudget?.node(e),e.method!=="get"&&e.method!=="exists")throw new ns(`unsupported method firestore.${e.method}()`);if(!t.firestoreLookup)throw new B(`firestore.${e.method}() is unsupported here — no Firestore lookup capability is configured`);if(e.args.length!==1)throw new B(`firestore.${e.method}() expects a single path argument`);const n=e.args[0];let r;if(n.kind==="path"){t.expressionBudget?.node(n);for(const i of n.segments)i.kind==="literal"&&t.expressionBudget?.pathSegment(n);r=bu(n,t)}else{const i=rt(n,t);if(K(i))return i;if(i instanceof He||i instanceof ct&&i.typeName==="path"){const a=(i instanceof He?i.path:String(i)).split("/").filter(Boolean).map(l=>({kind:"literal",value:l}));r=bu({segments:a},t)}else return new z(`Function not found error: Name: [${e.method}].`)}if(!t.firestoreAccesses.has(r)){if(t.firestoreAccesses.size>=2)throw new rs("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 z(`firestore.get() targeted a nonexistent document: ${r}`):{data:ra(s)}}function bu(e,t){const n=dt(e.segments.flatMap(o=>o.kind==="literal"?[]:[o.expr]),t);if(K(n))throw new B(n.message);let r=0;const s=e.segments.map(o=>{if(o.kind==="literal")return o.value;const a=n[r++];if(typeof a=="string")return a;if(typeof a=="number")return String(a);throw new B(`Firestore path interpolation resolved to ${De(a)} (expected a string)`)});if(s.length<4||s[0]!=="databases"||s[2]!=="documents")throw new B(`malformed Firestore path — expected /databases/<db>/documents/... , got /${s.join("/")}`);if(s[1]!=="(default)")throw new B(`Storage rules may access only the default Firestore database, got ${s[1]}`);const i=s.slice(3);if(i.length===0||i.length%2!==0)throw new B(`Firestore path does not point at a document (needs an even segment count): ${i.join("/")}`);return i.join("/")}const Yk=new Set(["crc32","crc32c","md5","sha256"]);function Qk(e,t){if(!Yk.has(e.method))throw new ns(`unsupported method hashing.${e.method}()`);const n=ss(e,t);if(K(n))return n;if(n.length!==1)throw new B(`hashing.${e.method}() expects a single string or bytes argument`);const[r]=n;if(typeof r!="string"&&!(r instanceof xi))throw new B(`Unsupported operation error. Received: hashing.${e.method}(${De(r)}). Expected: hashing.${e.method}(bytes), hashing.${e.method}(string).`);return zb(e.method,[r])}const Xk={toBase64:Oe,toHexString:Oe};function Zk(e,t){const n=ss(e,t);if(K(n))return n;const r=Hb(e.method,n);return r instanceof Kb?new z(r.message):r}function is(e,t){if(typeof e!="string")throw Ue(t.method);return e}function Sp(e,t){if(e.args.length!==1)throw new B(`${e.method}() expects a single pattern argument`);const n=Ze(e,t);if(K(n))return n;const[r]=n;if(typeof r!="string")throw new B(`${e.method}() pattern must be a string`);return r}function ej(e,t,n){const r=is(e,t),s=Sp(t,n);if(typeof s!="string")return s;try{return Gb(s,r)}catch(i){throw new B(i.message)}}function tj(e,t,n){const r=is(e,t),s=Sp(t,n);return typeof s!="string"?s:r.split(kp("split",s,s))}function nj(e,t,n){const r=is(e,t),s=Ze(t,n);if(K(s))return s;const[i,o]=s;if(s.length!==2||typeof i!="string"||typeof o!="string")throw new B("replace() expects (pattern: string, replacement: string)");const a=kp("replace",i,i,"g"),l=sj(a);return r.replace(a,(...u)=>{const d=u.slice(0,l+1);return ij(o,d,rj(u[u.length-1]))})}function rj(e){return typeof e=="object"&&e!==null?e:{}}function sj(e){const t=new RegExp(`${e.source}|`).exec("");return t===null?0:t.length-1}function ij(e,t,n){const r=t.length-1;let s="",i=0;for(;i<e.length;){const o=e[i];if(o==="\\"){if(i+1>=e.length)throw new B("replace() replacement ends with an escape character");s+=e[i+1],i+=2;continue}if(o!=="$"){s+=o,i+=1;continue}const a=e[i+1];if(a==="{"){const d=e.indexOf("}",i+2);if(d===-1)throw new B(`replace() replacement has an unclosed group name: ${e.slice(i)}`);const h=e.slice(i+2,d);if(!Object.hasOwn(n,h))throw new B(`replace() replacement names no group: ${e.slice(i,d+1)}`);s+=n[h]??"",i=d+1;continue}if(a===void 0||a<"0"||a>"9")throw new B(`replace() replacement has an illegal group reference: ${e.slice(i)}`);let l=Number(a),u=i+2;for(;u<e.length&&e[u]>="0"&&e[u]<="9";){const d=l*10+Number(e[u]);if(d>r)break;l=d,u+=1}if(l>r)throw new B(`replace() replacement names group ${l}, but the pattern has ${r}`);s+=t[l]??"",i=u}return s}function lo(e,t){const n=is(e,t);return yn(t),t.method==="lower"?n.toLowerCase():t.method==="upper"?n.toUpperCase():n.trim()}function oj(e,t){const n=is(e,t);return yn(t),xi.fromUtf8(n)}function aj(e){let t=!1,n=!1,r=!1,s=!1,i=!1,o=0;for(;o<e.length;){const l=e[o];if(l==="\\"){const u=e[o+1];if(!t&&u!==void 0&&u>="1"&&u<="9")return{unsupported:"backreference",inlineFlags:""};o+=2,n=!1;continue}if(t){l==="]"&&!n&&(t=!1),n=!1,o++;continue}if(l==="["){t=!0,o++,e[o]==="^"&&o++,n=!0;continue}if(l==="("&&e[o+1]==="?"){const u=e.slice(o+2);if(u.startsWith("=")||u.startsWith("!")||u.startsWith("<=")||u.startsWith("<!"))return{unsupported:"lookaround",inlineFlags:""};const d=/^([imsU-]+)[):]/.exec(u);if(d){let h=!1;for(const f of d[1])f==="-"?h=!0:f==="i"?r=!h:f==="m"?s=!h:f==="s"&&(i=!h)}}o++}return{unsupported:null,inlineFlags:`${r?"i":""}${s?"m":""}${i?"s":""}`}}function kp(e,t,n,r=""){const{unsupported:s,inlineFlags:i}=aj(t);if(s!==null)throw new B(`${e}() pattern uses an RE2-unsupported construct (${s}) that production would reject`);const o=Array.from(new Set((r+i).split(""))).join("");try{return new RegExp(Zf(n),o)}catch(a){throw new B(`${e}() invalid regex pattern: ${a.message}`)}}const cj={lower:lo,matches:ej,replace:nj,split:tj,toUtf8:oj,trim:lo,upper:lo},wu=["w","d","h","m","s","ms","ns"],lj=-621355968e5,uj=0xe677d21fdbff,vu=315576e6;function dj(e,t){const n=ss(e,t);if(K(n))return n;if(e.method==="value"){if(n.length!==1||typeof n[0]!="number"||!Number.isInteger(n[0]))throw new B("timestamp.value() expects (epochMillis: number)");const r=n[0];if(r<lj||r>uj)throw new B("timestamp.value() out of range [0001-01-01T00:00:00Z, 9999-12-31T23:59:59.999Z]");return jr.fromMillis(r)}if(e.method==="date"){if(n.length!==3||!n.every(o=>typeof o=="number"&&Number.isInteger(o)))throw new B("timestamp.date() expects (year, month, day) numbers");const[r,s,i]=n;try{return jr.fromYMD(r,s,i)}catch(o){throw new B(o.message)}}throw new B(`unsupported timestamp.${e.method}()`)}function fj(e,t){const n=ss(e,t);if(K(n))return n;if(e.method==="value"){if(n.length!==2||typeof n[0]!="number"||!Number.isInteger(n[0])||typeof n[1]!="string")throw new B("duration.value() expects (magnitude: number, unit: string)");const[r,s]=n;if(!wu.includes(s))throw new B(`duration.value() got unknown unit "${s}", expected one of ${wu.join(", ")}`);const i=fs.fromValue(r,s);if(!Number.isFinite(i.seconds)||Math.abs(i.seconds)>vu)throw new B("duration.value() exceeds maximum range of +/-10000 years");return i}if(e.method==="time"){if(n.length!==4||!n.every(l=>typeof l=="number"&&Number.isInteger(l)))throw new B("duration.time() expects (hours, minutes, seconds, nanos) numbers");const[r,s,i,o]=n,a=fs.fromTime(r,s,i,o);if(!Number.isFinite(a.seconds)||Math.abs(a.seconds)>vu)throw new B("duration.time() exceeds maximum range of +/-10000 years");return a}if(e.method==="abs"){if(n.length!==1||!(n[0]instanceof fs))throw new B("duration.abs() expects a single duration");return fs.abs(n[0])}throw new B(`unsupported duration.${e.method}()`)}const hj={date:Oe,day:Oe,dayOfWeek:Oe,dayOfYear:Oe,hours:Oe,minutes:Oe,month:Oe,nanos:Oe,seconds:Oe,time:Oe,toMillis:Oe,year:Oe},pj=new Map([["duration",fj],["firestore",Jk],["hashing",Qk],["latlng",Wk],["math",Zk],["timestamp",dj]]),mj=bj([Xk,Fk,Gk,Ik,cj,hj]);function yj(e,t){const n=gj(e,t);if(n!==void 0)return n(e,t);const r=mj.get(e.method);if(r===void 0)throw new ns(`unsupported method .${e.method}()`);const s=Dr(e.target,t);return K(s)?(Ze(e,t),s):r(s,e,t)}function gj(e,t){if(e.target.kind!=="ident")return;const n=e.target.name;if(!(Object.hasOwn(t.locals,n)||Object.hasOwn(t.params,n)))return pj.get(n)}function bj(e){const t=new Map;for(const n of e)for(const[r,s]of Object.entries(n)){if(t.has(r))throw new Error(`storage rules method .${r}() has two evaluators`);t.set(r,s)}return t}const wj=new Set(["timestamp","duration","bytes","latlng","path"]);function vj(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 Me||typeof e=="number"&&!Number.isInteger(e);case"number":return e instanceof Me||typeof e=="number";case"list":return Array.isArray(e);case"set":return e instanceof Gr;case"map":return Ft(e);case"null":return e===null}return wj.has(t)?e instanceof ct&&e.typeName===t:new z(`'is ${t}' is not supported by the storage evaluator.`)}function xu(e){return e instanceof ct&&!(e instanceof Me)}function xj(e,t,n){if(t instanceof ct){const r=t.binaryOp(e,n);if(r!==Bo)return r}if(e==="+"&&n instanceof ct){const r=n.binaryOp(e,t);if(r!==Bo)return r}return xc(e,t,n)}function xc(e,t,n){return new z(`Unsupported operation error. Received: ${De(t)} ${e} ${De(n)}.`)}function _u(e){return e instanceof Me}function _j(e,t,n){if(e==="+"&&typeof t=="string"&&typeof n=="string")return t+n;const r=si(t),s=si(n);if(r===void 0||s===void 0)return xc(e,t,n);const i=_u(t)||_u(n);let o;switch(e){case"+":o=r+s;break;case"-":o=r-s;break;case"*":o=r*s;break;case"/":if(!i&&s===0)return new z(il);o=i?r/s:Math.trunc(r/s);break;case"%":if(!i&&s===0)return new z(il);o=r%s;break}return i?new Me(o):o}function Sj(e,t,n){const r=si(t),s=si(n);return r!==void 0&&s!==void 0?Su(e,r,s):typeof t=="string"&&typeof n=="string"?Su(e,t,n):xc(e,t,n)}function Su(e,t,n){switch(e){case"<":return t<n;case">":return t>n;case"<=":return t<=n;case">=":return t>=n}}function kj(e){return e.split("/").filter(t=>t.length>0)}function bn(e){return"/"+e.map(t=>t.kind==="literal"?t.value:t.kind==="param"?`{${t.name}}`:`{${t.name}=**}`).join("/")}function ku(e,t,n){let r=0;const s={...n};for(let i=0;i<e.length;i++){const o=e[i];if(o.kind==="wildcard"){const a=e.length-1-i,l=t.length-r-a;if(l<0)return null;const u=t.slice(r,r+l);s[o.name]=new He("/"+u.join("/")),r+=l;continue}if(r>=t.length)return null;if(o.kind==="literal"){if(t[r]!==o.value)return null;r++}else s[o.name]=t[r],r++}return{left:t.slice(r),params:s}}function jp(e,t,n=new Date,r){const s=n.getTime(),i=kj(t.request.path),o=[],a=new Set,l=new Jb((g,b)=>new pu(g,b));let u,d=!1,h;const f=new Set(au(t.request.method));function p(g,b,w){if(d)return!1;const x=ku(g.segments,b,w);if(!x)return!1;const v=x.params,_=x.left;if(_.length===0)for(const k of g.allows){const N=new Set(k.verbs.flatMap(au));if(![...f].some(R=>N.has(R)))continue;let P;try{let R=!0;if(k.condition&&(R=rt(k.condition,{input:t,now:s,params:v,matchParams:v,scopeKind:"match",locals:{},funcs:g.visibleFuncs??new Map,firestoreLookup:r,firestoreAccesses:a,expressionBudget:l})),typeof R=="boolean")P=R;else{let j;K(R)?j=R:j=new z(`Allow condition expected bool, got ${De(R)}.`),h??=j.message,o.push(`match ${bn(g.segments)} ${t.request.method}: ${j.message}`);continue}}catch(R){if(R instanceof pu)return d=!0,h===void 0?(u={message:R.message,position:R.position},o.push(`match ${bn(g.segments)} ${t.request.method}: ${Qb(R.message,R.position)}`)):o.push(`match ${bn(g.segments)} ${t.request.method}: ${R.message} Reached after an earlier allow rule raised an error; production reports that earlier error: ${h}`),!1;if(R instanceof rs)return d=!0,o.push(`match ${bn(g.segments)} ${t.request.method}: ${R.message}`),!1;if(R instanceof B){h??=R.message,o.push(`match ${bn(g.segments)} ${t.request.method}: ${R.message}`);continue}throw R}if(P)return!0;o.push(`match ${bn(g.segments)} ${t.request.method}: condition false`)}const S=g.segments[g.segments.length-1];if(g.children.length>0&&S!==void 0&&S.kind==="wildcard"){const k=g.segments.slice(0,-1),N=ku(k,b,w);if(N){const O=N.left;for(let P=O.length;P>=0;P--){const R=O.slice(0,P),j=O.slice(P),E={...N.params,[S.name]:new He("/"+R.join("/"))};for(const $ of g.children)if(p($,j,E))return!0}return!1}}for(const k of g.children)if(p(k,_,v))return!0;return!1}const m=p(e._root,i,{});return!m&&o.length===0&&o.push(`no rule matches ${t.request.method} /${i.join("/")}`),{allowed:m,reasons:o,evaluatedExpressions:l.evaluated,...u!==void 0?{resourceLimit:{kind:"expressions",limit:Yb,message:u.message,...u.position===void 0?{}:{line:u.position.line,column:u.position.column}}}:{}}}function jj(e,t){const n=rw(e,t);return n instanceof sh?new z(n.message):n}function rt(e,t){const n=t.expressionBudget;if(!n)return uo(e,t);if(e.kind==="call")return n.call(e),uo(e,t);let r;try{r=uo(e,t)}catch(s){throw s instanceof rs||n.node(e),s}return n.node(e),r}function uo(e,t){switch(e.kind){case"literal":return e.value;case"ident":{if(Object.hasOwn(t.locals,e.name))return t.locals[e.name];if(t.scopeKind!=="global"){if(e.name==="request")return Ok(t.input,t.now);if(e.name==="resource")return t.input.resource===null?new z("Null value error."):Ak(t.input.resource)}return Object.hasOwn(t.params,e.name)?t.params[e.name]:new z(`Identifier ${e.name} is undefined.`)}case"member":{const n=rt(e.target,t);return K(n)?n:n==null?new z("Null value error."):jj(n,e.name)}case"index":{const n=dt([e.index,e.target],t);if(K(n))return n;const[r,s]=n;if(s==null)return new z("Null value error.");const i=nw(s,r);return i instanceof sh?new z(i.message):i}case"call":return Ej(e,t);case"methodcall":return yj(e,t);case"path":{t.expressionBudget?.node(e);for(const i of e.segments)i.kind==="literal"&&t.expressionBudget?.pathSegment(e);const n=dt(e.segments.flatMap(i=>i.kind==="literal"?[]:[i.expr]),t);if(K(n))return n;let r=0;const s=[];for(const i of e.segments){if(i.kind==="literal"){s.push(i.value);continue}const o=n[r++];if(typeof o!="string"&&typeof o!="number")return new z(`Path interpolation resolved to ${De(o)} (expected a string)`);s.push(String(o))}return new He(`/${s.join("/")}`)}case"unary":{const n=rt(e.arg,t);if(e.op==="!"){if(K(n))throw new B(n.message);if(typeof n!="boolean")throw new B(`Unary '!' expects a boolean, got ${De(n)}.`);return!n}return K(n)?n:e.op==="-"?n instanceof Me?new Me(-n.value):typeof n!="number"?new z(`Unary '-' applied to ${De(n)}.`):-n:void 0}case"ternary":{t.expressionBudget?.ternary(e);const n=rt(e.cond,t);return K(n)?n:typeof n!="boolean"?new z(`Ternary condition expected bool, got ${De(n)}.`):n?rt(e.then,t):(t.expressionBudget?.ternaryElse(e),rt(e.else,t))}case"in":{const n=dt([e.collection,e.element],t);if(K(n))return n;const[r,s]=n,i=ew(s,r);return i instanceof tw?new z(i.message):i}case"is":{const n=rt(e.value,t);return K(n)?n:vj(n,e.typeName)}case"list":return dt(e.elements,t);case"map":{const n=dt(e.entries.flatMap(s=>[s.key,s.value]),t);if(K(n))return n;const r=[];for(let s=0;s<n.length;s+=2){const i=n[s];if(typeof i!="string")return new z(`Map literal key is ${De(i)} (expected a string).`);r.push([i,n[s+1]])}return Zb(r)}case"slice":{const n=dt([e.target,e.start,e.end],t);if(K(n))return n;const[r,s,i]=n;if(typeof s!="number"||typeof i!="number"||!Number.isInteger(s)||!Number.isInteger(i))return new z("Slice bounds must be integers.");if(Array.isArray(r)||typeof r=="string"){const o=Xb(s,i,r.length);return o?new z(o):r.slice(s,i)}return new z(`Slice applied to ${De(r)} (expected a list or string).`)}case"binary":{if(e.op==="&&")return ju(e,!1,t);if(e.op==="||")return ju(e,!0,t);const n=dt([e.left,e.right],t);if(K(n))return n;const[r,s]=n;if(e.op!=="=="&&e.op!=="!="&&(xu(r)||xu(s)))return xj(e.op,r,s);switch(e.op){case"==":return ol(r,s);case"!=":return!ol(r,s);case"<":case">":case"<=":case">=":return Sj(e.op,r,s);case"+":case"-":case"*":case"/":case"%":return _j(e.op,r,s)}}}}function ju(e,t,n){const{left:r,right:s}=e,i=Eu(r,n);if(i===t)return t;n.expressionBudget?.logicalRight(e);const o=Eu(s,n);return o===t?t:K(i)?i:o}function Eu(e,t){const n=Dr(e,t);return K(n)?n:typeof n!="boolean"?new z(`Expected a boolean '&&'/'||' operand, got ${De(n)}.`):n}function Dr(e,t){try{return rt(e,t)}catch(n){if(Ck(n))return new z(n.message);throw n}}function dt(e,t){const n=[];let r;for(const s of e){const i=Dr(s,t);K(i)&&(r??=i),n.push(i)}return r??n}function Ej(e,t){const n=t.funcs.get(e.name);if(!n)return Cj(e,t);if(n.unresolvedImport!==void 0)throw new ns(`function ${e.name}() is imported from '${n.unresolvedImport}', but import module resolution is not implemented`);if(n.params.length!==e.args.length)return new z(`Incorrect number of arguments. Received: ${e.args.length}. Expected: ${e.name}(${n.params.join(", ")}).`);const r=e.args.map(l=>Dr(l,t)),s={};n.params.forEach((l,u)=>{s[l]=r[u]});const i=t.matchParams??t.params,o={};if(n.declCaptures)for(const l of n.declCaptures)Object.hasOwn(i,l)&&(o[l]=i[l]);const a={input:t.input,now:t.now,params:o,matchParams:i,scopeKind:n.scopeKind??"match",locals:s,funcs:n.declScope??new Map,firestoreLookup:t.firestoreLookup,firestoreAccesses:t.firestoreAccesses,expressionBudget:t.expressionBudget};for(const l of n.lets)s[l.name]=Dr(l.value,a),a.expressionBudget?.letBinding(l);return rt(n.body,a)}function Cj(e,t){if(e.name==="path"&&e.args.length===1){const i=rt(e.args[0],t);return K(i)?i:typeof i=="string"?i.includes("//")?new z("Invalid argument error in path(): empty path segment."):new He(i):new z(`path() expects a string, got ${De(i)}.`)}const n=sw(e.name);if(!n)return new z(`Function not found error: Name: [${e.name}].`);const r=dt(e.args,t);if(K(r))return r;const s=iw(n,r);return s instanceof ow?new z(s.message):s}function os(e,t,n,r){const s=n?.kind==="sandbox"?zt(n,r):r;if(n?.kind==="sandbox"&&n.admin===!0){ys(n,t,"not-applicable",void 0,"admin",!1,s);return}if(!e.rules)throw ys(n,t,"deny",["No Storage rules configured; default deny."],"user",!1,s),du(t.request.method,t.request.path," — No Storage rules configured; default deny.");const i=n?Nj(t,n.bucket):t,o=n?Te(n.sandbox).date():void 0,a=jp(e.rules,i,o,Rj(n,e.crossServiceIam));if(!a.allowed){ys(n,t,"deny",a.reasons,"user",!0,s);const l=a.reasons.length>0?` — ${a.reasons.join("; ")}`:"";throw du(t.request.method,t.request.path,l)}ys(n,t,"allow",a.reasons,"user",!0,s)}function Nj(e,t){const n=e.request.path.replace(/^\/+/,"");return{...e,request:{...e.request,path:n===""?`b/${t}/o`:`b/${t}/o/${n}`}}}function ys(e,t,n,r,s,i,o){if(e)try{pt(e.sandbox,Kf({at:Te(e.sandbox).now(),service:"storage",method:t.request.method,path:t.request.path,auth:t.request.auth,result:n,origin:s,reasons:r,detail:{bucket:e.bucket},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}),{...o,service:"storage"})}catch{}}function Rj(e,t){if(e)return Ij(e.sandbox,t)}function Ij(e,t){if(t==="denied")return Aj();const n=e.admin;return{get:r=>n.getDocument(r),exists:r=>n.getDocument(r)!==null}}function Aj(){const e=t=>{throw new B(`firestore.${t}() failed: cross-service Firestore access is not authorized: the Storage service agent lacks roles/firebaserules.firestoreServiceAgent (crossServiceIam: 'denied')`)};return{get:()=>e("get"),exists:()=>e("exists")}}function Tr(e){return e.admin===!0?"admin":"client"}const Oj="identity";function Ep(e,t){return e??`inline; filename*=utf-8''${Pj(t.split("/").pop()??"")}`}function Cp(e){return e??Oj}const $j=/[A-Za-z0-9!#$&+\-.^_`|~]/;function Pj(e){let t="";for(const n of e){if($j.test(n)){t+=n;continue}for(const r of new TextEncoder().encode(n))t+=`%${r.toString(16).toUpperCase().padStart(2,"0")}`}return t}function Np(e){const t={};for(const[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}function Ii(e){return e?Np({size:e.size,contentType:e.contentType,metadata:e.customMetadata,name:Rp(e.fullPath,e.bucket),bucket:e.bucket,timeCreated:e.timeCreated,updated:e.updated,generation:Cu(e.generation),metageneration:Cu(e.metageneration)}):null}function Rp(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 Cu(e){if(e===void 0)return;const t=Number(e);return Number.isFinite(t)?t:void 0}function Dj(e,t){const n=Rp(e.fullPath,e.bucket),r={name:n,bucket:e.bucket,size:e.size,contentType:e.contentType,contentDisposition:Ep(e.contentDisposition,n??""),contentEncoding:Cp(e.contentEncoding),contentLanguage:e.contentLanguage??null,cacheControl:e.cacheControl??null,metadata:e.customMetadata??null};return r.generation=null,r.metageneration=null,r.etag=null,Np(r)}function _c(e,t){return t==="admin"?{...e}:{...e,contentEncoding:Cp(e.contentEncoding)}}async function Tj(e){Mj(e,"getMetadata");const t=Le(e.storage),n=zt(t),r=await Ht(e.storage),s=await r.backend.getMetadata(e.fullPath);if(os(r,{request:{auth:qt(t),method:"get",path:e.fullPath},resource:Ii(s)},t,n),!s)throw vp(e.fullPath);return _c(s,Tr(t))}function Mj(e,t){if(e.fullPath==="")throw Ri(t)}const Lj="application/octet-stream";async function Uj(e,t,n,r){return Bj(e,t,n,{provenance:r})}async function Bj(e,t,n,r={}){const{result:s}=await Ip(e,t,n,r);return s}async function Ip(e,t,n,{provenance:r,downloadTokens:s}={}){Vj(e,"uploadBytes");const i=Le(e.storage),o=s!==void 0;if(o&&Tr(i)!=="admin")throw new Nt("unauthorized","Only the admin plane sets download tokens on upload.");const a=zt(i,r),l=Fj(t,n?.contentType),u=Te(i.sandbox).date(),d=Ap({ref:e,blob:l,settable:n,now:u});o&&(d.downloadTokens=s);const h=await Ht(e.storage),f=await h.backend.getMetadata(e.fullPath);os(h,{request:{auth:qt(i),method:"create",path:e.fullPath,resource:Dj(d)},resource:Ii(f)},i,a);const p=await h.backend.put(e.fullPath,l,d,JS(u.getTime()));try{pt(i.sandbox,Un({at:Te(i.sandbox).now(),service:"storage",op:"object_put",path:e.fullPath,auth:qt(i),before:p?.metadata,after:d,detail:{bucket:e.bucket,size:d.size,contentType:d.contentType,overwrite:p!==void 0}}),a)}catch{}return{result:{ref:e,metadata:_c(d,Tr(i))},replaced:p}}function Ap(e){const{ref:t,blob:n,settable:r}=e,s=(e.now??new Date).toISOString(),i=String(up((e.now??new Date).getTime())),o=t.name,a=Tr(Le(t.storage))==="client";return{fullPath:t.fullPath,name:o,bucket:t.bucket,generation:i,metageneration:"1",timeCreated:s,updated:s,size:n.size,contentType:r?.contentType||n.type||Lj,cacheControl:r?.cacheControl,contentDisposition:a?Ep(r?.contentDisposition,t.fullPath):r?.contentDisposition,contentEncoding:r?.contentEncoding,contentLanguage:r?.contentLanguage,customMetadata:r?.customMetadata}}function Fj(e,t){return e instanceof Blob?t&&t!==e.type?new Blob([e],{type:t}):e:new Blob([e],{type:t??""})}function Vj(e,t){if(e.fullPath==="")throw Ri(t)}async function qj(e,t){return Sc(e,"getBlob"),Hj(e,t)}async function Wj(e,t){Sc(e,"deleteObject");const n=Le(e.storage),r=zt(n,t),s=await Ht(e.storage),i=await s.backend.getMetadata(e.fullPath);os(s,{request:{auth:qt(n),method:"delete",path:e.fullPath},resource:Ii(i)},n,r),await s.backend.delete(e.fullPath),Op(e,i,r)}async function zj(e,t,n){Sc(e,"deleteObject");const r=Le(e.storage),s=await Ht(e.storage),i=await s.backend.getMetadata(e.fullPath),o=await s.backend.deleteIfGeneration(e.fullPath,t);return o&&Op(e,i,zt(r,n)),o}function Op(e,t,n){const r=Le(e.storage);try{pt(r.sandbox,Un({at:Te(r.sandbox).now(),service:"storage",op:"object_delete",path:e.fullPath,auth:qt(r),before:t??void 0,detail:{bucket:e.bucket}}),n)}catch{}}async function Hj(e,t){const n=Le(e.storage),r=zt(n),s=await Ht(e.storage),i=await s.backend.getMetadata(e.fullPath);os(s,{request:{auth:qt(n),method:"get",path:e.fullPath},resource:Ii(i)},n,r);const o=await s.backend.getBlob(e.fullPath);if(!o)throw vp(e.fullPath);return typeof t=="number"&&o.size>t?o.slice(0,t):o}function Sc(e,t){if(e.fullPath==="")throw Ri(t)}async function Kj(e,t,n,r){const s=(await Ht(e.storage)).backend,i=await s.getMetadata(e.fullPath),o=await s.replaceIfGeneration(e.fullPath,t,n);return o&&Gj(e,i,n.metadata,r),o}function Gj(e,t,n,r){const s=Le(e.storage);try{pt(s.sandbox,Un({at:Te(s.sandbox).now(),service:"storage",op:"object_put",path:e.fullPath,auth:qt(s),before:t,after:n,detail:{bucket:e.bucket,size:n.size,contentType:n.contentType,overwrite:!0}}),zt(s,r))}catch{}}async function Jj(e,t,n){const r=t.prior;return r!==void 0?Kj(e,t.generation,r,n).then(s=>({deleted:!1,restored:s}),s=>({deleted:!1,restored:!1,error:sa(e.fullPath,s,"restore")})):zj(e,t.generation,n).then(s=>({deleted:s,restored:!1}),s=>({deleted:!1,restored:!1,error:sa(e.fullPath,s,"remove")}))}async function Yj(e,t,n){return(await Jj(e,t,n)).error}const Qj={remove:"removing it failed",restore:"restoring the object it replaced failed"};function Xj(e){const t=e?.code;if(typeof t=="string")return t}function sa(e,t,n="remove"){const r=Xj(t)??"storage/unknown",s=t instanceof Error?t.message:String(t),i=Qj[n],o=`${r}: The upload to '${e}' was canceled after it was stored, and ${i}: ${s}`,a=new Error(o,{cause:t});return a.code=r,a}function Zj(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 eE{[Symbol.toStringTag]="UploadTask";_snapshot;_promise;_resolve;_reject;_observers=[];_didIntermediateProgress=!1;_committing=!1;_sentCommit;_heldOutcome;_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=Zj(n,i);const a=Ap({ref:t,blob:this._blob,settable:r}),l=_c(a,Tr(Le(t.storage)));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(()=>{if(!(this._snapshot.state==="running"))return;this._releaseHeldOutcome()||this._runStep()}),!0):!1}cancel(){let t=!1;return(this._snapshot.state==="running"||this._snapshot.state==="paused")&&(t=!0),t?(this._updateSnapshot("canceled",this._snapshot.bytesTransferred),this._rollBackCanceled().then(r=>this._settleCanceled(r)),!0):!1}on(t,n,r,s){let i,o,a,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&&(o=f.error),f.complete!==void 0&&(a=f.complete)}else typeof n=="function"&&(i=n),typeof r=="function"&&(o=r),typeof s=="function"&&(a=s);const d={next:i,error:o,complete:a};if(this._observers.push(d),this._snapshot.state==="running"){if(i!==void 0){const p=i;try{Ut(this),p(this._snapshot)}catch{}}}else if(this._snapshot.state==="paused"){if(i!==void 0){const m=i;try{Ut(this),m(this._snapshot)}catch{}}}else if(this._snapshot.state==="success"){if(i!==void 0){const b=i;try{Ut(this),b(this._snapshot)}catch{}}if(a!==void 0){const b=a;try{ri(this),b()}catch{}}}else if(this._snapshot.state==="error"){if(o!==void 0&&this._error!==void 0){const w=o,x=this._error;try{w(x)}catch{}}}else if(this._snapshot.state==="canceled"&&o!==void 0&&this._error!==void 0){const x=o,v=this._error;try{x(v)}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 a=i.next;try{Ut(this),a(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 a=i.complete;try{ri(this),a()}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(){const t=this._snapshot.state!=="running",n=this._committing||this._heldOutcome!==void 0;if(t||n)return;this._committing=!0;const r=this._storeUpload();this._sentCommit=r;const s=await r;this._committing=!1,this._settleCommit(s)}async _storeUpload(){try{if(await Ht(this._ref.storage),this._snapshot.state!=="running")return;const{result:n,replaced:r}=await Ip(this._ref,this._blob,this._metadata,{provenance:this._provenance});return{stored:{result:n,prior:r}}}catch(t){return{error:t}}}_settleCommit(t){const n=this._snapshot.state;if(n==="running"){this._report(t);return}n==="paused"&&(this._heldOutcome=t)}_releaseHeldOutcome(){const t=this._heldOutcome;return t===void 0?!1:(this._heldOutcome=void 0,this._report(t),!0)}_report(t){if(t===void 0){queueMicrotask(()=>this._runStep());return}if("stored"in t){this._updateSnapshot("success",this._snapshot.totalBytes,t.stored.result.metadata),this._notifyObservers("next"),this._notifyObservers("complete"),this._resolve(this._snapshot);return}this._fail(t.error)}_settleCanceled(t){this._error=t,this._notifyObservers("error"),this._reject(t)}_fail(t){let n;t instanceof Error?n=t:n=new Error(String(t)),this._error=n,this._updateSnapshot("error",this._snapshot.bytesTransferred),this._notifyObservers("error"),this._reject(this._error)}async _rollBackCanceled(){const t=this._heldOutcome;this._heldOutcome=void 0;const n=t??await this._sentCommit;if(!(n!==void 0&&"stored"in n))return fu();const s={generation:n.stored.result.metadata.generation,prior:n.stored.prior};return await Yj(this._ref,s,this._provenance)??fu()}}function tE(e,t,n,r){if(e.fullPath==="")throw Ri("uploadBytesResumable");return new eE(e,t,n,r)}async function nE(e){const t=e.storage,n=Le(t),r=zt(n),s=await Ht(t);os(s,{request:{auth:qt(n),method:"list",path:e.fullPath},resource:null},n,r);const i=e.fullPath===""?"":`${e.fullPath}/`,o=await s.backend.listByPrefix(i),a=[],l=new Set,u=[];for(const d of o){if(!d.fullPath.startsWith(i))continue;const h=d.fullPath.slice(i.length);if(h==="")continue;const f=h.indexOf("/");if(f===-1)a.push(Or(t,d.fullPath));else{const p=h.slice(0,f),m=`${i}${p}`;l.has(m)||(l.add(m),u.push(Or(t,m)))}}return u.sort((d,h)=>d.fullPath<h.fullPath?-1:d.fullPath>h.fullPath?1:0),{items:a,prefixes:u}}const rE=qn("uploadBytes",Uj),sE=qn("uploadBytesResumable",tE),iE=qn("getBlob",qj),$p=qn("deleteObject",Wj),oE=qn("getMetadata",Tj),kc=qn("listAll",nE),aE="/__pyric/storage/v0/b/";function cE(e,t,n){const r=new URLSearchParams({alt:"media"});return`${aE}${encodeURIComponent(e)}/o/${encodeURIComponent(t)}?${r}`}function lE(e){let t="",n=!1,r=!1,s=!1,i=0;for(;i<e.length;){const o=e[i],a=i+1<e.length?e[i+1]:"";if(r){(o===`
|
|
124
124
|
`||o==="\r")&&(r=!1,t+=o),i++;continue}if(s){o==="*"&&a==="/"?(s=!1,i+=2):((o===`
|
|
125
|
-
`||o==="\r")&&(t+=o),i++);continue}if(n){if(o==="\\"){t+=o,a!==""&&(t+=a,i++),i++;continue}o==='"'&&(n=!1),t+=o,i++;continue}if(o==='"'){n=!0,t+=o,i++;continue}if(o==="/"&&a==="/"){r=!0,i+=2;continue}if(o==="/"&&a==="*"){s=!0,i+=2;continue}t+=o,i++}return t}const
|
|
126
|
-
`||e==="\r"}function oE(e,t){let n=t+1;for(;n<e.length&&Ap(e[n]);)n++;const r=e[n];return r==="}"||r==="]"}function aE(e){const t=rE(e);let n="",r=!1,s="",i=0;for(;i<t.length;){const o=t[i];if(r){if(o==="\\"){n+=t.slice(i,i+2),i+=2;continue}o==='"'&&(r=!1);const f=o.charCodeAt(0)<32;n+=f?iE(o):o,i++;continue}o==='"'&&(r=!0);const u=o===","&&(s!==""&&s!=="{"&&s!=="["&&s!==",")&&oE(t,i);u||(n+=o),!u&&!Ap(o)&&(s=o),i++}return n}const jn=Symbol("pyric/firestore/followsCurrentUser"),br=Symbol("pyric/firestore/authSessionScope");function ur(e){const t=e.keys().next().value;t!==void 0&&e.delete(t)}const $e=Object.freeze({readThreshold:5,readWindowMs:1e3,duplicateListenerThreshold:3,churnAttachThreshold:4,churnDetachThreshold:3,listenerWindowMs:2e3,maxEventsPerFingerprint:32,criticalReadThreshold:20,criticalDuplicateListenerThreshold:10,criticalChurnThreshold:12});function cE(e,t){for(const n of e.keys())t.delete(n)}function lE(e,t){const n=e.keys().next().value;return n===void 0?!1:(e.delete(n),t.delete(n),!0)}const Cu=1800;function uE(e){const t=new Map,n=new Map;let r=1;const s=(i,o)=>{const a=i.get(o);if(a!==void 0)return a;i.size>=e&&ur(i);const l=r++;return i.set(o,l),l};return{incidentFingerprint:i=>`activity:#${s(n,i)}`,readTarget:(i,o)=>dr(o===i?i:`${i}|query:#${s(t,o)}`),listenerTarget:i=>{try{const o=JSON.parse(i);if(o.kind==="query"){const a=typeof o.collection=="string"?o.collection:typeof o.path=="string"?o.path:"<unknown>";return dr(JSON.stringify({collection:a,kind:"query",query:`#${s(t,i)}`}))}if(o.kind==="doc"&&typeof o.path=="string")return dr(JSON.stringify({kind:"doc",path:o.path}))}catch{}return JSON.stringify({kind:"unknown",target:`#${s(t,i)}`})},clear:()=>{t.clear(),n.clear()}}}function dr(e){if(e.length<=Cu)return e;const t=`…#${dE(e)}`;return e.slice(0,Cu-t.length)+t}function dE(e){let t=2166136261,n=2654435769;for(let r=0;r<e.length;r+=1){const s=e.charCodeAt(r);t=Math.imul(t^s,16777619),n=Math.imul(n^s,2246822507)}return(t>>>0).toString(16).padStart(8,"0")+(n>>>0).toString(16).padStart(8,"0")}const ys=256,fE=64,hE=8192;function pE(e,t){const n=new Map,r=new Map,s=new Map,i=new Map,o=new Map,a=new Set,l=uE(ys);let u=0,d=!1;const h=_=>{try{t(_)}catch{}},f=(_,S)=>{!i.has(_)&&i.size>=fE&&ur(i),i.set(_,S)},p=(_,S)=>{const k=o.get(_);return k!==void 0?(o.delete(_),k==="critical"||k===S?(o.set(_,k),!1):(o.set(_,S),!0)):(o.size>=ys&&ur(o),o.set(_,S),!0)},m=()=>{n.clear(),r.clear(),s.clear(),o.clear(),a.clear(),u+=1},g=(_,S)=>{if(a.has(_.id))return;if(a.size>=hE&&ur(a),a.add(_.id),_.kind==="session_boundary"){m();return}const k=yE(_);if(!k){const $=mE(_,s);$&&b(_,$,S);return}const N=`segment:${u}|read:${k.method}:${k.targetFingerprint}|actor:${k.actorAuthFingerprint}`;let O=n.get(N);O||(n.size>=ys&&ur(n),O={events:[]},n.set(N,O)),O.events.push({id:_.id,at:_.at});const D=_.at-$e.readWindowMs;for(;O.events.length>0&&O.events[0].at<D;)O.events.shift();if(O.events.length>$e.maxEventsPerFingerprint&&O.events.splice(0,O.events.length-$e.maxEventsPerFingerprint),O.events.length<$e.readThreshold)return;const R=O.events[0],j=O.events[O.events.length-1],E=Object.freeze({fingerprint:l.incidentFingerprint(N),pattern:"repeated-read",confidence:"high",severity:Nu("repeated-read",O.events.length),service:"firestore",method:k.method,targetFingerprint:l.readTarget(k.path,k.targetFingerprint),actor:k.actor,authLens:ii(k.authLens),authUid:k.authUid,count:O.events.length,windowMs:j.at-R.at,usage:Object.freeze({unit:"document-reads",lowerBound:O.events.length,limitations:Object.freeze(["Observed sandbox reads are a lower bound; production cache and billing behavior are not measured."])}),evidenceEventIds:Object.freeze(O.events.slice(-8).map($=>$.id)),sourceAttribution:Ru(k.actor)});f(N,E),!S&&p(N,E.severity)&&h(E)},b=(_,S,k)=>{const N=Er(S.target),O=l.listenerTarget(N),D=`segment:${u}|listener:${N}|actor:${S.actorAuthFingerprint}`;let R=r.get(D);if(!R){if(r.size>=ys){const I=r.keys().next().value;I!==void 0&&(cE(r.get(I).active,s),r.delete(I))}R={active:new Map,lifecycle:[],saturated:!1},r.set(D,R)}if(S.phase==="attach"){if(R.active.has(S.physicalListenerId))return;R.active.size>=$e.maxEventsPerFingerprint&&lE(R.active,s)&&(R.saturated=!0),R.active.set(S.physicalListenerId,{id:_.id,at:_.at}),s.set(S.physicalListenerId,{listenerId:S.listenerId,target:S.target,actor:S.actor,authLens:S.authLens,authUid:S.authUid,actorAuthFingerprint:S.actorAuthFingerprint})}else R.active.delete(S.physicalListenerId),s.delete(S.physicalListenerId);if(S.phase==="errored"||S.reauthorization)return;R.lifecycle.push({id:_.id,at:_.at,phase:S.phase});const j=_.at-$e.listenerWindowMs;for(;R.lifecycle.length>0&&R.lifecycle[0].at<j;)R.lifecycle.shift();R.lifecycle.length>$e.maxEventsPerFingerprint&&(R.lifecycle.splice(0,R.lifecycle.length-$e.maxEventsPerFingerprint),R.saturated=!0);const E=R.lifecycle.filter(I=>I.phase==="attach").length,$=R.lifecycle.length-E,C=Object.freeze({attaches:E,detaches:$,active:R.active.size,...R.saturated?{isLowerBound:!0}:{}});if(R.active.size>=$e.duplicateListenerThreshold){const I=[...R.active.values()],A=I[0],P=`${D}|duplicate`;w(P,"duplicate-listener",I.length,_.at-A.at,I.map(T=>T.id),k,S,O,C)}if(E>=$e.churnAttachThreshold&&$>=$e.churnDetachThreshold){const I=R.lifecycle[0],A=`${D}|churn`;w(A,"listener-churn",E,_.at-I.at,R.lifecycle.map(P=>P.id),k,S,O,C)}},w=(_,S,k,N,O,D,R,j,E)=>{const $=Object.freeze({fingerprint:l.incidentFingerprint(_),pattern:S,confidence:S==="duplicate-listener"&&k<$e.criticalDuplicateListenerThreshold?"medium":"high",severity:Nu(S,k),service:"firestore",method:"listen",targetFingerprint:dr(j),actor:R.actor,authLens:ii(R.authLens),authUid:R.authUid,count:k,windowMs:N,listenerBalance:E,usage:Object.freeze({unit:"listener-attaches",lowerBound:k,limitations:Object.freeze(["Listener lifecycle events count attachments; document deliveries and production billing are not measured.",...E.isLowerBound?["Listener retention saturated; reported counts are observed lower bounds."]:[]])}),evidenceEventIds:Object.freeze(O.slice(-8)),sourceAttribution:Ru(R.actor)});f(_,$),!D&&p(_,$.severity)&&h($)},x=e.history();for(const _ of x)g(_,!0);x.length>0&&m();const v=e.subscribe(_=>{d||g(_,!1)});return{report:()=>Object.freeze({incidents:Object.freeze([...i.values()])}),dispose:()=>{d||(d=!0,v(),n.clear(),r.clear(),s.clear(),o.clear(),a.clear(),l.clear())}}}function Nu(e,t){const n=e==="repeated-read"?$e.criticalReadThreshold:e==="duplicate-listener"?$e.criticalDuplicateListenerThreshold:$e.criticalChurnThreshold;return t>=n?"critical":"warning"}function mE(e,t){const n=e.kind==="listener_attach"||e.kind==="listener_detach"||e.kind==="listener_errored",r=e.kind==="listener"&&(e.phase==="attach"||e.phase==="detach"||e.phase==="errored");if(!n&&!r||(e.service??"firestore")!=="firestore"||e.planId)return null;let s;if(e.kind==="listener_attach")s="attach";else if(e.kind==="listener_detach")s="detach";else if(e.kind==="listener_errored")s="errored";else if(e.kind==="listener"&&(e.phase==="attach"||e.phase==="detach"||e.phase==="errored"))s=e.phase;else return null;const i=Qa(e),o=s!=="attach"?t.get(e.listenerId):void 0;if(!(o!==void 0)&&(i.source.kind!=="app"||i.authLens.mode==="admin"))return null;const l=e.activity?.listenerId??o?.listenerId??e.listenerId,u=o??{listenerId:l,target:e.target,actor:i.source,authLens:i.authLens,authUid:e.auth?.uid??null,actorAuthFingerprint:Er({actor:i.source,authLens:ii(i.authLens),uid:e.auth?.uid??null})};return{phase:s,physicalListenerId:e.listenerId,reauthorization:e.activity?.listenerLifecycle==="reauthorize",...u}}function Ru(e){return e.kind==="app"&&e.journeyId!==void 0?`app ${e.journeyId}`:"app"}function ii(e){return e.mode==="as"?{mode:"as",uid:e.uid}:{mode:e.mode}}function yE(e){if(e.kind!=="request"&&e.kind!=="operation"||(e.kind==="request"?e.service??"firestore":e.service)!=="firestore"||e.method!=="get"&&e.method!=="list"||e.origin!=="user"||e.result!=="allow"||e.groupId||e.groupKind||e.activity?.groupKind||e.planId||e.detail?.admin===!0)return null;const n=Qa(e);if(n.source.kind!=="app"||n.authLens.mode==="admin")return null;const r=e.path??"<unknown>",s=e.kind==="request"?e.detail?.activityQuery??e.detail?.query:e.request?.query,i=s===void 0?void 0:Er(s);return{method:e.method,path:r,targetFingerprint:i===void 0?r:`${r}|query:${i}`,actorAuthFingerprint:Er({actor:n.source,authLens:ii(n.authLens),uid:e.auth?.uid??null}),actor:n.source,authLens:n.authLens,authUid:e.auth?.uid??null}}const Op=new WeakMap;function gE(e){return Op.get(e)?.raw??e}const bE=new WeakMap,Iu=new WeakMap;function oi(e,t,n,r,s){Op.set(e,{target:n,path:t.ref.path,kind:s,converter:r,raw:t})}function Au(e){return typeof e.exists=="function"?e.exists():e.exists===!0}function wE(e,t){const n=Bo(e),r=Bo(t);return n.isStructurallyEqual?.(r)??n===r}function vE(e,t,n,r){const s=e,i=(Iu.get(s)??[]).filter(a=>a.query.deref()!==void 0),o=i.find(a=>{const l=a.query.deref();return l!==void 0&&wE(l,t)});if(o!==void 0){const a=xE(o.docs,n)&&o.metadata.fromCache===r.fromCache&&o.metadata.hasPendingWrites===r.hasPendingWrites;return o.docs=n,o.metadata=r,a?"settled":"initial"}return i.push({query:new WeakRef(t),docs:n,metadata:r}),Iu.set(s,i),"initial"}function xE(e,t){return e.length===t.length&&e.every((n,r)=>{const s=t[r];return n.path===s.path&&Ow(n.data,s.data)})}function sa(e,t,n,r,s){const i=t,o=d=>({path:d.ref?.path??"",data:ec(d.data?.(),n)}),a=Object.freeze((i.docs??[]).map(o)),l=Object.freeze((i.docChanges?.()??[]).map(d=>({...o(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});bE.set(e,{target:n,query:r,converter:Jr(r)??null,source:s,...s==="read"?{readPhase:vE(n,r,a,u)}:{},metadata:u,docs:a,changes:l})}function ai(e,t){const n=e;oa(n);const r=n.data.bind(e),s=t!==void 0;let i;if(s&&(i={create:o=>st({[Ws]:t},o)}),Object.defineProperty(n,"data",{value:()=>uh(r(),i),configurable:!0,writable:!0}),s){const o=n.ref?.path;o!==void 0&&o.length>0&&Object.defineProperty(n,"metadata",{value:Et(t).snapshotMetadata(o),configurable:!0})}return e}function $p(e,t,n,r){const s=st({[Ws]:n},e.ref.path),i=s.withConverter(t),o={create:l=>st({[Ws]:n},l)},a={id:e.id,ref:i,exists:()=>Au(e),metadata:Et(n).snapshotMetadata(e.ref.path),data:()=>{if(!Au(e))return;const u=uh(e.data(),o),d={id:e.id,ref:s,exists:()=>!0,metadata:Et(n).snapshotMetadata(e.ref.path),data:()=>u};return t.fromFirestore(d)}};return nn(a,n),nn(e.ref,n),ia(e.ref,n),oi(a,e,n,t,r),a}function Ou(e,t,n,r){const s=e,i=s.ref?.path??"",o=s.data.bind(e),a=st({[Ws]:n},i),l=a.withConverter(t);Object.defineProperty(s,"ref",{value:l,configurable:!0,writable:!0}),Object.defineProperty(s,"data",{value:()=>{const d=o();if(d===void 0)return;const f={id:s.id,ref:a,exists:()=>!0,metadata:Et(n).snapshotMetadata(i),data:()=>d};return t.fromFirestore(f)},configurable:!0,writable:!0});const u={ref:{path:i},exists:s.exists,data:o};oi(e,u,n,t,r)}function Ii(e,t){if(!e||typeof e!="object")return e;nn(e,t);const n=e;if(n.ref&&(nn(n.ref,t),ia(n.ref,t)),oa(n),Array.isArray(n.docs))for(const r of n.docs)r&&(nn(r,t),oi(r,r,t,null,"query-child")),r?.ref&&(nn(r.ref,t),ia(r.ref,t)),r&&oa(r);else n.ref&&oi(e,e,t,null,"document");return e}function ia(e,t){if(typeof e.path!="string"||e.path.length===0)return;const n=e.path;try{const r=al.get(e),s=r??Za(t).doc(n);r===void 0&&al.set(e,s),sh(e,n,t,s),t.kind==="sandbox-live"&&dh.set(s,i=>i.doc(n))}catch{}}function oa(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{}}function Dp(e){return _E(e,"getDoc")}async function _E(e,t){return SE(e,tc(Un(e),e,t,"operation"))}async function SE(e,t){const n=Un(e),r=Et(n);r.markStarted();try{const s=Jr(e),i=await fh(()=>Dw(n,e).get());return r.cachePath(e.path),s?On(t,$p(i,s,n,"document")):(Ii(i,n),On(t,ai(i,n)))}catch(s){throw t.fail(),s}}function ci(e){return kE(e,"getDocs")}async function kE(e,t){return jE(e,tc(Un(e),e,t,"operation"))}async function jE(e,t){const n=Un(e),r=Et(n);r.markStarted();try{const s=Jr(e),i=await fh(()=>$w(n,e).get());if(r.cacheQuery(e),s){const a=s,l=i.docs.map(d=>$p(d,a,n,"query-child")),u=nn({size:l.length,empty:l.length===0,docs:l,forEach:ih(l),metadata:r.querySnapshotMetadata()},n);for(const d of l)r.cachePath(d.ref.path);return sa(u,i,n,e,"read"),On(t,u)}Ii(i,n);const o=i.docs;for(const a of o)r.cachePath(a.ref.path),ai(a,n);return Object.defineProperty(i,"metadata",{value:r.querySnapshotMetadata(),configurable:!0}),sa(i,i,n,e,"read"),On(t,i)}catch(s){throw t.fail(),s}}function EE(e){if(e===null||typeof e!="object")return null;const t=e;return typeof t.path=="string"&&t.path.length>0?t.path:typeof t.collectionPath=="string"&&t.collectionPath.length>0?t.collectionPath:null}function $u(e){if(e!==null&&typeof e=="object"){const t=e.snapshotConstraints;if(typeof t=="function")return t.call(e)}}function CE(e){if(e!==null&&typeof e=="object"){const t=e.snapshotScope;if(typeof t=="function")return t.call(e)}}function Du(e){if(e===null||typeof e!="object")return!1;const t=e;return typeof t.path=="string"&&t.path.length>0&&t.parent!==void 0&&t.parent!==null}function Pp(e,t,n,r,s){let i={},o,a;if(typeof t=="object"&&t!==null&&typeof t.next!="function"&&typeof t.error!="function"&&typeof t.complete!="function"){if(i=t,typeof n=="function")o=n,a=r;else if(typeof n=="object"&&n!==null){const v=n;o=v.next,a=v.error}}else if(typeof t=="function")o=t,a=n;else if(typeof t=="object"&&t!==null){const v=t;o=v.next,a=v.error}if(!o&&!a)throw new TypeError("onSnapshot: missing handler. Provide a callback, or an observer with a `next` and/or `error` method.");const u=Mw(e);if(u){if(i[jn]===!0)throw new Yf("unimplemented","onSnapshot: live (follows-current-user) listeners are not supported on a remote sandbox — remote listeners are frozen to the identity of the context that created the ref.");return u(i,o,a)}const d=NE(e),h=Gr(d.sandbox);let f;const p=Du(e)?void 0:CE(e);if(Du(e))f={kind:"doc",path:e.path};else if(p?.kind==="collection-group")f={kind:"query",collection:p.collectionId,collectionGroup:!0,constraints:$u(e)};else{const v=EE(e);if(v===null)throw new TypeError("onSnapshot: could not determine the collection path for this Query. Pass a CollectionReference or a Query produced by `.where`/`.orderBy`/`.limit` on a CollectionReference obtained from `getFirestore(ctx)`.");const _=$u(e);f={kind:"query",collection:v,constraints:_}}const m=i[jn]===!0,g=i[br],b=e[Lw]===!0;if(jn in i){const{[jn]:v,..._}=i;i=_}if(br in i){const{[br]:v,..._}=i;i=_}const w=()=>h.addSnapshotListener(f,o??(()=>{}),i,d.auth,a?v=>a(IE(v,d)):void 0,m,b,g);return typeof d.sandbox.runWithProvenance=="function"?d.sandbox.runWithProvenance(Lo(d.operationContext),w):w()}function NE(e){if(e===null||typeof e!="object")throw new TypeError("onSnapshot: reference must be a DocumentReference or Query.");const t=e[Uw];if(!t)throw new TypeError("onSnapshot: reference was not produced by a sandbox context — pass a ref obtained from `getFirestore(ctx)`.");return t}Pw(Pp);Tw(Pp);function RE(e){return typeof e=="object"&&e!==null&&"code"in e&&iw.some(t=>t===e.code)&&"message"in e&&typeof e.message=="string"}function IE(e,t){if(!RE(e))return e;const n=Bw(new sw(e),{...t,auth:e.request?e.request.auth:t.auth});if(n instanceof Error)for(const r of["request","resource","query","rule","queryProof"])e[r]!==void 0&&Object.assign(n,{[r]:e[r]});return n}function Tp(e){return typeof e=="string"?e:e._internalPath.segments.join(".")}function li(e,...t){const n=Un(e),r=Jr(e),s=Fw(e);let i,o;try{i=t.map(u=>u.prepareSandbox?.(n)??u)}catch(u){throw Fo(u)}const a=u=>{let d=s(u);for(const h of i)d=h.applySandbox(d);return d};try{o=a(Za(n))}catch(u){throw Fo(u)}const l=qw(Vw(o,n,u=>a(u)));return r?Ww(l,r):l}function AE(e,t,n){return Mp(Tp(e),t,n,!1)}function Mp(e,t,n,r){return{type:"where",applySandbox:i=>i.where(e,t,n),prepareSandbox:r?void 0:i=>{const o=ec(n,i,t==="in"||t==="not-in");return Mp(e,t,o.executionValue,!0)},_sandboxFilter:{kind:"where",field:e,op:t,value:n}}}function Pu(e,t){const n=Tp(e);return{type:"orderBy",applySandbox:r=>r.orderBy(n,t)}}function ui(e){return{type:"limit",applySandbox:t=>t.limit(e)}}function OE(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 $E(...e){return OE(e)?Lp(e[0],!1,!0):Up(e,!1,!0)}function Lp(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=gE(e),i=s.data(),o=Object.freeze({id:s.id,ref:s.ref,exists:i!==void 0,data:()=>i});return Lp(o,t,n,!0)}}}function Up(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=>Up(e.map(i=>ec(i,s).executionValue),t,n,!0)}}function DE(e,t,n,r){const s=Un(e);Et(s).markStarted();const i=TE(s,e),o=typeof t=="object"&&t!==null&&!kc(t)?t:void 0,a=tc(s,e,"onSnapshot","subscription",o),l=ME(t,n,r,s,e,a),u=LE(l,s);let d;try{d=Hr.registering(a,()=>u.length===3?i.onSnapshot(u[0],u[1],u[2]):u.length===2?i.onSnapshot(u[0],u[1]):i.onSnapshot(u[0]))}catch(g){throw a.fail(),g}if(!s.own)return()=>{a.close(),d()};let h=!1;const f=()=>{h||(h=!0,a.close(),d())},p=()=>{h||(a.fail(),f(),PE(u)?.(new H("aborted","The operation was aborted.")))},m=s.own(p);return()=>{m(),f()}}function PE(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 TE(e,t){const n=Bo(t);if(e.kind==="sandbox")return n;const r=dh.get(n);if(!r)throw new TypeError("pyric/firestore: live ref missing rebuild closure for onSnapshot.");return r(Za(e))}function kc(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 ME(e,t,n,r,s,i){if(typeof e=="object"&&e!==null&&!kc(e)){const a=t;return typeof a=="function"?[e,Tu(a,r,s,i),ca(n??aa,i)]:a&&typeof a=="object"?[e,Mu(a,r,s,i)]:[e]}return typeof e=="function"?[Tu(e,r,s,i),ca(t??aa,i)]:e&&typeof e=="object"?[Mu(e,r,s,i)]:[e]}function LE(e,t){if(t.kind!=="sandbox-live")return e;const n=e[0];return typeof n=="object"&&n!==null&&!kc(n)?[{...n,[jn]:!0,...t.authScope?{[br]:t.authScope}:{}},...e.slice(1)]:[{[jn]:!0,...t.authScope?{[br]:t.authScope}:{}},...e]}function Bp(e,t,n){if(!e||typeof e!="object")return e;const r=e,s=Jr(n)??null,i=s!==null;if(typeof r.data=="function"&&(ai(e,t),i&&Ou(e,s,t,"document")),Array.isArray(r.docs)){for(const o of r.docs)ai(o,t),i&&Ou(o,s,t,"query-child");sa(e,e,t,n,"listener")}return e}function aa(e){console.error("pyric/firestore: Uncaught Error in snapshot listener:",e)}function Tu(e,t,n,r){return s=>{const i=Bp(Ii(s,t),t,n);r.delivered(i),e(i),Et(t).notifySnapshotDelivered()}}function Mu(e,t,n,r){return{...e,next:e.next?s=>{const i=Bp(Ii(s,t),t,n);r.delivered(i),e.next(i),Et(t).notifySnapshotDelivered()}:void 0,error:ca(e.error??aa,r)}}function ca(e,t){return n=>{t.fail(),e(Fo(n))}}const At={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"},tenant:{type:"string",description:"Tenant id, visible to rules as request.auth.token.firebase.tenant."},claims:{type:"object",description:"Custom claims forwarded to the rule context (request.auth.token)."}},required:["uid"]}]},UE={type:"object",properties:{field:{type:"string"},op:{type:"string",enum:[...zw]},value:{}},required:["field","op","value"]};function BE(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:At},required:["path"]},async execute(n){const r=n,s=await t(r.as),i=st(s,r.path),o=await Dp(i),a=typeof o.exists=="function"?o.exists():o.exists;return{ok:!0,summary:a?`Got ${r.path}`:`No document at ${r.path}`,data:{exists:a,data:a?o.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:At},required:["collection"]},async execute(n){const r=n,s=await t(r.as),i=hr(s,r.collection),o=[];r.orderBy&&o.push(Pu(r.orderBy)),r.limit&&o.push(ui(r.limit));const a=await ci(li(i,...o));return{ok:!0,summary:`${a.size} docs in ${r.collection}`,data:{docs:a.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:At},required:["path","data"]},async execute(n){const r=n,s=await t(r.as);return await zs(st(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:At},required:["collection","data"]},async execute(n){const r=n,s=await t(r.as),i=await hh(hr(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:At},required:["path","data"]},async execute(n){const r=n,s=await t(r.as);return await cl(st(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:At},required:["path"]},async execute(n){const r=n,s=await t(r.as);return await qo(st(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:At},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 o=st(s,i.path);i.op==="set"?await zs(o,i.data??{}):i.op==="update"?await cl(o,i.data??{}):await qo(o)}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:UE,minItems:1},orderBy:{type:"string"},limit:{type:"number"},as:At},required:["collection","where"]},async execute(n){const r=n,s=await t(r.as),i=hr(s,r.collection),o=r.where.map(l=>AE(l.field,l.op,l.value));r.orderBy&&o.push(Pu(r.orderBy)),r.limit&&o.push(ui(r.limit));const a=await ci(li(i,...o));return{ok:!0,summary:`${a.size} matches in ${r.collection}`,data:{docs:a.docs.map(l=>({id:l.id,data:l.data()}))}}}}]}function FE(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=ow(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 qE="modulepreload",VE=function(e){return"/__pyric/ui/"+e},Lu={},Fp=function(t,n,r){let s=Promise.resolve();if(n&&n.length>0){let o=function(u){return Promise.all(u.map(d=>Promise.resolve(d).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const a=document.querySelector("meta[property=csp-nonce]"),l=a?.nonce||a?.getAttribute("nonce");s=o(n.map(u=>{if(u=VE(u),u in Lu)return;Lu[u]=!0;const d=u.endsWith(".css"),h=d?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${h}`))return;const f=document.createElement("link");if(f.rel=d?"stylesheet":qE,d||(f.as="script"),f.crossOrigin="",f.href=u,l&&f.setAttribute("nonce",l),document.head.appendChild(f),d)return new Promise((p,m)=>{f.addEventListener("load",p),f.addEventListener("error",()=>m(new Error(`Unable to preload CSS for ${u}`)))})}))}function i(o){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=o,window.dispatchEvent(a),!a.defaultPrevented)throw o}return s.then(o=>{for(const a of o||[])a.status==="rejected"&&i(a.reason);return t().catch(i)})};function qp(e){return e.kind==="session_boundary"&&e.phase==="reset"}function WE(e,t){return qp(t)?[t]:[...e,t]}const Vp=y.createContext(null),Wp={status:"disabled",handles:null,events:[]};function zE({children:e}){return c.jsx(Vp.Provider,{value:Wp,children:e})}function Kt(){return y.useContext(Vp)??Wp}function $t(e,t){return`${e.replace(/\/$/,"")}${t}`}const uo=new Map;let fo=null;function HE(e){return e||(fo||(fo=`studio-writer-${Math.random().toString(36).slice(2)}`),fo)}function zp(e){return{token:e?.token,writerId:e?.writerId}}async function Ai(e,t){if(t)return t;const n=e.replace(/\/$/,""),r=uo.get(n);if(r)return r;const s=fetch($t(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||uo.delete(n),i));return uo.set(n,s),s}async function Hp(e,t,n=!1){const r={},{token:s,writerId:i}=zp(t);n&&(r["x-pyric-writer"]=HE(i));const o=await Ai(e,s);return o&&(r["x-pyric-session-token"]=o),r}function Kp(e,t){const n=e,{token:r}=zp(t),s=(i=!1)=>Hp(n,t,i);return{async read(i){const o=await s(!1),a=await fetch($t(n,`/__pyric/workspace?path=${encodeURIComponent(i)}`),{headers:o});if(a.status===404)return null;if(!a.ok)throw new Error(`workspace.read(${i}) → ${a.status}`);return a.text()},async write(i,o){const a=await s(!0),l=await fetch($t(n,`/__pyric/workspace?path=${encodeURIComponent(i)}`),{method:"PUT",headers:a,body:o});if(!l.ok)throw new Error(`workspace.write(${i}) → ${l.status}`)},async list(i){const o=await s(!1),a=i?`?dir=${encodeURIComponent(i)}`:"",l=await fetch($t(n,`/__pyric/workspace/list${a}`),{headers:o});if(!l.ok)throw new Error(`workspace.list(${i??""}) → ${l.status}`);return await l.json()},async branches(){const i=await s(!1),o=await fetch($t(n,"/__pyric/workspace/branches"),{headers:i});if(!o.ok)throw new Error(`workspace.branches() → ${o.status}`);return await o.json()},async remove(i){const o=await s(!0),a=await fetch($t(n,`/__pyric/workspace?path=${encodeURIComponent(i)}`),{method:"DELETE",headers:o});if(!a.ok)throw new Error(`workspace.remove(${i}) → ${a.status}`)},watch(i){let o=null,a=!1;const l=u=>{try{i(JSON.parse(u.data))}catch{}};return Ai(n,r).then(u=>{if(a)return;const d=u?$t(n,`/__pyric/workspace/watch?token=${encodeURIComponent(u)}`):$t(n,"/__pyric/workspace/watch");o=new EventSource(d),o.addEventListener("change",l)}),()=>{a=!0,o&&(o.removeEventListener("change",l),o.close())}}}}function er(e,t){return`${e.replace(/\/$/,"")}${t}`}function KE(e,t){const n=e,r=(s=!1)=>Hp(n,t,s);return{async list(){const s=await r(!1),i=await fetch(er(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),o=await fetch(er(n,`/__pyric/projects/${encodeURIComponent(s)}`),{headers:i});if(!o.ok)throw new Error(`projects.open(${s}) → ${o.status}`);return{meta:await o.json(),workspace:Kp(n,t)}},async create(s){const o={...await r(!0),"content-type":"application/json"},a=await fetch(er(n,"/__pyric/projects"),{method:"POST",headers:o,body:JSON.stringify(s)});if(!a.ok)throw new Error(`projects.create() → ${a.status}`);return await a.json()},async update(s,i){const a={...await r(!0),"content-type":"application/json"},l=await fetch(er(n,`/__pyric/projects/${encodeURIComponent(s)}`),{method:"PATCH",headers:a,body:JSON.stringify(i)});if(!l.ok)throw new Error(`projects.update(${s}) → ${l.status}`)},async remove(s){const i=await r(!0),o=await fetch(er(n,`/__pyric/projects/${encodeURIComponent(s)}`),{method:"DELETE",headers:i});if(!o.ok)throw new Error(`projects.remove(${s}) → ${o.status}`)}}}function GE(e,t){return`${e.replace(/\/$/,"")}${t}`}function ho(e){return/auth/i.test(e)?"auth":"firestore"}function JE(e){const t=e,n=`studio-${Math.random().toString(36).slice(2)}`,r=async()=>{const u=await Ai(t);return u!==null?{"x-pyric-session-token":u}:{}},s=async()=>({"content-type":"application/json","x-pyric-writer":n,...await r()}),i=new Map,o=u=>GE(t,`/__pyric/state?section=${ho(u)}`),a=async u=>{const d=ho(u),h=i.get(d);if(h)return h;const f=await fetch(o(u),{headers:await r()});let p=new Map;if(f.ok){const m=await f.text();m&&m!=="null"&&(p=aw(m))}else if(f.status!==404)throw new Error(`persistence.read(${u}) → ${f.status}`);return i.set(d,p),p},l=async(u,d)=>{const h=await fetch(o(u),{method:"POST",headers:await s(),body:cw(d)});if(h.status===423)throw new Error("persistence.write blocked, another tab holds the persist writer lock");if(!h.ok)throw new Error(`persistence.write(${u}) → ${h.status}`)};return{async getRecord(u,d){return(await a(u)).get(d)??null},async listRecords(u){return[...(await a(u)).keys()]},async putRecords(u,d){const h=await a(u);for(const[f,p]of d)h.set(f,p);await l(u,h)},async deleteRecords(u,d){const h=await a(u);for(const f of d)h.delete(f);await l(u,h)},async clear(u){i.set(ho(u),new Map);const d=await fetch(o(u),{method:"POST",headers:await s(),body:"null"});if(!d.ok&&d.status!==423)throw new Error(`persistence.clear(${u}) → ${d.status}`)}}}const YE="local";function QE(){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 o of e.keys())s&&!o.startsWith(s)||i.push({path:o,kind:"file"});return i},async remove(r){e.delete(r)&&n({path:r,type:"delete"})},async branches(){return[]},watch(r){return t.add(r),()=>t.delete(r)}}}function XE(){const e=QE();let t={id:YE,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(){}}}var po={};const ZE="/__pyric/sdk/worker.js",Dt="pyric-shared-worker",eC="/__pyric/ui/studio";function tC(e,t){if(typeof process<"u"&&po){const s=po.NEXT_PUBLIC_PYRIC_STUDIO_URL||po.PYRIC_STUDIO_URL;if(typeof s=="string"&&s.trim().length>0)return s.trim()}const n=globalThis.__PYRIC_WORKER_INIT__;if(typeof n?.studioUrl=="string"&&n.studioUrl.trim().length>0)return n.studioUrl.trim();if(typeof n?.bridgeUrl=="string"&&n.bridgeUrl.trim().length>0)try{const s=t?.href||(typeof location<"u"?location.href:""),i=new URL(n.bridgeUrl,s||"http://localhost"),o=t?.host||(typeof location<"u"?location.host:"")||(s?new URL(s).host:"");if(i.host&&(!o||i.host!==o))return`${i.protocol==="wss:"||i.protocol==="https:"?"https:":"http:"}//${i.host}/__pyric/ui/studio`}catch{}const r=e?.querySelector('meta[name="pyric-studio-url"]')?.getAttribute("content")?.trim()||e?.querySelector('meta[name="pyric-runtime-chip"]')?.getAttribute("data-studio-url")?.trim();return r||eC}function Gp(e=typeof document>"u"?void 0:document,t=typeof location>"u"?void 0:location){const n=e?.querySelector('meta[name="pyric-worker-v"]')?.getAttribute("content")?.trim()||null;return{studioUrl:tC(e,t),worker:{url:ZE,name:Dt,servedEpoch:n}}}const di="pyric:worker-generation",tr="pyric:worker-generation-probe";function nC(e,t){const n=e&&/^[a-f0-9]{16}$/.test(e)?e:null;if(!t)return n?`${Dt}:${n}`:Dt;try{const r=t.getItem(di);return r&&/^[a-f0-9]{16}$/.test(r)?`${Dt}:${r}`:n?(t.setItem(di,n),`${Dt}:${n}`):Dt}catch{return n?`${Dt}:${n}`:Dt}}function rC(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(di,e),t.getItem(di)!==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 sC(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(tr);if(e.setItem(tr,"ok"),e.getItem(tr)!=="ok")throw new Error("the worker generation probe could not be read back");t===null?e.removeItem(tr):e.setItem(tr,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 iC(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}}const oC=Symbol.for("pyric.ai-evidence"),aC=globalThis,cC=aC[oC]??=new WeakMap;function Uu(e,t){return cC.set(e,Object.freeze({...t})),e}function lC(){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 Jp=new WeakMap;let la;function uC(e,t,n=lC()){const r=e.name,s=n===t?void 0:{},i=new Map,o=new Set,a={app:e,sandbox:t,session:n,services:i,cleanups:o,assertAlive(){if(a.deleted)throw new H("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;a.assertAlive();const h=u();return i.set(l,h),h},onDelete(l){return a.deleted?(l(),()=>{}):(o.add(l),()=>o.delete(l))},deleted:!1};return Jp.set(e,a),a}function dC(e){la=e}Hw({resolve(e,t){const n=typeof e=="object"&&e!==null?Jp.get(e):void 0;if(n)return n},defaultApp(){if(!la)throw new TypeError("No default sandbox app registry is installed - import and initialize pyric/app before calling a service factory without an app.");return la()}});const fC="[DEFAULT]",hC=new Map;function pC(e,t){return new H(`app/${e}`,`Firebase: ${t} (app/${e}).`)}function mC(e){return pC("no-app",`No Firebase App '${e}' has been created - call initializeApp() first`)}function yC(e=fC){const t=hC.get(e);if(!t)throw mC(e);return t.app}dC(yC);const gC={mode:"wall",fixedAt:0,offsetMs:0};let fr=gC;function bC(e){fr=e}function wC(){return fr.mode==="fixed"?fr.fixedAt:fr.mode==="offset"?Date.now()+fr.offsetMs:Date.now()}const Bu=5174,Tr=12*1024*1024,vC=256,xC=24*1024*1024,Fu="/sandbox",_C=4001,SC="worker-relay",kC="storage-byte-route",jC="worker-port",EC=6e4,Yp=15e3,qu=3*Yp,CC=4004;function Qp(e){if(e===null||typeof e!="object")return!1;const n=e.type;return n==="hello"||n==="hello-ack"||n==="attach"||n==="attach-ack"||n==="tool-call"||n==="tool-result"||n==="worker-op"||n==="worker-res"||n==="worker-sub"||n==="worker-unsub"||n==="worker-snap"||n==="worker-client-disconnect"||n==="worker-client-interrupted"||n==="consumer-presence"||n==="remote-set-lens"||n==="remote-set-lens-ack"||n==="worker-event"||n==="worker-message"||n==="worker-message-result"||n==="ping"||n==="pong"}function ua(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=ua(t);if(n)return n}return null}for(const t of Object.values(e)){const n=ua(t);if(n)return n}return null}function Vu(e,t){const n=ua(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}const NC=new TextEncoder;function RC(){let e=0,t=0;return{reserve(n){if(e>=vC)return{accepted:!1,error:{code:"resource-exhausted",message:"This client already has 256 pending operations."}};let s;try{s=NC.encode(JSON.stringify(n)).byteLength}catch{return{accepted:!1,error:{code:"invalid-argument",message:"The operation must have a JSON-serializable encoding."}}}return t+s>xC?{accepted:!1,error:{code:"resource-exhausted",message:"This client exceeds the 24 MiB queued operation byte limit."}}:(e+=1,t+=s,{accepted:!0,release(){e-=1,t-=s}})}}}function Xp(e){if(e===null||typeof e!="object")return;const t=e,n=t.target,s=typeof n=="object"&&n!==null?n.instance:t.instance;return typeof s=="string"&&s.length>0?s:void 0}function An(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function IC(e){return An(e)?(e.mode==="wall"||e.mode==="fixed"||e.mode==="offset")&&Number.isFinite(e.fixedAt)&&Number.isFinite(e.offsetMs):!1}function Zp(e){if(e.ok===!0)return!0;const n=e.error,r=An(n);return e.ok===!1&&r&&typeof n.code=="string"&&typeof n.message=="string"}function em(e){if(!An(e)||e.clientSessionId!==void 0&&typeof e.clientSessionId!="string")return!1;switch(e.t){case"res":return typeof e.id=="string";case"snap":return typeof e.subId=="string";case"event":return typeof e.subId=="string"&&Array.isArray(e.events);case"runtime-reload":return typeof e.epoch=="string";case"clock":return IC(e.state);default:return!1}}function Wu(e){const t={code:"unavailable",message:"The sandbox sent a malformed subscription reply."};if(!Object.hasOwn(e,"value"))return t;const r=e.value;if(!(An(r)&&Object.hasOwn(r,"__error")))return;const o=r.__error;if(!An(o))return t;const u=o.code,d=o.message;if(typeof u!="string"||typeof d!="string")return t;const f=o.aiEvidence,p=An(f),m=o.codeless===!0?{codeless:!0}:{};return{code:u,...m,message:d,denialContext:o.denialContext,aiEnvelope:o.aiEnvelope,aiEvidence:p?f:void 0,envelope:o.envelope}}const Mr=new WeakMap;function tm(e){let t=Mr.get(e);return t===void 0&&(t={entries:[],closed:!1},Mr.set(e,t)),t}function AC(){return new H("app/app-deleted","Firebase App was deleted")}function nm(e,t){try{e.postMessage(t.message)}catch(n){t.failed?.(n)}}function OC(e,t){for(;t.entries.length>0;){const n=t.entries[0],r=n.frames.splice(0);for(const i of r)nm(e,i);if(!n.released)return;t.entries.shift()}}const $C=()=>performance.now();let DC=$C;function jc(){return DC()}function Oi(e,t,n){const r=Mr.get(e);if(!(r!==void 0&&r.entries.length>0)){e.postMessage(t);return}r.entries.push({frames:[{message:t,failed:n}],released:!0})}function rm(e){const t=tm(e),n={frames:[],released:!1};return t.closed||t.entries.push(n),{issuedAt:jc(),send(s,i){const o=t.entries[0]===n;if(t.closed){i(AC());return}if(o){nm(e,{message:s,failed:i});return}n.frames.push({message:s,failed:i})},release(){if(n.released)return;n.released=!0,t.entries[0]===n&&OC(e,t)}}}function sm(e,t){const n=Mr.get(e);for(const r of n?.entries??[]){const s=r.frames.findIndex(i=>"id"in i.message&&i.message.id===t);if(s>=0)return{entry:r,index:s}}}function im(e,t){return sm(e,t)!==void 0}function PC(e,t){const n=sm(e,t),r=n!==void 0;return r&&n.entry.frames.splice(n.index,1),r}function om(e,t){const n=Mr.get(e);for(const r of n?.entries??[]){const s=r.frames.findIndex(i=>i.message.t==="sub"&&i.message.subId===t);if(s>=0)return{entry:r,index:s}}}function TC(e,t){return om(e,t)!==void 0}function MC(e,t){const n=om(e,t),r=n!==void 0;return r&&n.entry.frames.splice(n.index,1),r}function am(e){const t=tm(e);t.closed=!0,t.entries.length=0}let LC=0,UC=0;function L(){return`op-${++LC}`}function un(){return`sub-${++UC}`}const Qe=new Map,ze=new Map,ot=new Map,Vn=new WeakSet,da=new Set;function BC(e){return da.add(e),()=>da.delete(e)}function Lr(){return Object.assign(new Error("Firebase App was deleted"),{code:"app/app-deleted"})}function FC(e,t,n){if(Vn.has(e))return;const s={...n,message:void 0};ze.set(t,s);const i=()=>ze.get(t)===s,o=a=>{i()&&ze.delete(t)&&n.error?.(a)};return{send(a,l){if(i()){s.message=a;try{l!==void 0?l.send(a,o):Oi(e,a,o)}catch(d){queueMicrotask(()=>o(d))}}}}}function os(e,t,n,r,s){const i=FC(e,t,n);return i===void 0?!1:(i.send(r,s),!0)}function qC(e,t,n,r,s,i){if(Vn.has(e))return s?.(Lr()),!1;ot.set(t,{port:e,next:n,error:s,message:r,restored:i});const a=l=>{ot.get(t)?.message===r&&ot.delete(t)&&s?.(l instanceof H?l:Lr())};try{Oi(e,r,a)}catch(l){queueMicrotask(()=>a(l))}return!0}function VC(e,t){const n=e.messagingVisibility;n&&t({...n,id:L()});for(const[r,s]of ze){const i=s.message;!(s.port===e&&i?.t==="sub")||!(i.target==="messaging.foreground"||i.target==="messaging.background")||(t({t:"unsub",subId:r}),t(i))}}function WC(e,t=n=>e.postMessage(n)){for(const[n,r]of ze){const s=r.message;if(!(r.port===e&&s?.t==="sub"))continue;const o=typeof s.target=="object"&&"service"in s.target&&s.target.service==="rtdb",a=r.service==="firestore"||o,l=s.target==="presence";(a||l)&&(t({t:"unsub",subId:n}),t(s))}for(const[n,r]of ot)r.port===e&&(r.restored?.(),t({t:"unsub",subId:n}),t(r.message))}function zC(e,t){for(const n of ze.values()){const r=n.message;n.port===e&&r?.t==="sub"&&(r.target==="authState"||r.target==="idToken")&&t(r)}}function it(e,t,n){const r=ze.get(t)??ot.get(t);if(!(r!==void 0)||(ze.delete(t),ot.delete(t),Vn.has(e))||r.message===void 0||MC(e,t)||e.withdrawSubscription?.(t)===!0)return;const a={t:"unsub",subId:t};n!==void 0&&n!==""&&(a.clientSessionId=n);const u=()=>{};try{Oi(e,a,u)}catch{}}function Ur(e,t,n=()=>!0){for(const[r,s]of[...Qe])s.port===e&&n(r)&&(Wn(r),s.reject(t))}function HC(e,t){const n=[];for(const[r,s]of Qe)s.port===e&&t(r)&&n.push({id:r,message:s.message});return n}function KC(e){const t=[];for(const n of e){const r=Qe.get(n),s=r?.message;if(!(r!==void 0&&s?.t==="op"))continue;const o={...s,id:L()};Qe.delete(n),Qe.set(o.id,{...r,message:o}),t.push(o)}return t}function zu(e,t){Wn(e)?.reject(t)}function GC(e){Wn(e)}function JC(e){Vn.add(e),Ur(e,Lr()),cm(e,new H("aborted","The operation was aborted."),Lr()),e.onmessage=null}function cm(e,t,n=t){for(const[r,s]of[...ze]){if(s.port!==e)continue;ze.delete(r),s.service==="firestore"?s.error?.(t):lm(s.message)&&s.error?.(n),s.close?.()}for(const[r,s]of[...ot])s.port===e&&(ot.delete(r),s.error?.(n))}function lm(e){if(!(e?.t==="sub"))return!1;const n=e.target;return typeof n=="object"&&n!==null&&"service"in n&&n.service==="ai"}function YC(e,t,n){for(const[r,s]of[...ze])!(s.port===e&&lm(s.message))||!(!n(r)&&!TC(e,r))||(it(e,r),s.error?.(t))}function Hu(e,t,n,r){if(t.denialContext===void 0||typeof fetch!="function")return;const s={kind:e,code:t.code??"unknown",message:t.message,denialContext:t.denialContext,...typeof t.remediation=="string"?{remediation:t.remediation}:{},...n===void 0?{}:{instance:n},...r!==void 0?{owners:r}:{}};try{fetch("/__pyric/denials",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(s)}).catch(()=>{})}catch{}}function $i(e){e.onmessage=t=>{const n=t.data;if(!em(n)){const u=new H("unavailable","The sandbox sent a malformed reply envelope. The operation may have completed; check state before retrying.");Ur(e,u);for(const[d,h]of ze)h.port===e&&(it(e,d),h.error?.(u));for(const[d,h]of ot)h.port===e&&(it(e,d),h.error?.(u));return}const s=n.t==="res",i=n.t==="snap",o=n.t==="event",a=n.t==="runtime-reload",l=n.t==="clock";if(s){const u=Qe.get(n.id);if(u===void 0||u.port!==e)return;if(Wn(n.id),!Zp(n)){u.reject(new H("unavailable","The sandbox sent a malformed operation reply. The operation may have completed; check state before retrying."));return}if(n.ok)u.resolve(n.value);else{const p=n.error.codeless!==!0;let m;p?m=new H(n.error.code,n.error.message):m=new Error(n.error.message),n.error.denialContext!==void 0&&(m.denialContext=n.error.denialContext);const b=n.error.aiEvidence;b!==void 0&&Uu(m,b),n.error.aiEnvelope!==void 0&&(m.aiEnvelope=n.error.aiEnvelope),Hu("read",m,u.instance),u.reject(m)}}else if(i){const u=ze.get(n.subId);if(u===void 0){const p=ot.get(n.subId),m=Wu(n);if(p!==void 0&&p.port===e&&m!==void 0){it(e,n.subId,p.message.clientSessionId);const g=m.codeless!==!0?new H(m.code,m.message):Object.assign(new Error(m.message),{code:"unavailable"});p.error?.(g)}return}if(u.port!==e)return;const h=Wu(n);if(h!==void 0){it(e,n.subId,u.message?.clientSessionId);const p=h.codeless!==!0;let m;p?m=new H(h.code,h.message):m=new Error(h.message),h.denialContext!==void 0&&(m.denialContext=h.denialContext);const b=h.aiEvidence;b!==void 0&&Uu(m,b),h.aiEnvelope!==void 0&&(m.aiEnvelope=h.aiEnvelope);const v=u.message,_=v!==void 0&&"owners"in v?v.owners:void 0;Hu("listener",m,Xp(v),_);const S=u.error;S!==void 0?S.call(u,m):console.error("pyric/firestore: Uncaught Error in snapshot listener:",m);return}u.next(n.value)}else if(o){const u=ot.get(n.subId);u!==void 0&&u.port===e&&u.next(n.events)}else if(a)for(const u of da)u(n);else l&&bC(n.state)},e.postMessage({t:"clock-subscribe"})}const wr="pyric:auth-lens";function QC(e){if(!e||typeof e!="object")return!1;const t=e;return t.mode==="admin"||t.mode==="anon"?!0:t.mode==="as"&&typeof t.uid=="string"}function um(e){if(QC(e))return e}function XC(){if(!(typeof sessionStorage>"u"))try{const e=sessionStorage.getItem(wr);if(!e)return;const t=JSON.parse(e),n=um(t);if(n)return n;sessionStorage.removeItem(wr);return}catch{try{sessionStorage.removeItem(wr)}catch{}return}}let jt=XC();const fa=new Set;function ZC(e){return fa.add(e),()=>{fa.delete(e)}}function Ku(e){if(jt=um(e),typeof sessionStorage<"u")try{jt?sessionStorage.setItem(wr,JSON.stringify(jt)):sessionStorage.removeItem(wr)}catch{}for(const t of[...fa])try{t(jt)}catch(n){console.error("Error in subscribeLens listener:",n)}}function eN(){return jt}let ha;function tN(e){ha=e}function Ec(e){return ha&&(e.t==="op"||e.t==="sub")?{...e,issuer:ha}:e}function Di(e,t,n,r){if(Vn.has(e))return Promise.reject(Lr());const o=t.t==="op"||t.t==="tool"?nN(e,t.clientSessionId):void 0,a=o?.reserve(t);return a?.accepted===!1?Promise.reject(new H(a.error.code,a.error.message)):(t.t==="disconnect"&&am(e),new Promise((d,h)=>{const f=t;Qe.set(f.id,{port:e,clientSessionId:t.clientSessionId,instance:Xp(t),budget:o,release:a?.release,issuedAt:r?.issuedAt??jc(),message:t,resolve:d,reject:h});const p=m=>{Wn(f.id)!==void 0&&h(m)};try{n!==void 0?n(t):r!==void 0?r.send(t,p):Oi(e,t,p)}catch(m){p(m)}}))}function nN(e,t){for(const n of Qe.values()){const r=n.port===e&&n.clientSessionId===t,s=n.budget;if(r&&s!==void 0)return s}return RC()}function Wn(e){const t=Qe.get(e);return Qe.delete(e),t!==void 0&&PC(t.port,e),t?.release?.(),t}function Q(e,t,n){return Di(e,Ec(t),void 0,n)}function dm(e,t,n,r){const s=t.id;let i;const o=new Promise((a,l)=>{i=setTimeout(()=>{Wn(s)!==void 0&&l(new Error(r))},n)});return Promise.race([Q(e,t),o]).finally(()=>{i!==void 0&&clearTimeout(i)})}function ye(e,t,n){if(Vn.has(e)&&!t.method.startsWith("rtdb."))return Promise.reject(new H("failed-precondition","The client has already been terminated."));const r=jt?{...t,actAs:jt}:t;return Q(e,r,n)}async function rN(e,t,n={}){const r=n.timeoutMs??12e3;await dm(e.port,{t:"op",id:L(),method:"retireRuntime",targetEpoch:t},r,`Timed out waiting for the Pyric worker to retire after ${r}ms.`)}function sN(e){return BC(t=>e(t.epoch))}const pa=Symbol("pyric/database/target"),iN=new WeakMap;function oN(e){let t;if(pa in e?t=e[pa]:t=iN.get(e),!t)throw new TypeError("pyric/database: unrecognized reference — was it produced by a factory in this package?");return t.kind==="sandbox-live"&&t.assertUsable?.(),t}const Gu=aN();function aN(){let e;try{const n=import.meta.url;typeof n=="string"&&(e=n)}catch{e=void 0}if(e===void 0)return"";const t=e.slice(0,e.lastIndexOf("/"));return t.startsWith("file://")?t.slice(7):t}function cN(e){return Gu.length===0?e:e.split(`
|
|
127
|
-
`).filter(t=>!t.includes(
|
|
128
|
-
`)}function fm(e){const t=[],n=lN();n!==void 0&&t.push(n);const r=lw(e?.owner);if(r!==void 0&&t.push(r),t.length!==0)return t}function lN(){if(!uw())return;const e=dw();if(e!==void 0)return fw(cN(e))}function uN(e){const t=new Map,n=new Set,r=()=>{for(const i of[...n])try{i()}catch{}},s=e.subscribe(i=>{i.phase==="remove"&&t.delete(i.record.id)});return{record(i,o){const a=Vs(o);a===void 0||a.kind!=="regions"||(t.set(i,Object.freeze([...a.selectors])),r())},regions:i=>t.get(i)??[],subscribe(i){return n.add(i),()=>{n.delete(i)}},dispose(){s(),t.clear(),n.clear()}}}const Ju=Symbol.for("pyric.delivered-regions"),Yu=globalThis,dN=Yu[Ju]??(Yu[Ju]=uN(Hr));function fN(e,t){dN.record(e,t)}function hN(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 o=i.message||`failed to load ${String(e)}`;n.onError?.(new Error(`Pyric SharedWorker error: ${o}`))});const s=r.port;return $i(s),s.start(),{__kind:"client-db",port:s}}async function pN(e,t={}){const n=L(),r=t.timeoutMs??2e3;return(await dm(e.port,{t:"op",id:n,method:"getRuntimeEpoch"},r,`Timed out waiting for the Pyric SharedWorker version handshake after ${r}ms.`)).version}async function mN(e){return(await Q(e.port,{t:"op",id:L(),method:"getVersion"})).instanceId??""}async function yN(e){return(await Q(e.port,{t:"op",id:L(),method:"exportState"})).bundle}async function gN(e,t){await Q(e.port,{t:"op",id:L(),method:"importState",bundle:t})}async function bN(e,t){await Q(e.port,{t:"op",id:L(),method:"checkpoint",name:t})}async function wN(e){return(await Q(e.port,{t:"op",id:L(),method:"listCheckpoints"})).checkpoints??[]}async function vN(e,t){await Q(e.port,{t:"op",id:L(),method:"restore",name:t})}async function xN(e,t){await Q(e.port,{t:"op",id:L(),method:"deleteCheckpoint",name:t})}async function _N(e,t,n,r,s){return await Q(e.port,{t:"tool",id:L(),name:t,args:n,clientSessionId:s,actAs:r})}function SN(e,t,n){return Di(e.port,{...t,issuer:void 0,relaySource:"remote",clientSessionId:n,t:"op",id:L()})}function kN(e,t,n,r){if(t.target==="events")throw new Error("event-stream subscriptions cannot be relayed over the bridge yet (needs bounded backpressure — slice 2)");const s=un();return os(e.port,s,{port:e.port,next:n,error:o=>n({__error:{code:o.code??"unknown",message:o instanceof Error?o.message:String(o)}})},{...t,issuer:void 0,relaySource:"remote",clientSessionId:r,t:"sub",subId:s})||queueMicrotask(()=>n({__error:{code:"app/app-deleted",message:"Firebase App was deleted"}})),()=>{it(e.port,s,r)}}function jN(e){const t=(e??"/").split("/").filter(Boolean).join("/");return t?`/${t}`:"/"}function hm(e){return e.kind==="where"?{...e,value:oh(e.value)}:{kind:e.kind,filters:e.filters.map(hm)}}function EN(e){return e.kind==="where"||e.kind==="and"||e.kind==="or"?hm(e):"values"in e?{...e,values:e.values.map(oh)}:e}function zn(e,t,n,r=fm(void 0)){const s=e.descriptor,i=s.__ref==="query"?s.source:s,o=i.__ref==="group"?i.collectionId:i.path,a=s.__ref==="query"?s.constraints:[];return Hr.begin({app:e.port,method:t,kind:n,owners:r,source:{service:"firestore",target:o,isQuery:s.__ref!=="doc",...s.__ref==="doc"?{}:{indexQuery:Kw(o,i.__ref==="group",a.filter(l=>["where","and","or"].includes(l.kind)),a.filter(l=>l.kind==="orderBy").map(l=>({...l,direction:l.direction??"asc"})))},key:Er({base:i,constraints:s.__ref==="query"?s.constraints.map(EN):[]})}})}const CN=[];function pm(e){for(const t of[...CN])t.port===e&&t.close()}const NN=5e3;function RN(){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 IN(e,t={}){let n;try{const r=Di(e.port,{t:"disconnect",id:L()}),s=new Promise((i,o)=>{n=setTimeout(()=>o(RN()),t.ackTimeoutMs??NN)});await Promise.race([r,s])}finally{n!==void 0&&clearTimeout(n),pm(e.port),JC(e.port),e.port.close()}}function AN(e,t){cm(e,t),pm(e)}function Cc(e){return e.split("/").at(-1)??e}function Wt(e,t,n=null){function r(i){return Wt(e,t,i)}const s={__kind:"doc-ref",descriptor:{__ref:"doc",path:t},port:e,id:Cc(t),path:t,converter:n,withConverter:r};return sh(s,t,e),s}function ON(e,t){const n=JSON.parse(e.json);return t!==void 0?hw(n,t,e.valueEncoding):Xa(n,e.valueEncoding)}const ma=4*1024*1024,Pi=512*1024*1024,$N="/__pyric/storage/v0/b/";function DN(e,t,n){const r=new URLSearchParams({alt:"media"});return`${$N}${encodeURIComponent(e)}/o/${encodeURIComponent(t)}?${r}`}function Nc(e,t){const n=new Error(`${t} is ${e} bytes — over the ${Pi/1048576} MiB maximum storage object cap (MAX_STORAGE_OBJECT_BYTES).`);return n.code="storage/quota-exceeded",n}function Qu(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 Xu(e){const t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}function PN(e,t){return ON(e,{create:r=>Wt(t,r)})}const mm=Object.freeze({fromCache:!1,hasPendingWrites:!1}),TN=Object.freeze({fromCache:!1,hasPendingWrites:!0});function ym(e){return e.hasPendingWrites===!0?TN:mm}const gm=new WeakMap;function MN(e){return gm.get(e)}function Rc(e,t,n,r=mm){if(!Ic(e))throw new H("invalid-argument","The sandbox sent a malformed document result.");let i;const o=e.data;e.exists&&o!==void 0&&(i=PN(o,t));const l=e.path??e.id,u=n??Wt(t,l),d=()=>{const f=i;if(f===void 0)return;const m=u.converter;if(m!==null){const b={id:e.id,ref:Wt(t,l),exists:()=>!0,metadata:r,data:()=>f};return m.fromFirestore(b)}return f},h={id:e.id,path:l,ref:u,exists:()=>e.exists,metadata:r,data:d,get:f=>LN(i,f)};return gm.set(h,{id:e.id,path:l,exists:e.exists,data:i}),h}function LN(e,t){try{return yw(e,t)}catch(n){const r=n instanceof Error?n.message:String(n);throw new H("invalid-argument",`Function DocumentSnapshot.get() called with invalid data. ${r}`)}}function ya(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ic(e){if(!ya(e))return!1;const r=e.data,s=r===void 0||ya(r)&&typeof r.json=="string",i=e.path===void 0||typeof e.path=="string";return typeof e.id=="string"&&typeof e.exists=="boolean"&&i&&s&&bm(e)}function bm(e){return e.hasPendingWrites===void 0||typeof e.hasPendingWrites=="boolean"}function wm(e){return ya(e)&&Array.isArray(e.docs)&&e.docs.every(Ic)&&bm(e)}function UN(e,t,n,r){if(wm(e)){const o=vm(e,t,n,r);return r.previous!==void 0&&o.docChanges().length===0&&(r.excludesMetadataChanges||o.metadata.hasPendingWrites===r.previousHasPendingWrites)?null:(r.previous=e.docs,r.previousHasPendingWrites=o.metadata.hasPendingWrites,o)}if(Ic(e)){const o=ym(e),a=r.previousDocument;return a!==void 0&&a.exists===e.exists&&(!e.exists||a.data?.json===e.data?.json)&&(r.excludesMetadataChanges||o.hasPendingWrites===r.previousHasPendingWrites)?null:(r.previousDocument=e,r.previousHasPendingWrites=o.hasPendingWrites,Rc(e,t,Wt(t,e.path??e.id,n),o))}throw new H("invalid-argument","The sandbox sent a malformed Firestore snapshot.")}function vm(e,t,n=null,r={excludesMetadataChanges:!1}){if(!wm(e))throw new H("invalid-argument","The sandbox sent a malformed query result.");const i=ym(e),o=h=>Rc(h,t,Wt(t,h.path??h.id,n),i),a=e.docs.map(o),l=e.docs.map(h=>({path:h.path??h.id,doc:h})),u=r.previous?.map(h=>({path:h.path??h.id,doc:h})),d=pw(u,l,a,(h,f)=>h.doc.data?.json===f.doc.data?.json,h=>o(h.doc));return{metadata:i,size:a.length,empty:a.length===0,docs:a,forEach:ih(a),docChanges:mw(d,r.excludesMetadataChanges)}}function BN(e,...t){const n=e.port;let r,s=null;const i=e.__kind==="client-db",o=t.length>0;if(i){if(!o)throw new TypeError("doc(db, path) requires a path segment.");r=t.join("/")}else{const a=e.descriptor.path;s=e.converter,o?r=`${a}/${t.join("/")}`:r=`${a}/${gw()}`}return Wt(n,r,s)}function FN(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("/")}`,xm(n,r,null)}function xm(e,t,n){function r(i){return xm(e,t,i)}return{__kind:"coll-ref",descriptor:{__ref:"collection",path:t},port:e,id:Cc(t),path:t,converter:n,withConverter:r}}function _m(e,t,n){function r(s){return _m(e,t,s)}return{__kind:"query",descriptor:t,port:e,converter:n,withConverter:r}}const gs="__name__",qN=new Set(["<","<=",">",">=","!=","not-in"]),Sm=new WeakMap,Zu=new WeakMap;function VN(e,t){if(!t.includes("."))return e[t];let n=e;for(const r of t.split(".")){if(n===null||typeof n!="object"||Array.isArray(n))return;n=n[r]}return n}function km(e,t){if(e.kind==="where"){qN.has(e.op)&&t.push(e.field);return}for(const n of e.filters)km(n,t)}function WN(e){return e.length===1&&e[0]!==null&&typeof e[0]=="object"&&"data"in e[0]&&typeof e[0].data=="function"}function zN(e,t){if(!WN(t))return{type:e,_descriptor:{kind:e,values:t.map(jr),valueEncoding:ln}};const n=t[0],r=MN(n)??(()=>{const i=n.data(),o=typeof n.id=="string"?n.id:"",a=typeof n.path=="string"?n.path:typeof n.ref?.path=="string"?n.ref.path:o,l=typeof n.exists=="function"?!!n.exists():i!==void 0;return{id:o,path:a,exists:l,data:i}})(),s={type:e,_descriptor:{kind:e,values:[],valueEncoding:ln}};return Sm.set(s,{__snapshotCursor:!0,kind:e,snapshot:r}),s}function mo(e){return"__snapshotCursor"in e}function HN(e){if(!e.some(mo))return e;const n=[],r=[];for(const l of e)mo(l)||(l.kind==="orderBy"?n.push({field:l.field,direction:l.direction??"asc"}):(l.kind==="where"||l.kind==="and"||l.kind==="or")&&km(l,r));const s=[...n],i=new Set(s.map(l=>l.field)),o=n.length>0?n[n.length-1].direction:"asc";for(const l of r)l!==gs&&!i.has(l)&&(i.add(l),s.push({field:l,direction:o}));i.has(gs)||s.push({field:gs,direction:o});const a=s.map(l=>({kind:"orderBy",field:l.field,direction:l.direction}));for(const l of e){if(mo(l)){const{snapshot:u}=l;if(!u.exists||u.data===void 0)throw new H("not-found",`Snapshot-based cursors require an existing document — got an empty snapshot for ${u.id||"<unknown>"}.`);const d=s.map(h=>h.field===gs?jr(u.path):jr(VN(u.data,h.field)));a.push({kind:l.kind,values:d,valueEncoding:ln});continue}l.kind!=="orderBy"&&a.push(l)}return a}function KN(e){return{type:"limit",_descriptor:{kind:"limit",n:e}}}function GN(...e){return zN("startAfter",e)}function JN(e,...t){const n=(e.__kind==="coll-ref",e.descriptor),s=[...e.__kind==="query"?Zu.get(e)??e.descriptor.constraints:[],...t.map(a=>Sm.get(a)??a._descriptor)],i={__ref:"query",source:n.__ref==="query"?n.source:n,constraints:HN(s)},o=_m(e.port,i,e.converter);return Zu.set(o,s),o}function YN(e){return QN(e,"getDoc")}async function QN(e,t){const n=zn(e,t,"operation");try{const r=await ye(e.port,{t:"op",id:L(),method:"getDoc",path:e.descriptor.path});return On(n,Rc(r,e.port,e))}catch(r){throw n.fail(),r}}function XN(e){return ZN(e,"getDocs")}async function ZN(e,t){const n=zn(e,t,"operation");try{const r=await ye(e.port,{t:"op",id:L(),method:"getDocs",source:(e.__kind==="coll-ref",e.descriptor)});return On(n,vm(r,e.port,e.converter))}catch(r){throw n.fail(),r}}async function eR(e){return(await ye(e.port,{t:"op",id:L(),method:"listRootCollections"})).ids}async function tR(e,t){return(await ye(e.port,{t:"op",id:L(),method:"listSubcollections",docPath:t})).ids}function nR(e,t,n,r){const s=typeof t=="function",i=s?void 0:t,o=fm(i),a=i?.includeMetadataChanges===!0,l={excludesMetadataChanges:!a},u=s?t:n,d=s?n:r;let h=un();const f=e.port,p=zn(e,"onSnapshot","subscription",o);p.transport(h);const m={port:f,service:"firestore",next:_=>{let S;try{S=UN(_,f,e.converter,l)}catch(O){v(),d!==void 0?d(O):console.error("pyric/firestore: Uncaught Error in snapshot listener:",O);return}if(S===null)return;const k=S,N=_;p.delivered(k,N.usage),fN(p.id,()=>u(k))},error:_=>{p.fail(),d?.(_)},close:()=>p.close()},g=e.descriptor;function b(){const _={t:"sub",subId:h,target:g};jt!==void 0&&(_.actAs=jt),o!==void 0&&(_.owners=o),a&&(_.includeMetadataChanges=!0);const N=os(f,h,m,Ec(_));return!N&&p.fail(),!N&&d!==void 0&&queueMicrotask(()=>d(new Error("Firebase App was deleted"))),N}b();let w=!1;const x=ZC(()=>{w||(it(f,h),h=un(),p.transport(h),b())});function v(){w=!0,p.close(),x(),it(f,h)}return v}function jm(e,t){const n=e.converter,r=n!==null;let s=t;return r&&(s=n.toFirestore(t)),bw(s)}async function rR(e,t,n){return nc(zn(e,"setDoc","operation"),async()=>{const r=jm(e,t);await ye(e.port,{t:"op",id:L(),method:"setDoc",path:e.descriptor.path,data:jr(r),valueEncoding:ln,options:n})})}async function sR(e){return nc(zn(e,"deleteDoc","operation"),async()=>{await ye(e.port,{t:"op",id:L(),method:"deleteDoc",path:e.descriptor.path})})}async function iR(e,t){return nc(zn(e,"addDoc","operation"),async()=>{const n=jm(e,t),r=await ye(e.port,{t:"op",id:L(),method:"addDoc",collectionPath:e.descriptor.path,data:jr(n),valueEncoding:ln});return Wt(e.port,r.path,e.converter)})}async function oR(e,t){return await Q(e.port,{t:"op",id:L(),method:"admin.listDocuments",path:t})}const aR=Xa({__type:"path",segments:[]},ln).constructor;class cR{port;subId=un();subscribers=new Set;history=new ah(ch);isAwaitingHistory=!0;hasReceivedHistory=!1;constructor(t){this.port=t}open(t){this.subscribers.add(t),En.set(this.port,this);const n={t:"sub",subId:this.subId,target:"events"};qC(this.port,this.subId,r=>this.receive(r),n,r=>this.fail(r),()=>{this.isAwaitingHistory=!0})}join(t){this.subscribers.add(t),this.hasReceivedHistory&&queueMicrotask(()=>{this.subscribers.has(t)&&ed(t,this.history.snapshot())})}leave(t){this.subscribers.delete(t)&&this.subscribers.size===0&&(En.delete(this.port),it(this.port,this.subId))}receive(t){const n=this.isAwaitingHistory;n&&this.history.clear();for(const s of t)this.record(s);this.isAwaitingHistory=!1;const r=n&&!this.hasReceivedHistory;this.hasReceivedHistory=!0;for(const s of[...this.subscribers])this.subscribers.has(s)&&(r?ed(s,t):s.isPrimed&&Em(s,t,n))}record(t){t.kind==="session_boundary"&&t.phase==="reset"?this.history.clear():this.history.append(t)}fail(t){En.get(this.port)===this&&En.delete(this.port);const n=[...this.subscribers];this.subscribers.clear();for(const r of n)try{r.onError?.(t)}catch(s){console.error("pyric: Uncaught Error in event subscriber error handler:",s)}}}const En=new WeakMap;function Em(e,t,n){try{e.callback(t,{history:n})}catch(r){console.error("pyric: Uncaught Error in event subscriber:",r)}}function ed(e,t){e.isPrimed=!0,Em(e,t,!0)}function lR(e,t,n){const r=e.port,s={callback:t,onError:n,isPrimed:!1},i=En.get(r);return i?i.join(s):new cR(r).open(s),()=>{En.get(r)?.leave(s)}}function uR(e){return e.__type__==="__vector__"&&Array.isArray(e.value)?!0:typeof e.__type=="string"?e.__type==="timestamp"||e.__type==="bytes"||e.__type==="latlng"||e.__type==="duration"||e.__type==="reference":typeof e.type=="string"?e.type==="firestore/timestamp/1.0"||e.type==="firestore/bytes/1.0"||e.type==="firestore/geoPoint/1.0"||e.type==="firestore/vectorValue/1.0":!1}function Ms(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(Ms);const t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)return e;const n=e;if(n.type==="pyric/map/1.0"){const s=n.fields;if(s===null||typeof s!="object"||Array.isArray(s))throw new TypeError("Invalid encoded map fields.");const i={};for(const[o,a]of Object.entries(s))i[o]=Ms(a);return i}if(n.__type==="number"){if(n.value==="NaN")return Number.NaN;if(n.value==="Infinity")return 1/0;if(n.value==="-Infinity")return-1/0;if(n.value==="-0")return-0}if(n.__type==="path"&&Array.isArray(n.segments)){const s=n.bindings,i=s!==null&&typeof s=="object"&&!Array.isArray(s)?s:void 0;return new aR(n.segments,i)}if(uR(n))return Xa(n,ln);const r={};for(const[s,i]of Object.entries(n))r[s]=Ms(i);return r}async function dR(e){const t=await Q(e.port,{t:"op",id:L(),method:"getSnapshot"}),n={};for(const[r,s]of Object.entries(t.firestore??{}))n[r]=Ms(s);return{firestore:n,services:t.services}}async function fR(e){return await Q(e.port,{t:"op",id:L(),method:"resetAll"})??{errors:[]}}const hR=15e3;function pR(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"}function td(){return typeof document<"u"&&typeof document.addEventListener=="function"&&typeof document.removeEventListener=="function"}function nd(){return typeof window<"u"&&typeof window.addEventListener=="function"&&typeof window.removeEventListener=="function"}function mR(){return pR()?crypto.randomUUID():`page-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function rd(){return typeof location>"u"?"/":`${location.pathname}${location.search}${location.hash}`}function sd(){return typeof document>"u"?"visible":document.visibilityState==="hidden"?"hidden":"visible"}function yR(e){const{db:t,kind:n}=e,r=e.clientId??mR(),s=e.heartbeatIntervalMs??hR;let i=!1,o=null;const a=()=>{Q(t.port,{t:"op",id:L(),method:"presence.register",clientId:r,kind:n,route:rd(),visibility:sd()}).catch(()=>{})},l=()=>{Q(t.port,{t:"op",id:L(),method:"presence.heartbeat",clientId:r}).catch(()=>{})},u=()=>{Q(t.port,{t:"op",id:L(),method:"presence.update",clientId:r,route:rd(),visibility:sd()}).catch(()=>{})},d=()=>{Q(t.port,{t:"op",id:L(),method:"presence.disconnect",clientId:r}).catch(()=>{})};a(),td()&&document.addEventListener("visibilitychange",u),nd()&&(window.addEventListener("popstate",u),window.addEventListener("hashchange",u),window.addEventListener("pagehide",h),o=setInterval(()=>{i||l()},s));function h(){f()}function f(){i||(i=!0,o!=null&&(clearInterval(o),o=null),td()&&document.removeEventListener("visibilitychange",u),nd()&&(window.removeEventListener("popstate",u),window.removeEventListener("hashchange",u),window.removeEventListener("pagehide",h)),d())}return{clientId:r,kind:n,stop:f}}function gR(e,t){const n=un();return os(e.port,n,{port:e.port,next:r=>{t(r)}},{t:"sub",subId:n,target:"presence"}),()=>{it(e.port,n)}}async function bR(e){return await Q(e.port,{t:"op",id:L(),method:"auth.listUsers"})}async function wR(e,t){return await Q(e.port,{t:"op",id:L(),method:"auth.adminCreateUser",request:t})}async function vR(e,t,n){return await Q(e.port,{t:"op",id:L(),method:"auth.adminUpdateUser",uid:t,request:n})}async function xR(e,t){await Q(e.port,{t:"op",id:L(),method:"auth.adminDeleteUser",uid:t})}async function _R(e){await Q(e.port,{t:"op",id:L(),method:"auth.adminClearUsers"})}async function SR(e){return await Q(e.port,{t:"op",id:L(),method:"auth.getProviderConfig"})}async function kR(e,t,n){await Q(e.port,{t:"op",id:L(),method:"auth.setProviderConfig",providerId:t,enabled:n})}const jR=Symbol("pyric.clientUser.port");function ER(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,tenantId:t.tenantId??null,providerId:t.providerId,providerData:t.providerData,async getIdToken(r){return await Q(e,{t:"op",id:L(),method:"auth.getIdToken",forceRefresh:r})},async getIdTokenResult(r){return await Q(e,{t:"op",id:L(),method:"auth.getIdTokenResult",forceRefresh:r})}};return Object.defineProperty(n,jR,{value:e,enumerable:!1}),n}function Cm(e,t){return t?ER(e,t):null}function CR(e,t){let n;if(typeof e=="string"||e instanceof URL){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(),$i(n)}else n=e.port;let s=null;const i={__kind:"client-auth",port:n,currentUser:null,get tenantId(){return s},set tenantId(a){s=a,Q(n,{t:"op",id:L(),method:"auth.setTenantId",tenantId:a})}};n.restoreAuth=async a=>{await a({t:"op",id:L(),method:"auth.setTenantId",tenantId:i.tenantId});const l=i.currentUser;l!==null&&await NR(i,l.uid,a,l.tenantId)};const o=un();return os(n,o,{port:n,next:a=>{i.currentUser=Cm(n,a)}},{t:"sub",subId:o,target:"idToken"}),i}async function NR(e,t,n=s=>Q(e.port,s),r=e.tenantId){const s=await n({t:"op",id:L(),method:"auth.restorePortSession",uid:t,tenantId:r}),i=Cm(e.port,s);return e.currentUser=i,i}const RR=1e4,Nm="The hosted sandbox connection was not restored within 10 seconds. The request was not sent.";let Rm=RR;function IR(e){let t;const n=new Promise((r,s)=>{t=setTimeout(()=>s(new H("unavailable",Nm)),Rm)});return Promise.race([e,n]).finally(()=>clearTimeout(t))}function yo(e){if("id"in e&&typeof e.id=="string")return e.id}function id(e){if(e.t==="sub"||e.t==="unsub")return e.subId}function AR(e){const t=[];function n(s,i){const o=t.indexOf(s);o<0||(t.splice(o,1),Ur(e,new H("unavailable",Nm),l=>l===i))}function r(){const s=t.splice(0);for(const i of s)clearTimeout(i.deadline);return s}return{hold(s){const i={message:s},o=yo(s);if(t.push(i),o===void 0)return;const l=Qe.get(o);if(!(l!==void 0&&l.port===e))return;const d=l.issuedAt+Rm-jc();if(d<=0){n(i,o);return}i.deadline=setTimeout(()=>n(i,o),d)},holdAgain(s){t.unshift(...s.map(i=>({message:i})))},holdsRequest(s){return t.some(i=>yo(i.message)===s)},holdsSubscription(s){const i=id(s);return i!==void 0?t.some(a=>a.message.t==="sub"&&a.message.subId===i):!1},forgetSubscription(s){const i=t.findIndex(a=>a.message.t==="sub"&&a.message.subId===s),o=i>=0;return o&&t.splice(i,1),o},flush(s){const i=r(),o=a=>id(a.message)!==void 0;for(const a of i.filter(o))s(a.message);for(const a of i.filter(l=>!o(l)))s(a.message)},drop(){r()},fail(s){const i=new Set(r().map(o=>yo(o.message)));Ur(e,s,o=>i.has(o))}}}function OR(e){return e.then(t=>({result:t}),t=>({error:t}))}function $R(e){return e!==void 0&&"result"in e?e.result:void 0}function Im(e){const t=e?.code;if(typeof t=="string")return t}async function DR(e,t){if(!(t!==void 0))return!1;try{return await XR(e,t),!0}catch(r){if(Im(r)==="storage/unauthorized")return!1;throw r}}async function PR(e,t){if(t.replacedObject===!0)throw new H("storage/unknown","The host no longer holds the object this upload replaced, so it cannot be restored.");try{await qm(e)}catch(n){if(!(Im(n)==="storage/object-not-found"))throw n}}function TR(e){return e.replacedObject===!0?"restore":"remove"}async function MR(e,t){try{await DR(e,t.rollbackToken)||await PR(e,t)}catch(n){throw ra(e.fullPath,n,TR(t))}}function LR(e){return e instanceof Error?e:new Error(String(e))}function UR(e){return e instanceof Blob?e.size:e.byteLength}function BR(){const e=new Error("storage/canceled: User canceled the upload/download.");return e.code="storage/canceled",e}function FR(){const e=new Error("storage/invalid-root-operation: uploadBytesResumable cannot operate on root reference.");return e.code="storage/invalid-root-operation",e}class qR{[Symbol.toStringTag]="UploadTask";_snapshot;_promise;_resolve;_reject;_observers=[];_didIntermediateProgress=!1;_committing=!1;_heldOutcome;_sentCommit;_error;_ref;_data;_metadata;_upload;_inFlight;_sending=!1;_resyncs=!1;constructor(t,n,r){this._ref=t,this._data=n,this._metadata=r;const s=UR(n),i=new Date(wC()).toISOString();let o="application/octet-stream";if(n instanceof Blob&&n.type!==""&&(o=n.type),r!==void 0&&r.contentType!==void 0){const h=r.contentType;h!==void 0&&(o=h)}const u={fullPath:t.fullPath,name:t.name,bucket:t.bucket||"default",generation:"1",metageneration:"1",timeCreated:i,updated:i,size:s,contentType:o};this._promise=new Promise((d,h)=>{this._resolve=d,this._reject=h}),this._promise.catch(()=>{}),this._snapshot={bytesTransferred:0,totalBytes:s,state:"running",metadata:u,ref:this._ref,task:this},this._start(),queueMicrotask(()=>{this._runStep()})}_start(){!(this._ref.port.byteRouteSettled?.()!==void 0)&&vr(this._ref)!==void 0?this._sendOverRoute():this._commitUpload()}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._resyncs=!0,this._inFlight?.abort(),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;if((this._snapshot.state==="running"||this._snapshot.state==="paused")&&(t=!0),t){const r=BR();return this._updateSnapshot("canceled",this._snapshot.bytesTransferred),this._inFlight?.abort(),this._rollBackCanceled().then(()=>this._settleCanceled(r),s=>this._settleCanceled(LR(s))),!0}return!1}_settleCanceled(t){this._error=t,this._notifyObservers("error"),this._reject(t)}async _rollBackCanceled(){const t=this._heldOutcome;this._heldOutcome=void 0;const n=this._sentCommit,r=t??(n===void 0?void 0:await n),s=this._upload;s!==void 0&&await Ls(s);const i=$R(r);i!==void 0&&await MR(this._ref,i)}_sendCommit(t){const n=OR(t);return this._sentCommit=n,n}_releaseHeldOutcome(){const t=this._heldOutcome;return t===void 0?!1:(this._heldOutcome=void 0,"result"in t?this._succeed(t.result.metadata):this._fail(t.error),!0)}on(t,n,r,s){let i,o,a,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&&(o=f.error),f.complete!==void 0&&(a=f.complete)}else typeof n=="function"&&(i=n),typeof r=="function"&&(o=r),typeof s=="function"&&(a=s);const d={next:i,error:o,complete:a};if(this._observers.push(d),this._snapshot.state==="running"){if(i!==void 0){const p=i;try{Ut(this),p(this._snapshot)}catch{}}}else if(this._snapshot.state==="paused"){if(i!==void 0){const m=i;try{Ut(this),m(this._snapshot)}catch{}}}else if(this._snapshot.state==="success"){if(i!==void 0){const b=i;try{Ut(this),b(this._snapshot)}catch{}}if(a!==void 0){const b=a;try{ni(this),b()}catch{}}}else if(this._snapshot.state==="error"){if(o!==void 0&&this._error!==void 0){const w=o,x=this._error;try{w(x)}catch{}}}else if(this._snapshot.state==="canceled"&&o!==void 0&&this._error!==void 0){const x=o,v=this._error;try{x(v)}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 a=i.next;try{Ut(this),a(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 a=i.complete;try{ni(this),a()}catch{}}}}async _sendOverRoute(){if(this._sending)return;this._sending=!0;const t=Um(this._data),n=()=>this._snapshot.state==="running";try{const r=vr(this._ref);let s=this._upload;if(s===void 0){const l=this._metadata?.contentType??(t.type!==""?t.type:void 0);if(s=await Pm(this._ref,r,t.size,l,this._metadata),this._upload=s,this._snapshot.state==="canceled"&&await Ls(s),!n())return}let i=this._snapshot.bytesTransferred;for(this._resyncs&&(i=await QR(s),this._resyncs=!1);n()&&i<s.size;){const l=new AbortController;if(this._inFlight=l,i=await Mm(s,t,i,l.signal),this._inFlight=void 0,!n())return;this._updateSnapshot("running",i),this._notifyObservers("next")}if(!n())return;const o=await this._sendCommit(Lm(s,!0));if("error"in o&&n())throw o.error;this._settleCommit(o)}catch(r){if(this._inFlight=void 0,!n())return;this._error=r instanceof Error?r:new Error(String(r)),this._updateSnapshot("error",this._snapshot.bytesTransferred);const s=this._upload;s!==void 0&&await Ls(s),this._notifyObservers("error"),this._reject(this._error)}finally{this._sending=!1,n()&&queueMicrotask(()=>this._runStep())}}_runStep(){if(this._snapshot.state!=="running")return;if(vr(this._ref)!==void 0&&!this._committing){this._releaseHeldOutcome()||this._sendOverRoute();return}if(this._didIntermediateProgress===!1){this._didIntermediateProgress=!0;let i=0;this._snapshot.totalBytes>0&&(i=Math.floor(this._snapshot.totalBytes/2)),this._updateSnapshot("running",i),this._notifyObservers("next")}this._releaseHeldOutcome()||this._commitUpload()}_succeed(t){this._updateSnapshot("success",this._snapshot.totalBytes,t),this._notifyObservers("next"),this._notifyObservers("complete"),this._resolve(this._snapshot)}_fail(t){this._error=t instanceof Error?t:new Error(String(t)),this._updateSnapshot("error",this._snapshot.bytesTransferred),this._notifyObservers("error"),this._reject(this._error)}async _commitUpload(){const t=this._snapshot.state!=="running",n=this._committing||this._heldOutcome!==void 0;if(t||n)return;this._committing=!0;const r=await this._sendCommit(Bm(this._ref,this._data,this._metadata,!0));this._committing=!1,this._settleCommit(r)}_settleCommit(t){const n=this._snapshot.state;if(n==="running"){"result"in t?this._succeed(t.result.metadata):this._fail(t.error);return}n==="paused"&&(this._heldOutcome=t)}}function VR(e,t,n){if(e.fullPath==="")throw FR();return new qR(e,t,n)}class Br{__kind="storage-ref";port;storage;bucket;fullPath;name;constructor(t,n,r,s){this.port=t,this.bucket=n,this.fullPath=r,this.name=Cc(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 Br(this.port,this.bucket,n,this.storage)}get root(){return this.fullPath===""?this:new Br(this.port,this.bucket,"",this.storage)}toString(){return`gs://${this.bucket}/${this.fullPath}`}}function WR(e){return e.replace(/^\/+|\/+$/g,"").replace(/\/+/g,"/")}function zR(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(),$i(r)}return{__kind:"client-storage",port:r,bucket:n??"pyric-default"}}function HR(e,t){const n=WR(ta(t,e.__kind==="client-storage"));let r,s,i="pyric-default",o;if(e.__kind==="client-storage")r=n,s=e.port,i=e.bucket,o=e;else{const a=e.fullPath;r=n?a?`${a}/${n}`:n:a,s=e.port,i=e.bucket,o=e.storage}return new Br(s,i,r,o)}async function KR(e){const t=await ye(e.port,{t:"op",id:L(),method:"storage.listAll",path:e.fullPath}),n=r=>new Br(e.port,e.bucket,r.fullPath,e.storage);return{items:t.items.map(n),prefixes:t.prefixes.map(n)}}function Am(e,t){return e.bucket?{...t,bucket:e.bucket}:t}async function Om(e){return await ye(e.port,{t:"op",id:L(),method:"storage.getMetadata",path:e.fullPath})}async function $m(e){return Am(e,await Om(e))}const GR=4*1024*1024;async function JR(e){const t=await e.sessionToken();if(t===null||t==="")throw new H("unavailable","The page has no session token for the hosted byte route. Reload the page.");return t}function Ac(e,t){return e===401||e===403?new H("storage/unauthorized",`The host refused bytes for '${t}' (HTTP ${e}).`):e===404?new H("storage/object-not-found",`Object '${t}' does not exist.`):new H("storage/unknown",`The host's byte route answered HTTP ${e} for '${t}'.`)}async function YR(e,t){for(let n=0;n<2;n++){const r=await Om(t),s=new URL(DN(r.bucket,t.fullPath),e.baseUrl);s.searchParams.set("generation",r.generation);const i=await fetch(s,{headers:{"x-pyric-session-token":await JR(e)}});if(i.status===412)continue;if(!i.ok)throw Ac(i.status,t.fullPath);const a=new Uint8Array(await i.arrayBuffer());return{bytes:a,contentType:i.headers.get("content-type")??r.contentType,size:a.byteLength}}throw new H("storage/retry-limit-exceeded",`Object '${t.fullPath}' kept changing while it was read.`)}function vr(e){return e.port.byteRoute}async function Dm(e,t){const n=e.port.byteRouteSettled?.();if(n===void 0)return t(vr(e),void 0);const s=rm(e.port);try{return await IR(n),await t(vr(e),s)}finally{s.release()}}async function Pm(e,t,n,r,s){const i=await ye(e.port,{t:"op",id:L(),method:"storage.beginUpload",path:e.fullPath,size:n,...r!==void 0?{contentType:r}:{},...s!==void 0?{metadata:s}:{}}),o=i.uploadUrl;if(o===void 0)throw new H("storage/unknown","The host began the upload without a byte route URL.");return{uploadId:i.uploadId,url:new URL(o,t.baseUrl).href,size:n,reference:e}}function Tm(e,t){if(e.status===200)return t;const r=/^bytes=0-(\d+)$/.exec(e.headers.get("range")??"");return r===null?0:Number(r[1])+1}async function Mm(e,t,n,r){const s=Math.min(n+GR,e.size),i=await fetch(e.url,{method:"PUT",headers:{"content-range":`bytes ${n}-${s-1}/${e.size}`},body:t.slice(n,s),signal:r});if(!(i.status===200||i.status===308||i.status===409))throw Ac(i.status,e.reference.fullPath);return Tm(i,e.size)}async function QR(e,t){const n=await fetch(e.url,{method:"PUT",headers:{"content-range":`bytes */${e.size}`},signal:t});if(!(n.status===200||n.status===308))throw Ac(n.status,e.reference.fullPath);return Tm(n,e.size)}function ga(e,t){const{rollbackToken:n,replacedObject:r,...s}=t,i=Am(e,s);return typeof n=="string"?{metadata:i,rollbackToken:n,replacedObject:r===!0}:{metadata:i}}function ba(e){return e?{rollback:!0}:{}}async function Lm(e,t=!1){const n=await ye(e.reference.port,{t:"op",id:L(),method:"storage.finishUpload",uploadId:e.uploadId,...ba(t)});return ga(e.reference,n)}async function XR(e,t){await ye(e.port,{t:"op",id:L(),method:"storage.rollbackUpload",rollbackToken:t})}async function Ls(e){try{await ye(e.reference.port,{t:"op",id:L(),method:"storage.abortUpload",uploadId:e.uploadId})}catch{}}function Um(e){return e instanceof Blob?e:new Blob([e])}async function ZR(e,t){const n=await eI(e),r=typeof t=="number"&&n.bytes.byteLength>t?n.bytes.subarray(0,Math.max(0,t)):n.bytes,s=r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength);return new Blob([s],{type:n.contentType??"application/octet-stream"})}async function eI(e){return Dm(e,(t,n)=>t!==void 0?(n?.release(),YR(t,e)):tI(e,n))}async function tI(e,t){try{const n=await ye(e.port,{t:"op",id:L(),method:"storage.getBytes",path:e.fullPath},t);return{bytes:Xu(n.dataB64),contentType:n.contentType,size:n.size}}catch(n){if(n?.code==="payload-too-large"){const r=await $m(e),s=[];let i=0;for(;i<r.size;){const l=Math.min(ma,r.size-i),u=await ye(e.port,{t:"op",id:L(),method:"storage.getBytes",path:e.fullPath,offset:i,length:l,expectedGeneration:r.generation});s.push(Xu(u.dataB64)),i+=l}const o=new Uint8Array(r.size);let a=0;for(const l of s)o.set(l,a),a+=l.byteLength;return{bytes:o,contentType:r.contentType,size:r.size}}throw n}}async function nI(e,t,n){const r=await Bm(e,t,n,!1);return{ref:e,metadata:r.metadata}}async function Bm(e,t,n,r){return Dm(e,(s,i)=>{if(s!==void 0)return i?.release(),sI(e,s,Um(t),n,r);if(t instanceof Blob)return rI(e,t,n,r,i);const l=t instanceof ArrayBuffer?new Uint8Array(t):t;return Fm(e,l,n?.contentType,n,r,i)})}async function rI(e,t,n,r,s){if(t.size>Pi)throw Nc(t.size,`uploadBytes payload for '${e.fullPath}'`);const o=n?.contentType??(t.type!==""?t.type:void 0),a=s??rm(e.port);try{const l=new Uint8Array(await t.arrayBuffer());return await Fm(e,l,o,n,r,a)}finally{a.release()}}async function Fm(e,t,n,r,s,i){if(t.byteLength>Pi)throw Nc(t.byteLength,`uploadBytes payload for '${e.fullPath}'`);if(t.byteLength<=ma){const u=ye(e.port,{t:"op",id:L(),method:"storage.putBytes",path:e.fullPath,dataB64:Qu(t),...n!==void 0?{contentType:n}:{},...r!==void 0?{metadata:r}:{},...ba(s)},i);return i?.release(),ga(e,await u)}const o=ye(e.port,{t:"op",id:L(),method:"storage.beginUpload",path:e.fullPath,size:t.byteLength,...n!==void 0?{contentType:n}:{},...r!==void 0?{metadata:r}:{}},i);i?.release();const l=(await o).uploadId;try{let u=0,d=0;for(;u<t.byteLength;){const f=Math.min(u+ma,t.byteLength),p=t.subarray(u,f);await ye(e.port,{t:"op",id:L(),method:"storage.putPart",uploadId:l,partIndex:d,dataB64:Qu(p)}),u=f,d++}const h=await ye(e.port,{t:"op",id:L(),method:"storage.finishUpload",uploadId:l,...ba(s)});return ga(e,h)}catch(u){try{await ye(e.port,{t:"op",id:L(),method:"storage.abortUpload",uploadId:l})}catch{}throw u}}async function sI(e,t,n,r,s){if(n.size>Pi)throw Nc(n.size,`uploadBytes payload for '${e.fullPath}'`);const o=r?.contentType??(n.type!==""?n.type:void 0),a=await Pm(e,t,n.size,o,r);try{let l=0;for(;l<a.size;)l=await Mm(a,n,l);return await Lm(a,s)}catch(l){throw await Ls(a),l}}async function qm(e){await ye(e.port,{t:"op",id:L(),method:"storage.deleteObject",path:e.fullPath})}function as(e,t){return{instance:t??("instance"in e?e.instance?.name:void 0)}}async function iI(e,t){return Q(e.port,{t:"op",id:L(),method:"rtdb.adminSnapshot",...as(e,t)})}async function oI(e,t,n,r){await Q(e.port,{t:"op",id:L(),method:"rtdb.set",path:t,value:n,actAs:{mode:"admin"},...as(e,r)})}async function aI(e,t,n,r){await Q(e.port,{t:"op",id:L(),method:"rtdb.update",path:t,values:n,actAs:{mode:"admin"},...as(e,r)})}async function cI(e,t,n){await Q(e.port,{t:"op",id:L(),method:"rtdb.remove",path:t,actAs:{mode:"admin"},...as(e,n)})}function lI(e,t,n,r,s){const i=un();return!os(e.port,i,{port:e.port,next:a=>n(a?.value??null),error:r},Ec({t:"sub",subId:i,target:{service:"rtdb",...as(e,s),path:jN(t)},actAs:{mode:"admin"}}))&&r&&queueMicrotask(()=>r(new Error("FIREBASE FATAL ERROR: Database has been deleted."))),()=>it(e.port,i)}const uI="/__pyric/diagnostics";function dI(e){const t=new URL(e);if(!["http:","https:","ws:","wss:"].includes(t.protocol))throw new Error("Unsupported diagnostic URL scheme.");const r=t.pathname==="/__pyric/sandbox"?t.pathname:"";return`${t.origin}${r}`}function fI(){if(globalThis.__pyricDiagnostics)return globalThis.__pyricDiagnostics;if(typeof location>"u"||!(location.protocol==="http:"||location.protocol==="https:"))return;const t={version:1,clientId:`browser-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,sequence:0,realm:typeof document>"u"?"service-worker":"page",pageOrigin:location.origin,events:[]};let n,r=!1;const s=()=>({...t,events:t.events.map(a=>({...a}))}),i=()=>{n!==void 0||r||(n=setTimeout(()=>{n=void 0,o.flush()},100))},o={getSnapshot:s,record(a){const l=a.endpoint?dI(a.endpoint):void 0;t.sequence+=1,t.events.push({...a,endpoint:l,at:Date.now()}),t.events=t.events.slice(-32),i()},async flush(){if(r)return;r=!0;const a=t.sequence,l=new AbortController,u=setTimeout(()=>l.abort(),2e3);try{await fetch(new URL(uI,location.href),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(s()),signal:l.signal,credentials:"same-origin",keepalive:!0})}catch{}finally{clearTimeout(u),r=!1,t.sequence>a&&i()}}};return globalThis.__pyricDiagnostics=o,globalThis.addEventListener("online",i),globalThis.addEventListener("pagehide",()=>{clearTimeout(n),n=void 0,o.flush()}),o}function hI(e){try{fI()?.record(e)}catch{}}function pI(e){const t=typeof e.bridgeVersion=="string"&&typeof e.peerConnected=="boolean"&&typeof e.clientSessionId=="string",r=[e.projectKey,e.serveVersion,e.sessionId,e.resumeToken,e.hostInstanceId].every(a=>a===void 0||typeof a=="string"),s=e.capabilities,i=s===void 0||Array.isArray(s)&&s.every(a=>typeof a=="string"),o=e.sandboxConnected===void 0||typeof e.sandboxConnected=="boolean";return t&&r&&i&&o}const Fr="Bridge response exceeds the 12 MiB encoded frame limit.",wa=4009,xr={code:"resource-exhausted",message:Fr},va=new TextEncoder;function Vm(e){const t=JSON.stringify(e);if(va.encode(t).byteLength<=Tr)return t;const r=yI(e),s=JSON.stringify(r);return va.encode(s).byteLength>Tr?mI(r):s}function mI(e){if(e.type!=="worker-message-result")return;const n=e.message;if(n.t!=="event")return;const s=n.events[0],i=n.events.at(-1);if(s===void 0||i===void 0)return;const a={...e,message:{...n,events:[{kind:"observation_gap",id:`observation-gap:${s.id}:${i.id}`,at:s.at,reason:"frame-limit",omittedCount:n.events.length,firstEventId:s.id,lastEventId:i.id}]}},l=JSON.stringify(a);if(va.encode(l).byteLength<=Tr)return l}function yI(e){switch(e.type){case"tool-result":return{type:"tool-result",id:e.id,ok:!1,error:xr};case"worker-message-result":return{...e,message:gI(e.message)};case"worker-res":return{type:"worker-res",id:e.id,clientSessionId:e.clientSessionId,ok:!1,error:xr};case"worker-snap":return{...e,value:{__error:xr}};default:return e}}function gI(e){switch(e.t){case"res":return{t:"res",id:e.id,clientSessionId:e.clientSessionId,ok:!1,error:xr};case"snap":return{...e,value:{__error:xr}};case"event":{const t=e.events.map(n=>{if(n.kind==="snapshot_delivery"){const s={...n};return delete s.sample,s}return n});return{...e,events:t}}default:return e}}const od={"rtdb.set":"resend","rtdb.setPriority":"resend","rtdb.setWithPriority":"resend","rtdb.update":"resend","rtdb.remove":"resend","rtdb.push":"resend","rtdb.get":"resend","rtdb.onDisconnectSet":"forget","rtdb.onDisconnectUpdate":"forget","rtdb.onDisconnectRemove":"forget","rtdb.onDisconnectCancel":"forget","rtdb.transactionCommit":"disconnect"};function bI(e){return Object.hasOwn(od,e)?od[e]:"fail"}function wI(e){return e.t==="op"?bI(e.method):"fail"}function vI(e,t,n,r){const s=[];for(const{id:i,message:o}of HC(e,a=>r(a)&&!im(e,a))){const a=wI(o);a==="resend"?s.push(i):a==="forget"?GC(i):a==="disconnect"?zu(i,new Error("disconnect")):zu(i,n)}t.holdAgain(KC(s))}function xI(e){const t=new URL(e);return t.protocol=t.protocol==="wss:"?"https:":"http:",t.origin}const go="The hosted sandbox connection was lost. Requests already sent may have completed; check state before retrying.",bo="The hosted sandbox connection is closed.",_I=new TextEncoder;function SI(e,t){const n=`socket-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,r=(M,ne)=>{hI({phase:M,connectionId:n,endpoint:e.url,code:ne})},s=new Set;let i="connecting",o,a,l=e.initialHostInstanceId,u=!1,d,h=!1,f=!1,p=0,m,g,b,w,x=0;const v=e.realm;let _=!1,S=()=>{};const k=new Promise(M=>{S=M}),N=()=>{_=!0,S()},O=M=>(v?.releaseTimer(M),M),D=M=>{v?.traffic(R,M)},R=Object.assign({},{onmessage:null,postMessage(M){if(i==="closed")throw new H("unavailable",bo);M.t==="appConfig"&&(d=M),D({sent:M});const ce=i==="attached";if(!ce&&M.t==="disconnect"){j.drop(),A({t:"res",id:M.id,ok:!0,value:void 0});return}if(!ce){if((M.t==="op"||M.t==="tool")&&!Qe.has(M.id))return;C({type:"worker-message",message:M}),j.hold(M);return}const fe=o;if(fe===void 0)throw new H("unavailable",bo);I(fe,{type:"worker-message",message:M})},start(){},withdrawSubscription(M){return j.forgetSubscription(M)},byteRouteSettled(){return _?void 0:k},observeConnection(M){return s.add(M),queueMicrotask(()=>{s.has(M)&&M(i==="attached")}),()=>{s.delete(M)}},close(){E(new H("unavailable",bo))}}),j=AR(R);function E(M){if(i==="closed")return;i="closed",$(),s.clear(),am(R),j.fail(M),Ur(R,M),AN(R,M),a=void 0,m=void 0,l=void 0,u=!1,d=void 0,R.restoreAuth=void 0,R.messagingVisibility=void 0,clearTimeout(g),clearTimeout(b),clearTimeout(w);const ge=o;o=void 0;const ce=ge?.readyState===WebSocket.OPEN;try{ce&&I(ge,{type:"worker-message",message:{t:"disconnect",id:L()}})}catch{}ge?.close(),R.onmessage=null,N(),D({closed:!0})}function $(){r(i),e.onConnection?.(i);const M=i==="attached";for(const ne of[...s])ne(M)}function C(M){const ne=Vm(M);if(ne===void 0)throw new H("resource-exhausted","Bridge request exceeds the 12 MiB encoded frame limit.");return ne}function I(M,ne){M.send(C(ne))}function A(M){R.onmessage?.(new MessageEvent("message",{data:M})),D({})}function P(M){if(i==="closed")return;const ge=new H("unavailable",M);E(ge),e.onError?.(ge)}function T(M){return o===M&&i!=="closed"}function W(M){if(!T(M))return;clearTimeout(g),clearTimeout(w),m??=performance.now(),i="interrupted",o=void 0,$();const ge=new H("unavailable",go);vI(R,j,ge,ve=>!j.holdsRequest(ve)&&!im(R,ve)),YC(R,ge,ve=>j.holdsSubscription({t:"unsub",subId:ve})),D({}),M.close();const ce=Math.min(5e3,250*2**p);p+=1;const Z=Math.random()*Math.min(250,ce/10);b=O(setTimeout(Se,Math.min(5e3,ce+Z)))}function U(M){const ne=qu-(performance.now()-x),ge=Math.max(0,Math.min(Yp,ne));w=O(setTimeout(()=>{if(!T(M))return;if(performance.now()-x>=qu){W(M);return}try{I(M,{type:"ping",id:L()})}catch{W(M);return}U(M)},ge))}async function V(M,ne){const ge=ne||p>0,ce=ve=>{if(!T(M))throw new H("unavailable",go);I(M,{type:"worker-message",message:ve})},Z=ve=>{j.holdsSubscription(ve)||ce(ve)};if(h){i="restoring",r(i),e.onConnection?.(i);const ve=d;if(ve!==void 0&&ce(u?{...ve,fromPriorHost:!0}:ve),await R.restoreAuth?.(wt=>Di(R,wt,ce)),!T(M))return;zC(R,Z),h=!1}clearTimeout(g),i="attached",f=!0,p=0,m=void 0,x=performance.now(),clearTimeout(w),U(M),ne&&(ce({t:"clock-subscribe"}),WC(R,Z)),ge&&VC(R,Z),j.flush(ce),$()}async function F(){const M=e.currentHostInstanceId;if(!(f&&M!==void 0))return l;try{return await M()??l}catch{return l}}function Se(){if(i==="closed")return;i="connecting",r("connecting");const ne=f?"interrupted":"connecting";e.onConnection?.(ne),m!==void 0&&performance.now()-m>=EC&&(a=void 0);const ce=a===void 0;let Z;try{Z=v?v.createSocket(e.url):new WebSocket(e.url)}catch(fe){throw r("socket-error"),fe}o=Z,g=O(setTimeout(()=>{if(!T(Z))return;r("timeout"),f||e.retryInitialConnection===!0?W(Z):P("Timed out connecting to the hosted sandbox.")},5e3)),Z.addEventListener("error",()=>{T(Z)&&r("socket-error")});let ve=l;Z.addEventListener("open",()=>{T(Z)&&(r("transport-open"),F().then(et=>{if(!T(Z))return;ve=et,et!==l&&(a=void 0),I(Z,{type:"attach",protocol:1,transport:"worker-port",resumeToken:a,hostInstanceId:et,clientInfo:{platform:v?.platform??"browser"}})}))}),Z.addEventListener("message",fe=>{if(!T(Z))return;if(_I.encode(fe.data).byteLength>Tr){Z.close(wa,Fr),P(Fr);return}let ut;try{ut=JSON.parse(fe.data)}catch{P("The hosted sandbox sent invalid JSON. Requests already sent may have completed; check state before retrying.");return}const ie=ut;if(!Qp(ie)){P("The hosted sandbox sent an invalid message. Requests already sent may have completed; check state before retrying.");return}switch(x=performance.now(),ie.type){case"attach-ack":{if(ie.protocol!==1){P("The hosted sandbox uses an unsupported bridge protocol. Expected version 1.");return}const Gn=ie.capabilities;if(!(Array.isArray(Gn)&&Gn.every(rl=>typeof rl=="string")&&Gn.includes(jC))){P("The selected host does not support browser worker ports. Upgrade @pyric/cli, restart with --hosted, and reload this page.");return}const yb=Gn.includes(kC),nl=e.sessionToken;if(yb&&nl!==void 0?R.byteRoute={baseUrl:xI(e.url),sessionToken:nl}:delete R.byteRoute,N(),v?.attached?.(ie),ie.projectKey!==e.projectKey){P("The selected hosted sandbox belongs to a different project.");return}if(!pI(ie)){P("The hosted sandbox sent a malformed attachment acknowledgment.");return}const ls=f,Ki=typeof ie.hostInstanceId=="string"&&ie.hostInstanceId.length>0,Gi=ls&&l!==void 0&&Ki&&ie.hostInstanceId!==l,gb=Ki&&ie.hostInstanceId===ve;Gi&&!gb&&(u=!0);const bb=ls&&!ce,wb=ie.resumeToken!==a;if(bb&&wb&&!Gi){P("The hosted session could not be resumed.");return}a=typeof ie.resumeToken=="string"&&ie.resumeToken.length>0?ie.resumeToken:void 0,l=Ki?ie.hostInstanceId:void 0,ls&&(Gi||ce)&&(h=!0),V(Z,ls).catch(()=>{T(Z)&&P("Could not restore the hosted app session.")});return}case"worker-message-result":{const Ge=ie.message;em(Ge)&&Ge.t==="res"&&Zp(Ge)&&Ge.ok===!1&&(Ge.error.code==="committed-but-not-durable"||Ge.error.code==="persistence-unhealthy")&&e.onError?.(new H(Ge.error.code,Ge.error.message)),A(Ge);return}}}),Z.addEventListener("close",fe=>{if(!T(Z))return;r("socket-close",fe.code),clearTimeout(g),f&&fe.code===CC&&(a=void 0),(f||e.retryInitialConnection===!0)&&fe.code!==1008?W(Z):P(go)})}const we={__kind:"client-db",port:R};return $i(R),Se(),we}function kI(){if(!(typeof document<"u"))return null;const n=document.querySelector('meta[name="pyric-sandbox-host"]');if(!(n?.getAttribute("content")==="node"))return null;const i=n.getAttribute("data-project-key");if(!(i!==null&&i.length>0))throw new Error("The hosted sandbox has no project identity. Restart the host and reload Studio.");return{url:`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}/__pyric/sandbox`,projectKey:i}}function jI(e){const t=new Set;let n={mode:"hosted",servedEpoch:null,runningEpoch:null,updateAvailable:!1,updating:!1,error:"Connecting to the hosted sandbox."};function r(o){n={...n,error:o};for(const a of t)a()}return{db:SI({...e,sessionToken:()=>Ai(location.origin),onConnection(o){switch(o){case"attached":r(null);return;case"connecting":r("Connecting to the hosted sandbox.");return;case"restoring":r("Restoring the hosted session.");return;case"interrupted":r("Hosted connection lost; reconnecting.");return;case"closed":r("Hosted connection closed. Repair the host and reload Studio.");return}},onError:o=>r(o.message)}),runtime:{getSnapshot:()=>n,subscribe(o){return t.add(o),()=>{t.delete(o)}},async update(){throw new Error("Restart the hosted sandbox and reload Studio to update it.")},dispose(){t.clear()}}}}function EI(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 o=null;const a=()=>i?(o??=iC({targetEpoch:i,retire:()=>e.retire?e.retire(i):rN(e.db,i),subscribeReload:e.subscribeReload??sN,preflight:e.preflight??(()=>sC(s)),commitGeneration:e.remember??(l=>rC(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}:{}}),o):null;return(e.readVersion??(()=>pN(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),a(),()=>{t.delete(l),t.size===0&&(o?.dispose(),o=null)}},async update(){const l=a();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(),o?.dispose(),o=null}}}function CI(e={}){const t=Gp(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:nC(t.worker.servedEpoch,n)}}const NI="/__pyric/sdk/worker.js";function RI(e){const t=new ah(ch);let n=!1;const r=new Set;let s=null;function i(){s||(s=lR(e,o=>{const a=!n;n=!0,a&&t.clear();for(const l of o)qp(l)&&t.clear(),t.append(l);for(const l of o)for(const u of r)u(l)}))}return{history:()=>t.snapshot(),subscribe:o=>(r.add(o),i(),()=>{r.delete(o),r.size===0&&s&&(s(),s=null,n=!1,t.clear())})}}function ad(e){let t=!1,n=null;const r=()=>{t=!0;const s=(async()=>e())(),i=()=>{t=!1;const o=n;n=null,o&&r().then(o.resolve,o.reject)};return s.then(i,i),s};return()=>{if(!t)return r();if(!n){let s,i;n={promise:new Promise((a,l)=>{s=a,i=l}),resolve:s,reject:i}}return n.promise}}function II(e=NI){const t=kI(),n=t!==null;if(!n&&typeof SharedWorker>"u")return null;tN("studio");const s=n?jI(t):null;let i;if(s!==null)i=s.db;else try{const m=CI({workerUrl:e});i=hN(m.url,m.name)}catch{return null}let a;try{a=typeof localStorage<"u"?localStorage:void 0}catch{a=void 0}const l=typeof document<"u",u=s?.runtime??EI({db:i,servedEpoch:Gp(l?document:void 0).worker.servedEpoch,storage:a});Ku({mode:"admin"});const d=yR({db:i,kind:"studio"}),h=RI(i),f=CR(i);let p=!1;return{db:i,runtime:u,dispose:async()=>{p||(p=!0,d.stop(),u.dispose(),await IN(i).catch(()=>{}))},presenceClientId:d.clientId,subscribePresence:m=>gR(i,m),instanceId:()=>mN(i),exportState:()=>yN(i),importState:m=>gN(i,m),saveState:m=>bN(i,m),listStates:()=>wN(i),restoreState:m=>vN(i,m),deleteState:m=>xN(i,m),feed:h,setLens:m=>Ku(m),getLens:()=>eN(),listRootCollections:ad(()=>eR(i)),listSubcollections:m=>tR(i,m),listDocuments:async m=>(await oR(i,m)).map(({path:g,phantom:b})=>({path:g,phantom:b})),readRtdbState:()=>iI(i),setRtdbValue:(m,g)=>oI(i,m,g),updateRtdbValue:(m,g)=>aI(i,m,g),deleteRtdbValue:m=>cI(i,m),subscribeRtdbValue:(m,g,b)=>lI(i,m,g,b),firestoreApi:{collection:FN,doc:BN,getDoc:YN,getDocs:XN,onSnapshot:nR,setDoc:rR,deleteDoc:sR,addDoc:iR,query:JN,limit:KN,startAfter:GN},auth:f,authApi:{listUsers:ad(()=>bR(f)),subscribeUsers:(m,g)=>h.subscribe(b=>{b.kind==="service_mutation"&&b.service==="auth"&&g()}),createUser:(m,g)=>wR(f,g),updateUser:(m,g,b)=>vR(f,g,b),deleteUser:(m,g)=>xR(f,g),clearUsers:()=>_R(f),getAuthProviderConfig:()=>SR(f),setAuthProviderConfig:(m,g,b)=>kR(f,g,b),subscribeAuthProviderConfig:(m,g)=>h.subscribe(b=>{b.kind==="service_mutation"&&b.op==="provider_config_update"&&g()})},storage:zR(i),storageApi:{ref:HR,listAll:KR,getMetadata:$m,getBlob:ZR,uploadBytes:nI,uploadBytesResumable:VR,deleteObject:qm},getSnapshot:()=>dR(i),resetAll:()=>fR(i)}}function Wm(e,t,n,r){const s={uid:e};n!==void 0&&(s.token={...n}),t!==void 0&&(s.tenant=t);const i=wi(s);if(i===null)throw new Error("projectIdentity requires a uid");const o={uid:i.uid,token:i.token??{}};return i.tenant!==void 0&&(o.tenant=i.tenant),o}const AI={transport:"in-process",order:80,tools:{auth_impersonate:"write",auth_reset:"write",auth_whoami:"read",auth_sessions:"read"}},OI={transport:"forwarded",order:70,tools:{auth_create_user:"write",auth_import_users:"write",auth_get_user:"read",auth_list_users:"read",auth_update_user:"write",auth_delete_user:"write",auth_set_claims:"write",auth_custom_token:"read"}},$I={transport:"in-process",order:90,tools:{sandbox_save_capture:"write",sandbox_list_captures:"read",sandbox_open_capture:"read",sandbox_rename_capture:"write",sandbox_delete_capture:"write"}},DI={transport:"in-process",order:60,tools:{pyric_can_i_use:"read"}},PI={transport:"forwarded",order:20,tools:{firestore_get_document:"read",firestore_list_documents:"read",firestore_create_document:"write",firestore_add_document:"write",firestore_update_document:"write",firestore_delete_document:"write",firestore_batch_write:"write",firestore_query_where:"read"}},TI={transport:"forwarded",order:30,tools:{sandbox_inspect:"read"}},MI={transport:"in-process",order:50,tools:{firestore_simulate_rules:"read",firestore_rules_stdlib_list:"read",firestore_rules_stdlib_get:"read",firestore_lint_rules:"read",firestore_resolve_modules:"read",rules_stdlib_list:"read",rules_stdlib_get:"read",rules_resolve_modules:"read"}},LI={transport:"forwarded",order:10,tools:{firestore_simulator_create:"write",firestore_simulator_execute:"write",firestore_simulator_read:"read",firestore_simulator_batch:"write",firestore_create_with_auto_id:"write",firestore_simulator_undo:"write",firestore_simulator_redo:"write",firestore_simulator_events:"read",firestore_simulator_transaction:"write"}},UI={transport:"forwarded",order:100,tools:{messaging_deliveries:"read"}},BI={transport:"forwarded",order:40,tools:{rtdb_simulate_access:"read",rtdb_crawl_structure:"read"}},FI=[{key:"auth-identity",...AI},{key:"auth-users",...OI},{key:"captures",...$I},{key:"conformance",...DI},{key:"firestore-data",...PI},{key:"firestore-inspect",...TI},{key:"firestore-rules",...MI},{key:"firestore-simulator",...LI},{key:"messaging-inspection",...UI},{key:"rtdb-inspection",...BI}];function wo(e,t){const n=new Set;for(const r of t){if(n.has(r))throw new Error(`duplicate tool family ${e} '${r}'`);n.add(r)}}function qI(e){return wo("key",e.map(t=>t.key)),wo("order",e.map(t=>t.order)),wo("tool name",e.flatMap(t=>Object.keys(t.tools))),[...e].sort((t,n)=>t.order-n.order)}const VI=qI(FI);function zm(e){return VI.filter(t=>t.transport===e)}function WI(e,t,n){const r=[...t].sort(),s=[...n].sort();if(r.length!==s.length||r.some((i,o)=>i!==s[o]))throw new Error(`${e} drifted from the default MCP contract
|
|
125
|
+
`||o==="\r")&&(t+=o),i++);continue}if(n){if(o==="\\"){t+=o,a!==""&&(t+=a,i++),i++;continue}o==='"'&&(n=!1),t+=o,i++;continue}if(o==='"'){n=!0,t+=o,i++;continue}if(o==="/"&&a==="/"){r=!0,i+=2;continue}if(o==="/"&&a==="*"){s=!0,i+=2;continue}t+=o,i++}return t}const uE={"\n":"\\n","\r":"\\r"," ":"\\t"};function dE(e){const t=uE[e];return t!==void 0?t:`\\u${e.charCodeAt(0).toString(16).padStart(4,"0")}`}function Pp(e){return e===" "||e===" "||e===`
|
|
126
|
+
`||e==="\r"}function fE(e,t){let n=t+1;for(;n<e.length&&Pp(e[n]);)n++;const r=e[n];return r==="}"||r==="]"}function hE(e){const t=lE(e);let n="",r=!1,s="",i=0;for(;i<t.length;){const o=t[i];if(r){if(o==="\\"){n+=t.slice(i,i+2),i+=2;continue}o==='"'&&(r=!1);const f=o.charCodeAt(0)<32;n+=f?dE(o):o,i++;continue}o==='"'&&(r=!0);const u=o===","&&(s!==""&&s!=="{"&&s!=="["&&s!==",")&&fE(t,i);u||(n+=o),!u&&!Pp(o)&&(s=o),i++}return n}const En=Symbol("pyric/firestore/followsCurrentUser"),wr=Symbol("pyric/firestore/authSessionScope");function dr(e){const t=e.keys().next().value;t!==void 0&&e.delete(t)}const $e=Object.freeze({readThreshold:5,readWindowMs:1e3,duplicateListenerThreshold:3,churnAttachThreshold:4,churnDetachThreshold:3,listenerWindowMs:2e3,maxEventsPerFingerprint:32,criticalReadThreshold:20,criticalDuplicateListenerThreshold:10,criticalChurnThreshold:12});function pE(e,t){for(const n of e.keys())t.delete(n)}function mE(e,t){const n=e.keys().next().value;return n===void 0?!1:(e.delete(n),t.delete(n),!0)}const Nu=1800;function yE(e){const t=new Map,n=new Map;let r=1;const s=(i,o)=>{const a=i.get(o);if(a!==void 0)return a;i.size>=e&&dr(i);const l=r++;return i.set(o,l),l};return{incidentFingerprint:i=>`activity:#${s(n,i)}`,readTarget:(i,o)=>fr(o===i?i:`${i}|query:#${s(t,o)}`),listenerTarget:i=>{try{const o=JSON.parse(i);if(o.kind==="query"){const a=typeof o.collection=="string"?o.collection:typeof o.path=="string"?o.path:"<unknown>";return fr(JSON.stringify({collection:a,kind:"query",query:`#${s(t,i)}`}))}if(o.kind==="doc"&&typeof o.path=="string")return fr(JSON.stringify({kind:"doc",path:o.path}))}catch{}return JSON.stringify({kind:"unknown",target:`#${s(t,i)}`})},clear:()=>{t.clear(),n.clear()}}}function fr(e){if(e.length<=Nu)return e;const t=`…#${gE(e)}`;return e.slice(0,Nu-t.length)+t}function gE(e){let t=2166136261,n=2654435769;for(let r=0;r<e.length;r+=1){const s=e.charCodeAt(r);t=Math.imul(t^s,16777619),n=Math.imul(n^s,2246822507)}return(t>>>0).toString(16).padStart(8,"0")+(n>>>0).toString(16).padStart(8,"0")}const gs=256,bE=64,wE=8192;function vE(e,t){const n=new Map,r=new Map,s=new Map,i=new Map,o=new Map,a=new Set,l=yE(gs);let u=0,d=!1;const h=_=>{try{t(_)}catch{}},f=(_,S)=>{!i.has(_)&&i.size>=bE&&dr(i),i.set(_,S)},p=(_,S)=>{const k=o.get(_);return k!==void 0?(o.delete(_),k==="critical"||k===S?(o.set(_,k),!1):(o.set(_,S),!0)):(o.size>=gs&&dr(o),o.set(_,S),!0)},m=()=>{n.clear(),r.clear(),s.clear(),o.clear(),a.clear(),u+=1},g=(_,S)=>{if(a.has(_.id))return;if(a.size>=wE&&dr(a),a.add(_.id),_.kind==="session_boundary"){m();return}const k=_E(_);if(!k){const $=xE(_,s);$&&b(_,$,S);return}const N=`segment:${u}|read:${k.method}:${k.targetFingerprint}|actor:${k.actorAuthFingerprint}`;let O=n.get(N);O||(n.size>=gs&&dr(n),O={events:[]},n.set(N,O)),O.events.push({id:_.id,at:_.at});const P=_.at-$e.readWindowMs;for(;O.events.length>0&&O.events[0].at<P;)O.events.shift();if(O.events.length>$e.maxEventsPerFingerprint&&O.events.splice(0,O.events.length-$e.maxEventsPerFingerprint),O.events.length<$e.readThreshold)return;const R=O.events[0],j=O.events[O.events.length-1],E=Object.freeze({fingerprint:l.incidentFingerprint(N),pattern:"repeated-read",confidence:"high",severity:Ru("repeated-read",O.events.length),service:"firestore",method:k.method,targetFingerprint:l.readTarget(k.path,k.targetFingerprint),actor:k.actor,authLens:oi(k.authLens),authUid:k.authUid,count:O.events.length,windowMs:j.at-R.at,usage:Object.freeze({unit:"document-reads",lowerBound:O.events.length,limitations:Object.freeze(["Observed sandbox reads are a lower bound; production cache and billing behavior are not measured."])}),evidenceEventIds:Object.freeze(O.events.slice(-8).map($=>$.id)),sourceAttribution:Iu(k.actor)});f(N,E),!S&&p(N,E.severity)&&h(E)},b=(_,S,k)=>{const N=Cr(S.target),O=l.listenerTarget(N),P=`segment:${u}|listener:${N}|actor:${S.actorAuthFingerprint}`;let R=r.get(P);if(!R){if(r.size>=gs){const I=r.keys().next().value;I!==void 0&&(pE(r.get(I).active,s),r.delete(I))}R={active:new Map,lifecycle:[],saturated:!1},r.set(P,R)}if(S.phase==="attach"){if(R.active.has(S.physicalListenerId))return;R.active.size>=$e.maxEventsPerFingerprint&&mE(R.active,s)&&(R.saturated=!0),R.active.set(S.physicalListenerId,{id:_.id,at:_.at}),s.set(S.physicalListenerId,{listenerId:S.listenerId,target:S.target,actor:S.actor,authLens:S.authLens,authUid:S.authUid,actorAuthFingerprint:S.actorAuthFingerprint})}else R.active.delete(S.physicalListenerId),s.delete(S.physicalListenerId);if(S.phase==="errored"||S.reauthorization)return;R.lifecycle.push({id:_.id,at:_.at,phase:S.phase});const j=_.at-$e.listenerWindowMs;for(;R.lifecycle.length>0&&R.lifecycle[0].at<j;)R.lifecycle.shift();R.lifecycle.length>$e.maxEventsPerFingerprint&&(R.lifecycle.splice(0,R.lifecycle.length-$e.maxEventsPerFingerprint),R.saturated=!0);const E=R.lifecycle.filter(I=>I.phase==="attach").length,$=R.lifecycle.length-E,C=Object.freeze({attaches:E,detaches:$,active:R.active.size,...R.saturated?{isLowerBound:!0}:{}});if(R.active.size>=$e.duplicateListenerThreshold){const I=[...R.active.values()],A=I[0],D=`${P}|duplicate`;w(D,"duplicate-listener",I.length,_.at-A.at,I.map(T=>T.id),k,S,O,C)}if(E>=$e.churnAttachThreshold&&$>=$e.churnDetachThreshold){const I=R.lifecycle[0],A=`${P}|churn`;w(A,"listener-churn",E,_.at-I.at,R.lifecycle.map(D=>D.id),k,S,O,C)}},w=(_,S,k,N,O,P,R,j,E)=>{const $=Object.freeze({fingerprint:l.incidentFingerprint(_),pattern:S,confidence:S==="duplicate-listener"&&k<$e.criticalDuplicateListenerThreshold?"medium":"high",severity:Ru(S,k),service:"firestore",method:"listen",targetFingerprint:fr(j),actor:R.actor,authLens:oi(R.authLens),authUid:R.authUid,count:k,windowMs:N,listenerBalance:E,usage:Object.freeze({unit:"listener-attaches",lowerBound:k,limitations:Object.freeze(["Listener lifecycle events count attachments; document deliveries and production billing are not measured.",...E.isLowerBound?["Listener retention saturated; reported counts are observed lower bounds."]:[]])}),evidenceEventIds:Object.freeze(O.slice(-8)),sourceAttribution:Iu(R.actor)});f(_,$),!P&&p(_,$.severity)&&h($)},x=e.history();for(const _ of x)g(_,!0);x.length>0&&m();const v=e.subscribe(_=>{d||g(_,!1)});return{report:()=>Object.freeze({incidents:Object.freeze([...i.values()])}),dispose:()=>{d||(d=!0,v(),n.clear(),r.clear(),s.clear(),o.clear(),a.clear(),l.clear())}}}function Ru(e,t){const n=e==="repeated-read"?$e.criticalReadThreshold:e==="duplicate-listener"?$e.criticalDuplicateListenerThreshold:$e.criticalChurnThreshold;return t>=n?"critical":"warning"}function xE(e,t){const n=e.kind==="listener_attach"||e.kind==="listener_detach"||e.kind==="listener_errored",r=e.kind==="listener"&&(e.phase==="attach"||e.phase==="detach"||e.phase==="errored");if(!n&&!r||(e.service??"firestore")!=="firestore"||e.planId)return null;let s;if(e.kind==="listener_attach")s="attach";else if(e.kind==="listener_detach")s="detach";else if(e.kind==="listener_errored")s="errored";else if(e.kind==="listener"&&(e.phase==="attach"||e.phase==="detach"||e.phase==="errored"))s=e.phase;else return null;const i=Xa(e),o=s!=="attach"?t.get(e.listenerId):void 0;if(!(o!==void 0)&&(i.source.kind!=="app"||i.authLens.mode==="admin"))return null;const l=e.activity?.listenerId??o?.listenerId??e.listenerId,u=o??{listenerId:l,target:e.target,actor:i.source,authLens:i.authLens,authUid:e.auth?.uid??null,actorAuthFingerprint:Cr({actor:i.source,authLens:oi(i.authLens),uid:e.auth?.uid??null})};return{phase:s,physicalListenerId:e.listenerId,reauthorization:e.activity?.listenerLifecycle==="reauthorize",...u}}function Iu(e){return e.kind==="app"&&e.journeyId!==void 0?`app ${e.journeyId}`:"app"}function oi(e){return e.mode==="as"?{mode:"as",uid:e.uid}:{mode:e.mode}}function _E(e){if(e.kind!=="request"&&e.kind!=="operation"||(e.kind==="request"?e.service??"firestore":e.service)!=="firestore"||e.method!=="get"&&e.method!=="list"||e.origin!=="user"||e.result!=="allow"||e.groupId||e.groupKind||e.activity?.groupKind||e.planId||e.detail?.admin===!0)return null;const n=Xa(e);if(n.source.kind!=="app"||n.authLens.mode==="admin")return null;const r=e.path??"<unknown>",s=e.kind==="request"?e.detail?.activityQuery??e.detail?.query:e.request?.query,i=s===void 0?void 0:Cr(s);return{method:e.method,path:r,targetFingerprint:i===void 0?r:`${r}|query:${i}`,actorAuthFingerprint:Cr({actor:n.source,authLens:oi(n.authLens),uid:e.auth?.uid??null}),actor:n.source,authLens:n.authLens,authUid:e.auth?.uid??null}}const Dp=new WeakMap;function SE(e){return Dp.get(e)?.raw??e}const kE=new WeakMap,Au=new WeakMap;function ai(e,t,n,r,s){Dp.set(e,{target:n,path:t.ref.path,kind:s,converter:r,raw:t})}function Ou(e){return typeof e.exists=="function"?e.exists():e.exists===!0}function jE(e,t){const n=Fo(e),r=Fo(t);return n.isStructurallyEqual?.(r)??n===r}function EE(e,t,n,r){const s=e,i=(Au.get(s)??[]).filter(a=>a.query.deref()!==void 0),o=i.find(a=>{const l=a.query.deref();return l!==void 0&&jE(l,t)});if(o!==void 0){const a=CE(o.docs,n)&&o.metadata.fromCache===r.fromCache&&o.metadata.hasPendingWrites===r.hasPendingWrites;return o.docs=n,o.metadata=r,a?"settled":"initial"}return i.push({query:new WeakRef(t),docs:n,metadata:r}),Au.set(s,i),"initial"}function CE(e,t){return e.length===t.length&&e.every((n,r)=>{const s=t[r];return n.path===s.path&&Dw(n.data,s.data)})}function ia(e,t,n,r,s){const i=t,o=d=>({path:d.ref?.path??"",data:tc(d.data?.(),n)}),a=Object.freeze((i.docs??[]).map(o)),l=Object.freeze((i.docChanges?.()??[]).map(d=>({...o(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});kE.set(e,{target:n,query:r,converter:Yr(r)??null,source:s,...s==="read"?{readPhase:EE(n,r,a,u)}:{},metadata:u,docs:a,changes:l})}function ci(e,t){const n=e;aa(n);const r=n.data.bind(e),s=t!==void 0;let i;if(s&&(i={create:o=>st({[zs]:t},o)}),Object.defineProperty(n,"data",{value:()=>dh(r(),i),configurable:!0,writable:!0}),s){const o=n.ref?.path;o!==void 0&&o.length>0&&Object.defineProperty(n,"metadata",{value:Et(t).snapshotMetadata(o),configurable:!0})}return e}function Tp(e,t,n,r){const s=st({[zs]:n},e.ref.path),i=s.withConverter(t),o={create:l=>st({[zs]:n},l)},a={id:e.id,ref:i,exists:()=>Ou(e),metadata:Et(n).snapshotMetadata(e.ref.path),data:()=>{if(!Ou(e))return;const u=dh(e.data(),o),d={id:e.id,ref:s,exists:()=>!0,metadata:Et(n).snapshotMetadata(e.ref.path),data:()=>u};return t.fromFirestore(d)}};return rn(a,n),rn(e.ref,n),oa(e.ref,n),ai(a,e,n,t,r),a}function $u(e,t,n,r){const s=e,i=s.ref?.path??"",o=s.data.bind(e),a=st({[zs]:n},i),l=a.withConverter(t);Object.defineProperty(s,"ref",{value:l,configurable:!0,writable:!0}),Object.defineProperty(s,"data",{value:()=>{const d=o();if(d===void 0)return;const f={id:s.id,ref:a,exists:()=>!0,metadata:Et(n).snapshotMetadata(i),data:()=>d};return t.fromFirestore(f)},configurable:!0,writable:!0});const u={ref:{path:i},exists:s.exists,data:o};ai(e,u,n,t,r)}function Ai(e,t){if(!e||typeof e!="object")return e;rn(e,t);const n=e;if(n.ref&&(rn(n.ref,t),oa(n.ref,t)),aa(n),Array.isArray(n.docs))for(const r of n.docs)r&&(rn(r,t),ai(r,r,t,null,"query-child")),r?.ref&&(rn(r.ref,t),oa(r.ref,t)),r&&aa(r);else n.ref&&ai(e,e,t,null,"document");return e}function oa(e,t){if(typeof e.path!="string"||e.path.length===0)return;const n=e.path;try{const r=cl.get(e),s=r??ec(t).doc(n);r===void 0&&cl.set(e,s),ih(e,n,t,s),t.kind==="sandbox-live"&&fh.set(s,i=>i.doc(n))}catch{}}function aa(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{}}function Mp(e){return NE(e,"getDoc")}async function NE(e,t){return RE(e,nc(Bn(e),e,t,"operation"))}async function RE(e,t){const n=Bn(e),r=Et(n);r.markStarted();try{const s=Yr(e),i=await hh(()=>Mw(n,e).get());return r.cachePath(e.path),s?$n(t,Tp(i,s,n,"document")):(Ai(i,n),$n(t,ci(i,n)))}catch(s){throw t.fail(),s}}function li(e){return IE(e,"getDocs")}async function IE(e,t){return AE(e,nc(Bn(e),e,t,"operation"))}async function AE(e,t){const n=Bn(e),r=Et(n);r.markStarted();try{const s=Yr(e),i=await hh(()=>Tw(n,e).get());if(r.cacheQuery(e),s){const a=s,l=i.docs.map(d=>Tp(d,a,n,"query-child")),u=rn({size:l.length,empty:l.length===0,docs:l,forEach:oh(l),metadata:r.querySnapshotMetadata()},n);for(const d of l)r.cachePath(d.ref.path);return ia(u,i,n,e,"read"),$n(t,u)}Ai(i,n);const o=i.docs;for(const a of o)r.cachePath(a.ref.path),ci(a,n);return Object.defineProperty(i,"metadata",{value:r.querySnapshotMetadata(),configurable:!0}),ia(i,i,n,e,"read"),$n(t,i)}catch(s){throw t.fail(),s}}function OE(e){if(e===null||typeof e!="object")return null;const t=e;return typeof t.path=="string"&&t.path.length>0?t.path:typeof t.collectionPath=="string"&&t.collectionPath.length>0?t.collectionPath:null}function Pu(e){if(e!==null&&typeof e=="object"){const t=e.snapshotConstraints;if(typeof t=="function")return t.call(e)}}function $E(e){if(e!==null&&typeof e=="object"){const t=e.snapshotScope;if(typeof t=="function")return t.call(e)}}function Du(e){if(e===null||typeof e!="object")return!1;const t=e;return typeof t.path=="string"&&t.path.length>0&&t.parent!==void 0&&t.parent!==null}function Lp(e,t,n,r,s){let i={},o,a;if(typeof t=="object"&&t!==null&&typeof t.next!="function"&&typeof t.error!="function"&&typeof t.complete!="function"){if(i=t,typeof n=="function")o=n,a=r;else if(typeof n=="object"&&n!==null){const v=n;o=v.next,a=v.error}}else if(typeof t=="function")o=t,a=n;else if(typeof t=="object"&&t!==null){const v=t;o=v.next,a=v.error}if(!o&&!a)throw new TypeError("onSnapshot: missing handler. Provide a callback, or an observer with a `next` and/or `error` method.");const u=Bw(e);if(u){if(i[En]===!0)throw new Qf("unimplemented","onSnapshot: live (follows-current-user) listeners are not supported on a remote sandbox — remote listeners are frozen to the identity of the context that created the ref.");return u(i,o,a)}const d=PE(e),h=Jr(d.sandbox);let f;const p=Du(e)?void 0:$E(e);if(Du(e))f={kind:"doc",path:e.path};else if(p?.kind==="collection-group")f={kind:"query",collection:p.collectionId,collectionGroup:!0,constraints:Pu(e)};else{const v=OE(e);if(v===null)throw new TypeError("onSnapshot: could not determine the collection path for this Query. Pass a CollectionReference or a Query produced by `.where`/`.orderBy`/`.limit` on a CollectionReference obtained from `getFirestore(ctx)`.");const _=Pu(e);f={kind:"query",collection:v,constraints:_}}const m=i[En]===!0,g=i[wr],b=e[Fw]===!0;if(En in i){const{[En]:v,..._}=i;i=_}if(wr in i){const{[wr]:v,..._}=i;i=_}const w=()=>h.addSnapshotListener(f,o??(()=>{}),i,d.auth,a?v=>a(TE(v,d)):void 0,m,b,g);return typeof d.sandbox.runWithProvenance=="function"?d.sandbox.runWithProvenance(Uo(d.operationContext),w):w()}function PE(e){if(e===null||typeof e!="object")throw new TypeError("onSnapshot: reference must be a DocumentReference or Query.");const t=e[Vw];if(!t)throw new TypeError("onSnapshot: reference was not produced by a sandbox context — pass a ref obtained from `getFirestore(ctx)`.");return t}Lw(Lp);Uw(Lp);function DE(e){return typeof e=="object"&&e!==null&&"code"in e&&cw.some(t=>t===e.code)&&"message"in e&&typeof e.message=="string"}function TE(e,t){if(!DE(e))return e;const n=qw(new aw(e),{...t,auth:e.request?e.request.auth:t.auth});if(n instanceof Error)for(const r of["request","resource","query","rule","queryProof"])e[r]!==void 0&&Object.assign(n,{[r]:e[r]});return n}function Up(e){return typeof e=="string"?e:e._internalPath.segments.join(".")}function ui(e,...t){const n=Bn(e),r=Yr(e),s=Ww(e);let i,o;try{i=t.map(u=>u.prepareSandbox?.(n)??u)}catch(u){throw Vo(u)}const a=u=>{let d=s(u);for(const h of i)d=h.applySandbox(d);return d};try{o=a(ec(n))}catch(u){throw Vo(u)}const l=zw(Hw(o,n,u=>a(u)));return r?Kw(l,r):l}function ME(e,t,n){return Bp(Up(e),t,n,!1)}function Bp(e,t,n,r){return{type:"where",applySandbox:i=>i.where(e,t,n),prepareSandbox:r?void 0:i=>{const o=tc(n,i,t==="in"||t==="not-in");return Bp(e,t,o.executionValue,!0)},_sandboxFilter:{kind:"where",field:e,op:t,value:n}}}function Tu(e,t){const n=Up(e);return{type:"orderBy",applySandbox:r=>r.orderBy(n,t)}}function di(e){return{type:"limit",applySandbox:t=>t.limit(e)}}function LE(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 UE(...e){return LE(e)?Fp(e[0],!1,!0):Vp(e,!1,!0)}function Fp(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=SE(e),i=s.data(),o=Object.freeze({id:s.id,ref:s.ref,exists:i!==void 0,data:()=>i});return Fp(o,t,n,!0)}}}function Vp(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=>Vp(e.map(i=>tc(i,s).executionValue),t,n,!0)}}function BE(e,t,n,r){const s=Bn(e);Et(s).markStarted();const i=VE(s,e),o=typeof t=="object"&&t!==null&&!jc(t)?t:void 0,a=nc(s,e,"onSnapshot","subscription",o),l=qE(t,n,r,s,e,a),u=WE(l,s);let d;try{d=Kr.registering(a,()=>u.length===3?i.onSnapshot(u[0],u[1],u[2]):u.length===2?i.onSnapshot(u[0],u[1]):i.onSnapshot(u[0]))}catch(g){throw a.fail(),g}if(!s.own)return()=>{a.close(),d()};let h=!1;const f=()=>{h||(h=!0,a.close(),d())},p=()=>{h||(a.fail(),f(),FE(u)?.(new H("aborted","The operation was aborted.")))},m=s.own(p);return()=>{m(),f()}}function FE(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 VE(e,t){const n=Fo(t);if(e.kind==="sandbox")return n;const r=fh.get(n);if(!r)throw new TypeError("pyric/firestore: live ref missing rebuild closure for onSnapshot.");return r(ec(e))}function jc(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 qE(e,t,n,r,s,i){if(typeof e=="object"&&e!==null&&!jc(e)){const a=t;return typeof a=="function"?[e,Mu(a,r,s,i),la(n??ca,i)]:a&&typeof a=="object"?[e,Lu(a,r,s,i)]:[e]}return typeof e=="function"?[Mu(e,r,s,i),la(t??ca,i)]:e&&typeof e=="object"?[Lu(e,r,s,i)]:[e]}function WE(e,t){if(t.kind!=="sandbox-live")return e;const n=e[0];return typeof n=="object"&&n!==null&&!jc(n)?[{...n,[En]:!0,...t.authScope?{[wr]:t.authScope}:{}},...e.slice(1)]:[{[En]:!0,...t.authScope?{[wr]:t.authScope}:{}},...e]}function qp(e,t,n){if(!e||typeof e!="object")return e;const r=e,s=Yr(n)??null,i=s!==null;if(typeof r.data=="function"&&(ci(e,t),i&&$u(e,s,t,"document")),Array.isArray(r.docs)){for(const o of r.docs)ci(o,t),i&&$u(o,s,t,"query-child");ia(e,e,t,n,"listener")}return e}function ca(e){console.error("pyric/firestore: Uncaught Error in snapshot listener:",e)}function Mu(e,t,n,r){return s=>{const i=qp(Ai(s,t),t,n);r.delivered(i),e(i),Et(t).notifySnapshotDelivered()}}function Lu(e,t,n,r){return{...e,next:e.next?s=>{const i=qp(Ai(s,t),t,n);r.delivered(i),e.next(i),Et(t).notifySnapshotDelivered()}:void 0,error:la(e.error??ca,r)}}function la(e,t){return n=>{t.fail(),e(Vo(n))}}const At={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"},tenant:{type:"string",description:"Tenant id, visible to rules as request.auth.token.firebase.tenant."},claims:{type:"object",description:"Custom claims forwarded to the rule context (request.auth.token)."}},required:["uid"]}]},zE={type:"object",properties:{field:{type:"string"},op:{type:"string",enum:[...Gw]},value:{}},required:["field","op","value"]};function HE(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:At},required:["path"]},async execute(n){const r=n,s=await t(r.as),i=st(s,r.path),o=await Mp(i),a=typeof o.exists=="function"?o.exists():o.exists;return{ok:!0,summary:a?`Got ${r.path}`:`No document at ${r.path}`,data:{exists:a,data:a?o.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:At},required:["collection"]},async execute(n){const r=n,s=await t(r.as),i=pr(s,r.collection),o=[];r.orderBy&&o.push(Tu(r.orderBy)),r.limit&&o.push(di(r.limit));const a=await li(ui(i,...o));return{ok:!0,summary:`${a.size} docs in ${r.collection}`,data:{docs:a.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:At},required:["path","data"]},async execute(n){const r=n,s=await t(r.as);return await Hs(st(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:At},required:["collection","data"]},async execute(n){const r=n,s=await t(r.as),i=await ph(pr(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:At},required:["path","data"]},async execute(n){const r=n,s=await t(r.as);return await ll(st(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:At},required:["path"]},async execute(n){const r=n,s=await t(r.as);return await qo(st(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:At},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 o=st(s,i.path);i.op==="set"?await Hs(o,i.data??{}):i.op==="update"?await ll(o,i.data??{}):await qo(o)}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:zE,minItems:1},orderBy:{type:"string"},limit:{type:"number"},as:At},required:["collection","where"]},async execute(n){const r=n,s=await t(r.as),i=pr(s,r.collection),o=r.where.map(l=>ME(l.field,l.op,l.value));r.orderBy&&o.push(Tu(r.orderBy)),r.limit&&o.push(di(r.limit));const a=await li(ui(i,...o));return{ok:!0,summary:`${a.size} matches in ${r.collection}`,data:{docs:a.docs.map(l=>({id:l.id,data:l.data()}))}}}}]}function KE(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=lw(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 GE="modulepreload",JE=function(e){return"/__pyric/ui/"+e},Uu={},Wp=function(t,n,r){let s=Promise.resolve();if(n&&n.length>0){let o=function(u){return Promise.all(u.map(d=>Promise.resolve(d).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const a=document.querySelector("meta[property=csp-nonce]"),l=a?.nonce||a?.getAttribute("nonce");s=o(n.map(u=>{if(u=JE(u),u in Uu)return;Uu[u]=!0;const d=u.endsWith(".css"),h=d?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${h}`))return;const f=document.createElement("link");if(f.rel=d?"stylesheet":GE,d||(f.as="script"),f.crossOrigin="",f.href=u,l&&f.setAttribute("nonce",l),document.head.appendChild(f),d)return new Promise((p,m)=>{f.addEventListener("load",p),f.addEventListener("error",()=>m(new Error(`Unable to preload CSS for ${u}`)))})}))}function i(o){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=o,window.dispatchEvent(a),!a.defaultPrevented)throw o}return s.then(o=>{for(const a of o||[])a.status==="rejected"&&i(a.reason);return t().catch(i)})};function zp(e){return e.kind==="session_boundary"&&e.phase==="reset"}function YE(e,t){return zp(t)?[t]:[...e,t]}const Hp=y.createContext(null),Kp={status:"disabled",handles:null,events:[]};function QE({children:e}){return c.jsx(Hp.Provider,{value:Kp,children:e})}function Kt(){return y.useContext(Hp)??Kp}function $t(e,t){return`${e.replace(/\/$/,"")}${t}`}const fo=new Map;let ho=null;function XE(e){return e||(ho||(ho=`studio-writer-${Math.random().toString(36).slice(2)}`),ho)}function Gp(e){return{token:e?.token,writerId:e?.writerId}}async function Oi(e,t){if(t)return t;const n=e.replace(/\/$/,""),r=fo.get(n);if(r)return r;const s=fetch($t(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||fo.delete(n),i));return fo.set(n,s),s}async function Jp(e,t,n=!1){const r={},{token:s,writerId:i}=Gp(t);n&&(r["x-pyric-writer"]=XE(i));const o=await Oi(e,s);return o&&(r["x-pyric-session-token"]=o),r}function Yp(e,t){const n=e,{token:r}=Gp(t),s=(i=!1)=>Jp(n,t,i);return{async read(i){const o=await s(!1),a=await fetch($t(n,`/__pyric/workspace?path=${encodeURIComponent(i)}`),{headers:o});if(a.status===404)return null;if(!a.ok)throw new Error(`workspace.read(${i}) → ${a.status}`);return a.text()},async write(i,o){const a=await s(!0),l=await fetch($t(n,`/__pyric/workspace?path=${encodeURIComponent(i)}`),{method:"PUT",headers:a,body:o});if(!l.ok)throw new Error(`workspace.write(${i}) → ${l.status}`)},async list(i){const o=await s(!1),a=i?`?dir=${encodeURIComponent(i)}`:"",l=await fetch($t(n,`/__pyric/workspace/list${a}`),{headers:o});if(!l.ok)throw new Error(`workspace.list(${i??""}) → ${l.status}`);return await l.json()},async branches(){const i=await s(!1),o=await fetch($t(n,"/__pyric/workspace/branches"),{headers:i});if(!o.ok)throw new Error(`workspace.branches() → ${o.status}`);return await o.json()},async remove(i){const o=await s(!0),a=await fetch($t(n,`/__pyric/workspace?path=${encodeURIComponent(i)}`),{method:"DELETE",headers:o});if(!a.ok)throw new Error(`workspace.remove(${i}) → ${a.status}`)},watch(i){let o=null,a=!1;const l=u=>{try{i(JSON.parse(u.data))}catch{}};return Oi(n,r).then(u=>{if(a)return;const d=u?$t(n,`/__pyric/workspace/watch?token=${encodeURIComponent(u)}`):$t(n,"/__pyric/workspace/watch");o=new EventSource(d),o.addEventListener("change",l)}),()=>{a=!0,o&&(o.removeEventListener("change",l),o.close())}}}}function tr(e,t){return`${e.replace(/\/$/,"")}${t}`}function ZE(e,t){const n=e,r=(s=!1)=>Jp(n,t,s);return{async list(){const s=await r(!1),i=await fetch(tr(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),o=await fetch(tr(n,`/__pyric/projects/${encodeURIComponent(s)}`),{headers:i});if(!o.ok)throw new Error(`projects.open(${s}) → ${o.status}`);return{meta:await o.json(),workspace:Yp(n,t)}},async create(s){const o={...await r(!0),"content-type":"application/json"},a=await fetch(tr(n,"/__pyric/projects"),{method:"POST",headers:o,body:JSON.stringify(s)});if(!a.ok)throw new Error(`projects.create() → ${a.status}`);return await a.json()},async update(s,i){const a={...await r(!0),"content-type":"application/json"},l=await fetch(tr(n,`/__pyric/projects/${encodeURIComponent(s)}`),{method:"PATCH",headers:a,body:JSON.stringify(i)});if(!l.ok)throw new Error(`projects.update(${s}) → ${l.status}`)},async remove(s){const i=await r(!0),o=await fetch(tr(n,`/__pyric/projects/${encodeURIComponent(s)}`),{method:"DELETE",headers:i});if(!o.ok)throw new Error(`projects.remove(${s}) → ${o.status}`)}}}function eC(e,t){return`${e.replace(/\/$/,"")}${t}`}function po(e){return/auth/i.test(e)?"auth":"firestore"}function tC(e){const t=e,n=`studio-${Math.random().toString(36).slice(2)}`,r=async()=>{const u=await Oi(t);return u!==null?{"x-pyric-session-token":u}:{}},s=async()=>({"content-type":"application/json","x-pyric-writer":n,...await r()}),i=new Map,o=u=>eC(t,`/__pyric/state?section=${po(u)}`),a=async u=>{const d=po(u),h=i.get(d);if(h)return h;const f=await fetch(o(u),{headers:await r()});let p=new Map;if(f.ok){const m=await f.text();m&&m!=="null"&&(p=uw(m))}else if(f.status!==404)throw new Error(`persistence.read(${u}) → ${f.status}`);return i.set(d,p),p},l=async(u,d)=>{const h=await fetch(o(u),{method:"POST",headers:await s(),body:dw(d)});if(h.status===423)throw new Error("persistence.write blocked, another tab holds the persist writer lock");if(!h.ok)throw new Error(`persistence.write(${u}) → ${h.status}`)};return{async getRecord(u,d){return(await a(u)).get(d)??null},async listRecords(u){return[...(await a(u)).keys()]},async putRecords(u,d){const h=await a(u);for(const[f,p]of d)h.set(f,p);await l(u,h)},async deleteRecords(u,d){const h=await a(u);for(const f of d)h.delete(f);await l(u,h)},async clear(u){i.set(po(u),new Map);const d=await fetch(o(u),{method:"POST",headers:await s(),body:"null"});if(!d.ok&&d.status!==423)throw new Error(`persistence.clear(${u}) → ${d.status}`)}}}const nC="local";function rC(){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 o of e.keys())s&&!o.startsWith(s)||i.push({path:o,kind:"file"});return i},async remove(r){e.delete(r)&&n({path:r,type:"delete"})},async branches(){return[]},watch(r){return t.add(r),()=>t.delete(r)}}}function sC(){const e=rC();let t={id:nC,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(){}}}var mo={};const iC="/__pyric/sdk/worker.js",Pt="pyric-shared-worker",oC="/__pyric/ui/studio";function aC(e,t){if(typeof process<"u"&&mo){const s=mo.NEXT_PUBLIC_PYRIC_STUDIO_URL||mo.PYRIC_STUDIO_URL;if(typeof s=="string"&&s.trim().length>0)return s.trim()}const n=globalThis.__PYRIC_WORKER_INIT__;if(typeof n?.studioUrl=="string"&&n.studioUrl.trim().length>0)return n.studioUrl.trim();if(typeof n?.bridgeUrl=="string"&&n.bridgeUrl.trim().length>0)try{const s=t?.href||(typeof location<"u"?location.href:""),i=new URL(n.bridgeUrl,s||"http://localhost"),o=t?.host||(typeof location<"u"?location.host:"")||(s?new URL(s).host:"");if(i.host&&(!o||i.host!==o))return`${i.protocol==="wss:"||i.protocol==="https:"?"https:":"http:"}//${i.host}/__pyric/ui/studio`}catch{}const r=e?.querySelector('meta[name="pyric-studio-url"]')?.getAttribute("content")?.trim()||e?.querySelector('meta[name="pyric-runtime-chip"]')?.getAttribute("data-studio-url")?.trim();return r||oC}function Qp(e=typeof document>"u"?void 0:document,t=typeof location>"u"?void 0:location){const n=e?.querySelector('meta[name="pyric-worker-v"]')?.getAttribute("content")?.trim()||null;return{studioUrl:aC(e,t),worker:{url:iC,name:Pt,servedEpoch:n}}}const fi="pyric:worker-generation",nr="pyric:worker-generation-probe";function cC(e,t){const n=e&&/^[a-f0-9]{16}$/.test(e)?e:null;if(!t)return n?`${Pt}:${n}`:Pt;try{const r=t.getItem(fi);return r&&/^[a-f0-9]{16}$/.test(r)?`${Pt}:${r}`:n?(t.setItem(fi,n),`${Pt}:${n}`):Pt}catch{return n?`${Pt}:${n}`:Pt}}function lC(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(fi,e),t.getItem(fi)!==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 uC(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(nr);if(e.setItem(nr,"ok"),e.getItem(nr)!=="ok")throw new Error("the worker generation probe could not be read back");t===null?e.removeItem(nr):e.setItem(nr,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 dC(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}}const fC=Symbol.for("pyric.ai-evidence"),hC=globalThis,pC=hC[fC]??=new WeakMap;function Bu(e,t){return pC.set(e,Object.freeze({...t})),e}function mC(){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 Xp=new WeakMap;let ua;function yC(e,t,n=mC()){const r=e.name,s=n===t?void 0:{},i=new Map,o=new Set,a={app:e,sandbox:t,session:n,services:i,cleanups:o,assertAlive(){if(a.deleted)throw new H("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;a.assertAlive();const h=u();return i.set(l,h),h},onDelete(l){return a.deleted?(l(),()=>{}):(o.add(l),()=>o.delete(l))},deleted:!1};return Xp.set(e,a),a}function gC(e){ua=e}Jw({resolve(e,t){const n=typeof e=="object"&&e!==null?Xp.get(e):void 0;if(n)return n},defaultApp(){if(!ua)throw new TypeError("No default sandbox app registry is installed - import and initialize pyric/app before calling a service factory without an app.");return ua()}});const bC="[DEFAULT]",wC=new Map;function vC(e,t){return new H(`app/${e}`,`Firebase: ${t} (app/${e}).`)}function xC(e){return vC("no-app",`No Firebase App '${e}' has been created - call initializeApp() first`)}function _C(e=bC){const t=wC.get(e);if(!t)throw xC(e);return t.app}gC(_C);const SC={mode:"wall",fixedAt:0,offsetMs:0};let hr=SC;function kC(e){hr=e}function jC(){return hr.mode==="fixed"?hr.fixedAt:hr.mode==="offset"?Date.now()+hr.offsetMs:Date.now()}const Fu=5174,Mr=12*1024*1024,EC=256,CC=24*1024*1024,Vu="/sandbox",NC=4001,RC="worker-relay",IC="storage-byte-route",AC="worker-port",OC=6e4,Zp=15e3,qu=3*Zp,$C=4004;function em(e){if(e===null||typeof e!="object")return!1;const n=e.type;return n==="hello"||n==="hello-ack"||n==="attach"||n==="attach-ack"||n==="tool-call"||n==="tool-result"||n==="worker-op"||n==="worker-res"||n==="worker-sub"||n==="worker-unsub"||n==="worker-snap"||n==="worker-client-disconnect"||n==="worker-client-interrupted"||n==="consumer-presence"||n==="remote-set-lens"||n==="remote-set-lens-ack"||n==="worker-event"||n==="worker-message"||n==="worker-message-result"||n==="ping"||n==="pong"}function da(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=da(t);if(n)return n}return null}for(const t of Object.values(e)){const n=da(t);if(n)return n}return null}function Wu(e,t){const n=da(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}const PC=new TextEncoder;function DC(){let e=0,t=0;return{reserve(n){if(e>=EC)return{accepted:!1,error:{code:"resource-exhausted",message:"This client already has 256 pending operations."}};let s;try{s=PC.encode(JSON.stringify(n)).byteLength}catch{return{accepted:!1,error:{code:"invalid-argument",message:"The operation must have a JSON-serializable encoding."}}}return t+s>CC?{accepted:!1,error:{code:"resource-exhausted",message:"This client exceeds the 24 MiB queued operation byte limit."}}:(e+=1,t+=s,{accepted:!0,release(){e-=1,t-=s}})}}}function tm(e){if(e===null||typeof e!="object")return;const t=e,n=t.target,s=typeof n=="object"&&n!==null?n.instance:t.instance;return typeof s=="string"&&s.length>0?s:void 0}function On(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function TC(e){return On(e)?(e.mode==="wall"||e.mode==="fixed"||e.mode==="offset")&&Number.isFinite(e.fixedAt)&&Number.isFinite(e.offsetMs):!1}function nm(e){if(e.ok===!0)return!0;const n=e.error,r=On(n);return e.ok===!1&&r&&typeof n.code=="string"&&typeof n.message=="string"}function rm(e){if(!On(e)||e.clientSessionId!==void 0&&typeof e.clientSessionId!="string")return!1;switch(e.t){case"res":return typeof e.id=="string";case"snap":return typeof e.subId=="string";case"event":return typeof e.subId=="string"&&Array.isArray(e.events);case"runtime-reload":return typeof e.epoch=="string";case"clock":return TC(e.state);default:return!1}}function zu(e){const t={code:"unavailable",message:"The sandbox sent a malformed subscription reply."};if(!Object.hasOwn(e,"value"))return t;const r=e.value;if(!(On(r)&&Object.hasOwn(r,"__error")))return;const o=r.__error;if(!On(o))return t;const u=o.code,d=o.message;if(typeof u!="string"||typeof d!="string")return t;const f=o.aiEvidence,p=On(f),m=o.codeless===!0?{codeless:!0}:{};return{code:u,...m,message:d,denialContext:o.denialContext,aiEnvelope:o.aiEnvelope,aiEvidence:p?f:void 0,envelope:o.envelope}}const Lr=new WeakMap;function sm(e){let t=Lr.get(e);return t===void 0&&(t={entries:[],closed:!1},Lr.set(e,t)),t}function MC(){return new H("app/app-deleted","Firebase App was deleted")}function im(e,t){try{e.postMessage(t.message)}catch(n){t.failed?.(n)}}function LC(e,t){for(;t.entries.length>0;){const n=t.entries[0],r=n.frames.splice(0);for(const i of r)im(e,i);if(!n.released)return;t.entries.shift()}}const UC=()=>performance.now();let BC=UC;function Ec(){return BC()}function $i(e,t,n){const r=Lr.get(e);if(!(r!==void 0&&r.entries.length>0)){e.postMessage(t);return}r.entries.push({frames:[{message:t,failed:n}],released:!0})}function om(e){const t=sm(e),n={frames:[],released:!1};return t.closed||t.entries.push(n),{issuedAt:Ec(),send(s,i){const o=t.entries[0]===n;if(t.closed){i(MC());return}if(o){im(e,{message:s,failed:i});return}n.frames.push({message:s,failed:i})},release(){if(n.released)return;n.released=!0,t.entries[0]===n&&LC(e,t)}}}function am(e,t){const n=Lr.get(e);for(const r of n?.entries??[]){const s=r.frames.findIndex(i=>"id"in i.message&&i.message.id===t);if(s>=0)return{entry:r,index:s}}}function cm(e,t){return am(e,t)!==void 0}function FC(e,t){const n=am(e,t),r=n!==void 0;return r&&n.entry.frames.splice(n.index,1),r}function lm(e,t){const n=Lr.get(e);for(const r of n?.entries??[]){const s=r.frames.findIndex(i=>i.message.t==="sub"&&i.message.subId===t);if(s>=0)return{entry:r,index:s}}}function VC(e,t){return lm(e,t)!==void 0}function qC(e,t){const n=lm(e,t),r=n!==void 0;return r&&n.entry.frames.splice(n.index,1),r}function um(e){const t=sm(e);t.closed=!0,t.entries.length=0}let WC=0,zC=0;function L(){return`op-${++WC}`}function dn(){return`sub-${++zC}`}const Qe=new Map,ze=new Map,ot=new Map,Wn=new WeakSet,fa=new Set;function HC(e){return fa.add(e),()=>fa.delete(e)}function Ur(){return Object.assign(new Error("Firebase App was deleted"),{code:"app/app-deleted"})}function KC(e,t,n){if(Wn.has(e))return;const s={...n,message:void 0};ze.set(t,s);const i=()=>ze.get(t)===s,o=a=>{i()&&ze.delete(t)&&n.error?.(a)};return{send(a,l){if(i()){s.message=a;try{l!==void 0?l.send(a,o):$i(e,a,o)}catch(d){queueMicrotask(()=>o(d))}}}}}function as(e,t,n,r,s){const i=KC(e,t,n);return i===void 0?!1:(i.send(r,s),!0)}function GC(e,t,n,r,s,i){if(Wn.has(e))return s?.(Ur()),!1;ot.set(t,{port:e,next:n,error:s,message:r,restored:i});const a=l=>{ot.get(t)?.message===r&&ot.delete(t)&&s?.(l instanceof H?l:Ur())};try{$i(e,r,a)}catch(l){queueMicrotask(()=>a(l))}return!0}function JC(e,t){const n=e.messagingVisibility;n&&t({...n,id:L()});for(const[r,s]of ze){const i=s.message;!(s.port===e&&i?.t==="sub")||!(i.target==="messaging.foreground"||i.target==="messaging.background")||(t({t:"unsub",subId:r}),t(i))}}function YC(e,t=n=>e.postMessage(n)){for(const[n,r]of ze){const s=r.message;if(!(r.port===e&&s?.t==="sub"))continue;const o=typeof s.target=="object"&&"service"in s.target&&s.target.service==="rtdb",a=r.service==="firestore"||o,l=s.target==="presence";(a||l)&&(t({t:"unsub",subId:n}),t(s))}for(const[n,r]of ot)r.port===e&&(r.restored?.(),t({t:"unsub",subId:n}),t(r.message))}function QC(e,t){for(const n of ze.values()){const r=n.message;n.port===e&&r?.t==="sub"&&(r.target==="authState"||r.target==="idToken")&&t(r)}}function it(e,t,n){const r=ze.get(t)??ot.get(t);if(!(r!==void 0)||(ze.delete(t),ot.delete(t),Wn.has(e))||r.message===void 0||qC(e,t)||e.withdrawSubscription?.(t)===!0)return;const a={t:"unsub",subId:t};n!==void 0&&n!==""&&(a.clientSessionId=n);const u=()=>{};try{$i(e,a,u)}catch{}}function Br(e,t,n=()=>!0){for(const[r,s]of[...Qe])s.port===e&&n(r)&&(zn(r),s.reject(t))}function XC(e,t){const n=[];for(const[r,s]of Qe)s.port===e&&t(r)&&n.push({id:r,message:s.message});return n}function ZC(e){const t=[];for(const n of e){const r=Qe.get(n),s=r?.message;if(!(r!==void 0&&s?.t==="op"))continue;const o={...s,id:L()};Qe.delete(n),Qe.set(o.id,{...r,message:o}),t.push(o)}return t}function Hu(e,t){zn(e)?.reject(t)}function eN(e){zn(e)}function tN(e){Wn.add(e),Br(e,Ur()),dm(e,new H("aborted","The operation was aborted."),Ur()),e.onmessage=null}function dm(e,t,n=t){for(const[r,s]of[...ze]){if(s.port!==e)continue;ze.delete(r),s.service==="firestore"?s.error?.(t):fm(s.message)&&s.error?.(n),s.close?.()}for(const[r,s]of[...ot])s.port===e&&(ot.delete(r),s.error?.(n))}function fm(e){if(!(e?.t==="sub"))return!1;const n=e.target;return typeof n=="object"&&n!==null&&"service"in n&&n.service==="ai"}function nN(e,t,n){for(const[r,s]of[...ze])!(s.port===e&&fm(s.message))||!(!n(r)&&!VC(e,r))||(it(e,r),s.error?.(t))}function Ku(e,t,n,r){if(t.denialContext===void 0||typeof fetch!="function")return;const s={kind:e,code:t.code??"unknown",message:t.message,denialContext:t.denialContext,...typeof t.remediation=="string"?{remediation:t.remediation}:{},...n===void 0?{}:{instance:n},...r!==void 0?{owners:r}:{}};try{fetch("/__pyric/denials",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(s)}).catch(()=>{})}catch{}}function Pi(e){e.onmessage=t=>{const n=t.data;if(!rm(n)){const u=new H("unavailable","The sandbox sent a malformed reply envelope. The operation may have completed; check state before retrying.");Br(e,u);for(const[d,h]of ze)h.port===e&&(it(e,d),h.error?.(u));for(const[d,h]of ot)h.port===e&&(it(e,d),h.error?.(u));return}const s=n.t==="res",i=n.t==="snap",o=n.t==="event",a=n.t==="runtime-reload",l=n.t==="clock";if(s){const u=Qe.get(n.id);if(u===void 0||u.port!==e)return;if(zn(n.id),!nm(n)){u.reject(new H("unavailable","The sandbox sent a malformed operation reply. The operation may have completed; check state before retrying."));return}if(n.ok)u.resolve(n.value);else{const p=n.error.codeless!==!0;let m;p?m=new H(n.error.code,n.error.message):m=new Error(n.error.message),n.error.denialContext!==void 0&&(m.denialContext=n.error.denialContext);const b=n.error.aiEvidence;b!==void 0&&Bu(m,b),n.error.aiEnvelope!==void 0&&(m.aiEnvelope=n.error.aiEnvelope),Ku("read",m,u.instance),u.reject(m)}}else if(i){const u=ze.get(n.subId);if(u===void 0){const p=ot.get(n.subId),m=zu(n);if(p!==void 0&&p.port===e&&m!==void 0){it(e,n.subId,p.message.clientSessionId);const g=m.codeless!==!0?new H(m.code,m.message):Object.assign(new Error(m.message),{code:"unavailable"});p.error?.(g)}return}if(u.port!==e)return;const h=zu(n);if(h!==void 0){it(e,n.subId,u.message?.clientSessionId);const p=h.codeless!==!0;let m;p?m=new H(h.code,h.message):m=new Error(h.message),h.denialContext!==void 0&&(m.denialContext=h.denialContext);const b=h.aiEvidence;b!==void 0&&Bu(m,b),h.aiEnvelope!==void 0&&(m.aiEnvelope=h.aiEnvelope);const v=u.message,_=v!==void 0&&"owners"in v?v.owners:void 0;Ku("listener",m,tm(v),_);const S=u.error;S!==void 0?S.call(u,m):console.error("pyric/firestore: Uncaught Error in snapshot listener:",m);return}u.next(n.value)}else if(o){const u=ot.get(n.subId);u!==void 0&&u.port===e&&u.next(n.events)}else if(a)for(const u of fa)u(n);else l&&kC(n.state)},e.postMessage({t:"clock-subscribe"})}const vr="pyric:auth-lens";function rN(e){if(!e||typeof e!="object")return!1;const t=e;return t.mode==="admin"||t.mode==="anon"?!0:t.mode==="as"&&typeof t.uid=="string"}function hm(e){if(rN(e))return e}function sN(){if(!(typeof sessionStorage>"u"))try{const e=sessionStorage.getItem(vr);if(!e)return;const t=JSON.parse(e),n=hm(t);if(n)return n;sessionStorage.removeItem(vr);return}catch{try{sessionStorage.removeItem(vr)}catch{}return}}let jt=sN();const ha=new Set;function iN(e){return ha.add(e),()=>{ha.delete(e)}}function Gu(e){if(jt=hm(e),typeof sessionStorage<"u")try{jt?sessionStorage.setItem(vr,JSON.stringify(jt)):sessionStorage.removeItem(vr)}catch{}for(const t of[...ha])try{t(jt)}catch(n){console.error("Error in subscribeLens listener:",n)}}function oN(){return jt}let pa;function aN(e){pa=e}function Cc(e){return pa&&(e.t==="op"||e.t==="sub")?{...e,issuer:pa}:e}function Di(e,t,n,r){if(Wn.has(e))return Promise.reject(Ur());const o=t.t==="op"||t.t==="tool"?cN(e,t.clientSessionId):void 0,a=o?.reserve(t);return a?.accepted===!1?Promise.reject(new H(a.error.code,a.error.message)):(t.t==="disconnect"&&um(e),new Promise((d,h)=>{const f=t;Qe.set(f.id,{port:e,clientSessionId:t.clientSessionId,instance:tm(t),budget:o,release:a?.release,issuedAt:r?.issuedAt??Ec(),message:t,resolve:d,reject:h});const p=m=>{zn(f.id)!==void 0&&h(m)};try{n!==void 0?n(t):r!==void 0?r.send(t,p):$i(e,t,p)}catch(m){p(m)}}))}function cN(e,t){for(const n of Qe.values()){const r=n.port===e&&n.clientSessionId===t,s=n.budget;if(r&&s!==void 0)return s}return DC()}function zn(e){const t=Qe.get(e);return Qe.delete(e),t!==void 0&&FC(t.port,e),t?.release?.(),t}function Q(e,t,n){return Di(e,Cc(t),void 0,n)}function pm(e,t,n,r){const s=t.id;let i;const o=new Promise((a,l)=>{i=setTimeout(()=>{zn(s)!==void 0&&l(new Error(r))},n)});return Promise.race([Q(e,t),o]).finally(()=>{i!==void 0&&clearTimeout(i)})}function ye(e,t,n){if(Wn.has(e)&&!t.method.startsWith("rtdb."))return Promise.reject(new H("failed-precondition","The client has already been terminated."));const r=jt?{...t,actAs:jt}:t;return Q(e,r,n)}async function lN(e,t,n={}){const r=n.timeoutMs??12e3;await pm(e.port,{t:"op",id:L(),method:"retireRuntime",targetEpoch:t},r,`Timed out waiting for the Pyric worker to retire after ${r}ms.`)}function uN(e){return HC(t=>e(t.epoch))}const ma=Symbol("pyric/database/target"),dN=new WeakMap;function fN(e){let t;if(ma in e?t=e[ma]:t=dN.get(e),!t)throw new TypeError("pyric/database: unrecognized reference — was it produced by a factory in this package?");return t.kind==="sandbox-live"&&t.assertUsable?.(),t}const Ju=hN();function hN(){let e;try{const n=import.meta.url;typeof n=="string"&&(e=n)}catch{e=void 0}if(e===void 0)return"";const t=e.slice(0,e.lastIndexOf("/"));return t.startsWith("file://")?t.slice(7):t}function pN(e){return Ju.length===0?e:e.split(`
|
|
127
|
+
`).filter(t=>!t.includes(Ju)).join(`
|
|
128
|
+
`)}function mm(e){const t=[],n=mN();n!==void 0&&t.push(n);const r=fw(e?.owner);if(r!==void 0&&t.push(r),t.length!==0)return t}function mN(){if(!hw())return;const e=pw();if(e!==void 0)return mw(pN(e))}function yN(e){const t=new Map,n=new Set,r=()=>{for(const i of[...n])try{i()}catch{}},s=e.subscribe(i=>{i.phase==="remove"&&t.delete(i.record.id)});return{record(i,o){const a=Ws(o);a===void 0||a.kind!=="regions"||(t.set(i,Object.freeze([...a.selectors])),r())},regions:i=>t.get(i)??[],subscribe(i){return n.add(i),()=>{n.delete(i)}},dispose(){s(),t.clear(),n.clear()}}}const Yu=Symbol.for("pyric.delivered-regions"),Qu=globalThis,gN=Qu[Yu]??(Qu[Yu]=yN(Kr));function bN(e,t){gN.record(e,t)}function wN(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 o=i.message||`failed to load ${String(e)}`;n.onError?.(new Error(`Pyric SharedWorker error: ${o}`))});const s=r.port;return Pi(s),s.start(),{__kind:"client-db",port:s}}async function vN(e,t={}){const n=L(),r=t.timeoutMs??2e3;return(await pm(e.port,{t:"op",id:n,method:"getRuntimeEpoch"},r,`Timed out waiting for the Pyric SharedWorker version handshake after ${r}ms.`)).version}async function xN(e){return(await Q(e.port,{t:"op",id:L(),method:"getVersion"})).instanceId??""}async function _N(e){return(await Q(e.port,{t:"op",id:L(),method:"exportState"})).bundle}async function SN(e,t){await Q(e.port,{t:"op",id:L(),method:"importState",bundle:t})}async function kN(e,t){await Q(e.port,{t:"op",id:L(),method:"checkpoint",name:t})}async function jN(e){return(await Q(e.port,{t:"op",id:L(),method:"listCheckpoints"})).checkpoints??[]}async function EN(e,t){await Q(e.port,{t:"op",id:L(),method:"restore",name:t})}async function CN(e,t){await Q(e.port,{t:"op",id:L(),method:"deleteCheckpoint",name:t})}async function NN(e,t,n,r,s){return await Q(e.port,{t:"tool",id:L(),name:t,args:n,clientSessionId:s,actAs:r})}function RN(e,t,n){return Di(e.port,{...t,issuer:void 0,relaySource:"remote",clientSessionId:n,t:"op",id:L()})}function IN(e,t,n,r){if(t.target==="events")throw new Error("event-stream subscriptions cannot be relayed over the bridge yet (needs bounded backpressure — slice 2)");const s=dn();return as(e.port,s,{port:e.port,next:n,error:o=>n({__error:{code:o.code??"unknown",message:o instanceof Error?o.message:String(o)}})},{...t,issuer:void 0,relaySource:"remote",clientSessionId:r,t:"sub",subId:s})||queueMicrotask(()=>n({__error:{code:"app/app-deleted",message:"Firebase App was deleted"}})),()=>{it(e.port,s,r)}}function AN(e){const t=(e??"/").split("/").filter(Boolean).join("/");return t?`/${t}`:"/"}function ym(e){return e.kind==="where"?{...e,value:ah(e.value)}:{kind:e.kind,filters:e.filters.map(ym)}}function ON(e){return e.kind==="where"||e.kind==="and"||e.kind==="or"?ym(e):"values"in e?{...e,values:e.values.map(ah)}:e}function Hn(e,t,n,r=mm(void 0)){const s=e.descriptor,i=s.__ref==="query"?s.source:s,o=i.__ref==="group"?i.collectionId:i.path,a=s.__ref==="query"?s.constraints:[];return Kr.begin({app:e.port,method:t,kind:n,owners:r,source:{service:"firestore",target:o,isQuery:s.__ref!=="doc",...s.__ref==="doc"?{}:{indexQuery:Yw(o,i.__ref==="group",a.filter(l=>["where","and","or"].includes(l.kind)),a.filter(l=>l.kind==="orderBy").map(l=>({...l,direction:l.direction??"asc"})))},key:Cr({base:i,constraints:s.__ref==="query"?s.constraints.map(ON):[]})}})}const $N=[];function gm(e){for(const t of[...$N])t.port===e&&t.close()}const PN=5e3;function DN(){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 TN(e,t={}){let n;try{const r=Di(e.port,{t:"disconnect",id:L()}),s=new Promise((i,o)=>{n=setTimeout(()=>o(DN()),t.ackTimeoutMs??PN)});await Promise.race([r,s])}finally{n!==void 0&&clearTimeout(n),gm(e.port),tN(e.port),e.port.close()}}function MN(e,t){dm(e,t),gm(e)}function Nc(e){return e.split("/").at(-1)??e}function Wt(e,t,n=null){function r(i){return Wt(e,t,i)}const s={__kind:"doc-ref",descriptor:{__ref:"doc",path:t},port:e,id:Nc(t),path:t,converter:n,withConverter:r};return ih(s,t,e),s}function LN(e,t){const n=JSON.parse(e.json);return t!==void 0?yw(n,t,e.valueEncoding):Za(n,e.valueEncoding)}const ya=4*1024*1024,Ti=512*1024*1024;function Rc(e,t){const n=new Error(`${t} is ${e} bytes — over the ${Ti/1048576} MiB maximum storage object cap (MAX_STORAGE_OBJECT_BYTES).`);return n.code="storage/quota-exceeded",n}function Xu(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 Zu(e){const t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}function UN(e,t){return LN(e,{create:r=>Wt(t,r)})}const bm=Object.freeze({fromCache:!1,hasPendingWrites:!1}),BN=Object.freeze({fromCache:!1,hasPendingWrites:!0});function wm(e){return e.hasPendingWrites===!0?BN:bm}const vm=new WeakMap;function FN(e){return vm.get(e)}function Ic(e,t,n,r=bm){if(!Ac(e))throw new H("invalid-argument","The sandbox sent a malformed document result.");let i;const o=e.data;e.exists&&o!==void 0&&(i=UN(o,t));const l=e.path??e.id,u=n??Wt(t,l),d=()=>{const f=i;if(f===void 0)return;const m=u.converter;if(m!==null){const b={id:e.id,ref:Wt(t,l),exists:()=>!0,metadata:r,data:()=>f};return m.fromFirestore(b)}return f},h={id:e.id,path:l,ref:u,exists:()=>e.exists,metadata:r,data:d,get:f=>VN(i,f)};return vm.set(h,{id:e.id,path:l,exists:e.exists,data:i}),h}function VN(e,t){try{return ww(e,t)}catch(n){const r=n instanceof Error?n.message:String(n);throw new H("invalid-argument",`Function DocumentSnapshot.get() called with invalid data. ${r}`)}}function ga(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ac(e){if(!ga(e))return!1;const r=e.data,s=r===void 0||ga(r)&&typeof r.json=="string",i=e.path===void 0||typeof e.path=="string";return typeof e.id=="string"&&typeof e.exists=="boolean"&&i&&s&&xm(e)}function xm(e){return e.hasPendingWrites===void 0||typeof e.hasPendingWrites=="boolean"}function _m(e){return ga(e)&&Array.isArray(e.docs)&&e.docs.every(Ac)&&xm(e)}function qN(e,t,n,r){if(_m(e)){const o=Sm(e,t,n,r);return r.previous!==void 0&&o.docChanges().length===0&&(r.excludesMetadataChanges||o.metadata.hasPendingWrites===r.previousHasPendingWrites)?null:(r.previous=e.docs,r.previousHasPendingWrites=o.metadata.hasPendingWrites,o)}if(Ac(e)){const o=wm(e),a=r.previousDocument;return a!==void 0&&a.exists===e.exists&&(!e.exists||a.data?.json===e.data?.json)&&(r.excludesMetadataChanges||o.hasPendingWrites===r.previousHasPendingWrites)?null:(r.previousDocument=e,r.previousHasPendingWrites=o.hasPendingWrites,Ic(e,t,Wt(t,e.path??e.id,n),o))}throw new H("invalid-argument","The sandbox sent a malformed Firestore snapshot.")}function Sm(e,t,n=null,r={excludesMetadataChanges:!1}){if(!_m(e))throw new H("invalid-argument","The sandbox sent a malformed query result.");const i=wm(e),o=h=>Ic(h,t,Wt(t,h.path??h.id,n),i),a=e.docs.map(o),l=e.docs.map(h=>({path:h.path??h.id,doc:h})),u=r.previous?.map(h=>({path:h.path??h.id,doc:h})),d=gw(u,l,a,(h,f)=>h.doc.data?.json===f.doc.data?.json,h=>o(h.doc));return{metadata:i,size:a.length,empty:a.length===0,docs:a,forEach:oh(a),docChanges:bw(d,r.excludesMetadataChanges)}}function WN(e,...t){const n=e.port;let r,s=null;const i=e.__kind==="client-db",o=t.length>0;if(i){if(!o)throw new TypeError("doc(db, path) requires a path segment.");r=t.join("/")}else{const a=e.descriptor.path;s=e.converter,o?r=`${a}/${t.join("/")}`:r=`${a}/${vw()}`}return Wt(n,r,s)}function zN(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("/")}`,km(n,r,null)}function km(e,t,n){function r(i){return km(e,t,i)}return{__kind:"coll-ref",descriptor:{__ref:"collection",path:t},port:e,id:Nc(t),path:t,converter:n,withConverter:r}}function jm(e,t,n){function r(s){return jm(e,t,s)}return{__kind:"query",descriptor:t,port:e,converter:n,withConverter:r}}const bs="__name__",HN=new Set(["<","<=",">",">=","!=","not-in"]),Em=new WeakMap,ed=new WeakMap;function KN(e,t){if(!t.includes("."))return e[t];let n=e;for(const r of t.split(".")){if(n===null||typeof n!="object"||Array.isArray(n))return;n=n[r]}return n}function Cm(e,t){if(e.kind==="where"){HN.has(e.op)&&t.push(e.field);return}for(const n of e.filters)Cm(n,t)}function GN(e){return e.length===1&&e[0]!==null&&typeof e[0]=="object"&&"data"in e[0]&&typeof e[0].data=="function"}function JN(e,t){if(!GN(t))return{type:e,_descriptor:{kind:e,values:t.map(Er),valueEncoding:un}};const n=t[0],r=FN(n)??(()=>{const i=n.data(),o=typeof n.id=="string"?n.id:"",a=typeof n.path=="string"?n.path:typeof n.ref?.path=="string"?n.ref.path:o,l=typeof n.exists=="function"?!!n.exists():i!==void 0;return{id:o,path:a,exists:l,data:i}})(),s={type:e,_descriptor:{kind:e,values:[],valueEncoding:un}};return Em.set(s,{__snapshotCursor:!0,kind:e,snapshot:r}),s}function yo(e){return"__snapshotCursor"in e}function YN(e){if(!e.some(yo))return e;const n=[],r=[];for(const l of e)yo(l)||(l.kind==="orderBy"?n.push({field:l.field,direction:l.direction??"asc"}):(l.kind==="where"||l.kind==="and"||l.kind==="or")&&Cm(l,r));const s=[...n],i=new Set(s.map(l=>l.field)),o=n.length>0?n[n.length-1].direction:"asc";for(const l of r)l!==bs&&!i.has(l)&&(i.add(l),s.push({field:l,direction:o}));i.has(bs)||s.push({field:bs,direction:o});const a=s.map(l=>({kind:"orderBy",field:l.field,direction:l.direction}));for(const l of e){if(yo(l)){const{snapshot:u}=l;if(!u.exists||u.data===void 0)throw new H("not-found",`Snapshot-based cursors require an existing document — got an empty snapshot for ${u.id||"<unknown>"}.`);const d=s.map(h=>h.field===bs?Er(u.path):Er(KN(u.data,h.field)));a.push({kind:l.kind,values:d,valueEncoding:un});continue}l.kind!=="orderBy"&&a.push(l)}return a}function QN(e){return{type:"limit",_descriptor:{kind:"limit",n:e}}}function XN(...e){return JN("startAfter",e)}function ZN(e,...t){const n=(e.__kind==="coll-ref",e.descriptor),s=[...e.__kind==="query"?ed.get(e)??e.descriptor.constraints:[],...t.map(a=>Em.get(a)??a._descriptor)],i={__ref:"query",source:n.__ref==="query"?n.source:n,constraints:YN(s)},o=jm(e.port,i,e.converter);return ed.set(o,s),o}function eR(e){return tR(e,"getDoc")}async function tR(e,t){const n=Hn(e,t,"operation");try{const r=await ye(e.port,{t:"op",id:L(),method:"getDoc",path:e.descriptor.path});return $n(n,Ic(r,e.port,e))}catch(r){throw n.fail(),r}}function nR(e){return rR(e,"getDocs")}async function rR(e,t){const n=Hn(e,t,"operation");try{const r=await ye(e.port,{t:"op",id:L(),method:"getDocs",source:(e.__kind==="coll-ref",e.descriptor)});return $n(n,Sm(r,e.port,e.converter))}catch(r){throw n.fail(),r}}async function sR(e){return(await ye(e.port,{t:"op",id:L(),method:"listRootCollections"})).ids}async function iR(e,t){return(await ye(e.port,{t:"op",id:L(),method:"listSubcollections",docPath:t})).ids}function oR(e,t,n,r){const s=typeof t=="function",i=s?void 0:t,o=mm(i),a=i?.includeMetadataChanges===!0,l={excludesMetadataChanges:!a},u=s?t:n,d=s?n:r;let h=dn();const f=e.port,p=Hn(e,"onSnapshot","subscription",o);p.transport(h);const m={port:f,service:"firestore",next:_=>{let S;try{S=qN(_,f,e.converter,l)}catch(O){v(),d!==void 0?d(O):console.error("pyric/firestore: Uncaught Error in snapshot listener:",O);return}if(S===null)return;const k=S,N=_;p.delivered(k,N.usage),bN(p.id,()=>u(k))},error:_=>{p.fail(),d?.(_)},close:()=>p.close()},g=e.descriptor;function b(){const _={t:"sub",subId:h,target:g};jt!==void 0&&(_.actAs=jt),o!==void 0&&(_.owners=o),a&&(_.includeMetadataChanges=!0);const N=as(f,h,m,Cc(_));return!N&&p.fail(),!N&&d!==void 0&&queueMicrotask(()=>d(new Error("Firebase App was deleted"))),N}b();let w=!1;const x=iN(()=>{w||(it(f,h),h=dn(),p.transport(h),b())});function v(){w=!0,p.close(),x(),it(f,h)}return v}function Nm(e,t){const n=e.converter,r=n!==null;let s=t;return r&&(s=n.toFirestore(t)),xw(s)}async function aR(e,t,n){return rc(Hn(e,"setDoc","operation"),async()=>{const r=Nm(e,t);await ye(e.port,{t:"op",id:L(),method:"setDoc",path:e.descriptor.path,data:Er(r),valueEncoding:un,options:n})})}async function cR(e){return rc(Hn(e,"deleteDoc","operation"),async()=>{await ye(e.port,{t:"op",id:L(),method:"deleteDoc",path:e.descriptor.path})})}async function lR(e,t){return rc(Hn(e,"addDoc","operation"),async()=>{const n=Nm(e,t),r=await ye(e.port,{t:"op",id:L(),method:"addDoc",collectionPath:e.descriptor.path,data:Er(n),valueEncoding:un});return Wt(e.port,r.path,e.converter)})}async function uR(e,t){return await Q(e.port,{t:"op",id:L(),method:"admin.listDocuments",path:t})}const dR=Za({__type:"path",segments:[]},un).constructor;class fR{port;subId=dn();subscribers=new Set;history=new ch(lh);isAwaitingHistory=!0;hasReceivedHistory=!1;constructor(t){this.port=t}open(t){this.subscribers.add(t),Cn.set(this.port,this);const n={t:"sub",subId:this.subId,target:"events"};GC(this.port,this.subId,r=>this.receive(r),n,r=>this.fail(r),()=>{this.isAwaitingHistory=!0})}join(t){this.subscribers.add(t),this.hasReceivedHistory&&queueMicrotask(()=>{this.subscribers.has(t)&&td(t,this.history.snapshot())})}leave(t){this.subscribers.delete(t)&&this.subscribers.size===0&&(Cn.delete(this.port),it(this.port,this.subId))}receive(t){const n=this.isAwaitingHistory;n&&this.history.clear();for(const s of t)this.record(s);this.isAwaitingHistory=!1;const r=n&&!this.hasReceivedHistory;this.hasReceivedHistory=!0;for(const s of[...this.subscribers])this.subscribers.has(s)&&(r?td(s,t):s.isPrimed&&Rm(s,t,n))}record(t){t.kind==="session_boundary"&&t.phase==="reset"?this.history.clear():this.history.append(t)}fail(t){Cn.get(this.port)===this&&Cn.delete(this.port);const n=[...this.subscribers];this.subscribers.clear();for(const r of n)try{r.onError?.(t)}catch(s){console.error("pyric: Uncaught Error in event subscriber error handler:",s)}}}const Cn=new WeakMap;function Rm(e,t,n){try{e.callback(t,{history:n})}catch(r){console.error("pyric: Uncaught Error in event subscriber:",r)}}function td(e,t){e.isPrimed=!0,Rm(e,t,!0)}function hR(e,t,n){const r=e.port,s={callback:t,onError:n,isPrimed:!1},i=Cn.get(r);return i?i.join(s):new fR(r).open(s),()=>{Cn.get(r)?.leave(s)}}function pR(e){return e.__type__==="__vector__"&&Array.isArray(e.value)?!0:typeof e.__type=="string"?e.__type==="timestamp"||e.__type==="bytes"||e.__type==="latlng"||e.__type==="duration"||e.__type==="reference":typeof e.type=="string"?e.type==="firestore/timestamp/1.0"||e.type==="firestore/bytes/1.0"||e.type==="firestore/geoPoint/1.0"||e.type==="firestore/vectorValue/1.0":!1}function Ls(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(Ls);const t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)return e;const n=e;if(n.type==="pyric/map/1.0"){const s=n.fields;if(s===null||typeof s!="object"||Array.isArray(s))throw new TypeError("Invalid encoded map fields.");const i={};for(const[o,a]of Object.entries(s))i[o]=Ls(a);return i}if(n.__type==="number"){if(n.value==="NaN")return Number.NaN;if(n.value==="Infinity")return 1/0;if(n.value==="-Infinity")return-1/0;if(n.value==="-0")return-0}if(n.__type==="path"&&Array.isArray(n.segments)){const s=n.bindings,i=s!==null&&typeof s=="object"&&!Array.isArray(s)?s:void 0;return new dR(n.segments,i)}if(pR(n))return Za(n,un);const r={};for(const[s,i]of Object.entries(n))r[s]=Ls(i);return r}async function mR(e){const t=await Q(e.port,{t:"op",id:L(),method:"getSnapshot"}),n={};for(const[r,s]of Object.entries(t.firestore??{}))n[r]=Ls(s);return{firestore:n,services:t.services}}async function yR(e){return await Q(e.port,{t:"op",id:L(),method:"resetAll"})??{errors:[]}}const gR=15e3;function bR(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"}function nd(){return typeof document<"u"&&typeof document.addEventListener=="function"&&typeof document.removeEventListener=="function"}function rd(){return typeof window<"u"&&typeof window.addEventListener=="function"&&typeof window.removeEventListener=="function"}function wR(){return bR()?crypto.randomUUID():`page-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function sd(){return typeof location>"u"?"/":`${location.pathname}${location.search}${location.hash}`}function id(){return typeof document>"u"?"visible":document.visibilityState==="hidden"?"hidden":"visible"}function vR(e){const{db:t,kind:n}=e,r=e.clientId??wR(),s=e.heartbeatIntervalMs??gR;let i=!1,o=null;const a=()=>{Q(t.port,{t:"op",id:L(),method:"presence.register",clientId:r,kind:n,route:sd(),visibility:id()}).catch(()=>{})},l=()=>{Q(t.port,{t:"op",id:L(),method:"presence.heartbeat",clientId:r}).catch(()=>{})},u=()=>{Q(t.port,{t:"op",id:L(),method:"presence.update",clientId:r,route:sd(),visibility:id()}).catch(()=>{})},d=()=>{Q(t.port,{t:"op",id:L(),method:"presence.disconnect",clientId:r}).catch(()=>{})};a(),nd()&&document.addEventListener("visibilitychange",u),rd()&&(window.addEventListener("popstate",u),window.addEventListener("hashchange",u),window.addEventListener("pagehide",h),o=setInterval(()=>{i||l()},s));function h(){f()}function f(){i||(i=!0,o!=null&&(clearInterval(o),o=null),nd()&&document.removeEventListener("visibilitychange",u),rd()&&(window.removeEventListener("popstate",u),window.removeEventListener("hashchange",u),window.removeEventListener("pagehide",h)),d())}return{clientId:r,kind:n,stop:f}}function xR(e,t){const n=dn();return as(e.port,n,{port:e.port,next:r=>{t(r)}},{t:"sub",subId:n,target:"presence"}),()=>{it(e.port,n)}}async function _R(e){return await Q(e.port,{t:"op",id:L(),method:"auth.listUsers"})}async function SR(e,t){return await Q(e.port,{t:"op",id:L(),method:"auth.adminCreateUser",request:t})}async function kR(e,t,n){return await Q(e.port,{t:"op",id:L(),method:"auth.adminUpdateUser",uid:t,request:n})}async function jR(e,t){await Q(e.port,{t:"op",id:L(),method:"auth.adminDeleteUser",uid:t})}async function ER(e){await Q(e.port,{t:"op",id:L(),method:"auth.adminClearUsers"})}async function CR(e){return await Q(e.port,{t:"op",id:L(),method:"auth.getProviderConfig"})}async function NR(e,t,n){await Q(e.port,{t:"op",id:L(),method:"auth.setProviderConfig",providerId:t,enabled:n})}const RR=Symbol("pyric.clientUser.port");function IR(e,t){const n={uid:t.uid,email:t.email,emailVerified:t.emailVerified,displayName:t.displayName,photoURL:sp(t.photoURL,ip()),phoneNumber:t.phoneNumber,isAnonymous:t.isAnonymous,tenantId:t.tenantId??null,providerId:t.providerId,providerData:t.providerData,async getIdToken(r){return await Q(e,{t:"op",id:L(),method:"auth.getIdToken",forceRefresh:r})},async getIdTokenResult(r){return await Q(e,{t:"op",id:L(),method:"auth.getIdTokenResult",forceRefresh:r})}};return Object.defineProperty(n,RR,{value:e,enumerable:!1}),n}function Im(e,t){return t?IR(e,t):null}function AR(e,t){let n;if(typeof e=="string"||e instanceof URL){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(),Pi(n)}else n=e.port;let s=null;const i={__kind:"client-auth",port:n,currentUser:null,get tenantId(){return s},set tenantId(a){s=a,Q(n,{t:"op",id:L(),method:"auth.setTenantId",tenantId:a})}};n.restoreAuth=async a=>{await a({t:"op",id:L(),method:"auth.setTenantId",tenantId:i.tenantId});const l=i.currentUser;l!==null&&await OR(i,l.uid,a,l.tenantId)};const o=dn();return as(n,o,{port:n,next:a=>{i.currentUser=Im(n,a)}},{t:"sub",subId:o,target:"idToken"}),i}async function OR(e,t,n=s=>Q(e.port,s),r=e.tenantId){const s=await n({t:"op",id:L(),method:"auth.restorePortSession",uid:t,tenantId:r}),i=Im(e.port,s);return e.currentUser=i,i}const $R=1e4,Am="The hosted sandbox connection was not restored within 10 seconds. The request was not sent.";let Om=$R;function PR(e){let t;const n=new Promise((r,s)=>{t=setTimeout(()=>s(new H("unavailable",Am)),Om)});return Promise.race([e,n]).finally(()=>clearTimeout(t))}function go(e){if("id"in e&&typeof e.id=="string")return e.id}function od(e){if(e.t==="sub"||e.t==="unsub")return e.subId}function DR(e){const t=[];function n(s,i){const o=t.indexOf(s);o<0||(t.splice(o,1),Br(e,new H("unavailable",Am),l=>l===i))}function r(){const s=t.splice(0);for(const i of s)clearTimeout(i.deadline);return s}return{hold(s){const i={message:s},o=go(s);if(t.push(i),o===void 0)return;const l=Qe.get(o);if(!(l!==void 0&&l.port===e))return;const d=l.issuedAt+Om-Ec();if(d<=0){n(i,o);return}i.deadline=setTimeout(()=>n(i,o),d)},holdAgain(s){t.unshift(...s.map(i=>({message:i})))},holdsRequest(s){return t.some(i=>go(i.message)===s)},holdsSubscription(s){const i=od(s);return i!==void 0?t.some(a=>a.message.t==="sub"&&a.message.subId===i):!1},forgetSubscription(s){const i=t.findIndex(a=>a.message.t==="sub"&&a.message.subId===s),o=i>=0;return o&&t.splice(i,1),o},flush(s){const i=r(),o=a=>od(a.message)!==void 0;for(const a of i.filter(o))s(a.message);for(const a of i.filter(l=>!o(l)))s(a.message)},drop(){r()},fail(s){const i=new Set(r().map(o=>go(o.message)));Br(e,s,o=>i.has(o))}}}function TR(e){return e.then(t=>({result:t}),t=>({error:t}))}function MR(e){return e!==void 0&&"result"in e?e.result:void 0}function $m(e){const t=e?.code;if(typeof t=="string")return t}async function LR(e,t){if(!(t!==void 0))return!1;try{return await nI(e,t),!0}catch(r){if($m(r)==="storage/unauthorized")return!1;throw r}}async function UR(e,t){if(t.replacedObject===!0)throw new H("storage/unknown","The host no longer holds the object this upload replaced, so it cannot be restored.");try{await zm(e)}catch(n){if(!($m(n)==="storage/object-not-found"))throw n}}function BR(e){return e.replacedObject===!0?"restore":"remove"}async function FR(e,t){try{await LR(e,t.rollbackToken)||await UR(e,t)}catch(n){throw sa(e.fullPath,n,BR(t))}}function VR(e){return e instanceof Error?e:new Error(String(e))}function qR(e){return e instanceof Blob?e.size:e.byteLength}function WR(){const e=new Error("storage/canceled: User canceled the upload/download.");return e.code="storage/canceled",e}function zR(){const e=new Error("storage/invalid-root-operation: uploadBytesResumable cannot operate on root reference.");return e.code="storage/invalid-root-operation",e}class HR{[Symbol.toStringTag]="UploadTask";_snapshot;_promise;_resolve;_reject;_observers=[];_didIntermediateProgress=!1;_committing=!1;_heldOutcome;_sentCommit;_error;_ref;_data;_metadata;_upload;_inFlight;_sending=!1;_resyncs=!1;constructor(t,n,r){this._ref=t,this._data=n,this._metadata=r;const s=qR(n),i=new Date(jC()).toISOString();let o="application/octet-stream";if(n instanceof Blob&&n.type!==""&&(o=n.type),r!==void 0&&r.contentType!==void 0){const h=r.contentType;h!==void 0&&(o=h)}const u={fullPath:t.fullPath,name:t.name,bucket:t.bucket||"default",generation:"1",metageneration:"1",timeCreated:i,updated:i,size:s,contentType:o};this._promise=new Promise((d,h)=>{this._resolve=d,this._reject=h}),this._promise.catch(()=>{}),this._snapshot={bytesTransferred:0,totalBytes:s,state:"running",metadata:u,ref:this._ref,task:this},this._start(),queueMicrotask(()=>{this._runStep()})}_start(){!(this._ref.port.byteRouteSettled?.()!==void 0)&&xr(this._ref)!==void 0?this._sendOverRoute():this._commitUpload()}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._resyncs=!0,this._inFlight?.abort(),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;if((this._snapshot.state==="running"||this._snapshot.state==="paused")&&(t=!0),t){const r=WR();return this._updateSnapshot("canceled",this._snapshot.bytesTransferred),this._inFlight?.abort(),this._rollBackCanceled().then(()=>this._settleCanceled(r),s=>this._settleCanceled(VR(s))),!0}return!1}_settleCanceled(t){this._error=t,this._notifyObservers("error"),this._reject(t)}async _rollBackCanceled(){const t=this._heldOutcome;this._heldOutcome=void 0;const n=this._sentCommit,r=t??(n===void 0?void 0:await n),s=this._upload;s!==void 0&&await Us(s);const i=MR(r);i!==void 0&&await FR(this._ref,i)}_sendCommit(t){const n=TR(t);return this._sentCommit=n,n}_releaseHeldOutcome(){const t=this._heldOutcome;return t===void 0?!1:(this._heldOutcome=void 0,"result"in t?this._succeed(t.result.metadata):this._fail(t.error),!0)}on(t,n,r,s){let i,o,a,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&&(o=f.error),f.complete!==void 0&&(a=f.complete)}else typeof n=="function"&&(i=n),typeof r=="function"&&(o=r),typeof s=="function"&&(a=s);const d={next:i,error:o,complete:a};if(this._observers.push(d),this._snapshot.state==="running"){if(i!==void 0){const p=i;try{Ut(this),p(this._snapshot)}catch{}}}else if(this._snapshot.state==="paused"){if(i!==void 0){const m=i;try{Ut(this),m(this._snapshot)}catch{}}}else if(this._snapshot.state==="success"){if(i!==void 0){const b=i;try{Ut(this),b(this._snapshot)}catch{}}if(a!==void 0){const b=a;try{ri(this),b()}catch{}}}else if(this._snapshot.state==="error"){if(o!==void 0&&this._error!==void 0){const w=o,x=this._error;try{w(x)}catch{}}}else if(this._snapshot.state==="canceled"&&o!==void 0&&this._error!==void 0){const x=o,v=this._error;try{x(v)}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 a=i.next;try{Ut(this),a(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 a=i.complete;try{ri(this),a()}catch{}}}}async _sendOverRoute(){if(this._sending)return;this._sending=!0;const t=Vm(this._data),n=()=>this._snapshot.state==="running";try{const r=xr(this._ref);let s=this._upload;if(s===void 0){const l=this._metadata?.contentType??(t.type!==""?t.type:void 0);if(s=await Lm(this._ref,r,t.size,l,this._metadata),this._upload=s,this._snapshot.state==="canceled"&&await Us(s),!n())return}let i=this._snapshot.bytesTransferred;for(this._resyncs&&(i=await tI(s),this._resyncs=!1);n()&&i<s.size;){const l=new AbortController;if(this._inFlight=l,i=await Bm(s,t,i,l.signal),this._inFlight=void 0,!n())return;this._updateSnapshot("running",i),this._notifyObservers("next")}if(!n())return;const o=await this._sendCommit(Fm(s,!0));if("error"in o&&n())throw o.error;this._settleCommit(o)}catch(r){if(this._inFlight=void 0,!n())return;this._error=r instanceof Error?r:new Error(String(r)),this._updateSnapshot("error",this._snapshot.bytesTransferred);const s=this._upload;s!==void 0&&await Us(s),this._notifyObservers("error"),this._reject(this._error)}finally{this._sending=!1,n()&&queueMicrotask(()=>this._runStep())}}_runStep(){if(this._snapshot.state!=="running")return;if(xr(this._ref)!==void 0&&!this._committing){this._releaseHeldOutcome()||this._sendOverRoute();return}if(this._didIntermediateProgress===!1){this._didIntermediateProgress=!0;let i=0;this._snapshot.totalBytes>0&&(i=Math.floor(this._snapshot.totalBytes/2)),this._updateSnapshot("running",i),this._notifyObservers("next")}this._releaseHeldOutcome()||this._commitUpload()}_succeed(t){this._updateSnapshot("success",this._snapshot.totalBytes,t),this._notifyObservers("next"),this._notifyObservers("complete"),this._resolve(this._snapshot)}_fail(t){this._error=t instanceof Error?t:new Error(String(t)),this._updateSnapshot("error",this._snapshot.bytesTransferred),this._notifyObservers("error"),this._reject(this._error)}async _commitUpload(){const t=this._snapshot.state!=="running",n=this._committing||this._heldOutcome!==void 0;if(t||n)return;this._committing=!0;const r=await this._sendCommit(qm(this._ref,this._data,this._metadata,!0));this._committing=!1,this._settleCommit(r)}_settleCommit(t){const n=this._snapshot.state;if(n==="running"){"result"in t?this._succeed(t.result.metadata):this._fail(t.error);return}n==="paused"&&(this._heldOutcome=t)}}function KR(e,t,n){if(e.fullPath==="")throw zR();return new HR(e,t,n)}class Fr{__kind="storage-ref";port;storage;bucket;fullPath;name;constructor(t,n,r,s){this.port=t,this.bucket=n,this.fullPath=r,this.name=Nc(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 Fr(this.port,this.bucket,n,this.storage)}get root(){return this.fullPath===""?this:new Fr(this.port,this.bucket,"",this.storage)}toString(){return`gs://${this.bucket}/${this.fullPath}`}}function GR(e){return e.replace(/^\/+|\/+$/g,"").replace(/\/+/g,"/")}function JR(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(),Pi(r)}return{__kind:"client-storage",port:r,bucket:n??"pyric-default"}}function YR(e,t){const n=GR(na(t,e.__kind==="client-storage"));let r,s,i="pyric-default",o;if(e.__kind==="client-storage")r=n,s=e.port,i=e.bucket,o=e;else{const a=e.fullPath;r=n?a?`${a}/${n}`:n:a,s=e.port,i=e.bucket,o=e.storage}return new Fr(s,i,r,o)}async function QR(e){const t=await ye(e.port,{t:"op",id:L(),method:"storage.listAll",path:e.fullPath}),n=r=>new Fr(e.port,e.bucket,r.fullPath,e.storage);return{items:t.items.map(n),prefixes:t.prefixes.map(n)}}function Pm(e,t){return e.bucket?{...t,bucket:e.bucket}:t}async function Dm(e){return await ye(e.port,{t:"op",id:L(),method:"storage.getMetadata",path:e.fullPath})}async function Tm(e){return Pm(e,await Dm(e))}const XR=4*1024*1024;async function ZR(e){const t=await e.sessionToken();if(t===null||t==="")throw new H("unavailable","The page has no session token for the hosted byte route. Reload the page.");return t}function Oc(e,t){return e===401||e===403?new H("storage/unauthorized",`The host refused bytes for '${t}' (HTTP ${e}).`):e===404?new H("storage/object-not-found",`Object '${t}' does not exist.`):new H("storage/unknown",`The host's byte route answered HTTP ${e} for '${t}'.`)}async function eI(e,t){for(let n=0;n<2;n++){const r=await Dm(t),s=new URL(cE(r.bucket,t.fullPath),e.baseUrl);s.searchParams.set("generation",r.generation);const i=await fetch(s,{headers:{"x-pyric-session-token":await ZR(e)}});if(i.status===412)continue;if(!i.ok)throw Oc(i.status,t.fullPath);const a=new Uint8Array(await i.arrayBuffer());return{bytes:a,contentType:i.headers.get("content-type")??r.contentType,size:a.byteLength}}throw new H("storage/retry-limit-exceeded",`Object '${t.fullPath}' kept changing while it was read.`)}function xr(e){return e.port.byteRoute}async function Mm(e,t){const n=e.port.byteRouteSettled?.();if(n===void 0)return t(xr(e),void 0);const s=om(e.port);try{return await PR(n),await t(xr(e),s)}finally{s.release()}}async function Lm(e,t,n,r,s){const i=await ye(e.port,{t:"op",id:L(),method:"storage.beginUpload",path:e.fullPath,size:n,...r!==void 0?{contentType:r}:{},...s!==void 0?{metadata:s}:{}}),o=i.uploadUrl;if(o===void 0)throw new H("storage/unknown","The host began the upload without a byte route URL.");return{uploadId:i.uploadId,url:new URL(o,t.baseUrl).href,size:n,reference:e}}function Um(e,t){if(e.status===200)return t;const r=/^bytes=0-(\d+)$/.exec(e.headers.get("range")??"");return r===null?0:Number(r[1])+1}async function Bm(e,t,n,r){const s=Math.min(n+XR,e.size),i=await fetch(e.url,{method:"PUT",headers:{"content-range":`bytes ${n}-${s-1}/${e.size}`},body:t.slice(n,s),signal:r});if(!(i.status===200||i.status===308||i.status===409))throw Oc(i.status,e.reference.fullPath);return Um(i,e.size)}async function tI(e,t){const n=await fetch(e.url,{method:"PUT",headers:{"content-range":`bytes */${e.size}`},signal:t});if(!(n.status===200||n.status===308))throw Oc(n.status,e.reference.fullPath);return Um(n,e.size)}function ba(e,t){const{rollbackToken:n,replacedObject:r,...s}=t,i=Pm(e,s);return typeof n=="string"?{metadata:i,rollbackToken:n,replacedObject:r===!0}:{metadata:i}}function wa(e){return e?{rollback:!0}:{}}async function Fm(e,t=!1){const n=await ye(e.reference.port,{t:"op",id:L(),method:"storage.finishUpload",uploadId:e.uploadId,...wa(t)});return ba(e.reference,n)}async function nI(e,t){await ye(e.port,{t:"op",id:L(),method:"storage.rollbackUpload",rollbackToken:t})}async function Us(e){try{await ye(e.reference.port,{t:"op",id:L(),method:"storage.abortUpload",uploadId:e.uploadId})}catch{}}function Vm(e){return e instanceof Blob?e:new Blob([e])}async function rI(e,t){const n=await sI(e),r=typeof t=="number"&&n.bytes.byteLength>t?n.bytes.subarray(0,Math.max(0,t)):n.bytes,s=r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength);return new Blob([s],{type:n.contentType??"application/octet-stream"})}async function sI(e){return Mm(e,(t,n)=>t!==void 0?(n?.release(),eI(t,e)):iI(e,n))}async function iI(e,t){try{const n=await ye(e.port,{t:"op",id:L(),method:"storage.getBytes",path:e.fullPath},t);return{bytes:Zu(n.dataB64),contentType:n.contentType,size:n.size}}catch(n){if(n?.code==="payload-too-large"){const r=await Tm(e),s=[];let i=0;for(;i<r.size;){const l=Math.min(ya,r.size-i),u=await ye(e.port,{t:"op",id:L(),method:"storage.getBytes",path:e.fullPath,offset:i,length:l,expectedGeneration:r.generation});s.push(Zu(u.dataB64)),i+=l}const o=new Uint8Array(r.size);let a=0;for(const l of s)o.set(l,a),a+=l.byteLength;return{bytes:o,contentType:r.contentType,size:r.size}}throw n}}async function oI(e,t,n){const r=await qm(e,t,n,!1);return{ref:e,metadata:r.metadata}}async function qm(e,t,n,r){return Mm(e,(s,i)=>{if(s!==void 0)return i?.release(),cI(e,s,Vm(t),n,r);if(t instanceof Blob)return aI(e,t,n,r,i);const l=t instanceof ArrayBuffer?new Uint8Array(t):t;return Wm(e,l,n?.contentType,n,r,i)})}async function aI(e,t,n,r,s){if(t.size>Ti)throw Rc(t.size,`uploadBytes payload for '${e.fullPath}'`);const o=n?.contentType??(t.type!==""?t.type:void 0),a=s??om(e.port);try{const l=new Uint8Array(await t.arrayBuffer());return await Wm(e,l,o,n,r,a)}finally{a.release()}}async function Wm(e,t,n,r,s,i){if(t.byteLength>Ti)throw Rc(t.byteLength,`uploadBytes payload for '${e.fullPath}'`);if(t.byteLength<=ya){const u=ye(e.port,{t:"op",id:L(),method:"storage.putBytes",path:e.fullPath,dataB64:Xu(t),...n!==void 0?{contentType:n}:{},...r!==void 0?{metadata:r}:{},...wa(s)},i);return i?.release(),ba(e,await u)}const o=ye(e.port,{t:"op",id:L(),method:"storage.beginUpload",path:e.fullPath,size:t.byteLength,...n!==void 0?{contentType:n}:{},...r!==void 0?{metadata:r}:{}},i);i?.release();const l=(await o).uploadId;try{let u=0,d=0;for(;u<t.byteLength;){const f=Math.min(u+ya,t.byteLength),p=t.subarray(u,f);await ye(e.port,{t:"op",id:L(),method:"storage.putPart",uploadId:l,partIndex:d,dataB64:Xu(p)}),u=f,d++}const h=await ye(e.port,{t:"op",id:L(),method:"storage.finishUpload",uploadId:l,...wa(s)});return ba(e,h)}catch(u){try{await ye(e.port,{t:"op",id:L(),method:"storage.abortUpload",uploadId:l})}catch{}throw u}}async function cI(e,t,n,r,s){if(n.size>Ti)throw Rc(n.size,`uploadBytes payload for '${e.fullPath}'`);const o=r?.contentType??(n.type!==""?n.type:void 0),a=await Lm(e,t,n.size,o,r);try{let l=0;for(;l<a.size;)l=await Bm(a,n,l);return await Fm(a,s)}catch(l){throw await Us(a),l}}async function zm(e){await ye(e.port,{t:"op",id:L(),method:"storage.deleteObject",path:e.fullPath})}function cs(e,t){return{instance:t??("instance"in e?e.instance?.name:void 0)}}async function lI(e,t){return Q(e.port,{t:"op",id:L(),method:"rtdb.adminSnapshot",...cs(e,t)})}async function uI(e,t,n,r){await Q(e.port,{t:"op",id:L(),method:"rtdb.set",path:t,value:n,actAs:{mode:"admin"},...cs(e,r)})}async function dI(e,t,n,r){await Q(e.port,{t:"op",id:L(),method:"rtdb.update",path:t,values:n,actAs:{mode:"admin"},...cs(e,r)})}async function fI(e,t,n){await Q(e.port,{t:"op",id:L(),method:"rtdb.remove",path:t,actAs:{mode:"admin"},...cs(e,n)})}function hI(e,t,n,r,s){const i=dn();return!as(e.port,i,{port:e.port,next:a=>n(a?.value??null),error:r},Cc({t:"sub",subId:i,target:{service:"rtdb",...cs(e,s),path:AN(t)},actAs:{mode:"admin"}}))&&r&&queueMicrotask(()=>r(new Error("FIREBASE FATAL ERROR: Database has been deleted."))),()=>it(e.port,i)}const pI="/__pyric/diagnostics";function mI(e){const t=new URL(e);if(!["http:","https:","ws:","wss:"].includes(t.protocol))throw new Error("Unsupported diagnostic URL scheme.");const r=t.pathname==="/__pyric/sandbox"?t.pathname:"";return`${t.origin}${r}`}function yI(){if(globalThis.__pyricDiagnostics)return globalThis.__pyricDiagnostics;if(typeof location>"u"||!(location.protocol==="http:"||location.protocol==="https:"))return;const t={version:1,clientId:`browser-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,sequence:0,realm:typeof document>"u"?"service-worker":"page",pageOrigin:location.origin,events:[]};let n,r=!1;const s=()=>({...t,events:t.events.map(a=>({...a}))}),i=()=>{n!==void 0||r||(n=setTimeout(()=>{n=void 0,o.flush()},100))},o={getSnapshot:s,record(a){const l=a.endpoint?mI(a.endpoint):void 0;t.sequence+=1,t.events.push({...a,endpoint:l,at:Date.now()}),t.events=t.events.slice(-32),i()},async flush(){if(r)return;r=!0;const a=t.sequence,l=new AbortController,u=setTimeout(()=>l.abort(),2e3);try{await fetch(new URL(pI,location.href),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(s()),signal:l.signal,credentials:"same-origin",keepalive:!0})}catch{}finally{clearTimeout(u),r=!1,t.sequence>a&&i()}}};return globalThis.__pyricDiagnostics=o,globalThis.addEventListener("online",i),globalThis.addEventListener("pagehide",()=>{clearTimeout(n),n=void 0,o.flush()}),o}function gI(e){try{yI()?.record(e)}catch{}}function bI(e){const t=typeof e.bridgeVersion=="string"&&typeof e.peerConnected=="boolean"&&typeof e.clientSessionId=="string",r=[e.projectKey,e.serveVersion,e.sessionId,e.resumeToken,e.hostInstanceId].every(a=>a===void 0||typeof a=="string"),s=e.capabilities,i=s===void 0||Array.isArray(s)&&s.every(a=>typeof a=="string"),o=e.sandboxConnected===void 0||typeof e.sandboxConnected=="boolean";return t&&r&&i&&o}const Vr="Bridge response exceeds the 12 MiB encoded frame limit.",va=4009,_r={code:"resource-exhausted",message:Vr},xa=new TextEncoder;function Hm(e){const t=JSON.stringify(e);if(xa.encode(t).byteLength<=Mr)return t;const r=vI(e),s=JSON.stringify(r);return xa.encode(s).byteLength>Mr?wI(r):s}function wI(e){if(e.type!=="worker-message-result")return;const n=e.message;if(n.t!=="event")return;const s=n.events[0],i=n.events.at(-1);if(s===void 0||i===void 0)return;const a={...e,message:{...n,events:[{kind:"observation_gap",id:`observation-gap:${s.id}:${i.id}`,at:s.at,reason:"frame-limit",omittedCount:n.events.length,firstEventId:s.id,lastEventId:i.id}]}},l=JSON.stringify(a);if(xa.encode(l).byteLength<=Mr)return l}function vI(e){switch(e.type){case"tool-result":return{type:"tool-result",id:e.id,ok:!1,error:_r};case"worker-message-result":return{...e,message:xI(e.message)};case"worker-res":return{type:"worker-res",id:e.id,clientSessionId:e.clientSessionId,ok:!1,error:_r};case"worker-snap":return{...e,value:{__error:_r}};default:return e}}function xI(e){switch(e.t){case"res":return{t:"res",id:e.id,clientSessionId:e.clientSessionId,ok:!1,error:_r};case"snap":return{...e,value:{__error:_r}};case"event":{const t=e.events.map(n=>{if(n.kind==="snapshot_delivery"){const s={...n};return delete s.sample,s}return n});return{...e,events:t}}default:return e}}const ad={"rtdb.set":"resend","rtdb.setPriority":"resend","rtdb.setWithPriority":"resend","rtdb.update":"resend","rtdb.remove":"resend","rtdb.push":"resend","rtdb.get":"resend","rtdb.onDisconnectSet":"forget","rtdb.onDisconnectUpdate":"forget","rtdb.onDisconnectRemove":"forget","rtdb.onDisconnectCancel":"forget","rtdb.transactionCommit":"disconnect"};function _I(e){return Object.hasOwn(ad,e)?ad[e]:"fail"}function SI(e){return e.t==="op"?_I(e.method):"fail"}function kI(e,t,n,r){const s=[];for(const{id:i,message:o}of XC(e,a=>r(a)&&!cm(e,a))){const a=SI(o);a==="resend"?s.push(i):a==="forget"?eN(i):a==="disconnect"?Hu(i,new Error("disconnect")):Hu(i,n)}t.holdAgain(ZC(s))}function jI(e){const t=new URL(e);return t.protocol=t.protocol==="wss:"?"https:":"http:",t.origin}const bo="The hosted sandbox connection was lost. Requests already sent may have completed; check state before retrying.",wo="The hosted sandbox connection is closed.",EI=new TextEncoder;function CI(e,t){const n=`socket-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,r=(M,ne)=>{gI({phase:M,connectionId:n,endpoint:e.url,code:ne})},s=new Set;let i="connecting",o,a,l=e.initialHostInstanceId,u=!1,d,h=!1,f=!1,p=0,m,g,b,w,x=0;const v=e.realm;let _=!1,S=()=>{};const k=new Promise(M=>{S=M}),N=()=>{_=!0,S()},O=M=>(v?.releaseTimer(M),M),P=M=>{v?.traffic(R,M)},R=Object.assign({},{onmessage:null,postMessage(M){if(i==="closed")throw new H("unavailable",wo);M.t==="appConfig"&&(d=M),P({sent:M});const ce=i==="attached";if(!ce&&M.t==="disconnect"){j.drop(),A({t:"res",id:M.id,ok:!0,value:void 0});return}if(!ce){if((M.t==="op"||M.t==="tool")&&!Qe.has(M.id))return;C({type:"worker-message",message:M}),j.hold(M);return}const fe=o;if(fe===void 0)throw new H("unavailable",wo);I(fe,{type:"worker-message",message:M})},start(){},withdrawSubscription(M){return j.forgetSubscription(M)},byteRouteSettled(){return _?void 0:k},observeConnection(M){return s.add(M),queueMicrotask(()=>{s.has(M)&&M(i==="attached")}),()=>{s.delete(M)}},close(){E(new H("unavailable",wo))}}),j=DR(R);function E(M){if(i==="closed")return;i="closed",$(),s.clear(),um(R),j.fail(M),Br(R,M),MN(R,M),a=void 0,m=void 0,l=void 0,u=!1,d=void 0,R.restoreAuth=void 0,R.messagingVisibility=void 0,clearTimeout(g),clearTimeout(b),clearTimeout(w);const ge=o;o=void 0;const ce=ge?.readyState===WebSocket.OPEN;try{ce&&I(ge,{type:"worker-message",message:{t:"disconnect",id:L()}})}catch{}ge?.close(),R.onmessage=null,N(),P({closed:!0})}function $(){r(i),e.onConnection?.(i);const M=i==="attached";for(const ne of[...s])ne(M)}function C(M){const ne=Hm(M);if(ne===void 0)throw new H("resource-exhausted","Bridge request exceeds the 12 MiB encoded frame limit.");return ne}function I(M,ne){M.send(C(ne))}function A(M){R.onmessage?.(new MessageEvent("message",{data:M})),P({})}function D(M){if(i==="closed")return;const ge=new H("unavailable",M);E(ge),e.onError?.(ge)}function T(M){return o===M&&i!=="closed"}function W(M){if(!T(M))return;clearTimeout(g),clearTimeout(w),m??=performance.now(),i="interrupted",o=void 0,$();const ge=new H("unavailable",bo);kI(R,j,ge,ve=>!j.holdsRequest(ve)&&!cm(R,ve)),nN(R,ge,ve=>j.holdsSubscription({t:"unsub",subId:ve})),P({}),M.close();const ce=Math.min(5e3,250*2**p);p+=1;const Z=Math.random()*Math.min(250,ce/10);b=O(setTimeout(Se,Math.min(5e3,ce+Z)))}function U(M){const ne=qu-(performance.now()-x),ge=Math.max(0,Math.min(Zp,ne));w=O(setTimeout(()=>{if(!T(M))return;if(performance.now()-x>=qu){W(M);return}try{I(M,{type:"ping",id:L()})}catch{W(M);return}U(M)},ge))}async function q(M,ne){const ge=ne||p>0,ce=ve=>{if(!T(M))throw new H("unavailable",bo);I(M,{type:"worker-message",message:ve})},Z=ve=>{j.holdsSubscription(ve)||ce(ve)};if(h){i="restoring",r(i),e.onConnection?.(i);const ve=d;if(ve!==void 0&&ce(u?{...ve,fromPriorHost:!0}:ve),await R.restoreAuth?.(wt=>Di(R,wt,ce)),!T(M))return;QC(R,Z),h=!1}clearTimeout(g),i="attached",f=!0,p=0,m=void 0,x=performance.now(),clearTimeout(w),U(M),ne&&(ce({t:"clock-subscribe"}),YC(R,Z)),ge&&JC(R,Z),j.flush(ce),$()}async function F(){const M=e.currentHostInstanceId;if(!(f&&M!==void 0))return l;try{return await M()??l}catch{return l}}function Se(){if(i==="closed")return;i="connecting",r("connecting");const ne=f?"interrupted":"connecting";e.onConnection?.(ne),m!==void 0&&performance.now()-m>=OC&&(a=void 0);const ce=a===void 0;let Z;try{Z=v?v.createSocket(e.url):new WebSocket(e.url)}catch(fe){throw r("socket-error"),fe}o=Z,g=O(setTimeout(()=>{if(!T(Z))return;r("timeout"),f||e.retryInitialConnection===!0?W(Z):D("Timed out connecting to the hosted sandbox.")},5e3)),Z.addEventListener("error",()=>{T(Z)&&r("socket-error")});let ve=l;Z.addEventListener("open",()=>{T(Z)&&(r("transport-open"),F().then(et=>{if(!T(Z))return;ve=et,et!==l&&(a=void 0),I(Z,{type:"attach",protocol:1,transport:"worker-port",resumeToken:a,hostInstanceId:et,clientInfo:{platform:v?.platform??"browser"}})}))}),Z.addEventListener("message",fe=>{if(!T(Z))return;if(EI.encode(fe.data).byteLength>Mr){Z.close(va,Vr),D(Vr);return}let ut;try{ut=JSON.parse(fe.data)}catch{D("The hosted sandbox sent invalid JSON. Requests already sent may have completed; check state before retrying.");return}const ie=ut;if(!em(ie)){D("The hosted sandbox sent an invalid message. Requests already sent may have completed; check state before retrying.");return}switch(x=performance.now(),ie.type){case"attach-ack":{if(ie.protocol!==1){D("The hosted sandbox uses an unsupported bridge protocol. Expected version 1.");return}const Jn=ie.capabilities;if(!(Array.isArray(Jn)&&Jn.every(sl=>typeof sl=="string")&&Jn.includes(AC))){D("The selected host does not support browser worker ports. Upgrade @pyric/cli, restart with --hosted, and reload this page.");return}const wb=Jn.includes(IC),rl=e.sessionToken;if(wb&&rl!==void 0?R.byteRoute={baseUrl:jI(e.url),sessionToken:rl}:delete R.byteRoute,N(),v?.attached?.(ie),ie.projectKey!==e.projectKey){D("The selected hosted sandbox belongs to a different project.");return}if(!bI(ie)){D("The hosted sandbox sent a malformed attachment acknowledgment.");return}const us=f,Gi=typeof ie.hostInstanceId=="string"&&ie.hostInstanceId.length>0,Ji=us&&l!==void 0&&Gi&&ie.hostInstanceId!==l,vb=Gi&&ie.hostInstanceId===ve;Ji&&!vb&&(u=!0);const xb=us&&!ce,_b=ie.resumeToken!==a;if(xb&&_b&&!Ji){D("The hosted session could not be resumed.");return}a=typeof ie.resumeToken=="string"&&ie.resumeToken.length>0?ie.resumeToken:void 0,l=Gi?ie.hostInstanceId:void 0,us&&(Ji||ce)&&(h=!0),q(Z,us).catch(()=>{T(Z)&&D("Could not restore the hosted app session.")});return}case"worker-message-result":{const Ge=ie.message;rm(Ge)&&Ge.t==="res"&&nm(Ge)&&Ge.ok===!1&&(Ge.error.code==="committed-but-not-durable"||Ge.error.code==="persistence-unhealthy")&&e.onError?.(new H(Ge.error.code,Ge.error.message)),A(Ge);return}}}),Z.addEventListener("close",fe=>{if(!T(Z))return;r("socket-close",fe.code),clearTimeout(g),f&&fe.code===$C&&(a=void 0),(f||e.retryInitialConnection===!0)&&fe.code!==1008?W(Z):D(bo)})}const we={__kind:"client-db",port:R};return Pi(R),Se(),we}function NI(){if(!(typeof document<"u"))return null;const n=document.querySelector('meta[name="pyric-sandbox-host"]');if(!(n?.getAttribute("content")==="node"))return null;const i=n.getAttribute("data-project-key");if(!(i!==null&&i.length>0))throw new Error("The hosted sandbox has no project identity. Restart the host and reload Studio.");return{url:`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}/__pyric/sandbox`,projectKey:i}}function RI(e){const t=new Set;let n={mode:"hosted",servedEpoch:null,runningEpoch:null,updateAvailable:!1,updating:!1,error:"Connecting to the hosted sandbox."};function r(o){n={...n,error:o};for(const a of t)a()}return{db:CI({...e,sessionToken:()=>Oi(location.origin),onConnection(o){switch(o){case"attached":r(null);return;case"connecting":r("Connecting to the hosted sandbox.");return;case"restoring":r("Restoring the hosted session.");return;case"interrupted":r("Hosted connection lost; reconnecting.");return;case"closed":r("Hosted connection closed. Repair the host and reload Studio.");return}},onError:o=>r(o.message)}),runtime:{getSnapshot:()=>n,subscribe(o){return t.add(o),()=>{t.delete(o)}},async update(){throw new Error("Restart the hosted sandbox and reload Studio to update it.")},dispose(){t.clear()}}}}function II(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 o=null;const a=()=>i?(o??=dC({targetEpoch:i,retire:()=>e.retire?e.retire(i):lN(e.db,i),subscribeReload:e.subscribeReload??uN,preflight:e.preflight??(()=>uC(s)),commitGeneration:e.remember??(l=>lC(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}:{}}),o):null;return(e.readVersion??(()=>vN(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),a(),()=>{t.delete(l),t.size===0&&(o?.dispose(),o=null)}},async update(){const l=a();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(),o?.dispose(),o=null}}}function AI(e={}){const t=Qp(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:cC(t.worker.servedEpoch,n)}}const OI="/__pyric/sdk/worker.js";function $I(e){const t=new ch(lh);let n=!1;const r=new Set;let s=null;function i(){s||(s=hR(e,o=>{const a=!n;n=!0,a&&t.clear();for(const l of o)zp(l)&&t.clear(),t.append(l);for(const l of o)for(const u of r)u(l)}))}return{history:()=>t.snapshot(),subscribe:o=>(r.add(o),i(),()=>{r.delete(o),r.size===0&&s&&(s(),s=null,n=!1,t.clear())})}}function cd(e){let t=!1,n=null;const r=()=>{t=!0;const s=(async()=>e())(),i=()=>{t=!1;const o=n;n=null,o&&r().then(o.resolve,o.reject)};return s.then(i,i),s};return()=>{if(!t)return r();if(!n){let s,i;n={promise:new Promise((a,l)=>{s=a,i=l}),resolve:s,reject:i}}return n.promise}}function PI(e=OI){const t=NI(),n=t!==null;if(!n&&typeof SharedWorker>"u")return null;aN("studio");const s=n?RI(t):null;let i;if(s!==null)i=s.db;else try{const m=AI({workerUrl:e});i=wN(m.url,m.name)}catch{return null}let a;try{a=typeof localStorage<"u"?localStorage:void 0}catch{a=void 0}const l=typeof document<"u",u=s?.runtime??II({db:i,servedEpoch:Qp(l?document:void 0).worker.servedEpoch,storage:a});Gu({mode:"admin"});const d=vR({db:i,kind:"studio"}),h=$I(i),f=AR(i);let p=!1;return{db:i,runtime:u,dispose:async()=>{p||(p=!0,d.stop(),u.dispose(),await TN(i).catch(()=>{}))},presenceClientId:d.clientId,subscribePresence:m=>xR(i,m),instanceId:()=>xN(i),exportState:()=>_N(i),importState:m=>SN(i,m),saveState:m=>kN(i,m),listStates:()=>jN(i),restoreState:m=>EN(i,m),deleteState:m=>CN(i,m),feed:h,setLens:m=>Gu(m),getLens:()=>oN(),listRootCollections:cd(()=>sR(i)),listSubcollections:m=>iR(i,m),listDocuments:async m=>(await uR(i,m)).map(({path:g,phantom:b})=>({path:g,phantom:b})),readRtdbState:()=>lI(i),setRtdbValue:(m,g)=>uI(i,m,g),updateRtdbValue:(m,g)=>dI(i,m,g),deleteRtdbValue:m=>fI(i,m),subscribeRtdbValue:(m,g,b)=>hI(i,m,g,b),firestoreApi:{collection:zN,doc:WN,getDoc:eR,getDocs:nR,onSnapshot:oR,setDoc:aR,deleteDoc:cR,addDoc:lR,query:ZN,limit:QN,startAfter:XN},auth:f,authApi:{listUsers:cd(()=>_R(f)),subscribeUsers:(m,g)=>h.subscribe(b=>{b.kind==="service_mutation"&&b.service==="auth"&&g()}),createUser:(m,g)=>SR(f,g),updateUser:(m,g,b)=>kR(f,g,b),deleteUser:(m,g)=>jR(f,g),clearUsers:()=>ER(f),getAuthProviderConfig:()=>CR(f),setAuthProviderConfig:(m,g,b)=>NR(f,g,b),subscribeAuthProviderConfig:(m,g)=>h.subscribe(b=>{b.kind==="service_mutation"&&b.op==="provider_config_update"&&g()})},storage:JR(i),storageApi:{ref:YR,listAll:QR,getMetadata:Tm,getBlob:rI,uploadBytes:oI,uploadBytesResumable:KR,deleteObject:zm},getSnapshot:()=>mR(i),resetAll:()=>yR(i)}}function Km(e,t,n,r){const s={uid:e};n!==void 0&&(s.token={...n}),t!==void 0&&(s.tenant=t);const i=vi(s);if(i===null)throw new Error("projectIdentity requires a uid");const o={uid:i.uid,token:i.token??{}};return i.tenant!==void 0&&(o.tenant=i.tenant),o}const DI={transport:"in-process",order:80,tools:{auth_impersonate:"write",auth_reset:"write",auth_whoami:"read",auth_sessions:"read"}},TI={transport:"forwarded",order:70,tools:{auth_create_user:"write",auth_import_users:"write",auth_get_user:"read",auth_list_users:"read",auth_update_user:"write",auth_delete_user:"write",auth_set_claims:"write",auth_custom_token:"read"}},MI={transport:"in-process",order:90,tools:{sandbox_save_capture:"write",sandbox_list_captures:"read",sandbox_open_capture:"read",sandbox_rename_capture:"write",sandbox_delete_capture:"write"}},LI={transport:"in-process",order:60,tools:{pyric_can_i_use:"read"}},UI={transport:"forwarded",order:20,tools:{firestore_get_document:"read",firestore_list_documents:"read",firestore_create_document:"write",firestore_add_document:"write",firestore_update_document:"write",firestore_delete_document:"write",firestore_batch_write:"write",firestore_query_where:"read"}},BI={transport:"forwarded",order:30,tools:{sandbox_inspect:"read"}},FI={transport:"in-process",order:50,tools:{firestore_simulate_rules:"read",firestore_rules_stdlib_list:"read",firestore_rules_stdlib_get:"read",firestore_lint_rules:"read",firestore_resolve_modules:"read",rules_stdlib_list:"read",rules_stdlib_get:"read",rules_resolve_modules:"read"}},VI={transport:"forwarded",order:10,tools:{firestore_simulator_create:"write",firestore_simulator_execute:"write",firestore_simulator_read:"read",firestore_simulator_batch:"write",firestore_create_with_auto_id:"write",firestore_simulator_undo:"write",firestore_simulator_redo:"write",firestore_simulator_events:"read",firestore_simulator_transaction:"write"}},qI={transport:"forwarded",order:100,tools:{messaging_deliveries:"read"}},WI={transport:"forwarded",order:40,tools:{rtdb_simulate_access:"read",rtdb_crawl_structure:"read"}},zI=[{key:"auth-identity",...DI},{key:"auth-users",...TI},{key:"captures",...MI},{key:"conformance",...LI},{key:"firestore-data",...UI},{key:"firestore-inspect",...BI},{key:"firestore-rules",...FI},{key:"firestore-simulator",...VI},{key:"messaging-inspection",...qI},{key:"rtdb-inspection",...WI}];function vo(e,t){const n=new Set;for(const r of t){if(n.has(r))throw new Error(`duplicate tool family ${e} '${r}'`);n.add(r)}}function HI(e){return vo("key",e.map(t=>t.key)),vo("order",e.map(t=>t.order)),vo("tool name",e.flatMap(t=>Object.keys(t.tools))),[...e].sort((t,n)=>t.order-n.order)}const KI=HI(zI);function Gm(e){return KI.filter(t=>t.transport===e)}function GI(e,t,n){const r=[...t].sort(),s=[...n].sort();if(r.length!==s.length||r.some((i,o)=>i!==s[o]))throw new Error(`${e} drifted from the default MCP contract
|
|
129
129
|
expected: ${n.join(", ")}
|
|
130
|
-
actual: ${t.join(", ")}`)}function zI(e){const t=e.detail??{};return{messageId:String(t.messageId),recipientId:String(t.recipientId??"sandbox-default"),receipt:"unconfirmed",acknowledgments:[],route:t.route,handled:t.handled===!0,at:e.at,payload:t.payload}}function HI(e,t){const n=e.filter(a=>a.kind==="service_mutation"&&a.service==="messaging"),r=new Map,s=(a,l)=>JSON.stringify([a,l]);for(const a of n){if(a.op!=="delivery_acknowledged")continue;const u=a.detail??{},d=s(u.messageId,u.recipientId),h=r.get(d)??[];h.push({observerId:String(u.observerId),stage:u.stage,at:a.at}),r.set(d,h)}const i=n.filter(a=>a.op==="message_delivered").map(a=>{const l=zI(a);l.acknowledgments=r.get(s(l.messageId,l.recipientId))??[];const u=l.acknowledgments.some(d=>d.stage==="received");return l.receipt=u?"received":"unconfirmed",l});return t===void 0?i:i.filter(a=>a.at>=t)}const cd="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",KI=142,ld="APA91b",ud=22;function dd(e){const t=new Uint8Array(e);crypto.getRandomValues(t);let n="";for(let r=0;r<e;r++)n+=cd[t[r]%cd.length];return n}function GI(){const e=dd(ud),t=KI-ud-1-ld.length;return`${e}:${ld}${dd(t)}`}const JI="pyric-sandbox",YI="999999999999",nr="sandbox-default",QI=null;class XI{projectId;senderId;sandbox;registrations=new Map;tokenRecords=new Map;subscriptions=new Map;clients=new Map;foregroundHandlers=new Map;backgroundHandlers=new Map;numericIdCounter=0;changeListeners=new Set;constructor(t={}){this.projectId=t.projectId??JI,this.senderId=t.senderId??YI,this.sandbox=t.sandbox}snapshot(){return{version:1,tokens:[...this.tokenRecords].map(([t,n])=>[t,{...n}]),topics:[...this.subscriptions].map(([t,n])=>[t,[...n]])}}restore(t){if(!RS(t))throw new Error("Invalid Messaging persistence snapshot.");this.registrations.clear(),this.tokenRecords.clear(),this.subscriptions.clear();for(const[n,r]of t.tokens)this.tokenRecords.set(n,{...r}),r.state==="active"&&this.registrations.set(r.registrationId,n);for(const[n,r]of t.topics)this.subscriptions.set(n,new Set(r))}reset(){this.registrations.clear(),this.tokenRecords.clear(),this.subscriptions.clear(),this.changed()}onChange(t){return this.changeListeners.add(t),()=>this.changeListeners.delete(t)}changed(){for(const t of this.changeListeners)t()}getTokenFor(t,n=nr){const r=this.registrations.get(t);if(r!==void 0)return r;const s=GI();return this.registrations.set(t,s),this.tokenRecords.set(s,{registrationId:t,recipientId:n,state:"active"}),this.changed(),this.emit("token_minted",{path:s,detail:{registrationId:t}}),s}deleteTokenFor(t){const n=this.registrations.get(t);if(n===void 0)return!0;this.registrations.delete(t);const r=this.tokenRecords.get(n);return r!==void 0&&(r.state="unregistered"),this.changed(),this.emit("token_deleted",{path:n,detail:{registrationId:t}}),!0}tokenState(t){return this.tokenRecords.get(t)?.state??"unknown"}subscribeToTopic(t,n){return this.mutateSubscriptions(t,n,"subscribe")}unsubscribeFromTopic(t,n){return this.mutateSubscriptions(t,n,"unsubscribe")}mutateSubscriptions(t,n,r){if(!ji(n))throw new tt(tp());const s=pc(n),i=this.subscriptions.get(s)??new Set;this.subscriptions.set(s,i);const o={successCount:0,failureCount:0,errors:[]};return t.forEach((a,l)=>{if(!ki.test(a)){o.failureCount++,o.errors.push({index:l,reason:"invalid-token"});return}if(this.tokenState(a)==="unregistered"){o.failureCount++,o.errors.push({index:l,reason:"unregistered-token"});return}r==="subscribe"?i.add(a):i.delete(a),o.successCount++}),this.changed(),this.emit("subscription_changed",{path:s,detail:{action:r,tokenCount:t.length,successCount:o.successCount,failureCount:o.failureCount}}),o}topicsOf(t){const n=new Set;for(const[r,s]of this.subscriptions)s.has(t)&&n.add(r);return n}tokens(){const t=new Set(this.tokenRecords.keys());for(const n of this.subscriptions.values())for(const r of n)t.add(r);return[...t].sort().map(n=>({token:n,state:this.tokenState(n),topics:[...this.topicsOf(n)].sort()}))}send(t,n={}){const r=n.validateOnly===!0;let s;try{if(s=jS(t),s.kind==="token"&&this.tokenState(s.token)!=="active")throw new tt(wS())}catch(a){throw a instanceof tt&&this.emit("message_rejected",{detail:{status:a.envelope.status,errorStatus:a.envelope.error.status,errorCode:a.errorCode,message:a.envelope.error.message,validateOnly:r}}),a}const i=s.kind==="token"?crypto.randomUUID():this.mintNumericId(),o={name:`projects/${this.projectId}/messages/${i}`,messageId:i,target:s,validateOnly:r};if(this.emit("message_accepted",{path:ZI(s),detail:{target:s.kind,name:o.name,messageId:i,validateOnly:r}}),!r){const a=this.toPayload(t,i);for(const l of this.matchingRecipients(s))this.route(a,l)}return o}mintNumericId(){return this.numericIdCounter=(this.numericIdCounter+1)%1e6,`${Date.now()}${String(this.numericIdCounter).padStart(6,"0")}`}matchingRecipients(t){const n=new Set;for(const[r,s]of this.tokenRecords){if(!(s.state==="active"))continue;let o;switch(t.kind){case"token":o=r===t.token;break;case"topic":o=this.subscriptions.get(t.topic)?.has(r)===!0;break;case"condition":o=eA(t.condition,this.topicsOf(r));break}o&&n.add(s.recipientId)}return n}toPayload(t,n){const r={from:this.senderId,messageId:n};if(t.data!==void 0&&(r.data={...t.data}),t.notification!==void 0){const{title:s,body:i,imageUrl:o}=t.notification;r.notification={...s!==void 0?{title:s}:{},...i!==void 0?{body:i}:{},...o!==void 0?{image:o}:{}}}return r}setClientVisibility(t,n,r=nr){this.clients.set(t,{state:n,recipientId:r})}removeClient(t){this.clients.delete(t)}onForegroundMessage(t,n=nr){return this.foregroundHandlers.set(t,n),()=>this.foregroundHandlers.delete(t)}onBackgroundMessage(t,n=nr){return this.backgroundHandlers.set(t,n),()=>this.backgroundHandlers.delete(t)}deliver(t,n=nr){const r={from:t.from??this.senderId,messageId:t.messageId??crypto.randomUUID()};return t.data!==void 0&&(r.data={...t.data}),t.notification!==void 0&&(r.notification={...t.notification}),this.route(r,n)}route(t,n){let r=!1;for(const a of this.clients.values())if(a.recipientId===n&&a.state==="visible"){r=!0;break}const s=r?"foreground":"background",i=s==="foreground"?this.foregroundHandlers:this.backgroundHandlers;this.emit("delivery_routed",{detail:{route:s,recipientId:n,visibleClient:r,messageId:t.messageId}});let o=0;for(const[a,l]of[...i])if(l===n){o++;try{a(structuredClone(t))}catch{}}return this.emit("message_delivered",{detail:{recipientId:n,route:s,handlerCount:o,handled:o>0,messageId:t.messageId,payload:structuredClone(t)}}),{route:s,handlerCount:o,payload:t}}acknowledge(t,n,r,s){this.emit("delivery_acknowledged",{detail:{messageId:t,recipientId:n,observerId:r,stage:s}})}deliveries(t){return HI(this.sandbox?.history()??[],t)}emit(t,n){if(this.sandbox!==void 0)try{pt(this.sandbox,Ln({at:Te(this.sandbox).now(),service:"messaging",op:t,auth:QI,...n}),{service:"messaging"})}catch{}}}function ZI(e){return e.kind==="token"?e.token:e.kind==="topic"?e.topic:e.condition}function eA(e,t){const n=e;let r=0;function s(){for(;r<n.length&&/\s/.test(n[r]);)r++}function i(l){return s(),n.startsWith(l,r)?(r+=l.length,!0):!1}function o(){if(s(),i("!"))return!o();if(i("(")){const d=a();return i(")"),d}s(),r++;const l=r;for(;r<n.length&&n[r]!=="'";)r++;const u=n.slice(l,r);return r++,i("in"),i("topics"),t.has(u)}function a(){let l=o();for(;;){if(s(),i("&&")){const u=o();l=l&&u;continue}if(i("||")){const u=o();l=l||u;continue}return l}}return a()}const fd=new WeakMap;function tA(e,t){const n=fd.get(e);if(n!==void 0)return n;const r=new XI({...t,sandbox:e});return fd.set(e,r),e.registerPersistableService("messaging",{snapshot:()=>r.snapshot(),restore:s=>r.restore(s),reset:()=>r.reset(),subscribe:s=>r.onChange(s)}),r}function nA(e){return[{name:"messaging_deliveries",description:"Inspect message routing and browser-reported receipt, callback and native display outcomes. handled only means a broker handler ran; display-accepted is not proof of OS visibility. Missing receipt is unconfirmed.",parameters:{type:"object",properties:{}},async execute(){const t=await e(),n=tA(t).deliveries();return{ok:!0,summary:`${n.length} deliveries`,data:{deliveries:n}}}}]}class xa extends Error{issues;constructor(t,n){super(t),this.name="RulesCompileError",this.issues=n}}function rA(e){const t=e.severity==="critical"||e.severity==="high"?"error":e.severity==="medium"?"warning":"info";return{code:e.code,severity:t,message:e.message,path:e.path,origin:"validate"}}function sA(e){return{...rA(e),rule:e.rule,fix:e.fix}}const iA=new Set(["PARSE_ERROR","COMPILE_ERROR"]);function hd(e,t){const n=t==="warning"?"lint":iA.has(e.code)?"parse":"validate",r={code:e.code,severity:t,message:e.message,path:e.path,origin:n};return e.rule!=="ruleset"&&(r.rule=e.rule),r}const oA="/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/";function Hm(e,t){if(!(e instanceof ol)){const l=e?.constructor?.name??typeof e;throw new Error(`Unsupported Zod schema for RTDB rules: expected ZodObject, got ${l}`)}const n=e._def;if(n.catchall&&!(n.catchall instanceof ww))throw new Error("Unsupported Zod object catchall for RTDB rules");const r=e.shape;if(t){for(const l of Object.keys(t))if(!(l in r))throw new Error(`fieldConstraints: field "${l}" is not in schema.`)}const s=[],i={};for(const[l,u]of Object.entries(r)){Iv("schemaRules",l);const d=u,h=d instanceof vw,f=h?d.unwrap():d;h||s.push(l);const p=t?.[l];if(f instanceof ol){const m=Hm(f);let g=m.validate;p&&p.length>0&&(g=In(m.validate,...p)),i[l]={validate:g,children:m.children}}else{const m=Km(f,l);p&&p.length>0?i[l]={validate:In(m,...p)}:i[l]={validate:m}}}n?.unknownKeys==="strict"&&(i.$other={validate:ae("false")});const o=[rx()];for(const l of s)o.push(sx(l));return{validate:In(...o),children:i}}function aA(e,t){const n=[ae("newData.isString()")];for(const r of e._def.checks)if(r.kind==="min")n.push(ae(`newData.val().length >= ${Ye(r.value)}`));else if(r.kind==="max")n.push(ae(`newData.val().length <= ${Ye(r.value)}`));else if(r.kind==="length")n.push(ae(`newData.val().length == ${Ye(r.value)}`));else if(r.kind==="regex"){const s=r.regex;if(!sc(s.flags))throw new Error(`Unsupported Zod regex flags "${s.flags}" on field "${t}"; RTDB rules only support the "i" flag`);if(/[\r\n]/.test(s.source))throw new Error(`Unsupported Zod regex with newline on field "${t}"`);n.push(ae(`newData.val().matches(/${s.source}/${s.flags})`))}else if(r.kind==="email")n.push(ae(`newData.val().matches(${oA})`));else if(r.kind==="startsWith")n.push(ae(`newData.val().beginsWith(${Ye(r.value)})`));else if(r.kind==="endsWith")n.push(ae(`newData.val().endsWith(${Ye(r.value)})`));else if(r.kind==="includes")n.push(ae(`newData.val().contains(${Ye(r.value)})`));else throw new Error(`Unsupported Zod string check "${String(r.kind)}" for RTDB rules on field "${t}"`);return In(...n)}function cA(e,t){const n=[ae("newData.isNumber()")];for(const r of e._def.checks)if(r.kind==="min"){const s=r.inclusive===!1?">":">=";n.push(ae(`newData.val() ${s} ${Ye(r.value)}`))}else if(r.kind==="max"){const s=r.inclusive===!1?"<":"<=";n.push(ae(`newData.val() ${s} ${Ye(r.value)}`))}else if(r.kind==="int")n.push(ae("newData.val() % 1 == 0"));else if(r.kind==="multipleOf")n.push(ae(`newData.val() % ${Ye(r.value)} == 0`));else throw new Error(`Unsupported Zod number check "${String(r.kind)}" for RTDB rules on field "${t}"`);return In(...n)}function Km(e,t){if(e instanceof xw)return aA(e,t);if(e instanceof _w)return cA(e,t);if(e instanceof Sw)return ae("newData.isBoolean()");if(e instanceof kw){const n=e.options;return pl(...n.map(r=>ae(`newData.val() == ${Ye(r)}`)))}if(e instanceof jw){const n=e.value;return ae(`newData.val() == ${Ye(n)}`)}if(e instanceof Ew){const n=e._def.options;return pl(...n.map(r=>Km(r,t)))}throw new Error(`Unsupported Zod type for RTDB rules: ${e.constructor.name} on field "${t}"`)}function lA(e){let t;if(typeof e=="function"){const s=[];e({path:(i,o)=>s.push([i,o])}),t=s}else t=Object.entries(e);const n=Ym(t);pA(n),n.sort((s,i)=>{const o=pd(s[0]),a=pd(i[0]);return o-a||s[0].localeCompare(i[0])});const r={path:"/",pathVariables:[],children:[]};for(const[s]of n)s!=="/"&&uA(r,s);for(const[s,i]of n){const o=Oc(r,s);o&&dA(r,o,i,s)}return r}function uA(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("/"),o=n.slice(0,s+1).filter(l=>l.startsWith("$"));let a=r.children.find(l=>l.path===i);a||(a={path:i,pathVariables:o,children:[]},r.children.push(a)),r=a}}function _a(e,t,n){const r=e.validate?In(ae(e.validate.raw),t):t;e.validate=Sa(r,"validate",n)}function Gm(e,t,n){for(const[r,s]of Object.entries(t)){const i=Jm(`${e.path}/${r}`),o=r.startsWith("$")?[...n,r]:n;let a=e.children.find(l=>l.path===i);a||(a={path:i,pathVariables:o,children:[]},e.children.push(a)),_a(a,s.validate,o),s.children&&Gm(a,s.children,o)}}function dA(e,t,n,r){const s=r.split("/").filter(Boolean),i=s.filter(o=>o.startsWith("$"));if(n.fieldConstraints&&!n.schema)throw new Error(`fieldConstraints on "${r}" requires a schema.`);if(n.read&&(t.read=Sa(n.read,"read",i)),n.write&&(t.write=Sa(n.write,"write",i)),n.validate&&_a(t,n.validate,i),n.schema){const o=Hm(n.schema,n.fieldConstraints);_a(t,o.validate,i),Gm(t,o.children,i)}if(n.indexOn){const o=fA(e,t,s);if(o){if(!o.indexOn)o.indexOn=[...n.indexOn];else if(!hA(o.indexOn,n.indexOn))throw new Error(`Conflicting indexOn declarations for "${o.path}": ${JSON.stringify(o.indexOn)} vs ${JSON.stringify(n.indexOn)}`)}}}function fA(e,t,n){if(n[n.length-1]?.startsWith("$")){const s="/"+n.slice(0,-1).join("/");return Oc(e,s)}return t}function hA(e,t){return e.length===t.length&&e.every((n,r)=>n===t[r])}function Jm(e){return"/"+e.split("/").filter(Boolean).join("/")}function pd(e){return e.split("/").filter(Boolean).length}function pA(e){const t=new Set;for(const[n]of e){if(t.has(n))throw new Error(`Duplicate ruleset path declaration for "${n}"`);t.add(n)}}function Ym(e){const t=[];for(const[n,r]of e){const s=Jm(n),{children:i,...o}=r;if(t.push([s,o]),i){const a=Object.entries(i).map(([l,u])=>[`${s}/${l}`,u]);t.push(...Ym(a))}}return t}function Sa(e,t,n){return Hh(String(e),t,n)}function Oc(e,t){if(e.path===t)return e;for(const n of e.children){const r=Oc(n,t);if(r)return r}return null}function mA(e){if(e==null)return null;if(typeof e=="string")return{uid:e,token:{}};const t={uid:e.uid,token:e.token??{}};return e.tenant!==void 0&&(t.tenant=e.tenant),t}function yA(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&e.__type==="serverTimestamp"}function fi(e){if(yA(e))return{".sv":"timestamp"};if(Array.isArray(e))return e.map(fi);if(typeof e=="object"&&e!==null){const t={};for(const[n,r]of Object.entries(e))t[n]=fi(r);return t}return e}function Qm(e){const t={operation:e.operation,path:e.path,auth:mA(e.auth),mockData:e.mockData??e.data??{}};return e.newData!==void 0&&(t.newData=fi(e.newData)),e.now!==void 0&&(t.now=e.now),e.updates!==void 0&&(t.updates=e.updates.map(n=>({path:n.path,value:fi(n.value)}))),e.query!==void 0&&(t.query=e.query),t}function vo(e,t,n,r){return(n?.parsed[r]??[]).map(s=>({path:e,rule:t,code:s.code,message:s.message}))}function ka(e,t){const n=[...vo(e.path,".read",e.read,t),...vo(e.path,".write",e.write,t),...vo(e.path,".validate",e.validate,t),...(e.structure??[]).filter(r=>r.severity===(t==="errors"?"error":"warning")).map(r=>({path:r.path,rule:"ruleset",code:r.code,message:r.message}))];for(const r of e.children)n.push(...ka(r,t));return n}function Xm(e){let t;try{t=e()}catch(s){return{ok:!1,errors:[{path:"/",rule:"ruleset",code:"COMPILE_ERROR",message:s instanceof Error?s.message:String(s)}],warnings:[]}}const n=ka(t,"errors"),r=ka(t,"warnings");return{ok:n.length===0,errors:n,warnings:r}}function Zm(e){const t={};e.read&&(t[".read"]=e.read.raw),e.write&&(t[".write"]=e.write.raw),e.validate&&(t[".validate"]=e.validate.raw),e.indexOn&&(t[".indexOn"]=e.indexOn);for(const r of e.children){const s=r.path.slice(r.path.lastIndexOf("/")+1);t[s]={},Zm(r)}const n=gh(e.path,t);return n.length>0&&(e.structure=n),e}class gA{definition;compiled;constructor(t){this.definition=t}compile(){return this.compiled??=Zm(lA(this.definition.paths)),this.compiled}toJSON(){return M_(this.compile())}check(){return Xm(()=>this.compile())}simulate(t){return dc(this.compile(),Qm(t))}}function bA(e){return new gA(e)}function rn(e){return{success:!1,error:{code:"INVALID_INPUT",message:e,recoverable:!0}}}function md(e){return e.split("/").filter(Boolean)}function wA(e){return`/${e.join("/")}`}function vA(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function xA(e){if(typeof e!="object"||e===null)return!1;const t=e.path;return typeof t=="string"&&t.length>0&&t.startsWith("/")}function _A(e){if(!Array.isArray(e))return"'updates' must be an array of { path, value } entries.";for(const t of e)if(!xA(t))return"each 'updates' entry needs an absolute 'path' starting with '/'.";return null}function ey(e){const t={operation:e.operation==="update"?"write":e.operation,path:e.path,auth:e.auth??null};return e.data!==void 0&&(t.data=e.data),e.newData!==void 0&&(t.newData=e.newData),e.now!==void 0&&(t.now=e.now),t}function SA(e,t){if(!vA(t.newData))return rn("an 'update' case needs newData to be an object keyed by the paths it writes.");const n=md(t.path),r=Object.entries(t.newData).map(([u,d])=>({path:wA([...n,...md(u)]),value:d}));if(r.length===0)return rn("an 'update' case needs newData to name at least one path.");let s,i;const o=[];let a=[];for(const u of r){const d=ey(t);d.path=u.path,d.newData=u.value,d.updates=r;const h=e.simulate(d);if(!h.success)return h;const f=h.data.trace.filter(m=>m.kind==="write"),p=h.data.trace.filter(m=>m.kind==="validate");if(o.push(...f),!h.data.allowed||h.data.unsupported===!0){if(p.length===0)return{success:!0,data:{...h.data,trace:o}};i??={result:h,validates:p};continue}a=p,s??=h}return i?{success:!0,data:{...i.result.data,trace:[...o,...i.validates]}}:{success:!0,data:{...s.data,trace:[...o,...a]}}}function kA(e,t){if(t.query!==void 0){if(t.operation!=="read")return rn(`a query applies to a 'read' case, and this case is '${t.operation}'.`);const r=Bh(t.query);if(r!==null)return rn(r)}if(t.updates!==void 0){if(t.operation!=="write"&&t.operation!=="validate")return rn(`'updates' applies to a 'write' or 'validate' case, and this case is '${t.operation}'.`);const r=_A(t.updates);if(r!==null)return rn(r)}if(t.operation==="update")return SA(e,t);const n=ey(t);return t.query!==void 0&&(n.query={...t.query}),t.updates!==void 0&&(n.updates=t.updates),e.simulate(n)}function ja(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function jA(e){if(!ja(e))return!1;const t=Object.keys(e);return t.length===1&&t[0]==="instances"&&ja(e.instances)}function yd(e,t,n){if(typeof e!="string")return{problem:'instance must be a string naming a database instance, such as "my-app-default-rtdb".'};try{const r=Ax(e)?.name;return{name:r===void 0||Dh(r,n)?t:r}}catch(r){const s=r instanceof Error?r.message.trim():String(r);return{problem:`"${e}" is not a database instance name: ${s}`}}}function Ea(e){return[...e].map(t=>`"${t}"`).join(", ")}function ty(e,t,n){if(e.kind==="every-instance")return e.rules;const r=e.instances.get(t);if(r!==void 0)return r;const s=e.instances.size===0?"it declares no instances":`it holds rules for ${Ea(e.instances.keys())}`;return{problem:`this ruleset has no rules for ${n?`database instance "${t}"`:`the default instance "${t}"`}; ${s}.`}}function EA(e,t){const n=e.kind==="per-instance",r=n?e.defaultInstance:Oh,s=n?e.projectId:void 0;let i;if(t.instance!==void 0){const d=yd(t.instance,r,s);if("problem"in d)return d;i=d.name}else n&&(i=r);const o=d=>i===void 0?d:{...d,instance:i},a=ty(e,i??r,t.instance!==void 0);if("problem"in a)return o(a);const l={...t};if(i!==void 0&&jA(t.data)){const d=new Map;for(const[f,p]of Object.entries(t.data.instances)){const m=yd(f,r,s);if("problem"in m)return o({problem:`data.instances: ${m.problem}`});if(!ja(p))return o({problem:`data.instances["${f}"] must be an object: the tree of database instance "${m.name}".`});d.set(m.name,p)}if(e.kind==="per-instance"){const f=[...d.keys()].filter(p=>!e.instances.has(p));if(f.length>0)return o({problem:`data.instances names ${Ea(f)}, which this ruleset does not declare; it holds rules for ${Ea(e.instances.keys())}.`})}const h=d.get(i);h===void 0?delete l.data:l.data=h}return o({rules:a,evaluated:l})}const tn="rtdbRules.fromFirebaseJson";function CA(){const e=globalThis.process?.getBuiltinModule,t=typeof e=="function"?e.call(process,"node:fs"):void 0,n=typeof e=="function"?e.call(process,"node:path"):void 0;if(t===void 0||n===void 0)throw new Error(`${tn} reads files, which needs Node.js 20.16 or later, Bun or Deno. Without a file system, pass each instance's rules text to rtdbRules.`);return{fs:t,path:n}}function xo(e,t){try{return e.readFileSync(t,"utf-8")}catch(n){if(n?.code==="ENOENT")return null;throw n}}function gd(e,t){try{return JSON.parse(e)}catch(n){throw new Error(`${tn}: ${t} is not valid JSON: ${n instanceof Error?n.message:String(n)}`)}}function NA(e,t={}){const{fs:n,path:r}=CA(),s=r.resolve(e),i=r.dirname(s),o=xo(n,s);if(o===null)throw new Error(`${tn}: there is no firebase.json at ${s}.`);const a=gd(o,s);let l;const u=()=>{if(l!==void 0)return l;const m=r.resolve(i,".firebaserc"),g=xo(n,m);return l=g===null?null:gd(g,m),l};let d=t.projectId;if(d===void 0){const m=u()?.projects?.default;typeof m=="string"&&m!==""&&(d=m)}let h;try{h=$S(a?.database,{...d===void 0?{}:{projectId:d},targetInstances:m=>d===void 0?void 0:u()?.targets?.[d]?.database?.[m],resolveFile:m=>r.resolve(i,m)})}catch(m){throw new Error(`${tn}: ${m instanceof Error?m.message:String(m)}`)}const[f]=h.unresolved;if(f!==void 0){const m=d===void 0?"no project id is set: pass { projectId } or set projects.default in .firebaserc":`.firebaserc maps it to no instance for project "${d}" (firebase target:apply database ${f.target} <instance>)`;throw new Error(`${tn}: ${f.label} deploys to target "${f.target}", and ${m}.`)}const p=new Map;for(const m of h.targets){const g=p.get(m.file);if(g!==void 0){g.instances.push(m.instance);continue}const b=xo(n,m.file);if(!(b===null&&!m.configured)){if(b===null)throw new Error(`${tn}: ${m.file} does not exist, and ${m.label} deploys it to database instance "${m.instance}".`);p.set(m.file,{file:m.configuredFile,path:m.file,text:b,instances:[m.instance]})}}if(p.size===0)throw new Error(`${tn}: ${s} deploys no Realtime Database rules.`);return{defaultInstance:h.defaultInstance,...d===void 0?{}:{projectId:d},files:[...p.values()]}}class ny{text;pos=0;line=1;lineStart=0;constructor(t){this.text=t}parseDocument(){try{this.skipTrivia();const t=this.parseValue();return this.skipTrivia(),this.pos<this.text.length?void 0:t}catch{return}}newline(){this.line++,this.lineStart=this.pos}skipTrivia(){const t=this.text;for(;this.pos<t.length;){const n=t[this.pos];if(n===`
|
|
130
|
+
actual: ${t.join(", ")}`)}function JI(e){const t=e.detail??{};return{messageId:String(t.messageId),recipientId:String(t.recipientId??"sandbox-default"),receipt:"unconfirmed",acknowledgments:[],route:t.route,handled:t.handled===!0,at:e.at,payload:t.payload}}function YI(e,t){const n=e.filter(a=>a.kind==="service_mutation"&&a.service==="messaging"),r=new Map,s=(a,l)=>JSON.stringify([a,l]);for(const a of n){if(a.op!=="delivery_acknowledged")continue;const u=a.detail??{},d=s(u.messageId,u.recipientId),h=r.get(d)??[];h.push({observerId:String(u.observerId),stage:u.stage,at:a.at}),r.set(d,h)}const i=n.filter(a=>a.op==="message_delivered").map(a=>{const l=JI(a);l.acknowledgments=r.get(s(l.messageId,l.recipientId))??[];const u=l.acknowledgments.some(d=>d.stage==="received");return l.receipt=u?"received":"unconfirmed",l});return t===void 0?i:i.filter(a=>a.at>=t)}const ld="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",QI=142,ud="APA91b",dd=22;function fd(e){const t=new Uint8Array(e);crypto.getRandomValues(t);let n="";for(let r=0;r<e;r++)n+=ld[t[r]%ld.length];return n}function XI(){const e=fd(dd),t=QI-dd-1-ud.length;return`${e}:${ud}${fd(t)}`}const ZI="pyric-sandbox",eA="999999999999",rr="sandbox-default",tA=null;class nA{projectId;senderId;sandbox;registrations=new Map;tokenRecords=new Map;subscriptions=new Map;clients=new Map;foregroundHandlers=new Map;backgroundHandlers=new Map;numericIdCounter=0;changeListeners=new Set;constructor(t={}){this.projectId=t.projectId??ZI,this.senderId=t.senderId??eA,this.sandbox=t.sandbox}snapshot(){return{version:1,tokens:[...this.tokenRecords].map(([t,n])=>[t,{...n}]),topics:[...this.subscriptions].map(([t,n])=>[t,[...n]])}}restore(t){if(!OS(t))throw new Error("Invalid Messaging persistence snapshot.");this.registrations.clear(),this.tokenRecords.clear(),this.subscriptions.clear();for(const[n,r]of t.tokens)this.tokenRecords.set(n,{...r}),r.state==="active"&&this.registrations.set(r.registrationId,n);for(const[n,r]of t.topics)this.subscriptions.set(n,new Set(r))}reset(){this.registrations.clear(),this.tokenRecords.clear(),this.subscriptions.clear(),this.changed()}onChange(t){return this.changeListeners.add(t),()=>this.changeListeners.delete(t)}changed(){for(const t of this.changeListeners)t()}getTokenFor(t,n=rr){const r=this.registrations.get(t);if(r!==void 0)return r;const s=XI();return this.registrations.set(t,s),this.tokenRecords.set(s,{registrationId:t,recipientId:n,state:"active"}),this.changed(),this.emit("token_minted",{path:s,detail:{registrationId:t}}),s}deleteTokenFor(t){const n=this.registrations.get(t);if(n===void 0)return!0;this.registrations.delete(t);const r=this.tokenRecords.get(n);return r!==void 0&&(r.state="unregistered"),this.changed(),this.emit("token_deleted",{path:n,detail:{registrationId:t}}),!0}tokenState(t){return this.tokenRecords.get(t)?.state??"unknown"}subscribeToTopic(t,n){return this.mutateSubscriptions(t,n,"subscribe")}unsubscribeFromTopic(t,n){return this.mutateSubscriptions(t,n,"unsubscribe")}mutateSubscriptions(t,n,r){if(!Ei(n))throw new tt(np());const s=mc(n),i=this.subscriptions.get(s)??new Set;this.subscriptions.set(s,i);const o={successCount:0,failureCount:0,errors:[]};return t.forEach((a,l)=>{if(!ji.test(a)){o.failureCount++,o.errors.push({index:l,reason:"invalid-token"});return}if(this.tokenState(a)==="unregistered"){o.failureCount++,o.errors.push({index:l,reason:"unregistered-token"});return}r==="subscribe"?i.add(a):i.delete(a),o.successCount++}),this.changed(),this.emit("subscription_changed",{path:s,detail:{action:r,tokenCount:t.length,successCount:o.successCount,failureCount:o.failureCount}}),o}topicsOf(t){const n=new Set;for(const[r,s]of this.subscriptions)s.has(t)&&n.add(r);return n}tokens(){const t=new Set(this.tokenRecords.keys());for(const n of this.subscriptions.values())for(const r of n)t.add(r);return[...t].sort().map(n=>({token:n,state:this.tokenState(n),topics:[...this.topicsOf(n)].sort()}))}send(t,n={}){const r=n.validateOnly===!0;let s;try{if(s=NS(t),s.kind==="token"&&this.tokenState(s.token)!=="active")throw new tt(_S())}catch(a){throw a instanceof tt&&this.emit("message_rejected",{detail:{status:a.envelope.status,errorStatus:a.envelope.error.status,errorCode:a.errorCode,message:a.envelope.error.message,validateOnly:r}}),a}const i=s.kind==="token"?crypto.randomUUID():this.mintNumericId(),o={name:`projects/${this.projectId}/messages/${i}`,messageId:i,target:s,validateOnly:r};if(this.emit("message_accepted",{path:rA(s),detail:{target:s.kind,name:o.name,messageId:i,validateOnly:r}}),!r){const a=this.toPayload(t,i);for(const l of this.matchingRecipients(s))this.route(a,l)}return o}mintNumericId(){return this.numericIdCounter=(this.numericIdCounter+1)%1e6,`${Date.now()}${String(this.numericIdCounter).padStart(6,"0")}`}matchingRecipients(t){const n=new Set;for(const[r,s]of this.tokenRecords){if(!(s.state==="active"))continue;let o;switch(t.kind){case"token":o=r===t.token;break;case"topic":o=this.subscriptions.get(t.topic)?.has(r)===!0;break;case"condition":o=sA(t.condition,this.topicsOf(r));break}o&&n.add(s.recipientId)}return n}toPayload(t,n){const r={from:this.senderId,messageId:n};if(t.data!==void 0&&(r.data={...t.data}),t.notification!==void 0){const{title:s,body:i,imageUrl:o}=t.notification;r.notification={...s!==void 0?{title:s}:{},...i!==void 0?{body:i}:{},...o!==void 0?{image:o}:{}}}return r}setClientVisibility(t,n,r=rr){this.clients.set(t,{state:n,recipientId:r})}removeClient(t){this.clients.delete(t)}onForegroundMessage(t,n=rr){return this.foregroundHandlers.set(t,n),()=>this.foregroundHandlers.delete(t)}onBackgroundMessage(t,n=rr){return this.backgroundHandlers.set(t,n),()=>this.backgroundHandlers.delete(t)}deliver(t,n=rr){const r={from:t.from??this.senderId,messageId:t.messageId??crypto.randomUUID()};return t.data!==void 0&&(r.data={...t.data}),t.notification!==void 0&&(r.notification={...t.notification}),this.route(r,n)}route(t,n){let r=!1;for(const a of this.clients.values())if(a.recipientId===n&&a.state==="visible"){r=!0;break}const s=r?"foreground":"background",i=s==="foreground"?this.foregroundHandlers:this.backgroundHandlers;this.emit("delivery_routed",{detail:{route:s,recipientId:n,visibleClient:r,messageId:t.messageId}});let o=0;for(const[a,l]of[...i])if(l===n){o++;try{a(structuredClone(t))}catch{}}return this.emit("message_delivered",{detail:{recipientId:n,route:s,handlerCount:o,handled:o>0,messageId:t.messageId,payload:structuredClone(t)}}),{route:s,handlerCount:o,payload:t}}acknowledge(t,n,r,s){this.emit("delivery_acknowledged",{detail:{messageId:t,recipientId:n,observerId:r,stage:s}})}deliveries(t){return YI(this.sandbox?.history()??[],t)}emit(t,n){if(this.sandbox!==void 0)try{pt(this.sandbox,Un({at:Te(this.sandbox).now(),service:"messaging",op:t,auth:tA,...n}),{service:"messaging"})}catch{}}}function rA(e){return e.kind==="token"?e.token:e.kind==="topic"?e.topic:e.condition}function sA(e,t){const n=e;let r=0;function s(){for(;r<n.length&&/\s/.test(n[r]);)r++}function i(l){return s(),n.startsWith(l,r)?(r+=l.length,!0):!1}function o(){if(s(),i("!"))return!o();if(i("(")){const d=a();return i(")"),d}s(),r++;const l=r;for(;r<n.length&&n[r]!=="'";)r++;const u=n.slice(l,r);return r++,i("in"),i("topics"),t.has(u)}function a(){let l=o();for(;;){if(s(),i("&&")){const u=o();l=l&&u;continue}if(i("||")){const u=o();l=l||u;continue}return l}}return a()}const hd=new WeakMap;function iA(e,t){const n=hd.get(e);if(n!==void 0)return n;const r=new nA({...t,sandbox:e});return hd.set(e,r),e.registerPersistableService("messaging",{snapshot:()=>r.snapshot(),restore:s=>r.restore(s),reset:()=>r.reset(),subscribe:s=>r.onChange(s)}),r}function oA(e){return[{name:"messaging_deliveries",description:"Inspect message routing and browser-reported receipt, callback and native display outcomes. handled only means a broker handler ran; display-accepted is not proof of OS visibility. Missing receipt is unconfirmed.",parameters:{type:"object",properties:{}},async execute(){const t=await e(),n=iA(t).deliveries();return{ok:!0,summary:`${n.length} deliveries`,data:{deliveries:n}}}}]}class _a extends Error{issues;constructor(t,n){super(t),this.name="RulesCompileError",this.issues=n}}function aA(e){const t=e.severity==="critical"||e.severity==="high"?"error":e.severity==="medium"?"warning":"info";return{code:e.code,severity:t,message:e.message,path:e.path,origin:"validate"}}function cA(e){return{...aA(e),rule:e.rule,fix:e.fix}}const lA=new Set(["PARSE_ERROR","COMPILE_ERROR"]);function pd(e,t){const n=t==="warning"?"lint":lA.has(e.code)?"parse":"validate",r={code:e.code,severity:t,message:e.message,path:e.path,origin:n};return e.rule!=="ruleset"&&(r.rule=e.rule),r}const uA="/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/";function Jm(e,t){if(!(e instanceof al)){const l=e?.constructor?.name??typeof e;throw new Error(`Unsupported Zod schema for RTDB rules: expected ZodObject, got ${l}`)}const n=e._def;if(n.catchall&&!(n.catchall instanceof _w))throw new Error("Unsupported Zod object catchall for RTDB rules");const r=e.shape;if(t){for(const l of Object.keys(t))if(!(l in r))throw new Error(`fieldConstraints: field "${l}" is not in schema.`)}const s=[],i={};for(const[l,u]of Object.entries(r)){$v("schemaRules",l);const d=u,h=d instanceof Sw,f=h?d.unwrap():d;h||s.push(l);const p=t?.[l];if(f instanceof al){const m=Jm(f);let g=m.validate;p&&p.length>0&&(g=An(m.validate,...p)),i[l]={validate:g,children:m.children}}else{const m=Ym(f,l);p&&p.length>0?i[l]={validate:An(m,...p)}:i[l]={validate:m}}}n?.unknownKeys==="strict"&&(i.$other={validate:ae("false")});const o=[ox()];for(const l of s)o.push(ax(l));return{validate:An(...o),children:i}}function dA(e,t){const n=[ae("newData.isString()")];for(const r of e._def.checks)if(r.kind==="min")n.push(ae(`newData.val().length >= ${Ye(r.value)}`));else if(r.kind==="max")n.push(ae(`newData.val().length <= ${Ye(r.value)}`));else if(r.kind==="length")n.push(ae(`newData.val().length == ${Ye(r.value)}`));else if(r.kind==="regex"){const s=r.regex;if(!ic(s.flags))throw new Error(`Unsupported Zod regex flags "${s.flags}" on field "${t}"; RTDB rules only support the "i" flag`);if(/[\r\n]/.test(s.source))throw new Error(`Unsupported Zod regex with newline on field "${t}"`);n.push(ae(`newData.val().matches(/${s.source}/${s.flags})`))}else if(r.kind==="email")n.push(ae(`newData.val().matches(${uA})`));else if(r.kind==="startsWith")n.push(ae(`newData.val().beginsWith(${Ye(r.value)})`));else if(r.kind==="endsWith")n.push(ae(`newData.val().endsWith(${Ye(r.value)})`));else if(r.kind==="includes")n.push(ae(`newData.val().contains(${Ye(r.value)})`));else throw new Error(`Unsupported Zod string check "${String(r.kind)}" for RTDB rules on field "${t}"`);return An(...n)}function fA(e,t){const n=[ae("newData.isNumber()")];for(const r of e._def.checks)if(r.kind==="min"){const s=r.inclusive===!1?">":">=";n.push(ae(`newData.val() ${s} ${Ye(r.value)}`))}else if(r.kind==="max"){const s=r.inclusive===!1?"<":"<=";n.push(ae(`newData.val() ${s} ${Ye(r.value)}`))}else if(r.kind==="int")n.push(ae("newData.val() % 1 == 0"));else if(r.kind==="multipleOf")n.push(ae(`newData.val() % ${Ye(r.value)} == 0`));else throw new Error(`Unsupported Zod number check "${String(r.kind)}" for RTDB rules on field "${t}"`);return An(...n)}function Ym(e,t){if(e instanceof kw)return dA(e,t);if(e instanceof jw)return fA(e,t);if(e instanceof Ew)return ae("newData.isBoolean()");if(e instanceof Cw){const n=e.options;return ml(...n.map(r=>ae(`newData.val() == ${Ye(r)}`)))}if(e instanceof Nw){const n=e.value;return ae(`newData.val() == ${Ye(n)}`)}if(e instanceof Rw){const n=e._def.options;return ml(...n.map(r=>Ym(r,t)))}throw new Error(`Unsupported Zod type for RTDB rules: ${e.constructor.name} on field "${t}"`)}function hA(e){let t;if(typeof e=="function"){const s=[];e({path:(i,o)=>s.push([i,o])}),t=s}else t=Object.entries(e);const n=Zm(t);bA(n),n.sort((s,i)=>{const o=md(s[0]),a=md(i[0]);return o-a||s[0].localeCompare(i[0])});const r={path:"/",pathVariables:[],children:[]};for(const[s]of n)s!=="/"&&pA(r,s);for(const[s,i]of n){const o=$c(r,s);o&&mA(r,o,i,s)}return r}function pA(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("/"),o=n.slice(0,s+1).filter(l=>l.startsWith("$"));let a=r.children.find(l=>l.path===i);a||(a={path:i,pathVariables:o,children:[]},r.children.push(a)),r=a}}function Sa(e,t,n){const r=e.validate?An(ae(e.validate.raw),t):t;e.validate=ka(r,"validate",n)}function Qm(e,t,n){for(const[r,s]of Object.entries(t)){const i=Xm(`${e.path}/${r}`),o=r.startsWith("$")?[...n,r]:n;let a=e.children.find(l=>l.path===i);a||(a={path:i,pathVariables:o,children:[]},e.children.push(a)),Sa(a,s.validate,o),s.children&&Qm(a,s.children,o)}}function mA(e,t,n,r){const s=r.split("/").filter(Boolean),i=s.filter(o=>o.startsWith("$"));if(n.fieldConstraints&&!n.schema)throw new Error(`fieldConstraints on "${r}" requires a schema.`);if(n.read&&(t.read=ka(n.read,"read",i)),n.write&&(t.write=ka(n.write,"write",i)),n.validate&&Sa(t,n.validate,i),n.schema){const o=Jm(n.schema,n.fieldConstraints);Sa(t,o.validate,i),Qm(t,o.children,i)}if(n.indexOn){const o=yA(e,t,s);if(o){if(!o.indexOn)o.indexOn=[...n.indexOn];else if(!gA(o.indexOn,n.indexOn))throw new Error(`Conflicting indexOn declarations for "${o.path}": ${JSON.stringify(o.indexOn)} vs ${JSON.stringify(n.indexOn)}`)}}}function yA(e,t,n){if(n[n.length-1]?.startsWith("$")){const s="/"+n.slice(0,-1).join("/");return $c(e,s)}return t}function gA(e,t){return e.length===t.length&&e.every((n,r)=>n===t[r])}function Xm(e){return"/"+e.split("/").filter(Boolean).join("/")}function md(e){return e.split("/").filter(Boolean).length}function bA(e){const t=new Set;for(const[n]of e){if(t.has(n))throw new Error(`Duplicate ruleset path declaration for "${n}"`);t.add(n)}}function Zm(e){const t=[];for(const[n,r]of e){const s=Xm(n),{children:i,...o}=r;if(t.push([s,o]),i){const a=Object.entries(i).map(([l,u])=>[`${s}/${l}`,u]);t.push(...Zm(a))}}return t}function ka(e,t,n){return Kh(String(e),t,n)}function $c(e,t){if(e.path===t)return e;for(const n of e.children){const r=$c(n,t);if(r)return r}return null}function wA(e){if(e==null)return null;if(typeof e=="string")return{uid:e,token:{}};const t={uid:e.uid,token:e.token??{}};return e.tenant!==void 0&&(t.tenant=e.tenant),t}function vA(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&e.__type==="serverTimestamp"}function hi(e){if(vA(e))return{".sv":"timestamp"};if(Array.isArray(e))return e.map(hi);if(typeof e=="object"&&e!==null){const t={};for(const[n,r]of Object.entries(e))t[n]=hi(r);return t}return e}function ey(e){const t={operation:e.operation,path:e.path,auth:wA(e.auth),mockData:e.mockData??e.data??{}};return e.newData!==void 0&&(t.newData=hi(e.newData)),e.now!==void 0&&(t.now=e.now),e.updates!==void 0&&(t.updates=e.updates.map(n=>({path:n.path,value:hi(n.value)}))),e.query!==void 0&&(t.query=e.query),t}function xo(e,t,n,r){return(n?.parsed[r]??[]).map(s=>({path:e,rule:t,code:s.code,message:s.message}))}function ja(e,t){const n=[...xo(e.path,".read",e.read,t),...xo(e.path,".write",e.write,t),...xo(e.path,".validate",e.validate,t),...(e.structure??[]).filter(r=>r.severity===(t==="errors"?"error":"warning")).map(r=>({path:r.path,rule:"ruleset",code:r.code,message:r.message}))];for(const r of e.children)n.push(...ja(r,t));return n}function ty(e){let t;try{t=e()}catch(s){return{ok:!1,errors:[{path:"/",rule:"ruleset",code:"COMPILE_ERROR",message:s instanceof Error?s.message:String(s)}],warnings:[]}}const n=ja(t,"errors"),r=ja(t,"warnings");return{ok:n.length===0,errors:n,warnings:r}}function ny(e){const t={};e.read&&(t[".read"]=e.read.raw),e.write&&(t[".write"]=e.write.raw),e.validate&&(t[".validate"]=e.validate.raw),e.indexOn&&(t[".indexOn"]=e.indexOn);for(const r of e.children){const s=r.path.slice(r.path.lastIndexOf("/")+1);t[s]={},ny(r)}const n=bh(e.path,t);return n.length>0&&(e.structure=n),e}class xA{definition;compiled;constructor(t){this.definition=t}compile(){return this.compiled??=ny(hA(this.definition.paths)),this.compiled}toJSON(){return B_(this.compile())}check(){return ty(()=>this.compile())}simulate(t){return fc(this.compile(),ey(t))}}function _A(e){return new xA(e)}function sn(e){return{success:!1,error:{code:"INVALID_INPUT",message:e,recoverable:!0}}}function yd(e){return e.split("/").filter(Boolean)}function SA(e){return`/${e.join("/")}`}function kA(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function jA(e){if(typeof e!="object"||e===null)return!1;const t=e.path;return typeof t=="string"&&t.length>0&&t.startsWith("/")}function EA(e){if(!Array.isArray(e))return"'updates' must be an array of { path, value } entries.";for(const t of e)if(!jA(t))return"each 'updates' entry needs an absolute 'path' starting with '/'.";return null}function ry(e){const t={operation:e.operation==="update"?"write":e.operation,path:e.path,auth:e.auth??null};return e.data!==void 0&&(t.data=e.data),e.newData!==void 0&&(t.newData=e.newData),e.now!==void 0&&(t.now=e.now),t}function CA(e,t){if(!kA(t.newData))return sn("an 'update' case needs newData to be an object keyed by the paths it writes.");const n=yd(t.path),r=Object.entries(t.newData).map(([u,d])=>({path:SA([...n,...yd(u)]),value:d}));if(r.length===0)return sn("an 'update' case needs newData to name at least one path.");let s,i;const o=[];let a=[];for(const u of r){const d=ry(t);d.path=u.path,d.newData=u.value,d.updates=r;const h=e.simulate(d);if(!h.success)return h;const f=h.data.trace.filter(m=>m.kind==="write"),p=h.data.trace.filter(m=>m.kind==="validate");if(o.push(...f),!h.data.allowed||h.data.unsupported===!0){if(p.length===0)return{success:!0,data:{...h.data,trace:o}};i??={result:h,validates:p};continue}a=p,s??=h}return i?{success:!0,data:{...i.result.data,trace:[...o,...i.validates]}}:{success:!0,data:{...s.data,trace:[...o,...a]}}}function NA(e,t){if(t.query!==void 0){if(t.operation!=="read")return sn(`a query applies to a 'read' case, and this case is '${t.operation}'.`);const r=Fh(t.query);if(r!==null)return sn(r)}if(t.updates!==void 0){if(t.operation!=="write"&&t.operation!=="validate")return sn(`'updates' applies to a 'write' or 'validate' case, and this case is '${t.operation}'.`);const r=EA(t.updates);if(r!==null)return sn(r)}if(t.operation==="update")return CA(e,t);const n=ry(t);return t.query!==void 0&&(n.query={...t.query}),t.updates!==void 0&&(n.updates=t.updates),e.simulate(n)}function Ea(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function RA(e){if(!Ea(e))return!1;const t=Object.keys(e);return t.length===1&&t[0]==="instances"&&Ea(e.instances)}function gd(e,t,n){if(typeof e!="string")return{problem:'instance must be a string naming a database instance, such as "my-app-default-rtdb".'};try{const r=Px(e)?.name;return{name:r===void 0||Dh(r,n)?t:r}}catch(r){const s=r instanceof Error?r.message.trim():String(r);return{problem:`"${e}" is not a database instance name: ${s}`}}}function Ca(e){return[...e].map(t=>`"${t}"`).join(", ")}function sy(e,t,n){if(e.kind==="every-instance")return e.rules;const r=e.instances.get(t);if(r!==void 0)return r;const s=e.instances.size===0?"it declares no instances":`it holds rules for ${Ca(e.instances.keys())}`;return{problem:`this ruleset has no rules for ${n?`database instance "${t}"`:`the default instance "${t}"`}; ${s}.`}}function IA(e,t){const n=e.kind==="per-instance",r=n?e.defaultInstance:$h,s=n?e.projectId:void 0;let i;if(t.instance!==void 0){const d=gd(t.instance,r,s);if("problem"in d)return d;i=d.name}else n&&(i=r);const o=d=>i===void 0?d:{...d,instance:i},a=sy(e,i??r,t.instance!==void 0);if("problem"in a)return o(a);const l={...t};if(i!==void 0&&RA(t.data)){const d=new Map;for(const[f,p]of Object.entries(t.data.instances)){const m=gd(f,r,s);if("problem"in m)return o({problem:`data.instances: ${m.problem}`});if(!Ea(p))return o({problem:`data.instances["${f}"] must be an object: the tree of database instance "${m.name}".`});d.set(m.name,p)}if(e.kind==="per-instance"){const f=[...d.keys()].filter(p=>!e.instances.has(p));if(f.length>0)return o({problem:`data.instances names ${Ca(f)}, which this ruleset does not declare; it holds rules for ${Ca(e.instances.keys())}.`})}const h=d.get(i);h===void 0?delete l.data:l.data=h}return o({rules:a,evaluated:l})}const nn="rtdbRules.fromFirebaseJson";function AA(){const e=globalThis.process?.getBuiltinModule,t=typeof e=="function"?e.call(process,"node:fs"):void 0,n=typeof e=="function"?e.call(process,"node:path"):void 0;if(t===void 0||n===void 0)throw new Error(`${nn} reads files, which needs Node.js 20.16 or later, Bun or Deno. Without a file system, pass each instance's rules text to rtdbRules.`);return{fs:t,path:n}}function _o(e,t){try{return e.readFileSync(t,"utf-8")}catch(n){if(n?.code==="ENOENT")return null;throw n}}function bd(e,t){try{return JSON.parse(e)}catch(n){throw new Error(`${nn}: ${t} is not valid JSON: ${n instanceof Error?n.message:String(n)}`)}}function OA(e,t={}){const{fs:n,path:r}=AA(),s=r.resolve(e),i=r.dirname(s),o=_o(n,s);if(o===null)throw new Error(`${nn}: there is no firebase.json at ${s}.`);const a=bd(o,s);let l;const u=()=>{if(l!==void 0)return l;const m=r.resolve(i,".firebaserc"),g=_o(n,m);return l=g===null?null:bd(g,m),l};let d=t.projectId;if(d===void 0){const m=u()?.projects?.default;typeof m=="string"&&m!==""&&(d=m)}let h;try{h=TS(a?.database,{...d===void 0?{}:{projectId:d},targetInstances:m=>d===void 0?void 0:u()?.targets?.[d]?.database?.[m],resolveFile:m=>r.resolve(i,m)})}catch(m){throw new Error(`${nn}: ${m instanceof Error?m.message:String(m)}`)}const[f]=h.unresolved;if(f!==void 0){const m=d===void 0?"no project id is set: pass { projectId } or set projects.default in .firebaserc":`.firebaserc maps it to no instance for project "${d}" (firebase target:apply database ${f.target} <instance>)`;throw new Error(`${nn}: ${f.label} deploys to target "${f.target}", and ${m}.`)}const p=new Map;for(const m of h.targets){const g=p.get(m.file);if(g!==void 0){g.instances.push(m.instance);continue}const b=_o(n,m.file);if(!(b===null&&!m.configured)){if(b===null)throw new Error(`${nn}: ${m.file} does not exist, and ${m.label} deploys it to database instance "${m.instance}".`);p.set(m.file,{file:m.configuredFile,path:m.file,text:b,instances:[m.instance]})}}if(p.size===0)throw new Error(`${nn}: ${s} deploys no Realtime Database rules.`);return{defaultInstance:h.defaultInstance,...d===void 0?{}:{projectId:d},files:[...p.values()]}}class iy{text;pos=0;line=1;lineStart=0;constructor(t){this.text=t}parseDocument(){try{this.skipTrivia();const t=this.parseValue();return this.skipTrivia(),this.pos<this.text.length?void 0:t}catch{return}}newline(){this.line++,this.lineStart=this.pos}skipTrivia(){const t=this.text;for(;this.pos<t.length;){const n=t[this.pos];if(n===`
|
|
131
131
|
`)this.pos++,this.newline();else if(n==="\r")this.pos++,t[this.pos]===`
|
|
132
132
|
`&&this.pos++,this.newline();else if(n===" "||n===" "||n==="\uFEFF")this.pos++;else if(n==="/"&&t[this.pos+1]==="/")for(;this.pos<t.length&&t[this.pos]!==`
|
|
133
133
|
`&&t[this.pos]!=="\r";)this.pos++;else if(n==="/"&&t[this.pos+1]==="*")for(this.pos+=2;;){if(this.pos>=t.length)throw new Error("unterminated comment");const r=t[this.pos];if(r==="*"&&t[this.pos+1]==="/"){this.pos+=2;break}this.pos++,r===`
|
|
134
134
|
`?this.newline():r==="\r"&&(t[this.pos]===`
|
|
135
135
|
`&&this.pos++,this.newline())}else return}}parseValue(){const t=this.text[this.pos];return t==="{"?this.parseObject():t==="["?(this.parseArray(),null):t==='"'?(this.parseString(),null):(this.parseLiteral(),null)}parseObject(){const t=new Map;if(this.pos++,this.skipTrivia(),this.text[this.pos]==="}")return this.pos++,t;for(;;){if(this.skipTrivia(),this.text[this.pos]!=='"')throw new Error("expected key");const n={line:this.line,column:this.pos-this.lineStart+1},r=this.parseString();if(this.skipTrivia(),this.text[this.pos]!==":")throw new Error("expected colon");this.pos++,this.skipTrivia();const s=this.parseValue();t.set(r,{location:n,value:s}),this.skipTrivia();const i=this.text[this.pos++];if(i==="}")return t;if(i!==",")throw new Error("expected comma");if(this.skipTrivia(),this.text[this.pos]==="}")return this.pos++,t}}parseArray(){if(this.pos++,this.skipTrivia(),this.text[this.pos]==="]"){this.pos++;return}for(;;){this.skipTrivia(),this.parseValue(),this.skipTrivia();const t=this.text[this.pos++];if(t==="]")return;if(t!==",")throw new Error("expected comma");if(this.skipTrivia(),this.text[this.pos]==="]"){this.pos++;return}}}parseString(){const t=this.text,n=this.pos;for(this.pos++;;){if(this.pos>=t.length)throw new Error("unterminated string");const s=t[this.pos];if(s==="\\"){if(this.pos+1>=t.length||t.charCodeAt(this.pos+1)<32)throw new Error("invalid escape");this.pos+=2}else if(s==='"'){this.pos++;break}else s===`
|
|
136
136
|
`?(this.pos++,this.newline()):s==="\r"?(this.pos++,t[this.pos]===`
|
|
137
|
-
`&&this.pos++,this.newline()):this.pos++}const r=t.slice(n,this.pos).replace(/[\u0000-\u001f]/g,s=>`\\u${s.charCodeAt(0).toString(16).padStart(4,"0")}`);return JSON.parse(r)}parseLiteral(){const t=/^(?:true|false|null|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)/.exec(this.text.slice(this.pos,this.pos+64));if(!t)throw new Error("unexpected token");this.pos+=t[0].length}}function ry(e,t,n){let r=e.get("rules")?.value??null;for(const s of t.split("/").filter(i=>i.length>0))r=r?.get(s)?.value??null;return r?.get(n)?.location??null}function RA(e,t,n){const r=new ny(e).parseDocument();return r?ry(r,t,n):null}function sy(e,t){const n=new ny(e).parseDocument();return t.map(r=>{const s=n?ry(n,r.path,`.${r.kind}`):null;return s?{...r,line:s.line}:{...r}})}const bd=["read","write","validate","indexOn"];function _o(e,t){return`${e}\0${t}`}function IA(e){const t=["allow","deny","error"].filter(n=>e[n]>0);return t.length>1?"mixed":t.length===1?t[0]:e.unsupported>0?"unsupported":"never-evaluated"}class AA{compiled;rows=new Map;missing=new Map;constructor(t){this.compiled=t,this.collect(t)}collect(t){for(const n of bd){let r;n==="indexOn"?t.indexOn!==void 0&&(r=JSON.stringify(t.indexOn)):r=t[n]?.raw,r!==void 0&&this.rows.set(_o(t.path,n),{path:t.path,kind:n,expression:r,counts:{allow:0,deny:0,error:0,unsupported:0}})}for(const n of t.children)this.collect(n)}record(t){for(const n of t??[]){const r=this.rows.get(_o(n.path,n.kind));r!==void 0&&(n.verdict==="ALLOW"?r.counts.allow++:n.verdict==="DENY"?r.counts.deny++:n.verdict==="ERROR"?r.counts.error++:r.counts.unsupported++)}}recordQuery(t,n){if(n===void 0)return;let r=null;if(n.orderByValue===!0)r=".value";else if(typeof n.orderByChild=="string"){const o=n.orderByChild.split("/").filter(Boolean).join("/");o!==""&&(r=o)}if(r===null)return;const s=t.split("/").filter(Boolean),i=Yh(this.compiled,s,r);for(const o of i){const a=this.rows.get(_o(o.path,"indexOn"));a!==void 0&&a.counts.allow++}if(i.length===0){const o=`/${s.join("/")}`;this.missing.set(`${o}\0${r}`,{path:o,index:r})}}summarize(t={}){const n=[];for(const a of this.rows.values()){const{allow:l,deny:u,error:d,unsupported:h}=a.counts,f={path:a.path,kind:a.kind,expression:a.expression,evaluated:l+u+d,allow:l,deny:u,error:d,unsupported:h,status:IA(a.counts)};n.push(f)}const r=t.source===void 0?n:sy(t.source,n),s=Object.fromEntries(bd.map(a=>[a,{total:0,covered:0,unsupported:0}]));let i=0,o=0;for(const a of r)s[a.kind].total++,a.evaluated>0?(s[a.kind].covered++,i++):a.status==="unsupported"&&(s[a.kind].unsupported++,o++);return{rules:r,uncovered:r.filter(a=>a.status==="never-evaluated").map(a=>`${a.path} .${a.kind}`),missingIndexes:[...this.missing.values()],files:[{file:t.file??null,total:r.length,covered:i,neverEvaluated:r.filter(a=>a.status==="never-evaluated").length,unsupported:o,byKind:s}]}}}function OA(e){const t={rules:[],uncovered:[],missingIndexes:[],files:[]};for(const n of e){const r=n.files[0]?.file??"rules";t.rules.push(...n.rules.map(s=>({file:r,...s}))),t.uncovered.push(...n.uncovered.map(s=>`${r} ${s}`)),t.missingIndexes.push(...n.missingIndexes.map(s=>({...s,file:r}))),t.files.push(...n.files)}return t}const $A=new Set(["exists","isString","isNumber","isBoolean","hasChild","hasChildren"]);function xn(e){return e===!1||e==="exists-false"||e==="delete-guard"}function wd(e,t){return e.length>=t.length&&t.every((n,r)=>e[r]===n)}function vd(e,t){const n=e.split("/").filter(Boolean);return t.split("/").filter(Boolean).slice(n.length)}function DA(e){const t=e.newDataRelPath();return t!==void 0&&t.length===0}function xd(e,t,n){const r=this.args.acc;(e.newDataRelPath()?.join("/")===".val()"&&n.constVal()===null||n.newDataRelPath()?.join("/")===".val()"&&e.constVal()===null)&&r.newDataExistsCalls++,e.collect(r),n.collect(r)}function bs(e){return function(t,n,r){const s=t.constVal(),i=r.constVal();if(typeof s!="number"||typeof i!="number")return;const o=e(s,i);return o!==void 0&&Number.isFinite(o)?o:void 0}}function ws(e){return function(t,n,r){const s=t.constVal(),i=r.constVal();if(typeof s=="number"&&typeof i=="number"||typeof s=="string"&&typeof i=="string")return e===">"?s>i:e===">="?s>=i:e==="<"?s<i:s<=i}}function vs(e){return function(t,n,r){const s=t.constVal(),i=r.constVal();if(!(s===void 0||i===void 0))return e?s===i:s!==i}}function xs(e,t,n){const r=this.args.relSegments;return e.evalOnDelete(r)===null||n.evalOnDelete(r)===null?!1:this.constVal()}function _d(e,t,n){const r=this.args.relSegments,s=e.evalOnDelete(r),i=n.evalOnDelete(r);if(s===null&&i===null&&e.constVal()===null!=(n.constVal()===null))return"delete-guard";if(s!==void 0&&i!==void 0)return s===i;if(s===null&&e.constVal()!==null||i===null&&n.constVal()!==null)return!1}function Sd(e,t,n){const r=this.args.relSegments,s=e.evalOnDelete(r),i=n.evalOnDelete(r);return s!==void 0&&i!==void 0?s!==i:void 0}let So;function PA(){if(So)return So;const e=Zr();return e.addOperation("newDataRelPath",{_nonterminal(...t){return t.length===1?t[0].newDataRelPath():void 0},_iter(){},_terminal(){},Primary_paren(t,n,r){return n.newDataRelPath()},ident(t,n,r){return this.sourceString==="newData"?[]:void 0},CallExpr_methodCall(t,n,r,s,i,o){const a=t.newDataRelPath();if(a===void 0||a[0]===".val()")return;const l=r.sourceString;if(l==="val"&&a.length===0&&i.asIteration().children.length===0)return[".val()"];if(l==="child"){const u=i.asIteration().children,d=u.length===1?u[0].constVal():void 0;return typeof d=="string"?[...a,...d.split("/").filter(Boolean)]:void 0}return l==="parent"&&a.length>0?a.slice(0,-1):void 0}}),e.addOperation("collect(acc)",{_nonterminal(...t){t.forEach(n=>n.collect(this.args.acc))},_iter(...t){t.forEach(n=>n.collect(this.args.acc))},_terminal(){},CallExpr_methodCall(t,n,r,s,i,o){const a=this.args.acc;if(DA(t)){const l=r.sourceString;l==="exists"&&a.newDataExistsCalls++,(l==="hasChild"||l==="child")&&(a.checksNamedChildren=!0),l==="hasChildren"&&i.asIteration().children.length>0&&(a.checksNamedChildren=!0)}t.collect(a),i.asIteration().children.forEach(l=>l.collect(a))},Equality_strictNeq:xd,Equality_looseNeq:xd,CallExpr_memberAccess(t,n,r){t.collect(this.args.acc)},ident(t,n,r){const s=this.args.acc,i=this.sourceString;i==="auth"?s.readsAuth=!0:i==="data"?s.readsData=!0:i==="root"?s.readsRoot=!0:i==="newData"&&s.newDataReads++}}),e.addOperation("constVal",{_nonterminal(...t){return t.length===1?t[0].constVal():void 0},_iter(){},_terminal(){},Primary_paren(t,n,r){return n.constVal()},bool_true(t){return!0},bool_false(t){return!1},null(t){return null},number(t){const n=Number(this.sourceString);return Number.isFinite(n)?n:void 0},string_single(t,n,r){return Cr(this.sourceString)?void 0:Nr(this.sourceString)},string_double(t,n,r){return Cr(this.sourceString)?void 0:Nr(this.sourceString)},UnaryExpr_not(t,n){const r=n.constVal();return typeof r=="boolean"?!r:void 0},UnaryExpr_neg(t,n){const r=n.constVal();return typeof r=="number"&&Number.isFinite(-r)?-r:void 0},Multiplicative_mul:bs((t,n)=>t*n),Multiplicative_div:bs((t,n)=>n===0?void 0:t/n),Multiplicative_mod:bs((t,n)=>n===0?void 0:t%n),Additive_sub:bs((t,n)=>t-n),Additive_add(t,n,r){const s=t.constVal(),i=r.constVal();return typeof s=="number"&&typeof i=="number"?Number.isFinite(s+i)?s+i:void 0:typeof s=="string"&&typeof i=="string"?s+i:void 0},Comparison_gt:ws(">"),Comparison_gte:ws(">="),Comparison_lt:ws("<"),Comparison_lte:ws("<="),Equality_strictEq:vs(!0),Equality_looseEq:vs(!0),Equality_strictNeq:vs(!1),Equality_looseNeq:vs(!1),LogicalAnd_and(t,n,r){const s=t.constVal();if(s===!1)return!1;if(s===!0){const i=r.constVal();return typeof i=="boolean"?i:void 0}},LogicalOr_or(t,n,r){const s=t.constVal();if(s===!0)return!0;if(s===!1){const i=r.constVal();return typeof i=="boolean"?i:void 0}},Ternary_ternary(t,n,r,s,i){const o=t.constVal();if(o===!0)return r.constVal();if(o===!1)return i.constVal()}}),e.addOperation("constant",{_nonterminal(){const t=this.constVal();return typeof t=="boolean"?t:void 0},_iter(){},_terminal(){}}),e.addOperation("evalOnDelete(relSegments)",{_nonterminal(...t){const n=this.constVal();return n!==void 0?n:t.length===1?t[0].evalOnDelete(this.args.relSegments):void 0},_iter(){},_terminal(){return this.constVal()},Primary_paren(t,n,r){return n.evalOnDelete(this.args.relSegments)},CallExpr_methodCall(t,n,r,s,i,o){const a=this.args.relSegments,l=t.newDataRelPath(),u=r.sourceString;if(l!==void 0&&l[0]!==".val()"){if(wd(l,a)){if(u==="exists")return"exists-false";if($A.has(u))return!1;if(u==="val"||u==="getPriority")return null}const d=i.asIteration().children;let h=[];u==="hasChild"&&d.length===1?h=[d[0]]:u==="hasChildren"&&d.length===1&&d[0].ctorName==="Array"&&(h=d[0].children[1].asIteration().children);for(const f of h){const p=f.constVal();if(typeof p=="string"&&wd([...l,...p.split("/").filter(Boolean)],a))return!1}}return t.evalOnDelete(a)===null?!1:void 0},CallExpr_memberAccess(t,n,r){return t.evalOnDelete(this.args.relSegments)===null?!1:void 0},UnaryExpr_not(t,n){const r=n.evalOnDelete(this.args.relSegments);return r==="exists-false"?"delete-guard":r==="delete-guard"?!1:typeof r=="boolean"?!r:void 0},Comparison_gt:xs,Comparison_gte:xs,Comparison_lt:xs,Comparison_lte:xs,Equality_strictEq:_d,Equality_looseEq:_d,Equality_strictNeq:Sd,Equality_looseNeq:Sd,LogicalAnd_and(t,n,r){const s=this.args.relSegments,i=t.evalOnDelete(s),o=r.evalOnDelete(s);return i===!1||i==="exists-false"||o===!1||o==="exists-false"?!1:i==="delete-guard"||o==="delete-guard"?"delete-guard":i===!0&&o===!0?!0:void 0},LogicalOr_or(t,n,r){const s=this.args.relSegments,i=t.evalOnDelete(s);if(i===!0)return!0;const o=r.evalOnDelete(s);return xn(i)&&xn(o)?i==="delete-guard"||o==="delete-guard"?"delete-guard":!1:xn(i)&&o===!0?!0:void 0},Ternary_ternary(t,n,r,s,i){const o=this.args.relSegments,a=t.evalOnDelete(o);if(a===!0)return r.evalOnDelete(o);if(a===!1||a==="exists-false")return i.evalOnDelete(o);if(xn(r.evalOnDelete(o))&&xn(i.evalOnDelete(o)))return!1}}),So=e,e}function ko(e){if(e===void 0||!e.parsed.valid||e.parsed.errors.length>0)return;const t=Xr(e.raw);if(!t.ok)return;const n=PA()(t.match),r={readsAuth:!1,readsData:!1,readsRoot:!1,newDataReads:0,newDataExistsCalls:0,checksNamedChildren:!1};n.collect(r);const s=n.constant();return{constant:s,...r,canGrantOnDelete:i=>s!==!1&&!xn(n.evalOnDelete(i))}}function iy(e){return{node:e,read:ko(e.read),write:ko(e.write),validate:ko(e.validate),children:e.children.map(iy)}}function _s(e){return e!==void 0&&e.constant!==!1}function TA(e){const t=e.validate;return t===void 0||t.constant!==void 0?!1:!(t.newDataReads>0&&t.newDataReads===t.newDataExistsCalls&&!t.readsData&&!t.readsRoot)}function _r(e){if(TA(e))return!0;if(e.children.length===0)return!1;const t=e.children.filter(n=>!Ca(n));return e.children.some(_r)&&t.every(_r)}function oy(e){const t=e.split("/").filter(Boolean);return t[t.length-1]??""}function Ca(e){return oy(e.node.path).startsWith("$")}function Ss(e){const t=e.raw.trim();return t.length<=80?t:`${t.slice(0,77)}...`}function jo(e){return e==="/"?"the database":e}function MA(e){const t=[];return ay(iy(e),{ancestors:[],unboundedAbove:!1},t),t}function ay(e,t,n){const r=e.node.path,s=e.write,i=e.read;if(s?.constant===!0&&n.push({code:"RTDB-SEC-1",severity:"critical",path:r,rule:".write",message:`${r} .write is true: anyone, signed in or not, can write, replace or delete any value under ${jo(r)}.`,fix:`Replace ${r} .write true with a condition on auth, such as "auth != null && auth.uid == $uid" on the node each user owns.`}),i?.constant===!0){const p=r==="/";n.push({code:"RTDB-SEC-2",severity:p?"critical":"medium",path:r,rule:".read",message:p?"/ .read is true: anyone, signed in or not, can read the entire database.":`${r} .read is true: anyone, signed in or not, can read everything under ${r}.`,fix:p?"Remove .read from the root and grant .read on the subtrees clients need, with a condition on auth.":`Require auth in ${r} .read ("auth != null"), or keep ${r} only if every value under it is meant to be public.`})}s!==void 0&&s.constant===void 0&&!s.readsAuth&&n.push({code:"RTDB-SEC-3",severity:"high",path:r,rule:".write",message:`${r} .write does not read auth: a signed-out client can write under ${jo(r)} whenever "${Ss(e.node.write)}" holds.`,fix:`Add an auth condition to ${r} .write, such as "auth != null && (${Ss(e.node.write)})".`});for(const p of["read","write"]){const m=e[p];if(m===void 0)continue;const g=p==="read"?".read":".write",b=t.ancestors.find(v=>{const _=v[p];return _s(_)?_.constant===!0?m.constant!==!0:m.constant===!1:!1});if(b===void 0)continue;const w=b.node.path,x=b.node[p];n.push({code:"RTDB-SEC-4",severity:"high",path:r,rule:g,message:b[p].constant===!0?`${r} ${g} never restricts access: ${w} ${g} is true and grants ${p} on every path under it, and a deeper rule cannot revoke an ancestor's grant.`:`${r} ${g} false does not revoke ${w} ${g}: whenever "${Ss(x)}" holds, ${w} grants ${p} on every path under it, including ${r}.`,fix:`Move the grant from ${w} ${g} down to the children that need it, so that no ancestor of ${r} grants ${p}.`})}const o=e.validate;if(o!==void 0&&o.constant===void 0&&(o.readsData||o.readsRoot||o.newDataExistsCalls>0)){const p=[...t.ancestors,e].find(m=>_s(m.write)&&m.write.canGrantOnDelete(vd(m.node.path,r)));if(p!==void 0){const m=p.node.path,g=vd(m,r),b=g.length>0&&g.every(w=>!w.startsWith("$"))?`newData.child('${g.join("/")}').exists()`:"newData.exists()";n.push({code:"RTDB-SEC-5",severity:"high",path:r,rule:".validate",message:`${r} .validate does not run when ${r} is deleted: .validate runs only on a non-null new value, and ${m} .write grants without requiring ${b}, so a client it admits can delete ${r} (write null at ${m}) and bypass "${Ss(e.node.validate)}".`,fix:`Add "${b}" to ${m} .write to refuse deletes, or write the delete condition there, such as "${b} || <who may delete>".`})}}let a=t.unboundedAbove;!a&&_s(s)&&s.newDataReads===s.newDataExistsCalls&&!_r(e)&&(a=!0,n.push({code:"RTDB-SEC-6",severity:"high",path:r,rule:".write",message:`${r} .write accepts any value: no .validate rule sits at or below ${r} and the .write rule does not check newData, so a client it admits can store data of any shape and size under ${jo(r)}.`,fix:`Add .validate rules under ${r} that fix the shape and bound sizes, such as "newData.isString() && newData.val().length <= 100", and "$other": { ".validate": false } for keys you do not name.`}));const l=e.children.filter(p=>!Ca(p)&&_r(p)).map(p=>oy(p.node.path)),u=l.length>0||o?.checksNamedChildren===!0,d=e.children.some(p=>Ca(p)&&(p.validate?.constant===!1||_r(p))),h=[...t.ancestors,e].some(p=>_s(p.write));if(u&&!d&&h){const p=l.length>0?`names ${l.join(", ")} with .validate rules`:"checks named children in .validate";n.push({code:"RTDB-SEC-7",severity:"medium",path:r,rule:".validate",message:`${r} ${p} but has no $other rule: a write at or above ${r} can add any other key under it, and no .validate rule checks that key.`,fix:`Add "$other": { ".validate": false } under ${r} to reject keys it does not name.`})}const f={ancestors:[...t.ancestors,e],unboundedAbove:a};for(const p of e.children)ay(p,f,n)}function LA(e){const t=e;return typeof t.toJSON=="function"&&typeof t.simulate=="function"&&typeof t.check=="function"}function UA(e){const t=e;return typeof t=="object"&&t!==null&&"rules"in t&&!("paths"in t)&&typeof t.toJSON!="function"}class cy{placement;constructor(t){this.placement=t}get doc(){if(this.placement.kind!=="every-instance")throw new Error("per-instance rules hold one ruleset per instance");return this.placement.rules.doc}lint(){return this.placement.kind==="every-instance"?kd(this.doc):[...new Set(this.placement.instances.values())].flatMap(t=>kd(t.doc).map(n=>t.file===void 0?n:{...n,file:t.file}))}runOne(t){const n=EA(this.placement,t),r=n.instance,s={case:t,...t.description!==void 0?{description:t.description}:{},...r!==void 0?{instance:r}:{}},i="problem"in n?rn(n.problem):kA(n.rules.doc,n.evaluated);if(!i.success)return{...s,expectation:t.expectation,decision:"UNSUPPORTED",passed:!1,unsupported:!0,matchedPath:t.path,matchedRule:"",reason:i.error.message,trace:[]};const o=i.data,a=o.unsupported===!0,l=a?"UNSUPPORTED":o.allowed?"ALLOW":"DENY",u=!a&&l===t.expectation;return{...s,expectation:t.expectation,decision:l,passed:u,unsupported:a,matchedPath:o.matchedPath,matchedRule:o.matchedRule,reason:o.reason,trace:r===void 0?o.trace:o.trace.map(d=>({...d,instance:r}))}}simulate(t){const n=t.map(o=>this.runOne(o));let r=0,s=0,i=0;for(const o of n)o.unsupported?i++:o.passed?r++:s++;return{passed:r,failed:s,unsupported:i,cases:n,coverage:this.coverage(n)}}coverage(t,n){if(this.placement.kind==="every-instance")return jd(this.doc,t,n);const{defaultInstance:r,instances:s}=this.placement,o=[...new Set(s.values())].map(a=>{const l=t.filter(u=>s.get(u.instance??r)===a);return jd(a.doc,l,{...a.file===void 0?{}:{file:a.file},...a.source===void 0?{}:{source:a.source}})});return o.length===1?o[0]:OA(o)}explain(t){const n=this.runOne(t);return{...n.instance!==void 0?{instance:n.instance}:{},decision:n.decision,expectation:n.expectation,passed:n.passed,unsupported:n.unsupported,matchedPath:n.matchedPath,matchedRule:n.matchedRule,reason:n.reason,trace:n.trace}}toJSON(){if(this.placement.kind==="every-instance")return this.doc.toJSON();const t=ty(this.placement,this.placement.defaultInstance,!1);if("problem"in t)throw new Error(t.problem);return t.doc.toJSON()}}function kd(e){const t=e.check(),n=[...t.errors.map(r=>hd(r,"error")),...t.warnings.map(r=>hd(r,"warning"))];return t.errors.some(r=>r.code==="COMPILE_ERROR")?n:[...n,...MA(e.compile()).map(sA)]}function jd(e,t,n){const r=new AA(e.compile());for(const s of t)r.record(s.trace),s.case.operation==="read"&&r.recordQuery(s.case.path,s.case.query);return r.summarize(n)}function Eo(e){return new cy({kind:"every-instance",rules:{doc:e}})}class ly{json;compiled;constructor(t){this.json=t}toJSON(){return this.json}compile(){return this.compiled??=Gh(this.json),this.compiled}check(){return Xm(()=>this.compile())}simulate(t){return dc(this.compile(),Qm(t))}}function uy(e){let t;try{t=JSON.parse(aE(e))}catch(s){const i=s instanceof Error?s.message:String(s);throw Ed(`Realtime Database rules text is not valid JSON: ${i}`)}const n=t?.rules;if(!(typeof n=="object"&&n!==null&&!Array.isArray(n)))throw Ed('Realtime Database rules text has no top-level "rules" object');return t}function Ed(e){return new xa(e,[{code:"PARSE_ERROR",severity:"error",message:e,origin:"parse"}])}function BA(e){return typeof e=="string"&&(e=uy(e)),LA(e)?Eo(e):UA(e)?Eo(new ly(e)):Eo(bA(e))}function FA(e,t={}){const n=NA(e,t),r=new Map;for(const s of n.files){let i;try{i=uy(s.text)}catch(a){throw a instanceof xa?new xa(`${s.path}: ${a.message}`,a.issues):a}const o={doc:new ly(i),file:s.file,source:s.text};for(const a of s.instances)r.set(a,o)}return new cy({kind:"per-instance",defaultInstance:n.defaultInstance,...n.projectId===void 0?{}:{projectId:n.projectId},instances:r})}const qA=Object.assign(BA,{fromFirebaseJson:FA});function dy(e){return e&&typeof e=="object"&&pa in e?oN(e).backend:fS(e)}function fy(e){return dy(e).getActiveRules()}function Cd(e){return dy(e).snapshotState()}function VA(e,t){return e==="/"?`/${t}`:`${e}/${t}`}function Nd(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function WA(e){const t=(e??"/").split("/").filter(Boolean);return t.length===0?"/":`/${t.join("/")}`}function zA(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 hy(e,t,n,r,s){if(e===null||typeof e!="object"||Array.isArray(e))return{path:t,childCount:0,truncated:!1,children:[],schema:{},valueType:Nd(e)};const i=Object.entries(e).sort(([h],[f])=>h.localeCompare(f)),o={},a=[];for(const[h,f]of i)f!==null&&typeof f=="object"&&!Array.isArray(f)?a.push([h,f]):o[h]=Nd(f);const l=n>=r&&a.length>0,u=i.length>s,d=n>=r?[]:a.slice(0,s).map(([h,f])=>hy(f,VA(t,h),n+1,r,s));return{path:t,childCount:i.length,truncated:l||u,children:d,schema:o}}function HA(e,t={}){const n=WA(t.path),r=t.maxDepth??10,s=t.maxChildren??100;return hy(zA(e,n),n,0,r,s)}function py(e){return e.children.reduce((t,n)=>t+1+py(n),0)}const Co={anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"}]};function KA(e){return[{name:"rtdb_simulate_access",description:"Simulate one read, write, update, or validate operation against the RTDB rules and data currently loaded in the local sandbox. newData may be any JSON value, such as 5 or true; for update it is the patch keyed by the paths written, relative to path. A read may carry a query so query.* rules evaluate. No production database is contacted and no prior rules-loading tool call is required.",parameters:{type:"object",properties:{operation:{type:"string",enum:["read","write","update","validate"]},path:{type:"string"},auth:{anyOf:[{type:"null"},{type:"object",properties:{uid:{type:"string"},tenant:{type:"string"},claims:{type:"object"}},required:["uid"]}]},newData:{},query:{type:"object",properties:{orderByChild:{type:"string"},orderByKey:{type:"boolean",enum:[!0]},orderByValue:{type:"boolean",enum:[!0]},equalTo:Co,startAt:Co,endAt:Co,limitToFirst:{type:"integer"},limitToLast:{type:"integer"}},additionalProperties:!1},now:{type:"number"}},required:["operation","path"]},async execute(t){const n=t,r=await e.resolveSandbox(),s=fy(r);if(!s)return{ok:!1,summary:"No RTDB rules are loaded in the local sandbox.",data:{code:"NO_ACTIVE_RULES"}};const i=Cd(r),o=i!==null&&typeof i=="object"&&!Array.isArray(i)?i:{};let a=n.now;a===void 0&&(a=Te(r).now());let l=null;if(n.auth){const h=Wm(n.auth.uid,n.auth.tenant,n.auth.claims);l={uid:h.uid,token:h.token}}const u={expectation:"ALLOW",operation:n.operation,path:n.path,auth:l,data:o,now:a};n.newData!==void 0&&(u.newData=n.newData),n.query!==void 0&&(u.query=n.query);const d=qA(s).simulate([u]).cases[0];return{ok:!d.unsupported,summary:d.unsupported?`Simulation unsupported: ${d.reason}`:`Simulation: ${d.decision.toLowerCase()}`,data:{decision:d.decision,allowed:d.decision==="ALLOW",unsupported:d.unsupported,matchedPath:d.matchedPath,matchedRule:d.matchedRule,reason:d.reason,trace:d.trace}}}},{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=HA(Cd(r),n);return{ok:!0,summary:`Crawled ${py(s)} object paths from ${s.path}`,data:s}}}]}function rr(e){return{uid:e.uid,email:e.email,displayName:e.displayName,phoneNumber:e.phoneNumber,photoUrl:e.photoUrl,claims:{...e.customClaims},providers:e.providerUserInfo.map(t=>t.providerId),isAnonymous:e.isAnonymous,disabled:e.disabled,emailVerified:e.emailVerified,tenantId:e.tenantId,createdAt:e.createdAt,lastLoginAt:e.lastLoginAt}}function GA(e,t){const n=JSON.stringify(t?{uid:e,claims:t}:{uid:e}),r=new TextEncoder().encode(n);let s="";for(const i of r)s+=String.fromCharCode(i);return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Tt(e,t){return{ok:!1,summary:t,data:{code:e}}}function sr(e){const t=typeof e?.code=="string"?e.code:"auth/internal-error";return Tt(t,e instanceof Error?e.message:String(e))}function Us(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ot(e){return Us(e)?e:{}}function ks(e,t){const n=e.uid;return typeof n!="string"||n.length===0?Tt("auth/argument-error",`${t}: uid must be a non-empty string.`):n}function my(e){if(Array.isArray(e))return e.filter(t=>typeof t=="string"&&t.trim().length>0).map(t=>({providerId:t}))}function Rd(e){return{uid:e.uid,email:e.email,password:e.password,displayName:e.displayName,phoneNumber:e.phoneNumber,customClaims:e.claims,disabled:e.disabled,emailVerified:e.emailVerified,providerUserInfo:my(e.providers)}}const Na={type:"object",description:"Custom claims. Rules read them as request.auth.token.<name>."},JA={type:"array",items:{type:"string"},description:"Provider ids to link, for example google.com. A user created under a dotted provider id and no password is assigned a generated photoUrl."},Ra={email:{type:"string"},password:{type:"string",description:"At least six characters. Never returned."},displayName:{type:"string"},phoneNumber:{type:"string"},claims:Na,providers:JA,disabled:{type:"boolean"},emailVerified:{type:"boolean"}},YA={type:"object",properties:{uid:{type:"string",description:"Generated when omitted."},...Ra},required:["email"]},Id="Users land in the one pool the application, Studio, and rules evaluation share. Creating a user does not sign anyone in, and a password is never returned. A user created under a dotted provider id with no password is assigned a generated photoUrl; password, phone, and anonymous users keep photoUrl null.";function QA(e){const t=async()=>mc(await e.resolveSandbox());return[{name:"auth_create_user",description:`Create one user in the connected sandbox's user store. ${Id}`,parameters:{type:"object",properties:{uid:{type:"string",description:"User id. Generated when omitted."},...Ra}},async execute(n){const r=Ot(n),s=await t();try{const i=xe.createUser(s,Rd(r));return{ok:!0,summary:`Created user ${i.uid}`,data:{user:rr(i)}}}catch(i){return sr(i)}}},{name:"auth_import_users",description:`Create many users in order, reporting each failure without stopping. ${Id}`,parameters:{type:"object",properties:{users:{type:"array",items:YA,description:"Users to create, in order. Each requires an email."}},required:["users"]},async execute(n){const s=Ot(n).users;if(!Array.isArray(s))return Tt("auth/argument-error","auth_import_users: users must be an array.");const i=await t(),o=[],a=[];s.forEach((u,d)=>{const h=Us(u)?u:{};if(typeof h.email!="string"||h.email.length===0){a.push({index:d,...h.uid?{uid:h.uid}:{},email:String(h.email??""),code:"auth/argument-error",message:`auth_import_users: users[${d}].email is required.`});return}try{o.push(xe.createUser(i,Rd(h)).uid)}catch(f){const p=sr(f).data;a.push({index:d,...h.uid?{uid:h.uid}:{},email:h.email,code:p.code,message:f instanceof Error?f.message:String(f)})}});const l=a.length===0?`Imported ${o.length} of ${s.length} users`:`Imported ${o.length} of ${s.length} users; ${a.length} failed`;return{ok:a.length===0,summary:l,data:{created:o,errors:a}}}},{name:"auth_get_user",description:"Read one user of the connected sandbox's user store by uid, or by email when uid is omitted.",parameters:{type:"object",properties:{uid:{type:"string"},email:{type:"string",description:"Matched case-insensitively. Used when uid is omitted."}}},async execute(n){const{uid:r,email:s}=Ot(n);if(typeof r!="string"&&typeof s!="string")return Tt("auth/argument-error","auth_get_user: uid or email is required.");const i=xe.listUsers(await t()),o=typeof r=="string"?i.find(a=>a.uid===r):i.find(a=>a.email?.toLowerCase()===s.toLowerCase());return o?{ok:!0,summary:`Got user ${o.uid}`,data:{user:rr(o)}}:Tt("auth/user-not-found",typeof r=="string"?`No user found for uid ${r}.`:`No user found for email ${s}.`)}},{name:"auth_list_users",description:"Read every user of the connected sandbox's user store.",parameters:{type:"object",properties:{limit:{type:"number",description:"Return at most this many users."}}},async execute(n){const{limit:r}=Ot(n);if(r!==void 0&&(typeof r!="number"||!Number.isFinite(r)||r<0))return Tt("auth/argument-error","auth_list_users: limit must be a non-negative number.");const s=xe.listUsers(await t()),i=(r!==void 0?s.slice(0,r):s).map(rr);return{ok:!0,summary:`${i.length} of ${s.length} users`,data:{users:i,total:s.length}}}},{name:"auth_update_user",description:"Change one user. Every supplied field replaces what is stored; claims replaces the whole claims map. Omitted fields are left alone.",parameters:{type:"object",properties:{uid:{type:"string",description:"The user to change."},...Ra},required:["uid"]},async execute(n){const r=Ot(n),s=ks(r,"auth_update_user");if(typeof s!="string")return s;const i=r,o={...i.email!==void 0?{email:i.email}:{},...i.password!==void 0?{password:i.password}:{},...i.displayName!==void 0?{displayName:i.displayName}:{},...i.phoneNumber!==void 0?{phoneNumber:i.phoneNumber}:{},...i.disabled!==void 0?{disabled:i.disabled}:{},...i.emailVerified!==void 0?{emailVerified:i.emailVerified}:{},...i.claims!==void 0?{customClaims:i.claims}:{},...i.providers!==void 0?{providerUserInfo:my(i.providers)}:{}};try{const a=xe.updateUser(await t(),s,o);return{ok:!0,summary:`Updated user ${s}`,data:{user:rr(a)}}}catch(a){return sr(a)}}},{name:"auth_delete_user",description:"Remove one user from the connected sandbox's user store.",parameters:{type:"object",properties:{uid:{type:"string",description:"The user to remove."}},required:["uid"]},async execute(n){const r=Ot(n),s=ks(r,"auth_delete_user");if(typeof s!="string")return s;try{return xe.deleteUser(await t(),s),{ok:!0,summary:`Deleted user ${s}`,data:{uid:s}}}catch(i){return sr(i)}}},{name:"auth_set_claims",description:"Replace one user's custom claims. Rules read them as request.auth.token.<name> on the next sign-in or token refresh. An empty object clears them.",parameters:{type:"object",properties:{uid:{type:"string",description:"The user to change."},claims:Na},required:["uid","claims"]},async execute(n){const r=Ot(n),s=ks(r,"auth_set_claims");if(typeof s!="string")return s;if(!Us(r.claims))return Tt("auth/argument-error","auth_set_claims: claims must be an object.");const i=r.claims;try{const o=xe.updateUser(await t(),s,{customClaims:i});return{ok:!0,summary:`Set claims on user ${s}`,data:{user:rr(o)}}}catch(o){return sr(o)}}},{name:"auth_custom_token",description:"Mint a custom token for a uid that the sandbox's signInWithCustomToken accepts. The sandbox has no signing key, so the token is unsigned and is only good against this sandbox.",parameters:{type:"object",properties:{uid:{type:"string",description:"The user the token signs in."},claims:Na},required:["uid"]},async execute(n){const r=Ot(n),s=ks(r,"auth_custom_token");if(typeof s!="string")return s;const i=r.claims;return i!==void 0&&!Us(i)?Tt("auth/argument-error","auth_custom_token: claims must be an object."):{ok:!0,summary:`Minted custom token for ${s}`,data:{uid:s,claims:i??{},token:GA(s,i)}}}}]}const XA={"firestore-simulator":({env:e})=>jv({resolveSandbox:()=>e}),"firestore-data":({resolveDb:e})=>BE({resolveDb:e}),"firestore-inspect":({sandbox:e})=>FE({resolveSandbox:()=>e}),"messaging-inspection":({sandbox:e})=>nA(()=>e),"rtdb-inspection":({sandbox:e})=>KA({resolveSandbox:()=>e}),"auth-users":({sandbox:e})=>QA({resolveSandbox:()=>e})};function ZA(e,t){return t==="admin"?rc(e):Hs(e.withAuth(Wm(t.uid,t.tenant,t.claims)))}function e0(e,t){return t===void 0||t.mode==="app-session"||t.mode==="admin"?rc(e):t.mode==="anon"?Hs(e.withAuth(null)):Hs(e.withAuth({uid:t.uid,...t.token!==void 0?{token:t.token}:{},...t.tenant!==void 0?{tenant:t.tenant}:{}}))}function t0(e,t){const n={sandbox:e,env:Gr(e),resolveDb:r=>r!==void 0?ZA(e,r):e0(e,t)};return zm("forwarded").flatMap(r=>XA[r.key](n))}function n0(e){return e===void 0||e.mode==="app-session"?"app-session":e.mode==="admin"||e.mode==="anon"?e.mode:JSON.stringify([e.uid,e.tenant??null,e.token??null])}const r0=16;function s0(e){const t=new Map;function n(r){const s=n0(r),i=t.get(s);if(i)return i;const o=t0(e,r);WI("sandbox dispatcher tools",o.map(l=>l.name),yy);const a=new Map(o.map(l=>[l.name,l]));if(t.size>=r0)for(const l of[...t.keys()])l!=="app-session"&&t.delete(l);return t.set(s,a),a}return n(void 0),async(r,s,i)=>{const o=n(i).get(r);if(!o)throw new o0(r);const a={signal:new AbortController().signal},l=await o.execute(s,a);return{ok:l.ok,summary:l.summary,data:l.data}}}const Ad=new WeakMap;async function i0(e,t,n,r){let s=Ad.get(e);return s||(s=s0(e),Ad.set(e,s)),s(t,n,r)}const yy=zm("forwarded").flatMap(e=>Object.keys(e.tools));class o0 extends Error{tool;constructor(t){super(`unknown sandbox tool: ${t}`),this.tool=t,this.name="UnknownToolError"}}function a0(e){if(e!==void 0&&e.length>0)return e;if(typeof window<"u"){const r=window;if("__PYRIC_BRIDGE_URL__"in r){const l=r.__PYRIC_BRIDGE_URL__;if(typeof l=="string"&&l.length>0)return l}const i=r.location.hostname||"localhost";return`${r.location.protocol==="https:"?"wss:":"ws:"}//${i}:${Bu}${Fu}`}return`ws://localhost:${Bu}${Fu}`}function c0(e){try{const t=new URL(e),n=t.protocol==="wss:";return t.protocol=n?"https:":"http:",[`${t.origin}/__pyric/health`,`${t.origin}/health`]}catch{return[]}}const l0={op:!0,sub:!0,unsub:!0,disconnect:!0,appConfig:!0,"clock-subscribe":!0,tool:!0};function Pn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function u0(e){return!Pn(e)||!(typeof e.t=="string"&&Object.hasOwn(l0,e.t))?!1:e.t==="op"||e.t==="tool"||e.t==="disconnect"?typeof e.id=="string":e.t==="sub"||e.t==="unsub"?typeof e.subId=="string":!0}function d0(e){return Pn(e)?typeof e.method=="string":!1}function f0(e){if(!Pn(e))return!1;const n=typeof e.target=="string",r=Pn(e.target);return n||r}function Od(e){if(!Pn(e))return!1;switch(e.mode){case"admin":case"anon":case"app-session":return!0;case"as":try{return Cw(e),!0}catch{return!1}default:return!1}}function $d(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function h0(e){if("clientSessionId"in e&&e.clientSessionId!==void 0&&typeof e.clientSessionId!="string")return"Invalid bridge client session ID.";switch(e.type){case"hello":{const n=!$d(e.tools),r=typeof e.sandboxId!="string",s=e.capabilities===void 0||$d(e.capabilities);return n||r||!s?"Invalid sandbox peer handshake.":void 0}case"hello-ack":return typeof e.bridgeVersion!="string"?"Invalid sandbox peer acknowledgement.":void 0;case"tool-call":{const n=typeof e.id=="string",r=typeof e.name=="string",s=Pn(e.args),i=e.callerId===void 0||typeof e.callerId=="string",o=e.actAs===void 0||Od(e.actAs);return!n||!r||!s||!i||!o?"Invalid sandbox tool call envelope.":void 0}case"worker-client-disconnect":case"worker-client-interrupted":return typeof e.clientSessionId=="string"?void 0:"Invalid bridge client session ID.";case"ping":case"pong":return typeof e.id!="string"?"Invalid bridge heartbeat ID.":void 0;case"remote-set-lens":{const n=typeof e.clientSessionId=="string",r=e.id===void 0||typeof e.id=="string",s=Od(e.lens);return!n||!r||!s?"Invalid remote identity lens envelope.":void 0}case"worker-message":return u0(e.message)?void 0:"Invalid worker message envelope.";case"worker-op":{const n=typeof e.id=="string",r=d0(e.op);return!n||!r?"Invalid worker relay operation envelope.":void 0}case"worker-sub":{const n=typeof e.subId=="string",r=f0(e.sub);return!n||!r?"Invalid worker relay subscription envelope.":void 0}case"worker-unsub":return typeof e.subId!="string"?"Invalid worker relay unsubscribe envelope.":void 0;default:return}}const p0=new Set(["hello-ack","tool-call","worker-op","worker-sub","worker-unsub","worker-client-disconnect","ping"]),m0=new TextEncoder,y0=500,g0=3e4,b0=2e3,w0=.5,v0=3;function x0(e,t={}){const n=a0(t.url),r=t.sandboxId??_0(),s=t.dispatcher??i0,i=t.toolNames??[...yy],o=t.initialReconnectDelayMs??y0,a=t.maxReconnectDelayMs??g0,l=t.noReconnect??!1,u=t.onStateChange??(()=>{}),d=t.standbyPollMs??b0,h=t.fetchImpl??(A=>fetch(A)),f=t.workerRelay??null;let p=null,m=!1,g=0,b=null,w=null,x=0,v={kind:"connecting"};const _=new Map;function S(){for(const A of _.values())try{A()}catch{}_.clear()}function k(A){v=A;try{u(A)}catch{}}function N(A){const P=p;if(P!==null&&P.readyState===WebSocket.OPEN)try{const W=Vm(A);if(W===void 0){P.close(wa,Fr);return}P.send(W)}catch{}}function O(){if(m)return;k({kind:"connecting"});let A;try{A=new WebSocket(n)}catch(P){const W=P instanceof Error?P.message:String(P);I(`failed to open WebSocket: ${W}`);return}p=A,A.onopen=()=>{g=0;const P={type:"hello",protocol:1,tools:i,sandboxId:r};f!==null&&(P.capabilities=[SC]),N(P)},A.onmessage=P=>{const T=P.data,W=typeof T=="string";if(W&&m0.encode(T).byteLength>Tr){A.close(wa,Fr);return}let V;try{V=JSON.parse(W?T:"")}catch{A.close(4002,"Invalid bridge message JSON.");return}const F=V;if(!Qp(F)){A.close(4002,"Unrecognized bridge message envelope.");return}if(!p0.has(F.type))return;const M=h0(F);if(M!==void 0){A.close(4002,M);return}if(F.type==="hello-ack"){if(F.protocol!==1){const ie="Unsupported bridge protocol. Expected version 1.";m=!0,k({kind:"disconnected",reason:ie}),A.close(1e3,ie);return}k({kind:"connected",bridgeVersion:F.bridgeVersion});return}if(F.type==="tool-call"){D(F);return}if(F.type==="worker-op"){R(F);return}if(F.type==="worker-sub"){j(F);return}if(F.type==="worker-unsub"){const ut=_.get(F.subId);if(ut!==void 0){_.delete(F.subId);try{ut()}catch{}}return}if(F.type==="worker-client-disconnect"){f?.disconnect?.(F.clientSessionId);return}if(F.type==="ping"){N({type:"pong",id:F.id});return}},A.onclose=P=>{const T=P.reason||`closed (code ${P.code})`;if(p=null,S(),P.code===_C){E();return}I(T)},A.onerror=()=>{}}async function D(A){let P;try{const T=await s(e,A.name,A.args??{},A.actAs,A.callerId);P={type:"tool-result",id:A.id,ok:!0,result:T}}catch(T){const W=T instanceof Error;P={type:"tool-result",id:A.id,ok:!1,error:{code:W?T.name:"Error",message:W?T.message:String(T)}}}N(P)}async function R(A){if(f!==null)try{const T=await f.op(A.op,A.clientSessionId);Vu(`op '${A.op.method}'`,T),N({type:"worker-res",id:A.id,clientSessionId:A.clientSessionId,ok:!0,value:T})}catch(T){const W=T.denialContext,U=T instanceof Error,V={code:T.code??"unknown",message:U?T.message:String(T)};W!==void 0&&(V.denialContext=W),N({type:"worker-res",id:A.id,clientSessionId:A.clientSessionId,ok:!1,error:V})}}function j(A){if(!(f===null||_.has(A.subId)))try{const W=f.subscribe(A.sub,U=>{try{Vu(`subscription '${A.subId}'`,U)}catch(V){const F=V instanceof Error;N({type:"worker-snap",subId:A.subId,clientSessionId:A.clientSessionId,value:{__error:{code:V.code??"invalid-argument",message:F?V.message:String(V)}}});return}N({type:"worker-snap",subId:A.subId,clientSessionId:A.clientSessionId,value:U})},A.clientSessionId);_.set(A.subId,W)}catch(W){const U=W.denialContext,V=W instanceof Error,F={code:W.code??"unknown",message:V?W.message:String(W)};U!==void 0&&(F.denialContext=U),N({type:"worker-snap",subId:A.subId,clientSessionId:A.clientSessionId,value:{__error:F}})}}function E(){if(!m){if(l){k({kind:"disconnected",reason:"replaced by a newer sandbox peer"});return}g=0,x=0,k({kind:"standby"}),$()}}function $(){if(m)return;const A=d*(1+Math.random()*w0);w=setTimeout(()=>{w=null,C()},A)}async function C(){if(m)return;let A=null;for(const U of c0(n))try{const V=await h(U);if(!V.ok)continue;const Se=await V.json();if(typeof Se.sandboxConnected=="boolean"){A=!Se.sandboxConnected;break}}catch{}if(m)return;if(A===!0){O();return}if(A===!1){x=0,$();return}if(x+=1,x>=v0){I("standby health poll unreachable");return}$()}function I(A){if(m)return;if(l){k({kind:"disconnected",reason:A});return}g+=1;const P=Math.min(o*2**(g-1),a);k({kind:"reconnecting",attempt:g,delayMs:P}),b=setTimeout(()=>{b=null,O()},P)}return O(),{disconnect(){m=!0,S();const A=b;A!==null&&(clearTimeout(A),b=null);const T=w;T!==null&&(clearTimeout(T),w=null);const U=p;if(U!==null){try{U.close()}catch{}p=null}k({kind:"disconnected",reason:"client closed"})},state(){return v}}}function _0(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`sb-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function gy(e,t,n="bridge-port"){try{const r=new URL(e,t.href),s=new URL(t.href),i=t.protocol==="https:"?"wss:":"ws:",o=s.port.length>0,a=r.port.length>0,d=n==="bridge-port"&&o&&a?`${s.hostname}:${r.port}`:s.host;return`${i}//${d}${r.pathname}`}catch{return e}}function S0(e,t){return{url:t,dispatcher:(n,r,s,i)=>_N(e,r,s,i),workerRelay:{op:n=>SN(e,n),subscribe:(n,r)=>kN(e,n,r)}}}async function k0(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 o=t.locationLike??(typeof window<"u"?window.location:null),a=o?gy(i,o):i,l=x0(null,{...S0(e,a),...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",a),l}const j0={};function E0(){return!1}function C0(){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 N0(e,t={}){if(e==="local"){const r=t.baseUrl??"",s=E0(),o=t.persistence==="memory"||s?Nw():JE(r),l=t.disableLive===!0?null:II(t.workerUrl),d=l!==null&&l.runtime.getSnapshot().mode!=="hosted"?C0():null;let h=!1,f=null;l!==null&&d!==null&&k0(l.db,{baseUrl:r,onStateChange:x=>d.set(x)}).then(x=>{h?x?.disconnect():f=x});const m={mode:e,projects:s?XE():KE(r),persistence:o,dispose(){h=!0,f?.disconnect(),l?.dispose()}},g=l!==null,b=d!==null;return g&&(m.live=l),b&&(m.bridge=d),!s&&(m.workspace=Kp(r)),m}throw new Error(`createStudioEnvironment(${e}): only 'local' is wired in v1 (T3). 'browser'/'hosted' land in A3.`)}const by=y.createContext(null),R0={status:"pending",env:null,error:null};function I0(e){try{return{status:"ready",env:N0(e),error:null}}catch(t){return{status:"error",env:null,error:t instanceof Error?t:new Error(String(t))}}}function A0({mode:e="local",children:t}){const[n,r]=y.useState(null);y.useEffect(()=>{const i=I0(e);return r({mode:e,state:i}),()=>{i.status==="ready"&&i.env.dispose()}},[e]);const s=n?.mode===e?n.state:R0;return c.jsx(by.Provider,{value:s,children:t})}function lt(){const e=y.useContext(by);if(!e)throw new Error("useEnvironment must be used within an <EnvironmentProvider>");return e}const O0="pyric-studio:theme",Bs="dark";function $0(){return Bs}function D0(){typeof document>"u"||document.documentElement.setAttribute("data-theme","dark")}const P0=y.createContext(null);function T0({children:e}){const[t,n]=y.useState($0);y.useEffect(()=>{D0();try{localStorage.setItem(O0,Bs)}catch{}},[t]);const r="dark",s=y.useCallback(a=>n(Bs),[]),i=y.useCallback(()=>n(Bs),[]),o=y.useMemo(()=>({choice:t,resolvedTheme:r,setChoice:s,cycleChoice:i}),[t,r,s,i]);return c.jsx(P0.Provider,{value:o,children:e})}function Ti(){const e=typeof import.meta<"u"&&"/__pyric/ui/"||"/";return e.endsWith("/")?e:`${e}/`}function M0(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 $c(e,t="",n=Ti()){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)),[o="",...a]=i;return{tab:o,rest:a,query:M0(t)}}function L0(e,t=Ti()){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 wy="studio",U0=[{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 B0({assuranceEnabled:e=!1}={}){return U0.filter(t=>t.id!=="assurance"||e)}const dn=B0({assuranceEnabled:!1}),F0=dn.map(e=>e.id);function q0(e){return dn.find(t=>t.id===e)??dn[0]}const Ia="pyric:studio:navigated",V0={tab:"",rest:[],query:{}};function Dc(){return typeof window<"u"?window.location.pathname+window.location.search:""}function W0(e){return e===""||e===wy?"home":e}function Ke(){if(typeof window>"u")return V0;const e=$c(window.location.pathname,window.location.search);return{...e,tab:W0(e.tab)}}function z0(e){return e.tab==="home"?{...e,tab:wy}:e}function Ct(e){return L0(z0(e))}function vy(){typeof window<"u"&&window.dispatchEvent(new Event(Ia))}function Ae(e){if(typeof window>"u")return;const t=Ct(e);Dc()!==t&&(window.history.pushState(null,"",t),vy())}function qr(e){typeof window>"u"||(window.history.replaceState(null,"",Ct(e)),vy())}function Gt(e){return typeof window>"u"?()=>{}:(window.addEventListener("popstate",e),window.addEventListener(Ia,e),()=>{window.removeEventListener("popstate",e),window.removeEventListener(Ia,e)})}function H0(e,t){const n=y.useCallback(i=>e.includes(i)?i:t,[e,t]),r=y.useSyncExternalStore(Gt,()=>n(Ke().tab),()=>t);y.useEffect(()=>{const i=typeof window<"u"?window.location.hash:"";if(i.length>1){const a=i.slice(1),l=a.indexOf("?"),u=$c(`/${l===-1?a:a.slice(0,l)}`,l===-1?"":a.slice(l),"/");if(e.includes(u.tab)){qr(u);return}}const o=Ke();e.includes(o.tab)||qr({tab:n(o.tab)})},[n]);const s=y.useCallback(i=>{const o=n(i);o!==r&&Ae({tab:o})},[n,r]);return[r,s]}let Aa=null;function K0(e){Aa=e}function G0(){return Aa?(Aa(),!0):!1}function J0(e){return(e.metaKey||e.ctrlKey)&&!e.altKey&&!e.shiftKey&&(e.key==="k"||e.key==="K")}function Y0(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 Q0=7;function X0(e,t){const n=e.trim();if(!n)return[];const r=t.filter(h=>h.id!=="settings"),s=[],i=[],o=[],[a="",...l]=n.split(/\s+/),u=l.join(" ");for(const h of r){const f={id:`tab:${h.id}`,label:`Go to ${h.label}`,hint:h.description,target:{tab:h.id}},p=h.label.toLowerCase();if(p.startsWith(n.toLowerCase())?s.push(f):Y0(n,h.label)&&i.push(f),u&&(p===a.toLowerCase()||p.startsWith(a.toLowerCase()))){const m=u.split("/").filter(Boolean);h.id==="firestore"||h.id==="storage"?o.push({id:`deep:${h.id}:${u}`,label:`Open /${m.join("/")} in ${h.label}`,hint:h.id==="firestore"?"Firestore path":"Storage object path",target:{tab:h.id,rest:m}}):h.id==="auth"?o.push({id:`deep:auth:${u}`,label:`Open user ${u} in Auth`,hint:"Auth uid",target:{tab:"auth",rest:[u]}}):h.id==="traffic"&&o.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 h=d[1].split("/").filter(Boolean);o.unshift({id:`deep:storage:${d[1]}`,label:`Open ${d[1]} in Storage`,hint:"Storage object path",target:{tab:"storage",rest:h}})}else if(n.includes("/")&&!n.includes(" ")){const h=n.split("/").filter(Boolean);h.length&&o.push({id:`deep:firestore:${n}`,label:`Open /${h.join("/")} in Firestore`,hint:"Firestore path",target:{tab:"firestore",rest:h}})}return[...s,...o,...i].slice(0,Q0)}function Oa(e){return`${e.kind}:${e.target.tab}:${(e.target.rest??[]).join("/")}`}const $a={docsPerCollection:50,collectionsScanned:20,users:100,objects:200,storageListCalls:20,subcollections:30,subcollectionRpcCalls:40};async function Z0(e,t,{maxObjects:n,maxListCalls:r}){const s=[],i=[e];let o=0;for(;i.length&&s.length<n&&o<r;){o++;const a=await t(i.shift());for(const l of a.items){if(s.length>=n)break;s.push(l.fullPath)}i.push(...a.prefixes)}return s}async function eO(e,t,n,{maxSubcollections:r,maxRpcCalls:s,docsPerCollection:i}){const o=[],a=[],l=[...e];let u=0;for(;l.length&&o.length<r&&u<s;){const d=l.shift();u++;let h=[];try{h=await t(d)}catch{continue}for(const f of h){if(o.length>=r)break;const p=`${d}/${f}`;o.push(p);try{const m=await n(p,i);for(const g of m.slice(0,i))a.push(g),l.push(g)}catch{}}}return{subcollections:o,documents:a}}const tO=5;function hi(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,o=-1,a=-1;for(let u=0;u<r.length&&i<n.length;u++)r[u]===n[i]&&(o===-1&&(o=u),a=u,i++);if(i!==n.length)return 0;const l=a-o+1;return Math.max(1,400-(l-n.length)*10-Math.min(o,50))}const nO={collection:"Firestore collections",document:"Firestore documents",subcollection:"Firestore subcollections",user:"Auth users",object:"Storage objects","rtdb-key":"RTDB keys"},rO=["collection","document","subcollection","user","object","rtdb-key"];function sO(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 xy(e){return e.endsWith("/")?{base:e.slice(0,-1),trailing:!0}:{base:e,trailing:!1}}function iO(e,t){const{base:n,trailing:r}=xy(e);if(!n)return 0;const s=n.split("/"),i=t.split("/");if(s.length>i.length)return 0;const o=s.length-1;for(let a=0;a<o;a++)if(s[a].toLowerCase()!==i[a].toLowerCase())return 0;return r?s[o].toLowerCase()===i[o].toLowerCase()?850:0:hi(s[o],i[o])}function oO(e,t){const{base:n,trailing:r}=xy(e);if(!n||n.includes("/"))return 0;const s=t.split("/").pop()??t;return r?s.toLowerCase()===n.toLowerCase()?850:0:hi(n,s)}function Dd(e,t,n,r=tO){const s=e.trim();if(!s)return[];const i=[],o=X0(e,t);o.length&&i.push({kind:"navigate",title:"Go to",results:o});for(const a of rO){const l=a==="document"||a==="subcollection",u=a==="collection"||a==="subcollection",d=new Map;for(const f of n)f.kind===a&&d.set(Oa(f),f);const h=[...d.values()].map(f=>({entry:f,score:Math.max(hi(s,f.label),f.alt?hi(s,f.alt):0,l?iO(s,f.label):0,u?oO(s,f.label):0)})).filter(f=>f.score>0).sort((f,p)=>p.score-f.score||f.entry.label.localeCompare(p.entry.label)).slice(0,r);h.length&&i.push({kind:a,title:nO[a],results:h.map(({entry:f})=>({id:Oa(f),label:f.label,hint:sO(f),target:f.target}))})}return i}function Pd(e){return e.flatMap(t=>t.results)}function aO(e){return{kind:"collection",label:e,target:{tab:"firestore",rest:[e]}}}function Td(e){return{kind:"document",label:e,target:{tab:"firestore",rest:e.split("/").filter(Boolean)}}}function cO(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 lO(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 uO(e){return{kind:"object",label:e,target:{tab:"storage",rest:e.split("/").filter(Boolean)}}}function dO(e){return{kind:"rtdb-key",label:e,target:{tab:"rtdb",rest:[e]}}}async function fO(e,t={},n){const r={...$a,...t},s=[],i=d=>{d.length&&(s.push(...d),n?.(d))},o=(async()=>{let d=[];try{d=await e.listRootCollections?.()??[]}catch{d=[]}d.length&&i(d.map(aO));const h=[];if(e.listDocumentPaths)for(const f of d.slice(0,r.collectionsScanned))try{const m=(await e.listDocumentPaths(f,r.docsPerCollection)).slice(0,r.docsPerCollection);h.push(...m),i(m.map(Td))}catch{}if(e.listSubcollections&&e.listDocumentPaths)try{const{subcollections:f,documents:p}=await eO(h,e.listSubcollections,e.listDocumentPaths,{maxSubcollections:r.subcollections,maxRpcCalls:r.subcollectionRpcCalls,docsPerCollection:r.docsPerCollection});i(f.map(cO)),i(p.map(Td))}catch{}})(),a=(async()=>{if(e.listUsers)try{const d=await e.listUsers(r.users);i(d.slice(0,r.users).map(lO))}catch{}})(),l=(async()=>{if(e.listStorageObjectPaths)try{const d=await e.listStorageObjectPaths(r.objects);i(d.slice(0,r.objects).map(uO))}catch{}})(),u=(async()=>{if(e.listRtdbTopLevelKeys)try{i((await e.listRtdbTopLevelKeys()).map(dO))}catch{}})();return await Promise.allSettled([o,a,l,u]),s}function hO(e,t,n){const r={name:n,options:structuredClone(t),automaticDataCollectionEnabled:!0};return uC(r,e),r}const pO=Object.freeze({source:Object.freeze({kind:"studio"}),authLens:Object.freeze({mode:"admin"})});function mO(e){return Zf(e.withAuth(null),pO)}const yO="pyric-studio";function _y(e,t){return e.listDocuments(t).map(({path:n,phantom:r})=>({path:n,phantom:r}))}let gO=0;function bO(e){const t=hO(e,{projectId:"pyric-studio"},`pyric-studio-${gO++}`),n=Gr(e),r=mO(e);return{sandbox:e,app:t,firestore:Hs(e),adminFirestore:rc(r),auth:mc(e),storage:hk(r),listRootCollections:()=>n.listRootCollections(),listSubcollections:s=>n.listSubcollections(s),listDocuments:s=>_y(n,s)}}function wO(e,t){const[n,r]=y.useState(!1),[s,i]=y.useState(null),o=y.useMemo(()=>Gw(),[]),a=y.useMemo(()=>{try{return bO(o)}catch(u){return i(u instanceof Error?u:new Error(String(u))),null}},[o]);return y.useEffect(()=>{let u=!1;if(!e){r(!1);return}return o.enablePersistence({key:yO,injectedBackend:e}).then(()=>{u||r(!0)}).catch(d=>{u||i(d instanceof Error?d:new Error(String(d)))}),()=>{u=!0}},[o,e]),s?{status:"error",handles:null,error:s}:a?e!=null&&n||t==="ready"?{status:"ready",handles:a}:{status:"pending",handles:null}:{status:"error",handles:null,error:new Error("Studio: failed to construct the sandbox data handles.")}}function vO(e){const t=Gr(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=>_y(t,n)}}function Rt(){const e=Kt(),t=lt(),n=t.status==="ready"?t.env.persistence:void 0,r=wO(n,t.status),s=t.status==="ready"?t.env.live:void 0,i=xO(s);return y.useMemo(()=>{switch(e.status){case"ready":return{status:"ready",handles:vO(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 o=s.db;return{status:"ready",firestoreApi:s.firestoreApi,authApi:s.authApi,storageApi:s.storageApi,handles:{...r.handles,firestore:o,adminFirestore:o,auth:s.auth,storage:s.storage,listRootCollections:()=>i,listSubcollections:a=>s.listSubcollections(a),listDocuments:a=>s.listDocuments(a)}}}return r}}},[e,r,s,i])}function xO(e){const[t,n]=y.useState([]);return y.useEffect(()=>{if(!e){n([]);return}let r=!0;const s=()=>{e.listRootCollections().then(o=>{r&&n(o)}).catch(()=>{})};try{e.setLens({mode:"admin"})}catch{}s();const i=e.feed.subscribe(()=>s());return()=>{r=!1,i()}},[e]),t}function _O(e){let t=!0;return n=>{const r=t;t=!1,e(s=>kO(s,n,r))}}function SO(e){const t=new Map;for(const n of e)t.set(Oa(n),n);return[...t.values()]}function kO(e,t,n){return SO(n?t:[...e??[],...t])}const jO=3e4;function Sy(){const e=Rt(),t=lt(),[n,r]=y.useState(null),[s,i]=y.useState(!1),o=y.useRef(!1),a=y.useRef(e);a.current=e;const l=t.status==="ready"?t.env.live:void 0,u=y.useRef(l);u.current=l;const d=y.useRef(null),h=y.useRef(0),f=y.useRef(null),p=y.useRef(0),m=y.useCallback(b=>{const w=a.current;if(w.status!=="ready")return;const x=++h.current;o.current=!0,i(!0);const v=w.handles,_=v.adminFirestore,S=w.firestoreApi?.collection??hr,k=w.firestoreApi?.query??li,N=w.firestoreApi?.getDocs??ci,O=w.firestoreApi?.limit??ui,D=w.storageApi?.ref??Ar,R=w.storageApi?.listAll??Sc,j=w.authApi?.listUsers??xe.listUsers,E={listRootCollections:()=>v.listRootCollections(),listDocumentPaths:async(C,I)=>(await N(k(S(_,C),O(I)))).docs.slice(0,I).map(P=>`${C}/${P.id}`),listSubcollections:C=>Promise.resolve(v.listSubcollections(C)),listUsers:async C=>(await Promise.resolve(j(v.auth))).slice(0,C).map(A=>({uid:A.uid,email:A.email??null})),listStorageObjectPaths:C=>Z0(D(v.storage,""),R,{maxObjects:C,maxListCalls:$a.storageListCalls}),listRtdbTopLevelKeys:async()=>{const C=u.current;if(!C)return[];const I=Date.now()-p.current<jO;if(f.current!==null&&I&&!b?.rtdbLikely)return f.current;const A=await C.readRtdbState(),P=A===null||typeof A!="object"||Array.isArray(A)?[]:Object.keys(A);return f.current=P,p.current=Date.now(),P}},$=_O(C=>r(C));fO(E,$a,C=>{x===h.current&&$(C)}).catch(()=>{}).finally(()=>{if(x===h.current&&(o.current=!1,i(!1),r(C=>C??[]),d.current)){const C=d.current;d.current=null,m(C)}})},[]),g=y.useCallback(b=>{if(a.current.status==="ready"){if(o.current){d.current={...d.current,...b};return}m(b)}},[m]);return y.useEffect(()=>{e.status==="ready"&&n===null&&!o.current&&m()},[e,n,m]),{entries:n,building:s,ensure:g}}const EO=150;function CO(e){return e.startsWith("/")||/rtdb/i.test(e)}function ky({autoFocus:e,onNavigated:t,onEscape:n,exposeFocus:r}){const[s,i]=y.useState(""),[o,a]=y.useState(""),[l,u]=y.useState(0),[d,h]=y.useState(!1),f=y.useRef(null),{entries:p,building:m,ensure:g}=Sy();y.useEffect(()=>{if(r)return r(()=>f.current?.focus()),()=>r(null)},[r]),y.useEffect(()=>{e&&f.current?.focus()},[e]),y.useEffect(()=>{const S=setTimeout(()=>a(s),EO);return()=>clearTimeout(S)},[s]);const b=y.useMemo(()=>Dd(o,dn,p??[]),[o,p]),w=y.useMemo(()=>Pd(b),[b]);y.useEffect(()=>{u(S=>w.length===0?0:Math.min(S,w.length-1))},[w.length]);const x=S=>{S&&(i(""),a(""),h(!1),Ae(S.target),t?.(S.target))},v=()=>{if(s===o){x(w[l]??w[0]);return}const S=Pd(Dd(s,dn,p??[]));x(S[0])};let _=0;return c.jsxs("div",{className:"studio-home__command",children:[c.jsx("div",{className:"studio-home__command-row",children:c.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&&w.length>0,"aria-autocomplete":"list",onFocus:()=>{g(),h(!0)},onBlur:()=>h(!1),onChange:S=>{const k=S.target.value;i(k),h(!0),CO(k)&&g({rtdbLikely:!0})},onKeyDown:S=>{if(S.key==="ArrowDown")S.preventDefault(),u(k=>Math.min(k+1,Math.max(w.length-1,0)));else if(S.key==="ArrowUp")S.preventDefault(),u(k=>Math.max(k-1,0));else if(S.key==="Enter")v();else if(S.key==="Escape"){if(n){n();return}i(""),a(""),h(!1)}}})}),d&&!b.length&&m&&p===null?c.jsx("div",{className:"studio-home__command-results",role:"status","aria-live":"polite",children:c.jsx("span",{className:"studio-home__command-group-title",children:"Indexing sandbox…"})}):null,d&&b.length?c.jsx("div",{className:"studio-home__command-results",role:"listbox","aria-label":"Suggestions",onMouseDown:S=>S.preventDefault(),children:b.map(S=>{const k=_;return _+=S.results.length,c.jsxs("div",{className:"studio-home__command-group",children:[c.jsx("span",{className:"studio-home__command-group-title","aria-hidden":"true",children:S.title}),c.jsx("ul",{className:"studio-home__command-group-list",children:S.results.map((N,O)=>{const D=k+O;return c.jsx("li",{children:c.jsxs("button",{type:"button",role:"option","aria-selected":D===l,className:"studio-home__command-result","data-active":D===l?"true":void 0,onMouseEnter:()=>u(D),onClick:()=>x(N),children:[c.jsx("span",{className:"studio-home__command-label",children:N.label}),c.jsx("span",{className:"studio-home__command-sub",children:N.hint})]})},N.id)})})]},S.kind)})}):null]})}function NO({onClose:e}){const t=y.useRef(null);return y.useEffect(()=>(t.current=document.activeElement,()=>{const n=t.current;n instanceof HTMLElement&&n.focus()}),[]),y.useEffect(()=>{const n=r=>{r.key==="Escape"&&e()};return window.addEventListener("keydown",n),()=>window.removeEventListener("keydown",n)},[e]),c.jsx("div",{className:"studio__cmdk-backdrop",onMouseDown:e,children:c.jsx("div",{className:"studio__cmdk",role:"dialog","aria-modal":"true","aria-label":"Command",onMouseDown:n=>n.stopPropagation(),children:c.jsx(ky,{autoFocus:!0,onEscape:e,onNavigated:e})})})}function Pc(e){if(e.result==="allow")return!1;const t=e.queryProof?.kind;return t==="unsupported-predicate"||t==="unsupported-path"}function RO(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=lh(e);return t?t.rules.kind==="evaluated":!1}function IO(e){return"service"in e&&typeof e.service=="string"?e.service:"firestore"}function AO(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 OO(e){if(!("request"in e)||!e.request)return;const n=e.request.updateMask;return Array.isArray(n)&&n.every(s=>Array.isArray(s)&&s.every(i=>typeof i=="string"))?n:void 0}function $O(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 DO(e){const t=[];for(const r of e)RO(r)&&t.push(PO(r));return $O(t,e).sort((r,s)=>s.at-r.at)}function PO(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:IO(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),"queryProof"in e&&e.queryProof&&(i.queryProof=e.queryProof),"rules"in e&&e.rules&&(i.rules=e.rules);const o=AO(e);o!==void 0&&(i.resourceData=o);const a=OO(e);return a!==void 0&&(i.updateMask=a),"resourceBefore"in e&&e.resourceBefore&&(i.resourceBefore={data:e.resourceBefore.data,exists:e.resourceBefore.exists}),i}const Md=/^Rule #(\d+) \(([^)]+)\) → (ALLOW|deny|unsupported)/;function TO(e){const t=e.rules?.engine??e.service;return t==="rtdb"||t==="storage"?t:"firestore"}function MO(e){return e==="Validation rule evaluated to false"||!!e?.startsWith("Validation rule at '")}function jy(e){if(MO(e.rules?.reason))return"validate";const t=e.method;return t==="get"||t==="list"||t==="listen"?"read":"write"}function LO(e,t){const n=e.rules?.matchedPath;if(!(!t||!n||e.rules?.errorCode==="NO_MATCHING_RULE"))return RA(t,n,`.${jy(e)}`)?.line}function Tc(e){if(e.result!=="allow")return e.queryProof?.failures.find(t=>t.kind===e.queryProof?.kind)}function UO(e){const t=TO(e),n=e.reasons.filter(i=>Md.test(i)),r=e.reasons.filter(i=>!Md.test(i)),s=Tc(e);if(s)return{headline:Pc(e)?`Query proof unsupported: Pyric could not prove ${e.method} ${e.path} safe. This does not establish Firebase's decision.`:`The query constraints do not satisfy the list rule for ${e.path}.`,engine:t,ruleNode:s.rule?.citation??"list rule",ruleExpression:s.rule?.expression,ruleLines:n,otherLines:r,implicitDeny:!1};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 o=e.matchedRule,a=`Rule #${o.ruleIndex} (${o.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"?FO(e,n,r):t==="storage"?qO(e,n,r):BO(e,n,r)}function BO(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 o=e.matchedRule;i=`Rule #${o.ruleIndex} (${o.operations.join(", ")})`,s=`${i} denied ${e.method} on ${e.path}.`}return{headline:s,engine:"firestore",ruleNode:i,ruleLines:t,otherLines:n,implicitDeny:r}}function FO(e,t,n){const r=e.rules,s=jy(e),i=!r?.matchedPath||r?.errorCode==="NO_MATCHING_RULE",o=r?.pathVariableBindings&&Object.keys(r.pathVariableBindings).length>0?r.pathVariableBindings:void 0;let a,l;return i?a=`No \`.${s}\` rule granted ${e.method} on ${e.path}: RTDB implicit deny (no rule matched).`:s==="validate"?(l=`${r.matchedPath} .validate`,a=`The \`.validate\` rule at \`${r.matchedPath}\` rejected the proposed value for ${e.method} ${e.path}.`):(l=`${r.matchedPath} .${s}`,a=`The \`.${s}\` rule at \`${r.matchedPath}\` evaluated false for ${e.method} ${e.path}.`),{headline:a,engine:"rtdb",ruleNode:l,ruleExpression:r?.matchedRule,phase:s,bindings:o,ruleLines:t,otherLines:n,implicitDeny:i}}function qO(e,t,n){const r=e.reasons.find(a=>/^match\s/.test(a)),i=e.reasons.some(a=>/^no rule matches/.test(a))||!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 VO(e){return e.skipped?"skipped":e.error!==void 0?"error":e.value===!0?"true":e.value===!1?"false":"value"}function WO(e){const t=e.evaluatedRule?.expressionTrace;if(!t||t.length===0)return[];const n=t.map(s=>({source:s.source,outcome:VO(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}const zO={ALLOW:"true",DENY:"false",ERROR:"error",UNSUPPORTED:"unsupported"};function HO(e,t){const n=e.rules?.rtdbTrace;return!n||n.length===0?[]:(t===void 0?[...n]:sy(t,n)).map(s=>{const i={source:s.conditionText,outcome:zO[s.verdict],...s.verdict==="ALLOW"||s.verdict==="DENY"?{value:s.verdict==="ALLOW"}:{},...s.message!==void 0?{error:s.message}:{},depth:0,children:[]},o={path:s.path,kind:s.kind,verdict:s.verdict,step:i,bindings:s.pathVariableBindings};return s.line!==void 0&&(o.line=s.line),o})}function KO(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}const Sr=500;function No(e,t){if(e.length<=Sr)return e;const n=e.slice(-Sr);if(t==="recent")return n;const r=new Set(oc(e).map(i=>i.id));return[...e.slice(0,-Sr).filter(i=>(i.kind==="listener_attach"||i.kind==="listener"&&i.phase==="attach")&&r.has(i.listenerId)),...n]}function Jt(e="recent"){const t=Kt(),n=lt(),r=n.status==="ready"?n.env.live?.feed:void 0,s=t.status==="ready",[i,o]=y.useState([]);y.useEffect(()=>{if(s||!r){o([]);return}return o(No(r.history(),e)),r.subscribe(u=>o(d=>No(WE(d,u),e)))},[s,r,e]);const a=y.useMemo(()=>s?No(t.events,e):[],[s,t,e]);return s?a:i}function GO(e){return Rw(e)}function JO(e){if(typeof e!="string")return!1;const t=e.toLowerCase();return t==="permission_denied"||t==="permission-denied"||t==="auth/permission-denied"}function YO(e){const t=lh(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,queryProof:t.queryProof};if(e.kind==="listener"){let s="error";if(e.result!==void 0)s=e.result;else{const a=e.error;a!==void 0&&JO(a.code)&&(s="deny")}let i="(service)";e.target.path!==void 0&&(i=e.target.path);let o=[];if(e.reasons!==void 0)o=e.reasons;else{const a=e.error;a!==void 0&&a.reasons!==void 0&&(o=a.reasons)}return{kind:"operation",service:e.service,id:e.id,at:e.at,method:"listen",path:i,auth:e.auth,result:s,reasons:o,origin:"listener",triggeredBy:e.triggeredBy,operationContext:t.context,rulesDisposition:t.rules,queryProof:t.queryProof}}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,queryProof:t.queryProof}}function QO(){const e=Jt();return y.useMemo(()=>e.filter(GO).map(YO),[e])}function XO(){const e=Jt();return y.useMemo(()=>DO(e),[e])}const ZO={status:"loading",payload:null},js={status:"absent",payload:null};let pi=ZO,Ld=!1;const Da=new Set;function Es(e){pi=e;for(const t of Da)t()}function e$(){if(!Ld){if(Ld=!0,typeof fetch>"u"){pi=js;return}fetch("/__pyric/init.json").then(async e=>{if(!e.ok||!(e.headers.get("content-type")??"").includes("json"))return Es(js);const n=await e.json();Es({status:"ready",payload:n})}).catch(()=>Es(js))}}function t$(e){return Da.add(e),e$(),()=>Da.delete(e)}function cs(){return y.useSyncExternalStore(t$,()=>pi,()=>pi)}function n$(e){return e.kind==="absent"?"absent":e.sandboxConnected?"available":"idle"}function r$(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 s$(e){try{const t=await e("/__pyric/health");return t.ok?(t.headers.get("content-type")??"").includes("json")?r$(t.status,await t.json()):{kind:"absent"}:{kind:"absent"}}catch{return{kind:"absent"}}}function i$(e=5e3){const[t,n]=y.useState("checking");return y.useEffect(()=>{if(typeof fetch>"u"){n("absent");return}let r=!0,s=null;const i=async()=>{const u=n$(await s$(fetch));return r&&(n(u),u==="absent"&&s&&(clearInterval(s),s=null)),u},o=()=>typeof document>"u"||document.visibilityState!=="hidden",a=()=>{s||(s=setInterval(()=>{o()&&i()},e))},l=()=>{o()&&i()};return i().then(u=>{r&&u!=="absent"&&a()}),typeof document<"u"&&document.addEventListener("visibilitychange",l),()=>{r=!1,s&&clearInterval(s),typeof document<"u"&&document.removeEventListener("visibilitychange",l)}},[e]),t}const o$="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 a$(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 c$(e){return e==="studio"?"Studio":"App"}function l$(e,t,n=Date.now()){const r=e.clients.length,s=e.clients.map(o=>({clientId:o.clientId,kindLabel:c$(o.kind),route:o.route||"/",visibilityLabel:o.visibility==="hidden"?"Hidden":"Visible",isThisPage:o.clientId===t,freshnessLabel:a$(o.lastSeen,n)}));s.sort((o,a)=>o.isThisPage!==a.isThisPage?o.isThisPage?-1:1:o.kindLabel!==a.kindLabel?o.kindLabel==="Studio"?-1:1:o.route.localeCompare(a.route));const i=s.filter(o=>!o.isThisPage).length;return{count:r,chipLabel:r===1?"1 page connected":`${r} pages connected`,prominent:r>1,clients:s,boundaryCopy:o$,otherCount:i}}function u$(){const e=lt(),t=e.status==="ready"&&e.env.live?e.env.live:null,[n,r]=y.useState(null);return y.useEffect(()=>{if(!t){r(null);return}const s=t.presenceClientId;return t.subscribePresence(i=>{r(l$(i,s))})},[t]),n}const d$=new Set(["flutter","swift","ios","kotlin","android"]);function f$(e){const t=(e.platform||"").toLowerCase();return d$.has(t)}function h$(){const e=cs(),[t,n]=y.useState([]),[r,s]=y.useState(!1),i=y.useRef(null),o=y.useRef(new Map);return y.useEffect(()=>{if(e.status!=="ready"||!e.payload.bridgeUrl){s(!1),n([]);return}let l=!1,u=null,d=1e3;const h=typeof window<"u"?window.location:null,f=h?gy(e.payload.bridgeUrl,h):e.payload.bridgeUrl;function p(){if(!l)try{const m=new WebSocket(f);i.current=m,m.onopen=()=>{if(l){m.close();return}s(!0),d=1e3;try{m.send(JSON.stringify({type:"attach",protocol:1,clientInfo:{platform:"studio",deviceLabel:"Desktop Studio"}}))}catch{}},m.onmessage=g=>{if(!l)try{const b=JSON.parse(g.data);if(b.type==="consumer-presence"){const x=(b.consumers||[]).filter(f$);n(x)}else if(b.type==="remote-set-lens-ack"){const w=b;if(w.id&&o.current.has(w.id)){const x=o.current.get(w.id);o.current.delete(w.id),x?.(w.ok)}}}catch{}},m.onclose=()=>{i.current=null,!l&&(s(!1),u=setTimeout(()=>{d=Math.min(d*1.5,1e4),p()},d))},m.onerror=()=>{}}catch{s(!1)}}return p(),()=>{if(l=!0,u&&clearTimeout(u),i.current){try{i.current.close()}catch{}i.current=null}for(const m of o.current.values())m(!1);o.current.clear(),s(!1)}},[e]),{consumers:t,connected:r,setLens:async(l,u)=>{n(f=>f.map(p=>p.clientSessionId===l?{...p,activeLens:u,lastSeen:Date.now()}:p));const d=i.current;if(!d||d.readyState!==WebSocket.OPEN)return!1;const h=`lens-${Date.now()}-${Math.random().toString(36).slice(2,7)}`;return new Promise(f=>{const p=setTimeout(()=>{o.current.delete(h),f(!0)},5e3);o.current.set(h,m=>{clearTimeout(p),f(m)});try{d.send(JSON.stringify({type:"remote-set-lens",id:h,clientSessionId:l,lens:u}))}catch{clearTimeout(p),o.current.delete(h),f(!1)}})}}}const p$={listUsers:xe.listUsers,subscribeUsers:xe.subscribeUsers,createUser:xe.createUser,updateUser:xe.updateUser,deleteUser:xe.deleteUser,clearUsers:xe.clearUsers,getAuthProviderConfig:xe.getAuthProviderConfig,setAuthProviderConfig:xe.setAuthProviderConfig,subscribeAuthProviderConfig:xe.subscribeAuthProviderConfig},Ey=y.createContext(p$);function m$(){return y.useContext(Ey)}function Cy({value:e,children:t}){return y.createElement(Ey.Provider,{value:e},t)}function y$(e,t){return[e.uid,e.email,e.displayName,e.phoneNumber].some(n=>n!=null&&n.toLowerCase().includes(t))}function Mi(e){const{listUsers:t,subscribeUsers:n,createUser:r,updateUser:s,deleteUser:i,clearUsers:o}=m$(),[a,l]=y.useState([]),[u,d]=y.useState(!0),[h,f]=y.useState(void 0),[p,m]=y.useState(""),g=y.useCallback(k=>{l(k),f(void 0),d(!1)},[]);y.useEffect(()=>{let k=!1;d(!0),f(void 0);const N=j=>{k||g(j)},O=j=>{k||(l([]),f(j instanceof Error?j:new Error(String(j))),d(!1))},D=()=>{try{const j=t(e);j&&typeof j.then=="function"?j.then(N).catch(O):N(j)}catch(j){O(j)}};let R;try{D(),R=n(e,D)}catch(j){O(j)}return()=>{k=!0,R?.()}},[e,t,n,g]);const b=y.useMemo(()=>{const k=p.trim().toLowerCase();return k?a.filter(N=>y$(N,k)):a},[a,p]),w=y.useCallback(k=>r(e,k),[e,r]),x=y.useCallback((k,N)=>s(e,k,N),[e,s]),v=y.useCallback(k=>i(e,k),[e,i]),_=y.useCallback(()=>o(e),[e,o]),S=y.useCallback(()=>{const k=t(e);k&&typeof k.then=="function"?k.then(g).catch(()=>{}):g(k)},[e,t,g]);return{users:b,totalCount:a.length,isLoading:u,error:h,filter:p,setFilter:m,createUser:w,updateUser:x,deleteUser:v,clearUsers:_,refresh:S}}const g$=["iss","aud","sub","iat","exp","nbf","jti","nonce","azp","acr","amr","cnf","auth_time","firebase","at_hash","c_hash"],b$=1e3;function Ny(e){const t=e.trim();if(!t)return{ok:!0,claims:void 0};if(t.length>b$)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 g$)if(r in n)return{ok:!1,message:`Custom claims must not have forbidden key: ${r}`};return{ok:!0,claims:n}}const w$={email:"",password:"",displayName:"",phoneNumber:"",photoUrl:"",emailVerified:!1,disabled:!1,claimsText:"",providerIds:[]},v$=new Set(["password","anonymous","phone"]),x$=/^[^@]+@[^@]+\.[^@]+$/,Ud=6;function _$(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=>!v$.has(t))}:{...w$}}function S$(e){const t=_$(e);return{fields:t,initial:{...t}}}function k$(e,t){switch(t.type){case"setField":return{...e,fields:{...e.fields,[t.field]:t.value}};case"reset":return{...e,fields:{...e.initial}}}}function j$(e){const t={},n=e.email.trim(),r=e.password;n&&!x$.test(n)&&(t.email="Invalid email"),r&&r.length<Ud&&(t.password=`Password should be at least ${Ud} characters`),r&&!n&&(t.password="Email is required for password authentication");const s=Ny(e.claimsText);return s.ok||(t.claims=s.message),t}function E$(e){const{fields:t,initial:n}=e;return Object.keys(t).some(r=>r==="providerIds"?!Ry(t.providerIds,n.providerIds):t[r]!==n[r])}function Ry(e,t){if(e.length!==t.length)return!1;const n=[...t].sort();return[...e].sort().every((r,s)=>r===n[s])}function Iy(e){const t=Ny(e.claimsText);return t.ok?t.claims:void 0}function C$(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=Iy(t);return r&&(n.customClaims=r),t.providerIds.length&&(n.providerUserInfo=t.providerIds.map(s=>({providerId:s}))),n}function N$(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=Iy(t)??{}),Ry(t.providerIds,n.providerIds)||(r.providerUserInfo=t.providerIds.map(s=>({providerId:s}))),r}function Ay(e={}){const[t,n]=y.useReducer(k$,e.initial,S$),r=y.useMemo(()=>j$(t.fields),[t.fields]),s=y.useMemo(()=>E$(t),[t]),i=y.useCallback((a,l)=>n({type:"setField",field:a,value:l}),[]),o=y.useCallback(()=>n({type:"reset"}),[]);return{fields:t.fields,errors:r,isDirty:s,isValid:Object.keys(r).length===0,setField:i,reset:o,toCreateRequest:()=>C$(t),toUpdateRequest:()=>N$(t),dispatch:n}}const R$={"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 mi(e){return R$[e]??e}var Mc=Jw();function bn(e,t,n){let r=n.initialDeps??[],s,i=!0;function o(){var a,l,u;let d;n.key&&((a=n.debug)!=null&&a.call(n))&&(d=Date.now());const h=e();if(!(h.length!==r.length||h.some((m,g)=>r[g]!==m)))return s;r=h;let p;if(n.key&&((l=n.debug)!=null&&l.call(n))&&(p=Date.now()),s=t(...h),n.key&&((u=n.debug)!=null&&u.call(n))){const m=Math.round((Date.now()-d)*100)/100,g=Math.round((Date.now()-p)*100)/100,b=g/16,w=(x,v)=>{for(x=String(x);x.length<v;)x=" "+x;return x};console.info(`%c⏱ ${w(g,5)} /${w(m,5)} ms`,`
|
|
137
|
+
`&&this.pos++,this.newline()):this.pos++}const r=t.slice(n,this.pos).replace(/[\u0000-\u001f]/g,s=>`\\u${s.charCodeAt(0).toString(16).padStart(4,"0")}`);return JSON.parse(r)}parseLiteral(){const t=/^(?:true|false|null|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)/.exec(this.text.slice(this.pos,this.pos+64));if(!t)throw new Error("unexpected token");this.pos+=t[0].length}}function oy(e,t,n){let r=e.get("rules")?.value??null;for(const s of t.split("/").filter(i=>i.length>0))r=r?.get(s)?.value??null;return r?.get(n)?.location??null}function $A(e,t,n){const r=new iy(e).parseDocument();return r?oy(r,t,n):null}function ay(e,t){const n=new iy(e).parseDocument();return t.map(r=>{const s=n?oy(n,r.path,`.${r.kind}`):null;return s?{...r,line:s.line}:{...r}})}const wd=["read","write","validate","indexOn"];function So(e,t){return`${e}\0${t}`}function PA(e){const t=["allow","deny","error"].filter(n=>e[n]>0);return t.length>1?"mixed":t.length===1?t[0]:e.unsupported>0?"unsupported":"never-evaluated"}class DA{compiled;rows=new Map;missing=new Map;constructor(t){this.compiled=t,this.collect(t)}collect(t){for(const n of wd){let r;n==="indexOn"?t.indexOn!==void 0&&(r=JSON.stringify(t.indexOn)):r=t[n]?.raw,r!==void 0&&this.rows.set(So(t.path,n),{path:t.path,kind:n,expression:r,counts:{allow:0,deny:0,error:0,unsupported:0}})}for(const n of t.children)this.collect(n)}record(t){for(const n of t??[]){const r=this.rows.get(So(n.path,n.kind));r!==void 0&&(n.verdict==="ALLOW"?r.counts.allow++:n.verdict==="DENY"?r.counts.deny++:n.verdict==="ERROR"?r.counts.error++:r.counts.unsupported++)}}recordQuery(t,n){if(n===void 0)return;let r=null;if(n.orderByValue===!0)r=".value";else if(typeof n.orderByChild=="string"){const o=n.orderByChild.split("/").filter(Boolean).join("/");o!==""&&(r=o)}if(r===null)return;const s=t.split("/").filter(Boolean),i=Qh(this.compiled,s,r);for(const o of i){const a=this.rows.get(So(o.path,"indexOn"));a!==void 0&&a.counts.allow++}if(i.length===0){const o=`/${s.join("/")}`;this.missing.set(`${o}\0${r}`,{path:o,index:r})}}summarize(t={}){const n=[];for(const a of this.rows.values()){const{allow:l,deny:u,error:d,unsupported:h}=a.counts,f={path:a.path,kind:a.kind,expression:a.expression,evaluated:l+u+d,allow:l,deny:u,error:d,unsupported:h,status:PA(a.counts)};n.push(f)}const r=t.source===void 0?n:ay(t.source,n),s=Object.fromEntries(wd.map(a=>[a,{total:0,covered:0,unsupported:0}]));let i=0,o=0;for(const a of r)s[a.kind].total++,a.evaluated>0?(s[a.kind].covered++,i++):a.status==="unsupported"&&(s[a.kind].unsupported++,o++);return{rules:r,uncovered:r.filter(a=>a.status==="never-evaluated").map(a=>`${a.path} .${a.kind}`),missingIndexes:[...this.missing.values()],files:[{file:t.file??null,total:r.length,covered:i,neverEvaluated:r.filter(a=>a.status==="never-evaluated").length,unsupported:o,byKind:s}]}}}function TA(e){const t={rules:[],uncovered:[],missingIndexes:[],files:[]};for(const n of e){const r=n.files[0]?.file??"rules";t.rules.push(...n.rules.map(s=>({file:r,...s}))),t.uncovered.push(...n.uncovered.map(s=>`${r} ${s}`)),t.missingIndexes.push(...n.missingIndexes.map(s=>({...s,file:r}))),t.files.push(...n.files)}return t}const MA=new Set(["exists","isString","isNumber","isBoolean","hasChild","hasChildren"]);function _n(e){return e===!1||e==="exists-false"||e==="delete-guard"}function vd(e,t){return e.length>=t.length&&t.every((n,r)=>e[r]===n)}function xd(e,t){const n=e.split("/").filter(Boolean);return t.split("/").filter(Boolean).slice(n.length)}function LA(e){const t=e.newDataRelPath();return t!==void 0&&t.length===0}function _d(e,t,n){const r=this.args.acc;(e.newDataRelPath()?.join("/")===".val()"&&n.constVal()===null||n.newDataRelPath()?.join("/")===".val()"&&e.constVal()===null)&&r.newDataExistsCalls++,e.collect(r),n.collect(r)}function ws(e){return function(t,n,r){const s=t.constVal(),i=r.constVal();if(typeof s!="number"||typeof i!="number")return;const o=e(s,i);return o!==void 0&&Number.isFinite(o)?o:void 0}}function vs(e){return function(t,n,r){const s=t.constVal(),i=r.constVal();if(typeof s=="number"&&typeof i=="number"||typeof s=="string"&&typeof i=="string")return e===">"?s>i:e===">="?s>=i:e==="<"?s<i:s<=i}}function xs(e){return function(t,n,r){const s=t.constVal(),i=r.constVal();if(!(s===void 0||i===void 0))return e?s===i:s!==i}}function _s(e,t,n){const r=this.args.relSegments;return e.evalOnDelete(r)===null||n.evalOnDelete(r)===null?!1:this.constVal()}function Sd(e,t,n){const r=this.args.relSegments,s=e.evalOnDelete(r),i=n.evalOnDelete(r);if(s===null&&i===null&&e.constVal()===null!=(n.constVal()===null))return"delete-guard";if(s!==void 0&&i!==void 0)return s===i;if(s===null&&e.constVal()!==null||i===null&&n.constVal()!==null)return!1}function kd(e,t,n){const r=this.args.relSegments,s=e.evalOnDelete(r),i=n.evalOnDelete(r);return s!==void 0&&i!==void 0?s!==i:void 0}let ko;function UA(){if(ko)return ko;const e=es();return e.addOperation("newDataRelPath",{_nonterminal(...t){return t.length===1?t[0].newDataRelPath():void 0},_iter(){},_terminal(){},Primary_paren(t,n,r){return n.newDataRelPath()},ident(t,n,r){return this.sourceString==="newData"?[]:void 0},CallExpr_methodCall(t,n,r,s,i,o){const a=t.newDataRelPath();if(a===void 0||a[0]===".val()")return;const l=r.sourceString;if(l==="val"&&a.length===0&&i.asIteration().children.length===0)return[".val()"];if(l==="child"){const u=i.asIteration().children,d=u.length===1?u[0].constVal():void 0;return typeof d=="string"?[...a,...d.split("/").filter(Boolean)]:void 0}return l==="parent"&&a.length>0?a.slice(0,-1):void 0}}),e.addOperation("collect(acc)",{_nonterminal(...t){t.forEach(n=>n.collect(this.args.acc))},_iter(...t){t.forEach(n=>n.collect(this.args.acc))},_terminal(){},CallExpr_methodCall(t,n,r,s,i,o){const a=this.args.acc;if(LA(t)){const l=r.sourceString;l==="exists"&&a.newDataExistsCalls++,(l==="hasChild"||l==="child")&&(a.checksNamedChildren=!0),l==="hasChildren"&&i.asIteration().children.length>0&&(a.checksNamedChildren=!0)}t.collect(a),i.asIteration().children.forEach(l=>l.collect(a))},Equality_strictNeq:_d,Equality_looseNeq:_d,CallExpr_memberAccess(t,n,r){t.collect(this.args.acc)},ident(t,n,r){const s=this.args.acc,i=this.sourceString;i==="auth"?s.readsAuth=!0:i==="data"?s.readsData=!0:i==="root"?s.readsRoot=!0:i==="newData"&&s.newDataReads++}}),e.addOperation("constVal",{_nonterminal(...t){return t.length===1?t[0].constVal():void 0},_iter(){},_terminal(){},Primary_paren(t,n,r){return n.constVal()},bool_true(t){return!0},bool_false(t){return!1},null(t){return null},number(t){const n=Number(this.sourceString);return Number.isFinite(n)?n:void 0},string_single(t,n,r){return Nr(this.sourceString)?void 0:Rr(this.sourceString)},string_double(t,n,r){return Nr(this.sourceString)?void 0:Rr(this.sourceString)},UnaryExpr_not(t,n){const r=n.constVal();return typeof r=="boolean"?!r:void 0},UnaryExpr_neg(t,n){const r=n.constVal();return typeof r=="number"&&Number.isFinite(-r)?-r:void 0},Multiplicative_mul:ws((t,n)=>t*n),Multiplicative_div:ws((t,n)=>n===0?void 0:t/n),Multiplicative_mod:ws((t,n)=>n===0?void 0:t%n),Additive_sub:ws((t,n)=>t-n),Additive_add(t,n,r){const s=t.constVal(),i=r.constVal();return typeof s=="number"&&typeof i=="number"?Number.isFinite(s+i)?s+i:void 0:typeof s=="string"&&typeof i=="string"?s+i:void 0},Comparison_gt:vs(">"),Comparison_gte:vs(">="),Comparison_lt:vs("<"),Comparison_lte:vs("<="),Equality_strictEq:xs(!0),Equality_looseEq:xs(!0),Equality_strictNeq:xs(!1),Equality_looseNeq:xs(!1),LogicalAnd_and(t,n,r){const s=t.constVal();if(s===!1)return!1;if(s===!0){const i=r.constVal();return typeof i=="boolean"?i:void 0}},LogicalOr_or(t,n,r){const s=t.constVal();if(s===!0)return!0;if(s===!1){const i=r.constVal();return typeof i=="boolean"?i:void 0}},Ternary_ternary(t,n,r,s,i){const o=t.constVal();if(o===!0)return r.constVal();if(o===!1)return i.constVal()}}),e.addOperation("constant",{_nonterminal(){const t=this.constVal();return typeof t=="boolean"?t:void 0},_iter(){},_terminal(){}}),e.addOperation("evalOnDelete(relSegments)",{_nonterminal(...t){const n=this.constVal();return n!==void 0?n:t.length===1?t[0].evalOnDelete(this.args.relSegments):void 0},_iter(){},_terminal(){return this.constVal()},Primary_paren(t,n,r){return n.evalOnDelete(this.args.relSegments)},CallExpr_methodCall(t,n,r,s,i,o){const a=this.args.relSegments,l=t.newDataRelPath(),u=r.sourceString;if(l!==void 0&&l[0]!==".val()"){if(vd(l,a)){if(u==="exists")return"exists-false";if(MA.has(u))return!1;if(u==="val"||u==="getPriority")return null}const d=i.asIteration().children;let h=[];u==="hasChild"&&d.length===1?h=[d[0]]:u==="hasChildren"&&d.length===1&&d[0].ctorName==="Array"&&(h=d[0].children[1].asIteration().children);for(const f of h){const p=f.constVal();if(typeof p=="string"&&vd([...l,...p.split("/").filter(Boolean)],a))return!1}}return t.evalOnDelete(a)===null?!1:void 0},CallExpr_memberAccess(t,n,r){return t.evalOnDelete(this.args.relSegments)===null?!1:void 0},UnaryExpr_not(t,n){const r=n.evalOnDelete(this.args.relSegments);return r==="exists-false"?"delete-guard":r==="delete-guard"?!1:typeof r=="boolean"?!r:void 0},Comparison_gt:_s,Comparison_gte:_s,Comparison_lt:_s,Comparison_lte:_s,Equality_strictEq:Sd,Equality_looseEq:Sd,Equality_strictNeq:kd,Equality_looseNeq:kd,LogicalAnd_and(t,n,r){const s=this.args.relSegments,i=t.evalOnDelete(s),o=r.evalOnDelete(s);return i===!1||i==="exists-false"||o===!1||o==="exists-false"?!1:i==="delete-guard"||o==="delete-guard"?"delete-guard":i===!0&&o===!0?!0:void 0},LogicalOr_or(t,n,r){const s=this.args.relSegments,i=t.evalOnDelete(s);if(i===!0)return!0;const o=r.evalOnDelete(s);return _n(i)&&_n(o)?i==="delete-guard"||o==="delete-guard"?"delete-guard":!1:_n(i)&&o===!0?!0:void 0},Ternary_ternary(t,n,r,s,i){const o=this.args.relSegments,a=t.evalOnDelete(o);if(a===!0)return r.evalOnDelete(o);if(a===!1||a==="exists-false")return i.evalOnDelete(o);if(_n(r.evalOnDelete(o))&&_n(i.evalOnDelete(o)))return!1}}),ko=e,e}function jo(e){if(e===void 0||!e.parsed.valid||e.parsed.errors.length>0)return;const t=Zr(e.raw);if(!t.ok)return;const n=UA()(t.match),r={readsAuth:!1,readsData:!1,readsRoot:!1,newDataReads:0,newDataExistsCalls:0,checksNamedChildren:!1};n.collect(r);const s=n.constant();return{constant:s,...r,canGrantOnDelete:i=>s!==!1&&!_n(n.evalOnDelete(i))}}function cy(e){return{node:e,read:jo(e.read),write:jo(e.write),validate:jo(e.validate),children:e.children.map(cy)}}function Ss(e){return e!==void 0&&e.constant!==!1}function BA(e){const t=e.validate;return t===void 0||t.constant!==void 0?!1:!(t.newDataReads>0&&t.newDataReads===t.newDataExistsCalls&&!t.readsData&&!t.readsRoot)}function Sr(e){if(BA(e))return!0;if(e.children.length===0)return!1;const t=e.children.filter(n=>!Na(n));return e.children.some(Sr)&&t.every(Sr)}function ly(e){const t=e.split("/").filter(Boolean);return t[t.length-1]??""}function Na(e){return ly(e.node.path).startsWith("$")}function ks(e){const t=e.raw.trim();return t.length<=80?t:`${t.slice(0,77)}...`}function Eo(e){return e==="/"?"the database":e}function FA(e){const t=[];return uy(cy(e),{ancestors:[],unboundedAbove:!1},t),t}function uy(e,t,n){const r=e.node.path,s=e.write,i=e.read;if(s?.constant===!0&&n.push({code:"RTDB-SEC-1",severity:"critical",path:r,rule:".write",message:`${r} .write is true: anyone, signed in or not, can write, replace or delete any value under ${Eo(r)}.`,fix:`Replace ${r} .write true with a condition on auth, such as "auth != null && auth.uid == $uid" on the node each user owns.`}),i?.constant===!0){const p=r==="/";n.push({code:"RTDB-SEC-2",severity:p?"critical":"medium",path:r,rule:".read",message:p?"/ .read is true: anyone, signed in or not, can read the entire database.":`${r} .read is true: anyone, signed in or not, can read everything under ${r}.`,fix:p?"Remove .read from the root and grant .read on the subtrees clients need, with a condition on auth.":`Require auth in ${r} .read ("auth != null"), or keep ${r} only if every value under it is meant to be public.`})}s!==void 0&&s.constant===void 0&&!s.readsAuth&&n.push({code:"RTDB-SEC-3",severity:"high",path:r,rule:".write",message:`${r} .write does not read auth: a signed-out client can write under ${Eo(r)} whenever "${ks(e.node.write)}" holds.`,fix:`Add an auth condition to ${r} .write, such as "auth != null && (${ks(e.node.write)})".`});for(const p of["read","write"]){const m=e[p];if(m===void 0)continue;const g=p==="read"?".read":".write",b=t.ancestors.find(v=>{const _=v[p];return Ss(_)?_.constant===!0?m.constant!==!0:m.constant===!1:!1});if(b===void 0)continue;const w=b.node.path,x=b.node[p];n.push({code:"RTDB-SEC-4",severity:"high",path:r,rule:g,message:b[p].constant===!0?`${r} ${g} never restricts access: ${w} ${g} is true and grants ${p} on every path under it, and a deeper rule cannot revoke an ancestor's grant.`:`${r} ${g} false does not revoke ${w} ${g}: whenever "${ks(x)}" holds, ${w} grants ${p} on every path under it, including ${r}.`,fix:`Move the grant from ${w} ${g} down to the children that need it, so that no ancestor of ${r} grants ${p}.`})}const o=e.validate;if(o!==void 0&&o.constant===void 0&&(o.readsData||o.readsRoot||o.newDataExistsCalls>0)){const p=[...t.ancestors,e].find(m=>Ss(m.write)&&m.write.canGrantOnDelete(xd(m.node.path,r)));if(p!==void 0){const m=p.node.path,g=xd(m,r),b=g.length>0&&g.every(w=>!w.startsWith("$"))?`newData.child('${g.join("/")}').exists()`:"newData.exists()";n.push({code:"RTDB-SEC-5",severity:"high",path:r,rule:".validate",message:`${r} .validate does not run when ${r} is deleted: .validate runs only on a non-null new value, and ${m} .write grants without requiring ${b}, so a client it admits can delete ${r} (write null at ${m}) and bypass "${ks(e.node.validate)}".`,fix:`Add "${b}" to ${m} .write to refuse deletes, or write the delete condition there, such as "${b} || <who may delete>".`})}}let a=t.unboundedAbove;!a&&Ss(s)&&s.newDataReads===s.newDataExistsCalls&&!Sr(e)&&(a=!0,n.push({code:"RTDB-SEC-6",severity:"high",path:r,rule:".write",message:`${r} .write accepts any value: no .validate rule sits at or below ${r} and the .write rule does not check newData, so a client it admits can store data of any shape and size under ${Eo(r)}.`,fix:`Add .validate rules under ${r} that fix the shape and bound sizes, such as "newData.isString() && newData.val().length <= 100", and "$other": { ".validate": false } for keys you do not name.`}));const l=e.children.filter(p=>!Na(p)&&Sr(p)).map(p=>ly(p.node.path)),u=l.length>0||o?.checksNamedChildren===!0,d=e.children.some(p=>Na(p)&&(p.validate?.constant===!1||Sr(p))),h=[...t.ancestors,e].some(p=>Ss(p.write));if(u&&!d&&h){const p=l.length>0?`names ${l.join(", ")} with .validate rules`:"checks named children in .validate";n.push({code:"RTDB-SEC-7",severity:"medium",path:r,rule:".validate",message:`${r} ${p} but has no $other rule: a write at or above ${r} can add any other key under it, and no .validate rule checks that key.`,fix:`Add "$other": { ".validate": false } under ${r} to reject keys it does not name.`})}const f={ancestors:[...t.ancestors,e],unboundedAbove:a};for(const p of e.children)uy(p,f,n)}function VA(e){const t=e;return typeof t.toJSON=="function"&&typeof t.simulate=="function"&&typeof t.check=="function"}function qA(e){const t=e;return typeof t=="object"&&t!==null&&"rules"in t&&!("paths"in t)&&typeof t.toJSON!="function"}class dy{placement;constructor(t){this.placement=t}get doc(){if(this.placement.kind!=="every-instance")throw new Error("per-instance rules hold one ruleset per instance");return this.placement.rules.doc}lint(){return this.placement.kind==="every-instance"?jd(this.doc):[...new Set(this.placement.instances.values())].flatMap(t=>jd(t.doc).map(n=>t.file===void 0?n:{...n,file:t.file}))}runOne(t){const n=IA(this.placement,t),r=n.instance,s={case:t,...t.description!==void 0?{description:t.description}:{},...r!==void 0?{instance:r}:{}},i="problem"in n?sn(n.problem):NA(n.rules.doc,n.evaluated);if(!i.success)return{...s,expectation:t.expectation,decision:"UNSUPPORTED",passed:!1,unsupported:!0,matchedPath:t.path,matchedRule:"",reason:i.error.message,trace:[]};const o=i.data,a=o.unsupported===!0,l=a?"UNSUPPORTED":o.allowed?"ALLOW":"DENY",u=!a&&l===t.expectation;return{...s,expectation:t.expectation,decision:l,passed:u,unsupported:a,matchedPath:o.matchedPath,matchedRule:o.matchedRule,reason:o.reason,trace:r===void 0?o.trace:o.trace.map(d=>({...d,instance:r}))}}simulate(t){const n=t.map(o=>this.runOne(o));let r=0,s=0,i=0;for(const o of n)o.unsupported?i++:o.passed?r++:s++;return{passed:r,failed:s,unsupported:i,cases:n,coverage:this.coverage(n)}}coverage(t,n){if(this.placement.kind==="every-instance")return Ed(this.doc,t,n);const{defaultInstance:r,instances:s}=this.placement,o=[...new Set(s.values())].map(a=>{const l=t.filter(u=>s.get(u.instance??r)===a);return Ed(a.doc,l,{...a.file===void 0?{}:{file:a.file},...a.source===void 0?{}:{source:a.source}})});return o.length===1?o[0]:TA(o)}explain(t){const n=this.runOne(t);return{...n.instance!==void 0?{instance:n.instance}:{},decision:n.decision,expectation:n.expectation,passed:n.passed,unsupported:n.unsupported,matchedPath:n.matchedPath,matchedRule:n.matchedRule,reason:n.reason,trace:n.trace}}toJSON(){if(this.placement.kind==="every-instance")return this.doc.toJSON();const t=sy(this.placement,this.placement.defaultInstance,!1);if("problem"in t)throw new Error(t.problem);return t.doc.toJSON()}}function jd(e){const t=e.check(),n=[...t.errors.map(r=>pd(r,"error")),...t.warnings.map(r=>pd(r,"warning"))];return t.errors.some(r=>r.code==="COMPILE_ERROR")?n:[...n,...FA(e.compile()).map(cA)]}function Ed(e,t,n){const r=new DA(e.compile());for(const s of t)r.record(s.trace),s.case.operation==="read"&&r.recordQuery(s.case.path,s.case.query);return r.summarize(n)}function Co(e){return new dy({kind:"every-instance",rules:{doc:e}})}class fy{json;compiled;constructor(t){this.json=t}toJSON(){return this.json}compile(){return this.compiled??=Jh(this.json),this.compiled}check(){return ty(()=>this.compile())}simulate(t){return fc(this.compile(),ey(t))}}function hy(e){let t;try{t=JSON.parse(hE(e))}catch(s){const i=s instanceof Error?s.message:String(s);throw Cd(`Realtime Database rules text is not valid JSON: ${i}`)}const n=t?.rules;if(!(typeof n=="object"&&n!==null&&!Array.isArray(n)))throw Cd('Realtime Database rules text has no top-level "rules" object');return t}function Cd(e){return new _a(e,[{code:"PARSE_ERROR",severity:"error",message:e,origin:"parse"}])}function WA(e){return typeof e=="string"&&(e=hy(e)),VA(e)?Co(e):qA(e)?Co(new fy(e)):Co(_A(e))}function zA(e,t={}){const n=OA(e,t),r=new Map;for(const s of n.files){let i;try{i=hy(s.text)}catch(a){throw a instanceof _a?new _a(`${s.path}: ${a.message}`,a.issues):a}const o={doc:new fy(i),file:s.file,source:s.text};for(const a of s.instances)r.set(a,o)}return new dy({kind:"per-instance",defaultInstance:n.defaultInstance,...n.projectId===void 0?{}:{projectId:n.projectId},instances:r})}const HA=Object.assign(WA,{fromFirebaseJson:zA});function py(e){return e&&typeof e=="object"&&ma in e?fN(e).backend:mS(e)}function my(e){return py(e).getActiveRules()}function Nd(e){return py(e).snapshotState()}function KA(e,t){return e==="/"?`/${t}`:`${e}/${t}`}function Rd(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function GA(e){const t=(e??"/").split("/").filter(Boolean);return t.length===0?"/":`/${t.join("/")}`}function JA(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 yy(e,t,n,r,s){if(e===null||typeof e!="object"||Array.isArray(e))return{path:t,childCount:0,truncated:!1,children:[],schema:{},valueType:Rd(e)};const i=Object.entries(e).sort(([h],[f])=>h.localeCompare(f)),o={},a=[];for(const[h,f]of i)f!==null&&typeof f=="object"&&!Array.isArray(f)?a.push([h,f]):o[h]=Rd(f);const l=n>=r&&a.length>0,u=i.length>s,d=n>=r?[]:a.slice(0,s).map(([h,f])=>yy(f,KA(t,h),n+1,r,s));return{path:t,childCount:i.length,truncated:l||u,children:d,schema:o}}function YA(e,t={}){const n=GA(t.path),r=t.maxDepth??10,s=t.maxChildren??100;return yy(JA(e,n),n,0,r,s)}function gy(e){return e.children.reduce((t,n)=>t+1+gy(n),0)}const No={anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"}]};function QA(e){return[{name:"rtdb_simulate_access",description:"Simulate one read, write, update, or validate operation against the RTDB rules and data currently loaded in the local sandbox. newData may be any JSON value, such as 5 or true; for update it is the patch keyed by the paths written, relative to path. A read may carry a query so query.* rules evaluate. No production database is contacted and no prior rules-loading tool call is required.",parameters:{type:"object",properties:{operation:{type:"string",enum:["read","write","update","validate"]},path:{type:"string"},auth:{anyOf:[{type:"null"},{type:"object",properties:{uid:{type:"string"},tenant:{type:"string"},claims:{type:"object"}},required:["uid"]}]},newData:{},query:{type:"object",properties:{orderByChild:{type:"string"},orderByKey:{type:"boolean",enum:[!0]},orderByValue:{type:"boolean",enum:[!0]},equalTo:No,startAt:No,endAt:No,limitToFirst:{type:"integer"},limitToLast:{type:"integer"}},additionalProperties:!1},now:{type:"number"}},required:["operation","path"]},async execute(t){const n=t,r=await e.resolveSandbox(),s=my(r);if(!s)return{ok:!1,summary:"No RTDB rules are loaded in the local sandbox.",data:{code:"NO_ACTIVE_RULES"}};const i=Nd(r),o=i!==null&&typeof i=="object"&&!Array.isArray(i)?i:{};let a=n.now;a===void 0&&(a=Te(r).now());let l=null;if(n.auth){const h=Km(n.auth.uid,n.auth.tenant,n.auth.claims);l={uid:h.uid,token:h.token}}const u={expectation:"ALLOW",operation:n.operation,path:n.path,auth:l,data:o,now:a};n.newData!==void 0&&(u.newData=n.newData),n.query!==void 0&&(u.query=n.query);const d=HA(s).simulate([u]).cases[0];return{ok:!d.unsupported,summary:d.unsupported?`Simulation unsupported: ${d.reason}`:`Simulation: ${d.decision.toLowerCase()}`,data:{decision:d.decision,allowed:d.decision==="ALLOW",unsupported:d.unsupported,matchedPath:d.matchedPath,matchedRule:d.matchedRule,reason:d.reason,trace:d.trace}}}},{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=YA(Nd(r),n);return{ok:!0,summary:`Crawled ${gy(s)} object paths from ${s.path}`,data:s}}}]}function sr(e){return{uid:e.uid,email:e.email,displayName:e.displayName,phoneNumber:e.phoneNumber,photoUrl:e.photoUrl,claims:{...e.customClaims},providers:e.providerUserInfo.map(t=>t.providerId),isAnonymous:e.isAnonymous,disabled:e.disabled,emailVerified:e.emailVerified,tenantId:e.tenantId,createdAt:e.createdAt,lastLoginAt:e.lastLoginAt}}function XA(e,t){const n=JSON.stringify(t?{uid:e,claims:t}:{uid:e}),r=new TextEncoder().encode(n);let s="";for(const i of r)s+=String.fromCharCode(i);return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Tt(e,t){return{ok:!1,summary:t,data:{code:e}}}function ir(e){const t=typeof e?.code=="string"?e.code:"auth/internal-error";return Tt(t,e instanceof Error?e.message:String(e))}function Bs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ot(e){return Bs(e)?e:{}}function js(e,t){const n=e.uid;return typeof n!="string"||n.length===0?Tt("auth/argument-error",`${t}: uid must be a non-empty string.`):n}function by(e){if(Array.isArray(e))return e.filter(t=>typeof t=="string"&&t.trim().length>0).map(t=>({providerId:t}))}function Id(e){return{uid:e.uid,email:e.email,password:e.password,displayName:e.displayName,phoneNumber:e.phoneNumber,customClaims:e.claims,disabled:e.disabled,emailVerified:e.emailVerified,providerUserInfo:by(e.providers)}}const Ra={type:"object",description:"Custom claims. Rules read them as request.auth.token.<name>."},ZA={type:"array",items:{type:"string"},description:"Provider ids to link, for example google.com. A user created under a dotted provider id and no password is assigned a generated photoUrl."},Ia={email:{type:"string"},password:{type:"string",description:"At least six characters. Never returned."},displayName:{type:"string"},phoneNumber:{type:"string"},claims:Ra,providers:ZA,disabled:{type:"boolean"},emailVerified:{type:"boolean"}},e0={type:"object",properties:{uid:{type:"string",description:"Generated when omitted."},...Ia},required:["email"]},Ad="Users land in the one pool the application, Studio, and rules evaluation share. Creating a user does not sign anyone in, and a password is never returned. A user created under a dotted provider id with no password is assigned a generated photoUrl; password, phone, and anonymous users keep photoUrl null.";function t0(e){const t=async()=>yc(await e.resolveSandbox());return[{name:"auth_create_user",description:`Create one user in the connected sandbox's user store. ${Ad}`,parameters:{type:"object",properties:{uid:{type:"string",description:"User id. Generated when omitted."},...Ia}},async execute(n){const r=Ot(n),s=await t();try{const i=xe.createUser(s,Id(r));return{ok:!0,summary:`Created user ${i.uid}`,data:{user:sr(i)}}}catch(i){return ir(i)}}},{name:"auth_import_users",description:`Create many users in order, reporting each failure without stopping. ${Ad}`,parameters:{type:"object",properties:{users:{type:"array",items:e0,description:"Users to create, in order. Each requires an email."}},required:["users"]},async execute(n){const s=Ot(n).users;if(!Array.isArray(s))return Tt("auth/argument-error","auth_import_users: users must be an array.");const i=await t(),o=[],a=[];s.forEach((u,d)=>{const h=Bs(u)?u:{};if(typeof h.email!="string"||h.email.length===0){a.push({index:d,...h.uid?{uid:h.uid}:{},email:String(h.email??""),code:"auth/argument-error",message:`auth_import_users: users[${d}].email is required.`});return}try{o.push(xe.createUser(i,Id(h)).uid)}catch(f){const p=ir(f).data;a.push({index:d,...h.uid?{uid:h.uid}:{},email:h.email,code:p.code,message:f instanceof Error?f.message:String(f)})}});const l=a.length===0?`Imported ${o.length} of ${s.length} users`:`Imported ${o.length} of ${s.length} users; ${a.length} failed`;return{ok:a.length===0,summary:l,data:{created:o,errors:a}}}},{name:"auth_get_user",description:"Read one user of the connected sandbox's user store by uid, or by email when uid is omitted.",parameters:{type:"object",properties:{uid:{type:"string"},email:{type:"string",description:"Matched case-insensitively. Used when uid is omitted."}}},async execute(n){const{uid:r,email:s}=Ot(n);if(typeof r!="string"&&typeof s!="string")return Tt("auth/argument-error","auth_get_user: uid or email is required.");const i=xe.listUsers(await t()),o=typeof r=="string"?i.find(a=>a.uid===r):i.find(a=>a.email?.toLowerCase()===s.toLowerCase());return o?{ok:!0,summary:`Got user ${o.uid}`,data:{user:sr(o)}}:Tt("auth/user-not-found",typeof r=="string"?`No user found for uid ${r}.`:`No user found for email ${s}.`)}},{name:"auth_list_users",description:"Read every user of the connected sandbox's user store.",parameters:{type:"object",properties:{limit:{type:"number",description:"Return at most this many users."}}},async execute(n){const{limit:r}=Ot(n);if(r!==void 0&&(typeof r!="number"||!Number.isFinite(r)||r<0))return Tt("auth/argument-error","auth_list_users: limit must be a non-negative number.");const s=xe.listUsers(await t()),i=(r!==void 0?s.slice(0,r):s).map(sr);return{ok:!0,summary:`${i.length} of ${s.length} users`,data:{users:i,total:s.length}}}},{name:"auth_update_user",description:"Change one user. Every supplied field replaces what is stored; claims replaces the whole claims map. Omitted fields are left alone.",parameters:{type:"object",properties:{uid:{type:"string",description:"The user to change."},...Ia},required:["uid"]},async execute(n){const r=Ot(n),s=js(r,"auth_update_user");if(typeof s!="string")return s;const i=r,o={...i.email!==void 0?{email:i.email}:{},...i.password!==void 0?{password:i.password}:{},...i.displayName!==void 0?{displayName:i.displayName}:{},...i.phoneNumber!==void 0?{phoneNumber:i.phoneNumber}:{},...i.disabled!==void 0?{disabled:i.disabled}:{},...i.emailVerified!==void 0?{emailVerified:i.emailVerified}:{},...i.claims!==void 0?{customClaims:i.claims}:{},...i.providers!==void 0?{providerUserInfo:by(i.providers)}:{}};try{const a=xe.updateUser(await t(),s,o);return{ok:!0,summary:`Updated user ${s}`,data:{user:sr(a)}}}catch(a){return ir(a)}}},{name:"auth_delete_user",description:"Remove one user from the connected sandbox's user store.",parameters:{type:"object",properties:{uid:{type:"string",description:"The user to remove."}},required:["uid"]},async execute(n){const r=Ot(n),s=js(r,"auth_delete_user");if(typeof s!="string")return s;try{return xe.deleteUser(await t(),s),{ok:!0,summary:`Deleted user ${s}`,data:{uid:s}}}catch(i){return ir(i)}}},{name:"auth_set_claims",description:"Replace one user's custom claims. Rules read them as request.auth.token.<name> on the next sign-in or token refresh. An empty object clears them.",parameters:{type:"object",properties:{uid:{type:"string",description:"The user to change."},claims:Ra},required:["uid","claims"]},async execute(n){const r=Ot(n),s=js(r,"auth_set_claims");if(typeof s!="string")return s;if(!Bs(r.claims))return Tt("auth/argument-error","auth_set_claims: claims must be an object.");const i=r.claims;try{const o=xe.updateUser(await t(),s,{customClaims:i});return{ok:!0,summary:`Set claims on user ${s}`,data:{user:sr(o)}}}catch(o){return ir(o)}}},{name:"auth_custom_token",description:"Mint a custom token for a uid that the sandbox's signInWithCustomToken accepts. The sandbox has no signing key, so the token is unsigned and is only good against this sandbox.",parameters:{type:"object",properties:{uid:{type:"string",description:"The user the token signs in."},claims:Ra},required:["uid"]},async execute(n){const r=Ot(n),s=js(r,"auth_custom_token");if(typeof s!="string")return s;const i=r.claims;return i!==void 0&&!Bs(i)?Tt("auth/argument-error","auth_custom_token: claims must be an object."):{ok:!0,summary:`Minted custom token for ${s}`,data:{uid:s,claims:i??{},token:XA(s,i)}}}}]}const n0={"firestore-simulator":({env:e})=>Nv({resolveSandbox:()=>e}),"firestore-data":({resolveDb:e})=>HE({resolveDb:e}),"firestore-inspect":({sandbox:e})=>KE({resolveSandbox:()=>e}),"messaging-inspection":({sandbox:e})=>oA(()=>e),"rtdb-inspection":({sandbox:e})=>QA({resolveSandbox:()=>e}),"auth-users":({sandbox:e})=>t0({resolveSandbox:()=>e})};function r0(e,t){return t==="admin"?sc(e):Ks(e.withAuth(Km(t.uid,t.tenant,t.claims)))}function s0(e,t){return t===void 0||t.mode==="app-session"||t.mode==="admin"?sc(e):t.mode==="anon"?Ks(e.withAuth(null)):Ks(e.withAuth({uid:t.uid,...t.token!==void 0?{token:t.token}:{},...t.tenant!==void 0?{tenant:t.tenant}:{}}))}function i0(e,t){const n={sandbox:e,env:Jr(e),resolveDb:r=>r!==void 0?r0(e,r):s0(e,t)};return Gm("forwarded").flatMap(r=>n0[r.key](n))}function o0(e){return e===void 0||e.mode==="app-session"?"app-session":e.mode==="admin"||e.mode==="anon"?e.mode:JSON.stringify([e.uid,e.tenant??null,e.token??null])}const a0=16;function c0(e){const t=new Map;function n(r){const s=o0(r),i=t.get(s);if(i)return i;const o=i0(e,r);GI("sandbox dispatcher tools",o.map(l=>l.name),wy);const a=new Map(o.map(l=>[l.name,l]));if(t.size>=a0)for(const l of[...t.keys()])l!=="app-session"&&t.delete(l);return t.set(s,a),a}return n(void 0),async(r,s,i)=>{const o=n(i).get(r);if(!o)throw new u0(r);const a={signal:new AbortController().signal},l=await o.execute(s,a);return{ok:l.ok,summary:l.summary,data:l.data}}}const Od=new WeakMap;async function l0(e,t,n,r){let s=Od.get(e);return s||(s=c0(e),Od.set(e,s)),s(t,n,r)}const wy=Gm("forwarded").flatMap(e=>Object.keys(e.tools));class u0 extends Error{tool;constructor(t){super(`unknown sandbox tool: ${t}`),this.tool=t,this.name="UnknownToolError"}}function d0(e){if(e!==void 0&&e.length>0)return e;if(typeof window<"u"){const r=window;if("__PYRIC_BRIDGE_URL__"in r){const l=r.__PYRIC_BRIDGE_URL__;if(typeof l=="string"&&l.length>0)return l}const i=r.location.hostname||"localhost";return`${r.location.protocol==="https:"?"wss:":"ws:"}//${i}:${Fu}${Vu}`}return`ws://localhost:${Fu}${Vu}`}function f0(e){try{const t=new URL(e),n=t.protocol==="wss:";return t.protocol=n?"https:":"http:",[`${t.origin}/__pyric/health`,`${t.origin}/health`]}catch{return[]}}const h0={op:!0,sub:!0,unsub:!0,disconnect:!0,appConfig:!0,"clock-subscribe":!0,tool:!0};function Tn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function p0(e){return!Tn(e)||!(typeof e.t=="string"&&Object.hasOwn(h0,e.t))?!1:e.t==="op"||e.t==="tool"||e.t==="disconnect"?typeof e.id=="string":e.t==="sub"||e.t==="unsub"?typeof e.subId=="string":!0}function m0(e){return Tn(e)?typeof e.method=="string":!1}function y0(e){if(!Tn(e))return!1;const n=typeof e.target=="string",r=Tn(e.target);return n||r}function $d(e){if(!Tn(e))return!1;switch(e.mode){case"admin":case"anon":case"app-session":return!0;case"as":try{return Iw(e),!0}catch{return!1}default:return!1}}function Pd(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function g0(e){if("clientSessionId"in e&&e.clientSessionId!==void 0&&typeof e.clientSessionId!="string")return"Invalid bridge client session ID.";switch(e.type){case"hello":{const n=!Pd(e.tools),r=typeof e.sandboxId!="string",s=e.capabilities===void 0||Pd(e.capabilities);return n||r||!s?"Invalid sandbox peer handshake.":void 0}case"hello-ack":return typeof e.bridgeVersion!="string"?"Invalid sandbox peer acknowledgement.":void 0;case"tool-call":{const n=typeof e.id=="string",r=typeof e.name=="string",s=Tn(e.args),i=e.callerId===void 0||typeof e.callerId=="string",o=e.actAs===void 0||$d(e.actAs);return!n||!r||!s||!i||!o?"Invalid sandbox tool call envelope.":void 0}case"worker-client-disconnect":case"worker-client-interrupted":return typeof e.clientSessionId=="string"?void 0:"Invalid bridge client session ID.";case"ping":case"pong":return typeof e.id!="string"?"Invalid bridge heartbeat ID.":void 0;case"remote-set-lens":{const n=typeof e.clientSessionId=="string",r=e.id===void 0||typeof e.id=="string",s=$d(e.lens);return!n||!r||!s?"Invalid remote identity lens envelope.":void 0}case"worker-message":return p0(e.message)?void 0:"Invalid worker message envelope.";case"worker-op":{const n=typeof e.id=="string",r=m0(e.op);return!n||!r?"Invalid worker relay operation envelope.":void 0}case"worker-sub":{const n=typeof e.subId=="string",r=y0(e.sub);return!n||!r?"Invalid worker relay subscription envelope.":void 0}case"worker-unsub":return typeof e.subId!="string"?"Invalid worker relay unsubscribe envelope.":void 0;default:return}}const b0=new Set(["hello-ack","tool-call","worker-op","worker-sub","worker-unsub","worker-client-disconnect","ping"]),w0=new TextEncoder,v0=500,x0=3e4,_0=2e3,S0=.5,k0=3;function j0(e,t={}){const n=d0(t.url),r=t.sandboxId??E0(),s=t.dispatcher??l0,i=t.toolNames??[...wy],o=t.initialReconnectDelayMs??v0,a=t.maxReconnectDelayMs??x0,l=t.noReconnect??!1,u=t.onStateChange??(()=>{}),d=t.standbyPollMs??_0,h=t.fetchImpl??(A=>fetch(A)),f=t.workerRelay??null;let p=null,m=!1,g=0,b=null,w=null,x=0,v={kind:"connecting"};const _=new Map;function S(){for(const A of _.values())try{A()}catch{}_.clear()}function k(A){v=A;try{u(A)}catch{}}function N(A){const D=p;if(D!==null&&D.readyState===WebSocket.OPEN)try{const W=Hm(A);if(W===void 0){D.close(va,Vr);return}D.send(W)}catch{}}function O(){if(m)return;k({kind:"connecting"});let A;try{A=new WebSocket(n)}catch(D){const W=D instanceof Error?D.message:String(D);I(`failed to open WebSocket: ${W}`);return}p=A,A.onopen=()=>{g=0;const D={type:"hello",protocol:1,tools:i,sandboxId:r};f!==null&&(D.capabilities=[RC]),N(D)},A.onmessage=D=>{const T=D.data,W=typeof T=="string";if(W&&w0.encode(T).byteLength>Mr){A.close(va,Vr);return}let q;try{q=JSON.parse(W?T:"")}catch{A.close(4002,"Invalid bridge message JSON.");return}const F=q;if(!em(F)){A.close(4002,"Unrecognized bridge message envelope.");return}if(!b0.has(F.type))return;const M=g0(F);if(M!==void 0){A.close(4002,M);return}if(F.type==="hello-ack"){if(F.protocol!==1){const ie="Unsupported bridge protocol. Expected version 1.";m=!0,k({kind:"disconnected",reason:ie}),A.close(1e3,ie);return}k({kind:"connected",bridgeVersion:F.bridgeVersion});return}if(F.type==="tool-call"){P(F);return}if(F.type==="worker-op"){R(F);return}if(F.type==="worker-sub"){j(F);return}if(F.type==="worker-unsub"){const ut=_.get(F.subId);if(ut!==void 0){_.delete(F.subId);try{ut()}catch{}}return}if(F.type==="worker-client-disconnect"){f?.disconnect?.(F.clientSessionId);return}if(F.type==="ping"){N({type:"pong",id:F.id});return}},A.onclose=D=>{const T=D.reason||`closed (code ${D.code})`;if(p=null,S(),D.code===NC){E();return}I(T)},A.onerror=()=>{}}async function P(A){let D;try{const T=await s(e,A.name,A.args??{},A.actAs,A.callerId);D={type:"tool-result",id:A.id,ok:!0,result:T}}catch(T){const W=T instanceof Error;D={type:"tool-result",id:A.id,ok:!1,error:{code:W?T.name:"Error",message:W?T.message:String(T)}}}N(D)}async function R(A){if(f!==null)try{const T=await f.op(A.op,A.clientSessionId);Wu(`op '${A.op.method}'`,T),N({type:"worker-res",id:A.id,clientSessionId:A.clientSessionId,ok:!0,value:T})}catch(T){const W=T.denialContext,U=T instanceof Error,q={code:T.code??"unknown",message:U?T.message:String(T)};W!==void 0&&(q.denialContext=W),N({type:"worker-res",id:A.id,clientSessionId:A.clientSessionId,ok:!1,error:q})}}function j(A){if(!(f===null||_.has(A.subId)))try{const W=f.subscribe(A.sub,U=>{try{Wu(`subscription '${A.subId}'`,U)}catch(q){const F=q instanceof Error;N({type:"worker-snap",subId:A.subId,clientSessionId:A.clientSessionId,value:{__error:{code:q.code??"invalid-argument",message:F?q.message:String(q)}}});return}N({type:"worker-snap",subId:A.subId,clientSessionId:A.clientSessionId,value:U})},A.clientSessionId);_.set(A.subId,W)}catch(W){const U=W.denialContext,q=W instanceof Error,F={code:W.code??"unknown",message:q?W.message:String(W)};U!==void 0&&(F.denialContext=U),N({type:"worker-snap",subId:A.subId,clientSessionId:A.clientSessionId,value:{__error:F}})}}function E(){if(!m){if(l){k({kind:"disconnected",reason:"replaced by a newer sandbox peer"});return}g=0,x=0,k({kind:"standby"}),$()}}function $(){if(m)return;const A=d*(1+Math.random()*S0);w=setTimeout(()=>{w=null,C()},A)}async function C(){if(m)return;let A=null;for(const U of f0(n))try{const q=await h(U);if(!q.ok)continue;const Se=await q.json();if(typeof Se.sandboxConnected=="boolean"){A=!Se.sandboxConnected;break}}catch{}if(m)return;if(A===!0){O();return}if(A===!1){x=0,$();return}if(x+=1,x>=k0){I("standby health poll unreachable");return}$()}function I(A){if(m)return;if(l){k({kind:"disconnected",reason:A});return}g+=1;const D=Math.min(o*2**(g-1),a);k({kind:"reconnecting",attempt:g,delayMs:D}),b=setTimeout(()=>{b=null,O()},D)}return O(),{disconnect(){m=!0,S();const A=b;A!==null&&(clearTimeout(A),b=null);const T=w;T!==null&&(clearTimeout(T),w=null);const U=p;if(U!==null){try{U.close()}catch{}p=null}k({kind:"disconnected",reason:"client closed"})},state(){return v}}}function E0(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`sb-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function vy(e,t,n="bridge-port"){try{const r=new URL(e,t.href),s=new URL(t.href),i=t.protocol==="https:"?"wss:":"ws:",o=s.port.length>0,a=r.port.length>0,d=n==="bridge-port"&&o&&a?`${s.hostname}:${r.port}`:s.host;return`${i}//${d}${r.pathname}`}catch{return e}}function C0(e,t){return{url:t,dispatcher:(n,r,s,i)=>NN(e,r,s,i),workerRelay:{op:n=>RN(e,n),subscribe:(n,r)=>IN(e,n,r)}}}async function N0(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 o=t.locationLike??(typeof window<"u"?window.location:null),a=o?vy(i,o):i,l=j0(null,{...C0(e,a),...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",a),l}const R0={};function I0(){return!1}function A0(){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 O0(e,t={}){if(e==="local"){const r=t.baseUrl??"",s=I0(),o=t.persistence==="memory"||s?Aw():tC(r),l=t.disableLive===!0?null:PI(t.workerUrl),d=l!==null&&l.runtime.getSnapshot().mode!=="hosted"?A0():null;let h=!1,f=null;l!==null&&d!==null&&N0(l.db,{baseUrl:r,onStateChange:x=>d.set(x)}).then(x=>{h?x?.disconnect():f=x});const m={mode:e,projects:s?sC():ZE(r),persistence:o,dispose(){h=!0,f?.disconnect(),l?.dispose()}},g=l!==null,b=d!==null;return g&&(m.live=l),b&&(m.bridge=d),!s&&(m.workspace=Yp(r)),m}throw new Error(`createStudioEnvironment(${e}): only 'local' is wired in v1 (T3). 'browser'/'hosted' land in A3.`)}const xy=y.createContext(null),$0={status:"pending",env:null,error:null};function P0(e){try{return{status:"ready",env:O0(e),error:null}}catch(t){return{status:"error",env:null,error:t instanceof Error?t:new Error(String(t))}}}function D0({mode:e="local",children:t}){const[n,r]=y.useState(null);y.useEffect(()=>{const i=P0(e);return r({mode:e,state:i}),()=>{i.status==="ready"&&i.env.dispose()}},[e]);const s=n?.mode===e?n.state:$0;return c.jsx(xy.Provider,{value:s,children:t})}function lt(){const e=y.useContext(xy);if(!e)throw new Error("useEnvironment must be used within an <EnvironmentProvider>");return e}const T0="pyric-studio:theme",Fs="dark";function M0(){return Fs}function L0(){typeof document>"u"||document.documentElement.setAttribute("data-theme","dark")}const U0=y.createContext(null);function B0({children:e}){const[t,n]=y.useState(M0);y.useEffect(()=>{L0();try{localStorage.setItem(T0,Fs)}catch{}},[t]);const r="dark",s=y.useCallback(a=>n(Fs),[]),i=y.useCallback(()=>n(Fs),[]),o=y.useMemo(()=>({choice:t,resolvedTheme:r,setChoice:s,cycleChoice:i}),[t,r,s,i]);return c.jsx(U0.Provider,{value:o,children:e})}function Mi(){const e=typeof import.meta<"u"&&"/__pyric/ui/"||"/";return e.endsWith("/")?e:`${e}/`}function F0(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 Pc(e,t="",n=Mi()){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)),[o="",...a]=i;return{tab:o,rest:a,query:F0(t)}}function V0(e,t=Mi()){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 _y="studio",q0=[{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 W0({assuranceEnabled:e=!1}={}){return q0.filter(t=>t.id!=="assurance"||e)}const fn=W0({assuranceEnabled:!1}),z0=fn.map(e=>e.id);function H0(e){return fn.find(t=>t.id===e)??fn[0]}const Aa="pyric:studio:navigated",K0={tab:"",rest:[],query:{}};function Dc(){return typeof window<"u"?window.location.pathname+window.location.search:""}function G0(e){return e===""||e===_y?"home":e}function Ke(){if(typeof window>"u")return K0;const e=Pc(window.location.pathname,window.location.search);return{...e,tab:G0(e.tab)}}function J0(e){return e.tab==="home"?{...e,tab:_y}:e}function Ct(e){return V0(J0(e))}function Sy(){typeof window<"u"&&window.dispatchEvent(new Event(Aa))}function Ae(e){if(typeof window>"u")return;const t=Ct(e);Dc()!==t&&(window.history.pushState(null,"",t),Sy())}function qr(e){typeof window>"u"||(window.history.replaceState(null,"",Ct(e)),Sy())}function Gt(e){return typeof window>"u"?()=>{}:(window.addEventListener("popstate",e),window.addEventListener(Aa,e),()=>{window.removeEventListener("popstate",e),window.removeEventListener(Aa,e)})}function Y0(e,t){const n=y.useCallback(i=>e.includes(i)?i:t,[e,t]),r=y.useSyncExternalStore(Gt,()=>n(Ke().tab),()=>t);y.useEffect(()=>{const i=typeof window<"u"?window.location.hash:"";if(i.length>1){const a=i.slice(1),l=a.indexOf("?"),u=Pc(`/${l===-1?a:a.slice(0,l)}`,l===-1?"":a.slice(l),"/");if(e.includes(u.tab)){qr(u);return}}const o=Ke();e.includes(o.tab)||qr({tab:n(o.tab)})},[n]);const s=y.useCallback(i=>{const o=n(i);o!==r&&Ae({tab:o})},[n,r]);return[r,s]}let Oa=null;function Q0(e){Oa=e}function X0(){return Oa?(Oa(),!0):!1}function Z0(e){return(e.metaKey||e.ctrlKey)&&!e.altKey&&!e.shiftKey&&(e.key==="k"||e.key==="K")}function eO(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 tO=7;function nO(e,t){const n=e.trim();if(!n)return[];const r=t.filter(h=>h.id!=="settings"),s=[],i=[],o=[],[a="",...l]=n.split(/\s+/),u=l.join(" ");for(const h of r){const f={id:`tab:${h.id}`,label:`Go to ${h.label}`,hint:h.description,target:{tab:h.id}},p=h.label.toLowerCase();if(p.startsWith(n.toLowerCase())?s.push(f):eO(n,h.label)&&i.push(f),u&&(p===a.toLowerCase()||p.startsWith(a.toLowerCase()))){const m=u.split("/").filter(Boolean);h.id==="firestore"||h.id==="storage"?o.push({id:`deep:${h.id}:${u}`,label:`Open /${m.join("/")} in ${h.label}`,hint:h.id==="firestore"?"Firestore path":"Storage object path",target:{tab:h.id,rest:m}}):h.id==="auth"?o.push({id:`deep:auth:${u}`,label:`Open user ${u} in Auth`,hint:"Auth uid",target:{tab:"auth",rest:[u]}}):h.id==="traffic"&&o.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 h=d[1].split("/").filter(Boolean);o.unshift({id:`deep:storage:${d[1]}`,label:`Open ${d[1]} in Storage`,hint:"Storage object path",target:{tab:"storage",rest:h}})}else if(n.includes("/")&&!n.includes(" ")){const h=n.split("/").filter(Boolean);h.length&&o.push({id:`deep:firestore:${n}`,label:`Open /${h.join("/")} in Firestore`,hint:"Firestore path",target:{tab:"firestore",rest:h}})}return[...s,...o,...i].slice(0,tO)}function $a(e){return`${e.kind}:${e.target.tab}:${(e.target.rest??[]).join("/")}`}const Pa={docsPerCollection:50,collectionsScanned:20,users:100,objects:200,storageListCalls:20,subcollections:30,subcollectionRpcCalls:40};async function rO(e,t,{maxObjects:n,maxListCalls:r}){const s=[],i=[e];let o=0;for(;i.length&&s.length<n&&o<r;){o++;const a=await t(i.shift());for(const l of a.items){if(s.length>=n)break;s.push(l.fullPath)}i.push(...a.prefixes)}return s}async function sO(e,t,n,{maxSubcollections:r,maxRpcCalls:s,docsPerCollection:i}){const o=[],a=[],l=[...e];let u=0;for(;l.length&&o.length<r&&u<s;){const d=l.shift();u++;let h=[];try{h=await t(d)}catch{continue}for(const f of h){if(o.length>=r)break;const p=`${d}/${f}`;o.push(p);try{const m=await n(p,i);for(const g of m.slice(0,i))a.push(g),l.push(g)}catch{}}}return{subcollections:o,documents:a}}const iO=5;function pi(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,o=-1,a=-1;for(let u=0;u<r.length&&i<n.length;u++)r[u]===n[i]&&(o===-1&&(o=u),a=u,i++);if(i!==n.length)return 0;const l=a-o+1;return Math.max(1,400-(l-n.length)*10-Math.min(o,50))}const oO={collection:"Firestore collections",document:"Firestore documents",subcollection:"Firestore subcollections",user:"Auth users",object:"Storage objects","rtdb-key":"RTDB keys"},aO=["collection","document","subcollection","user","object","rtdb-key"];function cO(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 ky(e){return e.endsWith("/")?{base:e.slice(0,-1),trailing:!0}:{base:e,trailing:!1}}function lO(e,t){const{base:n,trailing:r}=ky(e);if(!n)return 0;const s=n.split("/"),i=t.split("/");if(s.length>i.length)return 0;const o=s.length-1;for(let a=0;a<o;a++)if(s[a].toLowerCase()!==i[a].toLowerCase())return 0;return r?s[o].toLowerCase()===i[o].toLowerCase()?850:0:pi(s[o],i[o])}function uO(e,t){const{base:n,trailing:r}=ky(e);if(!n||n.includes("/"))return 0;const s=t.split("/").pop()??t;return r?s.toLowerCase()===n.toLowerCase()?850:0:pi(n,s)}function Dd(e,t,n,r=iO){const s=e.trim();if(!s)return[];const i=[],o=nO(e,t);o.length&&i.push({kind:"navigate",title:"Go to",results:o});for(const a of aO){const l=a==="document"||a==="subcollection",u=a==="collection"||a==="subcollection",d=new Map;for(const f of n)f.kind===a&&d.set($a(f),f);const h=[...d.values()].map(f=>({entry:f,score:Math.max(pi(s,f.label),f.alt?pi(s,f.alt):0,l?lO(s,f.label):0,u?uO(s,f.label):0)})).filter(f=>f.score>0).sort((f,p)=>p.score-f.score||f.entry.label.localeCompare(p.entry.label)).slice(0,r);h.length&&i.push({kind:a,title:oO[a],results:h.map(({entry:f})=>({id:$a(f),label:f.label,hint:cO(f),target:f.target}))})}return i}function Td(e){return e.flatMap(t=>t.results)}function dO(e){return{kind:"collection",label:e,target:{tab:"firestore",rest:[e]}}}function Md(e){return{kind:"document",label:e,target:{tab:"firestore",rest:e.split("/").filter(Boolean)}}}function fO(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 hO(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 pO(e){return{kind:"object",label:e,target:{tab:"storage",rest:e.split("/").filter(Boolean)}}}function mO(e){return{kind:"rtdb-key",label:e,target:{tab:"rtdb",rest:[e]}}}async function yO(e,t={},n){const r={...Pa,...t},s=[],i=d=>{d.length&&(s.push(...d),n?.(d))},o=(async()=>{let d=[];try{d=await e.listRootCollections?.()??[]}catch{d=[]}d.length&&i(d.map(dO));const h=[];if(e.listDocumentPaths)for(const f of d.slice(0,r.collectionsScanned))try{const m=(await e.listDocumentPaths(f,r.docsPerCollection)).slice(0,r.docsPerCollection);h.push(...m),i(m.map(Md))}catch{}if(e.listSubcollections&&e.listDocumentPaths)try{const{subcollections:f,documents:p}=await sO(h,e.listSubcollections,e.listDocumentPaths,{maxSubcollections:r.subcollections,maxRpcCalls:r.subcollectionRpcCalls,docsPerCollection:r.docsPerCollection});i(f.map(fO)),i(p.map(Md))}catch{}})(),a=(async()=>{if(e.listUsers)try{const d=await e.listUsers(r.users);i(d.slice(0,r.users).map(hO))}catch{}})(),l=(async()=>{if(e.listStorageObjectPaths)try{const d=await e.listStorageObjectPaths(r.objects);i(d.slice(0,r.objects).map(pO))}catch{}})(),u=(async()=>{if(e.listRtdbTopLevelKeys)try{i((await e.listRtdbTopLevelKeys()).map(mO))}catch{}})();return await Promise.allSettled([o,a,l,u]),s}function gO(e,t,n){const r={name:n,options:structuredClone(t),automaticDataCollectionEnabled:!0};return yC(r,e),r}const bO=Object.freeze({source:Object.freeze({kind:"studio"}),authLens:Object.freeze({mode:"admin"})});function wO(e){return eh(e.withAuth(null),bO)}const vO="pyric-studio";function jy(e,t){return e.listDocuments(t).map(({path:n,phantom:r})=>({path:n,phantom:r}))}let xO=0;function _O(e){const t=gO(e,{projectId:"pyric-studio"},`pyric-studio-${xO++}`),n=Jr(e),r=wO(e);return{sandbox:e,app:t,firestore:Ks(e),adminFirestore:sc(r),auth:yc(e),storage:yk(r),listRootCollections:()=>n.listRootCollections(),listSubcollections:s=>n.listSubcollections(s),listDocuments:s=>jy(n,s)}}function SO(e,t){const[n,r]=y.useState(!1),[s,i]=y.useState(null),o=y.useMemo(()=>Qw(),[]),a=y.useMemo(()=>{try{return _O(o)}catch(u){return i(u instanceof Error?u:new Error(String(u))),null}},[o]);return y.useEffect(()=>{let u=!1;if(!e){r(!1);return}return o.enablePersistence({key:vO,injectedBackend:e}).then(()=>{u||r(!0)}).catch(d=>{u||i(d instanceof Error?d:new Error(String(d)))}),()=>{u=!0}},[o,e]),s?{status:"error",handles:null,error:s}:a?e!=null&&n||t==="ready"?{status:"ready",handles:a}:{status:"pending",handles:null}:{status:"error",handles:null,error:new Error("Studio: failed to construct the sandbox data handles.")}}function kO(e){const t=Jr(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=>jy(t,n)}}function Rt(){const e=Kt(),t=lt(),n=t.status==="ready"?t.env.persistence:void 0,r=SO(n,t.status),s=t.status==="ready"?t.env.live:void 0,i=jO(s);return y.useMemo(()=>{switch(e.status){case"ready":return{status:"ready",handles:kO(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 o=s.db;return{status:"ready",firestoreApi:s.firestoreApi,authApi:s.authApi,storageApi:s.storageApi,handles:{...r.handles,firestore:o,adminFirestore:o,auth:s.auth,storage:s.storage,listRootCollections:()=>i,listSubcollections:a=>s.listSubcollections(a),listDocuments:a=>s.listDocuments(a)}}}return r}}},[e,r,s,i])}function jO(e){const[t,n]=y.useState([]);return y.useEffect(()=>{if(!e){n([]);return}let r=!0;const s=()=>{e.listRootCollections().then(o=>{r&&n(o)}).catch(()=>{})};try{e.setLens({mode:"admin"})}catch{}s();const i=e.feed.subscribe(()=>s());return()=>{r=!1,i()}},[e]),t}function EO(e){let t=!0;return n=>{const r=t;t=!1,e(s=>NO(s,n,r))}}function CO(e){const t=new Map;for(const n of e)t.set($a(n),n);return[...t.values()]}function NO(e,t,n){return CO(n?t:[...e??[],...t])}const RO=3e4;function Ey(){const e=Rt(),t=lt(),[n,r]=y.useState(null),[s,i]=y.useState(!1),o=y.useRef(!1),a=y.useRef(e);a.current=e;const l=t.status==="ready"?t.env.live:void 0,u=y.useRef(l);u.current=l;const d=y.useRef(null),h=y.useRef(0),f=y.useRef(null),p=y.useRef(0),m=y.useCallback(b=>{const w=a.current;if(w.status!=="ready")return;const x=++h.current;o.current=!0,i(!0);const v=w.handles,_=v.adminFirestore,S=w.firestoreApi?.collection??pr,k=w.firestoreApi?.query??ui,N=w.firestoreApi?.getDocs??li,O=w.firestoreApi?.limit??di,P=w.storageApi?.ref??Or,R=w.storageApi?.listAll??kc,j=w.authApi?.listUsers??xe.listUsers,E={listRootCollections:()=>v.listRootCollections(),listDocumentPaths:async(C,I)=>(await N(k(S(_,C),O(I)))).docs.slice(0,I).map(D=>`${C}/${D.id}`),listSubcollections:C=>Promise.resolve(v.listSubcollections(C)),listUsers:async C=>(await Promise.resolve(j(v.auth))).slice(0,C).map(A=>({uid:A.uid,email:A.email??null})),listStorageObjectPaths:C=>rO(P(v.storage,""),R,{maxObjects:C,maxListCalls:Pa.storageListCalls}),listRtdbTopLevelKeys:async()=>{const C=u.current;if(!C)return[];const I=Date.now()-p.current<RO;if(f.current!==null&&I&&!b?.rtdbLikely)return f.current;const A=await C.readRtdbState(),D=A===null||typeof A!="object"||Array.isArray(A)?[]:Object.keys(A);return f.current=D,p.current=Date.now(),D}},$=EO(C=>r(C));yO(E,Pa,C=>{x===h.current&&$(C)}).catch(()=>{}).finally(()=>{if(x===h.current&&(o.current=!1,i(!1),r(C=>C??[]),d.current)){const C=d.current;d.current=null,m(C)}})},[]),g=y.useCallback(b=>{if(a.current.status==="ready"){if(o.current){d.current={...d.current,...b};return}m(b)}},[m]);return y.useEffect(()=>{e.status==="ready"&&n===null&&!o.current&&m()},[e,n,m]),{entries:n,building:s,ensure:g}}const IO=150;function AO(e){return e.startsWith("/")||/rtdb/i.test(e)}function Cy({autoFocus:e,onNavigated:t,onEscape:n,exposeFocus:r}){const[s,i]=y.useState(""),[o,a]=y.useState(""),[l,u]=y.useState(0),[d,h]=y.useState(!1),f=y.useRef(null),{entries:p,building:m,ensure:g}=Ey();y.useEffect(()=>{if(r)return r(()=>f.current?.focus()),()=>r(null)},[r]),y.useEffect(()=>{e&&f.current?.focus()},[e]),y.useEffect(()=>{const S=setTimeout(()=>a(s),IO);return()=>clearTimeout(S)},[s]);const b=y.useMemo(()=>Dd(o,fn,p??[]),[o,p]),w=y.useMemo(()=>Td(b),[b]);y.useEffect(()=>{u(S=>w.length===0?0:Math.min(S,w.length-1))},[w.length]);const x=S=>{S&&(i(""),a(""),h(!1),Ae(S.target),t?.(S.target))},v=()=>{if(s===o){x(w[l]??w[0]);return}const S=Td(Dd(s,fn,p??[]));x(S[0])};let _=0;return c.jsxs("div",{className:"studio-home__command",children:[c.jsx("div",{className:"studio-home__command-row",children:c.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&&w.length>0,"aria-autocomplete":"list",onFocus:()=>{g(),h(!0)},onBlur:()=>h(!1),onChange:S=>{const k=S.target.value;i(k),h(!0),AO(k)&&g({rtdbLikely:!0})},onKeyDown:S=>{if(S.key==="ArrowDown")S.preventDefault(),u(k=>Math.min(k+1,Math.max(w.length-1,0)));else if(S.key==="ArrowUp")S.preventDefault(),u(k=>Math.max(k-1,0));else if(S.key==="Enter")v();else if(S.key==="Escape"){if(n){n();return}i(""),a(""),h(!1)}}})}),d&&!b.length&&m&&p===null?c.jsx("div",{className:"studio-home__command-results",role:"status","aria-live":"polite",children:c.jsx("span",{className:"studio-home__command-group-title",children:"Indexing sandbox…"})}):null,d&&b.length?c.jsx("div",{className:"studio-home__command-results",role:"listbox","aria-label":"Suggestions",onMouseDown:S=>S.preventDefault(),children:b.map(S=>{const k=_;return _+=S.results.length,c.jsxs("div",{className:"studio-home__command-group",children:[c.jsx("span",{className:"studio-home__command-group-title","aria-hidden":"true",children:S.title}),c.jsx("ul",{className:"studio-home__command-group-list",children:S.results.map((N,O)=>{const P=k+O;return c.jsx("li",{children:c.jsxs("button",{type:"button",role:"option","aria-selected":P===l,className:"studio-home__command-result","data-active":P===l?"true":void 0,onMouseEnter:()=>u(P),onClick:()=>x(N),children:[c.jsx("span",{className:"studio-home__command-label",children:N.label}),c.jsx("span",{className:"studio-home__command-sub",children:N.hint})]})},N.id)})})]},S.kind)})}):null]})}function OO({onClose:e}){const t=y.useRef(null);return y.useEffect(()=>(t.current=document.activeElement,()=>{const n=t.current;n instanceof HTMLElement&&n.focus()}),[]),y.useEffect(()=>{const n=r=>{r.key==="Escape"&&e()};return window.addEventListener("keydown",n),()=>window.removeEventListener("keydown",n)},[e]),c.jsx("div",{className:"studio__cmdk-backdrop",onMouseDown:e,children:c.jsx("div",{className:"studio__cmdk",role:"dialog","aria-modal":"true","aria-label":"Command",onMouseDown:n=>n.stopPropagation(),children:c.jsx(Cy,{autoFocus:!0,onEscape:e,onNavigated:e})})})}function Tc(e){if(e.result==="allow")return!1;const t=e.queryProof?.kind;return t==="unsupported-predicate"||t==="unsupported-path"}function $O(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=uh(e);return t?t.rules.kind==="evaluated":!1}function PO(e){return"service"in e&&typeof e.service=="string"?e.service:"firestore"}function DO(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 TO(e){if(!("request"in e)||!e.request)return;const n=e.request.updateMask;return Array.isArray(n)&&n.every(s=>Array.isArray(s)&&s.every(i=>typeof i=="string"))?n:void 0}function MO(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 LO(e){const t=[];for(const r of e)$O(r)&&t.push(UO(r));return MO(t,e).sort((r,s)=>s.at-r.at)}function UO(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:PO(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),"queryProof"in e&&e.queryProof&&(i.queryProof=e.queryProof),"rules"in e&&e.rules&&(i.rules=e.rules);const o=DO(e);o!==void 0&&(i.resourceData=o);const a=TO(e);return a!==void 0&&(i.updateMask=a),"resourceBefore"in e&&e.resourceBefore&&(i.resourceBefore={data:e.resourceBefore.data,exists:e.resourceBefore.exists}),i}const Ld=/^Rule #(\d+) \(([^)]+)\) → (ALLOW|deny|unsupported)/;function BO(e){const t=e.rules?.engine??e.service;return t==="rtdb"||t==="storage"?t:"firestore"}function FO(e){return e==="Validation rule evaluated to false"||!!e?.startsWith("Validation rule at '")}function Ny(e){if(FO(e.rules?.reason))return"validate";const t=e.method;return t==="get"||t==="list"||t==="listen"?"read":"write"}function VO(e,t){const n=e.rules?.matchedPath;if(!(!t||!n||e.rules?.errorCode==="NO_MATCHING_RULE"))return $A(t,n,`.${Ny(e)}`)?.line}function Mc(e){if(e.result!=="allow")return e.queryProof?.failures.find(t=>t.kind===e.queryProof?.kind)}function qO(e){const t=BO(e),n=e.reasons.filter(i=>Ld.test(i)),r=e.reasons.filter(i=>!Ld.test(i)),s=Mc(e);if(s)return{headline:Tc(e)?`Query proof unsupported: Pyric could not prove ${e.method} ${e.path} safe. This does not establish Firebase's decision.`:`The query constraints do not satisfy the list rule for ${e.path}.`,engine:t,ruleNode:s.rule?.citation??"list rule",ruleExpression:s.rule?.expression,ruleLines:n,otherLines:r,implicitDeny:!1};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 o=e.matchedRule,a=`Rule #${o.ruleIndex} (${o.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"?zO(e,n,r):t==="storage"?HO(e,n,r):WO(e,n,r)}function WO(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 o=e.matchedRule;i=`Rule #${o.ruleIndex} (${o.operations.join(", ")})`,s=`${i} denied ${e.method} on ${e.path}.`}return{headline:s,engine:"firestore",ruleNode:i,ruleLines:t,otherLines:n,implicitDeny:r}}function zO(e,t,n){const r=e.rules,s=Ny(e),i=!r?.matchedPath||r?.errorCode==="NO_MATCHING_RULE",o=r?.pathVariableBindings&&Object.keys(r.pathVariableBindings).length>0?r.pathVariableBindings:void 0;let a,l;return i?a=`No \`.${s}\` rule granted ${e.method} on ${e.path}: RTDB implicit deny (no rule matched).`:s==="validate"?(l=`${r.matchedPath} .validate`,a=`The \`.validate\` rule at \`${r.matchedPath}\` rejected the proposed value for ${e.method} ${e.path}.`):(l=`${r.matchedPath} .${s}`,a=`The \`.${s}\` rule at \`${r.matchedPath}\` evaluated false for ${e.method} ${e.path}.`),{headline:a,engine:"rtdb",ruleNode:l,ruleExpression:r?.matchedRule,phase:s,bindings:o,ruleLines:t,otherLines:n,implicitDeny:i}}function HO(e,t,n){const r=e.reasons.find(a=>/^match\s/.test(a)),i=e.reasons.some(a=>/^no rule matches/.test(a))||!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 KO(e){return e.skipped?"skipped":e.error!==void 0?"error":e.value===!0?"true":e.value===!1?"false":"value"}function GO(e){const t=e.evaluatedRule?.expressionTrace;if(!t||t.length===0)return[];const n=t.map(s=>({source:s.source,outcome:KO(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}const JO={ALLOW:"true",DENY:"false",ERROR:"error",UNSUPPORTED:"unsupported"};function YO(e,t){const n=e.rules?.rtdbTrace;return!n||n.length===0?[]:(t===void 0?[...n]:ay(t,n)).map(s=>{const i={source:s.conditionText,outcome:JO[s.verdict],...s.verdict==="ALLOW"||s.verdict==="DENY"?{value:s.verdict==="ALLOW"}:{},...s.message!==void 0?{error:s.message}:{},depth:0,children:[]},o={path:s.path,kind:s.kind,verdict:s.verdict,step:i,bindings:s.pathVariableBindings};return s.line!==void 0&&(o.line=s.line),o})}function QO(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}const kr=500;function Ro(e,t){if(e.length<=kr)return e;const n=e.slice(-kr);if(t==="recent")return n;const r=new Set(ac(e).map(i=>i.id));return[...e.slice(0,-kr).filter(i=>(i.kind==="listener_attach"||i.kind==="listener"&&i.phase==="attach")&&r.has(i.listenerId)),...n]}function Jt(e="recent"){const t=Kt(),n=lt(),r=n.status==="ready"?n.env.live?.feed:void 0,s=t.status==="ready",[i,o]=y.useState([]);y.useEffect(()=>{if(s||!r){o([]);return}return o(Ro(r.history(),e)),r.subscribe(u=>o(d=>Ro(YE(d,u),e)))},[s,r,e]);const a=y.useMemo(()=>s?Ro(t.events,e):[],[s,t,e]);return s?a:i}function XO(e){return Ow(e)}function ZO(e){if(typeof e!="string")return!1;const t=e.toLowerCase();return t==="permission_denied"||t==="permission-denied"||t==="auth/permission-denied"}function e$(e){const t=uh(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,queryProof:t.queryProof};if(e.kind==="listener"){let s="error";if(e.result!==void 0)s=e.result;else{const a=e.error;a!==void 0&&ZO(a.code)&&(s="deny")}let i="(service)";e.target.path!==void 0&&(i=e.target.path);let o=[];if(e.reasons!==void 0)o=e.reasons;else{const a=e.error;a!==void 0&&a.reasons!==void 0&&(o=a.reasons)}return{kind:"operation",service:e.service,id:e.id,at:e.at,method:"listen",path:i,auth:e.auth,result:s,reasons:o,origin:"listener",triggeredBy:e.triggeredBy,operationContext:t.context,rulesDisposition:t.rules,queryProof:t.queryProof}}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,queryProof:t.queryProof}}function t$(){const e=Jt();return y.useMemo(()=>e.filter(XO).map(e$),[e])}function n$(){const e=Jt();return y.useMemo(()=>LO(e),[e])}const r$={status:"loading",payload:null},Es={status:"absent",payload:null};let mi=r$,Ud=!1;const Da=new Set;function Cs(e){mi=e;for(const t of Da)t()}function s$(){if(!Ud){if(Ud=!0,typeof fetch>"u"){mi=Es;return}fetch("/__pyric/init.json").then(async e=>{if(!e.ok||!(e.headers.get("content-type")??"").includes("json"))return Cs(Es);const n=await e.json();Cs({status:"ready",payload:n})}).catch(()=>Cs(Es))}}function i$(e){return Da.add(e),s$(),()=>Da.delete(e)}function ls(){return y.useSyncExternalStore(i$,()=>mi,()=>mi)}function o$(e){return e.kind==="absent"?"absent":e.sandboxConnected?"available":"idle"}function a$(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 c$(e){try{const t=await e("/__pyric/health");return t.ok?(t.headers.get("content-type")??"").includes("json")?a$(t.status,await t.json()):{kind:"absent"}:{kind:"absent"}}catch{return{kind:"absent"}}}function l$(e=5e3){const[t,n]=y.useState("checking");return y.useEffect(()=>{if(typeof fetch>"u"){n("absent");return}let r=!0,s=null;const i=async()=>{const u=o$(await c$(fetch));return r&&(n(u),u==="absent"&&s&&(clearInterval(s),s=null)),u},o=()=>typeof document>"u"||document.visibilityState!=="hidden",a=()=>{s||(s=setInterval(()=>{o()&&i()},e))},l=()=>{o()&&i()};return i().then(u=>{r&&u!=="absent"&&a()}),typeof document<"u"&&document.addEventListener("visibilitychange",l),()=>{r=!1,s&&clearInterval(s),typeof document<"u"&&document.removeEventListener("visibilitychange",l)}},[e]),t}const u$="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 d$(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 f$(e){return e==="studio"?"Studio":"App"}function h$(e,t,n=Date.now()){const r=e.clients.length,s=e.clients.map(o=>({clientId:o.clientId,kindLabel:f$(o.kind),route:o.route||"/",visibilityLabel:o.visibility==="hidden"?"Hidden":"Visible",isThisPage:o.clientId===t,freshnessLabel:d$(o.lastSeen,n)}));s.sort((o,a)=>o.isThisPage!==a.isThisPage?o.isThisPage?-1:1:o.kindLabel!==a.kindLabel?o.kindLabel==="Studio"?-1:1:o.route.localeCompare(a.route));const i=s.filter(o=>!o.isThisPage).length;return{count:r,chipLabel:r===1?"1 page connected":`${r} pages connected`,prominent:r>1,clients:s,boundaryCopy:u$,otherCount:i}}function p$(){const e=lt(),t=e.status==="ready"&&e.env.live?e.env.live:null,[n,r]=y.useState(null);return y.useEffect(()=>{if(!t){r(null);return}const s=t.presenceClientId;return t.subscribePresence(i=>{r(h$(i,s))})},[t]),n}const m$=new Set(["flutter","swift","ios","kotlin","android"]);function y$(e){const t=(e.platform||"").toLowerCase();return m$.has(t)}function g$(){const e=ls(),[t,n]=y.useState([]),[r,s]=y.useState(!1),i=y.useRef(null),o=y.useRef(new Map);return y.useEffect(()=>{if(e.status!=="ready"||!e.payload.bridgeUrl){s(!1),n([]);return}let l=!1,u=null,d=1e3;const h=typeof window<"u"?window.location:null,f=h?vy(e.payload.bridgeUrl,h):e.payload.bridgeUrl;function p(){if(!l)try{const m=new WebSocket(f);i.current=m,m.onopen=()=>{if(l){m.close();return}s(!0),d=1e3;try{m.send(JSON.stringify({type:"attach",protocol:1,clientInfo:{platform:"studio",deviceLabel:"Desktop Studio"}}))}catch{}},m.onmessage=g=>{if(!l)try{const b=JSON.parse(g.data);if(b.type==="consumer-presence"){const x=(b.consumers||[]).filter(y$);n(x)}else if(b.type==="remote-set-lens-ack"){const w=b;if(w.id&&o.current.has(w.id)){const x=o.current.get(w.id);o.current.delete(w.id),x?.(w.ok)}}}catch{}},m.onclose=()=>{i.current=null,!l&&(s(!1),u=setTimeout(()=>{d=Math.min(d*1.5,1e4),p()},d))},m.onerror=()=>{}}catch{s(!1)}}return p(),()=>{if(l=!0,u&&clearTimeout(u),i.current){try{i.current.close()}catch{}i.current=null}for(const m of o.current.values())m(!1);o.current.clear(),s(!1)}},[e]),{consumers:t,connected:r,setLens:async(l,u)=>{n(f=>f.map(p=>p.clientSessionId===l?{...p,activeLens:u,lastSeen:Date.now()}:p));const d=i.current;if(!d||d.readyState!==WebSocket.OPEN)return!1;const h=`lens-${Date.now()}-${Math.random().toString(36).slice(2,7)}`;return new Promise(f=>{const p=setTimeout(()=>{o.current.delete(h),f(!0)},5e3);o.current.set(h,m=>{clearTimeout(p),f(m)});try{d.send(JSON.stringify({type:"remote-set-lens",id:h,clientSessionId:l,lens:u}))}catch{clearTimeout(p),o.current.delete(h),f(!1)}})}}}const b$={listUsers:xe.listUsers,subscribeUsers:xe.subscribeUsers,createUser:xe.createUser,updateUser:xe.updateUser,deleteUser:xe.deleteUser,clearUsers:xe.clearUsers,getAuthProviderConfig:xe.getAuthProviderConfig,setAuthProviderConfig:xe.setAuthProviderConfig,subscribeAuthProviderConfig:xe.subscribeAuthProviderConfig},Ry=y.createContext(b$);function w$(){return y.useContext(Ry)}function Iy({value:e,children:t}){return y.createElement(Ry.Provider,{value:e},t)}function v$(e,t){return[e.uid,e.email,e.displayName,e.phoneNumber].some(n=>n!=null&&n.toLowerCase().includes(t))}function Li(e){const{listUsers:t,subscribeUsers:n,createUser:r,updateUser:s,deleteUser:i,clearUsers:o}=w$(),[a,l]=y.useState([]),[u,d]=y.useState(!0),[h,f]=y.useState(void 0),[p,m]=y.useState(""),g=y.useCallback(k=>{l(k),f(void 0),d(!1)},[]);y.useEffect(()=>{let k=!1;d(!0),f(void 0);const N=j=>{k||g(j)},O=j=>{k||(l([]),f(j instanceof Error?j:new Error(String(j))),d(!1))},P=()=>{try{const j=t(e);j&&typeof j.then=="function"?j.then(N).catch(O):N(j)}catch(j){O(j)}};let R;try{P(),R=n(e,P)}catch(j){O(j)}return()=>{k=!0,R?.()}},[e,t,n,g]);const b=y.useMemo(()=>{const k=p.trim().toLowerCase();return k?a.filter(N=>v$(N,k)):a},[a,p]),w=y.useCallback(k=>r(e,k),[e,r]),x=y.useCallback((k,N)=>s(e,k,N),[e,s]),v=y.useCallback(k=>i(e,k),[e,i]),_=y.useCallback(()=>o(e),[e,o]),S=y.useCallback(()=>{const k=t(e);k&&typeof k.then=="function"?k.then(g).catch(()=>{}):g(k)},[e,t,g]);return{users:b,totalCount:a.length,isLoading:u,error:h,filter:p,setFilter:m,createUser:w,updateUser:x,deleteUser:v,clearUsers:_,refresh:S}}const x$=["iss","aud","sub","iat","exp","nbf","jti","nonce","azp","acr","amr","cnf","auth_time","firebase","at_hash","c_hash"],_$=1e3;function Ay(e){const t=e.trim();if(!t)return{ok:!0,claims:void 0};if(t.length>_$)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 x$)if(r in n)return{ok:!1,message:`Custom claims must not have forbidden key: ${r}`};return{ok:!0,claims:n}}const S$={email:"",password:"",displayName:"",phoneNumber:"",photoUrl:"",emailVerified:!1,disabled:!1,claimsText:"",providerIds:[]},k$=new Set(["password","anonymous","phone"]),j$=/^[^@]+@[^@]+\.[^@]+$/,Bd=6;function E$(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=>!k$.has(t))}:{...S$}}function C$(e){const t=E$(e);return{fields:t,initial:{...t}}}function N$(e,t){switch(t.type){case"setField":return{...e,fields:{...e.fields,[t.field]:t.value}};case"reset":return{...e,fields:{...e.initial}}}}function R$(e){const t={},n=e.email.trim(),r=e.password;n&&!j$.test(n)&&(t.email="Invalid email"),r&&r.length<Bd&&(t.password=`Password should be at least ${Bd} characters`),r&&!n&&(t.password="Email is required for password authentication");const s=Ay(e.claimsText);return s.ok||(t.claims=s.message),t}function I$(e){const{fields:t,initial:n}=e;return Object.keys(t).some(r=>r==="providerIds"?!Oy(t.providerIds,n.providerIds):t[r]!==n[r])}function Oy(e,t){if(e.length!==t.length)return!1;const n=[...t].sort();return[...e].sort().every((r,s)=>r===n[s])}function $y(e){const t=Ay(e.claimsText);return t.ok?t.claims:void 0}function A$(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=$y(t);return r&&(n.customClaims=r),t.providerIds.length&&(n.providerUserInfo=t.providerIds.map(s=>({providerId:s}))),n}function O$(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=$y(t)??{}),Oy(t.providerIds,n.providerIds)||(r.providerUserInfo=t.providerIds.map(s=>({providerId:s}))),r}function Py(e={}){const[t,n]=y.useReducer(N$,e.initial,C$),r=y.useMemo(()=>R$(t.fields),[t.fields]),s=y.useMemo(()=>I$(t),[t]),i=y.useCallback((a,l)=>n({type:"setField",field:a,value:l}),[]),o=y.useCallback(()=>n({type:"reset"}),[]);return{fields:t.fields,errors:r,isDirty:s,isValid:Object.keys(r).length===0,setField:i,reset:o,toCreateRequest:()=>A$(t),toUpdateRequest:()=>O$(t),dispatch:n}}const $$={"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 yi(e){return $$[e]??e}var Lc=Xw();function wn(e,t,n){let r=n.initialDeps??[],s,i=!0;function o(){var a,l,u;let d;n.key&&((a=n.debug)!=null&&a.call(n))&&(d=Date.now());const h=e();if(!(h.length!==r.length||h.some((m,g)=>r[g]!==m)))return s;r=h;let p;if(n.key&&((l=n.debug)!=null&&l.call(n))&&(p=Date.now()),s=t(...h),n.key&&((u=n.debug)!=null&&u.call(n))){const m=Math.round((Date.now()-d)*100)/100,g=Math.round((Date.now()-p)*100)/100,b=g/16,w=(x,v)=>{for(x=String(x);x.length<v;)x=" "+x;return x};console.info(`%c⏱ ${w(g,5)} /${w(m,5)} ms`,`
|
|
138
138
|
font-size: .6rem;
|
|
139
139
|
font-weight: bold;
|
|
140
|
-
color: hsl(${Math.max(0,Math.min(120-120*b,120))}deg 100% 31%);`,n?.key)}return n?.onChange&&!(i&&n.skipInitialOnChange)&&n.onChange(s),i=!1,s}return o.updateDeps=a=>{r=a},o}function Bd(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const I$=(e,t)=>Math.abs(e-t)<1.01,A$=(e,t,n)=>{let r;return function(...s){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,s),n)}},Fd=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},O$=e=>e,$$=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},D$=(e,t)=>{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;const s=o=>{const{width:a,height:l}=o;t({width:Math.round(a),height:Math.round(l)})};if(s(Fd(n)),!r.ResizeObserver)return()=>{};const i=new r.ResizeObserver(o=>{const a=()=>{const l=o[0];if(l?.borderBoxSize){const u=l.borderBoxSize[0];if(u){s({width:u.inlineSize,height:u.blockSize});return}}s(Fd(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(a):a()});return i.observe(n,{box:"border-box"}),()=>{i.unobserve(n)}},qd={passive:!0},Vd=typeof window>"u"?!0:"onscrollend"in window,P$=(e,t)=>{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;let s=0;const i=e.options.useScrollendEvent&&Vd?()=>{}:A$(r,()=>{t(s,!1)},e.options.isScrollingResetDelay),o=d=>()=>{const{horizontal:h,isRtl:f}=e.options;s=h?n.scrollLeft*(f&&-1||1):n.scrollTop,i(),t(s,d)},a=o(!0),l=o(!1);n.addEventListener("scroll",a,qd);const u=e.options.useScrollendEvent&&Vd;return u&&n.addEventListener("scrollend",l,qd),()=>{n.removeEventListener("scroll",a),u&&n.removeEventListener("scrollend",l)}},T$=(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"]},M$=(e,{adjustments:t=0,behavior:n},r)=>{var s,i;const o=e+t;(i=(s=r.scrollElement)==null?void 0:s.scrollTo)==null||i.call(s,{[r.options.horizontal?"left":"top"]:o,behavior:n})};class L${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 o=()=>{const a=i.target,l=this.indexFromElement(a);if(!a.isConnected){this.observer.unobserve(a);return}this.shouldMeasureDuringScroll(l)&&this.resizeItem(l,this.options.measureElement(a,i,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(o):o()})}));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:O$,rangeExtractor:$$,onChange:()=>{},measureElement:T$,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=bn(()=>(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 o=r-1;o>=0;o--){const a=n[o];if(s.has(a.lane))continue;const l=i.get(a.lane);if(l==null||a.end>l.end?i.set(a.lane,a):a.end<l.end&&s.set(a.lane,!0),s.size===this.options.lanes)break}return i.size===this.options.lanes?Array.from(i.values()).sort((o,a)=>o.end===a.end?o.index-a.index:o.end-a.end)[0]:void 0},this.getMeasurementOptions=bn(()=>[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,o,a,l)=>(this.prevLanes!==void 0&&this.prevLanes!==a&&(this.lanesChangedFlag=!0),this.prevLanes=a,this.pendingMeasuredCacheIndexes=[],{count:n,paddingStart:r,scrollMargin:s,getItemKey:i,enabled:o,lanes:a,laneAssignmentMode:l}),{key:!1}),this.getMeasurements=bn(()=>[this.getMeasurementOptions(),this.itemSizeCache],({count:n,paddingStart:r,scrollMargin:s,getItemKey:i,enabled:o,lanes:a,laneAssignmentMode:l},u)=>{if(!o)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>n)for(const p of this.laneAssignments.keys())p>=n&&this.laneAssignments.delete(p);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(p=>{this.itemSizeCache.set(p.key,p.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 h=this.measurementsCache.slice(0,d),f=new Array(a).fill(void 0);for(let p=0;p<d;p++){const m=h[p];m&&(f[m.lane]=p)}for(let p=d;p<n;p++){const m=i(p),g=this.laneAssignments.get(p);let b,w;const x=l==="estimate"||u.has(m);if(g!==void 0&&this.options.lanes>1){b=g;const k=f[b],N=k!==void 0?h[k]:void 0;w=N?N.end+this.options.gap:r+s}else{const k=this.options.lanes===1?h[p-1]:this.getFurthestMeasurement(h,p);w=k?k.end+this.options.gap:r+s,b=k?k.lane:p%this.options.lanes,this.options.lanes>1&&x&&this.laneAssignments.set(p,b)}const v=u.get(m),_=typeof v=="number"?v:this.options.estimateSize(p),S=w+_;h[p]={index:p,start:w,size:_,end:S,key:m,lane:b},f[b]=p}return this.measurementsCache=h,h},{key:!1,debug:()=>this.options.debug}),this.calculateRange=bn(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,s,i)=>this.range=n.length>0&&r>0?U$({measurements:n,outerSize:r,scrollOffset:s,lanes:i}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=bn(()=>{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,o)=>i===null||o===null?[]:n({startIndex:i,endIndex:o,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)),o=Math.max(0,s-i),a=Math.min(this.options.count-1,s+i);return n>=o&&n<=a}return!0},this.measureElement=n=>{if(!n){this.elementsCache.forEach((o,a)=>{o.isConnected||(this.observer.unobserve(o),this.elementsCache.delete(a))});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 o=this.itemSizeCache.get(i.key)??i.size,a=r-o;a!==0&&(((s=this.scrollState)==null?void 0:s.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(i,a,this):i.start<this.getScrollOffset()+this.scrollAdjustments)&&this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=a,behavior:void 0}),this.pendingMeasuredCacheIndexes.push(i.index),this.itemSizeCache=new Map(this.itemSizeCache.set(i.key,r)),this.notify(!1))},this.getVirtualItems=bn(()=>[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const s=[];for(let i=0,o=n.length;i<o;i++){const a=n[i],l=r[a];s.push(l)}return s},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length!==0)return Bd(r[Oy(0,r.length-1,s=>Bd(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(),o=this.getScrollOffset();r==="auto"&&(r=n>=o+i?"end":"start"),r==="center"?n+=(s-i)/2:r==="end"&&(n-=i);const a=this.getMaxScrollOffset();return Math.max(Math.min(a,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(),o=this.measurementsCache[n];if(!o)return;if(r==="auto")if(o.end>=i+s-this.options.scrollPaddingEnd)r="end";else if(o.start<=i+this.options.scrollPaddingStart)r="start";else return[i,r];if(r==="end"&&n===this.options.count-1)return[this.getMaxScrollOffset(),r];const a=r==="end"?o.end+this.options.scrollPaddingEnd:o.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(a,r,o.size),r]},this.scrollToOffset=(n,{align:r="start",behavior:s="auto"}={})=>{const i=this.getOffsetForAlignment(n,r),o=this.now();this.scrollState={index:null,align:r,behavior:s,startedAt:o,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[o,a]=i,l=this.now();this.scrollState={index:n,align:a,behavior:s,startedAt:l,lastTargetOffset:o,stableFrames:0},this._scrollToOffset(o,{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 o=r.length-1;for(;o>=0&&i.some(a=>a===null);){const a=r[o];i[a.lane]===null&&(i[a.lane]=a.end),o--}s=Math.max(...i.filter(a=>a!==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,o=s!==this.scrollState.lastTargetOffset;if(!o&&I$(s,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=i){this.scrollState=null;return}}else this.scrollState.stableFrames=0,o&&(this.scrollState.lastTargetOffset=s,this.scrollState.behavior="auto",this._scrollToOffset(s,{adjustments:void 0,behavior:"auto"}));this.scheduleScrollReconcile()}}const Oy=(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 U$({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 o=Oy(0,s,i,n),a=o;if(r===1)for(;a<s&&e[a].end<n+t;)a++;else if(r>1){const l=Array(r).fill(0);for(;a<s&&l.some(d=>d<n+t);){const d=e[a];l[d.lane]=d.end,a++}const u=Array(r).fill(n+t);for(;o>=0&&u.some(d=>d>=n);){const d=e[o];u[d.lane]=d.start,o--}o=Math.max(0,o-o%r),a=Math.min(s,a+(r-1-a%r))}return{startIndex:o,endIndex:a}}const Wd=typeof document<"u"?y.useLayoutEffect:y.useEffect;function B$({useFlushSync:e=!0,...t}){const n=y.useReducer(()=>({}),{})[1],r={...t,onChange:(i,o)=>{var a;e&&o?Mc.flushSync(n):n(),(a=t.onChange)==null||a.call(t,i,o)}},[s]=y.useState(()=>new L$(r));return s.setOptions(r),Wd(()=>s._didMount(),[]),Wd(()=>s._willUpdate()),s}function F$(e){return B$({observeElementRect:D$,observeElementOffset:P$,scrollToFn:M$,...e})}function Lc({items:e,estimateSize:t,renderItem:n,overscan:r=5,className:s,height:i="100%",getItemKey:o}){const a=y.useRef(null),l=typeof t=="function"?t:()=>t,u=F$({count:e.length,getScrollElement:()=>a.current,estimateSize:l,overscan:r});return c.jsx("div",{ref:a,className:s,"data-pyric-ui":"virtual-list",style:{height:i,overflowY:"auto",contain:"strict"},children:c.jsx("div",{"data-pyric-virtual-inner":!0,style:{height:`${u.getTotalSize()}px`,width:"100%",position:"relative"},children:u.getVirtualItems().map(d=>{const h=e[d.index],f=o?o(h,d.index):d.key;return c.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(h,d.index)},f)})})})}function zd(e){return e.email??e.phoneNumber??(e.isAnonymous?"anonymous":e.uid)}function q$(e){return e.isAnonymous&&e.providerUserInfo.length===0?c.jsx("span",{"data-pyric-provider-id":"anonymous",children:mi("anonymous")}):e.providerUserInfo.map(t=>c.jsx("span",{"data-pyric-provider-id":t.providerId,children:mi(t.providerId)},t.providerId))}function Hd(e){if(!e)return"—";const t=new Date(e);return Number.isNaN(t.getTime())?"—":t.toLocaleDateString()}function $y({users:e,isLoading:t,error:n,filter:r,onSelect:s,renderIdentifier:i,renderProviders:o,renderSelection:a,renderSelectionHeader:l,renderActions:u,renderActionsHeader:d,formatCreatedAt:h=Hd,formatLastLoginAt:f=Hd,emptyState:p,noResultsState:m,className:g,virtualizeThreshold:b=100,rowHeight:w=44,virtualizedHeight:x="60vh"}){if(n)return c.jsx("div",{className:g,"data-pyric-ui":"auth-user-list","data-pyric-error":"",role:"alert",children:n.message});if(t&&e.length===0)return c.jsx("div",{className:g,"data-pyric-ui":"auth-user-list","data-pyric-loading":""});if(e.length===0){const S=!!r?.trim();return c.jsx("div",{className:g,"data-pyric-ui":"auth-user-list","data-pyric-empty":"","data-pyric-no-results":S?"":void 0,children:S?m??"No results":p??"No users for this project yet"})}const v=e.length>b,_=S=>c.jsxs("div",{role:"row","data-pyric-user-entry":!0,"data-pyric-user-uid":S.uid,"data-pyric-user-disabled":S.disabled?"":void 0,children:[a?c.jsx("span",{role:"cell","data-pyric-user-cell":"selection",children:a(S)}):null,c.jsx("span",{role:"cell","data-pyric-user-cell":"identifier",children:s?c.jsx("button",{type:"button","data-pyric-user-select":!0,onClick:()=>s(S),children:i?i(S):zd(S)}):(i??zd)(S)}),c.jsx("span",{role:"cell","data-pyric-user-cell":"providers",children:(o??q$)(S)}),c.jsx("span",{role:"cell","data-pyric-user-cell":"created",children:h(S.createdAt)}),c.jsx("span",{role:"cell","data-pyric-user-cell":"signed-in",children:f(S.lastLoginAt)}),c.jsx("span",{role:"cell","data-pyric-user-cell":"uid",children:S.uid}),u?c.jsx("span",{role:"cell","data-pyric-user-cell":"actions",children:u(S)}):null]},S.uid);return c.jsxs("div",{className:g,role:"table","aria-label":"Authentication users","data-pyric-ui":"auth-user-list","data-pyric-virtualized":v?"":void 0,"data-pyric-selection":a?"":void 0,"data-pyric-actions":u?"":void 0,children:[c.jsxs("div",{role:"row","data-pyric-user-header":!0,children:[a?c.jsx("span",{role:"columnheader","data-pyric-user-cell":"selection","aria-label":"Selection",children:l}):null,c.jsx("span",{role:"columnheader","data-pyric-user-cell":"identifier",children:"Identifier"}),c.jsx("span",{role:"columnheader","data-pyric-user-cell":"providers",children:"Provider"}),c.jsx("span",{role:"columnheader","data-pyric-user-cell":"created",children:"Created"}),c.jsx("span",{role:"columnheader","data-pyric-user-cell":"signed-in",children:"Signed In"}),c.jsx("span",{role:"columnheader","data-pyric-user-cell":"uid",children:"User UID"}),u?c.jsx("span",{role:"columnheader","data-pyric-user-cell":"actions","aria-label":"Actions",children:d}):null]}),v?c.jsx(Lc,{items:e,estimateSize:w,height:x,getItemKey:S=>S.uid,renderItem:_}):c.jsx("div",{role:"rowgroup","data-pyric-user-rows":!0,children:e.map(_)})]})}function V$({value:e,onChange:t,error:n,hint:r,placeholder:s='{"role":"admin"}',className:i}){return c.jsxs("div",{className:i,"data-pyric-ui":"claims-field",children:[c.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:o=>t(o.target.value)}),n!=null&&c.jsx("p",{role:"alert","data-pyric-claims-error":!0,children:n}),r!=null&&c.jsx("p",{"data-pyric-claims-hint":!0,children:r})]})}function W$({selected:e,onChange:t}){return c.jsx("div",{"data-pyric-provider-checklist":!0,children:Ih.map(n=>c.jsxs("label",{"data-pyric-provider-option":n,children:[c.jsx("input",{type:"checkbox",checked:e.includes(n),onChange:r=>t(r.target.checked?[...e,n]:e.filter(s=>s!==n))}),c.jsx("span",{"data-pyric-provider-option-label":!0,children:mi(n)}),c.jsx("span",{"data-pyric-provider-option-id":!0,children:n})]},n))})}function Dy({initial:e,onSubmit:t,onCancel:n,submitLabel:r="Save",cancelLabel:s="Cancel",children:i,className:o,renderField:a}){const l=Ay({initial:e}),u=e?"edit":"create",d=l.isValid&&(u==="create"||l.isDirty),h=(m,g,b,w,x=null)=>({name:m,label:g,input:w,error:x,kind:b,defaultRender:()=>b==="checkbox"?c.jsxs("label",{"data-pyric-field-label":m,children:[w,c.jsx("span",{"data-pyric-label-text":!0,children:g})]},m):b==="group"?c.jsxs("fieldset",{"data-pyric-field-label":m,children:[c.jsx("legend",{"data-pyric-label-text":!0,children:g}),w]},m):c.jsxs("label",{"data-pyric-field-label":m,children:[c.jsx("span",{"data-pyric-label-text":!0,children:g}),w,x!=null&&c.jsx("p",{role:"alert","data-pyric-field-error":m,children:x})]},m)}),f=[h("email","Email","text",c.jsx("input",{type:"email","data-pyric-field":"email",placeholder:"email@example.com",value:l.fields.email,onChange:m=>l.setField("email",m.target.value)}),l.errors.email??null),h("password","Password","text",c.jsx("input",{type:"password","data-pyric-field":"password",placeholder:u==="edit"?"New password (unchanged if empty)":"Password",value:l.fields.password,onChange:m=>l.setField("password",m.target.value)}),l.errors.password??null),h("display-name","Display name","text",c.jsx("input",{type:"text","data-pyric-field":"display-name",placeholder:"Display name (optional)",value:l.fields.displayName,onChange:m=>l.setField("displayName",m.target.value)})),h("phone-number","Phone number","text",c.jsx("input",{type:"tel","data-pyric-field":"phone-number",placeholder:"+1 555 555 0100",value:l.fields.phoneNumber,onChange:m=>l.setField("phoneNumber",m.target.value)})),h("photo-url","Photo URL","text",c.jsx("input",{type:"url","data-pyric-field":"photo-url",placeholder:"https://example.com/avatar.png",value:l.fields.photoUrl,onChange:m=>l.setField("photoUrl",m.target.value)})),...u==="create"?[h("providers","Sign-in providers","group",c.jsx(W$,{selected:l.fields.providerIds,onChange:m=>l.setField("providerIds",m)}))]:[],h("email-verified","Verified email","checkbox",c.jsx("input",{type:"checkbox","data-pyric-field":"email-verified",checked:l.fields.emailVerified,onChange:m=>l.setField("emailVerified",m.target.checked)})),h("disabled","Disabled (sign-in attempts are rejected)","checkbox",c.jsx("input",{type:"checkbox","data-pyric-field":"disabled",checked:l.fields.disabled,onChange:m=>l.setField("disabled",m.target.checked)}))],p=m=>{m.preventDefault(),d&&t(u==="edit"?{mode:u,uid:e.uid,request:l.toUpdateRequest()}:{mode:u,request:l.toCreateRequest()})};return c.jsxs("form",{className:o,"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:p,children:[f.map(m=>a?c.jsx(y.Fragment,{children:a(m)},m.name):m.defaultRender()),c.jsx(V$,{value:l.fields.claimsText,onChange:m=>l.setField("claimsText",m),error:l.errors.claims}),i,c.jsxs("footer",{"data-pyric-form-actions":!0,children:[n?c.jsx("button",{type:"button","data-pyric-cancel":!0,onClick:n,children:s}):null,c.jsx("button",{type:"submit","data-pyric-submit":!0,disabled:!d,children:r})]})]})}const Py=["a[href]","area[href]",'input:not([disabled]):not([type="hidden"])',"select:not([disabled])","textarea:not([disabled])","button:not([disabled])","iframe","object","embed",'[contenteditable="true"]','[tabindex]:not([tabindex^="-"])'].join(", ");function z$(e){return Array.from(e.querySelectorAll(Py)).filter(t=>{if(t.disabled||t.hasAttribute("disabled")||t.getAttribute("aria-hidden")==="true"||t.tabIndex<0)return!1;if(typeof window<"u"&&typeof window.getComputedStyle=="function")try{const n=window.getComputedStyle(t);if(n.display==="none"||n.visibility==="hidden")return!1}catch{}return!0})}function H$(e,t,n){const r=y.useRef(n);r.current=n,y.useEffect(()=>{if(!t)return;const s=i=>{if(i.key==="Escape"){i.stopPropagation(),r.current();return}if(i.key!=="Tab")return;const o=e.current;if(!o)return;const a=z$(o);if(a.length===0){i.preventDefault(),o.focus();return}const l=a[0],u=a[a.length-1],d=document.activeElement;let h=a.indexOf(d);if(h===-1&&d&&o.contains(d)){const f=d.closest?.(Py);f&&(h=a.indexOf(f))}if(i.preventDefault(),h===-1){i.shiftKey?u.focus():l.focus();return}i.shiftKey?h<=0?u.focus():a[h-1].focus():h>=a.length-1?l.focus():a[h+1].focus()};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[t,e])}function K$({open:e,onOpenChange:t,title:n,body:r,destructive:s,confirmLabel:i="Confirm",cancelLabel:o="Cancel",onConfirm:a,className:l}){const u=y.useRef(null),d=y.useRef(null),h=y.useRef(null);return H$(u,e,()=>t(!1)),y.useEffect(()=>{if(e)return h.current=document.activeElement,d.current?.focus(),()=>{h.current?.focus?.()}},[e]),!e||typeof document>"u"?null:Mc.createPortal(c.jsxs("div",{role:"presentation","data-pyric-ui":"confirm-portal",onClick:f=>{f.target===f.currentTarget&&t(!1)},children:[c.jsx("div",{"data-pyric-ui":"confirm-overlay","aria-hidden":"true"}),c.jsxs("div",{ref:u,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:[c.jsx("div",{id:"pyric-confirm-title","data-pyric-confirm-title":!0,children:n}),r?c.jsx("div",{id:"pyric-confirm-body","data-pyric-confirm-body":!0,children:r}):null,c.jsxs("div",{"data-pyric-confirm-actions":!0,children:[c.jsx("button",{type:"button","data-pyric-confirm-cancel":!0,onClick:()=>t(!1),children:o}),c.jsx("button",{ref:d,type:"button","data-pyric-confirm-confirm":!0,"data-pyric-destructive":s?"":void 0,onClick:a,children:i})]})]})]}),document.body)}const Ty=y.createContext(null);function Hn(){const e=y.useContext(Ty);if(!e)throw new Error("useConfirm: missing <ConfirmProvider> ancestor");return e}function Uc({children:e,dialogClassName:t}){const[n,r]=y.useState(null),s=y.useRef(!1),i=y.useCallback(u=>new Promise(d=>{s.current=!1,r({options:u,resolve:d})}),[]),o=y.useCallback(()=>{n&&(s.current||(s.current=!0,n.resolve(!0),r(null)))},[n]),a=y.useCallback(u=>{u||n&&(s.current||(s.current=!0,n.resolve(!1),r(null)))},[n]),l=y.useMemo(()=>i,[i]);return c.jsxs(Ty.Provider,{value:l,children:[e,n?c.jsx(K$,{open:!0,onOpenChange:a,title:n.options.title,body:n.options.body,destructive:n.options.destructive,confirmLabel:n.options.confirmLabel,cancelLabel:n.options.cancelLabel,onConfirm:o,className:t}):null]})}function G$(e){return e.email??e.phoneNumber??e.displayName??e.uid}function J$({user:e,onDelete:t,title:n="Delete user",body:r,confirmLabel:s="Delete",renderTrigger:i,className:o}){const a=Hn(),l=async()=>{await a({title:n,body:r??`This will permanently delete ${G$(e)}.`,destructive:!0,confirmLabel:s})&&t(e.uid)};return i?c.jsx(c.Fragment,{children:i({onClick:l})}):c.jsx("button",{type:"button",className:o,"data-pyric-ui":"delete-user","data-pyric-destructive":!0,onClick:l,children:"Delete user"})}function Y$(e,t=Date.now()){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 Q$(e){const t=e.toLowerCase();return t==="flutter"?c.jsx("span",{className:"studio-remote-client__badge studio-remote-client__badge--flutter",children:"Flutter"}):t==="swift"||t==="ios"?c.jsx("span",{className:"studio-remote-client__badge studio-remote-client__badge--swift",children:"iOS Swift"}):t==="kotlin"||t==="android"?c.jsx("span",{className:"studio-remote-client__badge studio-remote-client__badge--kotlin",children:"Android Kotlin"}):c.jsx("span",{className:"studio-remote-client__badge",children:e})}function X$(e){if(!e||e.mode==="app-session")return"App Session";if(e.mode==="admin")return"Admin Bypass";if(e.mode==="anon")return"Anonymous";if(e.mode==="as"){const t=e.token?" +claims":"",n=e.tenant?` @${e.tenant}`:"";return`User: ${e.uid}${t}${n}`}return"Unknown"}function Z$({auth:e,onSelectUser:t}){const{users:n,isLoading:r}=Mi(e);return c.jsxs("select",{className:"studio-remote-client__select",defaultValue:"",disabled:r||n.length===0,onChange:s=>{const i=n.find(o=>o.uid===s.target.value);i&&(t(i),s.target.value="")},children:[c.jsx("option",{value:"",disabled:!0,children:r?"Loading sandbox users…":n.length===0?"No sandbox users found":"Impersonate sandbox user…"}),n.map(s=>c.jsx("option",{value:s.uid,children:s.email?`${s.email} (${s.uid.slice(0,6)}…)`:s.uid},s.uid))]})}function eD({isOpen:e,onClose:t,consumers:n,onSetLens:r,triggerRef:s,auth:i}){const[o,a]=y.useState(""),[l,u]=y.useState(""),[d,h]=y.useState(""),[f,p]=y.useState(!1),[m,g]=y.useState("");if(y.useEffect(()=>{if(!e)return;const x=v=>{v.key==="Escape"&&(t(),s?.current?.focus())};return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[e,t,s]),!e)return null;const b=i,w=(x,v)=>{let _;if(l.trim())try{_=JSON.parse(l)}catch{alert("Invalid JSON for custom claims");return}const S=d.trim()||void 0;r(x,{mode:"as",uid:v,token:_,tenant:S})};return c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"studio-remote-clients__backdrop",onMouseDown:t}),c.jsxs("div",{id:"studio-remote-clients-panel",className:"studio-remote-clients__panel",role:"dialog","aria-label":"Remote Mobile Clients",children:[c.jsxs("div",{className:"studio-remote-clients__header",children:[c.jsx("h3",{className:"studio-remote-clients__title",children:"Remote Mobile Clients"}),c.jsxs("span",{className:"studio-remote-clients__count",children:[n.length," connected"]})]}),n.length===0?c.jsx("p",{className:"studio-remote-clients__empty",children:"No remote mobile clients connected over the bridge. Connect your Flutter, iOS, or Android app to control its identity remotely."}):c.jsx("ul",{className:"studio-remote-clients__list",children:n.map(x=>c.jsxs("li",{className:"studio-remote-clients__item",children:[c.jsxs("div",{className:"studio-remote-clients__item-top",children:[c.jsxs("div",{className:"studio-remote-clients__item-info",children:[Q$(x.platform),c.jsx("span",{className:"studio-remote-clients__device",children:x.deviceLabel||"Mobile Device"})]}),c.jsx("span",{className:"studio-remote-clients__freshness",children:Y$(x.lastSeen)})]}),c.jsxs("div",{className:"studio-remote-clients__session",children:["Session: ",c.jsxs("code",{children:[x.clientSessionId.slice(0,10),"…"]})]}),c.jsxs("div",{className:"studio-remote-clients__current-lens",children:[c.jsx("span",{className:"studio-remote-clients__lens-label",children:"Active Lens:"}),c.jsx("span",{className:"studio-remote-clients__lens-pill",children:X$(x.activeLens)})]}),c.jsxs("div",{className:"studio-remote-clients__actions",children:[c.jsxs("div",{className:"studio-remote-clients__btn-group",children:[c.jsx("button",{type:"button",className:`studio-remote-btn ${x.activeLens?.mode==="app-session"?"studio-remote-btn--active":""}`,onClick:()=>void r(x.clientSessionId,{mode:"app-session"}),children:"App Session"}),c.jsx("button",{type:"button",className:`studio-remote-btn ${x.activeLens?.mode==="admin"?"studio-remote-btn--active":""}`,onClick:()=>void r(x.clientSessionId,{mode:"admin"}),children:"Admin"}),c.jsx("button",{type:"button",className:`studio-remote-btn ${x.activeLens?.mode==="anon"?"studio-remote-btn--active":""}`,onClick:()=>void r(x.clientSessionId,{mode:"anon"}),children:"Anon"})]}),c.jsx("div",{className:"studio-remote-clients__switcher",children:b?c.jsx(Z$,{auth:b,onSelectUser:v=>w(x.clientSessionId,v.uid)}):c.jsxs("div",{className:"studio-remote-clients__manual-row",children:[c.jsx("input",{type:"text",placeholder:"Impersonate UID…",className:"studio-remote-client__input",value:o===x.clientSessionId?m:"",onChange:v=>{a(x.clientSessionId),g(v.target.value)}}),c.jsx("button",{type:"button",className:"studio-remote-btn studio-remote-btn--primary",disabled:!m.trim(),onClick:()=>{w(x.clientSessionId,m.trim()),g("")},children:"Switch"})]})}),c.jsxs("div",{className:"studio-remote-clients__advanced",children:[c.jsx("button",{type:"button",className:"studio-remote-clients__advanced-toggle",onClick:()=>p(!f),children:f?"▲ Hide Claims & Tenant":"▼ Custom Claims / Tenant"}),f?c.jsxs("div",{className:"studio-remote-clients__advanced-inputs",children:[c.jsx("input",{type:"text",placeholder:"Custom Claims JSON, e.g. { role: 'admin' }",className:"studio-remote-client__input",value:l,onChange:v=>u(v.target.value)}),c.jsx("input",{type:"text",placeholder:"Tenant ID (optional)",className:"studio-remote-client__input",value:d,onChange:v=>h(v.target.value)})]}):null]})]})]},x.clientSessionId))})]})]})}const tD={servedEpoch:null,runningEpoch:null,updateAvailable:!1,updating:!1,error:null},nD=()=>()=>{},Kd=()=>tD;function rD(){const e=lt(),t=cs(),n=Jt(),[r,s]=y.useState(!1),i=n.some(he=>he.kind==="runtime_error"&&he.error.code==="persistence-unhealthy"),o=t.status==="ready"&&t.payload.persistenceUnhealthy===!0;y.useEffect(()=>{(i||o)&&s(!0)},[i,o]);const a=i$(),l=u$(),[u,d]=y.useState(!1),h=y.useRef(null),{consumers:f,setLens:p}=h$(),[m,g]=y.useState(!1),b=y.useRef(null),w=Rt(),v=w.status==="ready"?w.handles?.auth:void 0,S=e.status==="ready"?e.env.live?.runtime:void 0,k=y.useSyncExternalStore(S?.subscribe??nD,S?.getSnapshot??Kd,S?.getSnapshot??Kd),O=t.status==="ready"&&e.status==="ready"&&!e.env.live,D=e.status==="error",R="mode"in k&&k.mode==="hosted",j=R?k.error:"worker update failed",E=k.error!==null;let $=null;O&&($="worker unreachable"),D&&($="backend error"),E&&($=j),r&&($="persistence failed — writes blocked");let C="Served, but the shared sandbox worker is not reachable; data views may be stale. Open Settings diagnostics.";D&&(C=e.error.message),E&&(C=k.error??C),r&&(C="Reads may include unsaved changes. Repair the hosted store and restart the host.");const I=!E,A=R?I:a==="available",P=!R||I;y.useEffect(()=>{if(!u)return;const he=Ge=>{Ge.key==="Escape"&&(d(!1),h.current?.focus())};return document.addEventListener("keydown",he),()=>document.removeEventListener("keydown",he)},[u]);const T=k.updateAvailable,U=k.updating?"updating worker…":"update worker",V=$!==null,F=P&&l!==null&&l.count>0,we=l?.prominent===!0?"studio-chip studio-chip--live studio-presence__trigger":"studio-chip studio-presence__trigger",M=l!==null&&l.otherCount>0,ge=l?.otherCount===1?"":"s";let ce=`${l?.chipLabel}. Expand for details.`;M&&(ce=`${l.chipLabel}. ${l.otherCount} other page${ge} can keep the worker alive.`),R&&(ce=`${l?.chipLabel}. These pages share the Node host.`);const Z=R?"Data is shared by every client connected to this host.":l?.boundaryCopy;let fe=l?.count===1?"This page is the only connection to the shared sandbox worker.":`${l?.count} pages share this sandbox worker. Closing this page alone will not restart it.`;R&&(fe="These pages share the Node-hosted sandbox. Closing a page does not stop the host.");const et=P&&f.length>0,wt=f.length===1,ut=wt?"":"s",ie=wt?"1 remote client":`${f.length} remote clients`;return c.jsxs("div",{className:"studio__status","aria-label":"Studio status",children:[T&&c.jsxs("button",{type:"button",className:"studio-chip studio-chip--warn",disabled:k.updating,title:"The Studio backend is running older code. Update every connected page to the served worker version.",onClick:()=>void S?.update().catch(()=>{}),children:[c.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),U]}),V&&c.jsxs("a",{className:"studio-chip studio-chip--warn",href:Ct({tab:"settings"}),title:C,onClick:he=>{he.preventDefault(),Ae({tab:"settings"})},children:[c.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),$]}),F&&c.jsxs("span",{className:"studio-presence",children:[c.jsxs("button",{ref:h,type:"button",className:we,"aria-haspopup":"dialog","aria-expanded":u,"aria-controls":"studio-presence-panel",title:ce,onClick:()=>d(he=>!he),children:[c.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),l.chipLabel]}),u&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"studio-presence__backdrop",onMouseDown:()=>d(!1)}),c.jsxs("div",{id:"studio-presence-panel",className:"studio-presence__panel",role:"dialog","aria-label":"Connected pages",children:[c.jsx("p",{className:"studio-presence__lead",children:fe}),c.jsx("ul",{className:"studio-presence__list",children:l.clients.map(he=>c.jsxs("li",{className:"studio-presence__item",children:[c.jsxs("div",{className:"studio-presence__item-head",children:[c.jsx("span",{className:"studio-presence__kind",children:he.kindLabel}),he.isThisPage?c.jsx("span",{className:"studio-presence__this",children:"This page"}):null]}),c.jsx("div",{className:"studio-presence__route",title:he.route,children:he.route}),c.jsxs("div",{className:"studio-presence__meta",children:[he.visibilityLabel," · ",he.freshnessLabel]})]},he.clientId))}),c.jsx("p",{className:"studio-presence__boundary",children:Z})]})]})]}),et&&c.jsxs("span",{className:"studio-remote-clients",children:[c.jsxs("button",{ref:b,type:"button",className:"studio-chip studio-chip--live studio-remote-clients__trigger","aria-haspopup":"dialog","aria-expanded":m,"aria-controls":"studio-remote-clients-panel",title:`${f.length} remote client${ut} connected over the bridge. Click to control identity.`,onClick:()=>g(he=>!he),children:[c.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),ie]}),c.jsx(eD,{isOpen:m,onClose:()=>g(!1),consumers:f,onSetLens:p,triggerRef:b,auth:v})]}),A&&c.jsxs("span",{className:"studio-chip studio-chip--live",title:"MCP bridge available — a sandbox peer is connected; external agents can reach this sandbox.",children:[c.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),"MCP bridge"]})]})}function sD(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 Gd(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 iD({events:e,groupBatches:t=!0,groupListenerRuns:n=!0}){return y.useMemo(()=>{const r=[];let s=0;for(;s<e.length;){const i=e[s];if(t&&i.groupId){let o=s+1;for(;o<e.length&&e[o].groupId===i.groupId;)o++;const a=e.slice(s,o),l=i.origin==="transaction"?"transaction":"batch";r.push(Gd(l,i.groupId,a)),s=o;continue}if(n&&i.origin==="listener"){let o=s+1;for(;o<e.length&&e[o].origin==="listener"&&!e[o].groupId&&sD(e[o],i);)o++;const a=e.slice(s,o);if(a.length>1){const l=i.triggeredBy?`${i.triggeredBy.method}:${i.triggeredBy.path}`:"unknown";r.push(Gd("listener-run",`listener-run:${l}:${s}`,a))}else r.push({type:"single",event:i});s=o;continue}r.push({type:"single",event:i}),s++}return{items:r}},[e,t,n])}const oD={buckets:[],total:0,denies:0,maxCount:0,outOfWindow:0};function aD({events:e,window:t,bucketCount:n=30}){return y.useMemo(()=>cD(e,t,n),[e,t.start,t.end,n])}function cD(e,t,n=30){const r=t.end-t.start;if(n<=0||r<=0)return oD;const s=r/n,i=new Array(n).fill(0),o=new Array(n).fill(0);let a=0,l=0,u=0;for(const f of e){const p=f.at;if(p<t.start||p>=t.end){u++;continue}let m=Math.floor((p-t.start)/s);m>=n&&(m=n-1),i[m]++,a++,f.result==="deny"&&(o[m]++,l++)}let d=0;for(const f of i)f>d&&(d=f);return{buckets:i.map((f,p)=>{const m=o[p];return{index:p,start:t.start+p*s,end:t.start+(p+1)*s,count:f,denies:m,allows:f-m,heightRatio:d===0?0:f/d,denyHeightRatio:d===0?0:m/d}}),total:a,denies:l,maxCount:d,outOfWindow:u}}const lD=new Set(["get","list"]),uD=new Set(["create","update","set"]),dD=new Set(["delete","remove"]),fD=[{key:"reads",label:"Read ops"},{key:"writes",label:"Writes"},{key:"deletes",label:"Deletes"}],hD=[{key:"allows",label:"Allows"},{key:"denies",label:"Denies"},{key:"errors",label:"Errors"}];function Li(e){return e.origin==="admin"}function pD(e,t=Li){return e.result==="allow"||t(e)?lD.has(e.method)?"reads":uD.has(e.method)?"writes":dD.has(e.method)?"deletes":null:null}function mD(e,t=Li){return t(e)?null:e.result==="allow"?"allows":e.result==="deny"?"denies":e.result==="error"?"errors":null}const yD=e=>({points:[],series:e.map(t=>({key:t.key,label:t.label,values:[],total:0})),maxValue:0});function My(e,t,n,r,s){const i=t.end-t.start;if(n<=0||i<=0)return yD(r);const o=i/n,a=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 p=f.at;if(p<t.start||p>=t.end)continue;const m=s(f);if(m==null)continue;let g=Math.floor((p-t.start)/o);g>=n&&(g=n-1);const b=a.get(m);b[g]++,l.set(m,(l.get(m)??0)+1)}let u=0;for(const f of a.values())for(const p of f)p>u&&(u=p);const d=new Array(n);for(let f=0;f<n;f++)d[f]={index:f,start:t.start+f*o,end:t.start+(f+1)*o};const h=r.map(f=>({key:f.key,label:f.label,values:a.get(f.key),total:l.get(f.key)??0}));return{points:d,series:h,maxValue:u}}function gD(e,t,n=24,r=Li){return My(e,t,n,fD,s=>pD(s,r))}function bD(e,t,n=24,r=Li){return My(e,t,n,hD,s=>mD(s,r))}function wD({events:e,window:t,bucketCount:n=24,isAdmin:r}){return y.useMemo(()=>gD(e,t,n,r),[e,t.start,t.end,n,r])}function vD({events:e,window:t,bucketCount:n=24,isAdmin:r}){return y.useMemo(()=>bD(e,t,n,r),[e,t.start,t.end,n,r])}function Pa({children:e,kind:t,className:n,ariaLabel:r}){return c.jsx("span",{"data-pyric-badge":"","data-pyric-badge-kind":t,className:n,"aria-label":r,children:r?c.jsx("span",{"aria-hidden":"true",children:e}):e})}function Vr(e){const t=new Date(e),n=r=>String(r).padStart(2,"0");return`${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`}function Ly({event:e,selected:t,onSelect:n,renderClassification:r,formatTime:s=Vr,className:i}){return c.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:[c.jsx("span",{"data-pyric-traffic-time":"",children:s(e.at)}),c.jsx("span",{"data-pyric-traffic-service":e.service??"",children:e.service??""}),c.jsx(Pa,{kind:e.method,children:e.method}),c.jsx("span",{"data-pyric-traffic-path":"",children:e.path||"/"}),r?r(e):null]})}const xD={batch:"batch write",transaction:"transaction","listener-run":"listener re-evals"};function _D({group:e,defaultExpanded:t=!1,onSelect:n,selectedId:r,renderClassification:s,formatTime:i,className:o}){const[a,l]=y.useState(t);return c.jsxs("div",{className:o,"data-pyric-traffic-group":"","data-pyric-group-kind":e.kind,"data-pyric-expanded":a?"":void 0,children:[c.jsxs("button",{type:"button",onClick:()=>l(u=>!u),"data-pyric-traffic-group-header":"","data-pyric-group-kind":e.kind,"aria-expanded":a,children:[c.jsx("span",{"data-pyric-group-kind-label":"",children:xD[e.kind]}),c.jsxs("span",{"data-pyric-group-count":"",children:["×",e.count]}),e.denies>0?c.jsxs("span",{"data-pyric-group-denies":"",children:[e.denies," denied"]}):null]}),a?c.jsx("ul",{"data-pyric-traffic-group-members":"",children:e.events.map(u=>c.jsx("li",{"data-pyric-traffic-entry":"","data-pyric-traffic-id":u.id,children:c.jsx(Ly,{event:u,selected:u.id===r,onSelect:n,renderClassification:s,formatTime:i})},u.id))}):null]})}function SD(e){return e<0?0:e>1?1:e}function Ro(e,t){const n=t.end-t.start;return n<=0?0:SD((e-t.start)/n)}function Uy({events:e,buckets:t,window:n,bucketCount:r=30,brush:s,onBrush:i,renderBucketSummary:o,liveAt:a,header:l,axis:u,emptyState:d,className:h}){const f=y.useId(),[p,m]=y.useState(null),[g,b]=y.useState(null),w=aD({events:e??[],window:n,bucketCount:r}),x=t??w,{buckets:v,total:_}=x,S=p??g,k=S===null?null:v.find(E=>E.index===S)??null,N=k!==null&&s?.start===k.start&&s.end===k.end;if(v.length===0)return c.jsx("div",{className:h,"data-pyric-ui":"traffic-timeline","data-pyric-empty":"",children:d});const O=_===0,D=a===void 0?n.end:a,R=D==null?null:Ro(D,n),j=typeof u=="function"?u(n):u;return c.jsxs("div",{className:h,"data-pyric-ui":"traffic-timeline","data-pyric-empty":O?"":void 0,children:[l!==void 0&&c.jsx("div",{"data-pyric-timeline-header":"",children:l}),c.jsxs("div",{"data-pyric-timeline-chart":"",children:[c.jsx("div",{"data-pyric-timeline-bars":"",role:i?"group":"img","aria-label":"request volume over time",children:v.map(E=>c.jsx(kD,{bucket:E,window:n,onBrush:i,onHover:o?m:void 0,onFocus:o?b:void 0,summaryId:o&&!N&&k?.index===E.index?f:void 0,selected:s?.start===E.start&&s.end===E.end},E.index))}),k&&o&&!N?c.jsx("div",{id:f,role:"tooltip","data-pyric-bucket-summary":"",style:{"--pyric-bucket-summary-x":(k.index+.5)/Math.max(v.length,1)},children:o(k)}):null,s&&c.jsx("div",{"data-pyric-brush":"","aria-hidden":"true",style:{"--pyric-brush-left":Ro(s.start,n),"--pyric-brush-right":1-Ro(s.end,n)}}),R!=null&&c.jsx("div",{"data-pyric-live":"","aria-hidden":"true",style:{"--pyric-live-x":R}})]}),j!=null&&c.jsx("div",{"data-pyric-timeline-axis":"",children:j})]})}function kD({bucket:e,window:t,onBrush:n,onHover:r,onFocus:s,summaryId:i,selected:o}){const a=n!==void 0,l=`${e.count} ${e.count===1?"request":"requests"}`,u=`${e.denies} denied`;return c.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":o?"":void 0,disabled:!a,"aria-label":`${l}, ${u}`,"aria-describedby":i,"aria-pressed":a?o: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:a?()=>n?.({start:e.start,end:e.end}):void 0,style:{"--pyric-bucket-h":e.heightRatio,"--pyric-bucket-deny-h":e.denyHeightRatio},children:[c.jsx("span",{"data-pyric-bucket-allow":"","aria-hidden":"true"}),c.jsx("span",{"data-pyric-bucket-deny":"","aria-hidden":"true"})]})}const jD=e=>String(e);function Bc({series:e,visible:t,onToggle:n,formatValue:r=jD,className:s}){const i=t!==void 0&&n!==void 0;return c.jsx("div",{className:s,"data-pyric-ui":"traffic-metric-cards",role:i?"group":void 0,children:e.map((o,a)=>{const l=t?t.has(o.key):!0,u=c.jsxs(c.Fragment,{children:[c.jsx("span",{"data-pyric-metric-swatch":"","aria-hidden":"true"}),c.jsx("span",{"data-pyric-metric-label":"",children:o.label}),c.jsx("span",{"data-pyric-metric-value":"",children:r(o.total)})]});return i?c.jsxs("label",{"data-pyric-metric-card":"","data-pyric-metric-key":o.key,"data-pyric-series-index":a,"data-pyric-metric-hidden":l?void 0:"",children:[c.jsx("input",{type:"checkbox",checked:l,onChange:()=>n(o.key),"data-pyric-metric-checkbox":""}),u]},o.key):c.jsx("span",{"data-pyric-metric-card":"","data-pyric-metric-key":o.key,"data-pyric-series-index":a,children:u},o.key)})})}const ED=e=>String(e),CD=e=>new Date(e).toLocaleTimeString();function By({points:e,series:t,visible:n,omitZeroSeries:r=!1,formatValue:s=ED,formatTime:i=CD,emptyState:o,className:a}){const[l,u]=y.useState(null);if(e.length===0)return c.jsx("div",{className:a,"data-pyric-ui":"traffic-line-chart","data-pyric-empty":"",children:o});const d=t.filter(w=>(!n||n.has(w.key))&&(!r||w.total>0));let h=0;for(const w of d)for(const x of w.values)x>h&&(h=x);const f=h===0?1:h,p=e.length,m=w=>p===1?50:w/(p-1)*100,g=w=>100-w/f*100,b=l!=null?e[l]:null;return c.jsx("div",{className:a,"data-pyric-ui":"traffic-line-chart",children:c.jsxs("div",{"data-pyric-chart-svg":"",children:[c.jsx("svg",{viewBox:"0 0 100 100",preserveAspectRatio:"none",role:"img","aria-label":"metrics over time",children:t.map(w=>{const x=t.indexOf(w);if(!((!n||n.has(w.key))&&(!r||w.total>0)))return null;const _=w.values.map((S,k)=>`${k===0?"M":"L"}${m(k)},${g(S)}`).join(" ");return c.jsx("path",{"data-pyric-chart-line":"","data-pyric-series-key":w.key,"data-pyric-series-index":x,d:_,fill:"none",vectorEffect:"non-scaling-stroke"},w.key)})}),c.jsx("div",{"data-pyric-chart-hits":"",children:e.map((w,x)=>c.jsx("button",{type:"button","data-pyric-chart-hit":"","data-pyric-point-index":x,onMouseEnter:()=>u(x),onFocus:()=>u(x),onMouseLeave:()=>u(v=>v===x?null:v),onBlur:()=>u(v=>v===x?null:v),"aria-label":`${i(w.start)} to ${i(w.end)}`},w.index))}),b&&c.jsxs("div",{"data-pyric-chart-tooltip":"",style:{"--pyric-hover-x":m(b.index)},children:[c.jsxs("div",{"data-pyric-tooltip-time":"",children:[i(b.start)," – ",i(b.end)]}),d.map(w=>c.jsxs("div",{"data-pyric-tooltip-row":"","data-pyric-series-key":w.key,"data-pyric-series-index":t.indexOf(w),children:[c.jsx("span",{"data-pyric-tooltip-label":"",children:w.label}),c.jsx("span",{"data-pyric-tooltip-value":"",children:s(w.values[b.index])})]},w.key))]})]})})}function Fy(e={}){const[t]=y.useState(()=>(e.captureOwnerStack,void 0)),[n,r]=y.useState(void 0),s=y.useCallback(o=>{o!==null&&r(o)},[]);return{owner:y.useMemo(()=>{if(t!==void 0)return n===void 0?t:{...t,element:n}},[t,n]),ref:s}}function ND(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 RD={addDoc:hh,collection:hr,deleteDoc:qo,doc:st,getDoc:Dp,getDocs:ci,limit:ui,onSnapshot:DE,query:li,setDoc:zs,startAfter:$E},qy=y.createContext(RD);function Fc(){return y.useContext(qy)}function ID({value:e,children:t}){return y.createElement(qy.Provider,{value:e},t)}function AD(e){const{onSnapshot:t}=Fc(),{owner:n}=Fy(),[r,s]=y.useState(()=>({data:void 0,error:void 0,isLoading:e!=null}));return y.useEffect(()=>{if(!e){s({data:void 0,error:void 0,isLoading:!1});return}return s(o=>({data:o.data,error:void 0,isLoading:!0})),t(e,{owner:n},o=>s({data:o,error:void 0,isLoading:!1}),o=>s({data:void 0,error:ND(o),isLoading:!1}))},[t,n,e]),r}function Ui(e){return e==null?"null":typeof e=="string"?"string":typeof e=="number"?"number":typeof e=="boolean"?"boolean":typeof e=="object"&&yn(e)!==null?"vector":Array.isArray(e)?"array":e instanceof qt?"timestamp":e instanceof $n?"geopoint":e instanceof sn?"bytes":typeof e=="object"&&Vy(e)?"timestamp":typeof e=="object"&&zy(e)?"geopoint":typeof e=="object"&&Wy(e)?"bytes":typeof e=="object"&&OD(e)?"reference":typeof e=="object"?"map":"null"}function Vy(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 Wy(e){const t=e,n=Object.keys(t);return n.length===1?t.bytes instanceof Uint8Array:n.length===2&&t.type==="firestore/bytes/1.0"&&typeof t.bytes=="string"}function qc(e){if(e instanceof sn)return e;const t=e;return typeof t.bytes=="string"?sn.fromBase64String(t.bytes):sn.fromUint8Array(t.bytes)}function zy(e){const t=e;return Object.keys(t).length===2&&typeof t.latitude=="number"&&typeof t.longitude=="number"}function OD(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 yn(e){if(e===null||typeof e!="object")return null;const t=e;if(t.typeName==="vector"&&Cs(t.value)||t.__type__==="__vector__"&&Cs(t.value))return Ns(t.value);if(Cs(t._values))return Ns(t._values);if(typeof t.toArray=="function")try{const n=t.toArray();if(Cs(n))return Ns(n)}catch{}return null}function Cs(e){return Array.isArray(e)&&e.every(t=>typeof t=="number")}function Ns(e){const t=e.slice();return{values:t,dimension:t.length}}const Jd=4;function Hy(e){const t=e.values.slice(0,Jd).join(", "),n=e.values.length>Jd?", …":"";return`vector · ${e.dimension} [${t}${n}]`}function yi(e){const t=yn(e);if(t)return Hy(t);if(Array.isArray(e))return e.map(yi);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]=yi(i);return r}}return e}function Ky(){return crypto.randomUUID()}function $D(e){const t=Ky(),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))Ta(n,t,r,s);return n}function Ta(e,t,n,r){const s=Ui(r),i=Ky(),o={id:i,parentId:t,key:n,type:s,value:DD(s)?void 0:r};if(e.nodes[i]=o,e.childIds[i]=[],e.childIds[t].push(i),s==="map"&&r&&typeof r=="object")for(const[a,l]of Object.entries(r))Ta(e,i,a,l);else if(s==="array"&&Array.isArray(r))for(const a of r)Ta(e,i,null,a);return i}function DD(e){return e==="map"||e==="array"}function Gy(e){const t=e.nodes[e.rootId];if(!t||t.type!=="map")throw new Error("treeToData: tree root must be a map node");return Ma(e,e.rootId)}function Ma(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]=Ma(e,s))}return r}case"array":{const r=[];for(const s of e.childIds[t]??[])r.push(Ma(e,s));return r}default:return n.value}}function La(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 Jy(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 Yy(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 qt?void 0:"Expected a Timestamp";case"geopoint":return t instanceof $n?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 sn?void 0:"Expected a Bytes value";case"vector":return yn(t)!==null?void 0:"Expected a vector value";case"map":case"array":return}}function Qy(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=Yy(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]??[],o=new Map;for(const a of i){const l=t[a];if(!l)continue;const u=l.key??"";u||(l.error||n++,t[a].error=t[a].error??"Field name is required");const d=o.get(u)??[];d.push(a),o.set(u,d)}for(const[a,l]of o)if(a&&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 Vc(e){switch(e){case"string":return"";case"number":return 0;case"boolean":return!1;case"null":return null;case"timestamp":return qt.now();case"geopoint":return new $n(0,0);case"reference":return{path:"",id:"",firestore:{}};case"bytes":return sn.fromUint8Array(new Uint8Array);case"vector":return{__type__:"__vector__",value:[]};case"map":case"array":return}}function Ua(e){if(e===null||typeof e!="object"||yn(e)!==null)return e;if(Vy(e)){const n=e;return new qt(n.seconds??n._seconds??0,n.nanoseconds??n._nanoseconds??0)}if(zy(e)){const n=e;return new $n(n.latitude,n.longitude)}if(Wy(e))return qc(e);if(Array.isArray(e))return e.map(Ua);const t=Object.getPrototypeOf(e);if(t===Object.prototype||t===null){const n={};for(const[r,s]of Object.entries(e))n[r]=Ua(s);return n}return e}function Xy(e){const t=$D(Ua(e)),{tree:n,errorCount:r}=Qy(t);return{tree:n,initial:n,errorCount:r}}function PD(e,t){switch(t.type){case"setValue":return wn(e,n=>MD(n,t.nodeId,t.value));case"setType":return wn(e,n=>LD(n,t.nodeId,t.newType));case"setKey":return wn(e,n=>UD(n,t.nodeId,t.key));case"addMapEntry":return wn(e,n=>BD(n,t.parentId,t.key,t.childType));case"addArrayEntry":return wn(e,n=>FD(n,t.parentId,t.childType));case"remove":return wn(e,n=>qD(n,t.nodeId));case"reset":return{tree:e.initial,initial:e.initial,errorCount:TD(e.initial)};case"replaceData":return Xy(t.data);case"touch":{const n=e.tree.nodes[t.nodeId];if(!n||n.touched)return e;const r=La(e.tree);return r.nodes[t.nodeId]={...r.nodes[t.nodeId],touched:!0},{...e,tree:r}}case"touchAll":{const n=La(e.tree);for(const r of Object.keys(n.nodes))n.nodes[r]={...n.nodes[r],touched:!0};return{...e,tree:n}}}}function wn(e,t){const n=t(La(e.tree)),{tree:r,errorCount:s}=Qy(n);return{...e,tree:r,errorCount:s}}function TD(e){let t=0;for(const n of Object.values(e.nodes))n.error&&t++;return t}function MD(e,t,n){const r=e.nodes[t];return!r||r.type==="map"||r.type==="array"||(e.nodes[t]={...r,value:n}),e}function LD(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 o of i)for(const a of Jy(e,o))delete e.nodes[a],delete e.childIds[a];e.childIds[t]=[]}const s=n==="map"||n==="array"?void 0:Vc(n);return e.nodes[t]={...r,type:n,value:s},e}function UD(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 BD(e,t,n,r){const s=e.nodes[t];if(!s||s.type!=="map")return e;const i=crypto.randomUUID(),o=r==="map"||r==="array"?void 0:Vc(r);return e.nodes[i]={id:i,parentId:t,key:n,type:r,value:o},e.childIds[i]=[],e.childIds[t]=[...e.childIds[t]??[],i],e}function FD(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:Vc(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 qD(e,t){const n=e.nodes[t];if(!n||n.id===e.rootId)return e;const r=Jy(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 Zy(e={}){const t=e.initial??{},n=y.useRef(null);n.current==null&&(n.current=Xy(t));const[r,s]=y.useReducer(PD,n.current),i=y.useCallback((x,v)=>s({type:"setValue",nodeId:x,value:v}),[]),o=y.useCallback((x,v)=>s({type:"setType",nodeId:x,newType:v}),[]),a=y.useCallback((x,v)=>s({type:"setKey",nodeId:x,key:v}),[]),l=y.useCallback((x,v,_)=>s({type:"addMapEntry",parentId:x,key:v,childType:_}),[]),u=y.useCallback((x,v)=>s({type:"addArrayEntry",parentId:x,childType:v}),[]),d=y.useCallback(x=>s({type:"remove",nodeId:x}),[]),h=y.useCallback(()=>s({type:"reset"}),[]),f=y.useCallback(x=>s({type:"replaceData",data:x}),[]),p=y.useCallback(x=>s({type:"touch",nodeId:x}),[]),m=y.useCallback(()=>s({type:"touchAll"}),[]),g=y.useCallback(()=>Gy(r.tree),[r.tree]),b=r.tree!==r.initial,w=r.errorCount===0;return y.useMemo(()=>({...r,isDirty:b,isValid:w,dispatch:s,setValue:i,setType:o,setKey:a,addMapEntry:l,addArrayEntry:u,remove:d,reset:h,replaceData:f,touch:p,touchAll:m,toData:g}),[r,b,w,i,o,a,l,u,d,h,f,p,m,g])}function VD({collection:e,query:t,pageSize:n=50,mode:r="paged"}){const[s,i]=y.useState([]),[o,a]=y.useState(!0),[l,u]=y.useState(void 0),[d,h]=y.useState(!1),[f,p]=y.useState(0),[m,g]=y.useState(n),b=y.useRef(0),[w,x]=y.useState(0),{addDoc:v,deleteDoc:_,doc:S,getDoc:k,getDocs:N,limit:O,onSnapshot:D,query:R,setDoc:j,startAfter:E}=Fc(),{owner:$}=Fy();y.useEffect(()=>{g(n)},[e,r,n,t]),y.useEffect(()=>{let T=!1;r==="paged"&&i([]),h(!1),a(!0),u(void 0);const W=t??e,U=r==="live"?m:n,V=R(W,O(U)),F=we=>{T||(i([...we.docs]),h(we.docs.length===U),a(!1))},Se=we=>{T||(u(we instanceof Error?we:new Error(String(we))),a(!1))};if(r==="live"){const we=++b.current,M=D(V,{owner:$},ne=>{x(we),F(ne)},Se);return()=>{T=!0,M()}}return N(V).then(we=>{F(we)}).catch(Se),()=>{T=!0}},[e,N,O,r,D,$,n,t,R,m,f]);const C=y.useCallback(()=>{if(!d||o)return;if(r==="live"){a(!0),g(V=>V+n);return}const T=s[s.length-1];if(!T)return;a(!0);const U=R(t??e,E(T),O(n));N(U).then(V=>{i(F=>[...F,...V.docs]),h(V.docs.length===n),a(!1)}).catch(V=>{u(V instanceof Error?V:new Error(String(V))),a(!1)})},[e,s,N,d,o,O,r,n,t,R,E]),I=y.useCallback(async(T,W,U)=>{if(T==null){const F=await v(e,W);return r==="paged"&&p(Se=>Se+1),F}const V=S(e,T);if(U?.onExisting==="fail"){const F=await k(V);if(typeof F.exists=="function"?F.exists():!!F.exists){const we=new Error(`Document "${T}" already exists.`);throw we.code="already-exists",we}}return await j(V,W),r==="paged"&&p(F=>F+1),V},[v,e,S,k,r,j]),A=y.useCallback(async T=>{await _(T),r==="paged"&&p(W=>W+1)},[_,r]),P=y.useCallback(()=>p(T=>T+1),[]);return{documents:s,isLoading:o,error:l,subscriptionGeneration:w,hasMore:d,loadMore:C,createDocument:I,deleteDocument:A,refresh:P}}function WD({firestore:e,documentRef:t,listSubcollections:n}){const[r,s]=y.useState([]),[i,o]=y.useState(!1),[a,l]=y.useState(void 0),u=y.useRef(n);u.current=n;const d=t?.path;return y.useEffect(()=>{if(!t){s([]),o(!1),l(void 0);return}let h=!1;return o(!0),l(void 0),u.current(e,t).then(f=>{h||(s(f),o(!1))}).catch(f=>{h||(l(f instanceof Error?f:new Error(String(f))),o(!1))}),()=>{h=!0}},[e,d]),{subcollections:r,isLoading:i,error:a}}function Yd(e){return typeof e=="object"&&e!==null&&"isEqual"in e&&typeof e.isEqual=="function"}function Qd(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function gi(e,t){if(Object.is(e,t))return!0;if(Yd(e))return e.isEqual(t);if(Yd(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)=>gi(s,t[i]));if(!Qd(e)||!Qd(t))return!1;const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(s=>s in t&&gi(e[s],t[s]))}function zD({value:e,path:t}){return c.jsx("span",{"data-pyric-field-type":"string","data-pyric-field-path":t,children:e})}function HD({value:e,onChange:t,error:n,path:r}){return c.jsxs("label",{"data-pyric-field-type":"string","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[c.jsx("input",{type:"text",value:e,onChange:s=>t(s.target.value),"aria-invalid":n?"true":void 0}),n?c.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const KD={type:"string",Display:zD,Edit:HD};function GD({value:e,path:t}){return c.jsx("span",{"data-pyric-field-type":"number","data-pyric-field-path":t,children:String(e)})}function JD({value:e,onChange:t,error:n,path:r}){return c.jsxs("label",{"data-pyric-field-type":"number","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[c.jsx("input",{type:"number",value:Number.isFinite(e)?e:"",onChange:s=>{const i=s.target.value,o=i===""?Number.NaN:parseFloat(i);t(o)},"aria-invalid":n?"true":void 0}),n?c.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const YD={type:"number",Display:GD,Edit:JD};function QD({value:e,path:t}){return c.jsx("span",{"data-pyric-field-type":"boolean","data-pyric-field-path":t,"data-value":e?"true":"false",children:e?"true":"false"})}function XD({value:e,onChange:t,path:n}){return c.jsx("span",{"data-pyric-field-type":"boolean","data-pyric-field-path":n,"data-value":e?"true":"false",children:c.jsxs("select",{value:e?"true":"false",onChange:r=>t(r.target.value==="true"),"aria-label":"Boolean value","data-pyric-boolean-select":!0,children:[c.jsx("option",{value:"true",children:"true"}),c.jsx("option",{value:"false",children:"false"})]})})}const ZD={type:"boolean",Display:QD,Edit:XD};function eP({path:e}){return c.jsx("span",{"data-pyric-field-type":"null","data-pyric-field-path":e,children:"null"})}function tP({path:e}){return c.jsx("span",{"data-pyric-field-type":"null","data-pyric-field-path":e,children:"null"})}const nP={type:"null",Display:eP,Edit:tP};function Wc(e){if(e instanceof qt)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 rP(e){const t=e;return new qt(t.seconds??t._seconds??0,t.nanoseconds??t._nanoseconds??0)}function sP(e,t){const n=new Date(e);if(Number.isNaN(n.getTime()))return null;const r=Wc(t);return!Number.isNaN(r.getTime())&&r.getTime()===n.getTime()?t instanceof qt?t:rP(t):qt.fromDate(n)}function iP({value:e,path:t}){const n=Wc(e),r=Number.isNaN(n.getTime())?"":n.toISOString();return c.jsx("time",{dateTime:r,"data-pyric-field-type":"timestamp","data-pyric-field-path":t,children:r})}function oP({value:e,onChange:t,error:n,path:r}){const s=Wc(e),i=new Date(s.getTime()-s.getTimezoneOffset()*6e4),o=Number.isNaN(i.getTime())?"":i.toISOString().slice(0,23);return c.jsxs("label",{"data-pyric-field-type":"timestamp","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[c.jsx("input",{type:"datetime-local",step:"0.001",value:o,onChange:a=>{const l=a.target.value;if(!l)return;const u=sP(l,e);u&&t(u)},"aria-invalid":n?"true":void 0}),n?c.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const aP={type:"timestamp",Display:iP,Edit:oP};function cP({value:e,path:t}){return c.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 lP({value:e,onChange:t,error:n,path:r}){return c.jsxs("span",{"data-pyric-field-type":"geopoint","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[c.jsx("label",{children:c.jsx("input",{type:"number",step:"any",min:-90,max:90,value:e.latitude,onChange:s=>{const i=parseFloat(s.target.value);try{t(new $n(i,e.longitude))}catch{}},"aria-label":"Latitude"})}),c.jsx("label",{children:c.jsx("input",{type:"number",step:"any",min:-180,max:180,value:e.longitude,onChange:s=>{const i=parseFloat(s.target.value);try{t(new $n(e.latitude,i))}catch{}},"aria-label":"Longitude"})}),n?c.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const uP={type:"geopoint",Display:cP,Edit:lP},eg=y.createContext({});eg.Provider;function dP(){return y.useContext(eg)}function fP({value:e,path:t}){const{onReferenceClick:n}=dP();return n?c.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}):c.jsx("span",{"data-pyric-field-type":"reference","data-pyric-field-path":t,"data-target-path":e.path,children:e.path})}function hP({value:e,onChange:t,error:n,path:r}){return c.jsxs("label",{"data-pyric-field-type":"reference","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[c.jsx("input",{type:"text",value:e.path,placeholder:"users/alice",onChange:s=>{const i=s.target.value,o=i.split("/").filter(Boolean),a=o[o.length-1]??"",l=e.firestore??{};t({path:i,id:a,firestore:l,type:"document"})},"aria-invalid":n?"true":void 0}),n?c.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const pP={type:"reference",Display:fP,Edit:hP};function mP({value:e,path:t}){const n=qc(e),r=n.toBase64();return c.jsx("code",{"data-pyric-field-type":"bytes","data-pyric-field-path":t,"data-byte-length":String(n.toUint8Array().byteLength),children:r})}function yP({value:e,onChange:t,error:n,path:r}){return c.jsxs("label",{"data-pyric-field-type":"bytes","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[c.jsx("textarea",{value:qc(e).toBase64(),onChange:s=>{try{t(sn.fromBase64String(s.target.value))}catch{}},"aria-invalid":n?"true":void 0}),n?c.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const gP={type:"bytes",Display:mP,Edit:yP};function Ba({value:e,path:t,fieldEditors:n}){const r=Ui(e),s=n[r];if(!s)return null;const{Display:i}=s;return c.jsx(i,{value:e,path:t,fieldEditors:n})}function tg({label:e,value:t,path:n,fieldEditors:r,kind:s}){const i=Ui(t),o=i==="map"||i==="array",[a,l]=y.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 o?c.jsxs("li",{"data-pyric-tree-entry":!0,"data-pyric-tree-nested":!0,...d,children:[c.jsxs("button",{type:"button","data-pyric-tree-toggle":!0,"aria-expanded":a,onClick:()=>l(h=>!h),children:[c.jsx("span",{"data-pyric-tree-chevron":!0,"aria-hidden":"true",children:"›"}),c.jsx("span",{...u,children:e})]}),a?c.jsx(Ba,{value:t,path:n,fieldEditors:r}):null]}):c.jsxs("li",{"data-pyric-tree-entry":!0,...d,children:[c.jsx("span",{"data-pyric-tree-chevron":!0,"data-pyric-tree-chevron-empty":!0,"aria-hidden":"true"}),c.jsx("span",{...u,children:e}),c.jsx(Ba,{value:t,path:n,fieldEditors:r})]})}function bP({value:e,path:t,fieldEditors:n}){const r=Object.entries(e).sort(([s],[i])=>s.localeCompare(i));return c.jsx("ul",{"data-pyric-field-type":"map","data-pyric-tree":!0,"data-pyric-field-path":t,children:r.map(([s,i])=>c.jsx(tg,{label:s,value:i,path:t?`${t}.${s}`:s,fieldEditors:n??{},kind:"key"},s))})}const wP={type:"map",Display:bP};function vP({value:e,path:t,fieldEditors:n}){return c.jsx("ul",{"data-pyric-field-type":"array","data-pyric-tree":!0,"data-pyric-field-path":t,children:e.map((r,s)=>c.jsx(tg,{label:String(s),value:r,path:t?`${t}[${s}]`:`[${s}]`,fieldEditors:n??{},kind:"index"},s))})}const xP={type:"array",Display:vP},Xd=4;function _P(e){return e.length<=Xd?`[${e.join(", ")}]`:`[${e.slice(0,Xd).join(", ")}, …]`}function SP({value:e,path:t}){const n=yn(e);return n?c.jsxs("span",{"data-pyric-field-type":"vector","data-pyric-field-path":t,"data-dimension":String(n.dimension),children:[c.jsx("span",{"data-pyric-vector-dims":!0,children:`vector · ${n.dimension}`}),c.jsx("span",{"data-pyric-vector-preview":!0,children:_P(n.values)})]}):c.jsx("span",{"data-pyric-field-type":"vector","data-pyric-field-path":t})}function kP(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 jP({value:e,onChange:t,error:n,path:r}){const s=yn(e),i=s?JSON.stringify(s.values):"[]",[o,a]=y.useState(i),[l,u]=y.useState(void 0),d=p=>{a(p);const m=kP(p);if(!m.ok){u(m.error);return}u(void 0),t(m.value)},h=s?s.dimension:0,f=l??n;return c.jsxs("label",{"data-pyric-field-type":"vector","data-pyric-field-path":r,"data-dimension":String(h),"data-pyric-error":f?"":void 0,children:[c.jsx("span",{"data-pyric-vector-dims":!0,children:`vector · ${h}`}),c.jsx("span",{"data-pyric-vector-note":!0,children:"Replace whole. Paste a JSON number array."}),c.jsx("textarea",{"data-pyric-vector-raw":!0,value:o,onChange:p=>d(p.target.value),"aria-invalid":f?"true":void 0,"aria-label":"Vector value (JSON number array)"}),f?c.jsx("span",{"data-pyric-error-message":!0,children:f}):null]})}const EP={type:"vector",Display:SP,Edit:jP},Zd={string:KD,number:YD,boolean:ZD,null:nP,timestamp:aP,geopoint:uP,reference:pP,bytes:gP,map:wP,array:xP,vector:EP};function ng(e){return e?{...Zd,...e}:Zd}function Bi(e={}){const t=y.useRef(null),n=e.narrowBreakpoint??480,r=e.mediumBreakpoint??768,[s,i]=y.useState("wide");return y.useEffect(()=>{const o=t.current;if(!o||typeof ResizeObserver>"u")return;const a=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 a.observe(o),()=>a.disconnect()},[n,r]),{ref:t,size:s}}const rg=y.createContext(null);function Yt(){const e=y.useContext(rg);if(!e)throw new Error("DocumentEditor.* components must render inside <DocumentEditor.Root>");return e}function CP({initial:e,fieldEditors:t,onChange:n,children:r,className:s}){const i=Zy({initial:e}),o=ng(t),a=y.useRef(n);a.current=n,y.useEffect(()=>{a.current?.(i)},[i]);const{ref:l,size:u}=Bi();return c.jsx(rg.Provider,{value:{editor:i,fieldEditors:o},children:c.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 NP(){const{editor:e}=Yt(),t=e.tree.childIds[e.tree.rootId]??[];return c.jsxs("div",{"data-pyric-editor-fields":!0,children:[t.map(n=>c.jsx(zc,{nodeId:n,path:RP(e,n)},n)),c.jsx(sg,{parentId:e.tree.rootId})]})}function RP(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 zc({nodeId:e,path:t}){const{editor:n,fieldEditors:r}=Yt(),s=n.tree.nodes[e];if(!s)return null;if(s.type==="map")return c.jsx(OP,{node:s,path:t});if(s.type==="array")return c.jsx($P,{node:s,path:t});const o=r[s.type]?.Edit;if(!o)return null;const a=s.touched?s.error:void 0;return c.jsxs("div",{"data-pyric-field-entry":!0,"data-field-name":s.key??void 0,"data-pyric-error":a?"":void 0,onBlur:()=>n.touch(s.id),children:[c.jsx(Hc,{node:s,path:t}),c.jsx(o,{value:s.value,path:t,error:a,onChange:l=>n.setValue(s.id,l)})]})}function Hc({node:e,path:t}){const{editor:n}=Yt(),s=(e.parentId!=null?n.tree.nodes[e.parentId]:null)?.type==="map";return e.id===n.tree.rootId?null:c.jsxs("div",{"data-pyric-field-chrome":!0,"data-pyric-field-path":t,children:[s?c.jsx("input",{type:"text",value:e.key??"",onChange:o=>n.setKey(e.id,o.target.value),"aria-label":"Field name","data-pyric-field-key-input":!0,"aria-invalid":e.touched&&e.error?"true":void 0}):null,c.jsx(AP,{node:e}),c.jsx("button",{type:"button",onClick:()=>n.remove(e.id),"data-pyric-remove":!0,"aria-label":"Remove field",children:"×"})]})}const IP=["string","number","boolean","null","timestamp","geopoint","reference","bytes","vector","map","array"];function AP({node:e}){const{editor:t}=Yt(),n=e.parentId!=null?t.tree.nodes[e.parentId]:null,r=IP.filter(s=>!(n?.type==="array"&&s==="array"));return c.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=>c.jsx("option",{value:s,children:s},s))})}function OP({node:e,path:t}){const{editor:n}=Yt(),r=n.tree.childIds[e.id]??[];return c.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?c.jsx(Hc,{node:e,path:t}):null,c.jsx("div",{"data-pyric-map-children":!0,children:r.map(s=>{const i=n.tree.nodes[s];if(!i)return null;const o=t?`${t}.${i.key??""}`:i.key??"";return c.jsx(zc,{nodeId:s,path:o},s)})}),c.jsx(sg,{parentId:e.id})]})}function $P({node:e,path:t}){const{editor:n}=Yt(),r=n.tree.childIds[e.id]??[];return c.jsxs("div",{"data-pyric-field-entry":!0,"data-pyric-field-type":"array","data-field-name":e.key??void 0,children:[c.jsx(Hc,{node:e,path:t}),c.jsx("ol",{"data-pyric-array-children":!0,children:r.map((s,i)=>{const o=t?`${t}[${i}]`:`[${i}]`;return c.jsx("li",{"data-field-index":String(i),children:c.jsx(zc,{nodeId:s,path:o})},s)})}),c.jsx(DP,{parentId:e.id})]})}function sg({parentId:e}){const{editor:t}=Yt();return c.jsx("button",{type:"button","data-pyric-add-map-entry":!0,onClick:()=>t.addMapEntry(e,"","string"),children:"+ Add field"})}function DP({parentId:e}){const{editor:t}=Yt();return c.jsx("button",{type:"button","data-pyric-add-array-entry":!0,onClick:()=>t.addArrayEntry(e,"string"),children:"+ Add item"})}const ef={Root:CP,Fields:NP};function PP({collections:e,isLoading:t,error:n,onSelect:r,emptyState:s,className:i}){return n?c.jsx("div",{className:i,"data-pyric-ui":"collection-list","data-pyric-error":"",role:"alert",children:n.message}):t&&e.length===0?c.jsx("div",{className:i,"data-pyric-ui":"collection-list","data-pyric-loading":""}):e.length===0?c.jsx("div",{className:i,"data-pyric-ui":"collection-list","data-pyric-empty":"",children:s}):c.jsx("ul",{className:i,"data-pyric-ui":"collection-list",children:e.map(o=>c.jsx("li",{"data-pyric-collection-entry":!0,"data-pyric-collection-id":o.id,children:c.jsx("button",{type:"button",onClick:()=>r?.(o),"data-pyric-collection-select":!0,children:o.id})},o.path))})}const ir=new Map;function Kc({scope:e,entries:t,equals:n=Object.is,durationMs:r=1200,ready:s=!0}){const i=y.useRef(null),o=y.useRef(new Map),a=y.useRef(new Map),[l,u]=y.useState(ir);return y.useEffect(()=>{const d=i.current;if(!s){if(d&&d.scope!==e){i.current=null;for(const f of a.current.values())clearTimeout(f);a.current.clear(),o.current.clear(),u(ir)}return}if(!d||d.scope!==e){i.current={scope:e,entries:t};for(const f of a.current.values())clearTimeout(f);a.current.clear(),o.current.clear(),u(ir);return}const h=new Map;for(const[f,p]of t){const m=d.entries.has(f),g=d.entries.get(f);if(m&&n(g,p))continue;const b=o.current.get(f)===0?1:0;o.current.set(f,b),h.set(f,{kind:m?"modified":"added",cycle:b})}i.current={scope:e,entries:t},u(f=>{const p=new Map(f);let m=h.size>0;for(const g of f.keys())t.has(g)||(p.delete(g),m=!0);for(const[g,b]of h)p.set(g,b);return m?p.size===0?ir:p:f});for(const[f,p]of h){const m=a.current.get(f);m&&clearTimeout(m);const g=setTimeout(()=>{a.current.delete(f),u(b=>{if(b.get(f)?.cycle!==p.cycle)return b;const w=new Map(b);return w.delete(f),w.size===0?ir:w})},r);a.current.set(f,g)}},[r,t,n,s,e]),y.useEffect(()=>()=>{for(const d of a.current.values())clearTimeout(d);a.current.clear()},[]),l}function or(e){return e.ref}function TP({documents:e,isLoading:t,error:n,hasMore:r,onSelect:s,onLoadMore:i,renderLabel:o,renderRowAction:a,emptyState:l,className:u,updateScope:d="document-list",virtualizeThreshold:h=100,rowHeight:f=36,virtualizedHeight:p="60vh"}){const m=y.useMemo(()=>new Map(e.map(w=>[or(w).path,w.data()])),[e]),g=Kc({scope:d,entries:m,equals:gi,ready:!t});if(n)return c.jsx("div",{className:u,"data-pyric-ui":"document-list","data-pyric-error":"",role:"alert",children:n.message});if(t&&e.length===0)return c.jsx("div",{className:u,"data-pyric-ui":"document-list","data-pyric-loading":""});if(e.length===0)return c.jsx("div",{className:u,"data-pyric-ui":"document-list","data-pyric-empty":"",children:l});const b=e.length>h;return c.jsxs("div",{className:u,"data-pyric-ui":"document-list","data-pyric-virtualized":b?"":void 0,children:[b?c.jsx(Lc,{items:e,estimateSize:f,height:p,getItemKey:w=>or(w).path,renderItem:w=>{const x=g.get(or(w).path);return c.jsxs("div",{"data-pyric-document-entry":!0,"data-pyric-document-id":w.id,"data-pyric-update":x?.kind,"data-pyric-update-cycle":x?.cycle,children:[c.jsx("button",{type:"button",onClick:()=>s?.(or(w)),"data-pyric-document-select":!0,"data-pyric-update":x?.kind,"data-pyric-update-cycle":x?.cycle,children:o?o(w):w.id}),a?c.jsx("span",{"data-pyric-document-action":!0,children:a(w)}):null]})}}):c.jsx("ul",{"data-pyric-document-list-items":!0,children:e.map(w=>{const x=or(w),v=g.get(x.path);return c.jsxs("li",{"data-pyric-document-entry":!0,"data-pyric-document-id":w.id,"data-pyric-update":v?.kind,"data-pyric-update-cycle":v?.cycle,children:[c.jsx("button",{type:"button",onClick:()=>s?.(x),"data-pyric-document-select":!0,"data-pyric-update":v?.kind,"data-pyric-update-cycle":v?.cycle,children:o?o(w):w.id}),a?c.jsx("span",{"data-pyric-document-action":!0,children:a(w)}):null]},x.path)})}),r&&i?c.jsx("button",{type:"button",onClick:i,"data-pyric-load-more":!0,disabled:t,children:"Load more"}):null]})}const MP=/^__.*__$/;function ig(e){if(e.length===0)return"Cannot be empty";if(e.includes("/"))return'Cannot contain "/"';if(e==="."||e==="..")return'Cannot be "." or ".."';if(MP.test(e))return"Cannot match __.*__ (reserved)";if(UP(e)>1500)return"Cannot exceed 1500 bytes"}function LP(e){return ig(e)}function UP(e){return new TextEncoder().encode(e).length}function BP(e){return ig(e)}const tf="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function FP(){let e="";for(let t=0;t<20;t++)e+=tf.charAt(Math.floor(Math.random()*tf.length));return e}const qP={ref:Ar,listAll:Sc,getMetadata:nE,getBlob:tE,uploadBytes:Zj,uploadBytesResumable:eE,deleteObject:Ip},og=y.createContext(qP);function Fi(){return y.useContext(og)}function VP({value:e,children:t}){return y.createElement(og.Provider,{value:e},t)}function Io(e){return e.replace(/^\/+|\/+$/g,"")}function Fa(e,t){return e.fullPath<t.fullPath?-1:e.fullPath>t.fullPath?1:0}function Ao(e,t){return e.some(n=>n.fullPath===t.fullPath)?e:[...e,t].sort(Fa)}function WP(e,t){const{listAll:n,ref:r}=Fi(),s=Io(t),[i,o]=y.useState(()=>({status:e==null?"idle":"loading",items:[],prefixes:[],error:void 0})),[a,l]=y.useState(0),u=y.useRef(new Map);y.useEffect(()=>{if(u.current.clear(),e==null){o({status:"idle",items:[],prefixes:[],error:void 0});return}let m=!1;return o({status:"loading",items:[],prefixes:[],error:void 0}),n(r(e,s)).then(g=>{m||o({status:"success",items:[...g.items].sort(Fa),prefixes:[...g.prefixes].sort(Fa),error:void 0})}).catch(g=>{m||o({status:"error",items:[],prefixes:[],error:g instanceof Error?g:new Error(String(g))})}),()=>{m=!0}},[e,s,a]);const d=y.useCallback(()=>l(m=>m+1),[]),h=y.useCallback(m=>{if(e==null)return;const g=m.endsWith("/"),b=Io(m),w=s===""?"":`${s}/`;if(!b.startsWith(w)||b===s)return;const x=b.slice(w.length),v=x.indexOf("/");o(_=>{if(_.status==="idle")return _;if(v===-1)return g?(u.current.set(b,_.prefixes.some(k=>k.fullPath===b)?null:b),{..._,prefixes:Ao(_.prefixes,r(e,b))}):(u.current.set(b,_.items.some(k=>k.fullPath===b)?null:b),{..._,items:Ao(_.items,r(e,b))});const S=`${w}${x.slice(0,v)}`;return u.current.set(b,_.prefixes.some(k=>k.fullPath===S)?null:S),{..._,prefixes:Ao(_.prefixes,r(e,S))}})},[e,s]),f=y.useCallback(m=>{const g=Io(m),b=u.current.get(g);if(u.current.delete(g),b===null)return;const w=b??g;o(x=>({...x,items:x.items.filter(v=>v.fullPath!==w),prefixes:x.prefixes.filter(v=>v.fullPath!==w)}))},[]),p=y.useMemo(()=>[...i.prefixes.map(m=>({kind:"folder",name:m.name,fullPath:m.fullPath,ref:m})),...i.items.map(m=>({kind:"object",name:m.name,fullPath:m.fullPath,ref:m}))],[i.prefixes,i.items]);return{status:i.status,items:i.items,prefixes:i.prefixes,entries:p,error:i.error,refresh:d,insertItem:h,removeItem:f}}function de(e){return e.split("/").filter(Boolean).join("/")}function zP(e={}){const{path:t,onPathChange:n,defaultPath:r=""}=e,s=t!==void 0,[i,o]=y.useState(()=>de(r)),a=s?de(t):i,l=y.useCallback(p=>{const m=de(p);s||o(m),n?.(m)},[s,n]),u=y.useMemo(()=>a===""?[]:a.split("/"),[a]),d=y.useCallback(p=>{const m=de(p);l(m.includes("/")||a===""?m:`${a}/${m}`)},[a,l]),h=y.useCallback(()=>{u.length!==0&&l(u.slice(0,-1).join("/"))},[u,l]),f=y.useCallback(p=>{l(p<0?"":u.slice(0,p+1).join("/"))},[u,l]);return{path:a,segments:u,setPath:l,enter:d,up:h,navigateToIndex:f}}const nf={status:"idle",blob:void 0,url:void 0,error:void 0};function HP(e,t){const{getBlob:n,getMetadata:r,ref:s}=Fi(),i=t==null?null:de(t),o=e!=null&&i!=null&&i!=="",[a,l]=y.useState(()=>({status:o?"loading":"idle",metadata:void 0,error:void 0})),[u,d]=y.useState(nf),[h,f]=y.useState(0),p=y.useRef(0);y.useEffect(()=>{if(p.current++,d(nf),!o){l({status:"idle",metadata:void 0,error:void 0});return}let w=!1;return l({status:"loading",metadata:void 0,error:void 0}),r(s(e,i)).then(x=>{w||l({status:"success",metadata:x,error:void 0})}).catch(x=>{w||l({status:"error",metadata:void 0,error:x instanceof Error?x:new Error(String(x))})}),()=>{w=!0}},[e,i,h]);const m=u.url;y.useEffect(()=>{if(m!==void 0)return()=>{URL.revokeObjectURL(m)}},[m]);const g=y.useCallback(()=>f(w=>w+1),[]),b=y.useCallback(()=>{if(e==null||i==null||i==="")return;const w=++p.current;d({status:"loading",blob:void 0,url:void 0,error:void 0}),n(s(e,i)).then(x=>{w===p.current&&d({status:"success",blob:x,url:URL.createObjectURL(x),error:void 0})}).catch(x=>{w===p.current&&d({status:"error",blob:void 0,url:void 0,error:x instanceof Error?x:new Error(String(x))})})},[e,i]);return{status:a.status,metadata:a.metadata,error:a.error,refresh:g,blobStatus:u.status,blob:u.blob,blobUrl:u.url,blobError:u.error,loadBlob:b}}function KP(){const[e,t]=y.useState(()=>new Map),n=y.useCallback(u=>e.has(u),[e]),r=y.useCallback(u=>{t(d=>{if(d.has(u.fullPath))return d;const h=new Map(d);return h.set(u.fullPath,u),h})},[]),s=y.useCallback(u=>{t(d=>{if(!d.has(u))return d;const h=new Map(d);return h.delete(u),h})},[]),i=y.useCallback(u=>{t(d=>{const h=new Map(d);return h.has(u.fullPath)?h.delete(u.fullPath):h.set(u.fullPath,u),h})},[]),o=y.useCallback(u=>{t(new Map(u.map(d=>[d.fullPath,d])))},[]),a=y.useCallback(()=>t(new Map),[]);return{selected:y.useMemo(()=>[...e.values()],[e]),size:e.size,isSelected:n,toggle:i,select:r,deselect:s,selectAll:o,clear:a}}function GP(e,t){const n=Ar(e,t);return{storage:e,bucket:n.bucket,fullPath:`${n.fullPath}/`,name:"",parent:n,root:n.root,toString:()=>`${n.toString()}/`}}function JP(e){return{...e,fullPath:`${e.fullPath}/`,name:""}}function YP(e){return{async*start(t){const n=e??{listAll:Sc,deleteObject:Ip};let r=0;const s=[t],i=[];for(;s.length>0;){const o=s.pop();i.push(o);const a=await n.listAll(o);s.push(...a.prefixes);for(const l of a.items)await n.deleteObject(l),r++,yield{deletedCount:r,done:!1}}for(const o of i)try{await n.deleteObject(JP(o))}catch{}yield{deletedCount:r,done:!0}}}}function QP(e,t={}){const n=Fi(),[r,s]=y.useState(0),[i,o]=y.useState(!1),[a,l]=y.useState(void 0),u=y.useRef(0),d=y.useRef(t);return d.current=t,{deleteEntries:y.useCallback(async f=>{const p=++u.current;s(0),l(void 0);const m={deleted:[],failed:[]};if(e==null||f.length===0)return m;o(!0);const g=d.current.impl??YP(n);let b=0;try{for(const w of f){d.current.list?.removeItem(w.fullPath);try{if(w.kind==="object")await n.deleteObject(n.ref(e,w.fullPath)),b++;else for await(const x of g.start(n.ref(e,w.fullPath))){if(p!==u.current)return m;if(s(b+x.deletedCount),x.done){b+=x.deletedCount;break}}m.deleted.push(w.fullPath),p===u.current&&s(b)}catch(x){const v=x instanceof Error?x:new Error(String(x));m.failed.push({fullPath:w.fullPath,error:v}),d.current.list?.insertItem(w.kind==="folder"?`${w.fullPath}/`:w.fullPath),p===u.current&&m.failed.length===1&&l(v)}}return m}finally{p===u.current&&o(!1)}},[n,e]),progress:r,isRunning:i,error:a}}const XP=Object.freeze({read:!0,write:!0,delete:!0,upload:!0,reasons:Object.freeze({read:[],write:[]})}),ZP=Object.freeze({read:!1,write:!1,delete:!1,upload:!1,reasons:Object.freeze({read:["No Storage rules configured; default deny."],write:["No Storage rules configured; default deny."]})});function eT(e,t={}){const{paths:n,rules:r,identity:s,writeResource:i}=t,o=e==null?null:e[Ci],[a,l]=y.useState(()=>({status:e==null?"idle":"loading",rules:null,source:"none",error:void 0}));y.useEffect(()=>{if(o==null){l({status:"idle",rules:null,source:"none",error:void 0});return}if(r!=null){try{const x=typeof r=="string"?ea(r):r;l({status:"ready",rules:x,source:"option",error:void 0})}catch(x){l({status:"error",rules:null,source:"none",error:x instanceof Error?x:new Error(String(x))})}return}let w=!1;return l({status:"loading",rules:null,source:"none",error:void 0}),o.servicePromise.then(x=>{w||l({status:"ready",rules:x.rules,source:x.rules?"sandbox":"none",error:void 0})}).catch(x=>{w||l({status:"error",rules:null,source:"none",error:x instanceof Error?x:new Error(String(x))})}),()=>{w=!0}},[o,r]);const u=s!==void 0?s:o?.context.auth??null,{rules:d,status:h}=a,f=i?.size,p=i?.contentType,m=y.useCallback(w=>{if(d==null)return h==="ready"?ZP:XP;const x=de(w),v=o?.bucket??"pyric-default",_=x===""?`b/${v}/o`:`b/${v}/o/${x}`,S=R=>_p(d,{request:{auth:u,method:R,path:_,...R==="create"&&f!==void 0?{resource:{size:f,contentType:p}}:{}},resource:null}),k=S("read"),N=S("create"),O=S("delete"),D=N;return{read:k.allowed,write:D.allowed,delete:O.allowed,upload:N.allowed,reasons:{read:k.allowed?[]:k.reasons,write:D.allowed?[]:D.reasons}}},[d,h,o?.bucket,u,f,p]),g=typeof n=="string"?n:(n??[]).join(`
|
|
141
|
-
`),b=y.useMemo(()=>{const w=typeof n=="string"?[n]:n??[],x={};for(const v of w)x[de(v)]=m(v);return x},[g,m]);return{status:h,source:a.source,advisory:!1,identity:u,verdicts:b,verdictFor:m,error:a.error}}function rf(e,t){return e===""?t:t===""?e:`${e}/${t}`}function tT(e){return e instanceof Blob?e.size:e.byteLength}function nT(e){if(e instanceof Blob){const t=e;return{path:t.webkitRelativePath||t.name,data:t}}return e}function rT(e,t={}){const{ref:n,uploadBytes:r}=Fi(),s=de(t.path??""),[i,o]=y.useState([]),a=y.useRef(t);a.current=t;const l=y.useCallback(f=>{o(p=>p.map(m=>m.id===f.id?f:m))},[]),u=y.useCallback(async f=>{if(e==null)throw new Error("useObjectUpload: storage handle is null");const m=(Array.isArray(f)?f:[f]).map(g=>{const b=nT(g);return{task:{id:crypto.randomUUID(),fullPath:rf(s,de(b.path)),status:"running",bytesTransferred:0,totalBytes:tT(b.data)},entry:b}});o(g=>[...g,...m.map(b=>b.task)]);for(const{task:g}of m)a.current.list?.insertItem(g.fullPath),a.current.onProgress?.(g);return Promise.all(m.map(async({task:g,entry:b})=>{try{const w=await r(n(e,g.fullPath),b.data,b.metadata),x={...g,status:"success",bytesTransferred:g.totalBytes,metadata:w.metadata};return l(x),a.current.onProgress?.(x),a.current.onComplete?.(x),x}catch(w){const x={...g,status:"error",error:w instanceof Error?w:new Error(String(w))};return a.current.list?.removeItem(g.fullPath),l(x),a.current.onError?.(x),x}}))},[e,s,l,n,r]),d=y.useCallback(async f=>{if(e==null)throw new Error("useObjectUpload: storage handle is null");const p=rf(s,de(f));if(p==="")throw new Error("createFolder: folder name is empty");a.current.list?.insertItem(`${p}/`);try{await r(GP(e,p),new Blob([]),{contentType:"text/plain"})}catch(m){throw a.current.list?.removeItem(p),m}},[e,s,r]),h=y.useCallback(()=>{o(f=>f.filter(p=>p.status==="running"))},[]);return{tasks:i,isUploading:i.some(f=>f.status==="running"),upload:u,createFolder:d,clearCompleted:h}}function sT({path:e,onNavigate:t,rootLabel:n="/",separator:r="/",className:s}){const i=de(e),o=i===""?[]:i.split("/");return c.jsx("nav",{className:s,"data-pyric-ui":"path-breadcrumb","aria-label":"Storage path",children:c.jsxs("ol",{"data-pyric-breadcrumb-list":!0,children:[c.jsx("li",{"data-pyric-breadcrumb-item":!0,children:c.jsx("button",{type:"button",onClick:()=>t?.(""),"data-pyric-breadcrumb-link":!0,"data-pyric-breadcrumb-root":!0,"data-pyric-current":o.length===0?"":void 0,"aria-current":o.length===0?"page":void 0,children:n})}),o.map((a,l)=>{const u=l===o.length-1,d=o.slice(0,l+1).join("/");return c.jsxs("li",{"data-pyric-breadcrumb-item":!0,children:[c.jsx("span",{"aria-hidden":!0,"data-pyric-breadcrumb-separator":!0,children:r}),c.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:a})]},d)})]})})}function iT({entries:e,status:t="success",error:n,onNavigate:r,onSelect:s,selectedPath:i,gate:o,renderEntry:a,renderRowAction:l,emptyState:u,className:d,virtualizeThreshold:h=100,rowHeight:f=36,virtualizedHeight:p="60vh"}){const{ref:m,size:g}=Bi();if(n)return c.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 c.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 c.jsx("div",{className:d,"data-pyric-ui":"object-browser","data-pyric-empty":"",children:u});const b=v=>{if(!o)return{denied:!1};const _=o.verdictFor(v.fullPath);return _.read?{denied:!1}:{denied:!0,reason:_.reasons.read.join("; ")}},w=v=>{const _=v.kind==="object"&&v.fullPath===i;return c.jsxs(c.Fragment,{children:[c.jsx("button",{type:"button",onClick:()=>v.kind==="folder"?r?.(v.fullPath):s?.(v.ref),"data-pyric-entry-select":!0,"data-pyric-selected":_?"":void 0,"aria-selected":_||void 0,children:a?a(v):v.name}),l?c.jsx("span",{"data-pyric-storage-action":!0,children:l(v)}):null]})},x=e.length>h;return c.jsx("div",{ref:m,className:d,"data-pyric-ui":"object-browser","data-size":g,"data-pyric-virtualized":x?"":void 0,children:x?c.jsx(Lc,{items:e,estimateSize:f,height:p,getItemKey:v=>`${v.kind}:${v.fullPath}`,renderItem:v=>{const _=b(v);return c.jsx("div",{"data-pyric-storage-entry":!0,"data-pyric-entry-kind":v.kind,"data-pyric-entry-path":v.fullPath,"data-pyric-denied":_.denied?"":void 0,"data-pyric-denied-reason":_.reason,children:w(v)})}}):c.jsx("ul",{"data-pyric-object-browser-items":!0,children:e.map(v=>{const _=b(v);return c.jsx("li",{"data-pyric-storage-entry":!0,"data-pyric-entry-kind":v.kind,"data-pyric-entry-path":v.fullPath,"data-pyric-denied":_.denied?"":void 0,"data-pyric-denied-reason":_.reason,children:w(v)},`${v.kind}:${v.fullPath}`)})})})}async function ag(e,t,n){const r=t===""?e.name:`${t}/${e.name}`;if(e.isFile){const s=await new Promise((i,o)=>e.file(i,o));n.push({file:s,relativePath:r});return}if(e.isDirectory){const s=e.createReader();for(;;){const i=await new Promise((o,a)=>s.readEntries(o,a));if(i.length===0)break;for(const o of i)await ag(o,r,n)}}}async function oT(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 ag(i,"",t);else{const o=r.getAsFile?.();o&&t.push({file:o,relativePath:o.name})}}if(t.length===0)for(const r of Array.from(e.files??[]))t.push({file:r,relativePath:r.name});return t}function aT({onFiles:e,children:t,disabled:n,disabledReason:r,className:s}){const[i,o]=y.useState(!1),a=y.useRef(0),l=y.useCallback(f=>{f.preventDefault(),!n&&(a.current+=1,o(!0))},[n]),u=y.useCallback(f=>{f.preventDefault()},[]),d=y.useCallback(f=>{f.preventDefault(),!n&&(a.current=Math.max(0,a.current-1),a.current===0&&o(!1))},[n]),h=y.useCallback(f=>{if(f.preventDefault(),a.current=0,o(!1),n)return;const p=f.dataTransfer;p&&oT(p).then(m=>{m.length>0&&e(m)})},[n,e]);return c.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:h,children:t})}function cT(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 lT(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 sf(e,t){if(!t.has(e))return e;const{stem:n,ext:r}=cT(e),{base:s,counter:i}=lT(n);let o=i===null?1:i+1;for(;;){const a=`${s} (${o})${r}`;if(!t.has(a))return a;o+=1}}function uT(e,t){const n=new Set(t),r=new Map;return e.map(s=>{const i=s.indexOf("/");if(i===-1){const l=sf(s,n);return n.add(l),l}const o=s.slice(0,i);let a=r.get(o);return a===void 0&&(a=sf(o,n),n.add(a),r.set(o,a)),`${a}${s.slice(i)}`})}function of(e){const t=de(e);if(t==="")return[];const n=t.split("/");return n.map((r,s)=>n.slice(0,s+1).join("/"))}const cg=[];function dT(e,t){switch(t.type){case"create":{const n=of(t.path).filter(r=>!e.includes(r));return n.length===0?e:[...e,...n].sort()}case"materialize":{const n=new Set(of(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=de(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:cg}}function fT(e,t){const n=de(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 af(e,t){return e.includes(de(t))}function hT(e){const t=de(e);return t===""?"Enter a folder name.":t.split("/").some(r=>r==="."||r==="..")?'Folder names may not be "." or "..".':null}const pT=256*1024;function qa(e){return(e.contentType??"").split(";")[0].trim().toLowerCase()}const mT={id:"image",match:e=>qa(e).startsWith("image/"),needsBlob:!0,render:({metadata:e,blobUrl:t})=>t?c.jsx("img",{"data-pyric-preview-image":!0,src:t,alt:e.name}):null};function yT({blob:e,isJson:t}){const[n,r]=y.useState(void 0);return y.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:c.jsx("pre",{"data-pyric-preview-text":!0,children:n})}const gT={id:"text",match:e=>{const t=qa(e);return t.startsWith("text/")||t==="application/json"},needsBlob:!0,maxBytes:pT,render:({metadata:e,blob:t})=>t?c.jsx(yT,{blob:t,isJson:qa(e)==="application/json"}):null},bT=[mT,gT];function wT(e,t){for(const n of[...t??[],...bT])if(n.match(e))return n}const vT=[{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 xT({metadata:e}){return c.jsxs("dl",{"data-pyric-object-metadata":!0,children:[vT.map(({key:t,label:n,value:r})=>{const s=r(e);return s===void 0?null:c.jsxs("div",{"data-pyric-metadata-field":t,children:[c.jsx("dt",{children:n}),c.jsx("dd",{children:s})]},t)}),Object.entries(e.customMetadata??{}).map(([t,n])=>c.jsxs("div",{"data-pyric-metadata-field":"customMetadata","data-pyric-metadata-key":t,children:[c.jsx("dt",{children:t}),c.jsx("dd",{children:n})]},`custom:${t}`))]})}function _T({storage:e,path:t,previews:n,renderMetadata:r,children:s,className:i}){const{ref:o,size:a}=Bi(),l=HP(e,t),{metadata:u,blobStatus:d,loadBlob:h}=l,f=u?wT(u,n):void 0,p=f?.maxBytes!==void 0&&u!==void 0&&u.size>f.maxBytes,m=f?.needsBlob===!0&&!p;if(y.useEffect(()=>{m&&d==="idle"&&h()},[m,d,h]),l.status==="idle")return c.jsx("div",{className:i,"data-pyric-ui":"object-inspector","data-pyric-idle":""});if(l.status==="loading")return c.jsx("div",{className:i,"data-pyric-ui":"object-inspector","data-pyric-loading":""});if(l.status==="error"||u===void 0)return c.jsx("div",{className:i,"data-pyric-ui":"object-inspector","data-pyric-error":"",role:"alert",children:l.error?.message});let g,b={};return f===void 0?b={"data-pyric-preview-none":""}:p?b={"data-pyric-preview-too-large":""}:m&&d==="loading"?b={"data-pyric-preview-loading":""}:m&&d==="error"?(b={"data-pyric-preview-error":""},g=l.blobError?.message):(!m||d==="success")&&(g=f.render({metadata:u,blob:l.blob,blobUrl:l.blobUrl})),c.jsxs("div",{ref:o,className:i,"data-pyric-ui":"object-inspector","data-size":a,children:[c.jsx("div",{"data-pyric-object-name":!0,children:u.name}),r?r(u):c.jsx(xT,{metadata:u}),c.jsx("div",{"data-pyric-object-preview":!0,"data-pyric-preview":f?.id,...b,children:g}),s]})}const lg=y.createContext(null);function ST(){const e=y.useContext(lg);if(!e)throw new Error("useToast: missing <ToastProvider> ancestor");return e}function kT({children:e,defaultDuration:t=5e3,className:n,regionLabel:r="Notifications"}){const[s,i]=y.useState([]),o=y.useCallback(u=>{i(d=>d.filter(h=>h.id!==u))},[]),a=y.useCallback(u=>{const d=crypto.randomUUID(),h=u.duration??t;return i(f=>[...f,{id:d,...u}]),h>0&&window.setTimeout(()=>{i(f=>f.filter(p=>p.id!==d))},h),d},[t]),l=y.useMemo(()=>({toast:a,dismiss:o,toasts:s}),[a,o,s]);return c.jsxs(lg.Provider,{value:l,children:[e,c.jsx(jT,{toasts:s,dismiss:o,className:n,regionLabel:r})]})}function jT({toasts:e,dismiss:t,className:n,regionLabel:r}){const[s,i]=y.useState(!1);return y.useEffect(()=>i(!0),[]),!s||typeof document>"u"?null:Mc.createPortal(c.jsx("ol",{"aria-label":r,"aria-live":"polite","data-pyric-ui":"toast-region",className:n,children:e.map(o=>c.jsxs("li",{"data-pyric-toast":!0,"data-pyric-toast-kind":o.kind??"info",role:o.kind==="error"?"alert":"status",children:[c.jsx("div",{"data-pyric-toast-title":!0,children:o.title}),o.body?c.jsx("div",{"data-pyric-toast-body":!0,children:o.body}):null,c.jsx("button",{type:"button","data-pyric-toast-dismiss":!0,"aria-label":"Dismiss",onClick:()=>t(o.id),children:"×"})]},o.id))}),document.body)}function ET({storage:e,entries:t,impl:n,list:r,gate:s,title:i,body:o,confirmLabel:a="Delete",onDeleted:l,onFailed:u,renderTrigger:d,className:h}){const f=Hn(),{toast:p}=ST(),{deleteEntries:m,isRunning:g,progress:b}=QP(e,{impl:n,list:r}),w=s?t.map(S=>({entry:S,verdict:s.verdictFor(S.fullPath)})).filter(S=>!S.verdict.delete):[],x=w.length===0?void 0:`Delete denied for ${w[0].entry.fullPath}${w.length>1?` (+${w.length-1} more)`:""}: ${w[0].verdict.reasons.write.join("; ")}`,v=g||t.length===0||e==null||w.length>0,_=async()=>{if(v||!await f({title:i??(t.length===1?`Delete ${t[0].fullPath}?`:`Delete ${t.length} items?`),body:o??c.jsx("ul",{"data-pyric-delete-selection-paths":!0,children:t.map(N=>c.jsxs("li",{"data-pyric-entry-kind":N.kind,children:[N.fullPath,N.kind==="folder"?"/":""]},N.fullPath))}),destructive:!0,confirmLabel:a}))return;const k=await m(t);k.failed.length===0?(p({title:`Deleted ${k.deleted.length} ${k.deleted.length===1?"item":"items"}`,kind:"success"}),l?.(k)):(p({title:`Delete failed for ${k.failed.length} of ${t.length}`,kind:"error",body:c.jsx("ul",{"data-pyric-delete-selection-failures":!0,children:k.failed.map(N=>c.jsxs("li",{children:[N.fullPath,":"," ",N.error.code??N.error.message]},N.fullPath))})}),u?.(k))};return d?c.jsx(c.Fragment,{children:d({onClick:_,isRunning:g,progress:b,disabled:v,deniedReason:x})}):c.jsx("button",{type:"button",onClick:_,className:h,disabled:v,title:x,"data-pyric-ui":"delete-selection","data-pyric-destructive":"","data-pyric-running":g?"":void 0,"data-pyric-denied":x?"":void 0,"data-pyric-denied-reason":x,children:g?`Deleting… (${b})`:a})}function Wr(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 ug(e){const t=e.indexOf("?");return $c(t===-1?e:e.slice(0,t),t===-1?"":e.slice(t))}function CT(e){const{tab:t,rest:n,query:r}=ug(e),s=n.join("/");return t==="firestore"?{view:"firestore",path:Wr(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 dg(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 fg(e){const{tab:t,query:n}=ug(e),r=CT(e),s=t==="traffic"?n.inspect??null:null;return{target:r,selectedInspectId:s}}let cf=null,Va=fg("");function NT(){const e=Dc();return e!==cf&&(cf=e,Va=fg(e)),Va}function RT(){return Va}function Rs(e){Ae(dg(e))}function IT(e){Ae({tab:"traffic",query:{inspect:e}})}function qi(){const e=y.useSyncExternalStore(Gt,NT,RT),t=y.useCallback(s=>Rs(s),[]),n=y.useCallback(s=>{switch(s.kind){case"user":Rs({view:"auth",uid:s.uid});break;case"storage":Rs({view:"storage",kind:"object",path:s.objectPath});break;case"document":Rs({view:"firestore",path:Wr(s.path)});break}},[]),r=y.useCallback(s=>IT(s),[]);return y.useMemo(()=>({target:e.target,navigate:t,navigateRef:n,selectedInspectId:e.selectedInspectId,navigateInspect:r}),[e,t,n,r])}const AT={narrowBreakpoint:640,mediumBreakpoint:920};function OT(e){switch(e){case"narrow":return 1;case"medium":return 2;case"wide":return 3}}function $T(e,t){const n=OT(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 Oo({label:e,error:t,hint:n,children:r}){return c.jsxs("div",{className:"fs-modal__group",children:[c.jsx("span",{className:"fs-modal__label",children:e}),r,t?c.jsx("span",{className:"fs-modal__err",role:"alert",children:t}):n?c.jsx("span",{className:"fs-modal__hint",children:n}):null]})}function hg({mode:e,parentPath:t,onCreate:n,onClose:r}){const[s,i]=y.useState(""),[o,a]=y.useState(()=>FP()),[l,u]=y.useState(null),[d,h]=y.useState(null),[f,p]=y.useState(!1),m=y.useRef(null),g=e==="collection"&&s?LP(s):void 0,b=o?BP(o):void 0,x=!(e==="collection"&&(!s||g))&&!!o&&!b&&!f;y.useEffect(()=>{const S=k=>{k.key==="Escape"&&!f&&r()};return document.addEventListener("keydown",S),()=>document.removeEventListener("keydown",S)},[f,r]);const v=async()=>{if(!(!x||!l)){if(!l.isValid){l.touchAll();return}p(!0),h(null);try{await n({collectionId:e==="collection"?s:null,docId:o,data:Gy(l.tree)}),r()}catch(S){h(S instanceof Error?S:new Error(String(S))),p(!1)}}},_=e==="collection"?"Start a collection":"Add a document";return c.jsx("div",{className:"fs-modal-backdrop",onMouseDown:S=>{S.target===S.currentTarget&&!f&&r()},children:c.jsxs("div",{ref:m,className:"fs-modal",role:"dialog","aria-modal":"true","aria-label":_,"data-pyric-ui":"fs-create-modal","data-fs-create-mode":e,children:[c.jsx("h2",{className:"fs-modal__title",children:_}),c.jsx(Oo,{label:"Parent path",children:c.jsx("span",{className:"fs-modal__path",children:t})}),e==="collection"?c.jsx(Oo,{label:"Collection ID",error:g,children:c.jsx("input",{autoFocus:!0,type:"text",value:s,placeholder:"e.g. users",onChange:S=>i(S.target.value),"data-pyric-field":"collection-id","aria-invalid":g?"true":void 0})}):null,c.jsx(Oo,{label:"Document ID",error:o?b:"Cannot be empty",hint:"Auto-generated — edit to set your own.",children:c.jsx("input",{autoFocus:e==="document",type:"text",value:o,onChange:S=>a(S.target.value),"data-pyric-field":"doc-id","aria-invalid":b||!o?"true":void 0})}),c.jsxs("div",{className:"fs-modal__group",children:[c.jsx("span",{className:"fs-modal__label",children:"Fields"}),c.jsx("div",{className:"fs-modal__fields",children:c.jsx(ef.Root,{initial:{},onChange:u,children:c.jsx(ef.Fields,{})})})]}),d?c.jsx("p",{className:"fs-modal__err",role:"alert",children:d.message}):null,c.jsxs("div",{className:"fs-modal__actions",children:[c.jsx("button",{type:"button",className:"fs-editor__cancel",disabled:f,onClick:r,children:"Cancel"}),c.jsx("button",{type:"button",className:"fs-editor__save",disabled:!x,onClick:()=>void v(),children:f?"Saving…":"Save"})]})]})})}function pg({items:e,label:t="More actions"}){const[n,r]=y.useState(!1),[s,i]=y.useState(null),o=y.useRef(null),a=()=>{if(!n){const l=o.current?.getBoundingClientRect();l&&i({top:l.bottom+4,right:window.innerWidth-l.right})}r(l=>!l)};return y.useEffect(()=>{if(!n)return;const l=u=>{u.key==="Escape"&&(r(!1),o.current?.focus())};return document.addEventListener("keydown",l),()=>document.removeEventListener("keydown",l)},[n]),c.jsxs("span",{className:"fs-overflow","data-pyric-ui":"fs-overflow-menu",children:[c.jsx("button",{ref:o,type:"button",className:"fs-overflow__trigger","aria-haspopup":"menu","aria-expanded":n,"aria-label":t,onClick:a,children:c.jsx("span",{"aria-hidden":"true",children:"⋮"})}),n?c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"fs-overflow__backdrop",onMouseDown:()=>r(!1)}),c.jsx("div",{className:"fs-overflow__menu",role:"menu",style:s?{top:s.top,right:s.right}:void 0,children:e.map(l=>c.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 mg(e){return JSON.stringify(e)}function DT(e,t){const n=new Map,r=(s,i)=>{const o=t(s),a=mg(i);if(o==="map"){const l=s,u=Object.keys(l).sort();n.set(a,[o,u]);for(const d of u)r(l[d],[...i,["field",d]]);return}if(o==="array"){const l=s;n.set(a,[o,l.map((u,d)=>String(d))]),l.forEach((u,d)=>r(u,[...i,["index",d]]));return}n.set(a,[o,s])};for(const[s,i]of Object.entries(e))r(i,[["field",s]]);return n}function yg(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 mg(n)}function PT(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 TT(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 lf(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 MT=42;function LT(e,t,n,r=MT){const s=e.nodes[t],i=e.childIds[t]??[];let o;return s.type==="array"?o=`[${i.slice(0,3).map(l=>lf(e.nodes[l],n.asVectorView,n.vectorPreview)).join(", ")}${i.length>3?", …":""}]`:o=`{${i.slice(0,2).map(l=>`"${e.nodes[l].key}": ${lf(e.nodes[l],n.asVectorView,n.vectorPreview)}`).join(", ")}${i.length>2?", …":""}}`,o.length>r?`${o.slice(0,r-1)}…`:o}function UT(e,t,n){return t.parentId==null?!1:(e.childIds[t.parentId]??[]).some(s=>s!==t.id&&e.nodes[s]?.key===n)}function BT(e){return e.shiftKey===!0}const gg=["string","number","boolean","null","timestamp","geopoint","reference","bytes","vector"],FT=[...gg,"map","array"];function qT({snapshot:e,documentRef:t,onCommit:n,onDeleteDocument:r,onDeleteDocumentFields:s,fieldEditors:i,onReferenceClick:o,onStartCollection:a,firestore:l,listSubcollections:u,onSubcollectionClick:d}){const h=y.useMemo(()=>e?.data()??{},[e]),f=y.useMemo(()=>h,[]),p=Zy({initial:f}),m=p.replaceData,g=y.useMemo(()=>ng(i),[i]),b=Hn(),[w,x]=y.useState(()=>new Set),[v,_]=y.useState(null),S=y.useRef(e),k=y.useRef(new Set),N=y.useRef(!1),[O,D]=y.useState(null),R=y.useMemo(()=>DT(h,Ui),[h]),j=Kc({scope:t.path,entries:R,equals:gi,ready:v===null});y.useEffect(()=>{N.current&&(N.current=!1,D(null),n(p.toData()).catch(U=>{D(U instanceof Error?U:new Error(String(U)))}))},[p.tree]),y.useEffect(()=>{!e||e===S.current||v!==null||(S.current=e,k.current.clear(),m(e.data()??{}))},[v,m,e]);const E=y.useCallback(U=>{x(V=>{const F=new Set(V);return F.has(U)?F.delete(U):F.add(U),F})},[]),[$,C]=y.useState(null),I=y.useCallback((U,V)=>{if(V==="map"?p.addMapEntry(U,"","string"):p.addArrayEntry(U,"string"),U!==p.tree.rootId){const F=yg(p.tree,U);x(Se=>new Set(Se).add(F))}C(U)},[p]);y.useEffect(()=>{if(!$)return;const U=p.tree.childIds[$]??[],V=U[U.length-1];V&&!v&&(k.current.add(V),_(V),C(null))},[p.tree,$]);const A=y.useCallback(U=>{p.remove(U),k.current.delete(U),N.current=!0,v===U&&_(null)},[p,v]),P=y.useCallback(async(U,V,F)=>{if(BT(F)){A(U.id);return}await b({title:`Delete field "${V}"?`,destructive:!0,confirmLabel:"Delete"})&&A(U.id)},[b,A]),T=t.id,W=p.tree.childIds[p.tree.rootId]??[];return c.jsxs("div",{"data-pyric-ui":"fs-doctree",className:"fs-doctree",children:[c.jsxs("div",{className:"fs-doctree__head",children:[c.jsx("span",{className:"fs-doctree__docid",children:T}),c.jsx(pg,{items:[{label:"Delete document fields",onSelect:()=>{(async()=>await b({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}]})]}),O?c.jsx("p",{className:"fs-doctree__err",children:O.message}):null,c.jsxs("ul",{className:"fs-doctree__rows",children:[a?c.jsx("li",{className:"fs-doctree__action-row",children:c.jsxs("button",{type:"button",className:"fs-doctree__action",onClick:a,children:[c.jsx("span",{"aria-hidden":"true",children:"+"})," Start collection"]})}):null,c.jsx("li",{className:"fs-doctree__action-row",children:c.jsxs("button",{type:"button",className:"fs-doctree__action",onClick:()=>I(p.tree.rootId,"map"),children:[c.jsx("span",{"aria-hidden":"true",children:"+"})," Add field"]})}),W.map(U=>c.jsx(bg,{nodeId:U,depth:0,editor:p,registry:g,expanded:w,onToggle:E,editingId:v,setEditingId:_,newIdsRef:k,onAdd:I,onDelete:P,onCommitNeeded:()=>{N.current=!0},onReferenceClick:o,updates:j},U))]}),l&&u?c.jsx(wg,{firestore:l,documentRef:t,listSubcollections:u,onSubcollectionClick:d}):null]})}function bg({nodeId:e,depth:t,editor:n,registry:r,expanded:s,onToggle:i,editingId:o,setEditingId:a,newIdsRef:l,onAdd:u,onDelete:d,onCommitNeeded:h,onReferenceClick:f,updates:p}){const{tree:m}=n,g=m.nodes[e];if(!g)return null;const{label:b,isArrayChild:w}=TT(m,e),x=g.type==="map"||g.type==="array",v=PT(m,e),_=yg(m,e),S=p.get(_),k=s.has(_),N=o===e,O=l.current.has(e);return N?c.jsx("li",{className:"fs-doctree__row fs-doctree__row--editing","data-pyric-doctree-depth":t,style:{"--fs-depth":t},children:c.jsx(VT,{node:g,isNew:O,isArrayChild:w,tree:m,editor:n,registry:r,path:v,onCommitNeeded:h,onDone:()=>{l.current.delete(e),a(null)},onCancelNew:()=>{n.remove(e),l.current.delete(e),a(null)}})}):c.jsxs("li",{className:"fs-doctree__row","data-pyric-doctree-depth":t,"data-pyric-doctree-nested":x?"":void 0,style:{"--fs-depth":t},children:[c.jsxs("div",{className:"fs-doctree__line","data-pyric-update":S?.kind,"data-pyric-update-cycle":S?.cycle,children:[x?c.jsx("button",{type:"button",className:"fs-doctree__caret","aria-expanded":k,onClick:()=>i(_),children:c.jsx("span",{"aria-hidden":"true",children:k?"▼":"▶"})}):c.jsx("span",{className:"fs-doctree__caret fs-doctree__caret--empty","aria-hidden":"true"}),w?c.jsx("span",{className:"fs-doctree__chip",children:b}):c.jsx("span",{className:"fs-doctree__key",children:b}),x?k?null:c.jsx("span",{className:"fs-doctree__preview",children:LT(m,e,{asVectorView:yn,vectorPreview:Hy})}):c.jsx("span",{className:"fs-doctree__value",children:c.jsx(Ba,{value:g.value,path:v,fieldEditors:r})}),c.jsxs("span",{className:"fs-doctree__hover",children:[c.jsxs("span",{className:"fs-doctree__typenote",children:["(",g.type,")"]}),x?c.jsx("button",{type:"button",className:"fs-doctree__icon",title:"Add field","aria-label":`Add field to ${b||"document"}`,onClick:()=>u(e,g.type==="array"?"array":"map"),children:"+"}):c.jsx("button",{type:"button",className:"fs-doctree__icon",title:"Edit","aria-label":`Edit ${b}`,onClick:()=>a(e),children:"✎"}),c.jsx("button",{type:"button",className:"fs-doctree__icon fs-doctree__icon--danger",title:"Delete (shift-click to skip confirmation)","aria-label":`Delete ${b||"field"} (shift-click to skip confirmation)`,onClick:D=>void d(g,b,{shiftKey:D.shiftKey}),children:"🗑"})]})]}),x&&k?c.jsxs("ul",{className:"fs-doctree__children",children:[(m.childIds[e]??[]).map(D=>c.jsx(bg,{nodeId:D,depth:t+1,editor:n,registry:r,expanded:s,onToggle:i,editingId:o,setEditingId:a,newIdsRef:l,onAdd:u,onDelete:d,onCommitNeeded:h,onReferenceClick:f,updates:p},D)),c.jsx("li",{className:"fs-doctree__action-row fs-doctree__action-row--nested",children:c.jsxs("button",{type:"button",className:"fs-doctree__action",onClick:()=>u(e,g.type==="array"?"array":"map"),children:[c.jsx("span",{"aria-hidden":"true",children:"+"})," ",g.type==="array"?"Add item":"Add field"]})})]}):null]})}function VT({node:e,isNew:t,isArrayChild:n,tree:r,editor:s,registry:i,path:o,onCommitNeeded:a,onDone:l,onCancelNew:u}){const[d,h]=y.useState(e.key??""),[f,p]=y.useState(e.type),[m,g]=y.useState(e.value),[b,w]=y.useState(!1),x=n?void 0:d===""?"Field name is required":UT(r,e,d)?"Field name must be unique":void 0,v=f==="map"||f==="array"?void 0:Yy(f,m),_=!x&&!v,S=()=>{if(!_){w(!0);return}n||s.setKey(e.id,d),f!==e.type&&s.setType(e.id,f),f!=="map"&&f!=="array"&&s.setValue(e.id,m),a(),l()},k=()=>{t?u():l()},O=i[f]?.Edit,D=f!=="map"&&f!=="array"&&O?c.jsx(O,{value:m,path:o,error:b?v:void 0,onChange:E=>g(E)}):f==="map"||f==="array"?c.jsxs("span",{className:"fs-doctree__editnote",children:["Saves as an empty ",f," — add its children afterward."]}):null,R=c.jsxs("span",{className:"fs-doctree__editactions",children:[c.jsx("button",{type:"button",className:"fs-doctree__editsave",onClick:S,"aria-label":"Save field",children:"✓"}),c.jsx("button",{type:"button",className:"fs-doctree__editcancel",onClick:k,"aria-label":"Cancel edit",children:"✕"})]}),j=c.jsx("select",{className:"fs-doctree__edittype",value:f,onChange:E=>{const $=E.target.value;p($),$!=="map"&&$!=="array"&&$!==f&&g(WT($))},"aria-label":"Field type",children:(t?FT:gg).map(E=>c.jsx("option",{value:E,children:E},E))});return c.jsxs("div",{className:"fs-doctree__editrow",onKeyDown:E=>{E.key==="Enter"&&!E.target.matches("textarea")?(E.preventDefault(),S()):E.key==="Escape"&&(E.preventDefault(),k())},children:[n?null:c.jsxs("div",{className:"fs-doctree__editline",children:[c.jsx("input",{type:"text",className:"fs-doctree__editkey",value:d,placeholder:"Field name",autoFocus:t,onChange:E=>h(E.target.value),onBlur:()=>w(!0),"aria-label":"Field name","aria-invalid":b&&x?"true":void 0}),j]}),c.jsxs("div",{className:"fs-doctree__editline",children:[n?j:null,D,R]}),b&&x?c.jsx("span",{className:"fs-doctree__editerr",children:x}):null]})}function WT(e){switch(e){case"string":return"";case"number":return 0;case"boolean":return!1;default:return null}}function wg({firestore:e,documentRef:t,listSubcollections:n,onSubcollectionClick:r}){const{subcollections:s,isLoading:i}=WD({firestore:e,documentRef:t,listSubcollections:n});return!i&&s.length===0?null:c.jsxs("section",{"data-pyric-ui":"fs-doctree-subcollections","data-pyric-loading":i?"":void 0,children:[c.jsx("div",{className:"fs-doctree__subhead",children:"Subcollections"}),c.jsx("ul",{className:"fs-doctree__sublist",children:s.map(o=>c.jsx("li",{children:r?c.jsxs("button",{type:"button",className:"fs-doctree__subrow",onClick:()=>r(o),"aria-label":`Open subcollection ${o.id}`,children:[c.jsx("span",{children:o.id}),c.jsx("span",{className:"fs-doctree__subtype",children:"subcollection"}),c.jsx("span",{"aria-hidden":"true",children:"›"})]}):c.jsxs("div",{className:"fs-doctree__subrow",children:[c.jsx("span",{children:o.id}),c.jsx("span",{className:"fs-doctree__subtype",children:"subcollection"})]})},o.path))})]})}function zT(e){return e.split("/").filter(Boolean).length%2===0}function vg(e,t){async function*n(s,i,o=!1){const a=await t.listSubcollections(s.path);for(const l of a)yield*r(e.collection(s,l),i);o||(await e.deleteDoc(s),i.n++,yield{deletedCount:i.n,done:!1})}async function*r(s,i){const o=await t.listDocuments(s.path);for(const a of o){const l=a.path.split("/").pop();l&&(yield*n(e.doc(s,l),i,a.phantom===!0))}}return{async*start(s){const i={n:0};zT(s.path)?yield*n(s,i):yield*r(s,i),yield{deletedCount:i.n,done:!0}}}}async function xg(e,t){for await(const n of e.start(t))if(n.done)return}async function _g({confirm:e,ref:t,api:n,recursiveImpl:r}){let s=!1;return await e({title:`Delete document "${t.id}"?`,body:c.jsxs("label",{className:"fs-delete-recursive",children:[c.jsx("input",{type:"checkbox",onChange:o=>{s=o.currentTarget.checked}}),c.jsx("span",{children:"Also delete subcollections recursively. Leave this off to keep nested data."})]}),destructive:!0,confirmLabel:"Delete document"})?(s?await xg(r,t):await n.deleteDoc(t),!0):!1}function HT(e){const t=e.exists;return typeof t=="function"?t.call(e):t}async function KT(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 GT(e){return{id:e.id,ref:e,data:()=>{},__pyricPhantom:!0}}function uf(e){return e.__pyricPhantom===!0}function JT(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 YT({handles:e}){const{target:t,navigate:n}=qi(),r=e.adminFirestore,s=Fc(),i=y.useMemo(()=>t?.view==="firestore"?t.path:[],[t]),o=y.useCallback(_=>{const S=typeof _=="function"?_(i):_;n({view:"firestore",path:S})},[n,i]),a=(_,S)=>o(k=>[...k.slice(0,_+1),S]),[l,u]=y.useState(null),d=y.useCallback(async({collectionId:_,docId:S,data:k})=>{if(!l||!_)return;const N=l.parentDocPath,O=N?s.collection(s.doc(r,N),_):s.collection(r,_);await KT(s,O,S,k);const D=N?`${N}/${_}`:_;n({view:"firestore",path:Wr(`${D}/${S}`)})},[s,r,l,n]),h=[c.jsx(ZT,{api:s,firestore:r,collectionIds:e.listRootCollections(),onSelect:_=>o([{kind:"collection",id:_,path:_}]),onStartCollection:()=>u({parentDocPath:null})},"__root__"),...i.map((_,S)=>_.kind==="collection"?c.jsx(eM,{api:s,firestore:r,handles:e,collectionPath:_.path,selectedId:i[S+1]?.id??null,onSelect:k=>a(S,{kind:"document",id:k.id,path:k.path}),onCollectionDeleted:()=>o(k=>k.slice(0,S))},_.path):c.jsx(tM,{api:s,firestore:r,handles:e,docPath:_.path,onOpenSubcollection:k=>a(S,{kind:"collection",id:k.id,path:k.path}),onReferenceClick:k=>n({view:"firestore",path:Wr(k.path)}),onStartCollection:()=>u({parentDocPath:_.path}),onDeleted:()=>o(k=>k.slice(0,S))},_.path))],{ref:f,size:p}=Bi(AT),{startIndex:m,visibleCount:g,emptySlots:b}=$T(h.length,p),w=h.slice(m,m+g),x=i.length===0?"Select a collection":i[i.length-1]?.kind==="collection"?"Select a document":null,v=[...w,...Array.from({length:b},(_,S)=>c.jsx(XT,{hint:S===0?x:null},`__empty_${S}__`))];return y.useEffect(()=>{if(p==="wide")return;const _=f.current;if(!_)return;const S=document.activeElement;if(S&&S!==document.body&&_.contains(S))return;const k=_.querySelector(".fs-columns > .fs-col:last-child");k&&(k.tabIndex=-1,k.focus({preventScroll:!0}))},[i.length,p]),c.jsx(Uc,{children:c.jsxs("div",{ref:f,"data-pyric-ui":"fs-browser","data-fs-depth":i.length,"data-size":p,children:[c.jsx(QT,{path:i,onHome:()=>o([]),onJump:_=>o(S=>S.slice(0,_+1))}),c.jsx("div",{className:"fs-columns",children:v}),l?c.jsx(hg,{mode:"collection",parentPath:l.parentDocPath?`/${l.parentDocPath}`:"/",onCreate:d,onClose:()=>u(null)}):null]})})}function QT({path:e,onHome:t,onJump:n}){return c.jsxs("nav",{"data-pyric-ui":"fs-breadcrumb","aria-label":"Firestore path",children:[c.jsx("button",{type:"button",className:"fs-crumb",onClick:t,children:"home"}),e.map((r,s)=>c.jsxs(y.Fragment,{children:[c.jsx("span",{className:"fs-crumb-sep","aria-hidden":!0,children:"›"}),s===e.length-1?c.jsx("span",{className:"fs-crumb fs-crumb--current",children:r.id}):c.jsx("button",{type:"button",className:"fs-crumb",onClick:()=>n(s),children:r.id})]},r.path))]})}function XT({hint:e}){return c.jsx("section",{"data-pyric-ui":"fs-empty-col",className:"fs-pane fs-col fs-col--empty","aria-hidden":e?void 0:!0,children:e?c.jsx("p",{className:"fs-empty",children:e}):null})}function ZT({api:e,firestore:t,collectionIds:n,onSelect:r,onStartCollection:s}){const i=y.useMemo(()=>n.map(o=>e.collection(t,o)),[e,t,n]);return c.jsxs("section",{"data-pyric-ui":"fs-collections",className:"fs-pane fs-col",children:[c.jsxs("div",{className:"fs-phead",children:[c.jsx("span",{className:"fs-phead-title",children:"Collections"}),c.jsx("button",{type:"button",className:"fs-add",onClick:s,children:"+ New"})]}),c.jsx(PP,{collections:i,onSelect:o=>r(o.id),emptyState:c.jsx("p",{className:"fs-empty",children:"No collections yet. App or agent writes show up here."})})]})}function eM({api:e,firestore:t,handles:n,collectionPath:r,selectedId:s,onSelect:i,onCollectionDeleted:o}){const a=y.useMemo(()=>JT(e,t,r),[e,t,r]),{documents:l,isLoading:u,error:d,subscriptionGeneration:h,hasMore:f,loadMore:p,createDocument:m}=VD({collection:a,mode:"live"}),[g,b]=y.useState([]);y.useEffect(()=>{let j=!1;return Promise.resolve(n.listDocuments(r)).then(E=>{j||b(E.filter($=>$.phantom).map($=>$.path.split("/").pop()??""))}).catch(()=>{j||b([])}),()=>{j=!0}},[n,r,l]);const w=y.useMemo(()=>{const j=new Set(l.map(E=>E.id));return[...l,...g.filter(E=>E.length>0&&!j.has(E)).map(E=>GT(e.doc(t,`${r}/${E}`)))]},[l,g,e,t,r]),x=r.split("/").pop()??r,[v,_]=y.useState(null),[S,k]=y.useState(!1),N=Hn(),O=y.useMemo(()=>vg(e,n),[e,n]),D=y.useCallback(async j=>{_(null);try{await _g({confirm:N,ref:j,api:e,recursiveImpl:O})}catch(E){_(E instanceof Error?E:new Error(String(E)))}},[e,N,O]),R=y.useCallback(async()=>{if(await N({title:`Delete collection "${x}"?`,body:"This deletes every document in it (and their subcollections).",destructive:!0,confirmLabel:"Delete collection"})){_(null);try{await xg(O,a),o()}catch(E){_(E instanceof Error?E:new Error(String(E)))}}},[N,O,a,x,o]);return c.jsxs("section",{"data-pyric-ui":"fs-documents",className:"fs-pane fs-col",children:[c.jsxs("div",{className:"fs-phead",children:[c.jsx("span",{className:"fs-phead-title",children:x}),c.jsx("span",{className:"fs-phead-actions",children:c.jsx("button",{type:"button",className:"fs-add",onClick:()=>k(!0),children:"+ New"})}),c.jsx(pg,{items:[{label:"Delete collection",onSelect:()=>void R(),destructive:!0}]})]}),S?c.jsx(hg,{mode:"document",parentPath:`/${r}`,onCreate:async({docId:j,data:E})=>{const $=await m(j,E,{onExisting:"fail"});i($)},onClose:()=>k(!1)}):null,c.jsx(TP,{documents:w,isLoading:u,error:d,updateScope:`${r}:${h}`,hasMore:f,onLoadMore:p,onSelect:i,renderLabel:j=>{const E=j.ref;return c.jsx("span",{"data-pyric-selected":s===E.id?"":void 0,style:{display:"contents"},children:uf(j)?c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"fs-doc-phantom",children:j.id}),c.jsx("span",{className:"fs-sub fs-doc-phantom-hint",children:"missing"})]}):j.id})},renderRowAction:j=>{if(uf(j))return null;const E=j.ref;return c.jsx("button",{type:"button",className:"fs-doc-del",title:"Delete document","aria-label":`Delete ${E.id}`,onClick:$=>{$.stopPropagation(),D(E)},children:"×"})},emptyState:c.jsx("p",{className:"fs-empty",children:"No documents."})}),v?c.jsx("p",{className:"fs-empty fs-doc-del-err",children:v.message}):null]})}function tM({api:e,firestore:t,handles:n,docPath:r,onOpenSubcollection:s,onReferenceClick:i,onStartCollection:o,onDeleted:a}){const l=y.useMemo(()=>e.doc(t,r),[e,t,r]),{data:u,error:d,isLoading:h}=AD(l),f=y.useCallback(async(_,S)=>(await n.listSubcollections(S.path)).map(N=>e.collection(S,N)),[n,e]),p=Hn(),m=y.useMemo(()=>vg(e,n),[e,n]),[g,b]=y.useState(null),w=y.useCallback(async()=>{b(null);try{await _g({confirm:p,ref:l,api:e,recursiveImpl:m})&&a()}catch(_){b(_ instanceof Error?_:new Error(String(_)))}},[e,p,m,l,a]),x=y.useCallback(async()=>{await e.setDoc(l,{})},[e,l]),v=u!=null&&HT(u);return c.jsxs("section",{"data-pyric-ui":"fs-document",className:"fs-pane fs-col doc",children:[v?null:c.jsxs("div",{className:"fs-phead",children:[c.jsx("span",{className:"fs-phead-title",children:l.id}),c.jsx("span",{className:"fs-phead-actions",children:c.jsx("button",{type:"button",className:"fs-add",onClick:o,children:"+ Collection"})})]}),u&&v?c.jsx(qT,{snapshot:u,documentRef:l,firestore:t,listSubcollections:f,onReferenceClick:i,onSubcollectionClick:s,onStartCollection:o,onDeleteDocument:()=>void w(),onDeleteDocumentFields:x,onCommit:async _=>{await e.setDoc(l,_)}},r):d?c.jsx("p",{className:"fs-empty fs-doc-del-err",children:d.message}):h?c.jsx("p",{className:"fs-empty",children:"Loading document…"}):c.jsxs(c.Fragment,{children:[c.jsx("p",{className:"fs-empty",children:"This document does not exist."}),c.jsx(wg,{firestore:t,documentRef:l,listSubcollections:f,onSubcollectionClick:s})]}),g?c.jsx("p",{className:"fs-empty fs-doc-del-err",children:g.message}):null]})}const nM="block w-full text-sm text-soft-white";function rM({auth:e,focusUid:t}){const{users:n,totalCount:r,isLoading:s,error:i,filter:o,setFilter:a,updateUser:l}=Mi(e),[u,d]=y.useState(null);y.useEffect(()=>{t&&(d(t),a(t))},[t,a]);const h=n.find(f=>f.uid===u)??null;return c.jsxs("div",{className:"grid grid-cols-[1fr_320px] gap-4",children:[c.jsxs("section",{className:"min-w-0",children:[c.jsx("input",{value:o,onChange:f=>a(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"}),c.jsx($y,{users:n,isLoading:s,error:i,filter:o,onSelect:f=>d(f.uid),className:nM,emptyState:c.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:c.jsx("p",{className:"py-6 text-sm text-slate-gray",children:"No users match the filter."})}),c.jsxs("p",{className:"mt-2 text-xs text-slate-gray",children:[r," user(s) total"]})]}),c.jsx("section",{className:"min-w-0 border-l border-border pl-4",children:h?c.jsx(sM,{user:h,onSave:f=>l(h.uid,f)},h.uid):c.jsx("p",{className:"py-6 text-sm text-slate-gray",children:"Select a user to view and edit."})})]})}function sM({user:e,onSave:t}){const n=Ay({initial:e}),[r,s]=y.useState(null),[i,o]=y.useState(!1),a=()=>{s(null),o(!1);try{t(n.toUpdateRequest()),o(!0)}catch(l){s(l instanceof Error?l:new Error(String(l)))}};return c.jsxs("div",{"data-pyric-ui":"auth-editor",children:[c.jsx("h3",{className:"mb-3 truncate font-mono text-xs text-slate-gray",title:e.uid,children:e.uid}),c.jsxs("label",{className:"mb-3 block text-xs text-slate-gray",children:["Display name",c.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"})]}),c.jsxs("label",{className:"mb-3 block text-xs text-slate-gray",children:["Custom claims (JSON)",c.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?c.jsx("span",{className:"text-danger",children:n.errors.claims}):null]}),c.jsxs("label",{className:"mb-3 flex items-center gap-2 text-xs text-slate-gray",children:[c.jsx("input",{type:"checkbox",checked:n.fields.disabled,onChange:l=>n.setField("disabled",l.target.checked)}),"Disabled"]}),r?c.jsx("p",{className:"mb-2 text-xs text-danger",children:r.message}):null,i?c.jsx("p",{className:"mb-2 text-xs text-primary",children:"Saved."}):null,c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{type:"button",onClick:a,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"}),c.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 df(e){const t=de(e),n=t.lastIndexOf("/");return n===-1?"":t.slice(0,n)}function ff(e,t){return e===""?t:t===""?e:`${e}/${t}`}function hf(e){const t=e.lastIndexOf("/");return t===-1?e:e.slice(t+1)}const iM=[{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 oM(e){const t=Object.entries(e.customMetadata??{});return c.jsxs("dl",{"data-pyric-object-metadata":!0,children:[c.jsx("div",{"data-storage-meta-group":!0,children:"Metadata"}),iM.map(({key:n,label:r,value:s})=>{const i=s(e);return i===void 0?null:c.jsxs("div",{"data-pyric-metadata-field":n,children:[c.jsx("dt",{children:r}),c.jsx("dd",{children:i})]},n)}),t.length>0?c.jsx("div",{"data-storage-meta-group":!0,children:"Custom metadata"}):null,t.map(([n,r])=>c.jsxs("div",{"data-pyric-metadata-field":"customMetadata","data-pyric-metadata-key":n,children:[c.jsx("dt",{children:n}),c.jsx("dd",{children:r})]},`custom:${n}`))]})}function aM(){return c.jsx("svg",{"aria-hidden":!0,viewBox:"0 0 16 16",width:"13",height:"13",fill:"none",stroke:"currentColor",strokeWidth:"1.25",strokeLinejoin:"round",children:c.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 cM(){return c.jsxs("svg",{"aria-hidden":!0,viewBox:"0 0 16 16",width:"13",height:"13",fill:"none",stroke:"currentColor",strokeWidth:"1.25",strokeLinejoin:"round",children:[c.jsx("path",{d:"M4.25 1.75h5l3 3v9.5h-8z"}),c.jsx("path",{d:"M9.25 1.75v3h3"})]})}function lM(e){const t=e.kind==="folder";return c.jsxs(c.Fragment,{children:[c.jsxs("span",{className:"storage__cell-name",children:[c.jsx("span",{className:"storage__ic","aria-hidden":!0,children:t?c.jsx(aM,{}):c.jsx(cM,{})}),c.jsx("span",{className:"storage__nm",children:e.name}),t?c.jsx("span",{"aria-hidden":!0,className:"storage__chev",children:"›"}):null]}),c.jsx("span",{className:"storage__cell-type",children:t?"folder":"file"}),c.jsx("span",{className:"storage__cell-size"}),c.jsx("span",{className:"storage__cell-updated"})]})}function uM({storage:e,focusTarget:t}){const n=qi(),r=t.kind==="object"?de(t.path):null,s=t.kind==="prefix"?de(t.path):r?df(r):"",i=y.useCallback(j=>{const E=de(j);n.navigate(E?{view:"storage",kind:"prefix",path:E}:{view:"storage",kind:"root"})},[n.navigate]),o=zP({path:s,onPathChange:i}),a=j=>{n.navigate({view:"storage",kind:"object",path:de(j)})},l=WP(e,o.path),u=KP(),d=eT(e),[h,f]=y.useReducer(dT,cg),p=rT(e,{path:o.path,list:l,onComplete:j=>f({type:"materialize",path:df(j.fullPath)})});y.useEffect(()=>{if(l.status==="success")for(const j of l.entries)j.kind==="folder"&&af(h,j.fullPath)&&f({type:"materialize",path:j.fullPath})},[l.status,l.entries,h]);const[m,g]=y.useState(!1),[b,w]=y.useState(""),[x,v]=y.useState(null),_=y.useRef(null),S=y.useMemo(()=>{const j=fT(h,o.path).filter(C=>!l.entries.some(I=>I.kind==="folder"&&I.name===C));if(j.length===0)return l.entries;const E=j.map(C=>{const I=ff(o.path,C);return{kind:"folder",name:C,fullPath:I,ref:{fullPath:I,name:C}}});return[...[...l.entries.filter(C=>C.kind==="folder"),...E].sort((C,I)=>C.name<I.name?-1:C.name>I.name?1:0),...l.entries.filter(C=>C.kind==="object")]},[l.entries,h,o.path]),k=S.length>0&&S.every(j=>u.isSelected(j.fullPath)),N=j=>{const E=new Set(S.map(C=>C.name)),$=uT(j.map(C=>C.relativePath),E);p.upload(j.map((C,I)=>({path:$[I],data:C.file})))},O=j=>{j.preventDefault();const E=hT(b);if(E){v(E);return}const $=ff(o.path,de(b));f({type:"create",path:$}),o.setPath($),w(""),v(null),g(!1)};y.useEffect(()=>u.clear(),[o.path,u.clear]);const D=p.tasks.filter(j=>j.status==="error"),R=d.verdictFor(o.path);return c.jsx(kT,{children:c.jsx(Uc,{children:c.jsxs("div",{className:"storage",children:[c.jsxs("div",{className:"storage__sub",children:[c.jsx(sT,{path:o.path,rootLabel:"files",onNavigate:o.setPath}),c.jsx("div",{className:"storage__actions",children:u.size>0?c.jsxs(c.Fragment,{children:[c.jsxs("span",{className:"studio-selection-count",children:[u.size," selected"]}),c.jsx(ET,{storage:e,entries:u.selected,list:l,gate:d,className:"studio-selection-delete",onDeleted:j=>{for(const E of u.selected)E.kind==="folder"&&j.deleted.includes(E.fullPath)&&f({type:"discard",path:E.fullPath});r&&u.selected.some(E=>E.kind==="object"?E.fullPath===r:r.startsWith(`${E.fullPath}/`))&&o.setPath(o.path),u.clear(),l.refresh()},onFailed:j=>{const E=new Set(j.failed.map($=>$.fullPath));u.selectAll(u.selected.filter($=>E.has($.fullPath))),l.refresh()}}),c.jsx("button",{type:"button",className:"storage__action",onClick:u.clear,children:"Clear selection"})]}):c.jsxs(c.Fragment,{children:[c.jsx("button",{type:"button",className:"storage__action","aria-expanded":m,onClick:()=>{g(j=>!j),v(null)},children:"New folder"}),c.jsx("button",{type:"button",className:"storage__action storage__action--upload",onClick:()=>_.current?.click(),children:"Upload files"}),c.jsx("input",{ref:_,type:"file",multiple:!0,hidden:!0,onChange:j=>{const E=Array.from(j.currentTarget.files??[]);E.length>0&&N(E.map($=>({file:$,relativePath:$.name}))),j.currentTarget.value=""}})]})})]}),m?c.jsxs("form",{className:"storage__newfolder",onSubmit:O,children:[c.jsx("input",{autoFocus:!0,className:"storage__newfolder-input",placeholder:"folder or nested/path/of/folders","aria-label":"New folder name",value:b,onChange:j=>{w(j.currentTarget.value),v(null)},onKeyDown:j=>{j.key==="Escape"&&g(!1)}}),c.jsx("button",{type:"submit",className:"storage__newfolder-btn",children:"Create"}),x?c.jsx("span",{className:"storage__newfolder-err",role:"alert",children:x}):c.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,D.length>0?c.jsxs("p",{className:"storage__upload-err",role:"alert",children:[D.length===1?`Upload failed: ${hf(D[0].fullPath)} — ${D[0].error?.message??"error"}`:`${D.length} uploads failed: ${D.map(j=>hf(j.fullPath)).join(", ")}`,c.jsx("button",{type:"button",className:"storage__upload-err-dismiss",onClick:p.clearCompleted,children:"Dismiss"})]}):null,c.jsxs("div",{className:"storage__body","data-storage-level":r?"inspector":"browser",children:[c.jsxs(aT,{className:"storage__browser",onFiles:N,disabled:!R.upload,disabledReason:R.reasons.write.join("; "),children:[c.jsxs("div",{className:"storage__lhead",children:[c.jsx("label",{className:"storage__select-all",title:"Select all in this folder",children:c.jsx("input",{type:"checkbox","aria-label":"Select all in this folder",checked:k,onChange:j=>j.currentTarget.checked?u.selectAll(S):u.clear()})}),c.jsx("span",{children:"name"}),c.jsx("span",{children:"type"}),c.jsx("span",{children:"size"}),c.jsx("span",{children:"updated"})]}),c.jsx(iT,{entries:S,status:l.status,error:l.error,gate:d,selectedPath:r??void 0,renderEntry:lM,renderRowAction:j=>c.jsx("label",{className:"storage__select-row",title:`Select ${j.name}`,children:c.jsx("input",{type:"checkbox","aria-label":`Select ${j.name}`,checked:u.isSelected(j.fullPath),onChange:()=>u.toggle(j)})}),onNavigate:o.enter,onSelect:j=>a(j.fullPath),emptyState:c.jsx("p",{className:"storage__empty",children:af(h,o.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."})}),c.jsxs("div",{className:"storage__dropcue","aria-hidden":!0,children:["Drop to upload to /",o.path||""]})]}),c.jsx("div",{className:"storage__inspector",children:r?c.jsxs(c.Fragment,{children:[c.jsx("button",{type:"button",className:"storage__back",onClick:()=>o.setPath(o.path),"aria-label":"Back to files",children:"‹ Files"}),c.jsx(_T,{storage:e,path:r,renderMetadata:oM})]}):c.jsx("p",{className:"storage__inspector-hint",children:"Select an object to inspect its preview and metadata."})})]})]})})})}function dM({view:e}){const t=e==="firestore"?"Firestore":e==="auth"?"Auth":"Storage";return c.jsxs("div",{"data-pyric-ui":"data-pending",className:"flex flex-col items-center justify-center gap-2 py-16 text-center",children:[c.jsx("span",{className:"rounded-full border border-border px-3 py-1 text-xs uppercase tracking-wide text-slate-gray",children:"Local backend pending"}),c.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 Sg({view:e}){const{target:t}=qi(),n=Rt(),r=n.status==="ready"?n.handles.auth:null;return c.jsx("div",{"data-pyric-ui":"data-feature",children:n.status!=="ready"||!r?c.jsx(dM,{view:e}):n.authApi?c.jsx(Cy,{value:n.authApi,children:c.jsx(pf,{view:e,handles:n.handles,auth:r,target:t,firestoreApi:n.firestoreApi,storageApi:n.storageApi})}):c.jsx(pf,{view:e,handles:n.handles,auth:r,target:t,firestoreApi:n.firestoreApi,storageApi:n.storageApi})})}function pf({view:e,handles:t,auth:n,target:r,firestoreApi:s,storageApi:i}){const{users:o}=Mi(n),a=y.useMemo(()=>new Set(o.map(l=>l.uid)),[o]);switch(e){case"firestore":{const l=c.jsx(YT,{handles:t,knownUids:a});return s?c.jsx(ID,{value:s,children:l}):l}case"auth":return c.jsx(rM,{auth:n,focusUid:r?.view==="auth"?r.uid:null});case"storage":{const l=c.jsx(uM,{storage:t.storage,focusTarget:r?.view==="storage"?r:{kind:"root"}});return i?c.jsx(VP,{value:i,children:l}):l}}}function fM(){return c.jsx(Sg,{view:"firestore"})}function hM(){return c.jsx(Sg,{view:"storage"})}function pM(e,t){const n=new Set(t.map(r=>r.uid));return new Set([...e].filter(r=>n.has(r)))}async function mM(e,t){const n=[];for(const r of e)try{await t(r.uid)}catch{n.push(r.uid)}return n}function yM(e){const[t,n]=y.useState(()=>new Set);y.useEffect(()=>{n(s=>{const i=pM(s,e);return i.size===s.size&&[...i].every(o=>s.has(o))?s:i})},[e]);const r=y.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 o=new Set(i);return o.has(s)?o.delete(s):o.add(s),o})},selectAll(s){n(s?new Set(e.map(i=>i.uid)):new Set)},replace(s){n(new Set(s))},clear(){n(new Set)}}}function gM({users:e,filter:t,onDelete:n,onComplete:r}){const s=Hn(),[i,o]=y.useState(!1),[a,l]=y.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;o(!0),l(null);const f=await mM(e,n);o(!1),l(f.length>0?`Could not delete ${f.length} selected user(s).`:null),r(f)};return c.jsxs(c.Fragment,{children:[c.jsx("button",{type:"button",className:"studio-selection-delete",disabled:i,onClick:()=>void u(),children:i?"Deleting…":"Delete"}),a?c.jsx("span",{className:"auth-sub__error",children:a}):null]})}function kg(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 jg(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 bM(e){const t=e.isAnonymous&&!e.email,n=e.email??e.phoneNumber??(t?"anonymous":e.uid);return c.jsxs("span",{className:t?"auth-ident auth-ident--anon":"auth-ident",children:[c.jsx("span",{className:"auth-ident__primary",title:n,children:n}),c.jsx("span",{className:"auth-ident__uid",title:e.uid,children:e.uid})]})}function wM({auth:e}={}){const t=Kt(),n=Rt(),r=e??(n.status==="ready"?n.handles.auth:null),s=n.status==="ready"?n.authApi:void 0;if(!r)return c.jsx("div",{className:"auth-surface","data-pyric-ui":"auth-surface",children:c.jsx(kM,{status:t.status})});const i=c.jsx(Uc,{children:c.jsx(vM,{auth:r})});return s?c.jsx(Cy,{value:s,children:i}):i}function vM({auth:e}){const{users:t,totalCount:n,isLoading:r,error:s,filter:i,setFilter:o,createUser:a,updateUser:l,deleteUser:u}=Mi(e),d=qi(),h=d.target?.view==="auth"?d.target.uid:null,f=w=>d.navigate({view:"auth",uid:w}),p=y.useMemo(()=>t.find(w=>w.uid===h)??null,[t,h]),[m,g]=y.useState(!1),b=yM(t);return c.jsxs("div",{className:"auth-surface","data-pyric-ui":"auth-surface",children:[c.jsxs("div",{className:"auth-sub",children:[c.jsxs("span",{className:"auth-sub__h",children:["users ",c.jsxs("span",{className:"auth-sub__n",children:["· ",n]})]}),c.jsx("input",{className:"auth-sub__filter",value:i,onChange:w=>o(w.target.value),placeholder:"filter users…","aria-label":"Filter users"}),c.jsx("div",{className:"auth-sub__right",children:b.selectedUsers.length>0?c.jsxs(c.Fragment,{children:[c.jsxs("span",{className:"studio-selection-count",children:[b.selectedUsers.length," selected"]}),c.jsx(gM,{users:b.selectedUsers,filter:i,onDelete:w=>Promise.resolve(u(w)),onComplete:w=>{b.replace(w),h&&!w.includes(h)&&f(null)}}),c.jsx("button",{type:"button",className:"auth-sub__clear",onClick:b.clear,children:"Clear selection"})]}):c.jsx("button",{type:"button",className:"auth-sub__add",onClick:()=>{g(!0),f(null)},children:"Add user"})})]}),c.jsxs("div",{className:"auth-body","data-auth-level":p||m?"detail":"list",children:[c.jsx("div",{className:"auth-list",children:c.jsx($y,{users:t,isLoading:r,error:s,filter:i,onSelect:w=>{g(!1),f(w.uid)},renderIdentifier:bM,formatCreatedAt:jg,formatLastLoginAt:kg,renderSelectionHeader:c.jsx("label",{className:"auth-select",title:"Select all shown users",children:c.jsx("input",{type:"checkbox","aria-label":"Select all shown users",checked:b.allVisibleSelected,onChange:w=>b.selectAll(w.currentTarget.checked)})}),renderSelection:w=>c.jsx("label",{className:"auth-select",title:`Select ${w.uid}`,children:c.jsx("input",{type:"checkbox","aria-label":`Select ${w.uid}`,checked:b.isSelected(w.uid),onChange:()=>b.toggle(w.uid)})}),emptyState:c.jsx("p",{className:"auth-zero",children:"No users yet. Sign-ins from the app, agent-seeded users, and “Add user” all land here."}),noResultsState:c.jsxs("p",{className:"auth-zero",children:["No users match “",i,"”."]})})}),c.jsx("div",{className:"auth-detail",children:m?c.jsx(xM,{onCancel:()=>g(!1),onCreate:async w=>{const x=await Promise.resolve(a(w));g(!1),f(x.uid)}}):p?c.jsxs(c.Fragment,{children:[c.jsx("button",{type:"button",className:"auth-back",onClick:()=>f(null),"aria-label":"Back to users",children:"‹ Users"}),c.jsx(SM,{user:p,onSave:w=>{w.mode==="edit"&&l(w.uid,w.request)},onProvidersChange:async w=>{await Promise.resolve(l(p.uid,{providerUserInfo:w}))},onDelete:()=>{u(p.uid),f(null)}},p.uid)]}):c.jsx("div",{className:"auth-detail__empty",children:c.jsx("p",{className:"auth-zero",children:"Select a user to view and edit."})})})]})]})}function xM({onCreate:e,onCancel:t}){const[n,r]=y.useState(null),s=i=>{i.mode==="create"&&(r(null),e(i.request).catch(o=>{r(o instanceof Error?o:new Error(String(o)))}))};return c.jsxs("div",{className:"auth-editor","data-pyric-ui":"auth-create-user",children:[c.jsxs("div",{className:"auth-editor__head",children:[c.jsx("div",{className:"auth-editor__who",children:"New user"}),c.jsx("div",{className:"auth-editor__meta",children:"Created without signing in — admin semantics, like the emulator’s add-user flow."})]}),c.jsx(Dy,{onSubmit:s,onCancel:t,submitLabel:"Create user",children:n?c.jsx("p",{className:"auth-save auth-save--error",role:"alert",children:n.message}):null})]})}const mf=[...Ih];function _M({user:e,onChange:t}){const[n,r]=y.useState(null),[s,i]=y.useState(""),o=e.providerUserInfo.map(p=>p.providerId),a=o.includes("password"),l=o.filter(p=>p!=="password"),u=l.filter(p=>!mf.includes(p)),d=p=>{r(null),t(p.map(m=>({providerId:m}))).catch(m=>{r(m instanceof Error?m:new Error(String(m)))})},h=(p,m)=>{d(m?[...l,p]:l.filter(g=>g!==p))},f=()=>{const p=s.trim();p&&(i(""),!l.includes(p)&&d([...l,p]))};return c.jsxs("section",{className:"auth-providers-editor","aria-label":"Sign-in providers",children:[c.jsx("div",{className:"auth-group",children:"Sign-in providers"}),c.jsx("div",{className:"auth-providers-editor__list",children:[...mf,...u].map(p=>c.jsxs("label",{className:"auth-provider-row","data-pyric-provider-id":p,children:[c.jsx("input",{type:"checkbox",checked:l.includes(p),onChange:m=>h(p,m.target.checked)}),c.jsx("span",{className:"auth-provider-row__label",children:mi(p)}),c.jsx("span",{className:"auth-provider-row__id",children:p})]},p))}),a||e.isAnonymous?c.jsx("p",{className:"auth-providers-editor__derived",children:a?"Password is linked by the password credential above.":"Anonymous — the provider lives on the token, not the record."}):null,c.jsx("div",{className:"auth-provider-custom",children:c.jsxs("label",{className:"auth-provider-custom__field",children:[c.jsx("span",{className:"auth-provider-custom__label",children:"Custom provider ID"}),c.jsxs("span",{className:"auth-provider-custom__row",children:[c.jsx("input",{type:"text",value:s,placeholder:"oidc.my-provider",onChange:p=>i(p.target.value),onKeyDown:p=>{p.key==="Enter"&&(p.preventDefault(),f())}}),c.jsx("button",{type:"button",onClick:f,disabled:!s.trim(),children:"Link"})]})]})}),n?c.jsx("p",{className:"auth-save auth-save--error",role:"alert",children:n.message}):null]})}function SM({user:e,onSave:t,onProvidersChange:n,onDelete:r}){const[s,i]=y.useState(null),[o,a]=y.useState(!1),l=h=>{i(null),a(!1);try{t(h),a(!0)}catch(f){i(f instanceof Error?f:new Error(String(f)))}},u=jg(e.createdAt),d=kg(e.lastLoginAt);return c.jsxs("div",{className:"auth-editor","data-pyric-user-disabled":e.disabled?"":void 0,children:[c.jsxs("div",{className:"auth-editor__head",children:[c.jsxs("div",{className:"auth-editor__who",children:[e.email??(e.isAnonymous?"anonymous":e.uid),e.disabled?c.jsx("span",{className:"auth-tag-off",children:"disabled"}):null]}),c.jsxs("div",{className:"auth-editor__uid",children:["uid · ",e.uid]}),c.jsxs("div",{className:"auth-editor__meta",children:["created ",u," · signed in ",d]})]}),c.jsx(_M,{user:e,onChange:n}),c.jsxs(Dy,{initial:e,onSubmit:l,submitLabel:"Save",children:[s?c.jsx("p",{className:"auth-save auth-save--error",role:"alert",children:s.message}):null,o?c.jsx("p",{className:"auth-save auth-save--ok",children:"Saved."}):null]},e.uid),c.jsx("div",{className:"auth-editor__foot",children:c.jsx(J$,{user:e,onDelete:r,className:"auth-del"})})]})}function kM({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 c.jsx("div",{className:"auth-detail__empty","data-pyric-ui":"auth-surface-empty",children:c.jsx("p",{className:"auth-zero",children:t})})}function jM(e){return e.operationContext.source.kind==="studio"}function EM(e,t){return t?e.filter(n=>!jM(n)):[...e]}const CM=["all","allow","deny","proof-unsupported","bypassed"];function Kn(e){return e.rulesDisposition.kind==="bypassed"?"bypassed":Pc(e)?"proof-unsupported":e.rulesDisposition.kind==="evaluated"?e.rulesDisposition.verdict:null}function NM(e,t){return t==="all"?[...e]:e.filter(n=>Kn(n)===t)}function $o(e){return e.rulesDisposition.kind==="evaluated"}function yf(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}}function RM(e){return e.filter(t=>{const n=Kn(t);return n==="allow"||n==="deny"})}function IM(e,t){return e.filter(n=>n.at>=t.start&&n.at<t.end&&Kn(n)==="proof-unsupported").length}function Eg(e){return e==="proof-unsupported"?"Query proof unsupported":e}const Wa="inspect";function Cg(e){const t=e[Wa];return t||null}function Ng(e,t){const{[Wa]:n,...r}=e;return t?{...r,[Wa]:t}:r}function AM(e,t){return Ng(e,Cg(e)===t?null:t)}const OM=y.lazy(()=>Fp(()=>import("./RulesCodeEditor.kBYcclwV.js"),__vite__mapDeps([0,1,2])));function Rg(e){return c.jsx(y.Suspense,{fallback:c.jsx($M,{value:e.value,minHeightRem:e.minHeightRem}),children:c.jsx(OM,{...e})})}function $M({value:e,minHeightRem:t=14}){return c.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 Ig({denial:e,rulesSource:t}){const n=UO(e);let r="denied",s="deny";return Pc(e)?(r="Query proof unsupported",s="proof-unsupported"):e.unsupported&&(r="unsupported",s="unsupported"),c.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:[c.jsxs("section",{children:[c.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.result==="allow"?c.jsx(Pa,{kind:"allow",className:"rounded bg-primary/15 px-2 py-0.5 text-xs font-semibold uppercase text-primary",children:"allowed"}):c.jsx(Pa,{kind:s,className:"rounded bg-danger/15 px-2 py-0.5 text-xs font-semibold uppercase text-danger",children:r}),c.jsxs("span",{className:"font-mono text-sm text-soft-white",children:[e.service!=="firestore"?`${e.service} · `:"",e.method," ",e.path]})]}),c.jsx("p",{className:"text-sm leading-relaxed text-soft-white",children:n.headline})]}),n.noEvaluation?c.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."}):c.jsxs(c.Fragment,{children:[c.jsx(DM,{denial:e,exp:n,rulesSource:t}),c.jsx(UM,{denial:e})]}),c.jsx(FM,{denial:e})]})}function DM({denial:e,exp:t,rulesSource:n}){const r=t.engine==="rtdb",s=t.engine==="storage";return r?c.jsx(VM,{denial:e,exp:t,rulesSource:n},e.id):s?c.jsx(HM,{exp:t}):c.jsx(LM,{denial:e,exp:t,rulesSource:n})}function PM(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 o=JSON.parse(i);return Array.isArray(o)?o:null}catch{return null}}function TM(e){const n=e.indexOf("// @pyric-source-map:");return n!==-1?e.slice(0,n).trimEnd():e}function MM(e,t){if(e===void 0||t===void 0)return t;const s=PM(e);if(s!==null){const o=s.find(l=>l.authoredLine===t);if(o!==void 0)return o.generatedLine}return t}function LM({denial:e,exp:t,rulesSource:n}){const r=Tc(e),s=r?.rule?.line??e.evaluatedRule?.line,i=MM(n,s),o=n!==void 0?TM(n):void 0,a=e.result==="allow",l=!!(o&&o.trim().length>0);return c.jsxs(kt,{label:r?`query proof — ${t.ruleNode}`:t.implicitDeny||!t.ruleNode?"matched rule":`matched rule — ${t.ruleNode}${s?` · line ${s}`:""}`,children:[r?.predicate?c.jsxs("div",{className:"mb-3 text-sm text-slate-gray",children:[c.jsxs("p",{children:["Unsupported predicate",r.predicate.citation?` · ${r.predicate.citation}`:""]}),c.jsx("pre",{className:"overflow-auto font-mono text-xs",children:r.predicate.expression})]}):null,l?c.jsx(Rg,{value:o,readOnly:!0,markLine:i,markKind:a?"allow":"deny",minHeightRem:12,ariaLabel:r?"Deployed firestore.rules — the rule Pyric could not prove is marked":`Deployed firestore.rules — the ${a?"allowing":"denying"} rule is marked`}):c.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:[...r?.rule?.expression?[r.rule.expression]:[],...t.ruleLines,...t.otherLines].join(`
|
|
142
|
-
`)||"(no trace)"})]})}function
|
|
143
|
-
`)||"(no trace)"})]})}function kt({label:e,children:t}){return c.jsxs("div",{className:"flex flex-col gap-1",children:[c.jsx("span",{className:"text-[0.65rem] font-semibold uppercase tracking-wider text-slate-gray",children:e}),t]})}function KM(e="firestore"){const t=Kt(),n=t.status==="ready",[r,s]=y.useState({});return y.useEffect(()=>{if(n)return;let i=!0;return fetch("/__pyric/init.json").then(o=>o.ok?o.json():null).then(o=>{if(!i||!o||typeof o!="object")return;const l={};typeof o.rules=="string"&&(l.firestore=o.rules),o.databaseRules!==void 0&&o.databaseRules!==null&&(typeof o.databaseRules=="string"?l.rtdb=o.databaseRules:l.rtdb=JSON.stringify(o.databaseRules,null,2)),typeof o.storageRules=="string"&&(l.storage=o.storageRules),s(l)}).catch(()=>{}),()=>{i=!1}},[n]),y.useMemo(()=>{const i=t.status==="ready",o=e==="database"?"rtdb":e;if(!i){const a=r[o];return a!==void 0?a:""}try{if(o==="rtdb"){const u=fy(t.handles.sandbox);return u!=null?JSON.stringify(u,null,2):""}return Gr(t.handles.sandbox).getRules()}catch{return""}},[t,r,e])}function gf({eventId:e,onClose:t}){const r=XO().find(o=>o.id===e),s=r?.service??"firestore",i=KM(s);return r?c.jsxs("div",{"data-pyric-ui":"traffic-rules-inspector",className:"traffic__inspector",children:[c.jsxs("div",{className:"traffic__inspector-bar",children:[c.jsx("span",{className:"traffic__inspector-title",children:"rules inspector"}),c.jsx("button",{type:"button",className:"traffic__inspector-close",onClick:t,"aria-label":"Close rules inspector (Esc)",children:"close (esc)"})]}),c.jsx(Ig,{denial:r,rulesSource:i})]}):c.jsxs("div",{"data-pyric-ui":"traffic-inspect-missing",className:"traffic__inspector",children:[c.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."}),c.jsx("button",{type:"button",className:"traffic__inspector-close",onClick:t,children:"Back to the log"})]})}const GM=new Intl.NumberFormat,JM={reads:"read operations",writes:"writes",deletes:"deletes"},YM={allows:"allowed requests",denies:"denied requests"};function bf(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 wf(e){return e&&`${e[0].toUpperCase()}${e.slice(1)}`}function $g(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=`${GM.format(n)} observed ${n===1?t.singular:t.plural}`,o=u=>t.labels[u.key]??u.label.toLowerCase();if(s.length>1){const u=s.map(o);return{total:n,headline:i,finding:s.length===e.length?`${t.evenSplitPrefix} ${bf(u)}.`:`${wf(bf(u))} tied for the largest share of ${t.subject} in this window.`}}const a=s[0],l=Math.round(a.total/n*100);return{total:n,headline:i,finding:`${wf(o(a))} accounted for ${l}% of ${t.subject} in this window.`}}function QM(e){return $g(e,{labels:JM,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 XM(e){return $g(e,{labels:YM,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 ZM=new Intl.NumberFormat,eL=new Intl.DateTimeFormat(void 0,{hour:"numeric",minute:"2-digit"});function vf(e){return ZM.format(e)}function ar(e){return eL.format(e)}function tL(e){return Kn(e)==="bypassed"}function nL(e){return e.every(t=>t.total===0)}function Dg({eyebrow:e,story:t,series:n,points:r,window:s,emptyLabel:i,evidenceTitle:o,source:a,methodology:l}){const[u,d]=y.useState(()=>new Set(n.map(f=>f.key))),h=y.useCallback(f=>{d(p=>{const m=new Set(p);return m.has(f)?m.delete(f):m.add(f),m})},[]);return c.jsxs("section",{className:"traffic__metric-panel traffic__metric-panel--journal","data-pyric-ui":"traffic-metric-panel",children:[c.jsxs("header",{className:"traffic__metric-story",children:[c.jsx("p",{className:"traffic__metric-eyebrow",children:e}),c.jsx("h3",{className:"traffic__metric-headline",children:t.headline}),c.jsx("p",{className:"traffic__metric-finding",children:t.finding})]}),c.jsx(Bc,{series:n,visible:u,onToggle:h,formatValue:vf,className:`traffic__metric-cards traffic__metric-cards--journal traffic__metric-cards--${n.length}`}),nL(n)?c.jsx("p",{className:"traffic__empty",children:i}):c.jsxs("div",{className:"traffic__metric-evidence",children:[c.jsxs("div",{className:"traffic__metric-evidence-header",children:[c.jsx("h4",{children:o}),c.jsxs("span",{children:[ar(s.start),"–",ar(s.end)]})]}),c.jsx(By,{points:r,series:n,visible:u,omitZeroSeries:!0,formatValue:vf,formatTime:ar,className:"traffic__chart traffic__chart--journal"}),c.jsxs("div",{className:"traffic__metric-axis","aria-hidden":"true",children:[c.jsx("span",{children:ar(s.start)}),c.jsx("span",{children:ar(s.end)})]})]}),c.jsxs("footer",{className:"traffic__metric-footer",children:[c.jsx("p",{className:"traffic__metric-source",children:a}),c.jsxs("details",{className:"traffic__metric-methodology",children:[c.jsx("summary",{children:"How this is counted"}),c.jsx("div",{children:l})]})]})]})}function rL({events:e,window:t}){const n=y.useMemo(()=>e.filter(i=>(i.service??"firestore")==="firestore"),[e]),r=wD({events:n,window:t,isAdmin:tL}),s=y.useMemo(()=>QM(r.series),[r.series]);return c.jsx("div",{className:"traffic__metrics","data-pyric-ui":"traffic-billable-view",children:c.jsx(Dg,{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:c.jsxs(c.Fragment,{children:[c.jsxs("p",{children:["Counts successful Firestore sandbox ",c.jsx("code",{children:"get"}),"/",c.jsx("code",{children:"list"}),","," ",c.jsx("code",{children:"create"}),"/",c.jsx("code",{children:"update"}),"/",c.jsx("code",{children:"set"}),", and"," ",c.jsx("code",{children:"delete"}),"/",c.jsx("code",{children:"remove"})," operations in the displayed window. Rules-bypassed admin operations are included because they still execute."]}),c.jsxs("p",{children:[c.jsx("strong",{children:"Read ops are a proxy, not billed document reads."})," Each"," ",c.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 sL({events:e,window:t}){const n=y.useMemo(()=>RM(e),[e]),r=vD({events:n,window:t}),s=y.useMemo(()=>r.series.filter(o=>o.key==="allows"||o.key==="denies"),[r.series]),i=y.useMemo(()=>XM(s),[s]);return c.jsxs("div",{className:"traffic__metrics","data-pyric-ui":"traffic-rules-view",children:[c.jsxs("p",{children:["Query proof unsupported: ",IM(e,t)]}),c.jsx(Dg,{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:c.jsxs(c.Fragment,{children:[c.jsxs("p",{children:["Counts only operations whose canonical Rules disposition is"," ",c.jsx("code",{children:"evaluated"}),", grouped by its ",c.jsx("code",{children:"allow"})," or ",c.jsx("code",{children:"deny"})," ","verdict. Query-proof limitations are counted separately, not as ordinary denials."]}),c.jsxs("p",{children:[c.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."]})]})})]})}function Jc(e){for(const t of e??[])if(t.kind==="component")return t;return null}function Vi(e){for(const t of e??[])if(t.kind==="tag")return t;return null}function iL(e){for(const t of e??[])if(t.kind==="frame")return t;return null}function oL(e){const t=Jc(e);if(t?.element!==void 0)return t.element;const n=Vi(e);if(n?.element!==void 0)return n.element}function Tn(e){return typeof e=="string"?e:e.query!==void 0?`${e.collection} (query)`:e.collection}function aL(e,t){const n=Jc(e);if(n)return n.name;const r=Vi(e);return r?r.name:Tn(t)}function Wi(e){const t=Jc(e.owners);if(t)return{key:`component:${t.name}`,label:t.name};const n=Vi(e.owners);if(n)return{key:`tag:${n.name}`,label:n.name};const r=Tn(e.target);return{key:`target:${r}`,label:r}}function cL(e,t){return!(t.service!==void 0&&e.service!==t.service||t.targetPrefix!==void 0&&t.targetPrefix!==""&&!px(e.target,t.targetPrefix))}function lL(e,t={}){const n=new Map;for(const r of e){if(!cL(r,t))continue;const s=Wi(r),i=n.get(s.key);i?i.listeners.push(r):n.set(s.key,{identity:s,listeners:[r]})}return[...n.values()].map(r=>Object.freeze({identity:r.identity,listeners:Object.freeze(r.listeners)})).sort((r,s)=>r.listeners[0].attachedAt-s.listeners[0].attachedAt)}function uL(e){return{history:()=>e,subscribe:()=>()=>{}}}function Pg(e){const t=pE(uL(e),()=>{});try{return t.report().incidents}finally{t.dispose()}}function dL(e){try{const t=JSON.parse(e.targetFingerprint);if(t.kind==="doc"&&typeof t.path=="string")return t.path;if(t.kind==="query"&&typeof t.collection=="string")return{collection:t.collection,query:!0}}catch{}return null}function fL(e,t){return typeof e=="string"||typeof t=="string"?e===t:e.collection===t.collection}function Tg(e,t){return e.filter(n=>{if(n.pattern!=="duplicate-listener"&&n.pattern!=="listener-churn")return!1;const r=dL(n);return r!==null&&fL(r,t)})}function hL(e,t){return e?.column===t&&e.direction==="asc"?{column:t,direction:"desc"}:{column:t,direction:"asc"}}const pL=e=>e.deliveryCount;function mL(e,t,n){const r=new Map;for(const s of e.listeners){const i=Tn(s.target),o=r.get(i);o?o.push(s):r.set(i,[s])}return[...r.entries()].map(([s,i])=>{const o=[...i].sort((l,u)=>l.attachedAt-u.attachedAt),a=o[0];return Object.freeze({key:`${e.identity.key}|${s}`,listeners:Object.freeze(o),listener:a,ownerLabel:e.identity.label,target:s,count:o.length,deliveryCount:o.reduce((l,u)=>l+n(u),0),incidents:Tg(t,a.target)})})}function xf(e,t){return e<t?-1:e>t?1:0}function bi(e){return e.incidents.length>0?1:0}function yL(e,t,n){return n==="target"?xf(e.target,t.target):n==="service"?xf(e.listener.service,t.listener.service):n==="attached"?e.listener.attachedAt-t.listener.attachedAt:n==="deliveries"?e.deliveryCount-t.deliveryCount:bi(e)-bi(t)}function gL(e,t){const n=bi(t)-bi(e);if(n!==0)return n;const r=t.deliveryCount-e.deliveryCount;return r!==0?r:e.listener.attachedAt-t.listener.attachedAt}function bL(e){if(e===void 0)return gL;const t=e.direction==="asc"?1:-1;return(n,r)=>{const s=yL(n,r,e.column)*t;return s!==0?s:n.listener.attachedAt-r.listener.attachedAt}}function wL(e,t,n,r=pL){const s=bL(n);return e.map(i=>{const o=[...mL(i,t,r)].sort(s);return Object.freeze({identity:i.identity,rows:Object.freeze(o),listenerCount:i.listeners.length})}).sort((i,o)=>s(i.rows[0],o.rows[0]))}function vL(e,t){let n=0;const r=[];let s;for(const a of e){n+=a.listenerCount,(s===void 0||a.listenerCount>s.count)&&(s={label:a.identity.label,count:a.listenerCount});for(const l of a.rows)l.count>1&&r.push(l.count)}const i=t.filter(a=>a.pattern==="listener-churn").length,o={listeners:n,duplicates:r,churn:i};return s!==void 0&&(o.busiest=s),o}function xL(e){let t=0,n=0,r=0;for(const s of e)for(const i of s.rows)i.deliveryCount>0?t+=i.count:n+=i.count,i.incidents.length>0&&(r+=i.count);return{delivering:t,idle:n,incidents:r}}function _L(e){const t=[e.deliveryCount>0?"delivering":"idle"];return e.incidents.length>0&&t.push("incidents"),t}function Yc(e){return e.kind==="snapshot_delivery"?!0:e.kind==="listener"&&e.phase==="delivery"}const Mg=[{key:"delivering",label:"Delivering"},{key:"idle",label:"Idle"},{key:"incidents",label:"Incidents"}];function SL(e){return Mg.map(t=>({key:t.key,label:t.label,values:[],total:e[t.key]}))}const Do=[{key:"firestore",label:"Firestore"},{key:"database",label:"Database"}];function kL(e,t){const n=new Map;for(const r of e){if(!Yc(r)||r.at<t.start||r.at>=t.end)continue;const s=r.listenerId;s!==void 0&&n.set(s,(n.get(s)??0)+1)}return n}function jL(e,t,n,r=24){const s=n.end-n.start,i=Do.map(f=>({key:f.key,label:f.label,values:[],total:0}));if(r<=0||s<=0)return{points:[],series:i,total:0};const o=s/r,a=new Map;for(const f of t)a.set(f.id,f.service);const l=new Map(Do.map(f=>[f.key,new Array(r).fill(0)]));let u=0;for(const f of e){if(!Yc(f)||f.at<n.start||f.at>=n.end)continue;const p=f.listenerId;if(p===void 0)continue;const m=a.get(p);if(m===void 0)continue;const g=l.get(m);if(g===void 0)continue;let b=Math.floor((f.at-n.start)/o);b>=r&&(b=r-1),g[b]=(g[b]??0)+1,u+=1}const d=[];for(let f=0;f<r;f+=1)d.push({index:f,start:n.start+f*o,end:n.start+(f+1)*o});const h=Do.map(f=>{const p=l.get(f.key);return{key:f.key,label:f.label,values:p,total:p.reduce((m,g)=>m+g,0)}});return{points:d,series:h,total:u}}function za(e,t){if(e===t)return!0;if(typeof e!=typeof t||e===null||t===null)return!1;if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((i,o)=>za(i,t[o]));if(typeof e!="object"||typeof t!="object")return!1;const n=e,r=t,s=Object.keys(n);return s.length!==Object.keys(r).length?!1:s.every(i=>Object.prototype.hasOwnProperty.call(r,i)&&za(n[i],r[i]))}function EL(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function CL(e){if(e.kind==="snapshot_delivery"){const r=e.sample?.docs;return r===void 0?[]:r.map(s=>[s.path,s.data])}const t=e.target?.path;if(t===void 0||t==="")return[];const n=e.sample;return n==null?[]:EL(n)?Object.keys(n).map(r=>[`${t}/${r}`,n[r]]):[[t,n]]}function NL(e){if(e.kind!=="snapshot_delivery")return;const t=e;if(!(t.addedCount===void 0||t.modifiedCount===void 0||t.removedCount===void 0))return{added:t.addedCount,modified:t.modifiedCount,removed:t.removedCount}}function Lg(e,t){const n=[];let r=new Map;for(const s of e){if(!Yc(s)||s.listenerId!==t)continue;const i=CL(s),o=new Map(i.map(([f,p])=>[f,p])),a=[];let l=0,u=0;for(const[f,p]of i)r.has(f)?za(r.get(f),p)?a.push({path:f,change:"unchanged"}):(a.push({path:f,change:"modified"}),u+=1):(a.push({path:f,change:"added"}),l+=1);let d=0;for(const f of r.keys())o.has(f)||(a.push({path:f,change:"removed"}),d+=1);const h=NL(s);n.push({at:s.at,initial:n.length===0,addedCount:h?.added??l,modifiedCount:h?.modified??u,removedCount:h?.removed??d,size:i.length,docs:a}),r=o}return n}function Ug(e){const t=e[0];if(t===void 0)return 0;let n=Math.max(t.size,1);for(const r of e.slice(1))n+=r.addedCount+r.modifiedCount;return n}function Bg(e){const t=[{key:"deliveries",label:"Deliveries",total:e.deliveries},{key:"snapshot",label:"Snapshot",total:e.snapshot,unit:e.single||e.snapshot===1?"document":"documents"}];return e.service==="firestore"&&t.push({key:"reads",label:"Estimated reads",total:e.reads}),t}function RL(e){return e.map(t=>({key:t.key,label:t.label,values:[],total:t.total}))}function IL(e,t){let n=0;return r=>{const s=e[n];return n+=1,s?.unit===void 0?t(r):`${t(r)} ${s.unit}`}}function AL(e){if(e==="firestore")return"Estimated reads: initial snapshot + documents added or modified since · reconnects and duplicate listeners not counted"}function OL(e,t){return e.map((n,r)=>({id:`delivery-${r}`,at:n.at,method:"listen",path:t,auth:null,result:"allow",reasons:[],origin:"listener"}))}function _f(e,t){return e.filter(n=>n.at>=t.start&&n.at<t.end)}function Sf(e){let t=0,n=0,r=0;for(const o of e)t+=o.initial?o.size:o.addedCount,n+=o.initial?0:o.modifiedCount,r+=o.initial?0:o.removedCount;const s=e.length,i=[`${s} ${s===1?"delivery":"deliveries"}`];return t>0&&i.push(`${t} added`),n>0&&i.push(`${n} modified`),r>0&&i.push(`${r} removed`),i}function $L(e){if(e.initial)return"initial";const t=[];return e.addedCount>0&&t.push(`+${e.addedCount}`),e.modifiedCount>0&&t.push(`~${e.modifiedCount}`),e.removedCount>0&&t.push(`−${e.removedCount}`),t.join(" ")}const Fg="listeners";function qg(e,t){return e==="firestore"?dg({view:"firestore",path:Wr(t)}):{tab:"rtdb",rest:t.split("/").filter(Boolean)}}function DL(e,t){return Ct(qg(e,t))}function Vg(e){return{tab:"traffic",rest:[Fg,e]}}function PL(e){return Ct(Vg(e))}function Wg(){return{tab:"traffic",query:{view:"listeners"}}}function TL(){return Ct(Wg())}function zg(e){if(e.tab!=="traffic"||e.rest[0]!==Fg)return;const t=e.rest[1];return t===void 0||t===""?void 0:t}const Hg=new Intl.DateTimeFormat(void 0,{hour:"numeric",minute:"2-digit",second:"2-digit"});function kf(e){return Hg.formatToParts(e).filter(t=>t.type!=="dayPeriod").map(t=>t.value).join("").trim()}function ML(e){const t=e.lastIndexOf("/");return t===-1?{prefix:"",id:e}:{prefix:e.slice(0,t+1),id:e.slice(t+1)}}function LL({path:e,service:t}){const{prefix:n,id:r}=ML(e);return c.jsx("a",{className:"traffic__listener-path-link",href:DL(t,e),title:e,onClick:s=>{s.metaKey||s.ctrlKey||s.shiftKey||s.button!==0||(s.preventDefault(),Ae(qg(t,e)))},children:c.jsxs("span",{"data-pyric-path":e,children:[c.jsx("span",{"data-pyric-path-prefix":"",children:n}),c.jsx("span",{"data-pyric-path-id":"",children:r})]})})}function UL(e){return e.initial?[]:e.docs.filter(t=>t.change!=="unchanged")}function Kg({delivery:e,service:t,expanded:n=!1,onToggle:r}){const s=UL(e),i=n&&s.length>0;return c.jsxs("div",{className:"traffic__delivery-entry","data-pyric-delivery-entry":"",children:[c.jsxs("button",{type:"button",className:"traffic__delivery-row","data-pyric-delivery-row":"","data-pyric-delivery-at":e.at,"data-pyric-selected":i?"":void 0,disabled:s.length===0||r===void 0,onClick:r,children:[c.jsx("span",{"data-pyric-delivery-time":"",children:Hg.format(e.at)}),c.jsx("span",{"data-pyric-delivery-figures":"",children:$L(e)}),c.jsxs("span",{"data-pyric-delivery-snapshot":"",children:[e.size," in snapshot"]})]}),i?c.jsx("div",{className:"traffic__delivery-changes","data-pyric-delivery-changes":"",children:s.map(o=>c.jsxs("div",{className:"traffic__delivery-path","data-pyric-delivery-path":o.path,children:[c.jsx(LL,{path:o.path,service:t}),c.jsx("span",{className:"traffic__delivery-change","data-pyric-change":o.change,children:o.change})]},o.path))}):null]})}const BL=/^\[[a-zA-Z][\w-]*(?:=["']?([^"'\]]+)["']?)?\]$/,FL=/^([a-z][a-z0-9-]*?)-[0-9a-z]+$/,qL=/^[a-z][a-z0-9-]*$/;function VL(e){const n=e?.find(r=>r.kind==="component"&&typeof r.tag=="string")?.tag??Vi(e)?.name;if(!(n===void 0||!qL.test(n)))return n}function WL(e){const t=e.split(">");return t[t.length-1].trim()}function zL(e){const t=BL.exec(e);if(t!==null){const a=FL.exec(t[1]??"");return a===null?{}:{tag:a[1]}}const n=e.replace(/:[a-z-]+(\([^)]*\))?/g,""),r={},s=/^[a-zA-Z][\w-]*/.exec(n)?.[0];s!==void 0&&(r.tag=s.toLowerCase());const i=/#([\w-]+)/.exec(n)?.[1];i!==void 0&&(r.id=i);const o=/\.([\w-]+)/.exec(n)?.[1];return o!==void 0&&(r.className=o),r}function zi(e){const t=oL(e);if(t===void 0||t==="")return;const n=zL(WL(t)),r=n.tag??VL(e)??"";return n.id!==void 0?`${r}#${n.id}`:n.className!==void 0?`${r}.${n.className}`:r===""?void 0:r}function HL(e){const t="owners"in e&&Array.isArray(e.owners)?e.owners:void 0;if(e.kind==="listener_attach"){const n=e.target;if(n.kind==="doc"&&n.path!==void 0)return t===void 0?{target:n.path}:{target:n.path,owners:t};const r={collection:n.collection??"",query:n.query};return t===void 0?{target:r}:{target:r,owners:t}}if(e.kind==="listener"&&e.phase==="attach"){const n=e.target?.path??"";return t===void 0?{target:n}:{target:n,owners:t}}return null}function KL(e,t,n){const r=Tn(t),s=[];for(const i of e){const o=HL(i);if(o===null||Tn(o.target)!==r||aL(o.owners,o.target)!==n)continue;const a=iL(o.owners),l=zi(o.owners),u={at:i.at};a!==null&&(u.frame=`${a.file}:${a.line}`),l!==void 0&&(u.element=l),s.push(Object.freeze(u))}return Object.freeze(s)}function Gg(e){const t=Math.max(0,Math.round(e/1e3));if(t<60)return`${t}s`;const n=Math.round(t/60);return n<60?`${n}m`:`${Math.round(n/60)}h`}function Qc(e,t){return`${Gg(t-e)} ago`}function Ha(e,t){return`${e} ${t}${e===1?"":"s"}`}function Jg(e){return e===2?"twice":`${e} times`}function Yg(e){return e==="firestore"?"Firestore":"Database"}function GL(e){if(e.listeners===0)return"No listeners attached";const t=Ha(e.listeners,"listener");if(e.duplicates.length>0){const n=Math.max(...e.duplicates);return`${t}, ${e.duplicates.length} attached ${Jg(n)}`}return e.churn>0?`${t}, ${Ha(e.churn,"listener")} reattaching`:t}function JL(e){const t=e.busiest;if(!(t===void 0||t.count<2))return`${t.label} · ${Ha(t.count,"listener")}`}function Qg(e,t){const n=[];return e.owner!==void 0&&n.push(e.owner),e.element!==void 0&&n.push(e.element),n.push(Yg(e.service)),n.push(`attached ${Qc(e.attachedAt,t)}`),n.join(" · ")}function YL(e){return e.length<2?e.join(""):`${e.slice(0,-1).join(", ")} and ${e[e.length-1]}`}function QL(e,t,n){const r=t===void 0?"":` by ${t}`;if(e.pattern==="listener-churn")return`Reattached ${e.count} times in ${Gg(e.windowMs)}${r}`;const s=YL(n),i=`Attached ${Jg(e.count)}${r}`;return s===""?i:`${i} · ${s}`}function Xg({incident:e,listener:t,events:n,now:r}){const s=Wi(t).label,i=KL(n,t.target,s),o=e.pattern==="listener-churn"?i.slice(-1):i,a=e.pattern==="listener-churn"?[]:i.map(d=>Qc(d.at,r)),l=zi(t.owners),u=o.filter(d=>d.frame!==void 0||(d.element??l)!==void 0);return c.jsxs("div",{className:"traffic__listener-incident","data-pyric-incident-block":"",children:[c.jsxs("p",{className:"traffic__listener-incident-line",children:[c.jsx("span",{"aria-hidden":"true",children:"⚠"})," ",QL(e,s,a)]}),u.map((d,h)=>{const f=d.element??l;return c.jsxs("p",{className:"traffic__listener-incident-attach","data-pyric-incident-attach":"",children:[d.frame===void 0?null:c.jsx("span",{children:d.frame}),d.frame!==void 0&&f!==void 0?c.jsx("span",{children:" · "}):null,f===void 0?null:c.jsx("span",{"data-pyric-element":"",children:f})]},`${d.at}|${h}`)})]})}const Po=40,Cn=" ";function at(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ve(e){return`'${e.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n")}'`}function XL(e){return e.length<=Po?e:e.startsWith("'")&&e.endsWith("'")?`${e.slice(0,Po-2)}…'`:`${e.slice(0,Po-1)}…`}function zr(e,t){const n=ZL(e,t);return t?n:XL(n)}function ZL(e,t){if(typeof e=="string")return Ve(e);if(typeof e=="number"||typeof e=="boolean")return String(e);if(e===null)return"null";if(!at(e))return"…";switch(e.type){case"string":return typeof e.value=="string"?Ve(e.value):"…";case"number":case"boolean":return String(e.value);case"null":return"null";case"reference":return typeof e.path=="string"?`doc(db, ${Ve(e.path)})`:"…";case"timestamp":return typeof e.iso=="string"?Ve(e.iso):"…";case"geoPoint":return`GeoPoint(${String(e.latitude)}, ${String(e.longitude)})`;case"bytes":return`Bytes(${String(e.length)})`;case"vector":return`Vector(${String(e.length)})`;case"array":{const r=(Array.isArray(e.values)?e.values:[]).map(s=>zr(s,t));return e.truncated===!0&&r.push("…"),`[${r.join(", ")}]`}case"map":{const r=(Array.isArray(e.entries)?e.entries:[]).filter(s=>Array.isArray(s)&&typeof s[0]=="string").map(([s,i])=>`${s}: ${zr(i,t)}`);return e.truncated===!0&&r.push("…"),r.length===0?"{}":`{ ${r.join(", ")} }`}default:return"…"}}function Zg(e,t,n){if(!at(e))return;const r=Cn.repeat(t);if(e.kind==="where"){const o=typeof e.field=="string"?e.field:"",a=typeof e.op=="string"?e.op:"",l="display"in e?e.display:e.value;return`${r}where(${Ve(o)}, ${Ve(a)}, ${zr(l,n)})`}if(e.kind!=="or"&&e.kind!=="and")return;const i=(Array.isArray(e.filters)?e.filters:[]).map(o=>Zg(o,t+1,n)).filter(o=>o!==void 0);if(i.length!==0)return`${r}${e.kind}(
|
|
140
|
+
color: hsl(${Math.max(0,Math.min(120-120*b,120))}deg 100% 31%);`,n?.key)}return n?.onChange&&!(i&&n.skipInitialOnChange)&&n.onChange(s),i=!1,s}return o.updateDeps=a=>{r=a},o}function Fd(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const P$=(e,t)=>Math.abs(e-t)<1.01,D$=(e,t,n)=>{let r;return function(...s){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,s),n)}},Vd=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},T$=e=>e,M$=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},L$=(e,t)=>{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;const s=o=>{const{width:a,height:l}=o;t({width:Math.round(a),height:Math.round(l)})};if(s(Vd(n)),!r.ResizeObserver)return()=>{};const i=new r.ResizeObserver(o=>{const a=()=>{const l=o[0];if(l?.borderBoxSize){const u=l.borderBoxSize[0];if(u){s({width:u.inlineSize,height:u.blockSize});return}}s(Vd(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(a):a()});return i.observe(n,{box:"border-box"}),()=>{i.unobserve(n)}},qd={passive:!0},Wd=typeof window>"u"?!0:"onscrollend"in window,U$=(e,t)=>{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;let s=0;const i=e.options.useScrollendEvent&&Wd?()=>{}:D$(r,()=>{t(s,!1)},e.options.isScrollingResetDelay),o=d=>()=>{const{horizontal:h,isRtl:f}=e.options;s=h?n.scrollLeft*(f&&-1||1):n.scrollTop,i(),t(s,d)},a=o(!0),l=o(!1);n.addEventListener("scroll",a,qd);const u=e.options.useScrollendEvent&&Wd;return u&&n.addEventListener("scrollend",l,qd),()=>{n.removeEventListener("scroll",a),u&&n.removeEventListener("scrollend",l)}},B$=(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"]},F$=(e,{adjustments:t=0,behavior:n},r)=>{var s,i;const o=e+t;(i=(s=r.scrollElement)==null?void 0:s.scrollTo)==null||i.call(s,{[r.options.horizontal?"left":"top"]:o,behavior:n})};class V${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 o=()=>{const a=i.target,l=this.indexFromElement(a);if(!a.isConnected){this.observer.unobserve(a);return}this.shouldMeasureDuringScroll(l)&&this.resizeItem(l,this.options.measureElement(a,i,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(o):o()})}));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:T$,rangeExtractor:M$,onChange:()=>{},measureElement:B$,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=wn(()=>(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 o=r-1;o>=0;o--){const a=n[o];if(s.has(a.lane))continue;const l=i.get(a.lane);if(l==null||a.end>l.end?i.set(a.lane,a):a.end<l.end&&s.set(a.lane,!0),s.size===this.options.lanes)break}return i.size===this.options.lanes?Array.from(i.values()).sort((o,a)=>o.end===a.end?o.index-a.index:o.end-a.end)[0]:void 0},this.getMeasurementOptions=wn(()=>[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,o,a,l)=>(this.prevLanes!==void 0&&this.prevLanes!==a&&(this.lanesChangedFlag=!0),this.prevLanes=a,this.pendingMeasuredCacheIndexes=[],{count:n,paddingStart:r,scrollMargin:s,getItemKey:i,enabled:o,lanes:a,laneAssignmentMode:l}),{key:!1}),this.getMeasurements=wn(()=>[this.getMeasurementOptions(),this.itemSizeCache],({count:n,paddingStart:r,scrollMargin:s,getItemKey:i,enabled:o,lanes:a,laneAssignmentMode:l},u)=>{if(!o)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>n)for(const p of this.laneAssignments.keys())p>=n&&this.laneAssignments.delete(p);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(p=>{this.itemSizeCache.set(p.key,p.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 h=this.measurementsCache.slice(0,d),f=new Array(a).fill(void 0);for(let p=0;p<d;p++){const m=h[p];m&&(f[m.lane]=p)}for(let p=d;p<n;p++){const m=i(p),g=this.laneAssignments.get(p);let b,w;const x=l==="estimate"||u.has(m);if(g!==void 0&&this.options.lanes>1){b=g;const k=f[b],N=k!==void 0?h[k]:void 0;w=N?N.end+this.options.gap:r+s}else{const k=this.options.lanes===1?h[p-1]:this.getFurthestMeasurement(h,p);w=k?k.end+this.options.gap:r+s,b=k?k.lane:p%this.options.lanes,this.options.lanes>1&&x&&this.laneAssignments.set(p,b)}const v=u.get(m),_=typeof v=="number"?v:this.options.estimateSize(p),S=w+_;h[p]={index:p,start:w,size:_,end:S,key:m,lane:b},f[b]=p}return this.measurementsCache=h,h},{key:!1,debug:()=>this.options.debug}),this.calculateRange=wn(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,s,i)=>this.range=n.length>0&&r>0?q$({measurements:n,outerSize:r,scrollOffset:s,lanes:i}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=wn(()=>{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,o)=>i===null||o===null?[]:n({startIndex:i,endIndex:o,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)),o=Math.max(0,s-i),a=Math.min(this.options.count-1,s+i);return n>=o&&n<=a}return!0},this.measureElement=n=>{if(!n){this.elementsCache.forEach((o,a)=>{o.isConnected||(this.observer.unobserve(o),this.elementsCache.delete(a))});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 o=this.itemSizeCache.get(i.key)??i.size,a=r-o;a!==0&&(((s=this.scrollState)==null?void 0:s.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(i,a,this):i.start<this.getScrollOffset()+this.scrollAdjustments)&&this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=a,behavior:void 0}),this.pendingMeasuredCacheIndexes.push(i.index),this.itemSizeCache=new Map(this.itemSizeCache.set(i.key,r)),this.notify(!1))},this.getVirtualItems=wn(()=>[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const s=[];for(let i=0,o=n.length;i<o;i++){const a=n[i],l=r[a];s.push(l)}return s},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length!==0)return Fd(r[Dy(0,r.length-1,s=>Fd(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(),o=this.getScrollOffset();r==="auto"&&(r=n>=o+i?"end":"start"),r==="center"?n+=(s-i)/2:r==="end"&&(n-=i);const a=this.getMaxScrollOffset();return Math.max(Math.min(a,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(),o=this.measurementsCache[n];if(!o)return;if(r==="auto")if(o.end>=i+s-this.options.scrollPaddingEnd)r="end";else if(o.start<=i+this.options.scrollPaddingStart)r="start";else return[i,r];if(r==="end"&&n===this.options.count-1)return[this.getMaxScrollOffset(),r];const a=r==="end"?o.end+this.options.scrollPaddingEnd:o.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(a,r,o.size),r]},this.scrollToOffset=(n,{align:r="start",behavior:s="auto"}={})=>{const i=this.getOffsetForAlignment(n,r),o=this.now();this.scrollState={index:null,align:r,behavior:s,startedAt:o,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[o,a]=i,l=this.now();this.scrollState={index:n,align:a,behavior:s,startedAt:l,lastTargetOffset:o,stableFrames:0},this._scrollToOffset(o,{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 o=r.length-1;for(;o>=0&&i.some(a=>a===null);){const a=r[o];i[a.lane]===null&&(i[a.lane]=a.end),o--}s=Math.max(...i.filter(a=>a!==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,o=s!==this.scrollState.lastTargetOffset;if(!o&&P$(s,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=i){this.scrollState=null;return}}else this.scrollState.stableFrames=0,o&&(this.scrollState.lastTargetOffset=s,this.scrollState.behavior="auto",this._scrollToOffset(s,{adjustments:void 0,behavior:"auto"}));this.scheduleScrollReconcile()}}const Dy=(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 q$({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 o=Dy(0,s,i,n),a=o;if(r===1)for(;a<s&&e[a].end<n+t;)a++;else if(r>1){const l=Array(r).fill(0);for(;a<s&&l.some(d=>d<n+t);){const d=e[a];l[d.lane]=d.end,a++}const u=Array(r).fill(n+t);for(;o>=0&&u.some(d=>d>=n);){const d=e[o];u[d.lane]=d.start,o--}o=Math.max(0,o-o%r),a=Math.min(s,a+(r-1-a%r))}return{startIndex:o,endIndex:a}}const zd=typeof document<"u"?y.useLayoutEffect:y.useEffect;function W$({useFlushSync:e=!0,...t}){const n=y.useReducer(()=>({}),{})[1],r={...t,onChange:(i,o)=>{var a;e&&o?Lc.flushSync(n):n(),(a=t.onChange)==null||a.call(t,i,o)}},[s]=y.useState(()=>new V$(r));return s.setOptions(r),zd(()=>s._didMount(),[]),zd(()=>s._willUpdate()),s}function z$(e){return W$({observeElementRect:L$,observeElementOffset:U$,scrollToFn:F$,...e})}function Uc({items:e,estimateSize:t,renderItem:n,overscan:r=5,className:s,height:i="100%",getItemKey:o}){const a=y.useRef(null),l=typeof t=="function"?t:()=>t,u=z$({count:e.length,getScrollElement:()=>a.current,estimateSize:l,overscan:r});return c.jsx("div",{ref:a,className:s,"data-pyric-ui":"virtual-list",style:{height:i,overflowY:"auto",contain:"strict"},children:c.jsx("div",{"data-pyric-virtual-inner":!0,style:{height:`${u.getTotalSize()}px`,width:"100%",position:"relative"},children:u.getVirtualItems().map(d=>{const h=e[d.index],f=o?o(h,d.index):d.key;return c.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(h,d.index)},f)})})})}function Hd(e){return e.email??e.phoneNumber??(e.isAnonymous?"anonymous":e.uid)}function H$(e){return e.isAnonymous&&e.providerUserInfo.length===0?c.jsx("span",{"data-pyric-provider-id":"anonymous",children:yi("anonymous")}):e.providerUserInfo.map(t=>c.jsx("span",{"data-pyric-provider-id":t.providerId,children:yi(t.providerId)},t.providerId))}function Kd(e){if(!e)return"—";const t=new Date(e);return Number.isNaN(t.getTime())?"—":t.toLocaleDateString()}function Ty({users:e,isLoading:t,error:n,filter:r,onSelect:s,renderIdentifier:i,renderProviders:o,renderSelection:a,renderSelectionHeader:l,renderActions:u,renderActionsHeader:d,formatCreatedAt:h=Kd,formatLastLoginAt:f=Kd,emptyState:p,noResultsState:m,className:g,virtualizeThreshold:b=100,rowHeight:w=44,virtualizedHeight:x="60vh"}){if(n)return c.jsx("div",{className:g,"data-pyric-ui":"auth-user-list","data-pyric-error":"",role:"alert",children:n.message});if(t&&e.length===0)return c.jsx("div",{className:g,"data-pyric-ui":"auth-user-list","data-pyric-loading":""});if(e.length===0){const S=!!r?.trim();return c.jsx("div",{className:g,"data-pyric-ui":"auth-user-list","data-pyric-empty":"","data-pyric-no-results":S?"":void 0,children:S?m??"No results":p??"No users for this project yet"})}const v=e.length>b,_=S=>c.jsxs("div",{role:"row","data-pyric-user-entry":!0,"data-pyric-user-uid":S.uid,"data-pyric-user-disabled":S.disabled?"":void 0,children:[a?c.jsx("span",{role:"cell","data-pyric-user-cell":"selection",children:a(S)}):null,c.jsx("span",{role:"cell","data-pyric-user-cell":"identifier",children:s?c.jsx("button",{type:"button","data-pyric-user-select":!0,onClick:()=>s(S),children:i?i(S):Hd(S)}):(i??Hd)(S)}),c.jsx("span",{role:"cell","data-pyric-user-cell":"providers",children:(o??H$)(S)}),c.jsx("span",{role:"cell","data-pyric-user-cell":"created",children:h(S.createdAt)}),c.jsx("span",{role:"cell","data-pyric-user-cell":"signed-in",children:f(S.lastLoginAt)}),c.jsx("span",{role:"cell","data-pyric-user-cell":"uid",children:S.uid}),u?c.jsx("span",{role:"cell","data-pyric-user-cell":"actions",children:u(S)}):null]},S.uid);return c.jsxs("div",{className:g,role:"table","aria-label":"Authentication users","data-pyric-ui":"auth-user-list","data-pyric-virtualized":v?"":void 0,"data-pyric-selection":a?"":void 0,"data-pyric-actions":u?"":void 0,children:[c.jsxs("div",{role:"row","data-pyric-user-header":!0,children:[a?c.jsx("span",{role:"columnheader","data-pyric-user-cell":"selection","aria-label":"Selection",children:l}):null,c.jsx("span",{role:"columnheader","data-pyric-user-cell":"identifier",children:"Identifier"}),c.jsx("span",{role:"columnheader","data-pyric-user-cell":"providers",children:"Provider"}),c.jsx("span",{role:"columnheader","data-pyric-user-cell":"created",children:"Created"}),c.jsx("span",{role:"columnheader","data-pyric-user-cell":"signed-in",children:"Signed In"}),c.jsx("span",{role:"columnheader","data-pyric-user-cell":"uid",children:"User UID"}),u?c.jsx("span",{role:"columnheader","data-pyric-user-cell":"actions","aria-label":"Actions",children:d}):null]}),v?c.jsx(Uc,{items:e,estimateSize:w,height:x,getItemKey:S=>S.uid,renderItem:_}):c.jsx("div",{role:"rowgroup","data-pyric-user-rows":!0,children:e.map(_)})]})}function K$({value:e,onChange:t,error:n,hint:r,placeholder:s='{"role":"admin"}',className:i}){return c.jsxs("div",{className:i,"data-pyric-ui":"claims-field",children:[c.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:o=>t(o.target.value)}),n!=null&&c.jsx("p",{role:"alert","data-pyric-claims-error":!0,children:n}),r!=null&&c.jsx("p",{"data-pyric-claims-hint":!0,children:r})]})}function G$({selected:e,onChange:t}){return c.jsx("div",{"data-pyric-provider-checklist":!0,children:Ah.map(n=>c.jsxs("label",{"data-pyric-provider-option":n,children:[c.jsx("input",{type:"checkbox",checked:e.includes(n),onChange:r=>t(r.target.checked?[...e,n]:e.filter(s=>s!==n))}),c.jsx("span",{"data-pyric-provider-option-label":!0,children:yi(n)}),c.jsx("span",{"data-pyric-provider-option-id":!0,children:n})]},n))})}function My({initial:e,onSubmit:t,onCancel:n,submitLabel:r="Save",cancelLabel:s="Cancel",children:i,className:o,renderField:a}){const l=Py({initial:e}),u=e?"edit":"create",d=l.isValid&&(u==="create"||l.isDirty),h=(m,g,b,w,x=null)=>({name:m,label:g,input:w,error:x,kind:b,defaultRender:()=>b==="checkbox"?c.jsxs("label",{"data-pyric-field-label":m,children:[w,c.jsx("span",{"data-pyric-label-text":!0,children:g})]},m):b==="group"?c.jsxs("fieldset",{"data-pyric-field-label":m,children:[c.jsx("legend",{"data-pyric-label-text":!0,children:g}),w]},m):c.jsxs("label",{"data-pyric-field-label":m,children:[c.jsx("span",{"data-pyric-label-text":!0,children:g}),w,x!=null&&c.jsx("p",{role:"alert","data-pyric-field-error":m,children:x})]},m)}),f=[h("email","Email","text",c.jsx("input",{type:"email","data-pyric-field":"email",placeholder:"email@example.com",value:l.fields.email,onChange:m=>l.setField("email",m.target.value)}),l.errors.email??null),h("password","Password","text",c.jsx("input",{type:"password","data-pyric-field":"password",placeholder:u==="edit"?"New password (unchanged if empty)":"Password",value:l.fields.password,onChange:m=>l.setField("password",m.target.value)}),l.errors.password??null),h("display-name","Display name","text",c.jsx("input",{type:"text","data-pyric-field":"display-name",placeholder:"Display name (optional)",value:l.fields.displayName,onChange:m=>l.setField("displayName",m.target.value)})),h("phone-number","Phone number","text",c.jsx("input",{type:"tel","data-pyric-field":"phone-number",placeholder:"+1 555 555 0100",value:l.fields.phoneNumber,onChange:m=>l.setField("phoneNumber",m.target.value)})),h("photo-url","Photo URL","text",c.jsx("input",{type:"url","data-pyric-field":"photo-url",placeholder:"https://example.com/avatar.png",value:l.fields.photoUrl,onChange:m=>l.setField("photoUrl",m.target.value)})),...u==="create"?[h("providers","Sign-in providers","group",c.jsx(G$,{selected:l.fields.providerIds,onChange:m=>l.setField("providerIds",m)}))]:[],h("email-verified","Verified email","checkbox",c.jsx("input",{type:"checkbox","data-pyric-field":"email-verified",checked:l.fields.emailVerified,onChange:m=>l.setField("emailVerified",m.target.checked)})),h("disabled","Disabled (sign-in attempts are rejected)","checkbox",c.jsx("input",{type:"checkbox","data-pyric-field":"disabled",checked:l.fields.disabled,onChange:m=>l.setField("disabled",m.target.checked)}))],p=m=>{m.preventDefault(),d&&t(u==="edit"?{mode:u,uid:e.uid,request:l.toUpdateRequest()}:{mode:u,request:l.toCreateRequest()})};return c.jsxs("form",{className:o,"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:p,children:[f.map(m=>a?c.jsx(y.Fragment,{children:a(m)},m.name):m.defaultRender()),c.jsx(K$,{value:l.fields.claimsText,onChange:m=>l.setField("claimsText",m),error:l.errors.claims}),i,c.jsxs("footer",{"data-pyric-form-actions":!0,children:[n?c.jsx("button",{type:"button","data-pyric-cancel":!0,onClick:n,children:s}):null,c.jsx("button",{type:"submit","data-pyric-submit":!0,disabled:!d,children:r})]})]})}const Ly=["a[href]","area[href]",'input:not([disabled]):not([type="hidden"])',"select:not([disabled])","textarea:not([disabled])","button:not([disabled])","iframe","object","embed",'[contenteditable="true"]','[tabindex]:not([tabindex^="-"])'].join(", ");function J$(e){return Array.from(e.querySelectorAll(Ly)).filter(t=>{if(t.disabled||t.hasAttribute("disabled")||t.getAttribute("aria-hidden")==="true"||t.tabIndex<0)return!1;if(typeof window<"u"&&typeof window.getComputedStyle=="function")try{const n=window.getComputedStyle(t);if(n.display==="none"||n.visibility==="hidden")return!1}catch{}return!0})}function Y$(e,t,n){const r=y.useRef(n);r.current=n,y.useEffect(()=>{if(!t)return;const s=i=>{if(i.key==="Escape"){i.stopPropagation(),r.current();return}if(i.key!=="Tab")return;const o=e.current;if(!o)return;const a=J$(o);if(a.length===0){i.preventDefault(),o.focus();return}const l=a[0],u=a[a.length-1],d=document.activeElement;let h=a.indexOf(d);if(h===-1&&d&&o.contains(d)){const f=d.closest?.(Ly);f&&(h=a.indexOf(f))}if(i.preventDefault(),h===-1){i.shiftKey?u.focus():l.focus();return}i.shiftKey?h<=0?u.focus():a[h-1].focus():h>=a.length-1?l.focus():a[h+1].focus()};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[t,e])}function Q$({open:e,onOpenChange:t,title:n,body:r,destructive:s,confirmLabel:i="Confirm",cancelLabel:o="Cancel",onConfirm:a,className:l}){const u=y.useRef(null),d=y.useRef(null),h=y.useRef(null);return Y$(u,e,()=>t(!1)),y.useEffect(()=>{if(e)return h.current=document.activeElement,d.current?.focus(),()=>{h.current?.focus?.()}},[e]),!e||typeof document>"u"?null:Lc.createPortal(c.jsxs("div",{role:"presentation","data-pyric-ui":"confirm-portal",onClick:f=>{f.target===f.currentTarget&&t(!1)},children:[c.jsx("div",{"data-pyric-ui":"confirm-overlay","aria-hidden":"true"}),c.jsxs("div",{ref:u,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:[c.jsx("div",{id:"pyric-confirm-title","data-pyric-confirm-title":!0,children:n}),r?c.jsx("div",{id:"pyric-confirm-body","data-pyric-confirm-body":!0,children:r}):null,c.jsxs("div",{"data-pyric-confirm-actions":!0,children:[c.jsx("button",{type:"button","data-pyric-confirm-cancel":!0,onClick:()=>t(!1),children:o}),c.jsx("button",{ref:d,type:"button","data-pyric-confirm-confirm":!0,"data-pyric-destructive":s?"":void 0,onClick:a,children:i})]})]})]}),document.body)}const Uy=y.createContext(null);function Kn(){const e=y.useContext(Uy);if(!e)throw new Error("useConfirm: missing <ConfirmProvider> ancestor");return e}function Bc({children:e,dialogClassName:t}){const[n,r]=y.useState(null),s=y.useRef(!1),i=y.useCallback(u=>new Promise(d=>{s.current=!1,r({options:u,resolve:d})}),[]),o=y.useCallback(()=>{n&&(s.current||(s.current=!0,n.resolve(!0),r(null)))},[n]),a=y.useCallback(u=>{u||n&&(s.current||(s.current=!0,n.resolve(!1),r(null)))},[n]),l=y.useMemo(()=>i,[i]);return c.jsxs(Uy.Provider,{value:l,children:[e,n?c.jsx(Q$,{open:!0,onOpenChange:a,title:n.options.title,body:n.options.body,destructive:n.options.destructive,confirmLabel:n.options.confirmLabel,cancelLabel:n.options.cancelLabel,onConfirm:o,className:t}):null]})}function X$(e){return e.email??e.phoneNumber??e.displayName??e.uid}function Z$({user:e,onDelete:t,title:n="Delete user",body:r,confirmLabel:s="Delete",renderTrigger:i,className:o}){const a=Kn(),l=async()=>{await a({title:n,body:r??`This will permanently delete ${X$(e)}.`,destructive:!0,confirmLabel:s})&&t(e.uid)};return i?c.jsx(c.Fragment,{children:i({onClick:l})}):c.jsx("button",{type:"button",className:o,"data-pyric-ui":"delete-user","data-pyric-destructive":!0,onClick:l,children:"Delete user"})}function eP(e,t=Date.now()){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 tP(e){const t=e.toLowerCase();return t==="flutter"?c.jsx("span",{className:"studio-remote-client__badge studio-remote-client__badge--flutter",children:"Flutter"}):t==="swift"||t==="ios"?c.jsx("span",{className:"studio-remote-client__badge studio-remote-client__badge--swift",children:"iOS Swift"}):t==="kotlin"||t==="android"?c.jsx("span",{className:"studio-remote-client__badge studio-remote-client__badge--kotlin",children:"Android Kotlin"}):c.jsx("span",{className:"studio-remote-client__badge",children:e})}function nP(e){if(!e||e.mode==="app-session")return"App Session";if(e.mode==="admin")return"Admin Bypass";if(e.mode==="anon")return"Anonymous";if(e.mode==="as"){const t=e.token?" +claims":"",n=e.tenant?` @${e.tenant}`:"";return`User: ${e.uid}${t}${n}`}return"Unknown"}function rP({auth:e,onSelectUser:t}){const{users:n,isLoading:r}=Li(e);return c.jsxs("select",{className:"studio-remote-client__select",defaultValue:"",disabled:r||n.length===0,onChange:s=>{const i=n.find(o=>o.uid===s.target.value);i&&(t(i),s.target.value="")},children:[c.jsx("option",{value:"",disabled:!0,children:r?"Loading sandbox users…":n.length===0?"No sandbox users found":"Impersonate sandbox user…"}),n.map(s=>c.jsx("option",{value:s.uid,children:s.email?`${s.email} (${s.uid.slice(0,6)}…)`:s.uid},s.uid))]})}function sP({isOpen:e,onClose:t,consumers:n,onSetLens:r,triggerRef:s,auth:i}){const[o,a]=y.useState(""),[l,u]=y.useState(""),[d,h]=y.useState(""),[f,p]=y.useState(!1),[m,g]=y.useState("");if(y.useEffect(()=>{if(!e)return;const x=v=>{v.key==="Escape"&&(t(),s?.current?.focus())};return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[e,t,s]),!e)return null;const b=i,w=(x,v)=>{let _;if(l.trim())try{_=JSON.parse(l)}catch{alert("Invalid JSON for custom claims");return}const S=d.trim()||void 0;r(x,{mode:"as",uid:v,token:_,tenant:S})};return c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"studio-remote-clients__backdrop",onMouseDown:t}),c.jsxs("div",{id:"studio-remote-clients-panel",className:"studio-remote-clients__panel",role:"dialog","aria-label":"Remote Mobile Clients",children:[c.jsxs("div",{className:"studio-remote-clients__header",children:[c.jsx("h3",{className:"studio-remote-clients__title",children:"Remote Mobile Clients"}),c.jsxs("span",{className:"studio-remote-clients__count",children:[n.length," connected"]})]}),n.length===0?c.jsx("p",{className:"studio-remote-clients__empty",children:"No remote mobile clients connected over the bridge. Connect your Flutter, iOS, or Android app to control its identity remotely."}):c.jsx("ul",{className:"studio-remote-clients__list",children:n.map(x=>c.jsxs("li",{className:"studio-remote-clients__item",children:[c.jsxs("div",{className:"studio-remote-clients__item-top",children:[c.jsxs("div",{className:"studio-remote-clients__item-info",children:[tP(x.platform),c.jsx("span",{className:"studio-remote-clients__device",children:x.deviceLabel||"Mobile Device"})]}),c.jsx("span",{className:"studio-remote-clients__freshness",children:eP(x.lastSeen)})]}),c.jsxs("div",{className:"studio-remote-clients__session",children:["Session: ",c.jsxs("code",{children:[x.clientSessionId.slice(0,10),"…"]})]}),c.jsxs("div",{className:"studio-remote-clients__current-lens",children:[c.jsx("span",{className:"studio-remote-clients__lens-label",children:"Active Lens:"}),c.jsx("span",{className:"studio-remote-clients__lens-pill",children:nP(x.activeLens)})]}),c.jsxs("div",{className:"studio-remote-clients__actions",children:[c.jsxs("div",{className:"studio-remote-clients__btn-group",children:[c.jsx("button",{type:"button",className:`studio-remote-btn ${x.activeLens?.mode==="app-session"?"studio-remote-btn--active":""}`,onClick:()=>void r(x.clientSessionId,{mode:"app-session"}),children:"App Session"}),c.jsx("button",{type:"button",className:`studio-remote-btn ${x.activeLens?.mode==="admin"?"studio-remote-btn--active":""}`,onClick:()=>void r(x.clientSessionId,{mode:"admin"}),children:"Admin"}),c.jsx("button",{type:"button",className:`studio-remote-btn ${x.activeLens?.mode==="anon"?"studio-remote-btn--active":""}`,onClick:()=>void r(x.clientSessionId,{mode:"anon"}),children:"Anon"})]}),c.jsx("div",{className:"studio-remote-clients__switcher",children:b?c.jsx(rP,{auth:b,onSelectUser:v=>w(x.clientSessionId,v.uid)}):c.jsxs("div",{className:"studio-remote-clients__manual-row",children:[c.jsx("input",{type:"text",placeholder:"Impersonate UID…",className:"studio-remote-client__input",value:o===x.clientSessionId?m:"",onChange:v=>{a(x.clientSessionId),g(v.target.value)}}),c.jsx("button",{type:"button",className:"studio-remote-btn studio-remote-btn--primary",disabled:!m.trim(),onClick:()=>{w(x.clientSessionId,m.trim()),g("")},children:"Switch"})]})}),c.jsxs("div",{className:"studio-remote-clients__advanced",children:[c.jsx("button",{type:"button",className:"studio-remote-clients__advanced-toggle",onClick:()=>p(!f),children:f?"▲ Hide Claims & Tenant":"▼ Custom Claims / Tenant"}),f?c.jsxs("div",{className:"studio-remote-clients__advanced-inputs",children:[c.jsx("input",{type:"text",placeholder:"Custom Claims JSON, e.g. { role: 'admin' }",className:"studio-remote-client__input",value:l,onChange:v=>u(v.target.value)}),c.jsx("input",{type:"text",placeholder:"Tenant ID (optional)",className:"studio-remote-client__input",value:d,onChange:v=>h(v.target.value)})]}):null]})]})]},x.clientSessionId))})]})]})}const iP={servedEpoch:null,runningEpoch:null,updateAvailable:!1,updating:!1,error:null},oP=()=>()=>{},Gd=()=>iP;function aP(){const e=lt(),t=ls(),n=Jt(),[r,s]=y.useState(!1),i=n.some(he=>he.kind==="runtime_error"&&he.error.code==="persistence-unhealthy"),o=t.status==="ready"&&t.payload.persistenceUnhealthy===!0;y.useEffect(()=>{(i||o)&&s(!0)},[i,o]);const a=l$(),l=p$(),[u,d]=y.useState(!1),h=y.useRef(null),{consumers:f,setLens:p}=g$(),[m,g]=y.useState(!1),b=y.useRef(null),w=Rt(),v=w.status==="ready"?w.handles?.auth:void 0,S=e.status==="ready"?e.env.live?.runtime:void 0,k=y.useSyncExternalStore(S?.subscribe??oP,S?.getSnapshot??Gd,S?.getSnapshot??Gd),O=t.status==="ready"&&e.status==="ready"&&!e.env.live,P=e.status==="error",R="mode"in k&&k.mode==="hosted",j=R?k.error:"worker update failed",E=k.error!==null;let $=null;O&&($="worker unreachable"),P&&($="backend error"),E&&($=j),r&&($="persistence failed — writes blocked");let C="Served, but the shared sandbox worker is not reachable; data views may be stale. Open Settings diagnostics.";P&&(C=e.error.message),E&&(C=k.error??C),r&&(C="Reads may include unsaved changes. Repair the hosted store and restart the host.");const I=!E,A=R?I:a==="available",D=!R||I;y.useEffect(()=>{if(!u)return;const he=Ge=>{Ge.key==="Escape"&&(d(!1),h.current?.focus())};return document.addEventListener("keydown",he),()=>document.removeEventListener("keydown",he)},[u]);const T=k.updateAvailable,U=k.updating?"updating worker…":"update worker",q=$!==null,F=D&&l!==null&&l.count>0,we=l?.prominent===!0?"studio-chip studio-chip--live studio-presence__trigger":"studio-chip studio-presence__trigger",M=l!==null&&l.otherCount>0,ge=l?.otherCount===1?"":"s";let ce=`${l?.chipLabel}. Expand for details.`;M&&(ce=`${l.chipLabel}. ${l.otherCount} other page${ge} can keep the worker alive.`),R&&(ce=`${l?.chipLabel}. These pages share the Node host.`);const Z=R?"Data is shared by every client connected to this host.":l?.boundaryCopy;let fe=l?.count===1?"This page is the only connection to the shared sandbox worker.":`${l?.count} pages share this sandbox worker. Closing this page alone will not restart it.`;R&&(fe="These pages share the Node-hosted sandbox. Closing a page does not stop the host.");const et=D&&f.length>0,wt=f.length===1,ut=wt?"":"s",ie=wt?"1 remote client":`${f.length} remote clients`;return c.jsxs("div",{className:"studio__status","aria-label":"Studio status",children:[T&&c.jsxs("button",{type:"button",className:"studio-chip studio-chip--warn",disabled:k.updating,title:"The Studio backend is running older code. Update every connected page to the served worker version.",onClick:()=>void S?.update().catch(()=>{}),children:[c.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),U]}),q&&c.jsxs("a",{className:"studio-chip studio-chip--warn",href:Ct({tab:"settings"}),title:C,onClick:he=>{he.preventDefault(),Ae({tab:"settings"})},children:[c.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),$]}),F&&c.jsxs("span",{className:"studio-presence",children:[c.jsxs("button",{ref:h,type:"button",className:we,"aria-haspopup":"dialog","aria-expanded":u,"aria-controls":"studio-presence-panel",title:ce,onClick:()=>d(he=>!he),children:[c.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),l.chipLabel]}),u&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"studio-presence__backdrop",onMouseDown:()=>d(!1)}),c.jsxs("div",{id:"studio-presence-panel",className:"studio-presence__panel",role:"dialog","aria-label":"Connected pages",children:[c.jsx("p",{className:"studio-presence__lead",children:fe}),c.jsx("ul",{className:"studio-presence__list",children:l.clients.map(he=>c.jsxs("li",{className:"studio-presence__item",children:[c.jsxs("div",{className:"studio-presence__item-head",children:[c.jsx("span",{className:"studio-presence__kind",children:he.kindLabel}),he.isThisPage?c.jsx("span",{className:"studio-presence__this",children:"This page"}):null]}),c.jsx("div",{className:"studio-presence__route",title:he.route,children:he.route}),c.jsxs("div",{className:"studio-presence__meta",children:[he.visibilityLabel," · ",he.freshnessLabel]})]},he.clientId))}),c.jsx("p",{className:"studio-presence__boundary",children:Z})]})]})]}),et&&c.jsxs("span",{className:"studio-remote-clients",children:[c.jsxs("button",{ref:b,type:"button",className:"studio-chip studio-chip--live studio-remote-clients__trigger","aria-haspopup":"dialog","aria-expanded":m,"aria-controls":"studio-remote-clients-panel",title:`${f.length} remote client${ut} connected over the bridge. Click to control identity.`,onClick:()=>g(he=>!he),children:[c.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),ie]}),c.jsx(sP,{isOpen:m,onClose:()=>g(!1),consumers:f,onSetLens:p,triggerRef:b,auth:v})]}),A&&c.jsxs("span",{className:"studio-chip studio-chip--live",title:"MCP bridge available — a sandbox peer is connected; external agents can reach this sandbox.",children:[c.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),"MCP bridge"]})]})}function cP(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 Jd(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 lP({events:e,groupBatches:t=!0,groupListenerRuns:n=!0}){return y.useMemo(()=>{const r=[];let s=0;for(;s<e.length;){const i=e[s];if(t&&i.groupId){let o=s+1;for(;o<e.length&&e[o].groupId===i.groupId;)o++;const a=e.slice(s,o),l=i.origin==="transaction"?"transaction":"batch";r.push(Jd(l,i.groupId,a)),s=o;continue}if(n&&i.origin==="listener"){let o=s+1;for(;o<e.length&&e[o].origin==="listener"&&!e[o].groupId&&cP(e[o],i);)o++;const a=e.slice(s,o);if(a.length>1){const l=i.triggeredBy?`${i.triggeredBy.method}:${i.triggeredBy.path}`:"unknown";r.push(Jd("listener-run",`listener-run:${l}:${s}`,a))}else r.push({type:"single",event:i});s=o;continue}r.push({type:"single",event:i}),s++}return{items:r}},[e,t,n])}const uP={buckets:[],total:0,denies:0,maxCount:0,outOfWindow:0};function dP({events:e,window:t,bucketCount:n=30}){return y.useMemo(()=>fP(e,t,n),[e,t.start,t.end,n])}function fP(e,t,n=30){const r=t.end-t.start;if(n<=0||r<=0)return uP;const s=r/n,i=new Array(n).fill(0),o=new Array(n).fill(0);let a=0,l=0,u=0;for(const f of e){const p=f.at;if(p<t.start||p>=t.end){u++;continue}let m=Math.floor((p-t.start)/s);m>=n&&(m=n-1),i[m]++,a++,f.result==="deny"&&(o[m]++,l++)}let d=0;for(const f of i)f>d&&(d=f);return{buckets:i.map((f,p)=>{const m=o[p];return{index:p,start:t.start+p*s,end:t.start+(p+1)*s,count:f,denies:m,allows:f-m,heightRatio:d===0?0:f/d,denyHeightRatio:d===0?0:m/d}}),total:a,denies:l,maxCount:d,outOfWindow:u}}const hP=new Set(["get","list"]),pP=new Set(["create","update","set"]),mP=new Set(["delete","remove"]),yP=[{key:"reads",label:"Read ops"},{key:"writes",label:"Writes"},{key:"deletes",label:"Deletes"}],gP=[{key:"allows",label:"Allows"},{key:"denies",label:"Denies"},{key:"errors",label:"Errors"}];function Ui(e){return e.origin==="admin"}function bP(e,t=Ui){return e.result==="allow"||t(e)?hP.has(e.method)?"reads":pP.has(e.method)?"writes":mP.has(e.method)?"deletes":null:null}function wP(e,t=Ui){return t(e)?null:e.result==="allow"?"allows":e.result==="deny"?"denies":e.result==="error"?"errors":null}const vP=e=>({points:[],series:e.map(t=>({key:t.key,label:t.label,values:[],total:0})),maxValue:0});function By(e,t,n,r,s){const i=t.end-t.start;if(n<=0||i<=0)return vP(r);const o=i/n,a=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 p=f.at;if(p<t.start||p>=t.end)continue;const m=s(f);if(m==null)continue;let g=Math.floor((p-t.start)/o);g>=n&&(g=n-1);const b=a.get(m);b[g]++,l.set(m,(l.get(m)??0)+1)}let u=0;for(const f of a.values())for(const p of f)p>u&&(u=p);const d=new Array(n);for(let f=0;f<n;f++)d[f]={index:f,start:t.start+f*o,end:t.start+(f+1)*o};const h=r.map(f=>({key:f.key,label:f.label,values:a.get(f.key),total:l.get(f.key)??0}));return{points:d,series:h,maxValue:u}}function xP(e,t,n=24,r=Ui){return By(e,t,n,yP,s=>bP(s,r))}function _P(e,t,n=24,r=Ui){return By(e,t,n,gP,s=>wP(s,r))}function SP({events:e,window:t,bucketCount:n=24,isAdmin:r}){return y.useMemo(()=>xP(e,t,n,r),[e,t.start,t.end,n,r])}function kP({events:e,window:t,bucketCount:n=24,isAdmin:r}){return y.useMemo(()=>_P(e,t,n,r),[e,t.start,t.end,n,r])}function Ta({children:e,kind:t,className:n,ariaLabel:r}){return c.jsx("span",{"data-pyric-badge":"","data-pyric-badge-kind":t,className:n,"aria-label":r,children:r?c.jsx("span",{"aria-hidden":"true",children:e}):e})}function Wr(e){const t=new Date(e),n=r=>String(r).padStart(2,"0");return`${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`}function Fy({event:e,selected:t,onSelect:n,renderClassification:r,formatTime:s=Wr,className:i}){return c.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:[c.jsx("span",{"data-pyric-traffic-time":"",children:s(e.at)}),c.jsx("span",{"data-pyric-traffic-service":e.service??"",children:e.service??""}),c.jsx(Ta,{kind:e.method,children:e.method}),c.jsx("span",{"data-pyric-traffic-path":"",children:e.path||"/"}),r?r(e):null]})}const jP={batch:"batch write",transaction:"transaction","listener-run":"listener re-evals"};function EP({group:e,defaultExpanded:t=!1,onSelect:n,selectedId:r,renderClassification:s,formatTime:i,className:o}){const[a,l]=y.useState(t);return c.jsxs("div",{className:o,"data-pyric-traffic-group":"","data-pyric-group-kind":e.kind,"data-pyric-expanded":a?"":void 0,children:[c.jsxs("button",{type:"button",onClick:()=>l(u=>!u),"data-pyric-traffic-group-header":"","data-pyric-group-kind":e.kind,"aria-expanded":a,children:[c.jsx("span",{"data-pyric-group-kind-label":"",children:jP[e.kind]}),c.jsxs("span",{"data-pyric-group-count":"",children:["×",e.count]}),e.denies>0?c.jsxs("span",{"data-pyric-group-denies":"",children:[e.denies," denied"]}):null]}),a?c.jsx("ul",{"data-pyric-traffic-group-members":"",children:e.events.map(u=>c.jsx("li",{"data-pyric-traffic-entry":"","data-pyric-traffic-id":u.id,children:c.jsx(Fy,{event:u,selected:u.id===r,onSelect:n,renderClassification:s,formatTime:i})},u.id))}):null]})}function CP(e){return e<0?0:e>1?1:e}function Io(e,t){const n=t.end-t.start;return n<=0?0:CP((e-t.start)/n)}function Vy({events:e,buckets:t,window:n,bucketCount:r=30,brush:s,onBrush:i,renderBucketSummary:o,liveAt:a,header:l,axis:u,emptyState:d,className:h}){const f=y.useId(),[p,m]=y.useState(null),[g,b]=y.useState(null),w=dP({events:e??[],window:n,bucketCount:r}),x=t??w,{buckets:v,total:_}=x,S=p??g,k=S===null?null:v.find(E=>E.index===S)??null,N=k!==null&&s?.start===k.start&&s.end===k.end;if(v.length===0)return c.jsx("div",{className:h,"data-pyric-ui":"traffic-timeline","data-pyric-empty":"",children:d});const O=_===0,P=a===void 0?n.end:a,R=P==null?null:Io(P,n),j=typeof u=="function"?u(n):u;return c.jsxs("div",{className:h,"data-pyric-ui":"traffic-timeline","data-pyric-empty":O?"":void 0,children:[l!==void 0&&c.jsx("div",{"data-pyric-timeline-header":"",children:l}),c.jsxs("div",{"data-pyric-timeline-chart":"",children:[c.jsx("div",{"data-pyric-timeline-bars":"",role:i?"group":"img","aria-label":"request volume over time",children:v.map(E=>c.jsx(NP,{bucket:E,window:n,onBrush:i,onHover:o?m:void 0,onFocus:o?b:void 0,summaryId:o&&!N&&k?.index===E.index?f:void 0,selected:s?.start===E.start&&s.end===E.end},E.index))}),k&&o&&!N?c.jsx("div",{id:f,role:"tooltip","data-pyric-bucket-summary":"",style:{"--pyric-bucket-summary-x":(k.index+.5)/Math.max(v.length,1)},children:o(k)}):null,s&&c.jsx("div",{"data-pyric-brush":"","aria-hidden":"true",style:{"--pyric-brush-left":Io(s.start,n),"--pyric-brush-right":1-Io(s.end,n)}}),R!=null&&c.jsx("div",{"data-pyric-live":"","aria-hidden":"true",style:{"--pyric-live-x":R}})]}),j!=null&&c.jsx("div",{"data-pyric-timeline-axis":"",children:j})]})}function NP({bucket:e,window:t,onBrush:n,onHover:r,onFocus:s,summaryId:i,selected:o}){const a=n!==void 0,l=`${e.count} ${e.count===1?"request":"requests"}`,u=`${e.denies} denied`;return c.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":o?"":void 0,disabled:!a,"aria-label":`${l}, ${u}`,"aria-describedby":i,"aria-pressed":a?o: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:a?()=>n?.({start:e.start,end:e.end}):void 0,style:{"--pyric-bucket-h":e.heightRatio,"--pyric-bucket-deny-h":e.denyHeightRatio},children:[c.jsx("span",{"data-pyric-bucket-allow":"","aria-hidden":"true"}),c.jsx("span",{"data-pyric-bucket-deny":"","aria-hidden":"true"})]})}const RP=e=>String(e);function Fc({series:e,visible:t,onToggle:n,formatValue:r=RP,className:s}){const i=t!==void 0&&n!==void 0;return c.jsx("div",{className:s,"data-pyric-ui":"traffic-metric-cards",role:i?"group":void 0,children:e.map((o,a)=>{const l=t?t.has(o.key):!0,u=c.jsxs(c.Fragment,{children:[c.jsx("span",{"data-pyric-metric-swatch":"","aria-hidden":"true"}),c.jsx("span",{"data-pyric-metric-label":"",children:o.label}),c.jsx("span",{"data-pyric-metric-value":"",children:r(o.total)})]});return i?c.jsxs("label",{"data-pyric-metric-card":"","data-pyric-metric-key":o.key,"data-pyric-series-index":a,"data-pyric-metric-hidden":l?void 0:"",children:[c.jsx("input",{type:"checkbox",checked:l,onChange:()=>n(o.key),"data-pyric-metric-checkbox":""}),u]},o.key):c.jsx("span",{"data-pyric-metric-card":"","data-pyric-metric-key":o.key,"data-pyric-series-index":a,children:u},o.key)})})}const IP=e=>String(e),AP=e=>new Date(e).toLocaleTimeString();function qy({points:e,series:t,visible:n,omitZeroSeries:r=!1,formatValue:s=IP,formatTime:i=AP,emptyState:o,className:a}){const[l,u]=y.useState(null);if(e.length===0)return c.jsx("div",{className:a,"data-pyric-ui":"traffic-line-chart","data-pyric-empty":"",children:o});const d=t.filter(w=>(!n||n.has(w.key))&&(!r||w.total>0));let h=0;for(const w of d)for(const x of w.values)x>h&&(h=x);const f=h===0?1:h,p=e.length,m=w=>p===1?50:w/(p-1)*100,g=w=>100-w/f*100,b=l!=null?e[l]:null;return c.jsx("div",{className:a,"data-pyric-ui":"traffic-line-chart",children:c.jsxs("div",{"data-pyric-chart-svg":"",children:[c.jsx("svg",{viewBox:"0 0 100 100",preserveAspectRatio:"none",role:"img","aria-label":"metrics over time",children:t.map(w=>{const x=t.indexOf(w);if(!((!n||n.has(w.key))&&(!r||w.total>0)))return null;const _=w.values.map((S,k)=>`${k===0?"M":"L"}${m(k)},${g(S)}`).join(" ");return c.jsx("path",{"data-pyric-chart-line":"","data-pyric-series-key":w.key,"data-pyric-series-index":x,d:_,fill:"none",vectorEffect:"non-scaling-stroke"},w.key)})}),c.jsx("div",{"data-pyric-chart-hits":"",children:e.map((w,x)=>c.jsx("button",{type:"button","data-pyric-chart-hit":"","data-pyric-point-index":x,onMouseEnter:()=>u(x),onFocus:()=>u(x),onMouseLeave:()=>u(v=>v===x?null:v),onBlur:()=>u(v=>v===x?null:v),"aria-label":`${i(w.start)} to ${i(w.end)}`},w.index))}),b&&c.jsxs("div",{"data-pyric-chart-tooltip":"",style:{"--pyric-hover-x":m(b.index)},children:[c.jsxs("div",{"data-pyric-tooltip-time":"",children:[i(b.start)," – ",i(b.end)]}),d.map(w=>c.jsxs("div",{"data-pyric-tooltip-row":"","data-pyric-series-key":w.key,"data-pyric-series-index":t.indexOf(w),children:[c.jsx("span",{"data-pyric-tooltip-label":"",children:w.label}),c.jsx("span",{"data-pyric-tooltip-value":"",children:s(w.values[b.index])})]},w.key))]})]})})}function Wy(e={}){const[t]=y.useState(()=>(e.captureOwnerStack,void 0)),[n,r]=y.useState(void 0),s=y.useCallback(o=>{o!==null&&r(o)},[]);return{owner:y.useMemo(()=>{if(t!==void 0)return n===void 0?t:{...t,element:n}},[t,n]),ref:s}}function OP(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 $P={addDoc:ph,collection:pr,deleteDoc:qo,doc:st,getDoc:Mp,getDocs:li,limit:di,onSnapshot:BE,query:ui,setDoc:Hs,startAfter:UE},zy=y.createContext($P);function Vc(){return y.useContext(zy)}function PP({value:e,children:t}){return y.createElement(zy.Provider,{value:e},t)}function DP(e){const{onSnapshot:t}=Vc(),{owner:n}=Wy(),[r,s]=y.useState(()=>({data:void 0,error:void 0,isLoading:e!=null}));return y.useEffect(()=>{if(!e){s({data:void 0,error:void 0,isLoading:!1});return}return s(o=>({data:o.data,error:void 0,isLoading:!0})),t(e,{owner:n},o=>s({data:o,error:void 0,isLoading:!1}),o=>s({data:void 0,error:OP(o),isLoading:!1}))},[t,n,e]),r}function Bi(e){return e==null?"null":typeof e=="string"?"string":typeof e=="number"?"number":typeof e=="boolean"?"boolean":typeof e=="object"&&gn(e)!==null?"vector":Array.isArray(e)?"array":e instanceof Vt?"timestamp":e instanceof Pn?"geopoint":e instanceof on?"bytes":typeof e=="object"&&Hy(e)?"timestamp":typeof e=="object"&&Gy(e)?"geopoint":typeof e=="object"&&Ky(e)?"bytes":typeof e=="object"&&TP(e)?"reference":typeof e=="object"?"map":"null"}function Hy(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 Ky(e){const t=e,n=Object.keys(t);return n.length===1?t.bytes instanceof Uint8Array:n.length===2&&t.type==="firestore/bytes/1.0"&&typeof t.bytes=="string"}function qc(e){if(e instanceof on)return e;const t=e;return typeof t.bytes=="string"?on.fromBase64String(t.bytes):on.fromUint8Array(t.bytes)}function Gy(e){const t=e;return Object.keys(t).length===2&&typeof t.latitude=="number"&&typeof t.longitude=="number"}function TP(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 gn(e){if(e===null||typeof e!="object")return null;const t=e;if(t.typeName==="vector"&&Ns(t.value)||t.__type__==="__vector__"&&Ns(t.value))return Rs(t.value);if(Ns(t._values))return Rs(t._values);if(typeof t.toArray=="function")try{const n=t.toArray();if(Ns(n))return Rs(n)}catch{}return null}function Ns(e){return Array.isArray(e)&&e.every(t=>typeof t=="number")}function Rs(e){const t=e.slice();return{values:t,dimension:t.length}}const Yd=4;function Jy(e){const t=e.values.slice(0,Yd).join(", "),n=e.values.length>Yd?", …":"";return`vector · ${e.dimension} [${t}${n}]`}function gi(e){const t=gn(e);if(t)return Jy(t);if(Array.isArray(e))return e.map(gi);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]=gi(i);return r}}return e}function Yy(){return crypto.randomUUID()}function MP(e){const t=Yy(),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))Ma(n,t,r,s);return n}function Ma(e,t,n,r){const s=Bi(r),i=Yy(),o={id:i,parentId:t,key:n,type:s,value:LP(s)?void 0:r};if(e.nodes[i]=o,e.childIds[i]=[],e.childIds[t].push(i),s==="map"&&r&&typeof r=="object")for(const[a,l]of Object.entries(r))Ma(e,i,a,l);else if(s==="array"&&Array.isArray(r))for(const a of r)Ma(e,i,null,a);return i}function LP(e){return e==="map"||e==="array"}function Qy(e){const t=e.nodes[e.rootId];if(!t||t.type!=="map")throw new Error("treeToData: tree root must be a map node");return La(e,e.rootId)}function La(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]=La(e,s))}return r}case"array":{const r=[];for(const s of e.childIds[t]??[])r.push(La(e,s));return r}default:return n.value}}function Ua(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 Xy(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 Zy(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 Vt?void 0:"Expected a Timestamp";case"geopoint":return t instanceof Pn?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 on?void 0:"Expected a Bytes value";case"vector":return gn(t)!==null?void 0:"Expected a vector value";case"map":case"array":return}}function eg(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=Zy(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]??[],o=new Map;for(const a of i){const l=t[a];if(!l)continue;const u=l.key??"";u||(l.error||n++,t[a].error=t[a].error??"Field name is required");const d=o.get(u)??[];d.push(a),o.set(u,d)}for(const[a,l]of o)if(a&&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 Wc(e){switch(e){case"string":return"";case"number":return 0;case"boolean":return!1;case"null":return null;case"timestamp":return Vt.now();case"geopoint":return new Pn(0,0);case"reference":return{path:"",id:"",firestore:{}};case"bytes":return on.fromUint8Array(new Uint8Array);case"vector":return{__type__:"__vector__",value:[]};case"map":case"array":return}}function Ba(e){if(e===null||typeof e!="object"||gn(e)!==null)return e;if(Hy(e)){const n=e;return new Vt(n.seconds??n._seconds??0,n.nanoseconds??n._nanoseconds??0)}if(Gy(e)){const n=e;return new Pn(n.latitude,n.longitude)}if(Ky(e))return qc(e);if(Array.isArray(e))return e.map(Ba);const t=Object.getPrototypeOf(e);if(t===Object.prototype||t===null){const n={};for(const[r,s]of Object.entries(e))n[r]=Ba(s);return n}return e}function tg(e){const t=MP(Ba(e)),{tree:n,errorCount:r}=eg(t);return{tree:n,initial:n,errorCount:r}}function UP(e,t){switch(t.type){case"setValue":return vn(e,n=>FP(n,t.nodeId,t.value));case"setType":return vn(e,n=>VP(n,t.nodeId,t.newType));case"setKey":return vn(e,n=>qP(n,t.nodeId,t.key));case"addMapEntry":return vn(e,n=>WP(n,t.parentId,t.key,t.childType));case"addArrayEntry":return vn(e,n=>zP(n,t.parentId,t.childType));case"remove":return vn(e,n=>HP(n,t.nodeId));case"reset":return{tree:e.initial,initial:e.initial,errorCount:BP(e.initial)};case"replaceData":return tg(t.data);case"touch":{const n=e.tree.nodes[t.nodeId];if(!n||n.touched)return e;const r=Ua(e.tree);return r.nodes[t.nodeId]={...r.nodes[t.nodeId],touched:!0},{...e,tree:r}}case"touchAll":{const n=Ua(e.tree);for(const r of Object.keys(n.nodes))n.nodes[r]={...n.nodes[r],touched:!0};return{...e,tree:n}}}}function vn(e,t){const n=t(Ua(e.tree)),{tree:r,errorCount:s}=eg(n);return{...e,tree:r,errorCount:s}}function BP(e){let t=0;for(const n of Object.values(e.nodes))n.error&&t++;return t}function FP(e,t,n){const r=e.nodes[t];return!r||r.type==="map"||r.type==="array"||(e.nodes[t]={...r,value:n}),e}function VP(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 o of i)for(const a of Xy(e,o))delete e.nodes[a],delete e.childIds[a];e.childIds[t]=[]}const s=n==="map"||n==="array"?void 0:Wc(n);return e.nodes[t]={...r,type:n,value:s},e}function qP(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 WP(e,t,n,r){const s=e.nodes[t];if(!s||s.type!=="map")return e;const i=crypto.randomUUID(),o=r==="map"||r==="array"?void 0:Wc(r);return e.nodes[i]={id:i,parentId:t,key:n,type:r,value:o},e.childIds[i]=[],e.childIds[t]=[...e.childIds[t]??[],i],e}function zP(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:Wc(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 HP(e,t){const n=e.nodes[t];if(!n||n.id===e.rootId)return e;const r=Xy(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 ng(e={}){const t=e.initial??{},n=y.useRef(null);n.current==null&&(n.current=tg(t));const[r,s]=y.useReducer(UP,n.current),i=y.useCallback((x,v)=>s({type:"setValue",nodeId:x,value:v}),[]),o=y.useCallback((x,v)=>s({type:"setType",nodeId:x,newType:v}),[]),a=y.useCallback((x,v)=>s({type:"setKey",nodeId:x,key:v}),[]),l=y.useCallback((x,v,_)=>s({type:"addMapEntry",parentId:x,key:v,childType:_}),[]),u=y.useCallback((x,v)=>s({type:"addArrayEntry",parentId:x,childType:v}),[]),d=y.useCallback(x=>s({type:"remove",nodeId:x}),[]),h=y.useCallback(()=>s({type:"reset"}),[]),f=y.useCallback(x=>s({type:"replaceData",data:x}),[]),p=y.useCallback(x=>s({type:"touch",nodeId:x}),[]),m=y.useCallback(()=>s({type:"touchAll"}),[]),g=y.useCallback(()=>Qy(r.tree),[r.tree]),b=r.tree!==r.initial,w=r.errorCount===0;return y.useMemo(()=>({...r,isDirty:b,isValid:w,dispatch:s,setValue:i,setType:o,setKey:a,addMapEntry:l,addArrayEntry:u,remove:d,reset:h,replaceData:f,touch:p,touchAll:m,toData:g}),[r,b,w,i,o,a,l,u,d,h,f,p,m,g])}function KP({collection:e,query:t,pageSize:n=50,mode:r="paged"}){const[s,i]=y.useState([]),[o,a]=y.useState(!0),[l,u]=y.useState(void 0),[d,h]=y.useState(!1),[f,p]=y.useState(0),[m,g]=y.useState(n),b=y.useRef(0),[w,x]=y.useState(0),{addDoc:v,deleteDoc:_,doc:S,getDoc:k,getDocs:N,limit:O,onSnapshot:P,query:R,setDoc:j,startAfter:E}=Vc(),{owner:$}=Wy();y.useEffect(()=>{g(n)},[e,r,n,t]),y.useEffect(()=>{let T=!1;r==="paged"&&i([]),h(!1),a(!0),u(void 0);const W=t??e,U=r==="live"?m:n,q=R(W,O(U)),F=we=>{T||(i([...we.docs]),h(we.docs.length===U),a(!1))},Se=we=>{T||(u(we instanceof Error?we:new Error(String(we))),a(!1))};if(r==="live"){const we=++b.current,M=P(q,{owner:$},ne=>{x(we),F(ne)},Se);return()=>{T=!0,M()}}return N(q).then(we=>{F(we)}).catch(Se),()=>{T=!0}},[e,N,O,r,P,$,n,t,R,m,f]);const C=y.useCallback(()=>{if(!d||o)return;if(r==="live"){a(!0),g(q=>q+n);return}const T=s[s.length-1];if(!T)return;a(!0);const U=R(t??e,E(T),O(n));N(U).then(q=>{i(F=>[...F,...q.docs]),h(q.docs.length===n),a(!1)}).catch(q=>{u(q instanceof Error?q:new Error(String(q))),a(!1)})},[e,s,N,d,o,O,r,n,t,R,E]),I=y.useCallback(async(T,W,U)=>{if(T==null){const F=await v(e,W);return r==="paged"&&p(Se=>Se+1),F}const q=S(e,T);if(U?.onExisting==="fail"){const F=await k(q);if(typeof F.exists=="function"?F.exists():!!F.exists){const we=new Error(`Document "${T}" already exists.`);throw we.code="already-exists",we}}return await j(q,W),r==="paged"&&p(F=>F+1),q},[v,e,S,k,r,j]),A=y.useCallback(async T=>{await _(T),r==="paged"&&p(W=>W+1)},[_,r]),D=y.useCallback(()=>p(T=>T+1),[]);return{documents:s,isLoading:o,error:l,subscriptionGeneration:w,hasMore:d,loadMore:C,createDocument:I,deleteDocument:A,refresh:D}}function GP({firestore:e,documentRef:t,listSubcollections:n}){const[r,s]=y.useState([]),[i,o]=y.useState(!1),[a,l]=y.useState(void 0),u=y.useRef(n);u.current=n;const d=t?.path;return y.useEffect(()=>{if(!t){s([]),o(!1),l(void 0);return}let h=!1;return o(!0),l(void 0),u.current(e,t).then(f=>{h||(s(f),o(!1))}).catch(f=>{h||(l(f instanceof Error?f:new Error(String(f))),o(!1))}),()=>{h=!0}},[e,d]),{subcollections:r,isLoading:i,error:a}}function Qd(e){return typeof e=="object"&&e!==null&&"isEqual"in e&&typeof e.isEqual=="function"}function Xd(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function bi(e,t){if(Object.is(e,t))return!0;if(Qd(e))return e.isEqual(t);if(Qd(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)=>bi(s,t[i]));if(!Xd(e)||!Xd(t))return!1;const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(s=>s in t&&bi(e[s],t[s]))}function JP({value:e,path:t}){return c.jsx("span",{"data-pyric-field-type":"string","data-pyric-field-path":t,children:e})}function YP({value:e,onChange:t,error:n,path:r}){return c.jsxs("label",{"data-pyric-field-type":"string","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[c.jsx("input",{type:"text",value:e,onChange:s=>t(s.target.value),"aria-invalid":n?"true":void 0}),n?c.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const QP={type:"string",Display:JP,Edit:YP};function XP({value:e,path:t}){return c.jsx("span",{"data-pyric-field-type":"number","data-pyric-field-path":t,children:String(e)})}function ZP({value:e,onChange:t,error:n,path:r}){return c.jsxs("label",{"data-pyric-field-type":"number","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[c.jsx("input",{type:"number",value:Number.isFinite(e)?e:"",onChange:s=>{const i=s.target.value,o=i===""?Number.NaN:parseFloat(i);t(o)},"aria-invalid":n?"true":void 0}),n?c.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const eD={type:"number",Display:XP,Edit:ZP};function tD({value:e,path:t}){return c.jsx("span",{"data-pyric-field-type":"boolean","data-pyric-field-path":t,"data-value":e?"true":"false",children:e?"true":"false"})}function nD({value:e,onChange:t,path:n}){return c.jsx("span",{"data-pyric-field-type":"boolean","data-pyric-field-path":n,"data-value":e?"true":"false",children:c.jsxs("select",{value:e?"true":"false",onChange:r=>t(r.target.value==="true"),"aria-label":"Boolean value","data-pyric-boolean-select":!0,children:[c.jsx("option",{value:"true",children:"true"}),c.jsx("option",{value:"false",children:"false"})]})})}const rD={type:"boolean",Display:tD,Edit:nD};function sD({path:e}){return c.jsx("span",{"data-pyric-field-type":"null","data-pyric-field-path":e,children:"null"})}function iD({path:e}){return c.jsx("span",{"data-pyric-field-type":"null","data-pyric-field-path":e,children:"null"})}const oD={type:"null",Display:sD,Edit:iD};function zc(e){if(e instanceof Vt)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 aD(e){const t=e;return new Vt(t.seconds??t._seconds??0,t.nanoseconds??t._nanoseconds??0)}function cD(e,t){const n=new Date(e);if(Number.isNaN(n.getTime()))return null;const r=zc(t);return!Number.isNaN(r.getTime())&&r.getTime()===n.getTime()?t instanceof Vt?t:aD(t):Vt.fromDate(n)}function lD({value:e,path:t}){const n=zc(e),r=Number.isNaN(n.getTime())?"":n.toISOString();return c.jsx("time",{dateTime:r,"data-pyric-field-type":"timestamp","data-pyric-field-path":t,children:r})}function uD({value:e,onChange:t,error:n,path:r}){const s=zc(e),i=new Date(s.getTime()-s.getTimezoneOffset()*6e4),o=Number.isNaN(i.getTime())?"":i.toISOString().slice(0,23);return c.jsxs("label",{"data-pyric-field-type":"timestamp","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[c.jsx("input",{type:"datetime-local",step:"0.001",value:o,onChange:a=>{const l=a.target.value;if(!l)return;const u=cD(l,e);u&&t(u)},"aria-invalid":n?"true":void 0}),n?c.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const dD={type:"timestamp",Display:lD,Edit:uD};function fD({value:e,path:t}){return c.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 hD({value:e,onChange:t,error:n,path:r}){return c.jsxs("span",{"data-pyric-field-type":"geopoint","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[c.jsx("label",{children:c.jsx("input",{type:"number",step:"any",min:-90,max:90,value:e.latitude,onChange:s=>{const i=parseFloat(s.target.value);try{t(new Pn(i,e.longitude))}catch{}},"aria-label":"Latitude"})}),c.jsx("label",{children:c.jsx("input",{type:"number",step:"any",min:-180,max:180,value:e.longitude,onChange:s=>{const i=parseFloat(s.target.value);try{t(new Pn(e.latitude,i))}catch{}},"aria-label":"Longitude"})}),n?c.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const pD={type:"geopoint",Display:fD,Edit:hD},rg=y.createContext({});rg.Provider;function mD(){return y.useContext(rg)}function yD({value:e,path:t}){const{onReferenceClick:n}=mD();return n?c.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}):c.jsx("span",{"data-pyric-field-type":"reference","data-pyric-field-path":t,"data-target-path":e.path,children:e.path})}function gD({value:e,onChange:t,error:n,path:r}){return c.jsxs("label",{"data-pyric-field-type":"reference","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[c.jsx("input",{type:"text",value:e.path,placeholder:"users/alice",onChange:s=>{const i=s.target.value,o=i.split("/").filter(Boolean),a=o[o.length-1]??"",l=e.firestore??{};t({path:i,id:a,firestore:l,type:"document"})},"aria-invalid":n?"true":void 0}),n?c.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const bD={type:"reference",Display:yD,Edit:gD};function wD({value:e,path:t}){const n=qc(e),r=n.toBase64();return c.jsx("code",{"data-pyric-field-type":"bytes","data-pyric-field-path":t,"data-byte-length":String(n.toUint8Array().byteLength),children:r})}function vD({value:e,onChange:t,error:n,path:r}){return c.jsxs("label",{"data-pyric-field-type":"bytes","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[c.jsx("textarea",{value:qc(e).toBase64(),onChange:s=>{try{t(on.fromBase64String(s.target.value))}catch{}},"aria-invalid":n?"true":void 0}),n?c.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const xD={type:"bytes",Display:wD,Edit:vD};function Fa({value:e,path:t,fieldEditors:n}){const r=Bi(e),s=n[r];if(!s)return null;const{Display:i}=s;return c.jsx(i,{value:e,path:t,fieldEditors:n})}function sg({label:e,value:t,path:n,fieldEditors:r,kind:s}){const i=Bi(t),o=i==="map"||i==="array",[a,l]=y.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 o?c.jsxs("li",{"data-pyric-tree-entry":!0,"data-pyric-tree-nested":!0,...d,children:[c.jsxs("button",{type:"button","data-pyric-tree-toggle":!0,"aria-expanded":a,onClick:()=>l(h=>!h),children:[c.jsx("span",{"data-pyric-tree-chevron":!0,"aria-hidden":"true",children:"›"}),c.jsx("span",{...u,children:e})]}),a?c.jsx(Fa,{value:t,path:n,fieldEditors:r}):null]}):c.jsxs("li",{"data-pyric-tree-entry":!0,...d,children:[c.jsx("span",{"data-pyric-tree-chevron":!0,"data-pyric-tree-chevron-empty":!0,"aria-hidden":"true"}),c.jsx("span",{...u,children:e}),c.jsx(Fa,{value:t,path:n,fieldEditors:r})]})}function _D({value:e,path:t,fieldEditors:n}){const r=Object.entries(e).sort(([s],[i])=>s.localeCompare(i));return c.jsx("ul",{"data-pyric-field-type":"map","data-pyric-tree":!0,"data-pyric-field-path":t,children:r.map(([s,i])=>c.jsx(sg,{label:s,value:i,path:t?`${t}.${s}`:s,fieldEditors:n??{},kind:"key"},s))})}const SD={type:"map",Display:_D};function kD({value:e,path:t,fieldEditors:n}){return c.jsx("ul",{"data-pyric-field-type":"array","data-pyric-tree":!0,"data-pyric-field-path":t,children:e.map((r,s)=>c.jsx(sg,{label:String(s),value:r,path:t?`${t}[${s}]`:`[${s}]`,fieldEditors:n??{},kind:"index"},s))})}const jD={type:"array",Display:kD},Zd=4;function ED(e){return e.length<=Zd?`[${e.join(", ")}]`:`[${e.slice(0,Zd).join(", ")}, …]`}function CD({value:e,path:t}){const n=gn(e);return n?c.jsxs("span",{"data-pyric-field-type":"vector","data-pyric-field-path":t,"data-dimension":String(n.dimension),children:[c.jsx("span",{"data-pyric-vector-dims":!0,children:`vector · ${n.dimension}`}),c.jsx("span",{"data-pyric-vector-preview":!0,children:ED(n.values)})]}):c.jsx("span",{"data-pyric-field-type":"vector","data-pyric-field-path":t})}function ND(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 RD({value:e,onChange:t,error:n,path:r}){const s=gn(e),i=s?JSON.stringify(s.values):"[]",[o,a]=y.useState(i),[l,u]=y.useState(void 0),d=p=>{a(p);const m=ND(p);if(!m.ok){u(m.error);return}u(void 0),t(m.value)},h=s?s.dimension:0,f=l??n;return c.jsxs("label",{"data-pyric-field-type":"vector","data-pyric-field-path":r,"data-dimension":String(h),"data-pyric-error":f?"":void 0,children:[c.jsx("span",{"data-pyric-vector-dims":!0,children:`vector · ${h}`}),c.jsx("span",{"data-pyric-vector-note":!0,children:"Replace whole. Paste a JSON number array."}),c.jsx("textarea",{"data-pyric-vector-raw":!0,value:o,onChange:p=>d(p.target.value),"aria-invalid":f?"true":void 0,"aria-label":"Vector value (JSON number array)"}),f?c.jsx("span",{"data-pyric-error-message":!0,children:f}):null]})}const ID={type:"vector",Display:CD,Edit:RD},ef={string:QP,number:eD,boolean:rD,null:oD,timestamp:dD,geopoint:pD,reference:bD,bytes:xD,map:SD,array:jD,vector:ID};function ig(e){return e?{...ef,...e}:ef}function Fi(e={}){const t=y.useRef(null),n=e.narrowBreakpoint??480,r=e.mediumBreakpoint??768,[s,i]=y.useState("wide");return y.useEffect(()=>{const o=t.current;if(!o||typeof ResizeObserver>"u")return;const a=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 a.observe(o),()=>a.disconnect()},[n,r]),{ref:t,size:s}}const og=y.createContext(null);function Yt(){const e=y.useContext(og);if(!e)throw new Error("DocumentEditor.* components must render inside <DocumentEditor.Root>");return e}function AD({initial:e,fieldEditors:t,onChange:n,children:r,className:s}){const i=ng({initial:e}),o=ig(t),a=y.useRef(n);a.current=n,y.useEffect(()=>{a.current?.(i)},[i]);const{ref:l,size:u}=Fi();return c.jsx(og.Provider,{value:{editor:i,fieldEditors:o},children:c.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 OD(){const{editor:e}=Yt(),t=e.tree.childIds[e.tree.rootId]??[];return c.jsxs("div",{"data-pyric-editor-fields":!0,children:[t.map(n=>c.jsx(Hc,{nodeId:n,path:$D(e,n)},n)),c.jsx(ag,{parentId:e.tree.rootId})]})}function $D(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 Hc({nodeId:e,path:t}){const{editor:n,fieldEditors:r}=Yt(),s=n.tree.nodes[e];if(!s)return null;if(s.type==="map")return c.jsx(TD,{node:s,path:t});if(s.type==="array")return c.jsx(MD,{node:s,path:t});const o=r[s.type]?.Edit;if(!o)return null;const a=s.touched?s.error:void 0;return c.jsxs("div",{"data-pyric-field-entry":!0,"data-field-name":s.key??void 0,"data-pyric-error":a?"":void 0,onBlur:()=>n.touch(s.id),children:[c.jsx(Kc,{node:s,path:t}),c.jsx(o,{value:s.value,path:t,error:a,onChange:l=>n.setValue(s.id,l)})]})}function Kc({node:e,path:t}){const{editor:n}=Yt(),s=(e.parentId!=null?n.tree.nodes[e.parentId]:null)?.type==="map";return e.id===n.tree.rootId?null:c.jsxs("div",{"data-pyric-field-chrome":!0,"data-pyric-field-path":t,children:[s?c.jsx("input",{type:"text",value:e.key??"",onChange:o=>n.setKey(e.id,o.target.value),"aria-label":"Field name","data-pyric-field-key-input":!0,"aria-invalid":e.touched&&e.error?"true":void 0}):null,c.jsx(DD,{node:e}),c.jsx("button",{type:"button",onClick:()=>n.remove(e.id),"data-pyric-remove":!0,"aria-label":"Remove field",children:"×"})]})}const PD=["string","number","boolean","null","timestamp","geopoint","reference","bytes","vector","map","array"];function DD({node:e}){const{editor:t}=Yt(),n=e.parentId!=null?t.tree.nodes[e.parentId]:null,r=PD.filter(s=>!(n?.type==="array"&&s==="array"));return c.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=>c.jsx("option",{value:s,children:s},s))})}function TD({node:e,path:t}){const{editor:n}=Yt(),r=n.tree.childIds[e.id]??[];return c.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?c.jsx(Kc,{node:e,path:t}):null,c.jsx("div",{"data-pyric-map-children":!0,children:r.map(s=>{const i=n.tree.nodes[s];if(!i)return null;const o=t?`${t}.${i.key??""}`:i.key??"";return c.jsx(Hc,{nodeId:s,path:o},s)})}),c.jsx(ag,{parentId:e.id})]})}function MD({node:e,path:t}){const{editor:n}=Yt(),r=n.tree.childIds[e.id]??[];return c.jsxs("div",{"data-pyric-field-entry":!0,"data-pyric-field-type":"array","data-field-name":e.key??void 0,children:[c.jsx(Kc,{node:e,path:t}),c.jsx("ol",{"data-pyric-array-children":!0,children:r.map((s,i)=>{const o=t?`${t}[${i}]`:`[${i}]`;return c.jsx("li",{"data-field-index":String(i),children:c.jsx(Hc,{nodeId:s,path:o})},s)})}),c.jsx(LD,{parentId:e.id})]})}function ag({parentId:e}){const{editor:t}=Yt();return c.jsx("button",{type:"button","data-pyric-add-map-entry":!0,onClick:()=>t.addMapEntry(e,"","string"),children:"+ Add field"})}function LD({parentId:e}){const{editor:t}=Yt();return c.jsx("button",{type:"button","data-pyric-add-array-entry":!0,onClick:()=>t.addArrayEntry(e,"string"),children:"+ Add item"})}const tf={Root:AD,Fields:OD};function UD({collections:e,isLoading:t,error:n,onSelect:r,emptyState:s,className:i}){return n?c.jsx("div",{className:i,"data-pyric-ui":"collection-list","data-pyric-error":"",role:"alert",children:n.message}):t&&e.length===0?c.jsx("div",{className:i,"data-pyric-ui":"collection-list","data-pyric-loading":""}):e.length===0?c.jsx("div",{className:i,"data-pyric-ui":"collection-list","data-pyric-empty":"",children:s}):c.jsx("ul",{className:i,"data-pyric-ui":"collection-list",children:e.map(o=>c.jsx("li",{"data-pyric-collection-entry":!0,"data-pyric-collection-id":o.id,children:c.jsx("button",{type:"button",onClick:()=>r?.(o),"data-pyric-collection-select":!0,children:o.id})},o.path))})}const or=new Map;function Gc({scope:e,entries:t,equals:n=Object.is,durationMs:r=1200,ready:s=!0}){const i=y.useRef(null),o=y.useRef(new Map),a=y.useRef(new Map),[l,u]=y.useState(or);return y.useEffect(()=>{const d=i.current;if(!s){if(d&&d.scope!==e){i.current=null;for(const f of a.current.values())clearTimeout(f);a.current.clear(),o.current.clear(),u(or)}return}if(!d||d.scope!==e){i.current={scope:e,entries:t};for(const f of a.current.values())clearTimeout(f);a.current.clear(),o.current.clear(),u(or);return}const h=new Map;for(const[f,p]of t){const m=d.entries.has(f),g=d.entries.get(f);if(m&&n(g,p))continue;const b=o.current.get(f)===0?1:0;o.current.set(f,b),h.set(f,{kind:m?"modified":"added",cycle:b})}i.current={scope:e,entries:t},u(f=>{const p=new Map(f);let m=h.size>0;for(const g of f.keys())t.has(g)||(p.delete(g),m=!0);for(const[g,b]of h)p.set(g,b);return m?p.size===0?or:p:f});for(const[f,p]of h){const m=a.current.get(f);m&&clearTimeout(m);const g=setTimeout(()=>{a.current.delete(f),u(b=>{if(b.get(f)?.cycle!==p.cycle)return b;const w=new Map(b);return w.delete(f),w.size===0?or:w})},r);a.current.set(f,g)}},[r,t,n,s,e]),y.useEffect(()=>()=>{for(const d of a.current.values())clearTimeout(d);a.current.clear()},[]),l}function ar(e){return e.ref}function BD({documents:e,isLoading:t,error:n,hasMore:r,onSelect:s,onLoadMore:i,renderLabel:o,renderRowAction:a,emptyState:l,className:u,updateScope:d="document-list",virtualizeThreshold:h=100,rowHeight:f=36,virtualizedHeight:p="60vh"}){const m=y.useMemo(()=>new Map(e.map(w=>[ar(w).path,w.data()])),[e]),g=Gc({scope:d,entries:m,equals:bi,ready:!t});if(n)return c.jsx("div",{className:u,"data-pyric-ui":"document-list","data-pyric-error":"",role:"alert",children:n.message});if(t&&e.length===0)return c.jsx("div",{className:u,"data-pyric-ui":"document-list","data-pyric-loading":""});if(e.length===0)return c.jsx("div",{className:u,"data-pyric-ui":"document-list","data-pyric-empty":"",children:l});const b=e.length>h;return c.jsxs("div",{className:u,"data-pyric-ui":"document-list","data-pyric-virtualized":b?"":void 0,children:[b?c.jsx(Uc,{items:e,estimateSize:f,height:p,getItemKey:w=>ar(w).path,renderItem:w=>{const x=g.get(ar(w).path);return c.jsxs("div",{"data-pyric-document-entry":!0,"data-pyric-document-id":w.id,"data-pyric-update":x?.kind,"data-pyric-update-cycle":x?.cycle,children:[c.jsx("button",{type:"button",onClick:()=>s?.(ar(w)),"data-pyric-document-select":!0,"data-pyric-update":x?.kind,"data-pyric-update-cycle":x?.cycle,children:o?o(w):w.id}),a?c.jsx("span",{"data-pyric-document-action":!0,children:a(w)}):null]})}}):c.jsx("ul",{"data-pyric-document-list-items":!0,children:e.map(w=>{const x=ar(w),v=g.get(x.path);return c.jsxs("li",{"data-pyric-document-entry":!0,"data-pyric-document-id":w.id,"data-pyric-update":v?.kind,"data-pyric-update-cycle":v?.cycle,children:[c.jsx("button",{type:"button",onClick:()=>s?.(x),"data-pyric-document-select":!0,"data-pyric-update":v?.kind,"data-pyric-update-cycle":v?.cycle,children:o?o(w):w.id}),a?c.jsx("span",{"data-pyric-document-action":!0,children:a(w)}):null]},x.path)})}),r&&i?c.jsx("button",{type:"button",onClick:i,"data-pyric-load-more":!0,disabled:t,children:"Load more"}):null]})}const FD=/^__.*__$/;function cg(e){if(e.length===0)return"Cannot be empty";if(e.includes("/"))return'Cannot contain "/"';if(e==="."||e==="..")return'Cannot be "." or ".."';if(FD.test(e))return"Cannot match __.*__ (reserved)";if(qD(e)>1500)return"Cannot exceed 1500 bytes"}function VD(e){return cg(e)}function qD(e){return new TextEncoder().encode(e).length}function WD(e){return cg(e)}const nf="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function zD(){let e="";for(let t=0;t<20;t++)e+=nf.charAt(Math.floor(Math.random()*nf.length));return e}const HD={ref:Or,listAll:kc,getMetadata:oE,getBlob:iE,uploadBytes:rE,uploadBytesResumable:sE,deleteObject:$p},lg=y.createContext(HD);function Vi(){return y.useContext(lg)}function KD({value:e,children:t}){return y.createElement(lg.Provider,{value:e},t)}function Ao(e){return e.replace(/^\/+|\/+$/g,"")}function Va(e,t){return e.fullPath<t.fullPath?-1:e.fullPath>t.fullPath?1:0}function Oo(e,t){return e.some(n=>n.fullPath===t.fullPath)?e:[...e,t].sort(Va)}function GD(e,t){const{listAll:n,ref:r}=Vi(),s=Ao(t),[i,o]=y.useState(()=>({status:e==null?"idle":"loading",items:[],prefixes:[],error:void 0})),[a,l]=y.useState(0),u=y.useRef(new Map);y.useEffect(()=>{if(u.current.clear(),e==null){o({status:"idle",items:[],prefixes:[],error:void 0});return}let m=!1;return o({status:"loading",items:[],prefixes:[],error:void 0}),n(r(e,s)).then(g=>{m||o({status:"success",items:[...g.items].sort(Va),prefixes:[...g.prefixes].sort(Va),error:void 0})}).catch(g=>{m||o({status:"error",items:[],prefixes:[],error:g instanceof Error?g:new Error(String(g))})}),()=>{m=!0}},[e,s,a]);const d=y.useCallback(()=>l(m=>m+1),[]),h=y.useCallback(m=>{if(e==null)return;const g=m.endsWith("/"),b=Ao(m),w=s===""?"":`${s}/`;if(!b.startsWith(w)||b===s)return;const x=b.slice(w.length),v=x.indexOf("/");o(_=>{if(_.status==="idle")return _;if(v===-1)return g?(u.current.set(b,_.prefixes.some(k=>k.fullPath===b)?null:b),{..._,prefixes:Oo(_.prefixes,r(e,b))}):(u.current.set(b,_.items.some(k=>k.fullPath===b)?null:b),{..._,items:Oo(_.items,r(e,b))});const S=`${w}${x.slice(0,v)}`;return u.current.set(b,_.prefixes.some(k=>k.fullPath===S)?null:S),{..._,prefixes:Oo(_.prefixes,r(e,S))}})},[e,s]),f=y.useCallback(m=>{const g=Ao(m),b=u.current.get(g);if(u.current.delete(g),b===null)return;const w=b??g;o(x=>({...x,items:x.items.filter(v=>v.fullPath!==w),prefixes:x.prefixes.filter(v=>v.fullPath!==w)}))},[]),p=y.useMemo(()=>[...i.prefixes.map(m=>({kind:"folder",name:m.name,fullPath:m.fullPath,ref:m})),...i.items.map(m=>({kind:"object",name:m.name,fullPath:m.fullPath,ref:m}))],[i.prefixes,i.items]);return{status:i.status,items:i.items,prefixes:i.prefixes,entries:p,error:i.error,refresh:d,insertItem:h,removeItem:f}}function de(e){return e.split("/").filter(Boolean).join("/")}function JD(e={}){const{path:t,onPathChange:n,defaultPath:r=""}=e,s=t!==void 0,[i,o]=y.useState(()=>de(r)),a=s?de(t):i,l=y.useCallback(p=>{const m=de(p);s||o(m),n?.(m)},[s,n]),u=y.useMemo(()=>a===""?[]:a.split("/"),[a]),d=y.useCallback(p=>{const m=de(p);l(m.includes("/")||a===""?m:`${a}/${m}`)},[a,l]),h=y.useCallback(()=>{u.length!==0&&l(u.slice(0,-1).join("/"))},[u,l]),f=y.useCallback(p=>{l(p<0?"":u.slice(0,p+1).join("/"))},[u,l]);return{path:a,segments:u,setPath:l,enter:d,up:h,navigateToIndex:f}}const rf={status:"idle",blob:void 0,url:void 0,error:void 0};function YD(e,t){const{getBlob:n,getMetadata:r,ref:s}=Vi(),i=t==null?null:de(t),o=e!=null&&i!=null&&i!=="",[a,l]=y.useState(()=>({status:o?"loading":"idle",metadata:void 0,error:void 0})),[u,d]=y.useState(rf),[h,f]=y.useState(0),p=y.useRef(0);y.useEffect(()=>{if(p.current++,d(rf),!o){l({status:"idle",metadata:void 0,error:void 0});return}let w=!1;return l({status:"loading",metadata:void 0,error:void 0}),r(s(e,i)).then(x=>{w||l({status:"success",metadata:x,error:void 0})}).catch(x=>{w||l({status:"error",metadata:void 0,error:x instanceof Error?x:new Error(String(x))})}),()=>{w=!0}},[e,i,h]);const m=u.url;y.useEffect(()=>{if(m!==void 0)return()=>{URL.revokeObjectURL(m)}},[m]);const g=y.useCallback(()=>f(w=>w+1),[]),b=y.useCallback(()=>{if(e==null||i==null||i==="")return;const w=++p.current;d({status:"loading",blob:void 0,url:void 0,error:void 0}),n(s(e,i)).then(x=>{w===p.current&&d({status:"success",blob:x,url:URL.createObjectURL(x),error:void 0})}).catch(x=>{w===p.current&&d({status:"error",blob:void 0,url:void 0,error:x instanceof Error?x:new Error(String(x))})})},[e,i]);return{status:a.status,metadata:a.metadata,error:a.error,refresh:g,blobStatus:u.status,blob:u.blob,blobUrl:u.url,blobError:u.error,loadBlob:b}}function QD(){const[e,t]=y.useState(()=>new Map),n=y.useCallback(u=>e.has(u),[e]),r=y.useCallback(u=>{t(d=>{if(d.has(u.fullPath))return d;const h=new Map(d);return h.set(u.fullPath,u),h})},[]),s=y.useCallback(u=>{t(d=>{if(!d.has(u))return d;const h=new Map(d);return h.delete(u),h})},[]),i=y.useCallback(u=>{t(d=>{const h=new Map(d);return h.has(u.fullPath)?h.delete(u.fullPath):h.set(u.fullPath,u),h})},[]),o=y.useCallback(u=>{t(new Map(u.map(d=>[d.fullPath,d])))},[]),a=y.useCallback(()=>t(new Map),[]);return{selected:y.useMemo(()=>[...e.values()],[e]),size:e.size,isSelected:n,toggle:i,select:r,deselect:s,selectAll:o,clear:a}}function XD(e,t){const n=Or(e,t);return{storage:e,bucket:n.bucket,fullPath:`${n.fullPath}/`,name:"",parent:n,root:n.root,toString:()=>`${n.toString()}/`}}function ZD(e){return{...e,fullPath:`${e.fullPath}/`,name:""}}function eT(e){return{async*start(t){const n=e??{listAll:kc,deleteObject:$p};let r=0;const s=[t],i=[];for(;s.length>0;){const o=s.pop();i.push(o);const a=await n.listAll(o);s.push(...a.prefixes);for(const l of a.items)await n.deleteObject(l),r++,yield{deletedCount:r,done:!1}}for(const o of i)try{await n.deleteObject(ZD(o))}catch{}yield{deletedCount:r,done:!0}}}}function tT(e,t={}){const n=Vi(),[r,s]=y.useState(0),[i,o]=y.useState(!1),[a,l]=y.useState(void 0),u=y.useRef(0),d=y.useRef(t);return d.current=t,{deleteEntries:y.useCallback(async f=>{const p=++u.current;s(0),l(void 0);const m={deleted:[],failed:[]};if(e==null||f.length===0)return m;o(!0);const g=d.current.impl??eT(n);let b=0;try{for(const w of f){d.current.list?.removeItem(w.fullPath);try{if(w.kind==="object")await n.deleteObject(n.ref(e,w.fullPath)),b++;else for await(const x of g.start(n.ref(e,w.fullPath))){if(p!==u.current)return m;if(s(b+x.deletedCount),x.done){b+=x.deletedCount;break}}m.deleted.push(w.fullPath),p===u.current&&s(b)}catch(x){const v=x instanceof Error?x:new Error(String(x));m.failed.push({fullPath:w.fullPath,error:v}),d.current.list?.insertItem(w.kind==="folder"?`${w.fullPath}/`:w.fullPath),p===u.current&&m.failed.length===1&&l(v)}}return m}finally{p===u.current&&o(!1)}},[n,e]),progress:r,isRunning:i,error:a}}const nT=Object.freeze({read:!0,write:!0,delete:!0,upload:!0,reasons:Object.freeze({read:[],write:[]})}),rT=Object.freeze({read:!1,write:!1,delete:!1,upload:!1,reasons:Object.freeze({read:["No Storage rules configured; default deny."],write:["No Storage rules configured; default deny."]})});function sT(e,t={}){const{paths:n,rules:r,identity:s,writeResource:i}=t,o=e==null?null:e[Ni],[a,l]=y.useState(()=>({status:e==null?"idle":"loading",rules:null,source:"none",error:void 0}));y.useEffect(()=>{if(o==null){l({status:"idle",rules:null,source:"none",error:void 0});return}if(r!=null){try{const x=typeof r=="string"?ta(r):r;l({status:"ready",rules:x,source:"option",error:void 0})}catch(x){l({status:"error",rules:null,source:"none",error:x instanceof Error?x:new Error(String(x))})}return}let w=!1;return l({status:"loading",rules:null,source:"none",error:void 0}),o.servicePromise.then(x=>{w||l({status:"ready",rules:x.rules,source:x.rules?"sandbox":"none",error:void 0})}).catch(x=>{w||l({status:"error",rules:null,source:"none",error:x instanceof Error?x:new Error(String(x))})}),()=>{w=!0}},[o,r]);const u=s!==void 0?s:o?.context.auth??null,{rules:d,status:h}=a,f=i?.size,p=i?.contentType,m=y.useCallback(w=>{if(d==null)return h==="ready"?rT:nT;const x=de(w),v=o?.bucket??"pyric-default",_=x===""?`b/${v}/o`:`b/${v}/o/${x}`,S=R=>jp(d,{request:{auth:u,method:R,path:_,...R==="create"&&f!==void 0?{resource:{size:f,contentType:p}}:{}},resource:null}),k=S("read"),N=S("create"),O=S("delete"),P=N;return{read:k.allowed,write:P.allowed,delete:O.allowed,upload:N.allowed,reasons:{read:k.allowed?[]:k.reasons,write:P.allowed?[]:P.reasons}}},[d,h,o?.bucket,u,f,p]),g=typeof n=="string"?n:(n??[]).join(`
|
|
141
|
+
`),b=y.useMemo(()=>{const w=typeof n=="string"?[n]:n??[],x={};for(const v of w)x[de(v)]=m(v);return x},[g,m]);return{status:h,source:a.source,advisory:!1,identity:u,verdicts:b,verdictFor:m,error:a.error}}function sf(e,t){return e===""?t:t===""?e:`${e}/${t}`}function iT(e){return e instanceof Blob?e.size:e.byteLength}function oT(e){if(e instanceof Blob){const t=e;return{path:t.webkitRelativePath||t.name,data:t}}return e}function aT(e,t={}){const{ref:n,uploadBytes:r}=Vi(),s=de(t.path??""),[i,o]=y.useState([]),a=y.useRef(t);a.current=t;const l=y.useCallback(f=>{o(p=>p.map(m=>m.id===f.id?f:m))},[]),u=y.useCallback(async f=>{if(e==null)throw new Error("useObjectUpload: storage handle is null");const m=(Array.isArray(f)?f:[f]).map(g=>{const b=oT(g);return{task:{id:crypto.randomUUID(),fullPath:sf(s,de(b.path)),status:"running",bytesTransferred:0,totalBytes:iT(b.data)},entry:b}});o(g=>[...g,...m.map(b=>b.task)]);for(const{task:g}of m)a.current.list?.insertItem(g.fullPath),a.current.onProgress?.(g);return Promise.all(m.map(async({task:g,entry:b})=>{try{const w=await r(n(e,g.fullPath),b.data,b.metadata),x={...g,status:"success",bytesTransferred:g.totalBytes,metadata:w.metadata};return l(x),a.current.onProgress?.(x),a.current.onComplete?.(x),x}catch(w){const x={...g,status:"error",error:w instanceof Error?w:new Error(String(w))};return a.current.list?.removeItem(g.fullPath),l(x),a.current.onError?.(x),x}}))},[e,s,l,n,r]),d=y.useCallback(async f=>{if(e==null)throw new Error("useObjectUpload: storage handle is null");const p=sf(s,de(f));if(p==="")throw new Error("createFolder: folder name is empty");a.current.list?.insertItem(`${p}/`);try{await r(XD(e,p),new Blob([]),{contentType:"text/plain"})}catch(m){throw a.current.list?.removeItem(p),m}},[e,s,r]),h=y.useCallback(()=>{o(f=>f.filter(p=>p.status==="running"))},[]);return{tasks:i,isUploading:i.some(f=>f.status==="running"),upload:u,createFolder:d,clearCompleted:h}}function cT({path:e,onNavigate:t,rootLabel:n="/",separator:r="/",className:s}){const i=de(e),o=i===""?[]:i.split("/");return c.jsx("nav",{className:s,"data-pyric-ui":"path-breadcrumb","aria-label":"Storage path",children:c.jsxs("ol",{"data-pyric-breadcrumb-list":!0,children:[c.jsx("li",{"data-pyric-breadcrumb-item":!0,children:c.jsx("button",{type:"button",onClick:()=>t?.(""),"data-pyric-breadcrumb-link":!0,"data-pyric-breadcrumb-root":!0,"data-pyric-current":o.length===0?"":void 0,"aria-current":o.length===0?"page":void 0,children:n})}),o.map((a,l)=>{const u=l===o.length-1,d=o.slice(0,l+1).join("/");return c.jsxs("li",{"data-pyric-breadcrumb-item":!0,children:[c.jsx("span",{"aria-hidden":!0,"data-pyric-breadcrumb-separator":!0,children:r}),c.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:a})]},d)})]})})}function lT({entries:e,status:t="success",error:n,onNavigate:r,onSelect:s,selectedPath:i,gate:o,renderEntry:a,renderRowAction:l,emptyState:u,className:d,virtualizeThreshold:h=100,rowHeight:f=36,virtualizedHeight:p="60vh"}){const{ref:m,size:g}=Fi();if(n)return c.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 c.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 c.jsx("div",{className:d,"data-pyric-ui":"object-browser","data-pyric-empty":"",children:u});const b=v=>{if(!o)return{denied:!1};const _=o.verdictFor(v.fullPath);return _.read?{denied:!1}:{denied:!0,reason:_.reasons.read.join("; ")}},w=v=>{const _=v.kind==="object"&&v.fullPath===i;return c.jsxs(c.Fragment,{children:[c.jsx("button",{type:"button",onClick:()=>v.kind==="folder"?r?.(v.fullPath):s?.(v.ref),"data-pyric-entry-select":!0,"data-pyric-selected":_?"":void 0,"aria-selected":_||void 0,children:a?a(v):v.name}),l?c.jsx("span",{"data-pyric-storage-action":!0,children:l(v)}):null]})},x=e.length>h;return c.jsx("div",{ref:m,className:d,"data-pyric-ui":"object-browser","data-size":g,"data-pyric-virtualized":x?"":void 0,children:x?c.jsx(Uc,{items:e,estimateSize:f,height:p,getItemKey:v=>`${v.kind}:${v.fullPath}`,renderItem:v=>{const _=b(v);return c.jsx("div",{"data-pyric-storage-entry":!0,"data-pyric-entry-kind":v.kind,"data-pyric-entry-path":v.fullPath,"data-pyric-denied":_.denied?"":void 0,"data-pyric-denied-reason":_.reason,children:w(v)})}}):c.jsx("ul",{"data-pyric-object-browser-items":!0,children:e.map(v=>{const _=b(v);return c.jsx("li",{"data-pyric-storage-entry":!0,"data-pyric-entry-kind":v.kind,"data-pyric-entry-path":v.fullPath,"data-pyric-denied":_.denied?"":void 0,"data-pyric-denied-reason":_.reason,children:w(v)},`${v.kind}:${v.fullPath}`)})})})}async function ug(e,t,n){const r=t===""?e.name:`${t}/${e.name}`;if(e.isFile){const s=await new Promise((i,o)=>e.file(i,o));n.push({file:s,relativePath:r});return}if(e.isDirectory){const s=e.createReader();for(;;){const i=await new Promise((o,a)=>s.readEntries(o,a));if(i.length===0)break;for(const o of i)await ug(o,r,n)}}}async function uT(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 ug(i,"",t);else{const o=r.getAsFile?.();o&&t.push({file:o,relativePath:o.name})}}if(t.length===0)for(const r of Array.from(e.files??[]))t.push({file:r,relativePath:r.name});return t}function dT({onFiles:e,children:t,disabled:n,disabledReason:r,className:s}){const[i,o]=y.useState(!1),a=y.useRef(0),l=y.useCallback(f=>{f.preventDefault(),!n&&(a.current+=1,o(!0))},[n]),u=y.useCallback(f=>{f.preventDefault()},[]),d=y.useCallback(f=>{f.preventDefault(),!n&&(a.current=Math.max(0,a.current-1),a.current===0&&o(!1))},[n]),h=y.useCallback(f=>{if(f.preventDefault(),a.current=0,o(!1),n)return;const p=f.dataTransfer;p&&uT(p).then(m=>{m.length>0&&e(m)})},[n,e]);return c.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:h,children:t})}function fT(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 hT(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 of(e,t){if(!t.has(e))return e;const{stem:n,ext:r}=fT(e),{base:s,counter:i}=hT(n);let o=i===null?1:i+1;for(;;){const a=`${s} (${o})${r}`;if(!t.has(a))return a;o+=1}}function pT(e,t){const n=new Set(t),r=new Map;return e.map(s=>{const i=s.indexOf("/");if(i===-1){const l=of(s,n);return n.add(l),l}const o=s.slice(0,i);let a=r.get(o);return a===void 0&&(a=of(o,n),n.add(a),r.set(o,a)),`${a}${s.slice(i)}`})}function af(e){const t=de(e);if(t==="")return[];const n=t.split("/");return n.map((r,s)=>n.slice(0,s+1).join("/"))}const dg=[];function mT(e,t){switch(t.type){case"create":{const n=af(t.path).filter(r=>!e.includes(r));return n.length===0?e:[...e,...n].sort()}case"materialize":{const n=new Set(af(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=de(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:dg}}function yT(e,t){const n=de(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 cf(e,t){return e.includes(de(t))}function gT(e){const t=de(e);return t===""?"Enter a folder name.":t.split("/").some(r=>r==="."||r==="..")?'Folder names may not be "." or "..".':null}const bT=256*1024;function qa(e){return(e.contentType??"").split(";")[0].trim().toLowerCase()}const wT={id:"image",match:e=>qa(e).startsWith("image/"),needsBlob:!0,render:({metadata:e,blobUrl:t})=>t?c.jsx("img",{"data-pyric-preview-image":!0,src:t,alt:e.name}):null};function vT({blob:e,isJson:t}){const[n,r]=y.useState(void 0);return y.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:c.jsx("pre",{"data-pyric-preview-text":!0,children:n})}const xT={id:"text",match:e=>{const t=qa(e);return t.startsWith("text/")||t==="application/json"},needsBlob:!0,maxBytes:bT,render:({metadata:e,blob:t})=>t?c.jsx(vT,{blob:t,isJson:qa(e)==="application/json"}):null},_T=[wT,xT];function ST(e,t){for(const n of[...t??[],..._T])if(n.match(e))return n}const kT=[{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 jT({metadata:e}){return c.jsxs("dl",{"data-pyric-object-metadata":!0,children:[kT.map(({key:t,label:n,value:r})=>{const s=r(e);return s===void 0?null:c.jsxs("div",{"data-pyric-metadata-field":t,children:[c.jsx("dt",{children:n}),c.jsx("dd",{children:s})]},t)}),Object.entries(e.customMetadata??{}).map(([t,n])=>c.jsxs("div",{"data-pyric-metadata-field":"customMetadata","data-pyric-metadata-key":t,children:[c.jsx("dt",{children:t}),c.jsx("dd",{children:n})]},`custom:${t}`))]})}function ET({storage:e,path:t,previews:n,renderMetadata:r,children:s,className:i}){const{ref:o,size:a}=Fi(),l=YD(e,t),{metadata:u,blobStatus:d,loadBlob:h}=l,f=u?ST(u,n):void 0,p=f?.maxBytes!==void 0&&u!==void 0&&u.size>f.maxBytes,m=f?.needsBlob===!0&&!p;if(y.useEffect(()=>{m&&d==="idle"&&h()},[m,d,h]),l.status==="idle")return c.jsx("div",{className:i,"data-pyric-ui":"object-inspector","data-pyric-idle":""});if(l.status==="loading")return c.jsx("div",{className:i,"data-pyric-ui":"object-inspector","data-pyric-loading":""});if(l.status==="error"||u===void 0)return c.jsx("div",{className:i,"data-pyric-ui":"object-inspector","data-pyric-error":"",role:"alert",children:l.error?.message});let g,b={};return f===void 0?b={"data-pyric-preview-none":""}:p?b={"data-pyric-preview-too-large":""}:m&&d==="loading"?b={"data-pyric-preview-loading":""}:m&&d==="error"?(b={"data-pyric-preview-error":""},g=l.blobError?.message):(!m||d==="success")&&(g=f.render({metadata:u,blob:l.blob,blobUrl:l.blobUrl})),c.jsxs("div",{ref:o,className:i,"data-pyric-ui":"object-inspector","data-size":a,children:[c.jsx("div",{"data-pyric-object-name":!0,children:u.name}),r?r(u):c.jsx(jT,{metadata:u}),c.jsx("div",{"data-pyric-object-preview":!0,"data-pyric-preview":f?.id,...b,children:g}),s]})}const fg=y.createContext(null);function CT(){const e=y.useContext(fg);if(!e)throw new Error("useToast: missing <ToastProvider> ancestor");return e}function NT({children:e,defaultDuration:t=5e3,className:n,regionLabel:r="Notifications"}){const[s,i]=y.useState([]),o=y.useCallback(u=>{i(d=>d.filter(h=>h.id!==u))},[]),a=y.useCallback(u=>{const d=crypto.randomUUID(),h=u.duration??t;return i(f=>[...f,{id:d,...u}]),h>0&&window.setTimeout(()=>{i(f=>f.filter(p=>p.id!==d))},h),d},[t]),l=y.useMemo(()=>({toast:a,dismiss:o,toasts:s}),[a,o,s]);return c.jsxs(fg.Provider,{value:l,children:[e,c.jsx(RT,{toasts:s,dismiss:o,className:n,regionLabel:r})]})}function RT({toasts:e,dismiss:t,className:n,regionLabel:r}){const[s,i]=y.useState(!1);return y.useEffect(()=>i(!0),[]),!s||typeof document>"u"?null:Lc.createPortal(c.jsx("ol",{"aria-label":r,"aria-live":"polite","data-pyric-ui":"toast-region",className:n,children:e.map(o=>c.jsxs("li",{"data-pyric-toast":!0,"data-pyric-toast-kind":o.kind??"info",role:o.kind==="error"?"alert":"status",children:[c.jsx("div",{"data-pyric-toast-title":!0,children:o.title}),o.body?c.jsx("div",{"data-pyric-toast-body":!0,children:o.body}):null,c.jsx("button",{type:"button","data-pyric-toast-dismiss":!0,"aria-label":"Dismiss",onClick:()=>t(o.id),children:"×"})]},o.id))}),document.body)}function IT({storage:e,entries:t,impl:n,list:r,gate:s,title:i,body:o,confirmLabel:a="Delete",onDeleted:l,onFailed:u,renderTrigger:d,className:h}){const f=Kn(),{toast:p}=CT(),{deleteEntries:m,isRunning:g,progress:b}=tT(e,{impl:n,list:r}),w=s?t.map(S=>({entry:S,verdict:s.verdictFor(S.fullPath)})).filter(S=>!S.verdict.delete):[],x=w.length===0?void 0:`Delete denied for ${w[0].entry.fullPath}${w.length>1?` (+${w.length-1} more)`:""}: ${w[0].verdict.reasons.write.join("; ")}`,v=g||t.length===0||e==null||w.length>0,_=async()=>{if(v||!await f({title:i??(t.length===1?`Delete ${t[0].fullPath}?`:`Delete ${t.length} items?`),body:o??c.jsx("ul",{"data-pyric-delete-selection-paths":!0,children:t.map(N=>c.jsxs("li",{"data-pyric-entry-kind":N.kind,children:[N.fullPath,N.kind==="folder"?"/":""]},N.fullPath))}),destructive:!0,confirmLabel:a}))return;const k=await m(t);k.failed.length===0?(p({title:`Deleted ${k.deleted.length} ${k.deleted.length===1?"item":"items"}`,kind:"success"}),l?.(k)):(p({title:`Delete failed for ${k.failed.length} of ${t.length}`,kind:"error",body:c.jsx("ul",{"data-pyric-delete-selection-failures":!0,children:k.failed.map(N=>c.jsxs("li",{children:[N.fullPath,":"," ",N.error.code??N.error.message]},N.fullPath))})}),u?.(k))};return d?c.jsx(c.Fragment,{children:d({onClick:_,isRunning:g,progress:b,disabled:v,deniedReason:x})}):c.jsx("button",{type:"button",onClick:_,className:h,disabled:v,title:x,"data-pyric-ui":"delete-selection","data-pyric-destructive":"","data-pyric-running":g?"":void 0,"data-pyric-denied":x?"":void 0,"data-pyric-denied-reason":x,children:g?`Deleting… (${b})`:a})}function zr(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 hg(e){const t=e.indexOf("?");return Pc(t===-1?e:e.slice(0,t),t===-1?"":e.slice(t))}function AT(e){const{tab:t,rest:n,query:r}=hg(e),s=n.join("/");return t==="firestore"?{view:"firestore",path:zr(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 pg(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 mg(e){const{tab:t,query:n}=hg(e),r=AT(e),s=t==="traffic"?n.inspect??null:null;return{target:r,selectedInspectId:s}}let lf=null,Wa=mg("");function OT(){const e=Dc();return e!==lf&&(lf=e,Wa=mg(e)),Wa}function $T(){return Wa}function Is(e){Ae(pg(e))}function PT(e){Ae({tab:"traffic",query:{inspect:e}})}function qi(){const e=y.useSyncExternalStore(Gt,OT,$T),t=y.useCallback(s=>Is(s),[]),n=y.useCallback(s=>{switch(s.kind){case"user":Is({view:"auth",uid:s.uid});break;case"storage":Is({view:"storage",kind:"object",path:s.objectPath});break;case"document":Is({view:"firestore",path:zr(s.path)});break}},[]),r=y.useCallback(s=>PT(s),[]);return y.useMemo(()=>({target:e.target,navigate:t,navigateRef:n,selectedInspectId:e.selectedInspectId,navigateInspect:r}),[e,t,n,r])}const DT={narrowBreakpoint:640,mediumBreakpoint:920};function TT(e){switch(e){case"narrow":return 1;case"medium":return 2;case"wide":return 3}}function MT(e,t){const n=TT(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 $o({label:e,error:t,hint:n,children:r}){return c.jsxs("div",{className:"fs-modal__group",children:[c.jsx("span",{className:"fs-modal__label",children:e}),r,t?c.jsx("span",{className:"fs-modal__err",role:"alert",children:t}):n?c.jsx("span",{className:"fs-modal__hint",children:n}):null]})}function yg({mode:e,parentPath:t,onCreate:n,onClose:r}){const[s,i]=y.useState(""),[o,a]=y.useState(()=>zD()),[l,u]=y.useState(null),[d,h]=y.useState(null),[f,p]=y.useState(!1),m=y.useRef(null),g=e==="collection"&&s?VD(s):void 0,b=o?WD(o):void 0,x=!(e==="collection"&&(!s||g))&&!!o&&!b&&!f;y.useEffect(()=>{const S=k=>{k.key==="Escape"&&!f&&r()};return document.addEventListener("keydown",S),()=>document.removeEventListener("keydown",S)},[f,r]);const v=async()=>{if(!(!x||!l)){if(!l.isValid){l.touchAll();return}p(!0),h(null);try{await n({collectionId:e==="collection"?s:null,docId:o,data:Qy(l.tree)}),r()}catch(S){h(S instanceof Error?S:new Error(String(S))),p(!1)}}},_=e==="collection"?"Start a collection":"Add a document";return c.jsx("div",{className:"fs-modal-backdrop",onMouseDown:S=>{S.target===S.currentTarget&&!f&&r()},children:c.jsxs("div",{ref:m,className:"fs-modal",role:"dialog","aria-modal":"true","aria-label":_,"data-pyric-ui":"fs-create-modal","data-fs-create-mode":e,children:[c.jsx("h2",{className:"fs-modal__title",children:_}),c.jsx($o,{label:"Parent path",children:c.jsx("span",{className:"fs-modal__path",children:t})}),e==="collection"?c.jsx($o,{label:"Collection ID",error:g,children:c.jsx("input",{autoFocus:!0,type:"text",value:s,placeholder:"e.g. users",onChange:S=>i(S.target.value),"data-pyric-field":"collection-id","aria-invalid":g?"true":void 0})}):null,c.jsx($o,{label:"Document ID",error:o?b:"Cannot be empty",hint:"Auto-generated — edit to set your own.",children:c.jsx("input",{autoFocus:e==="document",type:"text",value:o,onChange:S=>a(S.target.value),"data-pyric-field":"doc-id","aria-invalid":b||!o?"true":void 0})}),c.jsxs("div",{className:"fs-modal__group",children:[c.jsx("span",{className:"fs-modal__label",children:"Fields"}),c.jsx("div",{className:"fs-modal__fields",children:c.jsx(tf.Root,{initial:{},onChange:u,children:c.jsx(tf.Fields,{})})})]}),d?c.jsx("p",{className:"fs-modal__err",role:"alert",children:d.message}):null,c.jsxs("div",{className:"fs-modal__actions",children:[c.jsx("button",{type:"button",className:"fs-editor__cancel",disabled:f,onClick:r,children:"Cancel"}),c.jsx("button",{type:"button",className:"fs-editor__save",disabled:!x,onClick:()=>void v(),children:f?"Saving…":"Save"})]})]})})}function gg({items:e,label:t="More actions"}){const[n,r]=y.useState(!1),[s,i]=y.useState(null),o=y.useRef(null),a=()=>{if(!n){const l=o.current?.getBoundingClientRect();l&&i({top:l.bottom+4,right:window.innerWidth-l.right})}r(l=>!l)};return y.useEffect(()=>{if(!n)return;const l=u=>{u.key==="Escape"&&(r(!1),o.current?.focus())};return document.addEventListener("keydown",l),()=>document.removeEventListener("keydown",l)},[n]),c.jsxs("span",{className:"fs-overflow","data-pyric-ui":"fs-overflow-menu",children:[c.jsx("button",{ref:o,type:"button",className:"fs-overflow__trigger","aria-haspopup":"menu","aria-expanded":n,"aria-label":t,onClick:a,children:c.jsx("span",{"aria-hidden":"true",children:"⋮"})}),n?c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"fs-overflow__backdrop",onMouseDown:()=>r(!1)}),c.jsx("div",{className:"fs-overflow__menu",role:"menu",style:s?{top:s.top,right:s.right}:void 0,children:e.map(l=>c.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 bg(e){return JSON.stringify(e)}function LT(e,t){const n=new Map,r=(s,i)=>{const o=t(s),a=bg(i);if(o==="map"){const l=s,u=Object.keys(l).sort();n.set(a,[o,u]);for(const d of u)r(l[d],[...i,["field",d]]);return}if(o==="array"){const l=s;n.set(a,[o,l.map((u,d)=>String(d))]),l.forEach((u,d)=>r(u,[...i,["index",d]]));return}n.set(a,[o,s])};for(const[s,i]of Object.entries(e))r(i,[["field",s]]);return n}function wg(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 bg(n)}function UT(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 BT(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 uf(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 FT=42;function VT(e,t,n,r=FT){const s=e.nodes[t],i=e.childIds[t]??[];let o;return s.type==="array"?o=`[${i.slice(0,3).map(l=>uf(e.nodes[l],n.asVectorView,n.vectorPreview)).join(", ")}${i.length>3?", …":""}]`:o=`{${i.slice(0,2).map(l=>`"${e.nodes[l].key}": ${uf(e.nodes[l],n.asVectorView,n.vectorPreview)}`).join(", ")}${i.length>2?", …":""}}`,o.length>r?`${o.slice(0,r-1)}…`:o}function qT(e,t,n){return t.parentId==null?!1:(e.childIds[t.parentId]??[]).some(s=>s!==t.id&&e.nodes[s]?.key===n)}function WT(e){return e.shiftKey===!0}const vg=["string","number","boolean","null","timestamp","geopoint","reference","bytes","vector"],zT=[...vg,"map","array"];function HT({snapshot:e,documentRef:t,onCommit:n,onDeleteDocument:r,onDeleteDocumentFields:s,fieldEditors:i,onReferenceClick:o,onStartCollection:a,firestore:l,listSubcollections:u,onSubcollectionClick:d}){const h=y.useMemo(()=>e?.data()??{},[e]),f=y.useMemo(()=>h,[]),p=ng({initial:f}),m=p.replaceData,g=y.useMemo(()=>ig(i),[i]),b=Kn(),[w,x]=y.useState(()=>new Set),[v,_]=y.useState(null),S=y.useRef(e),k=y.useRef(new Set),N=y.useRef(!1),[O,P]=y.useState(null),R=y.useMemo(()=>LT(h,Bi),[h]),j=Gc({scope:t.path,entries:R,equals:bi,ready:v===null});y.useEffect(()=>{N.current&&(N.current=!1,P(null),n(p.toData()).catch(U=>{P(U instanceof Error?U:new Error(String(U)))}))},[p.tree]),y.useEffect(()=>{!e||e===S.current||v!==null||(S.current=e,k.current.clear(),m(e.data()??{}))},[v,m,e]);const E=y.useCallback(U=>{x(q=>{const F=new Set(q);return F.has(U)?F.delete(U):F.add(U),F})},[]),[$,C]=y.useState(null),I=y.useCallback((U,q)=>{if(q==="map"?p.addMapEntry(U,"","string"):p.addArrayEntry(U,"string"),U!==p.tree.rootId){const F=wg(p.tree,U);x(Se=>new Set(Se).add(F))}C(U)},[p]);y.useEffect(()=>{if(!$)return;const U=p.tree.childIds[$]??[],q=U[U.length-1];q&&!v&&(k.current.add(q),_(q),C(null))},[p.tree,$]);const A=y.useCallback(U=>{p.remove(U),k.current.delete(U),N.current=!0,v===U&&_(null)},[p,v]),D=y.useCallback(async(U,q,F)=>{if(WT(F)){A(U.id);return}await b({title:`Delete field "${q}"?`,destructive:!0,confirmLabel:"Delete"})&&A(U.id)},[b,A]),T=t.id,W=p.tree.childIds[p.tree.rootId]??[];return c.jsxs("div",{"data-pyric-ui":"fs-doctree",className:"fs-doctree",children:[c.jsxs("div",{className:"fs-doctree__head",children:[c.jsx("span",{className:"fs-doctree__docid",children:T}),c.jsx(gg,{items:[{label:"Delete document fields",onSelect:()=>{(async()=>await b({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}]})]}),O?c.jsx("p",{className:"fs-doctree__err",children:O.message}):null,c.jsxs("ul",{className:"fs-doctree__rows",children:[a?c.jsx("li",{className:"fs-doctree__action-row",children:c.jsxs("button",{type:"button",className:"fs-doctree__action",onClick:a,children:[c.jsx("span",{"aria-hidden":"true",children:"+"})," Start collection"]})}):null,c.jsx("li",{className:"fs-doctree__action-row",children:c.jsxs("button",{type:"button",className:"fs-doctree__action",onClick:()=>I(p.tree.rootId,"map"),children:[c.jsx("span",{"aria-hidden":"true",children:"+"})," Add field"]})}),W.map(U=>c.jsx(xg,{nodeId:U,depth:0,editor:p,registry:g,expanded:w,onToggle:E,editingId:v,setEditingId:_,newIdsRef:k,onAdd:I,onDelete:D,onCommitNeeded:()=>{N.current=!0},onReferenceClick:o,updates:j},U))]}),l&&u?c.jsx(_g,{firestore:l,documentRef:t,listSubcollections:u,onSubcollectionClick:d}):null]})}function xg({nodeId:e,depth:t,editor:n,registry:r,expanded:s,onToggle:i,editingId:o,setEditingId:a,newIdsRef:l,onAdd:u,onDelete:d,onCommitNeeded:h,onReferenceClick:f,updates:p}){const{tree:m}=n,g=m.nodes[e];if(!g)return null;const{label:b,isArrayChild:w}=BT(m,e),x=g.type==="map"||g.type==="array",v=UT(m,e),_=wg(m,e),S=p.get(_),k=s.has(_),N=o===e,O=l.current.has(e);return N?c.jsx("li",{className:"fs-doctree__row fs-doctree__row--editing","data-pyric-doctree-depth":t,style:{"--fs-depth":t},children:c.jsx(KT,{node:g,isNew:O,isArrayChild:w,tree:m,editor:n,registry:r,path:v,onCommitNeeded:h,onDone:()=>{l.current.delete(e),a(null)},onCancelNew:()=>{n.remove(e),l.current.delete(e),a(null)}})}):c.jsxs("li",{className:"fs-doctree__row","data-pyric-doctree-depth":t,"data-pyric-doctree-nested":x?"":void 0,style:{"--fs-depth":t},children:[c.jsxs("div",{className:"fs-doctree__line","data-pyric-update":S?.kind,"data-pyric-update-cycle":S?.cycle,children:[x?c.jsx("button",{type:"button",className:"fs-doctree__caret","aria-expanded":k,onClick:()=>i(_),children:c.jsx("span",{"aria-hidden":"true",children:k?"▼":"▶"})}):c.jsx("span",{className:"fs-doctree__caret fs-doctree__caret--empty","aria-hidden":"true"}),w?c.jsx("span",{className:"fs-doctree__chip",children:b}):c.jsx("span",{className:"fs-doctree__key",children:b}),x?k?null:c.jsx("span",{className:"fs-doctree__preview",children:VT(m,e,{asVectorView:gn,vectorPreview:Jy})}):c.jsx("span",{className:"fs-doctree__value",children:c.jsx(Fa,{value:g.value,path:v,fieldEditors:r})}),c.jsxs("span",{className:"fs-doctree__hover",children:[c.jsxs("span",{className:"fs-doctree__typenote",children:["(",g.type,")"]}),x?c.jsx("button",{type:"button",className:"fs-doctree__icon",title:"Add field","aria-label":`Add field to ${b||"document"}`,onClick:()=>u(e,g.type==="array"?"array":"map"),children:"+"}):c.jsx("button",{type:"button",className:"fs-doctree__icon",title:"Edit","aria-label":`Edit ${b}`,onClick:()=>a(e),children:"✎"}),c.jsx("button",{type:"button",className:"fs-doctree__icon fs-doctree__icon--danger",title:"Delete (shift-click to skip confirmation)","aria-label":`Delete ${b||"field"} (shift-click to skip confirmation)`,onClick:P=>void d(g,b,{shiftKey:P.shiftKey}),children:"🗑"})]})]}),x&&k?c.jsxs("ul",{className:"fs-doctree__children",children:[(m.childIds[e]??[]).map(P=>c.jsx(xg,{nodeId:P,depth:t+1,editor:n,registry:r,expanded:s,onToggle:i,editingId:o,setEditingId:a,newIdsRef:l,onAdd:u,onDelete:d,onCommitNeeded:h,onReferenceClick:f,updates:p},P)),c.jsx("li",{className:"fs-doctree__action-row fs-doctree__action-row--nested",children:c.jsxs("button",{type:"button",className:"fs-doctree__action",onClick:()=>u(e,g.type==="array"?"array":"map"),children:[c.jsx("span",{"aria-hidden":"true",children:"+"})," ",g.type==="array"?"Add item":"Add field"]})})]}):null]})}function KT({node:e,isNew:t,isArrayChild:n,tree:r,editor:s,registry:i,path:o,onCommitNeeded:a,onDone:l,onCancelNew:u}){const[d,h]=y.useState(e.key??""),[f,p]=y.useState(e.type),[m,g]=y.useState(e.value),[b,w]=y.useState(!1),x=n?void 0:d===""?"Field name is required":qT(r,e,d)?"Field name must be unique":void 0,v=f==="map"||f==="array"?void 0:Zy(f,m),_=!x&&!v,S=()=>{if(!_){w(!0);return}n||s.setKey(e.id,d),f!==e.type&&s.setType(e.id,f),f!=="map"&&f!=="array"&&s.setValue(e.id,m),a(),l()},k=()=>{t?u():l()},O=i[f]?.Edit,P=f!=="map"&&f!=="array"&&O?c.jsx(O,{value:m,path:o,error:b?v:void 0,onChange:E=>g(E)}):f==="map"||f==="array"?c.jsxs("span",{className:"fs-doctree__editnote",children:["Saves as an empty ",f," — add its children afterward."]}):null,R=c.jsxs("span",{className:"fs-doctree__editactions",children:[c.jsx("button",{type:"button",className:"fs-doctree__editsave",onClick:S,"aria-label":"Save field",children:"✓"}),c.jsx("button",{type:"button",className:"fs-doctree__editcancel",onClick:k,"aria-label":"Cancel edit",children:"✕"})]}),j=c.jsx("select",{className:"fs-doctree__edittype",value:f,onChange:E=>{const $=E.target.value;p($),$!=="map"&&$!=="array"&&$!==f&&g(GT($))},"aria-label":"Field type",children:(t?zT:vg).map(E=>c.jsx("option",{value:E,children:E},E))});return c.jsxs("div",{className:"fs-doctree__editrow",onKeyDown:E=>{E.key==="Enter"&&!E.target.matches("textarea")?(E.preventDefault(),S()):E.key==="Escape"&&(E.preventDefault(),k())},children:[n?null:c.jsxs("div",{className:"fs-doctree__editline",children:[c.jsx("input",{type:"text",className:"fs-doctree__editkey",value:d,placeholder:"Field name",autoFocus:t,onChange:E=>h(E.target.value),onBlur:()=>w(!0),"aria-label":"Field name","aria-invalid":b&&x?"true":void 0}),j]}),c.jsxs("div",{className:"fs-doctree__editline",children:[n?j:null,P,R]}),b&&x?c.jsx("span",{className:"fs-doctree__editerr",children:x}):null]})}function GT(e){switch(e){case"string":return"";case"number":return 0;case"boolean":return!1;default:return null}}function _g({firestore:e,documentRef:t,listSubcollections:n,onSubcollectionClick:r}){const{subcollections:s,isLoading:i}=GP({firestore:e,documentRef:t,listSubcollections:n});return!i&&s.length===0?null:c.jsxs("section",{"data-pyric-ui":"fs-doctree-subcollections","data-pyric-loading":i?"":void 0,children:[c.jsx("div",{className:"fs-doctree__subhead",children:"Subcollections"}),c.jsx("ul",{className:"fs-doctree__sublist",children:s.map(o=>c.jsx("li",{children:r?c.jsxs("button",{type:"button",className:"fs-doctree__subrow",onClick:()=>r(o),"aria-label":`Open subcollection ${o.id}`,children:[c.jsx("span",{children:o.id}),c.jsx("span",{className:"fs-doctree__subtype",children:"subcollection"}),c.jsx("span",{"aria-hidden":"true",children:"›"})]}):c.jsxs("div",{className:"fs-doctree__subrow",children:[c.jsx("span",{children:o.id}),c.jsx("span",{className:"fs-doctree__subtype",children:"subcollection"})]})},o.path))})]})}function JT(e){return e.split("/").filter(Boolean).length%2===0}function Sg(e,t){async function*n(s,i,o=!1){const a=await t.listSubcollections(s.path);for(const l of a)yield*r(e.collection(s,l),i);o||(await e.deleteDoc(s),i.n++,yield{deletedCount:i.n,done:!1})}async function*r(s,i){const o=await t.listDocuments(s.path);for(const a of o){const l=a.path.split("/").pop();l&&(yield*n(e.doc(s,l),i,a.phantom===!0))}}return{async*start(s){const i={n:0};JT(s.path)?yield*n(s,i):yield*r(s,i),yield{deletedCount:i.n,done:!0}}}}async function kg(e,t){for await(const n of e.start(t))if(n.done)return}async function jg({confirm:e,ref:t,api:n,recursiveImpl:r}){let s=!1;return await e({title:`Delete document "${t.id}"?`,body:c.jsxs("label",{className:"fs-delete-recursive",children:[c.jsx("input",{type:"checkbox",onChange:o=>{s=o.currentTarget.checked}}),c.jsx("span",{children:"Also delete subcollections recursively. Leave this off to keep nested data."})]}),destructive:!0,confirmLabel:"Delete document"})?(s?await kg(r,t):await n.deleteDoc(t),!0):!1}function YT(e){const t=e.exists;return typeof t=="function"?t.call(e):t}async function QT(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 XT(e){return{id:e.id,ref:e,data:()=>{},__pyricPhantom:!0}}function df(e){return e.__pyricPhantom===!0}function ZT(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 eM({handles:e}){const{target:t,navigate:n}=qi(),r=e.adminFirestore,s=Vc(),i=y.useMemo(()=>t?.view==="firestore"?t.path:[],[t]),o=y.useCallback(_=>{const S=typeof _=="function"?_(i):_;n({view:"firestore",path:S})},[n,i]),a=(_,S)=>o(k=>[...k.slice(0,_+1),S]),[l,u]=y.useState(null),d=y.useCallback(async({collectionId:_,docId:S,data:k})=>{if(!l||!_)return;const N=l.parentDocPath,O=N?s.collection(s.doc(r,N),_):s.collection(r,_);await QT(s,O,S,k);const P=N?`${N}/${_}`:_;n({view:"firestore",path:zr(`${P}/${S}`)})},[s,r,l,n]),h=[c.jsx(rM,{api:s,firestore:r,collectionIds:e.listRootCollections(),onSelect:_=>o([{kind:"collection",id:_,path:_}]),onStartCollection:()=>u({parentDocPath:null})},"__root__"),...i.map((_,S)=>_.kind==="collection"?c.jsx(sM,{api:s,firestore:r,handles:e,collectionPath:_.path,selectedId:i[S+1]?.id??null,onSelect:k=>a(S,{kind:"document",id:k.id,path:k.path}),onCollectionDeleted:()=>o(k=>k.slice(0,S))},_.path):c.jsx(iM,{api:s,firestore:r,handles:e,docPath:_.path,onOpenSubcollection:k=>a(S,{kind:"collection",id:k.id,path:k.path}),onReferenceClick:k=>n({view:"firestore",path:zr(k.path)}),onStartCollection:()=>u({parentDocPath:_.path}),onDeleted:()=>o(k=>k.slice(0,S))},_.path))],{ref:f,size:p}=Fi(DT),{startIndex:m,visibleCount:g,emptySlots:b}=MT(h.length,p),w=h.slice(m,m+g),x=i.length===0?"Select a collection":i[i.length-1]?.kind==="collection"?"Select a document":null,v=[...w,...Array.from({length:b},(_,S)=>c.jsx(nM,{hint:S===0?x:null},`__empty_${S}__`))];return y.useEffect(()=>{if(p==="wide")return;const _=f.current;if(!_)return;const S=document.activeElement;if(S&&S!==document.body&&_.contains(S))return;const k=_.querySelector(".fs-columns > .fs-col:last-child");k&&(k.tabIndex=-1,k.focus({preventScroll:!0}))},[i.length,p]),c.jsx(Bc,{children:c.jsxs("div",{ref:f,"data-pyric-ui":"fs-browser","data-fs-depth":i.length,"data-size":p,children:[c.jsx(tM,{path:i,onHome:()=>o([]),onJump:_=>o(S=>S.slice(0,_+1))}),c.jsx("div",{className:"fs-columns",children:v}),l?c.jsx(yg,{mode:"collection",parentPath:l.parentDocPath?`/${l.parentDocPath}`:"/",onCreate:d,onClose:()=>u(null)}):null]})})}function tM({path:e,onHome:t,onJump:n}){return c.jsxs("nav",{"data-pyric-ui":"fs-breadcrumb","aria-label":"Firestore path",children:[c.jsx("button",{type:"button",className:"fs-crumb",onClick:t,children:"home"}),e.map((r,s)=>c.jsxs(y.Fragment,{children:[c.jsx("span",{className:"fs-crumb-sep","aria-hidden":!0,children:"›"}),s===e.length-1?c.jsx("span",{className:"fs-crumb fs-crumb--current",children:r.id}):c.jsx("button",{type:"button",className:"fs-crumb",onClick:()=>n(s),children:r.id})]},r.path))]})}function nM({hint:e}){return c.jsx("section",{"data-pyric-ui":"fs-empty-col",className:"fs-pane fs-col fs-col--empty","aria-hidden":e?void 0:!0,children:e?c.jsx("p",{className:"fs-empty",children:e}):null})}function rM({api:e,firestore:t,collectionIds:n,onSelect:r,onStartCollection:s}){const i=y.useMemo(()=>n.map(o=>e.collection(t,o)),[e,t,n]);return c.jsxs("section",{"data-pyric-ui":"fs-collections",className:"fs-pane fs-col",children:[c.jsxs("div",{className:"fs-phead",children:[c.jsx("span",{className:"fs-phead-title",children:"Collections"}),c.jsx("button",{type:"button",className:"fs-add",onClick:s,children:"+ New"})]}),c.jsx(UD,{collections:i,onSelect:o=>r(o.id),emptyState:c.jsx("p",{className:"fs-empty",children:"No collections yet. App or agent writes show up here."})})]})}function sM({api:e,firestore:t,handles:n,collectionPath:r,selectedId:s,onSelect:i,onCollectionDeleted:o}){const a=y.useMemo(()=>ZT(e,t,r),[e,t,r]),{documents:l,isLoading:u,error:d,subscriptionGeneration:h,hasMore:f,loadMore:p,createDocument:m}=KP({collection:a,mode:"live"}),[g,b]=y.useState([]);y.useEffect(()=>{let j=!1;return Promise.resolve(n.listDocuments(r)).then(E=>{j||b(E.filter($=>$.phantom).map($=>$.path.split("/").pop()??""))}).catch(()=>{j||b([])}),()=>{j=!0}},[n,r,l]);const w=y.useMemo(()=>{const j=new Set(l.map(E=>E.id));return[...l,...g.filter(E=>E.length>0&&!j.has(E)).map(E=>XT(e.doc(t,`${r}/${E}`)))]},[l,g,e,t,r]),x=r.split("/").pop()??r,[v,_]=y.useState(null),[S,k]=y.useState(!1),N=Kn(),O=y.useMemo(()=>Sg(e,n),[e,n]),P=y.useCallback(async j=>{_(null);try{await jg({confirm:N,ref:j,api:e,recursiveImpl:O})}catch(E){_(E instanceof Error?E:new Error(String(E)))}},[e,N,O]),R=y.useCallback(async()=>{if(await N({title:`Delete collection "${x}"?`,body:"This deletes every document in it (and their subcollections).",destructive:!0,confirmLabel:"Delete collection"})){_(null);try{await kg(O,a),o()}catch(E){_(E instanceof Error?E:new Error(String(E)))}}},[N,O,a,x,o]);return c.jsxs("section",{"data-pyric-ui":"fs-documents",className:"fs-pane fs-col",children:[c.jsxs("div",{className:"fs-phead",children:[c.jsx("span",{className:"fs-phead-title",children:x}),c.jsx("span",{className:"fs-phead-actions",children:c.jsx("button",{type:"button",className:"fs-add",onClick:()=>k(!0),children:"+ New"})}),c.jsx(gg,{items:[{label:"Delete collection",onSelect:()=>void R(),destructive:!0}]})]}),S?c.jsx(yg,{mode:"document",parentPath:`/${r}`,onCreate:async({docId:j,data:E})=>{const $=await m(j,E,{onExisting:"fail"});i($)},onClose:()=>k(!1)}):null,c.jsx(BD,{documents:w,isLoading:u,error:d,updateScope:`${r}:${h}`,hasMore:f,onLoadMore:p,onSelect:i,renderLabel:j=>{const E=j.ref;return c.jsx("span",{"data-pyric-selected":s===E.id?"":void 0,style:{display:"contents"},children:df(j)?c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"fs-doc-phantom",children:j.id}),c.jsx("span",{className:"fs-sub fs-doc-phantom-hint",children:"missing"})]}):j.id})},renderRowAction:j=>{if(df(j))return null;const E=j.ref;return c.jsx("button",{type:"button",className:"fs-doc-del",title:"Delete document","aria-label":`Delete ${E.id}`,onClick:$=>{$.stopPropagation(),P(E)},children:"×"})},emptyState:c.jsx("p",{className:"fs-empty",children:"No documents."})}),v?c.jsx("p",{className:"fs-empty fs-doc-del-err",children:v.message}):null]})}function iM({api:e,firestore:t,handles:n,docPath:r,onOpenSubcollection:s,onReferenceClick:i,onStartCollection:o,onDeleted:a}){const l=y.useMemo(()=>e.doc(t,r),[e,t,r]),{data:u,error:d,isLoading:h}=DP(l),f=y.useCallback(async(_,S)=>(await n.listSubcollections(S.path)).map(N=>e.collection(S,N)),[n,e]),p=Kn(),m=y.useMemo(()=>Sg(e,n),[e,n]),[g,b]=y.useState(null),w=y.useCallback(async()=>{b(null);try{await jg({confirm:p,ref:l,api:e,recursiveImpl:m})&&a()}catch(_){b(_ instanceof Error?_:new Error(String(_)))}},[e,p,m,l,a]),x=y.useCallback(async()=>{await e.setDoc(l,{})},[e,l]),v=u!=null&&YT(u);return c.jsxs("section",{"data-pyric-ui":"fs-document",className:"fs-pane fs-col doc",children:[v?null:c.jsxs("div",{className:"fs-phead",children:[c.jsx("span",{className:"fs-phead-title",children:l.id}),c.jsx("span",{className:"fs-phead-actions",children:c.jsx("button",{type:"button",className:"fs-add",onClick:o,children:"+ Collection"})})]}),u&&v?c.jsx(HT,{snapshot:u,documentRef:l,firestore:t,listSubcollections:f,onReferenceClick:i,onSubcollectionClick:s,onStartCollection:o,onDeleteDocument:()=>void w(),onDeleteDocumentFields:x,onCommit:async _=>{await e.setDoc(l,_)}},r):d?c.jsx("p",{className:"fs-empty fs-doc-del-err",children:d.message}):h?c.jsx("p",{className:"fs-empty",children:"Loading document…"}):c.jsxs(c.Fragment,{children:[c.jsx("p",{className:"fs-empty",children:"This document does not exist."}),c.jsx(_g,{firestore:t,documentRef:l,listSubcollections:f,onSubcollectionClick:s})]}),g?c.jsx("p",{className:"fs-empty fs-doc-del-err",children:g.message}):null]})}const oM="block w-full text-sm text-soft-white";function aM({auth:e,focusUid:t}){const{users:n,totalCount:r,isLoading:s,error:i,filter:o,setFilter:a,updateUser:l}=Li(e),[u,d]=y.useState(null);y.useEffect(()=>{t&&(d(t),a(t))},[t,a]);const h=n.find(f=>f.uid===u)??null;return c.jsxs("div",{className:"grid grid-cols-[1fr_320px] gap-4",children:[c.jsxs("section",{className:"min-w-0",children:[c.jsx("input",{value:o,onChange:f=>a(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"}),c.jsx(Ty,{users:n,isLoading:s,error:i,filter:o,onSelect:f=>d(f.uid),className:oM,emptyState:c.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:c.jsx("p",{className:"py-6 text-sm text-slate-gray",children:"No users match the filter."})}),c.jsxs("p",{className:"mt-2 text-xs text-slate-gray",children:[r," user(s) total"]})]}),c.jsx("section",{className:"min-w-0 border-l border-border pl-4",children:h?c.jsx(cM,{user:h,onSave:f=>l(h.uid,f)},h.uid):c.jsx("p",{className:"py-6 text-sm text-slate-gray",children:"Select a user to view and edit."})})]})}function cM({user:e,onSave:t}){const n=Py({initial:e}),[r,s]=y.useState(null),[i,o]=y.useState(!1),a=()=>{s(null),o(!1);try{t(n.toUpdateRequest()),o(!0)}catch(l){s(l instanceof Error?l:new Error(String(l)))}};return c.jsxs("div",{"data-pyric-ui":"auth-editor",children:[c.jsx("h3",{className:"mb-3 truncate font-mono text-xs text-slate-gray",title:e.uid,children:e.uid}),c.jsxs("label",{className:"mb-3 block text-xs text-slate-gray",children:["Display name",c.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"})]}),c.jsxs("label",{className:"mb-3 block text-xs text-slate-gray",children:["Custom claims (JSON)",c.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?c.jsx("span",{className:"text-danger",children:n.errors.claims}):null]}),c.jsxs("label",{className:"mb-3 flex items-center gap-2 text-xs text-slate-gray",children:[c.jsx("input",{type:"checkbox",checked:n.fields.disabled,onChange:l=>n.setField("disabled",l.target.checked)}),"Disabled"]}),r?c.jsx("p",{className:"mb-2 text-xs text-danger",children:r.message}):null,i?c.jsx("p",{className:"mb-2 text-xs text-primary",children:"Saved."}):null,c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{type:"button",onClick:a,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"}),c.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 ff(e){const t=de(e),n=t.lastIndexOf("/");return n===-1?"":t.slice(0,n)}function hf(e,t){return e===""?t:t===""?e:`${e}/${t}`}function pf(e){const t=e.lastIndexOf("/");return t===-1?e:e.slice(t+1)}const lM=[{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 uM(e){const t=Object.entries(e.customMetadata??{});return c.jsxs("dl",{"data-pyric-object-metadata":!0,children:[c.jsx("div",{"data-storage-meta-group":!0,children:"Metadata"}),lM.map(({key:n,label:r,value:s})=>{const i=s(e);return i===void 0?null:c.jsxs("div",{"data-pyric-metadata-field":n,children:[c.jsx("dt",{children:r}),c.jsx("dd",{children:i})]},n)}),t.length>0?c.jsx("div",{"data-storage-meta-group":!0,children:"Custom metadata"}):null,t.map(([n,r])=>c.jsxs("div",{"data-pyric-metadata-field":"customMetadata","data-pyric-metadata-key":n,children:[c.jsx("dt",{children:n}),c.jsx("dd",{children:r})]},`custom:${n}`))]})}function dM(){return c.jsx("svg",{"aria-hidden":!0,viewBox:"0 0 16 16",width:"13",height:"13",fill:"none",stroke:"currentColor",strokeWidth:"1.25",strokeLinejoin:"round",children:c.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 fM(){return c.jsxs("svg",{"aria-hidden":!0,viewBox:"0 0 16 16",width:"13",height:"13",fill:"none",stroke:"currentColor",strokeWidth:"1.25",strokeLinejoin:"round",children:[c.jsx("path",{d:"M4.25 1.75h5l3 3v9.5h-8z"}),c.jsx("path",{d:"M9.25 1.75v3h3"})]})}function hM(e){const t=e.kind==="folder";return c.jsxs(c.Fragment,{children:[c.jsxs("span",{className:"storage__cell-name",children:[c.jsx("span",{className:"storage__ic","aria-hidden":!0,children:t?c.jsx(dM,{}):c.jsx(fM,{})}),c.jsx("span",{className:"storage__nm",children:e.name}),t?c.jsx("span",{"aria-hidden":!0,className:"storage__chev",children:"›"}):null]}),c.jsx("span",{className:"storage__cell-type",children:t?"folder":"file"}),c.jsx("span",{className:"storage__cell-size"}),c.jsx("span",{className:"storage__cell-updated"})]})}function pM({storage:e,focusTarget:t}){const n=qi(),r=t.kind==="object"?de(t.path):null,s=t.kind==="prefix"?de(t.path):r?ff(r):"",i=y.useCallback(j=>{const E=de(j);n.navigate(E?{view:"storage",kind:"prefix",path:E}:{view:"storage",kind:"root"})},[n.navigate]),o=JD({path:s,onPathChange:i}),a=j=>{n.navigate({view:"storage",kind:"object",path:de(j)})},l=GD(e,o.path),u=QD(),d=sT(e),[h,f]=y.useReducer(mT,dg),p=aT(e,{path:o.path,list:l,onComplete:j=>f({type:"materialize",path:ff(j.fullPath)})});y.useEffect(()=>{if(l.status==="success")for(const j of l.entries)j.kind==="folder"&&cf(h,j.fullPath)&&f({type:"materialize",path:j.fullPath})},[l.status,l.entries,h]);const[m,g]=y.useState(!1),[b,w]=y.useState(""),[x,v]=y.useState(null),_=y.useRef(null),S=y.useMemo(()=>{const j=yT(h,o.path).filter(C=>!l.entries.some(I=>I.kind==="folder"&&I.name===C));if(j.length===0)return l.entries;const E=j.map(C=>{const I=hf(o.path,C);return{kind:"folder",name:C,fullPath:I,ref:{fullPath:I,name:C}}});return[...[...l.entries.filter(C=>C.kind==="folder"),...E].sort((C,I)=>C.name<I.name?-1:C.name>I.name?1:0),...l.entries.filter(C=>C.kind==="object")]},[l.entries,h,o.path]),k=S.length>0&&S.every(j=>u.isSelected(j.fullPath)),N=j=>{const E=new Set(S.map(C=>C.name)),$=pT(j.map(C=>C.relativePath),E);p.upload(j.map((C,I)=>({path:$[I],data:C.file})))},O=j=>{j.preventDefault();const E=gT(b);if(E){v(E);return}const $=hf(o.path,de(b));f({type:"create",path:$}),o.setPath($),w(""),v(null),g(!1)};y.useEffect(()=>u.clear(),[o.path,u.clear]);const P=p.tasks.filter(j=>j.status==="error"),R=d.verdictFor(o.path);return c.jsx(NT,{children:c.jsx(Bc,{children:c.jsxs("div",{className:"storage",children:[c.jsxs("div",{className:"storage__sub",children:[c.jsx(cT,{path:o.path,rootLabel:"files",onNavigate:o.setPath}),c.jsx("div",{className:"storage__actions",children:u.size>0?c.jsxs(c.Fragment,{children:[c.jsxs("span",{className:"studio-selection-count",children:[u.size," selected"]}),c.jsx(IT,{storage:e,entries:u.selected,list:l,gate:d,className:"studio-selection-delete",onDeleted:j=>{for(const E of u.selected)E.kind==="folder"&&j.deleted.includes(E.fullPath)&&f({type:"discard",path:E.fullPath});r&&u.selected.some(E=>E.kind==="object"?E.fullPath===r:r.startsWith(`${E.fullPath}/`))&&o.setPath(o.path),u.clear(),l.refresh()},onFailed:j=>{const E=new Set(j.failed.map($=>$.fullPath));u.selectAll(u.selected.filter($=>E.has($.fullPath))),l.refresh()}}),c.jsx("button",{type:"button",className:"storage__action",onClick:u.clear,children:"Clear selection"})]}):c.jsxs(c.Fragment,{children:[c.jsx("button",{type:"button",className:"storage__action","aria-expanded":m,onClick:()=>{g(j=>!j),v(null)},children:"New folder"}),c.jsx("button",{type:"button",className:"storage__action storage__action--upload",onClick:()=>_.current?.click(),children:"Upload files"}),c.jsx("input",{ref:_,type:"file",multiple:!0,hidden:!0,onChange:j=>{const E=Array.from(j.currentTarget.files??[]);E.length>0&&N(E.map($=>({file:$,relativePath:$.name}))),j.currentTarget.value=""}})]})})]}),m?c.jsxs("form",{className:"storage__newfolder",onSubmit:O,children:[c.jsx("input",{autoFocus:!0,className:"storage__newfolder-input",placeholder:"folder or nested/path/of/folders","aria-label":"New folder name",value:b,onChange:j=>{w(j.currentTarget.value),v(null)},onKeyDown:j=>{j.key==="Escape"&&g(!1)}}),c.jsx("button",{type:"submit",className:"storage__newfolder-btn",children:"Create"}),x?c.jsx("span",{className:"storage__newfolder-err",role:"alert",children:x}):c.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,P.length>0?c.jsxs("p",{className:"storage__upload-err",role:"alert",children:[P.length===1?`Upload failed: ${pf(P[0].fullPath)} — ${P[0].error?.message??"error"}`:`${P.length} uploads failed: ${P.map(j=>pf(j.fullPath)).join(", ")}`,c.jsx("button",{type:"button",className:"storage__upload-err-dismiss",onClick:p.clearCompleted,children:"Dismiss"})]}):null,c.jsxs("div",{className:"storage__body","data-storage-level":r?"inspector":"browser",children:[c.jsxs(dT,{className:"storage__browser",onFiles:N,disabled:!R.upload,disabledReason:R.reasons.write.join("; "),children:[c.jsxs("div",{className:"storage__lhead",children:[c.jsx("label",{className:"storage__select-all",title:"Select all in this folder",children:c.jsx("input",{type:"checkbox","aria-label":"Select all in this folder",checked:k,onChange:j=>j.currentTarget.checked?u.selectAll(S):u.clear()})}),c.jsx("span",{children:"name"}),c.jsx("span",{children:"type"}),c.jsx("span",{children:"size"}),c.jsx("span",{children:"updated"})]}),c.jsx(lT,{entries:S,status:l.status,error:l.error,gate:d,selectedPath:r??void 0,renderEntry:hM,renderRowAction:j=>c.jsx("label",{className:"storage__select-row",title:`Select ${j.name}`,children:c.jsx("input",{type:"checkbox","aria-label":`Select ${j.name}`,checked:u.isSelected(j.fullPath),onChange:()=>u.toggle(j)})}),onNavigate:o.enter,onSelect:j=>a(j.fullPath),emptyState:c.jsx("p",{className:"storage__empty",children:cf(h,o.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."})}),c.jsxs("div",{className:"storage__dropcue","aria-hidden":!0,children:["Drop to upload to /",o.path||""]})]}),c.jsx("div",{className:"storage__inspector",children:r?c.jsxs(c.Fragment,{children:[c.jsx("button",{type:"button",className:"storage__back",onClick:()=>o.setPath(o.path),"aria-label":"Back to files",children:"‹ Files"}),c.jsx(ET,{storage:e,path:r,renderMetadata:uM})]}):c.jsx("p",{className:"storage__inspector-hint",children:"Select an object to inspect its preview and metadata."})})]})]})})})}function mM({view:e}){const t=e==="firestore"?"Firestore":e==="auth"?"Auth":"Storage";return c.jsxs("div",{"data-pyric-ui":"data-pending",className:"flex flex-col items-center justify-center gap-2 py-16 text-center",children:[c.jsx("span",{className:"rounded-full border border-border px-3 py-1 text-xs uppercase tracking-wide text-slate-gray",children:"Local backend pending"}),c.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 Eg({view:e}){const{target:t}=qi(),n=Rt(),r=n.status==="ready"?n.handles.auth:null;return c.jsx("div",{"data-pyric-ui":"data-feature",children:n.status!=="ready"||!r?c.jsx(mM,{view:e}):n.authApi?c.jsx(Iy,{value:n.authApi,children:c.jsx(mf,{view:e,handles:n.handles,auth:r,target:t,firestoreApi:n.firestoreApi,storageApi:n.storageApi})}):c.jsx(mf,{view:e,handles:n.handles,auth:r,target:t,firestoreApi:n.firestoreApi,storageApi:n.storageApi})})}function mf({view:e,handles:t,auth:n,target:r,firestoreApi:s,storageApi:i}){const{users:o}=Li(n),a=y.useMemo(()=>new Set(o.map(l=>l.uid)),[o]);switch(e){case"firestore":{const l=c.jsx(eM,{handles:t,knownUids:a});return s?c.jsx(PP,{value:s,children:l}):l}case"auth":return c.jsx(aM,{auth:n,focusUid:r?.view==="auth"?r.uid:null});case"storage":{const l=c.jsx(pM,{storage:t.storage,focusTarget:r?.view==="storage"?r:{kind:"root"}});return i?c.jsx(KD,{value:i,children:l}):l}}}function yM(){return c.jsx(Eg,{view:"firestore"})}function gM(){return c.jsx(Eg,{view:"storage"})}function bM(e,t){const n=new Set(t.map(r=>r.uid));return new Set([...e].filter(r=>n.has(r)))}async function wM(e,t){const n=[];for(const r of e)try{await t(r.uid)}catch{n.push(r.uid)}return n}function vM(e){const[t,n]=y.useState(()=>new Set);y.useEffect(()=>{n(s=>{const i=bM(s,e);return i.size===s.size&&[...i].every(o=>s.has(o))?s:i})},[e]);const r=y.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 o=new Set(i);return o.has(s)?o.delete(s):o.add(s),o})},selectAll(s){n(s?new Set(e.map(i=>i.uid)):new Set)},replace(s){n(new Set(s))},clear(){n(new Set)}}}function xM({users:e,filter:t,onDelete:n,onComplete:r}){const s=Kn(),[i,o]=y.useState(!1),[a,l]=y.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;o(!0),l(null);const f=await wM(e,n);o(!1),l(f.length>0?`Could not delete ${f.length} selected user(s).`:null),r(f)};return c.jsxs(c.Fragment,{children:[c.jsx("button",{type:"button",className:"studio-selection-delete",disabled:i,onClick:()=>void u(),children:i?"Deleting…":"Delete"}),a?c.jsx("span",{className:"auth-sub__error",children:a}):null]})}function Cg(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 Ng(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 _M(e){const t=e.isAnonymous&&!e.email,n=e.email??e.phoneNumber??(t?"anonymous":e.uid);return c.jsxs("span",{className:t?"auth-ident auth-ident--anon":"auth-ident",children:[c.jsx("span",{className:"auth-ident__primary",title:n,children:n}),c.jsx("span",{className:"auth-ident__uid",title:e.uid,children:e.uid})]})}function SM({auth:e}={}){const t=Kt(),n=Rt(),r=e??(n.status==="ready"?n.handles.auth:null),s=n.status==="ready"?n.authApi:void 0;if(!r)return c.jsx("div",{className:"auth-surface","data-pyric-ui":"auth-surface",children:c.jsx(NM,{status:t.status})});const i=c.jsx(Bc,{children:c.jsx(kM,{auth:r})});return s?c.jsx(Iy,{value:s,children:i}):i}function kM({auth:e}){const{users:t,totalCount:n,isLoading:r,error:s,filter:i,setFilter:o,createUser:a,updateUser:l,deleteUser:u}=Li(e),d=qi(),h=d.target?.view==="auth"?d.target.uid:null,f=w=>d.navigate({view:"auth",uid:w}),p=y.useMemo(()=>t.find(w=>w.uid===h)??null,[t,h]),[m,g]=y.useState(!1),b=vM(t);return c.jsxs("div",{className:"auth-surface","data-pyric-ui":"auth-surface",children:[c.jsxs("div",{className:"auth-sub",children:[c.jsxs("span",{className:"auth-sub__h",children:["users ",c.jsxs("span",{className:"auth-sub__n",children:["· ",n]})]}),c.jsx("input",{className:"auth-sub__filter",value:i,onChange:w=>o(w.target.value),placeholder:"filter users…","aria-label":"Filter users"}),c.jsx("div",{className:"auth-sub__right",children:b.selectedUsers.length>0?c.jsxs(c.Fragment,{children:[c.jsxs("span",{className:"studio-selection-count",children:[b.selectedUsers.length," selected"]}),c.jsx(xM,{users:b.selectedUsers,filter:i,onDelete:w=>Promise.resolve(u(w)),onComplete:w=>{b.replace(w),h&&!w.includes(h)&&f(null)}}),c.jsx("button",{type:"button",className:"auth-sub__clear",onClick:b.clear,children:"Clear selection"})]}):c.jsx("button",{type:"button",className:"auth-sub__add",onClick:()=>{g(!0),f(null)},children:"Add user"})})]}),c.jsxs("div",{className:"auth-body","data-auth-level":p||m?"detail":"list",children:[c.jsx("div",{className:"auth-list",children:c.jsx(Ty,{users:t,isLoading:r,error:s,filter:i,onSelect:w=>{g(!1),f(w.uid)},renderIdentifier:_M,formatCreatedAt:Ng,formatLastLoginAt:Cg,renderSelectionHeader:c.jsx("label",{className:"auth-select",title:"Select all shown users",children:c.jsx("input",{type:"checkbox","aria-label":"Select all shown users",checked:b.allVisibleSelected,onChange:w=>b.selectAll(w.currentTarget.checked)})}),renderSelection:w=>c.jsx("label",{className:"auth-select",title:`Select ${w.uid}`,children:c.jsx("input",{type:"checkbox","aria-label":`Select ${w.uid}`,checked:b.isSelected(w.uid),onChange:()=>b.toggle(w.uid)})}),emptyState:c.jsx("p",{className:"auth-zero",children:"No users yet. Sign-ins from the app, agent-seeded users, and “Add user” all land here."}),noResultsState:c.jsxs("p",{className:"auth-zero",children:["No users match “",i,"”."]})})}),c.jsx("div",{className:"auth-detail",children:m?c.jsx(jM,{onCancel:()=>g(!1),onCreate:async w=>{const x=await Promise.resolve(a(w));g(!1),f(x.uid)}}):p?c.jsxs(c.Fragment,{children:[c.jsx("button",{type:"button",className:"auth-back",onClick:()=>f(null),"aria-label":"Back to users",children:"‹ Users"}),c.jsx(CM,{user:p,onSave:w=>{w.mode==="edit"&&l(w.uid,w.request)},onProvidersChange:async w=>{await Promise.resolve(l(p.uid,{providerUserInfo:w}))},onDelete:()=>{u(p.uid),f(null)}},p.uid)]}):c.jsx("div",{className:"auth-detail__empty",children:c.jsx("p",{className:"auth-zero",children:"Select a user to view and edit."})})})]})]})}function jM({onCreate:e,onCancel:t}){const[n,r]=y.useState(null),s=i=>{i.mode==="create"&&(r(null),e(i.request).catch(o=>{r(o instanceof Error?o:new Error(String(o)))}))};return c.jsxs("div",{className:"auth-editor","data-pyric-ui":"auth-create-user",children:[c.jsxs("div",{className:"auth-editor__head",children:[c.jsx("div",{className:"auth-editor__who",children:"New user"}),c.jsx("div",{className:"auth-editor__meta",children:"Created without signing in — admin semantics, like the emulator’s add-user flow."})]}),c.jsx(My,{onSubmit:s,onCancel:t,submitLabel:"Create user",children:n?c.jsx("p",{className:"auth-save auth-save--error",role:"alert",children:n.message}):null})]})}const yf=[...Ah];function EM({user:e,onChange:t}){const[n,r]=y.useState(null),[s,i]=y.useState(""),o=e.providerUserInfo.map(p=>p.providerId),a=o.includes("password"),l=o.filter(p=>p!=="password"),u=l.filter(p=>!yf.includes(p)),d=p=>{r(null),t(p.map(m=>({providerId:m}))).catch(m=>{r(m instanceof Error?m:new Error(String(m)))})},h=(p,m)=>{d(m?[...l,p]:l.filter(g=>g!==p))},f=()=>{const p=s.trim();p&&(i(""),!l.includes(p)&&d([...l,p]))};return c.jsxs("section",{className:"auth-providers-editor","aria-label":"Sign-in providers",children:[c.jsx("div",{className:"auth-group",children:"Sign-in providers"}),c.jsx("div",{className:"auth-providers-editor__list",children:[...yf,...u].map(p=>c.jsxs("label",{className:"auth-provider-row","data-pyric-provider-id":p,children:[c.jsx("input",{type:"checkbox",checked:l.includes(p),onChange:m=>h(p,m.target.checked)}),c.jsx("span",{className:"auth-provider-row__label",children:yi(p)}),c.jsx("span",{className:"auth-provider-row__id",children:p})]},p))}),a||e.isAnonymous?c.jsx("p",{className:"auth-providers-editor__derived",children:a?"Password is linked by the password credential above.":"Anonymous — the provider lives on the token, not the record."}):null,c.jsx("div",{className:"auth-provider-custom",children:c.jsxs("label",{className:"auth-provider-custom__field",children:[c.jsx("span",{className:"auth-provider-custom__label",children:"Custom provider ID"}),c.jsxs("span",{className:"auth-provider-custom__row",children:[c.jsx("input",{type:"text",value:s,placeholder:"oidc.my-provider",onChange:p=>i(p.target.value),onKeyDown:p=>{p.key==="Enter"&&(p.preventDefault(),f())}}),c.jsx("button",{type:"button",onClick:f,disabled:!s.trim(),children:"Link"})]})]})}),n?c.jsx("p",{className:"auth-save auth-save--error",role:"alert",children:n.message}):null]})}function CM({user:e,onSave:t,onProvidersChange:n,onDelete:r}){const[s,i]=y.useState(null),[o,a]=y.useState(!1),l=h=>{i(null),a(!1);try{t(h),a(!0)}catch(f){i(f instanceof Error?f:new Error(String(f)))}},u=Ng(e.createdAt),d=Cg(e.lastLoginAt);return c.jsxs("div",{className:"auth-editor","data-pyric-user-disabled":e.disabled?"":void 0,children:[c.jsxs("div",{className:"auth-editor__head",children:[c.jsxs("div",{className:"auth-editor__who",children:[e.email??(e.isAnonymous?"anonymous":e.uid),e.disabled?c.jsx("span",{className:"auth-tag-off",children:"disabled"}):null]}),c.jsxs("div",{className:"auth-editor__uid",children:["uid · ",e.uid]}),c.jsxs("div",{className:"auth-editor__meta",children:["created ",u," · signed in ",d]})]}),c.jsx(EM,{user:e,onChange:n}),c.jsxs(My,{initial:e,onSubmit:l,submitLabel:"Save",children:[s?c.jsx("p",{className:"auth-save auth-save--error",role:"alert",children:s.message}):null,o?c.jsx("p",{className:"auth-save auth-save--ok",children:"Saved."}):null]},e.uid),c.jsx("div",{className:"auth-editor__foot",children:c.jsx(Z$,{user:e,onDelete:r,className:"auth-del"})})]})}function NM({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 c.jsx("div",{className:"auth-detail__empty","data-pyric-ui":"auth-surface-empty",children:c.jsx("p",{className:"auth-zero",children:t})})}function RM(e){return e.operationContext.source.kind==="studio"}function IM(e,t){return t?e.filter(n=>!RM(n)):[...e]}const AM=["all","allow","deny","proof-unsupported","bypassed"];function Gn(e){return e.rulesDisposition.kind==="bypassed"?"bypassed":Tc(e)?"proof-unsupported":e.rulesDisposition.kind==="evaluated"?e.rulesDisposition.verdict:null}function OM(e,t){return t==="all"?[...e]:e.filter(n=>Gn(n)===t)}function Po(e){return e.rulesDisposition.kind==="evaluated"}function gf(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}}function $M(e){return e.filter(t=>{const n=Gn(t);return n==="allow"||n==="deny"})}function PM(e,t){return e.filter(n=>n.at>=t.start&&n.at<t.end&&Gn(n)==="proof-unsupported").length}function Rg(e){return e==="proof-unsupported"?"Query proof unsupported":e}const za="inspect";function Ig(e){const t=e[za];return t||null}function Ag(e,t){const{[za]:n,...r}=e;return t?{...r,[za]:t}:r}function DM(e,t){return Ag(e,Ig(e)===t?null:t)}const TM=y.lazy(()=>Wp(()=>import("./RulesCodeEditor.kBYcclwV.js"),__vite__mapDeps([0,1,2])));function Og(e){return c.jsx(y.Suspense,{fallback:c.jsx(MM,{value:e.value,minHeightRem:e.minHeightRem}),children:c.jsx(TM,{...e})})}function MM({value:e,minHeightRem:t=14}){return c.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 $g({denial:e,rulesSource:t}){const n=qO(e);let r="denied",s="deny";return Tc(e)?(r="Query proof unsupported",s="proof-unsupported"):e.unsupported&&(r="unsupported",s="unsupported"),c.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:[c.jsxs("section",{children:[c.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.result==="allow"?c.jsx(Ta,{kind:"allow",className:"rounded bg-primary/15 px-2 py-0.5 text-xs font-semibold uppercase text-primary",children:"allowed"}):c.jsx(Ta,{kind:s,className:"rounded bg-danger/15 px-2 py-0.5 text-xs font-semibold uppercase text-danger",children:r}),c.jsxs("span",{className:"font-mono text-sm text-soft-white",children:[e.service!=="firestore"?`${e.service} · `:"",e.method," ",e.path]})]}),c.jsx("p",{className:"text-sm leading-relaxed text-soft-white",children:n.headline})]}),n.noEvaluation?c.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."}):c.jsxs(c.Fragment,{children:[c.jsx(LM,{denial:e,exp:n,rulesSource:t}),c.jsx(qM,{denial:e})]}),c.jsx(zM,{denial:e})]})}function LM({denial:e,exp:t,rulesSource:n}){const r=t.engine==="rtdb",s=t.engine==="storage";return r?c.jsx(KM,{denial:e,exp:t,rulesSource:n},e.id):s?c.jsx(YM,{exp:t}):c.jsx(VM,{denial:e,exp:t,rulesSource:n})}function UM(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 o=JSON.parse(i);return Array.isArray(o)?o:null}catch{return null}}function BM(e){const n=e.indexOf("// @pyric-source-map:");return n!==-1?e.slice(0,n).trimEnd():e}function FM(e,t){if(e===void 0||t===void 0)return t;const s=UM(e);if(s!==null){const o=s.find(l=>l.authoredLine===t);if(o!==void 0)return o.generatedLine}return t}function VM({denial:e,exp:t,rulesSource:n}){const r=Mc(e),s=r?.rule?.line??e.evaluatedRule?.line,i=FM(n,s),o=n!==void 0?BM(n):void 0,a=e.result==="allow",l=!!(o&&o.trim().length>0);return c.jsxs(kt,{label:r?`query proof — ${t.ruleNode}`:t.implicitDeny||!t.ruleNode?"matched rule":`matched rule — ${t.ruleNode}${s?` · line ${s}`:""}`,children:[r?.predicate?c.jsxs("div",{className:"mb-3 text-sm text-slate-gray",children:[c.jsxs("p",{children:["Unsupported predicate",r.predicate.citation?` · ${r.predicate.citation}`:""]}),c.jsx("pre",{className:"overflow-auto font-mono text-xs",children:r.predicate.expression})]}):null,l?c.jsx(Og,{value:o,readOnly:!0,markLine:i,markKind:a?"allow":"deny",minHeightRem:12,ariaLabel:r?"Deployed firestore.rules — the rule Pyric could not prove is marked":`Deployed firestore.rules — the ${a?"allowing":"denying"} rule is marked`}):c.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:[...r?.rule?.expression?[r.rule.expression]:[],...t.ruleLines,...t.otherLines].join(`
|
|
142
|
+
`)||"(no trace)"})]})}function qM({denial:e}){const t=GO(e);return t.length===0?null:c.jsx(kt,{label:Mc(e)?"residual evaluation — separate from the static proof":"show the work — how the condition evaluated",children:c.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)=>c.jsx(Jc,{step:n},r))})})}const WM={true:"✓",false:"✗",skipped:"⊘",error:"!",unsupported:"?",value:"·"};function Jc({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:e.outcome==="unsupported"?`unsupported${e.error?`: ${e.error}`:""}`:`→ ${Pg(e.value)}`;return c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"flex items-baseline gap-2 font-mono text-xs",style:{paddingLeft:`${e.depth*.9}rem`},children:[c.jsx("span",{"aria-hidden":!0,className:`w-3 shrink-0 text-center font-bold ${t}`,children:WM[e.outcome]}),c.jsxs("span",{className:e.outcome==="skipped"?"text-slate-gray line-through":"text-soft-white",children:[e.letBinding?`let ${e.letBinding} = `:"",e.source]}),c.jsx("span",{className:"text-slate-gray",children:n}),e.inlinedFrom?c.jsxs("span",{className:"text-[0.6rem] uppercase tracking-wide text-slate-gray",children:[e.inlinedFrom,"()"]}):null]}),e.children.map((r,s)=>c.jsx(Jc,{step:r},s))]})}function Pg(e){if(e===void 0)return"undefined";try{return JSON.stringify(gi(e))}catch{return String(e)}}function zM({denial:e}){const t=QO(e);return c.jsx(kt,{label:"what the rule saw (request / resource)",children:c.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=>c.jsx(HM,{variable:n},n.name))})})}function HM({variable:e}){return c.jsxs("div",{className:"flex flex-col gap-0.5",children:[c.jsx("span",{className:"font-mono text-[0.7rem] text-primary",children:e.name}),e.present?c.jsx(Dg,{value:e.value}):c.jsxs("span",{className:"font-mono text-xs italic text-slate-gray",children:["absent",e.absentNote?` — ${e.absentNote}`:""]})]})}function Dg({value:e,depth:t=0}){const[n,r]=y.useState(t<2),s=gi(e);if(s===null||typeof s!="object")return c.jsx("span",{className:"font-mono text-xs text-soft-white",children:Pg(s)});const i=Array.isArray(s)?s.map((o,a)=>[String(a),o]):Object.entries(s);return i.length===0?c.jsx("span",{className:"font-mono text-xs text-slate-gray",children:Array.isArray(s)?"[]":"{}"}):c.jsxs("div",{className:"flex flex-col",children:[c.jsxs("button",{type:"button",onClick:()=>r(o=>!o),"aria-expanded":n,className:"flex w-fit items-center gap-1 font-mono text-xs text-slate-gray hover:text-soft-white",children:[c.jsx("span",{"aria-hidden":!0,children:n?"▾":"▸"}),c.jsx("span",{children:Array.isArray(s)?`[${i.length}]`:`{${i.length}}`})]}),n?c.jsx("div",{className:"flex flex-col gap-0.5 border-l border-border pl-3",children:i.map(([o,a])=>c.jsxs("div",{className:"flex flex-wrap items-baseline gap-2",children:[c.jsxs("span",{className:"font-mono text-xs text-slate-gray",children:[o,":"]}),c.jsx(Dg,{value:a,depth:t+1})]},o))}):null]})}function KM({denial:e,exp:t,rulesSource:n}){const r=VO(e,n),s=YO(e,n),[i,o]=y.useState(null),[a,l]=y.useState(!1),u=a?s:s.slice(0,GM),d=i===null?void 0:s[i];let h=r;d&&(h=d.verdict==="UNSUPPORTED"?void 0:d.line);const f=d?d.verdict==="ALLOW":e.result==="allow",p=n!==void 0&&n.trim().length>0;let m;t.implicitDeny||!t.ruleNode?m="rule node":r!==void 0?m=`rule node: ${t.ruleNode} · line ${r}`:m=`rule node: ${t.ruleNode}`;let g;return f?g="Deployed database.rules.json, the allowing rule is marked":g="Deployed database.rules.json, the denying rule is marked",c.jsxs(c.Fragment,{children:[c.jsx(kt,{label:m,children:p?c.jsx("div",{"data-pyric-ui":"rtdb-rule-source","data-marked-line":h,children:c.jsx(Og,{value:n,readOnly:!0,markLine:h,markKind:f?"allow":"deny",minHeightRem:12,ariaLabel:g})}):c.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}`:""]})}),s.length>0?c.jsxs(kt,{label:"evaluated rules, root first",children:[c.jsx("ul",{"data-pyric-ui":"rtdb-trace",className:"flex flex-col gap-1",children:u.map((b,w)=>c.jsx(JM,{row:b,current:w===i,onSelect:()=>o(w)},w))}),s.length>u.length?c.jsxs("button",{type:"button","data-pyric-ui":"rtdb-trace-show-all",onClick:()=>l(!0),className:"w-fit font-mono text-xs text-slate-gray hover:text-soft-white",children:["show all ",s.length," rules"]}):null]}):null,!p&&t.ruleExpression?c.jsx(kt,{label:"rule expression",children:c.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?c.jsx(kt,{label:"$variable bindings",children:c.jsx("code",{className:"font-mono text-xs text-soft-white",children:Object.entries(t.bindings).map(([b,w])=>`${b.startsWith("$")?b:`$${b}`} → ${w}`).join(", ")})}):null,e.rules?.reason?c.jsx(kt,{label:"simulator reason",children:c.jsx("code",{className:"font-mono text-xs text-slate-gray",children:e.rules.reason})}):null]})}const GM=20;function JM({row:e,current:t,onSelect:n}){const r=Object.entries(e.bindings);return c.jsxs("li",{"data-pyric-ui":"rtdb-trace-row","data-line":e.line,"aria-current":t?"true":void 0,onClick:n,className:`flex cursor-pointer flex-col gap-1 rounded-md border px-3 py-2 ${t?"border-primary bg-primary/10":"border-border bg-content-bg hover:bg-sidebar-bg"}`,children:[c.jsxs("button",{type:"button",onClick:s=>{s.stopPropagation(),n()},className:"flex w-fit items-baseline gap-2 font-mono text-xs text-slate-gray",children:[c.jsx("span",{className:"text-soft-white",children:e.path}),c.jsxs("span",{children:[".",e.kind]}),e.line!==void 0?c.jsxs("span",{children:["line ",e.line]}):null]}),c.jsx(Jc,{step:e.step}),r.length>0?c.jsx("code",{className:"font-mono text-xs text-slate-gray",children:r.map(([s,i])=>`${s} → ${i}`).join(", ")}):null]})}function YM({exp:e}){return c.jsxs(kt,{label:e.implicitDeny?"matched rule":"matched rule (match block)",children:[e.ruleNode?c.jsx("code",{className:"mb-2 block font-mono text-xs text-soft-white",children:e.ruleNode}):null,c.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(`
|
|
143
|
+
`)||"(no trace)"})]})}function kt({label:e,children:t}){return c.jsxs("div",{className:"flex flex-col gap-1",children:[c.jsx("span",{className:"text-[0.65rem] font-semibold uppercase tracking-wider text-slate-gray",children:e}),t]})}function QM(e="firestore"){const t=Kt(),n=t.status==="ready",[r,s]=y.useState({});return y.useEffect(()=>{if(n)return;let i=!0;return fetch("/__pyric/init.json").then(o=>o.ok?o.json():null).then(o=>{if(!i||!o||typeof o!="object")return;const l={};typeof o.rules=="string"&&(l.firestore=o.rules),o.databaseRules!==void 0&&o.databaseRules!==null&&(typeof o.databaseRules=="string"?l.rtdb=o.databaseRules:l.rtdb=JSON.stringify(o.databaseRules,null,2)),typeof o.storageRules=="string"&&(l.storage=o.storageRules),s(l)}).catch(()=>{}),()=>{i=!1}},[n]),y.useMemo(()=>{const i=t.status==="ready",o=e==="database"?"rtdb":e;if(!i){const a=r[o];return a!==void 0?a:""}try{if(o==="rtdb"){const u=my(t.handles.sandbox);return u!=null?JSON.stringify(u,null,2):""}return Jr(t.handles.sandbox).getRules()}catch{return""}},[t,r,e])}function bf({eventId:e,onClose:t}){const r=n$().find(o=>o.id===e),s=r?.service??"firestore",i=QM(s);return r?c.jsxs("div",{"data-pyric-ui":"traffic-rules-inspector",className:"traffic__inspector",children:[c.jsxs("div",{className:"traffic__inspector-bar",children:[c.jsx("span",{className:"traffic__inspector-title",children:"rules inspector"}),c.jsx("button",{type:"button",className:"traffic__inspector-close",onClick:t,"aria-label":"Close rules inspector (Esc)",children:"close (esc)"})]}),c.jsx($g,{denial:r,rulesSource:i})]}):c.jsxs("div",{"data-pyric-ui":"traffic-inspect-missing",className:"traffic__inspector",children:[c.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."}),c.jsx("button",{type:"button",className:"traffic__inspector-close",onClick:t,children:"Back to the log"})]})}const XM=new Intl.NumberFormat,ZM={reads:"read operations",writes:"writes",deletes:"deletes"},eL={allows:"allowed requests",denies:"denied requests"};function wf(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 vf(e){return e&&`${e[0].toUpperCase()}${e.slice(1)}`}function Tg(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=`${XM.format(n)} observed ${n===1?t.singular:t.plural}`,o=u=>t.labels[u.key]??u.label.toLowerCase();if(s.length>1){const u=s.map(o);return{total:n,headline:i,finding:s.length===e.length?`${t.evenSplitPrefix} ${wf(u)}.`:`${vf(wf(u))} tied for the largest share of ${t.subject} in this window.`}}const a=s[0],l=Math.round(a.total/n*100);return{total:n,headline:i,finding:`${vf(o(a))} accounted for ${l}% of ${t.subject} in this window.`}}function tL(e){return Tg(e,{labels:ZM,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 nL(e){return Tg(e,{labels:eL,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 rL=new Intl.NumberFormat,sL=new Intl.DateTimeFormat(void 0,{hour:"numeric",minute:"2-digit"});function xf(e){return rL.format(e)}function cr(e){return sL.format(e)}function iL(e){return Gn(e)==="bypassed"}function oL(e){return e.every(t=>t.total===0)}function Mg({eyebrow:e,story:t,series:n,points:r,window:s,emptyLabel:i,evidenceTitle:o,source:a,methodology:l}){const[u,d]=y.useState(()=>new Set(n.map(f=>f.key))),h=y.useCallback(f=>{d(p=>{const m=new Set(p);return m.has(f)?m.delete(f):m.add(f),m})},[]);return c.jsxs("section",{className:"traffic__metric-panel traffic__metric-panel--journal","data-pyric-ui":"traffic-metric-panel",children:[c.jsxs("header",{className:"traffic__metric-story",children:[c.jsx("p",{className:"traffic__metric-eyebrow",children:e}),c.jsx("h3",{className:"traffic__metric-headline",children:t.headline}),c.jsx("p",{className:"traffic__metric-finding",children:t.finding})]}),c.jsx(Fc,{series:n,visible:u,onToggle:h,formatValue:xf,className:`traffic__metric-cards traffic__metric-cards--journal traffic__metric-cards--${n.length}`}),oL(n)?c.jsx("p",{className:"traffic__empty",children:i}):c.jsxs("div",{className:"traffic__metric-evidence",children:[c.jsxs("div",{className:"traffic__metric-evidence-header",children:[c.jsx("h4",{children:o}),c.jsxs("span",{children:[cr(s.start),"–",cr(s.end)]})]}),c.jsx(qy,{points:r,series:n,visible:u,omitZeroSeries:!0,formatValue:xf,formatTime:cr,className:"traffic__chart traffic__chart--journal"}),c.jsxs("div",{className:"traffic__metric-axis","aria-hidden":"true",children:[c.jsx("span",{children:cr(s.start)}),c.jsx("span",{children:cr(s.end)})]})]}),c.jsxs("footer",{className:"traffic__metric-footer",children:[c.jsx("p",{className:"traffic__metric-source",children:a}),c.jsxs("details",{className:"traffic__metric-methodology",children:[c.jsx("summary",{children:"How this is counted"}),c.jsx("div",{children:l})]})]})]})}function aL({events:e,window:t}){const n=y.useMemo(()=>e.filter(i=>(i.service??"firestore")==="firestore"),[e]),r=SP({events:n,window:t,isAdmin:iL}),s=y.useMemo(()=>tL(r.series),[r.series]);return c.jsx("div",{className:"traffic__metrics","data-pyric-ui":"traffic-billable-view",children:c.jsx(Mg,{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:c.jsxs(c.Fragment,{children:[c.jsxs("p",{children:["Counts successful Firestore sandbox ",c.jsx("code",{children:"get"}),"/",c.jsx("code",{children:"list"}),","," ",c.jsx("code",{children:"create"}),"/",c.jsx("code",{children:"update"}),"/",c.jsx("code",{children:"set"}),", and"," ",c.jsx("code",{children:"delete"}),"/",c.jsx("code",{children:"remove"})," operations in the displayed window. Rules-bypassed admin operations are included because they still execute."]}),c.jsxs("p",{children:[c.jsx("strong",{children:"Read ops are a proxy, not billed document reads."})," Each"," ",c.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 cL({events:e,window:t}){const n=y.useMemo(()=>$M(e),[e]),r=kP({events:n,window:t}),s=y.useMemo(()=>r.series.filter(o=>o.key==="allows"||o.key==="denies"),[r.series]),i=y.useMemo(()=>nL(s),[s]);return c.jsxs("div",{className:"traffic__metrics","data-pyric-ui":"traffic-rules-view",children:[c.jsxs("p",{children:["Query proof unsupported: ",PM(e,t)]}),c.jsx(Mg,{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:c.jsxs(c.Fragment,{children:[c.jsxs("p",{children:["Counts only operations whose canonical Rules disposition is"," ",c.jsx("code",{children:"evaluated"}),", grouped by its ",c.jsx("code",{children:"allow"})," or ",c.jsx("code",{children:"deny"})," ","verdict. Query-proof limitations are counted separately, not as ordinary denials."]}),c.jsxs("p",{children:[c.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."]})]})})]})}function Yc(e){for(const t of e??[])if(t.kind==="component")return t;return null}function Wi(e){for(const t of e??[])if(t.kind==="tag")return t;return null}function lL(e){for(const t of e??[])if(t.kind==="frame")return t;return null}function uL(e){const t=Yc(e);if(t?.element!==void 0)return t.element;const n=Wi(e);if(n?.element!==void 0)return n.element}function Mn(e){return typeof e=="string"?e:e.query!==void 0?`${e.collection} (query)`:e.collection}function dL(e,t){const n=Yc(e);if(n)return n.name;const r=Wi(e);return r?r.name:Mn(t)}function zi(e){const t=Yc(e.owners);if(t)return{key:`component:${t.name}`,label:t.name};const n=Wi(e.owners);if(n)return{key:`tag:${n.name}`,label:n.name};const r=Mn(e.target);return{key:`target:${r}`,label:r}}function fL(e,t){return!(t.service!==void 0&&e.service!==t.service||t.targetPrefix!==void 0&&t.targetPrefix!==""&&!gx(e.target,t.targetPrefix))}function hL(e,t={}){const n=new Map;for(const r of e){if(!fL(r,t))continue;const s=zi(r),i=n.get(s.key);i?i.listeners.push(r):n.set(s.key,{identity:s,listeners:[r]})}return[...n.values()].map(r=>Object.freeze({identity:r.identity,listeners:Object.freeze(r.listeners)})).sort((r,s)=>r.listeners[0].attachedAt-s.listeners[0].attachedAt)}function pL(e){return{history:()=>e,subscribe:()=>()=>{}}}function Lg(e){const t=vE(pL(e),()=>{});try{return t.report().incidents}finally{t.dispose()}}function mL(e){try{const t=JSON.parse(e.targetFingerprint);if(t.kind==="doc"&&typeof t.path=="string")return t.path;if(t.kind==="query"&&typeof t.collection=="string")return{collection:t.collection,query:!0}}catch{}return null}function yL(e,t){return typeof e=="string"||typeof t=="string"?e===t:e.collection===t.collection}function Ug(e,t){return e.filter(n=>{if(n.pattern!=="duplicate-listener"&&n.pattern!=="listener-churn")return!1;const r=mL(n);return r!==null&&yL(r,t)})}function gL(e,t){return e?.column===t&&e.direction==="asc"?{column:t,direction:"desc"}:{column:t,direction:"asc"}}const bL=e=>e.deliveryCount;function wL(e,t,n){const r=new Map;for(const s of e.listeners){const i=Mn(s.target),o=r.get(i);o?o.push(s):r.set(i,[s])}return[...r.entries()].map(([s,i])=>{const o=[...i].sort((l,u)=>l.attachedAt-u.attachedAt),a=o[0];return Object.freeze({key:`${e.identity.key}|${s}`,listeners:Object.freeze(o),listener:a,ownerLabel:e.identity.label,target:s,count:o.length,deliveryCount:o.reduce((l,u)=>l+n(u),0),incidents:Ug(t,a.target)})})}function _f(e,t){return e<t?-1:e>t?1:0}function wi(e){return e.incidents.length>0?1:0}function vL(e,t,n){return n==="target"?_f(e.target,t.target):n==="service"?_f(e.listener.service,t.listener.service):n==="attached"?e.listener.attachedAt-t.listener.attachedAt:n==="deliveries"?e.deliveryCount-t.deliveryCount:wi(e)-wi(t)}function xL(e,t){const n=wi(t)-wi(e);if(n!==0)return n;const r=t.deliveryCount-e.deliveryCount;return r!==0?r:e.listener.attachedAt-t.listener.attachedAt}function _L(e){if(e===void 0)return xL;const t=e.direction==="asc"?1:-1;return(n,r)=>{const s=vL(n,r,e.column)*t;return s!==0?s:n.listener.attachedAt-r.listener.attachedAt}}function SL(e,t,n,r=bL){const s=_L(n);return e.map(i=>{const o=[...wL(i,t,r)].sort(s);return Object.freeze({identity:i.identity,rows:Object.freeze(o),listenerCount:i.listeners.length})}).sort((i,o)=>s(i.rows[0],o.rows[0]))}function kL(e,t){let n=0;const r=[];let s;for(const a of e){n+=a.listenerCount,(s===void 0||a.listenerCount>s.count)&&(s={label:a.identity.label,count:a.listenerCount});for(const l of a.rows)l.count>1&&r.push(l.count)}const i=t.filter(a=>a.pattern==="listener-churn").length,o={listeners:n,duplicates:r,churn:i};return s!==void 0&&(o.busiest=s),o}function jL(e){let t=0,n=0,r=0;for(const s of e)for(const i of s.rows)i.deliveryCount>0?t+=i.count:n+=i.count,i.incidents.length>0&&(r+=i.count);return{delivering:t,idle:n,incidents:r}}function EL(e){const t=[e.deliveryCount>0?"delivering":"idle"];return e.incidents.length>0&&t.push("incidents"),t}function Qc(e){return e.kind==="snapshot_delivery"?!0:e.kind==="listener"&&e.phase==="delivery"}const Bg=[{key:"delivering",label:"Delivering"},{key:"idle",label:"Idle"},{key:"incidents",label:"Incidents"}];function CL(e){return Bg.map(t=>({key:t.key,label:t.label,values:[],total:e[t.key]}))}const Do=[{key:"firestore",label:"Firestore"},{key:"database",label:"Database"}];function NL(e,t){const n=new Map;for(const r of e){if(!Qc(r)||r.at<t.start||r.at>=t.end)continue;const s=r.listenerId;s!==void 0&&n.set(s,(n.get(s)??0)+1)}return n}function RL(e,t,n,r=24){const s=n.end-n.start,i=Do.map(f=>({key:f.key,label:f.label,values:[],total:0}));if(r<=0||s<=0)return{points:[],series:i,total:0};const o=s/r,a=new Map;for(const f of t)a.set(f.id,f.service);const l=new Map(Do.map(f=>[f.key,new Array(r).fill(0)]));let u=0;for(const f of e){if(!Qc(f)||f.at<n.start||f.at>=n.end)continue;const p=f.listenerId;if(p===void 0)continue;const m=a.get(p);if(m===void 0)continue;const g=l.get(m);if(g===void 0)continue;let b=Math.floor((f.at-n.start)/o);b>=r&&(b=r-1),g[b]=(g[b]??0)+1,u+=1}const d=[];for(let f=0;f<r;f+=1)d.push({index:f,start:n.start+f*o,end:n.start+(f+1)*o});const h=Do.map(f=>{const p=l.get(f.key);return{key:f.key,label:f.label,values:p,total:p.reduce((m,g)=>m+g,0)}});return{points:d,series:h,total:u}}function Ha(e,t){if(e===t)return!0;if(typeof e!=typeof t||e===null||t===null)return!1;if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((i,o)=>Ha(i,t[o]));if(typeof e!="object"||typeof t!="object")return!1;const n=e,r=t,s=Object.keys(n);return s.length!==Object.keys(r).length?!1:s.every(i=>Object.prototype.hasOwnProperty.call(r,i)&&Ha(n[i],r[i]))}function IL(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function AL(e){if(e.kind==="snapshot_delivery"){const r=e.sample?.docs;return r===void 0?[]:r.map(s=>[s.path,s.data])}const t=e.target?.path;if(t===void 0||t==="")return[];const n=e.sample;return n==null?[]:IL(n)?Object.keys(n).map(r=>[`${t}/${r}`,n[r]]):[[t,n]]}function OL(e){if(e.kind!=="snapshot_delivery")return;const t=e;if(!(t.addedCount===void 0||t.modifiedCount===void 0||t.removedCount===void 0))return{added:t.addedCount,modified:t.modifiedCount,removed:t.removedCount}}function Fg(e,t){const n=[];let r=new Map;for(const s of e){if(!Qc(s)||s.listenerId!==t)continue;const i=AL(s),o=new Map(i.map(([f,p])=>[f,p])),a=[];let l=0,u=0;for(const[f,p]of i)r.has(f)?Ha(r.get(f),p)?a.push({path:f,change:"unchanged"}):(a.push({path:f,change:"modified"}),u+=1):(a.push({path:f,change:"added"}),l+=1);let d=0;for(const f of r.keys())o.has(f)||(a.push({path:f,change:"removed"}),d+=1);const h=OL(s);n.push({at:s.at,initial:n.length===0,addedCount:h?.added??l,modifiedCount:h?.modified??u,removedCount:h?.removed??d,size:i.length,docs:a}),r=o}return n}function Vg(e){const t=e[0];if(t===void 0)return 0;let n=Math.max(t.size,1);for(const r of e.slice(1))n+=r.addedCount+r.modifiedCount;return n}function qg(e){const t=[{key:"deliveries",label:"Deliveries",total:e.deliveries},{key:"snapshot",label:"Snapshot",total:e.snapshot,unit:e.single||e.snapshot===1?"document":"documents"}];return e.service==="firestore"&&t.push({key:"reads",label:"Estimated reads",total:e.reads}),t}function $L(e){return e.map(t=>({key:t.key,label:t.label,values:[],total:t.total}))}function PL(e,t){let n=0;return r=>{const s=e[n];return n+=1,s?.unit===void 0?t(r):`${t(r)} ${s.unit}`}}function DL(e){if(e==="firestore")return"Estimated reads: initial snapshot + documents added or modified since · reconnects and duplicate listeners not counted"}function TL(e,t){return e.map((n,r)=>({id:`delivery-${r}`,at:n.at,method:"listen",path:t,auth:null,result:"allow",reasons:[],origin:"listener"}))}function Sf(e,t){return e.filter(n=>n.at>=t.start&&n.at<t.end)}function kf(e){let t=0,n=0,r=0;for(const o of e)t+=o.initial?o.size:o.addedCount,n+=o.initial?0:o.modifiedCount,r+=o.initial?0:o.removedCount;const s=e.length,i=[`${s} ${s===1?"delivery":"deliveries"}`];return t>0&&i.push(`${t} added`),n>0&&i.push(`${n} modified`),r>0&&i.push(`${r} removed`),i}function ML(e){if(e.initial)return"initial";const t=[];return e.addedCount>0&&t.push(`+${e.addedCount}`),e.modifiedCount>0&&t.push(`~${e.modifiedCount}`),e.removedCount>0&&t.push(`−${e.removedCount}`),t.join(" ")}const Wg="listeners";function zg(e,t){return e==="firestore"?pg({view:"firestore",path:zr(t)}):{tab:"rtdb",rest:t.split("/").filter(Boolean)}}function LL(e,t){return Ct(zg(e,t))}function Hg(e){return{tab:"traffic",rest:[Wg,e]}}function UL(e){return Ct(Hg(e))}function Kg(){return{tab:"traffic",query:{view:"listeners"}}}function BL(){return Ct(Kg())}function Gg(e){if(e.tab!=="traffic"||e.rest[0]!==Wg)return;const t=e.rest[1];return t===void 0||t===""?void 0:t}const Jg=new Intl.DateTimeFormat(void 0,{hour:"numeric",minute:"2-digit",second:"2-digit"});function jf(e){return Jg.formatToParts(e).filter(t=>t.type!=="dayPeriod").map(t=>t.value).join("").trim()}function FL(e){const t=e.lastIndexOf("/");return t===-1?{prefix:"",id:e}:{prefix:e.slice(0,t+1),id:e.slice(t+1)}}function VL({path:e,service:t}){const{prefix:n,id:r}=FL(e);return c.jsx("a",{className:"traffic__listener-path-link",href:LL(t,e),title:e,onClick:s=>{s.metaKey||s.ctrlKey||s.shiftKey||s.button!==0||(s.preventDefault(),Ae(zg(t,e)))},children:c.jsxs("span",{"data-pyric-path":e,children:[c.jsx("span",{"data-pyric-path-prefix":"",children:n}),c.jsx("span",{"data-pyric-path-id":"",children:r})]})})}function qL(e){return e.initial?[]:e.docs.filter(t=>t.change!=="unchanged")}function Yg({delivery:e,service:t,expanded:n=!1,onToggle:r}){const s=qL(e),i=n&&s.length>0;return c.jsxs("div",{className:"traffic__delivery-entry","data-pyric-delivery-entry":"",children:[c.jsxs("button",{type:"button",className:"traffic__delivery-row","data-pyric-delivery-row":"","data-pyric-delivery-at":e.at,"data-pyric-selected":i?"":void 0,disabled:s.length===0||r===void 0,onClick:r,children:[c.jsx("span",{"data-pyric-delivery-time":"",children:Jg.format(e.at)}),c.jsx("span",{"data-pyric-delivery-figures":"",children:ML(e)}),c.jsxs("span",{"data-pyric-delivery-snapshot":"",children:[e.size," in snapshot"]})]}),i?c.jsx("div",{className:"traffic__delivery-changes","data-pyric-delivery-changes":"",children:s.map(o=>c.jsxs("div",{className:"traffic__delivery-path","data-pyric-delivery-path":o.path,children:[c.jsx(VL,{path:o.path,service:t}),c.jsx("span",{className:"traffic__delivery-change","data-pyric-change":o.change,children:o.change})]},o.path))}):null]})}const WL=/^\[[a-zA-Z][\w-]*(?:=["']?([^"'\]]+)["']?)?\]$/,zL=/^([a-z][a-z0-9-]*?)-[0-9a-z]+$/,HL=/^[a-z][a-z0-9-]*$/;function KL(e){const n=e?.find(r=>r.kind==="component"&&typeof r.tag=="string")?.tag??Wi(e)?.name;if(!(n===void 0||!HL.test(n)))return n}function GL(e){const t=e.split(">");return t[t.length-1].trim()}function JL(e){const t=WL.exec(e);if(t!==null){const a=zL.exec(t[1]??"");return a===null?{}:{tag:a[1]}}const n=e.replace(/:[a-z-]+(\([^)]*\))?/g,""),r={},s=/^[a-zA-Z][\w-]*/.exec(n)?.[0];s!==void 0&&(r.tag=s.toLowerCase());const i=/#([\w-]+)/.exec(n)?.[1];i!==void 0&&(r.id=i);const o=/\.([\w-]+)/.exec(n)?.[1];return o!==void 0&&(r.className=o),r}function Hi(e){const t=uL(e);if(t===void 0||t==="")return;const n=JL(GL(t)),r=n.tag??KL(e)??"";return n.id!==void 0?`${r}#${n.id}`:n.className!==void 0?`${r}.${n.className}`:r===""?void 0:r}function YL(e){const t="owners"in e&&Array.isArray(e.owners)?e.owners:void 0;if(e.kind==="listener_attach"){const n=e.target;if(n.kind==="doc"&&n.path!==void 0)return t===void 0?{target:n.path}:{target:n.path,owners:t};const r={collection:n.collection??"",query:n.query};return t===void 0?{target:r}:{target:r,owners:t}}if(e.kind==="listener"&&e.phase==="attach"){const n=e.target?.path??"";return t===void 0?{target:n}:{target:n,owners:t}}return null}function QL(e,t,n){const r=Mn(t),s=[];for(const i of e){const o=YL(i);if(o===null||Mn(o.target)!==r||dL(o.owners,o.target)!==n)continue;const a=lL(o.owners),l=Hi(o.owners),u={at:i.at};a!==null&&(u.frame=`${a.file}:${a.line}`),l!==void 0&&(u.element=l),s.push(Object.freeze(u))}return Object.freeze(s)}function Qg(e){const t=Math.max(0,Math.round(e/1e3));if(t<60)return`${t}s`;const n=Math.round(t/60);return n<60?`${n}m`:`${Math.round(n/60)}h`}function Xc(e,t){return`${Qg(t-e)} ago`}function Ka(e,t){return`${e} ${t}${e===1?"":"s"}`}function Xg(e){return e===2?"twice":`${e} times`}function Zg(e){return e==="firestore"?"Firestore":"Database"}function XL(e){if(e.listeners===0)return"No listeners attached";const t=Ka(e.listeners,"listener");if(e.duplicates.length>0){const n=Math.max(...e.duplicates);return`${t}, ${e.duplicates.length} attached ${Xg(n)}`}return e.churn>0?`${t}, ${Ka(e.churn,"listener")} reattaching`:t}function ZL(e){const t=e.busiest;if(!(t===void 0||t.count<2))return`${t.label} · ${Ka(t.count,"listener")}`}function eb(e,t){const n=[];return e.owner!==void 0&&n.push(e.owner),e.element!==void 0&&n.push(e.element),n.push(Zg(e.service)),n.push(`attached ${Xc(e.attachedAt,t)}`),n.join(" · ")}function eU(e){return e.length<2?e.join(""):`${e.slice(0,-1).join(", ")} and ${e[e.length-1]}`}function tU(e,t,n){const r=t===void 0?"":` by ${t}`;if(e.pattern==="listener-churn")return`Reattached ${e.count} times in ${Qg(e.windowMs)}${r}`;const s=eU(n),i=`Attached ${Xg(e.count)}${r}`;return s===""?i:`${i} · ${s}`}function tb({incident:e,listener:t,events:n,now:r}){const s=zi(t).label,i=QL(n,t.target,s),o=e.pattern==="listener-churn"?i.slice(-1):i,a=e.pattern==="listener-churn"?[]:i.map(d=>Xc(d.at,r)),l=Hi(t.owners),u=o.filter(d=>d.frame!==void 0||(d.element??l)!==void 0);return c.jsxs("div",{className:"traffic__listener-incident","data-pyric-incident-block":"",children:[c.jsxs("p",{className:"traffic__listener-incident-line",children:[c.jsx("span",{"aria-hidden":"true",children:"⚠"})," ",tU(e,s,a)]}),u.map((d,h)=>{const f=d.element??l;return c.jsxs("p",{className:"traffic__listener-incident-attach","data-pyric-incident-attach":"",children:[d.frame===void 0?null:c.jsx("span",{children:d.frame}),d.frame!==void 0&&f!==void 0?c.jsx("span",{children:" · "}):null,f===void 0?null:c.jsx("span",{"data-pyric-element":"",children:f})]},`${d.at}|${h}`)})]})}const To=40,Nn=" ";function at(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function qe(e){return`'${e.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n")}'`}function nU(e){return e.length<=To?e:e.startsWith("'")&&e.endsWith("'")?`${e.slice(0,To-2)}…'`:`${e.slice(0,To-1)}…`}function Hr(e,t){const n=rU(e,t);return t?n:nU(n)}function rU(e,t){if(typeof e=="string")return qe(e);if(typeof e=="number"||typeof e=="boolean")return String(e);if(e===null)return"null";if(!at(e))return"…";switch(e.type){case"string":return typeof e.value=="string"?qe(e.value):"…";case"number":case"boolean":return String(e.value);case"null":return"null";case"reference":return typeof e.path=="string"?`doc(db, ${qe(e.path)})`:"…";case"timestamp":return typeof e.iso=="string"?qe(e.iso):"…";case"geoPoint":return`GeoPoint(${String(e.latitude)}, ${String(e.longitude)})`;case"bytes":return`Bytes(${String(e.length)})`;case"vector":return`Vector(${String(e.length)})`;case"array":{const r=(Array.isArray(e.values)?e.values:[]).map(s=>Hr(s,t));return e.truncated===!0&&r.push("…"),`[${r.join(", ")}]`}case"map":{const r=(Array.isArray(e.entries)?e.entries:[]).filter(s=>Array.isArray(s)&&typeof s[0]=="string").map(([s,i])=>`${s}: ${Hr(i,t)}`);return e.truncated===!0&&r.push("…"),r.length===0?"{}":`{ ${r.join(", ")} }`}default:return"…"}}function nb(e,t,n){if(!at(e))return;const r=Nn.repeat(t);if(e.kind==="where"){const o=typeof e.field=="string"?e.field:"",a=typeof e.op=="string"?e.op:"",l="display"in e?e.display:e.value;return`${r}where(${qe(o)}, ${qe(a)}, ${Hr(l,n)})`}if(e.kind!=="or"&&e.kind!=="and")return;const i=(Array.isArray(e.filters)?e.filters:[]).map(o=>nb(o,t+1,n)).filter(o=>o!==void 0);if(i.length!==0)return`${r}${e.kind}(
|
|
144
144
|
${i.join(`,
|
|
145
|
-
`)})`}function
|
|
145
|
+
`)})`}function Ef(e,t,n){if(!at(e))return;const r=Array.isArray(e.display)?e.display:Array.isArray(e.values)?e.values:[];if(r.length===0)return;const s=e.inclusive!==!1;return`${Nn}${t==="start"?s?"startAt":"startAfter":s?"endAt":"endBefore"}(${r.map(o=>Hr(o,n)).join(", ")})`}function sU(e,t){return(at(t?.scope)?t.scope:void 0)?.kind==="collection-group"?`collectionGroup(db, ${qe(e)})`:`collection(db, ${qe(e)})`}function iU(e,t){const n=[],r=Array.isArray(e.filters)?e.filters:[];for(const a of r){const l=nb(a,1,t);l!==void 0&&n.push(l)}const s=Array.isArray(e.orderBy)?e.orderBy:[];for(const a of s)!at(a)||typeof a.field!="string"||n.push(a.direction==="desc"?`${Nn}orderBy(${qe(a.field)}, 'desc')`:`${Nn}orderBy(${qe(a.field)})`);typeof e.limit=="number"&&n.push(e.limitFromEnd===!0?`${Nn}limitToLast(${String(e.limit)})`:`${Nn}limit(${String(e.limit)})`);const i=Ef(e.start,"start",t);i!==void 0&&n.push(i);const o=Ef(e.end,"end",t);return o!==void 0&&n.push(o),n}function Cf(e,t,n){const r=sU(e,t),s=t===void 0?[]:iU(t,n);return s.length===0?r:`query(${r},
|
|
146
146
|
${s.join(`,
|
|
147
|
-
`)})`}function nU(e){return at(e)?e.kind==="child"?typeof e.path=="string"?`.orderByChild(${Ve(e.path)})`:"":e.kind==="key"?".orderByKey()":e.kind==="value"?".orderByValue()":e.kind==="priority"?".orderByPriority()":"":""}const rU=new Set(["startAt","startAfter","endAt","endBefore","equalTo"]);function Cf(e,t,n){const r=[];if(at(t)){r.push(nU(t.orderBy));const s=Array.isArray(t.bounds)?t.bounds:[];for(const o of s){if(!at(o)||typeof o.kind!="string"||!rU.has(o.kind))continue;const a=[zr(o.value,n)];typeof o.key=="string"&&a.push(Ve(o.key)),r.push(`.${o.kind}(${a.join(", ")})`)}const i=t.limit;at(i)&&typeof i.n=="number"&&(i.kind==="limitToFirst"||i.kind==="limitToLast")&&r.push(`.${i.kind}(${String(i.n)})`)}return`ref(db, ${Ve(e)})${r.join("")}`}function sU(e){if(e.service==="database"){const r=typeof e.target=="string"?e.target:"";return r===""?void 0:{text:Cf(r,e.query,!1),full:Cf(r,e.query,!0)}}if(typeof e.target=="string")return;const t=e.target.collection;if(t==="")return;const n=at(e.query)?e.query:at(e.target.query)?e.target.query:void 0;return{text:Ef(t,n,!1),full:Ef(t,n,!0)}}function iU({value:e,clipboard:t}){const[n,r]=y.useState(!1),s=t??globalThis.navigator?.clipboard;return c.jsx("button",{type:"button",className:"traffic__listener-query-copy","data-pyric-query-copy":"","data-pyric-copy-value":e,"data-pyric-copy-failed":n?"":void 0,"aria-label":n?"Copy failed":"Copy the query",title:n?"Copy failed":"Copy the query",disabled:s===void 0,onClick:()=>{s!==void 0&&Promise.resolve(s.writeText(e)).then(()=>r(!1),()=>r(!0))},children:c.jsxs("svg",{className:"traffic__listener-query-icon","aria-hidden":"true",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",children:[c.jsx("rect",{x:"8",y:"8",width:"11",height:"11",rx:"1"}),c.jsx("path",{d:"M16 8V5H5v11h3"})]})})}function eb({listener:e,clipboard:t}){const n=y.useMemo(()=>sU({service:e.service,target:e.target,query:e.query}),[e.service,e.target,e.query]);return n===void 0?null:c.jsxs("div",{className:"traffic__listener-query","data-pyric-query-block":"",children:[c.jsx("pre",{className:"traffic__listener-query-text","data-pyric-query-text":"",title:n.full===n.text?void 0:n.full,children:n.text}),c.jsx(iU,{value:n.full,clipboard:t})]})}const oU=new Intl.NumberFormat,aU=new Intl.DateTimeFormat(void 0,{hour:"numeric",minute:"2-digit"});function Nn(e){return oU.format(e)}function cr(e){return aU.format(e)}const cU=[{id:"incident",label:"",name:"Incidents"},{id:"target",label:"Target",name:"Target"},{id:"deliveries",label:"Deliveries",name:"Deliveries"},{id:"attached",label:"Attached",name:"Attached"},{id:"service",label:"Service",name:"Service"}];function lU(e,t){const n={};return e!==""&&(n.service=e),t!==""&&(n.targetPrefix=t),n}function uU(e,t){return e?.column!==t?"none":e.direction==="asc"?"ascending":"descending"}function dU({metric:e,label:t,value:n,unit:r}){return c.jsxs("span",{className:"traffic__listener-figure","data-pyric-inspector-figure":e,children:[c.jsx("span",{className:"traffic__listener-figure-label",children:t}),c.jsx("span",{className:"traffic__listener-figure-value",children:r===void 0?Nn(n):`${Nn(n)} ${r}`})]})}function fU({listener:e,row:t,events:n,now:r,onClose:s}){const[i,o]=y.useState(!1),a=y.useMemo(()=>Lg(n,e.id),[n,e.id]),l=a[a.length-1],u=zi(e.owners),d={service:e.service,attachedAt:e.attachedAt};d.owner=Wi(e).label,u!==void 0&&(d.element=u);const h=t.incidents[0],f=Bg({deliveries:a.length,snapshot:l===void 0?0:l.size,reads:Ug(a),service:e.service,single:typeof e.target=="string"&&e.service==="firestore"});return c.jsxs("div",{className:"traffic__inspector","data-pyric-listener-inspector":"",children:[c.jsxs("div",{className:"traffic__inspector-bar",children:[c.jsx("a",{className:"traffic__listener-inspector-target","data-pyric-inspector-title":"",href:PL(e.id),onClick:p=>{p.metaKey||p.ctrlKey||p.shiftKey||p.button!==0||(p.preventDefault(),Ae(Vg(e.id)))},children:t.target}),c.jsx("button",{type:"button",className:"traffic__inspector-close","data-pyric-inspector-close":"",onClick:s,"aria-label":"Close the listener inspector",children:"✕"})]}),c.jsx("p",{className:"traffic__listener-facts","data-pyric-inspector-facts":"",children:Qg(d,r)}),c.jsx(eb,{listener:e}),h===void 0?null:c.jsx(Xg,{incident:h,listener:e,events:n,now:r}),c.jsx("div",{className:"traffic__listener-figures",children:f.map(p=>c.jsx(dU,{metric:p.key,label:p.label,value:p.total,unit:p.unit},p.key))}),l===void 0?null:c.jsx(Kg,{delivery:l,service:e.service,expanded:i,onToggle:()=>o(p=>!p)})]})}function hU({events:e,window:t,selectedListenerId:n,initialTargetPrefix:r,hideStudio:s=!1,now:i}){const[o,a]=y.useState(""),[l,u]=y.useState(r??""),[d,h]=y.useState(void 0),[f,p]=y.useState(n),[m,g]=y.useState([]),b=y.useRef(null),w=y.useMemo(()=>{const I=oc(e);return s?I.filter(A=>A.actor.kind!=="studio"):I},[e,s]),x=y.useMemo(()=>Pg(e),[e]),v=y.useMemo(()=>kL(e,t),[e,t]),_=y.useMemo(()=>wL(lL(w,lU(o,l)),x,d,I=>v.get(I.id)??0),[w,o,l,x,d,v]),S=y.useMemo(()=>vL(_,x),[_,x]),k=y.useMemo(()=>SL(xL(_)),[_]),N=y.useMemo(()=>jL(e,w,t),[e,w,t]),O=y.useMemo(()=>new Set(Mg.map(I=>I.key).filter(I=>!m.includes(I))),[m]),D=I=>g(A=>A.includes(I)?A.filter(P=>P!==I):[...A,I]),R=i??Date.now(),j=y.useMemo(()=>{if(n!==void 0){for(const I of _)for(const A of I.rows)if(A.listeners.some(P=>P.id===n))return A.listener.id;return n}},[n,_]);y.useEffect(()=>{j!==void 0&&(p(j),b.current?.scrollIntoView({block:"center"}))},[j]);const E=y.useMemo(()=>_.map(I=>({...I,rows:I.rows.filter(A=>_L(A).some(P=>O.has(P)))})).filter(I=>I.rows.length>0),[_,O]);function $(I){const A=I.listener,P=A.id===f;return c.jsxs("div",{className:"traffic__listener-entry","data-pyric-listener-entry":"",children:[c.jsxs("button",{type:"button",className:"traffic__listener-row",ref:P?b:void 0,"data-pyric-listener-row":"","data-pyric-listener-id":A.id,"data-pyric-selected":P?"":void 0,"data-pyric-incident":I.incidents.length>0?"":void 0,onClick:()=>p(P?void 0:A.id),children:[c.jsx("span",{"data-col":"incident","aria-hidden":"true",children:I.incidents.length>0?"⚠":""}),c.jsxs("span",{"data-col":"target",title:I.target,children:[c.jsx("span",{className:"traffic__listener-target-text",children:I.target}),I.count>1?c.jsxs("span",{className:"traffic__listener-duplicate","data-pyric-listener-duplicate":"",children:["×",I.count]}):null]}),c.jsx("span",{"data-col":"deliveries",children:Nn(I.deliveryCount)}),c.jsx("span",{"data-col":"attached",children:Qc(A.attachedAt,R)}),c.jsx("span",{"data-col":"service",children:Yg(A.service)})]}),P?c.jsx(fU,{listener:A,row:I,events:e,now:R,onClose:()=>p(void 0)}):null]},I.key)}const C=JL(S);return c.jsx("div",{className:"traffic__metrics","data-pyric-ui":"traffic-listeners-view",children:c.jsxs("section",{className:"traffic__metric-panel traffic__metric-panel--journal",children:[c.jsxs("header",{className:"traffic__metric-story",children:[c.jsx("p",{className:"traffic__metric-eyebrow",children:"Listener activity"}),c.jsx("h3",{className:"traffic__metric-headline",children:GL(S)}),C===void 0?null:c.jsx("p",{className:"traffic__metric-finding","data-pyric-listener-owner-fact":"",children:C})]}),c.jsx(Bc,{series:k,visible:O,onToggle:D,formatValue:Nn,className:"traffic__metric-cards traffic__metric-cards--journal traffic__metric-cards--3"}),c.jsxs("div",{className:"traffic__metric-evidence",children:[c.jsxs("div",{className:"traffic__metric-evidence-header",children:[c.jsx("h4",{children:"When deliveries happened"}),c.jsxs("span",{children:[cr(t.start),"–",cr(t.end)]})]}),N.total===0?c.jsx("p",{className:"traffic__empty",children:"No deliveries in this window."}):c.jsxs(c.Fragment,{children:[c.jsx(By,{points:N.points,series:N.series,omitZeroSeries:!0,formatValue:Nn,formatTime:cr,className:"traffic__chart traffic__chart--journal"}),c.jsxs("div",{className:"traffic__metric-axis","aria-hidden":"true",children:[c.jsx("span",{children:cr(t.start)}),c.jsx("span",{children:cr(t.end)})]})]})]}),c.jsxs("div",{className:"traffic__filters traffic__filters--listeners",role:"group","aria-label":"Listener filters",children:[c.jsxs("label",{className:"traffic__filter-field",children:[c.jsx("span",{className:"traffic__filters-label",children:"Service"}),c.jsxs("select",{className:"traffic__filter-select",value:o,onChange:I=>a(I.target.value),children:[c.jsx("option",{value:"",children:"All"}),c.jsx("option",{value:"firestore",children:"Firestore"}),c.jsx("option",{value:"database",children:"Database"})]})]}),c.jsxs("label",{className:"traffic__filter-field",children:[c.jsx("span",{className:"traffic__filters-label",children:"Target"}),c.jsx("input",{className:"traffic__filter-input",type:"text",value:l,onChange:I=>u(I.target.value)})]})]}),w.length===0?null:E.length===0?c.jsx("p",{className:"traffic__empty","data-pyric-listener-empty":"",children:"No listeners match these filters"}):c.jsxs("div",{className:"traffic__log traffic__listener-grid","data-pyric-listener-grid":"","data-pyric-ui":"traffic-listeners-log",children:[c.jsx("div",{className:"traffic__listener-header","data-pyric-listener-header":"",role:"row",children:cU.map(I=>c.jsxs("button",{type:"button",role:"columnheader",className:"traffic__listener-column","data-col":I.id,"aria-label":I.label===""?I.name:void 0,"aria-sort":uU(d,I.id),onClick:()=>h(A=>hL(A,I.id)),children:[I.label,d?.column===I.id?c.jsx("span",{"aria-hidden":"true",children:d.direction==="asc"?"↑":"↓"}):null]},I.id))}),E.map(I=>c.jsxs("div",{className:"traffic__listener-run",children:[c.jsxs("div",{className:"traffic__listener-group","data-pyric-listener-group":I.identity.key,children:[c.jsx("span",{"data-col":"owner",children:I.identity.label}),c.jsx("span",{"data-col":"count",children:Nn(I.listenerCount)})]}),I.rows.map(A=>$(A))]},I.identity.key))]}),c.jsxs("footer",{className:"traffic__metric-footer",children:[c.jsx("p",{className:"traffic__metric-source",children:"Source: sandbox listener events · listeners attached now, deliveries in this window"}),c.jsxs("details",{className:"traffic__metric-methodology",children:[c.jsx("summary",{children:"How this is counted"}),c.jsxs("div",{children:[c.jsxs("p",{children:["A listener is attached when the sandbox recorded its ",c.jsx("code",{children:"attach"})," and has not recorded a ",c.jsx("code",{children:"detach"})," or an error for it since. The count is that fold, not the number of attach events."]}),c.jsxs("p",{children:[c.jsx("strong",{children:"Owners come from the attach, deliveries from the window."})," The owner is the React component the listener was opened in, else the tag the app gave it, else the target itself. Two listeners on the same target under the same owner are one thing attached twice, so they collapse into one row carrying"," ",c.jsx("code",{children:"×N"}),". Delivery counts cover the displayed window only; a listener with none is idle, not gone."]})]})]})]})]})})}const tb={open:!1};function nb(e){const t=new URLSearchParams(e);if(t.get("view")!=="listeners")return tb;const n={open:!0},r=t.get("listener");r!==null&&r!==""&&(n.listenerId=r);const s=t.get("target");return s!==null&&s!==""&&(n.targetPrefix=s),n}function pU(e){const t=new URLSearchParams;for(const[n,r]of Object.entries(e))r!==void 0&&t.set(n,r);return nb(t.toString())}function mU(){return typeof window>"u"?tb:nb(window.location.search)}const yU={open:!1};function gU(){return pU(Ke().query)}function bU({window:e,hideStudio:t,deepLink:n}){const r=Jt("active-listeners"),s=y.useSyncExternalStore(Gt,Dc,()=>""),i=y.useMemo(()=>s===""?yU:gU(),[s]),o=n??i,a={events:r,window:e};return t!==void 0&&(a.hideStudio=t),o.listenerId!==void 0&&(a.selectedListenerId=o.listenerId),o.targetPrefix!==void 0&&(a.initialTargetPrefix=o.targetPrefix),c.jsx(hU,{...a})}function wU(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 vU(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:wU(n.length,r)}}function rb(e,t){return e?.start===t.start&&e.end===t.end?null:t}const xU=new Intl.NumberFormat;function _U(e){return xU.format(e)}function Nf(e){return`${kf(e.start)}–${kf(e.end)}`}function SU(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 Rf(){return c.jsx("a",{className:"traffic__listener-back",href:TL(),"data-pyric-page-back":"",onClick:e=>{e.metaKey||e.ctrlKey||e.shiftKey||e.button!==0||(e.preventDefault(),Ae(Wg()))},children:"← Listeners"})}function kU({events:e,listenerId:t,window:n,now:r}){const[s,i]=y.useState(null),[o,a]=y.useState(null),l=y.useMemo(()=>oc(e).find(_=>_.id===t),[e,t]),u=y.useMemo(()=>Lg(e,t),[e,t]),d=y.useMemo(()=>{if(l!==void 0)return Tg(Pg(e),l.target)[0]},[e,l]);if(l===void 0)return c.jsxs("div",{className:"traffic__metrics","data-pyric-ui":"traffic-listener-page",children:[c.jsx(Rf,{}),c.jsx("p",{className:"traffic__empty","data-pyric-listener-missing":"",children:"This listener is not attached in this session."})]});const h=r??Date.now(),f=zi(l.owners),p={service:l.service,attachedAt:l.attachedAt};p.owner=Wi(l).label,f!==void 0&&(p.element=f);const m=Tn(l.target),g=Bg({deliveries:u.length,snapshot:u.length===0?0:u[u.length-1].size,reads:Ug(u),service:l.service,single:typeof l.target=="string"&&l.service==="firestore"}),b=AL(l.service),w=OL(u,m),x=s===null?u:_f(u,s),v=u.map((_,S)=>({delivery:_,index:S})).filter(({delivery:_})=>s===null||_.at>=s.start&&_.at<s.end).reverse();return c.jsxs("div",{className:"traffic__metrics","data-pyric-ui":"traffic-listener-page",children:[c.jsx(Rf,{}),c.jsxs("div",{className:"traffic__metric-panel traffic__metric-panel--journal",children:[c.jsxs("section",{className:"traffic__metric-story","data-pyric-section":"header",children:[c.jsx("h3",{className:"traffic__metric-headline","data-pyric-page-title":"",children:m}),c.jsx("p",{className:"traffic__listener-facts","data-pyric-page-facts":"",children:Qg(p,h)})]}),c.jsx(eb,{listener:l}),d===void 0?null:c.jsx(Xg,{incident:d,listener:l,events:e,now:h}),c.jsxs("section",{"data-pyric-section":"cards",children:[c.jsx(Bc,{series:RL(g),formatValue:IL(g,_U),className:`traffic__metric-cards traffic__metric-cards--journal${g.length===2?" traffic__metric-cards--2":""}`}),b===void 0?null:c.jsx("p",{className:"traffic__metric-source","data-pyric-metric-footnote":"",children:b})]}),u.length===0?null:c.jsxs("section",{className:"traffic__listener-section","data-pyric-section":"deliveries",children:[c.jsx(Uy,{events:w,window:n,brush:s??void 0,onBrush:_=>{i(S=>rb(S,_)),a(null)},liveAt:n.end,bucketCount:36,className:"traffic__timeline",axis:_=>c.jsxs("div",{className:"traffic__tl-axis",children:[c.jsx("span",{children:SU(_.start,h)}),c.jsx("span",{children:"now"})]}),renderBucketSummary:_=>c.jsxs("div",{className:"traffic__bucket-summary",children:[c.jsx("span",{children:Nf(_)}),c.jsx("strong",{children:Sf(_f(u,_))[0]})]})}),s===null?null:c.jsxs("p",{className:"traffic__listener-interval","data-pyric-interval":"",children:[c.jsx("span",{className:"traffic__time-focus-eyebrow",children:"Selected interval"}),c.jsx("span",{"data-pyric-interval-facts":"",children:[Nf(s),...Sf(x)].join(" · ")})]}),v.length===0?null:c.jsx("div",{className:"traffic__log","data-pyric-delivery-log":"",children:v.map(_=>c.jsx(Kg,{delivery:_.delivery,service:l.service,expanded:o===_.index,onToggle:()=>a(o===_.index?null:_.index)},_.index))})]}),c.jsxs("footer",{className:"traffic__metric-footer",children:[c.jsx("p",{className:"traffic__metric-source",children:"Source: sandbox delivery events · every delivery this session recorded for this listener"}),c.jsxs("details",{className:"traffic__metric-methodology",children:[c.jsx("summary",{children:"How this is counted"}),c.jsxs("div",{children:[c.jsx("p",{children:"Every delivery event carries the result set the callback received: a Firestore delivery carries the documents in callback order, and a database delivery carries the value at the target path, whose keys are child paths when that value is an object. The paths under a delivery are that result set, not a re-read of the store."}),c.jsxs("p",{children:[c.jsx("strong",{children:"The labels come from the previous delivery."})," A path is"," ",c.jsx("code",{children:"added"})," when the previous delivery did not carry it,"," ",c.jsx("code",{children:"modified"})," when it did and the data differs, and ",c.jsx("code",{children:"removed"})," ","when the previous delivery carried it and this one does not. A path whose data is identical is not listed. The first delivery is ",c.jsx("code",{children:"initial"}),": every path in it arrived, so it lists none."]}),c.jsx("p",{children:"Firestore charges a listener for the documents in its first snapshot, then for each document a later delivery adds or changes; a delivery that only drops documents costs nothing, and an empty first snapshot still costs one read. The estimate covers this session's deliveries, so a reconnect that re-read the result set and a second listener on the same query are not in it."})]})]})]})]})]})}function jU({listenerId:e,window:t}){const n=Jt();return c.jsx(kU,{events:n,listenerId:e,window:t})}const EU=[{id:"timeline",label:"Timeline"},{id:"billable",label:"Billable metrics"},{id:"rules",label:"Rules"},{id:"listeners",label:"Listeners"}];function CU(e){return e==="billable"?"billable":e==="rules"||e==="subscriptions"?"rules":e==="listeners"?"listeners":"timeline"}function NU(e){return e.tab!=="traffic"?"timeline":zg(e)!==void 0?"listeners":CU(e.query.view)}function RU(){return NU(Ke())}function IU(){const{tab:e,rest:t}=Ke();return zg({tab:e,rest:t})}function AU(){return y.useSyncExternalStore(Gt,IU,()=>{})}function OU(){const e=y.useSyncExternalStore(Gt,RU,()=>"timeline"),t=y.useCallback(n=>{const r={...Ke().query,view:n==="timeline"?void 0:n};r.view===void 0&&delete r.view,Ae({tab:"traffic",query:r})},[]);return[e,t]}function $U(){const e=y.useSyncExternalStore(Gt,()=>Ke().query.hide==="studio",()=>!1),t=y.useCallback(()=>{const n={...Ke().query};n.hide==="studio"?delete n.hide:n.hide="studio",Ae({tab:"traffic",query:n})},[]);return[e,t]}function DU(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 If(e){return`${Vr(e.start)}–${Vr(e.end)}`}function PU({event:e}){const t=Kn(e);return t?c.jsx("span",{className:"traffic__verdict","data-verdict":t,children:Eg(t)}):null}function TU(){return y.useSyncExternalStore(Gt,()=>Cg(Ke().query),()=>null)}const To=100;function MU(){const e=QO(),[t,n]=OU(),r=AU(),[s,i]=$U(),o=y.useMemo(()=>EM(e,s),[e,s]),a=e.length-o.length,[l,u]=y.useState("all"),[d,h]=y.useState(null),f=TU(),[p,m]=y.useState(To),g=C=>{Ae({tab:"traffic",query:AM(Ke().query,C)})},b=()=>{Ae({tab:"traffic",query:Ng(Ke().query,null)})};y.useEffect(()=>{if(!f)return;const C=I=>{I.key==="Escape"&&b()};return globalThis.addEventListener("keydown",C),()=>globalThis.removeEventListener("keydown",C)},[f]);const w=y.useMemo(()=>{const C=Date.now();if(o.length===0)return{start:C-15*6e4,end:C};let I=1/0;for(const A of o)A.at<I&&(I=A.at);return{start:Math.min(I,C-6e4),end:C+1e3}},[o]),x=w.end,v=y.useMemo(()=>d?vU(o,d):null,[o,d]),_=v?.events??o,S=y.useMemo(()=>NM(_,l).sort((C,I)=>I.at-C.at),[_,l]),{items:k}=iD({events:S}),N=k.slice(0,p),O=k.length-N.length,D=o.length>=Sr,R=o.filter(C=>C.result==="deny").length,j=C=>c.jsx(PU,{event:C}),E=C=>{if($o(C)){g(C.id);return}const I=yf(C);I&&Ae(I)},$=f!=null&&N.some(C=>C.type!=="group"&&C.event.id===f);return c.jsxs("section",{"data-pyric-ui":"traffic-surface",className:"traffic",children:[c.jsxs("div",{className:"traffic__tabs",role:"tablist","aria-label":"Traffic views",children:[EU.map(C=>c.jsx("button",{type:"button",role:"tab",className:"traffic__tab","aria-selected":t===C.id,onClick:()=>n(C.id),children:C.label},C.id)),c.jsxs("button",{type:"button",className:"traffic__hide-studio","aria-pressed":s,onClick:i,title:"Hide ops issued by Pyric Studio's own viewers and editors",children:["Hide Studio traffic",s&&a>0?` (${a} hidden)`:""]})]}),r!==void 0?c.jsx(jU,{listenerId:r,window:w}):t==="billable"?c.jsx(rL,{events:o,window:w}):t==="rules"?c.jsx(sL,{events:o,window:w}):t==="listeners"?c.jsx(bU,{window:w,hideStudio:s}):c.jsxs(c.Fragment,{children:[c.jsx(Uy,{events:o,window:w,brush:d??void 0,onBrush:C=>{h(I=>rb(I,C)),f&&b()},liveAt:w.end,bucketCount:36,className:"traffic__timeline",header:c.jsxs("div",{className:"traffic__tl-header",children:[c.jsxs("span",{className:"traffic__tl-count",children:[o.length," requests",D?` (showing latest ${Sr})`:""]}),R>0?c.jsxs("button",{type:"button",className:"traffic__tl-deny","aria-pressed":l==="deny",onClick:()=>u(C=>C==="deny"?"all":"deny"),title:"Filter the stream to denied requests",children:[R," denied"]}):null,c.jsx("span",{className:"traffic__tl-live",children:"live"})]}),axis:C=>c.jsxs("div",{className:"traffic__tl-axis",children:[c.jsx("span",{children:DU(C.start,x)}),c.jsx("span",{children:"now"})]}),renderBucketSummary:C=>c.jsxs("div",{className:"traffic__bucket-summary",children:[c.jsx("span",{children:If(C)}),c.jsxs("strong",{children:[C.count," ",C.count===1?"request":"requests"]}),c.jsxs("span",{children:[C.denies," denied"]})]}),emptyState:c.jsx("p",{className:"traffic__empty",children:"No requests in this window yet."})}),v?c.jsxs("section",{className:"traffic__time-focus","aria-label":"Selected traffic interval","aria-live":"polite",children:[c.jsxs("div",{className:"traffic__time-focus-story",children:[c.jsx("p",{className:"traffic__time-focus-eyebrow",children:"Selected interval"}),c.jsx("h3",{children:If(v.window)}),c.jsx("p",{children:v.finding})]}),c.jsx("button",{type:"button",onClick:()=>h(null),children:"Show all traffic"})]}):null,c.jsxs("div",{className:"traffic__filters",role:"group","aria-label":"Traffic filters",children:[c.jsx("span",{className:"traffic__filters-label","aria-hidden":"true",children:"verdict"}),CM.map(C=>c.jsx("button",{type:"button",className:"traffic__filter","aria-pressed":l===C,onClick:()=>u(C),children:Eg(C)},C))]}),f&&!$?c.jsx(gf,{eventId:f,onClose:b},f):null,k.length===0?c.jsx("p",{className:"traffic__empty",children:v?l==="all"?"No requests occurred in the selected interval.":`No ${l} traffic occurred in the selected interval.`:l==="all"?"No requests yet. Reads, writes, and listeners against the sandbox stream in live.":`No ${l} traffic in this session.`}):c.jsxs("div",{className:"traffic__log","data-pyric-ui":"traffic-log","data-pyric-grouped":"","data-pyric-time-focused":v?"":void 0,children:[c.jsx("ul",{"data-pyric-traffic-log-items":"",children:N.map(C=>C.type==="group"?c.jsx("li",{"data-pyric-traffic-group-entry":"",children:c.jsx(_D,{group:C,onSelect:I=>{const A=I;if($o(A)){g(A.id);return}const P=yf(A);P&&Ae(P)},renderClassification:I=>j(I),formatTime:Vr})},C.key):c.jsxs("li",{"data-pyric-traffic-entry":"","data-pyric-traffic-id":C.event.id,"data-verdict":Kn(C.event)??void 0,children:[c.jsx(Ly,{event:C.event,selected:C.event.id===f,onSelect:I=>E(I),renderClassification:I=>j(I),formatTime:Vr}),C.event.id===f&&$o(C.event)?c.jsx(gf,{eventId:f,onClose:b},f):null]},C.event.id))}),O>0?c.jsxs("button",{type:"button",className:"traffic__show-more",onClick:()=>m(C=>C+To),children:["Show ",Math.min(O,To)," more (",O," hidden)"]}):null]})]})]})}const Af=["amber","teal","coral","slate","olive","plum","rust","indigo","mint","sand","ash","jade"],Of=["fox","owl","lynx","crane","otter","wren","ibex","hare","newt","moth","seal","vole"];function Xc(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`${Af[t%Af.length]}-${Of[(t>>>4)%Of.length]}`}function Zc(){const e=lt(),t=e.status==="ready"?e.env.live:void 0,[n,r]=y.useState("");return y.useEffect(()=>{if(!t){r("");return}let s=!1;return t.instanceId().then(i=>{s||r(i)}),()=>{s=!0}},[t]),n}function LU(){const e=lt(),t=e.status==="ready"?e.env.live:void 0;return y.useCallback(async()=>t?t.exportState():null,[t])}function UU(){const e=lt(),t=e.status==="ready"?e.env.live:void 0;return y.useCallback(async n=>t?(await t.importState(n),!0):!1,[t])}function BU(){const e=lt(),t=e.status==="ready"?e.env.live:void 0,[n,r]=y.useState([]),s=y.useCallback(async()=>{if(!t){r([]);return}const l=await t.listStates();r(l.map(u=>u.name))},[t]);y.useEffect(()=>{s()},[s]);const i=y.useCallback(async l=>{t&&(await t.saveState(l),await s())},[t,s]),o=y.useCallback(async l=>{t&&await t.restoreState(l)},[t]),a=y.useCallback(async l=>{t&&(await t.deleteState(l),await s())},[t,s]);return{names:n,save:i,restore:o,remove:a}}function FU(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 qU(e){return e?{tab:"firestore",rest:e.split("/").filter(Boolean)}:null}function VU(e){const{provenance:t,identity:n}=FU(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:qU(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 WU(e,t=20){const n=[];for(let r=e.length-1;r>=0&&n.length<t;r--){const s=VU(e[r]);s&&n.push(s)}return n}const zU=20;function HU(e){Ae(e)}function Mn({target:e,className:t,children:n,title:r}){return c.jsx("a",{className:t,href:Ct(e),title:r,onClick:s=>{s.metaKey||s.ctrlKey||s.shiftKey||s.altKey||(s.preventDefault(),HU(e))},children:n})}function KU(){const e=Kt(),t=cs(),n=Zc();if(t.status==="loading"||e.status==="pending")return c.jsxs("div",{className:"studio-home__status","aria-label":"Sandbox status",children:[c.jsx("span",{className:"studio-chip studio-home__skeleton-chip","aria-hidden":"true"}),c.jsx("span",{className:"studio-chip studio-home__skeleton-chip","aria-hidden":"true"})]});const s=[];if(e.status==="ready"&&t.status!=="ready"&&s.push(c.jsxs("span",{className:"studio-chip",title:"In-page seeded sandbox — no server. Data resets on reload.",children:[c.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),"dev seed · in-page"]},"seed")),t.status==="ready"){const i=t.payload;s.push(c.jsxs(Mn,{className:"studio-chip",target:{tab:"settings"},title:"Persistence mode — manage in Settings.",children:[c.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),i.persist?"persisted to disk":"ephemeral"]},"persist")),i.rulesHash&&s.push(c.jsxs("span",{className:"studio-chip",title:"Hash of the rules this serve deployed to the sandbox.",children:[c.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),"rules ",i.rulesHash.slice(0,8)]},"rules"))}return n&&s.push(c.jsxs(Mn,{className:"studio-chip",target:{tab:"settings"},title:`Sandbox instance ${n} — maintenance lives in Settings.`,children:[c.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),Xc(n)]},"instance")),c.jsx("div",{className:"studio-home__status","aria-label":"Sandbox status",children:s})}function GU(e){return new Date(e).toLocaleTimeString(void 0,{hour12:!1})}function JU(){const e=Jt(),t=y.useMemo(()=>WU(e,zU),[e]);return c.jsxs("section",{className:"studio-panel studio-home__feed","aria-label":"Live activity",children:[c.jsxs("header",{className:"studio-home__feed-head",children:[c.jsx("h2",{className:"studio-panel__title studio-home__feed-title",children:"Activity"}),c.jsx(Mn,{className:"studio-home__feed-all",target:{tab:"traffic"},children:"view all in Traffic →"})]}),t.length===0?c.jsx("p",{className:"studio-home__feed-empty",children:"No activity yet — writes, denials, and seeds show up here live."}):c.jsx("div",{className:"studio-home__feed-scroll",children:c.jsx("ol",{className:"studio-home__feed-list",children:t.map(n=>{const r=c.jsxs(c.Fragment,{children:[c.jsxs("span",{className:"studio-home__feed-ident","data-provenance":n.provenance,children:[c.jsx("span",{className:"studio-home__feed-dot","aria-hidden":"true"}),n.identity]}),c.jsx("span",{className:"studio-home__feed-summary","data-denied":n.denied?"true":void 0,children:n.summary}),c.jsx("time",{className:"studio-home__feed-time",dateTime:new Date(n.at).toISOString(),children:GU(n.at)})]});return c.jsx("li",{children:n.target?c.jsx(Mn,{className:"studio-home__feed-row",target:n.target,children:r}):c.jsx("span",{className:"studio-home__feed-row",children:r})},n.id)})})})]})}const YU=["firestore","auth","rtdb","storage","traffic"];function QU(){const e=Rt(),t=Jt(),n=y.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 c.jsx("div",{className:"studio-home__tiles",children:YU.map(r=>{const s=dn.find(i=>i.id===r);return s?c.jsxs(Mn,{className:"studio-card studio-home__tile",target:{tab:r},children:[c.jsxs("span",{className:"studio-home__tile-top",children:[c.jsx("span",{className:"studio-home__tile-label",children:s.label}),n[r]?c.jsx("span",{className:"studio-badge",children:n[r]}):null]}),c.jsx("span",{className:"studio-home__tile-desc",children:s.description})]},r):null})})}function XU(){const e=cs(),t=e.status==="ready",n=t&&!!e.payload.bridgeUrl,r=typeof window<"u"?window.location.origin:"",s=t?e.payload.rulesHash:null;return c.jsxs(c.Fragment,{children:[c.jsxs("section",{className:"studio-card studio-home__onboard","aria-label":"Connect your agent",children:[c.jsx("span",{className:"studio-home__tile-label",children:"Connect your agent"}),c.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."}),c.jsx("code",{className:"studio-home__snippet",children:n?`${r}/__pyric/mcp`:"pyric sandbox --bridge # then <url>/__pyric/mcp"})]}),c.jsxs("section",{className:"studio-card studio-home__onboard","aria-label":"Seed data",children:[c.jsx("span",{className:"studio-home__tile-label",children:"Seed data"}),c.jsx("span",{className:"studio-home__tile-desc",children:"Start from a fixture, or create documents by hand in the Firestore browser."}),c.jsx("code",{className:"studio-home__snippet",children:"pyric sandbox --seed seed.json"}),c.jsx(Mn,{className:"studio-home__onboard-link",target:{tab:"firestore"},children:"open Firestore →"})]}),c.jsxs("section",{className:"studio-card studio-home__onboard","aria-label":"Bring your rules",children:[c.jsx("span",{className:"studio-home__tile-label",children:"Bring your rules"}),s?c.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."]}):c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"studio-home__tile-desc",children:"Serve your repo's rules file and every denial becomes a debuggable event."}),c.jsxs("code",{className:"studio-home__snippet",children:["pyric.json: ",'{"rules":"firestore.rules"}']})]})]})]})}function ZU(){const e=Rt(),t=Jt(),n=Kt(),r=e.status==="pending"||n.status==="pending",s=!r&&t.length===0&&(e.status!=="ready"||e.handles.listRootCollections().length===0);return c.jsxs("section",{className:"studio-surface studio-home","aria-label":"Home",children:[c.jsxs("div",{className:"studio-home__hero",children:[c.jsx("img",{className:"studio-home__hero-logo",src:"/__pyric/ui/pyric-logo.svg",alt:"","aria-hidden":"true"}),c.jsx("h1",{className:"studio-home__hero-title",children:"Firebase tooling for the agent era"})]}),c.jsx(ky,{exposeFocus:K0}),c.jsx(KU,{}),c.jsx("div",{className:"studio-home__body",children:r?c.jsxs("section",{className:"studio-panel studio-home__feed studio-home__skeleton","aria-hidden":"true",children:[c.jsx("div",{className:"studio-home__skeleton-row"}),c.jsx("div",{className:"studio-home__skeleton-row"}),c.jsx("div",{className:"studio-home__skeleton-row"})]}):s?c.jsx(XU,{}):c.jsxs(c.Fragment,{children:[c.jsx(JU,{}),c.jsx(QU,{})]})})]})}function _e(e){const t=e.split("/").filter(Boolean);return t.length===0?"/":`/${t.join("/")}`}function bt(e){return _e(e).split("/").filter(Boolean)}function Ka(e,t){return _e([...bt(e),...t.split("/").filter(Boolean)].join("/"))}function eB(e){const t=bt(e);return t.length<=1?"/":`/${t.slice(0,-1).join("/")}`}function el(e,t){const n=bt(e),r=bt(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 sb(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 o=sb(i);if(o===null){n=!0;continue}o!==i&&(n=!0),r[s]=o}return Object.keys(r).length===0?null:n?r:e}function tB(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 tl(e){return e===null||typeof e!="object"?!1:Object.keys(e).length>0}function ib(e){return e===null||typeof e!="object"?[]:Object.entries(e).sort(([t],[n])=>t.localeCompare(n,void 0,{numeric:!0}))}function ob(e,t){let n=e??null;for(const r of bt(t)){if(n===null||typeof n!="object")return null;n=n[r]??null}return n}function nB(e){return e==null?"null":Array.isArray(e)?"array":typeof e}function Ga(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((o,a)=>Ga(o,t[a]));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(o=>o in r&&Ga(n[o],r[o]))}function rB(e,t){const n=new Map,r=(s,i)=>{if(!tl(s)){n.set(i,["leaf",s??null]);return}const o=ib(s);n.set(i,["parent",o.map(([a])=>a)]);for(const[a,l]of o)r(l,Ka(i,a))};return r(e,_e(t)),n}function sB(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(/[?#].*$/,""),_e(t)}function iB(e){const t=bt(e);return t.map((n,r)=>({label:n,path:`/${t.slice(0,r+1).join("/")}`}))}const oB=["string","number","boolean","json"];function $f(e){switch(typeof e){case"string":return"string";case"number":return"number";case"boolean":return"boolean";default:return"json"}}function aB(e,t){return t==="json"?JSON.stringify(e??null):e==null?"":String(e)}function cB(e){if(e.trim().length===0)return"Enter a key.";const t=e.match(/[.$#[\]/]/);return t?`Keys can't contain "${t[0]}".`:null}function lB(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 ab(e){return{path:_e(e),status:"loading",value:null,error:null,expanded:{},pages:{}}}function cb(e,t){const n=el(e.path,t);return n===null?null:ob(e.value,n)}function uB(e,t){const n=_e(t);return n===e.path||e.expanded[n]===!0}function dB(e,t,n){const r=ib(cb(e,t)),s=Math.min(r.length,e.pages[_e(t)]??n);return{entries:r.slice(0,s),total:r.length,hiddenCount:r.length-s}}function Df(e,t){const n={};let r=!1;for(const[s,i]of Object.entries(e)){const o=el(t.path,s);o!==null&&tl(ob(t.value,o))?n[s]=i:r=!0}return r?n:e}function lb(e,t){switch(t.type){case"navigate":{const n=_e(t.path);return n===e.path?e:ab(n)}case"value":{if(_e(t.path)!==e.path)return e;const n={...e,status:"live",value:sb(t.value),error:null};return n.expanded=Df(e.expanded,n),n.pages=Df(e.pages,n),n}case"error":return _e(t.path)!==e.path?e:{...e,status:"error",error:t.message};case"expand":{const n=_e(t.path);return n===e.path||e.expanded[n]?e:{...e,expanded:{...e.expanded,[n]:!0}}}case"collapse":{const n=_e(t.path);if(!e.expanded[n])return e;const r={...e.expanded};return delete r[n],{...e,expanded:r}}case"toggle":{const n=_e(t.path);return lb(e,{type:e.expanded[n]?"collapse":"expand",path:n})}case"show-more":{const n=_e(t.path),r=e.pages[n]??t.pageSize;return{...e,pages:{...e.pages,[n]:r+t.pageSize}}}}}const fB=50;function hB(e,t,n={}){const r=n.pageSize??fB,s=_e(t),[i,o]=y.useReducer(lb,s,ab),a=y.useMemo(()=>rB(i.value,i.path),[i.path,i.value]),l=Kc({scope:i.path,entries:a,equals:Ga,ready:i.status==="live"});i.path!==s&&o({type:"navigate",path:s}),y.useEffect(()=>{let g=!1;const b=e.subscribeValue(s,w=>{g||o({type:"value",path:s,value:w})},w=>{g||o({type:"error",path:s,message:w instanceof Error?w.message:String(w)})});return()=>{g=!0,b()}},[e,s]);const u=y.useCallback(g=>cb(i,g),[i]),d=y.useCallback(g=>uB(i,g),[i]),h=y.useCallback(g=>dB(i,g,r),[i,r]),f=y.useCallback(g=>o({type:"toggle",path:g}),[]),p=y.useCallback(g=>o({type:"show-more",path:g,pageSize:r}),[r]),m=y.useCallback(g=>l.get(_e(g)),[l]);return y.useMemo(()=>({state:i,pageSize:r,valueAt:u,isExpanded:d,childrenAt:h,toggle:f,showMore:p,updateAt:m}),[i,r,u,d,h,f,p,m])}function pB({path:e,onNavigate:t,rootLabel:n="/",inputPrefix:r,className:s}){const i=_e(e),[o,a]=y.useState(!1),l=y.useRef(null);y.useEffect(()=>{o&&l.current?.select()},[o]);const u=f=>{f.preventDefault(),t(sB(l.current?.value??"")),a(!1)},d=()=>a(!1),h=iB(i);return c.jsx("nav",{className:s,"data-pyric-ui":"rtdb-path-bar","data-rtdb-editing":o?"":void 0,"aria-label":"Database path",children:o?c.jsxs("form",{"data-rtdb-path-form":!0,onSubmit:u,children:[r?c.jsx("span",{"data-rtdb-path-prefix":!0,children:r}):null,c.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})]}):c.jsxs(c.Fragment,{children:[c.jsxs("ol",{"data-rtdb-crumb-list":!0,children:[c.jsx("li",{"data-rtdb-crumb-item":!0,children:c.jsx("button",{type:"button","data-rtdb-crumb":!0,"data-rtdb-crumb-root":!0,"data-pyric-current":h.length===0?"":void 0,"aria-current":h.length===0?"page":void 0,onClick:()=>t("/"),children:n})}),h.map((f,p)=>{const m=p===h.length-1;return c.jsxs("li",{"data-rtdb-crumb-item":!0,children:[c.jsx("span",{"aria-hidden":!0,"data-rtdb-crumb-separator":!0,children:"/"}),c.jsx("button",{type:"button","data-rtdb-crumb":!0,"data-pyric-current":m?"":void 0,"aria-current":m?"page":void 0,onClick:()=>t(f.path),children:f.label})]},f.path)})]}),c.jsx("button",{type:"button","data-rtdb-path-edit":!0,"aria-label":"Edit path",title:"Edit path",onClick:()=>a(!0),children:c.jsx("svg",{"aria-hidden":!0,viewBox:"0 0 16 16",width:"12",height:"12",fill:"currentColor",children:c.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 mB({tree:e,api:t,onNavigate:n,rootLabel:r="/",className:s}){const{state:i}=e,o=bt(i.path),a=o.length===0?r:o[o.length-1];return c.jsx("div",{className:s,"data-pyric-ui":"rtdb-tree",children:i.status==="loading"?c.jsx("p",{"data-rtdb-loading":!0,children:"Loading…"}):i.status==="error"?c.jsx("p",{role:"alert","data-rtdb-error":!0,children:i.error}):c.jsx(ub,{tree:e,api:t,onNavigate:n,path:i.path,label:a,isViewRoot:!0})})}function ub({tree:e,api:t,onNavigate:n,path:r,label:s,isViewRoot:i}){const o=e.valueAt(r),a=tl(o),l=e.isExpanded(r),u=e.updateAt(r),[d,h]=y.useState(!1),[f,p]=y.useState(!1),[m,g]=y.useState(!1),[b,w]=y.useState(null),x=async(S,k)=>{try{await S(),w(null),k()}catch(N){w(N instanceof Error?N.message:String(N))}},v=()=>{h(!0),g(!1),a&&!l&&e.toggle(r)},_=a&&l?e.childrenAt(r):null;return c.jsxs("div",{"data-rtdb-node":!0,"data-rtdb-kind":a?"parent":"leaf","data-rtdb-view-root":i?"":void 0,"data-rtdb-expanded":a&&l?"":void 0,children:[c.jsxs("div",{"data-rtdb-row":!0,"data-pyric-update":u?.kind,"data-pyric-update-cycle":u?.cycle,children:[a&&!i?c.jsx("button",{type:"button","data-rtdb-caret":!0,"aria-expanded":l,"aria-label":l?"Collapse":"Expand",onClick:()=>e.toggle(r),children:c.jsx("svg",{"aria-hidden":!0,viewBox:"0 0 8 8",width:"8",height:"8",fill:"currentColor",children:c.jsx("path",{d:"M1 0l6 4-6 4z"})})}):c.jsx("span",{"aria-hidden":!0,"data-rtdb-caret-spacer":!0}),c.jsx("button",{type:"button","data-rtdb-key":!0,"aria-label":"Key name",onClick:()=>n?.(r),children:s}),a?null:c.jsxs(c.Fragment,{children:[c.jsx("span",{"aria-hidden":!0,"data-rtdb-sep":!0,children:":"}),c.jsx("button",{type:"button","data-rtdb-value":!0,"data-rtdb-type":nB(o),title:"Edit value",onClick:()=>{p(!0),g(!1)},children:tB(o)})]}),c.jsx("span",{"data-rtdb-actions":!0,children:m?c.jsxs("span",{"data-rtdb-confirm":!0,children:[c.jsxs("span",{"data-rtdb-confirm-label":!0,children:["Delete",a?" subtree":"","?"]}),c.jsx("button",{type:"button","data-rtdb-confirm-yes":!0,onClick:()=>void x(()=>t.remove(r),()=>g(!1)),children:"Delete"}),c.jsx("button",{type:"button","data-rtdb-confirm-no":!0,onClick:()=>g(!1),children:"Cancel"})]}):c.jsxs(c.Fragment,{children:[c.jsx("button",{type:"button","data-rtdb-action-add":!0,"aria-label":`Add child to ${Pf(r)}`,title:"Add child",onClick:v,children:"+"}),c.jsx("button",{type:"button","data-rtdb-action-delete":!0,"aria-label":`Delete ${Pf(r)}`,title:"Delete",onClick:()=>g(!0),children:"×"})]})})]}),b?c.jsx("p",{role:"alert","data-rtdb-error":!0,children:b}):null,f?c.jsx(Tf,{initialType:$f(o),initialText:aB(o,$f(o)),submitLabel:"Save",onCancel:()=>p(!1),onSubmit:S=>x(()=>t.set(r,S),()=>p(!1))}):null,d?c.jsx(Tf,{withKey:!0,initialType:"string",initialText:"",submitLabel:"Add",onCancel:()=>h(!1),onSubmit:(S,k)=>x(()=>t.set(Ka(r,k),S),()=>h(!1))}):null,_?c.jsxs("ul",{"data-rtdb-children":!0,children:[_.entries.map(([S])=>c.jsx("li",{children:c.jsx(ub,{tree:e,api:t,onNavigate:n,path:Ka(r,S),label:S})},S)),_.hiddenCount>0?c.jsx("li",{"data-rtdb-show-more-item":!0,children:c.jsxs("button",{type:"button","data-rtdb-show-more":!0,onClick:()=>e.showMore(r),children:["Show more (",_.hiddenCount," hidden)"]})}):null]}):null]})}function Pf(e){const t=bt(e);return t.length===0?"root":t[t.length-1]}function Tf({withKey:e,initialType:t,initialText:n,submitLabel:r,onSubmit:s,onCancel:i}){const o=y.useRef(null),a=y.useRef(null),[l,u]=y.useState(t),[d,h]=y.useState(null),f=m=>{m.preventDefault();const g=o.current?.value??"";if(e){const w=cB(g);if(w){h(w);return}}const b=lB(l,a.current?.value??"");if(!b.ok){h(b.error);return}h(null),s(b.value,e?g.trim():void 0)},p=m=>{m.key==="Escape"&&i()};return c.jsxs("form",{"data-rtdb-editor":!0,onSubmit:f,children:[e?c.jsx("input",{ref:o,"data-rtdb-editor-key":!0,"aria-label":"Child key",placeholder:"key",autoFocus:!0,onKeyDown:p,spellCheck:!1}):null,c.jsx("select",{"data-rtdb-editor-type":!0,"aria-label":"Value type",value:l,onChange:m=>u(m.currentTarget.value),onKeyDown:p,children:oB.map(m=>c.jsx("option",{value:m,children:m},m))}),l==="boolean"?c.jsxs("select",{ref:a,"data-rtdb-editor-value":!0,"aria-label":"Value",defaultValue:n.trim().toLowerCase()==="true"?"true":"false",onKeyDown:p,children:[c.jsx("option",{value:"true",children:"true"}),c.jsx("option",{value:"false",children:"false"})]}):c.jsx("input",{ref:a,"data-rtdb-editor-value":!0,"aria-label":"Value",placeholder:l==="json"?'{ "key": "value" }':"value",autoFocus:!e,defaultValue:n,onKeyDown:p,spellCheck:!1}),c.jsx("button",{type:"submit","data-rtdb-editor-save":!0,children:r}),c.jsx("button",{type:"button","data-rtdb-editor-cancel":!0,onClick:i,children:"Cancel"}),d?c.jsx("span",{role:"alert","data-rtdb-editor-error":!0,children:d}):null]})}const db="rtdb";function yB(e){return e.tab!==db?"/":_e(e.rest.join("/"))}function gB(e){return{tab:db,rest:bt(e)}}function bB(){const e=y.useSyncExternalStore(Gt,()=>yB(Ke()),()=>"/"),t=y.useCallback(n=>{Ae(gB(n))},[]);return[e,t]}function wB(){const e=lt(),t=e.status==="ready"?e.env.live:void 0;return c.jsxs("section",{className:"studio-surface grid gap-4","aria-labelledby":"rtdb-title",children:[c.jsxs("div",{className:"studio-surface__intro",children:[c.jsx("p",{className:"studio-surface__eyebrow",children:"RTDB"}),c.jsx("h1",{id:"rtdb-title",className:"studio-surface__title",children:"RTDB"}),c.jsx("p",{className:"studio-surface__copy",children:"Browse and edit RTDB data in the shared sandbox."})]}),t?c.jsx(xB,{live:t}):c.jsx(vB,{})]})}function vB(){return c.jsxs("div",{className:"rounded-md border border-dashed border-line bg-panel p-8 text-center",children:[c.jsx("span",{className:"rounded-full border border-line px-3 py-1 text-xs uppercase tracking-wide text-muted",children:"Shared worker pending"}),c.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 xB({live:e}){const t=Xc(Zc()),n=y.useMemo(()=>({set:(r,s)=>e.setRtdbValue(r,s),remove:r=>e.deleteRtdbValue(r),subscribeValue:(r,s,i)=>e.subscribeRtdbValue(r,s,i)}),[e]);return c.jsx(_B,{api:n,instanceLabel:t?`${t}-sandbox`:"sandbox"})}function _B({api:e,instanceLabel:t}){const[n,r]=bB(),{viewRoot:s,missingTail:i,tree:o}=SB(e,n),a=y.useRef(null);return y.useEffect(()=>{if(s==="/")return;const l=a.current;l&&typeof l.scrollIntoView=="function"&&l.scrollIntoView({block:"nearest"})},[s]),c.jsxs("div",{className:"rtdb",ref:a,children:[c.jsx(pB,{className:"rtdb__pathbar",path:n,onNavigate:r,rootLabel:t,inputPrefix:t}),i?c.jsxs("p",{className:"rtdb__missing","data-rtdb-missing":"",children:["This path does not exist. Showing ",c.jsx("code",{children:s}),", the nearest path that does; ",c.jsx("code",{children:i})," is not in the database."]}):null,c.jsx(mB,{className:"rtdb__tree",tree:o,api:e,onNavigate:r,rootLabel:t})]})}function SB(e,t){const[n,r]=y.useState({requested:t,root:t}),s=n.requested===t?n:{requested:t,root:t};s!==n&&r(s);const i=s.root,o=hB(e,i),{path:a,status:l,value:u}=o.state;y.useEffect(()=>{a===i&&l==="live"&&u==null&&i!=="/"&&r({requested:t,root:eB(i)})},[a,l,u,i,t]);const d=i===t?null:el(i,t);return{viewRoot:i,missingTail:d&&bt(d).length>0?d:null,tree:o}}function kB(){const e=Rt();return y.useCallback(async t=>{if(e.status!=="ready")throw new Error("No sandbox available to seed.");const n=e.handles.adminFirestore,r=e.firestoreApi?.doc??st,s=e.firestoreApi?.setDoc??zs;let i=0;const o=[];for(const a of t)try{await s(r(n,a.path),a.data),i++}catch(l){o.push(`${a.path}: ${l instanceof Error?l.message:String(l)}`)}return{written:i,errors:o}},[e])}function jB(){const e=Rt();return y.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??xe.createUser;let s=0;const i=[];for(const o of t)try{await r(n,o.request),s++}catch(a){const l=o.request.uid??o.request.email??"<auto>";i.push(`${l}: ${a instanceof Error?a.message:String(a)}`)}return{created:s,errors:i}},[e])}function EB(){const e=Rt(),t=lt(),n=t.status==="ready"?t.env.live:void 0;return y.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 CB(){const e=EB(),t=kB(),n=jB(),r=Kt();return y.useCallback(async()=>{const s=await e();if(r.status==="ready"){const{applySeed:i,deploySeedRules:o}=await Fp(async()=>{const{applySeed:a,deploySeedRules:l}=await import("./seed.BpXSRzLo.js");return{applySeed:a,deploySeedRules:l}},__vite__mapDeps([3,1,4,2,5]));o(r.handles.sandbox),await i(r.handles)}else try{const i=await fetch("/__pyric/init.json").then(l=>l.ok?l.json():null),o=i?.seed;o&&await t(Object.entries(o).map(([l,u])=>({path:l,data:u})));const a=i?.authUsers;Array.isArray(a)&&await n(a.map(l=>({request:l})))}catch(i){s.errors.push(`reseed: ${i instanceof Error?i.message:String(i)}`)}return s},[e,t,n,r])}function NB(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 Is(e,t,n=`${t}s`){return`${e} ${e===1?t:n}`}function RB(e){if(e===null)return"measuring…";const t=[];return e.collections&&t.push(Is(e.collections,"collection")),e.users&&t.push(Is(e.users,"user")),e.objects&&t.push(Is(e.objects,"file")),e.rtdbKeys&&t.push(Is(e.rtdbKeys,"RTDB key")),t.length?t.join(" · "):"empty — no data yet"}function Hi(){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 IB(){return c.jsxs("svg",{...Hi(),children:[c.jsx("path",{d:"M12 4v10"}),c.jsx("path",{d:"M8 10l4 4 4-4"}),c.jsx("path",{d:"M4 19h16"})]})}function AB(){return c.jsxs("svg",{...Hi(),children:[c.jsx("path",{d:"M12 14V4"}),c.jsx("path",{d:"M8 8l4-4 4 4"}),c.jsx("path",{d:"M4 19h16"})]})}function OB(){return c.jsxs("svg",{...Hi(),children:[c.jsx("circle",{cx:"7",cy:"6",r:"2.4"}),c.jsx("circle",{cx:"7",cy:"18",r:"2.4"}),c.jsx("circle",{cx:"17",cy:"8",r:"2.4"}),c.jsx("path",{d:"M7 8.4v7.2"}),c.jsx("path",{d:"M17 10.4c0 3-4 3.6-7 4.4"})]})}function $B(){return c.jsxs("svg",{...Hi(),children:[c.jsx("path",{d:"M4 5v5h5"}),c.jsx("path",{d:"M4.6 10a8 8 0 1 0 1.7-5.3"})]})}function As({glyph:e,name:t,caption:n,disabled:r,danger:s,onClick:i}){return c.jsxs("button",{type:"button",className:"studio-sandbox__action","data-danger":s?"true":void 0,disabled:r,onClick:i,children:[c.jsxs("span",{className:"studio-sandbox__action-top",children:[e,c.jsx("span",{className:"studio-sandbox__action-name",children:t})]}),c.jsx("span",{className:"studio-sandbox__action-caption",children:n})]})}function DB(){const e=CB(),t=LU(),n=UU(),r=BU(),s=cs(),i=y.useRef(null),o=Xc(Zc()),[a,l]=y.useState(!1),[u,d]=y.useState(!1),[h,f]=y.useState(!1),[p,m]=y.useState(!1),[g,b]=y.useState(""),w=Sy(),{ensure:x}=w;y.useEffect(()=>x(),[x]);const v=NB(w.entries),_=RB(v),S=s.status==="ready"?s.payload.persist?"persisted to disk":"ephemeral":"in-page · resets on reload",k=async()=>{const E=await t();if(!E||typeof document>"u")return;const $=URL.createObjectURL(new Blob([E],{type:"application/json"})),C=document.createElement("a");C.href=$,C.download=`pyric-sandbox-${o||"export"}.json`,C.click(),URL.revokeObjectURL($)},N=async E=>{const $=E.target.files?.[0];if(E.target.value="",!!$&&!(typeof window<"u"&&!window.confirm("Import replaces all data in this sandbox. This cannot be undone. Continue?"))){d(!0);try{await n(await $.text())}finally{d(!1)}}},O=async()=>{f(!1),l(!0);try{await e()}finally{l(!1)}},D=async()=>{const E=g.trim();E&&(await r.save(E),b(""),m(!1))},R=async E=>{typeof window<"u"&&!window.confirm(`Restore saved state "${E}"? This replaces the current sandbox state.`)||await r.restore(E)},j=async E=>{typeof window<"u"&&!window.confirm(`Delete saved state "${E}"?`)||await r.remove(E)};return c.jsxs("section",{className:"studio-surface studio-settings","aria-labelledby":"settings-title",children:[c.jsxs("div",{className:"studio-surface__intro",children:[c.jsx("p",{className:"studio-surface__eyebrow",children:"Settings"}),c.jsx("h1",{id:"settings-title",className:"studio-surface__title",children:"Configuration and maintenance."}),c.jsx("p",{className:"studio-surface__copy",children:"Global controls live here so service surfaces can stay focused on their primary work."})]}),c.jsx("div",{className:"studio-settings__grid",children:c.jsxs("section",{className:"studio-panel studio-settings__panel","aria-labelledby":"settings-sandbox-title",children:[c.jsx("h2",{id:"settings-sandbox-title",className:"studio-panel__title",children:"Sandbox"}),c.jsxs("div",{className:"studio-sandbox__live","aria-label":"Sandbox contents",children:[c.jsx("span",{className:"studio-sandbox__instance mono",children:o||"local"}),c.jsx("span",{className:"studio-sandbox__inventory",children:_}),c.jsx("span",{className:"studio-sandbox__persist",children:S})]}),c.jsxs("div",{className:"studio-sandbox__actions",children:[c.jsx(As,{glyph:c.jsx(IB,{}),name:"Export",caption:"Downloads all of this as one file.",onClick:()=>void k()}),c.jsx(As,{glyph:c.jsx(AB,{}),name:u?"Importing…":"Import",caption:"A chosen file replaces everything here.",disabled:u,onClick:()=>i.current?.click()}),c.jsx(As,{glyph:c.jsx(OB,{}),name:"Save state",caption:"Keeps a copy you can return to.",onClick:()=>m(E=>!E)}),c.jsx(As,{glyph:c.jsx($B,{}),name:a?"Resetting…":"Reset session",caption:"Everything returns to the seeded start.",disabled:a,danger:!0,onClick:()=>f(!0)})]}),c.jsx("input",{ref:i,type:"file",accept:"application/json,.json",className:"studio-settings__file",onChange:N}),p?c.jsxs("form",{className:"studio-sandbox__name-row",onSubmit:E=>{E.preventDefault(),D()},children:[c.jsx("input",{className:"studio-sandbox__name-input",type:"text",value:g,placeholder:"saved state name","aria-label":"Saved state name",autoFocus:!0,onChange:E=>b(E.target.value),onKeyDown:E=>{E.key==="Escape"&&(m(!1),b(""))}}),c.jsx("button",{type:"submit",className:"studio-button",disabled:!g.trim(),children:"Save"}),c.jsx("button",{type:"button",className:"studio-button",onClick:()=>{m(!1),b("")},children:"Cancel"})]}):null,h?c.jsxs("div",{className:"studio-sandbox__confirm",role:"alert",children:[c.jsx("span",{className:"studio-sandbox__confirm-copy",children:v&&_!=="empty — no data yet"?`This erases ${_}.`:"This erases everything in this sandbox."}),c.jsxs("span",{className:"studio-sandbox__confirm-actions",children:[c.jsx("button",{type:"button",className:"studio-button studio-button--danger",onClick:()=>void O(),children:"Erase and reseed"}),c.jsx("button",{type:"button",className:"studio-button",onClick:()=>f(!1),children:"Keep"})]})]}):null,r.names.length>0?c.jsx("div",{className:"studio-settings__saved-states",children:r.names.map(E=>c.jsxs("div",{className:"studio-settings__saved-state",children:[c.jsx("span",{className:"mono",children:E}),c.jsxs("span",{className:"studio-settings__saved-state-actions",children:[c.jsx("button",{type:"button",className:"studio-button",onClick:()=>void R(E),children:"Restore"}),c.jsx("button",{type:"button",className:"studio-button",onClick:()=>void j(E),children:"Delete"})]})]},E))}):c.jsx("p",{className:"studio-sandbox__saved-states-empty",children:"No saved states yet. Save state keeps this exact sandbox to come back to."})]})})]})}function Os(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 PB(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(o=>JSON.stringify(n[o])!==JSON.stringify(r[o]));if(i.length>0&&i.length<=3)return i.map(o=>`${o}: ${Os(n[o])} -> ${Os(r[o])}`).join(", ")}return`${Os(t.before)} -> ${Os(t.after)}`}function TB(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:PB(t),supported:t.qualification.supported}))}function MB(e){const t=e.mutation.events.find(o=>o.result==="allow"||o.result==="deny"||o.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.queryProof&&(r.queryProof=t.queryProof),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 LB="pyric:assurance-campaign",UB="pyric-assurance-v1",Ja=new Set;let Mf=!1,Lf;function Uf(e){for(const t of Ja)t(e)}function Bf(e){return!!e&&typeof e=="object"&&e.schema==="pyric.assurance.visualization.v1"&&typeof e.campaignId=="string"}function BB(){if(!(Mf||typeof document>"u")){Mf=!0,globalThis.addEventListener(LB,e=>{const t=e.detail;Bf(t)&&Uf(t)});try{Lf=new BroadcastChannel(UB),Lf.onmessage=e=>{Bf(e.data)&&Uf(e.data)}}catch{}}}function FB(e){return BB(),Ja.add(e),()=>Ja.delete(e)}function Mo(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 qB=[Mo({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"}}),Mo({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"}),Mo({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"}}})],y1=qB.map(e=>({...e,campaignId:"collaboration-local-v1-fixed",targetHash:"fnv1a32-a9f18f23",mutation:{...e.mutation,decision:"DENY",events:[]},stateDiff:void 0,classification:"no-counterexample"}));const Ya="pyric:assurance:campaigns",fb="pyric:assurance:campaign:";function VB(e){return!!e&&typeof e=="object"&&e.schema==="pyric.assurance.visualization.v1"&&typeof e.campaignId=="string"}function WB(){if(typeof sessionStorage>"u")return[];try{const e=JSON.parse(sessionStorage.getItem(Ya)??"[]");if(!Array.isArray(e))return[];const t=e.map(n=>sessionStorage.getItem(`${fb}${String(n)}`)).filter(n=>!!n).map(n=>JSON.parse(n)).filter(VB);return t.length,t}catch{return[]}}function zB(e){if(!(typeof sessionStorage>"u"))try{const t=JSON.parse(sessionStorage.getItem(Ya)??"[]"),n=Array.isArray(t)?t.map(String):[];n.includes(e.campaignId)||n.push(e.campaignId),sessionStorage.setItem(Ya,JSON.stringify(n)),sessionStorage.setItem(`${fb}${e.campaignId}`,JSON.stringify(e))}catch{}}function HB(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 KB(){const[e,t]=y.useState(WB);return y.useEffect(()=>{const r=FB(s=>{zB(s),t(i=>HB(i,s))});return()=>{r()}},[]),e}function GB(e,t){return e!==t?"assurance-verdict--mismatch":t==="ALLOW"?"assurance-verdict--allow":"assurance-verdict--deny"}function JB(e){return e.replaceAll("-"," ")}function Ff({value:e}){return c.jsx("pre",{className:"assurance-evidence__json",children:JSON.stringify(e,null,2)})}function YB(){return c.jsxs("section",{className:"assurance-empty","aria-labelledby":"assurance-empty-title",children:[c.jsx("p",{className:"assurance-surface__eyebrow",children:"Local authorization assurance"}),c.jsx("h1",{id:"assurance-empty-title",children:"No campaign in this Studio session"}),c.jsx("p",{children:"Campaigns appear here as the local assurance tools map actors, run controls, and test explicit security invariants."}),c.jsx("span",{className:"assurance-local-state",children:"Pyric sandboxes only | network off"})]})}function qf({attachment:e}){return e?c.jsxs("div",{className:"assurance-attachment","aria-label":"Attached sandbox inventory",children:[c.jsxs("span",{children:[c.jsx("strong",{children:e.source.origin}),"read-only clone"]}),c.jsxs("span",{children:[c.jsx("strong",{children:e.inventory.firestoreDocuments}),"Firestore docs"]}),c.jsxs("span",{children:[c.jsx("strong",{children:e.inventory.authUsers}),"Auth users"]}),c.jsxs("span",{children:[c.jsx("strong",{children:e.inventory.rtdbPresent?"present":"empty"}),"RTDB"]})]}):null}function QB({campaigns:e}){const t=KB(),n=e??t,r=Ke().query,[s,i]=y.useState(r.campaign??n.find(v=>v.report)?.campaignId??n[0]?.campaignId??""),o=n.find(v=>v.campaignId===s)??n[0],a=y.useMemo(()=>o?.report?TB(o.report):[],[o]),[l,u]=y.useState(r.probe??a[0]?.id??"");if(y.useEffect(()=>{!s&&n[0]&&i(n[0].campaignId)},[s,n]),y.useEffect(()=>{a.some(v=>v.id===l)||u(a[0]?.id??"")},[a,l]),!o)return c.jsx(YB,{});const d=o.context?.attachment,h=o.report;if(!h)return c.jsxs("section",{className:"assurance-empty","aria-labelledby":"assurance-mapped-title",children:[c.jsx("p",{className:"assurance-surface__eyebrow",children:o.campaignId}),c.jsx("h1",{id:"assurance-mapped-title",children:"Campaign mapped, awaiting its first run"}),c.jsxs("p",{children:[o.observations.length," known-good operation(s) and"," ",o.probes.length," probe(s) are available."]}),c.jsx(qf,{attachment:d}),d?.coverageGaps.length?c.jsx("ul",{className:"assurance-coverage-gaps","aria-label":"Attachment coverage gaps",children:d.coverageGaps.map(v=>c.jsxs("li",{children:[c.jsx("code",{children:v.service}),v.reason]},v.code))}):null,c.jsx("span",{className:"assurance-local-state",children:"Pyric sandboxes only | network off"})]});const f=a.find(v=>v.id===l)??a[0],p=h.results.find(v=>v.probeId===f?.id),m=p?MB(p):null,g=o.verifications?.at(-1),b=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 w(v){i(v);const S=n.find(k=>k.campaignId===v)?.report?.results[0]?.probeId??"";u(S),qr({tab:"assurance",query:{campaign:v,probe:S||void 0}})}function x(v){u(v.id),qr({tab:"assurance",query:{campaign:o.campaignId,probe:v.id}})}return c.jsxs("section",{className:"assurance-surface","aria-labelledby":"assurance-title",children:[c.jsxs("header",{className:"assurance-surface__header",children:[c.jsxs("div",{children:[c.jsx("p",{className:"assurance-surface__eyebrow",children:"Local authorization assurance"}),c.jsx("h1",{id:"assurance-title",children:o.campaignId})]}),c.jsxs("div",{className:"assurance-surface__controls",children:[n.length>1?c.jsxs("label",{children:[c.jsx("span",{children:"Campaign"}),c.jsx("select",{value:o.campaignId,onChange:v=>w(v.target.value),children:n.map(v=>c.jsx("option",{value:v.campaignId,children:v.campaignId},v.campaignId))})]}):null,c.jsx("span",{className:"assurance-local-state",children:"Pyric sandboxes only | network off"})]})]}),c.jsx(qf,{attachment:d}),c.jsxs("div",{className:"assurance-summary","aria-label":"Campaign summary",children:[c.jsxs("div",{children:[c.jsx("span",{children:"Controls"}),c.jsxs("strong",{children:[h.summary.controlsPassed,"/",h.summary.probes]})]}),c.jsxs("div",{children:[c.jsx("span",{children:"Counterexamples"}),c.jsx("strong",{children:h.summary.localCounterexamples})]}),c.jsxs("div",{children:[c.jsx("span",{children:"Candidate signals"}),c.jsx("strong",{children:h.summary.candidateSignals})]}),c.jsxs("div",{children:[c.jsx("span",{children:"Engine gaps"}),c.jsx("strong",{children:h.summary.engineGaps})]}),c.jsxs("div",{children:[c.jsx("span",{children:"Coverage gaps"}),c.jsx("strong",{children:d?.coverageGaps.length??0})]})]}),g?c.jsxs("div",{className:`assurance-verification-band assurance-verification-band--${b?"passed":"failed"}`,role:"status",children:[c.jsx("strong",{children:b?"Candidate rules verified":"Candidate rules need review"}),c.jsxs("span",{children:[g.summary.controlsPassed,"/",g.summary.probes," ","controls preserved"," | ",g.summary.noCounterexamples,"/",g.summary.probes," negative cases denied"]}),c.jsx("code",{children:g.campaignId})]}):null,d?.coverageGaps.length?c.jsxs("div",{className:"assurance-coverage-band",children:[c.jsxs("strong",{children:[d.coverageGaps.length," attachment gap(s)"]}),c.jsx("span",{children:d.coverageGaps.map(v=>`${v.service}: ${v.reason}`).join(" ")})]}):null,c.jsxs("div",{className:"assurance-workspace",children:[c.jsxs("section",{className:"assurance-matrix","aria-labelledby":"assurance-matrix-title",children:[c.jsxs("div",{className:"assurance-section-heading",children:[c.jsx("h2",{id:"assurance-matrix-title",children:"Expected and observed access"}),c.jsx("span",{children:h.targetHash})]}),c.jsxs("div",{className:"assurance-table",role:"table",children:[c.jsxs("div",{className:"assurance-table__header",role:"row",children:[c.jsx("span",{role:"columnheader",children:"Operation"}),c.jsx("span",{role:"columnheader",children:"Actor"}),c.jsx("span",{role:"columnheader",children:"Expected"}),c.jsx("span",{role:"columnheader",children:"Observed"}),c.jsx("span",{role:"columnheader",children:"Impact"})]}),a.map(v=>c.jsxs("button",{type:"button",className:"assurance-table__row","aria-pressed":v.id===f?.id,onClick:()=>x(v),role:"row",children:[c.jsxs("span",{role:"cell",children:[c.jsx("small",{children:v.service}),v.operation]}),c.jsx("span",{role:"cell",children:v.actor}),c.jsx("span",{role:"cell",className:`assurance-verdict ${v.expected==="ALLOW"?"assurance-verdict--allow":"assurance-verdict--deny"}`,children:v.expected}),c.jsx("span",{role:"cell",className:`assurance-verdict ${GB(v.expected,v.observed)}`,children:v.observed}),c.jsx("span",{role:"cell",children:v.impact})]},v.id))]})]}),p?c.jsxs("aside",{className:"assurance-inspector","aria-labelledby":"assurance-inspector-title",children:[c.jsxs("div",{className:"assurance-section-heading",children:[c.jsxs("div",{children:[c.jsx("span",{className:`assurance-classification assurance-classification--${p.classification}`,children:JB(p.classification)}),c.jsx("h2",{id:"assurance-inspector-title",children:p.probeId})]}),c.jsx("span",{children:p.actorEvidence.reachability})]}),c.jsxs("dl",{className:"assurance-facts",children:[c.jsxs("div",{children:[c.jsx("dt",{children:"Invariant"}),c.jsx("dd",{children:p.invariant.statement})]}),c.jsxs("div",{children:[c.jsx("dt",{children:"Mutation"}),c.jsx("dd",{children:p.mutationSpec.description})]}),c.jsxs("div",{children:[c.jsx("dt",{children:"Actor"}),c.jsxs("dd",{children:[p.actorEvidence.uid??p.actorEvidence.actorId," ","via ",p.actorEvidence.acquisition]})]}),c.jsxs("div",{children:[c.jsx("dt",{children:"Fidelity"}),c.jsx("dd",{children:p.qualification.supported?"Supported for this probe":"Engine gap"})]})]}),p.qualification.requirements.some(v=>!v.supported)?c.jsx("ul",{className:"assurance-gaps",children:p.qualification.requirements.filter(v=>!v.supported).map(v=>c.jsxs("li",{children:[c.jsx("code",{children:v.id}),v.reason]},v.id))}):null,p.stateDiff?c.jsxs("section",{className:"assurance-evidence","aria-labelledby":"assurance-state-title",children:[c.jsx("h3",{id:"assurance-state-title",children:"State evidence"}),c.jsxs("div",{className:"assurance-evidence__diff",children:[c.jsxs("div",{children:[c.jsx("span",{children:"Before"}),c.jsx(Ff,{value:p.stateDiff.before})]}),c.jsxs("div",{children:[c.jsx("span",{children:"After"}),c.jsx(Ff,{value:p.stateDiff.after})]})]})]}):null,m?c.jsxs("section",{className:"assurance-rule-decision","aria-labelledby":"assurance-rule-title",children:[c.jsx("h3",{id:"assurance-rule-title",children:"Rule decision"}),c.jsx(Ig,{denial:m})]}):c.jsx("p",{className:"assurance-no-decision",children:"This service recorded operation and state evidence but no canonical rule-decision event."})]}):null]})]})}function Vf(){return Ti()}function hb(){return`${Ti()}docs`}function Wf(e){return t=>{t.metaKey||t.ctrlKey||t.shiftKey||t.altKey||(t.preventDefault(),e())}}function XB(){const[e,t]=y.useState(!1);return y.useEffect(()=>{let n=!0;return fetch(`${hb()}/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 ZB({id:e}){const t=q0(e),n=Kt(),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"),c.jsxs("section",{className:"studio__placeholder","aria-labelledby":`route-${t.id}`,children:[c.jsx("p",{className:"studio__placeholder-eyebrow",children:"Surface"}),c.jsx("h2",{id:`route-${t.id}`,className:"studio__placeholder-title",children:t.label}),c.jsx("p",{className:"studio__placeholder-blurb",children:t.description}),c.jsx("div",{className:"studio__placeholder-meta",children:r.map(s=>c.jsx("span",{children:s},s))})]})}function e1({id:e}){switch(e){case"home":return c.jsx(ZU,{});case"firestore":return c.jsx(fM,{});case"auth":return c.jsx(wM,{});case"storage":return c.jsx(hM,{});case"rtdb":return c.jsx(wB,{});case"traffic":return c.jsx(MU,{});case"assurance":return c.jsx(QB,{});case"settings":return c.jsx(DB,{});default:return c.jsx(ZB,{id:e})}}function t1(){const[e,t]=H0(F0,"home"),n=u=>t(u),[r,s]=y.useState(!1),i=XB(),[o]=y.useState(()=>mU());y.useEffect(()=>{if(!o.open)return;const u={view:"listeners"};o.listenerId!==void 0&&(u.listener=o.listenerId),o.targetPrefix!==void 0&&(u.target=o.targetPrefix),qr({tab:"traffic",query:u})},[]);const a=e==="home";y.useEffect(()=>{const u=d=>{if(J0(d)){if(r){d.preventDefault(),s(!1);return}if(a){G0()&&d.preventDefault();return}d.preventDefault(),s(!0)}};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[a,r]),y.useEffect(()=>{a&&s(!1)},[a]),y.useEffect(()=>{document.querySelector('.studio__rail [aria-current="page"]')?.scrollIntoView({block:"nearest",inline:"center"})},[e]);const l=dn.filter(u=>u.id!=="home");return c.jsxs("div",{className:"studio","data-surface":e,children:[c.jsxs("header",{className:"studio__chrome",children:[c.jsx("div",{className:"studio__bar",children:c.jsxs("div",{className:"studio__chrome-inner",children:[c.jsxs("nav",{className:"studio__nav","aria-label":"Site",children:[c.jsx("a",{className:"studio__brand",href:Vf(),"aria-label":"Pyric",children:"pyric"}),c.jsx("a",{className:"studio__nav-tab",href:Vf(),children:"Home"}),i?c.jsx("a",{className:"studio__nav-tab",href:hb(),children:"Docs"}):null,c.jsx("a",{className:"studio__nav-tab",href:Ct({tab:"home"}),"aria-current":e==="home"?"page":!0,onClick:Wf(()=>n("home")),children:"Studio"})]}),c.jsx(rD,{})]})}),c.jsx("nav",{className:"studio__rail","aria-label":"Studio",children:c.jsx("div",{className:"studio__chrome-inner",children:c.jsx("div",{className:"studio__nav",children:l.map(u=>c.jsx("a",{className:"studio__nav-tab",href:Ct({tab:u.id}),"aria-current":u.id===e?"page":void 0,onClick:Wf(()=>n(u.id)),children:u.label},u.id))})})})]}),c.jsx("main",{className:"studio__content","data-surface":e,children:c.jsx("div",{className:"studio__surface-slot","data-active":"true",children:c.jsx(e1,{id:e})})}),r?c.jsx(NO,{onClose:()=>s(!1)}):null]})}function n1(){return c.jsx(T0,{children:c.jsx(zE,{children:c.jsx(A0,{mode:"local",children:c.jsx(t1,{})})})})}function g1(){return c.jsx(y.StrictMode,{children:c.jsx(n1,{})})}export{g1 as S,m1 as a,FS as b,Ar as r,xe as s,Zj as u};
|
|
147
|
+
`)})`}function oU(e){return at(e)?e.kind==="child"?typeof e.path=="string"?`.orderByChild(${qe(e.path)})`:"":e.kind==="key"?".orderByKey()":e.kind==="value"?".orderByValue()":e.kind==="priority"?".orderByPriority()":"":""}const aU=new Set(["startAt","startAfter","endAt","endBefore","equalTo"]);function Nf(e,t,n){const r=[];if(at(t)){r.push(oU(t.orderBy));const s=Array.isArray(t.bounds)?t.bounds:[];for(const o of s){if(!at(o)||typeof o.kind!="string"||!aU.has(o.kind))continue;const a=[Hr(o.value,n)];typeof o.key=="string"&&a.push(qe(o.key)),r.push(`.${o.kind}(${a.join(", ")})`)}const i=t.limit;at(i)&&typeof i.n=="number"&&(i.kind==="limitToFirst"||i.kind==="limitToLast")&&r.push(`.${i.kind}(${String(i.n)})`)}return`ref(db, ${qe(e)})${r.join("")}`}function cU(e){if(e.service==="database"){const r=typeof e.target=="string"?e.target:"";return r===""?void 0:{text:Nf(r,e.query,!1),full:Nf(r,e.query,!0)}}if(typeof e.target=="string")return;const t=e.target.collection;if(t==="")return;const n=at(e.query)?e.query:at(e.target.query)?e.target.query:void 0;return{text:Cf(t,n,!1),full:Cf(t,n,!0)}}function lU({value:e,clipboard:t}){const[n,r]=y.useState(!1),s=t??globalThis.navigator?.clipboard;return c.jsx("button",{type:"button",className:"traffic__listener-query-copy","data-pyric-query-copy":"","data-pyric-copy-value":e,"data-pyric-copy-failed":n?"":void 0,"aria-label":n?"Copy failed":"Copy the query",title:n?"Copy failed":"Copy the query",disabled:s===void 0,onClick:()=>{s!==void 0&&Promise.resolve(s.writeText(e)).then(()=>r(!1),()=>r(!0))},children:c.jsxs("svg",{className:"traffic__listener-query-icon","aria-hidden":"true",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",children:[c.jsx("rect",{x:"8",y:"8",width:"11",height:"11",rx:"1"}),c.jsx("path",{d:"M16 8V5H5v11h3"})]})})}function rb({listener:e,clipboard:t}){const n=y.useMemo(()=>cU({service:e.service,target:e.target,query:e.query}),[e.service,e.target,e.query]);return n===void 0?null:c.jsxs("div",{className:"traffic__listener-query","data-pyric-query-block":"",children:[c.jsx("pre",{className:"traffic__listener-query-text","data-pyric-query-text":"",title:n.full===n.text?void 0:n.full,children:n.text}),c.jsx(lU,{value:n.full,clipboard:t})]})}const uU=new Intl.NumberFormat,dU=new Intl.DateTimeFormat(void 0,{hour:"numeric",minute:"2-digit"});function Rn(e){return uU.format(e)}function lr(e){return dU.format(e)}const fU=[{id:"incident",label:"",name:"Incidents"},{id:"target",label:"Target",name:"Target"},{id:"deliveries",label:"Deliveries",name:"Deliveries"},{id:"attached",label:"Attached",name:"Attached"},{id:"service",label:"Service",name:"Service"}];function hU(e,t){const n={};return e!==""&&(n.service=e),t!==""&&(n.targetPrefix=t),n}function pU(e,t){return e?.column!==t?"none":e.direction==="asc"?"ascending":"descending"}function mU({metric:e,label:t,value:n,unit:r}){return c.jsxs("span",{className:"traffic__listener-figure","data-pyric-inspector-figure":e,children:[c.jsx("span",{className:"traffic__listener-figure-label",children:t}),c.jsx("span",{className:"traffic__listener-figure-value",children:r===void 0?Rn(n):`${Rn(n)} ${r}`})]})}function yU({listener:e,row:t,events:n,now:r,onClose:s}){const[i,o]=y.useState(!1),a=y.useMemo(()=>Fg(n,e.id),[n,e.id]),l=a[a.length-1],u=Hi(e.owners),d={service:e.service,attachedAt:e.attachedAt};d.owner=zi(e).label,u!==void 0&&(d.element=u);const h=t.incidents[0],f=qg({deliveries:a.length,snapshot:l===void 0?0:l.size,reads:Vg(a),service:e.service,single:typeof e.target=="string"&&e.service==="firestore"});return c.jsxs("div",{className:"traffic__inspector","data-pyric-listener-inspector":"",children:[c.jsxs("div",{className:"traffic__inspector-bar",children:[c.jsx("a",{className:"traffic__listener-inspector-target","data-pyric-inspector-title":"",href:UL(e.id),onClick:p=>{p.metaKey||p.ctrlKey||p.shiftKey||p.button!==0||(p.preventDefault(),Ae(Hg(e.id)))},children:t.target}),c.jsx("button",{type:"button",className:"traffic__inspector-close","data-pyric-inspector-close":"",onClick:s,"aria-label":"Close the listener inspector",children:"✕"})]}),c.jsx("p",{className:"traffic__listener-facts","data-pyric-inspector-facts":"",children:eb(d,r)}),c.jsx(rb,{listener:e}),h===void 0?null:c.jsx(tb,{incident:h,listener:e,events:n,now:r}),c.jsx("div",{className:"traffic__listener-figures",children:f.map(p=>c.jsx(mU,{metric:p.key,label:p.label,value:p.total,unit:p.unit},p.key))}),l===void 0?null:c.jsx(Yg,{delivery:l,service:e.service,expanded:i,onToggle:()=>o(p=>!p)})]})}function gU({events:e,window:t,selectedListenerId:n,initialTargetPrefix:r,hideStudio:s=!1,now:i}){const[o,a]=y.useState(""),[l,u]=y.useState(r??""),[d,h]=y.useState(void 0),[f,p]=y.useState(n),[m,g]=y.useState([]),b=y.useRef(null),w=y.useMemo(()=>{const I=ac(e);return s?I.filter(A=>A.actor.kind!=="studio"):I},[e,s]),x=y.useMemo(()=>Lg(e),[e]),v=y.useMemo(()=>NL(e,t),[e,t]),_=y.useMemo(()=>SL(hL(w,hU(o,l)),x,d,I=>v.get(I.id)??0),[w,o,l,x,d,v]),S=y.useMemo(()=>kL(_,x),[_,x]),k=y.useMemo(()=>CL(jL(_)),[_]),N=y.useMemo(()=>RL(e,w,t),[e,w,t]),O=y.useMemo(()=>new Set(Bg.map(I=>I.key).filter(I=>!m.includes(I))),[m]),P=I=>g(A=>A.includes(I)?A.filter(D=>D!==I):[...A,I]),R=i??Date.now(),j=y.useMemo(()=>{if(n!==void 0){for(const I of _)for(const A of I.rows)if(A.listeners.some(D=>D.id===n))return A.listener.id;return n}},[n,_]);y.useEffect(()=>{j!==void 0&&(p(j),b.current?.scrollIntoView({block:"center"}))},[j]);const E=y.useMemo(()=>_.map(I=>({...I,rows:I.rows.filter(A=>EL(A).some(D=>O.has(D)))})).filter(I=>I.rows.length>0),[_,O]);function $(I){const A=I.listener,D=A.id===f;return c.jsxs("div",{className:"traffic__listener-entry","data-pyric-listener-entry":"",children:[c.jsxs("button",{type:"button",className:"traffic__listener-row",ref:D?b:void 0,"data-pyric-listener-row":"","data-pyric-listener-id":A.id,"data-pyric-selected":D?"":void 0,"data-pyric-incident":I.incidents.length>0?"":void 0,onClick:()=>p(D?void 0:A.id),children:[c.jsx("span",{"data-col":"incident","aria-hidden":"true",children:I.incidents.length>0?"⚠":""}),c.jsxs("span",{"data-col":"target",title:I.target,children:[c.jsx("span",{className:"traffic__listener-target-text",children:I.target}),I.count>1?c.jsxs("span",{className:"traffic__listener-duplicate","data-pyric-listener-duplicate":"",children:["×",I.count]}):null]}),c.jsx("span",{"data-col":"deliveries",children:Rn(I.deliveryCount)}),c.jsx("span",{"data-col":"attached",children:Xc(A.attachedAt,R)}),c.jsx("span",{"data-col":"service",children:Zg(A.service)})]}),D?c.jsx(yU,{listener:A,row:I,events:e,now:R,onClose:()=>p(void 0)}):null]},I.key)}const C=ZL(S);return c.jsx("div",{className:"traffic__metrics","data-pyric-ui":"traffic-listeners-view",children:c.jsxs("section",{className:"traffic__metric-panel traffic__metric-panel--journal",children:[c.jsxs("header",{className:"traffic__metric-story",children:[c.jsx("p",{className:"traffic__metric-eyebrow",children:"Listener activity"}),c.jsx("h3",{className:"traffic__metric-headline",children:XL(S)}),C===void 0?null:c.jsx("p",{className:"traffic__metric-finding","data-pyric-listener-owner-fact":"",children:C})]}),c.jsx(Fc,{series:k,visible:O,onToggle:P,formatValue:Rn,className:"traffic__metric-cards traffic__metric-cards--journal traffic__metric-cards--3"}),c.jsxs("div",{className:"traffic__metric-evidence",children:[c.jsxs("div",{className:"traffic__metric-evidence-header",children:[c.jsx("h4",{children:"When deliveries happened"}),c.jsxs("span",{children:[lr(t.start),"–",lr(t.end)]})]}),N.total===0?c.jsx("p",{className:"traffic__empty",children:"No deliveries in this window."}):c.jsxs(c.Fragment,{children:[c.jsx(qy,{points:N.points,series:N.series,omitZeroSeries:!0,formatValue:Rn,formatTime:lr,className:"traffic__chart traffic__chart--journal"}),c.jsxs("div",{className:"traffic__metric-axis","aria-hidden":"true",children:[c.jsx("span",{children:lr(t.start)}),c.jsx("span",{children:lr(t.end)})]})]})]}),c.jsxs("div",{className:"traffic__filters traffic__filters--listeners",role:"group","aria-label":"Listener filters",children:[c.jsxs("label",{className:"traffic__filter-field",children:[c.jsx("span",{className:"traffic__filters-label",children:"Service"}),c.jsxs("select",{className:"traffic__filter-select",value:o,onChange:I=>a(I.target.value),children:[c.jsx("option",{value:"",children:"All"}),c.jsx("option",{value:"firestore",children:"Firestore"}),c.jsx("option",{value:"database",children:"Database"})]})]}),c.jsxs("label",{className:"traffic__filter-field",children:[c.jsx("span",{className:"traffic__filters-label",children:"Target"}),c.jsx("input",{className:"traffic__filter-input",type:"text",value:l,onChange:I=>u(I.target.value)})]})]}),w.length===0?null:E.length===0?c.jsx("p",{className:"traffic__empty","data-pyric-listener-empty":"",children:"No listeners match these filters"}):c.jsxs("div",{className:"traffic__log traffic__listener-grid","data-pyric-listener-grid":"","data-pyric-ui":"traffic-listeners-log",children:[c.jsx("div",{className:"traffic__listener-header","data-pyric-listener-header":"",role:"row",children:fU.map(I=>c.jsxs("button",{type:"button",role:"columnheader",className:"traffic__listener-column","data-col":I.id,"aria-label":I.label===""?I.name:void 0,"aria-sort":pU(d,I.id),onClick:()=>h(A=>gL(A,I.id)),children:[I.label,d?.column===I.id?c.jsx("span",{"aria-hidden":"true",children:d.direction==="asc"?"↑":"↓"}):null]},I.id))}),E.map(I=>c.jsxs("div",{className:"traffic__listener-run",children:[c.jsxs("div",{className:"traffic__listener-group","data-pyric-listener-group":I.identity.key,children:[c.jsx("span",{"data-col":"owner",children:I.identity.label}),c.jsx("span",{"data-col":"count",children:Rn(I.listenerCount)})]}),I.rows.map(A=>$(A))]},I.identity.key))]}),c.jsxs("footer",{className:"traffic__metric-footer",children:[c.jsx("p",{className:"traffic__metric-source",children:"Source: sandbox listener events · listeners attached now, deliveries in this window"}),c.jsxs("details",{className:"traffic__metric-methodology",children:[c.jsx("summary",{children:"How this is counted"}),c.jsxs("div",{children:[c.jsxs("p",{children:["A listener is attached when the sandbox recorded its ",c.jsx("code",{children:"attach"})," and has not recorded a ",c.jsx("code",{children:"detach"})," or an error for it since. The count is that fold, not the number of attach events."]}),c.jsxs("p",{children:[c.jsx("strong",{children:"Owners come from the attach, deliveries from the window."})," The owner is the React component the listener was opened in, else the tag the app gave it, else the target itself. Two listeners on the same target under the same owner are one thing attached twice, so they collapse into one row carrying"," ",c.jsx("code",{children:"×N"}),". Delivery counts cover the displayed window only; a listener with none is idle, not gone."]})]})]})]})]})})}const sb={open:!1};function ib(e){const t=new URLSearchParams(e);if(t.get("view")!=="listeners")return sb;const n={open:!0},r=t.get("listener");r!==null&&r!==""&&(n.listenerId=r);const s=t.get("target");return s!==null&&s!==""&&(n.targetPrefix=s),n}function bU(e){const t=new URLSearchParams;for(const[n,r]of Object.entries(e))r!==void 0&&t.set(n,r);return ib(t.toString())}function wU(){return typeof window>"u"?sb:ib(window.location.search)}const vU={open:!1};function xU(){return bU(Ke().query)}function _U({window:e,hideStudio:t,deepLink:n}){const r=Jt("active-listeners"),s=y.useSyncExternalStore(Gt,Dc,()=>""),i=y.useMemo(()=>s===""?vU:xU(),[s]),o=n??i,a={events:r,window:e};return t!==void 0&&(a.hideStudio=t),o.listenerId!==void 0&&(a.selectedListenerId=o.listenerId),o.targetPrefix!==void 0&&(a.initialTargetPrefix=o.targetPrefix),c.jsx(gU,{...a})}function SU(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 kU(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:SU(n.length,r)}}function ob(e,t){return e?.start===t.start&&e.end===t.end?null:t}const jU=new Intl.NumberFormat;function EU(e){return jU.format(e)}function Rf(e){return`${jf(e.start)}–${jf(e.end)}`}function CU(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 If(){return c.jsx("a",{className:"traffic__listener-back",href:BL(),"data-pyric-page-back":"",onClick:e=>{e.metaKey||e.ctrlKey||e.shiftKey||e.button!==0||(e.preventDefault(),Ae(Kg()))},children:"← Listeners"})}function NU({events:e,listenerId:t,window:n,now:r}){const[s,i]=y.useState(null),[o,a]=y.useState(null),l=y.useMemo(()=>ac(e).find(_=>_.id===t),[e,t]),u=y.useMemo(()=>Fg(e,t),[e,t]),d=y.useMemo(()=>{if(l!==void 0)return Ug(Lg(e),l.target)[0]},[e,l]);if(l===void 0)return c.jsxs("div",{className:"traffic__metrics","data-pyric-ui":"traffic-listener-page",children:[c.jsx(If,{}),c.jsx("p",{className:"traffic__empty","data-pyric-listener-missing":"",children:"This listener is not attached in this session."})]});const h=r??Date.now(),f=Hi(l.owners),p={service:l.service,attachedAt:l.attachedAt};p.owner=zi(l).label,f!==void 0&&(p.element=f);const m=Mn(l.target),g=qg({deliveries:u.length,snapshot:u.length===0?0:u[u.length-1].size,reads:Vg(u),service:l.service,single:typeof l.target=="string"&&l.service==="firestore"}),b=DL(l.service),w=TL(u,m),x=s===null?u:Sf(u,s),v=u.map((_,S)=>({delivery:_,index:S})).filter(({delivery:_})=>s===null||_.at>=s.start&&_.at<s.end).reverse();return c.jsxs("div",{className:"traffic__metrics","data-pyric-ui":"traffic-listener-page",children:[c.jsx(If,{}),c.jsxs("div",{className:"traffic__metric-panel traffic__metric-panel--journal",children:[c.jsxs("section",{className:"traffic__metric-story","data-pyric-section":"header",children:[c.jsx("h3",{className:"traffic__metric-headline","data-pyric-page-title":"",children:m}),c.jsx("p",{className:"traffic__listener-facts","data-pyric-page-facts":"",children:eb(p,h)})]}),c.jsx(rb,{listener:l}),d===void 0?null:c.jsx(tb,{incident:d,listener:l,events:e,now:h}),c.jsxs("section",{"data-pyric-section":"cards",children:[c.jsx(Fc,{series:$L(g),formatValue:PL(g,EU),className:`traffic__metric-cards traffic__metric-cards--journal${g.length===2?" traffic__metric-cards--2":""}`}),b===void 0?null:c.jsx("p",{className:"traffic__metric-source","data-pyric-metric-footnote":"",children:b})]}),u.length===0?null:c.jsxs("section",{className:"traffic__listener-section","data-pyric-section":"deliveries",children:[c.jsx(Vy,{events:w,window:n,brush:s??void 0,onBrush:_=>{i(S=>ob(S,_)),a(null)},liveAt:n.end,bucketCount:36,className:"traffic__timeline",axis:_=>c.jsxs("div",{className:"traffic__tl-axis",children:[c.jsx("span",{children:CU(_.start,h)}),c.jsx("span",{children:"now"})]}),renderBucketSummary:_=>c.jsxs("div",{className:"traffic__bucket-summary",children:[c.jsx("span",{children:Rf(_)}),c.jsx("strong",{children:kf(Sf(u,_))[0]})]})}),s===null?null:c.jsxs("p",{className:"traffic__listener-interval","data-pyric-interval":"",children:[c.jsx("span",{className:"traffic__time-focus-eyebrow",children:"Selected interval"}),c.jsx("span",{"data-pyric-interval-facts":"",children:[Rf(s),...kf(x)].join(" · ")})]}),v.length===0?null:c.jsx("div",{className:"traffic__log","data-pyric-delivery-log":"",children:v.map(_=>c.jsx(Yg,{delivery:_.delivery,service:l.service,expanded:o===_.index,onToggle:()=>a(o===_.index?null:_.index)},_.index))})]}),c.jsxs("footer",{className:"traffic__metric-footer",children:[c.jsx("p",{className:"traffic__metric-source",children:"Source: sandbox delivery events · every delivery this session recorded for this listener"}),c.jsxs("details",{className:"traffic__metric-methodology",children:[c.jsx("summary",{children:"How this is counted"}),c.jsxs("div",{children:[c.jsx("p",{children:"Every delivery event carries the result set the callback received: a Firestore delivery carries the documents in callback order, and a database delivery carries the value at the target path, whose keys are child paths when that value is an object. The paths under a delivery are that result set, not a re-read of the store."}),c.jsxs("p",{children:[c.jsx("strong",{children:"The labels come from the previous delivery."})," A path is"," ",c.jsx("code",{children:"added"})," when the previous delivery did not carry it,"," ",c.jsx("code",{children:"modified"})," when it did and the data differs, and ",c.jsx("code",{children:"removed"})," ","when the previous delivery carried it and this one does not. A path whose data is identical is not listed. The first delivery is ",c.jsx("code",{children:"initial"}),": every path in it arrived, so it lists none."]}),c.jsx("p",{children:"Firestore charges a listener for the documents in its first snapshot, then for each document a later delivery adds or changes; a delivery that only drops documents costs nothing, and an empty first snapshot still costs one read. The estimate covers this session's deliveries, so a reconnect that re-read the result set and a second listener on the same query are not in it."})]})]})]})]})]})}function RU({listenerId:e,window:t}){const n=Jt();return c.jsx(NU,{events:n,listenerId:e,window:t})}const IU=[{id:"timeline",label:"Timeline"},{id:"billable",label:"Billable metrics"},{id:"rules",label:"Rules"},{id:"listeners",label:"Listeners"}];function AU(e){return e==="billable"?"billable":e==="rules"||e==="subscriptions"?"rules":e==="listeners"?"listeners":"timeline"}function OU(e){return e.tab!=="traffic"?"timeline":Gg(e)!==void 0?"listeners":AU(e.query.view)}function $U(){return OU(Ke())}function PU(){const{tab:e,rest:t}=Ke();return Gg({tab:e,rest:t})}function DU(){return y.useSyncExternalStore(Gt,PU,()=>{})}function TU(){const e=y.useSyncExternalStore(Gt,$U,()=>"timeline"),t=y.useCallback(n=>{const r={...Ke().query,view:n==="timeline"?void 0:n};r.view===void 0&&delete r.view,Ae({tab:"traffic",query:r})},[]);return[e,t]}function MU(){const e=y.useSyncExternalStore(Gt,()=>Ke().query.hide==="studio",()=>!1),t=y.useCallback(()=>{const n={...Ke().query};n.hide==="studio"?delete n.hide:n.hide="studio",Ae({tab:"traffic",query:n})},[]);return[e,t]}function LU(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 Af(e){return`${Wr(e.start)}–${Wr(e.end)}`}function UU({event:e}){const t=Gn(e);return t?c.jsx("span",{className:"traffic__verdict","data-verdict":t,children:Rg(t)}):null}function BU(){return y.useSyncExternalStore(Gt,()=>Ig(Ke().query),()=>null)}const Mo=100;function FU(){const e=t$(),[t,n]=TU(),r=DU(),[s,i]=MU(),o=y.useMemo(()=>IM(e,s),[e,s]),a=e.length-o.length,[l,u]=y.useState("all"),[d,h]=y.useState(null),f=BU(),[p,m]=y.useState(Mo),g=C=>{Ae({tab:"traffic",query:DM(Ke().query,C)})},b=()=>{Ae({tab:"traffic",query:Ag(Ke().query,null)})};y.useEffect(()=>{if(!f)return;const C=I=>{I.key==="Escape"&&b()};return globalThis.addEventListener("keydown",C),()=>globalThis.removeEventListener("keydown",C)},[f]);const w=y.useMemo(()=>{const C=Date.now();if(o.length===0)return{start:C-15*6e4,end:C};let I=1/0;for(const A of o)A.at<I&&(I=A.at);return{start:Math.min(I,C-6e4),end:C+1e3}},[o]),x=w.end,v=y.useMemo(()=>d?kU(o,d):null,[o,d]),_=v?.events??o,S=y.useMemo(()=>OM(_,l).sort((C,I)=>I.at-C.at),[_,l]),{items:k}=lP({events:S}),N=k.slice(0,p),O=k.length-N.length,P=o.length>=kr,R=o.filter(C=>C.result==="deny").length,j=C=>c.jsx(UU,{event:C}),E=C=>{if(Po(C)){g(C.id);return}const I=gf(C);I&&Ae(I)},$=f!=null&&N.some(C=>C.type!=="group"&&C.event.id===f);return c.jsxs("section",{"data-pyric-ui":"traffic-surface",className:"traffic",children:[c.jsxs("div",{className:"traffic__tabs",role:"tablist","aria-label":"Traffic views",children:[IU.map(C=>c.jsx("button",{type:"button",role:"tab",className:"traffic__tab","aria-selected":t===C.id,onClick:()=>n(C.id),children:C.label},C.id)),c.jsxs("button",{type:"button",className:"traffic__hide-studio","aria-pressed":s,onClick:i,title:"Hide ops issued by Pyric Studio's own viewers and editors",children:["Hide Studio traffic",s&&a>0?` (${a} hidden)`:""]})]}),r!==void 0?c.jsx(RU,{listenerId:r,window:w}):t==="billable"?c.jsx(aL,{events:o,window:w}):t==="rules"?c.jsx(cL,{events:o,window:w}):t==="listeners"?c.jsx(_U,{window:w,hideStudio:s}):c.jsxs(c.Fragment,{children:[c.jsx(Vy,{events:o,window:w,brush:d??void 0,onBrush:C=>{h(I=>ob(I,C)),f&&b()},liveAt:w.end,bucketCount:36,className:"traffic__timeline",header:c.jsxs("div",{className:"traffic__tl-header",children:[c.jsxs("span",{className:"traffic__tl-count",children:[o.length," requests",P?` (showing latest ${kr})`:""]}),R>0?c.jsxs("button",{type:"button",className:"traffic__tl-deny","aria-pressed":l==="deny",onClick:()=>u(C=>C==="deny"?"all":"deny"),title:"Filter the stream to denied requests",children:[R," denied"]}):null,c.jsx("span",{className:"traffic__tl-live",children:"live"})]}),axis:C=>c.jsxs("div",{className:"traffic__tl-axis",children:[c.jsx("span",{children:LU(C.start,x)}),c.jsx("span",{children:"now"})]}),renderBucketSummary:C=>c.jsxs("div",{className:"traffic__bucket-summary",children:[c.jsx("span",{children:Af(C)}),c.jsxs("strong",{children:[C.count," ",C.count===1?"request":"requests"]}),c.jsxs("span",{children:[C.denies," denied"]})]}),emptyState:c.jsx("p",{className:"traffic__empty",children:"No requests in this window yet."})}),v?c.jsxs("section",{className:"traffic__time-focus","aria-label":"Selected traffic interval","aria-live":"polite",children:[c.jsxs("div",{className:"traffic__time-focus-story",children:[c.jsx("p",{className:"traffic__time-focus-eyebrow",children:"Selected interval"}),c.jsx("h3",{children:Af(v.window)}),c.jsx("p",{children:v.finding})]}),c.jsx("button",{type:"button",onClick:()=>h(null),children:"Show all traffic"})]}):null,c.jsxs("div",{className:"traffic__filters",role:"group","aria-label":"Traffic filters",children:[c.jsx("span",{className:"traffic__filters-label","aria-hidden":"true",children:"verdict"}),AM.map(C=>c.jsx("button",{type:"button",className:"traffic__filter","aria-pressed":l===C,onClick:()=>u(C),children:Rg(C)},C))]}),f&&!$?c.jsx(bf,{eventId:f,onClose:b},f):null,k.length===0?c.jsx("p",{className:"traffic__empty",children:v?l==="all"?"No requests occurred in the selected interval.":`No ${l} traffic occurred in the selected interval.`:l==="all"?"No requests yet. Reads, writes, and listeners against the sandbox stream in live.":`No ${l} traffic in this session.`}):c.jsxs("div",{className:"traffic__log","data-pyric-ui":"traffic-log","data-pyric-grouped":"","data-pyric-time-focused":v?"":void 0,children:[c.jsx("ul",{"data-pyric-traffic-log-items":"",children:N.map(C=>C.type==="group"?c.jsx("li",{"data-pyric-traffic-group-entry":"",children:c.jsx(EP,{group:C,onSelect:I=>{const A=I;if(Po(A)){g(A.id);return}const D=gf(A);D&&Ae(D)},renderClassification:I=>j(I),formatTime:Wr})},C.key):c.jsxs("li",{"data-pyric-traffic-entry":"","data-pyric-traffic-id":C.event.id,"data-verdict":Gn(C.event)??void 0,children:[c.jsx(Fy,{event:C.event,selected:C.event.id===f,onSelect:I=>E(I),renderClassification:I=>j(I),formatTime:Wr}),C.event.id===f&&Po(C.event)?c.jsx(bf,{eventId:f,onClose:b},f):null]},C.event.id))}),O>0?c.jsxs("button",{type:"button",className:"traffic__show-more",onClick:()=>m(C=>C+Mo),children:["Show ",Math.min(O,Mo)," more (",O," hidden)"]}):null]})]})]})}const Of=["amber","teal","coral","slate","olive","plum","rust","indigo","mint","sand","ash","jade"],$f=["fox","owl","lynx","crane","otter","wren","ibex","hare","newt","moth","seal","vole"];function Zc(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`${Of[t%Of.length]}-${$f[(t>>>4)%$f.length]}`}function el(){const e=lt(),t=e.status==="ready"?e.env.live:void 0,[n,r]=y.useState("");return y.useEffect(()=>{if(!t){r("");return}let s=!1;return t.instanceId().then(i=>{s||r(i)}),()=>{s=!0}},[t]),n}function VU(){const e=lt(),t=e.status==="ready"?e.env.live:void 0;return y.useCallback(async()=>t?t.exportState():null,[t])}function qU(){const e=lt(),t=e.status==="ready"?e.env.live:void 0;return y.useCallback(async n=>t?(await t.importState(n),!0):!1,[t])}function WU(){const e=lt(),t=e.status==="ready"?e.env.live:void 0,[n,r]=y.useState([]),s=y.useCallback(async()=>{if(!t){r([]);return}const l=await t.listStates();r(l.map(u=>u.name))},[t]);y.useEffect(()=>{s()},[s]);const i=y.useCallback(async l=>{t&&(await t.saveState(l),await s())},[t,s]),o=y.useCallback(async l=>{t&&await t.restoreState(l)},[t]),a=y.useCallback(async l=>{t&&(await t.deleteState(l),await s())},[t,s]);return{names:n,save:i,restore:o,remove:a}}function zU(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 HU(e){return e?{tab:"firestore",rest:e.split("/").filter(Boolean)}:null}function KU(e){const{provenance:t,identity:n}=zU(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:HU(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 GU(e,t=20){const n=[];for(let r=e.length-1;r>=0&&n.length<t;r--){const s=KU(e[r]);s&&n.push(s)}return n}const JU=20;function YU(e){Ae(e)}function Ln({target:e,className:t,children:n,title:r}){return c.jsx("a",{className:t,href:Ct(e),title:r,onClick:s=>{s.metaKey||s.ctrlKey||s.shiftKey||s.altKey||(s.preventDefault(),YU(e))},children:n})}function QU(){const e=Kt(),t=ls(),n=el();if(t.status==="loading"||e.status==="pending")return c.jsxs("div",{className:"studio-home__status","aria-label":"Sandbox status",children:[c.jsx("span",{className:"studio-chip studio-home__skeleton-chip","aria-hidden":"true"}),c.jsx("span",{className:"studio-chip studio-home__skeleton-chip","aria-hidden":"true"})]});const s=[];if(e.status==="ready"&&t.status!=="ready"&&s.push(c.jsxs("span",{className:"studio-chip",title:"In-page seeded sandbox — no server. Data resets on reload.",children:[c.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),"dev seed · in-page"]},"seed")),t.status==="ready"){const i=t.payload;s.push(c.jsxs(Ln,{className:"studio-chip",target:{tab:"settings"},title:"Persistence mode — manage in Settings.",children:[c.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),i.persist?"persisted to disk":"ephemeral"]},"persist")),i.rulesHash&&s.push(c.jsxs("span",{className:"studio-chip",title:"Hash of the rules this serve deployed to the sandbox.",children:[c.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),"rules ",i.rulesHash.slice(0,8)]},"rules"))}return n&&s.push(c.jsxs(Ln,{className:"studio-chip",target:{tab:"settings"},title:`Sandbox instance ${n} — maintenance lives in Settings.`,children:[c.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),Zc(n)]},"instance")),c.jsx("div",{className:"studio-home__status","aria-label":"Sandbox status",children:s})}function XU(e){return new Date(e).toLocaleTimeString(void 0,{hour12:!1})}function ZU(){const e=Jt(),t=y.useMemo(()=>GU(e,JU),[e]);return c.jsxs("section",{className:"studio-panel studio-home__feed","aria-label":"Live activity",children:[c.jsxs("header",{className:"studio-home__feed-head",children:[c.jsx("h2",{className:"studio-panel__title studio-home__feed-title",children:"Activity"}),c.jsx(Ln,{className:"studio-home__feed-all",target:{tab:"traffic"},children:"view all in Traffic →"})]}),t.length===0?c.jsx("p",{className:"studio-home__feed-empty",children:"No activity yet — writes, denials, and seeds show up here live."}):c.jsx("div",{className:"studio-home__feed-scroll",children:c.jsx("ol",{className:"studio-home__feed-list",children:t.map(n=>{const r=c.jsxs(c.Fragment,{children:[c.jsxs("span",{className:"studio-home__feed-ident","data-provenance":n.provenance,children:[c.jsx("span",{className:"studio-home__feed-dot","aria-hidden":"true"}),n.identity]}),c.jsx("span",{className:"studio-home__feed-summary","data-denied":n.denied?"true":void 0,children:n.summary}),c.jsx("time",{className:"studio-home__feed-time",dateTime:new Date(n.at).toISOString(),children:XU(n.at)})]});return c.jsx("li",{children:n.target?c.jsx(Ln,{className:"studio-home__feed-row",target:n.target,children:r}):c.jsx("span",{className:"studio-home__feed-row",children:r})},n.id)})})})]})}const eB=["firestore","auth","rtdb","storage","traffic"];function tB(){const e=Rt(),t=Jt(),n=y.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 c.jsx("div",{className:"studio-home__tiles",children:eB.map(r=>{const s=fn.find(i=>i.id===r);return s?c.jsxs(Ln,{className:"studio-card studio-home__tile",target:{tab:r},children:[c.jsxs("span",{className:"studio-home__tile-top",children:[c.jsx("span",{className:"studio-home__tile-label",children:s.label}),n[r]?c.jsx("span",{className:"studio-badge",children:n[r]}):null]}),c.jsx("span",{className:"studio-home__tile-desc",children:s.description})]},r):null})})}function nB(){const e=ls(),t=e.status==="ready",n=t&&!!e.payload.bridgeUrl,r=typeof window<"u"?window.location.origin:"",s=t?e.payload.rulesHash:null;return c.jsxs(c.Fragment,{children:[c.jsxs("section",{className:"studio-card studio-home__onboard","aria-label":"Connect your agent",children:[c.jsx("span",{className:"studio-home__tile-label",children:"Connect your agent"}),c.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."}),c.jsx("code",{className:"studio-home__snippet",children:n?`${r}/__pyric/mcp`:"pyric sandbox --bridge # then <url>/__pyric/mcp"})]}),c.jsxs("section",{className:"studio-card studio-home__onboard","aria-label":"Seed data",children:[c.jsx("span",{className:"studio-home__tile-label",children:"Seed data"}),c.jsx("span",{className:"studio-home__tile-desc",children:"Start from a fixture, or create documents by hand in the Firestore browser."}),c.jsx("code",{className:"studio-home__snippet",children:"pyric sandbox --seed seed.json"}),c.jsx(Ln,{className:"studio-home__onboard-link",target:{tab:"firestore"},children:"open Firestore →"})]}),c.jsxs("section",{className:"studio-card studio-home__onboard","aria-label":"Bring your rules",children:[c.jsx("span",{className:"studio-home__tile-label",children:"Bring your rules"}),s?c.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."]}):c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"studio-home__tile-desc",children:"Serve your repo's rules file and every denial becomes a debuggable event."}),c.jsxs("code",{className:"studio-home__snippet",children:["pyric.json: ",'{"rules":"firestore.rules"}']})]})]})]})}function rB(){const e=Rt(),t=Jt(),n=Kt(),r=e.status==="pending"||n.status==="pending",s=!r&&t.length===0&&(e.status!=="ready"||e.handles.listRootCollections().length===0);return c.jsxs("section",{className:"studio-surface studio-home","aria-label":"Home",children:[c.jsxs("div",{className:"studio-home__hero",children:[c.jsx("img",{className:"studio-home__hero-logo",src:"/__pyric/ui/pyric-logo.svg",alt:"","aria-hidden":"true"}),c.jsx("h1",{className:"studio-home__hero-title",children:"Firebase tooling for the agent era"})]}),c.jsx(Cy,{exposeFocus:Q0}),c.jsx(QU,{}),c.jsx("div",{className:"studio-home__body",children:r?c.jsxs("section",{className:"studio-panel studio-home__feed studio-home__skeleton","aria-hidden":"true",children:[c.jsx("div",{className:"studio-home__skeleton-row"}),c.jsx("div",{className:"studio-home__skeleton-row"}),c.jsx("div",{className:"studio-home__skeleton-row"})]}):s?c.jsx(nB,{}):c.jsxs(c.Fragment,{children:[c.jsx(ZU,{}),c.jsx(tB,{})]})})]})}function _e(e){const t=e.split("/").filter(Boolean);return t.length===0?"/":`/${t.join("/")}`}function bt(e){return _e(e).split("/").filter(Boolean)}function Ga(e,t){return _e([...bt(e),...t.split("/").filter(Boolean)].join("/"))}function sB(e){const t=bt(e);return t.length<=1?"/":`/${t.slice(0,-1).join("/")}`}function tl(e,t){const n=bt(e),r=bt(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 ab(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 o=ab(i);if(o===null){n=!0;continue}o!==i&&(n=!0),r[s]=o}return Object.keys(r).length===0?null:n?r:e}function iB(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 nl(e){return e===null||typeof e!="object"?!1:Object.keys(e).length>0}function cb(e){return e===null||typeof e!="object"?[]:Object.entries(e).sort(([t],[n])=>t.localeCompare(n,void 0,{numeric:!0}))}function lb(e,t){let n=e??null;for(const r of bt(t)){if(n===null||typeof n!="object")return null;n=n[r]??null}return n}function oB(e){return e==null?"null":Array.isArray(e)?"array":typeof e}function Ja(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((o,a)=>Ja(o,t[a]));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(o=>o in r&&Ja(n[o],r[o]))}function aB(e,t){const n=new Map,r=(s,i)=>{if(!nl(s)){n.set(i,["leaf",s??null]);return}const o=cb(s);n.set(i,["parent",o.map(([a])=>a)]);for(const[a,l]of o)r(l,Ga(i,a))};return r(e,_e(t)),n}function cB(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(/[?#].*$/,""),_e(t)}function lB(e){const t=bt(e);return t.map((n,r)=>({label:n,path:`/${t.slice(0,r+1).join("/")}`}))}const uB=["string","number","boolean","json"];function Pf(e){switch(typeof e){case"string":return"string";case"number":return"number";case"boolean":return"boolean";default:return"json"}}function dB(e,t){return t==="json"?JSON.stringify(e??null):e==null?"":String(e)}function fB(e){if(e.trim().length===0)return"Enter a key.";const t=e.match(/[.$#[\]/]/);return t?`Keys can't contain "${t[0]}".`:null}function hB(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 ub(e){return{path:_e(e),status:"loading",value:null,error:null,expanded:{},pages:{}}}function db(e,t){const n=tl(e.path,t);return n===null?null:lb(e.value,n)}function pB(e,t){const n=_e(t);return n===e.path||e.expanded[n]===!0}function mB(e,t,n){const r=cb(db(e,t)),s=Math.min(r.length,e.pages[_e(t)]??n);return{entries:r.slice(0,s),total:r.length,hiddenCount:r.length-s}}function Df(e,t){const n={};let r=!1;for(const[s,i]of Object.entries(e)){const o=tl(t.path,s);o!==null&&nl(lb(t.value,o))?n[s]=i:r=!0}return r?n:e}function fb(e,t){switch(t.type){case"navigate":{const n=_e(t.path);return n===e.path?e:ub(n)}case"value":{if(_e(t.path)!==e.path)return e;const n={...e,status:"live",value:ab(t.value),error:null};return n.expanded=Df(e.expanded,n),n.pages=Df(e.pages,n),n}case"error":return _e(t.path)!==e.path?e:{...e,status:"error",error:t.message};case"expand":{const n=_e(t.path);return n===e.path||e.expanded[n]?e:{...e,expanded:{...e.expanded,[n]:!0}}}case"collapse":{const n=_e(t.path);if(!e.expanded[n])return e;const r={...e.expanded};return delete r[n],{...e,expanded:r}}case"toggle":{const n=_e(t.path);return fb(e,{type:e.expanded[n]?"collapse":"expand",path:n})}case"show-more":{const n=_e(t.path),r=e.pages[n]??t.pageSize;return{...e,pages:{...e.pages,[n]:r+t.pageSize}}}}}const yB=50;function gB(e,t,n={}){const r=n.pageSize??yB,s=_e(t),[i,o]=y.useReducer(fb,s,ub),a=y.useMemo(()=>aB(i.value,i.path),[i.path,i.value]),l=Gc({scope:i.path,entries:a,equals:Ja,ready:i.status==="live"});i.path!==s&&o({type:"navigate",path:s}),y.useEffect(()=>{let g=!1;const b=e.subscribeValue(s,w=>{g||o({type:"value",path:s,value:w})},w=>{g||o({type:"error",path:s,message:w instanceof Error?w.message:String(w)})});return()=>{g=!0,b()}},[e,s]);const u=y.useCallback(g=>db(i,g),[i]),d=y.useCallback(g=>pB(i,g),[i]),h=y.useCallback(g=>mB(i,g,r),[i,r]),f=y.useCallback(g=>o({type:"toggle",path:g}),[]),p=y.useCallback(g=>o({type:"show-more",path:g,pageSize:r}),[r]),m=y.useCallback(g=>l.get(_e(g)),[l]);return y.useMemo(()=>({state:i,pageSize:r,valueAt:u,isExpanded:d,childrenAt:h,toggle:f,showMore:p,updateAt:m}),[i,r,u,d,h,f,p,m])}function bB({path:e,onNavigate:t,rootLabel:n="/",inputPrefix:r,className:s}){const i=_e(e),[o,a]=y.useState(!1),l=y.useRef(null);y.useEffect(()=>{o&&l.current?.select()},[o]);const u=f=>{f.preventDefault(),t(cB(l.current?.value??"")),a(!1)},d=()=>a(!1),h=lB(i);return c.jsx("nav",{className:s,"data-pyric-ui":"rtdb-path-bar","data-rtdb-editing":o?"":void 0,"aria-label":"Database path",children:o?c.jsxs("form",{"data-rtdb-path-form":!0,onSubmit:u,children:[r?c.jsx("span",{"data-rtdb-path-prefix":!0,children:r}):null,c.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})]}):c.jsxs(c.Fragment,{children:[c.jsxs("ol",{"data-rtdb-crumb-list":!0,children:[c.jsx("li",{"data-rtdb-crumb-item":!0,children:c.jsx("button",{type:"button","data-rtdb-crumb":!0,"data-rtdb-crumb-root":!0,"data-pyric-current":h.length===0?"":void 0,"aria-current":h.length===0?"page":void 0,onClick:()=>t("/"),children:n})}),h.map((f,p)=>{const m=p===h.length-1;return c.jsxs("li",{"data-rtdb-crumb-item":!0,children:[c.jsx("span",{"aria-hidden":!0,"data-rtdb-crumb-separator":!0,children:"/"}),c.jsx("button",{type:"button","data-rtdb-crumb":!0,"data-pyric-current":m?"":void 0,"aria-current":m?"page":void 0,onClick:()=>t(f.path),children:f.label})]},f.path)})]}),c.jsx("button",{type:"button","data-rtdb-path-edit":!0,"aria-label":"Edit path",title:"Edit path",onClick:()=>a(!0),children:c.jsx("svg",{"aria-hidden":!0,viewBox:"0 0 16 16",width:"12",height:"12",fill:"currentColor",children:c.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 wB({tree:e,api:t,onNavigate:n,rootLabel:r="/",className:s}){const{state:i}=e,o=bt(i.path),a=o.length===0?r:o[o.length-1];return c.jsx("div",{className:s,"data-pyric-ui":"rtdb-tree",children:i.status==="loading"?c.jsx("p",{"data-rtdb-loading":!0,children:"Loading…"}):i.status==="error"?c.jsx("p",{role:"alert","data-rtdb-error":!0,children:i.error}):c.jsx(hb,{tree:e,api:t,onNavigate:n,path:i.path,label:a,isViewRoot:!0})})}function hb({tree:e,api:t,onNavigate:n,path:r,label:s,isViewRoot:i}){const o=e.valueAt(r),a=nl(o),l=e.isExpanded(r),u=e.updateAt(r),[d,h]=y.useState(!1),[f,p]=y.useState(!1),[m,g]=y.useState(!1),[b,w]=y.useState(null),x=async(S,k)=>{try{await S(),w(null),k()}catch(N){w(N instanceof Error?N.message:String(N))}},v=()=>{h(!0),g(!1),a&&!l&&e.toggle(r)},_=a&&l?e.childrenAt(r):null;return c.jsxs("div",{"data-rtdb-node":!0,"data-rtdb-kind":a?"parent":"leaf","data-rtdb-view-root":i?"":void 0,"data-rtdb-expanded":a&&l?"":void 0,children:[c.jsxs("div",{"data-rtdb-row":!0,"data-pyric-update":u?.kind,"data-pyric-update-cycle":u?.cycle,children:[a&&!i?c.jsx("button",{type:"button","data-rtdb-caret":!0,"aria-expanded":l,"aria-label":l?"Collapse":"Expand",onClick:()=>e.toggle(r),children:c.jsx("svg",{"aria-hidden":!0,viewBox:"0 0 8 8",width:"8",height:"8",fill:"currentColor",children:c.jsx("path",{d:"M1 0l6 4-6 4z"})})}):c.jsx("span",{"aria-hidden":!0,"data-rtdb-caret-spacer":!0}),c.jsx("button",{type:"button","data-rtdb-key":!0,"aria-label":"Key name",onClick:()=>n?.(r),children:s}),a?null:c.jsxs(c.Fragment,{children:[c.jsx("span",{"aria-hidden":!0,"data-rtdb-sep":!0,children:":"}),c.jsx("button",{type:"button","data-rtdb-value":!0,"data-rtdb-type":oB(o),title:"Edit value",onClick:()=>{p(!0),g(!1)},children:iB(o)})]}),c.jsx("span",{"data-rtdb-actions":!0,children:m?c.jsxs("span",{"data-rtdb-confirm":!0,children:[c.jsxs("span",{"data-rtdb-confirm-label":!0,children:["Delete",a?" subtree":"","?"]}),c.jsx("button",{type:"button","data-rtdb-confirm-yes":!0,onClick:()=>void x(()=>t.remove(r),()=>g(!1)),children:"Delete"}),c.jsx("button",{type:"button","data-rtdb-confirm-no":!0,onClick:()=>g(!1),children:"Cancel"})]}):c.jsxs(c.Fragment,{children:[c.jsx("button",{type:"button","data-rtdb-action-add":!0,"aria-label":`Add child to ${Tf(r)}`,title:"Add child",onClick:v,children:"+"}),c.jsx("button",{type:"button","data-rtdb-action-delete":!0,"aria-label":`Delete ${Tf(r)}`,title:"Delete",onClick:()=>g(!0),children:"×"})]})})]}),b?c.jsx("p",{role:"alert","data-rtdb-error":!0,children:b}):null,f?c.jsx(Mf,{initialType:Pf(o),initialText:dB(o,Pf(o)),submitLabel:"Save",onCancel:()=>p(!1),onSubmit:S=>x(()=>t.set(r,S),()=>p(!1))}):null,d?c.jsx(Mf,{withKey:!0,initialType:"string",initialText:"",submitLabel:"Add",onCancel:()=>h(!1),onSubmit:(S,k)=>x(()=>t.set(Ga(r,k),S),()=>h(!1))}):null,_?c.jsxs("ul",{"data-rtdb-children":!0,children:[_.entries.map(([S])=>c.jsx("li",{children:c.jsx(hb,{tree:e,api:t,onNavigate:n,path:Ga(r,S),label:S})},S)),_.hiddenCount>0?c.jsx("li",{"data-rtdb-show-more-item":!0,children:c.jsxs("button",{type:"button","data-rtdb-show-more":!0,onClick:()=>e.showMore(r),children:["Show more (",_.hiddenCount," hidden)"]})}):null]}):null]})}function Tf(e){const t=bt(e);return t.length===0?"root":t[t.length-1]}function Mf({withKey:e,initialType:t,initialText:n,submitLabel:r,onSubmit:s,onCancel:i}){const o=y.useRef(null),a=y.useRef(null),[l,u]=y.useState(t),[d,h]=y.useState(null),f=m=>{m.preventDefault();const g=o.current?.value??"";if(e){const w=fB(g);if(w){h(w);return}}const b=hB(l,a.current?.value??"");if(!b.ok){h(b.error);return}h(null),s(b.value,e?g.trim():void 0)},p=m=>{m.key==="Escape"&&i()};return c.jsxs("form",{"data-rtdb-editor":!0,onSubmit:f,children:[e?c.jsx("input",{ref:o,"data-rtdb-editor-key":!0,"aria-label":"Child key",placeholder:"key",autoFocus:!0,onKeyDown:p,spellCheck:!1}):null,c.jsx("select",{"data-rtdb-editor-type":!0,"aria-label":"Value type",value:l,onChange:m=>u(m.currentTarget.value),onKeyDown:p,children:uB.map(m=>c.jsx("option",{value:m,children:m},m))}),l==="boolean"?c.jsxs("select",{ref:a,"data-rtdb-editor-value":!0,"aria-label":"Value",defaultValue:n.trim().toLowerCase()==="true"?"true":"false",onKeyDown:p,children:[c.jsx("option",{value:"true",children:"true"}),c.jsx("option",{value:"false",children:"false"})]}):c.jsx("input",{ref:a,"data-rtdb-editor-value":!0,"aria-label":"Value",placeholder:l==="json"?'{ "key": "value" }':"value",autoFocus:!e,defaultValue:n,onKeyDown:p,spellCheck:!1}),c.jsx("button",{type:"submit","data-rtdb-editor-save":!0,children:r}),c.jsx("button",{type:"button","data-rtdb-editor-cancel":!0,onClick:i,children:"Cancel"}),d?c.jsx("span",{role:"alert","data-rtdb-editor-error":!0,children:d}):null]})}const pb="rtdb";function vB(e){return e.tab!==pb?"/":_e(e.rest.join("/"))}function xB(e){return{tab:pb,rest:bt(e)}}function _B(){const e=y.useSyncExternalStore(Gt,()=>vB(Ke()),()=>"/"),t=y.useCallback(n=>{Ae(xB(n))},[]);return[e,t]}function SB(){const e=lt(),t=e.status==="ready"?e.env.live:void 0;return c.jsxs("section",{className:"studio-surface grid gap-4","aria-labelledby":"rtdb-title",children:[c.jsxs("div",{className:"studio-surface__intro",children:[c.jsx("p",{className:"studio-surface__eyebrow",children:"RTDB"}),c.jsx("h1",{id:"rtdb-title",className:"studio-surface__title",children:"RTDB"}),c.jsx("p",{className:"studio-surface__copy",children:"Browse and edit RTDB data in the shared sandbox."})]}),t?c.jsx(jB,{live:t}):c.jsx(kB,{})]})}function kB(){return c.jsxs("div",{className:"rounded-md border border-dashed border-line bg-panel p-8 text-center",children:[c.jsx("span",{className:"rounded-full border border-line px-3 py-1 text-xs uppercase tracking-wide text-muted",children:"Shared worker pending"}),c.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 jB({live:e}){const t=Zc(el()),n=y.useMemo(()=>({set:(r,s)=>e.setRtdbValue(r,s),remove:r=>e.deleteRtdbValue(r),subscribeValue:(r,s,i)=>e.subscribeRtdbValue(r,s,i)}),[e]);return c.jsx(EB,{api:n,instanceLabel:t?`${t}-sandbox`:"sandbox"})}function EB({api:e,instanceLabel:t}){const[n,r]=_B(),{viewRoot:s,missingTail:i,tree:o}=CB(e,n),a=y.useRef(null);return y.useEffect(()=>{if(s==="/")return;const l=a.current;l&&typeof l.scrollIntoView=="function"&&l.scrollIntoView({block:"nearest"})},[s]),c.jsxs("div",{className:"rtdb",ref:a,children:[c.jsx(bB,{className:"rtdb__pathbar",path:n,onNavigate:r,rootLabel:t,inputPrefix:t}),i?c.jsxs("p",{className:"rtdb__missing","data-rtdb-missing":"",children:["This path does not exist. Showing ",c.jsx("code",{children:s}),", the nearest path that does; ",c.jsx("code",{children:i})," is not in the database."]}):null,c.jsx(wB,{className:"rtdb__tree",tree:o,api:e,onNavigate:r,rootLabel:t})]})}function CB(e,t){const[n,r]=y.useState({requested:t,root:t}),s=n.requested===t?n:{requested:t,root:t};s!==n&&r(s);const i=s.root,o=gB(e,i),{path:a,status:l,value:u}=o.state;y.useEffect(()=>{a===i&&l==="live"&&u==null&&i!=="/"&&r({requested:t,root:sB(i)})},[a,l,u,i,t]);const d=i===t?null:tl(i,t);return{viewRoot:i,missingTail:d&&bt(d).length>0?d:null,tree:o}}function NB(){const e=Rt();return y.useCallback(async t=>{if(e.status!=="ready")throw new Error("No sandbox available to seed.");const n=e.handles.adminFirestore,r=e.firestoreApi?.doc??st,s=e.firestoreApi?.setDoc??Hs;let i=0;const o=[];for(const a of t)try{await s(r(n,a.path),a.data),i++}catch(l){o.push(`${a.path}: ${l instanceof Error?l.message:String(l)}`)}return{written:i,errors:o}},[e])}function RB(){const e=Rt();return y.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??xe.createUser;let s=0;const i=[];for(const o of t)try{await r(n,o.request),s++}catch(a){const l=o.request.uid??o.request.email??"<auto>";i.push(`${l}: ${a instanceof Error?a.message:String(a)}`)}return{created:s,errors:i}},[e])}function IB(){const e=Rt(),t=lt(),n=t.status==="ready"?t.env.live:void 0;return y.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 AB(){const e=IB(),t=NB(),n=RB(),r=Kt();return y.useCallback(async()=>{const s=await e();if(r.status==="ready"){const{applySeed:i,deploySeedRules:o}=await Wp(async()=>{const{applySeed:a,deploySeedRules:l}=await import("./seed.BO5CXcqE.js");return{applySeed:a,deploySeedRules:l}},__vite__mapDeps([3,1,4,2,5]));o(r.handles.sandbox),await i(r.handles)}else try{const i=await fetch("/__pyric/init.json").then(l=>l.ok?l.json():null),o=i?.seed;o&&await t(Object.entries(o).map(([l,u])=>({path:l,data:u})));const a=i?.authUsers;Array.isArray(a)&&await n(a.map(l=>({request:l})))}catch(i){s.errors.push(`reseed: ${i instanceof Error?i.message:String(i)}`)}return s},[e,t,n,r])}function OB(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 As(e,t,n=`${t}s`){return`${e} ${e===1?t:n}`}function $B(e){if(e===null)return"measuring…";const t=[];return e.collections&&t.push(As(e.collections,"collection")),e.users&&t.push(As(e.users,"user")),e.objects&&t.push(As(e.objects,"file")),e.rtdbKeys&&t.push(As(e.rtdbKeys,"RTDB key")),t.length?t.join(" · "):"empty — no data yet"}function Ki(){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 PB(){return c.jsxs("svg",{...Ki(),children:[c.jsx("path",{d:"M12 4v10"}),c.jsx("path",{d:"M8 10l4 4 4-4"}),c.jsx("path",{d:"M4 19h16"})]})}function DB(){return c.jsxs("svg",{...Ki(),children:[c.jsx("path",{d:"M12 14V4"}),c.jsx("path",{d:"M8 8l4-4 4 4"}),c.jsx("path",{d:"M4 19h16"})]})}function TB(){return c.jsxs("svg",{...Ki(),children:[c.jsx("circle",{cx:"7",cy:"6",r:"2.4"}),c.jsx("circle",{cx:"7",cy:"18",r:"2.4"}),c.jsx("circle",{cx:"17",cy:"8",r:"2.4"}),c.jsx("path",{d:"M7 8.4v7.2"}),c.jsx("path",{d:"M17 10.4c0 3-4 3.6-7 4.4"})]})}function MB(){return c.jsxs("svg",{...Ki(),children:[c.jsx("path",{d:"M4 5v5h5"}),c.jsx("path",{d:"M4.6 10a8 8 0 1 0 1.7-5.3"})]})}function Os({glyph:e,name:t,caption:n,disabled:r,danger:s,onClick:i}){return c.jsxs("button",{type:"button",className:"studio-sandbox__action","data-danger":s?"true":void 0,disabled:r,onClick:i,children:[c.jsxs("span",{className:"studio-sandbox__action-top",children:[e,c.jsx("span",{className:"studio-sandbox__action-name",children:t})]}),c.jsx("span",{className:"studio-sandbox__action-caption",children:n})]})}function LB(){const e=AB(),t=VU(),n=qU(),r=WU(),s=ls(),i=y.useRef(null),o=Zc(el()),[a,l]=y.useState(!1),[u,d]=y.useState(!1),[h,f]=y.useState(!1),[p,m]=y.useState(!1),[g,b]=y.useState(""),w=Ey(),{ensure:x}=w;y.useEffect(()=>x(),[x]);const v=OB(w.entries),_=$B(v),S=s.status==="ready"?s.payload.persist?"persisted to disk":"ephemeral":"in-page · resets on reload",k=async()=>{const E=await t();if(!E||typeof document>"u")return;const $=URL.createObjectURL(new Blob([E],{type:"application/json"})),C=document.createElement("a");C.href=$,C.download=`pyric-sandbox-${o||"export"}.json`,C.click(),URL.revokeObjectURL($)},N=async E=>{const $=E.target.files?.[0];if(E.target.value="",!!$&&!(typeof window<"u"&&!window.confirm("Import replaces all data in this sandbox. This cannot be undone. Continue?"))){d(!0);try{await n(await $.text())}finally{d(!1)}}},O=async()=>{f(!1),l(!0);try{await e()}finally{l(!1)}},P=async()=>{const E=g.trim();E&&(await r.save(E),b(""),m(!1))},R=async E=>{typeof window<"u"&&!window.confirm(`Restore saved state "${E}"? This replaces the current sandbox state.`)||await r.restore(E)},j=async E=>{typeof window<"u"&&!window.confirm(`Delete saved state "${E}"?`)||await r.remove(E)};return c.jsxs("section",{className:"studio-surface studio-settings","aria-labelledby":"settings-title",children:[c.jsxs("div",{className:"studio-surface__intro",children:[c.jsx("p",{className:"studio-surface__eyebrow",children:"Settings"}),c.jsx("h1",{id:"settings-title",className:"studio-surface__title",children:"Configuration and maintenance."}),c.jsx("p",{className:"studio-surface__copy",children:"Global controls live here so service surfaces can stay focused on their primary work."})]}),c.jsx("div",{className:"studio-settings__grid",children:c.jsxs("section",{className:"studio-panel studio-settings__panel","aria-labelledby":"settings-sandbox-title",children:[c.jsx("h2",{id:"settings-sandbox-title",className:"studio-panel__title",children:"Sandbox"}),c.jsxs("div",{className:"studio-sandbox__live","aria-label":"Sandbox contents",children:[c.jsx("span",{className:"studio-sandbox__instance mono",children:o||"local"}),c.jsx("span",{className:"studio-sandbox__inventory",children:_}),c.jsx("span",{className:"studio-sandbox__persist",children:S})]}),c.jsxs("div",{className:"studio-sandbox__actions",children:[c.jsx(Os,{glyph:c.jsx(PB,{}),name:"Export",caption:"Downloads all of this as one file.",onClick:()=>void k()}),c.jsx(Os,{glyph:c.jsx(DB,{}),name:u?"Importing…":"Import",caption:"A chosen file replaces everything here.",disabled:u,onClick:()=>i.current?.click()}),c.jsx(Os,{glyph:c.jsx(TB,{}),name:"Save state",caption:"Keeps a copy you can return to.",onClick:()=>m(E=>!E)}),c.jsx(Os,{glyph:c.jsx(MB,{}),name:a?"Resetting…":"Reset session",caption:"Everything returns to the seeded start.",disabled:a,danger:!0,onClick:()=>f(!0)})]}),c.jsx("input",{ref:i,type:"file",accept:"application/json,.json",className:"studio-settings__file",onChange:N}),p?c.jsxs("form",{className:"studio-sandbox__name-row",onSubmit:E=>{E.preventDefault(),P()},children:[c.jsx("input",{className:"studio-sandbox__name-input",type:"text",value:g,placeholder:"saved state name","aria-label":"Saved state name",autoFocus:!0,onChange:E=>b(E.target.value),onKeyDown:E=>{E.key==="Escape"&&(m(!1),b(""))}}),c.jsx("button",{type:"submit",className:"studio-button",disabled:!g.trim(),children:"Save"}),c.jsx("button",{type:"button",className:"studio-button",onClick:()=>{m(!1),b("")},children:"Cancel"})]}):null,h?c.jsxs("div",{className:"studio-sandbox__confirm",role:"alert",children:[c.jsx("span",{className:"studio-sandbox__confirm-copy",children:v&&_!=="empty — no data yet"?`This erases ${_}.`:"This erases everything in this sandbox."}),c.jsxs("span",{className:"studio-sandbox__confirm-actions",children:[c.jsx("button",{type:"button",className:"studio-button studio-button--danger",onClick:()=>void O(),children:"Erase and reseed"}),c.jsx("button",{type:"button",className:"studio-button",onClick:()=>f(!1),children:"Keep"})]})]}):null,r.names.length>0?c.jsx("div",{className:"studio-settings__saved-states",children:r.names.map(E=>c.jsxs("div",{className:"studio-settings__saved-state",children:[c.jsx("span",{className:"mono",children:E}),c.jsxs("span",{className:"studio-settings__saved-state-actions",children:[c.jsx("button",{type:"button",className:"studio-button",onClick:()=>void R(E),children:"Restore"}),c.jsx("button",{type:"button",className:"studio-button",onClick:()=>void j(E),children:"Delete"})]})]},E))}):c.jsx("p",{className:"studio-sandbox__saved-states-empty",children:"No saved states yet. Save state keeps this exact sandbox to come back to."})]})})]})}function $s(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 UB(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(o=>JSON.stringify(n[o])!==JSON.stringify(r[o]));if(i.length>0&&i.length<=3)return i.map(o=>`${o}: ${$s(n[o])} -> ${$s(r[o])}`).join(", ")}return`${$s(t.before)} -> ${$s(t.after)}`}function BB(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:UB(t),supported:t.qualification.supported}))}function FB(e){const t=e.mutation.events.find(o=>o.result==="allow"||o.result==="deny"||o.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.queryProof&&(r.queryProof=t.queryProof),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 VB="pyric:assurance-campaign",qB="pyric-assurance-v1",Ya=new Set;let Lf=!1,Uf;function Bf(e){for(const t of Ya)t(e)}function Ff(e){return!!e&&typeof e=="object"&&e.schema==="pyric.assurance.visualization.v1"&&typeof e.campaignId=="string"}function WB(){if(!(Lf||typeof document>"u")){Lf=!0,globalThis.addEventListener(VB,e=>{const t=e.detail;Ff(t)&&Bf(t)});try{Uf=new BroadcastChannel(qB),Uf.onmessage=e=>{Ff(e.data)&&Bf(e.data)}}catch{}}}function zB(e){return WB(),Ya.add(e),()=>Ya.delete(e)}function Lo(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 HB=[Lo({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"}}),Lo({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"}),Lo({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"}}})],v1=HB.map(e=>({...e,campaignId:"collaboration-local-v1-fixed",targetHash:"fnv1a32-a9f18f23",mutation:{...e.mutation,decision:"DENY",events:[]},stateDiff:void 0,classification:"no-counterexample"}));const Qa="pyric:assurance:campaigns",mb="pyric:assurance:campaign:";function KB(e){return!!e&&typeof e=="object"&&e.schema==="pyric.assurance.visualization.v1"&&typeof e.campaignId=="string"}function GB(){if(typeof sessionStorage>"u")return[];try{const e=JSON.parse(sessionStorage.getItem(Qa)??"[]");if(!Array.isArray(e))return[];const t=e.map(n=>sessionStorage.getItem(`${mb}${String(n)}`)).filter(n=>!!n).map(n=>JSON.parse(n)).filter(KB);return t.length,t}catch{return[]}}function JB(e){if(!(typeof sessionStorage>"u"))try{const t=JSON.parse(sessionStorage.getItem(Qa)??"[]"),n=Array.isArray(t)?t.map(String):[];n.includes(e.campaignId)||n.push(e.campaignId),sessionStorage.setItem(Qa,JSON.stringify(n)),sessionStorage.setItem(`${mb}${e.campaignId}`,JSON.stringify(e))}catch{}}function YB(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 QB(){const[e,t]=y.useState(GB);return y.useEffect(()=>{const r=zB(s=>{JB(s),t(i=>YB(i,s))});return()=>{r()}},[]),e}function XB(e,t){return e!==t?"assurance-verdict--mismatch":t==="ALLOW"?"assurance-verdict--allow":"assurance-verdict--deny"}function ZB(e){return e.replaceAll("-"," ")}function Vf({value:e}){return c.jsx("pre",{className:"assurance-evidence__json",children:JSON.stringify(e,null,2)})}function e1(){return c.jsxs("section",{className:"assurance-empty","aria-labelledby":"assurance-empty-title",children:[c.jsx("p",{className:"assurance-surface__eyebrow",children:"Local authorization assurance"}),c.jsx("h1",{id:"assurance-empty-title",children:"No campaign in this Studio session"}),c.jsx("p",{children:"Campaigns appear here as the local assurance tools map actors, run controls, and test explicit security invariants."}),c.jsx("span",{className:"assurance-local-state",children:"Pyric sandboxes only | network off"})]})}function qf({attachment:e}){return e?c.jsxs("div",{className:"assurance-attachment","aria-label":"Attached sandbox inventory",children:[c.jsxs("span",{children:[c.jsx("strong",{children:e.source.origin}),"read-only clone"]}),c.jsxs("span",{children:[c.jsx("strong",{children:e.inventory.firestoreDocuments}),"Firestore docs"]}),c.jsxs("span",{children:[c.jsx("strong",{children:e.inventory.authUsers}),"Auth users"]}),c.jsxs("span",{children:[c.jsx("strong",{children:e.inventory.rtdbPresent?"present":"empty"}),"RTDB"]})]}):null}function t1({campaigns:e}){const t=QB(),n=e??t,r=Ke().query,[s,i]=y.useState(r.campaign??n.find(v=>v.report)?.campaignId??n[0]?.campaignId??""),o=n.find(v=>v.campaignId===s)??n[0],a=y.useMemo(()=>o?.report?BB(o.report):[],[o]),[l,u]=y.useState(r.probe??a[0]?.id??"");if(y.useEffect(()=>{!s&&n[0]&&i(n[0].campaignId)},[s,n]),y.useEffect(()=>{a.some(v=>v.id===l)||u(a[0]?.id??"")},[a,l]),!o)return c.jsx(e1,{});const d=o.context?.attachment,h=o.report;if(!h)return c.jsxs("section",{className:"assurance-empty","aria-labelledby":"assurance-mapped-title",children:[c.jsx("p",{className:"assurance-surface__eyebrow",children:o.campaignId}),c.jsx("h1",{id:"assurance-mapped-title",children:"Campaign mapped, awaiting its first run"}),c.jsxs("p",{children:[o.observations.length," known-good operation(s) and"," ",o.probes.length," probe(s) are available."]}),c.jsx(qf,{attachment:d}),d?.coverageGaps.length?c.jsx("ul",{className:"assurance-coverage-gaps","aria-label":"Attachment coverage gaps",children:d.coverageGaps.map(v=>c.jsxs("li",{children:[c.jsx("code",{children:v.service}),v.reason]},v.code))}):null,c.jsx("span",{className:"assurance-local-state",children:"Pyric sandboxes only | network off"})]});const f=a.find(v=>v.id===l)??a[0],p=h.results.find(v=>v.probeId===f?.id),m=p?FB(p):null,g=o.verifications?.at(-1),b=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 w(v){i(v);const S=n.find(k=>k.campaignId===v)?.report?.results[0]?.probeId??"";u(S),qr({tab:"assurance",query:{campaign:v,probe:S||void 0}})}function x(v){u(v.id),qr({tab:"assurance",query:{campaign:o.campaignId,probe:v.id}})}return c.jsxs("section",{className:"assurance-surface","aria-labelledby":"assurance-title",children:[c.jsxs("header",{className:"assurance-surface__header",children:[c.jsxs("div",{children:[c.jsx("p",{className:"assurance-surface__eyebrow",children:"Local authorization assurance"}),c.jsx("h1",{id:"assurance-title",children:o.campaignId})]}),c.jsxs("div",{className:"assurance-surface__controls",children:[n.length>1?c.jsxs("label",{children:[c.jsx("span",{children:"Campaign"}),c.jsx("select",{value:o.campaignId,onChange:v=>w(v.target.value),children:n.map(v=>c.jsx("option",{value:v.campaignId,children:v.campaignId},v.campaignId))})]}):null,c.jsx("span",{className:"assurance-local-state",children:"Pyric sandboxes only | network off"})]})]}),c.jsx(qf,{attachment:d}),c.jsxs("div",{className:"assurance-summary","aria-label":"Campaign summary",children:[c.jsxs("div",{children:[c.jsx("span",{children:"Controls"}),c.jsxs("strong",{children:[h.summary.controlsPassed,"/",h.summary.probes]})]}),c.jsxs("div",{children:[c.jsx("span",{children:"Counterexamples"}),c.jsx("strong",{children:h.summary.localCounterexamples})]}),c.jsxs("div",{children:[c.jsx("span",{children:"Candidate signals"}),c.jsx("strong",{children:h.summary.candidateSignals})]}),c.jsxs("div",{children:[c.jsx("span",{children:"Engine gaps"}),c.jsx("strong",{children:h.summary.engineGaps})]}),c.jsxs("div",{children:[c.jsx("span",{children:"Coverage gaps"}),c.jsx("strong",{children:d?.coverageGaps.length??0})]})]}),g?c.jsxs("div",{className:`assurance-verification-band assurance-verification-band--${b?"passed":"failed"}`,role:"status",children:[c.jsx("strong",{children:b?"Candidate rules verified":"Candidate rules need review"}),c.jsxs("span",{children:[g.summary.controlsPassed,"/",g.summary.probes," ","controls preserved"," | ",g.summary.noCounterexamples,"/",g.summary.probes," negative cases denied"]}),c.jsx("code",{children:g.campaignId})]}):null,d?.coverageGaps.length?c.jsxs("div",{className:"assurance-coverage-band",children:[c.jsxs("strong",{children:[d.coverageGaps.length," attachment gap(s)"]}),c.jsx("span",{children:d.coverageGaps.map(v=>`${v.service}: ${v.reason}`).join(" ")})]}):null,c.jsxs("div",{className:"assurance-workspace",children:[c.jsxs("section",{className:"assurance-matrix","aria-labelledby":"assurance-matrix-title",children:[c.jsxs("div",{className:"assurance-section-heading",children:[c.jsx("h2",{id:"assurance-matrix-title",children:"Expected and observed access"}),c.jsx("span",{children:h.targetHash})]}),c.jsxs("div",{className:"assurance-table",role:"table",children:[c.jsxs("div",{className:"assurance-table__header",role:"row",children:[c.jsx("span",{role:"columnheader",children:"Operation"}),c.jsx("span",{role:"columnheader",children:"Actor"}),c.jsx("span",{role:"columnheader",children:"Expected"}),c.jsx("span",{role:"columnheader",children:"Observed"}),c.jsx("span",{role:"columnheader",children:"Impact"})]}),a.map(v=>c.jsxs("button",{type:"button",className:"assurance-table__row","aria-pressed":v.id===f?.id,onClick:()=>x(v),role:"row",children:[c.jsxs("span",{role:"cell",children:[c.jsx("small",{children:v.service}),v.operation]}),c.jsx("span",{role:"cell",children:v.actor}),c.jsx("span",{role:"cell",className:`assurance-verdict ${v.expected==="ALLOW"?"assurance-verdict--allow":"assurance-verdict--deny"}`,children:v.expected}),c.jsx("span",{role:"cell",className:`assurance-verdict ${XB(v.expected,v.observed)}`,children:v.observed}),c.jsx("span",{role:"cell",children:v.impact})]},v.id))]})]}),p?c.jsxs("aside",{className:"assurance-inspector","aria-labelledby":"assurance-inspector-title",children:[c.jsxs("div",{className:"assurance-section-heading",children:[c.jsxs("div",{children:[c.jsx("span",{className:`assurance-classification assurance-classification--${p.classification}`,children:ZB(p.classification)}),c.jsx("h2",{id:"assurance-inspector-title",children:p.probeId})]}),c.jsx("span",{children:p.actorEvidence.reachability})]}),c.jsxs("dl",{className:"assurance-facts",children:[c.jsxs("div",{children:[c.jsx("dt",{children:"Invariant"}),c.jsx("dd",{children:p.invariant.statement})]}),c.jsxs("div",{children:[c.jsx("dt",{children:"Mutation"}),c.jsx("dd",{children:p.mutationSpec.description})]}),c.jsxs("div",{children:[c.jsx("dt",{children:"Actor"}),c.jsxs("dd",{children:[p.actorEvidence.uid??p.actorEvidence.actorId," ","via ",p.actorEvidence.acquisition]})]}),c.jsxs("div",{children:[c.jsx("dt",{children:"Fidelity"}),c.jsx("dd",{children:p.qualification.supported?"Supported for this probe":"Engine gap"})]})]}),p.qualification.requirements.some(v=>!v.supported)?c.jsx("ul",{className:"assurance-gaps",children:p.qualification.requirements.filter(v=>!v.supported).map(v=>c.jsxs("li",{children:[c.jsx("code",{children:v.id}),v.reason]},v.id))}):null,p.stateDiff?c.jsxs("section",{className:"assurance-evidence","aria-labelledby":"assurance-state-title",children:[c.jsx("h3",{id:"assurance-state-title",children:"State evidence"}),c.jsxs("div",{className:"assurance-evidence__diff",children:[c.jsxs("div",{children:[c.jsx("span",{children:"Before"}),c.jsx(Vf,{value:p.stateDiff.before})]}),c.jsxs("div",{children:[c.jsx("span",{children:"After"}),c.jsx(Vf,{value:p.stateDiff.after})]})]})]}):null,m?c.jsxs("section",{className:"assurance-rule-decision","aria-labelledby":"assurance-rule-title",children:[c.jsx("h3",{id:"assurance-rule-title",children:"Rule decision"}),c.jsx($g,{denial:m})]}):c.jsx("p",{className:"assurance-no-decision",children:"This service recorded operation and state evidence but no canonical rule-decision event."})]}):null]})]})}function Wf(){return Mi()}function yb(){return`${Mi()}docs`}function zf(e){return t=>{t.metaKey||t.ctrlKey||t.shiftKey||t.altKey||(t.preventDefault(),e())}}function n1(){const[e,t]=y.useState(!1);return y.useEffect(()=>{let n=!0;return fetch(`${yb()}/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 r1({id:e}){const t=H0(e),n=Kt(),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"),c.jsxs("section",{className:"studio__placeholder","aria-labelledby":`route-${t.id}`,children:[c.jsx("p",{className:"studio__placeholder-eyebrow",children:"Surface"}),c.jsx("h2",{id:`route-${t.id}`,className:"studio__placeholder-title",children:t.label}),c.jsx("p",{className:"studio__placeholder-blurb",children:t.description}),c.jsx("div",{className:"studio__placeholder-meta",children:r.map(s=>c.jsx("span",{children:s},s))})]})}function s1({id:e}){switch(e){case"home":return c.jsx(rB,{});case"firestore":return c.jsx(yM,{});case"auth":return c.jsx(SM,{});case"storage":return c.jsx(gM,{});case"rtdb":return c.jsx(SB,{});case"traffic":return c.jsx(FU,{});case"assurance":return c.jsx(t1,{});case"settings":return c.jsx(LB,{});default:return c.jsx(r1,{id:e})}}function i1(){const[e,t]=Y0(z0,"home"),n=u=>t(u),[r,s]=y.useState(!1),i=n1(),[o]=y.useState(()=>wU());y.useEffect(()=>{if(!o.open)return;const u={view:"listeners"};o.listenerId!==void 0&&(u.listener=o.listenerId),o.targetPrefix!==void 0&&(u.target=o.targetPrefix),qr({tab:"traffic",query:u})},[]);const a=e==="home";y.useEffect(()=>{const u=d=>{if(Z0(d)){if(r){d.preventDefault(),s(!1);return}if(a){X0()&&d.preventDefault();return}d.preventDefault(),s(!0)}};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[a,r]),y.useEffect(()=>{a&&s(!1)},[a]),y.useEffect(()=>{document.querySelector('.studio__rail [aria-current="page"]')?.scrollIntoView({block:"nearest",inline:"center"})},[e]);const l=fn.filter(u=>u.id!=="home");return c.jsxs("div",{className:"studio","data-surface":e,children:[c.jsxs("header",{className:"studio__chrome",children:[c.jsx("div",{className:"studio__bar",children:c.jsxs("div",{className:"studio__chrome-inner",children:[c.jsxs("nav",{className:"studio__nav","aria-label":"Site",children:[c.jsx("a",{className:"studio__brand",href:Wf(),"aria-label":"Pyric",children:"pyric"}),c.jsx("a",{className:"studio__nav-tab",href:Wf(),children:"Home"}),i?c.jsx("a",{className:"studio__nav-tab",href:yb(),children:"Docs"}):null,c.jsx("a",{className:"studio__nav-tab",href:Ct({tab:"home"}),"aria-current":e==="home"?"page":!0,onClick:zf(()=>n("home")),children:"Studio"})]}),c.jsx(aP,{})]})}),c.jsx("nav",{className:"studio__rail","aria-label":"Studio",children:c.jsx("div",{className:"studio__chrome-inner",children:c.jsx("div",{className:"studio__nav",children:l.map(u=>c.jsx("a",{className:"studio__nav-tab",href:Ct({tab:u.id}),"aria-current":u.id===e?"page":void 0,onClick:zf(()=>n(u.id)),children:u.label},u.id))})})})]}),c.jsx("main",{className:"studio__content","data-surface":e,children:c.jsx("div",{className:"studio__surface-slot","data-active":"true",children:c.jsx(s1,{id:e})})}),r?c.jsx(OO,{onClose:()=>s(!1)}):null]})}function o1(){return c.jsx(B0,{children:c.jsx(QE,{children:c.jsx(D0,{mode:"local",children:c.jsx(i1,{})})})})}function x1(){return c.jsx(y.StrictMode,{children:c.jsx(o1,{})})}export{x1 as S,w1 as a,WS as b,Or as r,xe as s,rE as u};
|