@pyric/cli 0.1.0-alpha.17 → 0.1.0-alpha.19
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/README.md +34 -3
- package/README.md.orig +5 -1
- package/dist/bridge/server/bridge.d.ts.map +1 -1
- package/dist/bridge/server/bridge.js +4 -2
- package/dist/bridge/server/bridge.js.map +1 -1
- package/dist/bridge/server/mcp-contract.d.ts +2 -2
- package/dist/bridge/server/mcp-contract.d.ts.map +1 -1
- package/dist/bridge/server/mcp-contract.js +3 -0
- package/dist/bridge/server/mcp-contract.js.map +1 -1
- package/dist/bridge/server/peer.d.ts.map +1 -1
- package/dist/bridge/server/peer.js +1 -0
- package/dist/bridge/server/peer.js.map +1 -1
- package/dist/cli/index.d.ts +1 -0
- package/dist/cli/index.d.ts.map +1 -1
- package/dist/cli/index.js +3 -0
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/mcp-proxy.d.ts.map +1 -1
- package/dist/cli/mcp-proxy.js.map +1 -1
- package/dist/cli/rules.d.ts +1 -0
- package/dist/cli/rules.d.ts.map +1 -1
- package/dist/cli/rules.js +18 -4
- package/dist/cli/rules.js.map +1 -1
- package/dist/cli/serve.d.ts.map +1 -1
- package/dist/cli/serve.js +1 -0
- package/dist/cli/serve.js.map +1 -1
- package/dist/cli/service-command-records/storage-rules-resolve.d.ts +4 -0
- package/dist/cli/service-command-records/storage-rules-resolve.d.ts.map +1 -0
- package/dist/cli/service-command-records/storage-rules-resolve.js +3 -0
- package/dist/cli/service-command-records/storage-rules-resolve.js.map +1 -0
- package/dist/cli/service-commands.generated.d.ts +3 -0
- package/dist/cli/service-commands.generated.d.ts.map +1 -1
- package/dist/cli/service-commands.generated.js +2 -0
- package/dist/cli/service-commands.generated.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/functions-rtdb/child.d.ts +1 -0
- package/dist/functions-rtdb/child.d.ts.map +1 -1
- package/dist/functions-rtdb/child.js +11 -1
- package/dist/functions-rtdb/child.js.map +1 -1
- package/dist/functions-rtdb/development-runtime.d.ts +1 -0
- package/dist/functions-rtdb/development-runtime.d.ts.map +1 -1
- package/dist/functions-rtdb/development-runtime.js +1 -0
- package/dist/functions-rtdb/development-runtime.js.map +1 -1
- package/dist/remote/index.d.ts.map +1 -1
- package/dist/remote/index.js +5 -3
- package/dist/remote/index.js.map +1 -1
- package/dist/serve/rules.d.ts +3 -3
- package/dist/serve/rules.d.ts.map +1 -1
- package/dist/serve/rules.js +13 -5
- package/dist/serve/rules.js.map +1 -1
- package/dist/serve/runtime/chip.d.ts.map +1 -1
- package/dist/serve/runtime/chip.js +24 -3
- package/dist/serve/runtime/chip.js.map +1 -1
- package/dist/serve/runtime/status.d.ts +1 -0
- package/dist/serve/runtime/status.d.ts.map +1 -1
- package/dist/serve/runtime/status.js +71 -13
- package/dist/serve/runtime/status.js.map +1 -1
- package/dist/serve/site-ui/_astro/{RulesCodeEditor.CzwHdCi9.js → RulesCodeEditor.Bl-XMkhD.js} +1 -1
- package/dist/serve/site-ui/_astro/_example_.B9DG9HLJ.css +1 -0
- package/dist/serve/site-ui/_astro/_slug_.CupVK4TM.css +1 -0
- package/dist/serve/site-ui/_astro/_studio_.CfxiQWkk.css +1 -0
- package/dist/serve/site-ui/_astro/app.Ce3MTLQm.js +1 -0
- package/dist/serve/site-ui/_astro/app.taqzyjD0.js +11 -0
- package/dist/serve/site-ui/_astro/chess-showcase.Dh5D8kqe.js +354 -0
- package/dist/serve/site-ui/_astro/{example-runtime.D79PnoSk.js → example-runtime.CuyAjjiG.js} +2 -26
- package/dist/serve/site-ui/_astro/sandbox-controls.BP4M5f1M.js +1169 -0
- package/dist/serve/site-ui/_astro/seed.CSUkloMi.js +20 -0
- package/dist/serve/site-ui/_astro/writes.C57paAj2.js +99 -0
- package/dist/serve/site-ui/auth/index.html +2 -2
- package/dist/serve/site-ui/docs/_rhythm/index.html +1 -1
- package/dist/serve/site-ui/docs/agent/set-up-your-agent/index.html +73 -13
- package/dist/serve/site-ui/docs/agent/set-up-your-agent.md +77 -11
- 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 +1 -1
- package/dist/serve/site-ui/docs/app-compat/index.html +1 -1
- package/dist/serve/site-ui/docs/auth-compat/index.html +1 -1
- package/dist/serve/site-ui/docs/build/ai-logic/index.html +19 -2
- package/dist/serve/site-ui/docs/build/ai-logic.md +28 -0
- package/dist/serve/site-ui/docs/build/authentication/index.html +1 -1
- package/dist/serve/site-ui/docs/build/cloud-firestore/index.html +30 -52
- package/dist/serve/site-ui/docs/build/cloud-firestore.md +40 -36
- package/dist/serve/site-ui/docs/build/cloud-messaging/index.html +1 -1
- package/dist/serve/site-ui/docs/build/cloud-storage/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 +22 -7
- package/dist/serve/site-ui/docs/conformance-scores.md +20 -5
- 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 +645 -249
- package/dist/serve/site-ui/docs/examples/chess.md +45 -16
- package/dist/serve/site-ui/docs/examples/index.html +2 -2
- package/dist/serve/site-ui/docs/firestore-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/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/start-building/index.html +43 -5
- package/dist/serve/site-ui/docs/get-started/start-building.md +34 -3
- package/dist/serve/site-ui/docs/get-started/vite/index.html +1 -1
- package/dist/serve/site-ui/docs/index.json +66 -26
- 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/overview/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-database-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-messaging-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-app-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-auth-reference-api/index.html +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-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-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-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-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 +1 -1
- package/dist/serve/site-ui/docs/pyric-database-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-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-rules-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-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-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 -10
- package/dist/serve/site-ui/docs/pyric-ui-rules-reference-api.md +0 -9
- 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/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/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/storage-rules-stdlib-research/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 +2 -1
- package/dist/serve/site-ui/docs/tutorial.md +2 -0
- package/dist/serve/site-ui/examples/chess/index.html +2 -2
- package/dist/serve/site-ui/firestore/index.html +2 -2
- package/dist/serve/site-ui/index.html +2 -2
- package/dist/serve/site-ui/llms.txt +2 -2
- package/dist/serve/site-ui/rtdb/index.html +2 -2
- package/dist/serve/site-ui/settings/index.html +2 -2
- package/dist/serve/site-ui/storage/index.html +2 -2
- package/dist/serve/site-ui/traffic/index.html +2 -2
- package/dist/serve/vite-functions-development.d.ts.map +1 -1
- package/dist/serve/vite-functions-development.js +1 -0
- package/dist/serve/vite-functions-development.js.map +1 -1
- package/dist/serve/vite-rules-source.d.ts.map +1 -1
- package/dist/serve/vite-rules-source.js +28 -7
- package/dist/serve/vite-rules-source.js.map +1 -1
- package/package.json +4 -4
- package/src/bridge/server/bridge.ts +5 -2
- package/src/bridge/server/mcp-contract.ts +3 -0
- package/src/bridge/server/peer.ts +2 -1
- package/src/cli/index.ts +3 -0
- package/src/cli/mcp-proxy.ts +6 -7
- package/src/cli/rules.ts +31 -4
- package/src/cli/serve.ts +1 -0
- package/src/cli/service-command-records/storage-rules-resolve.ts +4 -0
- package/src/cli/service-commands.generated.ts +2 -0
- package/src/conformance/.generated/conformance-docs.ts +1 -1
- package/src/functions-rtdb/child.ts +12 -1
- package/src/functions-rtdb/development-runtime.ts +2 -0
- package/src/remote/index.ts +7 -5
- package/src/serve/rules.ts +15 -5
- package/src/serve/runtime/chip.ts +24 -3
- package/src/serve/runtime/status.ts +76 -13
- package/src/serve/vite-functions-development.ts +1 -0
- package/src/serve/vite-rules-source.ts +29 -7
- package/dist/serve/site-ui/_astro/_example_.jevZ7OdV.css +0 -1
- package/dist/serve/site-ui/_astro/_slug_.BoKXYrnu.css +0 -1
- package/dist/serve/site-ui/_astro/_studio_.B6b_G1ev.css +0 -1
- package/dist/serve/site-ui/_astro/app.bnmVTkIY.js +0 -11
- package/dist/serve/site-ui/_astro/app.t6u-adB_.js +0 -1
- package/dist/serve/site-ui/_astro/chess-showcase.kC8dXLKY.js +0 -1
- package/dist/serve/site-ui/_astro/chess-source-explorer.C5k9c5yK.js +0 -1
- package/dist/serve/site-ui/_astro/chess-v2.CFHmd3UL.js +0 -354
- package/dist/serve/site-ui/_astro/index.DzVde04M.js +0 -1
- package/dist/serve/site-ui/_astro/jsx-runtime.D_zvdyIk.js +0 -9
- package/dist/serve/site-ui/_astro/reads.BYBRLbsE.js +0 -1
- package/dist/serve/site-ui/_astro/sandbox-controls.C9Aaazt8.js +0 -1252
- package/dist/serve/site-ui/_astro/seed.DANAIyRw.js +0 -20
- package/dist/serve/site-ui/examples/firestore-first-write/index.html +0 -2
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["_astro/seed.CSUkloMi.js","_astro/sandbox-controls.BP4M5f1M.js","_astro/writes.C57paAj2.js","_astro/index.DBy5LfQW.js","_astro/index.DNyk7q8W.js","_astro/RulesCodeEditor.Bl-XMkhD.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{r as wa,e as Re,m as vn,d as xa,f as il,g as al,h as ol,i as cl,j as o,p as ll,k as ul,l as dl,n as fl,R as ke,o as hl,q as ks,t as ja,S as pl,Z as ka,u as ml,v as yl,w as bl,x as gl,y as vl,z as wl,A as xl,B as wn,C as jl,D as kl,E as Sa,F as Sl,T as ut}from"./sandbox-controls.BP4M5f1M.js";import{r as h}from"./index.DBy5LfQW.js";import{m as Kr,c as Hr,S as _l,v as El,a as Cl,b as Ie,t as Fe,f as _a,e as xn,r as Ss,h as Gr,j as Ea,k as Jr,u as ir,l as Nl,n as jn,o as Rl,p as Al,q as Il,w as _s,x as Dl,y as Pl,A as Es,F as Cs,z as dt,d as Le,B as _t,s as en,C as Ca,D as Ns,E as ar,G as $l,g as Na,H as Ra,I as Ol,J as Ml,i as Ul,K as it,L as kn}from"./writes.C57paAj2.js";import{r as Tl}from"./index.DNyk7q8W.js";const qe={maxExpressionLength:256,maxStringLiteralLength:1024,maxAstDepth:16},Bl=["serverTimestamp","increment","arrayUnion","arrayRemove","deleteField"],Ll={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 Fl(e){return Bl.includes(e)}class Z extends Error{code="invalid-argument";pos;constructor(t,n){super(t),this.name="ExpressionLexError",this.pos=n}}class ye extends Error{code="invalid-argument";pos;constructor(t,n){super(t),this.name="ExpressionParseError",this.pos=n}}const Vl={"(":"lparen",")":"rparen","[":"lbracket","]":"rbracket",",":"comma",".":"dot","?":"question",":":"colon","+":"plus","-":"minus","*":"star","/":"slash","%":"percent"},ql={true:"true",false:"false",null:"null"};function Wl(e){if(e.length>qe.maxExpressionLength)throw new Z(`expression exceeds ${qe.maxExpressionLength}-character cap (got ${e.length})`,F(qe.maxExpressionLength));const t=[];let n=0;for(;n<e.length;){const r=n,s=e[n];if(s===" "||s===" "||s==="\r"||s===`
|
|
3
|
+
`){n+=1;continue}if(s==='"'||s==="'"){const{token:a,next:c}=Hl(e,n,s);if(t.push(a),n=c,n<=r)throw new Z("lexer stalled on string",F(r));continue}if(s>="0"&&s<="9"){const{token:a,next:c}=Kl(e,n);if(t.push(a),n=c,n<=r)throw new Z("lexer stalled on number",F(r));continue}if(Sn(s)){const{token:a,next:c}=zl(e,n);t.push(a),n=c;continue}if(s==="$"){const{token:a,next:c}=Rs(e,n,"$","reference");t.push(a),n=c;continue}if(s==="@"){const{token:a,next:c}=Rs(e,n,"@","sentinel");t.push(a),n=c;continue}if(s==="="&&e[n+1]==="="){t.push({kind:"eq",pos:F(n)}),n+=2;continue}if(s==="!"&&e[n+1]==="="){t.push({kind:"neq",pos:F(n)}),n+=2;continue}if(s==="<"){e[n+1]==="="?(t.push({kind:"lte",pos:F(n)}),n+=2):(t.push({kind:"lt",pos:F(n)}),n+=1);continue}if(s===">"){e[n+1]==="="?(t.push({kind:"gte",pos:F(n)}),n+=2):(t.push({kind:"gt",pos:F(n)}),n+=1);continue}if(s==="&"){if(e[n+1]!=="&")throw new Z("unexpected '&' (did you mean '&&'?)",F(n));t.push({kind:"and",pos:F(n)}),n+=2;continue}if(s==="|"){if(e[n+1]!=="|")throw new Z("unexpected '|' (did you mean '||'?)",F(n));t.push({kind:"or",pos:F(n)}),n+=2;continue}if(s==="!"){t.push({kind:"bang",pos:F(n)}),n+=1;continue}if(s==="=")throw new Z("unexpected '=' (did you mean '=='?)",F(n));const i=Vl[s];if(i){t.push({kind:i,pos:F(n)}),n+=1;continue}throw new Z(`unexpected character ${JSON.stringify(s)}`,F(n))}return t.push({kind:"eof",pos:F(e.length)}),t}function F(e){return{offset:e,column:e+1}}function Sn(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"||e==="_"}function Aa(e){return Sn(e)||e>="0"&&e<="9"}function zl(e,t){let n=t+1;for(;n<e.length&&Aa(e[n]);)n+=1;const r=e.slice(t,n),s=ql[r];return s?{token:{kind:s,pos:F(t)},next:n}:{token:{kind:"identifier",pos:F(t),value:r},next:n}}function Rs(e,t,n,r){const s=t+1;if(s>=e.length||!Sn(e[s]))throw new Z(`expected identifier after '${n}'`,F(t));let i=s+1;for(;i<e.length&&Aa(e[i]);)i+=1;const a=e.slice(s,i);return{token:{kind:r,pos:F(t),value:a},next:i}}function Kl(e,t){let n=t;const r=e[n];if(n+=1,r==="0"){if(n<e.length&&e[n]>="0"&&e[n]<="9")throw new Z("leading zeros are not allowed in number literals",F(t))}else for(;n<e.length&&e[n]>="0"&&e[n]<="9";)n+=1;let s=!1;if(n<e.length&&e[n]==="."){const c=e[n+1];if(c!==void 0&&c>="0"&&c<="9")for(s=!0,n+=1;n<e.length&&e[n]>="0"&&e[n]<="9";)n+=1;else if(!(c!==void 0&&Sn(c)))throw new Z("expected digit after '.' in number literal",F(n))}const i=e.slice(t,n),a=Number.parseFloat(i);if(!Number.isFinite(a))throw new Z(`numeric literal '${i}' is not finite`,F(t));if(!s&&!Number.isSafeInteger(a))throw new Z(`integer literal '${i}' exceeds safe integer range`,F(t));return{token:{kind:"number",pos:F(t),value:a},next:n}}function Hl(e,t,n){let r=t+1,s="";for(;r<e.length;){const i=e[r];if(i===n)return{token:{kind:"string",pos:F(t),value:s},next:r+1};if(i==="\\"){const a=e[r+1];if(a===void 0)throw new Z("unterminated escape sequence in string literal",F(r));switch(a){case'"':s+='"';break;case"'":s+="'";break;case"\\":s+="\\";break;case"n":s+=`
|
|
4
|
+
`;break;case"t":s+=" ";break;default:throw new Z(`invalid escape sequence '\\${a}' (only \\", \\', \\\\, \\n, \\t are allowed)`,F(r))}r+=2}else{if(i===`
|
|
5
|
+
`||i==="\r")throw new Z("unterminated string literal (newline before closing quote)",F(t));s+=i,r+=1}if(s.length>qe.maxStringLiteralLength)throw new Z(`string literal exceeds ${qe.maxStringLiteralLength}-character cap`,F(t))}throw new Z("unterminated string literal",F(t))}function Gl(e){const t=new Jl(e),n=t.parseExpression();return t.expect("eof","unexpected trailing tokens"),Xl(n),n}class Jl{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=Yl(this.peek().kind);if(!n)break;const r=this.consume(),s=this.parseSum();t={kind:"binary",op:n,left:t,right:s,pos:r.pos}}return t}parseSum(){let t=this.parseProduct();for(;;){const n=this.peek().kind;if(n!=="plus"&&n!=="minus")break;const r=this.consume(),s=this.parseProduct();t={kind:"binary",op:n==="plus"?"+":"-",left:t,right:s,pos:r.pos}}return t}parseProduct(){let t=this.parseUnary();for(;;){const n=this.peek().kind;if(n!=="star"&&n!=="slash"&&n!=="percent")break;const r=this.consume(),s=this.parseUnary();t={kind:"binary",op:n==="star"?"*":n==="slash"?"/":"%",left:t,right:s,pos:r.pos}}return t}parseUnary(){const t=this.peek().kind;if(t==="minus"||t==="bang"){const n=this.consume(),r=this.parseUnary();return{kind:"unary",op:t==="minus"?"-":"!",operand:r,pos:n.pos}}return this.parsePostfix()}parsePostfix(){let t=this.parsePrimary();for(;;){const n=this.peek().kind;if(n==="dot"){const r=this.consume(),s=this.expect("identifier","expected identifier after '.'");t={kind:"fieldAccess",target:t,field:s.value,pos:r.pos}}else if(n==="lbracket"){const r=this.consume(),s=this.parseExpression();this.expect("rbracket","expected ']'"),t={kind:"indexAccess",target:t,index:s,pos:r.pos}}else break}return t}parsePrimary(){const t=this.peek();switch(t.kind){case"number":return this.consume(),{kind:"literal",value:t.value,pos:t.pos};case"string":return this.consume(),{kind:"literal",value:t.value,pos:t.pos};case"true":return this.consume(),{kind:"literal",value:!0,pos:t.pos};case"false":return this.consume(),{kind:"literal",value:!1,pos:t.pos};case"null":return this.consume(),{kind:"literal",value:null,pos:t.pos};case"reference":return this.consume(),{kind:"reference",alias:t.value,pos:t.pos};case"sentinel":return this.parseSentinelCall();case"lparen":{this.consume();const n=this.parseExpression();return this.expect("rparen","expected ')'"),n}case"identifier":throw new ye(`bare identifier '${t.value}' is not a value (did you mean '$${t.value}' or '@${t.value}'?)`,t.pos);case"eof":throw new ye("unexpected end of expression",t.pos);default:throw new ye("unexpected token",t.pos)}}parseSentinelCall(){const t=this.consume(),n=t.value;if(!Fl(n))throw new ye(`unknown sentinel '@${n}' (allowed: serverTimestamp, increment, arrayUnion, arrayRemove, deleteField)`,t.pos);this.expect("lparen",`expected '(' after sentinel '@${n}'`);const r=[];if(this.peek().kind!=="rparen")for(r.push(this.parseExpression());this.peek().kind==="comma";)this.consume(),r.push(this.parseExpression());this.expect("rparen","expected ')' after sentinel arguments");const s=Ll[n];if(r.length<s.min||r.length>s.max){const i=s.max===1/0?`at least ${s.min}`:s.min===s.max?`exactly ${s.min}`:`${s.min}..${s.max}`;throw new ye(`sentinel '@${n}' expects ${i} argument(s), got ${r.length}`,t.pos)}return{kind:"sentinel",name:n,args:r,pos:t.pos}}peek(){return this.tokens[this.cursor]}consume(){const t=this.tokens[this.cursor];return this.cursor+=1,t}expect(t,n){const r=this.peek();if(r.kind!==t)throw new ye(`${n} (got ${Ql(r)})`,r.pos);return this.consume()}}function Yl(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 Ql(e){return e.kind==="eof"?"end of expression":e.value!==void 0?`${e.kind} ${JSON.stringify(e.value)}`:e.kind}function Xl(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>qe.maxAstDepth)throw new ye(`expression AST exceeds depth cap of ${qe.maxAstDepth}`,n.pos);return s}}class oe extends Error{code;pos;constructor(t,n,r){super(n),this.name="EvalError",this.code=t,this.pos=r}}function Pt(e){if(typeof e!="object"||e===null)return!1;const t=e,n=t.__type,r=Object.keys(t);switch(n){case"serverTimestamp":case"deleteField":return r.length===1;case"increment":return r.length===2&&typeof t.value=="number";case"arrayUnion":case"arrayRemove":return r.length===2&&Array.isArray(t.values);default:return!1}}function ue(e,t){return new oe("type-mismatch",t,e.pos)}function ce(e,t){switch(e.kind){case"literal":return e.value;case"reference":return Zl(e,t);case"sentinel":return eu(e,t);case"unary":return tu(e,t);case"binary":return nu(e,t);case"logical":return su(e,t);case"ternary":return iu(e,t);case"fieldAccess":return au(e,t);case"indexAccess":return ou(e,t)}}function Zl(e,t){if(!Object.prototype.hasOwnProperty.call(t.reads,e.alias))throw new oe("unknown-reference",`unknown alias '$${e.alias}' (not in reads). Hint: aliases are case-sensitive; sentinels use '@' not '$'.`,e.pos);return t.reads[e.alias]??null}function eu(e,t){const n=e.args.map(r=>{const s=ce(r,t);if(Pt(s))throw new oe("sentinel-misuse",`sentinel '@${s.__type}' cannot be a sentinel argument`,r.pos);return s});switch(e.name){case"serverTimestamp":return{__type:"serverTimestamp"};case"deleteField":return{__type:"deleteField"};case"increment":{const r=n[0];if(typeof r!="number")throw ue(e,`'@increment' expects a numeric argument, got ${re(r)}`);return tn(r,e),{__type:"increment",value:r}}case"arrayUnion":return{__type:"arrayUnion",values:n};case"arrayRemove":return{__type:"arrayRemove",values:n}}}function tu(e,t){const n=ce(e.operand,t);if(or(n,e),e.op==="-"){if(typeof n!="number")throw ue(e,`unary '-' expects a number, got ${re(n)}`);const r=-n;return tn(r,e),r}if(typeof n!="boolean")throw ue(e,`unary '!' expects a boolean, got ${re(n)}`);return!n}function nu(e,t){const n=ce(e.left,t),r=ce(e.right,t);switch(or(n,e),or(r,e),e.op){case"+":if(typeof n=="number"&&typeof r=="number"){const s=n+r;return tn(s,e),s}if(typeof n=="string"&&typeof r=="string")return n+r;throw ue(e,`'+' expects (number, number) or (string, string); got (${re(n)}, ${re(r)})`);case"-":case"*":case"/":case"%":{if(typeof n!="number"||typeof r!="number")throw ue(e,`'${e.op}' expects (number, number); got (${re(n)}, ${re(r)})`);let s;switch(e.op){case"-":s=n-r;break;case"*":s=n*r;break;case"/":s=n/r;break;case"%":s=n%r;break}return tn(s,e),s}case"==":return As(e,n,r);case"!=":return!As(e,n,r);case"<":case"<=":case">":case">=":return ru(e,n,r)}}function As(e,t,n){if(t===null||n===null)return t===n;const r=typeof t;if(r!==typeof n)return!1;if(r==="number"||r==="string"||r==="boolean")return t===n;throw ue(e,"equality between objects/arrays is not supported (compare specific fields instead)")}function ru(e,t,n){if(!(typeof t=="number"&&typeof n=="number"||typeof t=="string"&&typeof n=="string"))throw ue(e,`'${e.op}' expects matching number/number or string/string operands; got (${re(t)}, ${re(n)})`);switch(e.op){case"<":return t<n;case"<=":return t<=n;case">":return t>n;case">=":return t>=n;default:throw new Error("unreachable")}}function su(e,t){const n=ce(e.left,t);if(typeof n!="boolean")throw ue(e,`'${e.op}' expects boolean operands; left is ${re(n)}`);if(e.op==="&&"){if(!n)return!1}else if(n)return!0;const r=ce(e.right,t);if(typeof r!="boolean")throw ue(e,`'${e.op}' expects boolean operands; right is ${re(r)}`);return r}function iu(e,t){const n=ce(e.cond,t);if(typeof n!="boolean")throw ue(e,`ternary condition must be boolean, got ${re(n)}`);return ce(n?e.whenTrue:e.whenFalse,t)}function au(e,t){const n=ce(e.target,t);if(n==null)throw new oe("null-access",`cannot access field '${e.field}' on null`,e.pos);if(typeof n!="object"||Array.isArray(n)||Pt(n))throw ue(e,`cannot access field '${e.field}' on ${re(n)}`);const r=n;return Object.prototype.hasOwnProperty.call(r,e.field)?r[e.field]:null}function ou(e,t){const n=ce(e.target,t);if(n==null)throw new oe("null-access","cannot index null target",e.pos);const r=ce(e.index,t);if(Array.isArray(n)){if(typeof r!="number"||!Number.isInteger(r))throw new oe("invalid-index",`array index must be a non-negative integer, got ${re(r)}`,e.pos);if(r<0)throw new oe("invalid-index",`negative array index ${r} not supported (use length-based indexing in eval)`,e.pos);return r>=n.length?null:n[r]}if(typeof n=="object"&&!Pt(n)){if(typeof r!="string")throw new oe("invalid-index",`object key must be a string, got ${re(r)}`,e.pos);const s=n;return Object.prototype.hasOwnProperty.call(s,r)?s[r]:null}throw ue(e,`cannot index into ${re(n)}`)}function or(e,t){if(Pt(e))throw new oe("sentinel-misuse",`sentinel '@${e.__type}' cannot be used as an operator operand`,t.pos)}function tn(e,t){if(!Number.isFinite(e))throw new oe("division-by-zero",`arithmetic produced a non-finite value (${Number.isNaN(e)?"NaN":"Infinity"})`,t.pos)}function re(e){if(e===null)return"null";if(Array.isArray(e))return`array(${e.length})`;if(typeof e=="object"&&e!==null){if(Pt(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 Ia="$expr";class nn extends Error{code="invalid-argument";path;constructor(t,n){super(t),this.name="ExpressionWalkError",this.path=n}}function cu(e,t){return cr(e,t,"")}function cr(e,t,n){if(e===null)return null;if(typeof e!="object")return e;if(Array.isArray(e)){const i=new Array(e.length);for(let a=0;a<e.length;a+=1)i[a]=cr(e[a],t,n===""?String(a):`${n}.${a}`);return i}const r=e;if(Object.prototype.hasOwnProperty.call(r,Ia))return lu(r,t,n);const s={};for(const i of Object.keys(r))s[i]=cr(r[i],t,n===""?i:`${n}.${i}`);return s}function lu(e,t,n){const r=Object.keys(e);if(r.length!==1)throw new nn(`expression wrapper at '${n||"<root>"}' must have only the '$expr' key, got [${r.map(c=>JSON.stringify(c)).join(", ")}]`,n);const s=e[Ia];if(typeof s!="string")throw new nn(`'$expr' value at '${n||"<root>"}' must be a string, got ${fu(s)}`,n);const i=du(s,n);return uu(i,t,n)}function uu(e,t,n){try{return ce(e,t)}catch(r){if(r instanceof oe){const s=new oe(r.code,`at '${n||"<root>"}': ${r.message}`,r.pos);throw s.cause=r,s}throw r}}function du(e,t){try{return Gl(Wl(e))}catch(n){throw n instanceof Z?Is(n,Z,t):n instanceof ye?Is(n,ye,t):n}}function Is(e,t,n){const r=new t(`at '${n||"<root>"}': ${e.message}`,e.pos);return r.cause=e,r}function fu(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function hu(e){const{resolveSandbox:t,resolveModulesFn:n}=e;return[{name:"firestore_simulator_create",description:'Seed the session\'s local Firestore environment with rules and optional initial documents. Resets any prior state. Supports `rules_version = "2+modules"` — modules resolve in-process before seeding. Returns the lint result + document count for verification.',parameters:{type:"object",properties:{rules:{type:"string",description:"Firestore security rules source (version 2 or 2+modules)."},documents:{type:"object",description:'Initial documents keyed by full path, e.g. `{ "users/u1": { name: "alice" } }`.',additionalProperties:!0}},required:["rules"]},async execute(r){const{rules:s,documents:i}=r;let a=s;if(a.includes("'2+modules'")||a.includes('"2+modules"')){if(!n)return{ok:!1,summary:"Module resolve unavailable: this builder was not wired with `resolveModulesFn`. Use a package entry that wires module resolution, such as pyric/rules/internal/node, instead of importing the impl directly.",data:{code:"NO_MODULE_RESOLVER"}};const u=n(a);if(!u.success)return{ok:!1,summary:`Module resolve failed: ${u.error.message}`,data:u};a=u.data.resolved}const l=(await t()).seed({rules:a,documents:i??{}});return{ok:!0,summary:`Seeded sandbox with ${Object.keys(i??{}).length} document(s)`,data:{lint:l,documentCount:Object.keys(i??{}).length}}}},{name:"firestore_simulator_execute",description:"Execute a single write (create / update / delete) against the seeded sandbox. Rules evaluate against the in-memory state; allow → state mutates and the op is logged, deny → state unchanged and `debugMessages` explain the rule decision.",parameters:{type:"object",properties:{method:{type:"string",enum:["create","update","delete"]},path:{type:"string",description:"Document path, e.g. `users/u1`."},auth:{description:"Auth context. `null` for unauthenticated. Otherwise `{ uid, token? }` where `token` is the custom-claims object."},data:{type:"object",description:"Document data. Required for create / update.",additionalProperties:!0}},required:["method","path","auth"]},async execute(r){const{method:s,path:i,auth:a,data:c}=r,u=(await t()).execute({method:s,path:i,auth:a,data:c});return{ok:u.allowed,summary:u.allowed?`${s} on ${i} allowed`:`${s} on ${i} denied`,data:{allowed:u.allowed,debugMessages:u.debugMessages}}}},{name:"firestore_simulator_read",description:"Read a document (`get`) or list a collection (`list`) from the seeded sandbox. Default uses admin access (bypasses rules). Set `evaluateRules: true` with an `auth` context to test read access control through the rules engine.",parameters:{type:"object",properties:{path:{type:"string",description:"Doc path for `get`, collection path for `list`."},method:{type:"string",enum:["get","list"],description:"Default `get`."},auth:{description:"Auth context. Required when `evaluateRules` is true."},evaluateRules:{type:"boolean",description:"Evaluate read rules against `auth`. Default false (admin read)."}},required:["path"]},async execute(r){const{path:s,method:i,auth:a,evaluateRules:c}=r,l=await t();if(c){const u=l.execute({method:i??"get",path:s,auth:a??null});return{ok:u.allowed,summary:u.allowed?`${i??"get"} on ${s} allowed`:`${i??"get"} on ${s} denied`,data:{allowed:u.allowed,document:u.data,debugMessages:u.debugMessages}}}return i==="list"?{ok:!0,summary:`Listed ${s}`,data:{documents:l.listDocuments(s)}}:{ok:!0,summary:`Read ${s}`,data:{document:l.getDocument(s)}}}},{name:"firestore_simulator_batch",description:"Execute multiple writes atomically. All operations must pass rules — if any denies, none apply. Rules evaluate each op against pre-batch state (no cross-visibility within the batch).",parameters:{type:"object",properties:{operations:{type:"array",items:{type:"object",properties:{method:{type:"string",enum:["create","update","delete"]},path:{type:"string"},data:{type:"object",additionalProperties:!0}},required:["method","path"]}},auth:{description:"Auth context for every op. `null` for unauthenticated."}},required:["operations","auth"]},async execute(r){const{operations:s,auth:i}=r,c=(await t()).batch(s,i);return{ok:c.allowed,summary:c.allowed?`Batch of ${s.length} op(s) committed`:`Batch of ${s.length} op(s) rejected by rules. To SEED data, use the admin data tool firestore_batch_write; to test rules, pass an auth the rules permit.`,data:{allowed:c.allowed,results:c.results}}}},{name:"firestore_create_with_auto_id",description:"Create a document at `<collection>/<auto-id>` with a Firestore-compatible 20-char alphanumeric id (mirrors the live SDK `addDoc()` flow). Rules evaluate as for an explicit-id `create`. Returns the minted path so the caller can re-read the doc without a side channel.",parameters:{type:"object",properties:{collection:{type:"string",description:"Collection path under which to mint the new document, e.g. `users` or `users/u1/posts`."},auth:{description:"Auth context. `null` for unauthenticated. Otherwise `{ uid, token? }`."},data:{type:"object",description:"Document data.",additionalProperties:!0}},required:["collection","auth","data"]},async execute(r){const{collection:s,auth:i,data:a}=r,c=await t(),{path:l,result:u}=c.createWithAutoId(s,a,i);return{ok:u.allowed,summary:u.allowed?`Created ${l}`:`Create at ${l} denied by rules (as ${i?i.uid:"unauthenticated"}). To SEED data, use the admin data tool firestore_add_document; to test rules, pass an auth the rules permit.`,data:{path:l,allowed:u.allowed,debugMessages:u.debugMessages}}}},{name:"firestore_simulator_undo",description:"Undo the last allowed write. Restores state to immediately before that op. Returns the undone event, or a `{ undone: false }` outcome when the log is empty.",parameters:{type:"object",properties:{}},async execute(){const s=(await t()).undo();return s?{ok:!0,summary:`Undid ${s.method} on ${s.path}`,data:{undone:!0,event:{method:s.method,path:s.path}}}:{ok:!0,summary:"Nothing to undo",data:{undone:!1}}}},{name:"firestore_simulator_redo",description:"Re-apply the most recently undone write. Pairs with `firestore_simulator_undo`. Returns the re-applied event, or `{ redone: false }` when the undo stack is empty (no recent undo to redo).",parameters:{type:"object",properties:{}},async execute(){const s=(await t()).redo();return s?{ok:s.allowed,summary:s.allowed?`Redid ${s.event?.method??"op"} on ${s.event?.path??"?"}`:"Redo restored a denied event (no state change)",data:{redone:!0,allowed:s.allowed,event:s.event?{method:s.event.method,path:s.event.path}:null,debugMessages:s.debugMessages}}:{ok:!0,summary:"Nothing to redo",data:{redone:!1}}}},{name:"firestore_simulator_events",description:'Return every event the sandbox has seen — allowed and denied — with timestamps, auth, and debug messages. Useful for audit / replay / "why did this rule deny?" investigations.',parameters:{type:"object",properties:{}},async execute(){return{ok:!0,summary:"Event log",data:{events:(await t()).getEvents().map(s=>({id:s.id,method:s.method,path:s.path,allowed:s.allowed,auth:s.auth,debugMessages:s.debugMessages}))}}}},{name:"firestore_simulator_transaction",description:'Run a declarative transaction. Reads are captured server-side and referenced from write data via `{ "$expr": "..." }` wrappers — agents never see the read values, eliminating the "round-trip the doc through context" cost. Expression DSL: arithmetic (+ - * / %), comparison, &&/||/?:, $alias.field references, string literals in either "double" or \'single\' quotes, and @sentinel(...) calls (@increment, @serverTimestamp, @arrayUnion, @arrayRemove, @deleteField). Reads are omitted from the response by default; set `includeReads: true` when debugging a denial.',parameters:{type:"object",properties:{auth:{description:"Auth context for rule eval. `null` for unauthenticated."},readOnly:{type:"boolean",description:"Hint that the transaction is read-only. v1: writes are still committed; `readOnlyViolation: true` surfaces on the response if any was queued."},includeReads:{type:"boolean",description:"Default false. When true, the response includes the captured read data + per-write debugMessages."},reads:{type:"object",description:"Reads keyed by alias. Aliases referenced from write expressions as `$alias` (e.g. `$src.balance`).",additionalProperties:{type:"string"}},writes:{type:"array",minItems:1,items:{type:"object",properties:{method:{type:"string",enum:["create","update","set","delete"]},path:{type:"string"},data:{type:"object",additionalProperties:!0}},required:["method","path"]},description:"Write operations to apply atomically."}},required:["reads","writes","auth"]},async execute(r){const{auth:s,readOnly:i,includeReads:a,reads:c,writes:l}=r;for(let p=0;p<l.length;p+=1){const f=l[p];if(f.method==="delete"&&f.data!==void 0)return{ok:!1,summary:`writes[${p}]: 'delete' must not include 'data'`,data:{code:"INVALID_INPUT"}};if(f.method!=="delete"&&f.data===void 0)return{ok:!1,summary:`writes[${p}]: '${f.method}' requires 'data'`,data:{code:"INVALID_INPUT"}}}const u=await t(),d=a===!0;try{const p=u.transaction(m=>{const y={};for(const[g,v]of Object.entries(c)){const w=m.get(v).data();y[g]=w===void 0?null:w}for(let g=0;g<l.length;g+=1){const v=l[g];if(v.method==="delete"){m.delete(v.path);continue}const b=cu(v.data,{reads:y});if(b===null||typeof b!="object"||Array.isArray(b))throw new nn(`writes[${g}].data resolved to a non-object`,`writes.${g}.data`);const w=b;switch(v.method){case"create":m.create(v.path,w);break;case"update":m.update(v.path,w);break;case"set":m.set(v.path,w);break}}},{auth:s,readOnly:i}),f={allowed:p.allowed,writes:p.writes.map(m=>{const y={path:m.path,method:m.method,allowed:m.allowed};return m.error&&(y.error={code:m.error.code,message:m.error.message}),d&&(y.debugMessages=m.debugMessages),y})};return p.error&&(f.error={code:p.error.code,message:p.error.message}),p.readOnlyViolation&&(f.readOnlyViolation=!0),d&&(f.reads=p.reads.map(m=>({path:m.path,data:m.data}))),{ok:p.allowed,summary:p.allowed?`Transaction committed (${l.length} write(s))`:"Transaction rolled back",data:f}}catch(p){if(p instanceof nn||p instanceof Z||p instanceof ye||p instanceof oe)return{ok:!1,summary:`Transaction failed: ${p.message}`,data:{allowed:!1,writes:[],error:{code:"invalid-argument",message:p.message}}};throw p}}}]}function Da(e){return hu({resolveSandbox:e.resolveSandbox,resolveModulesFn:wa})}let Ln;function pu(){if(Ln)return Ln;const e=Hr();return e.addOperation("identifiers",{_nonterminal(...t){return t.flatMap(n=>n.identifiers())},_iter(...t){return t.flatMap(n=>n.identifiers())},_terminal(){return[]},CallExpr_methodCall(t,n,r,s,i,a){return[...t.identifiers(),...i.asIteration().children.flatMap(c=>c.identifiers())]},CallExpr_memberAccess(t,n,r){return t.identifiers()},ident(t,n,r){return[this.sourceString]}}),Ln=e,e}function mu(e){const t=Kr(e);if(t.failed())return{raw:e,valid:!1,errors:[{code:"PARSE_ERROR",message:t.message??"Parse failed"}],warnings:[],referencedIdentifiers:[]};const n=pu()(t).identifiers(),r=[...new Set(n)];return{raw:e,valid:!0,errors:[],warnings:[],referencedIdentifiers:r}}const yu=new Set(["__proto__","prototype","constructor"]);function L(e){if(e===""||e==="/")return[];const t=e.split("/").filter(n=>n.length>0);for(const n of t)if(yu.has(n))throw new Error(`Invalid RTDB path segment '${n}': the keys __proto__, prototype, and constructor are reserved and cannot appear in a path.`);return t}function J(e){return e.length===0?"/":"/"+e.join("/")}function Ne(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>Ne(n));const t={};for(const[n,r]of Object.entries(e))t[n]=Ne(r);return t}function Ds(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function at(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)=>at(s,t[i]));if(!Ds(e)||!Ds(t))return!1;const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(s=>s in t&&at(e[s],t[s]))}class bu{root={};snapshot(){return Ne(this.root)}restore(t){this.root=Ne(t)}read(t){const n=L(t);if(n.length>0&&n[0]===".info")return n.length===1?{connected:!0,serverTimeOffset:0}:n[1]==="connected"?!0:n[1]==="serverTimeOffset"?0:null;let s=this.root;for(const i of n){if(s===null||typeof s!="object"||Array.isArray(s))return null;const a=s;if(!Object.hasOwn(a,i))return null;s=a[i]}return Ne(s)}write(t,n){const r=L(t),s=this.read(t);if(r.length===0)return n===null?(this.root={},s):(this.root=Ne(n),s);(this.root===null||typeof this.root!="object"||Array.isArray(this.root))&&(this.root={});let i=this.root;for(let c=0;c<r.length-1;c++){const l=r[c],u=Object.hasOwn(i,l)?i[l]:void 0;if(u==null||typeof u!="object"||Array.isArray(u)){const d={};i[l]=d,i=d}else i=u}const a=r[r.length-1];return n===null?(delete i[a],this.trim(r)):i[a]=Ne(n),s}multiUpdate(t){const r=Object.entries(t).map(([i,a])=>({path:J(L(i)),value:a}));for(let i=0;i<r.length;i++)for(let a=i+1;a<r.length;a++){const c=r[i].path,l=r[a].path;if(c===l)throw new Error(`multi-path update: duplicate path '${c}'.`);const u=c==="/"?"/":c+"/",d=l==="/"?"/":l+"/";if(c!=="/"&&l.startsWith(u))throw new Error(`multi-path update: '${l}' is a descendant of '${c}'.`);if(l!=="/"&&c.startsWith(d))throw new Error(`multi-path update: '${c}' is a descendant of '${l}'.`)}const s=[];for(const{path:i,value:a}of r){const c=this.write(i,a);s.push({path:i,prior:c})}return s}shallowUpdate(t,n){const r=[],s=L(t);for(const[i,a]of Object.entries(n)){const c=[...s,...L(i)],l=J(c),u=this.write(l,a);r.push({path:l,prior:u})}return r}trim(t){if(!(this.root===null||typeof this.root!="object"||Array.isArray(this.root)))for(let n=t.length-1;n>=1;n--){const r=t.slice(0,n),s=t[n-1];let i=this.root;for(let c=0;c<r.length-1;c++){const l=i[r[c]];if(l==null||typeof l!="object"||Array.isArray(l))return;i=l}const a=i[s];if(a!==void 0&&typeof a=="object"&&a!==null&&!Array.isArray(a)&&Object.keys(a).length===0){delete i[s];continue}return}}}function gu(e,t){return e==="/"||t==="/"?!0:e===t||e.startsWith(`${t}/`)||t.startsWith(`${e}/`)}class vu{version=0;activeVersions=[];mutations=[];get entries(){return this.mutations}get currentVersion(){return this.version}begin(){const t=this.version;return this.activeVersions.push(t),t}mark(t="/"){this.version+=1,this.activeVersions.length>0&&this.mutations.push({version:this.version,paths:(Array.isArray(t)?t:[t]).map(n=>J(L(n)))})}conflictsSince(t,n){const r=J(L(n));return this.mutations.some(s=>s.version>t&&s.paths.some(i=>gu(r,i)))}release(t){const n=this.activeVersions.lastIndexOf(t);if(n>=0&&this.activeVersions.splice(n,1),this.activeVersions.length===0){this.mutations.length=0;return}const r=Math.min(...this.activeVersions),s=this.mutations.findIndex(i=>i.version>r);s<0?this.mutations.length=0:s>0&&this.mutations.splice(0,s)}}function he(e){return e==="unsupported"?"unsupported":"deny"}function xe(e){return J(L(e))}class wu{sandbox;nextId=0;constructor(t){this.sandbox=t}nextListenerId(){return this.nextId+=1,`rtdb-listener-${this.nextId.toString(36)}`}nextGroupId(t){return this.nextId+=1,`rtdb-${t}-${this.nextId.toString(36)}`}mutation(t,n,r,s={}){if(this.sandbox)try{Re(this.sandbox,vn({service:"rtdb",op:n,path:r,auth:t,before:s.before,after:s.after,detail:s.detail}),{service:"rtdb"})}catch{}}operation(t,n,r,s,i,a={}){if(this.sandbox)try{let c;i&&(c={engine:"rtdb",matchedPath:i.matchedPath,matchedRule:i.matchedRule,pathVariableBindings:i.pathVariableBindings,reason:i.reason,errorCode:i.errorCode});let l="user";a.origin&&(l=a.origin),Re(this.sandbox,xa({service:"rtdb",method:n,path:xe(r),auth:t,result:s,origin:l,durationMs:a.durationMs,reasons:i?.reasons,rules:c,request:a.request,resourceBefore:a.resourceBefore,resourceAfter:a.resourceAfter,groupId:a.groupId,groupKind:a.groupKind,triggeredBy:a.triggeredBy,detail:a.detail,at:a.at}),{service:"rtdb"})}catch{}}commit(t,n,r,s={}){if(this.sandbox)try{Re(this.sandbox,il({service:"rtdb",method:n,path:xe(r),auth:t,data:s.data,priorState:s.priorState,nextState:s.nextState,groupId:s.groupId,groupKind:s.groupKind,replay:s.replay,detail:s.detail}),{service:"rtdb"})}catch{}}listener(t,n,r,s={}){if(this.sandbox)try{let i="value";s.event&&(i=s.event),Re(this.sandbox,al({service:"rtdb",phase:t,listenerId:n.id,target:{kind:i,path:xe(n.path)},auth:r,result:s.result,size:s.size,sample:s.sample,reason:s.reason,error:s.error,triggeredBy:s.triggeredBy,detail:s.detail,reasons:s.reasons,rules:s.rules}),{service:"rtdb"})}catch{}}}class xu{values=new Map;get(t){return this.values.get(J(L(t)))??null}forChild(t){const n=L(t);return r=>this.get(J([...n,r]))}clear(){this.values.clear()}clearAtOrBelow(t){const n=J(L(t)),r=n==="/"?"/":`${n}/`;for(const s of this.values.keys())(s===n||s.startsWith(r))&&this.values.delete(s)}replace(t,n){this.clearAtOrBelow(t),n!==null&&this.values.set(J(L(t)),n)}set(t,n){const r=J(L(t));n===null?this.values.delete(r):this.values.set(r,n)}stateAtOrBelow(t){const n=J(L(t)),r=n==="/"?"/":`${n}/`;return JSON.stringify([...this.values].filter(([s])=>s===n||s.startsWith(r)).sort(([s],[i])=>s.localeCompare(i)))}applyUpdate(t){for(const n of t){const r=this.get(n.path);this.clearAtOrBelow(n.path),n.value!==null&&r!==null&&this.values.set(J(L(n.path)),r)}}entries(){return this.values.entries()}restore(t){this.values.clear();for(const[n,r]of Object.entries(t))this.values.set(J(L(n)),r)}}function rn(e){if(e!==null&&typeof e!="string"&&(typeof e!="number"||!Number.isFinite(e)))throw new Error("priority must be a valid Firebase priority (string, finite number, or null)")}let Ve=[],lr=!1,ur=!1,dr=!1,Fn;function ju(){if(Fn)return Fn;const e=Hr();return e.addOperation("lint",{_nonterminal(...t){t.forEach(n=>n.lint())},_iter(...t){t.forEach(n=>n.lint())},_terminal(){},CallExpr_methodCall(t,n,r,s,i,a){t.lint(),i.asIteration().children.forEach(c=>c.lint()),r.sourceString==="child"&&t.sourceString==="data"&&(dr=!0)},ident(t,n,r){const s=this.sourceString;s==="data"&&(lr=!0),s==="newData"&&(ur=!0)},bool_true(t){Ve.push({code:"HARDCODED_TRUE",message:"Rule expression is hardcoded to true"})},bool_false(t){Ve.push({code:"HARDCODED_FALSE",message:"Rule expression is hardcoded to false"})},Comparison_looseEq(t,n,r){Ve.push({code:"LOOSE_EQUALITY",message:"Use '===' instead of '=='"}),t.lint(),r.lint()},Comparison_looseNeq(t,n,r){Ve.push({code:"LOOSE_INEQUALITY",message:"Use '!==' instead of '!='"}),t.lint(),r.lint()}}),Fn=e,e}function ku(e,t="read"){const n=Kr(e);return n.failed()?[]:(Ve=[],lr=!1,ur=!1,dr=!1,ju()(n).lint(),t==="write"&&lr&&!ur&&!dr&&Ve.push({code:"DATA_IN_WRITE",message:"Write rule references 'data' but not 'newData'; consider using 'newData' to check incoming data"}),[...Ve])}const Su=new Set(["__proto__","prototype","constructor"]);function Ps(e,t){return Su.has(t)?null:typeof e=="string"?t==="length"?e.length:null:e===null||typeof e!="object"||!Object.hasOwn(e,t)?null:e[t]??null}class je{_value;_path;_root;constructor(t,n="/",r){this._value=t??null,this._path=n,this._root=r!==void 0?r:t}val(){return this._value}exists(){return this._value!==null&&this._value!==void 0}hasChild(t){return this.child(t).exists()}hasChildren(t){return Array.isArray(t)?t.every(n=>this.hasChild(String(n))):typeof this._value=="object"&&this._value!==null&&Object.keys(this._value).length>0}isString(){return typeof this._value=="string"}isNumber(){return typeof this._value=="number"}isBoolean(){return typeof this._value=="boolean"}child(t){const n=t.split("/").filter(i=>i.length>0);let r=this._value,s=this._path;for(const i of n){if(r==null||typeof r!="object"){r=null,s=`${s}/${i}`.replace(/\/+/g,"/");break}r=Object.hasOwn(r,i)?r[i]??null:null,s=`${s==="/"?"":s}/${i}`}return new je(r,s,this._root)}parent(){if(this._path==="/")return null;const t=this._path.split("/").filter(s=>s.length>0);t.pop();const n="/"+t.join("/"),r=new je(this._root,"/");return n==="/"?r:r.child(t.join("/"))}getPriority(){return null}}class _u{value;constructor(t){this.value=t}matches(t){return(t instanceof RegExp?t:new RegExp(t)).test(this.value)}contains(t){return this.value.includes(t)}beginsWith(t){return this.value.startsWith(t)}endsWith(t){return this.value.endsWith(t)}replace(t,n){if(t instanceof RegExp){const r=t.flags.includes("g")?t.flags:`${t.flags}g`;return this.value.replace(new RegExp(t.source,r),n)}return t===""?this.value:this.value.split(t).join(n)}toLowerCase(){return this.value.toLowerCase()}toUpperCase(){return this.value.toUpperCase()}get length(){return this.value.length}}let Ee={auth:null,data:new je(null),newData:new je(null),root:new je(null),now:Date.now(),pathVariableBindings:{}},Vn;function Eu(){if(Vn)return Vn;const e=Hr();return e.addOperation("eval",{Expr(t){return t.eval()},Ternary_ternary(t,n,r,s,i){return t.eval()?r.eval():i.eval()},Ternary(t){return t.eval()},Logical_and(t,n,r){return t.eval()&&r.eval()},Logical_or(t,n,r){return t.eval()||r.eval()},Logical(t){return t.eval()},Comparison_strictEq(t,n,r){return t.eval()===r.eval()},Comparison_strictNeq(t,n,r){return t.eval()!==r.eval()},Comparison_gte(t,n,r){return t.eval()>=r.eval()},Comparison_lte(t,n,r){return t.eval()<=r.eval()},Comparison_gt(t,n,r){return t.eval()>r.eval()},Comparison_lt(t,n,r){return t.eval()<r.eval()},Comparison_looseEq(t,n,r){return t.eval()==r.eval()},Comparison_looseNeq(t,n,r){return t.eval()!=r.eval()},Comparison(t){return t.eval()},Additive_add(t,n,r){return t.eval()+r.eval()},Additive_sub(t,n,r){return t.eval()-r.eval()},Additive(t){return t.eval()},Multiplicative_mul(t,n,r){return t.eval()*r.eval()},Multiplicative_div(t,n,r){return t.eval()/r.eval()},Multiplicative_mod(t,n,r){return t.eval()%r.eval()},Multiplicative(t){return t.eval()},UnaryExpr_not(t,n){return!n.eval()},UnaryExpr_neg(t,n){return-n.eval()},UnaryExpr(t){return t.eval()},CallExpr_methodCall(t,n,r,s,i,a){const c=t.eval(),l=r.sourceString,u=i.asIteration().children.map(d=>d.eval());if(c instanceof je)switch(l){case"val":return c.val();case"exists":return c.exists();case"hasChild":return c.hasChild(String(u[0]));case"hasChildren":return c.hasChildren(u.length>0?u[0]:void 0);case"isString":return c.isString();case"isNumber":return c.isNumber();case"isBoolean":return c.isBoolean();case"child":return c.child(String(u[0]));case"parent":return c.parent();case"getPriority":return c.getPriority();default:throw new Error(`Unknown DataSnapshot method: ${l}`)}if(typeof c=="string"){const d=new _u(c);switch(l){case"matches":return d.matches(u[0]);case"contains":return d.contains(String(u[0]));case"beginsWith":return d.beginsWith(String(u[0]));case"endsWith":return d.endsWith(String(u[0]));case"replace":return d.replace(u[0],String(u[1]));case"toLowerCase":return d.toLowerCase();case"toUpperCase":return d.toUpperCase();default:throw new Error(`Unknown string method: ${l}`)}}throw new Error(`Unknown method '${l}' for the given value.`)},CallExpr_memberAccess(t,n,r){const s=t.eval();return s==null?null:Ps(s,r.sourceString)},CallExpr_indexAccess(t,n,r,s){const i=t.eval(),a=r.eval();return i==null?null:Ps(i,String(a))},CallExpr(t){return t.eval()},Primary_paren(t,n,r){return n.eval()},Primary(t){return t.eval()},Array(t,n,r){return n.asIteration().children.map(s=>s.eval())},literal(t){return t.eval()},number_float(t,n,r){return parseFloat(this.sourceString)},number_int(t){return parseInt(this.sourceString,10)},number(t){return t.eval()},string_double(t,n,r){return JSON.parse(this.sourceString)},string_single(t,n,r){return n.children.map(s=>s.sourceString).join("")},string(t){return t.eval()},regex(t,n,r,s){return new RegExp(n.sourceString,s.sourceString)},bool_true(t){return!0},bool_false(t){return!1},bool(t){return t.eval()},null(t){return null},ident(t,n,r){const s=this.sourceString;if(s in Ee.pathVariableBindings)return Ee.pathVariableBindings[s];switch(s){case"auth":return Ee.auth;case"data":return Ee.data;case"newData":return Ee.newData;case"root":return Ee.root;case"now":return Ee.now;default:return}}}),Vn=e,e}function Pa(e,t){const n=Kr(e);if(n.failed())throw new Error(n.message??"RTDB expression failed to parse");return Ee=t,Eu()(n).eval()}function Cu(e){const t=e.val();return t===null||typeof t!="object"?[]:Object.keys(t)}function Nu(e,t,n,r,s,i){let a=null;function c(u,d,p,f,m){if(!p.exists())return null;const y=u.validate;if(y){if(!y.parsed.valid)a||(a={node:u,rule:y,bindings:f,unsupported:!0});else if(!Pa(y.raw,s(d,p,f)))return{node:u,rule:y,bindings:f}}for(const g of u.children){const v=g.path.split("/").filter(Boolean);if(v.length===0)continue;const b=v[v.length-1],w=b.startsWith("$");if(m.length>0){if(!w&&m[0]!==b)continue;return c(g,d.child(m[0]),p.child(m[0]),w?{...f,[b]:m[0]}:f,m.slice(1))}if(w)for(const x of Cu(p)){const k=c(g,d.child(x),p.child(x),{...f,[b]:x},[]);if(k)return k}else{const x=c(g,d.child(b),p.child(b),f,[]);if(x)return x}}return null}return c(e,t,n,r,i)??a}function $a(e,t,n,r=0){const s=[{node:e,pathVariableBindings:{...n},depth:r}];if(t.length===0)return s;for(const i of e.children){const a=i.path.split("/").filter(Boolean);if(a.length===0)continue;const c=a[a.length-1],l=c.startsWith("$");if(l||t[0]===c){const u=l?{...n,[c]:t[0]}:{...n},d=$a(i,t.slice(1),u,r+1);return s.push(...d),s}}return s}function fr(e,t,n){if(t.length===0)return n??null;const[r,...s]=t,i=e!==null&&typeof e=="object"&&!Array.isArray(e)?{...e}:{},a=Object.hasOwn(i,r)?i[r]:null,c=fr(a,s,n);return c==null?delete i[r]:i[r]=c,i}function Ru(e,t,n,r){if(!r||r.length===0)return fr(e,t,n??null);let s=e;for(const i of r){const a=i.path.split("/").filter(Boolean);s=fr(s,a,i.value??null)}return s}class Au{execute(t,n){const r=_l.safeParse(n);if(!r.success)return{success:!1,error:{code:"INVALID_INPUT",message:r.error.message,recoverable:!0}};const{operation:s,path:i,auth:a,mockData:c,newData:l,updates:u}=r.data;try{const d=i.split("/").filter(Boolean),p=t,f=$a(p,d,{}),m=new je(c,"/"),y=s==="read"?c:Ru(c,d,l,u),g=new je(y,"/"),v=(k,j,S)=>{const N={};for(const[P,I]of Object.entries(S))N[P]=I,N[P.slice(1)]=I;return{auth:a?{uid:a.uid,token:a.token}:null,data:k,newData:j,root:m,now:Date.now(),pathVariableBindings:N}};let b;for(const k of f){const j=k.node[s];if(!j)continue;if(!j.parsed.valid){b||(b=k);continue}const S=d.slice(0,k.depth).join("/"),N=m.child(S),P=g.child(S);if(Pa(j.raw,v(N,P,k.pathVariableBindings))){if(s==="write"){const D=Nu(p,m,g,{},v,d);if(D)return{success:!0,data:{allowed:!1,unsupported:D.unsupported===!0,matchedPath:D.node.path,matchedRule:D.rule.raw,reason:D.unsupported?`Validation rule at '${D.node.path}' contains an expression the simulator cannot evaluate: ${D.rule.raw} — not evaluated; production may reject this write.`:"Validation rule evaluated to false",pathVariableBindings:D.bindings}}}return{success:!0,data:{allowed:!0,matchedPath:k.node.path,matchedRule:j.raw,reason:"Rule expression evaluated to true",pathVariableBindings:k.pathVariableBindings}}}}if(b){const k=b.node[s];return{success:!0,data:{allowed:!1,unsupported:!0,matchedPath:b.node.path,matchedRule:k.raw,reason:`'${s}' rule at '${b.node.path}' contains an expression the simulator cannot evaluate: ${k.raw} — not evaluated; production may reject or allow this ${s}.`,pathVariableBindings:b.pathVariableBindings}}}const w=f[f.length-1],x=w.node[s];return x?{success:!0,data:{allowed:!1,matchedPath:w.node.path,matchedRule:x.raw,reason:"Rule expression evaluated to false",pathVariableBindings:w.pathVariableBindings}}:{success:!1,error:{code:"NO_MATCHING_RULE",message:`No '${s}' rule found for path '${i}'`,recoverable:!0}}}catch(d){return{success:!1,error:{code:"EVALUATION_ERROR",message:d instanceof Error?d.message:String(d),recoverable:!1}}}}}const Iu=new Set([".read",".write",".validate",".indexOn"]);function Oa(e,t,n=[]){const r=mu(e),s=r.valid?El(e,t,n):r.errors,i=r.valid?ku(e,t):[];return{raw:e,parsed:{...r,errors:s,warnings:i}}}function Ma(e,t,n){const r={path:t,pathVariables:[...n],children:[]};for(const[i,a]of[[".read","read"],[".write","write"],[".validate","validate"]]){const c=e[i];c!==void 0&&(r[a]=Oa(String(c),a,n))}const s=e[".indexOn"];s!==void 0&&(r.indexOn=Array.isArray(s)?s.map(String):[String(s)]);for(const[i,a]of Object.entries(e)){if(Iu.has(i)||typeof a!="object"||a===null)continue;const c=t==="/"?`/${i}`:`${t}/${i}`,l=i.startsWith("$")?[...n,i]:[...n];r.children.push(Ma(a,c,l))}return r}function Ua(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 Ma(t.rules,"/",[])}function qn(e){return e==="true"?!0:e==="false"?!1:e}function Ta(e){const t={};e.read&&(t[".read"]=qn(e.read.raw)),e.write&&(t[".write"]=qn(e.write.raw)),e.validate&&(t[".validate"]=qn(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]]=Ta(n)}return t}function Du(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:Ta(e)}}function Yr(e,t){return new Au().execute(e,t)}function ve(){const e=new Error("PERMISSION_DENIED: Permission denied");return e.code="PERMISSION_DENIED",e}class Pu{compiled=null;setRules(t){if(t===null){this.compiled=null;return}this.compiled=Ua(t)}hasRules(){return this.compiled!==null}check(t,n,r){return this.evaluate(t,n,r).check}evaluate(t,n,r){if(t==="read"){if(n==="/.info"||n===".info")return{check:"allow",reasons:["/.info/ system metadata paths are always readable regardless of security rules."]};if(n.startsWith("/.info/"))return{check:"allow",reasons:["/.info/ system metadata paths are always readable regardless of security rules."]};if(n.startsWith(".info/"))return{check:"allow",reasons:["/.info/ system metadata paths are always readable regardless of security rules."]}}if(this.compiled===null)return{check:"allow",reasons:["No RTDB rules loaded; default allow."]};const i=r.auth===null?null:{uid:r.auth.uid,token:r.auth.token??{}},a=Yr(this.compiled,{operation:t,path:n==="/"?"/":n,auth:i,mockData:r.mockData,newData:r.newData,updates:r.updates});return a.success?a.data.unsupported?{check:"unsupported",reasons:[`${a.data.matchedPath} ${t} UNSUPPORTED: ${a.data.reason}`],matchedPath:a.data.matchedPath,matchedRule:a.data.matchedRule,reason:a.data.reason,pathVariableBindings:a.data.pathVariableBindings}:{check:a.data.allowed?"allow":"deny",reasons:[`${a.data.matchedPath} ${t} ${a.data.allowed?"ALLOW":"DENY"}: ${a.data.reason}`],matchedPath:a.data.matchedPath,matchedRule:a.data.matchedRule,reason:a.data.reason,pathVariableBindings:a.data.pathVariableBindings}:a.error.code==="NO_MATCHING_RULE"?{check:"no-rule",reasons:[a.error.message],errorCode:a.error.code,errorMessage:a.error.message}:{check:"no-rule",reasons:[a.error.message],errorCode:a.error.code,errorMessage:a.error.message}}}class $u{tree=new bu;rules=new Pu;activeRules=null;valueListeners=new Set;childListeners=new Set;priorities=new xu;mutations=new vu;events;writeSubscribers=new Set;resetGeneration=0;constructor(t){this.events=new wu(t)}notifyWrite(){for(const t of this.writeSubscribers)try{t()}catch{}}}function Qr(e,t){if(e===t)return 0;if(e===null)return-1;if(t===null)return 1;const n=$s(e),r=$s(t);return n!==r?n-r:typeof e=="number"&&typeof t=="number"?e<t?-1:e>t?1:0:typeof e=="boolean"&&typeof t=="boolean"?e===t?0:e?1:-1:typeof e=="string"&&typeof t=="string"?e<t?-1:e>t?1:0:0}function $s(e){return e===null?0:typeof e=="boolean"?1:typeof e=="number"?2:typeof e=="string"?3:4}const Ou=/^-?(0*)\d{1,10}$/,Mu=-2147483648,Uu=2147483647;function Os(e){if(Ou.test(e)){const t=Number(e);if(t>=Mu&&t<=Uu)return t}return null}function sn(e,t){if(e===t)return 0;const n=Os(e),r=Os(t);return n!==null?r!==null?n-r===0?e.length-t.length:n-r:-1:r!==null?1:e<t?-1:1}function Et(e,t,n,r=null){const s=e??{kind:"priority"};switch(s.kind){case"key":return t;case"value":return n;case"priority":return r;case"child":{if(n===null||typeof n!="object"||Array.isArray(n))return null;const i=s.path.split("/").filter(c=>c.length>0);let a=n;for(const c of i){if(a===null||typeof a!="object"||Array.isArray(a))return null;a=a[c]??null}return a}}}function We(e,t,n=()=>null){if(e===null||typeof e!="object"||Array.isArray(e))return[];let s=Object.entries(e).map(([a,c])=>({key:a,value:c,priority:n(a)}));const i=t.orderBy?.kind==="key";s.sort((a,c)=>{if(i)return sn(a.key,c.key);const l=Et(t.orderBy,a.key,a.value,a.priority),u=Et(t.orderBy,c.key,c.value,c.priority),d=Qr(l,u);return d!==0?d:sn(a.key,c.key)});for(const a of t.bounds)s=s.filter(c=>Tu(a,c,t.orderBy));if(t.limit){const a=t.limit.n;t.limit.kind==="limitToFirst"?s=s.slice(0,a):s=a>=s.length?s:s.slice(s.length-a)}return s}function Tu(e,t,n){const s=n?.kind==="key"?sn(t.key,String(e.value)):Qr(Et(n,t.key,t.value,t.priority),e.value),i=a=>sn(t.key,a);switch(e.kind){case"startAt":return s>0?!0:s<0?!1:e.key===void 0||i(e.key)>=0;case"startAfter":return s>0?!0:s<0||e.key===void 0?!1:i(e.key)>0;case"endAt":return s<0?!0:s>0?!1:e.key===void 0||i(e.key)<=0;case"endBefore":return s<0?!0:s>0||e.key===void 0?!1:i(e.key)<0;case"equalTo":return s!==0?!1:e.key===void 0||i(e.key)===0}}function Ms(e){return e.length===0?null:Object.fromEntries(e.map(({key:t,value:n})=>[t,n]))}function Bu(e,t){return e.length===t.length&&e.every((n,r)=>{const s=t[r];return n.key===s.key&&n.priority===s.priority&&at(n.value,s.value)})}function Xr(e){const t=new Error(`permission_denied at ${J(L(e))}: Client doesn't have permission to access the desired data.`);return t.code="PERMISSION_DENIED",t}class Lu{state;constructor(t){this.state=t}onValue(t,n,r,s,i,a){const c=Date.now(),l=this.state.rules.evaluate("read",n==="/"?"/":n,{auth:t,mockData:this.state.tree.snapshot()});if(l.check!=="allow"){let u;s&&(u={query:s}),this.state.events.operation(t,"listen",n,he(l.check),l,{at:c,durationMs:Date.now()-c,request:u,origin:"listener"});const d={engine:"rtdb",matchedPath:l.matchedPath,matchedRule:l.matchedRule,pathVariableBindings:l.pathVariableBindings,reason:l.reason,errorCode:l.errorCode};if(this.state.events.listener("errored",{id:this.state.events.nextListenerId(),path:n},t,{event:"value",result:"deny",error:{code:"PERMISSION_DENIED",message:"PERMISSION_DENIED: Permission denied",reasons:l.reasons},reasons:l.reasons,rules:d}),i)return queueMicrotask(()=>{a&&a(),i(Xr(n))}),()=>{};throw ve()}return this.attach(t,n,r,s,{origin:"listener",result:"allow",evaluation:l,at:c},i,a)}adminOnValue(t,n,r){return this.attach(null,t,n,r,{origin:"admin",result:"not-applicable",evaluation:void 0,at:Date.now()})}attach(t,n,r,s,i,a,c){const l=this.state.events.nextListenerId();this.state.events.operation(t,"listen",n,i.result,i.evaluation,{at:i.at,durationMs:Date.now()-i.at,request:s?{query:s}:void 0,origin:i.origin});const u={id:l,auth:t,cb:r,path:n,query:s,cancelCallback:a,onCanceled:c};if(this.state.valueListeners.add(u),this.state.events.listener("attach",u,t,{event:"value",result:"allow",detail:s?{query:s}:void 0}),s){const d=We(this.state.tree.read(n),s,this.state.priorities.forChild(n));u.lastWindow=d,this.deliverInitial(u,{val:Ms(d),exists:d.length>0,key:this.key(n),rows:d},{initial:!0,query:!0})}else{const d=this.snapshot(n);u.lastValue=d.val,u.lastPriorityState=this.state.priorities.stateAtOrBelow(n),this.deliverInitial(u,d,{initial:!0})}return()=>{this.state.valueListeners.delete(u),this.state.events.listener("detach",u,t,{event:"value"})}}fanOut(t){if(this.state.valueListeners.size===0)return;const n=t.map(r=>J(L(r)));for(const r of this.state.valueListeners){const s=J(L(r.path));if(!n.some(c=>Fu(s,c)))continue;if(r.query){const c=We(this.state.tree.read(r.path),r.query,this.state.priorities.forChild(r.path));if(Bu(r.lastWindow??[],c)){this.state.events.listener("suppressed",r,r.auth,{event:"value",reason:"no-op",detail:{query:!0}});continue}r.lastWindow=c,this.deliver(r,{val:Ms(c),exists:c.length>0,key:this.key(r.path),rows:c},{query:!0});continue}const i=this.snapshot(r.path),a=this.state.priorities.stateAtOrBelow(r.path);if(at(r.lastValue??null,i.val)&&r.lastPriorityState===a){this.state.events.listener("suppressed",r,r.auth,{event:"value",reason:"no-op"});continue}r.lastValue=i.val,r.lastPriorityState=a,this.deliver(r,i,{})}}off(t,n){const r=J(L(t));for(const s of[...this.state.valueListeners])J(L(s.path))===r&&(n!==void 0&&s.cb!==n||(this.state.valueListeners.delete(s),this.state.events.listener("detach",s,s.auth,{event:"value"})))}count(){return this.state.valueListeners.size}snapshot(t){const n=this.state.tree.read(t);return{val:n,exists:n!==null,key:this.key(t)}}key(t){const n=L(t);return n.length===0?null:n[n.length-1]}deliver(t,n,r){this.state.events.listener("delivery",t,t.auth,{event:"value",size:n.rows?.length??(n.exists?1:0),sample:n.val,detail:r});try{t.cb(n)}catch(s){this.state.events.listener("errored",t,t.auth,{event:"value",result:"error",error:{message:s instanceof Error?s.message:String(s)},detail:r})}}deliverInitial(t,n,r){try{t.cb(n),this.state.events.listener("delivery",t,t.auth,{event:"value",size:n.rows?.length??(n.exists?1:0),sample:n.val,detail:r})}catch(s){this.state.events.listener("errored",t,t.auth,{event:"value",result:"error",error:{message:s instanceof Error?s.message:String(s)},detail:r})}}}function Fu(e,t){if(e===t||e==="/")return!0;const n=`${e}/`,r=t==="/"?"/":`${t}/`;return t.startsWith(n)||e.startsWith(r)}function Je(e,t){const n=e.findIndex(r=>r.key===t);return n>0?e[n-1].key:null}function bt(e,t){const n=e.findIndex(r=>r.key===t);return n>0?e[n-1].key:null}function Us(e,t){if(t===void 0)return null;const n=L(e),r=L(t);return r.length!==n.length+1||!n.every((s,i)=>r[i]===s)?null:r[r.length-1]??null}class Vu{state;constructor(t){this.state=t}onChild(t,n,r,s,i,a,c){const l=Date.now(),u=this.state.events.nextListenerId(),d=this.state.rules.evaluate("read",r==="/"?"/":r,{auth:t,mockData:this.state.tree.snapshot()});if(d.check!=="allow"){this.state.events.operation(t,"listen",r,he(d.check),d,{at:l,durationMs:Date.now()-l,origin:"listener",detail:{event:n}});const f={engine:"rtdb",matchedPath:d.matchedPath,matchedRule:d.matchedRule,pathVariableBindings:d.pathVariableBindings,reason:d.reason,errorCode:d.errorCode};if(this.state.events.listener("errored",{id:u,path:r},t,{event:n,result:"deny",error:{code:"PERMISSION_DENIED",message:"PERMISSION_DENIED: Permission denied",reasons:d.reasons},reasons:d.reasons,rules:f}),a)return queueMicrotask(()=>{c&&c(),a(Xr(r))}),()=>{};throw ve()}this.state.events.operation(t,"listen",r,"allow",d,{at:l,durationMs:Date.now()-l,origin:"listener",detail:{event:n}});const p={id:u,auth:t,event:n,path:r,cb:s,spec:i,cancelCallback:a,onCanceled:c};if(this.state.childListeners.add(p),this.state.events.listener("attach",p,t,{event:n,result:"allow",detail:i?{query:i}:void 0}),i){const f=We(this.state.tree.read(r),i,this.state.priorities.forChild(r));if(p.lastWindow=f,n==="child_added")for(const{key:m,value:y}of f)this.deliver(p,{key:m,val:y,previousChildName:Je(f,m)},{initial:!0,query:!0})}else if(n==="child_added")for(const{key:f,val:m}of this.directChildren(r)){const y=this.directChildren(r);this.deliver(p,{key:f,val:m,previousChildName:bt(y,f)},{initial:!0})}return()=>{this.state.childListeners.delete(p),this.state.events.listener("detach",p,t,{event:n})}}off(t,n,r){const s=J(L(t));for(const i of[...this.state.childListeners])n!==void 0&&i.event!==n||J(L(i.path))===s&&(r!==void 0&&i.cb!==r||(this.state.childListeners.delete(i),this.state.events.listener("detach",i,i.auth,{event:i.event})))}snapshotParents(){const t=new Map;for(const n of this.state.childListeners){const r=J(L(n.path));t.has(r)||t.set(r,new Map(this.directChildren(r).map(({key:s,val:i})=>[s,i])))}return t}fanOut(t,n){if(this.state.childListeners.size===0)return;const r=new Map;for(const s of this.state.childListeners){if(s.spec){this.fanOutQuery(s,n);continue}const i=J(L(s.path)),a=r.get(i)??[];a.push(s),r.set(i,a)}for(const[s,i]of r){const a=t.get(s)??new Map,c=new Map(this.directChildren(s).map(({key:f,val:m})=>[f,m])),l=[...c].map(([f,m])=>({key:f,val:m})),u=[...a].map(([f,m])=>({key:f,val:m})),d={child_added:[],child_changed:[],child_removed:[],child_moved:[]};for(const[f,m]of c)a.has(f)?at(a.get(f),m)||d.child_changed.push({key:f,val:m,previousChildName:bt(l,f)}):d.child_added.push({key:f,val:m,previousChildName:bt(l,f)});for(const[f,m]of a)c.has(f)||d.child_removed.push({key:f,val:m,previousChildName:bt(u,f)});const p=Us(s,n);p!==null&&a.has(p)&&c.has(p)&&d.child_moved.push({key:p,val:c.get(p),previousChildName:bt(l,p)});for(const f of i)for(const m of d[f.event])this.deliver(f,m,{})}}count(){return this.state.childListeners.size}directChildren(t){const n=this.state.tree.read(t);return n===null||typeof n!="object"||Array.isArray(n)?[]:We(n,{orderBy:{kind:"priority"},bounds:[],limit:null},this.state.priorities.forChild(t)).map(({key:r,value:s})=>({key:r,val:s}))}fanOutQuery(t,n){const r=t.lastWindow??[],s=We(this.state.tree.read(t.path),t.spec,this.state.priorities.forChild(t.path));t.lastWindow=s;const i=new Map(r.map(l=>[l.key,l.value])),a=new Map(s.map(l=>[l.key,l.value])),c=[];if(t.event==="child_added")for(const l of s)i.has(l.key)||c.push({key:l.key,val:l.value,previousChildName:Je(s,l.key)});else if(t.event==="child_changed")for(const l of s)i.has(l.key)&&!at(i.get(l.key),l.value)&&c.push({key:l.key,val:l.value,previousChildName:Je(s,l.key)});else if(t.event==="child_removed")for(const l of r)a.has(l.key)||c.push({key:l.key,val:l.value,previousChildName:Je(r,l.key)});else if(t.spec?.orderBy&&t.spec.orderBy.kind!=="key"){const l=t.spec.orderBy.kind==="priority"?Us(t.path,n):null;let u=!1;if(l!==null){const d=s.find(p=>p.key===l);d&&i.has(l)&&(c.push({key:d.key,val:d.value,previousChildName:Je(s,d.key)}),u=!0)}if(!u){const d=new Map(r.map(p=>[p.key,p]));for(const p of s){const f=d.get(p.key);if(!f)continue;const m=Et(t.spec.orderBy,f.key,f.value,f.priority),y=Et(t.spec.orderBy,p.key,p.value,p.priority);Qr(m,y)!==0&&c.push({key:p.key,val:p.value,previousChildName:Je(s,p.key)})}}}for(const l of c)this.deliver(t,l,{query:!0})}deliver(t,n,r){this.state.events.listener("delivery",t,t.auth,{event:t.event,size:1,sample:r.query?{key:n.key,val:n.val}:n,detail:r});try{t.cb(n)}catch(s){this.state.events.listener("errored",t,t.auth,{event:t.event,result:"error",error:{message:s instanceof Error?s.message:String(s)},detail:r})}}}function qu(e){const t=e!==null;let n=!1;if(t){const r=typeof e=="object",s=Array.isArray(e);r&&(s||(n=!0))}if(n){const r=e,i=r[".pyricRtdbPersistence"]===1,a="data"in r;let c=!1;i&&a&&(c=!0);const l=r.priorities,u=l!==null,d=l!==void 0;let p=!1;if(u&&d){const m=typeof l=="object",y=Array.isArray(l);m&&(y||(p=!0))}let f=!1;if(c&&p&&(f=!0),f){const m={},y=Object.entries(l);for(const[j,S]of y){const N=typeof S=="string",P=typeof S=="number";let I=!1;P&&Number.isFinite(S)&&(I=!0);let D=!1;N&&(D=!0),I&&(D=!0),D&&(m[j]=S)}const g=r.data;let v=null;g!==void 0&&g!==null&&(v=g);const w=r.rules;let x=null;if(w!==void 0&&w!==null){const S=typeof w=="object",N=Array.isArray(w);let P=!1;if(S&&(N||(P=!0)),P){const I=w;if("rules"in I){const C=I.rules;if(C!==null&&C!==void 0){const R=typeof C=="object",V=Array.isArray(C);let G=!1;R&&(V||(G=!0)),G&&(x={rules:C})}}}}return{data:v,priorities:m,rules:x}}}return{data:e,priorities:{},rules:null}}class Wu{state;values;children;constructor(t,n,r){this.state=t,this.values=n,this.children=r}exportTree(){return this.state.tree.snapshot()}exportState(){const t=this.state.activeRules!==null,n={".pyricRtdbPersistence":1,data:this.state.tree.snapshot(),priorities:Object.fromEntries(this.state.priorities.entries())};return t&&(n.rules=structuredClone(this.state.activeRules)),n}restore(t){const n=this.children.snapshotParents(),r=qu(t);let s={};const i=r.data===null,a=r.data===void 0;let c=!1;i||a||(c=!0),c&&(s=r.data),r.rules!==null?(this.state.rules.setRules(r.rules),this.state.activeRules=structuredClone(r.rules)):(this.state.rules.setRules(null),this.state.activeRules=null),this.state.tree.restore(s),this.state.priorities.restore(r.priorities),this.state.mutations.mark("/"),this.values.fanOut(["/"]),this.children.fanOut(n)}reset(){this.state.resetGeneration+=1,this.restore(null)}subscribe(t){return this.state.writeSubscribers.add(t),()=>{this.state.writeSubscribers.delete(t)}}}const zu=/[\[\].#$/\u0000-\u001F\u007F]/;function Ku(e){return e.length!==0&&!zu.test(e)}function Hu(e){return typeof e=="number"&&(Number.isNaN(e)||e===1/0||e===-1/0)}function Gu(e){return e===".priority"||e===".value"||e===".sv"}function Ju(e,t){hr(e,t,"set")}function hr(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(Hu(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&&hr(s,`${t}/${r}`,n)}return}for(const[r,s]of Object.entries(e)){if(!Gu(r)&&!Ku(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 "]"`);hr(s,`${t}/${r}`,n)}}}function Be(e,t){return Ju(e,t),pr(e)}function pr(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=pr(e[r]);s!==null&&(n[String(r)]=s)}return Object.keys(n).length===0?null:n}const t={};for(const[n,r]of Object.entries(e)){if(n===".sv"){t[n]=r;continue}const s=pr(r);s!==null&&(t[n]=s)}return Object.keys(t).length===0?null:t}function Xt(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(a=>Xt(a));const t=e,n=Object.keys(t);let r=n.length>0,s=0;for(const a of n)if(/^(0|[1-9]\d*)$/.test(a))s=Math.max(s,Number(a));else{r=!1;break}if(r&&s<2*n.length){const a=[];for(let c=0;c<=s;c++){const l=t[String(c)];a[c]=l===void 0?null:Xt(l)}return a}const i={};for(const[a,c]of Object.entries(t))i[a]=Xt(c);return i}function Yu(e){return e===null||typeof e!="object"?!1:e[".sv"]==="timestamp"}function Qu(e){if(e===null||typeof e!="object")return!1;const t=e[".sv"];return t!==null&&typeof t=="object"&&typeof t.increment=="number"}function we(e,t,n){if(Yu(e))return t;if(Qu(e)){const i=e[".sv"].increment;return(typeof n=="number"?n:0)+i}if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map((i,a)=>we(i,t,Array.isArray(n)?n[a]:void 0));const r=n!==null&&typeof n=="object"&&!Array.isArray(n)?n:void 0,s={};for(const[i,a]of Object.entries(e))s[i]=we(a,t,r?r[i]:void 0);return s}function Ts(){return new Error("permission_denied")}class Xu{state;values;children;constructor(t,n,r){this.state=t,this.values=n,this.children=r}run(t,n,r,s){const i=s?.applyLocally!==!1,a=L(n),c=a.length===0?null:a[a.length-1];let l=null,u,d=0,p=!1;do{d+=1;const x=this.state.mutations.begin();l=this.state.tree.read(n);const k=l===null?null:Xt(Ne(l));let j=!1;try{u=r(k),j=this.state.mutations.conflictsSince(x,n)}finally{this.state.mutations.release(x)}if(!j||u===void 0){p=!0;break}}while(d<25);if(!p)throw new Error("maxretry");const f=this.state.events.nextGroupId("transaction");if(u===void 0)return this.state.events.operation(t,"transaction",n,"not-applicable",void 0,{origin:"transaction",groupId:f,groupKind:"transaction",resourceBefore:{data:l,exists:l!==null},detail:{committed:!1,aborted:!0}}),{committed:!1,val:l,key:c};const m=Date.now(),y=Be(we(u,m,l),n==="/"?"":n);if(i){const x=this.state.tree.snapshot(),k=Object.fromEntries(this.state.priorities.entries()),j=this.state.priorities.get(n),S=this.children.snapshotParents();this.state.tree.write(n,y),this.state.priorities.replace(n,j),this.values.fanOut([n]),this.children.fanOut(S);const N=Date.now(),P=this.state.rules.evaluate("write",n==="/"?"/":n,{auth:t,mockData:x,newData:y});if(P.check!=="allow"){this.state.events.operation(t,"transaction",n,he(P.check),P,{at:N,durationMs:Date.now()-N,origin:"transaction",request:{data:u,resourceData:u},resourceBefore:{data:l,exists:l!==null},resourceAfter:{data:y,exists:y!==null},groupId:f,groupKind:"transaction"});const I=this.children.snapshotParents();throw this.state.tree.restore(x),this.state.priorities.restore(k),this.values.fanOut([n]),this.children.fanOut(I),Ts()}return this.recordCommit(t,n,u,l,y,f,m,N,!0,P),{committed:!0,val:y,key:c}}const g=Date.now(),v=this.state.rules.evaluate("write",n==="/"?"/":n,{auth:t,mockData:this.state.tree.snapshot(),newData:y});if(v.check!=="allow")throw this.state.events.operation(t,"transaction",n,he(v.check),v,{at:g,durationMs:Date.now()-g,origin:"transaction",request:{data:u,resourceData:u},resourceBefore:{data:l,exists:l!==null},resourceAfter:{data:y,exists:y!==null},groupId:f,groupKind:"transaction"}),Ts();this.state.events.operation(t,"transaction",n,"allow",v,{at:g,durationMs:Date.now()-g,origin:"transaction",request:{data:u,resourceData:u},resourceBefore:{data:l,exists:l!==null},resourceAfter:{data:y,exists:y!==null},groupId:f,groupKind:"transaction"});const b=this.state.priorities.get(n),w=this.children.snapshotParents();return this.state.tree.write(n,y),this.state.priorities.replace(n,b),this.state.mutations.mark(n),this.values.fanOut([n]),this.children.fanOut(w),this.finishEvents(t,n,u,l,y,f,m,!1),this.state.notifyWrite(),{committed:!0,val:y,key:c}}recordCommit(t,n,r,s,i,a,c,l,u,d){this.state.events.operation(t,"transaction",n,"allow",d,{at:l,durationMs:Date.now()-l,origin:"transaction",request:{data:r,resourceData:r},resourceBefore:{data:s,exists:s!==null},resourceAfter:{data:i,exists:i!==null},groupId:a,groupKind:"transaction"}),this.finishEvents(t,n,r,s,i,a,c,u),this.state.mutations.mark(n),this.state.notifyWrite()}finishEvents(t,n,r,s,i,a,c,l){this.state.events.commit(t,"transaction",n,{data:r,priorState:s,nextState:i,groupId:a,groupKind:"transaction",replay:{requestTime:c},detail:{committed:!0,applyLocally:l}}),this.state.events.mutation(t,"transaction",xe(n),{before:s,after:i,detail:{committed:!0}})}}class Zu{state;values;children;constructor(t,n,r){this.state=t,this.values=n,this.children=r}adminSet(t,n){if(rn(n),this.state.tree.read(t)===null)return;const r=this.children.snapshotParents(),s=this.state.priorities.get(t)!==n;this.state.priorities.set(t,n),this.state.mutations.mark(t),s&&this.values.fanOut([t]),this.children.fanOut(r,s?t:void 0),this.state.notifyWrite()}set(t,n,r){rn(r);const s=this.state.tree.read(n),i=Date.now(),a=this.state.rules.evaluate("write",n==="/"?"/":n,{auth:t,mockData:this.state.tree.snapshot(),newData:s}),c=this.state.priorities.get(n),l={at:i,durationMs:Date.now()-i,request:{data:r},resourceBefore:{data:s,exists:s!==null},resourceAfter:{data:s,exists:s!==null},detail:{priority:r,priorPriority:c}};if(a.check!=="allow")throw this.state.events.operation(t,"setPriority",n,he(a.check),a,l),ve();if(this.state.events.operation(t,"setPriority",n,"allow",a,l),s===null)return;const u=this.children.snapshotParents(),d=c!==r;this.state.priorities.set(n,r),this.state.mutations.mark(n),d&&this.values.fanOut([n]),this.children.fanOut(u,d?n:void 0),d&&(this.state.events.commit(t,"setPriority",n,{data:r,priorState:c,nextState:r,detail:{priority:r,priorPriority:c}}),this.state.events.mutation(t,"setPriority",xe(n),{before:c,after:r,detail:{priorityMetadata:!0}})),this.state.notifyWrite()}}function Bs(e){return e.length===0?null:Object.fromEntries(e.map(({key:t,value:n})=>[t,n]))}class ed{state;values;children;priorityWrites;constructor(t,n,r){this.state=t,this.values=n,this.children=r,this.priorityWrites=new Zu(t,n,r)}setData(t){this.state.tree.restore({}),this.state.priorities.clear();for(const[n,r]of Object.entries(t))this.state.tree.write(n,Be(we(r,Date.now()),n==="/"?"":n));this.state.mutations.mark("/"),this.state.notifyWrite()}setRules(t){t===null?this.state.activeRules=null:this.state.activeRules=structuredClone(t),this.state.rules.setRules(t),this.cancelDeniedListeners(),this.state.notifyWrite()}getActiveRules(){const t=this.state.activeRules===null;let n=null;return t||(n=structuredClone(this.state.activeRules)),n}snapshotState(){return this.state.tree.snapshot()}adminGet(t){const n=this.state.tree.read(t);return this.state.events.operation(null,"get",t,"not-applicable",void 0,{origin:"admin",resourceBefore:{data:n,exists:n!==null}}),n}adminGetQuery(t,n){const r=We(this.state.tree.read(t),n,this.state.priorities.forChild(t));return this.state.events.operation(null,"get",t,"not-applicable",void 0,{origin:"admin",request:{query:n},resourceBefore:{data:Bs(r),exists:r.length>0}}),r}adminSet(t,n){this.adminSetWithPriority(t,n,null,!1)}adminSetWithPriority(t,n,r,s=!0){rn(r);const i=Date.now(),a=this.state.tree.read(t),c=Be(we(n,i,a),t==="/"?"":t),l=c===null?"remove":"set";this.state.events.operation(null,l,t,"not-applicable",void 0,{origin:"admin",request:{data:n,resourceData:n},resourceBefore:{data:a,exists:a!==null},resourceAfter:{data:c,exists:c!==null}});const u=this.children.snapshotParents(),d=this.state.priorities.get(t),p=this.state.priorities.stateAtOrBelow(t);this.state.tree.write(t,c),this.state.priorities.replace(t,c===null?null:r);const f=p!==this.state.priorities.stateAtOrBelow(t);this.changed([t],u,f?t:void 0);const m=this.state.tree.read(t);this.state.events.commit(null,m===null?"remove":"set",t,{data:n,priorState:a,nextState:m,replay:{requestTime:i},detail:s?{admin:!0,priority:r,priorPriority:d}:{admin:!0}}),this.state.notifyWrite()}adminUpdate(t,n){const r=Date.now(),s=this.state.tree.read(t),i=this.resolvePatch(t,n,r),a=Object.keys(n).some(u=>u.includes("/"));this.state.events.operation(null,"update",t,"not-applicable",void 0,{origin:"admin",request:{data:n,resourceData:n},resourceBefore:{data:s,exists:s!==null},detail:a?{admin:!0,multiPath:!0,paths:Object.keys(i)}:{admin:!0,multiPath:!1,keys:Object.keys(n)}});const c=this.children.snapshotParents();a?this.state.tree.multiUpdate(i):this.state.tree.shallowUpdate(t,Object.fromEntries(Object.entries(i).map(([u,d])=>[L(u).at(-1),d]))),this.state.priorities.applyUpdate(Object.entries(i).map(([u,d])=>({path:u,value:d}))),this.changed(Object.keys(i),c);const l=a?{admin:!0,multiPath:!0,paths:Object.keys(i)}:{admin:!0,multiPath:!1,keys:Object.keys(n)};this.state.events.commit(null,"update",t,{data:n,priorState:s,nextState:this.state.tree.read(t),replay:{requestTime:r},detail:l}),this.state.notifyWrite()}adminRemove(t){this.adminSet(t,null)}adminSetPriority(t,n){this.priorityWrites.adminSet(t,n)}get(t,n){const r=Date.now(),s=this.state.tree.read(n),i=this.readEvaluation(t,n);if(i.check!=="allow")throw this.state.events.operation(t,"get",n,he(i.check),i,{at:r,durationMs:Date.now()-r,resourceBefore:{data:s,exists:s!==null}}),ve();return this.state.events.operation(t,"get",n,"allow",i,{at:r,durationMs:Date.now()-r,resourceBefore:{data:s,exists:s!==null}}),this.state.tree.read(n)}getQuery(t,n,r){const s=Date.now(),i=this.readEvaluation(t,n);if(i.check!=="allow")throw this.state.events.operation(t,"get",n,he(i.check),i,{at:s,durationMs:Date.now()-s,request:{query:r}}),ve();const a=We(this.state.tree.read(n),r,this.state.priorities.forChild(n));return this.state.events.operation(t,"get",n,"allow",i,{at:s,durationMs:Date.now()-s,request:{query:r},resourceBefore:{data:Bs(a),exists:a.length>0}}),a}set(t,n,r){this.setInternal(t,n,r,"set",null,!1)}setWithPriority(t,n,r,s){rn(s),this.setInternal(t,n,r,"set",s,!0)}remove(t,n){this.setInternal(t,n,null,"remove",null,!1)}setPriority(t,n,r){this.priorityWrites.set(t,n,r)}validateSet(t,n,r){const s=Be(we(r,Date.now(),this.state.tree.read(n)),n==="/"?"":n);if(this.writeEvaluation(t,n,s).check!=="allow")throw ve()}validateUpdate(t,n,r){const s=this.state.tree.snapshot(),i=Object.entries(r).map(([a,c])=>{const l=J([...L(n),...L(a)]);return{path:l,value:Be(we(c,Date.now(),this.state.tree.read(l)),l)}});for(const a of i)if(this.state.rules.evaluate("write",a.path,{auth:t,mockData:s,newData:a.value,...i.length>1?{updates:i}:{}}).check!=="allow")throw ve()}update(t,n,r){const s=Date.now(),i=this.resolvePatch(n,r,s),a=Object.keys(r).some(y=>y.includes("/")),c=this.state.tree.snapshot(),l=Object.entries(i).map(([y,g])=>({path:y,value:g})),u=Object.fromEntries(Object.entries(i).map(([y,g])=>[L(y).at(-1),g])),d=this.state.events.nextGroupId("update");for(const y of l){const g=Date.now(),v=this.state.tree.read(y.path),b=this.state.rules.evaluate("write",y.path,{auth:t,mockData:c,newData:y.value,...a?{updates:l}:{}}),w={at:g,durationMs:Date.now()-g,origin:"batch",request:{data:y.value,resourceData:y.value},resourceBefore:{data:v,exists:v!==null},resourceAfter:{data:y.value,exists:y.value!==null},groupId:d,groupKind:"batch",detail:a?{multiPath:!0,rootPath:xe(n)}:{multiPath:!1,rootPath:xe(n),key:L(y.path).at(-1)}};if(b.check!=="allow")throw this.state.events.operation(t,"update",y.path,he(b.check),b,w),ve();this.state.events.operation(t,"update",y.path,"allow",b,w)}const p=this.state.tree.read(n),f=this.children.snapshotParents();a?this.state.tree.multiUpdate(i):this.state.tree.shallowUpdate(n,u),this.state.priorities.applyUpdate(l),this.changed(Object.keys(i),f);const m=this.state.tree.read(n);this.state.events.commit(t,"update",n,{data:r,priorState:p,nextState:m,groupId:d,groupKind:"batch",replay:{requestTime:s},detail:a?{multiPath:!0,paths:Object.keys(i)}:{multiPath:!1,keys:Object.keys(u)}}),this.state.events.mutation(t,"update",xe(n),{after:a?i:u,detail:a?{multiPath:!0,paths:Object.keys(i)}:{multiPath:!1,keys:Object.keys(u)}}),this.state.notifyWrite()}setInternal(t,n,r,s,i,a){const c=Date.now(),l=Be(we(r,c,this.state.tree.read(n)),n==="/"?"":n),u=this.state.tree.read(n),d=this.state.priorities.get(n),p=Date.now(),f=this.writeEvaluation(t,n,l),m={at:p,durationMs:Date.now()-p,request:{data:r,resourceData:r},resourceBefore:{data:u,exists:u!==null},resourceAfter:{data:l,exists:l!==null}};if(f.check!=="allow")throw this.state.events.operation(t,s,n,he(f.check),f,m),ve();this.state.events.operation(t,s,n,"allow",f,m);const y=this.children.snapshotParents(),g=this.state.priorities.stateAtOrBelow(n);this.state.tree.write(n,l),this.state.priorities.replace(n,l===null?null:i);const v=g!==this.state.priorities.stateAtOrBelow(n);this.changed([n],y,v?n:void 0);const b=this.state.tree.read(n),w=b===null?"remove":s;this.state.events.commit(t,w,n,{data:r,priorState:u,nextState:b,replay:{requestTime:c},...a?{detail:{priority:i,priorPriority:d}}:{}}),this.state.events.mutation(t,w,xe(n),{before:u,after:b}),this.state.notifyWrite()}resolvePatch(t,n,r){return Object.fromEntries(Object.entries(n).map(([s,i])=>{const a=J([...L(t),...L(s)]);return[a,Be(we(i,r,this.state.tree.read(a)),a)]}))}changed(t,n,r){this.state.mutations.mark(t),this.values.fanOut(t),this.children.fanOut(n,r)}cancelDeniedListeners(){const t=this.state.tree.snapshot(),n=[];for(const s of[...this.state.valueListeners]){const i=this.state.rules.evaluate("read",s.path,{auth:s.auth,mockData:t});if(i.check==="allow")continue;this.state.valueListeners.delete(s),this.state.events.operation(s.auth,"listen",s.path,he(i.check),i,{origin:"listener"});const a={engine:"rtdb",matchedPath:i.matchedPath,matchedRule:i.matchedRule,pathVariableBindings:i.pathVariableBindings,reason:i.reason,errorCode:i.errorCode};this.state.events.listener("errored",s,s.auth,{event:"value",result:"deny",error:{code:"PERMISSION_DENIED",message:"PERMISSION_DENIED: Permission denied",reasons:i.reasons},reasons:i.reasons,rules:a}),n.push(s)}const r=[];for(const s of[...this.state.childListeners]){const i=this.state.rules.evaluate("read",s.path,{auth:s.auth,mockData:t});if(i.check==="allow")continue;this.state.childListeners.delete(s),this.state.events.operation(s.auth,"listen",s.path,he(i.check),i,{origin:"listener",detail:{event:s.event}});const a={engine:"rtdb",matchedPath:i.matchedPath,matchedRule:i.matchedRule,pathVariableBindings:i.pathVariableBindings,reason:i.reason,errorCode:i.errorCode};this.state.events.listener("errored",s,s.auth,{event:s.event,result:"deny",error:{code:"PERMISSION_DENIED",message:"PERMISSION_DENIED: Permission denied",reasons:i.reasons},reasons:i.reasons,rules:a}),r.push(s)}for(const s of[...n,...r]){try{s.onCanceled&&s.onCanceled()}catch{}try{s.cancelCallback&&s.cancelCallback(Xr(s.path))}catch{}}}readEvaluation(t,n){return this.state.rules.evaluate("read",n==="/"?"/":n,{auth:t,mockData:this.state.tree.snapshot()})}writeEvaluation(t,n,r){return this.state.rules.evaluate("write",n==="/"?"/":n,{auth:t,mockData:this.state.tree.snapshot(),newData:r})}}class td{state;values;children;writes;transactions;persistence;constructor(t){this.state=new $u(t),this.values=new Lu(this.state),this.children=new Vu(this.state),this.writes=new ed(this.state,this.values,this.children),this.transactions=new Xu(this.state,this.values,this.children),this.persistence=new Wu(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)}getActiveRules(){return this.writes.getActiveRules()}snapshotState(){return this.writes.snapshotState()}adminGet(t){return this.writes.adminGet(t)}adminGetQuery(t,n){return this.writes.adminGetQuery(t,n)}adminSet(t,n){this.writes.adminSet(t,n)}adminSetWithPriority(t,n,r){this.writes.adminSetWithPriority(t,n,r)}adminUpdate(t,n){this.writes.adminUpdate(t,n)}adminRemove(t){this.writes.adminRemove(t)}adminSetPriority(t,n){this.writes.adminSetPriority(t,n)}get(t,n){return this.writes.get(t,n)}getQuery(t,n,r){return this.writes.getQuery(t,n,r)}set(t,n,r){this.writes.set(t,n,r)}setWithPriority(t,n,r,s){this.writes.setWithPriority(t,n,r,s)}update(t,n,r){this.writes.update(t,n,r)}remove(t,n){this.writes.remove(t,n)}setPriority(t,n,r){this.writes.setPriority(t,n,r)}validateSet(t,n,r){this.writes.validateSet(t,n,r)}validateUpdate(t,n,r){this.writes.validateUpdate(t,n,r)}onValue(t,n,r,s,i,a){return this.values.onValue(t,n,r,s,i,a)}adminOnValue(t,n,r){return this.values.adminOnValue(t,n,r)}runTransaction(t,n,r,s){return this.transactions.run(t,n,r,s)}onChild(t,n,r,s,i,a,c){return this.children.onChild(t,n,r,s,i,a,c)}off(t,n,r){(n===void 0||n==="value")&&this.values.off(t,r),n!=="value"&&this.children.off(t,n,r)}exportTree(){return this.persistence.exportTree()}exportPersistenceState(){return this.persistence.exportState()}restoreTree(t){this.persistence.restore(t)}resetTree(){this.persistence.reset()}subscribeWrites(t){return this.persistence.subscribe(t)}mintKey(){return Cl()}listenerCount(){return this.values.count()}childListenerCount(){return this.children.count()}}const Ls=new WeakMap;function Ba(e){let t=Ls.get(e);if(t)return t;t=new td(e),Ls.set(e,t);const n=t;return e.onEvent(r=>{r.kind==="session_boundary"&&r.phase==="reset"&&n.invalidateConnectionQueues()}),e.registerPersistableService("rtdb",{snapshot:()=>n.exportPersistenceState(),restore:r=>{n.restoreTree(r)},subscribe:r=>n.subscribeWrites(r),reset:()=>{n.resetTree()}}),t}function La(e){return Ba(e).getActiveRules()}function Fs(e){return Ba(e).snapshotState()}const Fa=new WeakMap;function nd(e){return Fa.get(e)?.raw??e}const rd=new WeakMap,Vs=new WeakMap;function mr(e,t,n,r,s){Fa.set(e,{target:n,path:t.ref.path,kind:s,converter:r,raw:t})}function sd(e,t){const n=ir(e),r=ir(t);return n.isStructurallyEqual?.(r)??n===r}function id(e,t,n,r){const s=e,i=(Vs.get(s)??[]).filter(c=>c.query.deref()!==void 0),a=i.find(c=>{const l=c.query.deref();return l!==void 0&&sd(l,t)});if(a!==void 0){const c=ad(a.docs,n)&&a.metadata.fromCache===r.fromCache&&a.metadata.hasPendingWrites===r.hasPendingWrites;return a.docs=n,a.metadata=r,c?"settled":"initial"}return i.push({query:new WeakRef(t),docs:n,metadata:r}),Vs.set(s,i),"initial"}function ad(e,t){return e.length===t.length&&e.every((n,r)=>{const s=t[r];return n.path===s.path&&Nl(n.data,s.data)})}function yr(e,t,n,r,s){const i=t,a=d=>({path:d.ref?.path??"",data:Jr(d.data?.(),n)}),c=Object.freeze((i.docs??[]).map(a)),l=Object.freeze((i.docChanges?.()??[]).map(d=>({...a(d.doc??{}),type:d.type??"",oldIndex:d.oldIndex??-1,newIndex:d.newIndex??-1}))),u=Object.freeze({fromCache:i.metadata?.fromCache===!0,hasPendingWrites:i.metadata?.hasPendingWrites===!0});rd.set(e,{target:n,query:r,converter:xn(r)??null,source:s,...s==="read"?{readPhase:id(n,r,c,u)}:{},metadata:u,docs:c,changes:l})}function an(e,t){const n=e,r=n.data.bind(e);return Object.defineProperty(n,"data",{value:()=>_a(r()),configurable:!0,writable:!0}),t&&n.ref?.path&&Object.defineProperty(n,"metadata",{value:Ie(t).snapshotMetadata(n.ref.path),configurable:!0}),e}function Va(e,t,n,r){const s={id:e.id,ref:e.ref,exists:e.exists,metadata:Ie(n).snapshotMetadata(e.ref.path),data:()=>{if(!(typeof e.exists=="function"?e.exists():e.exists))return;const a=_a(e.data()),c={id:e.id,ref:e.ref,exists:!0,metadata:Ie(n).snapshotMetadata(e.ref.path),data:()=>a};return t.fromFirestore(c)}};return Fe(s,n),Fe(e.ref,n),br(e.ref,n),mr(s,e,n,t,r),s}function _n(e,t){if(!e||typeof e!="object")return e;Fe(e,t);const n=e;if(n.ref&&(Fe(n.ref,t),br(n.ref,t)),qs(n),Array.isArray(n.docs))for(const r of n.docs)r&&(Fe(r,t),mr(r,r,t,null,"query-child")),r?.ref&&(Fe(r.ref,t),br(r.ref,t)),r&&qs(r);else n.ref&&mr(e,e,t,null,"document");return e}function br(e,t){if(typeof e.path!="string"||e.path.length===0)return;const n=e.path;try{const r=Ss.get(e),s=r??Gr(t).doc(n);r===void 0&&Ss.set(e,s),ol(e,n,t,s),t.kind==="sandbox-live"&&Ea.set(s,i=>i.doc(n))}catch{}}function qs(e){const t=e.exists;if(typeof t=="function")return;const n=t===!0;try{Object.defineProperty(e,"exists",{value:()=>n,writable:!0,configurable:!0,enumerable:!0})}catch{}}async function qa(e){const t=jn(e),n=Ie(t);n.markStarted();const r=xn(e),s=await Rl(t,e).get();return n.cachePath(e.path),r?Va(s,r,t,"document"):(_n(s,t),an(s,t))}async function on(e){const t=jn(e),n=Ie(t);n.markStarted();const r=xn(e),s=await Al(t,e).get();if(n.cacheQuery(e),r){const a=r,c=s.docs.map(u=>Va(u,a,t,"query-child")),l=Fe({size:c.length,empty:c.length===0,docs:c,metadata:n.querySnapshotMetadata()},t);for(const u of c)n.cachePath(u.ref.path);return yr(l,s,t,e,"read"),l}_n(s,t);const i=s.docs;for(const a of i)n.cachePath(a.ref.path),an(a,t);return Object.defineProperty(s,"metadata",{value:n.querySnapshotMetadata(),configurable:!0}),yr(s,s,t,e,"read"),s}function Wa(e){return typeof e=="string"?e:e._internalPath.segments.join(".")}function cn(e,...t){const n=jn(e),r=xn(e),s=Il(e);let i,a;try{i=t.map(u=>u.prepareSandbox?.(n)??u)}catch(u){throw _s(u)}const c=u=>{let d=s(u);for(const p of i)d=p.applySandbox(d);return d};try{a=c(Gr(n))}catch(u){throw _s(u)}const l=Dl(a,n,u=>c(u));return r?Pl(l,n,r):l}function od(e,t,n){return za(Wa(e),t,n,!1)}function za(e,t,n,r){return{type:"where",applySandbox:i=>i.where(e,t,n),prepareSandbox:r?void 0:i=>{const a=Jr(n,i,t==="in"||t==="not-in");return za(e,t,a.executionValue,!0)},_sandboxFilter:{kind:"where",field:e,op:t,value:n}}}function Ws(e,t){const n=Wa(e);return{type:"orderBy",applySandbox:r=>r.orderBy(n,t)}}function ln(e){return{type:"limit",applySandbox:t=>t.limit(e)}}function cd(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 ld(...e){return cd(e)?Ka(e[0],!1,!0):Ha(e,!1,!0)}function Ka(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=nd(e),i=s.data(),a=Object.freeze({id:s.id,ref:s.ref,exists:i!==void 0,data:()=>i});return Ka(a,t,n,!0)}}}function Ha(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=>Ha(e.map(i=>Jr(i,s).executionValue),t,n,!0)}}function ud(e,t,n,r){const s=jn(e);Ie(s).markStarted();const i=fd(s,e),a=hd(t,n,r,s,e),c=pd(a,s),l=c.length===3?i.onSnapshot(c[0],c[1],c[2]):c.length===2?i.onSnapshot(c[0],c[1]):i.onSnapshot(c[0]);if(!s.own)return l;let u=!1;const d=()=>{u||(u=!0,l())},p=()=>{u||(d(),dd(c)?.(new dt("aborted","The operation was aborted.")))},f=s.own(p);return()=>{f(),d()}}function dd(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 fd(e,t){const n=ir(t);if(e.kind==="sandbox")return n;const r=Ea.get(n);if(!r)throw new TypeError("pyric/firestore: live ref missing rebuild closure for onSnapshot.");return r(Gr(e))}function Ga(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 hd(e,t,n,r,s){if(typeof e=="object"&&e!==null&&!Ga(e)){const a=t;return typeof a=="function"?[e,zs(a,r,s),n??gr]:a&&typeof a=="object"?[e,Ks(a,r,s)]:[e]}return typeof e=="function"?[zs(e,r,s),t??gr]:e&&typeof e=="object"?[Ks(e,r,s)]:[e]}function pd(e,t){if(t.kind!=="sandbox-live")return e;const n=e[0];return typeof n=="object"&&n!==null&&!Ga(n)?[{...n,[Cs]:!0,...t.authScope?{[Es]:t.authScope}:{}},...e.slice(1)]:[{[Cs]:!0,...t.authScope?{[Es]:t.authScope}:{}},...e]}function Ja(e,t,n){if(!e||typeof e!="object")return e;const r=e;if(typeof r.data=="function"&&an(e,t),Array.isArray(r.docs)){for(const s of r.docs)an(s,t);yr(e,e,t,n,"listener")}return e}function gr(e){console.error("pyric/firestore: Uncaught Error in snapshot listener:",e)}function zs(e,t,n){return r=>{e(Ja(_n(r,t),t,n)),Ie(t).notifySnapshotDelivered()}}function Ks(e,t,n){return{...e,next:e.next?r=>{e.next(Ja(_n(r,t),t,n)),Ie(t).notifySnapshotDelivered()}:void 0,error:e.error??gr}}const _e={description:"Identity to act as. Omit or 'admin' = admin write that BYPASSES rules (sandbox seeding). { uid, claims? } = act as that user with rules ENFORCED.",oneOf:[{type:"string",enum:["admin"]},{type:"object",properties:{uid:{type:"string"},claims:{type:"object",description:"Custom claims forwarded to the rule context (request.auth.token)."}},required:["uid"]}]},md=["<","<=","==","!=",">=",">","in","not-in","array-contains","array-contains-any"],yd={type:"object",properties:{field:{type:"string"},op:{type:"string",enum:[...md]},value:{}},required:["field","op","value"]};function Ya(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:_e},required:["path"]},async execute(n){const r=n,s=await t(r.as),i=Le(s,r.path),a=await qa(i),c=typeof a.exists=="function"?a.exists():a.exists;return{ok:!0,summary:c?`Got ${r.path}`:`No document at ${r.path}`,data:{exists:c,data:c?a.data():null}}}},{name:"firestore_list_documents",description:"List documents in a collection. Supports orderBy + limit. Admin by default; pass `as:{uid}` to enforce rules.",parameters:{type:"object",properties:{collection:{type:"string"},orderBy:{type:"string"},limit:{type:"number"},as:_e},required:["collection"]},async execute(n){const r=n,s=await t(r.as),i=_t(s,r.collection),a=[];r.orderBy&&a.push(Ws(r.orderBy)),r.limit&&a.push(ln(r.limit));const c=await on(cn(i,...a));return{ok:!0,summary:`${c.size} docs in ${r.collection}`,data:{docs:c.docs.map(l=>({id:l.id,data:l.data()}))}}}},{name:"firestore_create_document",description:"Create or replace a Firestore document at an explicit path. Admin by default (bypasses rules — for seeding); pass `as:{uid}` to write as that user with rules enforced.",parameters:{type:"object",properties:{path:{type:"string"},data:{type:"object"},as:_e},required:["path","data"]},async execute(n){const r=n,s=await t(r.as);return await en(Le(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:_e},required:["collection","data"]},async execute(n){const r=n,s=await t(r.as),i=await Ca(_t(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:_e},required:["path","data"]},async execute(n){const r=n,s=await t(r.as);return await Ns(Le(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:_e},required:["path"]},async execute(n){const r=n,s=await t(r.as);return await ar(Le(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:_e},required:["operations"]},async execute(n){const r=n;if(r.operations.length===0||r.operations.length>500)return{ok:!1,summary:`firestore_batch_write: operations must be 1..500 (got ${r.operations.length}).`};const s=await t(r.as);for(const i of r.operations){const a=Le(s,i.path);i.op==="set"?await en(a,i.data??{}):i.op==="update"?await Ns(a,i.data??{}):await ar(a)}return{ok:!0,summary:`Applied ${r.operations.length} write(s)`,data:{count:r.operations.length}}}},{name:"firestore_query_where",description:"Query a collection with one or more where clauses (AND-semantics) + optional orderBy + limit. For OR semantics use a single where clause with the `in` / `array-contains-any` op. Admin by default; pass `as:{uid}` to enforce rules.",parameters:{type:"object",properties:{collection:{type:"string"},where:{type:"array",description:"One or more where clauses. AND across clauses.",items:yd,minItems:1},orderBy:{type:"string"},limit:{type:"number"},as:_e},required:["collection","where"]},async execute(n){const r=n,s=await t(r.as),i=_t(s,r.collection),a=r.where.map(l=>od(l.field,l.op,l.value));r.orderBy&&a.push(Ws(r.orderBy)),r.limit&&a.push(ln(r.limit));const c=await on(cn(i,...a));return{ok:!0,summary:`${c.size} matches in ${r.collection}`,data:{docs:c.docs.map(l=>({id:l.id,data:l.data()}))}}}}]}function Qa(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=cl(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 bd="modulepreload",gd=function(e){return"/__pyric/ui/"+e},Hs={},Xa=function(t,n,r){let s=Promise.resolve();if(n&&n.length>0){let a=function(u){return Promise.all(u.map(d=>Promise.resolve(d).then(p=>({status:"fulfilled",value:p}),p=>({status:"rejected",reason:p}))))};document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),l=c?.nonce||c?.getAttribute("nonce");s=a(n.map(u=>{if(u=gd(u),u in Hs)return;Hs[u]=!0;const d=u.endsWith(".css"),p=d?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${p}`))return;const f=document.createElement("link");if(f.rel=d?"stylesheet":bd,d||(f.as="script"),f.crossOrigin="",f.href=u,l&&f.setAttribute("nonce",l),document.head.appendChild(f),d)return new Promise((m,y)=>{f.addEventListener("load",m),f.addEventListener("error",()=>y(new Error(`Unable to preload CSS for ${u}`)))})}))}function i(a){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=a,window.dispatchEvent(c),!c.defaultPrevented)throw a}return s.then(a=>{for(const c of a||[])c.status==="rejected"&&i(c.reason);return t().catch(i)})};function Za(e){return e.kind==="session_boundary"&&e.phase==="reset"}function vd(e,t){return Za(t)?[t]:[...e,t]}const eo=h.createContext(null),to={status:"disabled",handles:null,events:[]};function wd({children:e}){return o.jsx(eo.Provider,{value:to,children:e})}function $e(){return h.useContext(eo)??to}function gt(e,t){return`${e.replace(/\/$/,"")}${t}`}function xd(e){const t=e;return{async read(n){const r=await fetch(gt(t,`/__pyric/workspace?path=${encodeURIComponent(n)}`));if(r.status===404)return null;if(!r.ok)throw new Error(`workspace.read(${n}) → ${r.status}`);return r.text()},async write(n,r){const s=await fetch(gt(t,`/__pyric/workspace?path=${encodeURIComponent(n)}`),{method:"PUT",body:r});if(!s.ok)throw new Error(`workspace.write(${n}) → ${s.status}`)},async list(n){const r=n?`?dir=${encodeURIComponent(n)}`:"",s=await fetch(gt(t,`/__pyric/workspace/list${r}`));if(!s.ok)throw new Error(`workspace.list(${n??""}) → ${s.status}`);return await s.json()},async remove(n){const r=await fetch(gt(t,`/__pyric/workspace?path=${encodeURIComponent(n)}`),{method:"DELETE"});if(!r.ok)throw new Error(`workspace.remove(${n}) → ${r.status}`)},watch(n){const r=new EventSource(gt(t,"/__pyric/workspace/watch")),s=i=>{try{n(JSON.parse(i.data))}catch{}};return r.addEventListener("change",s),()=>{r.removeEventListener("change",s),r.close()}}}}function vt(e,t){return`${e.replace(/\/$/,"")}${t}`}function jd(e){const t=e;return{async list(){const n=await fetch(vt(t,"/__pyric/projects"));if(!n.ok)throw new Error(`projects.list() → ${n.status}`);return await n.json()},async open(n){const r=await fetch(vt(t,`/__pyric/projects/${encodeURIComponent(n)}`));if(!r.ok)throw new Error(`projects.open(${n}) → ${r.status}`);return{meta:await r.json(),workspace:xd(t)}},async create(n){const r=await fetch(vt(t,"/__pyric/projects"),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(n)});if(!r.ok)throw new Error(`projects.create() → ${r.status}`);return await r.json()},async update(n,r){const s=await fetch(vt(t,`/__pyric/projects/${encodeURIComponent(n)}`),{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify(r)});if(!s.ok)throw new Error(`projects.update(${n}) → ${s.status}`)},async remove(n){const r=await fetch(vt(t,`/__pyric/projects/${encodeURIComponent(n)}`),{method:"DELETE"});if(!r.ok)throw new Error(`projects.remove(${n}) → ${r.status}`)}}}function kd(e,t){return`${e.replace(/\/$/,"")}${t}`}function Wn(e){return/auth/i.test(e)?"auth":"firestore"}function Sd(e){const t=e,r={"content-type":"application/json","x-pyric-writer":`studio-${Math.random().toString(36).slice(2)}`},s=new Map,i=l=>kd(t,`/__pyric/state?section=${Wn(l)}`),a=async l=>{const u=Wn(l),d=s.get(u);if(d)return d;const p=await fetch(i(l));let f=new Map;if(p.ok){const m=await p.text();m&&m!=="null"&&(f=ll(m))}else if(p.status!==404)throw new Error(`persistence.read(${l}) → ${p.status}`);return s.set(u,f),f},c=async(l,u)=>{const d=await fetch(i(l),{method:"POST",headers:r,body:ul(u)});if(d.status===423)throw new Error("persistence.write blocked, another tab holds the persist writer lock");if(!d.ok)throw new Error(`persistence.write(${l}) → ${d.status}`)};return{async getRecord(l,u){return(await a(l)).get(u)??null},async listRecords(l){return[...(await a(l)).keys()]},async putRecords(l,u){const d=await a(l);for(const[p,f]of u)d.set(p,f);await c(l,d)},async deleteRecords(l,u){const d=await a(l);for(const p of u)d.delete(p);await c(l,d)},async clear(l){s.set(Wn(l),new Map);const u=await fetch(i(l),{method:"POST",headers:r,body:"null"});if(!u.ok&&u.status!==423)throw new Error(`persistence.clear(${l}) → ${u.status}`)}}}const _d="local";function Ed(){const e=new Map,t=new Set,n=r=>{for(const s of t)s(r)};return{async read(r){return e.has(r)?e.get(r):null},async write(r,s){const i=e.has(r)?"update":"create";e.set(r,s),n({path:r,type:i})},async list(r){const s=r?`${r.replace(/\/+$/,"")}/`:"",i=[];for(const a of e.keys())s&&!a.startsWith(s)||i.push({path:a,kind:"file"});return i},async remove(r){e.delete(r)&&n({path:r,type:"delete"})},watch(r){return t.add(r),()=>t.delete(r)}}}function Cd(){const e=Ed();let t={id:_d,title:"Local Project",createdAt:Date.now(),updatedAt:Date.now()};return{async list(){return[t]},async open(n){if(n!==t.id)throw new Error(`Static Studio runs in single-project mode — no project '${n}'.`);return{meta:t,workspace:e}},async create(){throw new Error("Static Studio runs in single-project mode — creating additional projects is not supported.")},async update(n,r){n===t.id&&(t={...t,...r,updatedAt:Date.now()})},async remove(){}}}const Nd="/__pyric/sdk/worker.js",Ce="pyric-shared-worker",Rd="/__pyric/ui/";function no(e=typeof document>"u"?void 0:document){const t=e?.querySelector('meta[name="pyric-worker-v"]')?.getAttribute("content")?.trim()||null;return{studioUrl:Rd,worker:{url:Nd,name:Ce,servedEpoch:t}}}const un="pyric:worker-generation",wt="pyric:worker-generation-probe";function Ad(e,t){const n=e&&/^[a-f0-9]{16}$/.test(e)?e:null;if(!t)return n?`${Ce}:${n}`:Ce;try{const r=t.getItem(un);return r&&/^[a-f0-9]{16}$/.test(r)?`${Ce}:${r}`:n?(t.setItem(un,n),`${Ce}:${n}`):Ce}catch{return n?`${Ce}:${n}`:Ce}}function Id(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(un,e),t.getItem(un)!==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 Dd(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(wt);if(e.setItem(wt,"ok"),e.getItem(wt)!=="ok")throw new Error("the worker generation probe could not be read back");t===null?e.removeItem(wt):e.setItem(wt,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 Pd(e){const t=e.schedule??(s=>{setTimeout(s,100)});let n=!1;const r=e.subscribeReload(s=>{if(!n){try{e.commitGeneration(s)}catch(i){e.onPreparationError?.(i);return}n=!0,t(e.reload)}});return{async request(){e.preflight(),await e.retire()},dispose:r}}function $d(){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 ro=new WeakMap;let vr;function Od(e,t,n=$d()){const r=e.name,s=n===t?void 0:{},i=new Map,a=new Set,c={app:e,sandbox:t,session:n,services:i,cleanups:a,assertAlive(){if(c.deleted)throw new dt("app/app-deleted",`Firebase: Firebase App named '${r}' already deleted (app/app-deleted).`)},...s?{authScope:s}:{},service(l,u){const d=i.get(l);if(d!==void 0)return d;c.assertAlive();const p=u();return i.set(l,p),p},onDelete(l){return c.deleted?(l(),()=>{}):(a.add(l),()=>a.delete(l))},deleted:!1};return ro.set(e,c),c}function Md(e){vr=e}$l({resolve(e,t){const n=typeof e=="object"&&e!==null?ro.get(e):void 0;if(n)return n},defaultApp(){if(!vr)throw new TypeError("No default sandbox app registry is installed - import and initialize pyric/app before calling a service factory without an app.");return vr()}});const Ud="[DEFAULT]",Td=new Map;function Bd(e,t){return new dt(`app/${e}`,`Firebase: ${t} (app/${e}).`)}function Ld(e){return Bd("no-app",`No Firebase App '${e}' has been created - call initializeApp() first`)}function Fd(e=Ud){const t=Td.get(e);if(!t)throw Ld(e);return t.app}Md(Fd);let Vd=0,qd=0;function U(){return`op-${++Vd}`}function ft(){return`sub-${++qd}`}const ot=new Map,Ct=new Map,Nt=new Map,ht=new WeakSet,wr=new Set;function Wd(e){return wr.add(e),()=>wr.delete(e)}function so(){return Object.assign(new Error("Firebase App was deleted"),{code:"app/app-deleted"})}function $t(e,t,n,r){return ht.has(e)?!1:(Ct.set(t,n),e.postMessage(r),!0)}function zd(e,t,n,r){return ht.has(e)?!1:(Nt.set(t,{port:e,next:n}),e.postMessage(r),!0)}function Ot(e,t){Ct.delete(t),Nt.delete(t),ht.has(e)||e.postMessage({t:"unsub",subId:t})}function Kd(e){ht.add(e);const t=so();for(const[n,r]of[...ot])r.port===e&&(ot.delete(n),r.reject(t));for(const[n,r]of[...Ct])r.port===e&&(Ct.delete(n),r.service==="firestore"&&r.error?.(new dt("aborted","The operation was aborted.")));for(const[n,r]of[...Nt])r.port===e&&Nt.delete(n);e.onmessage=null}function Gs(e,t){if(t.denialContext===void 0||typeof fetch!="function")return;const n={kind:e,code:t.code,message:t.message,denialContext:t.denialContext,...typeof t.remediation=="string"?{remediation:t.remediation}:{}};try{fetch("/__pyric/denials",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(n)}).catch(()=>{})}catch{}}function Zr(e){e.onmessage=t=>{const n=t.data;if(n.t==="res"){const r=ot.get(n.id);if(!r)return;if(ot.delete(n.id),n.ok)r.resolve(n.value);else{const s=new Error(n.error.message);s.code=n.error.code,n.error.denialContext!==void 0&&(s.denialContext=n.error.denialContext),n.error.aiEnvelope!==void 0&&(s.aiEnvelope=n.error.aiEnvelope),Gs("read",s),r.reject(s)}}else if(n.t==="snap"){const r=Ct.get(n.subId);if(!r)return;const s=n.value??{};if(s.__error){const i=s.__error,a=new Error(i.message);a.code=i.code,i.denialContext!==void 0&&(a.denialContext=i.denialContext),i.aiEnvelope!==void 0&&(a.aiEnvelope=i.aiEnvelope),Gs("listener",a),r.error?r.error(a):console.error("pyric/firestore: Uncaught Error in snapshot listener:",a);return}r.next(n.value)}else if(n.t==="event"){const r=Nt.get(n.subId);r&&r.next(n.events)}else if(n.t==="runtime-reload")for(const r of wr)r(n)}}let ct;function Js(e){ct=e&&e.mode==="app-session"?void 0:e}function Hd(){return ct}let xr;function Gd(e){xr=e}function es(e){return xr&&(e.t==="op"||e.t==="sub")?{...e,issuer:xr}:e}function ts(e,t){return ht.has(e)?Promise.reject(so()):new Promise((n,r)=>{const s=t;ot.set(s.id,{port:e,resolve:n,reject:r}),e.postMessage(t)})}function W(e,t){return ts(e,es(t))}function io(e,t,n,r){const s=t.id;let i;const a=new Promise((c,l)=>{i=setTimeout(()=>{ot.delete(s)&&l(new Error(r))},n)});return Promise.race([W(e,t),a]).finally(()=>{i&&clearTimeout(i)})}function de(e,t){if(ht.has(e)&&!t.method.startsWith("rtdb."))return Promise.reject(new dt("failed-precondition","The client has already been terminated."));const n=ct?{...t,actAs:ct}:t;return W(e,n)}async function Jd(e,t,n={}){const r=n.timeoutMs??12e3;await io(e.port,{t:"op",id:U(),method:"retireRuntime",targetEpoch:t},r,`Timed out waiting for the Pyric worker to retire after ${r}ms.`)}function Yd(e){return Wd(t=>e(t.epoch))}function Qd(e,t,n={}){if(typeof SharedWorker>"u")throw new Error("SharedWorker is not available. Open this page over http:// (not file://) and use a supported browser (Chrome 4+, Firefox 29+, Safari 16.4+).");const r=new SharedWorker(e,{type:"classic",name:t??"pyric-shared-worker"});n.onError&&r.addEventListener("error",i=>{const a=i.message||`failed to load ${String(e)}`;n.onError?.(new Error(`Pyric SharedWorker error: ${a}`))});const s=r.port;return Zr(s),s.start(),{__kind:"client-db",port:s}}async function Xd(e,t={}){const n=U(),r=t.timeoutMs??2e3;return(await io(e.port,{t:"op",id:n,method:"getRuntimeEpoch"},r,`Timed out waiting for the Pyric SharedWorker version handshake after ${r}ms.`)).version}async function Zd(e){return(await W(e.port,{t:"op",id:U(),method:"getVersion"})).instanceId??""}async function ef(e){return(await W(e.port,{t:"op",id:U(),method:"exportState"})).bundle}async function tf(e,t){await W(e.port,{t:"op",id:U(),method:"importState",bundle:t})}async function nf(e,t){await W(e.port,{t:"op",id:U(),method:"saveBranch",name:t})}async function rf(e){return(await W(e.port,{t:"op",id:U(),method:"listBranches"})).branches??[]}async function sf(e,t){await W(e.port,{t:"op",id:U(),method:"switchBranch",name:t})}async function af(e,t){await W(e.port,{t:"op",id:U(),method:"deleteBranch",name:t})}async function of(e,t,n){return await W(e.port,{t:"tool",id:U(),name:t,args:n})}function cf(e,t){return ts(e.port,{...t,issuer:void 0,relaySource:"remote",t:"op",id:U()})}function lf(e,t,n){if(t.target==="events")throw new Error("event-stream subscriptions cannot be relayed over the bridge yet (needs bounded backpressure — slice 2)");const r=ft();return $t(e.port,r,{port:e.port,next:n,error:i=>n({__error:{code:i.code??"unknown",message:i instanceof Error?i.message:String(i)}})},{...t,issuer:void 0,relaySource:"remote",t:"sub",subId:r})||queueMicrotask(()=>n({__error:{code:"app/app-deleted",message:"Firebase App was deleted"}})),()=>{Ot(e.port,r)}}function uf(e){const t=(e??"/").split("/").filter(Boolean).join("/");return t?`/${t}`:"/"}const df=[];function ff(e){for(const t of[...df])t.port===e&&t.close()}const hf=5e3;function pf(){return Object.assign(new Error("Timed out waiting for SharedWorker app cleanup acknowledgment. Close all tabs using this pyric dev origin so the worker can restart."),{code:"app/delete-timeout"})}async function mf(e,t={}){let n;try{const r=ts(e.port,{t:"disconnect",id:U()}),s=new Promise((i,a)=>{n=setTimeout(()=>a(pf()),t.ackTimeoutMs??hf)});await Promise.race([r,s])}finally{n!==void 0&&clearTimeout(n),ff(e.port),Kd(e.port),e.port.close()}}function ns(e){return e.split("/").at(-1)??e}function yf(e,...t){const n=("port"in e,e.port);let r;if(e.__kind==="client-db"){if(t.length===0)throw new TypeError("doc(db, path) requires a path segment.");r=t.join("/")}else{const i=e.descriptor.path;r=t.length>0?`${i}/${t.join("/")}`:i}return{__kind:"doc-ref",descriptor:{__ref:"doc",path:r},port:n,id:ns(r),path:r}}function bf(e,...t){const n=e.port;if(t.length===0)throw new TypeError("collection() requires a path segment.");let r;return e.__kind==="client-db"?r=t.join("/"):r=`${e.descriptor.path}/${t.join("/")}`,{__kind:"coll-ref",descriptor:{__ref:"collection",path:r},port:n,id:ns(r),path:r}}function gf(e){return{_descriptor:{kind:"limit",n:e}}}function vf(...e){return{_descriptor:{kind:"startAfter",values:e}}}function wf(e,...t){const n=(e.__kind==="coll-ref",e.descriptor),r=e.__kind==="query"?e.descriptor.constraints:[];return{__kind:"query",descriptor:{__ref:"query",source:n.__ref==="query"?n.source:n,constraints:[...r,...t.map(i=>i._descriptor)]},port:e.port}}function xf(e){return dl(JSON.parse(e.json))}const ao=8*1024*1024;function jf(e,t){const n=new Error(`${t} is ${e} bytes — over the ${ao/1048576} MiB storage op cap (MAX_STORAGE_OP_BYTES). Streaming/resumable transfers are not supported on the sandbox backend; split the object or keep it under the cap.`);return n.code="payload-too-large",n}function kf(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 Sf(e){return xf(e)}function rs(e,t){const n=e.exists&&e.data?Sf(e.data):void 0,r=e.path??e.id,s={__kind:"doc-ref",descriptor:{__ref:"doc",path:r},port:t,id:e.id,path:r};return{id:e.id,path:r,ref:s,exists:()=>e.exists,data:()=>n}}function oo(e,t){const n=e.docs.map(r=>rs(r,t));return{size:n.length,empty:n.length===0,docs:n}}async function _f(e){const t=await de(e.port,{t:"op",id:U(),method:"getDoc",path:e.descriptor.path});return rs(t,e.port)}async function Ef(e){const t=await de(e.port,{t:"op",id:U(),method:"getDocs",source:(e.__kind==="coll-ref",e.descriptor)});return oo(t,e.port)}async function Cf(e){return(await de(e.port,{t:"op",id:U(),method:"listRootCollections"})).ids}async function Nf(e,t){return(await de(e.port,{t:"op",id:U(),method:"listSubcollections",docPath:t})).ids}function Rf(e,t,n){const r=ft(),s=e.port,i={port:s,service:"firestore",next:l=>{const u=l;"docs"in u?t(oo(u,s)):t(rs(u,s))},error:n},a=(e.__kind==="doc-ref"||e.__kind==="coll-ref",e.descriptor);return!$t(s,r,i,es(ct?{t:"sub",subId:r,target:a,actAs:ct}:{t:"sub",subId:r,target:a}))&&n&&queueMicrotask(()=>n(new Error("Firebase App was deleted"))),()=>{Ot(s,r)}}async function Af(e,t,n){await de(e.port,{t:"op",id:U(),method:"setDoc",path:e.descriptor.path,data:t,options:n})}async function If(e){await de(e.port,{t:"op",id:U(),method:"deleteDoc",path:e.descriptor.path})}async function Df(e,t){const n=await de(e.port,{t:"op",id:U(),method:"addDoc",collectionPath:e.descriptor.path,data:t});return{__kind:"doc-ref",descriptor:{__ref:"doc",path:n.path},port:e.port,id:n.id,path:n.path}}async function Pf(e,t){return await W(e.port,{t:"op",id:U(),method:"admin.listDocuments",path:t})}function $f(e,t){const n=ft(),r=e.port;return zd(r,n,t,{t:"sub",subId:n,target:"events"}),()=>{Ot(r,n)}}async function Of(e){return await W(e.port,{t:"op",id:U(),method:"getSnapshot"})}async function Mf(e){return await W(e.port,{t:"op",id:U(),method:"resetAll"})??{errors:[]}}const Uf=15e3;function Tf(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`page-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function Ys(){return typeof location>"u"?"/":`${location.pathname}${location.search}${location.hash}`}function Qs(){return typeof document>"u"?"visible":document.visibilityState==="hidden"?"hidden":"visible"}function Bf(e){const{db:t,kind:n}=e,r=e.clientId??Tf(),s=e.heartbeatIntervalMs??Uf;let i=!1,a=null;const c=()=>{W(t.port,{t:"op",id:U(),method:"presence.register",clientId:r,kind:n,route:Ys(),visibility:Qs()}).catch(()=>{})},l=()=>{W(t.port,{t:"op",id:U(),method:"presence.heartbeat",clientId:r}).catch(()=>{})},u=()=>{W(t.port,{t:"op",id:U(),method:"presence.update",clientId:r,route:Ys(),visibility:Qs()}).catch(()=>{})},d=()=>{W(t.port,{t:"op",id:U(),method:"presence.disconnect",clientId:r}).catch(()=>{})};c(),typeof document<"u"&&document.addEventListener("visibilitychange",u),typeof window<"u"&&(window.addEventListener("popstate",u),window.addEventListener("hashchange",u),window.addEventListener("pagehide",p),a=setInterval(()=>{i||l()},s));function p(){f()}function f(){i||(i=!0,a!=null&&(clearInterval(a),a=null),typeof document<"u"&&document.removeEventListener("visibilitychange",u),typeof window<"u"&&(window.removeEventListener("popstate",u),window.removeEventListener("hashchange",u),window.removeEventListener("pagehide",p)),d())}return{clientId:r,kind:n,stop:f}}function Lf(e,t){const n=ft();return $t(e.port,n,{port:e.port,next:r=>{t(r)}},{t:"sub",subId:n,target:"presence"}),()=>{Ot(e.port,n)}}const Ff=Symbol("pyric.clientUser.port");function Vf(e,t){const n={uid:t.uid,email:t.email,emailVerified:t.emailVerified,displayName:t.displayName,photoURL:t.photoURL,phoneNumber:t.phoneNumber,isAnonymous:t.isAnonymous,providerId:t.providerId,providerData:t.providerData,async getIdToken(r){return await W(e,{t:"op",id:U(),method:"auth.getIdToken",forceRefresh:r})},async getIdTokenResult(r){return await W(e,{t:"op",id:U(),method:"auth.getIdTokenResult",forceRefresh:r})}};return Object.defineProperty(n,Ff,{value:e,enumerable:!1}),n}function qf(e,t){return t?Vf(e,t):null}function Wf(e,t){let n;if(typeof e=="object"&&"__kind"in e&&e.__kind==="client-db")n=e.port;else{if(typeof SharedWorker>"u")throw new Error("SharedWorker is not available. Open this page over http:// (not file://) and use a supported browser (Chrome 4+, Firefox 29+, Safari 16.4+).");n=new SharedWorker(e,{type:"classic",name:"pyric-shared-worker"}).port,n.start(),Zr(n)}const r={__kind:"client-auth",port:n,currentUser:null},s=ft();return $t(n,s,{port:n,next:i=>{r.currentUser=qf(n,i)}},{t:"sub",subId:s,target:"authState"}),r}async function zf(e){return await W(e.port,{t:"op",id:U(),method:"auth.listUsers"})}async function Kf(e,t){return await W(e.port,{t:"op",id:U(),method:"auth.adminCreateUser",request:t})}async function Hf(e,t,n){return await W(e.port,{t:"op",id:U(),method:"auth.adminUpdateUser",uid:t,request:n})}async function Gf(e,t){await W(e.port,{t:"op",id:U(),method:"auth.adminDeleteUser",uid:t})}async function Jf(e){await W(e.port,{t:"op",id:U(),method:"auth.adminClearUsers"})}async function Yf(e){return await W(e.port,{t:"op",id:U(),method:"auth.getProviderConfig"})}async function Qf(e,t,n){await W(e.port,{t:"op",id:U(),method:"auth.setProviderConfig",providerId:t,enabled:n})}const jr="pyric-storage";function Xf(e){return e?`${jr}:${e}`:jr}const Zf=1,me="blobs",ie="metadata";function eh(e=jr){return nh(e).then(t=>new th(t))}class th{db;constructor(t){this.db=t}async put(t,n,r){const s=this.db.transaction([me,ie],"readwrite");s.objectStore(me).put(n,t),s.objectStore(ie).put(r,t),await Lt(s)}async getBlob(t){const n=this.db.transaction(me,"readonly");return zn(n.objectStore(me).get(t))}async getMetadata(t){const n=this.db.transaction(ie,"readonly");return zn(n.objectStore(ie).get(t))}async putMetadata(t,n){const r=this.db.transaction(ie,"readwrite");r.objectStore(ie).put(n,t),await Lt(r)}async delete(t){const n=this.db.transaction([me,ie],"readwrite");n.objectStore(me).delete(t),n.objectStore(ie).delete(t),await Lt(n)}async listByPrefix(t){const n=this.db.transaction(ie,"readonly"),r=IDBKeyRange.bound(t,t+"",!1,!1);return zn(n.objectStore(ie).getAll(r))}async reset(){const t=this.db.transaction([me,ie],"readwrite");t.objectStore(me).clear(),t.objectStore(ie).clear(),await Lt(t)}close(){this.db.close()}}function nh(e){return new Promise((t,n)=>{const r=indexedDB.open(e,Zf);r.addEventListener("upgradeneeded",()=>{const s=r.result;s.objectStoreNames.contains(me)||s.createObjectStore(me),s.objectStoreNames.contains(ie)||s.createObjectStore(ie)}),r.addEventListener("success",()=>t(r.result)),r.addEventListener("error",()=>n(r.error)),r.addEventListener("blocked",()=>n(new Error(`IndexedDB open blocked for db "${e}"`)))})}function zn(e){return new Promise((t,n)=>{e.addEventListener("success",()=>t(e.result)),e.addEventListener("error",()=>n(e.error))})}function Lt(e){return new Promise((t,n)=>{e.addEventListener("complete",()=>t()),e.addEventListener("error",()=>n(e.error)),e.addEventListener("abort",()=>n(e.error??new Error("IndexedDB transaction aborted")))})}function Xs(e){switch(e){case"read":return["get","list"];case"write":return["create","update","delete"];default:return[e]}}const rh=new Set(["&&","||","==","!=","<",">","<=",">=","+","-","*","/","%"]);function co(e){return{segments:e.path.segments.map(sh),children:e.children.map(co),allows:e.allows.map(t=>({verbs:t.operations,condition:H(t.condition)})),functions:e.functions.map(kr)}}function sh(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 kr(e){return{name:e.name,params:e.parameters,lets:e.lets.map(t=>({name:t.name,value:H(t.value)})),body:H(e.body)}}function H(e){switch(e.type){case"literal":return typeof e.value=="number"&&e.raw.includes(".")?{kind:"literal",value:new ke(e.value)}:{kind:"literal",value:e.value};case"identifier":return{kind:"ident",name:e.name};case"memberAccess":return{kind:"member",target:H(e.object),name:e.property};case"methodCall":return{kind:"methodcall",target:H(e.object),method:e.method,args:e.args.map(H)};case"bracketAccess":return{kind:"index",target:H(e.object),index:H(e.index)};case"sliceAccess":return{kind:"slice",target:H(e.object),start:H(e.start),end:H(e.end)};case"binaryOp":if(!rh.has(e.op))throw new SyntaxError(`Unsupported binary operator '${e.op}' in storage rules.`);return{kind:"binary",op:e.op,left:H(e.left),right:H(e.right)};case"unaryOp":if(e.op!=="!"&&e.op!=="-")throw new SyntaxError(`Unsupported unary operator '${e.op}' in storage rules.`);return{kind:"unary",op:e.op,arg:H(e.operand)};case"ternary":return{kind:"ternary",cond:H(e.condition),then:H(e.consequent),else:H(e.alternate)};case"inExpr":return{kind:"in",element:H(e.element),collection:H(e.collection)};case"isExpr":return{kind:"is",value:H(e.value),typeName:e.typeName};case"listLiteral":return{kind:"list",elements:e.elements.map(H)};case"mapLiteral":return{kind:"map",entries:e.entries.map(t=>({key:H(t.key),value:H(t.value)}))};case"pathLiteral":return{kind:"path",segments:e.segments.map(t=>typeof t=="string"?{kind:"literal",value:t}:{kind:"interp",expr:H(t)})};case"functionCall":return{kind:"call",name:e.name,args:e.args.map(H)};default:{const t=e;throw new SyntaxError(`Unsupported expression construct: ${JSON.stringify(t)}`)}}}function Sr(e){const t=fl(e);if(!t.ok)throw new SyntaxError(`Storage rules parse error at line ${t.error.line}, column ${t.error.column}: expected ${t.error.expected}.`);const n=t.ast;if(n.service.name!=="firebase.storage")throw new SyntaxError(`Expected 'service firebase.storage', got 'service ${n.service.name}'.`);const r={segments:[],children:[co(n.service.match)],allows:[],functions:[...(n.imports??[]).flatMap(s=>s.functions.map(i=>({name:i,params:[],lets:[],body:{kind:"literal",value:null},unresolvedImport:s.module}))),...(n.functions??[]).map(kr),...(n.service.functions??[]).map(kr)]};return lo(r,new Map),{_root:r,_version:n.version}}function lo(e,t){const n=new Map(t);for(const r of e.functions)n.set(r.name,r);e.visibleFuncs=n;for(const r of e.functions)r.declScope=n;for(const r of e.children)lo(r,n)}function X(e,t){if(e.kind==="methodcall"&&e.target.kind==="ident"&&e.target.name==="firestore"&&!t.has("firestore")&&(e.method==="get"||e.method==="exists"))return!0;switch(e.kind){case"member":return X(e.target,t);case"index":return X(e.target,t)||X(e.index,t);case"slice":return[e.target,e.start,e.end].some(n=>X(n,t));case"unary":return X(e.arg,t);case"ternary":return[e.cond,e.then,e.else].some(n=>X(n,t));case"in":return X(e.element,t)||X(e.collection,t);case"is":return X(e.value,t);case"list":return e.elements.some(n=>X(n,t));case"map":return e.entries.some(({key:n,value:r})=>X(n,t)||X(r,t));case"binary":return X(e.left,t)||X(e.right,t);case"call":return e.args.some(n=>X(n,t));case"methodcall":return X(e.target,t)||e.args.some(n=>X(n,t));case"path":return e.segments.some(n=>n.kind==="interp"&&X(n.expr,t));case"ident":case"literal":return!1}}function uo(e,t=new Set){const n=new Set(t);for(const r of e.segments)r.kind!=="literal"&&n.add(r.name);if(e.allows.some(({condition:r})=>r&&X(r,n)))return!0;for(const r of e.functions){const s=new Set([...n,...r.params]);for(const i of r.lets){if(X(i.value,s))return!0;s.add(i.name)}if(X(r.body,s))return!0}return e.children.some(r=>uo(r,n))}function ih(e,t,n,r,s){const i=new Set;for(const a of r)a.startsWith("storage-rules#")&&i.add(a);return uo(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 ah="pyric-default",En=Symbol("pyric/storage/target");function ze(e){return e.currentAuth?.()??e.context.auth}class oh{backend;rules;constructor(t,n=null){this.backend=t,this.rules=n}}const Zs=new WeakMap,ei=new WeakMap,ch=new WeakMap;function lh(e,t,n){const r=Zs.get(e);if(r){const c=ei.get(e)??null;if(t.rules!==void 0&&t.rules!==c)throw new Error(`pyric/storage: ${n} received a rules source, but this sandbox's storage service is already open ${c===null?"without rules":"with a different rules source"} — rules are honored only on the FIRST storage call per Sandbox, so these rules would be silently discarded. Configure rules on the first storage call for this sandbox.`);return r}let s=null,i=null;if(t.rules){let c=t.rules,l=[],u=[],d=[];if(s=Sr(c),s._version==="2+modules"){const p=wa(c);if(!p.success)throw new SyntaxError(`Storage rules module resolution failed (${p.error.code}): ${p.error.message}`);c=p.data.resolved,l=p.data.modules,u=p.data.bundledModules,d=p.data.evidenceIds,s=Sr(c)}i=ih(c,l,u,d,s)}const a=eh(t.dbName??Xf(t.projectId)).then(c=>new oh(c,s));return Zs.set(e,a),ei.set(e,t.rules??null),ch.set(e,i),e.registerPersistableService("storage",{snapshot:()=>null,restore:()=>{},reset:async()=>{await(await a).backend.reset()}}),a}function Kn(e){return e instanceof pl}const ti=new WeakMap,ni=new WeakMap;function uh(e,t={}){const n=!Kn(e),r=Kn(e)?e.sandbox:e,s=lh(r,t,"getAdminStorageSandbox");if(n){const d=ni.get(r);if(d)return d}const i=Kn(e)?e:r.withAuth(null),a=i.operationContext.authLens.mode==="admin"?i:ja(i,{source:i.operationContext.source,authLens:{mode:"admin"},...i.operationContext.planId===void 0?{}:{planId:i.operationContext.planId}}),c=ti.get(i);if(c)return c;const l={kind:"sandbox",sandbox:r,context:a,bucket:t.bucket??ah,servicePromise:s,admin:!0},u=Object.freeze({[En]:l});return ti.set(i,u),n&&ni.set(r,u),u}function pt(e,t){const n=hl(t,ks(e.context.operationContext));return{...t,...ks(n),service:"storage"}}function Se(e){const t=e[En];if(!t)throw new TypeError("pyric/storage: not a FirebaseStorage handle — was it produced by getStorageSandbox?");return t}function Mt(e){return Se(e).servicePromise}class T extends Error{}class ee{message;constructor(t){this.message=t}}function z(e){return e instanceof ee}function De(e){if(typeof e=="number")return e;if(e instanceof ke)return e.value}function Pe(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function st(e,t){if(e===t)return!0;if(e==null||t==null)return e==null&&t==null;const n=De(e),r=De(t);if(n!==void 0&&r!==void 0)return n===r;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((s,i)=>st(s,t[i]));if(Pe(e)&&Pe(t)){const s=Object.keys(e),i=Object.keys(t);return s.length===i.length&&s.every(a=>Object.prototype.hasOwnProperty.call(t,a)&&st(e[a],t[a]))}return!1}function ae(e){return e===null?"null":e===void 0?"undefined":e instanceof ke?"float":typeof e}function dh(e,t){if(e.target.kind==="ident"&&e.target.name==="timestamp"&&!(e.target.name in t.locals)&&!(e.target.name in t.params))return mh(e,t);if(e.target.kind==="ident"&&e.target.name==="duration"&&!(e.target.name in t.locals)&&!(e.target.name in t.params))return ph(e,t);if(e.target.kind==="ident"&&e.target.name==="firestore"&&!(e.target.name in t.locals)&&!(e.target.name in t.params))return fh(e,t);if(e.method==="matches")return yh(e,t);if(e.method==="split")return bh(e,t);if(e.method==="size")return gh(e,t);if(e.method==="keys")return vh(e,t);if(e.method==="hasAll")return wh(e,t);if(e.method==="get")return xh(e,t);throw new T(`unsupported method .${e.method}()`)}function fh(e,t){if(e.method!=="get"&&e.method!=="exists")throw new T(`unsupported method firestore.${e.method}()`);if(!t.firestoreLookup)throw new T(`firestore.${e.method}() is unsupported here — no Firestore lookup capability is configured`);if(e.args.length!==1)throw new T(`firestore.${e.method}() expects a single path argument`);const n=e.args[0];if(n.kind!=="path")throw new T(`firestore.${e.method}() requires a /databases/.../documents/... path literal`);const r=hh(n,t);if(!t.firestoreAccesses.has(r)){if(t.firestoreAccesses.size>=2)throw new T("firestore access limit exceeded: at most two distinct documents");t.firestoreAccesses.add(r)}if(e.method==="exists")return t.firestoreLookup.exists(r);const s=t.firestoreLookup.get(r);return s===null?new ee(`firestore.get() targeted a nonexistent document: ${r}`):{data:s}}function hh(e,t){const n=e.segments.map(s=>{if(s.kind==="literal")return s.value;const i=B(s.expr,t);if(typeof i=="string")return i;if(typeof i=="number")return String(i);throw new T(`Firestore path interpolation resolved to ${ae(i)} (expected a string)`)});if(n.length<4||n[0]!=="databases"||n[2]!=="documents")throw new T(`malformed Firestore path — expected /databases/<db>/documents/... , got /${n.join("/")}`);if(n[1]!=="(default)")throw new T(`Storage rules may access only the default Firestore database, got ${n[1]}`);const r=n.slice(3);if(r.length===0||r.length%2!==0)throw new T(`Firestore path does not point at a document (needs an even segment count): ${r.join("/")}`);return r.join("/")}const ri={w:10080*60*1e3,d:1440*60*1e3,h:3600*1e3,m:60*1e3,s:1e3,ms:1,ns:1e-6};function ph(e,t){if(e.method!=="value")throw new T(`unsupported duration.${e.method}()`);const n=e.args.map(a=>B(a,t));if(n.length!==2||typeof n[0]!="number"||typeof n[1]!="string")throw new T("duration.value() expects (magnitude: number, unit: string)");const[r,s]=n,i=ri[s];if(i===void 0)throw new T(`duration.value() got unknown unit "${s}" — expected one of ${Object.keys(ri).join(", ")}`);return r*i}function mh(e,t){const n=e.args.map(r=>B(r,t));if(e.method==="value"){if(n.length!==1||typeof n[0]!="number")throw new T("timestamp.value() expects (epochMillis: number)");return n[0]}if(e.method==="date"){if(n.length!==3||!n.every(a=>typeof a=="number"))throw new T("timestamp.date() expects (year, month, day) numbers");const[r,s,i]=n;return Date.UTC(r,s-1,i)}throw new T(`unsupported timestamp.${e.method}()`)}function yh(e,t){const n=B(e.target,t);if(z(n))return n;if(typeof n!="string")throw new T(`matches() requires a string target, got ${ae(n)}`);if(e.args.length!==1)throw new T("matches() expects a single pattern argument");const r=B(e.args[0],t);if(typeof r!="string")throw new T("matches() pattern must be a string");const s=/\\[1-9]/.test(r),i=/\(\?<?[=!]/.test(r);if(s||i)throw new T(`matches() pattern uses an RE2-unsupported construct (${s?"backreference":"lookaround"}) that production would reject`);let a;try{a=new RegExp(`^(?:${r})$`)}catch(c){throw new T(`matches() invalid regex pattern: ${c.message}`)}return a.test(n)}function bh(e,t){const n=B(e.target,t);if(z(n))return n;if(typeof n!="string")throw new T(`split() requires a string target, got ${ae(n)}`);if(e.args.length!==1)throw new T("split() expects a single pattern argument");const r=B(e.args[0],t);if(typeof r!="string")throw new T("split() pattern must be a string");const s=/\\[1-9]/.test(r),i=/\(\?<?[=!]/.test(r);if(s||i)throw new T(`split() pattern uses an RE2-unsupported construct (${s?"backreference":"lookaround"}) that production would reject`);let a;try{a=new RegExp(r)}catch(c){throw new T(`split() invalid regex pattern: ${c.message}`)}return n.split(a)}function gh(e,t){const n=B(e.target,t);if(z(n))return n;if(e.args.length!==0)throw new T("size() expects no arguments");if(typeof n=="string"||Array.isArray(n))return n.length;if(Pe(n))return Object.keys(n).length;throw new T(`size() requires a string, list, or map target, got ${ae(n)}`)}function vh(e,t){const n=B(e.target,t);if(z(n))return n;if(e.args.length!==0)throw new T("keys() expects no arguments");if(!Pe(n))throw new T(`keys() requires a map target, got ${ae(n)}`);return Object.keys(n)}function wh(e,t){const n=B(e.target,t);if(z(n))return n;if(!Array.isArray(n))throw new T(`hasAll() requires a list or set target, got ${ae(n)}`);if(e.args.length!==1)throw new T("hasAll() expects one list or set argument");const r=B(e.args[0],t);if(z(r))return r;if(!Array.isArray(r))throw new T("hasAll() argument must be a list or set");return r.every(s=>n.some(i=>st(i,s)))}function xh(e,t){const n=B(e.target,t);if(z(n))return n;if(!Pe(n))throw new T(`get() requires a map target, got ${ae(n)}`);if(e.args.length!==2)throw new T("get() expects a key and default value");const r=B(e.args[0],t);if(z(r))return r;if(typeof r!="string")throw new T("get() key must be a string");const s=B(e.args[1],t);return z(s)?s:Object.prototype.hasOwnProperty.call(n,r)?n[r]:s}function jh(e){return e.split("/").filter(t=>t.length>0)}function Hn(e){return"/"+e.map(t=>t.kind==="literal"?t.value:t.kind==="param"?`{${t.name}}`:`{${t.name}=**}`).join("/")}function kh(e,t,n){let r=0;const s={...n};for(let i=0;i<e.length;i++){const a=e[i];if(a.kind==="wildcard")return s[a.name]=t.slice(r),{left:[],params:s};if(r>=t.length)return null;if(a.kind==="literal"){if(t[r]!==a.value)return null;r++}else s[a.name]=t[r],r++}return{left:t.slice(r),params:s}}function fo(e,t,n=new Date,r){const s=n.getTime(),i=jh(t.request.path),a=[],c=new Set,l=new Set(Xs(t.request.method));function u(p,f,m){const y=kh(p.segments,f,m);if(!y)return!1;const g=y.params,v=y.left;if(v.length===0)for(const b of p.allows){const w=new Set(b.verbs.flatMap(Xs));if(![...l].some(j=>w.has(j)))continue;let k;try{const j=b.condition?B(b.condition,{input:t,now:s,params:g,locals:{},funcs:p.visibleFuncs??new Map,depth:0,firestoreLookup:r,firestoreAccesses:c}):!0;if(z(j)){a.push(`match ${Hn(p.segments)} ${t.request.method}: ${j.message}`);continue}k=Ze(j)}catch(j){if(j instanceof T){a.push(`match ${Hn(p.segments)} ${t.request.method}: ${j.message}`);continue}throw j}if(k)return!0;a.push(`match ${Hn(p.segments)} ${t.request.method}: condition false`)}for(const b of p.children)if(u(b,v,g))return!0;return!1}const d=u(e._root,i,{});return!d&&a.length===0&&a.push(`no rule matches ${t.request.method} /${i.join("/")}`),{allowed:d,reasons:a}}function si(e,t){if(!Pe(e)&&!Array.isArray(e))return new ee(`Property ${t} is undefined on ${ae(e)}.`);if(!Object.hasOwn(e,t))return new ee(`Property ${t} is undefined on object.`);const n=e[t];return n===void 0?new ee(`Property ${t} is undefined on object.`):n}function Ze(e){return z(e)?!1:e!==!1&&e!==null&&e!==void 0&&!(typeof e=="number"&&Number.isNaN(e))}const ii=20;function B(e,t){switch(e.kind){case"literal":return e.value;case"ident":return e.name in t.locals?t.locals[e.name]:e.name==="request"?Ch(t.input,t.now):e.name==="resource"?t.input.resource===null?new ee("Null value error."):Eh(t.input.resource):e.name in t.params?t.params[e.name]:void 0;case"member":{const n=B(e.target,t);return z(n)?n:n==null?new ee("Null value error."):si(n,e.name)}case"index":{const n=B(e.target,t);if(z(n))return n;if(n==null)return new ee("Null value error.");const r=B(e.index,t);return z(r)?r:si(n,String(r))}case"call":return Sh(e,t);case"methodcall":return dh(e,t);case"path":throw new T("a Firestore path literal is only valid as an argument to firestore.get()/exists()");case"unary":{const n=B(e.arg,t);return z(n)?n:e.op==="-"?n instanceof ke?new ke(-n.value):typeof n!="number"?new ee(`Unary '-' applied to ${ae(n)}.`):-n:!Ze(n)}case"ternary":{const n=B(e.cond,t);return z(n)?n:Ze(n)?B(e.then,t):B(e.else,t)}case"in":{const n=B(e.element,t);if(z(n))return n;const r=B(e.collection,t);return z(r)?r:Array.isArray(r)?r.some(s=>st(s,n)):Pe(r)?typeof n=="string"&&Object.prototype.hasOwnProperty.call(r,n):new ee(`'in' applied to ${ae(r)} (expected a list or map).`)}case"is":{const n=B(e.value,t);return z(n)?n:_h(n,e.typeName)}case"list":{const n=[];for(const r of e.elements){const s=B(r,t);if(z(s))return s;n.push(s)}return n}case"map":{const n={};for(const r of e.entries){const s=B(r.key,t);if(z(s))return s;if(typeof s!="string")return new ee(`Map literal key is ${ae(s)} (expected a string).`);const i=B(r.value,t);if(z(i))return i;n[s]=i}return n}case"slice":{const n=B(e.target,t);if(z(n))return n;const r=B(e.start,t);if(z(r))return r;const s=B(e.end,t);return z(s)?s:typeof r!="number"||typeof s!="number"||!Number.isInteger(r)||!Number.isInteger(s)?new ee("Slice bounds must be integers."):Array.isArray(n)||typeof n=="string"?r<0||s<r||s>n.length?new ee(`Slice bounds [${r}:${s}] out of range for ${ae(n)} of size ${n.length}.`):n.slice(r,s):new ee(`Slice applied to ${ae(n)} (expected a list or string).`)}case"binary":{if(e.op==="&&"){const s=B(e.left,t);return z(s)?s:Ze(s)?B(e.right,t):s}if(e.op==="||"){const s=B(e.left,t);if(z(s)){const i=B(e.right,t);return Ze(i)?i:s}return Ze(s)?s:B(e.right,t)}const n=B(e.left,t);if(z(n))return n;const r=B(e.right,t);if(z(r))return r;switch(e.op){case"==":return st(n,r);case"!=":return!st(n,r);case"<":return Ft(n,r)<0;case">":return Ft(n,r)>0;case"<=":return Ft(n,r)<=0;case">=":return Ft(n,r)>=0;case"+":return Ue(n,r,(s,i)=>s+i);case"-":return Ue(n,r,(s,i)=>s-i);case"*":return Ue(n,r,(s,i)=>s*i);case"/":return et(n)||et(r)?Ue(n,r,(s,i)=>s/i):De(r)===0?new ee("Division by zero."):Ue(n,r,(s,i)=>Math.trunc(s/i));case"%":return et(n)||et(r)?Ue(n,r,(s,i)=>s%i):De(r)===0?new ee("Modulo by zero."):Ue(n,r,(s,i)=>s%i)}}}}function Sh(e,t){const n=t.funcs.get(e.name);if(!n)throw new T(`undefined function ${e.name}()`);if(n.unresolvedImport!==void 0)throw new T(`function ${e.name}() is imported from '${n.unresolvedImport}', but import module resolution is not implemented`);if(n.params.length!==e.args.length)throw new T(`function ${e.name}() expects ${n.params.length} argument(s), got ${e.args.length}`);const r=t.depth+1;if(r>ii)throw new T(`function ${e.name}() exceeded max call depth ${ii}`);const s=e.args.map(c=>B(c,t)),i={};n.params.forEach((c,l)=>{i[c]=s[l]});const a={input:t.input,now:t.now,params:{},locals:i,funcs:n.declScope??new Map,depth:r,firestoreLookup:t.firestoreLookup,firestoreAccesses:t.firestoreAccesses};for(const c of n.lets)i[c.name]=B(c.value,a);return B(n.body,a)}function _h(e,t){switch(t){case"string":return typeof e=="string";case"bool":return typeof e=="boolean";case"int":return typeof e=="number"&&Number.isInteger(e);case"float":return e instanceof ke||typeof e=="number"&&!Number.isInteger(e);case"number":return e instanceof ke||typeof e=="number";case"list":return Array.isArray(e);case"map":return Pe(e);default:return new ee(`'is ${t}' is not supported by the storage evaluator.`)}}function et(e){return e instanceof ke}function Ft(e,t){const n=De(e),r=De(t);return n!==void 0&&r!==void 0?n-r:typeof e=="string"&&typeof t=="string"?e<t?-1:e>t?1:0:Number.NaN}function Ue(e,t,n){const r=De(e),s=De(t);if(r===void 0||s===void 0)return;const i=n(r,s);return et(e)||et(t)?new ke(i):i}function Eh(e){return{size:e.size,contentType:e.contentType,metadata:e.metadata,name:e.name,bucket:e.bucket,generation:e.generation,metageneration:e.metageneration,timeCreated:ai(e.timeCreated),updated:ai(e.updated)}}function ai(e){if(e===void 0)return;const t=Date.parse(e);return Number.isNaN(t)?void 0:t}function Ch(e,t){return{auth:e.request.auth??new ee("Property auth is undefined on object."),resource:e.request.resource??new ee("Property resource is undefined on object."),method:e.request.method,path:e.request.path,time:t}}function Nh(e){return`storage/${e}`}class mt extends Error{code;constructor(t,n){const r=Nh(t);super(`${r}: ${n}`),this.name="StorageError",this.code=r,Object.setPrototypeOf(this,mt.prototype)}}function ho(e){return new mt("object-not-found",`no object at "${e}".`)}function Rh(e,t,n){return new mt("unauthorized",`${e} "${t}" denied by rules${n}.`)}function Cn(e){return new mt("invalid-root-operation",`${e} cannot operate on the root reference.`)}function Ah(){return new mt("canceled","User canceled the upload/download.")}function Ut(e,t,n,r){const s=n?.kind==="sandbox"?pt(n,r):r;if(n?.kind==="sandbox"&&n.admin===!0){Vt(n,t,"not-applicable",void 0,"admin",!1,s);return}if(!e.rules){Vt(n,t,"allow",void 0,"user",!1,s);return}const i=n?Ih(t,n.bucket):t,a=fo(e.rules,i,void 0,Dh(n));if(!a.allowed){Vt(n,t,"deny",a.reasons,"user",!0,s);const c=a.reasons.length>0?` — ${a.reasons.join("; ")}`:"";throw Rh(t.request.method,t.request.path,c)}Vt(n,t,"allow",a.reasons,"user",!0,s)}function Ih(e,t){const n=e.request.path.replace(/^\/+/,"");return{...e,request:{...e.request,path:n===""?`b/${t}/o`:`b/${t}/o/${n}`}}}function Vt(e,t,n,r,s,i,a){if(e)try{Re(e.sandbox,xa({service:"storage",method:t.request.method,path:t.request.path,auth:t.request.auth,result:n,origin:s,reasons:r,rulesDisposition:s==="admin"?{kind:"bypassed",reason:"admin"}:i?{kind:"evaluated",verdict:n==="deny"?"deny":"allow"}:{kind:"not-evaluated",reason:"no-rules"},rules:i?{engine:"storage",reason:r&&r.length>0?r.join("; "):void 0}:void 0}),{...a,service:"storage"})}catch{}}function Dh(e){if(!e)return;const t=e.sandbox.admin;return{get:n=>t.getDocument(n),exists:n=>t.getDocument(n)!==null}}function Nn(e){return e?{size:e.size,contentType:e.contentType,metadata:e.customMetadata,name:Ph(e.fullPath,e.bucket),bucket:e.bucket,timeCreated:e.timeCreated,updated:e.updated,generation:oi(e.generation),metageneration:oi(e.metageneration)}:null}function Ph(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 oi(e){if(e===void 0)return;const t=Number(e);return Number.isFinite(t)?t:void 0}function $h(e){return{size:e.size,contentType:e.contentType,metadata:e.customMetadata}}function ss(e){return{...e}}async function Oh(e){Mh(e,"getMetadata");const t=Se(e.storage),n=pt(t),r=await Mt(e.storage),s=await r.backend.getMetadata(e.fullPath);if(Ut(r,{request:{auth:ze(t),method:"get",path:e.fullPath},resource:Nn(s)},t,n),!s)throw ho(e.fullPath);return ss(s)}function Mh(e,t){if(e.fullPath==="")throw Cn(t)}const Uh="application/octet-stream";async function po(e,t,n,r){Lh(e,"uploadBytes");const s=Se(e.storage),i=pt(s,r),a=Th(t,n?.contentType),c=mo({ref:e,blob:a,settable:n}),l=await Mt(e.storage),u=await l.backend.getMetadata(e.fullPath);Ut(l,{request:{auth:ze(s),method:u?"update":"create",path:e.fullPath,resource:$h({size:c.size,contentType:c.contentType,customMetadata:c.customMetadata})},resource:Nn(u)},s,i),await l.backend.put(e.fullPath,a,c);try{Re(s.sandbox,vn({service:"storage",op:"object_put",path:e.fullPath,auth:ze(s),before:u??void 0,after:c,detail:{bucket:e.bucket,size:c.size,contentType:c.contentType,overwrite:u!=null}}),i)}catch{}return{ref:e,metadata:ss(c)}}function mo(e){const{ref:t,blob:n,settable:r}=e,s=(e.now??new Date).toISOString(),i=Bh(e.now??new Date),a=t.name;return{fullPath:t.fullPath,name:a,bucket:t.bucket,generation:i,metageneration:"1",timeCreated:s,updated:s,size:n.size,contentType:r?.contentType||n.type||Uh,cacheControl:r?.cacheControl,contentDisposition:r?.contentDisposition,contentEncoding:r?.contentEncoding,contentLanguage:r?.contentLanguage,customMetadata:r?.customMetadata}}function Th(e,t){return e instanceof Blob?t&&t!==e.type?new Blob([e],{type:t}):e:new Blob([e],{type:t??""})}function Bh(e){return String(e.getTime())}function Lh(e,t){if(e.fullPath==="")throw Cn(t)}function Fh(e){return e instanceof Blob?e.size:e.byteLength}function Vh(){const e=new Error("storage/canceled: User canceled the upload/download.");return e.code="storage/canceled",e}function qh(){const e=new Error("storage/invalid-root-operation: uploadBytesResumable cannot operate on root reference.");return e.code="storage/invalid-root-operation",e}class Wh{[Symbol.toStringTag]="UploadTask";_snapshot;_promise;_resolve;_reject;_observers=[];_didIntermediateProgress=!1;_error;_ref;_data;_metadata;constructor(t,n,r){this._ref=t,this._data=n,this._metadata=r;const s=Fh(n),i=new Date().toISOString();let a="application/octet-stream";if(n instanceof Blob&&n.type!==""&&(a=n.type),r!==void 0&&r.contentType!==void 0){const p=r.contentType;p!==void 0&&(a=p)}const u={fullPath:t.fullPath,name:t.name,bucket:"default",generation:"1",metageneration:"1",timeCreated:i,updated:i,size:s,contentType:a};this._promise=new Promise((d,p)=>{this._resolve=d,this._reject=p}),this._promise.catch(()=>{}),this._snapshot={bytesTransferred:0,totalBytes:s,state:"running",metadata:u,ref:this._ref,task:this},queueMicrotask(()=>{this._runStep()})}get snapshot(){return this._snapshot}then(t,n){return this._promise.then(t,n)}catch(t){return this._promise.catch(t)}finally(t){return this._promise.finally(t)}pause(){return this._snapshot.state==="running"?(this._updateSnapshot("paused",this._snapshot.bytesTransferred),this._notifyObservers("next"),!0):!1}resume(){return this._snapshot.state==="paused"?(this._updateSnapshot("running",this._snapshot.bytesTransferred),this._notifyObservers("next"),queueMicrotask(()=>{this._runStep()}),!0):!1}cancel(){let t=!1;return(this._snapshot.state==="running"||this._snapshot.state==="paused")&&(t=!0),t?(this._error=Vh(),this._updateSnapshot("canceled",this._snapshot.bytesTransferred),this._notifyObservers("error"),this._reject(this._error),!0):!1}on(t,n,r,s){let i,a,c,l=!1;if(typeof n=="object"&&n!==null&&(l=!0),l){const f=n;f.next!==void 0&&(i=f.next),f.error!==void 0&&(a=f.error),f.complete!==void 0&&(c=f.complete)}else typeof n=="function"&&(i=n),typeof r=="function"&&(a=r),typeof s=="function"&&(c=s);const d={next:i,error:a,complete:c};if(this._observers.push(d),this._snapshot.state==="running"){if(i!==void 0){const m=i;try{m(this._snapshot)}catch{}}}else if(this._snapshot.state==="paused"){if(i!==void 0){const y=i;try{y(this._snapshot)}catch{}}}else if(this._snapshot.state==="success"){if(i!==void 0){const v=i;try{v(this._snapshot)}catch{}}if(c!==void 0){const v=c;try{v()}catch{}}}else if(this._snapshot.state==="error"){if(a!==void 0&&this._error!==void 0){const b=a,w=this._error;try{b(w)}catch{}}}else if(this._snapshot.state==="canceled"&&a!==void 0&&this._error!==void 0){const w=a,x=this._error;try{w(x)}catch{}}return()=>{const f=this._observers.indexOf(d);f!==-1&&this._observers.splice(f,1)}}_updateSnapshot(t,n,r){let s=this._snapshot.metadata;r!==void 0&&(s=r),this._snapshot={bytesTransferred:n,totalBytes:this._snapshot.totalBytes,state:t,metadata:s,ref:this._ref,task:this}}_notifyObservers(t){if(t==="next"){for(const i of this._observers)if(i.next!==void 0){const c=i.next;try{c(this._snapshot)}catch{}}}if(t==="error"){for(const i of this._observers)if(i.error!==void 0&&this._error!==void 0){const l=i.error,u=this._error;try{l(u)}catch{}}}if(t==="complete"){for(const i of this._observers)if(i.complete!==void 0){const c=i.complete;try{c()}catch{}}}}_runStep(){if(this._snapshot.state!=="running")return;if(this._didIntermediateProgress===!1){this._didIntermediateProgress=!0;let r=0;this._snapshot.totalBytes>0&&(r=Math.floor(this._snapshot.totalBytes/2)),this._updateSnapshot("running",r),this._notifyObservers("next"),queueMicrotask(()=>{this._runStep()});return}this._commitUpload()}async _commitUpload(){if(this._snapshot.state==="running")try{const n=await yo(this._ref,this._data,this._metadata);if(this._snapshot.state==="running")this._updateSnapshot("success",this._snapshot.totalBytes,n.metadata),this._notifyObservers("next"),this._notifyObservers("complete"),this._resolve(this._snapshot);else try{await bo(this._ref)}catch{}}catch(n){if(this._snapshot.state==="running"){let s;n instanceof Error?s=n:s=new Error(String(n)),this._error=s,this._updateSnapshot("error",this._snapshot.bytesTransferred),this._notifyObservers("error"),this._reject(this._error)}}}}function zh(e,t,n){if(e.fullPath==="")throw qh();return new Wh(e,t,n)}class Rt{__kind="storage-ref";port;storage;bucket;fullPath;name;constructor(t,n,r,s){this.port=t,this.bucket=n,this.fullPath=r,this.name=ns(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 Rt(this.port,this.bucket,n,this.storage)}get root(){return this.fullPath===""?this:new Rt(this.port,this.bucket,"",this.storage)}toString(){return`gs://${this.bucket}/${this.fullPath}`}}function Kh(e){return e.replace(/^\/+|\/+$/g,"")}function Hh(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(),Zr(r)}return{__kind:"client-storage",port:r,bucket:n??"pyric-default"}}function Gh(e,t){const n=Kh(t??"");let r,s,i="pyric-default",a;if(e.__kind==="client-storage")r=n,s=e.port,i=e.bucket,a=e;else{const c=e.fullPath;r=n?c?`${c}/${n}`:n:c,s=e.port,i=e.bucket,a=e.storage}return new Rt(s,i,r,a)}async function Jh(e){const t=await de(e.port,{t:"op",id:U(),method:"storage.listAll",path:e.fullPath}),n=r=>new Rt(e.port,e.bucket,r.fullPath,e.storage);return{items:t.items.map(n),prefixes:t.prefixes.map(n)}}async function Yh(e){return await de(e.port,{t:"op",id:U(),method:"storage.getMetadata",path:e.fullPath})}async function Qh(e){return await de(e.port,{t:"op",id:U(),method:"storage.getBlob",path:e.fullPath})}async function yo(e,t,n){const r=t instanceof Blob?new Uint8Array(await t.arrayBuffer()):t instanceof ArrayBuffer?new Uint8Array(t):t;if(r.byteLength>ao)throw jf(r.byteLength,`uploadBytes payload for '${e.fullPath}'`);const s=n?.contentType??(t instanceof Blob&&t.type?t.type:void 0),i=await de(e.port,{t:"op",id:U(),method:"storage.putBytes",path:e.fullPath,dataB64:kf(r),...s!==void 0?{contentType:s}:{},...n!==void 0?{metadata:n}:{}});return{ref:e,metadata:i}}async function bo(e){await de(e.port,{t:"op",id:U(),method:"storage.deleteObject",path:e.fullPath})}new Array(12).fill(0);async function Xh(e){return W(e.port,{t:"op",id:U(),method:"rtdb.adminSnapshot"})}async function Zh(e,t,n){await W(e.port,{t:"op",id:U(),method:"rtdb.set",path:t,value:n,actAs:{mode:"admin"}})}async function ep(e,t,n){await W(e.port,{t:"op",id:U(),method:"rtdb.update",path:t,values:n,actAs:{mode:"admin"}})}async function tp(e,t){await W(e.port,{t:"op",id:U(),method:"rtdb.remove",path:t,actAs:{mode:"admin"}})}function np(e,t,n,r){const s=ft();return!$t(e.port,s,{port:e.port,next:a=>n(a?.value??null),error:r},es({t:"sub",subId:s,target:{service:"rtdb",path:uf(t)},actAs:{mode:"admin"}}))&&r&&queueMicrotask(()=>r(new Error("FIREBASE FATAL ERROR: Database has been deleted."))),()=>Ot(e.port,s)}function rp(e){const t=new Set;let n={servedEpoch:e.servedEpoch,runningEpoch:null,updateAvailable:!1,updating:!1,error:null};const r=l=>{n={...n,...l};for(const u of t)u()},s=e.storage,i=e.servedEpoch;let a=null;const c=()=>i?(a??=Pd({targetEpoch:i,retire:()=>e.retire?e.retire(i):Jd(e.db,i),subscribeReload:e.subscribeReload??Yd,preflight:e.preflight??(()=>Dd(s)),commitGeneration:e.remember??(l=>Id(l,s)),onPreparationError:l=>r({updating:!1,error:l instanceof Error?l.message:String(l)}),reload:e.reload??(()=>window.location.reload()),...e.schedule?{schedule:e.schedule}:{}}),a):null;return(e.readVersion??(()=>Xd(e.db)))().then(l=>r({runningEpoch:l,updateAvailable:!!(i&&l!=="dev"&&l!==i)})).catch(l=>r({error:l instanceof Error?l.message:String(l)})),{getSnapshot:()=>n,subscribe(l){return t.add(l),c(),()=>{t.delete(l),t.size===0&&(a?.dispose(),a=null)}},async update(){const l=c();if(!l||!n.updateAvailable||n.updating)throw new Error("No Pyric worker update is available.");r({updating:!0,error:null});try{await l.request()}catch(u){throw r({updating:!1,error:u instanceof Error?u.message:String(u)}),u}},dispose(){t.clear(),a?.dispose(),a=null}}}function sp(e={}){const t=no(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:Ad(t.worker.servedEpoch,n)}}const ip="/__pyric/sdk/worker.js";function ap(e){let t=[],n=!1;const r=new Set;let s=null;function i(){s||(s=$f(e,a=>{const c=!n;n=!0;const l=c?[]:[...t];for(const u of a)Za(u)&&(l.length=0),l.push(u);t=l;for(const u of a)for(const d of r)d(u)}))}return{history:()=>t,subscribe:a=>(r.add(a),i(),()=>{r.delete(a),r.size===0&&s&&(s(),s=null,n=!1,t=[])})}}function op(e=ip){if(typeof SharedWorker>"u")return null;Gd("studio");let t;try{const l=sp({workerUrl:e});t=Qd(l.url,l.name)}catch{return null}let n;try{n=typeof localStorage>"u"?void 0:localStorage}catch{n=void 0}const r=rp({db:t,servedEpoch:no(typeof document>"u"?void 0:document).worker.servedEpoch,storage:n});Js({mode:"admin"});const s=Bf({db:t,kind:"studio"}),i=ap(t),a=Wf(t);let c=!1;return{db:t,runtime:r,dispose:async()=>{c||(c=!0,s.stop(),r.dispose(),await mf(t).catch(()=>{}))},presenceClientId:s.clientId,subscribePresence:l=>Lf(t,l),instanceId:()=>Zd(t),exportState:()=>ef(t),importState:l=>tf(t,l),saveBranch:l=>nf(t,l),listBranches:()=>rf(t),switchBranch:l=>sf(t,l),deleteBranch:l=>af(t,l),feed:i,setLens:l=>Js(l),getLens:()=>Hd(),listRootCollections:()=>Cf(t),listSubcollections:l=>Nf(t,l),listDocuments:async l=>(await Pf(t,l)).map(({path:u,phantom:d})=>({path:u,phantom:d})),readRtdbState:()=>Xh(t),setRtdbValue:(l,u)=>Zh(t,l,u),updateRtdbValue:(l,u)=>ep(t,l,u),deleteRtdbValue:l=>tp(t,l),subscribeRtdbValue:(l,u,d)=>np(t,l,u,d),firestoreApi:{collection:bf,doc:yf,getDoc:_f,getDocs:Ef,onSnapshot:Rf,setDoc:Af,deleteDoc:If,addDoc:Df,query:wf,limit:gf,startAfter:vf},auth:a,authApi:{listUsers:()=>zf(a),subscribeUsers:(l,u)=>i.subscribe(d=>{d.kind==="service_mutation"&&d.service==="auth"&&u()}),createUser:(l,u)=>Kf(a,u),updateUser:(l,u,d)=>Hf(a,u,d),deleteUser:(l,u)=>Gf(a,u),clearUsers:()=>Jf(a),getAuthProviderConfig:()=>Yf(a),setAuthProviderConfig:(l,u,d)=>Qf(a,u,d),subscribeAuthProviderConfig:(l,u)=>i.subscribe(d=>{d.kind==="service_mutation"&&d.op==="provider_config_update"&&u()})},storage:Hh(t),storageApi:{ref:Gh,listAll:Jh,getMetadata:Yh,getBlob:Qh,uploadBytes:yo,uploadBytesResumable:zh,deleteObject:bo},getSnapshot:()=>Of(t),resetAll:()=>Mf(t)}}const ci=5174,li="/sandbox",cp=4001,lp="worker-relay";function up(e){if(e===null||typeof e!="object")return!1;const t=e.type;return t==="hello"||t==="hello-ack"||t==="attach"||t==="attach-ack"||t==="tool-call"||t==="tool-result"||t==="worker-op"||t==="worker-res"||t==="worker-sub"||t==="worker-unsub"||t==="worker-snap"||t==="ping"||t==="pong"}function _r(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=_r(t);if(n)return n}return null}for(const t of Object.values(e)){const n=_r(t);if(n)return n}return null}function ui(e,t){const n=_r(t);if(!n)return;const r=new Error(`worker ${e} produced a binary payload (${n}) that cannot cross the JSON bridge relay — it would be silently corrupted by JSON.stringify. Use the base64 storage ops instead ('storage.getBytes' / 'storage.putBytes'), which carry bytes as JSON-safe 'dataB64' strings; 'storage.getBlob' is MessagePort-only.`);throw r.code="invalid-argument",r}function di(e,t){return{code:e.code,severity:t,message:e.message,path:e.path,origin:"validate"}}const ge=e=>e,fi=(...e)=>ge(e.map(t=>`(${t})`).join(" && ")),dp=(...e)=>ge(e.map(t=>`(${t})`).join(" || ")),go=e=>e,fp=()=>go("newData.hasChildren()"),hp=e=>go(`newData.hasChild("${e}")`);function vo(e,t){const n=e.shape,r=[],s={};for(const[c,l]of Object.entries(n)){const u=l,d=u instanceof ml,p=d?u.unwrap():u;d||r.push(c);const f=wo(p,c),m=t?.[c];if(m&&m.length>0?s[c]={validate:fi(f,...m)}:s[c]={validate:f},p instanceof ka){const y=vo(p);s[c]={validate:y.validate,children:y.children}}}const i=[fp()];for(const c of r)i.push(hp(c));return{validate:fi(...i),children:s}}function wo(e,t){if(e instanceof yl)return ge("newData.isString()");if(e instanceof bl)return ge("newData.isNumber()");if(e instanceof gl)return ge("newData.isBoolean()");if(e instanceof vl){const n=e.options;return ge(n.map(r=>`newData.val() === "${r}"`).join(" || "))}if(e instanceof wl){const n=e.value;return ge(typeof n=="string"?`newData.val() === "${n}"`:`newData.val() === ${n}`)}if(e instanceof xl){const n=e._def.options;return dp(...n.map(r=>wo(r,t)))}if(e instanceof ka)return ge("newData.hasChildren()");throw new Error(`Unsupported Zod type for RTDB rules: ${e.constructor.name} on field "${t}"`)}function pp(e){let t;if(typeof e=="function"){const s=[];e({path:(i,a)=>s.push([i,a])}),t=s}else t=Object.entries(e);const n=xo(t);n.sort((s,i)=>{const a=s[0]==="/"?0:s[0].split("/").filter(Boolean).length,c=i[0]==="/"?0:i[0].split("/").filter(Boolean).length;return a-c||s[0].localeCompare(i[0])});const r={path:"/",pathVariables:[],children:[]};for(const[s]of n)s!=="/"&&mp(r,s);for(const[s,i]of n){const a=s==="/"?r:is(r,s);a&&yp(r,a,i,s)}return r}function mp(e,t){const n=t.split("/").filter(Boolean);let r=e;for(let s=0;s<n.length;s++){const i="/"+n.slice(0,s+1).join("/"),a=n.slice(0,s+1).filter(l=>l.startsWith("$"));let c=r.children.find(l=>l.path===i);c||(c={path:i,pathVariables:a,children:[]},r.children.push(c)),r=c}}function yp(e,t,n,r){const s=r.split("/").filter(i=>i.startsWith("$"));if(n.read&&(t.read=Ye(n.read,"read",s)),n.write&&(t.write=Ye(n.write,"write",s)),n.validate&&(t.validate=Ye(n.validate,"validate",s)),n.schema){const i=vo(n.schema,n.fieldConstraints);t.validate||(t.validate=Ye(i.validate,"validate",s));for(const[a,c]of Object.entries(i.children)){const l=`${r}/${a}`;let u=t.children.find(d=>d.path===l);if(u||(u={path:l,pathVariables:s,children:[]},t.children.push(u)),u.validate=Ye(c.validate,"validate",s),"children"in c&&c.children)for(const[d,p]of Object.entries(c.children)){const f=`${l}/${d}`;let m=u.children.find(y=>y.path===f);m||(m={path:f,pathVariables:s,children:[]},u.children.push(m)),m.validate=Ye(p.validate,"validate",s)}}}if(n.indexOn){const i=r.split("/").filter(Boolean);if(i[i.length-1]?.startsWith("$")){const c="/"+i.slice(0,-1).join("/"),l=is(e,c);l&&(l.indexOn=n.indexOn)}}}function xo(e){const t=[];for(const[n,r]of e){const{children:s,...i}=r;if(t.push([n,i]),s){const a=Object.entries(s).map(([c,l])=>[n+c,l]);t.push(...xo(a))}}return t}function Ye(e,t,n){return Oa(String(e),t,n)}function is(e,t){if(e.path===t)return e;for(const n of e.children){const r=is(n,t);if(r)return r}return null}function bp(e){return e==null?null:typeof e=="string"?{uid:e,token:{}}:{uid:e.uid,token:e.token??{}}}function gp(e){return{operation:e.operation,path:e.path,auth:bp(e.auth),mockData:e.mockData??e.data??{},...e.newData!==void 0?{newData:e.newData}:{}}}function Gn(e,t,n,r){return(n?.parsed[r]??[]).map(s=>({path:e,rule:t,code:s.code,message:s.message}))}function Er(e,t){const n=[...Gn(e.path,".read",e.read,t),...Gn(e.path,".write",e.write,t),...Gn(e.path,".validate",e.validate,t)];for(const r of e.children)n.push(...Er(r,t));return n}class vp{definition;constructor(t){this.definition=t}compile(){return pp(this.definition.paths)}toJSON(){return Du(this.compile())}check(){try{const t=this.compile(),n=Er(t,"errors"),r=Er(t,"warnings");return{ok:n.length===0,errors:n,warnings:r}}catch(t){return{ok:!1,errors:[{path:"/",rule:"ruleset",code:"COMPILE_ERROR",message:t instanceof Error?t.message:String(t)}],warnings:[]}}}simulate(t){return Yr(this.compile(),gp(t))}}function wp(e){return new vp(e)}function xp(e){const t=e;return typeof t.toJSON=="function"&&typeof t.simulate=="function"&&typeof t.check=="function"}function jp(e){const t=e;return typeof t=="object"&&t!==null&&"rules"in t&&!("paths"in t)&&typeof t.toJSON!="function"}class Jn{doc;constructor(t){this.doc=t}lint(){const t=this.doc.check();return[...t.errors.map(n=>di(n,"error")),...t.warnings.map(n=>di(n,"warning"))]}runOne(t){const n=this.doc.simulate({operation:t.operation,path:t.path,auth:t.auth??null,...t.data!==void 0?{data:t.data}:{},...t.newData!==void 0?{newData:t.newData}:{}});if(!n.success)return{case:t,...t.description!==void 0?{description:t.description}:{},expectation:t.expectation,decision:"UNSUPPORTED",passed:!1,unsupported:!0,matchedPath:t.path,matchedRule:t.operation,reason:n.error.message};const r=n.data,s=r.unsupported===!0,i=s?"UNSUPPORTED":r.allowed?"ALLOW":"DENY",a=!s&&i===t.expectation;return{case:t,...t.description!==void 0?{description:t.description}:{},expectation:t.expectation,decision:i,passed:a,unsupported:s,matchedPath:r.matchedPath,matchedRule:r.matchedRule,reason:r.reason}}simulate(t){const n=t.map(a=>this.runOne(a));let r=0,s=0,i=0;for(const a of n)a.unsupported?i++:a.passed?r++:s++;return{passed:r,failed:s,unsupported:i,cases:n}}explain(t){const n=this.runOne(t);return{decision:n.decision,expectation:n.expectation,passed:n.passed,unsupported:n.unsupported,matchedPath:n.matchedPath,matchedRule:n.matchedRule,reason:n.reason}}toJSON(){return this.doc.toJSON()}}function kp(e){return e==null?null:typeof e=="string"?{uid:e,token:{}}:{uid:e.uid,token:e.token??{}}}class Sp{json;compiled;constructor(t){this.json=t,this.compiled=Ua(t)}toJSON(){return this.json}compile(){return this.compiled}check(){return{ok:!0,errors:[],warnings:[]}}simulate(t){return Yr(this.compiled,{operation:t.operation,path:t.path,auth:kp(t.auth),mockData:t.mockData??t.data??{},...t.newData!==void 0?{newData:t.newData}:{}})}}function _p(e){return xp(e)?new Jn(e):jp(e)?new Jn(new Sp(e)):new Jn(wp(e))}function Ep(e,t){return e==="/"?`/${t}`:`${e}/${t}`}function hi(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function Cp(e){const t=(e??"/").split("/").filter(Boolean);return t.length===0?"/":`/${t.join("/")}`}function Np(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 jo(e,t,n,r,s){if(e===null||typeof e!="object"||Array.isArray(e))return{path:t,childCount:0,truncated:!1,children:[],schema:{},valueType:hi(e)};const i=Object.entries(e).sort(([p],[f])=>p.localeCompare(f)),a={},c=[];for(const[p,f]of i)f!==null&&typeof f=="object"&&!Array.isArray(f)?c.push([p,f]):a[p]=hi(f);const l=n>=r&&c.length>0,u=i.length>s,d=n>=r?[]:c.slice(0,s).map(([p,f])=>jo(f,Ep(t,p),n+1,r,s));return{path:t,childCount:i.length,truncated:l||u,children:d,schema:a}}function Rp(e,t={}){const n=Cp(t.path),r=t.maxDepth??10,s=t.maxChildren??100;return jo(Np(e,n),n,0,r,s)}function ko(e){return e.children.reduce((t,n)=>t+1+ko(n),0)}function So(e){return[{name:"rtdb_simulate_access",description:"Simulate one read, write, or validate operation against the RTDB rules and data currently loaded in the local sandbox. No production database is contacted and no prior rules-loading tool call is required.",parameters:{type:"object",properties:{operation:{type:"string",enum:["read","write","validate"]},path:{type:"string"},auth:{anyOf:[{type:"null"},{type:"object",properties:{uid:{type:"string"},claims:{type:"object"}},required:["uid"]}]},newData:{}},required:["operation","path"]},async execute(t){const n=t,r=await e.resolveSandbox(),s=La(r);if(!s)return{ok:!1,summary:"No RTDB rules are loaded in the local sandbox.",data:{code:"NO_ACTIVE_RULES"}};const i=Fs(r),a=i!==null&&typeof i=="object"&&!Array.isArray(i)?i:{},c={expectation:"ALLOW",operation:n.operation,path:n.path,auth:n.auth?{uid:n.auth.uid,token:n.auth.claims??{}}:null,data:a,...n.newData!==void 0?{newData:n.newData}:{}},l=_p(s).simulate([c]).cases[0];return{ok:!l.unsupported,summary:l.unsupported?`Simulation unsupported: ${l.reason}`:`Simulation: ${l.decision.toLowerCase()}`,data:{decision:l.decision,allowed:l.decision==="ALLOW",unsupported:l.unsupported,matchedPath:l.matchedPath,matchedRule:l.matchedRule,reason:l.reason}}}},{name:"rtdb_crawl_structure",description:"Describe the structure of the RTDB data currently loaded in the local sandbox without returning leaf values or contacting a production database.",parameters:{type:"object",properties:{path:{type:"string",description:"Root-relative path to inspect. Defaults to /."},maxDepth:{type:"number",minimum:0,description:"Maximum object depth to return. Defaults to 10."},maxChildren:{type:"number",minimum:1,description:"Maximum object children to return per node. Defaults to 100."}}},async execute(t){const n=t,r=await e.resolveSandbox(),s=Rp(Fs(r),n);return{ok:!0,summary:`Crawled ${ko(s)} object paths from ${s.path}`,data:s}}}]}function Ap(e){const t=wn(e),n=r=>r&&r!=="admin"?Na(e.withAuth({uid:r.uid,token:r.claims})):Ra(e);return[...Da({resolveSandbox:()=>t}),...Ya({resolveDb:n}),...Qa({resolveSandbox:()=>e}),...So({resolveSandbox:()=>e})]}function Ip(e){const t=new Map(Ap(e).map(n=>[n.name,n]));return async(n,r)=>{const s=t.get(n);if(!s)throw new $p(n);const i={signal:new AbortController().signal},a=await s.execute(r,i);return{ok:a.ok,summary:a.summary,data:a.data}}}const pi=new WeakMap;async function Dp(e,t,n){let r=pi.get(e);return r||(r=Ip(e),pi.set(e,r)),r(t,n)}const Pp=(()=>{const e=async()=>{throw new Error("SANDBOX_TOOL_NAMES: stub resolver should never be invoked")};return[...Da({resolveSandbox:e}),...Ya({resolveDb:e}),...Qa({resolveSandbox:e}),...So({resolveSandbox:e})].map(t=>t.name)})();class $p extends Error{tool;constructor(t){super(`unknown sandbox tool: ${t}`),this.tool=t,this.name="UnknownToolError"}}const Op=500,Mp=3e4,Up=2e3,Tp=.5,Bp=3;function Lp(e,t={}){const n=Fp(t.url),r=t.sandboxId??Vp(),s=t.dispatcher??Dp,i=t.toolNames??[...Pp],a=t.initialReconnectDelayMs??Op,c=t.maxReconnectDelayMs??Mp,l=t.noReconnect??!1,u=t.onStateChange??(()=>{}),d=t.standbyPollMs??Up,p=t.fetchImpl??(A=>fetch(A)),f=t.workerRelay??null;let m=null,y=!1,g=0,v=null,b=null,w=0,x={kind:"connecting"};const k=new Map;function j(){for(const A of k.values())try{A()}catch{}k.clear()}function S(A){x=A;try{u(A)}catch{}}function N(A){if(m&&m.readyState===WebSocket.OPEN)try{m.send(JSON.stringify(A))}catch{}}function P(){if(y)return;S({kind:"connecting"});let A;try{A=new WebSocket(n)}catch(O){G(`failed to open WebSocket: ${O instanceof Error?O.message:String(O)}`);return}m=A,A.onopen=()=>{g=0;const O={type:"hello",protocol:1,tools:i,sandboxId:r,...f?{capabilities:[lp]}:{}};N(O)},A.onmessage=O=>{let M;try{M=JSON.parse(typeof O.data=="string"?O.data:"")}catch{return}if(up(M)){if(M.type==="hello-ack"){S({kind:"connected",bridgeVersion:M.bridgeVersion});return}if(M.type==="tool-call"){I(M);return}if(M.type==="worker-op"){D(M);return}if(M.type==="worker-sub"){C(M);return}if(M.type==="worker-unsub"){const $=k.get(M.subId);if($){k.delete(M.subId);try{$()}catch{}}return}if(M.type==="ping"){N({type:"pong",id:M.id});return}}},A.onclose=O=>{const M=O.reason||`closed (code ${O.code})`;if(m=null,j(),O.code===cp){E();return}G(M)},A.onerror=()=>{}}async function I(A){let O;try{const M=await s(e,A.name,A.args??{});O={type:"tool-result",id:A.id,ok:!0,result:M}}catch(M){O={type:"tool-result",id:A.id,ok:!1,error:{code:M instanceof Error?M.name:"Error",message:M instanceof Error?M.message:String(M)}}}N(O)}async function D(A){if(f)try{const O=await f.op(A.op);ui(`op '${A.op.method}'`,O),N({type:"worker-res",id:A.id,ok:!0,value:O})}catch(O){const M=O.denialContext;N({type:"worker-res",id:A.id,ok:!1,error:{code:O.code??"unknown",message:O instanceof Error?O.message:String(O),...M!==void 0?{denialContext:M}:{}}})}}function C(A){if(f&&!k.has(A.subId))try{const O=f.subscribe(A.sub,M=>{try{ui(`subscription '${A.subId}'`,M)}catch($){N({type:"worker-snap",subId:A.subId,value:{__error:{code:$.code??"invalid-argument",message:$ instanceof Error?$.message:String($)}}});return}N({type:"worker-snap",subId:A.subId,value:M})});k.set(A.subId,O)}catch(O){const M=O.denialContext;N({type:"worker-snap",subId:A.subId,value:{__error:{code:O.code??"unknown",message:O instanceof Error?O.message:String(O),...M!==void 0?{denialContext:M}:{}}}})}}function _(){try{const A=new URL(n);A.protocol=A.protocol==="wss:"?"https:":"http:";const O=A.origin;return[`${O}/__pyric/health`,`${O}/health`]}catch{return[]}}function E(){if(!y){if(l){S({kind:"disconnected",reason:"replaced by a newer sandbox peer"});return}g=0,w=0,S({kind:"standby"}),R()}}function R(){if(y)return;const A=d*(1+Math.random()*Tp);b=setTimeout(()=>{b=null,V()},A)}async function V(){if(y)return;let A=null;for(const O of _())try{const M=await p(O);if(!M.ok)continue;const $=await M.json();if(typeof $.sandboxConnected=="boolean"){A=!$.sandboxConnected;break}}catch{}if(!y){if(A===!0){P();return}if(A===!1){w=0,R();return}if(w+=1,w>=Bp){G("standby health poll unreachable");return}R()}}function G(A){if(y)return;if(l){S({kind:"disconnected",reason:A});return}g+=1;const O=Math.min(a*2**(g-1),c);S({kind:"reconnecting",attempt:g,delayMs:O}),v=setTimeout(()=>{v=null,P()},O)}return P(),{disconnect(){if(y=!0,j(),v&&(clearTimeout(v),v=null),b&&(clearTimeout(b),b=null),m){try{m.close()}catch{}m=null}S({kind:"disconnected",reason:"client closed"})},state(){return x}}}function Fp(e){if(e)return e;if(typeof window<"u"){const t=window.__PYRIC_BRIDGE_URL__;if(t)return t;const n=window.location.hostname||"localhost";return`${window.location.protocol==="https:"?"wss:":"ws:"}//${n}:${ci}${li}`}return`ws://localhost:${ci}${li}`}function Vp(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`sb-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function qp(e,t){try{const n=new URL(e,t.href),r=new URL(t.href),s=t.protocol==="https:"?"wss:":"ws:",i=r.port.length>0,a=n.port.length>0,l=i&&a?`${r.hostname}:${n.port}`:r.host;return`${s}//${l}${n.pathname}`}catch{return e}}function Wp(e,t){return{url:t,dispatcher:(n,r,s)=>of(e,r,s),workerRelay:{op:n=>cf(e,n),subscribe:(n,r)=>lf(e,n,r)}}}async function zp(e,t={}){const n=t.baseUrl??"",r=t.fetchImpl??(typeof fetch<"u"?fetch:null),s=u=>t.onStateChange?.({kind:"disconnected",reason:u});if(!r)return s("no fetch available"),null;let i;try{const u=await r(`${n}/__pyric/init.json`);if(!u.ok)return s("not served"),null;i=(await u.json()).bridgeUrl??null}catch{return s("not served"),null}if(!i)return s("bridge off"),null;const a=t.locationLike??(typeof window<"u"?window.location:null),c=a?qp(i,a):i,l=Lp(null,{...Wp(e,c),...t.onStateChange?{onStateChange:t.onStateChange}:{},...t.initialReconnectDelayMs!==void 0?{initialReconnectDelayMs:t.initialReconnectDelayMs}:{},...t.maxReconnectDelayMs!==void 0?{maxReconnectDelayMs:t.maxReconnectDelayMs}:{}});return console.info("[pyric studio] registered as the sandbox bridge peer at",c),l}const Kp={};function Hp(){return!1}function Gp(){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 Jp(e,t={}){if(e==="local"){const n=t.baseUrl??"",r=Hp(),s=t.persistence==="memory"||r?jl():Sd(n),i=t.disableLive?null:op(t.workerUrl),a=i?Gp():null;let c=!1,l=null;return i&&a&&zp(i.db,{baseUrl:n,onStateChange:u=>a.set(u)}).then(u=>{c?u?.disconnect():l=u}),{mode:e,projects:r?Cd():jd(n),persistence:s,...i?{live:i}:{},...a?{bridge:a}:{},dispose(){c=!0,l?.disconnect(),i?.dispose()}}}throw new Error(`createStudioEnvironment(${e}): only 'local' is wired in v1 (T3). 'browser'/'hosted' land in A3.`)}const _o=h.createContext(null),Yp={status:"pending",env:null,error:null};function Qp(e){try{return{status:"ready",env:Jp(e),error:null}}catch(t){return{status:"error",env:null,error:t instanceof Error?t:new Error(String(t))}}}function Xp({mode:e="local",children:t}){const[n,r]=h.useState(null);h.useEffect(()=>{const i=Qp(e);return r({mode:e,state:i}),()=>{i.status==="ready"&&i.env.dispose()}},[e]);const s=n?.mode===e?n.state:Yp;return o.jsx(_o.Provider,{value:s,children:t})}function pe(){const e=h.useContext(_o);if(!e)throw new Error("useEnvironment must be used within an <EnvironmentProvider>");return e}const Zp="pyric-studio:theme",Zt="dark";function em(){return Zt}function tm(){typeof document>"u"||document.documentElement.setAttribute("data-theme","dark")}const nm=h.createContext(null);function rm({children:e}){const[t,n]=h.useState(em);h.useEffect(()=>{tm();try{localStorage.setItem(Zp,Zt)}catch{}},[t]);const r="dark",s=h.useCallback(c=>n(Zt),[]),i=h.useCallback(()=>n(Zt),[]),a=h.useMemo(()=>({choice:t,resolvedTheme:r,setChoice:s,cycleChoice:i}),[t,r,s,i]);return o.jsx(nm.Provider,{value:a,children:e})}function Eo(){const e=typeof import.meta<"u"&&"/__pyric/ui/"||"/";return e.endsWith("/")?e:`${e}/`}function sm(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 as(e,t="",n=Eo()){let r=e;const s=n.replace(/\/$/,"");n!=="/"&&(e===s||e.startsWith(n))&&(r=e.slice(s.length));const i=r.split("/").filter(Boolean).map(l=>decodeURIComponent(l)),[a="",...c]=i;return{tab:a,rest:c,query:sm(t)}}function im(e,t=Eo()){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 Cr="pyric:studio:navigated",am={tab:"",rest:[],query:{}};function Co(){return typeof window<"u"?window.location.pathname+window.location.search:""}function be(){return typeof window>"u"?am:as(window.location.pathname,window.location.search)}function om(e){return e.tab==="home"?{...e,tab:""}:e}function Rn(e){return im(om(e))}function No(){typeof window<"u"&&window.dispatchEvent(new Event(Cr))}function le(e){if(typeof window>"u")return;const t=Rn(e);Co()!==t&&(window.history.pushState(null,"",t),No())}function dn(e){typeof window>"u"||(window.history.replaceState(null,"",Rn(e)),No())}function Tt(e){return typeof window>"u"?()=>{}:(window.addEventListener("popstate",e),window.addEventListener(Cr,e),()=>{window.removeEventListener("popstate",e),window.removeEventListener(Cr,e)})}function cm(e,t){const n=h.useCallback(i=>e.includes(i)?i:t,[e,t]),r=h.useSyncExternalStore(Tt,()=>n(be().tab),()=>t);h.useEffect(()=>{const i=typeof window<"u"?window.location.hash:"";if(i.length>1){const c=i.slice(1),l=c.indexOf("?"),u=as(`/${l===-1?c:c.slice(0,l)}`,l===-1?"":c.slice(l),"/");if(e.includes(u.tab)){dn(u);return}}const a=be();a.tab!==""&&!e.includes(a.tab)&&dn({tab:n(a.tab)})},[n]);const s=h.useCallback(i=>{const a=n(i);a!==r&&le({tab:a})},[n,r]);return[r,s]}let Nr=null;function lm(e){Nr=e}function um(){return Nr?(Nr(),!0):!1}function dm(e){return(e.metaKey||e.ctrlKey)&&!e.altKey&&!e.shiftKey&&(e.key==="k"||e.key==="K")}const fm=[{id:"home",label:"Home",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 hm({assuranceEnabled:e=!1}={}){return fm.filter(t=>t.id!=="assurance"||e)}const Ke=hm({assuranceEnabled:!1}),pm=Ke.map(e=>e.id);function mm(e){return Ke.find(t=>t.id===e)??Ke[0]}function ym(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 bm=7;function gm(e,t){const n=e.trim();if(!n)return[];const r=t.filter(p=>p.id!=="settings"),s=[],i=[],a=[],[c="",...l]=n.split(/\s+/),u=l.join(" ");for(const p of r){const f={id:`tab:${p.id}`,label:`Go to ${p.label}`,hint:p.description,target:{tab:p.id}},m=p.label.toLowerCase();if(m.startsWith(n.toLowerCase())?s.push(f):ym(n,p.label)&&i.push(f),u&&(m===c.toLowerCase()||m.startsWith(c.toLowerCase()))){const y=u.split("/").filter(Boolean);p.id==="firestore"||p.id==="storage"?a.push({id:`deep:${p.id}:${u}`,label:`Open /${y.join("/")} in ${p.label}`,hint:p.id==="firestore"?"Firestore path":"Storage object path",target:{tab:p.id,rest:y}}):p.id==="auth"?a.push({id:`deep:auth:${u}`,label:`Open user ${u} in Auth`,hint:"Auth uid",target:{tab:"auth",rest:[u]}}):p.id==="traffic"&&a.push({id:`deep:traffic:${u}`,label:`Open ${u} in the rules inspector`,hint:"Traffic event id",target:{tab:"traffic",query:{inspect:u}}})}}const d=n.match(/^gs:\/\/[^/]+\/(.+)$/);if(d){const p=d[1].split("/").filter(Boolean);a.unshift({id:`deep:storage:${d[1]}`,label:`Open ${d[1]} in Storage`,hint:"Storage object path",target:{tab:"storage",rest:p}})}else if(n.includes("/")&&!n.includes(" ")){const p=n.split("/").filter(Boolean);p.length&&a.push({id:`deep:firestore:${n}`,label:`Open /${p.join("/")} in Firestore`,hint:"Firestore path",target:{tab:"firestore",rest:p}})}return[...s,...a,...i].slice(0,bm)}function Rr(e){return`${e.kind}:${e.target.tab}:${(e.target.rest??[]).join("/")}`}const Ar={docsPerCollection:50,collectionsScanned:20,users:100,objects:200,storageListCalls:20,subcollections:30,subcollectionRpcCalls:40};async function vm(e,t,{maxObjects:n,maxListCalls:r}){const s=[],i=[e];let a=0;for(;i.length&&s.length<n&&a<r;){a++;const c=await t(i.shift());for(const l of c.items){if(s.length>=n)break;s.push(l.fullPath)}i.push(...c.prefixes)}return s}async function wm(e,t,n,{maxSubcollections:r,maxRpcCalls:s,docsPerCollection:i}){const a=[],c=[],l=[...e];let u=0;for(;l.length&&a.length<r&&u<s;){const d=l.shift();u++;let p=[];try{p=await t(d)}catch{continue}for(const f of p){if(a.length>=r)break;const m=`${d}/${f}`;a.push(m);try{const y=await n(m,i);for(const g of y.slice(0,i))c.push(g),l.push(g)}catch{}}}return{subcollections:a,documents:c}}const xm=5;function fn(e,t){const n=e.toLowerCase(),r=t.toLowerCase();if(!n||!r)return 0;if(r===n)return 1e3;if(r.startsWith(n))return 900-Math.min(r.length-n.length,100);const s=r.indexOf(n);if(s!==-1)return 700-Math.min(s,100);let i=0,a=-1,c=-1;for(let u=0;u<r.length&&i<n.length;u++)r[u]===n[i]&&(a===-1&&(a=u),c=u,i++);if(i!==n.length)return 0;const l=c-a+1;return Math.max(1,400-(l-n.length)*10-Math.min(a,50))}const jm={collection:"Firestore collections",document:"Firestore documents",subcollection:"Firestore subcollections",user:"Auth users",object:"Storage objects","rtdb-key":"RTDB keys"},km=["collection","document","subcollection","user","object","rtdb-key"];function Sm(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 Ro(e){return e.endsWith("/")?{base:e.slice(0,-1),trailing:!0}:{base:e,trailing:!1}}function _m(e,t){const{base:n,trailing:r}=Ro(e);if(!n)return 0;const s=n.split("/"),i=t.split("/");if(s.length>i.length)return 0;const a=s.length-1;for(let c=0;c<a;c++)if(s[c].toLowerCase()!==i[c].toLowerCase())return 0;return r?s[a].toLowerCase()===i[a].toLowerCase()?850:0:fn(s[a],i[a])}function Em(e,t){const{base:n,trailing:r}=Ro(e);if(!n||n.includes("/"))return 0;const s=t.split("/").pop()??t;return r?s.toLowerCase()===n.toLowerCase()?850:0:fn(n,s)}function mi(e,t,n,r=xm){const s=e.trim();if(!s)return[];const i=[],a=gm(e,t);a.length&&i.push({kind:"navigate",title:"Go to",results:a});for(const c of km){const l=c==="document"||c==="subcollection",u=c==="collection"||c==="subcollection",d=new Map;for(const f of n)f.kind===c&&d.set(Rr(f),f);const p=[...d.values()].map(f=>({entry:f,score:Math.max(fn(s,f.label),f.alt?fn(s,f.alt):0,l?_m(s,f.label):0,u?Em(s,f.label):0)})).filter(f=>f.score>0).sort((f,m)=>m.score-f.score||f.entry.label.localeCompare(m.entry.label)).slice(0,r);p.length&&i.push({kind:c,title:jm[c],results:p.map(({entry:f})=>({id:Rr(f),label:f.label,hint:Sm(f),target:f.target}))})}return i}function yi(e){return e.flatMap(t=>t.results)}function Cm(e){return{kind:"collection",label:e,target:{tab:"firestore",rest:[e]}}}function bi(e){return{kind:"document",label:e,target:{tab:"firestore",rest:e.split("/").filter(Boolean)}}}function Nm(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 Rm(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 Am(e){return{kind:"object",label:e,target:{tab:"storage",rest:e.split("/").filter(Boolean)}}}function Im(e){return{kind:"rtdb-key",label:e,target:{tab:"rtdb",rest:[e]}}}async function Dm(e,t={},n){const r={...Ar,...t},s=[],i=d=>{d.length&&(s.push(...d),n?.(d))},a=(async()=>{let d=[];try{d=await e.listRootCollections?.()??[]}catch{d=[]}d.length&&i(d.map(Cm));const p=[];if(e.listDocumentPaths)for(const f of d.slice(0,r.collectionsScanned))try{const y=(await e.listDocumentPaths(f,r.docsPerCollection)).slice(0,r.docsPerCollection);p.push(...y),i(y.map(bi))}catch{}if(e.listSubcollections&&e.listDocumentPaths)try{const{subcollections:f,documents:m}=await wm(p,e.listSubcollections,e.listDocumentPaths,{maxSubcollections:r.subcollections,maxRpcCalls:r.subcollectionRpcCalls,docsPerCollection:r.docsPerCollection});i(f.map(Nm)),i(m.map(bi))}catch{}})(),c=(async()=>{if(e.listUsers)try{const d=await e.listUsers(r.users);i(d.slice(0,r.users).map(Rm))}catch{}})(),l=(async()=>{if(e.listStorageObjectPaths)try{const d=await e.listStorageObjectPaths(r.objects);i(d.slice(0,r.objects).map(Am))}catch{}})(),u=(async()=>{if(e.listRtdbTopLevelKeys)try{i((await e.listRtdbTopLevelKeys()).map(Im))}catch{}})();return await Promise.allSettled([a,c,l,u]),s}const Ao=Symbol("pyric/auth/target"),Pm=Symbol("pyric.user.internal");function q(e,t){return new dt(e,`Firebase: ${t} (${e}).`)}const Io={PASSWORD:"password"},Yn={EMAIL_LINK:"emailLink",EMAIL_PASSWORD:"password"};class An{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"?$m(t):t;if(!n)return null;const r=n.providerId,s=n.signInMethod;if(typeof r!="string"||typeof s!="string")return null;if(r===Io.PASSWORD){const i=typeof n.email=="string"?n.email:"",a=typeof n.password=="string"?n.password:"";return new Om(i,a,s)}return new An(r,s)}}function $m(e){try{const t=JSON.parse(e);return typeof t=="object"&&t!==null?t:null}catch{return null}}class Om extends An{email;secret;constructor(t,n,r=Yn.EMAIL_PASSWORD){super(Io.PASSWORD,r),this.email=t,Object.defineProperty(this,"secret",{value:n,enumerable:!1,writable:!1})}get password(){return this.signInMethod===Yn.EMAIL_PASSWORD?this.secret:null}get emailLink(){return this.signInMethod===Yn.EMAIL_LINK?this.secret:null}toJSON(){return{providerId:this.providerId,signInMethod:this.signInMethod,email:this.email,password:this.secret}}}class In extends An{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 os(e,t){return t?new In(e,e):null}class tt{static PROVIDER_ID="google.com";static GOOGLE_SIGN_IN_METHOD="google.com";providerId=tt.PROVIDER_ID;addScope(t){return this}setCustomParameters(t){return this}static credentialFromResult(t){return os(tt.PROVIDER_ID,t)}static credentialFromError(t){return null}static credential(t,n){return new In(tt.PROVIDER_ID,tt.GOOGLE_SIGN_IN_METHOD,{idToken:t??void 0,accessToken:n??void 0})}}class nt{static PROVIDER_ID="facebook.com";static FACEBOOK_SIGN_IN_METHOD="facebook.com";providerId=nt.PROVIDER_ID;addScope(t){return this}setCustomParameters(t){return this}static credentialFromResult(t){return os(nt.PROVIDER_ID,t)}static credentialFromError(t){return null}static credential(t){return new In(nt.PROVIDER_ID,nt.FACEBOOK_SIGN_IN_METHOD,{accessToken:t})}}class rt{static PROVIDER_ID="github.com";static GITHUB_SIGN_IN_METHOD="github.com";providerId=rt.PROVIDER_ID;addScope(t){return this}setCustomParameters(t){return this}static credentialFromResult(t){return os(rt.PROVIDER_ID,t)}static credentialFromError(t){return null}static credential(t){return new In(rt.PROVIDER_ID,rt.GITHUB_SIGN_IN_METHOD,{accessToken:t})}}const Do=[tt.PROVIDER_ID,"apple.com",nt.PROVIDER_ID,rt.PROVIDER_ID,"twitter.com","microsoft.com","yahoo.com"];function cs(e,t=!1){const n=e[Ao];if(!n)throw new TypeError("pyric/auth: unrecognized Auth handle — was it produced by getAuth(...)?");return t||n.assertAlive?.(),n}class Mm{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 Um(e,t,n){const r=JSON.stringify(t);return`sandbox-id-token-${e}-${String(n)}:${r}`}function Te(e){if(typeof e!="string"||e.length===0)throw q("auth/invalid-email","Error");const t=e.indexOf("@");if(t<=0||t===e.length-1)throw q("auth/invalid-email","Error")}function xt(e){if(typeof e!="string"||e.length<6)throw q("auth/weak-password","Password should be at least 6 characters")}function Po(){return{usersByEmail:new Map,usersByUid:new Map,userDbSubscribers:new Set,providerConfig:new Map([["password",!0],["anonymous",!0]]),providerConfigSubscribers:new Set,counters:{nextAdminUserId:1,nextAnonymousId:1}}}const Tm="__pyric_no_password__";class $o{usersByEmail;usersByUid;authStateSubs=[];idTokenSubs=[];userDbSubs;beforeStateSubs=[];sharedCounters;flow=new Mm;sandbox;session;cachedUser=null;lastNotifiedUid=null;applyingTransition=!1;tokenCache=new Map;nextTokenSerial=1;persistenceMode="LOCAL";signInProviderByUid=new Map;providerConfig;providerConfigSubs;providerEnforcementDelegated=!1;constructor(t,n=t,r=Po(),s){this.sandbox=t,this.session=n,this.usersByEmail=r.usersByEmail,this.usersByUid=r.usersByUid,this.userDbSubs=r.userDbSubscribers,this.providerConfig=r.providerConfig,this.providerConfigSubs=r.providerConfigSubscribers,this.sharedCounters=r.counters,this.cachedUser=this.buildUserFromState(n.currentUser),this.lastNotifiedUid=this.cachedUser?.uid??null;const i=n.onCurrentUserChanged(a=>{if(this.applyingTransition)return;const c=a===null?null:a.uid,l=this.cachedUser?.uid??null;c!==l&&(this.cachedUser=this.buildUserFromState(a)),this.notifyAuthListeners()});s?.(()=>{i(),this.authStateSubs.length=0,this.idTokenSubs.length=0,this.beforeStateSubs.length=0})}getCurrentUser(){return this.cachedUser}subscribe(t,n){const r=t==="auth-state"?this.authStateSubs:this.idTokenSubs,s={observer:n,hasFired:!1,lastValue:null};return r.push(s),queueMicrotask(()=>{r.includes(s)&&(s.hasFired&&s.lastValue===this.cachedUser||this.deliverOne(s,this.cachedUser))}),()=>{const i=r.indexOf(s);i!==-1&&r.splice(i,1)}}fanOut(t="both"){const n=this.cachedUser;if(t==="both"||t==="auth-state")for(const r of[...this.authStateSubs])this.deliverOne(r,n);if(t==="both"||t==="id-token")for(const r of[...this.idTokenSubs])this.deliverOne(r,n)}notifyAuthListeners(){this.fanOut("id-token");const t=this.cachedUser?.uid??null;this.lastNotifiedUid!==t&&(this.lastNotifiedUid=t,this.fanOut("auth-state"))}deliverOne(t,n){t.hasFired=!0,t.lastValue=n;const r=t.observer;try{typeof r=="function"?r(n):r.next&&r.next(n)}catch{}}makeStored(t){return{email:null,password:null,displayName:null,phoneNumber:null,photoUrl:null,customClaims:{},isAnonymous:!1,providerUserInfo:[],disabled:!1,emailVerified:!1,createdAt:new Date().toISOString(),lastLoginAt:null,...t}}notifyUsersChanged(){for(const t of[...this.userDbSubs])try{t()}catch{}}emitAuthEvent(t,n={}){try{Re(this.sandbox,vn({service:"auth",op:t,path:n.path,auth:n.auth??this.session.currentUser,before:n.before,after:n.after,detail:n.detail}),{service:"auth"})}catch{}}subscribeUsers(t){return this.userDbSubs.add(t),()=>{this.userDbSubs.delete(t)}}isProviderEnabled(t){return this.providerConfig.get(t)??!0}listProviderConfig(){return[...this.providerConfig.entries()].map(([t,n])=>({providerId:t,enabled:n}))}setProviderConfig(t,n){const r=this.providerConfig.get(t)??!0;r!==n&&(this.providerConfig.set(t,n),this.notifyProviderConfigChanged(),this.emitAuthEvent("provider_config_update",{path:t,auth:null,before:{providerId:t,enabled:r},after:{providerId:t,enabled:n}}))}notifyProviderConfigChanged(){for(const t of[...this.providerConfigSubs])try{t()}catch{}}subscribeProviderConfig(t){return this.providerConfigSubs.add(t),()=>{this.providerConfigSubs.delete(t)}}setProviderEnforcementDelegated(t){this.providerEnforcementDelegated=t}assertProviderEnabled(t){if(!this.providerEnforcementDelegated&&!this.isProviderEnabled(t))throw q("auth/operation-not-allowed",`${t} sign-in is disabled for this sandbox project. Enable it with sandbox.setAuthProviderConfig(auth, '${t}', true).`)}exportProviderConfig(){return Object.fromEntries(this.providerConfig)}restoreProviderConfig(t){if(this.providerConfig.clear(),t&&typeof t=="object")for(const[n,r]of Object.entries(t))typeof r=="boolean"&&this.providerConfig.set(n,r);else this.providerConfig.set("password",!0),this.providerConfig.set("anonymous",!0);this.notifyProviderConfigChanged()}getPersistenceMode(){return this.persistenceMode}setPersistenceMode(t){this.persistenceMode!==t&&(this.persistenceMode=t,this.notifySessionChanged())}sessionChangeSubs=new Set;notifySessionChanged(){for(const t of[...this.sessionChangeSubs])try{t()}catch{}}subscribeSession(t){return this.sessionChangeSubs.add(t),()=>{this.sessionChangeSubs.delete(t)}}seedUsers(t){for(const n of t){const r=this.usersByUid.get(n.uid);r?.email&&r.email.toLowerCase()!==n.email.toLowerCase()&&this.usersByEmail.delete(r.email.toLowerCase());const s=this.makeStored({uid:n.uid,email:n.email,password:n.password,displayName:n.displayName??null,customClaims:n.customClaims??{},providerUserInfo:[{providerId:n.providerId??"password"}]});this.usersByEmail.set(n.email.toLowerCase(),s),this.usersByUid.set(n.uid,s)}t.length>0&&this.notifyUsersChanged()}exportUsers(){const t=[];for(const n of this.usersByUid.values()){if(n.email===null)continue;const r={uid:n.uid,email:n.email,password:n.password??Tm,providerId:n.providerUserInfo[0]?.providerId??"password"};n.displayName!==null&&(r.displayName=n.displayName),Object.keys(n.customClaims).length>0&&(r.customClaims=n.customClaims),t.push(r)}return t}restoreSession(t){const n=this.usersByUid.get(t);if(!n)throw q("auth/user-not-found",`restoreSession: no identity with uid ${t}.`);if(n.disabled)throw q("auth/user-disabled",`restoreSession: user ${t} is disabled.`);const r=n.isAnonymous?"anonymous":n.providerUserInfo[0]?.providerId??"password",s=this.buildUserFromStored(n);return this.setCurrentUser(s,r),s}findByEmail(t){return this.usersByEmail.get(t.toLowerCase())}findByUid(t){return this.usersByUid.get(t)}mintActionCode(t){return this.flow.mintActionCode(t)}stageActionCode(t,n){this.flow.stageActionCode(t,n)}peekActionCode(t){return this.flow.peekActionCode(t)}consumeActionCode(t){return this.flow.consumeActionCode(t)}deliverMail(t){this.flow.deliverMail(t)}takeMail(t){return this.flow.takeMail(t)}listMail(){return this.flow.listMail()}setMailResolver(t){this.flow.setMailResolver(t)}setEmailVerified(t,n){const r=this.requireByEmail(t);return r.emailVerified!==n&&(r.emailVerified=n,this.notifyUsersChanged(),this.emitAuthEvent("user_update",{path:r.uid,after:this.toRecord(r),detail:{emailVerified:n}})),r}setPasswordByEmail(t,n){xt(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){Te(n);const r=this.requireByEmail(t),s=n.toLowerCase(),i=this.usersByEmail.get(s);if(i&&i.uid!==r.uid)throw q("auth/email-already-in-use",`An account already exists for ${n}.`);return r.email&&this.usersByEmail.delete(r.email.toLowerCase()),r.email=n,r.emailVerified=!0,this.usersByEmail.set(s,r),this.notifyUsersChanged(),this.emitAuthEvent("user_update",{path:r.uid,after:this.toRecord(r),detail:{emailChanged:n}}),r}upsertEmailLinkUser(t){Te(t);const n=t.toLowerCase(),r=this.usersByEmail.get(n);if(r)return r.providerUserInfo.some(a=>a.providerId==="password")||r.providerUserInfo.push({providerId:"password"}),r.emailVerified=!0,this.notifyUsersChanged(),{stored:r,isNewUser:!1};const s=`email-${n}-${this.usersByEmail.size+1}`,i=this.makeStored({uid:s,email:t,providerUserInfo:[{providerId:"password"}]});return i.emailVerified=!0,this.usersByEmail.set(n,i),this.usersByUid.set(s,i),this.notifyUsersChanged(),this.emitAuthEvent("user_create",{path:s,after:this.toRecord(i),detail:{emailLink:!0}}),{stored:i,isNewUser:!0}}linkProvider(t,n,r){const s=this.usersByUid.get(t);if(!s)throw q("auth/user-not-found",`linkWithCredential: no identity with uid ${t}.`);if(s.providerUserInfo.some(a=>a.providerId===n))throw q("auth/provider-already-linked",`User can only be linked to one identity for the given provider (${n}).`);const i=r?.email;if(i){Te(i);const a=i.toLowerCase(),c=this.usersByEmail.get(a);if(c&&c.uid!==t)throw q("auth/email-already-in-use",`An account already exists for ${i}.`);r.password!==void 0&&r.password!==null&&(xt(r.password),s.password=r.password),s.email&&s.email.toLowerCase()!==a&&this.usersByEmail.delete(s.email.toLowerCase()),s.email=i,this.usersByEmail.set(a,s),r.emailVerified!==void 0&&(s.emailVerified=r.emailVerified)}return s.providerUserInfo.push({providerId:n}),s.isAnonymous&&(s.isAnonymous=!1),this.notifyUsersChanged(),this.emitAuthEvent("user_update",{path:t,after:this.toRecord(s),detail:{linked:n}}),s}unlinkProvider(t,n){const r=this.usersByUid.get(t);if(!r)throw q("auth/user-not-found",`unlink: no identity with uid ${t}.`);const s=r.providerUserInfo.findIndex(i=>i.providerId===n);if(s<0)throw q("auth/no-such-provider",`User was not linked to an account with the given provider (${n}).`);return r.providerUserInfo.splice(s,1),n==="password"&&(r.password=null),this.notifyUsersChanged(),this.emitAuthEvent("user_update",{path:t,after:this.toRecord(r),detail:{unlinked:n}}),r}requireByEmail(t){const n=this.usersByEmail.get(t.toLowerCase());if(!n)throw q("auth/user-not-found",`No user found for ${t}.`);return n}createEmailPasswordUser(t,n){Te(t),xt(n);const r=t.toLowerCase();if(this.usersByEmail.has(r))throw q("auth/email-already-in-use",`An account already exists for ${t}.`);const s=`email-${r}-${this.usersByEmail.size+1}`,i=this.makeStored({uid:s,email:t,password:n,providerUserInfo:[{providerId:"password"}]});return this.usersByEmail.set(r,i),this.usersByUid.set(s,i),this.notifyUsersChanged(),this.emitAuthEvent("user_create",{path:s,after:this.toRecord(i)}),i}beforeAuthStateChanged(t,n){const r={callback:t,onAbort:n,active:!0};return this.beforeStateSubs.push(r),()=>{r.active=!1}}async runBeforeStateChange(t){if(t===this.cachedUser)return;const n=[];try{for(const r of this.beforeStateSubs)r.active&&(await r.callback(t),r.onAbort&&n.push(r.onAbort))}catch(r){n.reverse();for(const i of n)try{i()}catch{}const s=r instanceof Error?r.message:String(r);throw q("auth/login-blocked",s)}}transitionCurrentUser(t,n){return!this.beforeStateSubs.some(s=>s.active)||t===this.cachedUser?(this.setCurrentUser(t,n),Promise.resolve()):this.runBeforeStateChange(t).then(()=>{this.setCurrentUser(t,n)})}setCurrentUser(t,n){if(t===null){const a=this.cachedUser;this.cachedUser=null,this.applyingTransition=!0;try{this.session.currentUser=null}finally{this.applyingTransition=!1}a&&(this.tokenCache.delete(a.uid),this.notifyAuthListeners(),this.notifySessionChanged(),this.emitAuthEvent("sign_out",{path:a.uid,auth:{uid:a.uid}}));return}n!==void 0&&this.signInProviderByUid.set(t.uid,n);const r=this.usersByUid.get(t.uid),s=r?.customClaims??{};n!==void 0&&r&&(r.lastLoginAt=new Date().toISOString(),this.notifyUsersChanged()),this.cachedUser=t,this.tokenCache.set(t.uid,this.mintToken(t.uid,s));const i={uid:t.uid,token:s};this.applyingTransition=!0;try{this.session.currentUser=i}finally{this.applyingTransition=!1}this.notifyAuthListeners(),this.notifySessionChanged(),n!==void 0&&this.emitAuthEvent("sign_in",{path:t.uid,auth:i,after:{uid:t.uid,isAnonymous:t.isAnonymous,email:t.email},detail:{providerId:n??"anonymous"}})}setMockResult(t,n){this.flow.setMockResult(t,n)}consumeMockResult(t){return this.flow.consumeMockResult(t)}setResolver(t){this.flow.setResolver(t)}getResolver(){return this.flow.getResolver()}setRedirectResult(t){this.flow.setRedirectResult(t)}takeRedirectResult(){return this.flow.takeRedirectResult()}recordProviderSignIn(t,n){let r=!1,s=this.usersByUid.get(t.uid);s||(s=this.makeStored({uid:t.uid,email:t.email,displayName:t.displayName,isAnonymous:t.isAnonymous}),this.usersByUid.set(t.uid,s),t.email&&this.usersByEmail.set(t.email.toLowerCase(),s),r=!0),s.providerUserInfo.some(i=>i.providerId===n)||(s.providerUserInfo.push({providerId:n}),r=!0),r&&this.notifyUsersChanged()}createSignInCredential(t){const{providerId:n}=t;let r;if("uid"in t){const s=this.usersByUid.get(t.uid);if(!s)throw q("auth/user-not-found",`createSignInCredential: no identity with uid ${t.uid}. Use the {spec} shape to create one.`);r=s}else{const{spec:s}=t,i=this.usersByEmail.get(s.email.toLowerCase());i?r=i:(r=this.makeStored({uid:s.uid??Bm(),email:s.email,displayName:s.displayName??null,customClaims:s.customClaims??{}}),this.usersByUid.set(r.uid,r),this.usersByEmail.set(s.email.toLowerCase(),r),this.notifyUsersChanged())}return r.providerUserInfo.some(s=>s.providerId===n)||(r.providerUserInfo.push({providerId:n}),this.notifyUsersChanged()),{user:this.buildUserFromStored(r),providerId:n,operationType:"signIn"}}listIdentities(){return[...this.usersByUid.values()].map(t=>({uid:t.uid,email:t.email,displayName:t.displayName,providerId:t.isAnonymous?"anonymous":t.providerUserInfo[0]?.providerId??"password",providerUserInfo:[...t.providerUserInfo],isAnonymous:t.isAnonymous,customClaims:t.customClaims}))}toRecord(t){return{uid:t.uid,email:t.email,displayName:t.displayName,phoneNumber:t.phoneNumber,photoUrl:t.photoUrl,customClaims:{...t.customClaims},providerUserInfo:t.providerUserInfo.map(n=>({...n})),isAnonymous:t.isAnonymous,disabled:t.disabled,emailVerified:t.emailVerified,createdAt:t.createdAt,lastLoginAt:t.lastLoginAt}}listUsers(){return[...this.usersByUid.values()].map(t=>this.toRecord(t))}sanitizeLinkedProviders(t,n,r){const s=new Set,i=[];for(const a of t){const c=a?.providerId?.trim();if(!c)throw q("auth/argument-error",`${r}: providerUserInfo entries need a non-empty providerId.`);c==="password"||c==="anonymous"||s.has(c)||(s.add(c),i.push({providerId:c}))}return n&&i.unshift({providerId:"password"}),i}createUser(t){const n=t.uid??`user-${this.sharedCounters.nextAdminUserId++}`;if(this.usersByUid.has(n))throw q("auth/uid-already-exists",`createUser: a user with uid ${n} already exists.`);if(t.email!==void 0&&(Te(t.email),this.usersByEmail.has(t.email.toLowerCase())))throw q("auth/email-already-in-use",`An account already exists for ${t.email}.`);if(t.password!==void 0&&(xt(t.password),t.email===void 0))throw q("auth/invalid-email","createUser: a password requires an email.");const r=this.makeStored({uid:n,email:t.email??null,password:t.password??null,displayName:t.displayName??null,phoneNumber:t.phoneNumber??null,photoUrl:t.photoUrl??null,customClaims:t.customClaims??{},disabled:t.disabled??!1,emailVerified:t.emailVerified??!1,providerUserInfo:this.sanitizeLinkedProviders(t.providerUserInfo??[],t.password!==void 0,"createUser")});this.usersByUid.set(n,r),r.email&&this.usersByEmail.set(r.email.toLowerCase(),r),this.notifyUsersChanged();const s=this.toRecord(r);return this.emitAuthEvent("user_create",{path:n,auth:null,after:s}),s}updateUser(t,n){const r=this.usersByUid.get(t);if(!r)throw q("auth/user-not-found",`No user found for uid ${t}.`);const s=this.toRecord(r);if(n.email!==void 0){Te(n.email);const a=n.email.toLowerCase(),c=this.usersByEmail.get(a);if(c&&c!==r)throw q("auth/email-already-in-use",`An account already exists for ${n.email}.`);r.email&&this.usersByEmail.delete(r.email.toLowerCase()),r.email=n.email,this.usersByEmail.set(a,r)}n.password!==void 0&&(xt(n.password),r.password=n.password,r.providerUserInfo.some(a=>a.providerId==="password")||r.providerUserInfo.push({providerId:"password"})),n.providerUserInfo!==void 0&&(r.providerUserInfo=this.sanitizeLinkedProviders(n.providerUserInfo,r.password!==null,"updateUser")),n.displayName!==void 0&&(r.displayName=n.displayName),n.customClaims!==void 0&&(r.customClaims={...n.customClaims}),n.disabled!==void 0&&(r.disabled=n.disabled),n.emailVerified!==void 0&&(r.emailVerified=n.emailVerified),this.notifyUsersChanged();const i=this.toRecord(r);return this.emitAuthEvent("user_update",{path:t,auth:null,before:s,after:i}),i}deleteUser(t){const n=this.usersByUid.get(t);if(!n)throw q("auth/user-not-found",`No user found for uid ${t}.`);const r=this.toRecord(n);this.usersByUid.delete(t),n.email&&this.usersByEmail.get(n.email.toLowerCase())===n&&this.usersByEmail.delete(n.email.toLowerCase()),this.tokenCache.delete(t),this.signInProviderByUid.delete(t),this.notifyUsersChanged(),this.emitAuthEvent("user_delete",{path:t,auth:null,before:r})}clearUsers(){if(this.usersByUid.size===0&&this.usersByEmail.size===0)return;const t=this.usersByUid.size;this.usersByUid.clear(),this.usersByEmail.clear(),this.notifyUsersChanged(),this.emitAuthEvent("users_clear",{path:"*",auth:null,detail:{count:t}})}assertSignInAllowed(t){if(this.usersByUid.get(t)?.disabled)throw q("auth/user-disabled","The user account has been disabled by an administrator.")}buildUserFromStored(t){return this.makeUser({uid:t.uid,email:t.email,displayName:t.displayName,isAnonymous:t.isAnonymous,claims:t.customClaims,photoURL:t.photoUrl,emailVerified:t.emailVerified,phoneNumber:t.phoneNumber,providers:t.providerUserInfo})}mintAnonymousUser(){const t=`anonymous-${this.sharedCounters.nextAnonymousId++}`,n=this.makeStored({uid:t,isAnonymous:!0});return this.usersByUid.set(t,n),this.notifyUsersChanged(),this.emitAuthEvent("user_create",{path:t,after:this.toRecord(n),detail:{isAnonymous:!0}}),this.makeUser({uid:t,email:null,displayName:null,isAnonymous:!0,claims:{}})}mintDetachedSession(t){switch(t.kind){case"anonymous":return this.assertProviderEnabled("anonymous"),this.establishDetachedSession(this.mintAnonymousUser(),"anonymous");case"password":return this.assertProviderEnabled("password"),this.establishDetachedSession(this.buildUserFromStored(this.validatePassword(t.email,t.password)),"password");case"createPassword":return this.assertProviderEnabled("password"),this.establishDetachedSession(this.buildUserFromStored(this.createEmailPasswordUser(t.email,t.password)),"password");case"uid":{const n=this.usersByUid.get(t.uid);if(!n)throw q("auth/user-not-found",`mintSession: no identity with uid ${t.uid}.`);if(n.disabled)throw q("auth/user-disabled",`mintSession: user ${t.uid} is disabled.`);const r=n.isAnonymous?"anonymous":n.providerUserInfo[0]?.providerId??"password";return this.establishDetachedSession(this.buildUserFromStored(n),r)}}}establishDetachedSession(t,n){this.signInProviderByUid.set(t.uid,n);const r=this.usersByUid.get(t.uid),s=r?.customClaims??{};r&&(r.lastLoginAt=new Date().toISOString(),this.notifyUsersChanged()),this.tokenCache.set(t.uid,this.mintToken(t.uid,s));const i={uid:t.uid,token:s};return this.emitAuthEvent("sign_in",{path:t.uid,auth:i,after:{uid:t.uid,isAnonymous:t.isAnonymous,email:t.email},detail:{providerId:n,session:"connection"}}),{user:t,state:i}}buildUserFromState(t){if(t===null)return null;const n=this.usersByUid.get(t.uid);return n?this.buildUserFromStored({...n,customClaims:t.token??n.customClaims}):this.makeUser({uid:t.uid,email:null,displayName:null,isAnonymous:t.uid.startsWith("anonymous-"),claims:t.token??{}})}mintToken(t,n){const r=new Date,s=new Date(r.getTime()+100*365*24*60*60*1e3),i=this.nextTokenSerial++,a=Um(t,n,i),c=this.signInProviderByUid.get(t)??null,l={sub:t,aud:"pyric-sandbox",iss:"https://sandbox.pyric.dev",auth_time:Math.floor(r.getTime()/1e3),iat:Math.floor(r.getTime()/1e3),exp:Math.floor(s.getTime()/1e3),...n,firebase:{sign_in_provider:c}},u={token:a,claims:l,expirationTime:s.toISOString(),issuedAtTime:r.toISOString(),authTime:r.toISOString(),signInProvider:c};return{token:a,result:u}}getIdTokenFor(t,n,r){if(r){const a=this.mintToken(t,n);return this.tokenCache.set(t,a),this.fanOut("id-token"),a.token}const s=this.tokenCache.get(t);if(s)return s.token;const i=this.mintToken(t,n);return this.tokenCache.set(t,i),i.token}getIdTokenResultFor(t,n,r){if(r){const a=this.mintToken(t,n);return this.tokenCache.set(t,a),this.fanOut("id-token"),a.result}const s=this.tokenCache.get(t);if(s)return s.result;const i=this.mintToken(t,n);return this.tokenCache.set(t,i),i.result}makeUser(t){const n=t.photoURL??null,r=t.phoneNumber??null,s=t.emailVerified??!1,i="firebase",a=t.providers??[{providerId:"password"}],c=t.isAnonymous?[]:a.map(u=>({uid:t.uid,displayName:t.displayName,email:t.email,phoneNumber:r,photoURL:n,providerId:u.providerId})),l={uid:t.uid,email:t.email,emailVerified:s,displayName:t.displayName,photoURL:n,phoneNumber:r,isAnonymous:t.isAnonymous,providerId:i,providerData:c,getIdToken:async u=>this.getIdTokenFor(t.uid,this.liveClaims(t.uid,t.claims),u===!0),getIdTokenResult:async u=>this.getIdTokenResultFor(t.uid,this.liveClaims(t.uid,t.claims),u===!0)};return Object.defineProperty(l,Pm,{value:{updateProfile:u=>(this.updateProfileFor(l,u),Promise.resolve()),delete:()=>(this.deleteFor(l),Promise.resolve()),updateEmail:u=>(this.updateEmailFor(l,u),Promise.resolve()),updatePassword:u=>(this.updatePasswordFor(l,u),Promise.resolve()),reload:()=>(this.reloadFor(l),Promise.resolve()),target:this.selfTarget()},enumerable:!1}),l}selfTarget(){return{kind:"sandbox",sandbox:this.sandbox,backend:this}}updateProfileFor(t,n){const r=this.usersByUid.get(t.uid),s=r?this.toRecord(r):void 0;r&&(n.displayName!==void 0&&(r.displayName=n.displayName),n.photoURL!==void 0&&(r.photoUrl=n.photoURL)),this.applyProfileToUser(t,n),this.cachedUser&&this.cachedUser.uid===t.uid&&this.cachedUser!==t&&this.applyProfileToUser(this.cachedUser,n),this.notifyUsersChanged(),this.emitAuthEvent("user_update",{path:t.uid,auth:{uid:t.uid},before:s,after:r?this.toRecord(r):void 0,detail:{displayName:n.displayName,photoURL:n.photoURL}})}applyProfileToUser(t,n){const r=t;n.displayName!==void 0&&(r.displayName=n.displayName),n.photoURL!==void 0&&(r.photoURL=n.photoURL);const s=t.providerData?.[0];s&&(n.displayName!==void 0&&(s.displayName=n.displayName),n.photoURL!==void 0&&(s.photoURL=n.photoURL))}updateProfileByUid(t,n){const r=this.usersByUid.get(t);if(!r)throw q("auth/user-not-found",`updateProfile: no identity with uid ${t}.`);const s=this.toRecord(r);n.displayName!==void 0&&(r.displayName=n.displayName),n.photoURL!==void 0&&(r.photoUrl=n.photoURL),this.cachedUser&&this.cachedUser.uid===t&&this.applyProfileToUser(this.cachedUser,n),this.notifyUsersChanged();const i=this.toRecord(r);return this.emitAuthEvent("user_update",{path:t,auth:{uid:t},before:s,after:i,detail:{displayName:n.displayName,photoURL:n.photoURL}}),i}deleteFor(t){this.usersByUid.has(t.uid)&&this.deleteUser(t.uid),this.cachedUser&&this.cachedUser.uid===t.uid&&this.setCurrentUser(null)}updateEmailFor(t,n){this.updateUser(t.uid,{email:n}),this.applyEmailToUser(t,n),this.cachedUser&&this.cachedUser.uid===t.uid&&this.cachedUser!==t&&this.applyEmailToUser(this.cachedUser,n)}applyEmailToUser(t,n){t.email=n;const r=t.providerData?.[0];r&&(r.email=n)}updatePasswordFor(t,n){this.updateUser(t.uid,{password:n})}reloadFor(t){const n=this.usersByUid.get(t.uid);if(!n)throw q("auth/user-token-expired","The user's credential is no longer valid. The user must sign in again.");this.applyStoredToUser(t,n),this.cachedUser&&this.cachedUser.uid===t.uid&&this.cachedUser!==t&&this.applyStoredToUser(this.cachedUser,n)}applyStoredToUser(t,n){const r=t;r.email=n.email,r.displayName=n.displayName,r.photoURL=n.photoUrl,r.emailVerified=n.emailVerified,r.phoneNumber=n.phoneNumber}liveClaims(t,n){return this.usersByUid.get(t)?.customClaims??n}validatePassword(t,n){if(Te(t),typeof n!="string"||n.length===0)throw q("auth/missing-password","A non-empty password must be provided");const r=this.findByEmail(t);if(!r)throw q("auth/user-not-found",`No user found for ${t}.`);if(r.disabled)throw q("auth/user-disabled","The user account has been disabled by an administrator.");if(r.password!==n)throw q("auth/wrong-password","Invalid password.");return r}}function Bm(){return`provider-${globalThis.crypto.randomUUID()}`}const gi=new WeakSet,qt=new WeakMap;function Oo(e,t,n,r="[DEFAULT]"){return Lm(e,t),Fm(e,t,n,r)}function Lm(e,t){gi.has(e)||(gi.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 vi(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 Fm(e,t,n,r){let s=qt.get(e);s||(s=new Map,qt.set(e,s));const i=`auth-session:${r}`,a=s.get(i);if(a){const u=++a.generation;return a.unregisterService?.(),a.unregisterService=void 0,a.unsubscribeBackend?.(),a.unsubscribeBackend=void 0,a.backend=t,a.session=n,a.unregisterService=e.registerPersistableService(i,vi(a)),()=>{a.generation===u&&(a.unregisterService?.(),a.unregisterService=void 0,a.unsubscribeBackend?.(),a.unsubscribeBackend=void 0,a.subscribers.clear(),s.get(i)===a&&s.delete(i),s.size===0&&qt.delete(e))}}const c={backend:t,session:n,subscribers:new Set,generation:1};s.set(i,c),c.unregisterService=e.registerPersistableService(i,vi(c));const l=c.generation;return()=>{c.generation===l&&(c.unregisterService?.(),c.unregisterService=void 0,c.unsubscribeBackend?.(),c.unsubscribeBackend=void 0,c.subscribers.clear(),s.get(i)===c&&s.delete(i),s.size===0&&qt.delete(e))}}async function sk(e){const{backend:t}=cs(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 Vm(e){const t=cs(e,!0);try{t.assertAlive?.()}catch(n){if(n.code==="app/app-deleted")return;throw n}await t.backend.transitionCurrentUser(null)}const wi=new WeakMap,xi=new WeakMap,ji=new WeakMap;function Mo(e){let t=xi.get(e);return t||(t=Po(),xi.set(e,t)),t}function qm(e){let t=wi.get(e);return t||(t=new $o(e,e,Mo(e)),wi.set(e,t),Oo(e,t,e)),t}function Wm(e,t){return t.service("auth/backend",()=>{const{sandbox:n,session:r}=t,s=new $o(n,r,Mo(n),i=>{t.onDelete(i)});return t.onDelete(Oo(n,s,r,e.name)),s})}function Uo(e){if(e===void 0)return Uo(Ol());const t=Ml(e);if(t)return t.service("auth/default",()=>{const n={kind:"sandbox",sandbox:t.sandbox,backend:Wm(e,t),own:r=>t.onDelete(r),assertAlive:()=>t.assertAlive()};return ki(n,e)});if(zm(e)){let n=ji.get(e);return n||(n=ki({kind:"sandbox",sandbox:e,backend:qm(e)}),ji.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 dev or @pyric/cli/register before importing to select the sandbox.")}function zm(e){return typeof e=="object"&&e!==null&&typeof e.onCurrentUserChanged=="function"&&typeof e.withAuth=="function"}function ki(e,t){const n={[Ao]:e,...t?{app:t}:{},signOut(){return Vm(n)}};return Object.defineProperty(n,"currentUser",{enumerable:!0,get(){return e.backend.getCurrentUser()}})}function K(e){return cs(e)}const fe={setUser(e,t){K(e).backend.setCurrentUser(t)},setAuthFlowResolver(e,t){K(e).backend.setResolver(t)},setAuthMailResolver(e,t){K(e).backend.setMailResolver(t)},takeAuthMail(e,t){return K(e).backend.takeMail(t)},listAuthMail(e){return K(e).backend.listMail()},mockActionCode(e,t,n){K(e).backend.stageActionCode(t,n)},listIdentities(e){return K(e).backend.listIdentities()},createSignInCredential(e,t){return K(e).backend.createSignInCredential(t)},mockSignInResult(e,t){const n=t.providerId;if(!n)throw new kl("invalid-argument","sandbox.mockSignInResult: result.providerId is required so the next signInWithPopup / signInWithCredential call can match.");K(e).backend.setMockResult(n,t)},seedUsers(e,t){K(e).backend.seedUsers(t)},exportUsers(e){return K(e).backend.exportUsers()},restoreSession(e,t){return K(e).backend.restoreSession(t)},mintSession(e,t){return K(e).backend.mintDetachedSession(t)},listUsers(e){return K(e).backend.listUsers()},createUser(e,t){return K(e).backend.createUser(t)},updateUser(e,t,n){return K(e).backend.updateUser(t,n)},updateProfile(e,t,n){return K(e).backend.updateProfileByUid(t,n)},deleteUser(e,t){K(e).backend.deleteUser(t)},clearUsers(e){K(e).backend.clearUsers()},subscribeUsers(e,t){return K(e).backend.subscribeUsers(t)},getAuthProviderConfig(e){return K(e).backend.listProviderConfig()},setAuthProviderConfig(e,t,n){K(e).backend.setProviderConfig(t,n)},assertAuthProviderEnabled(e,t){K(e).backend.assertProviderEnabled(t)},delegateProviderEnforcement(e,t){K(e).backend.setProviderEnforcementDelegated(t)},subscribeAuthProviderConfig(e,t){return K(e).backend.subscribeProviderConfig(t)}};function At(e,t){return Hm(e)?(Se(e.storage),new It(e.storage,Km(e.fullPath,t??""))):(Se(e),new It(e,To(t??"")))}class It{storage;bucket;fullPath;constructor(t,n){this.storage=t;const r=Se(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 It(this.storage,n)}get root(){return this.fullPath===""?this:new It(this.storage,"")}toString(){return`gs://${this.bucket}/${this.fullPath}`}}function To(e){return e===""?"":e.split("/").filter(t=>t.length>0).join("/")}function Km(e,t){const n=To(t);return e===""?n:n===""?e:`${e}/${n}`}function Hm(e){if(e===null||typeof e!="object"||En in e)return!1;const t=e;return typeof t.fullPath=="string"&&t.storage!==void 0}async function Gm(e,t){return Bo(e,"getBlob"),Jm(e,t)}async function ls(e,t){Bo(e,"deleteObject");const n=Se(e.storage),r=pt(n,t),s=await Mt(e.storage),i=await s.backend.getMetadata(e.fullPath);Ut(s,{request:{auth:ze(n),method:"delete",path:e.fullPath},resource:Nn(i)},n,r),await s.backend.delete(e.fullPath);try{Re(n.sandbox,vn({service:"storage",op:"object_delete",path:e.fullPath,auth:ze(n),before:i??void 0,detail:{bucket:e.bucket}}),r)}catch{}}async function Jm(e,t){const n=Se(e.storage),r=pt(n),s=await Mt(e.storage),i=await s.backend.getMetadata(e.fullPath);Ut(s,{request:{auth:ze(n),method:"get",path:e.fullPath},resource:Nn(i)},n,r);const a=await s.backend.getBlob(e.fullPath);if(!a)throw ho(e.fullPath);return typeof t=="number"&&a.size>t?a.slice(0,t):a}function Bo(e,t){if(e.fullPath==="")throw Cn(t)}function Ym(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 Qm{[Symbol.toStringTag]="UploadTask";_snapshot;_promise;_resolve;_reject;_observers=[];_didIntermediateProgress=!1;_error;_ref;_blob;_metadata;_provenance;constructor(t,n,r,s){this._ref=t,this._metadata=r,this._provenance=s;let i;r!==void 0&&(i=r.contentType),this._blob=Ym(n,i);const c=mo({ref:t,blob:this._blob,settable:r}),l=ss(c);this._promise=new Promise((u,d)=>{this._resolve=u,this._reject=d}),this._promise.catch(()=>{}),this._snapshot={bytesTransferred:0,totalBytes:this._blob.size,state:"running",metadata:l,ref:this._ref,task:this},queueMicrotask(()=>{this._runStep()})}get snapshot(){return this._snapshot}then(t,n){return this._promise.then(t,n)}catch(t){return this._promise.catch(t)}finally(t){return this._promise.finally(t)}pause(){return this._snapshot.state==="running"?(this._updateSnapshot("paused",this._snapshot.bytesTransferred),this._notifyObservers("next"),!0):!1}resume(){return this._snapshot.state==="paused"?(this._updateSnapshot("running",this._snapshot.bytesTransferred),this._notifyObservers("next"),queueMicrotask(()=>{this._runStep()}),!0):!1}cancel(){let t=!1;return(this._snapshot.state==="running"||this._snapshot.state==="paused")&&(t=!0),t?(this._error=Ah(),this._updateSnapshot("canceled",this._snapshot.bytesTransferred),this._notifyObservers("error"),this._reject(this._error),!0):!1}on(t,n,r,s){let i,a,c,l=!1;if(typeof n=="object"&&n!==null&&(l=!0),l){const f=n;f.next!==void 0&&(i=f.next),f.error!==void 0&&(a=f.error),f.complete!==void 0&&(c=f.complete)}else typeof n=="function"&&(i=n),typeof r=="function"&&(a=r),typeof s=="function"&&(c=s);const d={next:i,error:a,complete:c};if(this._observers.push(d),this._snapshot.state==="running"){if(i!==void 0){const m=i;try{m(this._snapshot)}catch{}}}else if(this._snapshot.state==="paused"){if(i!==void 0){const y=i;try{y(this._snapshot)}catch{}}}else if(this._snapshot.state==="success"){if(i!==void 0){const v=i;try{v(this._snapshot)}catch{}}if(c!==void 0){const v=c;try{v()}catch{}}}else if(this._snapshot.state==="error"){if(a!==void 0&&this._error!==void 0){const b=a,w=this._error;try{b(w)}catch{}}}else if(this._snapshot.state==="canceled"&&a!==void 0&&this._error!==void 0){const w=a,x=this._error;try{w(x)}catch{}}return()=>{const f=this._observers.indexOf(d);f!==-1&&this._observers.splice(f,1)}}_updateSnapshot(t,n,r){let s=this._snapshot.metadata;r!==void 0&&(s=r),this._snapshot={bytesTransferred:n,totalBytes:this._snapshot.totalBytes,state:t,metadata:s,ref:this._ref,task:this}}_notifyObservers(t){if(t==="next"){for(const i of this._observers)if(i.next!==void 0){const c=i.next;try{c(this._snapshot)}catch{}}}if(t==="error"){for(const i of this._observers)if(i.error!==void 0&&this._error!==void 0){const l=i.error,u=this._error;try{l(u)}catch{}}}if(t==="complete"){for(const i of this._observers)if(i.complete!==void 0){const c=i.complete;try{c()}catch{}}}}_runStep(){if(this._snapshot.state!=="running")return;if(this._didIntermediateProgress===!1){this._didIntermediateProgress=!0;let r=0;this._snapshot.totalBytes>0&&(r=Math.floor(this._snapshot.totalBytes/2)),this._updateSnapshot("running",r),this._notifyObservers("next"),queueMicrotask(()=>{this._runStep()});return}this._commitUpload()}async _commitUpload(){if(this._snapshot.state==="running")try{const n=await po(this._ref,this._blob,this._metadata,this._provenance);if(this._snapshot.state==="running")this._updateSnapshot("success",this._snapshot.totalBytes,n.metadata),this._notifyObservers("next"),this._notifyObservers("complete"),this._resolve(this._snapshot);else try{await ls(this._ref,this._provenance)}catch{}}catch(n){if(this._snapshot.state==="running"){let s;n instanceof Error?s=n:s=new Error(String(n)),this._error=s,this._updateSnapshot("error",this._snapshot.bytesTransferred),this._notifyObservers("error"),this._reject(this._error)}}}}function Xm(e,t,n,r){if(e.fullPath==="")throw Cn("uploadBytesResumable");return new Qm(e,t,n,r)}async function us(e){const t=e.storage,n=Se(t),r=pt(n),s=await Mt(t);Ut(s,{request:{auth:ze(n),method:"list",path:e.fullPath},resource:null},n,r);const i=e.fullPath===""?"":`${e.fullPath}/`,a=await s.backend.listByPrefix(i),c=[],l=new Set,u=[];for(const d of a){if(!d.fullPath.startsWith(i))continue;const p=d.fullPath.slice(i.length);if(p==="")continue;const f=p.indexOf("/");if(f===-1)c.push(At(t,d.fullPath));else{const m=p.slice(0,f),y=`${i}${m}`;l.has(y)||(l.add(y),u.push(At(t,y)))}}return u.sort((d,p)=>d.fullPath<p.fullPath?-1:d.fullPath>p.fullPath?1:0),{items:c,prefixes:u}}function Zm(e,t,n){const r={name:n,options:structuredClone(t),automaticDataCollectionEnabled:!0};return Od(r,e),r}const ey=Object.freeze({source:Object.freeze({kind:"studio"}),authLens:Object.freeze({mode:"admin"})});function ty(e){return ja(e.withAuth(null),ey)}const ny="pyric-studio";function Lo(e,t){return e.listDocuments(t).map(({path:n,phantom:r})=>({path:n,phantom:r}))}let ry=0;function sy(e){const t=Zm(e,{projectId:"pyric-studio"},`pyric-studio-${ry++}`),n=wn(e),r=ty(e);return{sandbox:e,app:t,firestore:Na(e),adminFirestore:Ra(r),auth:Uo(e),storage:uh(r),listRootCollections:()=>n.listRootCollections(),listSubcollections:s=>n.listSubcollections(s),listDocuments:s=>Lo(n,s)}}function iy(e,t){const[n,r]=h.useState(!1),[s,i]=h.useState(null),a=h.useMemo(()=>Ul(),[]),c=h.useMemo(()=>{try{return sy(a)}catch(u){return i(u instanceof Error?u:new Error(String(u))),null}},[a]);return h.useEffect(()=>{let u=!1;if(!e){r(!1);return}return a.enablePersistence({key:ny,injectedBackend:e}).then(()=>{u||r(!0)}).catch(d=>{u||i(d instanceof Error?d:new Error(String(d)))}),()=>{u=!0}},[a,e]),s?{status:"error",handles:null,error:s}:c?e!=null&&n||t==="ready"?{status:"ready",handles:c}:{status:"pending",handles:null}:{status:"error",handles:null,error:new Error("Studio: failed to construct the sandbox data handles.")}}function ay(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=Sa(e);return t?t.rules.kind==="evaluated":!1}function oy(e){return"service"in e&&typeof e.service=="string"?e.service:"firestore"}function cy(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 ly(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 uy(e){const t=[];for(const r of e)ay(r)&&t.push(dy(r));return ly(t,e).sort((r,s)=>s.at-r.at)}function dy(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:oy(e),path:n,auth:e.auth,reasons:e.reasons??[],origin:r,unsupported:s==="unsupported"};"matchedRule"in e&&e.matchedRule&&(i.matchedRule=e.matchedRule),"evaluatedRule"in e&&e.evaluatedRule&&(i.evaluatedRule=e.evaluatedRule),"rules"in e&&e.rules&&(i.rules=e.rules);const a=cy(e);return a!==void 0&&(i.resourceData=a),"resourceBefore"in e&&e.resourceBefore&&(i.resourceBefore={data:e.resourceBefore.data,exists:e.resourceBefore.exists}),i}const Si=/^Rule #(\d+) \(([^)]+)\) → (ALLOW|deny|unsupported)/;function fy(e){const t=e.rules?.engine??e.service;return t==="rtdb"||t==="storage"?t:"firestore"}function hy(e){if(e.rules?.reason==="Validation rule evaluated to false")return"validate";const t=e.method;return t==="get"||t==="list"||t==="listen"?"read":"write"}function py(e){const t=fy(e),n=e.reasons.filter(s=>Si.test(s)),r=e.reasons.filter(s=>!Si.test(s));if(e.unsupported)return{headline:`The simulator hit an unmodelled rules feature evaluating ${e.method} ${e.path}.`,engine:t,ruleLines:n,otherLines:r,implicitDeny:!1};if(e.result==="allow"){if(t==="firestore"&&e.matchedRule){const i=e.matchedRule,a=`Rule #${i.ruleIndex} (${i.operations.join(", ")})`;return{headline:`${a} allowed ${e.method} on ${e.path}.`,engine:t,ruleNode:a,ruleLines:n,otherLines:r,implicitDeny:!1}}return!e.matchedRule&&!e.rules&&!e.evaluatedRule&&n.length===0?{headline:`This ${e.method} on ${e.path} succeeded, but no rules evaluation was recorded for it — rules likely never ran (an admin/bypass operation from a worker that didn't stamp its lens, or a pre-provenance event).`,engine:t,ruleLines:n,otherLines:r,implicitDeny:!1,noEvaluation:!0}:{headline:`Rules allowed ${e.method} on ${e.path}.`,engine:t,...e.rules?.matchedRule?{ruleExpression:e.rules.matchedRule}:{},ruleLines:n,otherLines:r,implicitDeny:!1}}return t==="rtdb"?yy(e,n,r):t==="storage"?by(e,n,r):my(e,n,r)}function my(e,t,n){const r=!e.matchedRule;let s,i;if(r)s=`No rule allowed ${e.method} on ${e.path}: implicit deny (no matching \`allow\`).`;else{const a=e.matchedRule;i=`Rule #${a.ruleIndex} (${a.operations.join(", ")})`,s=`${i} denied ${e.method} on ${e.path}.`}return{headline:s,engine:"firestore",ruleNode:i,ruleLines:t,otherLines:n,implicitDeny:r}}function yy(e,t,n){const r=e.rules,s=hy(e),i=!r?.matchedPath||r?.errorCode==="NO_MATCHING_RULE",a=r?.pathVariableBindings&&Object.keys(r.pathVariableBindings).length>0?r.pathVariableBindings:void 0;let c,l;return i?c=`No \`.${s}\` rule granted ${e.method} on ${e.path}: RTDB implicit deny (no rule matched).`:s==="validate"?(l=`${r.matchedPath} .validate`,c=`The \`.validate\` rule at \`${r.matchedPath}\` rejected the proposed value for ${e.method} ${e.path}.`):(l=`${r.matchedPath} .${s}`,c=`The \`.${s}\` rule at \`${r.matchedPath}\` evaluated false for ${e.method} ${e.path}.`),{headline:c,engine:"rtdb",ruleNode:l,ruleExpression:r?.matchedRule,phase:s,bindings:a,ruleLines:t,otherLines:n,implicitDeny:i}}function by(e,t,n){const r=e.reasons.find(c=>/^match\s/.test(c)),i=e.reasons.some(c=>/^no rule matches/.test(c))||!r;return{headline:i?`No \`match\` block allowed ${e.method} on ${e.path}: Storage implicit deny (no rule matched).`:`A \`match\` block condition evaluated false for ${e.method} on ${e.path}.`,engine:"storage",ruleNode:i?void 0:r,ruleLines:t,otherLines:n,implicitDeny:i}}function gy(e){return e.skipped?"skipped":e.error!==void 0?"error":e.value===!0?"true":e.value===!1?"false":"value"}function vy(e){const t=e.evaluatedRule?.expressionTrace;if(!t||t.length===0)return[];const n=t.map(s=>({source:s.source,outcome:gy(s),...s.value!==void 0?{value:s.value}:{},...s.error!==void 0?{error:s.error}:{},...s.letBinding?{letBinding:s.letBinding.name}:{},...s.inlinedFrom?{inlinedFrom:s.inlinedFrom.name}:{},depth:0,children:[]})),r=[];return t.forEach((s,i)=>{s.parent===null||s.parent===void 0||!n[s.parent]?r.push(n[i]):(n[i].depth=n[s.parent].depth+1,n[s.parent].children.push(n[i]))}),r}function wy(e){const t=[{name:"request.auth",present:e.auth!==null,value:e.auth,...e.auth===null?{absentNote:"request.auth was null — the request was unauthenticated."}:{}},{name:"request.method",present:!0,value:e.method},{name:"request.path",present:!0,value:e.path}],n=e.method==="get"||e.method==="list"||e.method==="listen";return t.push({name:"request.resource.data",present:e.resourceData!==void 0,value:e.resourceData??null,...e.resourceData===void 0?{absentNote:n?"A read carries no proposed write, so request.resource.data is absent.":"No proposed write payload was captured for this denial."}:{}}),t.push({name:"resource",present:e.resourceBefore!==void 0,value:e.resourceBefore?{data:e.resourceBefore.data,exists:e.resourceBefore.exists}:null,...e.resourceBefore===void 0?{absentNote:"The rule evaluated no existing document (e.g. a list/query, or the doc did not exist)."}:{}}),t}function xy(e){const t=wn(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=>Lo(t,n)}}function Oe(){const e=$e(),t=pe(),n=t.status==="ready"?t.env.persistence:void 0,r=iy(n,t.status),s=t.status==="ready"?t.env.live:void 0,i=jy(s);return h.useMemo(()=>{switch(e.status){case"ready":return{status:"ready",handles:xy(e.handles)};case"pending":return{status:"pending",handles:null};case"error":return{status:"error",handles:null,error:e.error};case"disabled":{if(s&&r.status==="ready"){const a=s.db;return{status:"ready",firestoreApi:s.firestoreApi,authApi:s.authApi,storageApi:s.storageApi,handles:{...r.handles,firestore:a,adminFirestore:a,auth:s.auth,storage:s.storage,listRootCollections:()=>i,listSubcollections:c=>s.listSubcollections(c),listDocuments:c=>s.listDocuments(c)}}}return r}}},[e,r,s,i])}function jy(e){const[t,n]=h.useState([]);return h.useEffect(()=>{if(!e){n([]);return}let r=!0;const s=()=>{e.listRootCollections().then(a=>{r&&n(a)}).catch(()=>{})};try{e.setLens({mode:"admin"})}catch{}s();const i=e.feed.subscribe(()=>s());return()=>{r=!1,i()}},[e]),t}const hn=500;function Qn(e){return e.length>hn?e.slice(-hn):e}function Bt(){const e=$e(),t=pe(),n=t.status==="ready"?t.env.live?.feed:void 0,r=e.status==="ready",[s,i]=h.useState([]);h.useEffect(()=>{if(r||!n){i([]);return}return i(Qn(n.history())),n.subscribe(l=>i(u=>Qn(vd(u,l))))},[r,n]);const a=h.useMemo(()=>r?Qn(e.events):[],[r,e]);return r?a:s}function ky(e){return Sl(e)}function Sy(e){if(typeof e!="string")return!1;const t=e.toLowerCase();return t==="permission_denied"||t==="permission-denied"||t==="auth/permission-denied"}function _y(e){const t=Sa(e);if(!t)throw new Error("Studio traffic adapter received a non-operation event");if(e.kind==="request")return{...e,operationContext:t.context,rulesDisposition:t.rules};if(e.kind==="listener"){let s="error";if(e.result!==void 0)s=e.result;else{const c=e.error;c!==void 0&&Sy(c.code)&&(s="deny")}let i="(service)";e.target.path!==void 0&&(i=e.target.path);let a=[];if(e.reasons!==void 0)a=e.reasons;else{const c=e.error;c!==void 0&&c.reasons!==void 0&&(a=c.reasons)}return{kind:"operation",service:e.service,id:e.id,at:e.at,method:"listen",path:i,auth:e.auth,result:s,reasons:a,origin:"listener",triggeredBy:e.triggeredBy,operationContext:t.context,rulesDisposition:t.rules}}let n="(service)";e.path!==void 0&&(n=e.path);let r=[];return e.reasons!==void 0&&(r=e.reasons),{kind:"operation",service:e.service,id:e.id,at:e.at,durationMs:e.durationMs,method:e.method,path:n,auth:e.auth,result:e.result,reasons:r,request:e.request,resourceBefore:e.resourceBefore,resourceAfter:e.resourceAfter,origin:e.origin,groupId:e.groupId,groupKind:e.groupKind,triggeredBy:e.triggeredBy,operationContext:t.context,rulesDisposition:t.rules}}function Ey(){const e=Bt();return h.useMemo(()=>e.filter(ky).map(_y),[e])}function Cy(){const e=Bt();return h.useMemo(()=>uy(e),[e])}function Ny(){const e=Oe();return h.useCallback(async t=>{if(e.status!=="ready")throw new Error("No sandbox available to seed.");const n=e.handles.adminFirestore,r=e.firestoreApi?.doc??Le,s=e.firestoreApi?.setDoc??en;let i=0;const a=[];for(const c of t)try{await s(r(n,c.path),c.data),i++}catch(l){a.push(`${c.path}: ${l instanceof Error?l.message:String(l)}`)}return{written:i,errors:a}},[e])}function Ry(){const e=Oe();return h.useCallback(async t=>{if(e.status!=="ready")throw new Error("No sandbox available to seed auth.");const n=e.handles.auth,r=e.authApi?.createUser??fe.createUser;let s=0;const i=[];for(const a of t)try{await r(n,a.request),s++}catch(c){const l=a.request.uid??a.request.email??"<auto>";i.push(`${l}: ${c instanceof Error?c.message:String(c)}`)}return{created:s,errors:i}},[e])}function Ay(){const e=Oe(),t=pe(),n=t.status==="ready"?t.env.live:void 0;return h.useCallback(async()=>{if(e.status!=="ready")throw new Error("No sandbox to clear.");const r=[];try{const s=n?await n.resetAll():await e.handles.sandbox.resetAll();r.push(...s?.errors??[])}catch(s){r.push(`reset: ${s instanceof Error?s.message:String(s)}`)}return{errors:r}},[e,n])}function Iy(){const e=Ay(),t=Ny(),n=Ry(),r=$e();return h.useCallback(async()=>{const s=await e();if(r.status==="ready"){const{applySeed:i,deploySeedRules:a}=await Xa(async()=>{const{applySeed:c,deploySeedRules:l}=await import("./seed.CSUkloMi.js");return{applySeed:c,deploySeedRules:l}},__vite__mapDeps([0,1,2,3,4]));a(r.handles.sandbox),await i(r.handles)}else try{const i=await fetch("/__pyric/init.json").then(l=>l.ok?l.json():null),a=i?.seed;a&&await t(Object.entries(a).map(([l,u])=>({path:l,data:u})));const c=i?.authUsers;Array.isArray(c)&&await n(c.map(l=>({request:l})))}catch(i){s.errors.push(`reseed: ${i instanceof Error?i.message:String(i)}`)}return s},[e,t,n,r])}function ds(){const e=pe(),t=e.status==="ready"?e.env.live:void 0,[n,r]=h.useState("");return h.useEffect(()=>{if(!t){r("");return}let s=!1;return t.instanceId().then(i=>{s||r(i)}),()=>{s=!0}},[t]),n}function Dy(){const e=pe(),t=e.status==="ready"?e.env.live:void 0;return h.useCallback(async()=>t?t.exportState():null,[t])}function Py(){const e=pe(),t=e.status==="ready"?e.env.live:void 0;return h.useCallback(async n=>t?(await t.importState(n),!0):!1,[t])}function $y(){const e=pe(),t=e.status==="ready"?e.env.live:void 0,[n,r]=h.useState([]),s=h.useCallback(async()=>{r(t?await t.listBranches():[])},[t]);h.useEffect(()=>{s()},[s]);const i=h.useCallback(async l=>{t&&(await t.saveBranch(l),await s())},[t,s]),a=h.useCallback(async l=>{t&&await t.switchBranch(l)},[t]),c=h.useCallback(async l=>{t&&(await t.deleteBranch(l),await s())},[t,s]);return{branches:n,save:i,switchTo:a,remove:c}}function Oy(e="firestore"){const t=$e(),n=t.status==="ready",[r,s]=h.useState({});return h.useEffect(()=>{if(n)return;let i=!0;return fetch("/__pyric/init.json").then(a=>a.ok?a.json():null).then(a=>{if(!i||!a||typeof a!="object")return;const l={};typeof a.rules=="string"&&(l.firestore=a.rules),a.databaseRules!==void 0&&a.databaseRules!==null&&(typeof a.databaseRules=="string"?l.rtdb=a.databaseRules:l.rtdb=JSON.stringify(a.databaseRules,null,2)),typeof a.storageRules=="string"&&(l.storage=a.storageRules),s(l)}).catch(()=>{}),()=>{i=!1}},[n]),h.useMemo(()=>{const i=t.status==="ready",a=e==="database"?"rtdb":e;if(!i){const c=r[a];return c!==void 0?c:""}try{if(a==="rtdb"){const u=La(t.handles.sandbox);return u!=null?JSON.stringify(u,null,2):""}return wn(t.handles.sandbox).getRules()}catch{return""}},[t,r,e])}function My(e){let t=!0;return n=>{const r=t;t=!1,e(s=>Ty(s,n,r))}}function Uy(e){const t=new Map;for(const n of e)t.set(Rr(n),n);return[...t.values()]}function Ty(e,t,n){return Uy(n?t:[...e??[],...t])}const By=3e4;function Fo(){const e=Oe(),t=pe(),[n,r]=h.useState(null),[s,i]=h.useState(!1),a=h.useRef(!1),c=h.useRef(e);c.current=e;const l=t.status==="ready"?t.env.live:void 0,u=h.useRef(l);u.current=l;const d=h.useRef(null),p=h.useRef(0),f=h.useRef(null),m=h.useRef(0),y=h.useCallback(v=>{const b=c.current;if(b.status!=="ready")return;const w=++p.current;a.current=!0,i(!0);const x=b.handles,k=x.adminFirestore,j=b.firestoreApi?.collection??_t,S=b.firestoreApi?.query??cn,N=b.firestoreApi?.getDocs??on,P=b.firestoreApi?.limit??ln,I=b.storageApi?.ref??At,D=b.storageApi?.listAll??us,C=b.authApi?.listUsers??fe.listUsers,_={listRootCollections:()=>x.listRootCollections(),listDocumentPaths:async(R,V)=>(await N(S(j(k,R),P(V)))).docs.slice(0,V).map(A=>`${R}/${A.id}`),listSubcollections:R=>Promise.resolve(x.listSubcollections(R)),listUsers:async R=>(await Promise.resolve(C(x.auth))).slice(0,R).map(G=>({uid:G.uid,email:G.email??null})),listStorageObjectPaths:R=>vm(I(x.storage,""),D,{maxObjects:R,maxListCalls:Ar.storageListCalls}),listRtdbTopLevelKeys:async()=>{const R=u.current;if(!R)return[];const V=Date.now()-m.current<By;if(f.current!==null&&V&&!v?.rtdbLikely)return f.current;const G=await R.readRtdbState(),A=G===null||typeof G!="object"||Array.isArray(G)?[]:Object.keys(G);return f.current=A,m.current=Date.now(),A}},E=My(R=>r(R));Dm(_,Ar,R=>{w===p.current&&E(R)}).catch(()=>{}).finally(()=>{if(w===p.current&&(a.current=!1,i(!1),r(R=>R??[]),d.current)){const R=d.current;d.current=null,y(R)}})},[]),g=h.useCallback(v=>{if(c.current.status==="ready"){if(a.current){d.current={...d.current,...v};return}y(v)}},[y]);return h.useEffect(()=>{e.status==="ready"&&n===null&&!a.current&&y()},[e,n,y]),{entries:n,building:s,ensure:g}}const Ly=150;function Fy(e){return e.startsWith("/")||/rtdb/i.test(e)}function Vo({autoFocus:e,onNavigated:t,onEscape:n,exposeFocus:r}){const[s,i]=h.useState(""),[a,c]=h.useState(""),[l,u]=h.useState(0),[d,p]=h.useState(!1),f=h.useRef(null),{entries:m,building:y,ensure:g}=Fo();h.useEffect(()=>{if(r)return r(()=>f.current?.focus()),()=>r(null)},[r]),h.useEffect(()=>{e&&f.current?.focus()},[e]),h.useEffect(()=>{const j=setTimeout(()=>c(s),Ly);return()=>clearTimeout(j)},[s]);const v=h.useMemo(()=>mi(a,Ke,m??[]),[a,m]),b=h.useMemo(()=>yi(v),[v]);h.useEffect(()=>{u(j=>b.length===0?0:Math.min(j,b.length-1))},[b.length]);const w=j=>{j&&(i(""),c(""),p(!1),le(j.target),t?.(j.target))},x=()=>{if(s===a){w(b[l]??b[0]);return}const j=yi(mi(s,Ke,m??[]));w(j[0])};let k=0;return o.jsxs("div",{className:"studio-home__command",children:[o.jsx("div",{className:"studio-home__command-row",children:o.jsx("input",{ref:f,className:"studio-home__command-input",type:"text",value:s,placeholder:"Jump to a surface, collection, doc, user, or object…","aria-label":"Command input",role:"combobox","aria-expanded":d&&b.length>0,"aria-autocomplete":"list",onFocus:()=>{g(),p(!0)},onBlur:()=>p(!1),onChange:j=>{const S=j.target.value;i(S),p(!0),Fy(S)&&g({rtdbLikely:!0})},onKeyDown:j=>{if(j.key==="ArrowDown")j.preventDefault(),u(S=>Math.min(S+1,Math.max(b.length-1,0)));else if(j.key==="ArrowUp")j.preventDefault(),u(S=>Math.max(S-1,0));else if(j.key==="Enter")x();else if(j.key==="Escape"){if(n){n();return}i(""),c(""),p(!1)}}})}),d&&!v.length&&y&&m===null?o.jsx("div",{className:"studio-home__command-results",role:"status","aria-live":"polite",children:o.jsx("span",{className:"studio-home__command-group-title",children:"Indexing sandbox…"})}):null,d&&v.length?o.jsx("div",{className:"studio-home__command-results",role:"listbox","aria-label":"Suggestions",onMouseDown:j=>j.preventDefault(),children:v.map(j=>{const S=k;return k+=j.results.length,o.jsxs("div",{className:"studio-home__command-group",children:[o.jsx("span",{className:"studio-home__command-group-title","aria-hidden":"true",children:j.title}),o.jsx("ul",{className:"studio-home__command-group-list",children:j.results.map((N,P)=>{const I=S+P;return o.jsx("li",{children:o.jsxs("button",{type:"button",role:"option","aria-selected":I===l,className:"studio-home__command-result","data-active":I===l?"true":void 0,onMouseEnter:()=>u(I),onClick:()=>w(N),children:[o.jsx("span",{className:"studio-home__command-label",children:N.label}),o.jsx("span",{className:"studio-home__command-sub",children:N.hint})]})},N.id)})})]},j.kind)})}):null]})}function Vy({onClose:e}){const t=h.useRef(null);return h.useEffect(()=>(t.current=document.activeElement,()=>{const n=t.current;n instanceof HTMLElement&&n.focus()}),[]),h.useEffect(()=>{const n=r=>{r.key==="Escape"&&e()};return window.addEventListener("keydown",n),()=>window.removeEventListener("keydown",n)},[e]),o.jsx("div",{className:"studio__cmdk-backdrop",onMouseDown:e,children:o.jsx("div",{className:"studio__cmdk",role:"dialog","aria-modal":"true","aria-label":"Command",onMouseDown:n=>n.stopPropagation(),children:o.jsx(Vo,{autoFocus:!0,onEscape:e,onNavigated:e})})})}const qy={status:"loading",payload:null},Wt={status:"absent",payload:null};let pn=qy,_i=!1;const Ir=new Set;function zt(e){pn=e;for(const t of Ir)t()}function Wy(){if(!_i){if(_i=!0,typeof fetch>"u"){pn=Wt;return}fetch("/__pyric/init.json").then(async e=>{if(!e.ok||!(e.headers.get("content-type")??"").includes("json"))return zt(Wt);const n=await e.json();zt({status:"ready",payload:n})}).catch(()=>zt(Wt))}}function zy(e){return Ir.add(e),Wy(),()=>Ir.delete(e)}function Dn(){return h.useSyncExternalStore(zy,()=>pn,()=>pn)}function Ky(e){return e.kind==="absent"?"absent":e.sandboxConnected?"available":"idle"}function Hy(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 Gy(e){try{const t=await e("/__pyric/health");return t.ok?(t.headers.get("content-type")??"").includes("json")?Hy(t.status,await t.json()):{kind:"absent"}:{kind:"absent"}}catch{return{kind:"absent"}}}function Jy(e=5e3){const[t,n]=h.useState("checking");return h.useEffect(()=>{if(typeof fetch>"u"){n("absent");return}let r=!0,s=null;const i=async()=>{const u=Ky(await Gy(fetch));return r&&(n(u),u==="absent"&&s&&(clearInterval(s),s=null)),u},a=()=>typeof document>"u"||document.visibilityState!=="hidden",c=()=>{s||(s=setInterval(()=>{a()&&i()},e))},l=()=>{a()&&i()};return i().then(u=>{r&&u!=="absent"&&c()}),typeof document<"u"&&document.addEventListener("visibilitychange",l),()=>{r=!1,s&&clearInterval(s),typeof document<"u"&&document.removeEventListener("visibilitychange",l)}},[e]),t}const Yy="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 Qy(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 Xy(e){return e==="studio"?"Studio":"App"}function Zy(e,t,n=Date.now()){const r=e.clients.length,s=e.clients.map(a=>({clientId:a.clientId,kindLabel:Xy(a.kind),route:a.route||"/",visibilityLabel:a.visibility==="hidden"?"Hidden":"Visible",isThisPage:a.clientId===t,freshnessLabel:Qy(a.lastSeen,n)}));s.sort((a,c)=>a.isThisPage!==c.isThisPage?a.isThisPage?-1:1:a.kindLabel!==c.kindLabel?a.kindLabel==="Studio"?-1:1:a.route.localeCompare(c.route));const i=s.filter(a=>!a.isThisPage).length;return{count:r,chipLabel:r===1?"1 page connected":`${r} pages connected`,prominent:r>1,clients:s,boundaryCopy:Yy,otherCount:i}}function eb(){const e=pe(),t=e.status==="ready"&&e.env.live?e.env.live:null,[n,r]=h.useState(null);return h.useEffect(()=>{if(!t){r(null);return}const s=t.presenceClientId;return t.subscribePresence(i=>{r(Zy(i,s))})},[t]),n}const tb={servedEpoch:null,runningEpoch:null,updateAvailable:!1,updating:!1,error:null},nb=()=>()=>{},Ei=()=>tb;function rb(){const e=pe(),t=Dn(),n=Jy(),r=eb(),[s,i]=h.useState(!1),a=h.useRef(null),c=e.status==="ready"?e.env.live?.runtime:void 0,l=h.useSyncExternalStore(c?.subscribe??nb,c?.getSnapshot??Ei,c?.getSnapshot??Ei),d=t.status==="ready"&&e.status==="ready"&&!e.env.live,p=e.status==="error",f=l.error?"worker update failed":p?"backend error":d?"worker unreachable":null,m=l.error??(p?e.error.message:"Served, but the shared sandbox worker is not reachable; data views may be stale. Open Settings diagnostics."),y=n==="available";return h.useEffect(()=>{if(!s)return;const g=v=>{v.key==="Escape"&&(i(!1),a.current?.focus())};return document.addEventListener("keydown",g),()=>document.removeEventListener("keydown",g)},[s]),o.jsxs("div",{className:"studio__status","aria-label":"Studio status",children:[l.updateAvailable?o.jsxs("button",{type:"button",className:"studio-chip studio-chip--warn",disabled:l.updating,title:"The Studio backend is running older code. Update every connected page to the served worker version.",onClick:()=>void c?.update().catch(()=>{}),children:[o.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),l.updating?"updating worker…":"update worker"]}):null,f?o.jsxs("a",{className:"studio-chip studio-chip--warn",href:Rn({tab:"settings"}),title:m,onClick:g=>{g.preventDefault(),le({tab:"settings"})},children:[o.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),f]}):null,r&&r.count>0?o.jsxs("span",{className:"studio-presence",children:[o.jsxs("button",{ref:a,type:"button",className:r.prominent?"studio-chip studio-chip--live studio-presence__trigger":"studio-chip studio-presence__trigger","aria-haspopup":"dialog","aria-expanded":s,"aria-controls":"studio-presence-panel",title:r.otherCount>0?`${r.chipLabel}. ${r.otherCount} other page${r.otherCount===1?"":"s"} can keep the worker alive.`:`${r.chipLabel}. Expand for details.`,onClick:()=>i(g=>!g),children:[o.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),r.chipLabel]}),s?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"studio-presence__backdrop",onMouseDown:()=>i(!1)}),o.jsxs("div",{id:"studio-presence-panel",className:"studio-presence__panel",role:"dialog","aria-label":"Connected pages",children:[o.jsx("p",{className:"studio-presence__lead",children:r.count===1?"This page is the only connection to the shared sandbox worker.":`${r.count} pages share this sandbox worker. Closing this page alone will not restart it.`}),o.jsx("ul",{className:"studio-presence__list",children:r.clients.map(g=>o.jsxs("li",{className:"studio-presence__item",children:[o.jsxs("div",{className:"studio-presence__item-head",children:[o.jsx("span",{className:"studio-presence__kind",children:g.kindLabel}),g.isThisPage?o.jsx("span",{className:"studio-presence__this",children:"This page"}):null]}),o.jsx("div",{className:"studio-presence__route",title:g.route,children:g.route}),o.jsxs("div",{className:"studio-presence__meta",children:[g.visibilityLabel," · ",g.freshnessLabel]})]},g.clientId))}),o.jsx("p",{className:"studio-presence__boundary",children:r.boundaryCopy})]})]}):null]}):null,y?o.jsxs("span",{className:"studio-chip studio-chip--live",title:"MCP bridge available — a sandbox peer is connected; external agents can reach this sandbox.",children:[o.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),"MCP bridge"]}):null]})}function sb(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 Ci(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 ib({events:e,groupBatches:t=!0,groupListenerRuns:n=!0}){return h.useMemo(()=>{const r=[];let s=0;for(;s<e.length;){const i=e[s];if(t&&i.groupId){let a=s+1;for(;a<e.length&&e[a].groupId===i.groupId;)a++;const c=e.slice(s,a),l=i.origin==="transaction"?"transaction":"batch";r.push(Ci(l,i.groupId,c)),s=a;continue}if(n&&i.origin==="listener"){let a=s+1;for(;a<e.length&&e[a].origin==="listener"&&!e[a].groupId&&sb(e[a],i);)a++;const c=e.slice(s,a);if(c.length>1){const l=i.triggeredBy?`${i.triggeredBy.method}:${i.triggeredBy.path}`:"unknown";r.push(Ci("listener-run",`listener-run:${l}:${s}`,c))}else r.push({type:"single",event:i});s=a;continue}r.push({type:"single",event:i}),s++}return{items:r}},[e,t,n])}const ab={buckets:[],total:0,denies:0,maxCount:0,outOfWindow:0};function ob({events:e,window:t,bucketCount:n=30}){return h.useMemo(()=>cb(e,t,n),[e,t.start,t.end,n])}function cb(e,t,n=30){const r=t.end-t.start;if(n<=0||r<=0)return ab;const s=r/n,i=new Array(n).fill(0),a=new Array(n).fill(0);let c=0,l=0,u=0;for(const f of e){const m=f.at;if(m<t.start||m>=t.end){u++;continue}let y=Math.floor((m-t.start)/s);y>=n&&(y=n-1),i[y]++,c++,f.result==="deny"&&(a[y]++,l++)}let d=0;for(const f of i)f>d&&(d=f);return{buckets:i.map((f,m)=>{const y=a[m];return{index:m,start:t.start+m*s,end:t.start+(m+1)*s,count:f,denies:y,allows:f-y,heightRatio:d===0?0:f/d,denyHeightRatio:d===0?0:y/d}}),total:c,denies:l,maxCount:d,outOfWindow:u}}const lb=new Set(["get","list"]),ub=new Set(["create","update","set"]),db=new Set(["delete","remove"]),fb=[{key:"reads",label:"Read ops"},{key:"writes",label:"Writes"},{key:"deletes",label:"Deletes"}],hb=[{key:"allows",label:"Allows"},{key:"denies",label:"Denies"},{key:"errors",label:"Errors"}];function Pn(e){return e.origin==="admin"}function pb(e,t=Pn){return e.result==="allow"||t(e)?lb.has(e.method)?"reads":ub.has(e.method)?"writes":db.has(e.method)?"deletes":null:null}function mb(e,t=Pn){return t(e)?null:e.result==="allow"?"allows":e.result==="deny"?"denies":e.result==="error"?"errors":null}const yb=e=>({points:[],series:e.map(t=>({key:t.key,label:t.label,values:[],total:0})),maxValue:0});function qo(e,t,n,r,s){const i=t.end-t.start;if(n<=0||i<=0)return yb(r);const a=i/n,c=new Map(r.map(f=>[f.key,new Array(n).fill(0)])),l=new Map(r.map(f=>[f.key,0]));for(const f of e){const m=f.at;if(m<t.start||m>=t.end)continue;const y=s(f);if(y==null)continue;let g=Math.floor((m-t.start)/a);g>=n&&(g=n-1);const v=c.get(y);v[g]++,l.set(y,(l.get(y)??0)+1)}let u=0;for(const f of c.values())for(const m of f)m>u&&(u=m);const d=new Array(n);for(let f=0;f<n;f++)d[f]={index:f,start:t.start+f*a,end:t.start+(f+1)*a};const p=r.map(f=>({key:f.key,label:f.label,values:c.get(f.key),total:l.get(f.key)??0}));return{points:d,series:p,maxValue:u}}function bb(e,t,n=24,r=Pn){return qo(e,t,n,fb,s=>pb(s,r))}function gb(e,t,n=24,r=Pn){return qo(e,t,n,hb,s=>mb(s,r))}function vb({events:e,window:t,bucketCount:n=24,isAdmin:r}){return h.useMemo(()=>bb(e,t,n,r),[e,t.start,t.end,n,r])}function wb({events:e,window:t,bucketCount:n=24,isAdmin:r}){return h.useMemo(()=>gb(e,t,n,r),[e,t.start,t.end,n,r])}function Dr({children:e,kind:t,className:n,ariaLabel:r}){return o.jsx("span",{"data-pyric-badge":"","data-pyric-badge-kind":t,className:n,"aria-label":r,children:r?o.jsx("span",{"aria-hidden":"true",children:e}):e})}function Dt(e){const t=new Date(e),n=r=>String(r).padStart(2,"0");return`${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`}function Wo({event:e,selected:t,onSelect:n,renderClassification:r,formatTime:s=Dt,className:i}){return o.jsxs("button",{type:"button",onClick:()=>n?.(e),className:i,"data-pyric-traffic-row":"","data-pyric-result":e.result,"data-pyric-origin":e.origin,"data-pyric-method":e.method,"data-pyric-selected":t?"":void 0,children:[o.jsx("span",{"data-pyric-traffic-time":"",children:s(e.at)}),o.jsx("span",{"data-pyric-traffic-service":e.service??"",children:e.service??""}),o.jsx(Dr,{kind:e.method,children:e.method}),o.jsx("span",{"data-pyric-traffic-path":"",children:e.path||"/"}),r?r(e):null]})}var fs=Tl();function Qe(e,t,n){let r=n.initialDeps??[],s,i=!0;function a(){var c,l,u;let d;n.key&&((c=n.debug)!=null&&c.call(n))&&(d=Date.now());const p=e();if(!(p.length!==r.length||p.some((y,g)=>r[g]!==y)))return s;r=p;let m;if(n.key&&((l=n.debug)!=null&&l.call(n))&&(m=Date.now()),s=t(...p),n.key&&((u=n.debug)!=null&&u.call(n))){const y=Math.round((Date.now()-d)*100)/100,g=Math.round((Date.now()-m)*100)/100,v=g/16,b=(w,x)=>{for(w=String(w);w.length<x;)w=" "+w;return w};console.info(`%c⏱ ${b(g,5)} /${b(y,5)} ms`,`
|
|
6
|
+
font-size: .6rem;
|
|
7
|
+
font-weight: bold;
|
|
8
|
+
color: hsl(${Math.max(0,Math.min(120-120*v,120))}deg 100% 31%);`,n?.key)}return n?.onChange&&!(i&&n.skipInitialOnChange)&&n.onChange(s),i=!1,s}return a.updateDeps=c=>{r=c},a}function Ni(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const xb=(e,t)=>Math.abs(e-t)<1.01,jb=(e,t,n)=>{let r;return function(...s){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,s),n)}},Ri=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},kb=e=>e,Sb=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},_b=(e,t)=>{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;const s=a=>{const{width:c,height:l}=a;t({width:Math.round(c),height:Math.round(l)})};if(s(Ri(n)),!r.ResizeObserver)return()=>{};const i=new r.ResizeObserver(a=>{const c=()=>{const l=a[0];if(l?.borderBoxSize){const u=l.borderBoxSize[0];if(u){s({width:u.inlineSize,height:u.blockSize});return}}s(Ri(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(c):c()});return i.observe(n,{box:"border-box"}),()=>{i.unobserve(n)}},Ai={passive:!0},Ii=typeof window>"u"?!0:"onscrollend"in window,Eb=(e,t)=>{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;let s=0;const i=e.options.useScrollendEvent&&Ii?()=>{}:jb(r,()=>{t(s,!1)},e.options.isScrollingResetDelay),a=d=>()=>{const{horizontal:p,isRtl:f}=e.options;s=p?n.scrollLeft*(f&&-1||1):n.scrollTop,i(),t(s,d)},c=a(!0),l=a(!1);n.addEventListener("scroll",c,Ai);const u=e.options.useScrollendEvent&&Ii;return u&&n.addEventListener("scrollend",l,Ai),()=>{n.removeEventListener("scroll",c),u&&n.removeEventListener("scrollend",l)}},Cb=(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"]},Nb=(e,{adjustments:t=0,behavior:n},r)=>{var s,i;const a=e+t;(i=(s=r.scrollElement)==null?void 0:s.scrollTo)==null||i.call(s,{[r.options.horizontal?"left":"top"]:a,behavior:n})};class Rb{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this.itemSizeCache=new Map,this.laneAssignments=new Map,this.pendingMeasuredCacheIndexes=[],this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this.elementsCache=new Map,this.now=()=>{var n,r,s;return((s=(r=(n=this.targetWindow)==null?void 0:n.performance)==null?void 0:r.now)==null?void 0:s.call(r))??Date.now()},this.observer=(()=>{let n=null;const r=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(s=>{s.forEach(i=>{const a=()=>{const c=i.target,l=this.indexFromElement(c);if(!c.isConnected){this.observer.unobserve(c);return}this.shouldMeasureDuringScroll(l)&&this.resizeItem(l,this.options.measureElement(c,i,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(a):a()})}));return{disconnect:()=>{var s;(s=r())==null||s.disconnect(),n=null},observe:s=>{var i;return(i=r())==null?void 0:i.observe(s,{box:"border-box"})},unobserve:s=>{var i;return(i=r())==null?void 0:i.unobserve(s)}}})(),this.range=null,this.setOptions=n=>{Object.entries(n).forEach(([r,s])=>{typeof s>"u"&&delete n[r]}),this.options={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:kb,rangeExtractor:Sb,onChange:()=>{},measureElement:Cb,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=Qe(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),n=>{this.notify(n)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(n=>n()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var n;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((n=this.scrollElement)==null?void 0:n.window)??null,this.elementsCache.forEach(s=>{this.observer.observe(s)}),this.unsubs.push(this.options.observeElementRect(this,s=>{this.scrollRect=s,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(s,i)=>{this.scrollAdjustments=0,this.scrollDirection=i?this.getScrollOffset()<s?"forward":"backward":null,this.scrollOffset=s,this.isScrolling=i,this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getFurthestMeasurement=(n,r)=>{const s=new Map,i=new Map;for(let a=r-1;a>=0;a--){const c=n[a];if(s.has(c.lane))continue;const l=i.get(c.lane);if(l==null||c.end>l.end?i.set(c.lane,c):c.end<l.end&&s.set(c.lane,!0),s.size===this.options.lanes)break}return i.size===this.options.lanes?Array.from(i.values()).sort((a,c)=>a.end===c.end?a.index-c.index:a.end-c.end)[0]:void 0},this.getMeasurementOptions=Qe(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode],(n,r,s,i,a,c,l)=>(this.prevLanes!==void 0&&this.prevLanes!==c&&(this.lanesChangedFlag=!0),this.prevLanes=c,this.pendingMeasuredCacheIndexes=[],{count:n,paddingStart:r,scrollMargin:s,getItemKey:i,enabled:a,lanes:c,laneAssignmentMode:l}),{key:!1}),this.getMeasurements=Qe(()=>[this.getMeasurementOptions(),this.itemSizeCache],({count:n,paddingStart:r,scrollMargin:s,getItemKey:i,enabled:a,lanes:c,laneAssignmentMode:l},u)=>{if(!a)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>n)for(const m of this.laneAssignments.keys())m>=n&&this.laneAssignments.delete(m);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMeasuredCacheIndexes=[]),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(m=>{this.itemSizeCache.set(m.key,m.size)}));const d=this.lanesSettling?0:this.pendingMeasuredCacheIndexes.length>0?Math.min(...this.pendingMeasuredCacheIndexes):0;this.pendingMeasuredCacheIndexes=[],this.lanesSettling&&this.measurementsCache.length===n&&(this.lanesSettling=!1);const p=this.measurementsCache.slice(0,d),f=new Array(c).fill(void 0);for(let m=0;m<d;m++){const y=p[m];y&&(f[y.lane]=m)}for(let m=d;m<n;m++){const y=i(m),g=this.laneAssignments.get(m);let v,b;const w=l==="estimate"||u.has(y);if(g!==void 0&&this.options.lanes>1){v=g;const S=f[v],N=S!==void 0?p[S]:void 0;b=N?N.end+this.options.gap:r+s}else{const S=this.options.lanes===1?p[m-1]:this.getFurthestMeasurement(p,m);b=S?S.end+this.options.gap:r+s,v=S?S.lane:m%this.options.lanes,this.options.lanes>1&&w&&this.laneAssignments.set(m,v)}const x=u.get(y),k=typeof x=="number"?x:this.options.estimateSize(m),j=b+k;p[m]={index:m,start:b,size:k,end:j,key:y,lane:v},f[v]=m}return this.measurementsCache=p,p},{key:!1,debug:()=>this.options.debug}),this.calculateRange=Qe(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,s,i)=>this.range=n.length>0&&r>0?Ab({measurements:n,outerSize:r,scrollOffset:s,lanes:i}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=Qe(()=>{let n=null,r=null;const s=this.calculateRange();return s&&(n=s.startIndex,r=s.endIndex),this.maybeNotify.updateDeps([this.isScrolling,n,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,n,r]},(n,r,s,i,a)=>i===null||a===null?[]:n({startIndex:i,endIndex:a,overscan:r,count:s}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=n=>{const r=this.options.indexAttribute,s=n.getAttribute(r);return s?parseInt(s,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=n=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const s=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(s!==void 0&&this.range){const i=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),a=Math.max(0,s-i),c=Math.min(this.options.count-1,s+i);return n>=a&&n<=c}return!0},this.measureElement=n=>{if(!n){this.elementsCache.forEach((a,c)=>{a.isConnected||(this.observer.unobserve(a),this.elementsCache.delete(c))});return}const r=this.indexFromElement(n),s=this.options.getItemKey(r),i=this.elementsCache.get(s);i!==n&&(i&&this.observer.unobserve(i),this.observer.observe(n),this.elementsCache.set(s,n)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(n,void 0,this))},this.resizeItem=(n,r)=>{var s;const i=this.measurementsCache[n];if(!i)return;const a=this.itemSizeCache.get(i.key)??i.size,c=r-a;c!==0&&(((s=this.scrollState)==null?void 0:s.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(i,c,this):i.start<this.getScrollOffset()+this.scrollAdjustments)&&this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=c,behavior:void 0}),this.pendingMeasuredCacheIndexes.push(i.index),this.itemSizeCache=new Map(this.itemSizeCache.set(i.key,r)),this.notify(!1))},this.getVirtualItems=Qe(()=>[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const s=[];for(let i=0,a=n.length;i<a;i++){const c=n[i],l=r[c];s.push(l)}return s},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length!==0)return Ni(r[zo(0,r.length-1,s=>Ni(r[s]).start,n)])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const n=this.scrollElement.document.documentElement;return this.options.horizontal?n.scrollWidth-this.scrollElement.innerWidth:n.scrollHeight-this.scrollElement.innerHeight}},this.getOffsetForAlignment=(n,r,s=0)=>{if(!this.scrollElement)return 0;const i=this.getSize(),a=this.getScrollOffset();r==="auto"&&(r=n>=a+i?"end":"start"),r==="center"?n+=(s-i)/2:r==="end"&&(n-=i);const c=this.getMaxScrollOffset();return Math.max(Math.min(c,n),0)},this.getOffsetForIndex=(n,r="auto")=>{n=Math.max(0,Math.min(n,this.options.count-1));const s=this.getSize(),i=this.getScrollOffset(),a=this.measurementsCache[n];if(!a)return;if(r==="auto")if(a.end>=i+s-this.options.scrollPaddingEnd)r="end";else if(a.start<=i+this.options.scrollPaddingStart)r="start";else return[i,r];if(r==="end"&&n===this.options.count-1)return[this.getMaxScrollOffset(),r];const c=r==="end"?a.end+this.options.scrollPaddingEnd:a.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(c,r,a.size),r]},this.scrollToOffset=(n,{align:r="start",behavior:s="auto"}={})=>{const i=this.getOffsetForAlignment(n,r),a=this.now();this.scrollState={index:null,align:r,behavior:s,startedAt:a,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:s}),this.scheduleScrollReconcile()},this.scrollToIndex=(n,{align:r="auto",behavior:s="auto"}={})=>{n=Math.max(0,Math.min(n,this.options.count-1));const i=this.getOffsetForIndex(n,r);if(!i)return;const[a,c]=i,l=this.now();this.scrollState={index:n,align:c,behavior:s,startedAt:l,lastTargetOffset:a,stableFrames:0},this._scrollToOffset(a,{adjustments:void 0,behavior:s}),this.scheduleScrollReconcile()},this.scrollBy=(n,{behavior:r="auto"}={})=>{const s=this.getScrollOffset()+n,i=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:i,lastTargetOffset:s,stableFrames:0},this._scrollToOffset(s,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.getTotalSize=()=>{var n;const r=this.getMeasurements();let s;if(r.length===0)s=this.options.paddingStart;else if(this.options.lanes===1)s=((n=r[r.length-1])==null?void 0:n.end)??0;else{const i=Array(this.options.lanes).fill(null);let a=r.length-1;for(;a>=0&&i.some(c=>c===null);){const c=r[a];i[c.lane]===null&&(i[c.lane]=c.end),a--}s=Math.max(...i.filter(c=>c!==null))}return Math.max(s-this.options.scrollMargin+this.options.paddingEnd,0)},this._scrollToOffset=(n,{adjustments:r,behavior:s})=>{this.options.scrollToFn(n,{behavior:s,adjustments:r},this)},this.measure=()=>{this.itemSizeCache=new Map,this.laneAssignments=new Map,this.notify(!1)},this.setOptions(t)}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const r=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,s=r?r[0]:this.scrollState.lastTargetOffset,i=1,a=s!==this.scrollState.lastTargetOffset;if(!a&&xb(s,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=i){this.scrollState=null;return}}else this.scrollState.stableFrames=0,a&&(this.scrollState.lastTargetOffset=s,this.scrollState.behavior="auto",this._scrollToOffset(s,{adjustments:void 0,behavior:"auto"}));this.scheduleScrollReconcile()}}const zo=(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 Ab({measurements:e,outerSize:t,scrollOffset:n,lanes:r}){const s=e.length-1,i=l=>e[l].start;if(e.length<=r)return{startIndex:0,endIndex:s};let a=zo(0,s,i,n),c=a;if(r===1)for(;c<s&&e[c].end<n+t;)c++;else if(r>1){const l=Array(r).fill(0);for(;c<s&&l.some(d=>d<n+t);){const d=e[c];l[d.lane]=d.end,c++}const u=Array(r).fill(n+t);for(;a>=0&&u.some(d=>d>=n);){const d=e[a];u[d.lane]=d.start,a--}a=Math.max(0,a-a%r),c=Math.min(s,c+(r-1-c%r))}return{startIndex:a,endIndex:c}}const Di=typeof document<"u"?h.useLayoutEffect:h.useEffect;function Ib({useFlushSync:e=!0,...t}){const n=h.useReducer(()=>({}),{})[1],r={...t,onChange:(i,a)=>{var c;e&&a?fs.flushSync(n):n(),(c=t.onChange)==null||c.call(t,i,a)}},[s]=h.useState(()=>new Rb(r));return s.setOptions(r),Di(()=>s._didMount(),[]),Di(()=>s._willUpdate()),s}function Db(e){return Ib({observeElementRect:_b,observeElementOffset:Eb,scrollToFn:Nb,...e})}function hs({items:e,estimateSize:t,renderItem:n,overscan:r=5,className:s,height:i="100%",getItemKey:a}){const c=h.useRef(null),l=typeof t=="function"?t:()=>t,u=Db({count:e.length,getScrollElement:()=>c.current,estimateSize:l,overscan:r});return o.jsx("div",{ref:c,className:s,"data-pyric-ui":"virtual-list",style:{height:i,overflowY:"auto",contain:"strict"},children:o.jsx("div",{"data-pyric-virtual-inner":!0,style:{height:`${u.getTotalSize()}px`,width:"100%",position:"relative"},children:u.getVirtualItems().map(d=>{const p=e[d.index],f=a?a(p,d.index):d.key;return o.jsx("div",{"data-pyric-virtual-row":!0,"data-index":d.index,ref:u.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${d.start}px)`},children:n(p,d.index)},f)})})})}const Pb={batch:"batch write",transaction:"transaction","listener-run":"listener re-evals"};function $b({group:e,defaultExpanded:t=!1,onSelect:n,selectedId:r,renderClassification:s,formatTime:i,className:a}){const[c,l]=h.useState(t);return o.jsxs("div",{className:a,"data-pyric-traffic-group":"","data-pyric-group-kind":e.kind,"data-pyric-expanded":c?"":void 0,children:[o.jsxs("button",{type:"button",onClick:()=>l(u=>!u),"data-pyric-traffic-group-header":"","data-pyric-group-kind":e.kind,"aria-expanded":c,children:[o.jsx("span",{"data-pyric-group-kind-label":"",children:Pb[e.kind]}),o.jsxs("span",{"data-pyric-group-count":"",children:["×",e.count]}),e.denies>0?o.jsxs("span",{"data-pyric-group-denies":"",children:[e.denies," denied"]}):null]}),c?o.jsx("ul",{"data-pyric-traffic-group-members":"",children:e.events.map(u=>o.jsx("li",{"data-pyric-traffic-entry":"","data-pyric-traffic-id":u.id,children:o.jsx(Wo,{event:u,selected:u.id===r,onSelect:n,renderClassification:s,formatTime:i})},u.id))}):null]})}function Ob(e){return e<0?0:e>1?1:e}function Xn(e,t){const n=t.end-t.start;return n<=0?0:Ob((e-t.start)/n)}function Mb({events:e,buckets:t,window:n,bucketCount:r=30,brush:s,onBrush:i,renderBucketSummary:a,liveAt:c,header:l,axis:u,emptyState:d,className:p}){const f=h.useId(),[m,y]=h.useState(null),[g,v]=h.useState(null),b=ob({events:e??[],window:n,bucketCount:r}),w=t??b,{buckets:x,total:k}=w,j=m??g,S=j===null?null:x.find(_=>_.index===j)??null,N=S!==null&&s?.start===S.start&&s.end===S.end;if(x.length===0)return o.jsx("div",{className:p,"data-pyric-ui":"traffic-timeline","data-pyric-empty":"",children:d});const P=k===0,I=c===void 0?n.end:c,D=I==null?null:Xn(I,n),C=typeof u=="function"?u(n):u;return o.jsxs("div",{className:p,"data-pyric-ui":"traffic-timeline","data-pyric-empty":P?"":void 0,children:[l!==void 0&&o.jsx("div",{"data-pyric-timeline-header":"",children:l}),o.jsxs("div",{"data-pyric-timeline-chart":"",children:[o.jsx("div",{"data-pyric-timeline-bars":"",role:i?"group":"img","aria-label":"request volume over time",children:x.map(_=>o.jsx(Ub,{bucket:_,window:n,onBrush:i,onHover:a?y:void 0,onFocus:a?v:void 0,summaryId:a&&!N&&S?.index===_.index?f:void 0,selected:s?.start===_.start&&s.end===_.end},_.index))}),S&&a&&!N?o.jsx("div",{id:f,role:"tooltip","data-pyric-bucket-summary":"",style:{"--pyric-bucket-summary-x":(S.index+.5)/Math.max(x.length,1)},children:a(S)}):null,s&&o.jsx("div",{"data-pyric-brush":"","aria-hidden":"true",style:{"--pyric-brush-left":Xn(s.start,n),"--pyric-brush-right":1-Xn(s.end,n)}}),D!=null&&o.jsx("div",{"data-pyric-live":"","aria-hidden":"true",style:{"--pyric-live-x":D}})]}),C!=null&&o.jsx("div",{"data-pyric-timeline-axis":"",children:C})]})}function Ub({bucket:e,window:t,onBrush:n,onHover:r,onFocus:s,summaryId:i,selected:a}){const c=n!==void 0,l=`${e.count} ${e.count===1?"request":"requests"}`,u=`${e.denies} denied`;return o.jsxs("button",{type:"button","data-pyric-bucket":"","data-pyric-bucket-index":e.index,"data-pyric-bucket-count":e.count,"data-pyric-bucket-denies":e.denies,"data-pyric-has-denies":e.denies>0?"":void 0,"data-pyric-bucket-selected":a?"":void 0,disabled:!c,"aria-label":`${l}, ${u}`,"aria-describedby":i,"aria-pressed":c?a:void 0,onPointerEnter:r?()=>r(e.index):void 0,onPointerLeave:r?()=>r(null):void 0,onFocus:s?()=>s(e.index):void 0,onBlur:s?()=>s(null):void 0,onClick:c?()=>n?.({start:e.start,end:e.end}):void 0,style:{"--pyric-bucket-h":e.heightRatio,"--pyric-bucket-deny-h":e.denyHeightRatio},children:[o.jsx("span",{"data-pyric-bucket-allow":"","aria-hidden":"true"}),o.jsx("span",{"data-pyric-bucket-deny":"","aria-hidden":"true"})]})}const Tb=e=>String(e);function Bb({series:e,visible:t,onToggle:n,formatValue:r=Tb,className:s}){const i=t!==void 0&&n!==void 0;return o.jsx("div",{className:s,"data-pyric-ui":"traffic-metric-cards",role:i?"group":void 0,children:e.map((a,c)=>{const l=t?t.has(a.key):!0,u=o.jsxs(o.Fragment,{children:[o.jsx("span",{"data-pyric-metric-swatch":"","aria-hidden":"true"}),o.jsx("span",{"data-pyric-metric-label":"",children:a.label}),o.jsx("span",{"data-pyric-metric-value":"",children:r(a.total)})]});return i?o.jsxs("label",{"data-pyric-metric-card":"","data-pyric-metric-key":a.key,"data-pyric-series-index":c,"data-pyric-metric-hidden":l?void 0:"",children:[o.jsx("input",{type:"checkbox",checked:l,onChange:()=>n(a.key),"data-pyric-metric-checkbox":""}),u]},a.key):o.jsx("span",{"data-pyric-metric-card":"","data-pyric-metric-key":a.key,"data-pyric-series-index":c,children:u},a.key)})})}const Lb=e=>String(e),Fb=e=>new Date(e).toLocaleTimeString();function Vb({points:e,series:t,visible:n,omitZeroSeries:r=!1,formatValue:s=Lb,formatTime:i=Fb,emptyState:a,className:c}){const[l,u]=h.useState(null);if(e.length===0)return o.jsx("div",{className:c,"data-pyric-ui":"traffic-line-chart","data-pyric-empty":"",children:a});const d=t.filter(b=>(!n||n.has(b.key))&&(!r||b.total>0));let p=0;for(const b of d)for(const w of b.values)w>p&&(p=w);const f=p===0?1:p,m=e.length,y=b=>m===1?50:b/(m-1)*100,g=b=>100-b/f*100,v=l!=null?e[l]:null;return o.jsx("div",{className:c,"data-pyric-ui":"traffic-line-chart",children:o.jsxs("div",{"data-pyric-chart-svg":"",children:[o.jsx("svg",{viewBox:"0 0 100 100",preserveAspectRatio:"none",role:"img","aria-label":"metrics over time",children:t.map(b=>{const w=t.indexOf(b);if(!((!n||n.has(b.key))&&(!r||b.total>0)))return null;const k=b.values.map((j,S)=>`${S===0?"M":"L"}${y(S)},${g(j)}`).join(" ");return o.jsx("path",{"data-pyric-chart-line":"","data-pyric-series-key":b.key,"data-pyric-series-index":w,d:k,fill:"none",vectorEffect:"non-scaling-stroke"},b.key)})}),o.jsx("div",{"data-pyric-chart-hits":"",children:e.map((b,w)=>o.jsx("button",{type:"button","data-pyric-chart-hit":"","data-pyric-point-index":w,onMouseEnter:()=>u(w),onFocus:()=>u(w),onMouseLeave:()=>u(x=>x===w?null:x),onBlur:()=>u(x=>x===w?null:x),"aria-label":`${i(b.start)} to ${i(b.end)}`},b.index))}),v&&o.jsxs("div",{"data-pyric-chart-tooltip":"",style:{"--pyric-hover-x":y(v.index)},children:[o.jsxs("div",{"data-pyric-tooltip-time":"",children:[i(v.start)," – ",i(v.end)]}),d.map(b=>o.jsxs("div",{"data-pyric-tooltip-row":"","data-pyric-series-key":b.key,"data-pyric-series-index":t.indexOf(b),children:[o.jsx("span",{"data-pyric-tooltip-label":"",children:b.label}),o.jsx("span",{"data-pyric-tooltip-value":"",children:s(b.values[v.index])})]},b.key))]})]})})}const qb={listUsers:fe.listUsers,subscribeUsers:fe.subscribeUsers,createUser:fe.createUser,updateUser:fe.updateUser,deleteUser:fe.deleteUser,clearUsers:fe.clearUsers,getAuthProviderConfig:fe.getAuthProviderConfig,setAuthProviderConfig:fe.setAuthProviderConfig,subscribeAuthProviderConfig:fe.subscribeAuthProviderConfig},Ko=h.createContext(qb);function Wb(){return h.useContext(Ko)}function Ho({value:e,children:t}){return h.createElement(Ko.Provider,{value:e},t)}function zb(e,t){return[e.uid,e.email,e.displayName,e.phoneNumber].some(n=>n!=null&&n.toLowerCase().includes(t))}function ps(e){const{listUsers:t,subscribeUsers:n,createUser:r,updateUser:s,deleteUser:i,clearUsers:a}=Wb(),[c,l]=h.useState([]),[u,d]=h.useState(!0),[p,f]=h.useState(void 0),[m,y]=h.useState("");h.useEffect(()=>{let j=!1;d(!0),f(void 0);const S=D=>{j||(l(D),d(!1))},N=D=>{j||(l([]),f(D instanceof Error?D:new Error(String(D))),d(!1))},P=()=>{try{const D=t(e);D&&typeof D.then=="function"?D.then(S).catch(N):S(D)}catch(D){N(D)}};let I;try{P(),I=n(e,P)}catch(D){N(D)}return()=>{j=!0,I?.()}},[e,t,n]);const g=h.useMemo(()=>{const j=m.trim().toLowerCase();return j?c.filter(S=>zb(S,j)):c},[c,m]),v=h.useCallback(j=>r(e,j),[e,r]),b=h.useCallback((j,S)=>s(e,j,S),[e,s]),w=h.useCallback(j=>i(e,j),[e,i]),x=h.useCallback(()=>a(e),[e,a]),k=h.useCallback(()=>{const j=t(e);j&&typeof j.then=="function"?j.then(S=>l(S)).catch(()=>{}):l(j)},[e,t]);return{users:g,totalCount:c.length,isLoading:u,error:p,filter:m,setFilter:y,createUser:v,updateUser:b,deleteUser:w,clearUsers:x,refresh:k}}const Kb=["iss","aud","sub","iat","exp","nbf","jti","nonce","azp","acr","amr","cnf","auth_time","firebase","at_hash","c_hash"],Hb=1e3;function Go(e){const t=e.trim();if(!t)return{ok:!0,claims:void 0};if(t.length>Hb)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 Kb)if(r in n)return{ok:!1,message:`Custom claims must not have forbidden key: ${r}`};return{ok:!0,claims:n}}const Gb={email:"",password:"",displayName:"",phoneNumber:"",photoUrl:"",emailVerified:!1,disabled:!1,claimsText:"",providerIds:[]},Jb=new Set(["password","anonymous","phone"]),Yb=/^[^@]+@[^@]+\.[^@]+$/,Pi=6;function Qb(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=>!Jb.has(t))}:{...Gb}}function Xb(e){const t=Qb(e);return{fields:t,initial:{...t}}}function Zb(e,t){switch(t.type){case"setField":return{...e,fields:{...e.fields,[t.field]:t.value}};case"reset":return{...e,fields:{...e.initial}}}}function eg(e){const t={},n=e.email.trim(),r=e.password;n&&!Yb.test(n)&&(t.email="Invalid email"),r&&r.length<Pi&&(t.password=`Password should be at least ${Pi} characters`),r&&!n&&(t.password="Email is required for password authentication");const s=Go(e.claimsText);return s.ok||(t.claims=s.message),t}function tg(e){const{fields:t,initial:n}=e;return Object.keys(t).some(r=>r==="providerIds"?!Jo(t.providerIds,n.providerIds):t[r]!==n[r])}function Jo(e,t){if(e.length!==t.length)return!1;const n=[...t].sort();return[...e].sort().every((r,s)=>r===n[s])}function Yo(e){const t=Go(e.claimsText);return t.ok?t.claims:void 0}function ng(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=Yo(t);return r&&(n.customClaims=r),t.providerIds.length&&(n.providerUserInfo=t.providerIds.map(s=>({providerId:s}))),n}function rg(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=Yo(t)??{}),Jo(t.providerIds,n.providerIds)||(r.providerUserInfo=t.providerIds.map(s=>({providerId:s}))),r}function Qo(e={}){const[t,n]=h.useReducer(Zb,e.initial,Xb),r=h.useMemo(()=>eg(t.fields),[t.fields]),s=h.useMemo(()=>tg(t),[t]),i=h.useCallback((c,l)=>n({type:"setField",field:c,value:l}),[]),a=h.useCallback(()=>n({type:"reset"}),[]);return{fields:t.fields,errors:r,isDirty:s,isValid:Object.keys(r).length===0,setField:i,reset:a,toCreateRequest:()=>ng(t),toUpdateRequest:()=>rg(t),dispatch:n}}const sg={"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 mn(e){return sg[e]??e}function $i(e){return e.email??e.phoneNumber??(e.isAnonymous?"anonymous":e.uid)}function ig(e){return e.isAnonymous&&e.providerUserInfo.length===0?o.jsx("span",{"data-pyric-provider-id":"anonymous",children:mn("anonymous")}):e.providerUserInfo.map(t=>o.jsx("span",{"data-pyric-provider-id":t.providerId,children:mn(t.providerId)},t.providerId))}function Oi(e){if(!e)return"—";const t=new Date(e);return Number.isNaN(t.getTime())?"—":t.toLocaleDateString()}function Xo({users:e,isLoading:t,error:n,filter:r,onSelect:s,renderIdentifier:i,renderProviders:a,renderSelection:c,renderSelectionHeader:l,renderActions:u,renderActionsHeader:d,formatCreatedAt:p=Oi,formatLastLoginAt:f=Oi,emptyState:m,noResultsState:y,className:g,virtualizeThreshold:v=100,rowHeight:b=44,virtualizedHeight:w="60vh"}){if(n)return o.jsx("div",{className:g,"data-pyric-ui":"auth-user-list","data-pyric-error":"",role:"alert",children:n.message});if(t&&e.length===0)return o.jsx("div",{className:g,"data-pyric-ui":"auth-user-list","data-pyric-loading":""});if(e.length===0){const j=!!r?.trim();return o.jsx("div",{className:g,"data-pyric-ui":"auth-user-list","data-pyric-empty":"","data-pyric-no-results":j?"":void 0,children:j?y??"No results":m??"No users for this project yet"})}const x=e.length>v,k=j=>o.jsxs("div",{role:"row","data-pyric-user-entry":!0,"data-pyric-user-uid":j.uid,"data-pyric-user-disabled":j.disabled?"":void 0,children:[c?o.jsx("span",{role:"cell","data-pyric-user-cell":"selection",children:c(j)}):null,o.jsx("span",{role:"cell","data-pyric-user-cell":"identifier",children:s?o.jsx("button",{type:"button","data-pyric-user-select":!0,onClick:()=>s(j),children:i?i(j):$i(j)}):(i??$i)(j)}),o.jsx("span",{role:"cell","data-pyric-user-cell":"providers",children:(a??ig)(j)}),o.jsx("span",{role:"cell","data-pyric-user-cell":"created",children:p(j.createdAt)}),o.jsx("span",{role:"cell","data-pyric-user-cell":"signed-in",children:f(j.lastLoginAt)}),o.jsx("span",{role:"cell","data-pyric-user-cell":"uid",children:j.uid}),u?o.jsx("span",{role:"cell","data-pyric-user-cell":"actions",children:u(j)}):null]},j.uid);return o.jsxs("div",{className:g,role:"table","aria-label":"Authentication users","data-pyric-ui":"auth-user-list","data-pyric-virtualized":x?"":void 0,"data-pyric-selection":c?"":void 0,"data-pyric-actions":u?"":void 0,children:[o.jsxs("div",{role:"row","data-pyric-user-header":!0,children:[c?o.jsx("span",{role:"columnheader","data-pyric-user-cell":"selection","aria-label":"Selection",children:l}):null,o.jsx("span",{role:"columnheader","data-pyric-user-cell":"identifier",children:"Identifier"}),o.jsx("span",{role:"columnheader","data-pyric-user-cell":"providers",children:"Provider"}),o.jsx("span",{role:"columnheader","data-pyric-user-cell":"created",children:"Created"}),o.jsx("span",{role:"columnheader","data-pyric-user-cell":"signed-in",children:"Signed In"}),o.jsx("span",{role:"columnheader","data-pyric-user-cell":"uid",children:"User UID"}),u?o.jsx("span",{role:"columnheader","data-pyric-user-cell":"actions","aria-label":"Actions",children:d}):null]}),x?o.jsx(hs,{items:e,estimateSize:b,height:w,getItemKey:j=>j.uid,renderItem:k}):o.jsx("div",{role:"rowgroup","data-pyric-user-rows":!0,children:e.map(k)})]})}function ag({value:e,onChange:t,error:n,hint:r,placeholder:s='{"role":"admin"}',className:i}){return o.jsxs("div",{className:i,"data-pyric-ui":"claims-field",children:[o.jsx("textarea",{"data-pyric-field":"claims","data-pyric-claims-invalid":n!=null?"":void 0,"aria-label":"Custom claims (optional)","aria-invalid":n!=null||void 0,placeholder:s,value:e,onChange:a=>t(a.target.value)}),n!=null&&o.jsx("p",{role:"alert","data-pyric-claims-error":!0,children:n}),r!=null&&o.jsx("p",{"data-pyric-claims-hint":!0,children:r})]})}function og({selected:e,onChange:t}){return o.jsx("div",{"data-pyric-provider-checklist":!0,children:Do.map(n=>o.jsxs("label",{"data-pyric-provider-option":n,children:[o.jsx("input",{type:"checkbox",checked:e.includes(n),onChange:r=>t(r.target.checked?[...e,n]:e.filter(s=>s!==n))}),o.jsx("span",{"data-pyric-provider-option-label":!0,children:mn(n)}),o.jsx("span",{"data-pyric-provider-option-id":!0,children:n})]},n))})}function Zo({initial:e,onSubmit:t,onCancel:n,submitLabel:r="Save",cancelLabel:s="Cancel",children:i,className:a,renderField:c}){const l=Qo({initial:e}),u=e?"edit":"create",d=l.isValid&&(u==="create"||l.isDirty),p=(y,g,v,b,w=null)=>({name:y,label:g,input:b,error:w,kind:v,defaultRender:()=>v==="checkbox"?o.jsxs("label",{"data-pyric-field-label":y,children:[b,o.jsx("span",{"data-pyric-label-text":!0,children:g})]},y):v==="group"?o.jsxs("fieldset",{"data-pyric-field-label":y,children:[o.jsx("legend",{"data-pyric-label-text":!0,children:g}),b]},y):o.jsxs("label",{"data-pyric-field-label":y,children:[o.jsx("span",{"data-pyric-label-text":!0,children:g}),b,w!=null&&o.jsx("p",{role:"alert","data-pyric-field-error":y,children:w})]},y)}),f=[p("email","Email","text",o.jsx("input",{type:"email","data-pyric-field":"email",placeholder:"email@example.com",value:l.fields.email,onChange:y=>l.setField("email",y.target.value)}),l.errors.email??null),p("password","Password","text",o.jsx("input",{type:"password","data-pyric-field":"password",placeholder:u==="edit"?"New password (unchanged if empty)":"Password",value:l.fields.password,onChange:y=>l.setField("password",y.target.value)}),l.errors.password??null),p("display-name","Display name","text",o.jsx("input",{type:"text","data-pyric-field":"display-name",placeholder:"Display name (optional)",value:l.fields.displayName,onChange:y=>l.setField("displayName",y.target.value)})),p("phone-number","Phone number","text",o.jsx("input",{type:"tel","data-pyric-field":"phone-number",placeholder:"+1 555 555 0100",value:l.fields.phoneNumber,onChange:y=>l.setField("phoneNumber",y.target.value)})),p("photo-url","Photo URL","text",o.jsx("input",{type:"url","data-pyric-field":"photo-url",placeholder:"https://example.com/avatar.png",value:l.fields.photoUrl,onChange:y=>l.setField("photoUrl",y.target.value)})),...u==="create"?[p("providers","Sign-in providers","group",o.jsx(og,{selected:l.fields.providerIds,onChange:y=>l.setField("providerIds",y)}))]:[],p("email-verified","Verified email","checkbox",o.jsx("input",{type:"checkbox","data-pyric-field":"email-verified",checked:l.fields.emailVerified,onChange:y=>l.setField("emailVerified",y.target.checked)})),p("disabled","Disabled (sign-in attempts are rejected)","checkbox",o.jsx("input",{type:"checkbox","data-pyric-field":"disabled",checked:l.fields.disabled,onChange:y=>l.setField("disabled",y.target.checked)}))],m=y=>{y.preventDefault(),d&&t(u==="edit"?{mode:u,uid:e.uid,request:l.toUpdateRequest()}:{mode:u,request:l.toCreateRequest()})};return o.jsxs("form",{className:a,"data-pyric-ui":"auth-user-form","data-pyric-mode":u,"data-pyric-is-dirty":l.isDirty?"":void 0,"data-pyric-is-valid":l.isValid?"":void 0,onSubmit:m,children:[f.map(y=>c?o.jsx(h.Fragment,{children:c(y)},y.name):y.defaultRender()),o.jsx(ag,{value:l.fields.claimsText,onChange:y=>l.setField("claimsText",y),error:l.errors.claims}),i,o.jsxs("footer",{"data-pyric-form-actions":!0,children:[n?o.jsx("button",{type:"button","data-pyric-cancel":!0,onClick:n,children:s}):null,o.jsx("button",{type:"submit","data-pyric-submit":!0,disabled:!d,children:r})]})]})}function cg({open:e,onOpenChange:t,title:n,body:r,destructive:s,confirmLabel:i="Confirm",cancelLabel:a="Cancel",onConfirm:c,className:l}){const u=h.useRef(null),d=h.useRef(null);return h.useEffect(()=>{if(!e)return;const p=f=>{f.key==="Escape"&&(f.stopPropagation(),t(!1))};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[e,t]),h.useEffect(()=>{if(e)return d.current=document.activeElement,u.current?.focus(),()=>{d.current?.focus?.()}},[e]),!e||typeof document>"u"?null:fs.createPortal(o.jsxs("div",{role:"presentation","data-pyric-ui":"confirm-portal",onClick:p=>{p.target===p.currentTarget&&t(!1)},children:[o.jsx("div",{"data-pyric-ui":"confirm-overlay","aria-hidden":"true"}),o.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"pyric-confirm-title","aria-describedby":r?"pyric-confirm-body":void 0,className:l,"data-pyric-ui":"confirm-dialog","data-pyric-destructive":s?"":void 0,children:[o.jsx("div",{id:"pyric-confirm-title","data-pyric-confirm-title":!0,children:n}),r?o.jsx("div",{id:"pyric-confirm-body","data-pyric-confirm-body":!0,children:r}):null,o.jsxs("div",{"data-pyric-confirm-actions":!0,children:[o.jsx("button",{type:"button","data-pyric-confirm-cancel":!0,onClick:()=>t(!1),children:a}),o.jsx("button",{ref:u,type:"button","data-pyric-confirm-confirm":!0,"data-pyric-destructive":s?"":void 0,onClick:c,children:i})]})]})]}),document.body)}const ec=h.createContext(null);function yt(){const e=h.useContext(ec);if(!e)throw new Error("useConfirm: missing <ConfirmProvider> ancestor");return e}function ms({children:e,dialogClassName:t}){const[n,r]=h.useState(null),s=h.useRef(!1),i=h.useCallback(u=>new Promise(d=>{s.current=!1,r({options:u,resolve:d})}),[]),a=h.useCallback(()=>{n&&(s.current||(s.current=!0,n.resolve(!0),r(null)))},[n]),c=h.useCallback(u=>{u||n&&(s.current||(s.current=!0,n.resolve(!1),r(null)))},[n]),l=h.useMemo(()=>i,[i]);return o.jsxs(ec.Provider,{value:l,children:[e,n?o.jsx(cg,{open:!0,onOpenChange:c,title:n.options.title,body:n.options.body,destructive:n.options.destructive,confirmLabel:n.options.confirmLabel,cancelLabel:n.options.cancelLabel,onConfirm:a,className:t}):null]})}function lg(e){return e.email??e.phoneNumber??e.displayName??e.uid}function ug({user:e,onDelete:t,title:n="Delete user",body:r,confirmLabel:s="Delete",renderTrigger:i,className:a}){const c=yt(),l=async()=>{await c({title:n,body:r??`This will permanently delete ${lg(e)}.`,destructive:!0,confirmLabel:s})&&t(e.uid)};return i?o.jsx(o.Fragment,{children:i({onClick:l})}):o.jsx("button",{type:"button",className:a,"data-pyric-ui":"delete-user","data-pyric-destructive":!0,onClick:l,children:"Delete user"})}function dg(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 fg={addDoc:Ca,collection:_t,deleteDoc:ar,doc:Le,getDoc:qa,getDocs:on,limit:ln,onSnapshot:ud,query:cn,setDoc:en,startAfter:ld},tc=h.createContext(fg);function ys(){return h.useContext(tc)}function hg({value:e,children:t}){return h.createElement(tc.Provider,{value:e},t)}function pg(e){const{onSnapshot:t}=ys(),[n,r]=h.useState(()=>({data:void 0,error:void 0,isLoading:e!=null}));return h.useEffect(()=>{if(!e){r({data:void 0,error:void 0,isLoading:!1});return}return r(i=>({data:i.data,error:void 0,isLoading:!0})),t(e,i=>r({data:i,error:void 0,isLoading:!1}),i=>r({data:void 0,error:dg(i),isLoading:!1}))},[t,e]),n}function $n(e){return e==null?"null":typeof e=="string"?"string":typeof e=="number"?"number":typeof e=="boolean"?"boolean":typeof e=="object"&&Ge(e)!==null?"vector":Array.isArray(e)?"array":e instanceof ut?"timestamp":e instanceof it?"geopoint":e instanceof kn?"bytes":typeof e=="object"&&nc(e)?"timestamp":typeof e=="object"&&rc(e)?"geopoint":typeof e=="object"&&mg(e)?"reference":typeof e=="object"?"map":"null"}function nc(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 rc(e){const t=e;return Object.keys(t).length===2&&typeof t.latitude=="number"&&typeof t.longitude=="number"}function mg(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 Ge(e){if(e===null||typeof e!="object")return null;const t=e;if(t.typeName==="vector"&&Kt(t.value)||t.__type__==="__vector__"&&Kt(t.value))return Ht(t.value);if(Kt(t._values))return Ht(t._values);if(typeof t.toArray=="function")try{const n=t.toArray();if(Kt(n))return Ht(n)}catch{}return null}function Kt(e){return Array.isArray(e)&&e.every(t=>typeof t=="number")}function Ht(e){const t=e.slice();return{values:t,dimension:t.length}}const Mi=4;function sc(e){const t=e.values.slice(0,Mi).join(", "),n=e.values.length>Mi?", …":"";return`vector · ${e.dimension} [${t}${n}]`}function yn(e){const t=Ge(e);if(t)return sc(t);if(Array.isArray(e))return e.map(yn);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]=yn(i);return r}}return e}function ic(){return crypto.randomUUID()}function yg(e){const t=ic(),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))Pr(n,t,r,s);return n}function Pr(e,t,n,r){const s=$n(r),i=ic(),a={id:i,parentId:t,key:n,type:s,value:bg(s)?void 0:r};if(e.nodes[i]=a,e.childIds[i]=[],e.childIds[t].push(i),s==="map"&&r&&typeof r=="object")for(const[c,l]of Object.entries(r))Pr(e,i,c,l);else if(s==="array"&&Array.isArray(r))for(const c of r)Pr(e,i,null,c);return i}function bg(e){return e==="map"||e==="array"}function ac(e){const t=e.nodes[e.rootId];if(!t||t.type!=="map")throw new Error("treeToData: tree root must be a map node");return $r(e,e.rootId)}function $r(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]=$r(e,s))}return r}case"array":{const r=[];for(const s of e.childIds[t]??[])r.push($r(e,s));return r}default:return n.value}}function Or(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 oc(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 cc(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 ut?void 0:"Expected a Timestamp";case"geopoint":return t instanceof it?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 kn?void 0:"Expected a Bytes value";case"vector":return Ge(t)!==null?void 0:"Expected a vector value";case"map":case"array":return}}function lc(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=cc(r.type,r.value);s&&(t[r.id].error=s,n++)}for(const[r,s]of Object.entries(t)){if(s.type!=="map")continue;const i=e.childIds[r]??[],a=new Map;for(const c of i){const l=t[c];if(!l)continue;const u=l.key??"";u||(l.error||n++,t[c].error=t[c].error??"Field name is required");const d=a.get(u)??[];d.push(c),a.set(u,d)}for(const[c,l]of a)if(c&&l.length>1)for(const u of l)t[u].error||n++,t[u].error=t[u].error??"Field name must be unique"}return{tree:{rootId:e.rootId,nodes:t,childIds:e.childIds},errorCount:n}}function bs(e){switch(e){case"string":return"";case"number":return 0;case"boolean":return!1;case"null":return null;case"timestamp":return ut.now();case"geopoint":return new it(0,0);case"reference":return{path:"",id:"",firestore:{}};case"bytes":return kn.fromUint8Array(new Uint8Array);case"vector":return{__type__:"__vector__",value:[]};case"map":case"array":return}}function Mr(e){if(e===null||typeof e!="object"||Ge(e)!==null)return e;if(nc(e)){const n=e;return new ut(n.seconds??n._seconds??0,n.nanoseconds??n._nanoseconds??0)}if(rc(e)){const n=e;return new it(n.latitude,n.longitude)}if(Array.isArray(e))return e.map(Mr);const t=Object.getPrototypeOf(e);if(t===Object.prototype||t===null){const n={};for(const[r,s]of Object.entries(e))n[r]=Mr(s);return n}return e}function uc(e){const t=yg(Mr(e)),{tree:n,errorCount:r}=lc(t);return{tree:n,initial:n,errorCount:r}}function gg(e,t){switch(t.type){case"setValue":return Xe(e,n=>wg(n,t.nodeId,t.value));case"setType":return Xe(e,n=>xg(n,t.nodeId,t.newType));case"setKey":return Xe(e,n=>jg(n,t.nodeId,t.key));case"addMapEntry":return Xe(e,n=>kg(n,t.parentId,t.key,t.childType));case"addArrayEntry":return Xe(e,n=>Sg(n,t.parentId,t.childType));case"remove":return Xe(e,n=>_g(n,t.nodeId));case"reset":return{tree:e.initial,initial:e.initial,errorCount:vg(e.initial)};case"replaceData":return uc(t.data);case"touch":{const n=e.tree.nodes[t.nodeId];if(!n||n.touched)return e;const r=Or(e.tree);return r.nodes[t.nodeId]={...r.nodes[t.nodeId],touched:!0},{...e,tree:r}}case"touchAll":{const n=Or(e.tree);for(const r of Object.keys(n.nodes))n.nodes[r]={...n.nodes[r],touched:!0};return{...e,tree:n}}}}function Xe(e,t){const n=t(Or(e.tree)),{tree:r,errorCount:s}=lc(n);return{...e,tree:r,errorCount:s}}function vg(e){let t=0;for(const n of Object.values(e.nodes))n.error&&t++;return t}function wg(e,t,n){const r=e.nodes[t];return!r||r.type==="map"||r.type==="array"||(e.nodes[t]={...r,value:n}),e}function xg(e,t,n){const r=e.nodes[t];if(!r||r.id===e.rootId&&n!=="map"||r.type===n)return e;if(r.type==="map"||r.type==="array"){const i=(e.childIds[t]??[]).slice();for(const a of i)for(const c of oc(e,a))delete e.nodes[c],delete e.childIds[c];e.childIds[t]=[]}const s=n==="map"||n==="array"?void 0:bs(n);return e.nodes[t]={...r,type:n,value:s},e}function jg(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 kg(e,t,n,r){const s=e.nodes[t];if(!s||s.type!=="map")return e;const i=crypto.randomUUID(),a=r==="map"||r==="array"?void 0:bs(r);return e.nodes[i]={id:i,parentId:t,key:n,type:r,value:a},e.childIds[i]=[],e.childIds[t]=[...e.childIds[t]??[],i],e}function Sg(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:bs(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 _g(e,t){const n=e.nodes[t];if(!n||n.id===e.rootId)return e;const r=oc(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 dc(e={}){const t=e.initial??{},n=h.useRef(null);n.current==null&&(n.current=uc(t));const[r,s]=h.useReducer(gg,n.current),i=h.useCallback((w,x)=>s({type:"setValue",nodeId:w,value:x}),[]),a=h.useCallback((w,x)=>s({type:"setType",nodeId:w,newType:x}),[]),c=h.useCallback((w,x)=>s({type:"setKey",nodeId:w,key:x}),[]),l=h.useCallback((w,x,k)=>s({type:"addMapEntry",parentId:w,key:x,childType:k}),[]),u=h.useCallback((w,x)=>s({type:"addArrayEntry",parentId:w,childType:x}),[]),d=h.useCallback(w=>s({type:"remove",nodeId:w}),[]),p=h.useCallback(()=>s({type:"reset"}),[]),f=h.useCallback(w=>s({type:"replaceData",data:w}),[]),m=h.useCallback(w=>s({type:"touch",nodeId:w}),[]),y=h.useCallback(()=>s({type:"touchAll"}),[]),g=h.useCallback(()=>ac(r.tree),[r.tree]),v=r.tree!==r.initial,b=r.errorCount===0;return h.useMemo(()=>({...r,isDirty:v,isValid:b,dispatch:s,setValue:i,setType:a,setKey:c,addMapEntry:l,addArrayEntry:u,remove:d,reset:p,replaceData:f,touch:m,touchAll:y,toData:g}),[r,v,b,i,a,c,l,u,d,p,f,m,y,g])}function Eg({collection:e,query:t,pageSize:n=50,mode:r="paged"}){const[s,i]=h.useState([]),[a,c]=h.useState(!0),[l,u]=h.useState(void 0),[d,p]=h.useState(!1),[f,m]=h.useState(0),[y,g]=h.useState(n),v=h.useRef(0),[b,w]=h.useState(0),{addDoc:x,deleteDoc:k,doc:j,getDoc:S,getDocs:N,limit:P,onSnapshot:I,query:D,setDoc:C,startAfter:_}=ys();h.useEffect(()=>{g(n)},[e,r,n,t]),h.useEffect(()=>{let A=!1;r==="paged"&&i([]),p(!1),c(!0),u(void 0);const O=t??e,M=r==="live"?y:n,$=D(O,P(M)),Y=ne=>{A||(i([...ne.docs]),p(ne.docs.length===M),c(!1))},se=ne=>{A||(u(ne instanceof Error?ne:new Error(String(ne))),c(!1))};if(r==="live"){const ne=++v.current,rl=I($,sl=>{w(ne),Y(sl)},se);return()=>{A=!0,rl()}}return N($).then(ne=>{Y(ne)}).catch(se),()=>{A=!0}},[e,N,P,r,I,n,t,D,y,f]);const E=h.useCallback(()=>{if(!d||a)return;if(r==="live"){c(!0),g($=>$+n);return}const A=s[s.length-1];if(!A)return;c(!0);const M=D(t??e,_(A),P(n));N(M).then($=>{i(Y=>[...Y,...$.docs]),p($.docs.length===n),c(!1)}).catch($=>{u($ instanceof Error?$:new Error(String($))),c(!1)})},[e,s,N,d,a,P,r,n,t,D,_]),R=h.useCallback(async(A,O,M)=>{if(A==null){const Y=await x(e,O);return r==="paged"&&m(se=>se+1),Y}const $=j(e,A);if(M?.onExisting==="fail"){const Y=await S($);if(typeof Y.exists=="function"?Y.exists():!!Y.exists){const ne=new Error(`Document "${A}" already exists.`);throw ne.code="already-exists",ne}}return await C($,O),r==="paged"&&m(Y=>Y+1),$},[x,e,j,S,r,C]),V=h.useCallback(async A=>{await k(A),r==="paged"&&m(O=>O+1)},[k,r]),G=h.useCallback(()=>m(A=>A+1),[]);return{documents:s,isLoading:a,error:l,subscriptionGeneration:b,hasMore:d,loadMore:E,createDocument:R,deleteDocument:V,refresh:G}}function Cg({firestore:e,documentRef:t,listSubcollections:n}){const[r,s]=h.useState([]),[i,a]=h.useState(!1),[c,l]=h.useState(void 0),u=h.useRef(n);u.current=n;const d=t?.path;return h.useEffect(()=>{if(!t){s([]),a(!1),l(void 0);return}let p=!1;return a(!0),l(void 0),u.current(e,t).then(f=>{p||(s(f),a(!1))}).catch(f=>{p||(l(f instanceof Error?f:new Error(String(f))),a(!1))}),()=>{p=!0}},[e,d]),{subcollections:r,isLoading:i,error:c}}function Ui(e){return typeof e=="object"&&e!==null&&"isEqual"in e&&typeof e.isEqual=="function"}function Ti(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function bn(e,t){if(Object.is(e,t))return!0;if(Ui(e))return e.isEqual(t);if(Ui(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)=>bn(s,t[i]));if(!Ti(e)||!Ti(t))return!1;const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(s=>s in t&&bn(e[s],t[s]))}function Ng({value:e,path:t}){return o.jsx("span",{"data-pyric-field-type":"string","data-pyric-field-path":t,children:e})}function Rg({value:e,onChange:t,error:n,path:r}){return o.jsxs("label",{"data-pyric-field-type":"string","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[o.jsx("input",{type:"text",value:e,onChange:s=>t(s.target.value),"aria-invalid":n?"true":void 0}),n?o.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const Ag={type:"string",Display:Ng,Edit:Rg};function Ig({value:e,path:t}){return o.jsx("span",{"data-pyric-field-type":"number","data-pyric-field-path":t,children:String(e)})}function Dg({value:e,onChange:t,error:n,path:r}){return o.jsxs("label",{"data-pyric-field-type":"number","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[o.jsx("input",{type:"number",value:Number.isFinite(e)?e:"",onChange:s=>{const i=s.target.value,a=i===""?Number.NaN:parseFloat(i);t(a)},"aria-invalid":n?"true":void 0}),n?o.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const Pg={type:"number",Display:Ig,Edit:Dg};function $g({value:e,path:t}){return o.jsx("span",{"data-pyric-field-type":"boolean","data-pyric-field-path":t,"data-value":e?"true":"false",children:e?"true":"false"})}function Og({value:e,onChange:t,path:n}){return o.jsx("span",{"data-pyric-field-type":"boolean","data-pyric-field-path":n,"data-value":e?"true":"false",children:o.jsxs("select",{value:e?"true":"false",onChange:r=>t(r.target.value==="true"),"aria-label":"Boolean value","data-pyric-boolean-select":!0,children:[o.jsx("option",{value:"true",children:"true"}),o.jsx("option",{value:"false",children:"false"})]})})}const Mg={type:"boolean",Display:$g,Edit:Og};function Ug({path:e}){return o.jsx("span",{"data-pyric-field-type":"null","data-pyric-field-path":e,children:"null"})}function Tg({path:e}){return o.jsx("span",{"data-pyric-field-type":"null","data-pyric-field-path":e,children:"null"})}const Bg={type:"null",Display:Ug,Edit:Tg};function fc(e){if(e instanceof ut)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 Lg({value:e,path:t}){const n=fc(e),r=Number.isNaN(n.getTime())?"":n.toISOString();return o.jsx("time",{dateTime:r,"data-pyric-field-type":"timestamp","data-pyric-field-path":t,children:r})}function Fg({value:e,onChange:t,error:n,path:r}){const s=fc(e),i=new Date(s.getTime()-s.getTimezoneOffset()*6e4),a=Number.isNaN(i.getTime())?"":i.toISOString().slice(0,16);return o.jsxs("label",{"data-pyric-field-type":"timestamp","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[o.jsx("input",{type:"datetime-local",value:a,onChange:c=>{const l=c.target.value;if(!l)return;const u=new Date(l);t(ut.fromDate(u))},"aria-invalid":n?"true":void 0}),n?o.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const Vg={type:"timestamp",Display:Lg,Edit:Fg};function qg({value:e,path:t}){return o.jsxs("span",{"data-pyric-field-type":"geopoint","data-pyric-field-path":t,"data-lat":String(e.latitude),"data-lng":String(e.longitude),children:[e.latitude,", ",e.longitude]})}function Wg({value:e,onChange:t,error:n,path:r}){return o.jsxs("span",{"data-pyric-field-type":"geopoint","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[o.jsx("label",{children:o.jsx("input",{type:"number",step:"any",min:-90,max:90,value:e.latitude,onChange:s=>{const i=parseFloat(s.target.value);try{t(new it(i,e.longitude))}catch{}},"aria-label":"Latitude"})}),o.jsx("label",{children:o.jsx("input",{type:"number",step:"any",min:-180,max:180,value:e.longitude,onChange:s=>{const i=parseFloat(s.target.value);try{t(new it(e.latitude,i))}catch{}},"aria-label":"Longitude"})}),n?o.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const zg={type:"geopoint",Display:qg,Edit:Wg},hc=h.createContext({});hc.Provider;function Kg(){return h.useContext(hc)}function Hg({value:e,path:t}){const{onReferenceClick:n}=Kg();return n?o.jsx("button",{type:"button",onClick:()=>n(e),"data-pyric-field-type":"reference","data-pyric-field-path":t,"data-target-path":e.path,"data-pyric-clickable":"",children:e.path}):o.jsx("span",{"data-pyric-field-type":"reference","data-pyric-field-path":t,"data-target-path":e.path,children:e.path})}function Gg({value:e,onChange:t,error:n,path:r}){return o.jsxs("label",{"data-pyric-field-type":"reference","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[o.jsx("input",{type:"text",value:e.path,placeholder:"users/alice",onChange:s=>{const i=s.target.value,a=i.split("/").filter(Boolean),c=a[a.length-1]??"",l=e.firestore??{};t({path:i,id:c,firestore:l,type:"document"})},"aria-invalid":n?"true":void 0}),n?o.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const Jg={type:"reference",Display:Hg,Edit:Gg};function Yg({value:e,path:t}){const n=e.toBase64();return o.jsx("code",{"data-pyric-field-type":"bytes","data-pyric-field-path":t,"data-byte-length":String(e.toUint8Array().byteLength),children:n})}function Qg({value:e,onChange:t,error:n,path:r}){return o.jsxs("label",{"data-pyric-field-type":"bytes","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[o.jsx("textarea",{value:e.toBase64(),onChange:s=>{try{t(kn.fromBase64String(s.target.value))}catch{}},"aria-invalid":n?"true":void 0}),n?o.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const Xg={type:"bytes",Display:Yg,Edit:Qg};function Ur({value:e,path:t,fieldEditors:n}){const r=$n(e),s=n[r];if(!s)return null;const{Display:i}=s;return o.jsx(i,{value:e,path:t,fieldEditors:n})}function pc({label:e,value:t,path:n,fieldEditors:r,kind:s}){const i=$n(t),a=i==="map"||i==="array",[c,l]=h.useState(!0),u=s==="key"?{"data-pyric-tree-key":""}:{"data-pyric-tree-index":""},d=s==="key"?{"data-field-name":e}:{"data-field-index":e};return a?o.jsxs("li",{"data-pyric-tree-entry":!0,"data-pyric-tree-nested":!0,...d,children:[o.jsxs("button",{type:"button","data-pyric-tree-toggle":!0,"aria-expanded":c,onClick:()=>l(p=>!p),children:[o.jsx("span",{"data-pyric-tree-chevron":!0,"aria-hidden":"true",children:"›"}),o.jsx("span",{...u,children:e})]}),c?o.jsx(Ur,{value:t,path:n,fieldEditors:r}):null]}):o.jsxs("li",{"data-pyric-tree-entry":!0,...d,children:[o.jsx("span",{"data-pyric-tree-chevron":!0,"data-pyric-tree-chevron-empty":!0,"aria-hidden":"true"}),o.jsx("span",{...u,children:e}),o.jsx(Ur,{value:t,path:n,fieldEditors:r})]})}function Zg({value:e,path:t,fieldEditors:n}){const r=Object.entries(e).sort(([s],[i])=>s.localeCompare(i));return o.jsx("ul",{"data-pyric-field-type":"map","data-pyric-tree":!0,"data-pyric-field-path":t,children:r.map(([s,i])=>o.jsx(pc,{label:s,value:i,path:t?`${t}.${s}`:s,fieldEditors:n??{},kind:"key"},s))})}const ev={type:"map",Display:Zg};function tv({value:e,path:t,fieldEditors:n}){return o.jsx("ul",{"data-pyric-field-type":"array","data-pyric-tree":!0,"data-pyric-field-path":t,children:e.map((r,s)=>o.jsx(pc,{label:String(s),value:r,path:t?`${t}[${s}]`:`[${s}]`,fieldEditors:n??{},kind:"index"},s))})}const nv={type:"array",Display:tv},Bi=4;function rv(e){return e.length<=Bi?`[${e.join(", ")}]`:`[${e.slice(0,Bi).join(", ")}, …]`}function sv({value:e,path:t}){const n=Ge(e);return n?o.jsxs("span",{"data-pyric-field-type":"vector","data-pyric-field-path":t,"data-dimension":String(n.dimension),children:[o.jsx("span",{"data-pyric-vector-dims":!0,children:`vector · ${n.dimension}`}),o.jsx("span",{"data-pyric-vector-preview":!0,children:rv(n.values)})]}):o.jsx("span",{"data-pyric-field-type":"vector","data-pyric-field-path":t})}function iv(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 av({value:e,onChange:t,error:n,path:r}){const s=Ge(e),i=s?JSON.stringify(s.values):"[]",[a,c]=h.useState(i),[l,u]=h.useState(void 0),d=m=>{c(m);const y=iv(m);if(!y.ok){u(y.error);return}u(void 0),t(y.value)},p=s?s.dimension:0,f=l??n;return o.jsxs("label",{"data-pyric-field-type":"vector","data-pyric-field-path":r,"data-dimension":String(p),"data-pyric-error":f?"":void 0,children:[o.jsx("span",{"data-pyric-vector-dims":!0,children:`vector · ${p}`}),o.jsx("span",{"data-pyric-vector-note":!0,children:"Replace whole. Paste a JSON number array."}),o.jsx("textarea",{"data-pyric-vector-raw":!0,value:a,onChange:m=>d(m.target.value),"aria-invalid":f?"true":void 0,"aria-label":"Vector value (JSON number array)"}),f?o.jsx("span",{"data-pyric-error-message":!0,children:f}):null]})}const ov={type:"vector",Display:sv,Edit:av},Li={string:Ag,number:Pg,boolean:Mg,null:Bg,timestamp:Vg,geopoint:zg,reference:Jg,bytes:Xg,map:ev,array:nv,vector:ov};function mc(e){return e?{...Li,...e}:Li}function On(e={}){const t=h.useRef(null),n=e.narrowBreakpoint??480,r=e.mediumBreakpoint??768,[s,i]=h.useState("wide");return h.useEffect(()=>{const a=t.current;if(!a||typeof ResizeObserver>"u")return;const c=new ResizeObserver(l=>{const u=l[0];if(!u)return;const d=u.contentRect.width;d<n?i("narrow"):d<r?i("medium"):i("wide")});return c.observe(a),()=>c.disconnect()},[n,r]),{ref:t,size:s}}const yc=h.createContext(null);function Me(){const e=h.useContext(yc);if(!e)throw new Error("DocumentEditor.* components must render inside <DocumentEditor.Root>");return e}function cv({initial:e,fieldEditors:t,onChange:n,children:r,className:s}){const i=dc({initial:e}),a=mc(t),c=h.useRef(n);c.current=n,h.useEffect(()=>{c.current?.(i)},[i]);const{ref:l,size:u}=On();return o.jsx(yc.Provider,{value:{editor:i,fieldEditors:a},children:o.jsx("div",{ref:l,className:s,"data-pyric-ui":"document-editor","data-pyric-is-valid":i.isValid?"":void 0,"data-pyric-is-dirty":i.isDirty?"":void 0,"data-size":u,children:r})})}function lv(){const{editor:e}=Me(),t=e.tree.childIds[e.tree.rootId]??[];return o.jsxs("div",{"data-pyric-editor-fields":!0,children:[t.map(n=>o.jsx(gs,{nodeId:n,path:uv(e,n)},n)),o.jsx(bc,{parentId:e.tree.rootId})]})}function uv(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 gs({nodeId:e,path:t}){const{editor:n,fieldEditors:r}=Me(),s=n.tree.nodes[e];if(!s)return null;if(s.type==="map")return o.jsx(hv,{node:s,path:t});if(s.type==="array")return o.jsx(pv,{node:s,path:t});const a=r[s.type]?.Edit;if(!a)return null;const c=s.touched?s.error:void 0;return o.jsxs("div",{"data-pyric-field-entry":!0,"data-field-name":s.key??void 0,"data-pyric-error":c?"":void 0,onBlur:()=>n.touch(s.id),children:[o.jsx(vs,{node:s,path:t}),o.jsx(a,{value:s.value,path:t,error:c,onChange:l=>n.setValue(s.id,l)})]})}function vs({node:e,path:t}){const{editor:n}=Me(),s=(e.parentId!=null?n.tree.nodes[e.parentId]:null)?.type==="map";return e.id===n.tree.rootId?null:o.jsxs("div",{"data-pyric-field-chrome":!0,"data-pyric-field-path":t,children:[s?o.jsx("input",{type:"text",value:e.key??"",onChange:a=>n.setKey(e.id,a.target.value),"aria-label":"Field name","data-pyric-field-key-input":!0,"aria-invalid":e.touched&&e.error?"true":void 0}):null,o.jsx(fv,{node:e}),o.jsx("button",{type:"button",onClick:()=>n.remove(e.id),"data-pyric-remove":!0,"aria-label":"Remove field",children:"×"})]})}const dv=["string","number","boolean","null","timestamp","geopoint","reference","bytes","vector","map","array"];function fv({node:e}){const{editor:t}=Me(),n=e.parentId!=null?t.tree.nodes[e.parentId]:null,r=dv.filter(s=>!(n?.type==="array"&&s==="array"));return o.jsx("select",{value:e.type,onChange:s=>t.setType(e.id,s.target.value),"aria-label":"Field type","data-pyric-field-type-select":!0,children:r.map(s=>o.jsx("option",{value:s,children:s},s))})}function hv({node:e,path:t}){const{editor:n}=Me(),r=n.tree.childIds[e.id]??[];return o.jsxs("div",{"data-pyric-field-entry":!0,"data-pyric-field-type":"map","data-field-name":e.key??void 0,children:[e.id!==n.tree.rootId?o.jsx(vs,{node:e,path:t}):null,o.jsx("div",{"data-pyric-map-children":!0,children:r.map(s=>{const i=n.tree.nodes[s];if(!i)return null;const a=t?`${t}.${i.key??""}`:i.key??"";return o.jsx(gs,{nodeId:s,path:a},s)})}),o.jsx(bc,{parentId:e.id})]})}function pv({node:e,path:t}){const{editor:n}=Me(),r=n.tree.childIds[e.id]??[];return o.jsxs("div",{"data-pyric-field-entry":!0,"data-pyric-field-type":"array","data-field-name":e.key??void 0,children:[o.jsx(vs,{node:e,path:t}),o.jsx("ol",{"data-pyric-array-children":!0,children:r.map((s,i)=>{const a=t?`${t}[${i}]`:`[${i}]`;return o.jsx("li",{"data-field-index":String(i),children:o.jsx(gs,{nodeId:s,path:a})},s)})}),o.jsx(mv,{parentId:e.id})]})}function bc({parentId:e}){const{editor:t}=Me();return o.jsx("button",{type:"button","data-pyric-add-map-entry":!0,onClick:()=>t.addMapEntry(e,"","string"),children:"+ Add field"})}function mv({parentId:e}){const{editor:t}=Me();return o.jsx("button",{type:"button","data-pyric-add-array-entry":!0,onClick:()=>t.addArrayEntry(e,"string"),children:"+ Add item"})}const Fi={Root:cv,Fields:lv};function yv({collections:e,isLoading:t,error:n,onSelect:r,emptyState:s,className:i}){return n?o.jsx("div",{className:i,"data-pyric-ui":"collection-list","data-pyric-error":"",role:"alert",children:n.message}):t&&e.length===0?o.jsx("div",{className:i,"data-pyric-ui":"collection-list","data-pyric-loading":""}):e.length===0?o.jsx("div",{className:i,"data-pyric-ui":"collection-list","data-pyric-empty":"",children:s}):o.jsx("ul",{className:i,"data-pyric-ui":"collection-list",children:e.map(a=>o.jsx("li",{"data-pyric-collection-entry":!0,"data-pyric-collection-id":a.id,children:o.jsx("button",{type:"button",onClick:()=>r?.(a),"data-pyric-collection-select":!0,children:a.id})},a.path))})}const jt=new Map;function ws({scope:e,entries:t,equals:n=Object.is,durationMs:r=1200,ready:s=!0}){const i=h.useRef(null),a=h.useRef(new Map),c=h.useRef(new Map),[l,u]=h.useState(jt);return h.useEffect(()=>{const d=i.current;if(!s){if(d&&d.scope!==e){i.current=null;for(const f of c.current.values())clearTimeout(f);c.current.clear(),a.current.clear(),u(jt)}return}if(!d||d.scope!==e){i.current={scope:e,entries:t};for(const f of c.current.values())clearTimeout(f);c.current.clear(),a.current.clear(),u(jt);return}const p=new Map;for(const[f,m]of t){const y=d.entries.has(f),g=d.entries.get(f);if(y&&n(g,m))continue;const v=a.current.get(f)===0?1:0;a.current.set(f,v),p.set(f,{kind:y?"modified":"added",cycle:v})}i.current={scope:e,entries:t},u(f=>{const m=new Map(f);let y=p.size>0;for(const g of f.keys())t.has(g)||(m.delete(g),y=!0);for(const[g,v]of p)m.set(g,v);return y?m.size===0?jt:m:f});for(const[f,m]of p){const y=c.current.get(f);y&&clearTimeout(y);const g=setTimeout(()=>{c.current.delete(f),u(v=>{if(v.get(f)?.cycle!==m.cycle)return v;const b=new Map(v);return b.delete(f),b.size===0?jt:b})},r);c.current.set(f,g)}},[r,t,n,s,e]),h.useEffect(()=>()=>{for(const d of c.current.values())clearTimeout(d);c.current.clear()},[]),l}function kt(e){return e.ref}function bv({documents:e,isLoading:t,error:n,hasMore:r,onSelect:s,onLoadMore:i,renderLabel:a,renderRowAction:c,emptyState:l,className:u,updateScope:d="document-list",virtualizeThreshold:p=100,rowHeight:f=36,virtualizedHeight:m="60vh"}){const y=h.useMemo(()=>new Map(e.map(b=>[kt(b).path,b.data()])),[e]),g=ws({scope:d,entries:y,equals:bn,ready:!t});if(n)return o.jsx("div",{className:u,"data-pyric-ui":"document-list","data-pyric-error":"",role:"alert",children:n.message});if(t&&e.length===0)return o.jsx("div",{className:u,"data-pyric-ui":"document-list","data-pyric-loading":""});if(e.length===0)return o.jsx("div",{className:u,"data-pyric-ui":"document-list","data-pyric-empty":"",children:l});const v=e.length>p;return o.jsxs("div",{className:u,"data-pyric-ui":"document-list","data-pyric-virtualized":v?"":void 0,children:[v?o.jsx(hs,{items:e,estimateSize:f,height:m,getItemKey:b=>kt(b).path,renderItem:b=>{const w=g.get(kt(b).path);return o.jsxs("div",{"data-pyric-document-entry":!0,"data-pyric-document-id":b.id,"data-pyric-update":w?.kind,"data-pyric-update-cycle":w?.cycle,children:[o.jsx("button",{type:"button",onClick:()=>s?.(kt(b)),"data-pyric-document-select":!0,"data-pyric-update":w?.kind,"data-pyric-update-cycle":w?.cycle,children:a?a(b):b.id}),c?o.jsx("span",{"data-pyric-document-action":!0,children:c(b)}):null]})}}):o.jsx("ul",{"data-pyric-document-list-items":!0,children:e.map(b=>{const w=kt(b),x=g.get(w.path);return o.jsxs("li",{"data-pyric-document-entry":!0,"data-pyric-document-id":b.id,"data-pyric-update":x?.kind,"data-pyric-update-cycle":x?.cycle,children:[o.jsx("button",{type:"button",onClick:()=>s?.(w),"data-pyric-document-select":!0,"data-pyric-update":x?.kind,"data-pyric-update-cycle":x?.cycle,children:a?a(b):b.id}),c?o.jsx("span",{"data-pyric-document-action":!0,children:c(b)}):null]},w.path)})}),r&&i?o.jsx("button",{type:"button",onClick:i,"data-pyric-load-more":!0,disabled:t,children:"Load more"}):null]})}const gv=/^__.*__$/;function gc(e){if(e.length===0)return"Cannot be empty";if(e.includes("/"))return'Cannot contain "/"';if(e==="."||e==="..")return'Cannot be "." or ".."';if(gv.test(e))return"Cannot match __.*__ (reserved)";if(wv(e)>1500)return"Cannot exceed 1500 bytes"}function vv(e){return gc(e)}function wv(e){return new TextEncoder().encode(e).length}function xv(e){return gc(e)}const Vi="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function jv(){let e="";for(let t=0;t<20;t++)e+=Vi.charAt(Math.floor(Math.random()*Vi.length));return e}const kv={ref:At,listAll:us,getMetadata:Oh,getBlob:Gm,uploadBytes:po,uploadBytesResumable:Xm,deleteObject:ls},vc=h.createContext(kv);function Mn(){return h.useContext(vc)}function Sv({value:e,children:t}){return h.createElement(vc.Provider,{value:e},t)}function Zn(e){return e.replace(/^\/+|\/+$/g,"")}function Tr(e,t){return e.fullPath<t.fullPath?-1:e.fullPath>t.fullPath?1:0}function er(e,t){return e.some(n=>n.fullPath===t.fullPath)?e:[...e,t].sort(Tr)}function _v(e,t){const{listAll:n,ref:r}=Mn(),s=Zn(t),[i,a]=h.useState(()=>({status:e==null?"idle":"loading",items:[],prefixes:[],error:void 0})),[c,l]=h.useState(0),u=h.useRef(new Map);h.useEffect(()=>{if(u.current.clear(),e==null){a({status:"idle",items:[],prefixes:[],error:void 0});return}let y=!1;return a({status:"loading",items:[],prefixes:[],error:void 0}),n(r(e,s)).then(g=>{y||a({status:"success",items:[...g.items].sort(Tr),prefixes:[...g.prefixes].sort(Tr),error:void 0})}).catch(g=>{y||a({status:"error",items:[],prefixes:[],error:g instanceof Error?g:new Error(String(g))})}),()=>{y=!0}},[e,s,c]);const d=h.useCallback(()=>l(y=>y+1),[]),p=h.useCallback(y=>{if(e==null)return;const g=y.endsWith("/"),v=Zn(y),b=s===""?"":`${s}/`;if(!v.startsWith(b)||v===s)return;const w=v.slice(b.length),x=w.indexOf("/");a(k=>{if(k.status==="idle")return k;if(x===-1)return g?(u.current.set(v,k.prefixes.some(S=>S.fullPath===v)?null:v),{...k,prefixes:er(k.prefixes,r(e,v))}):(u.current.set(v,k.items.some(S=>S.fullPath===v)?null:v),{...k,items:er(k.items,r(e,v))});const j=`${b}${w.slice(0,x)}`;return u.current.set(v,k.prefixes.some(S=>S.fullPath===j)?null:j),{...k,prefixes:er(k.prefixes,r(e,j))}})},[e,s]),f=h.useCallback(y=>{const g=Zn(y),v=u.current.get(g);if(u.current.delete(g),v===null)return;const b=v??g;a(w=>({...w,items:w.items.filter(x=>x.fullPath!==b),prefixes:w.prefixes.filter(x=>x.fullPath!==b)}))},[]),m=h.useMemo(()=>[...i.prefixes.map(y=>({kind:"folder",name:y.name,fullPath:y.fullPath,ref:y})),...i.items.map(y=>({kind:"object",name:y.name,fullPath:y.fullPath,ref:y}))],[i.prefixes,i.items]);return{status:i.status,items:i.items,prefixes:i.prefixes,entries:m,error:i.error,refresh:d,insertItem:p,removeItem:f}}function Q(e){return e.split("/").filter(Boolean).join("/")}function Ev(e={}){const{path:t,onPathChange:n,defaultPath:r=""}=e,s=t!==void 0,[i,a]=h.useState(()=>Q(r)),c=s?Q(t):i,l=h.useCallback(m=>{const y=Q(m);s||a(y),n?.(y)},[s,n]),u=h.useMemo(()=>c===""?[]:c.split("/"),[c]),d=h.useCallback(m=>{const y=Q(m);l(y.includes("/")||c===""?y:`${c}/${y}`)},[c,l]),p=h.useCallback(()=>{u.length!==0&&l(u.slice(0,-1).join("/"))},[u,l]),f=h.useCallback(m=>{l(m<0?"":u.slice(0,m+1).join("/"))},[u,l]);return{path:c,segments:u,setPath:l,enter:d,up:p,navigateToIndex:f}}const qi={status:"idle",blob:void 0,url:void 0,error:void 0};function Cv(e,t){const{getBlob:n,getMetadata:r,ref:s}=Mn(),i=t==null?null:Q(t),a=e!=null&&i!=null&&i!=="",[c,l]=h.useState(()=>({status:a?"loading":"idle",metadata:void 0,error:void 0})),[u,d]=h.useState(qi),[p,f]=h.useState(0),m=h.useRef(0);h.useEffect(()=>{if(m.current++,d(qi),!a){l({status:"idle",metadata:void 0,error:void 0});return}let b=!1;return l({status:"loading",metadata:void 0,error:void 0}),r(s(e,i)).then(w=>{b||l({status:"success",metadata:w,error:void 0})}).catch(w=>{b||l({status:"error",metadata:void 0,error:w instanceof Error?w:new Error(String(w))})}),()=>{b=!0}},[e,i,p]);const y=u.url;h.useEffect(()=>{if(y!==void 0)return()=>{URL.revokeObjectURL(y)}},[y]);const g=h.useCallback(()=>f(b=>b+1),[]),v=h.useCallback(()=>{if(e==null||i==null||i==="")return;const b=++m.current;d({status:"loading",blob:void 0,url:void 0,error:void 0}),n(s(e,i)).then(w=>{b===m.current&&d({status:"success",blob:w,url:URL.createObjectURL(w),error:void 0})}).catch(w=>{b===m.current&&d({status:"error",blob:void 0,url:void 0,error:w instanceof Error?w:new Error(String(w))})})},[e,i]);return{status:c.status,metadata:c.metadata,error:c.error,refresh:g,blobStatus:u.status,blob:u.blob,blobUrl:u.url,blobError:u.error,loadBlob:v}}function Nv(){const[e,t]=h.useState(()=>new Map),n=h.useCallback(u=>e.has(u),[e]),r=h.useCallback(u=>{t(d=>{if(d.has(u.fullPath))return d;const p=new Map(d);return p.set(u.fullPath,u),p})},[]),s=h.useCallback(u=>{t(d=>{if(!d.has(u))return d;const p=new Map(d);return p.delete(u),p})},[]),i=h.useCallback(u=>{t(d=>{const p=new Map(d);return p.has(u.fullPath)?p.delete(u.fullPath):p.set(u.fullPath,u),p})},[]),a=h.useCallback(u=>{t(new Map(u.map(d=>[d.fullPath,d])))},[]),c=h.useCallback(()=>t(new Map),[]);return{selected:h.useMemo(()=>[...e.values()],[e]),size:e.size,isSelected:n,toggle:i,select:r,deselect:s,selectAll:a,clear:c}}function Rv(e,t){const n=At(e,t);return{storage:e,bucket:n.bucket,fullPath:`${n.fullPath}/`,name:"",parent:n,root:n.root,toString:()=>`${n.toString()}/`}}function Av(e){return{...e,fullPath:`${e.fullPath}/`,name:""}}function Iv(e){return{async*start(t){const n=e??{listAll:us,deleteObject:ls};let r=0;const s=[t],i=[];for(;s.length>0;){const a=s.pop();i.push(a);const c=await n.listAll(a);s.push(...c.prefixes);for(const l of c.items)await n.deleteObject(l),r++,yield{deletedCount:r,done:!1}}for(const a of i)try{await n.deleteObject(Av(a))}catch{}yield{deletedCount:r,done:!0}}}}function Dv(e,t={}){const n=Mn(),[r,s]=h.useState(0),[i,a]=h.useState(!1),[c,l]=h.useState(void 0),u=h.useRef(0),d=h.useRef(t);return d.current=t,{deleteEntries:h.useCallback(async f=>{const m=++u.current;s(0),l(void 0);const y={deleted:[],failed:[]};if(e==null||f.length===0)return y;a(!0);const g=d.current.impl??Iv(n);let v=0;try{for(const b of f){d.current.list?.removeItem(b.fullPath);try{if(b.kind==="object")await n.deleteObject(n.ref(e,b.fullPath)),v++;else for await(const w of g.start(n.ref(e,b.fullPath))){if(m!==u.current)return y;if(s(v+w.deletedCount),w.done){v+=w.deletedCount;break}}y.deleted.push(b.fullPath),m===u.current&&s(v)}catch(w){const x=w instanceof Error?w:new Error(String(w));y.failed.push({fullPath:b.fullPath,error:x}),d.current.list?.insertItem(b.kind==="folder"?`${b.fullPath}/`:b.fullPath),m===u.current&&y.failed.length===1&&l(x)}}return y}finally{m===u.current&&a(!1)}},[n,e]),progress:r,isRunning:i,error:c}}const Pv=Object.freeze({read:!0,write:!0,delete:!0,upload:!0,reasons:Object.freeze({read:[],write:[]})});function $v(e,t={}){const{paths:n,rules:r,identity:s,writeResource:i}=t,a=e==null?null:e[En],[c,l]=h.useState(()=>({status:e==null?"idle":"loading",rules:null,source:"none",error:void 0}));h.useEffect(()=>{if(a==null){l({status:"idle",rules:null,source:"none",error:void 0});return}if(r!=null){try{const w=typeof r=="string"?Sr(r):r;l({status:"ready",rules:w,source:"option",error:void 0})}catch(w){l({status:"error",rules:null,source:"none",error:w instanceof Error?w:new Error(String(w))})}return}let b=!1;return l({status:"loading",rules:null,source:"none",error:void 0}),a.servicePromise.then(w=>{b||l({status:"ready",rules:w.rules,source:w.rules?"sandbox":"none",error:void 0})}).catch(w=>{b||l({status:"error",rules:null,source:"none",error:w instanceof Error?w:new Error(String(w))})}),()=>{b=!0}},[a,r]);const u=s!==void 0?s:a?.context.auth??null,{rules:d,status:p}=c,f=i?.size,m=i?.contentType,y=h.useCallback(b=>{if(d==null)return Pv;const w=Q(b),x=a?.bucket??"pyric-default",k=w===""?`b/${x}/o`:`b/${x}/o/${w}`,j=D=>fo(d,{request:{auth:u,method:D,path:k,...D==="create"&&f!==void 0?{resource:{size:f,contentType:m}}:{}},resource:null}),S=j("read"),N=j("create"),P=j("delete"),I=N;return{read:S.allowed,write:I.allowed,delete:P.allowed,upload:N.allowed,reasons:{read:S.allowed?[]:S.reasons,write:I.allowed?[]:I.reasons}}},[d,a?.bucket,u,f,m]),g=typeof n=="string"?n:(n??[]).join(`
|
|
9
|
+
`),v=h.useMemo(()=>{const b=typeof n=="string"?[n]:n??[],w={};for(const x of b)w[Q(x)]=y(x);return w},[g,y]);return{status:p,source:c.source,advisory:!1,identity:u,verdicts:v,verdictFor:y,error:c.error}}function Wi(e,t){return e===""?t:t===""?e:`${e}/${t}`}function Ov(e){return e instanceof Blob?e.size:e.byteLength}function Mv(e){if(e instanceof Blob){const t=e;return{path:t.webkitRelativePath||t.name,data:t}}return e}function Uv(e,t={}){const{ref:n,uploadBytes:r}=Mn(),s=Q(t.path??""),[i,a]=h.useState([]),c=h.useRef(t);c.current=t;const l=h.useCallback(f=>{a(m=>m.map(y=>y.id===f.id?f:y))},[]),u=h.useCallback(async f=>{if(e==null)throw new Error("useObjectUpload: storage handle is null");const y=(Array.isArray(f)?f:[f]).map(g=>{const v=Mv(g);return{task:{id:crypto.randomUUID(),fullPath:Wi(s,Q(v.path)),status:"running",bytesTransferred:0,totalBytes:Ov(v.data)},entry:v}});a(g=>[...g,...y.map(v=>v.task)]);for(const{task:g}of y)c.current.list?.insertItem(g.fullPath),c.current.onProgress?.(g);return Promise.all(y.map(async({task:g,entry:v})=>{try{const b=await r(n(e,g.fullPath),v.data,v.metadata),w={...g,status:"success",bytesTransferred:g.totalBytes,metadata:b.metadata};return l(w),c.current.onProgress?.(w),c.current.onComplete?.(w),w}catch(b){const w={...g,status:"error",error:b instanceof Error?b:new Error(String(b))};return c.current.list?.removeItem(g.fullPath),l(w),c.current.onError?.(w),w}}))},[e,s,l,n,r]),d=h.useCallback(async f=>{if(e==null)throw new Error("useObjectUpload: storage handle is null");const m=Wi(s,Q(f));if(m==="")throw new Error("createFolder: folder name is empty");c.current.list?.insertItem(`${m}/`);try{await r(Rv(e,m),new Blob([]),{contentType:"text/plain"})}catch(y){throw c.current.list?.removeItem(m),y}},[e,s,r]),p=h.useCallback(()=>{a(f=>f.filter(m=>m.status==="running"))},[]);return{tasks:i,isUploading:i.some(f=>f.status==="running"),upload:u,createFolder:d,clearCompleted:p}}function Tv({path:e,onNavigate:t,rootLabel:n="/",separator:r="/",className:s}){const i=Q(e),a=i===""?[]:i.split("/");return o.jsx("nav",{className:s,"data-pyric-ui":"path-breadcrumb","aria-label":"Storage path",children:o.jsxs("ol",{"data-pyric-breadcrumb-list":!0,children:[o.jsx("li",{"data-pyric-breadcrumb-item":!0,children:o.jsx("button",{type:"button",onClick:()=>t?.(""),"data-pyric-breadcrumb-link":!0,"data-pyric-breadcrumb-root":!0,"data-pyric-current":a.length===0?"":void 0,"aria-current":a.length===0?"page":void 0,children:n})}),a.map((c,l)=>{const u=l===a.length-1,d=a.slice(0,l+1).join("/");return o.jsxs("li",{"data-pyric-breadcrumb-item":!0,children:[o.jsx("span",{"aria-hidden":!0,"data-pyric-breadcrumb-separator":!0,children:r}),o.jsx("button",{type:"button",onClick:()=>t?.(d),"data-pyric-breadcrumb-link":!0,"data-pyric-current":u?"":void 0,"aria-current":u?"page":void 0,children:c})]},d)})]})})}function Bv({entries:e,status:t="success",error:n,onNavigate:r,onSelect:s,selectedPath:i,gate:a,renderEntry:c,renderRowAction:l,emptyState:u,className:d,virtualizeThreshold:p=100,rowHeight:f=36,virtualizedHeight:m="60vh"}){const{ref:y,size:g}=On();if(n)return o.jsx("div",{className:d,"data-pyric-ui":"object-browser","data-pyric-error":"",role:"alert",children:n.message});if((t==="loading"||t==="idle")&&e.length===0)return o.jsx("div",{className:d,"data-pyric-ui":"object-browser","data-pyric-loading":t==="loading"?"":void 0,"data-pyric-idle":t==="idle"?"":void 0});if(e.length===0)return o.jsx("div",{className:d,"data-pyric-ui":"object-browser","data-pyric-empty":"",children:u});const v=x=>{if(!a)return{denied:!1};const k=a.verdictFor(x.fullPath);return k.read?{denied:!1}:{denied:!0,reason:k.reasons.read.join("; ")}},b=x=>{const k=x.kind==="object"&&x.fullPath===i;return o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",onClick:()=>x.kind==="folder"?r?.(x.fullPath):s?.(x.ref),"data-pyric-entry-select":!0,"data-pyric-selected":k?"":void 0,"aria-selected":k||void 0,children:c?c(x):x.name}),l?o.jsx("span",{"data-pyric-storage-action":!0,children:l(x)}):null]})},w=e.length>p;return o.jsx("div",{ref:y,className:d,"data-pyric-ui":"object-browser","data-size":g,"data-pyric-virtualized":w?"":void 0,children:w?o.jsx(hs,{items:e,estimateSize:f,height:m,getItemKey:x=>`${x.kind}:${x.fullPath}`,renderItem:x=>{const k=v(x);return o.jsx("div",{"data-pyric-storage-entry":!0,"data-pyric-entry-kind":x.kind,"data-pyric-entry-path":x.fullPath,"data-pyric-denied":k.denied?"":void 0,"data-pyric-denied-reason":k.reason,children:b(x)})}}):o.jsx("ul",{"data-pyric-object-browser-items":!0,children:e.map(x=>{const k=v(x);return o.jsx("li",{"data-pyric-storage-entry":!0,"data-pyric-entry-kind":x.kind,"data-pyric-entry-path":x.fullPath,"data-pyric-denied":k.denied?"":void 0,"data-pyric-denied-reason":k.reason,children:b(x)},`${x.kind}:${x.fullPath}`)})})})}async function wc(e,t,n){const r=t===""?e.name:`${t}/${e.name}`;if(e.isFile){const s=await new Promise((i,a)=>e.file(i,a));n.push({file:s,relativePath:r});return}if(e.isDirectory){const s=e.createReader();for(;;){const i=await new Promise((a,c)=>s.readEntries(a,c));if(i.length===0)break;for(const a of i)await wc(a,r,n)}}}async function Lv(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 wc(i,"",t);else{const a=r.getAsFile?.();a&&t.push({file:a,relativePath:a.name})}}if(t.length===0)for(const r of Array.from(e.files??[]))t.push({file:r,relativePath:r.name});return t}function Fv({onFiles:e,children:t,disabled:n,disabledReason:r,className:s}){const[i,a]=h.useState(!1),c=h.useRef(0),l=h.useCallback(f=>{f.preventDefault(),!n&&(c.current+=1,a(!0))},[n]),u=h.useCallback(f=>{f.preventDefault()},[]),d=h.useCallback(f=>{f.preventDefault(),!n&&(c.current=Math.max(0,c.current-1),c.current===0&&a(!1))},[n]),p=h.useCallback(f=>{if(f.preventDefault(),c.current=0,a(!1),n)return;const m=f.dataTransfer;m&&Lv(m).then(y=>{y.length>0&&e(y)})},[n,e]);return o.jsx("div",{className:s,"data-pyric-ui":"upload-dropzone","data-dragging":i?"":void 0,"data-disabled":n?"":void 0,"data-disabled-reason":n?r:void 0,"aria-disabled":n||void 0,onDragEnter:l,onDragOver:u,onDragLeave:d,onDrop:p,children:t})}function Vv(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 qv(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 zi(e,t){if(!t.has(e))return e;const{stem:n,ext:r}=Vv(e),{base:s,counter:i}=qv(n);let a=i===null?1:i+1;for(;;){const c=`${s} (${a})${r}`;if(!t.has(c))return c;a+=1}}function Wv(e,t){const n=new Set(t),r=new Map;return e.map(s=>{const i=s.indexOf("/");if(i===-1){const l=zi(s,n);return n.add(l),l}const a=s.slice(0,i);let c=r.get(a);return c===void 0&&(c=zi(a,n),n.add(c),r.set(a,c)),`${c}${s.slice(i)}`})}function Ki(e){const t=Q(e);if(t==="")return[];const n=t.split("/");return n.map((r,s)=>n.slice(0,s+1).join("/"))}const xc=[];function zv(e,t){switch(t.type){case"create":{const n=Ki(t.path).filter(r=>!e.includes(r));return n.length===0?e:[...e,...n].sort()}case"materialize":{const n=new Set(Ki(t.path));if(n.size===0)return e;const r=e.filter(s=>!n.has(s));return r.length===e.length?e:r}case"discard":{const n=Q(t.path);if(n==="")return e;const r=e.filter(s=>s!==n&&!s.startsWith(`${n}/`));return r.length===e.length?e:r}case"clear":return e.length===0?e:xc}}function Kv(e,t){const n=Q(t),r=n===""?"":`${n}/`;return e.filter(s=>s.startsWith(r)&&s!==n&&!s.slice(r.length).includes("/")).map(s=>s.slice(r.length))}function Hi(e,t){return e.includes(Q(t))}function Hv(e){const t=Q(e);return t===""?"Enter a folder name.":t.split("/").some(r=>r==="."||r==="..")?'Folder names may not be "." or "..".':null}const Gv=256*1024;function Br(e){return(e.contentType??"").split(";")[0].trim().toLowerCase()}const Jv={id:"image",match:e=>Br(e).startsWith("image/"),needsBlob:!0,render:({metadata:e,blobUrl:t})=>t?o.jsx("img",{"data-pyric-preview-image":!0,src:t,alt:e.name}):null};function Yv({blob:e,isJson:t}){const[n,r]=h.useState(void 0);return h.useEffect(()=>{let s=!1;return e.text().then(i=>{if(!s){if(t)try{r(JSON.stringify(JSON.parse(i),null,2));return}catch{}r(i)}}),()=>{s=!0}},[e,t]),n===void 0?null:o.jsx("pre",{"data-pyric-preview-text":!0,children:n})}const Qv={id:"text",match:e=>{const t=Br(e);return t.startsWith("text/")||t==="application/json"},needsBlob:!0,maxBytes:Gv,render:({metadata:e,blob:t})=>t?o.jsx(Yv,{blob:t,isJson:Br(e)==="application/json"}):null},Xv=[Jv,Qv];function Zv(e,t){for(const n of[...t??[],...Xv])if(n.match(e))return n}const ew=[{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 tw({metadata:e}){return o.jsxs("dl",{"data-pyric-object-metadata":!0,children:[ew.map(({key:t,label:n,value:r})=>{const s=r(e);return s===void 0?null:o.jsxs("div",{"data-pyric-metadata-field":t,children:[o.jsx("dt",{children:n}),o.jsx("dd",{children:s})]},t)}),Object.entries(e.customMetadata??{}).map(([t,n])=>o.jsxs("div",{"data-pyric-metadata-field":"customMetadata","data-pyric-metadata-key":t,children:[o.jsx("dt",{children:t}),o.jsx("dd",{children:n})]},`custom:${t}`))]})}function nw({storage:e,path:t,previews:n,renderMetadata:r,children:s,className:i}){const{ref:a,size:c}=On(),l=Cv(e,t),{metadata:u,blobStatus:d,loadBlob:p}=l,f=u?Zv(u,n):void 0,m=f?.maxBytes!==void 0&&u!==void 0&&u.size>f.maxBytes,y=f?.needsBlob===!0&&!m;if(h.useEffect(()=>{y&&d==="idle"&&p()},[y,d,p]),l.status==="idle")return o.jsx("div",{className:i,"data-pyric-ui":"object-inspector","data-pyric-idle":""});if(l.status==="loading")return o.jsx("div",{className:i,"data-pyric-ui":"object-inspector","data-pyric-loading":""});if(l.status==="error"||u===void 0)return o.jsx("div",{className:i,"data-pyric-ui":"object-inspector","data-pyric-error":"",role:"alert",children:l.error?.message});let g,v={};return f===void 0?v={"data-pyric-preview-none":""}:m?v={"data-pyric-preview-too-large":""}:y&&d==="loading"?v={"data-pyric-preview-loading":""}:y&&d==="error"?(v={"data-pyric-preview-error":""},g=l.blobError?.message):(!y||d==="success")&&(g=f.render({metadata:u,blob:l.blob,blobUrl:l.blobUrl})),o.jsxs("div",{ref:a,className:i,"data-pyric-ui":"object-inspector","data-size":c,children:[o.jsx("div",{"data-pyric-object-name":!0,children:u.name}),r?r(u):o.jsx(tw,{metadata:u}),o.jsx("div",{"data-pyric-object-preview":!0,"data-pyric-preview":f?.id,...v,children:g}),s]})}const jc=h.createContext(null);function rw(){const e=h.useContext(jc);if(!e)throw new Error("useToast: missing <ToastProvider> ancestor");return e}function sw({children:e,defaultDuration:t=5e3,className:n,regionLabel:r="Notifications"}){const[s,i]=h.useState([]),a=h.useCallback(u=>{i(d=>d.filter(p=>p.id!==u))},[]),c=h.useCallback(u=>{const d=crypto.randomUUID(),p=u.duration??t;return i(f=>[...f,{id:d,...u}]),p>0&&window.setTimeout(()=>{i(f=>f.filter(m=>m.id!==d))},p),d},[t]),l=h.useMemo(()=>({toast:c,dismiss:a,toasts:s}),[c,a,s]);return o.jsxs(jc.Provider,{value:l,children:[e,o.jsx(iw,{toasts:s,dismiss:a,className:n,regionLabel:r})]})}function iw({toasts:e,dismiss:t,className:n,regionLabel:r}){const[s,i]=h.useState(!1);return h.useEffect(()=>i(!0),[]),!s||typeof document>"u"?null:fs.createPortal(o.jsx("ol",{"aria-label":r,"aria-live":"polite","data-pyric-ui":"toast-region",className:n,children:e.map(a=>o.jsxs("li",{"data-pyric-toast":!0,"data-pyric-toast-kind":a.kind??"info",role:a.kind==="error"?"alert":"status",children:[o.jsx("div",{"data-pyric-toast-title":!0,children:a.title}),a.body?o.jsx("div",{"data-pyric-toast-body":!0,children:a.body}):null,o.jsx("button",{type:"button","data-pyric-toast-dismiss":!0,"aria-label":"Dismiss",onClick:()=>t(a.id),children:"×"})]},a.id))}),document.body)}function aw({storage:e,entries:t,impl:n,list:r,gate:s,title:i,body:a,confirmLabel:c="Delete",onDeleted:l,onFailed:u,renderTrigger:d,className:p}){const f=yt(),{toast:m}=rw(),{deleteEntries:y,isRunning:g,progress:v}=Dv(e,{impl:n,list:r}),b=s?t.map(j=>({entry:j,verdict:s.verdictFor(j.fullPath)})).filter(j=>!j.verdict.delete):[],w=b.length===0?void 0:`Delete denied for ${b[0].entry.fullPath}${b.length>1?` (+${b.length-1} more)`:""}: ${b[0].verdict.reasons.write.join("; ")}`,x=g||t.length===0||e==null||b.length>0,k=async()=>{if(x||!await f({title:i??(t.length===1?`Delete ${t[0].fullPath}?`:`Delete ${t.length} items?`),body:a??o.jsx("ul",{"data-pyric-delete-selection-paths":!0,children:t.map(N=>o.jsxs("li",{"data-pyric-entry-kind":N.kind,children:[N.fullPath,N.kind==="folder"?"/":""]},N.fullPath))}),destructive:!0,confirmLabel:c}))return;const S=await y(t);S.failed.length===0?(m({title:`Deleted ${S.deleted.length} ${S.deleted.length===1?"item":"items"}`,kind:"success"}),l?.(S)):(m({title:`Delete failed for ${S.failed.length} of ${t.length}`,kind:"error",body:o.jsx("ul",{"data-pyric-delete-selection-failures":!0,children:S.failed.map(N=>o.jsxs("li",{children:[N.fullPath,":"," ",N.error.code??N.error.message]},N.fullPath))})}),u?.(S))};return d?o.jsx(o.Fragment,{children:d({onClick:k,isRunning:g,progress:v,disabled:x,deniedReason:w})}):o.jsx("button",{type:"button",onClick:k,className:p,disabled:x,title:w,"data-pyric-ui":"delete-selection","data-pyric-destructive":"","data-pyric-running":g?"":void 0,"data-pyric-denied":w?"":void 0,"data-pyric-denied-reason":w,children:g?`Deleting… (${v})`:c})}function gn(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 kc(e){const t=e.indexOf("?");return as(t===-1?e:e.slice(0,t),t===-1?"":e.slice(t))}function ow(e){const{tab:t,rest:n,query:r}=kc(e),s=n.join("/");return t==="firestore"?{view:"firestore",path:gn(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 cw(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 Sc(e){const{tab:t,query:n}=kc(e),r=ow(e),s=t==="traffic"?n.inspect??null:null;return{target:r,selectedInspectId:s}}let Gi=null,Lr=Sc("");function lw(){const e=Co();return e!==Gi&&(Gi=e,Lr=Sc(e)),Lr}function uw(){return Lr}function Gt(e){le(cw(e))}function dw(e){le({tab:"traffic",query:{inspect:e}})}function Un(){const e=h.useSyncExternalStore(Tt,lw,uw),t=h.useCallback(s=>Gt(s),[]),n=h.useCallback(s=>{switch(s.kind){case"user":Gt({view:"auth",uid:s.uid});break;case"storage":Gt({view:"storage",kind:"object",path:s.objectPath});break;case"document":Gt({view:"firestore",path:gn(s.path)});break}},[]),r=h.useCallback(s=>dw(s),[]);return h.useMemo(()=>({target:e.target,navigate:t,navigateRef:n,selectedInspectId:e.selectedInspectId,navigateInspect:r}),[e,t,n,r])}const fw={narrowBreakpoint:640,mediumBreakpoint:920};function hw(e){switch(e){case"narrow":return 1;case"medium":return 2;case"wide":return 3}}function pw(e,t){const n=hw(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 tr({label:e,error:t,hint:n,children:r}){return o.jsxs("div",{className:"fs-modal__group",children:[o.jsx("span",{className:"fs-modal__label",children:e}),r,t?o.jsx("span",{className:"fs-modal__err",role:"alert",children:t}):n?o.jsx("span",{className:"fs-modal__hint",children:n}):null]})}function _c({mode:e,parentPath:t,onCreate:n,onClose:r}){const[s,i]=h.useState(""),[a,c]=h.useState(()=>jv()),[l,u]=h.useState(null),[d,p]=h.useState(null),[f,m]=h.useState(!1),y=h.useRef(null),g=e==="collection"&&s?vv(s):void 0,v=a?xv(a):void 0,w=!(e==="collection"&&(!s||g))&&!!a&&!v&&!f;h.useEffect(()=>{const j=S=>{S.key==="Escape"&&!f&&r()};return document.addEventListener("keydown",j),()=>document.removeEventListener("keydown",j)},[f,r]);const x=async()=>{if(!(!w||!l)){if(!l.isValid){l.touchAll();return}m(!0),p(null);try{await n({collectionId:e==="collection"?s:null,docId:a,data:ac(l.tree)}),r()}catch(j){p(j instanceof Error?j:new Error(String(j))),m(!1)}}},k=e==="collection"?"Start a collection":"Add a document";return o.jsx("div",{className:"fs-modal-backdrop",onMouseDown:j=>{j.target===j.currentTarget&&!f&&r()},children:o.jsxs("div",{ref:y,className:"fs-modal",role:"dialog","aria-modal":"true","aria-label":k,"data-pyric-ui":"fs-create-modal","data-fs-create-mode":e,children:[o.jsx("h2",{className:"fs-modal__title",children:k}),o.jsx(tr,{label:"Parent path",children:o.jsx("span",{className:"fs-modal__path",children:t})}),e==="collection"?o.jsx(tr,{label:"Collection ID",error:g,children:o.jsx("input",{autoFocus:!0,type:"text",value:s,placeholder:"e.g. users",onChange:j=>i(j.target.value),"data-pyric-field":"collection-id","aria-invalid":g?"true":void 0})}):null,o.jsx(tr,{label:"Document ID",error:a?v:"Cannot be empty",hint:"Auto-generated — edit to set your own.",children:o.jsx("input",{autoFocus:e==="document",type:"text",value:a,onChange:j=>c(j.target.value),"data-pyric-field":"doc-id","aria-invalid":v||!a?"true":void 0})}),o.jsxs("div",{className:"fs-modal__group",children:[o.jsx("span",{className:"fs-modal__label",children:"Fields"}),o.jsx("div",{className:"fs-modal__fields",children:o.jsx(Fi.Root,{initial:{},onChange:u,children:o.jsx(Fi.Fields,{})})})]}),d?o.jsx("p",{className:"fs-modal__err",role:"alert",children:d.message}):null,o.jsxs("div",{className:"fs-modal__actions",children:[o.jsx("button",{type:"button",className:"fs-editor__cancel",disabled:f,onClick:r,children:"Cancel"}),o.jsx("button",{type:"button",className:"fs-editor__save",disabled:!w,onClick:()=>void x(),children:f?"Saving…":"Save"})]})]})})}function Ec({items:e,label:t="More actions"}){const[n,r]=h.useState(!1),[s,i]=h.useState(null),a=h.useRef(null),c=()=>{if(!n){const l=a.current?.getBoundingClientRect();l&&i({top:l.bottom+4,right:window.innerWidth-l.right})}r(l=>!l)};return h.useEffect(()=>{if(!n)return;const l=u=>{u.key==="Escape"&&(r(!1),a.current?.focus())};return document.addEventListener("keydown",l),()=>document.removeEventListener("keydown",l)},[n]),o.jsxs("span",{className:"fs-overflow","data-pyric-ui":"fs-overflow-menu",children:[o.jsx("button",{ref:a,type:"button",className:"fs-overflow__trigger","aria-haspopup":"menu","aria-expanded":n,"aria-label":t,onClick:c,children:o.jsx("span",{"aria-hidden":"true",children:"⋮"})}),n?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"fs-overflow__backdrop",onMouseDown:()=>r(!1)}),o.jsx("div",{className:"fs-overflow__menu",role:"menu",style:s?{top:s.top,right:s.right}:void 0,children:e.map(l=>o.jsx("button",{type:"button",role:"menuitem",className:"fs-overflow__item","data-destructive":l.destructive?"":void 0,disabled:l.disabled,onClick:()=>{r(!1),l.onSelect()},children:l.label},l.label))})]}):null]})}function Cc(e){return JSON.stringify(e)}function mw(e,t){const n=new Map,r=(s,i)=>{const a=t(s),c=Cc(i);if(a==="map"){const l=s,u=Object.keys(l).sort();n.set(c,[a,u]);for(const d of u)r(l[d],[...i,["field",d]]);return}if(a==="array"){const l=s;n.set(c,[a,l.map((u,d)=>String(d))]),l.forEach((u,d)=>r(u,[...i,["index",d]]));return}n.set(c,[a,s])};for(const[s,i]of Object.entries(e))r(i,[["field",s]]);return n}function Nc(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 Cc(n)}function yw(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 bw(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 Ji(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 gw=42;function vw(e,t,n,r=gw){const s=e.nodes[t],i=e.childIds[t]??[];let a;return s.type==="array"?a=`[${i.slice(0,3).map(l=>Ji(e.nodes[l],n.asVectorView,n.vectorPreview)).join(", ")}${i.length>3?", …":""}]`:a=`{${i.slice(0,2).map(l=>`"${e.nodes[l].key}": ${Ji(e.nodes[l],n.asVectorView,n.vectorPreview)}`).join(", ")}${i.length>2?", …":""}}`,a.length>r?`${a.slice(0,r-1)}…`:a}function ww(e,t,n){return t.parentId==null?!1:(e.childIds[t.parentId]??[]).some(s=>s!==t.id&&e.nodes[s]?.key===n)}function xw(e){return e.shiftKey===!0}const Rc=["string","number","boolean","null","timestamp","geopoint","reference","bytes","vector"],jw=[...Rc,"map","array"];function kw({snapshot:e,documentRef:t,onCommit:n,onDeleteDocument:r,onDeleteDocumentFields:s,fieldEditors:i,onReferenceClick:a,onStartCollection:c,firestore:l,listSubcollections:u,onSubcollectionClick:d}){const p=h.useMemo(()=>e?.data()??{},[e]),f=h.useMemo(()=>p,[]),m=dc({initial:f}),y=m.replaceData,g=h.useMemo(()=>mc(i),[i]),v=yt(),[b,w]=h.useState(()=>new Set),[x,k]=h.useState(null),j=h.useRef(e),S=h.useRef(new Set),N=h.useRef(!1),[P,I]=h.useState(null),D=h.useMemo(()=>mw(p,$n),[p]),C=ws({scope:t.path,entries:D,equals:bn,ready:x===null});h.useEffect(()=>{N.current&&(N.current=!1,I(null),n(m.toData()).catch($=>{I($ instanceof Error?$:new Error(String($)))}))},[m.tree]),h.useEffect(()=>{!e||e===j.current||x!==null||(j.current=e,S.current.clear(),y(e.data()??{}))},[x,y,e]);const _=h.useCallback($=>{w(Y=>{const se=new Set(Y);return se.has($)?se.delete($):se.add($),se})},[]),[E,R]=h.useState(null),V=h.useCallback(($,Y)=>{if(Y==="map"?m.addMapEntry($,"","string"):m.addArrayEntry($,"string"),$!==m.tree.rootId){const se=Nc(m.tree,$);w(ne=>new Set(ne).add(se))}R($)},[m]);h.useEffect(()=>{if(!E)return;const $=m.tree.childIds[E]??[],Y=$[$.length-1];Y&&!x&&(S.current.add(Y),k(Y),R(null))},[m.tree,E]);const G=h.useCallback($=>{m.remove($),S.current.delete($),N.current=!0,x===$&&k(null)},[m,x]),A=h.useCallback(async($,Y,se)=>{if(xw(se)){G($.id);return}await v({title:`Delete field "${Y}"?`,destructive:!0,confirmLabel:"Delete"})&&G($.id)},[v,G]),O=t.id,M=m.tree.childIds[m.tree.rootId]??[];return o.jsxs("div",{"data-pyric-ui":"fs-doctree",className:"fs-doctree",children:[o.jsxs("div",{className:"fs-doctree__head",children:[o.jsx("span",{className:"fs-doctree__docid",children:O}),o.jsx(Ec,{items:[{label:"Delete document fields",onSelect:()=>{(async()=>await v({title:"Delete all fields?",body:"The document itself is kept, empty.",destructive:!0,confirmLabel:"Delete fields"})&&s())()},destructive:!0},{label:"Delete document",onSelect:r,destructive:!0}]})]}),P?o.jsx("p",{className:"fs-doctree__err",children:P.message}):null,o.jsxs("ul",{className:"fs-doctree__rows",children:[c?o.jsx("li",{className:"fs-doctree__action-row",children:o.jsxs("button",{type:"button",className:"fs-doctree__action",onClick:c,children:[o.jsx("span",{"aria-hidden":"true",children:"+"})," Start collection"]})}):null,o.jsx("li",{className:"fs-doctree__action-row",children:o.jsxs("button",{type:"button",className:"fs-doctree__action",onClick:()=>V(m.tree.rootId,"map"),children:[o.jsx("span",{"aria-hidden":"true",children:"+"})," Add field"]})}),M.map($=>o.jsx(Ac,{nodeId:$,depth:0,editor:m,registry:g,expanded:b,onToggle:_,editingId:x,setEditingId:k,newIdsRef:S,onAdd:V,onDelete:A,onCommitNeeded:()=>{N.current=!0},onReferenceClick:a,updates:C},$))]}),l&&u?o.jsx(Ic,{firestore:l,documentRef:t,listSubcollections:u,onSubcollectionClick:d}):null]})}function Ac({nodeId:e,depth:t,editor:n,registry:r,expanded:s,onToggle:i,editingId:a,setEditingId:c,newIdsRef:l,onAdd:u,onDelete:d,onCommitNeeded:p,onReferenceClick:f,updates:m}){const{tree:y}=n,g=y.nodes[e];if(!g)return null;const{label:v,isArrayChild:b}=bw(y,e),w=g.type==="map"||g.type==="array",x=yw(y,e),k=Nc(y,e),j=m.get(k),S=s.has(k),N=a===e,P=l.current.has(e);return N?o.jsx("li",{className:"fs-doctree__row fs-doctree__row--editing","data-pyric-doctree-depth":t,style:{"--fs-depth":t},children:o.jsx(Sw,{node:g,isNew:P,isArrayChild:b,tree:y,editor:n,registry:r,path:x,onCommitNeeded:p,onDone:()=>{l.current.delete(e),c(null)},onCancelNew:()=>{n.remove(e),l.current.delete(e),c(null)}})}):o.jsxs("li",{className:"fs-doctree__row","data-pyric-doctree-depth":t,"data-pyric-doctree-nested":w?"":void 0,style:{"--fs-depth":t},children:[o.jsxs("div",{className:"fs-doctree__line","data-pyric-update":j?.kind,"data-pyric-update-cycle":j?.cycle,children:[w?o.jsx("button",{type:"button",className:"fs-doctree__caret","aria-expanded":S,onClick:()=>i(k),children:o.jsx("span",{"aria-hidden":"true",children:S?"▼":"▶"})}):o.jsx("span",{className:"fs-doctree__caret fs-doctree__caret--empty","aria-hidden":"true"}),b?o.jsx("span",{className:"fs-doctree__chip",children:v}):o.jsx("span",{className:"fs-doctree__key",children:v}),w?S?null:o.jsx("span",{className:"fs-doctree__preview",children:vw(y,e,{asVectorView:Ge,vectorPreview:sc})}):o.jsx("span",{className:"fs-doctree__value",children:o.jsx(Ur,{value:g.value,path:x,fieldEditors:r})}),o.jsxs("span",{className:"fs-doctree__hover",children:[o.jsxs("span",{className:"fs-doctree__typenote",children:["(",g.type,")"]}),w?o.jsx("button",{type:"button",className:"fs-doctree__icon",title:"Add field","aria-label":`Add field to ${v||"document"}`,onClick:()=>u(e,g.type==="array"?"array":"map"),children:"+"}):o.jsx("button",{type:"button",className:"fs-doctree__icon",title:"Edit","aria-label":`Edit ${v}`,onClick:()=>c(e),children:"✎"}),o.jsx("button",{type:"button",className:"fs-doctree__icon fs-doctree__icon--danger",title:"Delete (shift-click to skip confirmation)","aria-label":`Delete ${v||"field"} (shift-click to skip confirmation)`,onClick:I=>void d(g,v,{shiftKey:I.shiftKey}),children:"🗑"})]})]}),w&&S?o.jsxs("ul",{className:"fs-doctree__children",children:[(y.childIds[e]??[]).map(I=>o.jsx(Ac,{nodeId:I,depth:t+1,editor:n,registry:r,expanded:s,onToggle:i,editingId:a,setEditingId:c,newIdsRef:l,onAdd:u,onDelete:d,onCommitNeeded:p,onReferenceClick:f,updates:m},I)),o.jsx("li",{className:"fs-doctree__action-row fs-doctree__action-row--nested",children:o.jsxs("button",{type:"button",className:"fs-doctree__action",onClick:()=>u(e,g.type==="array"?"array":"map"),children:[o.jsx("span",{"aria-hidden":"true",children:"+"})," ",g.type==="array"?"Add item":"Add field"]})})]}):null]})}function Sw({node:e,isNew:t,isArrayChild:n,tree:r,editor:s,registry:i,path:a,onCommitNeeded:c,onDone:l,onCancelNew:u}){const[d,p]=h.useState(e.key??""),[f,m]=h.useState(e.type),[y,g]=h.useState(e.value),[v,b]=h.useState(!1),w=n?void 0:d===""?"Field name is required":ww(r,e,d)?"Field name must be unique":void 0,x=f==="map"||f==="array"?void 0:cc(f,y),k=!w&&!x,j=()=>{if(!k){b(!0);return}n||s.setKey(e.id,d),f!==e.type&&s.setType(e.id,f),f!=="map"&&f!=="array"&&s.setValue(e.id,y),c(),l()},S=()=>{t?u():l()},P=i[f]?.Edit,I=f!=="map"&&f!=="array"&&P?o.jsx(P,{value:y,path:a,error:v?x:void 0,onChange:_=>g(_)}):f==="map"||f==="array"?o.jsxs("span",{className:"fs-doctree__editnote",children:["Saves as an empty ",f," — add its children afterward."]}):null,D=o.jsxs("span",{className:"fs-doctree__editactions",children:[o.jsx("button",{type:"button",className:"fs-doctree__editsave",onClick:j,"aria-label":"Save field",children:"✓"}),o.jsx("button",{type:"button",className:"fs-doctree__editcancel",onClick:S,"aria-label":"Cancel edit",children:"✕"})]}),C=o.jsx("select",{className:"fs-doctree__edittype",value:f,onChange:_=>{const E=_.target.value;m(E),E!=="map"&&E!=="array"&&E!==f&&g(_w(E))},"aria-label":"Field type",children:(t?jw:Rc).map(_=>o.jsx("option",{value:_,children:_},_))});return o.jsxs("div",{className:"fs-doctree__editrow",onKeyDown:_=>{_.key==="Enter"&&!_.target.matches("textarea")?(_.preventDefault(),j()):_.key==="Escape"&&(_.preventDefault(),S())},children:[n?null:o.jsxs("div",{className:"fs-doctree__editline",children:[o.jsx("input",{type:"text",className:"fs-doctree__editkey",value:d,placeholder:"Field name",autoFocus:t,onChange:_=>p(_.target.value),onBlur:()=>b(!0),"aria-label":"Field name","aria-invalid":v&&w?"true":void 0}),C]}),o.jsxs("div",{className:"fs-doctree__editline",children:[n?C:null,I,D]}),v&&w?o.jsx("span",{className:"fs-doctree__editerr",children:w}):null]})}function _w(e){switch(e){case"string":return"";case"number":return 0;case"boolean":return!1;default:return null}}function Ic({firestore:e,documentRef:t,listSubcollections:n,onSubcollectionClick:r}){const{subcollections:s,isLoading:i}=Cg({firestore:e,documentRef:t,listSubcollections:n});return!i&&s.length===0?null:o.jsxs("section",{"data-pyric-ui":"fs-doctree-subcollections","data-pyric-loading":i?"":void 0,children:[o.jsx("div",{className:"fs-doctree__subhead",children:"Subcollections"}),o.jsx("ul",{className:"fs-doctree__sublist",children:s.map(a=>o.jsx("li",{children:r?o.jsxs("button",{type:"button",className:"fs-doctree__subrow",onClick:()=>r(a),"aria-label":`Open subcollection ${a.id}`,children:[o.jsx("span",{children:a.id}),o.jsx("span",{className:"fs-doctree__subtype",children:"subcollection"}),o.jsx("span",{"aria-hidden":"true",children:"›"})]}):o.jsxs("div",{className:"fs-doctree__subrow",children:[o.jsx("span",{children:a.id}),o.jsx("span",{className:"fs-doctree__subtype",children:"subcollection"})]})},a.path))})]})}function Ew(e){return e.split("/").filter(Boolean).length%2===0}function Dc(e,t){async function*n(s,i,a=!1){const c=await t.listSubcollections(s.path);for(const l of c)yield*r(e.collection(s,l),i);a||(await e.deleteDoc(s),i.n++,yield{deletedCount:i.n,done:!1})}async function*r(s,i){const a=await t.listDocuments(s.path);for(const c of a){const l=c.path.split("/").pop();l&&(yield*n(e.doc(s,l),i,c.phantom===!0))}}return{async*start(s){const i={n:0};Ew(s.path)?yield*n(s,i):yield*r(s,i),yield{deletedCount:i.n,done:!0}}}}async function Pc(e,t){for await(const n of e.start(t))if(n.done)return}async function $c({confirm:e,ref:t,api:n,recursiveImpl:r}){let s=!1;return await e({title:`Delete document "${t.id}"?`,body:o.jsxs("label",{className:"fs-delete-recursive",children:[o.jsx("input",{type:"checkbox",onChange:a=>{s=a.currentTarget.checked}}),o.jsx("span",{children:"Also delete subcollections recursively. Leave this off to keep nested data."})]}),destructive:!0,confirmLabel:"Delete document"})?(s?await Pc(r,t):await n.deleteDoc(t),!0):!1}function Cw(e){const t=e.exists;return typeof t=="function"?t.call(e):t}async function Nw(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 Rw(e){return{id:e.id,ref:e,data:()=>{},__pyricPhantom:!0}}function Yi(e){return e.__pyricPhantom===!0}function Aw(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 Iw({handles:e}){const{target:t,navigate:n}=Un(),r=e.adminFirestore,s=ys(),i=h.useMemo(()=>t?.view==="firestore"?t.path:[],[t]),a=h.useCallback(k=>{const j=typeof k=="function"?k(i):k;n({view:"firestore",path:j})},[n,i]),c=(k,j)=>a(S=>[...S.slice(0,k+1),j]),[l,u]=h.useState(null),d=h.useCallback(async({collectionId:k,docId:j,data:S})=>{if(!l||!k)return;const N=l.parentDocPath,P=N?s.collection(s.doc(r,N),k):s.collection(r,k);await Nw(s,P,j,S);const I=N?`${N}/${k}`:k;n({view:"firestore",path:gn(`${I}/${j}`)})},[s,r,l,n]),p=[o.jsx($w,{api:s,firestore:r,collectionIds:e.listRootCollections(),onSelect:k=>a([{kind:"collection",id:k,path:k}]),onStartCollection:()=>u({parentDocPath:null})},"__root__"),...i.map((k,j)=>k.kind==="collection"?o.jsx(Ow,{api:s,firestore:r,handles:e,collectionPath:k.path,selectedId:i[j+1]?.id??null,onSelect:S=>c(j,{kind:"document",id:S.id,path:S.path}),onCollectionDeleted:()=>a(S=>S.slice(0,j))},k.path):o.jsx(Mw,{api:s,firestore:r,handles:e,docPath:k.path,onOpenSubcollection:S=>c(j,{kind:"collection",id:S.id,path:S.path}),onReferenceClick:S=>n({view:"firestore",path:gn(S.path)}),onStartCollection:()=>u({parentDocPath:k.path}),onDeleted:()=>a(S=>S.slice(0,j))},k.path))],{ref:f,size:m}=On(fw),{startIndex:y,visibleCount:g,emptySlots:v}=pw(p.length,m),b=p.slice(y,y+g),w=i.length===0?"Select a collection":i[i.length-1]?.kind==="collection"?"Select a document":null,x=[...b,...Array.from({length:v},(k,j)=>o.jsx(Pw,{hint:j===0?w:null},`__empty_${j}__`))];return h.useEffect(()=>{if(m==="wide")return;const k=f.current;if(!k)return;const j=document.activeElement;if(j&&j!==document.body&&k.contains(j))return;const S=k.querySelector(".fs-columns > .fs-col:last-child");S&&(S.tabIndex=-1,S.focus({preventScroll:!0}))},[i.length,m]),o.jsx(ms,{children:o.jsxs("div",{ref:f,"data-pyric-ui":"fs-browser","data-fs-depth":i.length,"data-size":m,children:[o.jsx(Dw,{path:i,onHome:()=>a([]),onJump:k=>a(j=>j.slice(0,k+1))}),o.jsx("div",{className:"fs-columns",children:x}),l?o.jsx(_c,{mode:"collection",parentPath:l.parentDocPath?`/${l.parentDocPath}`:"/",onCreate:d,onClose:()=>u(null)}):null]})})}function Dw({path:e,onHome:t,onJump:n}){return o.jsxs("nav",{"data-pyric-ui":"fs-breadcrumb","aria-label":"Firestore path",children:[o.jsx("button",{type:"button",className:"fs-crumb",onClick:t,children:"home"}),e.map((r,s)=>o.jsxs(h.Fragment,{children:[o.jsx("span",{className:"fs-crumb-sep","aria-hidden":!0,children:"›"}),s===e.length-1?o.jsx("span",{className:"fs-crumb fs-crumb--current",children:r.id}):o.jsx("button",{type:"button",className:"fs-crumb",onClick:()=>n(s),children:r.id})]},r.path))]})}function Pw({hint:e}){return o.jsx("section",{"data-pyric-ui":"fs-empty-col",className:"fs-pane fs-col fs-col--empty","aria-hidden":e?void 0:!0,children:e?o.jsx("p",{className:"fs-empty",children:e}):null})}function $w({api:e,firestore:t,collectionIds:n,onSelect:r,onStartCollection:s}){const i=h.useMemo(()=>n.map(a=>e.collection(t,a)),[e,t,n]);return o.jsxs("section",{"data-pyric-ui":"fs-collections",className:"fs-pane fs-col",children:[o.jsxs("div",{className:"fs-phead",children:[o.jsx("span",{className:"fs-phead-title",children:"Collections"}),o.jsx("button",{type:"button",className:"fs-add",onClick:s,children:"+ New"})]}),o.jsx(yv,{collections:i,onSelect:a=>r(a.id),emptyState:o.jsx("p",{className:"fs-empty",children:"No collections yet. App or agent writes show up here."})})]})}function Ow({api:e,firestore:t,handles:n,collectionPath:r,selectedId:s,onSelect:i,onCollectionDeleted:a}){const c=h.useMemo(()=>Aw(e,t,r),[e,t,r]),{documents:l,isLoading:u,error:d,subscriptionGeneration:p,hasMore:f,loadMore:m,createDocument:y}=Eg({collection:c,mode:"live"}),[g,v]=h.useState([]);h.useEffect(()=>{let C=!1;return Promise.resolve(n.listDocuments(r)).then(_=>{C||v(_.filter(E=>E.phantom).map(E=>E.path.split("/").pop()??""))}).catch(()=>{C||v([])}),()=>{C=!0}},[n,r,l]);const b=h.useMemo(()=>{const C=new Set(l.map(_=>_.id));return[...l,...g.filter(_=>_.length>0&&!C.has(_)).map(_=>Rw(e.doc(t,`${r}/${_}`)))]},[l,g,e,t,r]),w=r.split("/").pop()??r,[x,k]=h.useState(null),[j,S]=h.useState(!1),N=yt(),P=h.useMemo(()=>Dc(e,n),[e,n]),I=h.useCallback(async C=>{k(null);try{await $c({confirm:N,ref:C,api:e,recursiveImpl:P})}catch(_){k(_ instanceof Error?_:new Error(String(_)))}},[e,N,P]),D=h.useCallback(async()=>{if(await N({title:`Delete collection "${w}"?`,body:"This deletes every document in it (and their subcollections).",destructive:!0,confirmLabel:"Delete collection"})){k(null);try{await Pc(P,c),a()}catch(_){k(_ instanceof Error?_:new Error(String(_)))}}},[N,P,c,w,a]);return o.jsxs("section",{"data-pyric-ui":"fs-documents",className:"fs-pane fs-col",children:[o.jsxs("div",{className:"fs-phead",children:[o.jsx("span",{className:"fs-phead-title",children:w}),o.jsx("span",{className:"fs-phead-actions",children:o.jsx("button",{type:"button",className:"fs-add",onClick:()=>S(!0),children:"+ New"})}),o.jsx(Ec,{items:[{label:"Delete collection",onSelect:()=>void D(),destructive:!0}]})]}),j?o.jsx(_c,{mode:"document",parentPath:`/${r}`,onCreate:async({docId:C,data:_})=>{const E=await y(C,_,{onExisting:"fail"});i(E)},onClose:()=>S(!1)}):null,o.jsx(bv,{documents:b,isLoading:u,error:d,updateScope:`${r}:${p}`,hasMore:f,onLoadMore:m,onSelect:i,renderLabel:C=>{const _=C.ref;return o.jsx("span",{"data-pyric-selected":s===_.id?"":void 0,style:{display:"contents"},children:Yi(C)?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"fs-doc-phantom",children:C.id}),o.jsx("span",{className:"fs-sub fs-doc-phantom-hint",children:"missing"})]}):C.id})},renderRowAction:C=>{if(Yi(C))return null;const _=C.ref;return o.jsx("button",{type:"button",className:"fs-doc-del",title:"Delete document","aria-label":`Delete ${_.id}`,onClick:E=>{E.stopPropagation(),I(_)},children:"×"})},emptyState:o.jsx("p",{className:"fs-empty",children:"No documents."})}),x?o.jsx("p",{className:"fs-empty fs-doc-del-err",children:x.message}):null]})}function Mw({api:e,firestore:t,handles:n,docPath:r,onOpenSubcollection:s,onReferenceClick:i,onStartCollection:a,onDeleted:c}){const l=h.useMemo(()=>e.doc(t,r),[e,t,r]),{data:u,error:d,isLoading:p}=pg(l),f=h.useCallback(async(k,j)=>(await n.listSubcollections(j.path)).map(N=>e.collection(j,N)),[n,e]),m=yt(),y=h.useMemo(()=>Dc(e,n),[e,n]),[g,v]=h.useState(null),b=h.useCallback(async()=>{v(null);try{await $c({confirm:m,ref:l,api:e,recursiveImpl:y})&&c()}catch(k){v(k instanceof Error?k:new Error(String(k)))}},[e,m,y,l,c]),w=h.useCallback(async()=>{await e.setDoc(l,{})},[e,l]),x=u!=null&&Cw(u);return o.jsxs("section",{"data-pyric-ui":"fs-document",className:"fs-pane fs-col doc",children:[x?null:o.jsxs("div",{className:"fs-phead",children:[o.jsx("span",{className:"fs-phead-title",children:l.id}),o.jsx("span",{className:"fs-phead-actions",children:o.jsx("button",{type:"button",className:"fs-add",onClick:a,children:"+ Collection"})})]}),u&&x?o.jsx(kw,{snapshot:u,documentRef:l,firestore:t,listSubcollections:f,onReferenceClick:i,onSubcollectionClick:s,onStartCollection:a,onDeleteDocument:()=>void b(),onDeleteDocumentFields:w,onCommit:async k=>{await e.setDoc(l,k)}},r):d?o.jsx("p",{className:"fs-empty fs-doc-del-err",children:d.message}):p?o.jsx("p",{className:"fs-empty",children:"Loading document…"}):o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"fs-empty",children:"This document does not exist."}),o.jsx(Ic,{firestore:t,documentRef:l,listSubcollections:f,onSubcollectionClick:s})]}),g?o.jsx("p",{className:"fs-empty fs-doc-del-err",children:g.message}):null]})}const Uw="block w-full text-sm text-soft-white";function Tw({auth:e,focusUid:t}){const{users:n,totalCount:r,isLoading:s,error:i,filter:a,setFilter:c,updateUser:l}=ps(e),[u,d]=h.useState(null);h.useEffect(()=>{t&&(d(t),c(t))},[t,c]);const p=n.find(f=>f.uid===u)??null;return o.jsxs("div",{className:"grid grid-cols-[1fr_320px] gap-4",children:[o.jsxs("section",{className:"min-w-0",children:[o.jsx("input",{value:a,onChange:f=>c(f.target.value),placeholder:"Filter users…",className:"mb-3 w-full rounded border border-border bg-content-bg px-3 py-1.5 text-sm text-soft-white placeholder:text-slate-gray"}),o.jsx(Xo,{users:n,isLoading:s,error:i,filter:a,onSelect:f=>d(f.uid),className:Uw,emptyState:o.jsx("p",{className:"py-6 text-sm text-slate-gray",children:"No users yet. Sign in from the app, or the agent seeds them, and they appear here."}),noResultsState:o.jsx("p",{className:"py-6 text-sm text-slate-gray",children:"No users match the filter."})}),o.jsxs("p",{className:"mt-2 text-xs text-slate-gray",children:[r," user(s) total"]})]}),o.jsx("section",{className:"min-w-0 border-l border-border pl-4",children:p?o.jsx(Bw,{user:p,onSave:f=>l(p.uid,f)},p.uid):o.jsx("p",{className:"py-6 text-sm text-slate-gray",children:"Select a user to view and edit."})})]})}function Bw({user:e,onSave:t}){const n=Qo({initial:e}),[r,s]=h.useState(null),[i,a]=h.useState(!1),c=()=>{s(null),a(!1);try{t(n.toUpdateRequest()),a(!0)}catch(l){s(l instanceof Error?l:new Error(String(l)))}};return o.jsxs("div",{"data-pyric-ui":"auth-editor",children:[o.jsx("h3",{className:"mb-3 truncate font-mono text-xs text-slate-gray",title:e.uid,children:e.uid}),o.jsxs("label",{className:"mb-3 block text-xs text-slate-gray",children:["Display name",o.jsx("input",{value:n.fields.displayName,onChange:l=>n.setField("displayName",l.target.value),className:"mt-1 w-full rounded border border-border bg-content-bg px-2 py-1 text-sm text-soft-white"})]}),o.jsxs("label",{className:"mb-3 block text-xs text-slate-gray",children:["Custom claims (JSON)",o.jsx("textarea",{value:n.fields.claimsText,onChange:l=>n.setField("claimsText",l.target.value),rows:6,spellCheck:!1,className:"mt-1 w-full rounded border border-border bg-content-bg p-2 font-mono text-xs text-soft-white"}),n.errors.claims?o.jsx("span",{className:"text-danger",children:n.errors.claims}):null]}),o.jsxs("label",{className:"mb-3 flex items-center gap-2 text-xs text-slate-gray",children:[o.jsx("input",{type:"checkbox",checked:n.fields.disabled,onChange:l=>n.setField("disabled",l.target.checked)}),"Disabled"]}),r?o.jsx("p",{className:"mb-2 text-xs text-danger",children:r.message}):null,i?o.jsx("p",{className:"mb-2 text-xs text-primary",children:"Saved."}):null,o.jsxs("div",{className:"flex gap-2",children:[o.jsx("button",{type:"button",onClick:c,disabled:!n.isValid||!n.isDirty,className:"rounded bg-primary/15 px-3 py-1 text-xs font-medium text-primary hover:bg-primary/25 disabled:opacity-40",children:"Save"}),o.jsx("button",{type:"button",onClick:n.reset,disabled:!n.isDirty,className:"rounded border border-border px-3 py-1 text-xs text-slate-gray hover:text-soft-white disabled:opacity-40",children:"Reset"})]})]})}function Qi(e){const t=Q(e),n=t.lastIndexOf("/");return n===-1?"":t.slice(0,n)}function Xi(e,t){return e===""?t:t===""?e:`${e}/${t}`}function Zi(e){const t=e.lastIndexOf("/");return t===-1?e:e.slice(t+1)}const Lw=[{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 Fw(e){const t=Object.entries(e.customMetadata??{});return o.jsxs("dl",{"data-pyric-object-metadata":!0,children:[o.jsx("div",{"data-storage-meta-group":!0,children:"Metadata"}),Lw.map(({key:n,label:r,value:s})=>{const i=s(e);return i===void 0?null:o.jsxs("div",{"data-pyric-metadata-field":n,children:[o.jsx("dt",{children:r}),o.jsx("dd",{children:i})]},n)}),t.length>0?o.jsx("div",{"data-storage-meta-group":!0,children:"Custom metadata"}):null,t.map(([n,r])=>o.jsxs("div",{"data-pyric-metadata-field":"customMetadata","data-pyric-metadata-key":n,children:[o.jsx("dt",{children:n}),o.jsx("dd",{children:r})]},`custom:${n}`))]})}function Vw(){return o.jsx("svg",{"aria-hidden":!0,viewBox:"0 0 16 16",width:"13",height:"13",fill:"none",stroke:"currentColor",strokeWidth:"1.25",strokeLinejoin:"round",children:o.jsx("path",{d:"M1.75 4.25c0-.55.45-1 1-1h3.4l1.5 1.7h5.6c.55 0 1 .45 1 1v6.05c0 .55-.45 1-1 1H2.75c-.55 0-1-.45-1-1z"})})}function qw(){return o.jsxs("svg",{"aria-hidden":!0,viewBox:"0 0 16 16",width:"13",height:"13",fill:"none",stroke:"currentColor",strokeWidth:"1.25",strokeLinejoin:"round",children:[o.jsx("path",{d:"M4.25 1.75h5l3 3v9.5h-8z"}),o.jsx("path",{d:"M9.25 1.75v3h3"})]})}function Ww(e){const t=e.kind==="folder";return o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"storage__cell-name",children:[o.jsx("span",{className:"storage__ic","aria-hidden":!0,children:t?o.jsx(Vw,{}):o.jsx(qw,{})}),o.jsx("span",{className:"storage__nm",children:e.name}),t?o.jsx("span",{"aria-hidden":!0,className:"storage__chev",children:"›"}):null]}),o.jsx("span",{className:"storage__cell-type",children:t?"folder":"file"}),o.jsx("span",{className:"storage__cell-size"}),o.jsx("span",{className:"storage__cell-updated"})]})}function zw({storage:e,focusTarget:t}){const n=Un(),r=t.kind==="object"?Q(t.path):null,s=t.kind==="prefix"?Q(t.path):r?Qi(r):"",i=h.useCallback(C=>{const _=Q(C);n.navigate(_?{view:"storage",kind:"prefix",path:_}:{view:"storage",kind:"root"})},[n.navigate]),a=Ev({path:s,onPathChange:i}),c=C=>{n.navigate({view:"storage",kind:"object",path:Q(C)})},l=_v(e,a.path),u=Nv(),d=$v(e),[p,f]=h.useReducer(zv,xc),m=Uv(e,{path:a.path,list:l,onComplete:C=>f({type:"materialize",path:Qi(C.fullPath)})});h.useEffect(()=>{if(l.status==="success")for(const C of l.entries)C.kind==="folder"&&Hi(p,C.fullPath)&&f({type:"materialize",path:C.fullPath})},[l.status,l.entries,p]);const[y,g]=h.useState(!1),[v,b]=h.useState(""),[w,x]=h.useState(null),k=h.useRef(null),j=h.useMemo(()=>{const C=Kv(p,a.path).filter(R=>!l.entries.some(V=>V.kind==="folder"&&V.name===R));if(C.length===0)return l.entries;const _=C.map(R=>{const V=Xi(a.path,R);return{kind:"folder",name:R,fullPath:V,ref:{fullPath:V,name:R}}});return[...[...l.entries.filter(R=>R.kind==="folder"),..._].sort((R,V)=>R.name<V.name?-1:R.name>V.name?1:0),...l.entries.filter(R=>R.kind==="object")]},[l.entries,p,a.path]),S=j.length>0&&j.every(C=>u.isSelected(C.fullPath)),N=C=>{const _=new Set(j.map(R=>R.name)),E=Wv(C.map(R=>R.relativePath),_);m.upload(C.map((R,V)=>({path:E[V],data:R.file})))},P=C=>{C.preventDefault();const _=Hv(v);if(_){x(_);return}const E=Xi(a.path,Q(v));f({type:"create",path:E}),a.setPath(E),b(""),x(null),g(!1)};h.useEffect(()=>u.clear(),[a.path,u.clear]);const I=m.tasks.filter(C=>C.status==="error"),D=d.verdictFor(a.path);return o.jsx(sw,{children:o.jsx(ms,{children:o.jsxs("div",{className:"storage",children:[o.jsxs("div",{className:"storage__sub",children:[o.jsx(Tv,{path:a.path,rootLabel:"files",onNavigate:a.setPath}),o.jsx("div",{className:"storage__actions",children:u.size>0?o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"studio-selection-count",children:[u.size," selected"]}),o.jsx(aw,{storage:e,entries:u.selected,list:l,gate:d,className:"studio-selection-delete",onDeleted:C=>{for(const _ of u.selected)_.kind==="folder"&&C.deleted.includes(_.fullPath)&&f({type:"discard",path:_.fullPath});r&&u.selected.some(_=>_.kind==="object"?_.fullPath===r:r.startsWith(`${_.fullPath}/`))&&a.setPath(a.path),u.clear(),l.refresh()},onFailed:C=>{const _=new Set(C.failed.map(E=>E.fullPath));u.selectAll(u.selected.filter(E=>_.has(E.fullPath))),l.refresh()}}),o.jsx("button",{type:"button",className:"storage__action",onClick:u.clear,children:"Clear selection"})]}):o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:"storage__action","aria-expanded":y,onClick:()=>{g(C=>!C),x(null)},children:"New folder"}),o.jsx("button",{type:"button",className:"storage__action storage__action--upload",onClick:()=>k.current?.click(),children:"Upload files"}),o.jsx("input",{ref:k,type:"file",multiple:!0,hidden:!0,onChange:C=>{const _=Array.from(C.currentTarget.files??[]);_.length>0&&N(_.map(E=>({file:E,relativePath:E.name}))),C.currentTarget.value=""}})]})})]}),y?o.jsxs("form",{className:"storage__newfolder",onSubmit:P,children:[o.jsx("input",{autoFocus:!0,className:"storage__newfolder-input",placeholder:"folder or nested/path/of/folders","aria-label":"New folder name",value:v,onChange:C=>{b(C.currentTarget.value),x(null)},onKeyDown:C=>{C.key==="Escape"&&g(!1)}}),o.jsx("button",{type:"submit",className:"storage__newfolder-btn",children:"Create"}),w?o.jsx("span",{className:"storage__newfolder-err",role:"alert",children:w}):o.jsx("span",{className:"storage__newfolder-note",children:"Nested paths create the whole chain. Empty folders last this session only — upload a file to keep one."})]}):null,I.length>0?o.jsxs("p",{className:"storage__upload-err",role:"alert",children:[I.length===1?`Upload failed: ${Zi(I[0].fullPath)} — ${I[0].error?.message??"error"}`:`${I.length} uploads failed: ${I.map(C=>Zi(C.fullPath)).join(", ")}`,o.jsx("button",{type:"button",className:"storage__upload-err-dismiss",onClick:m.clearCompleted,children:"Dismiss"})]}):null,o.jsxs("div",{className:"storage__body","data-storage-level":r?"inspector":"browser",children:[o.jsxs(Fv,{className:"storage__browser",onFiles:N,disabled:!D.upload,disabledReason:D.reasons.write.join("; "),children:[o.jsxs("div",{className:"storage__lhead",children:[o.jsx("label",{className:"storage__select-all",title:"Select all in this folder",children:o.jsx("input",{type:"checkbox","aria-label":"Select all in this folder",checked:S,onChange:C=>C.currentTarget.checked?u.selectAll(j):u.clear()})}),o.jsx("span",{children:"name"}),o.jsx("span",{children:"type"}),o.jsx("span",{children:"size"}),o.jsx("span",{children:"updated"})]}),o.jsx(Bv,{entries:j,status:l.status,error:l.error,gate:d,selectedPath:r??void 0,renderEntry:Ww,renderRowAction:C=>o.jsx("label",{className:"storage__select-row",title:`Select ${C.name}`,children:o.jsx("input",{type:"checkbox","aria-label":`Select ${C.name}`,checked:u.isSelected(C.fullPath),onChange:()=>u.toggle(C)})}),onNavigate:a.enter,onSelect:C=>c(C.fullPath),emptyState:o.jsx("p",{className:"storage__empty",children:Hi(p,a.path)?"Empty folder — session-only until a file is uploaded here. Drop files anywhere in this pane, or use Upload files.":"No files yet. Drop files here or use Upload files; files your app uploads to Storage also appear here."})}),o.jsxs("div",{className:"storage__dropcue","aria-hidden":!0,children:["Drop to upload to /",a.path||""]})]}),o.jsx("div",{className:"storage__inspector",children:r?o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:"storage__back",onClick:()=>a.setPath(a.path),"aria-label":"Back to files",children:"‹ Files"}),o.jsx(nw,{storage:e,path:r,renderMetadata:Fw})]}):o.jsx("p",{className:"storage__inspector-hint",children:"Select an object to inspect its preview and metadata."})})]})]})})})}function Kw({view:e}){const t=e==="firestore"?"Firestore":e==="auth"?"Auth":"Storage";return o.jsxs("div",{"data-pyric-ui":"data-pending",className:"flex flex-col items-center justify-center gap-2 py-16 text-center",children:[o.jsx("span",{className:"rounded-full border border-border px-3 py-1 text-xs uppercase tracking-wide text-slate-gray",children:"Local backend pending"}),o.jsxs("p",{className:"max-w-md text-sm leading-relaxed text-slate-gray",children:["The ",t," viewer mounts here. It goes live once the local sandbox backend is reachable (the served `pyric dev --ui` workspace)."]})]})}function Oc({view:e}){const{target:t}=Un(),n=Oe(),r=n.status==="ready"?n.handles.auth:null;return o.jsx("div",{"data-pyric-ui":"data-feature",children:n.status!=="ready"||!r?o.jsx(Kw,{view:e}):n.authApi?o.jsx(Ho,{value:n.authApi,children:o.jsx(ea,{view:e,handles:n.handles,auth:r,target:t,firestoreApi:n.firestoreApi,storageApi:n.storageApi})}):o.jsx(ea,{view:e,handles:n.handles,auth:r,target:t,firestoreApi:n.firestoreApi,storageApi:n.storageApi})})}function ea({view:e,handles:t,auth:n,target:r,firestoreApi:s,storageApi:i}){const{users:a}=ps(n),c=h.useMemo(()=>new Set(a.map(l=>l.uid)),[a]);switch(e){case"firestore":{const l=o.jsx(Iw,{handles:t,knownUids:c});return s?o.jsx(hg,{value:s,children:l}):l}case"auth":return o.jsx(Tw,{auth:n,focusUid:r?.view==="auth"?r.uid:null});case"storage":{const l=o.jsx(zw,{storage:t.storage,focusTarget:r?.view==="storage"?r:{kind:"root"}});return i?o.jsx(Sv,{value:i,children:l}):l}}}function Hw(){return o.jsx(Oc,{view:"firestore"})}function Gw(){return o.jsx(Oc,{view:"storage"})}function Jw(e,t){const n=new Set(t.map(r=>r.uid));return new Set([...e].filter(r=>n.has(r)))}async function Yw(e,t){const n=[];for(const r of e)try{await t(r.uid)}catch{n.push(r.uid)}return n}function Qw(e){const[t,n]=h.useState(()=>new Set);h.useEffect(()=>{n(s=>{const i=Jw(s,e);return i.size===s.size&&[...i].every(a=>s.has(a))?s:i})},[e]);const r=h.useMemo(()=>e.filter(s=>t.has(s.uid)),[t,e]);return{selectedUsers:r,allVisibleSelected:e.length>0&&r.length===e.length,isSelected:s=>t.has(s),toggle(s){n(i=>{const a=new Set(i);return a.has(s)?a.delete(s):a.add(s),a})},selectAll(s){n(s?new Set(e.map(i=>i.uid)):new Set)},replace(s){n(new Set(s))},clear(){n(new Set)}}}function Xw({users:e,filter:t,onDelete:n,onComplete:r}){const s=yt(),[i,a]=h.useState(!1),[c,l]=h.useState(null),u=async()=>{const d=t.trim().length>0;if(!await s({title:`Delete ${e.length} ${e.length===1?"user":"users"}?`,body:d?`Only the ${e.length} users shown by the current filter will be deleted.`:`This will permanently delete the ${e.length} selected users.`,destructive:!0,confirmLabel:"Delete users"}))return;a(!0),l(null);const f=await Yw(e,n);a(!1),l(f.length>0?`Could not delete ${f.length} selected user(s).`:null),r(f)};return o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:"studio-selection-delete",disabled:i,onClick:()=>void u(),children:i?"Deleting…":"Delete"}),c?o.jsx("span",{className:"auth-sub__error",children:c}):null]})}function Mc(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 Uc(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 Zw(e){const t=e.isAnonymous&&!e.email,n=e.email??e.phoneNumber??(t?"anonymous":e.uid);return o.jsxs("span",{className:t?"auth-ident auth-ident--anon":"auth-ident",children:[o.jsx("span",{className:"auth-ident__primary",title:n,children:n}),o.jsx("span",{className:"auth-ident__uid",title:e.uid,children:e.uid})]})}function ex({auth:e}={}){const t=$e(),n=Oe(),r=e??(n.status==="ready"?n.handles.auth:null),s=n.status==="ready"?n.authApi:void 0;if(!r)return o.jsx("div",{className:"auth-surface","data-pyric-ui":"auth-surface",children:o.jsx(ix,{status:t.status})});const i=o.jsx(ms,{children:o.jsx(tx,{auth:r})});return s?o.jsx(Ho,{value:s,children:i}):i}function tx({auth:e}){const{users:t,totalCount:n,isLoading:r,error:s,filter:i,setFilter:a,createUser:c,updateUser:l,deleteUser:u}=ps(e),d=Un(),p=d.target?.view==="auth"?d.target.uid:null,f=b=>d.navigate({view:"auth",uid:b}),m=h.useMemo(()=>t.find(b=>b.uid===p)??null,[t,p]),[y,g]=h.useState(!1),v=Qw(t);return o.jsxs("div",{className:"auth-surface","data-pyric-ui":"auth-surface",children:[o.jsxs("div",{className:"auth-sub",children:[o.jsxs("span",{className:"auth-sub__h",children:["users ",o.jsxs("span",{className:"auth-sub__n",children:["· ",n]})]}),o.jsx("input",{className:"auth-sub__filter",value:i,onChange:b=>a(b.target.value),placeholder:"filter users…","aria-label":"Filter users"}),o.jsx("div",{className:"auth-sub__right",children:v.selectedUsers.length>0?o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"studio-selection-count",children:[v.selectedUsers.length," selected"]}),o.jsx(Xw,{users:v.selectedUsers,filter:i,onDelete:b=>Promise.resolve(u(b)),onComplete:b=>{v.replace(b),p&&!b.includes(p)&&f(null)}}),o.jsx("button",{type:"button",className:"auth-sub__clear",onClick:v.clear,children:"Clear selection"})]}):o.jsx("button",{type:"button",className:"auth-sub__add",onClick:()=>{g(!0),f(null)},children:"Add user"})})]}),o.jsxs("div",{className:"auth-body","data-auth-level":m||y?"detail":"list",children:[o.jsx("div",{className:"auth-list",children:o.jsx(Xo,{users:t,isLoading:r,error:s,filter:i,onSelect:b=>{g(!1),f(b.uid)},renderIdentifier:Zw,formatCreatedAt:Uc,formatLastLoginAt:Mc,renderSelectionHeader:o.jsx("label",{className:"auth-select",title:"Select all shown users",children:o.jsx("input",{type:"checkbox","aria-label":"Select all shown users",checked:v.allVisibleSelected,onChange:b=>v.selectAll(b.currentTarget.checked)})}),renderSelection:b=>o.jsx("label",{className:"auth-select",title:`Select ${b.uid}`,children:o.jsx("input",{type:"checkbox","aria-label":`Select ${b.uid}`,checked:v.isSelected(b.uid),onChange:()=>v.toggle(b.uid)})}),emptyState:o.jsx("p",{className:"auth-zero",children:"No users yet. Sign-ins from the app, agent-seeded users, and “Add user” all land here."}),noResultsState:o.jsxs("p",{className:"auth-zero",children:["No users match “",i,"”."]})})}),o.jsx("div",{className:"auth-detail",children:y?o.jsx(nx,{onCancel:()=>g(!1),onCreate:async b=>{const w=await Promise.resolve(c(b));g(!1),f(w.uid)}}):m?o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:"auth-back",onClick:()=>f(null),"aria-label":"Back to users",children:"‹ Users"}),o.jsx(sx,{user:m,onSave:b=>{b.mode==="edit"&&l(b.uid,b.request)},onProvidersChange:async b=>{await Promise.resolve(l(m.uid,{providerUserInfo:b}))},onDelete:()=>{u(m.uid),f(null)}},m.uid)]}):o.jsx("div",{className:"auth-detail__empty",children:o.jsx("p",{className:"auth-zero",children:"Select a user to view and edit."})})})]})]})}function nx({onCreate:e,onCancel:t}){const[n,r]=h.useState(null),s=i=>{i.mode==="create"&&(r(null),e(i.request).catch(a=>{r(a instanceof Error?a:new Error(String(a)))}))};return o.jsxs("div",{className:"auth-editor","data-pyric-ui":"auth-create-user",children:[o.jsxs("div",{className:"auth-editor__head",children:[o.jsx("div",{className:"auth-editor__who",children:"New user"}),o.jsx("div",{className:"auth-editor__meta",children:"Created without signing in — admin semantics, like the emulator’s add-user flow."})]}),o.jsx(Zo,{onSubmit:s,onCancel:t,submitLabel:"Create user",children:n?o.jsx("p",{className:"auth-save auth-save--error",role:"alert",children:n.message}):null})]})}const ta=[...Do];function rx({user:e,onChange:t}){const[n,r]=h.useState(null),[s,i]=h.useState(""),a=e.providerUserInfo.map(m=>m.providerId),c=a.includes("password"),l=a.filter(m=>m!=="password"),u=l.filter(m=>!ta.includes(m)),d=m=>{r(null),t(m.map(y=>({providerId:y}))).catch(y=>{r(y instanceof Error?y:new Error(String(y)))})},p=(m,y)=>{d(y?[...l,m]:l.filter(g=>g!==m))},f=()=>{const m=s.trim();m&&(i(""),!l.includes(m)&&d([...l,m]))};return o.jsxs("section",{className:"auth-providers-editor","aria-label":"Sign-in providers",children:[o.jsx("div",{className:"auth-group",children:"Sign-in providers"}),o.jsx("div",{className:"auth-providers-editor__list",children:[...ta,...u].map(m=>o.jsxs("label",{className:"auth-provider-row","data-pyric-provider-id":m,children:[o.jsx("input",{type:"checkbox",checked:l.includes(m),onChange:y=>p(m,y.target.checked)}),o.jsx("span",{className:"auth-provider-row__label",children:mn(m)}),o.jsx("span",{className:"auth-provider-row__id",children:m})]},m))}),c||e.isAnonymous?o.jsx("p",{className:"auth-providers-editor__derived",children:c?"Password is linked by the password credential above.":"Anonymous — the provider lives on the token, not the record."}):null,o.jsx("div",{className:"auth-provider-custom",children:o.jsxs("label",{className:"auth-provider-custom__field",children:[o.jsx("span",{className:"auth-provider-custom__label",children:"Custom provider ID"}),o.jsxs("span",{className:"auth-provider-custom__row",children:[o.jsx("input",{type:"text",value:s,placeholder:"oidc.my-provider",onChange:m=>i(m.target.value),onKeyDown:m=>{m.key==="Enter"&&(m.preventDefault(),f())}}),o.jsx("button",{type:"button",onClick:f,disabled:!s.trim(),children:"Link"})]})]})}),n?o.jsx("p",{className:"auth-save auth-save--error",role:"alert",children:n.message}):null]})}function sx({user:e,onSave:t,onProvidersChange:n,onDelete:r}){const[s,i]=h.useState(null),[a,c]=h.useState(!1),l=p=>{i(null),c(!1);try{t(p),c(!0)}catch(f){i(f instanceof Error?f:new Error(String(f)))}},u=Uc(e.createdAt),d=Mc(e.lastLoginAt);return o.jsxs("div",{className:"auth-editor","data-pyric-user-disabled":e.disabled?"":void 0,children:[o.jsxs("div",{className:"auth-editor__head",children:[o.jsxs("div",{className:"auth-editor__who",children:[e.email??(e.isAnonymous?"anonymous":e.uid),e.disabled?o.jsx("span",{className:"auth-tag-off",children:"disabled"}):null]}),o.jsxs("div",{className:"auth-editor__uid",children:["uid · ",e.uid]}),o.jsxs("div",{className:"auth-editor__meta",children:["created ",u," · signed in ",d]})]}),o.jsx(rx,{user:e,onChange:n}),o.jsxs(Zo,{initial:e,onSubmit:l,submitLabel:"Save",children:[s?o.jsx("p",{className:"auth-save auth-save--error",role:"alert",children:s.message}):null,a?o.jsx("p",{className:"auth-save auth-save--ok",children:"Saved."}):null]},e.uid),o.jsx("div",{className:"auth-editor__foot",children:o.jsx(ug,{user:e,onDelete:r,className:"auth-del"})})]})}function ix({status:e}){const t=e==="pending"?"Seeding the sandbox…":e==="error"?"The dev-seed failed. Check the console.":"No sandbox Auth handle. Run with the dev-seed (DEV) or a live env.";return o.jsx("div",{className:"auth-detail__empty","data-pyric-ui":"auth-surface-empty",children:o.jsx("p",{className:"auth-zero",children:t})})}function ax(e){return e.operationContext.source.kind==="studio"}function ox(e,t){return t?e.filter(n=>!ax(n)):[...e]}const cx=["all","allow","deny","bypassed"];function Tn(e){return e.rulesDisposition.kind==="bypassed"?"bypassed":e.rulesDisposition.kind==="evaluated"?e.rulesDisposition.verdict:null}function lx(e,t){return t==="all"?[...e]:e.filter(n=>Tn(n)===t)}function nr(e){return e.rulesDisposition.kind==="evaluated"}function na(e){const t=e.path;if(e.service==="storage"&&e.method==="list"&&(t===""||t==="/"))return{tab:"storage"};if(!t||t==="(service)")return null;const n=t.split("/").filter(Boolean);switch(e.service??"firestore"){case"firestore":return n.length?{tab:"firestore",rest:n}:null;case"rtdb":return{tab:"rtdb"};case"storage":return n.length?{tab:"storage",rest:n,...e.method==="list"?{query:{kind:"prefix"}}:{}}:null;case"auth":return t!=="*"?{tab:"auth",rest:[t]}:null;default:return null}}const Fr="inspect";function Tc(e){const t=e[Fr];return t||null}function Bc(e,t){const{[Fr]:n,...r}=e;return t?{...r,[Fr]:t}:r}function ux(e,t){return Bc(e,Tc(e)===t?null:t)}const dx=h.lazy(()=>Xa(()=>import("./RulesCodeEditor.Bl-XMkhD.js"),__vite__mapDeps([5,1,3])));function Lc(e){return o.jsx(h.Suspense,{fallback:o.jsx(fx,{value:e.value,minHeightRem:e.minHeightRem}),children:o.jsx(dx,{...e})})}function fx({value:e,minHeightRem:t=14}){return o.jsx("pre",{"data-pyric-ui":"rules-code-editor-loading",className:"overflow-auto rounded-md border border-border bg-content-bg p-3 font-mono text-xs text-slate-gray",style:{minHeight:`${t}rem`},children:e||"Loading editor…"})}function Fc({denial:e,rulesSource:t}){const n=py(e);return o.jsxs("div",{"data-pyric-ui":"denial-detail",className:"flex min-h-0 flex-col gap-4 overflow-auto rounded-lg border border-border bg-sidebar-bg p-5",children:[o.jsxs("section",{children:[o.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.result==="allow"?o.jsx(Dr,{kind:"allow",className:"rounded bg-primary/15 px-2 py-0.5 text-xs font-semibold uppercase text-primary",children:"allowed"}):o.jsx(Dr,{kind:"deny",className:"rounded bg-danger/15 px-2 py-0.5 text-xs font-semibold uppercase text-danger",children:e.unsupported?"unsupported":"denied"}),o.jsxs("span",{className:"font-mono text-sm text-soft-white",children:[e.service!=="firestore"?`${e.service} · `:"",e.method," ",e.path]})]}),o.jsx("p",{className:"text-sm leading-relaxed text-soft-white",children:n.headline})]}),n.noEvaluation?o.jsx("p",{"data-pyric-ui":"rules-debug-no-evaluation",className:"rounded-md border border-border bg-content-bg px-3 py-2 text-xs text-slate-gray",children:"No matched rule, evaluation trace, or re-run is shown because this event carries no rules verdict to ground them in."}):o.jsxs(o.Fragment,{children:[o.jsx(hx,{denial:e,exp:n,rulesSource:t}),o.jsx(gx,{denial:e})]}),o.jsx(wx,{denial:e})]})}function hx({denial:e,exp:t,rulesSource:n}){const r=t.engine==="rtdb",s=t.engine==="storage";return r?o.jsx(kx,{denial:e,exp:t,rulesSource:n}):s?o.jsx(Sx,{exp:t}):o.jsx(bx,{denial:e,exp:t,rulesSource:n})}function px(e){const t="// @pyric-source-map:",n=e.indexOf(t);if(!(n!==-1))return null;const s=n+t.length,i=e.slice(s).trim();try{const a=JSON.parse(i);return Array.isArray(a)?a:null}catch{return null}}function mx(e){const n=e.indexOf("// @pyric-source-map:");return n!==-1?e.slice(0,n).trimEnd():e}function yx(e,t){if(e===void 0||t===void 0)return t;const s=px(e);if(s!==null){const a=s.find(l=>l.authoredLine===t);if(a!==void 0)return a.generatedLine}return t}function bx({denial:e,exp:t,rulesSource:n}){const r=e.evaluatedRule?.line,s=yx(n,r),i=n!==void 0?mx(n):void 0,a=e.result==="allow",c=!!(i&&i.trim().length>0);return o.jsx(Ae,{label:t.implicitDeny||!t.ruleNode?"matched rule":`matched rule — ${t.ruleNode}${r?` · line ${r}`:""}`,children:c?o.jsx(Lc,{value:i,readOnly:!0,markLine:s,markKind:a?"allow":"deny",minHeightRem:12,ariaLabel:`Deployed firestore.rules — the ${a?"allowing":"denying"} rule is marked`}):o.jsx("pre",{className:"overflow-auto rounded-md border border-border bg-content-bg p-3 font-mono text-xs leading-relaxed text-slate-gray",children:[...t.ruleLines,...t.otherLines].join(`
|
|
10
|
+
`)||"(no trace)"})})}function gx({denial:e}){const t=vy(e);return t.length===0?null:o.jsx(Ae,{label:"show the work — how the condition evaluated",children:o.jsx("div",{"data-pyric-ui":"rules-debug-trace",className:"flex flex-col gap-0.5 overflow-auto rounded-md border border-border bg-content-bg p-3",children:t.map((n,r)=>o.jsx(Vc,{step:n},r))})})}const vx={true:"✓",false:"✗",skipped:"⊘",error:"!",value:"·"};function Vc({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:`→ ${qc(e.value)}`;return o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"flex items-baseline gap-2 font-mono text-xs",style:{paddingLeft:`${e.depth*.9}rem`},children:[o.jsx("span",{"aria-hidden":!0,className:`w-3 shrink-0 text-center font-bold ${t}`,children:vx[e.outcome]}),o.jsxs("span",{className:e.outcome==="skipped"?"text-slate-gray line-through":"text-soft-white",children:[e.letBinding?`let ${e.letBinding} = `:"",e.source]}),o.jsx("span",{className:"text-slate-gray",children:n}),e.inlinedFrom?o.jsxs("span",{className:"text-[0.6rem] uppercase tracking-wide text-slate-gray",children:[e.inlinedFrom,"()"]}):null]}),e.children.map((r,s)=>o.jsx(Vc,{step:r},s))]})}function qc(e){if(e===void 0)return"undefined";try{return JSON.stringify(yn(e))}catch{return String(e)}}function wx({denial:e}){const t=wy(e);return o.jsx(Ae,{label:"what the rule saw (request / resource)",children:o.jsx("div",{"data-pyric-ui":"rules-debug-variables",className:"flex flex-col gap-2 rounded-md border border-border bg-content-bg p-3",children:t.map(n=>o.jsx(xx,{variable:n},n.name))})})}function xx({variable:e}){return o.jsxs("div",{className:"flex flex-col gap-0.5",children:[o.jsx("span",{className:"font-mono text-[0.7rem] text-primary",children:e.name}),e.present?o.jsx(Wc,{value:e.value}):o.jsxs("span",{className:"font-mono text-xs italic text-slate-gray",children:["absent",e.absentNote?` — ${e.absentNote}`:""]})]})}function Wc({value:e,depth:t=0}){const[n,r]=h.useState(t<2),s=yn(e);if(s===null||typeof s!="object")return o.jsx("span",{className:"font-mono text-xs text-soft-white",children:qc(s)});const i=Array.isArray(s)?s.map((a,c)=>[String(c),a]):Object.entries(s);return i.length===0?o.jsx("span",{className:"font-mono text-xs text-slate-gray",children:Array.isArray(s)?"[]":"{}"}):o.jsxs("div",{className:"flex flex-col",children:[o.jsxs("button",{type:"button",onClick:()=>r(a=>!a),"aria-expanded":n,className:"flex w-fit items-center gap-1 font-mono text-xs text-slate-gray hover:text-soft-white",children:[o.jsx("span",{"aria-hidden":!0,children:n?"▾":"▸"}),o.jsx("span",{children:Array.isArray(s)?`[${i.length}]`:`{${i.length}}`})]}),n?o.jsx("div",{className:"flex flex-col gap-0.5 border-l border-border pl-3",children:i.map(([a,c])=>o.jsxs("div",{className:"flex flex-wrap items-baseline gap-2",children:[o.jsxs("span",{className:"font-mono text-xs text-slate-gray",children:[a,":"]}),o.jsx(Wc,{value:c,depth:t+1})]},a))}):null]})}function jx(e,t,n,r){if(!e||!n)return;const i=e.split(/\r?\n/),a=t!==void 0&&t.length>0;let c;a?c=`".${t}"`:c=null;const l=[];for(let m=0;m<i.length;m++){const y=i[m];!y.includes(n)||!(c===null||y.includes(c))||l.push(m+1)}if(l.length===1)return l[0];if(l.length===0)return;const d=(r??"").split("/").filter(Boolean);if(d.length===0)return l[0];let p=l[0],f=-1;for(const m of l){let y=0;const g=m-2,v=Math.max(0,g-30);for(let b=g;b>=v;b--){const w=i[b];for(const x of d)w.includes(`"${x}"`)&&y++}y>f&&(f=y,p=m)}return p}function kx({denial:e,exp:t,rulesSource:n}){const r=jx(n,t.phase,t.ruleExpression,e.rules?.matchedPath),s=e.result==="allow",i=n!==void 0&&n.trim().length>0;let a;t.implicitDeny||!t.ruleNode?a="rule node":r!==void 0?a=`rule node — ${t.ruleNode} · line ${r}`:a=`rule node — ${t.ruleNode}`;let c;return s?c="Deployed database.rules.json — the allowing rule is marked":c="Deployed database.rules.json — the denying rule is marked",o.jsxs(o.Fragment,{children:[o.jsx(Ae,{label:a,children:i?o.jsx(Lc,{value:n,readOnly:!0,markLine:r,markKind:s?"allow":"deny",minHeightRem:12,ariaLabel:c}):o.jsxs("code",{className:"font-mono text-xs text-soft-white",children:[t.phase?`.${t.phase}`:"(no matching rule)",e.rules?.matchedPath?` at ${e.rules.matchedPath}`:""]})}),!i&&t.ruleExpression?o.jsx(Ae,{label:"rule expression",children:o.jsx("pre",{className:"overflow-auto rounded-md border border-border bg-content-bg p-3 font-mono text-xs text-slate-gray",children:t.ruleExpression})}):null,t.bindings?o.jsx(Ae,{label:"$variable bindings",children:o.jsx("code",{className:"font-mono text-xs text-soft-white",children:Object.entries(t.bindings).map(([l,u])=>`${l.startsWith("$")?l:`$${l}`} → ${u}`).join(", ")})}):null,e.rules?.reason?o.jsx(Ae,{label:"simulator reason",children:o.jsx("code",{className:"font-mono text-xs text-slate-gray",children:e.rules.reason})}):null]})}function Sx({exp:e}){return o.jsxs(Ae,{label:e.implicitDeny?"matched rule":"matched rule (match block)",children:[e.ruleNode?o.jsx("code",{className:"mb-2 block font-mono text-xs text-soft-white",children:e.ruleNode}):null,o.jsx("pre",{className:"overflow-auto rounded-md border border-border bg-content-bg p-3 font-mono text-xs leading-relaxed text-slate-gray",children:[...e.ruleLines,...e.otherLines].join(`
|
|
11
|
+
`)||"(no trace)"})]})}function Ae({label:e,children:t}){return o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx("span",{className:"text-[0.65rem] font-semibold uppercase tracking-wider text-slate-gray",children:e}),t]})}function ra({eventId:e,onClose:t}){const r=Cy().find(a=>a.id===e),s=r?.service??"firestore",i=Oy(s);return r?o.jsxs("div",{"data-pyric-ui":"traffic-rules-inspector",className:"traffic__inspector",children:[o.jsxs("div",{className:"traffic__inspector-bar",children:[o.jsx("span",{className:"traffic__inspector-title",children:"rules inspector"}),o.jsx("button",{type:"button",className:"traffic__inspector-close",onClick:t,"aria-label":"Close rules inspector (Esc)",children:"close (esc)"})]}),o.jsx(Fc,{denial:r,rulesSource:i})]}):o.jsxs("div",{"data-pyric-ui":"traffic-inspect-missing",className:"traffic__inspector",children:[o.jsx("p",{className:"traffic__inspector-missing",children:"This operation isn't in this session's traffic. It may be from an earlier session, or the event has aged out of the buffer."}),o.jsx("button",{type:"button",className:"traffic__inspector-close",onClick:t,children:"Back to the log"})]})}const _x=new Intl.NumberFormat,Ex={reads:"read operations",writes:"writes",deletes:"deletes"},Cx={allows:"allowed requests",denies:"denied requests"};function sa(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 ia(e){return e&&`${e[0].toUpperCase()}${e.slice(1)}`}function zc(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=`${_x.format(n)} observed ${n===1?t.singular:t.plural}`,a=u=>t.labels[u.key]??u.label.toLowerCase();if(s.length>1){const u=s.map(a);return{total:n,headline:i,finding:s.length===e.length?`${t.evenSplitPrefix} ${sa(u)}.`:`${ia(sa(u))} tied for the largest share of ${t.subject} in this window.`}}const c=s[0],l=Math.round(c.total/n*100);return{total:n,headline:i,finding:`${ia(a(c))} accounted for ${l}% of ${t.subject} in this window.`}}function Nx(e){return zc(e,{labels:Ex,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 Rx(e){return zc(e,{labels:Cx,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 Ax=new Intl.NumberFormat,Ix=new Intl.DateTimeFormat(void 0,{hour:"numeric",minute:"2-digit"});function aa(e){return Ax.format(e)}function St(e){return Ix.format(e)}function Dx(e){return Tn(e)==="bypassed"}function Px(e){return e.every(t=>t.total===0)}function Kc({eyebrow:e,story:t,series:n,points:r,window:s,emptyLabel:i,evidenceTitle:a,source:c,methodology:l}){const[u,d]=h.useState(()=>new Set(n.map(f=>f.key))),p=h.useCallback(f=>{d(m=>{const y=new Set(m);return y.has(f)?y.delete(f):y.add(f),y})},[]);return o.jsxs("section",{className:"traffic__metric-panel traffic__metric-panel--journal","data-pyric-ui":"traffic-metric-panel",children:[o.jsxs("header",{className:"traffic__metric-story",children:[o.jsx("p",{className:"traffic__metric-eyebrow",children:e}),o.jsx("h3",{className:"traffic__metric-headline",children:t.headline}),o.jsx("p",{className:"traffic__metric-finding",children:t.finding})]}),o.jsx(Bb,{series:n,visible:u,onToggle:p,formatValue:aa,className:`traffic__metric-cards traffic__metric-cards--journal traffic__metric-cards--${n.length}`}),Px(n)?o.jsx("p",{className:"traffic__empty",children:i}):o.jsxs("div",{className:"traffic__metric-evidence",children:[o.jsxs("div",{className:"traffic__metric-evidence-header",children:[o.jsx("h4",{children:a}),o.jsxs("span",{children:[St(s.start),"–",St(s.end)]})]}),o.jsx(Vb,{points:r,series:n,visible:u,omitZeroSeries:!0,formatValue:aa,formatTime:St,className:"traffic__chart traffic__chart--journal"}),o.jsxs("div",{className:"traffic__metric-axis","aria-hidden":"true",children:[o.jsx("span",{children:St(s.start)}),o.jsx("span",{children:St(s.end)})]})]}),o.jsxs("footer",{className:"traffic__metric-footer",children:[o.jsx("p",{className:"traffic__metric-source",children:c}),o.jsxs("details",{className:"traffic__metric-methodology",children:[o.jsx("summary",{children:"How this is counted"}),o.jsx("div",{children:l})]})]})]})}function $x({events:e,window:t}){const n=h.useMemo(()=>e.filter(i=>(i.service??"firestore")==="firestore"),[e]),r=vb({events:n,window:t,isAdmin:Dx}),s=h.useMemo(()=>Nx(r.series),[r.series]);return o.jsx("div",{className:"traffic__metrics","data-pyric-ui":"traffic-billable-view",children:o.jsx(Kc,{eyebrow:"Billable activity",story:s,series:r.series,points:r.points,window:t,emptyLabel:"No reads, writes, or deletes in this session yet.",evidenceTitle:"When the activity happened",source:"Source: Pyric Firestore sandbox events · Operation counts, not a Firebase invoice",methodology:o.jsxs(o.Fragment,{children:[o.jsxs("p",{children:["Counts successful Firestore sandbox ",o.jsx("code",{children:"get"}),"/",o.jsx("code",{children:"list"}),","," ",o.jsx("code",{children:"create"}),"/",o.jsx("code",{children:"update"}),"/",o.jsx("code",{children:"set"}),", and"," ",o.jsx("code",{children:"delete"}),"/",o.jsx("code",{children:"remove"})," operations in the displayed window. Rules-bypassed admin operations are included because they still execute."]}),o.jsxs("p",{children:[o.jsx("strong",{children:"Read ops are a proxy, not billed document reads."})," Each"," ",o.jsx("code",{children:"list"})," is counted once because the event does not report how many documents the query returned. This is observed sandbox activity, not a Firebase invoice."]})]})})})}function Ox({events:e,window:t}){const n=h.useMemo(()=>e.filter(a=>a.rulesDisposition.kind==="evaluated"),[e]),r=wb({events:n,window:t}),s=h.useMemo(()=>r.series.filter(a=>a.key==="allows"||a.key==="denies"),[r.series]),i=h.useMemo(()=>Rx(s),[s]);return o.jsx("div",{className:"traffic__metrics","data-pyric-ui":"traffic-rules-view",children:o.jsx(Kc,{eyebrow:"Rules decisions",story:i,series:s,points:r.points,window:t,emptyLabel:"No allow or deny decisions in this session yet.",evidenceTitle:"When Rules evaluated requests",source:"Source: Pyric sandbox events · Evaluated Rules dispositions only",methodology:o.jsxs(o.Fragment,{children:[o.jsxs("p",{children:["Counts only operations whose canonical Rules disposition is"," ",o.jsx("code",{children:"evaluated"}),", grouped by its ",o.jsx("code",{children:"allow"})," or ",o.jsx("code",{children:"deny"})," ","verdict."]}),o.jsxs("p",{children:[o.jsx("strong",{children:"Bypasses and runtime failures are not Rules decisions."})," Admin bypasses, services without Rules, unsupported operations, and runtime errors are excluded because Rules did not produce a verdict."]})]})})})}const Mx=[{id:"timeline",label:"Timeline"},{id:"billable",label:"Billable metrics"},{id:"rules",label:"Rules"}];function Ux(e){return e==="billable"?"billable":e==="rules"||e==="subscriptions"?"rules":"timeline"}function Tx(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 Bx(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:Tx(n.length,r)}}function Lx(e,t){return e?.start===t.start&&e.end===t.end?null:t}function Fx(){const{tab:e,query:t}=be();return e!=="traffic"?"timeline":Ux(t.view)}function Vx(){const e=h.useSyncExternalStore(Tt,Fx,()=>"timeline"),t=h.useCallback(n=>{const r={...be().query,view:n==="timeline"?void 0:n};r.view===void 0&&delete r.view,le({tab:"traffic",query:r})},[]);return[e,t]}function qx(){const e=h.useSyncExternalStore(Tt,()=>be().query.hide==="studio",()=>!1),t=h.useCallback(()=>{const n={...be().query};n.hide==="studio"?delete n.hide:n.hide="studio",le({tab:"traffic",query:n})},[]);return[e,t]}function Wx(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 oa(e){return`${Dt(e.start)}–${Dt(e.end)}`}function zx({event:e}){const t=Tn(e);return t?o.jsx("span",{className:"traffic__verdict","data-verdict":t,children:t}):null}function Kx(){return h.useSyncExternalStore(Tt,()=>Tc(be().query),()=>null)}const rr=100;function Hx(){const e=Ey(),[t,n]=Vx(),[r,s]=qx(),i=h.useMemo(()=>ox(e,r),[e,r]),a=e.length-i.length,[c,l]=h.useState("all"),[u,d]=h.useState(null),p=Kx(),[f,m]=h.useState(rr),y=E=>{le({tab:"traffic",query:ux(be().query,E)})},g=()=>{le({tab:"traffic",query:Bc(be().query,null)})};h.useEffect(()=>{if(!p)return;const E=R=>{R.key==="Escape"&&g()};return globalThis.addEventListener("keydown",E),()=>globalThis.removeEventListener("keydown",E)},[p]);const v=h.useMemo(()=>{const E=Date.now();if(i.length===0)return{start:E-15*6e4,end:E};let R=1/0;for(const V of i)V.at<R&&(R=V.at);return{start:Math.min(R,E-6e4),end:E+1e3}},[i]),b=v.end,w=h.useMemo(()=>u?Bx(i,u):null,[i,u]),x=w?.events??i,k=h.useMemo(()=>lx(x,c).sort((E,R)=>R.at-E.at),[x,c]),{items:j}=ib({events:k}),S=j.slice(0,f),N=j.length-S.length,P=i.length>=hn,I=i.filter(E=>E.result==="deny").length,D=E=>o.jsx(zx,{event:E}),C=E=>{if(nr(E)){y(E.id);return}const R=na(E);R&&le(R)},_=p!=null&&S.some(E=>E.type!=="group"&&E.event.id===p);return o.jsxs("section",{"data-pyric-ui":"traffic-surface",className:"traffic",children:[o.jsxs("div",{className:"traffic__tabs",role:"tablist","aria-label":"Traffic views",children:[Mx.map(E=>o.jsx("button",{type:"button",role:"tab",className:"traffic__tab","aria-selected":t===E.id,onClick:()=>n(E.id),children:E.label},E.id)),o.jsxs("button",{type:"button",className:"traffic__hide-studio","aria-pressed":r,onClick:s,title:"Hide ops issued by Pyric Studio's own viewers and editors",children:["Hide Studio traffic",r&&a>0?` (${a} hidden)`:""]})]}),t==="billable"?o.jsx($x,{events:i,window:v}):t==="rules"?o.jsx(Ox,{events:i,window:v}):o.jsxs(o.Fragment,{children:[o.jsx(Mb,{events:i,window:v,brush:u??void 0,onBrush:E=>{d(R=>Lx(R,E)),p&&g()},liveAt:v.end,bucketCount:36,className:"traffic__timeline",header:o.jsxs("div",{className:"traffic__tl-header",children:[o.jsxs("span",{className:"traffic__tl-count",children:[i.length," requests",P?` (showing latest ${hn})`:""]}),I>0?o.jsxs("button",{type:"button",className:"traffic__tl-deny","aria-pressed":c==="deny",onClick:()=>l(E=>E==="deny"?"all":"deny"),title:"Filter the stream to denied requests",children:[I," denied"]}):null,o.jsx("span",{className:"traffic__tl-live",children:"live"})]}),axis:E=>o.jsxs("div",{className:"traffic__tl-axis",children:[o.jsx("span",{children:Wx(E.start,b)}),o.jsx("span",{children:"now"})]}),renderBucketSummary:E=>o.jsxs("div",{className:"traffic__bucket-summary",children:[o.jsx("span",{children:oa(E)}),o.jsxs("strong",{children:[E.count," ",E.count===1?"request":"requests"]}),o.jsxs("span",{children:[E.denies," denied"]})]}),emptyState:o.jsx("p",{className:"traffic__empty",children:"No requests in this window yet."})}),w?o.jsxs("section",{className:"traffic__time-focus","aria-label":"Selected traffic interval","aria-live":"polite",children:[o.jsxs("div",{className:"traffic__time-focus-story",children:[o.jsx("p",{className:"traffic__time-focus-eyebrow",children:"Selected interval"}),o.jsx("h3",{children:oa(w.window)}),o.jsx("p",{children:w.finding})]}),o.jsx("button",{type:"button",onClick:()=>d(null),children:"Show all traffic"})]}):null,o.jsxs("div",{className:"traffic__filters",role:"group","aria-label":"Traffic filters",children:[o.jsx("span",{className:"traffic__filters-label","aria-hidden":"true",children:"verdict"}),cx.map(E=>o.jsx("button",{type:"button",className:"traffic__filter","aria-pressed":c===E,onClick:()=>l(E),children:E},E))]}),p&&!_?o.jsx(ra,{eventId:p,onClose:g},p):null,j.length===0?o.jsx("p",{className:"traffic__empty",children:w?c==="all"?"No requests occurred in the selected interval.":`No ${c} traffic occurred in the selected interval.`:c==="all"?"No requests yet. Reads, writes, and listeners against the sandbox stream in live.":`No ${c} traffic in this session.`}):o.jsxs("div",{className:"traffic__log","data-pyric-ui":"traffic-log","data-pyric-grouped":"","data-pyric-time-focused":w?"":void 0,children:[o.jsx("ul",{"data-pyric-traffic-log-items":"",children:S.map(E=>E.type==="group"?o.jsx("li",{"data-pyric-traffic-group-entry":"",children:o.jsx($b,{group:E,onSelect:R=>{const V=R;if(nr(V)){y(V.id);return}const G=na(V);G&&le(G)},renderClassification:R=>D(R),formatTime:Dt})},E.key):o.jsxs("li",{"data-pyric-traffic-entry":"","data-pyric-traffic-id":E.event.id,"data-verdict":Tn(E.event)??void 0,children:[o.jsx(Wo,{event:E.event,selected:E.event.id===p,onSelect:R=>C(R),renderClassification:R=>D(R),formatTime:Dt}),E.event.id===p&&nr(E.event)?o.jsx(ra,{eventId:p,onClose:g},p):null]},E.event.id))}),N>0?o.jsxs("button",{type:"button",className:"traffic__show-more",onClick:()=>m(E=>E+rr),children:["Show ",Math.min(N,rr)," more (",N," hidden)"]}):null]})]})]})}const ca=["amber","teal","coral","slate","olive","plum","rust","indigo","mint","sand","ash","jade"],la=["fox","owl","lynx","crane","otter","wren","ibex","hare","newt","moth","seal","vole"];function xs(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`${ca[t%ca.length]}-${la[(t>>>4)%la.length]}`}function Gx(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 Jx(e){return e?{tab:"firestore",rest:e.split("/").filter(Boolean)}:null}function Yx(e){const{provenance:t,identity:n}=Gx(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:Jx(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 Qx(e,t=20){const n=[];for(let r=e.length-1;r>=0&&n.length<t;r--){const s=Yx(e[r]);s&&n.push(s)}return n}const Xx=20;function Zx(e){le(e)}function lt({target:e,className:t,children:n,title:r}){return o.jsx("a",{className:t,href:Rn(e),title:r,onClick:s=>{s.metaKey||s.ctrlKey||s.shiftKey||s.altKey||(s.preventDefault(),Zx(e))},children:n})}function ej(){const e=$e(),t=Dn(),n=ds();if(t.status==="loading"||e.status==="pending")return o.jsxs("div",{className:"studio-home__status","aria-label":"Sandbox status",children:[o.jsx("span",{className:"studio-chip studio-home__skeleton-chip","aria-hidden":"true"}),o.jsx("span",{className:"studio-chip studio-home__skeleton-chip","aria-hidden":"true"})]});const s=[];if(e.status==="ready"&&t.status!=="ready"&&s.push(o.jsxs("span",{className:"studio-chip",title:"In-page seeded sandbox — no server. Data resets on reload.",children:[o.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),"dev seed · in-page"]},"seed")),t.status==="ready"){const i=t.payload;s.push(o.jsxs(lt,{className:"studio-chip",target:{tab:"settings"},title:"Persistence mode — manage in Settings.",children:[o.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),i.persist?"persisted to disk":"ephemeral"]},"persist")),i.rulesHash&&s.push(o.jsxs("span",{className:"studio-chip",title:"Hash of the rules this serve deployed to the sandbox.",children:[o.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),"rules ",i.rulesHash.slice(0,8)]},"rules"))}return n&&s.push(o.jsxs(lt,{className:"studio-chip",target:{tab:"settings"},title:`Sandbox instance ${n} — maintenance lives in Settings.`,children:[o.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),xs(n)]},"instance")),o.jsx("div",{className:"studio-home__status","aria-label":"Sandbox status",children:s})}function tj(e){return new Date(e).toLocaleTimeString(void 0,{hour12:!1})}function nj(){const e=Bt(),t=h.useMemo(()=>Qx(e,Xx),[e]);return o.jsxs("section",{className:"studio-panel studio-home__feed","aria-label":"Live activity",children:[o.jsxs("header",{className:"studio-home__feed-head",children:[o.jsx("h2",{className:"studio-panel__title studio-home__feed-title",children:"Activity"}),o.jsx(lt,{className:"studio-home__feed-all",target:{tab:"traffic"},children:"view all in Traffic →"})]}),t.length===0?o.jsx("p",{className:"studio-home__feed-empty",children:"No activity yet — writes, denials, and seeds show up here live."}):o.jsx("div",{className:"studio-home__feed-scroll",children:o.jsx("ol",{className:"studio-home__feed-list",children:t.map(n=>{const r=o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"studio-home__feed-ident","data-provenance":n.provenance,children:[o.jsx("span",{className:"studio-home__feed-dot","aria-hidden":"true"}),n.identity]}),o.jsx("span",{className:"studio-home__feed-summary","data-denied":n.denied?"true":void 0,children:n.summary}),o.jsx("time",{className:"studio-home__feed-time",dateTime:new Date(n.at).toISOString(),children:tj(n.at)})]});return o.jsx("li",{children:n.target?o.jsx(lt,{className:"studio-home__feed-row",target:n.target,children:r}):o.jsx("span",{className:"studio-home__feed-row",children:r})},n.id)})})})]})}const rj=["firestore","auth","rtdb","storage","traffic"];function sj(){const e=Oe(),t=Bt(),n=h.useMemo(()=>{const r={};if(e.status==="ready"){const s=e.handles.listRootCollections().length;r.firestore=`${s} collection${s===1?"":"s"}`}return t.length&&(r.traffic=`${t.length} events`),r},[e,t]);return o.jsx("div",{className:"studio-home__tiles",children:rj.map(r=>{const s=Ke.find(i=>i.id===r);return s?o.jsxs(lt,{className:"studio-card studio-home__tile",target:{tab:r},children:[o.jsxs("span",{className:"studio-home__tile-top",children:[o.jsx("span",{className:"studio-home__tile-label",children:s.label}),n[r]?o.jsx("span",{className:"studio-badge",children:n[r]}):null]}),o.jsx("span",{className:"studio-home__tile-desc",children:s.description})]},r):null})})}function ij(){const e=Dn(),t=e.status==="ready",n=t&&!!e.payload.bridgeUrl,r=typeof window<"u"?window.location.origin:"",s=t?e.payload.rulesHash:null;return o.jsxs(o.Fragment,{children:[o.jsxs("section",{className:"studio-card studio-home__onboard","aria-label":"Connect your agent",children:[o.jsx("span",{className:"studio-home__tile-label",children:"Connect your agent"}),o.jsx("span",{className:"studio-home__tile-desc",children:"Point Claude Code, Cursor, or any MCP client at this sandbox and its writes show up in the feed, attributed."}),o.jsx("code",{className:"studio-home__snippet",children:n?`${r}/__pyric/mcp`:"pyric dev --bridge # then <url>/__pyric/mcp"})]}),o.jsxs("section",{className:"studio-card studio-home__onboard","aria-label":"Seed data",children:[o.jsx("span",{className:"studio-home__tile-label",children:"Seed data"}),o.jsx("span",{className:"studio-home__tile-desc",children:"Start from a fixture, or create documents by hand in the Firestore browser."}),o.jsx("code",{className:"studio-home__snippet",children:"pyric dev --seed seed.json"}),o.jsx(lt,{className:"studio-home__onboard-link",target:{tab:"firestore"},children:"open Firestore →"})]}),o.jsxs("section",{className:"studio-card studio-home__onboard","aria-label":"Bring your rules",children:[o.jsx("span",{className:"studio-home__tile-label",children:"Bring your rules"}),s?o.jsxs("span",{className:"studio-home__tile-desc",children:["Your repo rules are deployed to this sandbox (",s.slice(0,8),"). Denials will appear in the feed and in Traffic."]}):o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"studio-home__tile-desc",children:"Serve your repo's rules file and every denial becomes a debuggable event."}),o.jsx("code",{className:"studio-home__snippet",children:"pyric dev --rules firestore.rules"})]})]})]})}function aj(){const e=Oe(),t=Bt(),n=$e(),r=e.status==="pending"||n.status==="pending",s=!r&&t.length===0&&(e.status!=="ready"||e.handles.listRootCollections().length===0);return o.jsxs("section",{className:"studio-surface studio-home","aria-label":"Home",children:[o.jsxs("div",{className:"studio-home__hero",children:[o.jsx("img",{className:"studio-home__hero-logo",src:"/__pyric/ui/pyric-logo.svg",alt:"","aria-hidden":"true"}),o.jsx("h1",{className:"studio-home__hero-title",children:"Firebase that runs in the browser"})]}),o.jsx(Vo,{exposeFocus:lm}),o.jsx(ej,{}),o.jsx("div",{className:"studio-home__body",children:r?o.jsxs("section",{className:"studio-panel studio-home__feed studio-home__skeleton","aria-hidden":"true",children:[o.jsx("div",{className:"studio-home__skeleton-row"}),o.jsx("div",{className:"studio-home__skeleton-row"}),o.jsx("div",{className:"studio-home__skeleton-row"})]}):s?o.jsx(ij,{}):o.jsxs(o.Fragment,{children:[o.jsx(nj,{}),o.jsx(sj,{})]})})]})}function te(e){const t=e.split("/").filter(Boolean);return t.length===0?"/":`/${t.join("/")}`}function He(e){return te(e).split("/").filter(Boolean)}function Vr(e,t){return te([...He(e),...t.split("/").filter(Boolean)].join("/"))}function Hc(e,t){const n=He(e),r=He(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 Gc(e){if(e==null)return null;if(typeof e!="object")return e;const t=e;let n=!1;const r={};for(const[s,i]of Object.entries(t)){const a=Gc(i);if(a===null){n=!0;continue}a!==i&&(n=!0),r[s]=a}return Object.keys(r).length===0?null:n?r:e}function oj(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 js(e){return e===null||typeof e!="object"?!1:Object.keys(e).length>0}function Jc(e){return e===null||typeof e!="object"?[]:Object.entries(e).sort(([t],[n])=>t.localeCompare(n,void 0,{numeric:!0}))}function Yc(e,t){let n=e??null;for(const r of He(t)){if(n===null||typeof n!="object")return null;n=n[r]??null}return n}function cj(e){return e==null?"null":Array.isArray(e)?"array":typeof e}function qr(e,t){if(Object.is(e,t))return!0;if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((a,c)=>qr(a,t[c]));if(e===null||t===null||typeof e!="object"||typeof t!="object")return!1;const n=e,r=t,s=Object.keys(n),i=Object.keys(r);return s.length!==i.length?!1:s.every(a=>a in r&&qr(n[a],r[a]))}function lj(e,t){const n=new Map,r=(s,i)=>{if(!js(s)){n.set(i,["leaf",s??null]);return}const a=Jc(s);n.set(i,["parent",a.map(([c])=>c)]);for(const[c,l]of a)r(l,Vr(i,c))};return r(e,te(t)),n}function uj(e){let t=e.trim();if(t.length===0)return"/";const n=/^[a-z][a-z0-9+.-]*:\/\/[^/?#]+/i.exec(t);return n&&(t=t.slice(n[0].length)),t=t.replace(/[?#].*$/,""),te(t)}function dj(e){const t=He(e);return t.map((n,r)=>({label:n,path:`/${t.slice(0,r+1).join("/")}`}))}const fj=["string","number","boolean","json"];function ua(e){switch(typeof e){case"string":return"string";case"number":return"number";case"boolean":return"boolean";default:return"json"}}function hj(e,t){return t==="json"?JSON.stringify(e??null):e==null?"":String(e)}function pj(e){if(e.trim().length===0)return"Enter a key.";const t=e.match(/[.$#[\]/]/);return t?`Keys can't contain "${t[0]}".`:null}function mj(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 Qc(e){return{path:te(e),status:"loading",value:null,error:null,expanded:{},pages:{}}}function Xc(e,t){const n=Hc(e.path,t);return n===null?null:Yc(e.value,n)}function yj(e,t){const n=te(t);return n===e.path||e.expanded[n]===!0}function bj(e,t,n){const r=Jc(Xc(e,t)),s=Math.min(r.length,e.pages[te(t)]??n);return{entries:r.slice(0,s),total:r.length,hiddenCount:r.length-s}}function da(e,t){const n={};let r=!1;for(const[s,i]of Object.entries(e)){const a=Hc(t.path,s);a!==null&&js(Yc(t.value,a))?n[s]=i:r=!0}return r?n:e}function Zc(e,t){switch(t.type){case"navigate":{const n=te(t.path);return n===e.path?e:Qc(n)}case"value":{if(te(t.path)!==e.path)return e;const n={...e,status:"live",value:Gc(t.value),error:null};return n.expanded=da(e.expanded,n),n.pages=da(e.pages,n),n}case"error":return te(t.path)!==e.path?e:{...e,status:"error",error:t.message};case"expand":{const n=te(t.path);return n===e.path||e.expanded[n]?e:{...e,expanded:{...e.expanded,[n]:!0}}}case"collapse":{const n=te(t.path);if(!e.expanded[n])return e;const r={...e.expanded};return delete r[n],{...e,expanded:r}}case"toggle":{const n=te(t.path);return Zc(e,{type:e.expanded[n]?"collapse":"expand",path:n})}case"show-more":{const n=te(t.path),r=e.pages[n]??t.pageSize;return{...e,pages:{...e.pages,[n]:r+t.pageSize}}}}}const gj=50;function vj(e,t,n={}){const r=n.pageSize??gj,s=te(t),[i,a]=h.useReducer(Zc,s,Qc),c=h.useMemo(()=>lj(i.value,i.path),[i.path,i.value]),l=ws({scope:i.path,entries:c,equals:qr,ready:i.status==="live"});i.path!==s&&a({type:"navigate",path:s}),h.useEffect(()=>{let g=!1;const v=e.subscribeValue(s,b=>{g||a({type:"value",path:s,value:b})},b=>{g||a({type:"error",path:s,message:b instanceof Error?b.message:String(b)})});return()=>{g=!0,v()}},[e,s]);const u=h.useCallback(g=>Xc(i,g),[i]),d=h.useCallback(g=>yj(i,g),[i]),p=h.useCallback(g=>bj(i,g,r),[i,r]),f=h.useCallback(g=>a({type:"toggle",path:g}),[]),m=h.useCallback(g=>a({type:"show-more",path:g,pageSize:r}),[r]),y=h.useCallback(g=>l.get(te(g)),[l]);return h.useMemo(()=>({state:i,pageSize:r,valueAt:u,isExpanded:d,childrenAt:p,toggle:f,showMore:m,updateAt:y}),[i,r,u,d,p,f,m,y])}function wj({path:e,onNavigate:t,rootLabel:n="/",inputPrefix:r,className:s}){const i=te(e),[a,c]=h.useState(!1),l=h.useRef(null);h.useEffect(()=>{a&&l.current?.select()},[a]);const u=f=>{f.preventDefault(),t(uj(l.current?.value??"")),c(!1)},d=()=>c(!1),p=dj(i);return o.jsx("nav",{className:s,"data-pyric-ui":"rtdb-path-bar","data-rtdb-editing":a?"":void 0,"aria-label":"Database path",children:a?o.jsxs("form",{"data-rtdb-path-form":!0,onSubmit:u,children:[r?o.jsx("span",{"data-rtdb-path-prefix":!0,children:r}):null,o.jsx("input",{ref:l,"data-rtdb-path-input":!0,"aria-label":"Database path",autoFocus:!0,defaultValue:i,onBlur:d,onKeyDown:f=>{f.key==="Escape"&&d()},spellCheck:!1})]}):o.jsxs(o.Fragment,{children:[o.jsxs("ol",{"data-rtdb-crumb-list":!0,children:[o.jsx("li",{"data-rtdb-crumb-item":!0,children:o.jsx("button",{type:"button","data-rtdb-crumb":!0,"data-rtdb-crumb-root":!0,"data-pyric-current":p.length===0?"":void 0,"aria-current":p.length===0?"page":void 0,onClick:()=>t("/"),children:n})}),p.map((f,m)=>{const y=m===p.length-1;return o.jsxs("li",{"data-rtdb-crumb-item":!0,children:[o.jsx("span",{"aria-hidden":!0,"data-rtdb-crumb-separator":!0,children:"/"}),o.jsx("button",{type:"button","data-rtdb-crumb":!0,"data-pyric-current":y?"":void 0,"aria-current":y?"page":void 0,onClick:()=>t(f.path),children:f.label})]},f.path)})]}),o.jsx("button",{type:"button","data-rtdb-path-edit":!0,"aria-label":"Edit path",title:"Edit path",onClick:()=>c(!0),children:o.jsx("svg",{"aria-hidden":!0,viewBox:"0 0 16 16",width:"12",height:"12",fill:"currentColor",children:o.jsx("path",{d:"M11.7 1.3a1 1 0 0 1 1.4 0l1.6 1.6a1 1 0 0 1 0 1.4l-8.5 8.5-3.4 1.1a.5.5 0 0 1-.63-.63l1.1-3.4 8.43-8.57ZM10.9 3.5l1.6 1.6 1.2-1.2-1.6-1.6-1.2 1.2Z"})})})]})})}function xj({tree:e,api:t,onNavigate:n,rootLabel:r="/",className:s}){const{state:i}=e,a=He(i.path),c=a.length===0?r:a[a.length-1];return o.jsx("div",{className:s,"data-pyric-ui":"rtdb-tree",children:i.status==="loading"?o.jsx("p",{"data-rtdb-loading":!0,children:"Loading…"}):i.status==="error"?o.jsx("p",{role:"alert","data-rtdb-error":!0,children:i.error}):o.jsx(el,{tree:e,api:t,onNavigate:n,path:i.path,label:c,isViewRoot:!0})})}function el({tree:e,api:t,onNavigate:n,path:r,label:s,isViewRoot:i}){const a=e.valueAt(r),c=js(a),l=e.isExpanded(r),u=e.updateAt(r),[d,p]=h.useState(!1),[f,m]=h.useState(!1),[y,g]=h.useState(!1),[v,b]=h.useState(null),w=async(j,S)=>{try{await j(),b(null),S()}catch(N){b(N instanceof Error?N.message:String(N))}},x=()=>{p(!0),g(!1),c&&!l&&e.toggle(r)},k=c&&l?e.childrenAt(r):null;return o.jsxs("div",{"data-rtdb-node":!0,"data-rtdb-kind":c?"parent":"leaf","data-rtdb-view-root":i?"":void 0,"data-rtdb-expanded":c&&l?"":void 0,children:[o.jsxs("div",{"data-rtdb-row":!0,"data-pyric-update":u?.kind,"data-pyric-update-cycle":u?.cycle,children:[c&&!i?o.jsx("button",{type:"button","data-rtdb-caret":!0,"aria-expanded":l,"aria-label":l?"Collapse":"Expand",onClick:()=>e.toggle(r),children:o.jsx("svg",{"aria-hidden":!0,viewBox:"0 0 8 8",width:"8",height:"8",fill:"currentColor",children:o.jsx("path",{d:"M1 0l6 4-6 4z"})})}):o.jsx("span",{"aria-hidden":!0,"data-rtdb-caret-spacer":!0}),o.jsx("button",{type:"button","data-rtdb-key":!0,"aria-label":"Key name",onClick:()=>n?.(r),children:s}),c?null:o.jsxs(o.Fragment,{children:[o.jsx("span",{"aria-hidden":!0,"data-rtdb-sep":!0,children:":"}),o.jsx("button",{type:"button","data-rtdb-value":!0,"data-rtdb-type":cj(a),title:"Edit value",onClick:()=>{m(!0),g(!1)},children:oj(a)})]}),o.jsx("span",{"data-rtdb-actions":!0,children:y?o.jsxs("span",{"data-rtdb-confirm":!0,children:[o.jsxs("span",{"data-rtdb-confirm-label":!0,children:["Delete",c?" subtree":"","?"]}),o.jsx("button",{type:"button","data-rtdb-confirm-yes":!0,onClick:()=>void w(()=>t.remove(r),()=>g(!1)),children:"Delete"}),o.jsx("button",{type:"button","data-rtdb-confirm-no":!0,onClick:()=>g(!1),children:"Cancel"})]}):o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button","data-rtdb-action-add":!0,"aria-label":`Add child to ${fa(r)}`,title:"Add child",onClick:x,children:"+"}),o.jsx("button",{type:"button","data-rtdb-action-delete":!0,"aria-label":`Delete ${fa(r)}`,title:"Delete",onClick:()=>g(!0),children:"×"})]})})]}),v?o.jsx("p",{role:"alert","data-rtdb-error":!0,children:v}):null,f?o.jsx(ha,{initialType:ua(a),initialText:hj(a,ua(a)),submitLabel:"Save",onCancel:()=>m(!1),onSubmit:j=>w(()=>t.set(r,j),()=>m(!1))}):null,d?o.jsx(ha,{withKey:!0,initialType:"string",initialText:"",submitLabel:"Add",onCancel:()=>p(!1),onSubmit:(j,S)=>w(()=>t.set(Vr(r,S),j),()=>p(!1))}):null,k?o.jsxs("ul",{"data-rtdb-children":!0,children:[k.entries.map(([j])=>o.jsx("li",{children:o.jsx(el,{tree:e,api:t,onNavigate:n,path:Vr(r,j),label:j})},j)),k.hiddenCount>0?o.jsx("li",{"data-rtdb-show-more-item":!0,children:o.jsxs("button",{type:"button","data-rtdb-show-more":!0,onClick:()=>e.showMore(r),children:["Show more (",k.hiddenCount," hidden)"]})}):null]}):null]})}function fa(e){const t=He(e);return t.length===0?"root":t[t.length-1]}function ha({withKey:e,initialType:t,initialText:n,submitLabel:r,onSubmit:s,onCancel:i}){const a=h.useRef(null),c=h.useRef(null),[l,u]=h.useState(t),[d,p]=h.useState(null),f=y=>{y.preventDefault();const g=a.current?.value??"";if(e){const b=pj(g);if(b){p(b);return}}const v=mj(l,c.current?.value??"");if(!v.ok){p(v.error);return}p(null),s(v.value,e?g.trim():void 0)},m=y=>{y.key==="Escape"&&i()};return o.jsxs("form",{"data-rtdb-editor":!0,onSubmit:f,children:[e?o.jsx("input",{ref:a,"data-rtdb-editor-key":!0,"aria-label":"Child key",placeholder:"key",autoFocus:!0,onKeyDown:m,spellCheck:!1}):null,o.jsx("select",{"data-rtdb-editor-type":!0,"aria-label":"Value type",value:l,onChange:y=>u(y.currentTarget.value),onKeyDown:m,children:fj.map(y=>o.jsx("option",{value:y,children:y},y))}),l==="boolean"?o.jsxs("select",{ref:c,"data-rtdb-editor-value":!0,"aria-label":"Value",defaultValue:n.trim().toLowerCase()==="true"?"true":"false",onKeyDown:m,children:[o.jsx("option",{value:"true",children:"true"}),o.jsx("option",{value:"false",children:"false"})]}):o.jsx("input",{ref:c,"data-rtdb-editor-value":!0,"aria-label":"Value",placeholder:l==="json"?'{ "key": "value" }':"value",autoFocus:!e,defaultValue:n,onKeyDown:m,spellCheck:!1}),o.jsx("button",{type:"submit","data-rtdb-editor-save":!0,children:r}),o.jsx("button",{type:"button","data-rtdb-editor-cancel":!0,onClick:i,children:"Cancel"}),d?o.jsx("span",{role:"alert","data-rtdb-editor-error":!0,children:d}):null]})}function jj(){const e=pe(),t=e.status==="ready"?e.env.live:void 0;return o.jsxs("section",{className:"studio-surface grid gap-4","aria-labelledby":"rtdb-title",children:[o.jsxs("div",{className:"studio-surface__intro",children:[o.jsx("p",{className:"studio-surface__eyebrow",children:"RTDB"}),o.jsx("h1",{id:"rtdb-title",className:"studio-surface__title",children:"RTDB"}),o.jsx("p",{className:"studio-surface__copy",children:"Browse and edit RTDB data in the shared sandbox."})]}),t?o.jsx(Sj,{live:t}):o.jsx(kj,{})]})}function kj(){return o.jsxs("div",{className:"rounded-md border border-dashed border-line bg-panel p-8 text-center",children:[o.jsx("span",{className:"rounded-full border border-line px-3 py-1 text-xs uppercase tracking-wide text-muted",children:"Shared worker pending"}),o.jsx("p",{className:"mx-auto mt-3 max-w-md text-sm leading-relaxed text-muted",children:"The RTDB viewer goes live once Studio connects to the shared sandbox worker."})]})}function Sj({live:e}){const[t,n]=h.useState("/"),r=xs(ds()),s=r?`${r}-sandbox`:"sandbox",i=h.useMemo(()=>({set:(c,l)=>e.setRtdbValue(c,l),remove:c=>e.deleteRtdbValue(c),subscribeValue:(c,l,u)=>e.subscribeRtdbValue(c,l,u)}),[e]),a=vj(i,t);return o.jsxs("div",{className:"rtdb",children:[o.jsx(wj,{className:"rtdb__pathbar",path:t,onNavigate:n,rootLabel:s,inputPrefix:s}),o.jsx(xj,{className:"rtdb__tree",tree:a,api:i,onNavigate:n,rootLabel:s})]})}function _j(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 Jt(e,t,n=`${t}s`){return`${e} ${e===1?t:n}`}function Ej(e){if(e===null)return"measuring…";const t=[];return e.collections&&t.push(Jt(e.collections,"collection")),e.users&&t.push(Jt(e.users,"user")),e.objects&&t.push(Jt(e.objects,"file")),e.rtdbKeys&&t.push(Jt(e.rtdbKeys,"RTDB key")),t.length?t.join(" · "):"empty — no data yet"}function Bn(){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 Cj(){return o.jsxs("svg",{...Bn(),children:[o.jsx("path",{d:"M12 4v10"}),o.jsx("path",{d:"M8 10l4 4 4-4"}),o.jsx("path",{d:"M4 19h16"})]})}function Nj(){return o.jsxs("svg",{...Bn(),children:[o.jsx("path",{d:"M12 14V4"}),o.jsx("path",{d:"M8 8l4-4 4 4"}),o.jsx("path",{d:"M4 19h16"})]})}function Rj(){return o.jsxs("svg",{...Bn(),children:[o.jsx("circle",{cx:"7",cy:"6",r:"2.4"}),o.jsx("circle",{cx:"7",cy:"18",r:"2.4"}),o.jsx("circle",{cx:"17",cy:"8",r:"2.4"}),o.jsx("path",{d:"M7 8.4v7.2"}),o.jsx("path",{d:"M17 10.4c0 3-4 3.6-7 4.4"})]})}function Aj(){return o.jsxs("svg",{...Bn(),children:[o.jsx("path",{d:"M4 5v5h5"}),o.jsx("path",{d:"M4.6 10a8 8 0 1 0 1.7-5.3"})]})}function Yt({glyph:e,name:t,caption:n,disabled:r,danger:s,onClick:i}){return o.jsxs("button",{type:"button",className:"studio-sandbox__action","data-danger":s?"true":void 0,disabled:r,onClick:i,children:[o.jsxs("span",{className:"studio-sandbox__action-top",children:[e,o.jsx("span",{className:"studio-sandbox__action-name",children:t})]}),o.jsx("span",{className:"studio-sandbox__action-caption",children:n})]})}function Ij(){const e=Iy(),t=Dy(),n=Py(),r=$y(),s=Dn(),i=h.useRef(null),a=xs(ds()),[c,l]=h.useState(!1),[u,d]=h.useState(!1),[p,f]=h.useState(!1),[m,y]=h.useState(!1),[g,v]=h.useState(""),b=Fo(),{ensure:w}=b;h.useEffect(()=>w(),[w]);const x=_j(b.entries),k=Ej(x),j=s.status==="ready"?s.payload.persist?"persisted to disk":"ephemeral":"in-page · resets on reload",S=async()=>{const _=await t();if(!_||typeof document>"u")return;const E=URL.createObjectURL(new Blob([_],{type:"application/json"})),R=document.createElement("a");R.href=E,R.download=`pyric-sandbox-${a||"export"}.json`,R.click(),URL.revokeObjectURL(E)},N=async _=>{const E=_.target.files?.[0];if(_.target.value="",!!E&&!(typeof window<"u"&&!window.confirm("Import replaces all data in this sandbox. This cannot be undone. Continue?"))){d(!0);try{await n(await E.text())}finally{d(!1)}}},P=async()=>{f(!1),l(!0);try{await e()}finally{l(!1)}},I=async()=>{const _=g.trim();_&&(await r.save(_),v(""),y(!1))},D=async _=>{typeof window<"u"&&!window.confirm(`Switch to branch "${_}"? This replaces the current sandbox state.`)||await r.switchTo(_)},C=async _=>{typeof window<"u"&&!window.confirm(`Delete branch "${_}"?`)||await r.remove(_)};return o.jsxs("section",{className:"studio-surface studio-settings","aria-labelledby":"settings-title",children:[o.jsxs("div",{className:"studio-surface__intro",children:[o.jsx("p",{className:"studio-surface__eyebrow",children:"Settings"}),o.jsx("h1",{id:"settings-title",className:"studio-surface__title",children:"Configuration and maintenance."}),o.jsx("p",{className:"studio-surface__copy",children:"Global controls live here so service surfaces can stay focused on their primary work."})]}),o.jsx("div",{className:"studio-settings__grid",children:o.jsxs("section",{className:"studio-panel studio-settings__panel","aria-labelledby":"settings-sandbox-title",children:[o.jsx("h2",{id:"settings-sandbox-title",className:"studio-panel__title",children:"Sandbox"}),o.jsxs("div",{className:"studio-sandbox__live","aria-label":"Sandbox contents",children:[o.jsx("span",{className:"studio-sandbox__instance mono",children:a||"local"}),o.jsx("span",{className:"studio-sandbox__inventory",children:k}),o.jsx("span",{className:"studio-sandbox__persist",children:j})]}),o.jsxs("div",{className:"studio-sandbox__actions",children:[o.jsx(Yt,{glyph:o.jsx(Cj,{}),name:"Export",caption:"Downloads all of this as one file.",onClick:()=>void S()}),o.jsx(Yt,{glyph:o.jsx(Nj,{}),name:u?"Importing…":"Import",caption:"A chosen file replaces everything here.",disabled:u,onClick:()=>i.current?.click()}),o.jsx(Yt,{glyph:o.jsx(Rj,{}),name:"Save branch",caption:"Keeps a copy you can return to.",onClick:()=>y(_=>!_)}),o.jsx(Yt,{glyph:o.jsx(Aj,{}),name:c?"Resetting…":"Reset session",caption:"Everything returns to the seeded start.",disabled:c,danger:!0,onClick:()=>f(!0)})]}),o.jsx("input",{ref:i,type:"file",accept:"application/json,.json",className:"studio-settings__file",onChange:N}),m?o.jsxs("form",{className:"studio-sandbox__name-row",onSubmit:_=>{_.preventDefault(),I()},children:[o.jsx("input",{className:"studio-sandbox__name-input",type:"text",value:g,placeholder:"branch name","aria-label":"Branch name",autoFocus:!0,onChange:_=>v(_.target.value),onKeyDown:_=>{_.key==="Escape"&&(y(!1),v(""))}}),o.jsx("button",{type:"submit",className:"studio-button",disabled:!g.trim(),children:"Save"}),o.jsx("button",{type:"button",className:"studio-button",onClick:()=>{y(!1),v("")},children:"Cancel"})]}):null,p?o.jsxs("div",{className:"studio-sandbox__confirm",role:"alert",children:[o.jsx("span",{className:"studio-sandbox__confirm-copy",children:x&&k!=="empty — no data yet"?`This erases ${k}.`:"This erases everything in this sandbox."}),o.jsxs("span",{className:"studio-sandbox__confirm-actions",children:[o.jsx("button",{type:"button",className:"studio-button studio-button--danger",onClick:()=>void P(),children:"Erase and reseed"}),o.jsx("button",{type:"button",className:"studio-button",onClick:()=>f(!1),children:"Keep"})]})]}):null,r.branches.length>0?o.jsx("div",{className:"studio-settings__branches",children:r.branches.map(_=>o.jsxs("div",{className:"studio-settings__branch",children:[o.jsx("span",{className:"mono",children:_}),o.jsxs("span",{className:"studio-settings__branch-actions",children:[o.jsx("button",{type:"button",className:"studio-button",onClick:()=>void D(_),children:"Switch"}),o.jsx("button",{type:"button",className:"studio-button",onClick:()=>void C(_),children:"Delete"})]})]},_))}):o.jsx("p",{className:"studio-sandbox__branches-empty",children:"No branches yet — Save branch keeps this exact state to come back to."})]})})]})}function Qt(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 Dj(e){const t=e.stateDiff;if(!t)return"No state evidence";if(!t.changed)return e.mutation.output!==void 0?"Read result captured":"No state change";if(t.before&&t.after&&typeof t.before=="object"&&typeof t.after=="object"&&!Array.isArray(t.before)&&!Array.isArray(t.after)){const n=t.before,r=t.after,i=[...new Set([...Object.keys(n),...Object.keys(r)])].filter(a=>JSON.stringify(n[a])!==JSON.stringify(r[a]));if(i.length>0&&i.length<=3)return i.map(a=>`${a}: ${Qt(n[a])} -> ${Qt(r[a])}`).join(", ")}return`${Qt(t.before)} -> ${Qt(t.after)}`}function Pj(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:Dj(t),supported:t.qualification.supported}))}function $j(e){const t=e.mutation.events.find(a=>a.result==="allow"||a.result==="deny"||a.result==="unsupported");if(!t)return null;const n=t.result,r={id:t.id??`${e.probeId}-decision`,at:t.at??0,result:n,method:t.method??t.op??e.mutation.operation.method,service:t.service??e.mutation.operation.service,path:t.path??e.mutation.operation.path,auth:t.auth??null,reasons:t.reasons??[],origin:t.origin??"user",unsupported:n==="unsupported"};t.matchedRule&&(r.matchedRule=t.matchedRule),t.evaluatedRule&&(r.evaluatedRule=t.evaluatedRule),t.rules&&(r.rules=t.rules),t.resourceBefore&&(r.resourceBefore=t.resourceBefore);const s=t.request,i=s?.resourceData??s?.data;return i!==void 0&&(r.resourceData=i),r}const Oj="pyric:assurance-campaign",Mj="pyric-assurance-v1",Wr=new Set;let pa=!1,ma;function ya(e){for(const t of Wr)t(e)}function ba(e){return!!e&&typeof e=="object"&&e.schema==="pyric.assurance.visualization.v1"&&typeof e.campaignId=="string"}function Uj(){if(!(pa||typeof document>"u")){pa=!0,globalThis.addEventListener(Oj,e=>{const t=e.detail;ba(t)&&ya(t)});try{ma=new BroadcastChannel(Mj),ma.onmessage=e=>{ba(e.data)&&ya(e.data)}}catch{}}}function Tj(e){return Uj(),Wr.add(e),()=>Wr.delete(e)}function sr(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 Bj=[sr({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"}}),sr({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"}),sr({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"}}})],ik=Bj.map(e=>({...e,campaignId:"collaboration-local-v1-fixed",targetHash:"fnv1a32-a9f18f23",mutation:{...e.mutation,decision:"DENY",events:[]},stateDiff:void 0,classification:"no-counterexample"}));const zr="pyric:assurance:campaigns",tl="pyric:assurance:campaign:";function Lj(e){return!!e&&typeof e=="object"&&e.schema==="pyric.assurance.visualization.v1"&&typeof e.campaignId=="string"}function Fj(){if(typeof sessionStorage>"u")return[];try{const e=JSON.parse(sessionStorage.getItem(zr)??"[]");if(!Array.isArray(e))return[];const t=e.map(n=>sessionStorage.getItem(`${tl}${String(n)}`)).filter(n=>!!n).map(n=>JSON.parse(n)).filter(Lj);return t.length,t}catch{return[]}}function Vj(e){if(!(typeof sessionStorage>"u"))try{const t=JSON.parse(sessionStorage.getItem(zr)??"[]"),n=Array.isArray(t)?t.map(String):[];n.includes(e.campaignId)||n.push(e.campaignId),sessionStorage.setItem(zr,JSON.stringify(n)),sessionStorage.setItem(`${tl}${e.campaignId}`,JSON.stringify(e))}catch{}}function qj(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 Wj(){const[e,t]=h.useState(Fj);return h.useEffect(()=>{const r=Tj(s=>{Vj(s),t(i=>qj(i,s))});return()=>{r()}},[]),e}function zj(e,t){return e!==t?"assurance-verdict--mismatch":t==="ALLOW"?"assurance-verdict--allow":"assurance-verdict--deny"}function Kj(e){return e.replaceAll("-"," ")}function ga({value:e}){return o.jsx("pre",{className:"assurance-evidence__json",children:JSON.stringify(e,null,2)})}function Hj(){return o.jsxs("section",{className:"assurance-empty","aria-labelledby":"assurance-empty-title",children:[o.jsx("p",{className:"assurance-surface__eyebrow",children:"Local authorization assurance"}),o.jsx("h1",{id:"assurance-empty-title",children:"No campaign in this Studio session"}),o.jsx("p",{children:"Campaigns appear here as the local assurance tools map actors, run controls, and test explicit security invariants."}),o.jsx("span",{className:"assurance-local-state",children:"Pyric sandboxes only | network off"})]})}function va({attachment:e}){return e?o.jsxs("div",{className:"assurance-attachment","aria-label":"Attached sandbox inventory",children:[o.jsxs("span",{children:[o.jsx("strong",{children:e.source.origin}),"read-only clone"]}),o.jsxs("span",{children:[o.jsx("strong",{children:e.inventory.firestoreDocuments}),"Firestore docs"]}),o.jsxs("span",{children:[o.jsx("strong",{children:e.inventory.authUsers}),"Auth users"]}),o.jsxs("span",{children:[o.jsx("strong",{children:e.inventory.rtdbPresent?"present":"empty"}),"RTDB"]})]}):null}function Gj({campaigns:e}){const t=Wj(),n=e??t,r=be().query,[s,i]=h.useState(r.campaign??n.find(x=>x.report)?.campaignId??n[0]?.campaignId??""),a=n.find(x=>x.campaignId===s)??n[0],c=h.useMemo(()=>a?.report?Pj(a.report):[],[a]),[l,u]=h.useState(r.probe??c[0]?.id??"");if(h.useEffect(()=>{!s&&n[0]&&i(n[0].campaignId)},[s,n]),h.useEffect(()=>{c.some(x=>x.id===l)||u(c[0]?.id??"")},[c,l]),!a)return o.jsx(Hj,{});const d=a.context?.attachment,p=a.report;if(!p)return o.jsxs("section",{className:"assurance-empty","aria-labelledby":"assurance-mapped-title",children:[o.jsx("p",{className:"assurance-surface__eyebrow",children:a.campaignId}),o.jsx("h1",{id:"assurance-mapped-title",children:"Campaign mapped, awaiting its first run"}),o.jsxs("p",{children:[a.observations.length," known-good operation(s) and"," ",a.probes.length," probe(s) are available."]}),o.jsx(va,{attachment:d}),d?.coverageGaps.length?o.jsx("ul",{className:"assurance-coverage-gaps","aria-label":"Attachment coverage gaps",children:d.coverageGaps.map(x=>o.jsxs("li",{children:[o.jsx("code",{children:x.service}),x.reason]},x.code))}):null,o.jsx("span",{className:"assurance-local-state",children:"Pyric sandboxes only | network off"})]});const f=c.find(x=>x.id===l)??c[0],m=p.results.find(x=>x.probeId===f?.id),y=m?$j(m):null,g=a.verifications?.at(-1),v=g!==void 0&&g.summary.controlsPassed===g.summary.probes&&g.summary.noCounterexamples===g.summary.probes&&g.summary.localCounterexamples===0&&g.summary.engineGaps===0&&g.summary.invalidProbes===0;function b(x){i(x);const j=n.find(S=>S.campaignId===x)?.report?.results[0]?.probeId??"";u(j),dn({tab:"assurance",query:{campaign:x,probe:j||void 0}})}function w(x){u(x.id),dn({tab:"assurance",query:{campaign:a.campaignId,probe:x.id}})}return o.jsxs("section",{className:"assurance-surface","aria-labelledby":"assurance-title",children:[o.jsxs("header",{className:"assurance-surface__header",children:[o.jsxs("div",{children:[o.jsx("p",{className:"assurance-surface__eyebrow",children:"Local authorization assurance"}),o.jsx("h1",{id:"assurance-title",children:a.campaignId})]}),o.jsxs("div",{className:"assurance-surface__controls",children:[n.length>1?o.jsxs("label",{children:[o.jsx("span",{children:"Campaign"}),o.jsx("select",{value:a.campaignId,onChange:x=>b(x.target.value),children:n.map(x=>o.jsx("option",{value:x.campaignId,children:x.campaignId},x.campaignId))})]}):null,o.jsx("span",{className:"assurance-local-state",children:"Pyric sandboxes only | network off"})]})]}),o.jsx(va,{attachment:d}),o.jsxs("div",{className:"assurance-summary","aria-label":"Campaign summary",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Controls"}),o.jsxs("strong",{children:[p.summary.controlsPassed,"/",p.summary.probes]})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Counterexamples"}),o.jsx("strong",{children:p.summary.localCounterexamples})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Candidate signals"}),o.jsx("strong",{children:p.summary.candidateSignals})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Engine gaps"}),o.jsx("strong",{children:p.summary.engineGaps})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Coverage gaps"}),o.jsx("strong",{children:d?.coverageGaps.length??0})]})]}),g?o.jsxs("div",{className:`assurance-verification-band assurance-verification-band--${v?"passed":"failed"}`,role:"status",children:[o.jsx("strong",{children:v?"Candidate rules verified":"Candidate rules need review"}),o.jsxs("span",{children:[g.summary.controlsPassed,"/",g.summary.probes," ","controls preserved"," | ",g.summary.noCounterexamples,"/",g.summary.probes," negative cases denied"]}),o.jsx("code",{children:g.campaignId})]}):null,d?.coverageGaps.length?o.jsxs("div",{className:"assurance-coverage-band",children:[o.jsxs("strong",{children:[d.coverageGaps.length," attachment gap(s)"]}),o.jsx("span",{children:d.coverageGaps.map(x=>`${x.service}: ${x.reason}`).join(" ")})]}):null,o.jsxs("div",{className:"assurance-workspace",children:[o.jsxs("section",{className:"assurance-matrix","aria-labelledby":"assurance-matrix-title",children:[o.jsxs("div",{className:"assurance-section-heading",children:[o.jsx("h2",{id:"assurance-matrix-title",children:"Expected and observed access"}),o.jsx("span",{children:p.targetHash})]}),o.jsxs("div",{className:"assurance-table",role:"table",children:[o.jsxs("div",{className:"assurance-table__header",role:"row",children:[o.jsx("span",{role:"columnheader",children:"Operation"}),o.jsx("span",{role:"columnheader",children:"Actor"}),o.jsx("span",{role:"columnheader",children:"Expected"}),o.jsx("span",{role:"columnheader",children:"Observed"}),o.jsx("span",{role:"columnheader",children:"Impact"})]}),c.map(x=>o.jsxs("button",{type:"button",className:"assurance-table__row","aria-pressed":x.id===f?.id,onClick:()=>w(x),role:"row",children:[o.jsxs("span",{role:"cell",children:[o.jsx("small",{children:x.service}),x.operation]}),o.jsx("span",{role:"cell",children:x.actor}),o.jsx("span",{role:"cell",className:`assurance-verdict ${x.expected==="ALLOW"?"assurance-verdict--allow":"assurance-verdict--deny"}`,children:x.expected}),o.jsx("span",{role:"cell",className:`assurance-verdict ${zj(x.expected,x.observed)}`,children:x.observed}),o.jsx("span",{role:"cell",children:x.impact})]},x.id))]})]}),m?o.jsxs("aside",{className:"assurance-inspector","aria-labelledby":"assurance-inspector-title",children:[o.jsxs("div",{className:"assurance-section-heading",children:[o.jsxs("div",{children:[o.jsx("span",{className:`assurance-classification assurance-classification--${m.classification}`,children:Kj(m.classification)}),o.jsx("h2",{id:"assurance-inspector-title",children:m.probeId})]}),o.jsx("span",{children:m.actorEvidence.reachability})]}),o.jsxs("dl",{className:"assurance-facts",children:[o.jsxs("div",{children:[o.jsx("dt",{children:"Invariant"}),o.jsx("dd",{children:m.invariant.statement})]}),o.jsxs("div",{children:[o.jsx("dt",{children:"Mutation"}),o.jsx("dd",{children:m.mutationSpec.description})]}),o.jsxs("div",{children:[o.jsx("dt",{children:"Actor"}),o.jsxs("dd",{children:[m.actorEvidence.uid??m.actorEvidence.actorId," ","via ",m.actorEvidence.acquisition]})]}),o.jsxs("div",{children:[o.jsx("dt",{children:"Fidelity"}),o.jsx("dd",{children:m.qualification.supported?"Supported for this probe":"Engine gap"})]})]}),m.qualification.requirements.some(x=>!x.supported)?o.jsx("ul",{className:"assurance-gaps",children:m.qualification.requirements.filter(x=>!x.supported).map(x=>o.jsxs("li",{children:[o.jsx("code",{children:x.id}),x.reason]},x.id))}):null,m.stateDiff?o.jsxs("section",{className:"assurance-evidence","aria-labelledby":"assurance-state-title",children:[o.jsx("h3",{id:"assurance-state-title",children:"State evidence"}),o.jsxs("div",{className:"assurance-evidence__diff",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Before"}),o.jsx(ga,{value:m.stateDiff.before})]}),o.jsxs("div",{children:[o.jsx("span",{children:"After"}),o.jsx(ga,{value:m.stateDiff.after})]})]})]}):null,y?o.jsxs("section",{className:"assurance-rule-decision","aria-labelledby":"assurance-rule-title",children:[o.jsx("h3",{id:"assurance-rule-title",children:"Rule decision"}),o.jsx(Fc,{denial:y})]}):o.jsx("p",{className:"assurance-no-decision",children:"This service recorded operation and state evidence but no canonical rule-decision event."})]}):null]})]})}function nl(){const e="/__pyric/ui/";return`${e.endsWith("/")?e:`${e}/`}docs`}function Jj(){const[e,t]=h.useState(!1);return h.useEffect(()=>{let n=!0;return fetch(`${nl()}/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 Yj({id:e}){const t=mm(e),n=$e(),r=[`route #${t.id}`];return n.status==="ready"?(r.push(`events: ${n.events.length}`),r.push("dev-seed: ready")):n.status==="pending"?r.push("dev-seed: seeding…"):n.status==="error"?r.push("dev-seed: error"):r.push("dev-seed: off"),o.jsxs("section",{className:"studio__placeholder","aria-labelledby":`route-${t.id}`,children:[o.jsx("p",{className:"studio__placeholder-eyebrow",children:"Surface"}),o.jsx("h2",{id:`route-${t.id}`,className:"studio__placeholder-title",children:t.label}),o.jsx("p",{className:"studio__placeholder-blurb",children:t.description}),o.jsx("div",{className:"studio__placeholder-meta",children:r.map(s=>o.jsx("span",{children:s},s))})]})}function Qj({id:e}){switch(e){case"home":return o.jsx(aj,{});case"firestore":return o.jsx(Hw,{});case"auth":return o.jsx(ex,{});case"storage":return o.jsx(Gw,{});case"rtdb":return o.jsx(jj,{});case"traffic":return o.jsx(Hx,{});case"assurance":return o.jsx(Gj,{});case"settings":return o.jsx(Ij,{});default:return o.jsx(Yj,{id:e})}}function Xj(){const[e,t]=cm(pm,"home"),n=c=>t(c),[r,s]=h.useState(!1),i=Jj(),a=e==="home";return h.useEffect(()=>{const c=l=>{if(dm(l)){if(r){l.preventDefault(),s(!1);return}if(a){um()&&l.preventDefault();return}l.preventDefault(),s(!0)}};return window.addEventListener("keydown",c),()=>window.removeEventListener("keydown",c)},[a,r]),h.useEffect(()=>{a&&s(!1)},[a]),h.useEffect(()=>{document.querySelector('.studio__nav [aria-current="page"]')?.scrollIntoView({block:"nearest",inline:"center"})},[e]),o.jsxs("div",{className:"studio","data-surface":e,children:[o.jsx("header",{className:"studio__bar",children:o.jsxs("div",{className:"studio__bar-inner",children:[o.jsx("span",{className:"studio__brand","aria-label":"Pyric Studio",children:"Pyric"}),o.jsxs("nav",{className:"studio__nav","aria-label":"Studio tabs",children:[Ke.map(c=>o.jsx("button",{type:"button",className:"studio__nav-tab","aria-current":c.id===e?"page":void 0,onClick:()=>n(c.id),children:c.label},c.id)),i?o.jsx("a",{className:"studio__nav-tab",href:nl(),children:"Docs"}):null]}),o.jsx(rb,{})]})}),o.jsx("main",{className:"studio__content","data-surface":e,children:o.jsx("div",{className:"studio__surface-slot","data-active":"true",children:o.jsx(Qj,{id:e})})}),r?o.jsx(Vy,{onClose:()=>s(!1)}):null]})}function Zj(){return o.jsx(rm,{children:o.jsx(wd,{children:o.jsx(Xp,{mode:"local",children:o.jsx(Xj,{})})})})}function ak(){return o.jsx(h.StrictMode,{children:o.jsx(Zj,{})})}export{ak as S,sk as a,Vm as b,At as r,fe as s,po as u};
|