@pyric/cli 0.1.0-alpha.17 → 0.1.0-alpha.18
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 +29 -3
- 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/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/serve.d.ts.map +1 -1
- package/dist/cli/serve.js +1 -0
- package/dist/cli/serve.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/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/_slug_.C6QfVOxJ.css +1 -0
- package/dist/serve/site-ui/_astro/{app.bnmVTkIY.js → app.B7pBzz5N.js} +7 -7
- package/dist/serve/site-ui/_astro/app.boex5SnQ.js +1 -0
- package/dist/serve/site-ui/_astro/{chess-showcase.kC8dXLKY.js → chess-showcase.DDqE-QGe.js} +1 -1
- package/dist/serve/site-ui/_astro/{example-runtime.D79PnoSk.js → example-runtime.B0byNQOl.js} +1 -1
- package/dist/serve/site-ui/_astro/index.uwPvjH_1.js +1 -0
- package/dist/serve/site-ui/_astro/{reads.BYBRLbsE.js → reads.Dh3z0fJy.js} +1 -1
- package/dist/serve/site-ui/_astro/{sandbox-controls.C9Aaazt8.js → sandbox-controls.C2IqtoSw.js} +3 -3
- package/dist/serve/site-ui/_astro/{seed.DANAIyRw.js → seed.CCmj00su.js} +1 -1
- package/dist/serve/site-ui/auth/index.html +1 -1
- package/dist/serve/site-ui/docs/_rhythm/index.html +1 -1
- package/dist/serve/site-ui/docs/agent/set-up-your-agent/index.html +48 -13
- package/dist/serve/site-ui/docs/agent/set-up-your-agent.md +74 -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 +1 -1
- package/dist/serve/site-ui/docs/build/cloud-messaging/index.html +1 -1
- package/dist/serve/site-ui/docs/build/cloud-storage/index.html +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 +2 -2
- package/dist/serve/site-ui/docs/examples/index.html +1 -1
- package/dist/serve/site-ui/docs/firestore-compat/index.html +1 -1
- package/dist/serve/site-ui/docs/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 +17 -5
- package/dist/serve/site-ui/docs/get-started/start-building.md +29 -3
- package/dist/serve/site-ui/docs/get-started/vite/index.html +1 -1
- package/dist/serve/site-ui/docs/index.json +43 -8
- 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 +1 -1
- package/dist/serve/site-ui/examples/firestore-first-write/index.html +1 -1
- package/dist/serve/site-ui/firestore/index.html +1 -1
- package/dist/serve/site-ui/index.html +1 -1
- package/dist/serve/site-ui/llms.txt +2 -2
- package/dist/serve/site-ui/rtdb/index.html +1 -1
- package/dist/serve/site-ui/settings/index.html +1 -1
- package/dist/serve/site-ui/storage/index.html +1 -1
- package/dist/serve/site-ui/traffic/index.html +1 -1
- 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/package.json +4 -4
- package/src/bridge/server/bridge.ts +5 -2
- package/src/bridge/server/peer.ts +2 -1
- package/src/cli/serve.ts +1 -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/runtime/chip.ts +24 -3
- package/src/serve/runtime/status.ts +76 -13
- package/src/serve/vite-functions-development.ts +1 -0
- package/dist/serve/site-ui/_astro/_slug_.BoKXYrnu.css +0 -1
- package/dist/serve/site-ui/_astro/app.t6u-adB_.js +0 -1
- package/dist/serve/site-ui/_astro/index.DzVde04M.js +0 -1
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["_astro/seed.
|
|
2
|
-
import{j as o}from"./jsx-runtime.D_zvdyIk.js";import{r as h}from"./index.DBy5LfQW.js";import{r as oa,m as Ur,f as
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["_astro/seed.CCmj00su.js","_astro/sandbox-controls.C2IqtoSw.js","_astro/jsx-runtime.D_zvdyIk.js","_astro/index.DBy5LfQW.js","_astro/reads.Dh3z0fJy.js","_astro/index.uwPvjH_1.js","_astro/index.DNyk7q8W.js","_astro/RulesCodeEditor.CzwHdCi9.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{j as o}from"./jsx-runtime.D_zvdyIk.js";import{r as h}from"./index.DBy5LfQW.js";import{r as oa,m as Ur,f as Mr,h as Re,j as yn,k as la,l as Kl,n as Hl,S as Gl,v as Jl,o as Yl,t as ca,p as Xl,q as Ql,u as fs,w as ua,x as Zl,y as ec,z as da,A as Tr,B as tc,C as nc,D as hs,F as ps,E as lt,d as Be,G as kt,b as Qt,H as fa,I as ms,J as Zn,i as rc,K as sc,L as ic,M as ac,N as oc,O as lc,R as ke,P as cc,Q as ys,T as ha,U as uc,Z as pa,V as dc,W as fc,X as hc,Y as pc,_ as mc,$ as yc,a0 as bc,a1 as bn,g as ma,a2 as ya,a3 as gc,a4 as vc,a5 as wc,a6 as xc,a7 as ba,a8 as jc,a9 as ct,aa as rt,ab as gn}from"./sandbox-controls.C2IqtoSw.js";import{r as kc,t as ga,w as bs,a as _c,g as va,b as Zt}from"./reads.Dh3z0fJy.js";import{i as Sc}from"./index.uwPvjH_1.js";import{r as Ec}from"./index.DNyk7q8W.js";const Fe={maxExpressionLength:256,maxStringLiteralLength:1024,maxAstDepth:16},Cc=["serverTimestamp","increment","arrayUnion","arrayRemove","deleteField"],Nc={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 Rc(e){return Cc.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 Ac={"(":"lparen",")":"rparen","[":"lbracket","]":"rbracket",",":"comma",".":"dot","?":"question",":":"colon","+":"plus","-":"minus","*":"star","/":"slash","%":"percent"},Ic={true:"true",false:"false",null:"null"};function Dc(e){if(e.length>Fe.maxExpressionLength)throw new Z(`expression exceeds ${Fe.maxExpressionLength}-character cap (got ${e.length})`,F(Fe.maxExpressionLength));const t=[];let n=0;for(;n<e.length;){const r=n,s=e[n];if(s===" "||s===" "||s==="\r"||s===`
|
|
3
3
|
`){n+=1;continue}if(s==='"'||s==="'"){const{token:a,next:l}=Oc(e,n,s);if(t.push(a),n=l,n<=r)throw new Z("lexer stalled on string",F(r));continue}if(s>="0"&&s<="9"){const{token:a,next:l}=$c(e,n);if(t.push(a),n=l,n<=r)throw new Z("lexer stalled on number",F(r));continue}if(vn(s)){const{token:a,next:l}=Pc(e,n);t.push(a),n=l;continue}if(s==="$"){const{token:a,next:l}=gs(e,n,"$","reference");t.push(a),n=l;continue}if(s==="@"){const{token:a,next:l}=gs(e,n,"@","sentinel");t.push(a),n=l;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=Ac[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 vn(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"||e==="_"}function wa(e){return vn(e)||e>="0"&&e<="9"}function Pc(e,t){let n=t+1;for(;n<e.length&&wa(e[n]);)n+=1;const r=e.slice(t,n),s=Ic[r];return s?{token:{kind:s,pos:F(t)},next:n}:{token:{kind:"identifier",pos:F(t),value:r},next:n}}function gs(e,t,n,r){const s=t+1;if(s>=e.length||!vn(e[s]))throw new Z(`expected identifier after '${n}'`,F(t));let i=s+1;for(;i<e.length&&wa(e[i]);)i+=1;const a=e.slice(s,i);return{token:{kind:r,pos:F(t),value:a},next:i}}function $c(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 l=e[n+1];if(l!==void 0&&l>="0"&&l<="9")for(s=!0,n+=1;n<e.length&&e[n]>="0"&&e[n]<="9";)n+=1;else if(!(l!==void 0&&vn(l)))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 Oc(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
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>Fe.maxStringLiteralLength)throw new Z(`string literal exceeds ${Fe.maxStringLiteralLength}-character cap`,F(t))}throw new Z("unterminated string literal",F(t))}function Uc(e){const t=new Tc(e),n=t.parseExpression();return t.expect("eof","unexpected trailing tokens"),Lc(n),n}class Tc{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=Mc(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(!Rc(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=Nc[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 ${Bc(r)})`,r.pos);return this.consume()}}function Mc(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 Bc(e){return e.kind==="eof"?"end of expression":e.value!==void 0?`${e.kind} ${JSON.stringify(e.value)}`:e.kind}function Lc(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>Fe.maxAstDepth)throw new ye(`expression AST exceeds depth cap of ${Fe.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 It(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 le(e,t){switch(e.kind){case"literal":return e.value;case"reference":return Fc(e,t);case"sentinel":return Vc(e,t);case"unary":return qc(e,t);case"binary":return Wc(e,t);case"logical":return Kc(e,t);case"ternary":return Hc(e,t);case"fieldAccess":return Gc(e,t);case"indexAccess":return Jc(e,t)}}function Fc(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 Vc(e,t){const n=e.args.map(r=>{const s=le(r,t);if(It(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 en(r,e),{__type:"increment",value:r}}case"arrayUnion":return{__type:"arrayUnion",values:n};case"arrayRemove":return{__type:"arrayRemove",values:n}}}function qc(e,t){const n=le(e.operand,t);if(er(n,e),e.op==="-"){if(typeof n!="number")throw ue(e,`unary '-' expects a number, got ${re(n)}`);const r=-n;return en(r,e),r}if(typeof n!="boolean")throw ue(e,`unary '!' expects a boolean, got ${re(n)}`);return!n}function Wc(e,t){const n=le(e.left,t),r=le(e.right,t);switch(er(n,e),er(r,e),e.op){case"+":if(typeof n=="number"&&typeof r=="number"){const s=n+r;return en(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 en(s,e),s}case"==":return vs(e,n,r);case"!=":return!vs(e,n,r);case"<":case"<=":case">":case">=":return zc(e,n,r)}}function vs(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 zc(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 Kc(e,t){const n=le(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=le(e.right,t);if(typeof r!="boolean")throw ue(e,`'${e.op}' expects boolean operands; right is ${re(r)}`);return r}function Hc(e,t){const n=le(e.cond,t);if(typeof n!="boolean")throw ue(e,`ternary condition must be boolean, got ${re(n)}`);return le(n?e.whenTrue:e.whenFalse,t)}function Gc(e,t){const n=le(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)||It(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 Jc(e,t){const n=le(e.target,t);if(n==null)throw new oe("null-access","cannot index null target",e.pos);const r=le(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"&&!It(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 er(e,t){if(It(e))throw new oe("sentinel-misuse",`sentinel '@${e.__type}' cannot be used as an operator operand`,t.pos)}function en(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(It(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 xa="$expr";class tn extends Error{code="invalid-argument";path;constructor(t,n){super(t),this.name="ExpressionWalkError",this.path=n}}function Yc(e,t){return tr(e,t,"")}function tr(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]=tr(e[a],t,n===""?String(a):`${n}.${a}`);return i}const r=e;if(Object.prototype.hasOwnProperty.call(r,xa))return Xc(r,t,n);const s={};for(const i of Object.keys(r))s[i]=tr(r[i],t,n===""?i:`${n}.${i}`);return s}function Xc(e,t,n){const r=Object.keys(e);if(r.length!==1)throw new tn(`expression wrapper at '${n||"<root>"}' must have only the '$expr' key, got [${r.map(l=>JSON.stringify(l)).join(", ")}]`,n);const s=e[xa];if(typeof s!="string")throw new tn(`'$expr' value at '${n||"<root>"}' must be a string, got ${eu(s)}`,n);const i=Zc(s,n);return Qc(i,t,n)}function Qc(e,t,n){try{return le(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 Zc(e,t){try{return Uc(Dc(e))}catch(n){throw n instanceof Z?ws(n,Z,t):n instanceof ye?ws(n,ye,t):n}}function ws(e,t,n){const r=new t(`at '${n||"<root>"}': ${e.message}`,e.pos);return r.cause=e,r}function eu(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function tu(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/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 c=(await t()).seed({rules:a,documents:i??{}});return{ok:!0,summary:`Seeded sandbox with ${Object.keys(i??{}).length} document(s)`,data:{lint:c,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:l}=r,u=(await t()).execute({method:s,path:i,auth:a,data:l});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:l}=r,c=await t();if(l){const u=c.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:c.listDocuments(s)}}:{ok:!0,summary:`Read ${s}`,data:{document:c.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,l=(await t()).batch(s,i);return{ok:l.allowed,summary:l.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:l.allowed,results:l.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,l=await t(),{path:c,result:u}=l.createWithAutoId(s,a,i);return{ok:u.allowed,summary:u.allowed?`Created ${c}`:`Create at ${c} 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:c,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:l,writes:c}=r;for(let p=0;p<c.length;p+=1){const f=c[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(l)){const w=m.get(v).data();y[g]=w===void 0?null:w}for(let g=0;g<c.length;g+=1){const v=c[g];if(v.method==="delete"){m.delete(v.path);continue}const b=Yc(v.data,{reads:y});if(b===null||typeof b!="object"||Array.isArray(b))throw new tn(`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 (${c.length} write(s))`:"Transaction rolled back",data:f}}catch(p){if(p instanceof tn||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 ja(e){return tu({resolveSandbox:e.resolveSandbox,resolveModulesFn:oa})}let $n;function nu(){if($n)return $n;const e=Tr();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(l=>l.identifiers())]},CallExpr_memberAccess(t,n,r){return t.identifiers()},ident(t,n,r){return[this.sourceString]}}),$n=e,e}function ru(e){const t=Ur(e);if(t.failed())return{raw:e,valid:!1,errors:[{code:"PARSE_ERROR",message:t.message??"Parse failed"}],warnings:[],referencedIdentifiers:[]};const n=nu()(t).identifiers(),r=[...new Set(n)];return{raw:e,valid:!0,errors:[],warnings:[],referencedIdentifiers:r}}const su=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(su.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 xs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function st(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)=>st(s,t[i]));if(!xs(e)||!xs(t))return!1;const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(s=>s in t&&st(e[s],t[s]))}class iu{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 l=0;l<r.length-1;l++){const c=r[l],u=Object.hasOwn(i,c)?i[c]:void 0;if(u==null||typeof u!="object"||Array.isArray(u)){const d={};i[c]=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 l=r[i].path,c=r[a].path;if(l===c)throw new Error(`multi-path update: duplicate path '${l}'.`);const u=l==="/"?"/":l+"/",d=c==="/"?"/":c+"/";if(l!=="/"&&c.startsWith(u))throw new Error(`multi-path update: '${c}' is a descendant of '${l}'.`);if(c!=="/"&&l.startsWith(d))throw new Error(`multi-path update: '${l}' is a descendant of '${c}'.`)}const s=[];for(const{path:i,value:a}of r){const l=this.write(i,a);s.push({path:i,prior:l})}return s}shallowUpdate(t,n){const r=[],s=L(t);for(const[i,a]of Object.entries(n)){const l=[...s,...L(i)],c=J(l),u=this.write(c,a);r.push({path:c,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 l=0;l<r.length-1;l++){const c=i[r[l]];if(c==null||typeof c!="object"||Array.isArray(c))return;i=c}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 au(e,t){return e==="/"||t==="/"?!0:e===t||e.startsWith(`${t}/`)||t.startsWith(`${e}/`)}class ou{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=>au(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 lu{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,yn({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 l;i&&(l={engine:"rtdb",matchedPath:i.matchedPath,matchedRule:i.matchedRule,pathVariableBindings:i.pathVariableBindings,reason:i.reason,errorCode:i.errorCode});let c="user";a.origin&&(c=a.origin),Re(this.sandbox,la({service:"rtdb",method:n,path:xe(r),auth:t,result:s,origin:c,durationMs:a.durationMs,reasons:i?.reasons,rules:l,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,Kl({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,Hl({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 cu{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 nn(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 Le=[],nr=!1,rr=!1,sr=!1,On;function uu(){if(On)return On;const e=Tr();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(l=>l.lint()),r.sourceString==="child"&&t.sourceString==="data"&&(sr=!0)},ident(t,n,r){const s=this.sourceString;s==="data"&&(nr=!0),s==="newData"&&(rr=!0)},bool_true(t){Le.push({code:"HARDCODED_TRUE",message:"Rule expression is hardcoded to true"})},bool_false(t){Le.push({code:"HARDCODED_FALSE",message:"Rule expression is hardcoded to false"})},Comparison_looseEq(t,n,r){Le.push({code:"LOOSE_EQUALITY",message:"Use '===' instead of '=='"}),t.lint(),r.lint()},Comparison_looseNeq(t,n,r){Le.push({code:"LOOSE_INEQUALITY",message:"Use '!==' instead of '!='"}),t.lint(),r.lint()}}),On=e,e}function du(e,t="read"){const n=Ur(e);return n.failed()?[]:(Le=[],nr=!1,rr=!1,sr=!1,uu()(n).lint(),t==="write"&&nr&&!rr&&!sr&&Le.push({code:"DATA_IN_WRITE",message:"Write rule references 'data' but not 'newData'; consider using 'newData' to check incoming data"}),[...Le])}const fu=new Set(["__proto__","prototype","constructor"]);function js(e,t){return fu.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 hu{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:{}},Un;function pu(){if(Un)return Un;const e=Tr();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 l=t.eval(),c=r.sourceString,u=i.asIteration().children.map(d=>d.eval());if(l instanceof je)switch(c){case"val":return l.val();case"exists":return l.exists();case"hasChild":return l.hasChild(String(u[0]));case"hasChildren":return l.hasChildren(u.length>0?u[0]:void 0);case"isString":return l.isString();case"isNumber":return l.isNumber();case"isBoolean":return l.isBoolean();case"child":return l.child(String(u[0]));case"parent":return l.parent();case"getPriority":return l.getPriority();default:throw new Error(`Unknown DataSnapshot method: ${c}`)}if(typeof l=="string"){const d=new hu(l);switch(c){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: ${c}`)}}throw new Error(`Unknown method '${c}' for the given value.`)},CallExpr_memberAccess(t,n,r){const s=t.eval();return s==null?null:js(s,r.sourceString)},CallExpr_indexAccess(t,n,r,s){const i=t.eval(),a=r.eval();return i==null?null:js(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}}}),Un=e,e}function ka(e,t){const n=Ur(e);if(n.failed())throw new Error(n.message??"RTDB expression failed to parse");return Ee=t,pu()(n).eval()}function mu(e){const t=e.val();return t===null||typeof t!="object"?[]:Object.keys(t)}function yu(e,t,n,r,s,i){let a=null;function l(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(!ka(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 l(g,d.child(m[0]),p.child(m[0]),w?{...f,[b]:m[0]}:f,m.slice(1))}if(w)for(const x of mu(p)){const k=l(g,d.child(x),p.child(x),{...f,[b]:x},[]);if(k)return k}else{const x=l(g,d.child(b),p.child(b),f,[]);if(x)return x}}return null}return l(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 l=a[a.length-1],c=l.startsWith("$");if(c||t[0]===l){const u=c?{...n,[l]:t[0]}:{...n},d=_a(i,t.slice(1),u,r+1);return s.push(...d),s}}return s}function ir(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,l=ir(a,s,n);return l==null?delete i[r]:i[r]=l,i}function bu(e,t,n,r){if(!r||r.length===0)return ir(e,t,n??null);let s=e;for(const i of r){const a=i.path.split("/").filter(Boolean);s=ir(s,a,i.value??null)}return s}class gu{execute(t,n){const r=Gl.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:l,newData:c,updates:u}=r.data;try{const d=i.split("/").filter(Boolean),p=t,f=_a(p,d,{}),m=new je(l,"/"),y=s==="read"?l:bu(l,d,c,u),g=new je(y,"/"),v=(k,j,_)=>{const N={};for(const[P,I]of Object.entries(_))N[P]=I,N[P.slice(1)]=I;return{auth:a?{uid:a.uid,token:a.token}:null,data:k,newData:j,root:m,now:Date.now(),pathVariableBindings:N}};let b;for(const k of f){const j=k.node[s];if(!j)continue;if(!j.parsed.valid){b||(b=k);continue}const _=d.slice(0,k.depth).join("/"),N=m.child(_),P=g.child(_);if(ka(j.raw,v(N,P,k.pathVariableBindings))){if(s==="write"){const D=yu(p,m,g,{},v,d);if(D)return{success:!0,data:{allowed:!1,unsupported:D.unsupported===!0,matchedPath:D.node.path,matchedRule:D.rule.raw,reason:D.unsupported?`Validation rule at '${D.node.path}' contains an expression the simulator cannot evaluate: ${D.rule.raw} — not evaluated; production may reject this write.`:"Validation rule evaluated to false",pathVariableBindings:D.bindings}}}return{success:!0,data:{allowed:!0,matchedPath:k.node.path,matchedRule:j.raw,reason:"Rule expression evaluated to true",pathVariableBindings:k.pathVariableBindings}}}}if(b){const k=b.node[s];return{success:!0,data:{allowed:!1,unsupported:!0,matchedPath:b.node.path,matchedRule:k.raw,reason:`'${s}' rule at '${b.node.path}' contains an expression the simulator cannot evaluate: ${k.raw} — not evaluated; production may reject or allow this ${s}.`,pathVariableBindings:b.pathVariableBindings}}}const w=f[f.length-1],x=w.node[s];return x?{success:!0,data:{allowed:!1,matchedPath:w.node.path,matchedRule:x.raw,reason:"Rule expression evaluated to false",pathVariableBindings:w.pathVariableBindings}}:{success:!1,error:{code:"NO_MATCHING_RULE",message:`No '${s}' rule found for path '${i}'`,recoverable:!0}}}catch(d){return{success:!1,error:{code:"EVALUATION_ERROR",message:d instanceof Error?d.message:String(d),recoverable:!1}}}}}const vu=new Set([".read",".write",".validate",".indexOn"]);function Sa(e,t,n=[]){const r=ru(e),s=r.valid?Jl(e,t,n):r.errors,i=r.valid?du(e,t):[];return{raw:e,parsed:{...r,errors:s,warnings:i}}}function Ea(e,t,n){const r={path:t,pathVariables:[...n],children:[]};for(const[i,a]of[[".read","read"],[".write","write"],[".validate","validate"]]){const l=e[i];l!==void 0&&(r[a]=Sa(String(l),a,n))}const s=e[".indexOn"];s!==void 0&&(r.indexOn=Array.isArray(s)?s.map(String):[String(s)]);for(const[i,a]of Object.entries(e)){if(vu.has(i)||typeof a!="object"||a===null)continue;const l=t==="/"?`/${i}`:`${t}/${i}`,c=i.startsWith("$")?[...n,i]:[...n];r.children.push(Ea(a,l,c))}return r}function Ca(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 Ea(t.rules,"/",[])}function Tn(e){return e==="true"?!0:e==="false"?!1:e}function Na(e){const t={};e.read&&(t[".read"]=Tn(e.read.raw)),e.write&&(t[".write"]=Tn(e.write.raw)),e.validate&&(t[".validate"]=Tn(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]]=Na(n)}return t}function wu(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:Na(e)}}function Br(e,t){return new gu().execute(e,t)}function ve(){const e=new Error("PERMISSION_DENIED: Permission denied");return e.code="PERMISSION_DENIED",e}class xu{compiled=null;setRules(t){if(t===null){this.compiled=null;return}this.compiled=Ca(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=Br(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 ju{tree=new iu;rules=new xu;activeRules=null;valueListeners=new Set;childListeners=new Set;priorities=new cu;mutations=new ou;events;writeSubscribers=new Set;resetGeneration=0;constructor(t){this.events=new lu(t)}notifyWrite(){for(const t of this.writeSubscribers)try{t()}catch{}}}function Lr(e,t){if(e===t)return 0;if(e===null)return-1;if(t===null)return 1;const n=ks(e),r=ks(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 ks(e){return e===null?0:typeof e=="boolean"?1:typeof e=="number"?2:typeof e=="string"?3:4}const ku=/^-?(0*)\d{1,10}$/,_u=-2147483648,Su=2147483647;function _s(e){if(ku.test(e)){const t=Number(e);if(t>=_u&&t<=Su)return t}return null}function rn(e,t){if(e===t)return 0;const n=_s(e),r=_s(t);return n!==null?r!==null?n-r===0?e.length-t.length:n-r:-1:r!==null?1:e<t?-1:1}function _t(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(l=>l.length>0);let a=n;for(const l of i){if(a===null||typeof a!="object"||Array.isArray(a))return null;a=a[l]??null}return a}}}function Ve(e,t,n=()=>null){if(e===null||typeof e!="object"||Array.isArray(e))return[];let s=Object.entries(e).map(([a,l])=>({key:a,value:l,priority:n(a)}));const i=t.orderBy?.kind==="key";s.sort((a,l)=>{if(i)return rn(a.key,l.key);const c=_t(t.orderBy,a.key,a.value,a.priority),u=_t(t.orderBy,l.key,l.value,l.priority),d=Lr(c,u);return d!==0?d:rn(a.key,l.key)});for(const a of t.bounds)s=s.filter(l=>Eu(a,l,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 Eu(e,t,n){const s=n?.kind==="key"?rn(t.key,String(e.value)):Lr(_t(n,t.key,t.value,t.priority),e.value),i=a=>rn(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 Ss(e){return e.length===0?null:Object.fromEntries(e.map(({key:t,value:n})=>[t,n]))}function Cu(e,t){return e.length===t.length&&e.every((n,r)=>{const s=t[r];return n.key===s.key&&n.priority===s.priority&&st(n.value,s.value)})}function Fr(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 Nu{state;constructor(t){this.state=t}onValue(t,n,r,s,i,a){const l=Date.now(),c=this.state.rules.evaluate("read",n==="/"?"/":n,{auth:t,mockData:this.state.tree.snapshot()});if(c.check!=="allow"){let u;s&&(u={query:s}),this.state.events.operation(t,"listen",n,he(c.check),c,{at:l,durationMs:Date.now()-l,request:u,origin:"listener"});const d={engine:"rtdb",matchedPath:c.matchedPath,matchedRule:c.matchedRule,pathVariableBindings:c.pathVariableBindings,reason:c.reason,errorCode:c.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:c.reasons},reasons:c.reasons,rules:d}),i)return queueMicrotask(()=>{a&&a(),i(Fr(n))}),()=>{};throw ve()}return this.attach(t,n,r,s,{origin:"listener",result:"allow",evaluation:c,at:l},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,l){const c=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:c,auth:t,cb:r,path:n,query:s,cancelCallback:a,onCanceled:l};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=Ve(this.state.tree.read(n),s,this.state.priorities.forChild(n));u.lastWindow=d,this.deliverInitial(u,{val:Ss(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(l=>Ru(s,l)))continue;if(r.query){const l=Ve(this.state.tree.read(r.path),r.query,this.state.priorities.forChild(r.path));if(Cu(r.lastWindow??[],l)){this.state.events.listener("suppressed",r,r.auth,{event:"value",reason:"no-op",detail:{query:!0}});continue}r.lastWindow=l,this.deliver(r,{val:Ss(l),exists:l.length>0,key:this.key(r.path),rows:l},{query:!0});continue}const i=this.snapshot(r.path),a=this.state.priorities.stateAtOrBelow(r.path);if(st(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 Ru(e,t){if(e===t||e==="/")return!0;const n=`${e}/`,r=t==="/"?"/":`${t}/`;return t.startsWith(n)||e.startsWith(r)}function He(e,t){const n=e.findIndex(r=>r.key===t);return n>0?e[n-1].key:null}function mt(e,t){const n=e.findIndex(r=>r.key===t);return n>0?e[n-1].key:null}function Es(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 Au{state;constructor(t){this.state=t}onChild(t,n,r,s,i,a,l){const c=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:c,durationMs:Date.now()-c,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(()=>{l&&l(),a(Fr(r))}),()=>{};throw ve()}this.state.events.operation(t,"listen",r,"allow",d,{at:c,durationMs:Date.now()-c,origin:"listener",detail:{event:n}});const p={id:u,auth:t,event:n,path:r,cb:s,spec:i,cancelCallback:a,onCanceled:l};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=Ve(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:He(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:mt(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,l=new Map(this.directChildren(s).map(({key:f,val:m})=>[f,m])),c=[...l].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 l)a.has(f)?st(a.get(f),m)||d.child_changed.push({key:f,val:m,previousChildName:mt(c,f)}):d.child_added.push({key:f,val:m,previousChildName:mt(c,f)});for(const[f,m]of a)l.has(f)||d.child_removed.push({key:f,val:m,previousChildName:mt(u,f)});const p=Es(s,n);p!==null&&a.has(p)&&l.has(p)&&d.child_moved.push({key:p,val:l.get(p),previousChildName:mt(c,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)?[]:Ve(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=Ve(this.state.tree.read(t.path),t.spec,this.state.priorities.forChild(t.path));t.lastWindow=s;const i=new Map(r.map(c=>[c.key,c.value])),a=new Map(s.map(c=>[c.key,c.value])),l=[];if(t.event==="child_added")for(const c of s)i.has(c.key)||l.push({key:c.key,val:c.value,previousChildName:He(s,c.key)});else if(t.event==="child_changed")for(const c of s)i.has(c.key)&&!st(i.get(c.key),c.value)&&l.push({key:c.key,val:c.value,previousChildName:He(s,c.key)});else if(t.event==="child_removed")for(const c of r)a.has(c.key)||l.push({key:c.key,val:c.value,previousChildName:He(r,c.key)});else if(t.spec?.orderBy&&t.spec.orderBy.kind!=="key"){const c=t.spec.orderBy.kind==="priority"?Es(t.path,n):null;let u=!1;if(c!==null){const d=s.find(p=>p.key===c);d&&i.has(c)&&(l.push({key:d.key,val:d.value,previousChildName:He(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=_t(t.spec.orderBy,f.key,f.value,f.priority),y=_t(t.spec.orderBy,p.key,p.value,p.priority);Lr(m,y)!==0&&l.push({key:p.key,val:p.value,previousChildName:He(s,p.key)})}}}for(const c of l)this.deliver(t,c,{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 Iu(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 l=!1;i&&a&&(l=!0);const c=r.priorities,u=c!==null,d=c!==void 0;let p=!1;if(u&&d){const m=typeof c=="object",y=Array.isArray(c);m&&(y||(p=!0))}let f=!1;if(l&&p&&(f=!0),f){const m={},y=Object.entries(c);for(const[j,_]of y){const N=typeof _=="string",P=typeof _=="number";let I=!1;P&&Number.isFinite(_)&&(I=!0);let D=!1;N&&(D=!0),I&&(D=!0),D&&(m[j]=_)}const g=r.data;let v=null;g!==void 0&&g!==null&&(v=g);const w=r.rules;let x=null;if(w!==void 0&&w!==null){const _=typeof w=="object",N=Array.isArray(w);let P=!1;if(_&&(N||(P=!0)),P){const I=w;if("rules"in I){const C=I.rules;if(C!==null&&C!==void 0){const R=typeof C=="object",V=Array.isArray(C);let G=!1;R&&(V||(G=!0)),G&&(x={rules:C})}}}}return{data:v,priorities:m,rules:x}}}return{data:e,priorities:{},rules:null}}class Du{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=Iu(t);let s={};const i=r.data===null,a=r.data===void 0;let l=!1;i||a||(l=!0),l&&(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 Pu=/[\[\].#$/\u0000-\u001F\u007F]/;function $u(e){return e.length!==0&&!Pu.test(e)}function Ou(e){return typeof e=="number"&&(Number.isNaN(e)||e===1/0||e===-1/0)}function Uu(e){return e===".priority"||e===".value"||e===".sv"}function Tu(e,t){ar(e,t,"set")}function ar(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(Ou(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&&ar(s,`${t}/${r}`,n)}return}for(const[r,s]of Object.entries(e)){if(!Uu(r)&&!$u(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 "]"`);ar(s,`${t}/${r}`,n)}}}function Me(e,t){return Tu(e,t),or(e)}function or(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=or(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=or(r);s!==null&&(t[n]=s)}return Object.keys(t).length===0?null:t}function Yt(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(a=>Yt(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 l=0;l<=s;l++){const c=t[String(l)];a[l]=c===void 0?null:Yt(c)}return a}const i={};for(const[a,l]of Object.entries(t))i[a]=Yt(l);return i}function Mu(e){return e===null||typeof e!="object"?!1:e[".sv"]==="timestamp"}function Bu(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(Mu(e))return t;if(Bu(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 Cs(){return new Error("permission_denied")}class Lu{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),l=a.length===0?null:a[a.length-1];let c=null,u,d=0,p=!1;do{d+=1;const x=this.state.mutations.begin();c=this.state.tree.read(n);const k=c===null?null:Yt(Ne(c));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:c,exists:c!==null},detail:{committed:!1,aborted:!0}}),{committed:!1,val:c,key:l};const m=Date.now(),y=Me(we(u,m,c),n==="/"?"":n);if(i){const x=this.state.tree.snapshot(),k=Object.fromEntries(this.state.priorities.entries()),j=this.state.priorities.get(n),_=this.children.snapshotParents();this.state.tree.write(n,y),this.state.priorities.replace(n,j),this.values.fanOut([n]),this.children.fanOut(_);const N=Date.now(),P=this.state.rules.evaluate("write",n==="/"?"/":n,{auth:t,mockData:x,newData:y});if(P.check!=="allow"){this.state.events.operation(t,"transaction",n,he(P.check),P,{at:N,durationMs:Date.now()-N,origin:"transaction",request:{data:u,resourceData:u},resourceBefore:{data:c,exists:c!==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),Cs()}return this.recordCommit(t,n,u,c,y,f,m,N,!0,P),{committed:!0,val:y,key:l}}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:c,exists:c!==null},resourceAfter:{data:y,exists:y!==null},groupId:f,groupKind:"transaction"}),Cs();this.state.events.operation(t,"transaction",n,"allow",v,{at:g,durationMs:Date.now()-g,origin:"transaction",request:{data:u,resourceData:u},resourceBefore:{data:c,exists:c!==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,c,y,f,m,!1),this.state.notifyWrite(),{committed:!0,val:y,key:l}}recordCommit(t,n,r,s,i,a,l,c,u,d){this.state.events.operation(t,"transaction",n,"allow",d,{at:c,durationMs:Date.now()-c,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,l,u),this.state.mutations.mark(n),this.state.notifyWrite()}finishEvents(t,n,r,s,i,a,l,c){this.state.events.commit(t,"transaction",n,{data:r,priorState:s,nextState:i,groupId:a,groupKind:"transaction",replay:{requestTime:l},detail:{committed:!0,applyLocally:c}}),this.state.events.mutation(t,"transaction",xe(n),{before:s,after:i,detail:{committed:!0}})}}class Fu{state;values;children;constructor(t,n,r){this.state=t,this.values=n,this.children=r}adminSet(t,n){if(nn(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){nn(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}),l=this.state.priorities.get(n),c={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:l}};if(a.check!=="allow")throw this.state.events.operation(t,"setPriority",n,he(a.check),a,c),ve();if(this.state.events.operation(t,"setPriority",n,"allow",a,c),s===null)return;const u=this.children.snapshotParents(),d=l!==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:l,nextState:r,detail:{priority:r,priorPriority:l}}),this.state.events.mutation(t,"setPriority",xe(n),{before:l,after:r,detail:{priorityMetadata:!0}})),this.state.notifyWrite()}}function Ns(e){return e.length===0?null:Object.fromEntries(e.map(({key:t,value:n})=>[t,n]))}class Vu{state;values;children;priorityWrites;constructor(t,n,r){this.state=t,this.values=n,this.children=r,this.priorityWrites=new Fu(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,Me(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=Ve(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:Ns(r),exists:r.length>0}}),r}adminSet(t,n){this.adminSetWithPriority(t,n,null,!1)}adminSetWithPriority(t,n,r,s=!0){nn(r);const i=Date.now(),a=this.state.tree.read(t),l=Me(we(n,i,a),t==="/"?"":t),c=l===null?"remove":"set";this.state.events.operation(null,c,t,"not-applicable",void 0,{origin:"admin",request:{data:n,resourceData:n},resourceBefore:{data:a,exists:a!==null},resourceAfter:{data:l,exists:l!==null}});const u=this.children.snapshotParents(),d=this.state.priorities.get(t),p=this.state.priorities.stateAtOrBelow(t);this.state.tree.write(t,l),this.state.priorities.replace(t,l===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 l=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),l);const c=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:c}),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=Ve(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:Ns(a),exists:a.length>0}}),a}set(t,n,r){this.setInternal(t,n,r,"set",null,!1)}setWithPriority(t,n,r,s){nn(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=Me(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,l])=>{const c=J([...L(n),...L(a)]);return{path:c,value:Me(we(l,Date.now(),this.state.tree.read(c)),c)}});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("/")),l=this.state.tree.snapshot(),c=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 c){const g=Date.now(),v=this.state.tree.read(y.path),b=this.state.rules.evaluate("write",y.path,{auth:t,mockData:l,newData:y.value,...a?{updates:c}:{}}),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(c),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 l=Date.now(),c=Me(we(r,l,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,c),m={at:p,durationMs:Date.now()-p,request:{data:r,resourceData:r},resourceBefore:{data:u,exists:u!==null},resourceAfter:{data:c,exists:c!==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,c),this.state.priorities.replace(n,c===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:l},...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,Me(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(Fr(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 qu{state;values;children;writes;transactions;persistence;constructor(t){this.state=new ju(t),this.values=new Nu(this.state),this.children=new Au(this.state),this.writes=new Vu(this.state,this.values,this.children),this.transactions=new Lu(this.state,this.values,this.children),this.persistence=new Du(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,l){return this.children.onChild(t,n,r,s,i,a,l)}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 Yl()}listenerCount(){return this.values.count()}childListenerCount(){return this.children.count()}}const Rs=new WeakMap;function Ra(e){let t=Rs.get(e);if(t)return t;t=new qu(e),Rs.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 Aa(e){return Ra(e).getActiveRules()}function As(e){return Ra(e).snapshotState()}function Ia(e){return typeof e=="string"?e:e._internalPath.segments.join(".")}function sn(e,...t){const n=ca(e),r=Xl(e),s=Ql(e);let i,a;try{i=t.map(u=>u.prepareSandbox?.(n)??u)}catch(u){throw fs(u)}const l=u=>{let d=s(u);for(const p of i)d=p.applySandbox(d);return d};try{a=l(ua(n))}catch(u){throw fs(u)}const c=Zl(a,n,u=>l(u));return r?ec(c,n,r):c}function Wu(e,t,n){return Da(Ia(e),t,n,!1)}function Da(e,t,n,r){return{type:"where",applySandbox:i=>i.where(e,t,n),prepareSandbox:r?void 0:i=>{const a=da(n,i,t==="in"||t==="not-in");return Da(e,t,a.executionValue,!0)},_sandboxFilter:{kind:"where",field:e,op:t,value:n}}}function Is(e,t){const n=Ia(e);return{type:"orderBy",applySandbox:r=>r.orderBy(n,t)}}function an(e){return{type:"limit",applySandbox:t=>t.limit(e)}}function zu(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 Ku(...e){return zu(e)?Pa(e[0],!1,!0):$a(e,!1,!0)}function Pa(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=kc(e),i=s.data(),a=Object.freeze({id:s.id,ref:s.ref,exists:i!==void 0,data:()=>i});return Pa(a,t,n,!0)}}}function $a(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=>$a(e.map(i=>da(i,s).executionValue),t,n,!0)}}function Hu(e,t,n,r){const s=ca(e);Mr(s).markStarted();const i=Ju(s,e),a=Yu(t,n,r,s,e),l=Xu(a,s),c=l.length===3?i.onSnapshot(l[0],l[1],l[2]):l.length===2?i.onSnapshot(l[0],l[1]):i.onSnapshot(l[0]);if(!s.own)return c;let u=!1;const d=()=>{u||(u=!0,c())},p=()=>{u||(d(),Gu(l)?.(new lt("aborted","The operation was aborted.")))},f=s.own(p);return()=>{f(),d()}}function Gu(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 Ju(e,t){const n=tc(t);if(e.kind==="sandbox")return n;const r=nc.get(n);if(!r)throw new TypeError("pyric/firestore: live ref missing rebuild closure for onSnapshot.");return r(ua(e))}function Oa(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 Yu(e,t,n,r,s){if(typeof e=="object"&&e!==null&&!Oa(e)){const a=t;return typeof a=="function"?[e,Ds(a,r,s),n??lr]:a&&typeof a=="object"?[e,Ps(a,r,s)]:[e]}return typeof e=="function"?[Ds(e,r,s),t??lr]:e&&typeof e=="object"?[Ps(e,r,s)]:[e]}function Xu(e,t){if(t.kind!=="sandbox-live")return e;const n=e[0];return typeof n=="object"&&n!==null&&!Oa(n)?[{...n,[ps]:!0,...t.authScope?{[hs]:t.authScope}:{}},...e.slice(1)]:[{[ps]:!0,...t.authScope?{[hs]:t.authScope}:{}},...e]}function Ua(e,t,n){if(!e||typeof e!="object")return e;const r=e;if(typeof r.data=="function"&&bs(e,t),Array.isArray(r.docs)){for(const s of r.docs)bs(s,t);_c(e,e,t,n,"listener")}return e}function lr(e){console.error("pyric/firestore: Uncaught Error in snapshot listener:",e)}function Ds(e,t,n){return r=>{e(Ua(ga(r,t),t,n)),Mr(t).notifySnapshotDelivered()}}function Ps(e,t,n){return{...e,next:e.next?r=>{e.next(Ua(ga(r,t),t,n)),Mr(t).notifySnapshotDelivered()}:void 0,error:e.error??lr}}const Se={description:"Identity to act as. Omit or 'admin' = admin write that BYPASSES rules (sandbox seeding). { uid, claims? } = act as that user with rules ENFORCED.",oneOf:[{type:"string",enum:["admin"]},{type:"object",properties:{uid:{type:"string"},claims:{type:"object",description:"Custom claims forwarded to the rule context (request.auth.token)."}},required:["uid"]}]},Qu=["<","<=","==","!=",">=",">","in","not-in","array-contains","array-contains-any"],Zu={type:"object",properties:{field:{type:"string"},op:{type:"string",enum:[...Qu]},value:{}},required:["field","op","value"]};function Ta(e){const{resolveDb:t}=e;return[{name:"firestore_get_document",description:"Get a Firestore document by path. Admin by default; pass `as:{uid}` to read with rules enforced as that user.",parameters:{type:"object",properties:{path:{type:"string",description:'e.g. "users/alice"'},as:Se},required:["path"]},async execute(n){const r=n,s=await t(r.as),i=Be(s,r.path),a=await va(i),l=typeof a.exists=="function"?a.exists():a.exists;return{ok:!0,summary:l?`Got ${r.path}`:`No document at ${r.path}`,data:{exists:l,data:l?a.data():null}}}},{name:"firestore_list_documents",description:"List documents in a collection. Supports orderBy + limit. Admin by default; pass `as:{uid}` to enforce rules.",parameters:{type:"object",properties:{collection:{type:"string"},orderBy:{type:"string"},limit:{type:"number"},as:Se},required:["collection"]},async execute(n){const r=n,s=await t(r.as),i=kt(s,r.collection),a=[];r.orderBy&&a.push(Is(r.orderBy)),r.limit&&a.push(an(r.limit));const l=await Zt(sn(i,...a));return{ok:!0,summary:`${l.size} docs in ${r.collection}`,data:{docs:l.docs.map(c=>({id:c.id,data:c.data()}))}}}},{name:"firestore_create_document",description:"Create or replace a Firestore document at an explicit path. Admin by default (bypasses rules — for seeding); pass `as:{uid}` to write as that user with rules enforced.",parameters:{type:"object",properties:{path:{type:"string"},data:{type:"object"},as:Se},required:["path","data"]},async execute(n){const r=n,s=await t(r.as);return await Qt(Be(s,r.path),r.data),{ok:!0,summary:`Created ${r.path}`}}},{name:"firestore_add_document",description:"Add a document with an auto-generated id under a collection (mirrors the Web SDK addDoc). Admin by default — the right tool for seeding; pass `as:{uid}` to write as a user with rules enforced. Returns the minted path.",parameters:{type:"object",properties:{collection:{type:"string",description:'Collection to add the doc under, e.g. "users" or "users/u1/posts".'},data:{type:"object"},as:Se},required:["collection","data"]},async execute(n){const r=n,s=await t(r.as),i=await fa(kt(s,r.collection),r.data);return{ok:!0,summary:`Created ${i.path}`,data:{path:i.path,id:i.id}}}},{name:"firestore_update_document",description:"Merge fields into an existing Firestore document. Admin by default; pass `as:{uid}` to enforce rules.",parameters:{type:"object",properties:{path:{type:"string"},data:{type:"object"},as:Se},required:["path","data"]},async execute(n){const r=n,s=await t(r.as);return await ms(Be(s,r.path),r.data),{ok:!0,summary:`Updated ${r.path}`}}},{name:"firestore_delete_document",description:"Delete a Firestore document. Admin by default; pass `as:{uid}` to enforce rules.",parameters:{type:"object",properties:{path:{type:"string"},as:Se},required:["path"]},async execute(n){const r=n,s=await t(r.as);return await Zn(Be(s,r.path)),{ok:!0,summary:`Deleted ${r.path}`}}},{name:"firestore_batch_write",description:"Apply many writes (set / update / delete) in ONE call — the efficient way to seed or bulk-edit (one call, not N). Applied in order; stops on the first failure. Admin by default; pass `as:{uid}` to apply them as a user with rules enforced. Up to 500 ops.",parameters:{type:"object",properties:{operations:{type:"array",description:"Writes applied in order; stops on the first failure (NOT atomic — earlier writes are not rolled back).",minItems:1,maxItems:500,items:{type:"object",properties:{op:{type:"string",enum:["set","update","delete"]},path:{type:"string"},data:{type:"object",description:"Required for set/update; ignored for delete."}},required:["op","path"]}},as:Se},required:["operations"]},async execute(n){const r=n;if(r.operations.length===0||r.operations.length>500)return{ok:!1,summary:`firestore_batch_write: operations must be 1..500 (got ${r.operations.length}).`};const s=await t(r.as);for(const i of r.operations){const a=Be(s,i.path);i.op==="set"?await Qt(a,i.data??{}):i.op==="update"?await ms(a,i.data??{}):await Zn(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:Zu,minItems:1},orderBy:{type:"string"},limit:{type:"number"},as:Se},required:["collection","where"]},async execute(n){const r=n,s=await t(r.as),i=kt(s,r.collection),a=r.where.map(c=>Wu(c.field,c.op,c.value));r.orderBy&&a.push(Is(r.orderBy)),r.limit&&a.push(an(r.limit));const l=await Zt(sn(i,...a));return{ok:!0,summary:`${l.size} matches in ${r.collection}`,data:{docs:l.docs.map(c=>({id:c.id,data:c.data()}))}}}}]}function Ma(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=rc(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 ed="modulepreload",td=function(e){return"/__pyric/ui/"+e},$s={},Ba=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 l=document.querySelector("meta[property=csp-nonce]"),c=l?.nonce||l?.getAttribute("nonce");s=a(n.map(u=>{if(u=td(u),u in $s)return;$s[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":ed,d||(f.as="script"),f.crossOrigin="",f.href=u,c&&f.setAttribute("nonce",c),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 l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=a,window.dispatchEvent(l),!l.defaultPrevented)throw a}return s.then(a=>{for(const l of a||[])l.status==="rejected"&&i(l.reason);return t().catch(i)})};function La(e){return e.kind==="session_boundary"&&e.phase==="reset"}function nd(e,t){return La(t)?[t]:[...e,t]}const Fa=h.createContext(null),Va={status:"disabled",handles:null,events:[]};function rd({children:e}){return o.jsx(Fa.Provider,{value:Va,children:e})}function Pe(){return h.useContext(Fa)??Va}function yt(e,t){return`${e.replace(/\/$/,"")}${t}`}function sd(e){const t=e;return{async read(n){const r=await fetch(yt(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(yt(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(yt(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(yt(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(yt(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 bt(e,t){return`${e.replace(/\/$/,"")}${t}`}function id(e){const t=e;return{async list(){const n=await fetch(bt(t,"/__pyric/projects"));if(!n.ok)throw new Error(`projects.list() → ${n.status}`);return await n.json()},async open(n){const r=await fetch(bt(t,`/__pyric/projects/${encodeURIComponent(n)}`));if(!r.ok)throw new Error(`projects.open(${n}) → ${r.status}`);return{meta:await r.json(),workspace:sd(t)}},async create(n){const r=await fetch(bt(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(bt(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(bt(t,`/__pyric/projects/${encodeURIComponent(n)}`),{method:"DELETE"});if(!r.ok)throw new Error(`projects.remove(${n}) → ${r.status}`)}}}function ad(e,t){return`${e.replace(/\/$/,"")}${t}`}function Mn(e){return/auth/i.test(e)?"auth":"firestore"}function od(e){const t=e,r={"content-type":"application/json","x-pyric-writer":`studio-${Math.random().toString(36).slice(2)}`},s=new Map,i=c=>ad(t,`/__pyric/state?section=${Mn(c)}`),a=async c=>{const u=Mn(c),d=s.get(u);if(d)return d;const p=await fetch(i(c));let f=new Map;if(p.ok){const m=await p.text();m&&m!=="null"&&(f=sc(m))}else if(p.status!==404)throw new Error(`persistence.read(${c}) → ${p.status}`);return s.set(u,f),f},l=async(c,u)=>{const d=await fetch(i(c),{method:"POST",headers:r,body:ic(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(${c}) → ${d.status}`)};return{async getRecord(c,u){return(await a(c)).get(u)??null},async listRecords(c){return[...(await a(c)).keys()]},async putRecords(c,u){const d=await a(c);for(const[p,f]of u)d.set(p,f);await l(c,d)},async deleteRecords(c,u){const d=await a(c);for(const p of u)d.delete(p);await l(c,d)},async clear(c){s.set(Mn(c),new Map);const u=await fetch(i(c),{method:"POST",headers:r,body:"null"});if(!u.ok&&u.status!==423)throw new Error(`persistence.clear(${c}) → ${u.status}`)}}}const ld="local";function cd(){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 ud(){const e=cd();let t={id:ld,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 dd="/__pyric/sdk/worker.js",Ce="pyric-shared-worker",fd="/__pyric/ui/";function qa(e=typeof document>"u"?void 0:document){const t=e?.querySelector('meta[name="pyric-worker-v"]')?.getAttribute("content")?.trim()||null;return{studioUrl:fd,worker:{url:dd,name:Ce,servedEpoch:t}}}const on="pyric:worker-generation",gt="pyric:worker-generation-probe";function hd(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(on);return r&&/^[a-f0-9]{16}$/.test(r)?`${Ce}:${r}`:n?(t.setItem(on,n),`${Ce}:${n}`):Ce}catch{return n?`${Ce}:${n}`:Ce}}function pd(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(on,e),t.getItem(on)!==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 md(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(gt);if(e.setItem(gt,"ok"),e.getItem(gt)!=="ok")throw new Error("the worker generation probe could not be read back");t===null?e.removeItem(gt):e.setItem(gt,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 yd(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 bd(){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 Wa=new WeakMap;let cr;function gd(e,t,n=bd()){const r=e.name,s=n===t?void 0:{},i=new Map,a=new Set,l={app:e,sandbox:t,session:n,services:i,cleanups:a,assertAlive(){if(l.deleted)throw new lt("app/app-deleted",`Firebase: Firebase App named '${r}' already deleted (app/app-deleted).`)},...s?{authScope:s}:{},service(c,u){const d=i.get(c);if(d!==void 0)return d;l.assertAlive();const p=u();return i.set(c,p),p},onDelete(c){return l.deleted?(c(),()=>{}):(a.add(c),()=>a.delete(c))},deleted:!1};return Wa.set(e,l),l}function vd(e){cr=e}ac({resolve(e,t){const n=typeof e=="object"&&e!==null?Wa.get(e):void 0;if(n)return n},defaultApp(){if(!cr)throw new TypeError("No default sandbox app registry is installed - import and initialize pyric/app before calling a service factory without an app.");return cr()}});const wd="[DEFAULT]",xd=new Map;function jd(e,t){return new lt(`app/${e}`,`Firebase: ${t} (app/${e}).`)}function kd(e){return jd("no-app",`No Firebase App '${e}' has been created - call initializeApp() first`)}function _d(e=wd){const t=xd.get(e);if(!t)throw kd(e);return t.app}vd(_d);let Sd=0,Ed=0;function T(){return`op-${++Sd}`}function ut(){return`sub-${++Ed}`}const it=new Map,St=new Map,Et=new Map,dt=new WeakSet,ur=new Set;function Cd(e){return ur.add(e),()=>ur.delete(e)}function za(){return Object.assign(new Error("Firebase App was deleted"),{code:"app/app-deleted"})}function Dt(e,t,n,r){return dt.has(e)?!1:(St.set(t,n),e.postMessage(r),!0)}function Nd(e,t,n,r){return dt.has(e)?!1:(Et.set(t,{port:e,next:n}),e.postMessage(r),!0)}function Pt(e,t){St.delete(t),Et.delete(t),dt.has(e)||e.postMessage({t:"unsub",subId:t})}function Rd(e){dt.add(e);const t=za();for(const[n,r]of[...it])r.port===e&&(it.delete(n),r.reject(t));for(const[n,r]of[...St])r.port===e&&(St.delete(n),r.service==="firestore"&&r.error?.(new lt("aborted","The operation was aborted.")));for(const[n,r]of[...Et])r.port===e&&Et.delete(n);e.onmessage=null}function Os(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 Vr(e){e.onmessage=t=>{const n=t.data;if(n.t==="res"){const r=it.get(n.id);if(!r)return;if(it.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),Os("read",s),r.reject(s)}}else if(n.t==="snap"){const r=St.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),Os("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=Et.get(n.subId);r&&r.next(n.events)}else if(n.t==="runtime-reload")for(const r of ur)r(n)}}let at;function Us(e){at=e&&e.mode==="app-session"?void 0:e}function Ad(){return at}let dr;function Id(e){dr=e}function qr(e){return dr&&(e.t==="op"||e.t==="sub")?{...e,issuer:dr}:e}function Wr(e,t){return dt.has(e)?Promise.reject(za()):new Promise((n,r)=>{const s=t;it.set(s.id,{port:e,resolve:n,reject:r}),e.postMessage(t)})}function W(e,t){return Wr(e,qr(t))}function Ka(e,t,n,r){const s=t.id;let i;const a=new Promise((l,c)=>{i=setTimeout(()=>{it.delete(s)&&c(new Error(r))},n)});return Promise.race([W(e,t),a]).finally(()=>{i&&clearTimeout(i)})}function de(e,t){if(dt.has(e)&&!t.method.startsWith("rtdb."))return Promise.reject(new lt("failed-precondition","The client has already been terminated."));const n=at?{...t,actAs:at}:t;return W(e,n)}async function Dd(e,t,n={}){const r=n.timeoutMs??12e3;await Ka(e.port,{t:"op",id:T(),method:"retireRuntime",targetEpoch:t},r,`Timed out waiting for the Pyric worker to retire after ${r}ms.`)}function Pd(e){return Cd(t=>e(t.epoch))}function $d(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 Vr(s),s.start(),{__kind:"client-db",port:s}}async function Od(e,t={}){const n=T(),r=t.timeoutMs??2e3;return(await Ka(e.port,{t:"op",id:n,method:"getRuntimeEpoch"},r,`Timed out waiting for the Pyric SharedWorker version handshake after ${r}ms.`)).version}async function Ud(e){return(await W(e.port,{t:"op",id:T(),method:"getVersion"})).instanceId??""}async function Td(e){return(await W(e.port,{t:"op",id:T(),method:"exportState"})).bundle}async function Md(e,t){await W(e.port,{t:"op",id:T(),method:"importState",bundle:t})}async function Bd(e,t){await W(e.port,{t:"op",id:T(),method:"saveBranch",name:t})}async function Ld(e){return(await W(e.port,{t:"op",id:T(),method:"listBranches"})).branches??[]}async function Fd(e,t){await W(e.port,{t:"op",id:T(),method:"switchBranch",name:t})}async function Vd(e,t){await W(e.port,{t:"op",id:T(),method:"deleteBranch",name:t})}async function qd(e,t,n){return await W(e.port,{t:"tool",id:T(),name:t,args:n})}function Wd(e,t){return Wr(e.port,{...t,issuer:void 0,relaySource:"remote",t:"op",id:T()})}function zd(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=ut();return Dt(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"}})),()=>{Pt(e.port,r)}}function Kd(e){const t=(e??"/").split("/").filter(Boolean).join("/");return t?`/${t}`:"/"}const Hd=[];function Gd(e){for(const t of[...Hd])t.port===e&&t.close()}const Jd=5e3;function Yd(){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 Xd(e,t={}){let n;try{const r=Wr(e.port,{t:"disconnect",id:T()}),s=new Promise((i,a)=>{n=setTimeout(()=>a(Yd()),t.ackTimeoutMs??Jd)});await Promise.race([r,s])}finally{n!==void 0&&clearTimeout(n),Gd(e.port),Rd(e.port),e.port.close()}}function zr(e){return e.split("/").at(-1)??e}function Qd(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:zr(r),path:r}}function Zd(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:zr(r),path:r}}function ef(e){return{_descriptor:{kind:"limit",n:e}}}function tf(...e){return{_descriptor:{kind:"startAfter",values:e}}}function nf(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 rf(e){return oc(JSON.parse(e.json))}const Ha=8*1024*1024;function sf(e,t){const n=new Error(`${t} is ${e} bytes — over the ${Ha/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 af(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 of(e){return rf(e)}function Kr(e,t){const n=e.exists&&e.data?of(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 Ga(e,t){const n=e.docs.map(r=>Kr(r,t));return{size:n.length,empty:n.length===0,docs:n}}async function lf(e){const t=await de(e.port,{t:"op",id:T(),method:"getDoc",path:e.descriptor.path});return Kr(t,e.port)}async function cf(e){const t=await de(e.port,{t:"op",id:T(),method:"getDocs",source:(e.__kind==="coll-ref",e.descriptor)});return Ga(t,e.port)}async function uf(e){return(await de(e.port,{t:"op",id:T(),method:"listRootCollections"})).ids}async function df(e,t){return(await de(e.port,{t:"op",id:T(),method:"listSubcollections",docPath:t})).ids}function ff(e,t,n){const r=ut(),s=e.port,i={port:s,service:"firestore",next:c=>{const u=c;"docs"in u?t(Ga(u,s)):t(Kr(u,s))},error:n},a=(e.__kind==="doc-ref"||e.__kind==="coll-ref",e.descriptor);return!Dt(s,r,i,qr(at?{t:"sub",subId:r,target:a,actAs:at}:{t:"sub",subId:r,target:a}))&&n&&queueMicrotask(()=>n(new Error("Firebase App was deleted"))),()=>{Pt(s,r)}}async function hf(e,t,n){await de(e.port,{t:"op",id:T(),method:"setDoc",path:e.descriptor.path,data:t,options:n})}async function pf(e){await de(e.port,{t:"op",id:T(),method:"deleteDoc",path:e.descriptor.path})}async function mf(e,t){const n=await de(e.port,{t:"op",id:T(),method:"addDoc",collectionPath:e.descriptor.path,data:t});return{__kind:"doc-ref",descriptor:{__ref:"doc",path:n.path},port:e.port,id:n.id,path:n.path}}async function yf(e,t){return await W(e.port,{t:"op",id:T(),method:"admin.listDocuments",path:t})}function bf(e,t){const n=ut(),r=e.port;return Nd(r,n,t,{t:"sub",subId:n,target:"events"}),()=>{Pt(r,n)}}async function gf(e){return await W(e.port,{t:"op",id:T(),method:"getSnapshot"})}async function vf(e){return await W(e.port,{t:"op",id:T(),method:"resetAll"})??{errors:[]}}const wf=15e3;function xf(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`page-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function Ts(){return typeof location>"u"?"/":`${location.pathname}${location.search}${location.hash}`}function Ms(){return typeof document>"u"?"visible":document.visibilityState==="hidden"?"hidden":"visible"}function jf(e){const{db:t,kind:n}=e,r=e.clientId??xf(),s=e.heartbeatIntervalMs??wf;let i=!1,a=null;const l=()=>{W(t.port,{t:"op",id:T(),method:"presence.register",clientId:r,kind:n,route:Ts(),visibility:Ms()}).catch(()=>{})},c=()=>{W(t.port,{t:"op",id:T(),method:"presence.heartbeat",clientId:r}).catch(()=>{})},u=()=>{W(t.port,{t:"op",id:T(),method:"presence.update",clientId:r,route:Ts(),visibility:Ms()}).catch(()=>{})},d=()=>{W(t.port,{t:"op",id:T(),method:"presence.disconnect",clientId:r}).catch(()=>{})};l(),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||c()},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 kf(e,t){const n=ut();return Dt(e.port,n,{port:e.port,next:r=>{t(r)}},{t:"sub",subId:n,target:"presence"}),()=>{Pt(e.port,n)}}const _f=Symbol("pyric.clientUser.port");function Sf(e,t){const n={uid:t.uid,email:t.email,emailVerified:t.emailVerified,displayName:t.displayName,photoURL:t.photoURL,phoneNumber:t.phoneNumber,isAnonymous:t.isAnonymous,providerId:t.providerId,providerData:t.providerData,async getIdToken(r){return await W(e,{t:"op",id:T(),method:"auth.getIdToken",forceRefresh:r})},async getIdTokenResult(r){return await W(e,{t:"op",id:T(),method:"auth.getIdTokenResult",forceRefresh:r})}};return Object.defineProperty(n,_f,{value:e,enumerable:!1}),n}function Ef(e,t){return t?Sf(e,t):null}function Cf(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(),Vr(n)}const r={__kind:"client-auth",port:n,currentUser:null},s=ut();return Dt(n,s,{port:n,next:i=>{r.currentUser=Ef(n,i)}},{t:"sub",subId:s,target:"authState"}),r}async function Nf(e){return await W(e.port,{t:"op",id:T(),method:"auth.listUsers"})}async function Rf(e,t){return await W(e.port,{t:"op",id:T(),method:"auth.adminCreateUser",request:t})}async function Af(e,t,n){return await W(e.port,{t:"op",id:T(),method:"auth.adminUpdateUser",uid:t,request:n})}async function If(e,t){await W(e.port,{t:"op",id:T(),method:"auth.adminDeleteUser",uid:t})}async function Df(e){await W(e.port,{t:"op",id:T(),method:"auth.adminClearUsers"})}async function Pf(e){return await W(e.port,{t:"op",id:T(),method:"auth.getProviderConfig"})}async function $f(e,t,n){await W(e.port,{t:"op",id:T(),method:"auth.setProviderConfig",providerId:t,enabled:n})}const fr="pyric-storage";function Of(e){return e?`${fr}:${e}`:fr}const Uf=1,me="blobs",ie="metadata";function Tf(e=fr){return Bf(e).then(t=>new Mf(t))}class Mf{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 Mt(s)}async getBlob(t){const n=this.db.transaction(me,"readonly");return Bn(n.objectStore(me).get(t))}async getMetadata(t){const n=this.db.transaction(ie,"readonly");return Bn(n.objectStore(ie).get(t))}async putMetadata(t,n){const r=this.db.transaction(ie,"readwrite");r.objectStore(ie).put(n,t),await Mt(r)}async delete(t){const n=this.db.transaction([me,ie],"readwrite");n.objectStore(me).delete(t),n.objectStore(ie).delete(t),await Mt(n)}async listByPrefix(t){const n=this.db.transaction(ie,"readonly"),r=IDBKeyRange.bound(t,t+"",!1,!1);return Bn(n.objectStore(ie).getAll(r))}async reset(){const t=this.db.transaction([me,ie],"readwrite");t.objectStore(me).clear(),t.objectStore(ie).clear(),await Mt(t)}close(){this.db.close()}}function Bf(e){return new Promise((t,n)=>{const r=indexedDB.open(e,Uf);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 Bn(e){return new Promise((t,n)=>{e.addEventListener("success",()=>t(e.result)),e.addEventListener("error",()=>n(e.error))})}function Mt(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 Bs(e){switch(e){case"read":return["get","list"];case"write":return["create","update","delete"];default:return[e]}}const Lf=new Set(["&&","||","==","!=","<",">","<=",">=","+","-","*","/","%"]);function Ja(e){return{segments:e.path.segments.map(Ff),children:e.children.map(Ja),allows:e.allows.map(t=>({verbs:t.operations,condition:H(t.condition)})),functions:e.functions.map(hr)}}function Ff(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 hr(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(!Lf.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 pr(e){const t=lc(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:[Ja(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(hr),...(n.service.functions??[]).map(hr)]};return Ya(r,new Map),{_root:r,_version:n.version}}function Ya(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)Ya(r,n)}function Q(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 Q(e.target,t);case"index":return Q(e.target,t)||Q(e.index,t);case"slice":return[e.target,e.start,e.end].some(n=>Q(n,t));case"unary":return Q(e.arg,t);case"ternary":return[e.cond,e.then,e.else].some(n=>Q(n,t));case"in":return Q(e.element,t)||Q(e.collection,t);case"is":return Q(e.value,t);case"list":return e.elements.some(n=>Q(n,t));case"map":return e.entries.some(({key:n,value:r})=>Q(n,t)||Q(r,t));case"binary":return Q(e.left,t)||Q(e.right,t);case"call":return e.args.some(n=>Q(n,t));case"methodcall":return Q(e.target,t)||e.args.some(n=>Q(n,t));case"path":return e.segments.some(n=>n.kind==="interp"&&Q(n.expr,t));case"ident":case"literal":return!1}}function Xa(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&&Q(r,n)))return!0;for(const r of e.functions){const s=new Set([...n,...r.params]);for(const i of r.lets){if(Q(i.value,s))return!0;s.add(i.name)}if(Q(r.body,s))return!0}return e.children.some(r=>Xa(r,n))}function Vf(e,t,n,r,s){const i=new Set;for(const a of r)a.startsWith("storage-rules#")&&i.add(a);return Xa(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 qf="pyric-default",wn=Symbol("pyric/storage/target");function qe(e){return e.currentAuth?.()??e.context.auth}class Wf{backend;rules;constructor(t,n=null){this.backend=t,this.rules=n}}const Ls=new WeakMap,Fs=new WeakMap,zf=new WeakMap;function Kf(e,t,n){const r=Ls.get(e);if(r){const l=Fs.get(e)??null;if(t.rules!==void 0&&t.rules!==l)throw new Error(`pyric/storage: ${n} received a rules source, but this sandbox's storage service is already open ${l===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 l=t.rules,c=[],u=[],d=[];if(s=pr(l),s._version==="2+modules"){const p=oa(l);if(!p.success)throw new SyntaxError(`Storage rules module resolution failed (${p.error.code}): ${p.error.message}`);l=p.data.resolved,c=p.data.modules,u=p.data.bundledModules,d=p.data.evidenceIds,s=pr(l)}i=Vf(l,c,u,d,s)}const a=Tf(t.dbName??Of(t.projectId)).then(l=>new Wf(l,s));return Ls.set(e,a),Fs.set(e,t.rules??null),zf.set(e,i),e.registerPersistableService("storage",{snapshot:()=>null,restore:()=>{},reset:async()=>{await(await a).backend.reset()}}),a}function Ln(e){return e instanceof uc}const Vs=new WeakMap,qs=new WeakMap;function Hf(e,t={}){const n=!Ln(e),r=Ln(e)?e.sandbox:e,s=Kf(r,t,"getAdminStorageSandbox");if(n){const d=qs.get(r);if(d)return d}const i=Ln(e)?e:r.withAuth(null),a=i.operationContext.authLens.mode==="admin"?i:ha(i,{source:i.operationContext.source,authLens:{mode:"admin"},...i.operationContext.planId===void 0?{}:{planId:i.operationContext.planId}}),l=Vs.get(i);if(l)return l;const c={kind:"sandbox",sandbox:r,context:a,bucket:t.bucket??qf,servicePromise:s,admin:!0},u=Object.freeze({[wn]:c});return Vs.set(i,u),n&&qs.set(r,u),u}function ft(e,t){const n=cc(t,ys(e.context.operationContext));return{...t,...ys(n),service:"storage"}}function _e(e){const t=e[wn];if(!t)throw new TypeError("pyric/storage: not a FirebaseStorage handle — was it produced by getStorageSandbox?");return t}function $t(e){return _e(e).servicePromise}class M extends Error{}class ee{message;constructor(t){this.message=t}}function z(e){return e instanceof ee}function Ie(e){if(typeof e=="number")return e;if(e instanceof ke)return e.value}function De(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function nt(e,t){if(e===t)return!0;if(e==null||t==null)return e==null&&t==null;const n=Ie(e),r=Ie(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)=>nt(s,t[i]));if(De(e)&&De(t)){const s=Object.keys(e),i=Object.keys(t);return s.length===i.length&&s.every(a=>Object.prototype.hasOwnProperty.call(t,a)&&nt(e[a],t[a]))}return!1}function ae(e){return e===null?"null":e===void 0?"undefined":e instanceof ke?"float":typeof e}function Gf(e,t){if(e.target.kind==="ident"&&e.target.name==="timestamp"&&!(e.target.name in t.locals)&&!(e.target.name in t.params))return Qf(e,t);if(e.target.kind==="ident"&&e.target.name==="duration"&&!(e.target.name in t.locals)&&!(e.target.name in t.params))return Xf(e,t);if(e.target.kind==="ident"&&e.target.name==="firestore"&&!(e.target.name in t.locals)&&!(e.target.name in t.params))return Jf(e,t);if(e.method==="matches")return Zf(e,t);if(e.method==="split")return eh(e,t);if(e.method==="size")return th(e,t);if(e.method==="keys")return nh(e,t);if(e.method==="hasAll")return rh(e,t);if(e.method==="get")return sh(e,t);throw new M(`unsupported method .${e.method}()`)}function Jf(e,t){if(e.method!=="get"&&e.method!=="exists")throw new M(`unsupported method firestore.${e.method}()`);if(!t.firestoreLookup)throw new M(`firestore.${e.method}() is unsupported here — no Firestore lookup capability is configured`);if(e.args.length!==1)throw new M(`firestore.${e.method}() expects a single path argument`);const n=e.args[0];if(n.kind!=="path")throw new M(`firestore.${e.method}() requires a /databases/.../documents/... path literal`);const r=Yf(n,t);if(!t.firestoreAccesses.has(r)){if(t.firestoreAccesses.size>=2)throw new M("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 Yf(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 M(`Firestore path interpolation resolved to ${ae(i)} (expected a string)`)});if(n.length<4||n[0]!=="databases"||n[2]!=="documents")throw new M(`malformed Firestore path — expected /databases/<db>/documents/... , got /${n.join("/")}`);if(n[1]!=="(default)")throw new M(`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 M(`Firestore path does not point at a document (needs an even segment count): ${r.join("/")}`);return r.join("/")}const Ws={w:10080*60*1e3,d:1440*60*1e3,h:3600*1e3,m:60*1e3,s:1e3,ms:1,ns:1e-6};function Xf(e,t){if(e.method!=="value")throw new M(`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 M("duration.value() expects (magnitude: number, unit: string)");const[r,s]=n,i=Ws[s];if(i===void 0)throw new M(`duration.value() got unknown unit "${s}" — expected one of ${Object.keys(Ws).join(", ")}`);return r*i}function Qf(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 M("timestamp.value() expects (epochMillis: number)");return n[0]}if(e.method==="date"){if(n.length!==3||!n.every(a=>typeof a=="number"))throw new M("timestamp.date() expects (year, month, day) numbers");const[r,s,i]=n;return Date.UTC(r,s-1,i)}throw new M(`unsupported timestamp.${e.method}()`)}function Zf(e,t){const n=B(e.target,t);if(z(n))return n;if(typeof n!="string")throw new M(`matches() requires a string target, got ${ae(n)}`);if(e.args.length!==1)throw new M("matches() expects a single pattern argument");const r=B(e.args[0],t);if(typeof r!="string")throw new M("matches() pattern must be a string");const s=/\\[1-9]/.test(r),i=/\(\?<?[=!]/.test(r);if(s||i)throw new M(`matches() pattern uses an RE2-unsupported construct (${s?"backreference":"lookaround"}) that production would reject`);let a;try{a=new RegExp(`^(?:${r})$`)}catch(l){throw new M(`matches() invalid regex pattern: ${l.message}`)}return a.test(n)}function eh(e,t){const n=B(e.target,t);if(z(n))return n;if(typeof n!="string")throw new M(`split() requires a string target, got ${ae(n)}`);if(e.args.length!==1)throw new M("split() expects a single pattern argument");const r=B(e.args[0],t);if(typeof r!="string")throw new M("split() pattern must be a string");const s=/\\[1-9]/.test(r),i=/\(\?<?[=!]/.test(r);if(s||i)throw new M(`split() pattern uses an RE2-unsupported construct (${s?"backreference":"lookaround"}) that production would reject`);let a;try{a=new RegExp(r)}catch(l){throw new M(`split() invalid regex pattern: ${l.message}`)}return n.split(a)}function th(e,t){const n=B(e.target,t);if(z(n))return n;if(e.args.length!==0)throw new M("size() expects no arguments");if(typeof n=="string"||Array.isArray(n))return n.length;if(De(n))return Object.keys(n).length;throw new M(`size() requires a string, list, or map target, got ${ae(n)}`)}function nh(e,t){const n=B(e.target,t);if(z(n))return n;if(e.args.length!==0)throw new M("keys() expects no arguments");if(!De(n))throw new M(`keys() requires a map target, got ${ae(n)}`);return Object.keys(n)}function rh(e,t){const n=B(e.target,t);if(z(n))return n;if(!Array.isArray(n))throw new M(`hasAll() requires a list or set target, got ${ae(n)}`);if(e.args.length!==1)throw new M("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 M("hasAll() argument must be a list or set");return r.every(s=>n.some(i=>nt(i,s)))}function sh(e,t){const n=B(e.target,t);if(z(n))return n;if(!De(n))throw new M(`get() requires a map target, got ${ae(n)}`);if(e.args.length!==2)throw new M("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 M("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 ih(e){return e.split("/").filter(t=>t.length>0)}function Fn(e){return"/"+e.map(t=>t.kind==="literal"?t.value:t.kind==="param"?`{${t.name}}`:`{${t.name}=**}`).join("/")}function ah(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 Qa(e,t,n=new Date,r){const s=n.getTime(),i=ih(t.request.path),a=[],l=new Set,c=new Set(Bs(t.request.method));function u(p,f,m){const y=ah(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(Bs));if(![...c].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:l}):!0;if(z(j)){a.push(`match ${Fn(p.segments)} ${t.request.method}: ${j.message}`);continue}k=Xe(j)}catch(j){if(j instanceof M){a.push(`match ${Fn(p.segments)} ${t.request.method}: ${j.message}`);continue}throw j}if(k)return!0;a.push(`match ${Fn(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 zs(e,t){if(!De(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 Xe(e){return z(e)?!1:e!==!1&&e!==null&&e!==void 0&&!(typeof e=="number"&&Number.isNaN(e))}const Ks=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"?uh(t.input,t.now):e.name==="resource"?t.input.resource===null?new ee("Null value error."):ch(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."):zs(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:zs(n,String(r))}case"call":return oh(e,t);case"methodcall":return Gf(e,t);case"path":throw new M("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:!Xe(n)}case"ternary":{const n=B(e.cond,t);return z(n)?n:Xe(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=>nt(s,n)):De(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:lh(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:Xe(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 Xe(i)?i:s}return Xe(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 nt(n,r);case"!=":return!nt(n,r);case"<":return Bt(n,r)<0;case">":return Bt(n,r)>0;case"<=":return Bt(n,r)<=0;case">=":return Bt(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 Qe(n)||Qe(r)?Ue(n,r,(s,i)=>s/i):Ie(r)===0?new ee("Division by zero."):Ue(n,r,(s,i)=>Math.trunc(s/i));case"%":return Qe(n)||Qe(r)?Ue(n,r,(s,i)=>s%i):Ie(r)===0?new ee("Modulo by zero."):Ue(n,r,(s,i)=>s%i)}}}}function oh(e,t){const n=t.funcs.get(e.name);if(!n)throw new M(`undefined function ${e.name}()`);if(n.unresolvedImport!==void 0)throw new M(`function ${e.name}() is imported from '${n.unresolvedImport}', but import module resolution is not implemented`);if(n.params.length!==e.args.length)throw new M(`function ${e.name}() expects ${n.params.length} argument(s), got ${e.args.length}`);const r=t.depth+1;if(r>Ks)throw new M(`function ${e.name}() exceeded max call depth ${Ks}`);const s=e.args.map(l=>B(l,t)),i={};n.params.forEach((l,c)=>{i[l]=s[c]});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 l of n.lets)i[l.name]=B(l.value,a);return B(n.body,a)}function lh(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 De(e);default:return new ee(`'is ${t}' is not supported by the storage evaluator.`)}}function Qe(e){return e instanceof ke}function Bt(e,t){const n=Ie(e),r=Ie(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=Ie(e),s=Ie(t);if(r===void 0||s===void 0)return;const i=n(r,s);return Qe(e)||Qe(t)?new ke(i):i}function ch(e){return{size:e.size,contentType:e.contentType,metadata:e.metadata,name:e.name,bucket:e.bucket,generation:e.generation,metageneration:e.metageneration,timeCreated:Hs(e.timeCreated),updated:Hs(e.updated)}}function Hs(e){if(e===void 0)return;const t=Date.parse(e);return Number.isNaN(t)?void 0:t}function uh(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 dh(e){return`storage/${e}`}class ht extends Error{code;constructor(t,n){const r=dh(t);super(`${r}: ${n}`),this.name="StorageError",this.code=r,Object.setPrototypeOf(this,ht.prototype)}}function Za(e){return new ht("object-not-found",`no object at "${e}".`)}function fh(e,t,n){return new ht("unauthorized",`${e} "${t}" denied by rules${n}.`)}function xn(e){return new ht("invalid-root-operation",`${e} cannot operate on the root reference.`)}function hh(){return new ht("canceled","User canceled the upload/download.")}function Ot(e,t,n,r){const s=n?.kind==="sandbox"?ft(n,r):r;if(n?.kind==="sandbox"&&n.admin===!0){Lt(n,t,"not-applicable",void 0,"admin",!1,s);return}if(!e.rules){Lt(n,t,"allow",void 0,"user",!1,s);return}const i=n?ph(t,n.bucket):t,a=Qa(e.rules,i,void 0,mh(n));if(!a.allowed){Lt(n,t,"deny",a.reasons,"user",!0,s);const l=a.reasons.length>0?` — ${a.reasons.join("; ")}`:"";throw fh(t.request.method,t.request.path,l)}Lt(n,t,"allow",a.reasons,"user",!0,s)}function ph(e,t){const n=e.request.path.replace(/^\/+/,"");return{...e,request:{...e.request,path:n===""?`b/${t}/o`:`b/${t}/o/${n}`}}}function Lt(e,t,n,r,s,i,a){if(e)try{Re(e.sandbox,la({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 mh(e){if(!e)return;const t=e.sandbox.admin;return{get:n=>t.getDocument(n),exists:n=>t.getDocument(n)!==null}}function jn(e){return e?{size:e.size,contentType:e.contentType,metadata:e.customMetadata,name:yh(e.fullPath,e.bucket),bucket:e.bucket,timeCreated:e.timeCreated,updated:e.updated,generation:Gs(e.generation),metageneration:Gs(e.metageneration)}:null}function yh(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 Gs(e){if(e===void 0)return;const t=Number(e);return Number.isFinite(t)?t:void 0}function bh(e){return{size:e.size,contentType:e.contentType,metadata:e.customMetadata}}function Hr(e){return{...e}}async function gh(e){vh(e,"getMetadata");const t=_e(e.storage),n=ft(t),r=await $t(e.storage),s=await r.backend.getMetadata(e.fullPath);if(Ot(r,{request:{auth:qe(t),method:"get",path:e.fullPath},resource:jn(s)},t,n),!s)throw Za(e.fullPath);return Hr(s)}function vh(e,t){if(e.fullPath==="")throw xn(t)}const wh="application/octet-stream";async function eo(e,t,n,r){kh(e,"uploadBytes");const s=_e(e.storage),i=ft(s,r),a=xh(t,n?.contentType),l=to({ref:e,blob:a,settable:n}),c=await $t(e.storage),u=await c.backend.getMetadata(e.fullPath);Ot(c,{request:{auth:qe(s),method:u?"update":"create",path:e.fullPath,resource:bh({size:l.size,contentType:l.contentType,customMetadata:l.customMetadata})},resource:jn(u)},s,i),await c.backend.put(e.fullPath,a,l);try{Re(s.sandbox,yn({service:"storage",op:"object_put",path:e.fullPath,auth:qe(s),before:u??void 0,after:l,detail:{bucket:e.bucket,size:l.size,contentType:l.contentType,overwrite:u!=null}}),i)}catch{}return{ref:e,metadata:Hr(l)}}function to(e){const{ref:t,blob:n,settable:r}=e,s=(e.now??new Date).toISOString(),i=jh(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||wh,cacheControl:r?.cacheControl,contentDisposition:r?.contentDisposition,contentEncoding:r?.contentEncoding,contentLanguage:r?.contentLanguage,customMetadata:r?.customMetadata}}function xh(e,t){return e instanceof Blob?t&&t!==e.type?new Blob([e],{type:t}):e:new Blob([e],{type:t??""})}function jh(e){return String(e.getTime())}function kh(e,t){if(e.fullPath==="")throw xn(t)}function _h(e){return e instanceof Blob?e.size:e.byteLength}function Sh(){const e=new Error("storage/canceled: User canceled the upload/download.");return e.code="storage/canceled",e}function Eh(){const e=new Error("storage/invalid-root-operation: uploadBytesResumable cannot operate on root reference.");return e.code="storage/invalid-root-operation",e}class Ch{[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=_h(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=Sh(),this._updateSnapshot("canceled",this._snapshot.bytesTransferred),this._notifyObservers("error"),this._reject(this._error),!0):!1}on(t,n,r,s){let i,a,l,c=!1;if(typeof n=="object"&&n!==null&&(c=!0),c){const f=n;f.next!==void 0&&(i=f.next),f.error!==void 0&&(a=f.error),f.complete!==void 0&&(l=f.complete)}else typeof n=="function"&&(i=n),typeof r=="function"&&(a=r),typeof s=="function"&&(l=s);const d={next:i,error:a,complete:l};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(l!==void 0){const v=l;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 l=i.next;try{l(this._snapshot)}catch{}}}if(t==="error"){for(const i of this._observers)if(i.error!==void 0&&this._error!==void 0){const c=i.error,u=this._error;try{c(u)}catch{}}}if(t==="complete"){for(const i of this._observers)if(i.complete!==void 0){const l=i.complete;try{l()}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 no(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 ro(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 Nh(e,t,n){if(e.fullPath==="")throw Eh();return new Ch(e,t,n)}class Ct{__kind="storage-ref";port;storage;bucket;fullPath;name;constructor(t,n,r,s){this.port=t,this.bucket=n,this.fullPath=r,this.name=zr(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 Ct(this.port,this.bucket,n,this.storage)}get root(){return this.fullPath===""?this:new Ct(this.port,this.bucket,"",this.storage)}toString(){return`gs://${this.bucket}/${this.fullPath}`}}function Rh(e){return e.replace(/^\/+|\/+$/g,"")}function Ah(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(),Vr(r)}return{__kind:"client-storage",port:r,bucket:n??"pyric-default"}}function Ih(e,t){const n=Rh(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 l=e.fullPath;r=n?l?`${l}/${n}`:n:l,s=e.port,i=e.bucket,a=e.storage}return new Ct(s,i,r,a)}async function Dh(e){const t=await de(e.port,{t:"op",id:T(),method:"storage.listAll",path:e.fullPath}),n=r=>new Ct(e.port,e.bucket,r.fullPath,e.storage);return{items:t.items.map(n),prefixes:t.prefixes.map(n)}}async function Ph(e){return await de(e.port,{t:"op",id:T(),method:"storage.getMetadata",path:e.fullPath})}async function $h(e){return await de(e.port,{t:"op",id:T(),method:"storage.getBlob",path:e.fullPath})}async function no(e,t,n){const r=t instanceof Blob?new Uint8Array(await t.arrayBuffer()):t instanceof ArrayBuffer?new Uint8Array(t):t;if(r.byteLength>Ha)throw sf(r.byteLength,`uploadBytes payload for '${e.fullPath}'`);const s=n?.contentType??(t instanceof Blob&&t.type?t.type:void 0),i=await de(e.port,{t:"op",id:T(),method:"storage.putBytes",path:e.fullPath,dataB64:af(r),...s!==void 0?{contentType:s}:{},...n!==void 0?{metadata:n}:{}});return{ref:e,metadata:i}}async function ro(e){await de(e.port,{t:"op",id:T(),method:"storage.deleteObject",path:e.fullPath})}new Array(12).fill(0);async function Oh(e){return W(e.port,{t:"op",id:T(),method:"rtdb.adminSnapshot"})}async function Uh(e,t,n){await W(e.port,{t:"op",id:T(),method:"rtdb.set",path:t,value:n,actAs:{mode:"admin"}})}async function Th(e,t,n){await W(e.port,{t:"op",id:T(),method:"rtdb.update",path:t,values:n,actAs:{mode:"admin"}})}async function Mh(e,t){await W(e.port,{t:"op",id:T(),method:"rtdb.remove",path:t,actAs:{mode:"admin"}})}function Bh(e,t,n,r){const s=ut();return!Dt(e.port,s,{port:e.port,next:a=>n(a?.value??null),error:r},qr({t:"sub",subId:s,target:{service:"rtdb",path:Kd(t)},actAs:{mode:"admin"}}))&&r&&queueMicrotask(()=>r(new Error("FIREBASE FATAL ERROR: Database has been deleted."))),()=>Pt(e.port,s)}function Lh(e){const t=new Set;let n={servedEpoch:e.servedEpoch,runningEpoch:null,updateAvailable:!1,updating:!1,error:null};const r=c=>{n={...n,...c};for(const u of t)u()},s=e.storage,i=e.servedEpoch;let a=null;const l=()=>i?(a??=yd({targetEpoch:i,retire:()=>e.retire?e.retire(i):Dd(e.db,i),subscribeReload:e.subscribeReload??Pd,preflight:e.preflight??(()=>md(s)),commitGeneration:e.remember??(c=>pd(c,s)),onPreparationError:c=>r({updating:!1,error:c instanceof Error?c.message:String(c)}),reload:e.reload??(()=>window.location.reload()),...e.schedule?{schedule:e.schedule}:{}}),a):null;return(e.readVersion??(()=>Od(e.db)))().then(c=>r({runningEpoch:c,updateAvailable:!!(i&&c!=="dev"&&c!==i)})).catch(c=>r({error:c instanceof Error?c.message:String(c)})),{getSnapshot:()=>n,subscribe(c){return t.add(c),l(),()=>{t.delete(c),t.size===0&&(a?.dispose(),a=null)}},async update(){const c=l();if(!c||!n.updateAvailable||n.updating)throw new Error("No Pyric worker update is available.");r({updating:!0,error:null});try{await c.request()}catch(u){throw r({updating:!1,error:u instanceof Error?u.message:String(u)}),u}},dispose(){t.clear(),a?.dispose(),a=null}}}function Fh(e={}){const t=qa(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:hd(t.worker.servedEpoch,n)}}const Vh="/__pyric/sdk/worker.js";function qh(e){let t=[],n=!1;const r=new Set;let s=null;function i(){s||(s=bf(e,a=>{const l=!n;n=!0;const c=l?[]:[...t];for(const u of a)La(u)&&(c.length=0),c.push(u);t=c;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 Wh(e=Vh){if(typeof SharedWorker>"u")return null;Id("studio");let t;try{const c=Fh({workerUrl:e});t=$d(c.url,c.name)}catch{return null}let n;try{n=typeof localStorage>"u"?void 0:localStorage}catch{n=void 0}const r=Lh({db:t,servedEpoch:qa(typeof document>"u"?void 0:document).worker.servedEpoch,storage:n});Us({mode:"admin"});const s=jf({db:t,kind:"studio"}),i=qh(t),a=Cf(t);let l=!1;return{db:t,runtime:r,dispose:async()=>{l||(l=!0,s.stop(),r.dispose(),await Xd(t).catch(()=>{}))},presenceClientId:s.clientId,subscribePresence:c=>kf(t,c),instanceId:()=>Ud(t),exportState:()=>Td(t),importState:c=>Md(t,c),saveBranch:c=>Bd(t,c),listBranches:()=>Ld(t),switchBranch:c=>Fd(t,c),deleteBranch:c=>Vd(t,c),feed:i,setLens:c=>Us(c),getLens:()=>Ad(),listRootCollections:()=>uf(t),listSubcollections:c=>df(t,c),listDocuments:async c=>(await yf(t,c)).map(({path:u,phantom:d})=>({path:u,phantom:d})),readRtdbState:()=>Oh(t),setRtdbValue:(c,u)=>Uh(t,c,u),updateRtdbValue:(c,u)=>Th(t,c,u),deleteRtdbValue:c=>Mh(t,c),subscribeRtdbValue:(c,u,d)=>Bh(t,c,u,d),firestoreApi:{collection:Zd,doc:Qd,getDoc:lf,getDocs:cf,onSnapshot:ff,setDoc:hf,deleteDoc:pf,addDoc:mf,query:nf,limit:ef,startAfter:tf},auth:a,authApi:{listUsers:()=>Nf(a),subscribeUsers:(c,u)=>i.subscribe(d=>{d.kind==="service_mutation"&&d.service==="auth"&&u()}),createUser:(c,u)=>Rf(a,u),updateUser:(c,u,d)=>Af(a,u,d),deleteUser:(c,u)=>If(a,u),clearUsers:()=>Df(a),getAuthProviderConfig:()=>Pf(a),setAuthProviderConfig:(c,u,d)=>$f(a,u,d),subscribeAuthProviderConfig:(c,u)=>i.subscribe(d=>{d.kind==="service_mutation"&&d.op==="provider_config_update"&&u()})},storage:Ah(t),storageApi:{ref:Ih,listAll:Dh,getMetadata:Ph,getBlob:$h,uploadBytes:no,uploadBytesResumable:Nh,deleteObject:ro},getSnapshot:()=>gf(t),resetAll:()=>vf(t)}}const Js=5174,Ys="/sandbox",zh=4001,Kh="worker-relay";function Hh(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 mr(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=mr(t);if(n)return n}return null}for(const t of Object.values(e)){const n=mr(t);if(n)return n}return null}function Xs(e,t){const n=mr(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 Qs(e,t){return{code:e.code,severity:t,message:e.message,path:e.path,origin:"validate"}}const ge=e=>e,Zs=(...e)=>ge(e.map(t=>`(${t})`).join(" && ")),Gh=(...e)=>ge(e.map(t=>`(${t})`).join(" || ")),so=e=>e,Jh=()=>so("newData.hasChildren()"),Yh=e=>so(`newData.hasChild("${e}")`);function io(e,t){const n=e.shape,r=[],s={};for(const[l,c]of Object.entries(n)){const u=c,d=u instanceof dc,p=d?u.unwrap():u;d||r.push(l);const f=ao(p,l),m=t?.[l];if(m&&m.length>0?s[l]={validate:Zs(f,...m)}:s[l]={validate:f},p instanceof pa){const y=io(p);s[l]={validate:y.validate,children:y.children}}}const i=[Jh()];for(const l of r)i.push(Yh(l));return{validate:Zs(...i),children:s}}function ao(e,t){if(e instanceof fc)return ge("newData.isString()");if(e instanceof hc)return ge("newData.isNumber()");if(e instanceof pc)return ge("newData.isBoolean()");if(e instanceof mc){const n=e.options;return ge(n.map(r=>`newData.val() === "${r}"`).join(" || "))}if(e instanceof yc){const n=e.value;return ge(typeof n=="string"?`newData.val() === "${n}"`:`newData.val() === ${n}`)}if(e instanceof bc){const n=e._def.options;return Gh(...n.map(r=>ao(r,t)))}if(e instanceof pa)return ge("newData.hasChildren()");throw new Error(`Unsupported Zod type for RTDB rules: ${e.constructor.name} on field "${t}"`)}function Xh(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=oo(t);n.sort((s,i)=>{const a=s[0]==="/"?0:s[0].split("/").filter(Boolean).length,l=i[0]==="/"?0:i[0].split("/").filter(Boolean).length;return a-l||s[0].localeCompare(i[0])});const r={path:"/",pathVariables:[],children:[]};for(const[s]of n)s!=="/"&&Qh(r,s);for(const[s,i]of n){const a=s==="/"?r:Gr(r,s);a&&Zh(r,a,i,s)}return r}function Qh(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(c=>c.startsWith("$"));let l=r.children.find(c=>c.path===i);l||(l={path:i,pathVariables:a,children:[]},r.children.push(l)),r=l}}function Zh(e,t,n,r){const s=r.split("/").filter(i=>i.startsWith("$"));if(n.read&&(t.read=Ge(n.read,"read",s)),n.write&&(t.write=Ge(n.write,"write",s)),n.validate&&(t.validate=Ge(n.validate,"validate",s)),n.schema){const i=io(n.schema,n.fieldConstraints);t.validate||(t.validate=Ge(i.validate,"validate",s));for(const[a,l]of Object.entries(i.children)){const c=`${r}/${a}`;let u=t.children.find(d=>d.path===c);if(u||(u={path:c,pathVariables:s,children:[]},t.children.push(u)),u.validate=Ge(l.validate,"validate",s),"children"in l&&l.children)for(const[d,p]of Object.entries(l.children)){const f=`${c}/${d}`;let m=u.children.find(y=>y.path===f);m||(m={path:f,pathVariables:s,children:[]},u.children.push(m)),m.validate=Ge(p.validate,"validate",s)}}}if(n.indexOn){const i=r.split("/").filter(Boolean);if(i[i.length-1]?.startsWith("$")){const l="/"+i.slice(0,-1).join("/"),c=Gr(e,l);c&&(c.indexOn=n.indexOn)}}}function oo(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(([l,c])=>[n+l,c]);t.push(...oo(a))}}return t}function Ge(e,t,n){return Sa(String(e),t,n)}function Gr(e,t){if(e.path===t)return e;for(const n of e.children){const r=Gr(n,t);if(r)return r}return null}function ep(e){return e==null?null:typeof e=="string"?{uid:e,token:{}}:{uid:e.uid,token:e.token??{}}}function tp(e){return{operation:e.operation,path:e.path,auth:ep(e.auth),mockData:e.mockData??e.data??{},...e.newData!==void 0?{newData:e.newData}:{}}}function Vn(e,t,n,r){return(n?.parsed[r]??[]).map(s=>({path:e,rule:t,code:s.code,message:s.message}))}function yr(e,t){const n=[...Vn(e.path,".read",e.read,t),...Vn(e.path,".write",e.write,t),...Vn(e.path,".validate",e.validate,t)];for(const r of e.children)n.push(...yr(r,t));return n}class np{definition;constructor(t){this.definition=t}compile(){return Xh(this.definition.paths)}toJSON(){return wu(this.compile())}check(){try{const t=this.compile(),n=yr(t,"errors"),r=yr(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 Br(this.compile(),tp(t))}}function rp(e){return new np(e)}function sp(e){const t=e;return typeof t.toJSON=="function"&&typeof t.simulate=="function"&&typeof t.check=="function"}function ip(e){const t=e;return typeof t=="object"&&t!==null&&"rules"in t&&!("paths"in t)&&typeof t.toJSON!="function"}class qn{doc;constructor(t){this.doc=t}lint(){const t=this.doc.check();return[...t.errors.map(n=>Qs(n,"error")),...t.warnings.map(n=>Qs(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 ap(e){return e==null?null:typeof e=="string"?{uid:e,token:{}}:{uid:e.uid,token:e.token??{}}}class op{json;compiled;constructor(t){this.json=t,this.compiled=Ca(t)}toJSON(){return this.json}compile(){return this.compiled}check(){return{ok:!0,errors:[],warnings:[]}}simulate(t){return Br(this.compiled,{operation:t.operation,path:t.path,auth:ap(t.auth),mockData:t.mockData??t.data??{},...t.newData!==void 0?{newData:t.newData}:{}})}}function lp(e){return sp(e)?new qn(e):ip(e)?new qn(new op(e)):new qn(rp(e))}function cp(e,t){return e==="/"?`/${t}`:`${e}/${t}`}function ei(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function up(e){const t=(e??"/").split("/").filter(Boolean);return t.length===0?"/":`/${t.join("/")}`}function dp(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 lo(e,t,n,r,s){if(e===null||typeof e!="object"||Array.isArray(e))return{path:t,childCount:0,truncated:!1,children:[],schema:{},valueType:ei(e)};const i=Object.entries(e).sort(([p],[f])=>p.localeCompare(f)),a={},l=[];for(const[p,f]of i)f!==null&&typeof f=="object"&&!Array.isArray(f)?l.push([p,f]):a[p]=ei(f);const c=n>=r&&l.length>0,u=i.length>s,d=n>=r?[]:l.slice(0,s).map(([p,f])=>lo(f,cp(t,p),n+1,r,s));return{path:t,childCount:i.length,truncated:c||u,children:d,schema:a}}function fp(e,t={}){const n=up(t.path),r=t.maxDepth??10,s=t.maxChildren??100;return lo(dp(e,n),n,0,r,s)}function co(e){return e.children.reduce((t,n)=>t+1+co(n),0)}function uo(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=Aa(r);if(!s)return{ok:!1,summary:"No RTDB rules are loaded in the local sandbox.",data:{code:"NO_ACTIVE_RULES"}};const i=As(r),a=i!==null&&typeof i=="object"&&!Array.isArray(i)?i:{},l={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}:{}},c=lp(s).simulate([l]).cases[0];return{ok:!c.unsupported,summary:c.unsupported?`Simulation unsupported: ${c.reason}`:`Simulation: ${c.decision.toLowerCase()}`,data:{decision:c.decision,allowed:c.decision==="ALLOW",unsupported:c.unsupported,matchedPath:c.matchedPath,matchedRule:c.matchedRule,reason:c.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=fp(As(r),n);return{ok:!0,summary:`Crawled ${co(s)} object paths from ${s.path}`,data:s}}}]}function hp(e){const t=bn(e),n=r=>r&&r!=="admin"?ma(e.withAuth({uid:r.uid,token:r.claims})):ya(e);return[...ja({resolveSandbox:()=>t}),...Ta({resolveDb:n}),...Ma({resolveSandbox:()=>e}),...uo({resolveSandbox:()=>e})]}function pp(e){const t=new Map(hp(e).map(n=>[n.name,n]));return async(n,r)=>{const s=t.get(n);if(!s)throw new bp(n);const i={signal:new AbortController().signal},a=await s.execute(r,i);return{ok:a.ok,summary:a.summary,data:a.data}}}const ti=new WeakMap;async function mp(e,t,n){let r=ti.get(e);return r||(r=pp(e),ti.set(e,r)),r(t,n)}const yp=(()=>{const e=async()=>{throw new Error("SANDBOX_TOOL_NAMES: stub resolver should never be invoked")};return[...ja({resolveSandbox:e}),...Ta({resolveDb:e}),...Ma({resolveSandbox:e}),...uo({resolveSandbox:e})].map(t=>t.name)})();class bp extends Error{tool;constructor(t){super(`unknown sandbox tool: ${t}`),this.tool=t,this.name="UnknownToolError"}}const gp=500,vp=3e4,wp=2e3,xp=.5,jp=3;function kp(e,t={}){const n=_p(t.url),r=t.sandboxId??Sp(),s=t.dispatcher??mp,i=t.toolNames??[...yp],a=t.initialReconnectDelayMs??gp,l=t.maxReconnectDelayMs??vp,c=t.noReconnect??!1,u=t.onStateChange??(()=>{}),d=t.standbyPollMs??wp,p=t.fetchImpl??(A=>fetch(A)),f=t.workerRelay??null;let m=null,y=!1,g=0,v=null,b=null,w=0,x={kind:"connecting"};const k=new Map;function j(){for(const A of k.values())try{A()}catch{}k.clear()}function _(A){x=A;try{u(A)}catch{}}function N(A){if(m&&m.readyState===WebSocket.OPEN)try{m.send(JSON.stringify(A))}catch{}}function P(){if(y)return;_({kind:"connecting"});let A;try{A=new WebSocket(n)}catch(O){G(`failed to open WebSocket: ${O instanceof Error?O.message:String(O)}`);return}m=A,A.onopen=()=>{g=0;const O={type:"hello",protocol:1,tools:i,sandboxId:r,...f?{capabilities:[Kh]}:{}};N(O)},A.onmessage=O=>{let U;try{U=JSON.parse(typeof O.data=="string"?O.data:"")}catch{return}if(Hh(U)){if(U.type==="hello-ack"){_({kind:"connected",bridgeVersion:U.bridgeVersion});return}if(U.type==="tool-call"){I(U);return}if(U.type==="worker-op"){D(U);return}if(U.type==="worker-sub"){C(U);return}if(U.type==="worker-unsub"){const $=k.get(U.subId);if($){k.delete(U.subId);try{$()}catch{}}return}if(U.type==="ping"){N({type:"pong",id:U.id});return}}},A.onclose=O=>{const U=O.reason||`closed (code ${O.code})`;if(m=null,j(),O.code===zh){E();return}G(U)},A.onerror=()=>{}}async function I(A){let O;try{const U=await s(e,A.name,A.args??{});O={type:"tool-result",id:A.id,ok:!0,result:U}}catch(U){O={type:"tool-result",id:A.id,ok:!1,error:{code:U instanceof Error?U.name:"Error",message:U instanceof Error?U.message:String(U)}}}N(O)}async function D(A){if(f)try{const O=await f.op(A.op);Xs(`op '${A.op.method}'`,O),N({type:"worker-res",id:A.id,ok:!0,value:O})}catch(O){const U=O.denialContext;N({type:"worker-res",id:A.id,ok:!1,error:{code:O.code??"unknown",message:O instanceof Error?O.message:String(O),...U!==void 0?{denialContext:U}:{}}})}}function C(A){if(f&&!k.has(A.subId))try{const O=f.subscribe(A.sub,U=>{try{Xs(`subscription '${A.subId}'`,U)}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:U})});k.set(A.subId,O)}catch(O){const U=O.denialContext;N({type:"worker-snap",subId:A.subId,value:{__error:{code:O.code??"unknown",message:O instanceof Error?O.message:String(O),...U!==void 0?{denialContext:U}:{}}}})}}function S(){try{const A=new URL(n);A.protocol=A.protocol==="wss:"?"https:":"http:";const O=A.origin;return[`${O}/__pyric/health`,`${O}/health`]}catch{return[]}}function E(){if(!y){if(c){_({kind:"disconnected",reason:"replaced by a newer sandbox peer"});return}g=0,w=0,_({kind:"standby"}),R()}}function R(){if(y)return;const A=d*(1+Math.random()*xp);b=setTimeout(()=>{b=null,V()},A)}async function V(){if(y)return;let A=null;for(const O of S())try{const U=await p(O);if(!U.ok)continue;const $=await U.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>=jp){G("standby health poll unreachable");return}R()}}function G(A){if(y)return;if(c){_({kind:"disconnected",reason:A});return}g+=1;const O=Math.min(a*2**(g-1),l);_({kind:"reconnecting",attempt:g,delayMs:O}),v=setTimeout(()=>{v=null,P()},O)}return P(),{disconnect(){if(y=!0,j(),v&&(clearTimeout(v),v=null),b&&(clearTimeout(b),b=null),m){try{m.close()}catch{}m=null}_({kind:"disconnected",reason:"client closed"})},state(){return x}}}function _p(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}:${Js}${Ys}`}return`ws://localhost:${Js}${Ys}`}function Sp(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`sb-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function Ep(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,c=i&&a?`${r.hostname}:${n.port}`:r.host;return`${s}//${c}${n.pathname}`}catch{return e}}function Cp(e,t){return{url:t,dispatcher:(n,r,s)=>qd(e,r,s),workerRelay:{op:n=>Wd(e,n),subscribe:(n,r)=>zd(e,n,r)}}}async function Np(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),l=a?Ep(i,a):i,c=kp(null,{...Cp(e,l),...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",l),c}const Rp={};function Ap(){return!1}function Ip(){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 Dp(e,t={}){if(e==="local"){const n=t.baseUrl??"",r=Ap(),s=t.persistence==="memory"||r?gc():od(n),i=t.disableLive?null:Wh(t.workerUrl),a=i?Ip():null;let l=!1,c=null;return i&&a&&Np(i.db,{baseUrl:n,onStateChange:u=>a.set(u)}).then(u=>{l?u?.disconnect():c=u}),{mode:e,projects:r?ud():id(n),persistence:s,...i?{live:i}:{},...a?{bridge:a}:{},dispose(){l=!0,c?.disconnect(),i?.dispose()}}}throw new Error(`createStudioEnvironment(${e}): only 'local' is wired in v1 (T3). 'browser'/'hosted' land in A3.`)}const fo=h.createContext(null),Pp={status:"pending",env:null,error:null};function $p(e){try{return{status:"ready",env:Dp(e),error:null}}catch(t){return{status:"error",env:null,error:t instanceof Error?t:new Error(String(t))}}}function Op({mode:e="local",children:t}){const[n,r]=h.useState(null);h.useEffect(()=>{const i=$p(e);return r({mode:e,state:i}),()=>{i.status==="ready"&&i.env.dispose()}},[e]);const s=n?.mode===e?n.state:Pp;return o.jsx(fo.Provider,{value:s,children:t})}function pe(){const e=h.useContext(fo);if(!e)throw new Error("useEnvironment must be used within an <EnvironmentProvider>");return e}const Up="pyric-studio:theme",Xt="dark";function Tp(){return Xt}function Mp(){typeof document>"u"||document.documentElement.setAttribute("data-theme","dark")}const Bp=h.createContext(null);function Lp({children:e}){const[t,n]=h.useState(Tp);h.useEffect(()=>{Mp();try{localStorage.setItem(Up,Xt)}catch{}},[t]);const r="dark",s=h.useCallback(l=>n(Xt),[]),i=h.useCallback(()=>n(Xt),[]),a=h.useMemo(()=>({choice:t,resolvedTheme:r,setChoice:s,cycleChoice:i}),[t,r,s,i]);return o.jsx(Bp.Provider,{value:a,children:e})}function ho(){const e=typeof import.meta<"u"&&"/__pyric/ui/"||"/";return e.endsWith("/")?e:`${e}/`}function Fp(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 Jr(e,t="",n=ho()){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(c=>decodeURIComponent(c)),[a="",...l]=i;return{tab:a,rest:l,query:Fp(t)}}function Vp(e,t=ho()){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 br="pyric:studio:navigated",qp={tab:"",rest:[],query:{}};function po(){return typeof window<"u"?window.location.pathname+window.location.search:""}function be(){return typeof window>"u"?qp:Jr(window.location.pathname,window.location.search)}function Wp(e){return e.tab==="home"?{...e,tab:""}:e}function kn(e){return Vp(Wp(e))}function mo(){typeof window<"u"&&window.dispatchEvent(new Event(br))}function ce(e){if(typeof window>"u")return;const t=kn(e);po()!==t&&(window.history.pushState(null,"",t),mo())}function ln(e){typeof window>"u"||(window.history.replaceState(null,"",kn(e)),mo())}function Ut(e){return typeof window>"u"?()=>{}:(window.addEventListener("popstate",e),window.addEventListener(br,e),()=>{window.removeEventListener("popstate",e),window.removeEventListener(br,e)})}function zp(e,t){const n=h.useCallback(i=>e.includes(i)?i:t,[e,t]),r=h.useSyncExternalStore(Ut,()=>n(be().tab),()=>t);h.useEffect(()=>{const i=typeof window<"u"?window.location.hash:"";if(i.length>1){const l=i.slice(1),c=l.indexOf("?"),u=Jr(`/${c===-1?l:l.slice(0,c)}`,c===-1?"":l.slice(c),"/");if(e.includes(u.tab)){ln(u);return}}const a=be();a.tab!==""&&!e.includes(a.tab)&&ln({tab:n(a.tab)})},[n]);const s=h.useCallback(i=>{const a=n(i);a!==r&&ce({tab:a})},[n,r]);return[r,s]}let gr=null;function Kp(e){gr=e}function Hp(){return gr?(gr(),!0):!1}function Gp(e){return(e.metaKey||e.ctrlKey)&&!e.altKey&&!e.shiftKey&&(e.key==="k"||e.key==="K")}const Jp=[{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 Yp({assuranceEnabled:e=!1}={}){return Jp.filter(t=>t.id!=="assurance"||e)}const We=Yp({assuranceEnabled:!1}),Xp=We.map(e=>e.id);function Qp(e){return We.find(t=>t.id===e)??We[0]}function Zp(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 em=7;function tm(e,t){const n=e.trim();if(!n)return[];const r=t.filter(p=>p.id!=="settings"),s=[],i=[],a=[],[l="",...c]=n.split(/\s+/),u=c.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):Zp(n,p.label)&&i.push(f),u&&(m===l.toLowerCase()||m.startsWith(l.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,em)}function vr(e){return`${e.kind}:${e.target.tab}:${(e.target.rest??[]).join("/")}`}const wr={docsPerCollection:50,collectionsScanned:20,users:100,objects:200,storageListCalls:20,subcollections:30,subcollectionRpcCalls:40};async function nm(e,t,{maxObjects:n,maxListCalls:r}){const s=[],i=[e];let a=0;for(;i.length&&s.length<n&&a<r;){a++;const l=await t(i.shift());for(const c of l.items){if(s.length>=n)break;s.push(c.fullPath)}i.push(...l.prefixes)}return s}async function rm(e,t,n,{maxSubcollections:r,maxRpcCalls:s,docsPerCollection:i}){const a=[],l=[],c=[...e];let u=0;for(;c.length&&a.length<r&&u<s;){const d=c.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))l.push(g),c.push(g)}catch{}}}return{subcollections:a,documents:l}}const sm=5;function cn(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,l=-1;for(let u=0;u<r.length&&i<n.length;u++)r[u]===n[i]&&(a===-1&&(a=u),l=u,i++);if(i!==n.length)return 0;const c=l-a+1;return Math.max(1,400-(c-n.length)*10-Math.min(a,50))}const im={collection:"Firestore collections",document:"Firestore documents",subcollection:"Firestore subcollections",user:"Auth users",object:"Storage objects","rtdb-key":"RTDB keys"},am=["collection","document","subcollection","user","object","rtdb-key"];function om(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 yo(e){return e.endsWith("/")?{base:e.slice(0,-1),trailing:!0}:{base:e,trailing:!1}}function lm(e,t){const{base:n,trailing:r}=yo(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 l=0;l<a;l++)if(s[l].toLowerCase()!==i[l].toLowerCase())return 0;return r?s[a].toLowerCase()===i[a].toLowerCase()?850:0:cn(s[a],i[a])}function cm(e,t){const{base:n,trailing:r}=yo(e);if(!n||n.includes("/"))return 0;const s=t.split("/").pop()??t;return r?s.toLowerCase()===n.toLowerCase()?850:0:cn(n,s)}function ni(e,t,n,r=sm){const s=e.trim();if(!s)return[];const i=[],a=tm(e,t);a.length&&i.push({kind:"navigate",title:"Go to",results:a});for(const l of am){const c=l==="document"||l==="subcollection",u=l==="collection"||l==="subcollection",d=new Map;for(const f of n)f.kind===l&&d.set(vr(f),f);const p=[...d.values()].map(f=>({entry:f,score:Math.max(cn(s,f.label),f.alt?cn(s,f.alt):0,c?lm(s,f.label):0,u?cm(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:l,title:im[l],results:p.map(({entry:f})=>({id:vr(f),label:f.label,hint:om(f),target:f.target}))})}return i}function ri(e){return e.flatMap(t=>t.results)}function um(e){return{kind:"collection",label:e,target:{tab:"firestore",rest:[e]}}}function si(e){return{kind:"document",label:e,target:{tab:"firestore",rest:e.split("/").filter(Boolean)}}}function dm(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 fm(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 hm(e){return{kind:"object",label:e,target:{tab:"storage",rest:e.split("/").filter(Boolean)}}}function pm(e){return{kind:"rtdb-key",label:e,target:{tab:"rtdb",rest:[e]}}}async function mm(e,t={},n){const r={...wr,...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(um));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(si))}catch{}if(e.listSubcollections&&e.listDocumentPaths)try{const{subcollections:f,documents:m}=await rm(p,e.listSubcollections,e.listDocumentPaths,{maxSubcollections:r.subcollections,maxRpcCalls:r.subcollectionRpcCalls,docsPerCollection:r.docsPerCollection});i(f.map(dm)),i(m.map(si))}catch{}})(),l=(async()=>{if(e.listUsers)try{const d=await e.listUsers(r.users);i(d.slice(0,r.users).map(fm))}catch{}})(),c=(async()=>{if(e.listStorageObjectPaths)try{const d=await e.listStorageObjectPaths(r.objects);i(d.slice(0,r.objects).map(hm))}catch{}})(),u=(async()=>{if(e.listRtdbTopLevelKeys)try{i((await e.listRtdbTopLevelKeys()).map(pm))}catch{}})();return await Promise.allSettled([a,l,c,u]),s}const bo=Symbol("pyric/auth/target"),ym=Symbol("pyric.user.internal");function q(e,t){return new lt(e,`Firebase: ${t} (${e}).`)}const go={PASSWORD:"password"},Wn={EMAIL_LINK:"emailLink",EMAIL_PASSWORD:"password"};class _n{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"?bm(t):t;if(!n)return null;const r=n.providerId,s=n.signInMethod;if(typeof r!="string"||typeof s!="string")return null;if(r===go.PASSWORD){const i=typeof n.email=="string"?n.email:"",a=typeof n.password=="string"?n.password:"";return new gm(i,a,s)}return new _n(r,s)}}function bm(e){try{const t=JSON.parse(e);return typeof t=="object"&&t!==null?t:null}catch{return null}}class gm extends _n{email;secret;constructor(t,n,r=Wn.EMAIL_PASSWORD){super(go.PASSWORD,r),this.email=t,Object.defineProperty(this,"secret",{value:n,enumerable:!1,writable:!1})}get password(){return this.signInMethod===Wn.EMAIL_PASSWORD?this.secret:null}get emailLink(){return this.signInMethod===Wn.EMAIL_LINK?this.secret:null}toJSON(){return{providerId:this.providerId,signInMethod:this.signInMethod,email:this.email,password:this.secret}}}class Sn extends _n{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 Yr(e,t){return t?new Sn(e,e):null}class Ze{static PROVIDER_ID="google.com";static GOOGLE_SIGN_IN_METHOD="google.com";providerId=Ze.PROVIDER_ID;addScope(t){return this}setCustomParameters(t){return this}static credentialFromResult(t){return Yr(Ze.PROVIDER_ID,t)}static credentialFromError(t){return null}static credential(t,n){return new Sn(Ze.PROVIDER_ID,Ze.GOOGLE_SIGN_IN_METHOD,{idToken:t??void 0,accessToken:n??void 0})}}class et{static PROVIDER_ID="facebook.com";static FACEBOOK_SIGN_IN_METHOD="facebook.com";providerId=et.PROVIDER_ID;addScope(t){return this}setCustomParameters(t){return this}static credentialFromResult(t){return Yr(et.PROVIDER_ID,t)}static credentialFromError(t){return null}static credential(t){return new Sn(et.PROVIDER_ID,et.FACEBOOK_SIGN_IN_METHOD,{accessToken:t})}}class tt{static PROVIDER_ID="github.com";static GITHUB_SIGN_IN_METHOD="github.com";providerId=tt.PROVIDER_ID;addScope(t){return this}setCustomParameters(t){return this}static credentialFromResult(t){return Yr(tt.PROVIDER_ID,t)}static credentialFromError(t){return null}static credential(t){return new Sn(tt.PROVIDER_ID,tt.GITHUB_SIGN_IN_METHOD,{accessToken:t})}}const vo=[Ze.PROVIDER_ID,"apple.com",et.PROVIDER_ID,tt.PROVIDER_ID,"twitter.com","microsoft.com","yahoo.com"];function Xr(e,t=!1){const n=e[bo];if(!n)throw new TypeError("pyric/auth: unrecognized Auth handle — was it produced by getAuth(...)?");return t||n.assertAlive?.(),n}class vm{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 wm(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 vt(e){if(typeof e!="string"||e.length<6)throw q("auth/weak-password","Password should be at least 6 characters")}function wo(){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 xm="__pyric_no_password__";class xo{usersByEmail;usersByUid;authStateSubs=[];idTokenSubs=[];userDbSubs;beforeStateSubs=[];sharedCounters;flow=new vm;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=wo(),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 l=a===null?null:a.uid,c=this.cachedUser?.uid??null;l!==c&&(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,yn({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??xm,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){vt(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(),l=this.usersByEmail.get(a);if(l&&l.uid!==t)throw q("auth/email-already-in-use",`An account already exists for ${i}.`);r.password!==void 0&&r.password!==null&&(vt(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),vt(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??jm(),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 l=a?.providerId?.trim();if(!l)throw q("auth/argument-error",`${r}: providerUserInfo entries need a non-empty providerId.`);l==="password"||l==="anonymous"||s.has(l)||(s.add(l),i.push({providerId:l}))}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&&(vt(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(),l=this.usersByEmail.get(a);if(l&&l!==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&&(vt(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=wm(t,n,i),l=this.signInProviderByUid.get(t)??null,c={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:l}},u={token:a,claims:c,expirationTime:s.toISOString(),issuedAtTime:r.toISOString(),authTime:r.toISOString(),signInProvider:l};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"}],l=t.isAnonymous?[]:a.map(u=>({uid:t.uid,displayName:t.displayName,email:t.email,phoneNumber:r,photoURL:n,providerId:u.providerId})),c={uid:t.uid,email:t.email,emailVerified:s,displayName:t.displayName,photoURL:n,phoneNumber:r,isAnonymous:t.isAnonymous,providerId:i,providerData:l,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(c,ym,{value:{updateProfile:u=>(this.updateProfileFor(c,u),Promise.resolve()),delete:()=>(this.deleteFor(c),Promise.resolve()),updateEmail:u=>(this.updateEmailFor(c,u),Promise.resolve()),updatePassword:u=>(this.updatePasswordFor(c,u),Promise.resolve()),reload:()=>(this.reloadFor(c),Promise.resolve()),target:this.selfTarget()},enumerable:!1}),c}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 jm(){return`provider-${globalThis.crypto.randomUUID()}`}const ii=new WeakSet,Ft=new WeakMap;function jo(e,t,n,r="[DEFAULT]"){return km(e,t),_m(e,t,n,r)}function km(e,t){ii.has(e)||(ii.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 ai(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 _m(e,t,n,r){let s=Ft.get(e);s||(s=new Map,Ft.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,ai(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&&Ft.delete(e))}}const l={backend:t,session:n,subscribers:new Set,generation:1};s.set(i,l),l.unregisterService=e.registerPersistableService(i,ai(l));const c=l.generation;return()=>{l.generation===c&&(l.unregisterService?.(),l.unregisterService=void 0,l.unsubscribeBackend?.(),l.unsubscribeBackend=void 0,l.subscribers.clear(),s.get(i)===l&&s.delete(i),s.size===0&&Ft.delete(e))}}async function Bj(e){const{backend:t}=Xr(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 Sm(e){const t=Xr(e,!0);try{t.assertAlive?.()}catch(n){if(n.code==="app/app-deleted")return;throw n}await t.backend.transitionCurrentUser(null)}const oi=new WeakMap,li=new WeakMap,ci=new WeakMap;function ko(e){let t=li.get(e);return t||(t=wo(),li.set(e,t)),t}function Em(e){let t=oi.get(e);return t||(t=new xo(e,e,ko(e)),oi.set(e,t),jo(e,t,e)),t}function Cm(e,t){return t.service("auth/backend",()=>{const{sandbox:n,session:r}=t,s=new xo(n,r,ko(n),i=>{t.onDelete(i)});return t.onDelete(jo(n,s,r,e.name)),s})}function _o(e){if(e===void 0)return _o(vc());const t=wc(e);if(t)return t.service("auth/default",()=>{const n={kind:"sandbox",sandbox:t.sandbox,backend:Cm(e,t),own:r=>t.onDelete(r),assertAlive:()=>t.assertAlive()};return ui(n,e)});if(Nm(e)){let n=ci.get(e);return n||(n=ui({kind:"sandbox",sandbox:e,backend:Em(e)}),ci.set(e,n),n)}throw new TypeError("pyric/auth is a sandbox-only mirror. Package resolution must leave firebase/auth unchanged for production; activate pyric dev or @pyric/cli/register before importing to select the sandbox.")}function Nm(e){return typeof e=="object"&&e!==null&&typeof e.onCurrentUserChanged=="function"&&typeof e.withAuth=="function"}function ui(e,t){const n={[bo]:e,...t?{app:t}:{},signOut(){return Sm(n)}};return Object.defineProperty(n,"currentUser",{enumerable:!0,get(){return e.backend.getCurrentUser()}})}function K(e){return Xr(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 xc("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 Nt(e,t){return Am(e)?(_e(e.storage),new Rt(e.storage,Rm(e.fullPath,t??""))):(_e(e),new Rt(e,So(t??"")))}class Rt{storage;bucket;fullPath;constructor(t,n){this.storage=t;const r=_e(t);this.bucket=r.bucket,this.fullPath=n}get name(){if(this.fullPath==="")return"";const t=this.fullPath.lastIndexOf("/");return t===-1?this.fullPath:this.fullPath.slice(t+1)}get parent(){if(this.fullPath==="")return null;const t=this.fullPath.lastIndexOf("/"),n=t===-1?"":this.fullPath.slice(0,t);return new Rt(this.storage,n)}get root(){return this.fullPath===""?this:new Rt(this.storage,"")}toString(){return`gs://${this.bucket}/${this.fullPath}`}}function So(e){return e===""?"":e.split("/").filter(t=>t.length>0).join("/")}function Rm(e,t){const n=So(t);return e===""?n:n===""?e:`${e}/${n}`}function Am(e){if(e===null||typeof e!="object"||wn in e)return!1;const t=e;return typeof t.fullPath=="string"&&t.storage!==void 0}async function Im(e,t){return Eo(e,"getBlob"),Dm(e,t)}async function Qr(e,t){Eo(e,"deleteObject");const n=_e(e.storage),r=ft(n,t),s=await $t(e.storage),i=await s.backend.getMetadata(e.fullPath);Ot(s,{request:{auth:qe(n),method:"delete",path:e.fullPath},resource:jn(i)},n,r),await s.backend.delete(e.fullPath);try{Re(n.sandbox,yn({service:"storage",op:"object_delete",path:e.fullPath,auth:qe(n),before:i??void 0,detail:{bucket:e.bucket}}),r)}catch{}}async function Dm(e,t){const n=_e(e.storage),r=ft(n),s=await $t(e.storage),i=await s.backend.getMetadata(e.fullPath);Ot(s,{request:{auth:qe(n),method:"get",path:e.fullPath},resource:jn(i)},n,r);const a=await s.backend.getBlob(e.fullPath);if(!a)throw Za(e.fullPath);return typeof t=="number"&&a.size>t?a.slice(0,t):a}function Eo(e,t){if(e.fullPath==="")throw xn(t)}function Pm(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 $m{[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=Pm(n,i);const l=to({ref:t,blob:this._blob,settable:r}),c=Hr(l);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:c,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=hh(),this._updateSnapshot("canceled",this._snapshot.bytesTransferred),this._notifyObservers("error"),this._reject(this._error),!0):!1}on(t,n,r,s){let i,a,l,c=!1;if(typeof n=="object"&&n!==null&&(c=!0),c){const f=n;f.next!==void 0&&(i=f.next),f.error!==void 0&&(a=f.error),f.complete!==void 0&&(l=f.complete)}else typeof n=="function"&&(i=n),typeof r=="function"&&(a=r),typeof s=="function"&&(l=s);const d={next:i,error:a,complete:l};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(l!==void 0){const v=l;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 l=i.next;try{l(this._snapshot)}catch{}}}if(t==="error"){for(const i of this._observers)if(i.error!==void 0&&this._error!==void 0){const c=i.error,u=this._error;try{c(u)}catch{}}}if(t==="complete"){for(const i of this._observers)if(i.complete!==void 0){const l=i.complete;try{l()}catch{}}}}_runStep(){if(this._snapshot.state!=="running")return;if(this._didIntermediateProgress===!1){this._didIntermediateProgress=!0;let r=0;this._snapshot.totalBytes>0&&(r=Math.floor(this._snapshot.totalBytes/2)),this._updateSnapshot("running",r),this._notifyObservers("next"),queueMicrotask(()=>{this._runStep()});return}this._commitUpload()}async _commitUpload(){if(this._snapshot.state==="running")try{const n=await eo(this._ref,this._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 Qr(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 Om(e,t,n,r){if(e.fullPath==="")throw xn("uploadBytesResumable");return new $m(e,t,n,r)}async function Zr(e){const t=e.storage,n=_e(t),r=ft(n),s=await $t(t);Ot(s,{request:{auth:qe(n),method:"list",path:e.fullPath},resource:null},n,r);const i=e.fullPath===""?"":`${e.fullPath}/`,a=await s.backend.listByPrefix(i),l=[],c=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)l.push(Nt(t,d.fullPath));else{const m=p.slice(0,f),y=`${i}${m}`;c.has(y)||(c.add(y),u.push(Nt(t,y)))}}return u.sort((d,p)=>d.fullPath<p.fullPath?-1:d.fullPath>p.fullPath?1:0),{items:l,prefixes:u}}function Um(e,t,n){const r={name:n,options:structuredClone(t),automaticDataCollectionEnabled:!0};return gd(r,e),r}const Tm=Object.freeze({source:Object.freeze({kind:"studio"}),authLens:Object.freeze({mode:"admin"})});function Mm(e){return ha(e.withAuth(null),Tm)}const Bm="pyric-studio";function Co(e,t){return e.listDocuments(t).map(({path:n,phantom:r})=>({path:n,phantom:r}))}let Lm=0;function Fm(e){const t=Um(e,{projectId:"pyric-studio"},`pyric-studio-${Lm++}`),n=bn(e),r=Mm(e);return{sandbox:e,app:t,firestore:ma(e),adminFirestore:ya(r),auth:_o(e),storage:Hf(r),listRootCollections:()=>n.listRootCollections(),listSubcollections:s=>n.listSubcollections(s),listDocuments:s=>Co(n,s)}}function Vm(e,t){const[n,r]=h.useState(!1),[s,i]=h.useState(null),a=h.useMemo(()=>Sc(),[]),l=h.useMemo(()=>{try{return Fm(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:Bm,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}:l?e!=null&&n||t==="ready"?{status:"ready",handles:l}:{status:"pending",handles:null}:{status:"error",handles:null,error:new Error("Studio: failed to construct the sandbox data handles.")}}function qm(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=ba(e);return t?t.rules.kind==="evaluated":!1}function Wm(e){return"service"in e&&typeof e.service=="string"?e.service:"firestore"}function zm(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 Km(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 Hm(e){const t=[];for(const r of e)qm(r)&&t.push(Gm(r));return Km(t,e).sort((r,s)=>s.at-r.at)}function Gm(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:Wm(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=zm(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 di=/^Rule #(\d+) \(([^)]+)\) → (ALLOW|deny|unsupported)/;function Jm(e){const t=e.rules?.engine??e.service;return t==="rtdb"||t==="storage"?t:"firestore"}function Ym(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 Xm(e){const t=Jm(e),n=e.reasons.filter(s=>di.test(s)),r=e.reasons.filter(s=>!di.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"?Zm(e,n,r):t==="storage"?ey(e,n,r):Qm(e,n,r)}function Qm(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 Zm(e,t,n){const r=e.rules,s=Ym(e),i=!r?.matchedPath||r?.errorCode==="NO_MATCHING_RULE",a=r?.pathVariableBindings&&Object.keys(r.pathVariableBindings).length>0?r.pathVariableBindings:void 0;let l,c;return i?l=`No \`.${s}\` rule granted ${e.method} on ${e.path}: RTDB implicit deny (no rule matched).`:s==="validate"?(c=`${r.matchedPath} .validate`,l=`The \`.validate\` rule at \`${r.matchedPath}\` rejected the proposed value for ${e.method} ${e.path}.`):(c=`${r.matchedPath} .${s}`,l=`The \`.${s}\` rule at \`${r.matchedPath}\` evaluated false for ${e.method} ${e.path}.`),{headline:l,engine:"rtdb",ruleNode:c,ruleExpression:r?.matchedRule,phase:s,bindings:a,ruleLines:t,otherLines:n,implicitDeny:i}}function ey(e,t,n){const r=e.reasons.find(l=>/^match\s/.test(l)),i=e.reasons.some(l=>/^no rule matches/.test(l))||!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 ty(e){return e.skipped?"skipped":e.error!==void 0?"error":e.value===!0?"true":e.value===!1?"false":"value"}function ny(e){const t=e.evaluatedRule?.expressionTrace;if(!t||t.length===0)return[];const n=t.map(s=>({source:s.source,outcome:ty(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 ry(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 sy(e){const t=bn(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=>Co(t,n)}}function $e(){const e=Pe(),t=pe(),n=t.status==="ready"?t.env.persistence:void 0,r=Vm(n,t.status),s=t.status==="ready"?t.env.live:void 0,i=iy(s);return h.useMemo(()=>{switch(e.status){case"ready":return{status:"ready",handles:sy(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:l=>s.listSubcollections(l),listDocuments:l=>s.listDocuments(l)}}}return r}}},[e,r,s,i])}function iy(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 un=500;function zn(e){return e.length>un?e.slice(-un):e}function Tt(){const e=Pe(),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(zn(n.history())),n.subscribe(c=>i(u=>zn(nd(u,c))))},[r,n]);const a=h.useMemo(()=>r?zn(e.events):[],[r,e]);return r?a:s}function ay(e){return jc(e)}function oy(e){const t=ba(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 l=e.error;l!==void 0&&l.code==="PERMISSION_DENIED"&&(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 l=e.error;l!==void 0&&l.reasons!==void 0&&(a=l.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 ly(){const e=Tt();return h.useMemo(()=>e.filter(ay).map(oy),[e])}function cy(){const e=Tt();return h.useMemo(()=>Hm(e),[e])}function uy(){const e=$e();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??Be,s=e.firestoreApi?.setDoc??Qt;let i=0;const a=[];for(const l of t)try{await s(r(n,l.path),l.data),i++}catch(c){a.push(`${l.path}: ${c instanceof Error?c.message:String(c)}`)}return{written:i,errors:a}},[e])}function dy(){const e=$e();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(l){const c=a.request.uid??a.request.email??"<auto>";i.push(`${c}: ${l instanceof Error?l.message:String(l)}`)}return{created:s,errors:i}},[e])}function fy(){const e=$e(),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 hy(){const e=fy(),t=uy(),n=dy(),r=Pe();return h.useCallback(async()=>{const s=await e();if(r.status==="ready"){const{applySeed:i,deploySeedRules:a}=await Ba(async()=>{const{applySeed:l,deploySeedRules:c}=await import("./seed.DANAIyRw.js");return{applySeed:l,deploySeedRules:c}},__vite__mapDeps([0,1,2,3,4,5,6]));a(r.handles.sandbox),await i(r.handles)}else try{const i=await fetch("/__pyric/init.json").then(c=>c.ok?c.json():null),a=i?.seed;a&&await t(Object.entries(a).map(([c,u])=>({path:c,data:u})));const l=i?.authUsers;Array.isArray(l)&&await n(l.map(c=>({request:c})))}catch(i){s.errors.push(`reseed: ${i instanceof Error?i.message:String(i)}`)}return s},[e,t,n,r])}function es(){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 py(){const e=pe(),t=e.status==="ready"?e.env.live:void 0;return h.useCallback(async()=>t?t.exportState():null,[t])}function my(){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 yy(){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 c=>{t&&(await t.saveBranch(c),await s())},[t,s]),a=h.useCallback(async c=>{t&&await t.switchBranch(c)},[t]),l=h.useCallback(async c=>{t&&(await t.deleteBranch(c),await s())},[t,s]);return{branches:n,save:i,switchTo:a,remove:l}}function by(e="firestore"){const t=Pe(),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 c={};typeof a.rules=="string"&&(c.firestore=a.rules),a.databaseRules!==void 0&&a.databaseRules!==null&&(typeof a.databaseRules=="string"?c.rtdb=a.databaseRules:c.rtdb=JSON.stringify(a.databaseRules,null,2)),typeof a.storageRules=="string"&&(c.storage=a.storageRules),s(c)}).catch(()=>{}),()=>{i=!1}},[n]),h.useMemo(()=>{const i=t.status==="ready",a=e==="database"?"rtdb":e;if(!i){const l=r[a];return l!==void 0?l:""}try{if(a==="rtdb"){const c=Aa(t.handles.sandbox);return c!=null?JSON.stringify(c,null,2):""}return bn(t.handles.sandbox).getRules()}catch{return""}},[t,r,e])}function gy(e){let t=!0;return n=>{const r=t;t=!1,e(s=>wy(s,n,r))}}function vy(e){const t=new Map;for(const n of e)t.set(vr(n),n);return[...t.values()]}function wy(e,t,n){return vy(n?t:[...e??[],...t])}const xy=3e4;function No(){const e=$e(),t=pe(),[n,r]=h.useState(null),[s,i]=h.useState(!1),a=h.useRef(!1),l=h.useRef(e);l.current=e;const c=t.status==="ready"?t.env.live:void 0,u=h.useRef(c);u.current=c;const d=h.useRef(null),p=h.useRef(0),f=h.useRef(null),m=h.useRef(0),y=h.useCallback(v=>{const b=l.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??kt,_=b.firestoreApi?.query??sn,N=b.firestoreApi?.getDocs??Zt,P=b.firestoreApi?.limit??an,I=b.storageApi?.ref??Nt,D=b.storageApi?.listAll??Zr,C=b.authApi?.listUsers??fe.listUsers,S={listRootCollections:()=>x.listRootCollections(),listDocumentPaths:async(R,V)=>(await N(_(j(k,R),P(V)))).docs.slice(0,V).map(A=>`${R}/${A.id}`),listSubcollections:R=>Promise.resolve(x.listSubcollections(R)),listUsers:async R=>(await Promise.resolve(C(x.auth))).slice(0,R).map(G=>({uid:G.uid,email:G.email??null})),listStorageObjectPaths:R=>nm(I(x.storage,""),D,{maxObjects:R,maxListCalls:wr.storageListCalls}),listRtdbTopLevelKeys:async()=>{const R=u.current;if(!R)return[];const V=Date.now()-m.current<xy;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=gy(R=>r(R));mm(S,wr,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(l.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 jy=150;function ky(e){return e.startsWith("/")||/rtdb/i.test(e)}function Ro({autoFocus:e,onNavigated:t,onEscape:n,exposeFocus:r}){const[s,i]=h.useState(""),[a,l]=h.useState(""),[c,u]=h.useState(0),[d,p]=h.useState(!1),f=h.useRef(null),{entries:m,building:y,ensure:g}=No();h.useEffect(()=>{if(r)return r(()=>f.current?.focus()),()=>r(null)},[r]),h.useEffect(()=>{e&&f.current?.focus()},[e]),h.useEffect(()=>{const j=setTimeout(()=>l(s),jy);return()=>clearTimeout(j)},[s]);const v=h.useMemo(()=>ni(a,We,m??[]),[a,m]),b=h.useMemo(()=>ri(v),[v]);h.useEffect(()=>{u(j=>b.length===0?0:Math.min(j,b.length-1))},[b.length]);const w=j=>{j&&(i(""),l(""),p(!1),ce(j.target),t?.(j.target))},x=()=>{if(s===a){w(b[c]??b[0]);return}const j=ri(ni(s,We,m??[]));w(j[0])};let k=0;return o.jsxs("div",{className:"studio-home__command",children:[o.jsx("div",{className:"studio-home__command-row",children:o.jsx("input",{ref:f,className:"studio-home__command-input",type:"text",value:s,placeholder:"Jump to a surface, collection, doc, user, or object…","aria-label":"Command input",role:"combobox","aria-expanded":d&&b.length>0,"aria-autocomplete":"list",onFocus:()=>{g(),p(!0)},onBlur:()=>p(!1),onChange:j=>{const _=j.target.value;i(_),p(!0),ky(_)&&g({rtdbLikely:!0})},onKeyDown:j=>{if(j.key==="ArrowDown")j.preventDefault(),u(_=>Math.min(_+1,Math.max(b.length-1,0)));else if(j.key==="ArrowUp")j.preventDefault(),u(_=>Math.max(_-1,0));else if(j.key==="Enter")x();else if(j.key==="Escape"){if(n){n();return}i(""),l(""),p(!1)}}})}),d&&!v.length&&y&&m===null?o.jsx("div",{className:"studio-home__command-results",role:"status","aria-live":"polite",children:o.jsx("span",{className:"studio-home__command-group-title",children:"Indexing sandbox…"})}):null,d&&v.length?o.jsx("div",{className:"studio-home__command-results",role:"listbox","aria-label":"Suggestions",onMouseDown:j=>j.preventDefault(),children:v.map(j=>{const _=k;return k+=j.results.length,o.jsxs("div",{className:"studio-home__command-group",children:[o.jsx("span",{className:"studio-home__command-group-title","aria-hidden":"true",children:j.title}),o.jsx("ul",{className:"studio-home__command-group-list",children:j.results.map((N,P)=>{const I=_+P;return o.jsx("li",{children:o.jsxs("button",{type:"button",role:"option","aria-selected":I===c,className:"studio-home__command-result","data-active":I===c?"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 _y({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(Ro,{autoFocus:!0,onEscape:e,onNavigated:e})})})}const Sy={status:"loading",payload:null},Vt={status:"absent",payload:null};let dn=Sy,fi=!1;const xr=new Set;function qt(e){dn=e;for(const t of xr)t()}function Ey(){if(!fi){if(fi=!0,typeof fetch>"u"){dn=Vt;return}fetch("/__pyric/init.json").then(async e=>{if(!e.ok||!(e.headers.get("content-type")??"").includes("json"))return qt(Vt);const n=await e.json();qt({status:"ready",payload:n})}).catch(()=>qt(Vt))}}function Cy(e){return xr.add(e),Ey(),()=>xr.delete(e)}function En(){return h.useSyncExternalStore(Cy,()=>dn,()=>dn)}function Ny(e){return e.kind==="absent"?"absent":e.sandboxConnected?"available":"idle"}function Ry(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 Ay(e){try{const t=await e("/__pyric/health");return t.ok?(t.headers.get("content-type")??"").includes("json")?Ry(t.status,await t.json()):{kind:"absent"}:{kind:"absent"}}catch{return{kind:"absent"}}}function Iy(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=Ny(await Ay(fetch));return r&&(n(u),u==="absent"&&s&&(clearInterval(s),s=null)),u},a=()=>typeof document>"u"||document.visibilityState!=="hidden",l=()=>{s||(s=setInterval(()=>{a()&&i()},e))},c=()=>{a()&&i()};return i().then(u=>{r&&u!=="absent"&&l()}),typeof document<"u"&&document.addEventListener("visibilitychange",c),()=>{r=!1,s&&clearInterval(s),typeof document<"u"&&document.removeEventListener("visibilitychange",c)}},[e]),t}const Dy="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 Py(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 $y(e){return e==="studio"?"Studio":"App"}function Oy(e,t,n=Date.now()){const r=e.clients.length,s=e.clients.map(a=>({clientId:a.clientId,kindLabel:$y(a.kind),route:a.route||"/",visibilityLabel:a.visibility==="hidden"?"Hidden":"Visible",isThisPage:a.clientId===t,freshnessLabel:Py(a.lastSeen,n)}));s.sort((a,l)=>a.isThisPage!==l.isThisPage?a.isThisPage?-1:1:a.kindLabel!==l.kindLabel?a.kindLabel==="Studio"?-1:1:a.route.localeCompare(l.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:Dy,otherCount:i}}function Uy(){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(Oy(i,s))})},[t]),n}const Ty={servedEpoch:null,runningEpoch:null,updateAvailable:!1,updating:!1,error:null},My=()=>()=>{},hi=()=>Ty;function By(){const e=pe(),t=En(),n=Iy(),r=Uy(),[s,i]=h.useState(!1),a=h.useRef(null),l=e.status==="ready"?e.env.live?.runtime:void 0,c=h.useSyncExternalStore(l?.subscribe??My,l?.getSnapshot??hi,l?.getSnapshot??hi),d=t.status==="ready"&&e.status==="ready"&&!e.env.live,p=e.status==="error",f=c.error?"worker update failed":p?"backend error":d?"worker unreachable":null,m=c.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:[c.updateAvailable?o.jsxs("button",{type:"button",className:"studio-chip studio-chip--warn",disabled:c.updating,title:"The Studio backend is running older code. Update every connected page to the served worker version.",onClick:()=>void l?.update().catch(()=>{}),children:[o.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),c.updating?"updating worker…":"update worker"]}):null,f?o.jsxs("a",{className:"studio-chip studio-chip--warn",href:kn({tab:"settings"}),title:m,onClick:g=>{g.preventDefault(),ce({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 Ly(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 pi(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 Fy({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 l=e.slice(s,a),c=i.origin==="transaction"?"transaction":"batch";r.push(pi(c,i.groupId,l)),s=a;continue}if(n&&i.origin==="listener"){let a=s+1;for(;a<e.length&&e[a].origin==="listener"&&!e[a].groupId&&Ly(e[a],i);)a++;const l=e.slice(s,a);if(l.length>1){const c=i.triggeredBy?`${i.triggeredBy.method}:${i.triggeredBy.path}`:"unknown";r.push(pi("listener-run",`listener-run:${c}:${s}`,l))}else r.push({type:"single",event:i});s=a;continue}r.push({type:"single",event:i}),s++}return{items:r}},[e,t,n])}const Vy={buckets:[],total:0,denies:0,maxCount:0,outOfWindow:0};function qy({events:e,window:t,bucketCount:n=30}){return h.useMemo(()=>Wy(e,t,n),[e,t.start,t.end,n])}function Wy(e,t,n=30){const r=t.end-t.start;if(n<=0||r<=0)return Vy;const s=r/n,i=new Array(n).fill(0),a=new Array(n).fill(0);let l=0,c=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]++,l++,f.result==="deny"&&(a[y]++,c++)}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:l,denies:c,maxCount:d,outOfWindow:u}}const zy=new Set(["get","list"]),Ky=new Set(["create","update","set"]),Hy=new Set(["delete","remove"]),Gy=[{key:"reads",label:"Read ops"},{key:"writes",label:"Writes"},{key:"deletes",label:"Deletes"}],Jy=[{key:"allows",label:"Allows"},{key:"denies",label:"Denies"},{key:"errors",label:"Errors"}];function Cn(e){return e.origin==="admin"}function Yy(e,t=Cn){return e.result==="allow"||t(e)?zy.has(e.method)?"reads":Ky.has(e.method)?"writes":Hy.has(e.method)?"deletes":null:null}function Xy(e,t=Cn){return t(e)?null:e.result==="allow"?"allows":e.result==="deny"?"denies":e.result==="error"?"errors":null}const Qy=e=>({points:[],series:e.map(t=>({key:t.key,label:t.label,values:[],total:0})),maxValue:0});function Ao(e,t,n,r,s){const i=t.end-t.start;if(n<=0||i<=0)return Qy(r);const a=i/n,l=new Map(r.map(f=>[f.key,new Array(n).fill(0)])),c=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=l.get(y);v[g]++,c.set(y,(c.get(y)??0)+1)}let u=0;for(const f of l.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:l.get(f.key),total:c.get(f.key)??0}));return{points:d,series:p,maxValue:u}}function Zy(e,t,n=24,r=Cn){return Ao(e,t,n,Gy,s=>Yy(s,r))}function eb(e,t,n=24,r=Cn){return Ao(e,t,n,Jy,s=>Xy(s,r))}function tb({events:e,window:t,bucketCount:n=24,isAdmin:r}){return h.useMemo(()=>Zy(e,t,n,r),[e,t.start,t.end,n,r])}function nb({events:e,window:t,bucketCount:n=24,isAdmin:r}){return h.useMemo(()=>eb(e,t,n,r),[e,t.start,t.end,n,r])}function jr({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 At(e){const t=new Date(e),n=r=>String(r).padStart(2,"0");return`${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`}function Io({event:e,selected:t,onSelect:n,renderClassification:r,formatTime:s=At,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(jr,{kind:e.method,children:e.method}),o.jsx("span",{"data-pyric-traffic-path":"",children:e.path||"/"}),r?r(e):null]})}var ts=Ec();function Je(e,t,n){let r=n.initialDeps??[],s,i=!0;function a(){var l,c,u;let d;n.key&&((l=n.debug)!=null&&l.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&&((c=n.debug)!=null&&c.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`,`
|
|
5
|
+
`||i==="\r")throw new Z("unterminated string literal (newline before closing quote)",F(t));s+=i,r+=1}if(s.length>Fe.maxStringLiteralLength)throw new Z(`string literal exceeds ${Fe.maxStringLiteralLength}-character cap`,F(t))}throw new Z("unterminated string literal",F(t))}function Uc(e){const t=new Mc(e),n=t.parseExpression();return t.expect("eof","unexpected trailing tokens"),Lc(n),n}class Mc{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=Tc(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(!Rc(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=Nc[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 ${Bc(r)})`,r.pos);return this.consume()}}function Tc(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 Bc(e){return e.kind==="eof"?"end of expression":e.value!==void 0?`${e.kind} ${JSON.stringify(e.value)}`:e.kind}function Lc(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>Fe.maxAstDepth)throw new ye(`expression AST exceeds depth cap of ${Fe.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 It(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 le(e,t){switch(e.kind){case"literal":return e.value;case"reference":return Fc(e,t);case"sentinel":return Vc(e,t);case"unary":return qc(e,t);case"binary":return Wc(e,t);case"logical":return Kc(e,t);case"ternary":return Hc(e,t);case"fieldAccess":return Gc(e,t);case"indexAccess":return Jc(e,t)}}function Fc(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 Vc(e,t){const n=e.args.map(r=>{const s=le(r,t);if(It(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 en(r,e),{__type:"increment",value:r}}case"arrayUnion":return{__type:"arrayUnion",values:n};case"arrayRemove":return{__type:"arrayRemove",values:n}}}function qc(e,t){const n=le(e.operand,t);if(er(n,e),e.op==="-"){if(typeof n!="number")throw ue(e,`unary '-' expects a number, got ${re(n)}`);const r=-n;return en(r,e),r}if(typeof n!="boolean")throw ue(e,`unary '!' expects a boolean, got ${re(n)}`);return!n}function Wc(e,t){const n=le(e.left,t),r=le(e.right,t);switch(er(n,e),er(r,e),e.op){case"+":if(typeof n=="number"&&typeof r=="number"){const s=n+r;return en(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 en(s,e),s}case"==":return vs(e,n,r);case"!=":return!vs(e,n,r);case"<":case"<=":case">":case">=":return zc(e,n,r)}}function vs(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 zc(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 Kc(e,t){const n=le(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=le(e.right,t);if(typeof r!="boolean")throw ue(e,`'${e.op}' expects boolean operands; right is ${re(r)}`);return r}function Hc(e,t){const n=le(e.cond,t);if(typeof n!="boolean")throw ue(e,`ternary condition must be boolean, got ${re(n)}`);return le(n?e.whenTrue:e.whenFalse,t)}function Gc(e,t){const n=le(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)||It(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 Jc(e,t){const n=le(e.target,t);if(n==null)throw new oe("null-access","cannot index null target",e.pos);const r=le(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"&&!It(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 er(e,t){if(It(e))throw new oe("sentinel-misuse",`sentinel '@${e.__type}' cannot be used as an operator operand`,t.pos)}function en(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(It(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 xa="$expr";class tn extends Error{code="invalid-argument";path;constructor(t,n){super(t),this.name="ExpressionWalkError",this.path=n}}function Yc(e,t){return tr(e,t,"")}function tr(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]=tr(e[a],t,n===""?String(a):`${n}.${a}`);return i}const r=e;if(Object.prototype.hasOwnProperty.call(r,xa))return Xc(r,t,n);const s={};for(const i of Object.keys(r))s[i]=tr(r[i],t,n===""?i:`${n}.${i}`);return s}function Xc(e,t,n){const r=Object.keys(e);if(r.length!==1)throw new tn(`expression wrapper at '${n||"<root>"}' must have only the '$expr' key, got [${r.map(l=>JSON.stringify(l)).join(", ")}]`,n);const s=e[xa];if(typeof s!="string")throw new tn(`'$expr' value at '${n||"<root>"}' must be a string, got ${eu(s)}`,n);const i=Zc(s,n);return Qc(i,t,n)}function Qc(e,t,n){try{return le(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 Zc(e,t){try{return Uc(Dc(e))}catch(n){throw n instanceof Z?ws(n,Z,t):n instanceof ye?ws(n,ye,t):n}}function ws(e,t,n){const r=new t(`at '${n||"<root>"}': ${e.message}`,e.pos);return r.cause=e,r}function eu(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function tu(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/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 c=(await t()).seed({rules:a,documents:i??{}});return{ok:!0,summary:`Seeded sandbox with ${Object.keys(i??{}).length} document(s)`,data:{lint:c,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:l}=r,u=(await t()).execute({method:s,path:i,auth:a,data:l});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:l}=r,c=await t();if(l){const u=c.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:c.listDocuments(s)}}:{ok:!0,summary:`Read ${s}`,data:{document:c.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,l=(await t()).batch(s,i);return{ok:l.allowed,summary:l.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:l.allowed,results:l.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,l=await t(),{path:c,result:u}=l.createWithAutoId(s,a,i);return{ok:u.allowed,summary:u.allowed?`Created ${c}`:`Create at ${c} 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:c,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:l,writes:c}=r;for(let p=0;p<c.length;p+=1){const f=c[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(l)){const w=m.get(v).data();y[g]=w===void 0?null:w}for(let g=0;g<c.length;g+=1){const v=c[g];if(v.method==="delete"){m.delete(v.path);continue}const b=Yc(v.data,{reads:y});if(b===null||typeof b!="object"||Array.isArray(b))throw new tn(`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 (${c.length} write(s))`:"Transaction rolled back",data:f}}catch(p){if(p instanceof tn||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 ja(e){return tu({resolveSandbox:e.resolveSandbox,resolveModulesFn:oa})}let $n;function nu(){if($n)return $n;const e=Mr();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(l=>l.identifiers())]},CallExpr_memberAccess(t,n,r){return t.identifiers()},ident(t,n,r){return[this.sourceString]}}),$n=e,e}function ru(e){const t=Ur(e);if(t.failed())return{raw:e,valid:!1,errors:[{code:"PARSE_ERROR",message:t.message??"Parse failed"}],warnings:[],referencedIdentifiers:[]};const n=nu()(t).identifiers(),r=[...new Set(n)];return{raw:e,valid:!0,errors:[],warnings:[],referencedIdentifiers:r}}const su=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(su.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 xs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function st(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)=>st(s,t[i]));if(!xs(e)||!xs(t))return!1;const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(s=>s in t&&st(e[s],t[s]))}class iu{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 l=0;l<r.length-1;l++){const c=r[l],u=Object.hasOwn(i,c)?i[c]:void 0;if(u==null||typeof u!="object"||Array.isArray(u)){const d={};i[c]=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 l=r[i].path,c=r[a].path;if(l===c)throw new Error(`multi-path update: duplicate path '${l}'.`);const u=l==="/"?"/":l+"/",d=c==="/"?"/":c+"/";if(l!=="/"&&c.startsWith(u))throw new Error(`multi-path update: '${c}' is a descendant of '${l}'.`);if(c!=="/"&&l.startsWith(d))throw new Error(`multi-path update: '${l}' is a descendant of '${c}'.`)}const s=[];for(const{path:i,value:a}of r){const l=this.write(i,a);s.push({path:i,prior:l})}return s}shallowUpdate(t,n){const r=[],s=L(t);for(const[i,a]of Object.entries(n)){const l=[...s,...L(i)],c=J(l),u=this.write(c,a);r.push({path:c,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 l=0;l<r.length-1;l++){const c=i[r[l]];if(c==null||typeof c!="object"||Array.isArray(c))return;i=c}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 au(e,t){return e==="/"||t==="/"?!0:e===t||e.startsWith(`${t}/`)||t.startsWith(`${e}/`)}class ou{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=>au(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 lu{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,yn({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 l;i&&(l={engine:"rtdb",matchedPath:i.matchedPath,matchedRule:i.matchedRule,pathVariableBindings:i.pathVariableBindings,reason:i.reason,errorCode:i.errorCode});let c="user";a.origin&&(c=a.origin),Re(this.sandbox,la({service:"rtdb",method:n,path:xe(r),auth:t,result:s,origin:c,durationMs:a.durationMs,reasons:i?.reasons,rules:l,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,Kl({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,Hl({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 cu{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 nn(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 Le=[],nr=!1,rr=!1,sr=!1,On;function uu(){if(On)return On;const e=Mr();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(l=>l.lint()),r.sourceString==="child"&&t.sourceString==="data"&&(sr=!0)},ident(t,n,r){const s=this.sourceString;s==="data"&&(nr=!0),s==="newData"&&(rr=!0)},bool_true(t){Le.push({code:"HARDCODED_TRUE",message:"Rule expression is hardcoded to true"})},bool_false(t){Le.push({code:"HARDCODED_FALSE",message:"Rule expression is hardcoded to false"})},Comparison_looseEq(t,n,r){Le.push({code:"LOOSE_EQUALITY",message:"Use '===' instead of '=='"}),t.lint(),r.lint()},Comparison_looseNeq(t,n,r){Le.push({code:"LOOSE_INEQUALITY",message:"Use '!==' instead of '!='"}),t.lint(),r.lint()}}),On=e,e}function du(e,t="read"){const n=Ur(e);return n.failed()?[]:(Le=[],nr=!1,rr=!1,sr=!1,uu()(n).lint(),t==="write"&&nr&&!rr&&!sr&&Le.push({code:"DATA_IN_WRITE",message:"Write rule references 'data' but not 'newData'; consider using 'newData' to check incoming data"}),[...Le])}const fu=new Set(["__proto__","prototype","constructor"]);function js(e,t){return fu.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 hu{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:{}},Un;function pu(){if(Un)return Un;const e=Mr();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 l=t.eval(),c=r.sourceString,u=i.asIteration().children.map(d=>d.eval());if(l instanceof je)switch(c){case"val":return l.val();case"exists":return l.exists();case"hasChild":return l.hasChild(String(u[0]));case"hasChildren":return l.hasChildren(u.length>0?u[0]:void 0);case"isString":return l.isString();case"isNumber":return l.isNumber();case"isBoolean":return l.isBoolean();case"child":return l.child(String(u[0]));case"parent":return l.parent();case"getPriority":return l.getPriority();default:throw new Error(`Unknown DataSnapshot method: ${c}`)}if(typeof l=="string"){const d=new hu(l);switch(c){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: ${c}`)}}throw new Error(`Unknown method '${c}' for the given value.`)},CallExpr_memberAccess(t,n,r){const s=t.eval();return s==null?null:js(s,r.sourceString)},CallExpr_indexAccess(t,n,r,s){const i=t.eval(),a=r.eval();return i==null?null:js(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}}}),Un=e,e}function ka(e,t){const n=Ur(e);if(n.failed())throw new Error(n.message??"RTDB expression failed to parse");return Ee=t,pu()(n).eval()}function mu(e){const t=e.val();return t===null||typeof t!="object"?[]:Object.keys(t)}function yu(e,t,n,r,s,i){let a=null;function l(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(!ka(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 l(g,d.child(m[0]),p.child(m[0]),w?{...f,[b]:m[0]}:f,m.slice(1))}if(w)for(const x of mu(p)){const k=l(g,d.child(x),p.child(x),{...f,[b]:x},[]);if(k)return k}else{const x=l(g,d.child(b),p.child(b),f,[]);if(x)return x}}return null}return l(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 l=a[a.length-1],c=l.startsWith("$");if(c||t[0]===l){const u=c?{...n,[l]:t[0]}:{...n},d=_a(i,t.slice(1),u,r+1);return s.push(...d),s}}return s}function ir(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,l=ir(a,s,n);return l==null?delete i[r]:i[r]=l,i}function bu(e,t,n,r){if(!r||r.length===0)return ir(e,t,n??null);let s=e;for(const i of r){const a=i.path.split("/").filter(Boolean);s=ir(s,a,i.value??null)}return s}class gu{execute(t,n){const r=Gl.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:l,newData:c,updates:u}=r.data;try{const d=i.split("/").filter(Boolean),p=t,f=_a(p,d,{}),m=new je(l,"/"),y=s==="read"?l:bu(l,d,c,u),g=new je(y,"/"),v=(k,j,_)=>{const N={};for(const[P,I]of Object.entries(_))N[P]=I,N[P.slice(1)]=I;return{auth:a?{uid:a.uid,token:a.token}:null,data:k,newData:j,root:m,now:Date.now(),pathVariableBindings:N}};let b;for(const k of f){const j=k.node[s];if(!j)continue;if(!j.parsed.valid){b||(b=k);continue}const _=d.slice(0,k.depth).join("/"),N=m.child(_),P=g.child(_);if(ka(j.raw,v(N,P,k.pathVariableBindings))){if(s==="write"){const D=yu(p,m,g,{},v,d);if(D)return{success:!0,data:{allowed:!1,unsupported:D.unsupported===!0,matchedPath:D.node.path,matchedRule:D.rule.raw,reason:D.unsupported?`Validation rule at '${D.node.path}' contains an expression the simulator cannot evaluate: ${D.rule.raw} — not evaluated; production may reject this write.`:"Validation rule evaluated to false",pathVariableBindings:D.bindings}}}return{success:!0,data:{allowed:!0,matchedPath:k.node.path,matchedRule:j.raw,reason:"Rule expression evaluated to true",pathVariableBindings:k.pathVariableBindings}}}}if(b){const k=b.node[s];return{success:!0,data:{allowed:!1,unsupported:!0,matchedPath:b.node.path,matchedRule:k.raw,reason:`'${s}' rule at '${b.node.path}' contains an expression the simulator cannot evaluate: ${k.raw} — not evaluated; production may reject or allow this ${s}.`,pathVariableBindings:b.pathVariableBindings}}}const w=f[f.length-1],x=w.node[s];return x?{success:!0,data:{allowed:!1,matchedPath:w.node.path,matchedRule:x.raw,reason:"Rule expression evaluated to false",pathVariableBindings:w.pathVariableBindings}}:{success:!1,error:{code:"NO_MATCHING_RULE",message:`No '${s}' rule found for path '${i}'`,recoverable:!0}}}catch(d){return{success:!1,error:{code:"EVALUATION_ERROR",message:d instanceof Error?d.message:String(d),recoverable:!1}}}}}const vu=new Set([".read",".write",".validate",".indexOn"]);function Sa(e,t,n=[]){const r=ru(e),s=r.valid?Jl(e,t,n):r.errors,i=r.valid?du(e,t):[];return{raw:e,parsed:{...r,errors:s,warnings:i}}}function Ea(e,t,n){const r={path:t,pathVariables:[...n],children:[]};for(const[i,a]of[[".read","read"],[".write","write"],[".validate","validate"]]){const l=e[i];l!==void 0&&(r[a]=Sa(String(l),a,n))}const s=e[".indexOn"];s!==void 0&&(r.indexOn=Array.isArray(s)?s.map(String):[String(s)]);for(const[i,a]of Object.entries(e)){if(vu.has(i)||typeof a!="object"||a===null)continue;const l=t==="/"?`/${i}`:`${t}/${i}`,c=i.startsWith("$")?[...n,i]:[...n];r.children.push(Ea(a,l,c))}return r}function Ca(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 Ea(t.rules,"/",[])}function Mn(e){return e==="true"?!0:e==="false"?!1:e}function Na(e){const t={};e.read&&(t[".read"]=Mn(e.read.raw)),e.write&&(t[".write"]=Mn(e.write.raw)),e.validate&&(t[".validate"]=Mn(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]]=Na(n)}return t}function wu(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:Na(e)}}function Br(e,t){return new gu().execute(e,t)}function ve(){const e=new Error("PERMISSION_DENIED: Permission denied");return e.code="PERMISSION_DENIED",e}class xu{compiled=null;setRules(t){if(t===null){this.compiled=null;return}this.compiled=Ca(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=Br(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 ju{tree=new iu;rules=new xu;activeRules=null;valueListeners=new Set;childListeners=new Set;priorities=new cu;mutations=new ou;events;writeSubscribers=new Set;resetGeneration=0;constructor(t){this.events=new lu(t)}notifyWrite(){for(const t of this.writeSubscribers)try{t()}catch{}}}function Lr(e,t){if(e===t)return 0;if(e===null)return-1;if(t===null)return 1;const n=ks(e),r=ks(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 ks(e){return e===null?0:typeof e=="boolean"?1:typeof e=="number"?2:typeof e=="string"?3:4}const ku=/^-?(0*)\d{1,10}$/,_u=-2147483648,Su=2147483647;function _s(e){if(ku.test(e)){const t=Number(e);if(t>=_u&&t<=Su)return t}return null}function rn(e,t){if(e===t)return 0;const n=_s(e),r=_s(t);return n!==null?r!==null?n-r===0?e.length-t.length:n-r:-1:r!==null?1:e<t?-1:1}function _t(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(l=>l.length>0);let a=n;for(const l of i){if(a===null||typeof a!="object"||Array.isArray(a))return null;a=a[l]??null}return a}}}function Ve(e,t,n=()=>null){if(e===null||typeof e!="object"||Array.isArray(e))return[];let s=Object.entries(e).map(([a,l])=>({key:a,value:l,priority:n(a)}));const i=t.orderBy?.kind==="key";s.sort((a,l)=>{if(i)return rn(a.key,l.key);const c=_t(t.orderBy,a.key,a.value,a.priority),u=_t(t.orderBy,l.key,l.value,l.priority),d=Lr(c,u);return d!==0?d:rn(a.key,l.key)});for(const a of t.bounds)s=s.filter(l=>Eu(a,l,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 Eu(e,t,n){const s=n?.kind==="key"?rn(t.key,String(e.value)):Lr(_t(n,t.key,t.value,t.priority),e.value),i=a=>rn(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 Ss(e){return e.length===0?null:Object.fromEntries(e.map(({key:t,value:n})=>[t,n]))}function Cu(e,t){return e.length===t.length&&e.every((n,r)=>{const s=t[r];return n.key===s.key&&n.priority===s.priority&&st(n.value,s.value)})}function Fr(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 Nu{state;constructor(t){this.state=t}onValue(t,n,r,s,i,a){const l=Date.now(),c=this.state.rules.evaluate("read",n==="/"?"/":n,{auth:t,mockData:this.state.tree.snapshot()});if(c.check!=="allow"){let u;s&&(u={query:s}),this.state.events.operation(t,"listen",n,he(c.check),c,{at:l,durationMs:Date.now()-l,request:u,origin:"listener"});const d={engine:"rtdb",matchedPath:c.matchedPath,matchedRule:c.matchedRule,pathVariableBindings:c.pathVariableBindings,reason:c.reason,errorCode:c.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:c.reasons},reasons:c.reasons,rules:d}),i)return queueMicrotask(()=>{a&&a(),i(Fr(n))}),()=>{};throw ve()}return this.attach(t,n,r,s,{origin:"listener",result:"allow",evaluation:c,at:l},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,l){const c=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:c,auth:t,cb:r,path:n,query:s,cancelCallback:a,onCanceled:l};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=Ve(this.state.tree.read(n),s,this.state.priorities.forChild(n));u.lastWindow=d,this.deliverInitial(u,{val:Ss(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(l=>Ru(s,l)))continue;if(r.query){const l=Ve(this.state.tree.read(r.path),r.query,this.state.priorities.forChild(r.path));if(Cu(r.lastWindow??[],l)){this.state.events.listener("suppressed",r,r.auth,{event:"value",reason:"no-op",detail:{query:!0}});continue}r.lastWindow=l,this.deliver(r,{val:Ss(l),exists:l.length>0,key:this.key(r.path),rows:l},{query:!0});continue}const i=this.snapshot(r.path),a=this.state.priorities.stateAtOrBelow(r.path);if(st(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 Ru(e,t){if(e===t||e==="/")return!0;const n=`${e}/`,r=t==="/"?"/":`${t}/`;return t.startsWith(n)||e.startsWith(r)}function He(e,t){const n=e.findIndex(r=>r.key===t);return n>0?e[n-1].key:null}function mt(e,t){const n=e.findIndex(r=>r.key===t);return n>0?e[n-1].key:null}function Es(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 Au{state;constructor(t){this.state=t}onChild(t,n,r,s,i,a,l){const c=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:c,durationMs:Date.now()-c,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(()=>{l&&l(),a(Fr(r))}),()=>{};throw ve()}this.state.events.operation(t,"listen",r,"allow",d,{at:c,durationMs:Date.now()-c,origin:"listener",detail:{event:n}});const p={id:u,auth:t,event:n,path:r,cb:s,spec:i,cancelCallback:a,onCanceled:l};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=Ve(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:He(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:mt(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,l=new Map(this.directChildren(s).map(({key:f,val:m})=>[f,m])),c=[...l].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 l)a.has(f)?st(a.get(f),m)||d.child_changed.push({key:f,val:m,previousChildName:mt(c,f)}):d.child_added.push({key:f,val:m,previousChildName:mt(c,f)});for(const[f,m]of a)l.has(f)||d.child_removed.push({key:f,val:m,previousChildName:mt(u,f)});const p=Es(s,n);p!==null&&a.has(p)&&l.has(p)&&d.child_moved.push({key:p,val:l.get(p),previousChildName:mt(c,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)?[]:Ve(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=Ve(this.state.tree.read(t.path),t.spec,this.state.priorities.forChild(t.path));t.lastWindow=s;const i=new Map(r.map(c=>[c.key,c.value])),a=new Map(s.map(c=>[c.key,c.value])),l=[];if(t.event==="child_added")for(const c of s)i.has(c.key)||l.push({key:c.key,val:c.value,previousChildName:He(s,c.key)});else if(t.event==="child_changed")for(const c of s)i.has(c.key)&&!st(i.get(c.key),c.value)&&l.push({key:c.key,val:c.value,previousChildName:He(s,c.key)});else if(t.event==="child_removed")for(const c of r)a.has(c.key)||l.push({key:c.key,val:c.value,previousChildName:He(r,c.key)});else if(t.spec?.orderBy&&t.spec.orderBy.kind!=="key"){const c=t.spec.orderBy.kind==="priority"?Es(t.path,n):null;let u=!1;if(c!==null){const d=s.find(p=>p.key===c);d&&i.has(c)&&(l.push({key:d.key,val:d.value,previousChildName:He(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=_t(t.spec.orderBy,f.key,f.value,f.priority),y=_t(t.spec.orderBy,p.key,p.value,p.priority);Lr(m,y)!==0&&l.push({key:p.key,val:p.value,previousChildName:He(s,p.key)})}}}for(const c of l)this.deliver(t,c,{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 Iu(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 l=!1;i&&a&&(l=!0);const c=r.priorities,u=c!==null,d=c!==void 0;let p=!1;if(u&&d){const m=typeof c=="object",y=Array.isArray(c);m&&(y||(p=!0))}let f=!1;if(l&&p&&(f=!0),f){const m={},y=Object.entries(c);for(const[j,_]of y){const N=typeof _=="string",P=typeof _=="number";let I=!1;P&&Number.isFinite(_)&&(I=!0);let D=!1;N&&(D=!0),I&&(D=!0),D&&(m[j]=_)}const g=r.data;let v=null;g!==void 0&&g!==null&&(v=g);const w=r.rules;let x=null;if(w!==void 0&&w!==null){const _=typeof w=="object",N=Array.isArray(w);let P=!1;if(_&&(N||(P=!0)),P){const I=w;if("rules"in I){const C=I.rules;if(C!==null&&C!==void 0){const R=typeof C=="object",V=Array.isArray(C);let G=!1;R&&(V||(G=!0)),G&&(x={rules:C})}}}}return{data:v,priorities:m,rules:x}}}return{data:e,priorities:{},rules:null}}class Du{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=Iu(t);let s={};const i=r.data===null,a=r.data===void 0;let l=!1;i||a||(l=!0),l&&(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 Pu=/[\[\].#$/\u0000-\u001F\u007F]/;function $u(e){return e.length!==0&&!Pu.test(e)}function Ou(e){return typeof e=="number"&&(Number.isNaN(e)||e===1/0||e===-1/0)}function Uu(e){return e===".priority"||e===".value"||e===".sv"}function Mu(e,t){ar(e,t,"set")}function ar(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(Ou(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&&ar(s,`${t}/${r}`,n)}return}for(const[r,s]of Object.entries(e)){if(!Uu(r)&&!$u(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 "]"`);ar(s,`${t}/${r}`,n)}}}function Te(e,t){return Mu(e,t),or(e)}function or(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=or(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=or(r);s!==null&&(t[n]=s)}return Object.keys(t).length===0?null:t}function Yt(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(a=>Yt(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 l=0;l<=s;l++){const c=t[String(l)];a[l]=c===void 0?null:Yt(c)}return a}const i={};for(const[a,l]of Object.entries(t))i[a]=Yt(l);return i}function Tu(e){return e===null||typeof e!="object"?!1:e[".sv"]==="timestamp"}function Bu(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(Tu(e))return t;if(Bu(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 Cs(){return new Error("permission_denied")}class Lu{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),l=a.length===0?null:a[a.length-1];let c=null,u,d=0,p=!1;do{d+=1;const x=this.state.mutations.begin();c=this.state.tree.read(n);const k=c===null?null:Yt(Ne(c));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:c,exists:c!==null},detail:{committed:!1,aborted:!0}}),{committed:!1,val:c,key:l};const m=Date.now(),y=Te(we(u,m,c),n==="/"?"":n);if(i){const x=this.state.tree.snapshot(),k=Object.fromEntries(this.state.priorities.entries()),j=this.state.priorities.get(n),_=this.children.snapshotParents();this.state.tree.write(n,y),this.state.priorities.replace(n,j),this.values.fanOut([n]),this.children.fanOut(_);const N=Date.now(),P=this.state.rules.evaluate("write",n==="/"?"/":n,{auth:t,mockData:x,newData:y});if(P.check!=="allow"){this.state.events.operation(t,"transaction",n,he(P.check),P,{at:N,durationMs:Date.now()-N,origin:"transaction",request:{data:u,resourceData:u},resourceBefore:{data:c,exists:c!==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),Cs()}return this.recordCommit(t,n,u,c,y,f,m,N,!0,P),{committed:!0,val:y,key:l}}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:c,exists:c!==null},resourceAfter:{data:y,exists:y!==null},groupId:f,groupKind:"transaction"}),Cs();this.state.events.operation(t,"transaction",n,"allow",v,{at:g,durationMs:Date.now()-g,origin:"transaction",request:{data:u,resourceData:u},resourceBefore:{data:c,exists:c!==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,c,y,f,m,!1),this.state.notifyWrite(),{committed:!0,val:y,key:l}}recordCommit(t,n,r,s,i,a,l,c,u,d){this.state.events.operation(t,"transaction",n,"allow",d,{at:c,durationMs:Date.now()-c,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,l,u),this.state.mutations.mark(n),this.state.notifyWrite()}finishEvents(t,n,r,s,i,a,l,c){this.state.events.commit(t,"transaction",n,{data:r,priorState:s,nextState:i,groupId:a,groupKind:"transaction",replay:{requestTime:l},detail:{committed:!0,applyLocally:c}}),this.state.events.mutation(t,"transaction",xe(n),{before:s,after:i,detail:{committed:!0}})}}class Fu{state;values;children;constructor(t,n,r){this.state=t,this.values=n,this.children=r}adminSet(t,n){if(nn(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){nn(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}),l=this.state.priorities.get(n),c={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:l}};if(a.check!=="allow")throw this.state.events.operation(t,"setPriority",n,he(a.check),a,c),ve();if(this.state.events.operation(t,"setPriority",n,"allow",a,c),s===null)return;const u=this.children.snapshotParents(),d=l!==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:l,nextState:r,detail:{priority:r,priorPriority:l}}),this.state.events.mutation(t,"setPriority",xe(n),{before:l,after:r,detail:{priorityMetadata:!0}})),this.state.notifyWrite()}}function Ns(e){return e.length===0?null:Object.fromEntries(e.map(({key:t,value:n})=>[t,n]))}class Vu{state;values;children;priorityWrites;constructor(t,n,r){this.state=t,this.values=n,this.children=r,this.priorityWrites=new Fu(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,Te(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=Ve(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:Ns(r),exists:r.length>0}}),r}adminSet(t,n){this.adminSetWithPriority(t,n,null,!1)}adminSetWithPriority(t,n,r,s=!0){nn(r);const i=Date.now(),a=this.state.tree.read(t),l=Te(we(n,i,a),t==="/"?"":t),c=l===null?"remove":"set";this.state.events.operation(null,c,t,"not-applicable",void 0,{origin:"admin",request:{data:n,resourceData:n},resourceBefore:{data:a,exists:a!==null},resourceAfter:{data:l,exists:l!==null}});const u=this.children.snapshotParents(),d=this.state.priorities.get(t),p=this.state.priorities.stateAtOrBelow(t);this.state.tree.write(t,l),this.state.priorities.replace(t,l===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 l=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),l);const c=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:c}),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=Ve(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:Ns(a),exists:a.length>0}}),a}set(t,n,r){this.setInternal(t,n,r,"set",null,!1)}setWithPriority(t,n,r,s){nn(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=Te(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,l])=>{const c=J([...L(n),...L(a)]);return{path:c,value:Te(we(l,Date.now(),this.state.tree.read(c)),c)}});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("/")),l=this.state.tree.snapshot(),c=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 c){const g=Date.now(),v=this.state.tree.read(y.path),b=this.state.rules.evaluate("write",y.path,{auth:t,mockData:l,newData:y.value,...a?{updates:c}:{}}),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(c),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 l=Date.now(),c=Te(we(r,l,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,c),m={at:p,durationMs:Date.now()-p,request:{data:r,resourceData:r},resourceBefore:{data:u,exists:u!==null},resourceAfter:{data:c,exists:c!==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,c),this.state.priorities.replace(n,c===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:l},...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,Te(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(Fr(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 qu{state;values;children;writes;transactions;persistence;constructor(t){this.state=new ju(t),this.values=new Nu(this.state),this.children=new Au(this.state),this.writes=new Vu(this.state,this.values,this.children),this.transactions=new Lu(this.state,this.values,this.children),this.persistence=new Du(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,l){return this.children.onChild(t,n,r,s,i,a,l)}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 Yl()}listenerCount(){return this.values.count()}childListenerCount(){return this.children.count()}}const Rs=new WeakMap;function Ra(e){let t=Rs.get(e);if(t)return t;t=new qu(e),Rs.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 Aa(e){return Ra(e).getActiveRules()}function As(e){return Ra(e).snapshotState()}function Ia(e){return typeof e=="string"?e:e._internalPath.segments.join(".")}function sn(e,...t){const n=ca(e),r=Xl(e),s=Ql(e);let i,a;try{i=t.map(u=>u.prepareSandbox?.(n)??u)}catch(u){throw fs(u)}const l=u=>{let d=s(u);for(const p of i)d=p.applySandbox(d);return d};try{a=l(ua(n))}catch(u){throw fs(u)}const c=Zl(a,n,u=>l(u));return r?ec(c,n,r):c}function Wu(e,t,n){return Da(Ia(e),t,n,!1)}function Da(e,t,n,r){return{type:"where",applySandbox:i=>i.where(e,t,n),prepareSandbox:r?void 0:i=>{const a=da(n,i,t==="in"||t==="not-in");return Da(e,t,a.executionValue,!0)},_sandboxFilter:{kind:"where",field:e,op:t,value:n}}}function Is(e,t){const n=Ia(e);return{type:"orderBy",applySandbox:r=>r.orderBy(n,t)}}function an(e){return{type:"limit",applySandbox:t=>t.limit(e)}}function zu(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 Ku(...e){return zu(e)?Pa(e[0],!1,!0):$a(e,!1,!0)}function Pa(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=kc(e),i=s.data(),a=Object.freeze({id:s.id,ref:s.ref,exists:i!==void 0,data:()=>i});return Pa(a,t,n,!0)}}}function $a(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=>$a(e.map(i=>da(i,s).executionValue),t,n,!0)}}function Hu(e,t,n,r){const s=ca(e);Tr(s).markStarted();const i=Ju(s,e),a=Yu(t,n,r,s,e),l=Xu(a,s),c=l.length===3?i.onSnapshot(l[0],l[1],l[2]):l.length===2?i.onSnapshot(l[0],l[1]):i.onSnapshot(l[0]);if(!s.own)return c;let u=!1;const d=()=>{u||(u=!0,c())},p=()=>{u||(d(),Gu(l)?.(new lt("aborted","The operation was aborted.")))},f=s.own(p);return()=>{f(),d()}}function Gu(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 Ju(e,t){const n=tc(t);if(e.kind==="sandbox")return n;const r=nc.get(n);if(!r)throw new TypeError("pyric/firestore: live ref missing rebuild closure for onSnapshot.");return r(ua(e))}function Oa(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 Yu(e,t,n,r,s){if(typeof e=="object"&&e!==null&&!Oa(e)){const a=t;return typeof a=="function"?[e,Ds(a,r,s),n??lr]:a&&typeof a=="object"?[e,Ps(a,r,s)]:[e]}return typeof e=="function"?[Ds(e,r,s),t??lr]:e&&typeof e=="object"?[Ps(e,r,s)]:[e]}function Xu(e,t){if(t.kind!=="sandbox-live")return e;const n=e[0];return typeof n=="object"&&n!==null&&!Oa(n)?[{...n,[ps]:!0,...t.authScope?{[hs]:t.authScope}:{}},...e.slice(1)]:[{[ps]:!0,...t.authScope?{[hs]:t.authScope}:{}},...e]}function Ua(e,t,n){if(!e||typeof e!="object")return e;const r=e;if(typeof r.data=="function"&&bs(e,t),Array.isArray(r.docs)){for(const s of r.docs)bs(s,t);_c(e,e,t,n,"listener")}return e}function lr(e){console.error("pyric/firestore: Uncaught Error in snapshot listener:",e)}function Ds(e,t,n){return r=>{e(Ua(ga(r,t),t,n)),Tr(t).notifySnapshotDelivered()}}function Ps(e,t,n){return{...e,next:e.next?r=>{e.next(Ua(ga(r,t),t,n)),Tr(t).notifySnapshotDelivered()}:void 0,error:e.error??lr}}const Se={description:"Identity to act as. Omit or 'admin' = admin write that BYPASSES rules (sandbox seeding). { uid, claims? } = act as that user with rules ENFORCED.",oneOf:[{type:"string",enum:["admin"]},{type:"object",properties:{uid:{type:"string"},claims:{type:"object",description:"Custom claims forwarded to the rule context (request.auth.token)."}},required:["uid"]}]},Qu=["<","<=","==","!=",">=",">","in","not-in","array-contains","array-contains-any"],Zu={type:"object",properties:{field:{type:"string"},op:{type:"string",enum:[...Qu]},value:{}},required:["field","op","value"]};function Ma(e){const{resolveDb:t}=e;return[{name:"firestore_get_document",description:"Get a Firestore document by path. Admin by default; pass `as:{uid}` to read with rules enforced as that user.",parameters:{type:"object",properties:{path:{type:"string",description:'e.g. "users/alice"'},as:Se},required:["path"]},async execute(n){const r=n,s=await t(r.as),i=Be(s,r.path),a=await va(i),l=typeof a.exists=="function"?a.exists():a.exists;return{ok:!0,summary:l?`Got ${r.path}`:`No document at ${r.path}`,data:{exists:l,data:l?a.data():null}}}},{name:"firestore_list_documents",description:"List documents in a collection. Supports orderBy + limit. Admin by default; pass `as:{uid}` to enforce rules.",parameters:{type:"object",properties:{collection:{type:"string"},orderBy:{type:"string"},limit:{type:"number"},as:Se},required:["collection"]},async execute(n){const r=n,s=await t(r.as),i=kt(s,r.collection),a=[];r.orderBy&&a.push(Is(r.orderBy)),r.limit&&a.push(an(r.limit));const l=await Zt(sn(i,...a));return{ok:!0,summary:`${l.size} docs in ${r.collection}`,data:{docs:l.docs.map(c=>({id:c.id,data:c.data()}))}}}},{name:"firestore_create_document",description:"Create or replace a Firestore document at an explicit path. Admin by default (bypasses rules — for seeding); pass `as:{uid}` to write as that user with rules enforced.",parameters:{type:"object",properties:{path:{type:"string"},data:{type:"object"},as:Se},required:["path","data"]},async execute(n){const r=n,s=await t(r.as);return await Qt(Be(s,r.path),r.data),{ok:!0,summary:`Created ${r.path}`}}},{name:"firestore_add_document",description:"Add a document with an auto-generated id under a collection (mirrors the Web SDK addDoc). Admin by default — the right tool for seeding; pass `as:{uid}` to write as a user with rules enforced. Returns the minted path.",parameters:{type:"object",properties:{collection:{type:"string",description:'Collection to add the doc under, e.g. "users" or "users/u1/posts".'},data:{type:"object"},as:Se},required:["collection","data"]},async execute(n){const r=n,s=await t(r.as),i=await fa(kt(s,r.collection),r.data);return{ok:!0,summary:`Created ${i.path}`,data:{path:i.path,id:i.id}}}},{name:"firestore_update_document",description:"Merge fields into an existing Firestore document. Admin by default; pass `as:{uid}` to enforce rules.",parameters:{type:"object",properties:{path:{type:"string"},data:{type:"object"},as:Se},required:["path","data"]},async execute(n){const r=n,s=await t(r.as);return await ms(Be(s,r.path),r.data),{ok:!0,summary:`Updated ${r.path}`}}},{name:"firestore_delete_document",description:"Delete a Firestore document. Admin by default; pass `as:{uid}` to enforce rules.",parameters:{type:"object",properties:{path:{type:"string"},as:Se},required:["path"]},async execute(n){const r=n,s=await t(r.as);return await Zn(Be(s,r.path)),{ok:!0,summary:`Deleted ${r.path}`}}},{name:"firestore_batch_write",description:"Apply many writes (set / update / delete) in ONE call — the efficient way to seed or bulk-edit (one call, not N). Applied in order; stops on the first failure. Admin by default; pass `as:{uid}` to apply them as a user with rules enforced. Up to 500 ops.",parameters:{type:"object",properties:{operations:{type:"array",description:"Writes applied in order; stops on the first failure (NOT atomic — earlier writes are not rolled back).",minItems:1,maxItems:500,items:{type:"object",properties:{op:{type:"string",enum:["set","update","delete"]},path:{type:"string"},data:{type:"object",description:"Required for set/update; ignored for delete."}},required:["op","path"]}},as:Se},required:["operations"]},async execute(n){const r=n;if(r.operations.length===0||r.operations.length>500)return{ok:!1,summary:`firestore_batch_write: operations must be 1..500 (got ${r.operations.length}).`};const s=await t(r.as);for(const i of r.operations){const a=Be(s,i.path);i.op==="set"?await Qt(a,i.data??{}):i.op==="update"?await ms(a,i.data??{}):await Zn(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:Zu,minItems:1},orderBy:{type:"string"},limit:{type:"number"},as:Se},required:["collection","where"]},async execute(n){const r=n,s=await t(r.as),i=kt(s,r.collection),a=r.where.map(c=>Wu(c.field,c.op,c.value));r.orderBy&&a.push(Is(r.orderBy)),r.limit&&a.push(an(r.limit));const l=await Zt(sn(i,...a));return{ok:!0,summary:`${l.size} matches in ${r.collection}`,data:{docs:l.docs.map(c=>({id:c.id,data:c.data()}))}}}}]}function Ta(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=rc(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 ed="modulepreload",td=function(e){return"/__pyric/ui/"+e},$s={},Ba=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 l=document.querySelector("meta[property=csp-nonce]"),c=l?.nonce||l?.getAttribute("nonce");s=a(n.map(u=>{if(u=td(u),u in $s)return;$s[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":ed,d||(f.as="script"),f.crossOrigin="",f.href=u,c&&f.setAttribute("nonce",c),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 l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=a,window.dispatchEvent(l),!l.defaultPrevented)throw a}return s.then(a=>{for(const l of a||[])l.status==="rejected"&&i(l.reason);return t().catch(i)})};function La(e){return e.kind==="session_boundary"&&e.phase==="reset"}function nd(e,t){return La(t)?[t]:[...e,t]}const Fa=h.createContext(null),Va={status:"disabled",handles:null,events:[]};function rd({children:e}){return o.jsx(Fa.Provider,{value:Va,children:e})}function Pe(){return h.useContext(Fa)??Va}function yt(e,t){return`${e.replace(/\/$/,"")}${t}`}function sd(e){const t=e;return{async read(n){const r=await fetch(yt(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(yt(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(yt(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(yt(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(yt(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 bt(e,t){return`${e.replace(/\/$/,"")}${t}`}function id(e){const t=e;return{async list(){const n=await fetch(bt(t,"/__pyric/projects"));if(!n.ok)throw new Error(`projects.list() → ${n.status}`);return await n.json()},async open(n){const r=await fetch(bt(t,`/__pyric/projects/${encodeURIComponent(n)}`));if(!r.ok)throw new Error(`projects.open(${n}) → ${r.status}`);return{meta:await r.json(),workspace:sd(t)}},async create(n){const r=await fetch(bt(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(bt(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(bt(t,`/__pyric/projects/${encodeURIComponent(n)}`),{method:"DELETE"});if(!r.ok)throw new Error(`projects.remove(${n}) → ${r.status}`)}}}function ad(e,t){return`${e.replace(/\/$/,"")}${t}`}function Tn(e){return/auth/i.test(e)?"auth":"firestore"}function od(e){const t=e,r={"content-type":"application/json","x-pyric-writer":`studio-${Math.random().toString(36).slice(2)}`},s=new Map,i=c=>ad(t,`/__pyric/state?section=${Tn(c)}`),a=async c=>{const u=Tn(c),d=s.get(u);if(d)return d;const p=await fetch(i(c));let f=new Map;if(p.ok){const m=await p.text();m&&m!=="null"&&(f=sc(m))}else if(p.status!==404)throw new Error(`persistence.read(${c}) → ${p.status}`);return s.set(u,f),f},l=async(c,u)=>{const d=await fetch(i(c),{method:"POST",headers:r,body:ic(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(${c}) → ${d.status}`)};return{async getRecord(c,u){return(await a(c)).get(u)??null},async listRecords(c){return[...(await a(c)).keys()]},async putRecords(c,u){const d=await a(c);for(const[p,f]of u)d.set(p,f);await l(c,d)},async deleteRecords(c,u){const d=await a(c);for(const p of u)d.delete(p);await l(c,d)},async clear(c){s.set(Tn(c),new Map);const u=await fetch(i(c),{method:"POST",headers:r,body:"null"});if(!u.ok&&u.status!==423)throw new Error(`persistence.clear(${c}) → ${u.status}`)}}}const ld="local";function cd(){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 ud(){const e=cd();let t={id:ld,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 dd="/__pyric/sdk/worker.js",Ce="pyric-shared-worker",fd="/__pyric/ui/";function qa(e=typeof document>"u"?void 0:document){const t=e?.querySelector('meta[name="pyric-worker-v"]')?.getAttribute("content")?.trim()||null;return{studioUrl:fd,worker:{url:dd,name:Ce,servedEpoch:t}}}const on="pyric:worker-generation",gt="pyric:worker-generation-probe";function hd(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(on);return r&&/^[a-f0-9]{16}$/.test(r)?`${Ce}:${r}`:n?(t.setItem(on,n),`${Ce}:${n}`):Ce}catch{return n?`${Ce}:${n}`:Ce}}function pd(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(on,e),t.getItem(on)!==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 md(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(gt);if(e.setItem(gt,"ok"),e.getItem(gt)!=="ok")throw new Error("the worker generation probe could not be read back");t===null?e.removeItem(gt):e.setItem(gt,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 yd(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 bd(){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 Wa=new WeakMap;let cr;function gd(e,t,n=bd()){const r=e.name,s=n===t?void 0:{},i=new Map,a=new Set,l={app:e,sandbox:t,session:n,services:i,cleanups:a,assertAlive(){if(l.deleted)throw new lt("app/app-deleted",`Firebase: Firebase App named '${r}' already deleted (app/app-deleted).`)},...s?{authScope:s}:{},service(c,u){const d=i.get(c);if(d!==void 0)return d;l.assertAlive();const p=u();return i.set(c,p),p},onDelete(c){return l.deleted?(c(),()=>{}):(a.add(c),()=>a.delete(c))},deleted:!1};return Wa.set(e,l),l}function vd(e){cr=e}ac({resolve(e,t){const n=typeof e=="object"&&e!==null?Wa.get(e):void 0;if(n)return n},defaultApp(){if(!cr)throw new TypeError("No default sandbox app registry is installed - import and initialize pyric/app before calling a service factory without an app.");return cr()}});const wd="[DEFAULT]",xd=new Map;function jd(e,t){return new lt(`app/${e}`,`Firebase: ${t} (app/${e}).`)}function kd(e){return jd("no-app",`No Firebase App '${e}' has been created - call initializeApp() first`)}function _d(e=wd){const t=xd.get(e);if(!t)throw kd(e);return t.app}vd(_d);let Sd=0,Ed=0;function M(){return`op-${++Sd}`}function ut(){return`sub-${++Ed}`}const it=new Map,St=new Map,Et=new Map,dt=new WeakSet,ur=new Set;function Cd(e){return ur.add(e),()=>ur.delete(e)}function za(){return Object.assign(new Error("Firebase App was deleted"),{code:"app/app-deleted"})}function Dt(e,t,n,r){return dt.has(e)?!1:(St.set(t,n),e.postMessage(r),!0)}function Nd(e,t,n,r){return dt.has(e)?!1:(Et.set(t,{port:e,next:n}),e.postMessage(r),!0)}function Pt(e,t){St.delete(t),Et.delete(t),dt.has(e)||e.postMessage({t:"unsub",subId:t})}function Rd(e){dt.add(e);const t=za();for(const[n,r]of[...it])r.port===e&&(it.delete(n),r.reject(t));for(const[n,r]of[...St])r.port===e&&(St.delete(n),r.service==="firestore"&&r.error?.(new lt("aborted","The operation was aborted.")));for(const[n,r]of[...Et])r.port===e&&Et.delete(n);e.onmessage=null}function Os(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 Vr(e){e.onmessage=t=>{const n=t.data;if(n.t==="res"){const r=it.get(n.id);if(!r)return;if(it.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),Os("read",s),r.reject(s)}}else if(n.t==="snap"){const r=St.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),Os("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=Et.get(n.subId);r&&r.next(n.events)}else if(n.t==="runtime-reload")for(const r of ur)r(n)}}let at;function Us(e){at=e&&e.mode==="app-session"?void 0:e}function Ad(){return at}let dr;function Id(e){dr=e}function qr(e){return dr&&(e.t==="op"||e.t==="sub")?{...e,issuer:dr}:e}function Wr(e,t){return dt.has(e)?Promise.reject(za()):new Promise((n,r)=>{const s=t;it.set(s.id,{port:e,resolve:n,reject:r}),e.postMessage(t)})}function W(e,t){return Wr(e,qr(t))}function Ka(e,t,n,r){const s=t.id;let i;const a=new Promise((l,c)=>{i=setTimeout(()=>{it.delete(s)&&c(new Error(r))},n)});return Promise.race([W(e,t),a]).finally(()=>{i&&clearTimeout(i)})}function de(e,t){if(dt.has(e)&&!t.method.startsWith("rtdb."))return Promise.reject(new lt("failed-precondition","The client has already been terminated."));const n=at?{...t,actAs:at}:t;return W(e,n)}async function Dd(e,t,n={}){const r=n.timeoutMs??12e3;await Ka(e.port,{t:"op",id:M(),method:"retireRuntime",targetEpoch:t},r,`Timed out waiting for the Pyric worker to retire after ${r}ms.`)}function Pd(e){return Cd(t=>e(t.epoch))}function $d(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 Vr(s),s.start(),{__kind:"client-db",port:s}}async function Od(e,t={}){const n=M(),r=t.timeoutMs??2e3;return(await Ka(e.port,{t:"op",id:n,method:"getRuntimeEpoch"},r,`Timed out waiting for the Pyric SharedWorker version handshake after ${r}ms.`)).version}async function Ud(e){return(await W(e.port,{t:"op",id:M(),method:"getVersion"})).instanceId??""}async function Md(e){return(await W(e.port,{t:"op",id:M(),method:"exportState"})).bundle}async function Td(e,t){await W(e.port,{t:"op",id:M(),method:"importState",bundle:t})}async function Bd(e,t){await W(e.port,{t:"op",id:M(),method:"saveBranch",name:t})}async function Ld(e){return(await W(e.port,{t:"op",id:M(),method:"listBranches"})).branches??[]}async function Fd(e,t){await W(e.port,{t:"op",id:M(),method:"switchBranch",name:t})}async function Vd(e,t){await W(e.port,{t:"op",id:M(),method:"deleteBranch",name:t})}async function qd(e,t,n){return await W(e.port,{t:"tool",id:M(),name:t,args:n})}function Wd(e,t){return Wr(e.port,{...t,issuer:void 0,relaySource:"remote",t:"op",id:M()})}function zd(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=ut();return Dt(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"}})),()=>{Pt(e.port,r)}}function Kd(e){const t=(e??"/").split("/").filter(Boolean).join("/");return t?`/${t}`:"/"}const Hd=[];function Gd(e){for(const t of[...Hd])t.port===e&&t.close()}const Jd=5e3;function Yd(){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 Xd(e,t={}){let n;try{const r=Wr(e.port,{t:"disconnect",id:M()}),s=new Promise((i,a)=>{n=setTimeout(()=>a(Yd()),t.ackTimeoutMs??Jd)});await Promise.race([r,s])}finally{n!==void 0&&clearTimeout(n),Gd(e.port),Rd(e.port),e.port.close()}}function zr(e){return e.split("/").at(-1)??e}function Qd(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:zr(r),path:r}}function Zd(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:zr(r),path:r}}function ef(e){return{_descriptor:{kind:"limit",n:e}}}function tf(...e){return{_descriptor:{kind:"startAfter",values:e}}}function nf(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 rf(e){return oc(JSON.parse(e.json))}const Ha=8*1024*1024;function sf(e,t){const n=new Error(`${t} is ${e} bytes — over the ${Ha/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 af(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 of(e){return rf(e)}function Kr(e,t){const n=e.exists&&e.data?of(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 Ga(e,t){const n=e.docs.map(r=>Kr(r,t));return{size:n.length,empty:n.length===0,docs:n}}async function lf(e){const t=await de(e.port,{t:"op",id:M(),method:"getDoc",path:e.descriptor.path});return Kr(t,e.port)}async function cf(e){const t=await de(e.port,{t:"op",id:M(),method:"getDocs",source:(e.__kind==="coll-ref",e.descriptor)});return Ga(t,e.port)}async function uf(e){return(await de(e.port,{t:"op",id:M(),method:"listRootCollections"})).ids}async function df(e,t){return(await de(e.port,{t:"op",id:M(),method:"listSubcollections",docPath:t})).ids}function ff(e,t,n){const r=ut(),s=e.port,i={port:s,service:"firestore",next:c=>{const u=c;"docs"in u?t(Ga(u,s)):t(Kr(u,s))},error:n},a=(e.__kind==="doc-ref"||e.__kind==="coll-ref",e.descriptor);return!Dt(s,r,i,qr(at?{t:"sub",subId:r,target:a,actAs:at}:{t:"sub",subId:r,target:a}))&&n&&queueMicrotask(()=>n(new Error("Firebase App was deleted"))),()=>{Pt(s,r)}}async function hf(e,t,n){await de(e.port,{t:"op",id:M(),method:"setDoc",path:e.descriptor.path,data:t,options:n})}async function pf(e){await de(e.port,{t:"op",id:M(),method:"deleteDoc",path:e.descriptor.path})}async function mf(e,t){const n=await de(e.port,{t:"op",id:M(),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 yf(e,t){return await W(e.port,{t:"op",id:M(),method:"admin.listDocuments",path:t})}function bf(e,t){const n=ut(),r=e.port;return Nd(r,n,t,{t:"sub",subId:n,target:"events"}),()=>{Pt(r,n)}}async function gf(e){return await W(e.port,{t:"op",id:M(),method:"getSnapshot"})}async function vf(e){return await W(e.port,{t:"op",id:M(),method:"resetAll"})??{errors:[]}}const wf=15e3;function xf(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`page-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function Ms(){return typeof location>"u"?"/":`${location.pathname}${location.search}${location.hash}`}function Ts(){return typeof document>"u"?"visible":document.visibilityState==="hidden"?"hidden":"visible"}function jf(e){const{db:t,kind:n}=e,r=e.clientId??xf(),s=e.heartbeatIntervalMs??wf;let i=!1,a=null;const l=()=>{W(t.port,{t:"op",id:M(),method:"presence.register",clientId:r,kind:n,route:Ms(),visibility:Ts()}).catch(()=>{})},c=()=>{W(t.port,{t:"op",id:M(),method:"presence.heartbeat",clientId:r}).catch(()=>{})},u=()=>{W(t.port,{t:"op",id:M(),method:"presence.update",clientId:r,route:Ms(),visibility:Ts()}).catch(()=>{})},d=()=>{W(t.port,{t:"op",id:M(),method:"presence.disconnect",clientId:r}).catch(()=>{})};l(),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||c()},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 kf(e,t){const n=ut();return Dt(e.port,n,{port:e.port,next:r=>{t(r)}},{t:"sub",subId:n,target:"presence"}),()=>{Pt(e.port,n)}}const _f=Symbol("pyric.clientUser.port");function Sf(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:M(),method:"auth.getIdToken",forceRefresh:r})},async getIdTokenResult(r){return await W(e,{t:"op",id:M(),method:"auth.getIdTokenResult",forceRefresh:r})}};return Object.defineProperty(n,_f,{value:e,enumerable:!1}),n}function Ef(e,t){return t?Sf(e,t):null}function Cf(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(),Vr(n)}const r={__kind:"client-auth",port:n,currentUser:null},s=ut();return Dt(n,s,{port:n,next:i=>{r.currentUser=Ef(n,i)}},{t:"sub",subId:s,target:"authState"}),r}async function Nf(e){return await W(e.port,{t:"op",id:M(),method:"auth.listUsers"})}async function Rf(e,t){return await W(e.port,{t:"op",id:M(),method:"auth.adminCreateUser",request:t})}async function Af(e,t,n){return await W(e.port,{t:"op",id:M(),method:"auth.adminUpdateUser",uid:t,request:n})}async function If(e,t){await W(e.port,{t:"op",id:M(),method:"auth.adminDeleteUser",uid:t})}async function Df(e){await W(e.port,{t:"op",id:M(),method:"auth.adminClearUsers"})}async function Pf(e){return await W(e.port,{t:"op",id:M(),method:"auth.getProviderConfig"})}async function $f(e,t,n){await W(e.port,{t:"op",id:M(),method:"auth.setProviderConfig",providerId:t,enabled:n})}const fr="pyric-storage";function Of(e){return e?`${fr}:${e}`:fr}const Uf=1,me="blobs",ie="metadata";function Mf(e=fr){return Bf(e).then(t=>new Tf(t))}class Tf{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 Tt(s)}async getBlob(t){const n=this.db.transaction(me,"readonly");return Bn(n.objectStore(me).get(t))}async getMetadata(t){const n=this.db.transaction(ie,"readonly");return Bn(n.objectStore(ie).get(t))}async putMetadata(t,n){const r=this.db.transaction(ie,"readwrite");r.objectStore(ie).put(n,t),await Tt(r)}async delete(t){const n=this.db.transaction([me,ie],"readwrite");n.objectStore(me).delete(t),n.objectStore(ie).delete(t),await Tt(n)}async listByPrefix(t){const n=this.db.transaction(ie,"readonly"),r=IDBKeyRange.bound(t,t+"",!1,!1);return Bn(n.objectStore(ie).getAll(r))}async reset(){const t=this.db.transaction([me,ie],"readwrite");t.objectStore(me).clear(),t.objectStore(ie).clear(),await Tt(t)}close(){this.db.close()}}function Bf(e){return new Promise((t,n)=>{const r=indexedDB.open(e,Uf);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 Bn(e){return new Promise((t,n)=>{e.addEventListener("success",()=>t(e.result)),e.addEventListener("error",()=>n(e.error))})}function Tt(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 Bs(e){switch(e){case"read":return["get","list"];case"write":return["create","update","delete"];default:return[e]}}const Lf=new Set(["&&","||","==","!=","<",">","<=",">=","+","-","*","/","%"]);function Ja(e){return{segments:e.path.segments.map(Ff),children:e.children.map(Ja),allows:e.allows.map(t=>({verbs:t.operations,condition:H(t.condition)})),functions:e.functions.map(hr)}}function Ff(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 hr(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(!Lf.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 pr(e){const t=lc(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:[Ja(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(hr),...(n.service.functions??[]).map(hr)]};return Ya(r,new Map),{_root:r,_version:n.version}}function Ya(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)Ya(r,n)}function Q(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 Q(e.target,t);case"index":return Q(e.target,t)||Q(e.index,t);case"slice":return[e.target,e.start,e.end].some(n=>Q(n,t));case"unary":return Q(e.arg,t);case"ternary":return[e.cond,e.then,e.else].some(n=>Q(n,t));case"in":return Q(e.element,t)||Q(e.collection,t);case"is":return Q(e.value,t);case"list":return e.elements.some(n=>Q(n,t));case"map":return e.entries.some(({key:n,value:r})=>Q(n,t)||Q(r,t));case"binary":return Q(e.left,t)||Q(e.right,t);case"call":return e.args.some(n=>Q(n,t));case"methodcall":return Q(e.target,t)||e.args.some(n=>Q(n,t));case"path":return e.segments.some(n=>n.kind==="interp"&&Q(n.expr,t));case"ident":case"literal":return!1}}function Xa(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&&Q(r,n)))return!0;for(const r of e.functions){const s=new Set([...n,...r.params]);for(const i of r.lets){if(Q(i.value,s))return!0;s.add(i.name)}if(Q(r.body,s))return!0}return e.children.some(r=>Xa(r,n))}function Vf(e,t,n,r,s){const i=new Set;for(const a of r)a.startsWith("storage-rules#")&&i.add(a);return Xa(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 qf="pyric-default",wn=Symbol("pyric/storage/target");function qe(e){return e.currentAuth?.()??e.context.auth}class Wf{backend;rules;constructor(t,n=null){this.backend=t,this.rules=n}}const Ls=new WeakMap,Fs=new WeakMap,zf=new WeakMap;function Kf(e,t,n){const r=Ls.get(e);if(r){const l=Fs.get(e)??null;if(t.rules!==void 0&&t.rules!==l)throw new Error(`pyric/storage: ${n} received a rules source, but this sandbox's storage service is already open ${l===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 l=t.rules,c=[],u=[],d=[];if(s=pr(l),s._version==="2+modules"){const p=oa(l);if(!p.success)throw new SyntaxError(`Storage rules module resolution failed (${p.error.code}): ${p.error.message}`);l=p.data.resolved,c=p.data.modules,u=p.data.bundledModules,d=p.data.evidenceIds,s=pr(l)}i=Vf(l,c,u,d,s)}const a=Mf(t.dbName??Of(t.projectId)).then(l=>new Wf(l,s));return Ls.set(e,a),Fs.set(e,t.rules??null),zf.set(e,i),e.registerPersistableService("storage",{snapshot:()=>null,restore:()=>{},reset:async()=>{await(await a).backend.reset()}}),a}function Ln(e){return e instanceof uc}const Vs=new WeakMap,qs=new WeakMap;function Hf(e,t={}){const n=!Ln(e),r=Ln(e)?e.sandbox:e,s=Kf(r,t,"getAdminStorageSandbox");if(n){const d=qs.get(r);if(d)return d}const i=Ln(e)?e:r.withAuth(null),a=i.operationContext.authLens.mode==="admin"?i:ha(i,{source:i.operationContext.source,authLens:{mode:"admin"},...i.operationContext.planId===void 0?{}:{planId:i.operationContext.planId}}),l=Vs.get(i);if(l)return l;const c={kind:"sandbox",sandbox:r,context:a,bucket:t.bucket??qf,servicePromise:s,admin:!0},u=Object.freeze({[wn]:c});return Vs.set(i,u),n&&qs.set(r,u),u}function ft(e,t){const n=cc(t,ys(e.context.operationContext));return{...t,...ys(n),service:"storage"}}function _e(e){const t=e[wn];if(!t)throw new TypeError("pyric/storage: not a FirebaseStorage handle — was it produced by getStorageSandbox?");return t}function $t(e){return _e(e).servicePromise}class T extends Error{}class ee{message;constructor(t){this.message=t}}function z(e){return e instanceof ee}function Ie(e){if(typeof e=="number")return e;if(e instanceof ke)return e.value}function De(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function nt(e,t){if(e===t)return!0;if(e==null||t==null)return e==null&&t==null;const n=Ie(e),r=Ie(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)=>nt(s,t[i]));if(De(e)&&De(t)){const s=Object.keys(e),i=Object.keys(t);return s.length===i.length&&s.every(a=>Object.prototype.hasOwnProperty.call(t,a)&&nt(e[a],t[a]))}return!1}function ae(e){return e===null?"null":e===void 0?"undefined":e instanceof ke?"float":typeof e}function Gf(e,t){if(e.target.kind==="ident"&&e.target.name==="timestamp"&&!(e.target.name in t.locals)&&!(e.target.name in t.params))return Qf(e,t);if(e.target.kind==="ident"&&e.target.name==="duration"&&!(e.target.name in t.locals)&&!(e.target.name in t.params))return Xf(e,t);if(e.target.kind==="ident"&&e.target.name==="firestore"&&!(e.target.name in t.locals)&&!(e.target.name in t.params))return Jf(e,t);if(e.method==="matches")return Zf(e,t);if(e.method==="split")return eh(e,t);if(e.method==="size")return th(e,t);if(e.method==="keys")return nh(e,t);if(e.method==="hasAll")return rh(e,t);if(e.method==="get")return sh(e,t);throw new T(`unsupported method .${e.method}()`)}function Jf(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=Yf(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 Yf(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 Ws={w:10080*60*1e3,d:1440*60*1e3,h:3600*1e3,m:60*1e3,s:1e3,ms:1,ns:1e-6};function Xf(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=Ws[s];if(i===void 0)throw new T(`duration.value() got unknown unit "${s}" — expected one of ${Object.keys(Ws).join(", ")}`);return r*i}function Qf(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 Zf(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(l){throw new T(`matches() invalid regex pattern: ${l.message}`)}return a.test(n)}function eh(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(l){throw new T(`split() invalid regex pattern: ${l.message}`)}return n.split(a)}function th(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(De(n))return Object.keys(n).length;throw new T(`size() requires a string, list, or map target, got ${ae(n)}`)}function nh(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(!De(n))throw new T(`keys() requires a map target, got ${ae(n)}`);return Object.keys(n)}function rh(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=>nt(i,s)))}function sh(e,t){const n=B(e.target,t);if(z(n))return n;if(!De(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 ih(e){return e.split("/").filter(t=>t.length>0)}function Fn(e){return"/"+e.map(t=>t.kind==="literal"?t.value:t.kind==="param"?`{${t.name}}`:`{${t.name}=**}`).join("/")}function ah(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 Qa(e,t,n=new Date,r){const s=n.getTime(),i=ih(t.request.path),a=[],l=new Set,c=new Set(Bs(t.request.method));function u(p,f,m){const y=ah(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(Bs));if(![...c].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:l}):!0;if(z(j)){a.push(`match ${Fn(p.segments)} ${t.request.method}: ${j.message}`);continue}k=Xe(j)}catch(j){if(j instanceof T){a.push(`match ${Fn(p.segments)} ${t.request.method}: ${j.message}`);continue}throw j}if(k)return!0;a.push(`match ${Fn(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 zs(e,t){if(!De(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 Xe(e){return z(e)?!1:e!==!1&&e!==null&&e!==void 0&&!(typeof e=="number"&&Number.isNaN(e))}const Ks=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"?uh(t.input,t.now):e.name==="resource"?t.input.resource===null?new ee("Null value error."):ch(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."):zs(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:zs(n,String(r))}case"call":return oh(e,t);case"methodcall":return Gf(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:!Xe(n)}case"ternary":{const n=B(e.cond,t);return z(n)?n:Xe(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=>nt(s,n)):De(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:lh(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:Xe(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 Xe(i)?i:s}return Xe(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 nt(n,r);case"!=":return!nt(n,r);case"<":return Bt(n,r)<0;case">":return Bt(n,r)>0;case"<=":return Bt(n,r)<=0;case">=":return Bt(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 Qe(n)||Qe(r)?Ue(n,r,(s,i)=>s/i):Ie(r)===0?new ee("Division by zero."):Ue(n,r,(s,i)=>Math.trunc(s/i));case"%":return Qe(n)||Qe(r)?Ue(n,r,(s,i)=>s%i):Ie(r)===0?new ee("Modulo by zero."):Ue(n,r,(s,i)=>s%i)}}}}function oh(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>Ks)throw new T(`function ${e.name}() exceeded max call depth ${Ks}`);const s=e.args.map(l=>B(l,t)),i={};n.params.forEach((l,c)=>{i[l]=s[c]});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 l of n.lets)i[l.name]=B(l.value,a);return B(n.body,a)}function lh(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 De(e);default:return new ee(`'is ${t}' is not supported by the storage evaluator.`)}}function Qe(e){return e instanceof ke}function Bt(e,t){const n=Ie(e),r=Ie(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=Ie(e),s=Ie(t);if(r===void 0||s===void 0)return;const i=n(r,s);return Qe(e)||Qe(t)?new ke(i):i}function ch(e){return{size:e.size,contentType:e.contentType,metadata:e.metadata,name:e.name,bucket:e.bucket,generation:e.generation,metageneration:e.metageneration,timeCreated:Hs(e.timeCreated),updated:Hs(e.updated)}}function Hs(e){if(e===void 0)return;const t=Date.parse(e);return Number.isNaN(t)?void 0:t}function uh(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 dh(e){return`storage/${e}`}class ht extends Error{code;constructor(t,n){const r=dh(t);super(`${r}: ${n}`),this.name="StorageError",this.code=r,Object.setPrototypeOf(this,ht.prototype)}}function Za(e){return new ht("object-not-found",`no object at "${e}".`)}function fh(e,t,n){return new ht("unauthorized",`${e} "${t}" denied by rules${n}.`)}function xn(e){return new ht("invalid-root-operation",`${e} cannot operate on the root reference.`)}function hh(){return new ht("canceled","User canceled the upload/download.")}function Ot(e,t,n,r){const s=n?.kind==="sandbox"?ft(n,r):r;if(n?.kind==="sandbox"&&n.admin===!0){Lt(n,t,"not-applicable",void 0,"admin",!1,s);return}if(!e.rules){Lt(n,t,"allow",void 0,"user",!1,s);return}const i=n?ph(t,n.bucket):t,a=Qa(e.rules,i,void 0,mh(n));if(!a.allowed){Lt(n,t,"deny",a.reasons,"user",!0,s);const l=a.reasons.length>0?` — ${a.reasons.join("; ")}`:"";throw fh(t.request.method,t.request.path,l)}Lt(n,t,"allow",a.reasons,"user",!0,s)}function ph(e,t){const n=e.request.path.replace(/^\/+/,"");return{...e,request:{...e.request,path:n===""?`b/${t}/o`:`b/${t}/o/${n}`}}}function Lt(e,t,n,r,s,i,a){if(e)try{Re(e.sandbox,la({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 mh(e){if(!e)return;const t=e.sandbox.admin;return{get:n=>t.getDocument(n),exists:n=>t.getDocument(n)!==null}}function jn(e){return e?{size:e.size,contentType:e.contentType,metadata:e.customMetadata,name:yh(e.fullPath,e.bucket),bucket:e.bucket,timeCreated:e.timeCreated,updated:e.updated,generation:Gs(e.generation),metageneration:Gs(e.metageneration)}:null}function yh(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 Gs(e){if(e===void 0)return;const t=Number(e);return Number.isFinite(t)?t:void 0}function bh(e){return{size:e.size,contentType:e.contentType,metadata:e.customMetadata}}function Hr(e){return{...e}}async function gh(e){vh(e,"getMetadata");const t=_e(e.storage),n=ft(t),r=await $t(e.storage),s=await r.backend.getMetadata(e.fullPath);if(Ot(r,{request:{auth:qe(t),method:"get",path:e.fullPath},resource:jn(s)},t,n),!s)throw Za(e.fullPath);return Hr(s)}function vh(e,t){if(e.fullPath==="")throw xn(t)}const wh="application/octet-stream";async function eo(e,t,n,r){kh(e,"uploadBytes");const s=_e(e.storage),i=ft(s,r),a=xh(t,n?.contentType),l=to({ref:e,blob:a,settable:n}),c=await $t(e.storage),u=await c.backend.getMetadata(e.fullPath);Ot(c,{request:{auth:qe(s),method:u?"update":"create",path:e.fullPath,resource:bh({size:l.size,contentType:l.contentType,customMetadata:l.customMetadata})},resource:jn(u)},s,i),await c.backend.put(e.fullPath,a,l);try{Re(s.sandbox,yn({service:"storage",op:"object_put",path:e.fullPath,auth:qe(s),before:u??void 0,after:l,detail:{bucket:e.bucket,size:l.size,contentType:l.contentType,overwrite:u!=null}}),i)}catch{}return{ref:e,metadata:Hr(l)}}function to(e){const{ref:t,blob:n,settable:r}=e,s=(e.now??new Date).toISOString(),i=jh(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||wh,cacheControl:r?.cacheControl,contentDisposition:r?.contentDisposition,contentEncoding:r?.contentEncoding,contentLanguage:r?.contentLanguage,customMetadata:r?.customMetadata}}function xh(e,t){return e instanceof Blob?t&&t!==e.type?new Blob([e],{type:t}):e:new Blob([e],{type:t??""})}function jh(e){return String(e.getTime())}function kh(e,t){if(e.fullPath==="")throw xn(t)}function _h(e){return e instanceof Blob?e.size:e.byteLength}function Sh(){const e=new Error("storage/canceled: User canceled the upload/download.");return e.code="storage/canceled",e}function Eh(){const e=new Error("storage/invalid-root-operation: uploadBytesResumable cannot operate on root reference.");return e.code="storage/invalid-root-operation",e}class Ch{[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=_h(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=Sh(),this._updateSnapshot("canceled",this._snapshot.bytesTransferred),this._notifyObservers("error"),this._reject(this._error),!0):!1}on(t,n,r,s){let i,a,l,c=!1;if(typeof n=="object"&&n!==null&&(c=!0),c){const f=n;f.next!==void 0&&(i=f.next),f.error!==void 0&&(a=f.error),f.complete!==void 0&&(l=f.complete)}else typeof n=="function"&&(i=n),typeof r=="function"&&(a=r),typeof s=="function"&&(l=s);const d={next:i,error:a,complete:l};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(l!==void 0){const v=l;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 l=i.next;try{l(this._snapshot)}catch{}}}if(t==="error"){for(const i of this._observers)if(i.error!==void 0&&this._error!==void 0){const c=i.error,u=this._error;try{c(u)}catch{}}}if(t==="complete"){for(const i of this._observers)if(i.complete!==void 0){const l=i.complete;try{l()}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 no(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 ro(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 Nh(e,t,n){if(e.fullPath==="")throw Eh();return new Ch(e,t,n)}class Ct{__kind="storage-ref";port;storage;bucket;fullPath;name;constructor(t,n,r,s){this.port=t,this.bucket=n,this.fullPath=r,this.name=zr(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 Ct(this.port,this.bucket,n,this.storage)}get root(){return this.fullPath===""?this:new Ct(this.port,this.bucket,"",this.storage)}toString(){return`gs://${this.bucket}/${this.fullPath}`}}function Rh(e){return e.replace(/^\/+|\/+$/g,"")}function Ah(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(),Vr(r)}return{__kind:"client-storage",port:r,bucket:n??"pyric-default"}}function Ih(e,t){const n=Rh(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 l=e.fullPath;r=n?l?`${l}/${n}`:n:l,s=e.port,i=e.bucket,a=e.storage}return new Ct(s,i,r,a)}async function Dh(e){const t=await de(e.port,{t:"op",id:M(),method:"storage.listAll",path:e.fullPath}),n=r=>new Ct(e.port,e.bucket,r.fullPath,e.storage);return{items:t.items.map(n),prefixes:t.prefixes.map(n)}}async function Ph(e){return await de(e.port,{t:"op",id:M(),method:"storage.getMetadata",path:e.fullPath})}async function $h(e){return await de(e.port,{t:"op",id:M(),method:"storage.getBlob",path:e.fullPath})}async function no(e,t,n){const r=t instanceof Blob?new Uint8Array(await t.arrayBuffer()):t instanceof ArrayBuffer?new Uint8Array(t):t;if(r.byteLength>Ha)throw sf(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:M(),method:"storage.putBytes",path:e.fullPath,dataB64:af(r),...s!==void 0?{contentType:s}:{},...n!==void 0?{metadata:n}:{}});return{ref:e,metadata:i}}async function ro(e){await de(e.port,{t:"op",id:M(),method:"storage.deleteObject",path:e.fullPath})}new Array(12).fill(0);async function Oh(e){return W(e.port,{t:"op",id:M(),method:"rtdb.adminSnapshot"})}async function Uh(e,t,n){await W(e.port,{t:"op",id:M(),method:"rtdb.set",path:t,value:n,actAs:{mode:"admin"}})}async function Mh(e,t,n){await W(e.port,{t:"op",id:M(),method:"rtdb.update",path:t,values:n,actAs:{mode:"admin"}})}async function Th(e,t){await W(e.port,{t:"op",id:M(),method:"rtdb.remove",path:t,actAs:{mode:"admin"}})}function Bh(e,t,n,r){const s=ut();return!Dt(e.port,s,{port:e.port,next:a=>n(a?.value??null),error:r},qr({t:"sub",subId:s,target:{service:"rtdb",path:Kd(t)},actAs:{mode:"admin"}}))&&r&&queueMicrotask(()=>r(new Error("FIREBASE FATAL ERROR: Database has been deleted."))),()=>Pt(e.port,s)}function Lh(e){const t=new Set;let n={servedEpoch:e.servedEpoch,runningEpoch:null,updateAvailable:!1,updating:!1,error:null};const r=c=>{n={...n,...c};for(const u of t)u()},s=e.storage,i=e.servedEpoch;let a=null;const l=()=>i?(a??=yd({targetEpoch:i,retire:()=>e.retire?e.retire(i):Dd(e.db,i),subscribeReload:e.subscribeReload??Pd,preflight:e.preflight??(()=>md(s)),commitGeneration:e.remember??(c=>pd(c,s)),onPreparationError:c=>r({updating:!1,error:c instanceof Error?c.message:String(c)}),reload:e.reload??(()=>window.location.reload()),...e.schedule?{schedule:e.schedule}:{}}),a):null;return(e.readVersion??(()=>Od(e.db)))().then(c=>r({runningEpoch:c,updateAvailable:!!(i&&c!=="dev"&&c!==i)})).catch(c=>r({error:c instanceof Error?c.message:String(c)})),{getSnapshot:()=>n,subscribe(c){return t.add(c),l(),()=>{t.delete(c),t.size===0&&(a?.dispose(),a=null)}},async update(){const c=l();if(!c||!n.updateAvailable||n.updating)throw new Error("No Pyric worker update is available.");r({updating:!0,error:null});try{await c.request()}catch(u){throw r({updating:!1,error:u instanceof Error?u.message:String(u)}),u}},dispose(){t.clear(),a?.dispose(),a=null}}}function Fh(e={}){const t=qa(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:hd(t.worker.servedEpoch,n)}}const Vh="/__pyric/sdk/worker.js";function qh(e){let t=[],n=!1;const r=new Set;let s=null;function i(){s||(s=bf(e,a=>{const l=!n;n=!0;const c=l?[]:[...t];for(const u of a)La(u)&&(c.length=0),c.push(u);t=c;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 Wh(e=Vh){if(typeof SharedWorker>"u")return null;Id("studio");let t;try{const c=Fh({workerUrl:e});t=$d(c.url,c.name)}catch{return null}let n;try{n=typeof localStorage>"u"?void 0:localStorage}catch{n=void 0}const r=Lh({db:t,servedEpoch:qa(typeof document>"u"?void 0:document).worker.servedEpoch,storage:n});Us({mode:"admin"});const s=jf({db:t,kind:"studio"}),i=qh(t),a=Cf(t);let l=!1;return{db:t,runtime:r,dispose:async()=>{l||(l=!0,s.stop(),r.dispose(),await Xd(t).catch(()=>{}))},presenceClientId:s.clientId,subscribePresence:c=>kf(t,c),instanceId:()=>Ud(t),exportState:()=>Md(t),importState:c=>Td(t,c),saveBranch:c=>Bd(t,c),listBranches:()=>Ld(t),switchBranch:c=>Fd(t,c),deleteBranch:c=>Vd(t,c),feed:i,setLens:c=>Us(c),getLens:()=>Ad(),listRootCollections:()=>uf(t),listSubcollections:c=>df(t,c),listDocuments:async c=>(await yf(t,c)).map(({path:u,phantom:d})=>({path:u,phantom:d})),readRtdbState:()=>Oh(t),setRtdbValue:(c,u)=>Uh(t,c,u),updateRtdbValue:(c,u)=>Mh(t,c,u),deleteRtdbValue:c=>Th(t,c),subscribeRtdbValue:(c,u,d)=>Bh(t,c,u,d),firestoreApi:{collection:Zd,doc:Qd,getDoc:lf,getDocs:cf,onSnapshot:ff,setDoc:hf,deleteDoc:pf,addDoc:mf,query:nf,limit:ef,startAfter:tf},auth:a,authApi:{listUsers:()=>Nf(a),subscribeUsers:(c,u)=>i.subscribe(d=>{d.kind==="service_mutation"&&d.service==="auth"&&u()}),createUser:(c,u)=>Rf(a,u),updateUser:(c,u,d)=>Af(a,u,d),deleteUser:(c,u)=>If(a,u),clearUsers:()=>Df(a),getAuthProviderConfig:()=>Pf(a),setAuthProviderConfig:(c,u,d)=>$f(a,u,d),subscribeAuthProviderConfig:(c,u)=>i.subscribe(d=>{d.kind==="service_mutation"&&d.op==="provider_config_update"&&u()})},storage:Ah(t),storageApi:{ref:Ih,listAll:Dh,getMetadata:Ph,getBlob:$h,uploadBytes:no,uploadBytesResumable:Nh,deleteObject:ro},getSnapshot:()=>gf(t),resetAll:()=>vf(t)}}const Js=5174,Ys="/sandbox",zh=4001,Kh="worker-relay";function Hh(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 mr(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=mr(t);if(n)return n}return null}for(const t of Object.values(e)){const n=mr(t);if(n)return n}return null}function Xs(e,t){const n=mr(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 Qs(e,t){return{code:e.code,severity:t,message:e.message,path:e.path,origin:"validate"}}const ge=e=>e,Zs=(...e)=>ge(e.map(t=>`(${t})`).join(" && ")),Gh=(...e)=>ge(e.map(t=>`(${t})`).join(" || ")),so=e=>e,Jh=()=>so("newData.hasChildren()"),Yh=e=>so(`newData.hasChild("${e}")`);function io(e,t){const n=e.shape,r=[],s={};for(const[l,c]of Object.entries(n)){const u=c,d=u instanceof dc,p=d?u.unwrap():u;d||r.push(l);const f=ao(p,l),m=t?.[l];if(m&&m.length>0?s[l]={validate:Zs(f,...m)}:s[l]={validate:f},p instanceof pa){const y=io(p);s[l]={validate:y.validate,children:y.children}}}const i=[Jh()];for(const l of r)i.push(Yh(l));return{validate:Zs(...i),children:s}}function ao(e,t){if(e instanceof fc)return ge("newData.isString()");if(e instanceof hc)return ge("newData.isNumber()");if(e instanceof pc)return ge("newData.isBoolean()");if(e instanceof mc){const n=e.options;return ge(n.map(r=>`newData.val() === "${r}"`).join(" || "))}if(e instanceof yc){const n=e.value;return ge(typeof n=="string"?`newData.val() === "${n}"`:`newData.val() === ${n}`)}if(e instanceof bc){const n=e._def.options;return Gh(...n.map(r=>ao(r,t)))}if(e instanceof pa)return ge("newData.hasChildren()");throw new Error(`Unsupported Zod type for RTDB rules: ${e.constructor.name} on field "${t}"`)}function Xh(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=oo(t);n.sort((s,i)=>{const a=s[0]==="/"?0:s[0].split("/").filter(Boolean).length,l=i[0]==="/"?0:i[0].split("/").filter(Boolean).length;return a-l||s[0].localeCompare(i[0])});const r={path:"/",pathVariables:[],children:[]};for(const[s]of n)s!=="/"&&Qh(r,s);for(const[s,i]of n){const a=s==="/"?r:Gr(r,s);a&&Zh(r,a,i,s)}return r}function Qh(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(c=>c.startsWith("$"));let l=r.children.find(c=>c.path===i);l||(l={path:i,pathVariables:a,children:[]},r.children.push(l)),r=l}}function Zh(e,t,n,r){const s=r.split("/").filter(i=>i.startsWith("$"));if(n.read&&(t.read=Ge(n.read,"read",s)),n.write&&(t.write=Ge(n.write,"write",s)),n.validate&&(t.validate=Ge(n.validate,"validate",s)),n.schema){const i=io(n.schema,n.fieldConstraints);t.validate||(t.validate=Ge(i.validate,"validate",s));for(const[a,l]of Object.entries(i.children)){const c=`${r}/${a}`;let u=t.children.find(d=>d.path===c);if(u||(u={path:c,pathVariables:s,children:[]},t.children.push(u)),u.validate=Ge(l.validate,"validate",s),"children"in l&&l.children)for(const[d,p]of Object.entries(l.children)){const f=`${c}/${d}`;let m=u.children.find(y=>y.path===f);m||(m={path:f,pathVariables:s,children:[]},u.children.push(m)),m.validate=Ge(p.validate,"validate",s)}}}if(n.indexOn){const i=r.split("/").filter(Boolean);if(i[i.length-1]?.startsWith("$")){const l="/"+i.slice(0,-1).join("/"),c=Gr(e,l);c&&(c.indexOn=n.indexOn)}}}function oo(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(([l,c])=>[n+l,c]);t.push(...oo(a))}}return t}function Ge(e,t,n){return Sa(String(e),t,n)}function Gr(e,t){if(e.path===t)return e;for(const n of e.children){const r=Gr(n,t);if(r)return r}return null}function ep(e){return e==null?null:typeof e=="string"?{uid:e,token:{}}:{uid:e.uid,token:e.token??{}}}function tp(e){return{operation:e.operation,path:e.path,auth:ep(e.auth),mockData:e.mockData??e.data??{},...e.newData!==void 0?{newData:e.newData}:{}}}function Vn(e,t,n,r){return(n?.parsed[r]??[]).map(s=>({path:e,rule:t,code:s.code,message:s.message}))}function yr(e,t){const n=[...Vn(e.path,".read",e.read,t),...Vn(e.path,".write",e.write,t),...Vn(e.path,".validate",e.validate,t)];for(const r of e.children)n.push(...yr(r,t));return n}class np{definition;constructor(t){this.definition=t}compile(){return Xh(this.definition.paths)}toJSON(){return wu(this.compile())}check(){try{const t=this.compile(),n=yr(t,"errors"),r=yr(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 Br(this.compile(),tp(t))}}function rp(e){return new np(e)}function sp(e){const t=e;return typeof t.toJSON=="function"&&typeof t.simulate=="function"&&typeof t.check=="function"}function ip(e){const t=e;return typeof t=="object"&&t!==null&&"rules"in t&&!("paths"in t)&&typeof t.toJSON!="function"}class qn{doc;constructor(t){this.doc=t}lint(){const t=this.doc.check();return[...t.errors.map(n=>Qs(n,"error")),...t.warnings.map(n=>Qs(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 ap(e){return e==null?null:typeof e=="string"?{uid:e,token:{}}:{uid:e.uid,token:e.token??{}}}class op{json;compiled;constructor(t){this.json=t,this.compiled=Ca(t)}toJSON(){return this.json}compile(){return this.compiled}check(){return{ok:!0,errors:[],warnings:[]}}simulate(t){return Br(this.compiled,{operation:t.operation,path:t.path,auth:ap(t.auth),mockData:t.mockData??t.data??{},...t.newData!==void 0?{newData:t.newData}:{}})}}function lp(e){return sp(e)?new qn(e):ip(e)?new qn(new op(e)):new qn(rp(e))}function cp(e,t){return e==="/"?`/${t}`:`${e}/${t}`}function ei(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function up(e){const t=(e??"/").split("/").filter(Boolean);return t.length===0?"/":`/${t.join("/")}`}function dp(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 lo(e,t,n,r,s){if(e===null||typeof e!="object"||Array.isArray(e))return{path:t,childCount:0,truncated:!1,children:[],schema:{},valueType:ei(e)};const i=Object.entries(e).sort(([p],[f])=>p.localeCompare(f)),a={},l=[];for(const[p,f]of i)f!==null&&typeof f=="object"&&!Array.isArray(f)?l.push([p,f]):a[p]=ei(f);const c=n>=r&&l.length>0,u=i.length>s,d=n>=r?[]:l.slice(0,s).map(([p,f])=>lo(f,cp(t,p),n+1,r,s));return{path:t,childCount:i.length,truncated:c||u,children:d,schema:a}}function fp(e,t={}){const n=up(t.path),r=t.maxDepth??10,s=t.maxChildren??100;return lo(dp(e,n),n,0,r,s)}function co(e){return e.children.reduce((t,n)=>t+1+co(n),0)}function uo(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=Aa(r);if(!s)return{ok:!1,summary:"No RTDB rules are loaded in the local sandbox.",data:{code:"NO_ACTIVE_RULES"}};const i=As(r),a=i!==null&&typeof i=="object"&&!Array.isArray(i)?i:{},l={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}:{}},c=lp(s).simulate([l]).cases[0];return{ok:!c.unsupported,summary:c.unsupported?`Simulation unsupported: ${c.reason}`:`Simulation: ${c.decision.toLowerCase()}`,data:{decision:c.decision,allowed:c.decision==="ALLOW",unsupported:c.unsupported,matchedPath:c.matchedPath,matchedRule:c.matchedRule,reason:c.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=fp(As(r),n);return{ok:!0,summary:`Crawled ${co(s)} object paths from ${s.path}`,data:s}}}]}function hp(e){const t=bn(e),n=r=>r&&r!=="admin"?ma(e.withAuth({uid:r.uid,token:r.claims})):ya(e);return[...ja({resolveSandbox:()=>t}),...Ma({resolveDb:n}),...Ta({resolveSandbox:()=>e}),...uo({resolveSandbox:()=>e})]}function pp(e){const t=new Map(hp(e).map(n=>[n.name,n]));return async(n,r)=>{const s=t.get(n);if(!s)throw new bp(n);const i={signal:new AbortController().signal},a=await s.execute(r,i);return{ok:a.ok,summary:a.summary,data:a.data}}}const ti=new WeakMap;async function mp(e,t,n){let r=ti.get(e);return r||(r=pp(e),ti.set(e,r)),r(t,n)}const yp=(()=>{const e=async()=>{throw new Error("SANDBOX_TOOL_NAMES: stub resolver should never be invoked")};return[...ja({resolveSandbox:e}),...Ma({resolveDb:e}),...Ta({resolveSandbox:e}),...uo({resolveSandbox:e})].map(t=>t.name)})();class bp extends Error{tool;constructor(t){super(`unknown sandbox tool: ${t}`),this.tool=t,this.name="UnknownToolError"}}const gp=500,vp=3e4,wp=2e3,xp=.5,jp=3;function kp(e,t={}){const n=_p(t.url),r=t.sandboxId??Sp(),s=t.dispatcher??mp,i=t.toolNames??[...yp],a=t.initialReconnectDelayMs??gp,l=t.maxReconnectDelayMs??vp,c=t.noReconnect??!1,u=t.onStateChange??(()=>{}),d=t.standbyPollMs??wp,p=t.fetchImpl??(A=>fetch(A)),f=t.workerRelay??null;let m=null,y=!1,g=0,v=null,b=null,w=0,x={kind:"connecting"};const k=new Map;function j(){for(const A of k.values())try{A()}catch{}k.clear()}function _(A){x=A;try{u(A)}catch{}}function N(A){if(m&&m.readyState===WebSocket.OPEN)try{m.send(JSON.stringify(A))}catch{}}function P(){if(y)return;_({kind:"connecting"});let A;try{A=new WebSocket(n)}catch(O){G(`failed to open WebSocket: ${O instanceof Error?O.message:String(O)}`);return}m=A,A.onopen=()=>{g=0;const O={type:"hello",protocol:1,tools:i,sandboxId:r,...f?{capabilities:[Kh]}:{}};N(O)},A.onmessage=O=>{let U;try{U=JSON.parse(typeof O.data=="string"?O.data:"")}catch{return}if(Hh(U)){if(U.type==="hello-ack"){_({kind:"connected",bridgeVersion:U.bridgeVersion});return}if(U.type==="tool-call"){I(U);return}if(U.type==="worker-op"){D(U);return}if(U.type==="worker-sub"){C(U);return}if(U.type==="worker-unsub"){const $=k.get(U.subId);if($){k.delete(U.subId);try{$()}catch{}}return}if(U.type==="ping"){N({type:"pong",id:U.id});return}}},A.onclose=O=>{const U=O.reason||`closed (code ${O.code})`;if(m=null,j(),O.code===zh){E();return}G(U)},A.onerror=()=>{}}async function I(A){let O;try{const U=await s(e,A.name,A.args??{});O={type:"tool-result",id:A.id,ok:!0,result:U}}catch(U){O={type:"tool-result",id:A.id,ok:!1,error:{code:U instanceof Error?U.name:"Error",message:U instanceof Error?U.message:String(U)}}}N(O)}async function D(A){if(f)try{const O=await f.op(A.op);Xs(`op '${A.op.method}'`,O),N({type:"worker-res",id:A.id,ok:!0,value:O})}catch(O){const U=O.denialContext;N({type:"worker-res",id:A.id,ok:!1,error:{code:O.code??"unknown",message:O instanceof Error?O.message:String(O),...U!==void 0?{denialContext:U}:{}}})}}function C(A){if(f&&!k.has(A.subId))try{const O=f.subscribe(A.sub,U=>{try{Xs(`subscription '${A.subId}'`,U)}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:U})});k.set(A.subId,O)}catch(O){const U=O.denialContext;N({type:"worker-snap",subId:A.subId,value:{__error:{code:O.code??"unknown",message:O instanceof Error?O.message:String(O),...U!==void 0?{denialContext:U}:{}}}})}}function S(){try{const A=new URL(n);A.protocol=A.protocol==="wss:"?"https:":"http:";const O=A.origin;return[`${O}/__pyric/health`,`${O}/health`]}catch{return[]}}function E(){if(!y){if(c){_({kind:"disconnected",reason:"replaced by a newer sandbox peer"});return}g=0,w=0,_({kind:"standby"}),R()}}function R(){if(y)return;const A=d*(1+Math.random()*xp);b=setTimeout(()=>{b=null,V()},A)}async function V(){if(y)return;let A=null;for(const O of S())try{const U=await p(O);if(!U.ok)continue;const $=await U.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>=jp){G("standby health poll unreachable");return}R()}}function G(A){if(y)return;if(c){_({kind:"disconnected",reason:A});return}g+=1;const O=Math.min(a*2**(g-1),l);_({kind:"reconnecting",attempt:g,delayMs:O}),v=setTimeout(()=>{v=null,P()},O)}return P(),{disconnect(){if(y=!0,j(),v&&(clearTimeout(v),v=null),b&&(clearTimeout(b),b=null),m){try{m.close()}catch{}m=null}_({kind:"disconnected",reason:"client closed"})},state(){return x}}}function _p(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}:${Js}${Ys}`}return`ws://localhost:${Js}${Ys}`}function Sp(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`sb-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function Ep(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,c=i&&a?`${r.hostname}:${n.port}`:r.host;return`${s}//${c}${n.pathname}`}catch{return e}}function Cp(e,t){return{url:t,dispatcher:(n,r,s)=>qd(e,r,s),workerRelay:{op:n=>Wd(e,n),subscribe:(n,r)=>zd(e,n,r)}}}async function Np(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),l=a?Ep(i,a):i,c=kp(null,{...Cp(e,l),...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",l),c}const Rp={};function Ap(){return!1}function Ip(){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 Dp(e,t={}){if(e==="local"){const n=t.baseUrl??"",r=Ap(),s=t.persistence==="memory"||r?gc():od(n),i=t.disableLive?null:Wh(t.workerUrl),a=i?Ip():null;let l=!1,c=null;return i&&a&&Np(i.db,{baseUrl:n,onStateChange:u=>a.set(u)}).then(u=>{l?u?.disconnect():c=u}),{mode:e,projects:r?ud():id(n),persistence:s,...i?{live:i}:{},...a?{bridge:a}:{},dispose(){l=!0,c?.disconnect(),i?.dispose()}}}throw new Error(`createStudioEnvironment(${e}): only 'local' is wired in v1 (T3). 'browser'/'hosted' land in A3.`)}const fo=h.createContext(null),Pp={status:"pending",env:null,error:null};function $p(e){try{return{status:"ready",env:Dp(e),error:null}}catch(t){return{status:"error",env:null,error:t instanceof Error?t:new Error(String(t))}}}function Op({mode:e="local",children:t}){const[n,r]=h.useState(null);h.useEffect(()=>{const i=$p(e);return r({mode:e,state:i}),()=>{i.status==="ready"&&i.env.dispose()}},[e]);const s=n?.mode===e?n.state:Pp;return o.jsx(fo.Provider,{value:s,children:t})}function pe(){const e=h.useContext(fo);if(!e)throw new Error("useEnvironment must be used within an <EnvironmentProvider>");return e}const Up="pyric-studio:theme",Xt="dark";function Mp(){return Xt}function Tp(){typeof document>"u"||document.documentElement.setAttribute("data-theme","dark")}const Bp=h.createContext(null);function Lp({children:e}){const[t,n]=h.useState(Mp);h.useEffect(()=>{Tp();try{localStorage.setItem(Up,Xt)}catch{}},[t]);const r="dark",s=h.useCallback(l=>n(Xt),[]),i=h.useCallback(()=>n(Xt),[]),a=h.useMemo(()=>({choice:t,resolvedTheme:r,setChoice:s,cycleChoice:i}),[t,r,s,i]);return o.jsx(Bp.Provider,{value:a,children:e})}function ho(){const e=typeof import.meta<"u"&&"/__pyric/ui/"||"/";return e.endsWith("/")?e:`${e}/`}function Fp(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 Jr(e,t="",n=ho()){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(c=>decodeURIComponent(c)),[a="",...l]=i;return{tab:a,rest:l,query:Fp(t)}}function Vp(e,t=ho()){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 br="pyric:studio:navigated",qp={tab:"",rest:[],query:{}};function po(){return typeof window<"u"?window.location.pathname+window.location.search:""}function be(){return typeof window>"u"?qp:Jr(window.location.pathname,window.location.search)}function Wp(e){return e.tab==="home"?{...e,tab:""}:e}function kn(e){return Vp(Wp(e))}function mo(){typeof window<"u"&&window.dispatchEvent(new Event(br))}function ce(e){if(typeof window>"u")return;const t=kn(e);po()!==t&&(window.history.pushState(null,"",t),mo())}function ln(e){typeof window>"u"||(window.history.replaceState(null,"",kn(e)),mo())}function Ut(e){return typeof window>"u"?()=>{}:(window.addEventListener("popstate",e),window.addEventListener(br,e),()=>{window.removeEventListener("popstate",e),window.removeEventListener(br,e)})}function zp(e,t){const n=h.useCallback(i=>e.includes(i)?i:t,[e,t]),r=h.useSyncExternalStore(Ut,()=>n(be().tab),()=>t);h.useEffect(()=>{const i=typeof window<"u"?window.location.hash:"";if(i.length>1){const l=i.slice(1),c=l.indexOf("?"),u=Jr(`/${c===-1?l:l.slice(0,c)}`,c===-1?"":l.slice(c),"/");if(e.includes(u.tab)){ln(u);return}}const a=be();a.tab!==""&&!e.includes(a.tab)&&ln({tab:n(a.tab)})},[n]);const s=h.useCallback(i=>{const a=n(i);a!==r&&ce({tab:a})},[n,r]);return[r,s]}let gr=null;function Kp(e){gr=e}function Hp(){return gr?(gr(),!0):!1}function Gp(e){return(e.metaKey||e.ctrlKey)&&!e.altKey&&!e.shiftKey&&(e.key==="k"||e.key==="K")}const Jp=[{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 Yp({assuranceEnabled:e=!1}={}){return Jp.filter(t=>t.id!=="assurance"||e)}const We=Yp({assuranceEnabled:!1}),Xp=We.map(e=>e.id);function Qp(e){return We.find(t=>t.id===e)??We[0]}function Zp(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 em=7;function tm(e,t){const n=e.trim();if(!n)return[];const r=t.filter(p=>p.id!=="settings"),s=[],i=[],a=[],[l="",...c]=n.split(/\s+/),u=c.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):Zp(n,p.label)&&i.push(f),u&&(m===l.toLowerCase()||m.startsWith(l.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,em)}function vr(e){return`${e.kind}:${e.target.tab}:${(e.target.rest??[]).join("/")}`}const wr={docsPerCollection:50,collectionsScanned:20,users:100,objects:200,storageListCalls:20,subcollections:30,subcollectionRpcCalls:40};async function nm(e,t,{maxObjects:n,maxListCalls:r}){const s=[],i=[e];let a=0;for(;i.length&&s.length<n&&a<r;){a++;const l=await t(i.shift());for(const c of l.items){if(s.length>=n)break;s.push(c.fullPath)}i.push(...l.prefixes)}return s}async function rm(e,t,n,{maxSubcollections:r,maxRpcCalls:s,docsPerCollection:i}){const a=[],l=[],c=[...e];let u=0;for(;c.length&&a.length<r&&u<s;){const d=c.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))l.push(g),c.push(g)}catch{}}}return{subcollections:a,documents:l}}const sm=5;function cn(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,l=-1;for(let u=0;u<r.length&&i<n.length;u++)r[u]===n[i]&&(a===-1&&(a=u),l=u,i++);if(i!==n.length)return 0;const c=l-a+1;return Math.max(1,400-(c-n.length)*10-Math.min(a,50))}const im={collection:"Firestore collections",document:"Firestore documents",subcollection:"Firestore subcollections",user:"Auth users",object:"Storage objects","rtdb-key":"RTDB keys"},am=["collection","document","subcollection","user","object","rtdb-key"];function om(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 yo(e){return e.endsWith("/")?{base:e.slice(0,-1),trailing:!0}:{base:e,trailing:!1}}function lm(e,t){const{base:n,trailing:r}=yo(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 l=0;l<a;l++)if(s[l].toLowerCase()!==i[l].toLowerCase())return 0;return r?s[a].toLowerCase()===i[a].toLowerCase()?850:0:cn(s[a],i[a])}function cm(e,t){const{base:n,trailing:r}=yo(e);if(!n||n.includes("/"))return 0;const s=t.split("/").pop()??t;return r?s.toLowerCase()===n.toLowerCase()?850:0:cn(n,s)}function ni(e,t,n,r=sm){const s=e.trim();if(!s)return[];const i=[],a=tm(e,t);a.length&&i.push({kind:"navigate",title:"Go to",results:a});for(const l of am){const c=l==="document"||l==="subcollection",u=l==="collection"||l==="subcollection",d=new Map;for(const f of n)f.kind===l&&d.set(vr(f),f);const p=[...d.values()].map(f=>({entry:f,score:Math.max(cn(s,f.label),f.alt?cn(s,f.alt):0,c?lm(s,f.label):0,u?cm(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:l,title:im[l],results:p.map(({entry:f})=>({id:vr(f),label:f.label,hint:om(f),target:f.target}))})}return i}function ri(e){return e.flatMap(t=>t.results)}function um(e){return{kind:"collection",label:e,target:{tab:"firestore",rest:[e]}}}function si(e){return{kind:"document",label:e,target:{tab:"firestore",rest:e.split("/").filter(Boolean)}}}function dm(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 fm(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 hm(e){return{kind:"object",label:e,target:{tab:"storage",rest:e.split("/").filter(Boolean)}}}function pm(e){return{kind:"rtdb-key",label:e,target:{tab:"rtdb",rest:[e]}}}async function mm(e,t={},n){const r={...wr,...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(um));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(si))}catch{}if(e.listSubcollections&&e.listDocumentPaths)try{const{subcollections:f,documents:m}=await rm(p,e.listSubcollections,e.listDocumentPaths,{maxSubcollections:r.subcollections,maxRpcCalls:r.subcollectionRpcCalls,docsPerCollection:r.docsPerCollection});i(f.map(dm)),i(m.map(si))}catch{}})(),l=(async()=>{if(e.listUsers)try{const d=await e.listUsers(r.users);i(d.slice(0,r.users).map(fm))}catch{}})(),c=(async()=>{if(e.listStorageObjectPaths)try{const d=await e.listStorageObjectPaths(r.objects);i(d.slice(0,r.objects).map(hm))}catch{}})(),u=(async()=>{if(e.listRtdbTopLevelKeys)try{i((await e.listRtdbTopLevelKeys()).map(pm))}catch{}})();return await Promise.allSettled([a,l,c,u]),s}const bo=Symbol("pyric/auth/target"),ym=Symbol("pyric.user.internal");function q(e,t){return new lt(e,`Firebase: ${t} (${e}).`)}const go={PASSWORD:"password"},Wn={EMAIL_LINK:"emailLink",EMAIL_PASSWORD:"password"};class _n{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"?bm(t):t;if(!n)return null;const r=n.providerId,s=n.signInMethod;if(typeof r!="string"||typeof s!="string")return null;if(r===go.PASSWORD){const i=typeof n.email=="string"?n.email:"",a=typeof n.password=="string"?n.password:"";return new gm(i,a,s)}return new _n(r,s)}}function bm(e){try{const t=JSON.parse(e);return typeof t=="object"&&t!==null?t:null}catch{return null}}class gm extends _n{email;secret;constructor(t,n,r=Wn.EMAIL_PASSWORD){super(go.PASSWORD,r),this.email=t,Object.defineProperty(this,"secret",{value:n,enumerable:!1,writable:!1})}get password(){return this.signInMethod===Wn.EMAIL_PASSWORD?this.secret:null}get emailLink(){return this.signInMethod===Wn.EMAIL_LINK?this.secret:null}toJSON(){return{providerId:this.providerId,signInMethod:this.signInMethod,email:this.email,password:this.secret}}}class Sn extends _n{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 Yr(e,t){return t?new Sn(e,e):null}class Ze{static PROVIDER_ID="google.com";static GOOGLE_SIGN_IN_METHOD="google.com";providerId=Ze.PROVIDER_ID;addScope(t){return this}setCustomParameters(t){return this}static credentialFromResult(t){return Yr(Ze.PROVIDER_ID,t)}static credentialFromError(t){return null}static credential(t,n){return new Sn(Ze.PROVIDER_ID,Ze.GOOGLE_SIGN_IN_METHOD,{idToken:t??void 0,accessToken:n??void 0})}}class et{static PROVIDER_ID="facebook.com";static FACEBOOK_SIGN_IN_METHOD="facebook.com";providerId=et.PROVIDER_ID;addScope(t){return this}setCustomParameters(t){return this}static credentialFromResult(t){return Yr(et.PROVIDER_ID,t)}static credentialFromError(t){return null}static credential(t){return new Sn(et.PROVIDER_ID,et.FACEBOOK_SIGN_IN_METHOD,{accessToken:t})}}class tt{static PROVIDER_ID="github.com";static GITHUB_SIGN_IN_METHOD="github.com";providerId=tt.PROVIDER_ID;addScope(t){return this}setCustomParameters(t){return this}static credentialFromResult(t){return Yr(tt.PROVIDER_ID,t)}static credentialFromError(t){return null}static credential(t){return new Sn(tt.PROVIDER_ID,tt.GITHUB_SIGN_IN_METHOD,{accessToken:t})}}const vo=[Ze.PROVIDER_ID,"apple.com",et.PROVIDER_ID,tt.PROVIDER_ID,"twitter.com","microsoft.com","yahoo.com"];function Xr(e,t=!1){const n=e[bo];if(!n)throw new TypeError("pyric/auth: unrecognized Auth handle — was it produced by getAuth(...)?");return t||n.assertAlive?.(),n}class vm{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 wm(e,t,n){const r=JSON.stringify(t);return`sandbox-id-token-${e}-${String(n)}:${r}`}function Me(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 vt(e){if(typeof e!="string"||e.length<6)throw q("auth/weak-password","Password should be at least 6 characters")}function wo(){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 xm="__pyric_no_password__";class xo{usersByEmail;usersByUid;authStateSubs=[];idTokenSubs=[];userDbSubs;beforeStateSubs=[];sharedCounters;flow=new vm;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=wo(),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 l=a===null?null:a.uid,c=this.cachedUser?.uid??null;l!==c&&(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,yn({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??xm,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){vt(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){Me(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){Me(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){Me(i);const a=i.toLowerCase(),l=this.usersByEmail.get(a);if(l&&l.uid!==t)throw q("auth/email-already-in-use",`An account already exists for ${i}.`);r.password!==void 0&&r.password!==null&&(vt(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){Me(t),vt(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??jm(),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 l=a?.providerId?.trim();if(!l)throw q("auth/argument-error",`${r}: providerUserInfo entries need a non-empty providerId.`);l==="password"||l==="anonymous"||s.has(l)||(s.add(l),i.push({providerId:l}))}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&&(Me(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&&(vt(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){Me(n.email);const a=n.email.toLowerCase(),l=this.usersByEmail.get(a);if(l&&l!==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&&(vt(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=wm(t,n,i),l=this.signInProviderByUid.get(t)??null,c={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:l}},u={token:a,claims:c,expirationTime:s.toISOString(),issuedAtTime:r.toISOString(),authTime:r.toISOString(),signInProvider:l};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"}],l=t.isAnonymous?[]:a.map(u=>({uid:t.uid,displayName:t.displayName,email:t.email,phoneNumber:r,photoURL:n,providerId:u.providerId})),c={uid:t.uid,email:t.email,emailVerified:s,displayName:t.displayName,photoURL:n,phoneNumber:r,isAnonymous:t.isAnonymous,providerId:i,providerData:l,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(c,ym,{value:{updateProfile:u=>(this.updateProfileFor(c,u),Promise.resolve()),delete:()=>(this.deleteFor(c),Promise.resolve()),updateEmail:u=>(this.updateEmailFor(c,u),Promise.resolve()),updatePassword:u=>(this.updatePasswordFor(c,u),Promise.resolve()),reload:()=>(this.reloadFor(c),Promise.resolve()),target:this.selfTarget()},enumerable:!1}),c}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(Me(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 jm(){return`provider-${globalThis.crypto.randomUUID()}`}const ii=new WeakSet,Ft=new WeakMap;function jo(e,t,n,r="[DEFAULT]"){return km(e,t),_m(e,t,n,r)}function km(e,t){ii.has(e)||(ii.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 ai(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 _m(e,t,n,r){let s=Ft.get(e);s||(s=new Map,Ft.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,ai(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&&Ft.delete(e))}}const l={backend:t,session:n,subscribers:new Set,generation:1};s.set(i,l),l.unregisterService=e.registerPersistableService(i,ai(l));const c=l.generation;return()=>{l.generation===c&&(l.unregisterService?.(),l.unregisterService=void 0,l.unsubscribeBackend?.(),l.unsubscribeBackend=void 0,l.subscribers.clear(),s.get(i)===l&&s.delete(i),s.size===0&&Ft.delete(e))}}async function qj(e){const{backend:t}=Xr(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 Sm(e){const t=Xr(e,!0);try{t.assertAlive?.()}catch(n){if(n.code==="app/app-deleted")return;throw n}await t.backend.transitionCurrentUser(null)}const oi=new WeakMap,li=new WeakMap,ci=new WeakMap;function ko(e){let t=li.get(e);return t||(t=wo(),li.set(e,t)),t}function Em(e){let t=oi.get(e);return t||(t=new xo(e,e,ko(e)),oi.set(e,t),jo(e,t,e)),t}function Cm(e,t){return t.service("auth/backend",()=>{const{sandbox:n,session:r}=t,s=new xo(n,r,ko(n),i=>{t.onDelete(i)});return t.onDelete(jo(n,s,r,e.name)),s})}function _o(e){if(e===void 0)return _o(vc());const t=wc(e);if(t)return t.service("auth/default",()=>{const n={kind:"sandbox",sandbox:t.sandbox,backend:Cm(e,t),own:r=>t.onDelete(r),assertAlive:()=>t.assertAlive()};return ui(n,e)});if(Nm(e)){let n=ci.get(e);return n||(n=ui({kind:"sandbox",sandbox:e,backend:Em(e)}),ci.set(e,n),n)}throw new TypeError("pyric/auth is a sandbox-only mirror. Package resolution must leave firebase/auth unchanged for production; activate pyric dev or @pyric/cli/register before importing to select the sandbox.")}function Nm(e){return typeof e=="object"&&e!==null&&typeof e.onCurrentUserChanged=="function"&&typeof e.withAuth=="function"}function ui(e,t){const n={[bo]:e,...t?{app:t}:{},signOut(){return Sm(n)}};return Object.defineProperty(n,"currentUser",{enumerable:!0,get(){return e.backend.getCurrentUser()}})}function K(e){return Xr(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 xc("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 Nt(e,t){return Am(e)?(_e(e.storage),new Rt(e.storage,Rm(e.fullPath,t??""))):(_e(e),new Rt(e,So(t??"")))}class Rt{storage;bucket;fullPath;constructor(t,n){this.storage=t;const r=_e(t);this.bucket=r.bucket,this.fullPath=n}get name(){if(this.fullPath==="")return"";const t=this.fullPath.lastIndexOf("/");return t===-1?this.fullPath:this.fullPath.slice(t+1)}get parent(){if(this.fullPath==="")return null;const t=this.fullPath.lastIndexOf("/"),n=t===-1?"":this.fullPath.slice(0,t);return new Rt(this.storage,n)}get root(){return this.fullPath===""?this:new Rt(this.storage,"")}toString(){return`gs://${this.bucket}/${this.fullPath}`}}function So(e){return e===""?"":e.split("/").filter(t=>t.length>0).join("/")}function Rm(e,t){const n=So(t);return e===""?n:n===""?e:`${e}/${n}`}function Am(e){if(e===null||typeof e!="object"||wn in e)return!1;const t=e;return typeof t.fullPath=="string"&&t.storage!==void 0}async function Im(e,t){return Eo(e,"getBlob"),Dm(e,t)}async function Qr(e,t){Eo(e,"deleteObject");const n=_e(e.storage),r=ft(n,t),s=await $t(e.storage),i=await s.backend.getMetadata(e.fullPath);Ot(s,{request:{auth:qe(n),method:"delete",path:e.fullPath},resource:jn(i)},n,r),await s.backend.delete(e.fullPath);try{Re(n.sandbox,yn({service:"storage",op:"object_delete",path:e.fullPath,auth:qe(n),before:i??void 0,detail:{bucket:e.bucket}}),r)}catch{}}async function Dm(e,t){const n=_e(e.storage),r=ft(n),s=await $t(e.storage),i=await s.backend.getMetadata(e.fullPath);Ot(s,{request:{auth:qe(n),method:"get",path:e.fullPath},resource:jn(i)},n,r);const a=await s.backend.getBlob(e.fullPath);if(!a)throw Za(e.fullPath);return typeof t=="number"&&a.size>t?a.slice(0,t):a}function Eo(e,t){if(e.fullPath==="")throw xn(t)}function Pm(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 $m{[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=Pm(n,i);const l=to({ref:t,blob:this._blob,settable:r}),c=Hr(l);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:c,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=hh(),this._updateSnapshot("canceled",this._snapshot.bytesTransferred),this._notifyObservers("error"),this._reject(this._error),!0):!1}on(t,n,r,s){let i,a,l,c=!1;if(typeof n=="object"&&n!==null&&(c=!0),c){const f=n;f.next!==void 0&&(i=f.next),f.error!==void 0&&(a=f.error),f.complete!==void 0&&(l=f.complete)}else typeof n=="function"&&(i=n),typeof r=="function"&&(a=r),typeof s=="function"&&(l=s);const d={next:i,error:a,complete:l};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(l!==void 0){const v=l;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 l=i.next;try{l(this._snapshot)}catch{}}}if(t==="error"){for(const i of this._observers)if(i.error!==void 0&&this._error!==void 0){const c=i.error,u=this._error;try{c(u)}catch{}}}if(t==="complete"){for(const i of this._observers)if(i.complete!==void 0){const l=i.complete;try{l()}catch{}}}}_runStep(){if(this._snapshot.state!=="running")return;if(this._didIntermediateProgress===!1){this._didIntermediateProgress=!0;let r=0;this._snapshot.totalBytes>0&&(r=Math.floor(this._snapshot.totalBytes/2)),this._updateSnapshot("running",r),this._notifyObservers("next"),queueMicrotask(()=>{this._runStep()});return}this._commitUpload()}async _commitUpload(){if(this._snapshot.state==="running")try{const n=await eo(this._ref,this._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 Qr(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 Om(e,t,n,r){if(e.fullPath==="")throw xn("uploadBytesResumable");return new $m(e,t,n,r)}async function Zr(e){const t=e.storage,n=_e(t),r=ft(n),s=await $t(t);Ot(s,{request:{auth:qe(n),method:"list",path:e.fullPath},resource:null},n,r);const i=e.fullPath===""?"":`${e.fullPath}/`,a=await s.backend.listByPrefix(i),l=[],c=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)l.push(Nt(t,d.fullPath));else{const m=p.slice(0,f),y=`${i}${m}`;c.has(y)||(c.add(y),u.push(Nt(t,y)))}}return u.sort((d,p)=>d.fullPath<p.fullPath?-1:d.fullPath>p.fullPath?1:0),{items:l,prefixes:u}}function Um(e,t,n){const r={name:n,options:structuredClone(t),automaticDataCollectionEnabled:!0};return gd(r,e),r}const Mm=Object.freeze({source:Object.freeze({kind:"studio"}),authLens:Object.freeze({mode:"admin"})});function Tm(e){return ha(e.withAuth(null),Mm)}const Bm="pyric-studio";function Co(e,t){return e.listDocuments(t).map(({path:n,phantom:r})=>({path:n,phantom:r}))}let Lm=0;function Fm(e){const t=Um(e,{projectId:"pyric-studio"},`pyric-studio-${Lm++}`),n=bn(e),r=Tm(e);return{sandbox:e,app:t,firestore:ma(e),adminFirestore:ya(r),auth:_o(e),storage:Hf(r),listRootCollections:()=>n.listRootCollections(),listSubcollections:s=>n.listSubcollections(s),listDocuments:s=>Co(n,s)}}function Vm(e,t){const[n,r]=h.useState(!1),[s,i]=h.useState(null),a=h.useMemo(()=>Sc(),[]),l=h.useMemo(()=>{try{return Fm(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:Bm,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}:l?e!=null&&n||t==="ready"?{status:"ready",handles:l}:{status:"pending",handles:null}:{status:"error",handles:null,error:new Error("Studio: failed to construct the sandbox data handles.")}}function qm(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=ba(e);return t?t.rules.kind==="evaluated":!1}function Wm(e){return"service"in e&&typeof e.service=="string"?e.service:"firestore"}function zm(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 Km(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 Hm(e){const t=[];for(const r of e)qm(r)&&t.push(Gm(r));return Km(t,e).sort((r,s)=>s.at-r.at)}function Gm(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:Wm(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=zm(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 di=/^Rule #(\d+) \(([^)]+)\) → (ALLOW|deny|unsupported)/;function Jm(e){const t=e.rules?.engine??e.service;return t==="rtdb"||t==="storage"?t:"firestore"}function Ym(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 Xm(e){const t=Jm(e),n=e.reasons.filter(s=>di.test(s)),r=e.reasons.filter(s=>!di.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"?Zm(e,n,r):t==="storage"?ey(e,n,r):Qm(e,n,r)}function Qm(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 Zm(e,t,n){const r=e.rules,s=Ym(e),i=!r?.matchedPath||r?.errorCode==="NO_MATCHING_RULE",a=r?.pathVariableBindings&&Object.keys(r.pathVariableBindings).length>0?r.pathVariableBindings:void 0;let l,c;return i?l=`No \`.${s}\` rule granted ${e.method} on ${e.path}: RTDB implicit deny (no rule matched).`:s==="validate"?(c=`${r.matchedPath} .validate`,l=`The \`.validate\` rule at \`${r.matchedPath}\` rejected the proposed value for ${e.method} ${e.path}.`):(c=`${r.matchedPath} .${s}`,l=`The \`.${s}\` rule at \`${r.matchedPath}\` evaluated false for ${e.method} ${e.path}.`),{headline:l,engine:"rtdb",ruleNode:c,ruleExpression:r?.matchedRule,phase:s,bindings:a,ruleLines:t,otherLines:n,implicitDeny:i}}function ey(e,t,n){const r=e.reasons.find(l=>/^match\s/.test(l)),i=e.reasons.some(l=>/^no rule matches/.test(l))||!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 ty(e){return e.skipped?"skipped":e.error!==void 0?"error":e.value===!0?"true":e.value===!1?"false":"value"}function ny(e){const t=e.evaluatedRule?.expressionTrace;if(!t||t.length===0)return[];const n=t.map(s=>({source:s.source,outcome:ty(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 ry(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 sy(e){const t=bn(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=>Co(t,n)}}function $e(){const e=Pe(),t=pe(),n=t.status==="ready"?t.env.persistence:void 0,r=Vm(n,t.status),s=t.status==="ready"?t.env.live:void 0,i=iy(s);return h.useMemo(()=>{switch(e.status){case"ready":return{status:"ready",handles:sy(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:l=>s.listSubcollections(l),listDocuments:l=>s.listDocuments(l)}}}return r}}},[e,r,s,i])}function iy(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 un=500;function zn(e){return e.length>un?e.slice(-un):e}function Mt(){const e=Pe(),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(zn(n.history())),n.subscribe(c=>i(u=>zn(nd(u,c))))},[r,n]);const a=h.useMemo(()=>r?zn(e.events):[],[r,e]);return r?a:s}function ay(e){return jc(e)}function oy(e){if(typeof e!="string")return!1;const t=e.toLowerCase();return t==="permission_denied"||t==="permission-denied"||t==="auth/permission-denied"}function ly(e){const t=ba(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 l=e.error;l!==void 0&&oy(l.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 l=e.error;l!==void 0&&l.reasons!==void 0&&(a=l.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 cy(){const e=Mt();return h.useMemo(()=>e.filter(ay).map(ly),[e])}function uy(){const e=Mt();return h.useMemo(()=>Hm(e),[e])}function dy(){const e=$e();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??Be,s=e.firestoreApi?.setDoc??Qt;let i=0;const a=[];for(const l of t)try{await s(r(n,l.path),l.data),i++}catch(c){a.push(`${l.path}: ${c instanceof Error?c.message:String(c)}`)}return{written:i,errors:a}},[e])}function fy(){const e=$e();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(l){const c=a.request.uid??a.request.email??"<auto>";i.push(`${c}: ${l instanceof Error?l.message:String(l)}`)}return{created:s,errors:i}},[e])}function hy(){const e=$e(),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 py(){const e=hy(),t=dy(),n=fy(),r=Pe();return h.useCallback(async()=>{const s=await e();if(r.status==="ready"){const{applySeed:i,deploySeedRules:a}=await Ba(async()=>{const{applySeed:l,deploySeedRules:c}=await import("./seed.CCmj00su.js");return{applySeed:l,deploySeedRules:c}},__vite__mapDeps([0,1,2,3,4,5,6]));a(r.handles.sandbox),await i(r.handles)}else try{const i=await fetch("/__pyric/init.json").then(c=>c.ok?c.json():null),a=i?.seed;a&&await t(Object.entries(a).map(([c,u])=>({path:c,data:u})));const l=i?.authUsers;Array.isArray(l)&&await n(l.map(c=>({request:c})))}catch(i){s.errors.push(`reseed: ${i instanceof Error?i.message:String(i)}`)}return s},[e,t,n,r])}function es(){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 my(){const e=pe(),t=e.status==="ready"?e.env.live:void 0;return h.useCallback(async()=>t?t.exportState():null,[t])}function yy(){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 by(){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 c=>{t&&(await t.saveBranch(c),await s())},[t,s]),a=h.useCallback(async c=>{t&&await t.switchBranch(c)},[t]),l=h.useCallback(async c=>{t&&(await t.deleteBranch(c),await s())},[t,s]);return{branches:n,save:i,switchTo:a,remove:l}}function gy(e="firestore"){const t=Pe(),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 c={};typeof a.rules=="string"&&(c.firestore=a.rules),a.databaseRules!==void 0&&a.databaseRules!==null&&(typeof a.databaseRules=="string"?c.rtdb=a.databaseRules:c.rtdb=JSON.stringify(a.databaseRules,null,2)),typeof a.storageRules=="string"&&(c.storage=a.storageRules),s(c)}).catch(()=>{}),()=>{i=!1}},[n]),h.useMemo(()=>{const i=t.status==="ready",a=e==="database"?"rtdb":e;if(!i){const l=r[a];return l!==void 0?l:""}try{if(a==="rtdb"){const u=Aa(t.handles.sandbox);return u!=null?JSON.stringify(u,null,2):""}return bn(t.handles.sandbox).getRules()}catch{return""}},[t,r,e])}function vy(e){let t=!0;return n=>{const r=t;t=!1,e(s=>xy(s,n,r))}}function wy(e){const t=new Map;for(const n of e)t.set(vr(n),n);return[...t.values()]}function xy(e,t,n){return wy(n?t:[...e??[],...t])}const jy=3e4;function No(){const e=$e(),t=pe(),[n,r]=h.useState(null),[s,i]=h.useState(!1),a=h.useRef(!1),l=h.useRef(e);l.current=e;const c=t.status==="ready"?t.env.live:void 0,u=h.useRef(c);u.current=c;const d=h.useRef(null),p=h.useRef(0),f=h.useRef(null),m=h.useRef(0),y=h.useCallback(v=>{const b=l.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??kt,_=b.firestoreApi?.query??sn,N=b.firestoreApi?.getDocs??Zt,P=b.firestoreApi?.limit??an,I=b.storageApi?.ref??Nt,D=b.storageApi?.listAll??Zr,C=b.authApi?.listUsers??fe.listUsers,S={listRootCollections:()=>x.listRootCollections(),listDocumentPaths:async(R,V)=>(await N(_(j(k,R),P(V)))).docs.slice(0,V).map(A=>`${R}/${A.id}`),listSubcollections:R=>Promise.resolve(x.listSubcollections(R)),listUsers:async R=>(await Promise.resolve(C(x.auth))).slice(0,R).map(G=>({uid:G.uid,email:G.email??null})),listStorageObjectPaths:R=>nm(I(x.storage,""),D,{maxObjects:R,maxListCalls:wr.storageListCalls}),listRtdbTopLevelKeys:async()=>{const R=u.current;if(!R)return[];const V=Date.now()-m.current<jy;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=vy(R=>r(R));mm(S,wr,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(l.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 ky=150;function _y(e){return e.startsWith("/")||/rtdb/i.test(e)}function Ro({autoFocus:e,onNavigated:t,onEscape:n,exposeFocus:r}){const[s,i]=h.useState(""),[a,l]=h.useState(""),[c,u]=h.useState(0),[d,p]=h.useState(!1),f=h.useRef(null),{entries:m,building:y,ensure:g}=No();h.useEffect(()=>{if(r)return r(()=>f.current?.focus()),()=>r(null)},[r]),h.useEffect(()=>{e&&f.current?.focus()},[e]),h.useEffect(()=>{const j=setTimeout(()=>l(s),ky);return()=>clearTimeout(j)},[s]);const v=h.useMemo(()=>ni(a,We,m??[]),[a,m]),b=h.useMemo(()=>ri(v),[v]);h.useEffect(()=>{u(j=>b.length===0?0:Math.min(j,b.length-1))},[b.length]);const w=j=>{j&&(i(""),l(""),p(!1),ce(j.target),t?.(j.target))},x=()=>{if(s===a){w(b[c]??b[0]);return}const j=ri(ni(s,We,m??[]));w(j[0])};let k=0;return o.jsxs("div",{className:"studio-home__command",children:[o.jsx("div",{className:"studio-home__command-row",children:o.jsx("input",{ref:f,className:"studio-home__command-input",type:"text",value:s,placeholder:"Jump to a surface, collection, doc, user, or object…","aria-label":"Command input",role:"combobox","aria-expanded":d&&b.length>0,"aria-autocomplete":"list",onFocus:()=>{g(),p(!0)},onBlur:()=>p(!1),onChange:j=>{const _=j.target.value;i(_),p(!0),_y(_)&&g({rtdbLikely:!0})},onKeyDown:j=>{if(j.key==="ArrowDown")j.preventDefault(),u(_=>Math.min(_+1,Math.max(b.length-1,0)));else if(j.key==="ArrowUp")j.preventDefault(),u(_=>Math.max(_-1,0));else if(j.key==="Enter")x();else if(j.key==="Escape"){if(n){n();return}i(""),l(""),p(!1)}}})}),d&&!v.length&&y&&m===null?o.jsx("div",{className:"studio-home__command-results",role:"status","aria-live":"polite",children:o.jsx("span",{className:"studio-home__command-group-title",children:"Indexing sandbox…"})}):null,d&&v.length?o.jsx("div",{className:"studio-home__command-results",role:"listbox","aria-label":"Suggestions",onMouseDown:j=>j.preventDefault(),children:v.map(j=>{const _=k;return k+=j.results.length,o.jsxs("div",{className:"studio-home__command-group",children:[o.jsx("span",{className:"studio-home__command-group-title","aria-hidden":"true",children:j.title}),o.jsx("ul",{className:"studio-home__command-group-list",children:j.results.map((N,P)=>{const I=_+P;return o.jsx("li",{children:o.jsxs("button",{type:"button",role:"option","aria-selected":I===c,className:"studio-home__command-result","data-active":I===c?"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 Sy({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(Ro,{autoFocus:!0,onEscape:e,onNavigated:e})})})}const Ey={status:"loading",payload:null},Vt={status:"absent",payload:null};let dn=Ey,fi=!1;const xr=new Set;function qt(e){dn=e;for(const t of xr)t()}function Cy(){if(!fi){if(fi=!0,typeof fetch>"u"){dn=Vt;return}fetch("/__pyric/init.json").then(async e=>{if(!e.ok||!(e.headers.get("content-type")??"").includes("json"))return qt(Vt);const n=await e.json();qt({status:"ready",payload:n})}).catch(()=>qt(Vt))}}function Ny(e){return xr.add(e),Cy(),()=>xr.delete(e)}function En(){return h.useSyncExternalStore(Ny,()=>dn,()=>dn)}function Ry(e){return e.kind==="absent"?"absent":e.sandboxConnected?"available":"idle"}function Ay(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 Iy(e){try{const t=await e("/__pyric/health");return t.ok?(t.headers.get("content-type")??"").includes("json")?Ay(t.status,await t.json()):{kind:"absent"}:{kind:"absent"}}catch{return{kind:"absent"}}}function Dy(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=Ry(await Iy(fetch));return r&&(n(u),u==="absent"&&s&&(clearInterval(s),s=null)),u},a=()=>typeof document>"u"||document.visibilityState!=="hidden",l=()=>{s||(s=setInterval(()=>{a()&&i()},e))},c=()=>{a()&&i()};return i().then(u=>{r&&u!=="absent"&&l()}),typeof document<"u"&&document.addEventListener("visibilitychange",c),()=>{r=!1,s&&clearInterval(s),typeof document<"u"&&document.removeEventListener("visibilitychange",c)}},[e]),t}const Py="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 $y(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 Oy(e){return e==="studio"?"Studio":"App"}function Uy(e,t,n=Date.now()){const r=e.clients.length,s=e.clients.map(a=>({clientId:a.clientId,kindLabel:Oy(a.kind),route:a.route||"/",visibilityLabel:a.visibility==="hidden"?"Hidden":"Visible",isThisPage:a.clientId===t,freshnessLabel:$y(a.lastSeen,n)}));s.sort((a,l)=>a.isThisPage!==l.isThisPage?a.isThisPage?-1:1:a.kindLabel!==l.kindLabel?a.kindLabel==="Studio"?-1:1:a.route.localeCompare(l.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:Py,otherCount:i}}function My(){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(Uy(i,s))})},[t]),n}const Ty={servedEpoch:null,runningEpoch:null,updateAvailable:!1,updating:!1,error:null},By=()=>()=>{},hi=()=>Ty;function Ly(){const e=pe(),t=En(),n=Dy(),r=My(),[s,i]=h.useState(!1),a=h.useRef(null),l=e.status==="ready"?e.env.live?.runtime:void 0,c=h.useSyncExternalStore(l?.subscribe??By,l?.getSnapshot??hi,l?.getSnapshot??hi),d=t.status==="ready"&&e.status==="ready"&&!e.env.live,p=e.status==="error",f=c.error?"worker update failed":p?"backend error":d?"worker unreachable":null,m=c.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:[c.updateAvailable?o.jsxs("button",{type:"button",className:"studio-chip studio-chip--warn",disabled:c.updating,title:"The Studio backend is running older code. Update every connected page to the served worker version.",onClick:()=>void l?.update().catch(()=>{}),children:[o.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),c.updating?"updating worker…":"update worker"]}):null,f?o.jsxs("a",{className:"studio-chip studio-chip--warn",href:kn({tab:"settings"}),title:m,onClick:g=>{g.preventDefault(),ce({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 Fy(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 pi(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 Vy({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 l=e.slice(s,a),c=i.origin==="transaction"?"transaction":"batch";r.push(pi(c,i.groupId,l)),s=a;continue}if(n&&i.origin==="listener"){let a=s+1;for(;a<e.length&&e[a].origin==="listener"&&!e[a].groupId&&Fy(e[a],i);)a++;const l=e.slice(s,a);if(l.length>1){const c=i.triggeredBy?`${i.triggeredBy.method}:${i.triggeredBy.path}`:"unknown";r.push(pi("listener-run",`listener-run:${c}:${s}`,l))}else r.push({type:"single",event:i});s=a;continue}r.push({type:"single",event:i}),s++}return{items:r}},[e,t,n])}const qy={buckets:[],total:0,denies:0,maxCount:0,outOfWindow:0};function Wy({events:e,window:t,bucketCount:n=30}){return h.useMemo(()=>zy(e,t,n),[e,t.start,t.end,n])}function zy(e,t,n=30){const r=t.end-t.start;if(n<=0||r<=0)return qy;const s=r/n,i=new Array(n).fill(0),a=new Array(n).fill(0);let l=0,c=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]++,l++,f.result==="deny"&&(a[y]++,c++)}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:l,denies:c,maxCount:d,outOfWindow:u}}const Ky=new Set(["get","list"]),Hy=new Set(["create","update","set"]),Gy=new Set(["delete","remove"]),Jy=[{key:"reads",label:"Read ops"},{key:"writes",label:"Writes"},{key:"deletes",label:"Deletes"}],Yy=[{key:"allows",label:"Allows"},{key:"denies",label:"Denies"},{key:"errors",label:"Errors"}];function Cn(e){return e.origin==="admin"}function Xy(e,t=Cn){return e.result==="allow"||t(e)?Ky.has(e.method)?"reads":Hy.has(e.method)?"writes":Gy.has(e.method)?"deletes":null:null}function Qy(e,t=Cn){return t(e)?null:e.result==="allow"?"allows":e.result==="deny"?"denies":e.result==="error"?"errors":null}const Zy=e=>({points:[],series:e.map(t=>({key:t.key,label:t.label,values:[],total:0})),maxValue:0});function Ao(e,t,n,r,s){const i=t.end-t.start;if(n<=0||i<=0)return Zy(r);const a=i/n,l=new Map(r.map(f=>[f.key,new Array(n).fill(0)])),c=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=l.get(y);v[g]++,c.set(y,(c.get(y)??0)+1)}let u=0;for(const f of l.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:l.get(f.key),total:c.get(f.key)??0}));return{points:d,series:p,maxValue:u}}function eb(e,t,n=24,r=Cn){return Ao(e,t,n,Jy,s=>Xy(s,r))}function tb(e,t,n=24,r=Cn){return Ao(e,t,n,Yy,s=>Qy(s,r))}function nb({events:e,window:t,bucketCount:n=24,isAdmin:r}){return h.useMemo(()=>eb(e,t,n,r),[e,t.start,t.end,n,r])}function rb({events:e,window:t,bucketCount:n=24,isAdmin:r}){return h.useMemo(()=>tb(e,t,n,r),[e,t.start,t.end,n,r])}function jr({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 At(e){const t=new Date(e),n=r=>String(r).padStart(2,"0");return`${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`}function Io({event:e,selected:t,onSelect:n,renderClassification:r,formatTime:s=At,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(jr,{kind:e.method,children:e.method}),o.jsx("span",{"data-pyric-traffic-path":"",children:e.path||"/"}),r?r(e):null]})}var ts=Ec();function Je(e,t,n){let r=n.initialDeps??[],s,i=!0;function a(){var l,c,u;let d;n.key&&((l=n.debug)!=null&&l.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&&((c=n.debug)!=null&&c.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
6
|
font-size: .6rem;
|
|
7
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=l=>{r=l},a}function mi(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const rb=(e,t)=>Math.abs(e-t)<1.01,sb=(e,t,n)=>{let r;return function(...s){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,s),n)}},yi=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},ib=e=>e,ab=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},ob=(e,t)=>{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;const s=a=>{const{width:l,height:c}=a;t({width:Math.round(l),height:Math.round(c)})};if(s(yi(n)),!r.ResizeObserver)return()=>{};const i=new r.ResizeObserver(a=>{const l=()=>{const c=a[0];if(c?.borderBoxSize){const u=c.borderBoxSize[0];if(u){s({width:u.inlineSize,height:u.blockSize});return}}s(yi(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(l):l()});return i.observe(n,{box:"border-box"}),()=>{i.unobserve(n)}},bi={passive:!0},gi=typeof window>"u"?!0:"onscrollend"in window,lb=(e,t)=>{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;let s=0;const i=e.options.useScrollendEvent&&gi?()=>{}:sb(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)},l=a(!0),c=a(!1);n.addEventListener("scroll",l,bi);const u=e.options.useScrollendEvent&&gi;return u&&n.addEventListener("scrollend",c,bi),()=>{n.removeEventListener("scroll",l),u&&n.removeEventListener("scrollend",c)}},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"]},ub=(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 db{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 l=i.target,c=this.indexFromElement(l);if(!l.isConnected){this.observer.unobserve(l);return}this.shouldMeasureDuringScroll(c)&&this.resizeItem(c,this.options.measureElement(l,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:ib,rangeExtractor:ab,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=Je(()=>(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 l=n[a];if(s.has(l.lane))continue;const c=i.get(l.lane);if(c==null||l.end>c.end?i.set(l.lane,l):l.end<c.end&&s.set(l.lane,!0),s.size===this.options.lanes)break}return i.size===this.options.lanes?Array.from(i.values()).sort((a,l)=>a.end===l.end?a.index-l.index:a.end-l.end)[0]:void 0},this.getMeasurementOptions=Je(()=>[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,l,c)=>(this.prevLanes!==void 0&&this.prevLanes!==l&&(this.lanesChangedFlag=!0),this.prevLanes=l,this.pendingMeasuredCacheIndexes=[],{count:n,paddingStart:r,scrollMargin:s,getItemKey:i,enabled:a,lanes:l,laneAssignmentMode:c}),{key:!1}),this.getMeasurements=Je(()=>[this.getMeasurementOptions(),this.itemSizeCache],({count:n,paddingStart:r,scrollMargin:s,getItemKey:i,enabled:a,lanes:l,laneAssignmentMode:c},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(l).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=c==="estimate"||u.has(y);if(g!==void 0&&this.options.lanes>1){v=g;const _=f[v],N=_!==void 0?p[_]:void 0;b=N?N.end+this.options.gap:r+s}else{const _=this.options.lanes===1?p[m-1]:this.getFurthestMeasurement(p,m);b=_?_.end+this.options.gap:r+s,v=_?_.lane:m%this.options.lanes,this.options.lanes>1&&w&&this.laneAssignments.set(m,v)}const x=u.get(y),k=typeof x=="number"?x:this.options.estimateSize(m),j=b+k;p[m]={index:m,start:b,size:k,end:j,key:y,lane:v},f[v]=m}return this.measurementsCache=p,p},{key:!1,debug:()=>this.options.debug}),this.calculateRange=Je(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,s,i)=>this.range=n.length>0&&r>0?fb({measurements:n,outerSize:r,scrollOffset:s,lanes:i}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=Je(()=>{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),l=Math.min(this.options.count-1,s+i);return n>=a&&n<=l}return!0},this.measureElement=n=>{if(!n){this.elementsCache.forEach((a,l)=>{a.isConnected||(this.observer.unobserve(a),this.elementsCache.delete(l))});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,l=r-a;l!==0&&(((s=this.scrollState)==null?void 0:s.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(i,l,this):i.start<this.getScrollOffset()+this.scrollAdjustments)&&this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=l,behavior:void 0}),this.pendingMeasuredCacheIndexes.push(i.index),this.itemSizeCache=new Map(this.itemSizeCache.set(i.key,r)),this.notify(!1))},this.getVirtualItems=Je(()=>[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const s=[];for(let i=0,a=n.length;i<a;i++){const l=n[i],c=r[l];s.push(c)}return s},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length!==0)return mi(r[Do(0,r.length-1,s=>mi(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 l=this.getMaxScrollOffset();return Math.max(Math.min(l,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 l=r==="end"?a.end+this.options.scrollPaddingEnd:a.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(l,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,l]=i,c=this.now();this.scrollState={index:n,align:l,behavior:s,startedAt:c,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(l=>l===null);){const l=r[a];i[l.lane]===null&&(i[l.lane]=l.end),a--}s=Math.max(...i.filter(l=>l!==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&&rb(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 Do=(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 fb({measurements:e,outerSize:t,scrollOffset:n,lanes:r}){const s=e.length-1,i=c=>e[c].start;if(e.length<=r)return{startIndex:0,endIndex:s};let a=Do(0,s,i,n),l=a;if(r===1)for(;l<s&&e[l].end<n+t;)l++;else if(r>1){const c=Array(r).fill(0);for(;l<s&&c.some(d=>d<n+t);){const d=e[l];c[d.lane]=d.end,l++}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),l=Math.min(s,l+(r-1-l%r))}return{startIndex:a,endIndex:l}}const vi=typeof document<"u"?h.useLayoutEffect:h.useEffect;function hb({useFlushSync:e=!0,...t}){const n=h.useReducer(()=>({}),{})[1],r={...t,onChange:(i,a)=>{var l;e&&a?ts.flushSync(n):n(),(l=t.onChange)==null||l.call(t,i,a)}},[s]=h.useState(()=>new db(r));return s.setOptions(r),vi(()=>s._didMount(),[]),vi(()=>s._willUpdate()),s}function pb(e){return hb({observeElementRect:ob,observeElementOffset:lb,scrollToFn:ub,...e})}function ns({items:e,estimateSize:t,renderItem:n,overscan:r=5,className:s,height:i="100%",getItemKey:a}){const l=h.useRef(null),c=typeof t=="function"?t:()=>t,u=pb({count:e.length,getScrollElement:()=>l.current,estimateSize:c,overscan:r});return o.jsx("div",{ref:l,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 mb={batch:"batch write",transaction:"transaction","listener-run":"listener re-evals"};function yb({group:e,defaultExpanded:t=!1,onSelect:n,selectedId:r,renderClassification:s,formatTime:i,className:a}){const[l,c]=h.useState(t);return o.jsxs("div",{className:a,"data-pyric-traffic-group":"","data-pyric-group-kind":e.kind,"data-pyric-expanded":l?"":void 0,children:[o.jsxs("button",{type:"button",onClick:()=>c(u=>!u),"data-pyric-traffic-group-header":"","data-pyric-group-kind":e.kind,"aria-expanded":l,children:[o.jsx("span",{"data-pyric-group-kind-label":"",children:mb[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]}),l?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(Io,{event:u,selected:u.id===r,onSelect:n,renderClassification:s,formatTime:i})},u.id))}):null]})}function bb(e){return e<0?0:e>1?1:e}function Kn(e,t){const n=t.end-t.start;return n<=0?0:bb((e-t.start)/n)}function gb({events:e,buckets:t,window:n,bucketCount:r=30,brush:s,onBrush:i,renderBucketSummary:a,liveAt:l,header:c,axis:u,emptyState:d,className:p}){const f=h.useId(),[m,y]=h.useState(null),[g,v]=h.useState(null),b=qy({events:e??[],window:n,bucketCount:r}),w=t??b,{buckets:x,total:k}=w,j=m??g,_=j===null?null:x.find(S=>S.index===j)??null,N=_!==null&&s?.start===_.start&&s.end===_.end;if(x.length===0)return o.jsx("div",{className:p,"data-pyric-ui":"traffic-timeline","data-pyric-empty":"",children:d});const P=k===0,I=l===void 0?n.end:l,D=I==null?null:Kn(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:[c!==void 0&&o.jsx("div",{"data-pyric-timeline-header":"",children:c}),o.jsxs("div",{"data-pyric-timeline-chart":"",children:[o.jsx("div",{"data-pyric-timeline-bars":"",role:i?"group":"img","aria-label":"request volume over time",children:x.map(S=>o.jsx(vb,{bucket:S,window:n,onBrush:i,onHover:a?y:void 0,onFocus:a?v:void 0,summaryId:a&&!N&&_?.index===S.index?f:void 0,selected:s?.start===S.start&&s.end===S.end},S.index))}),_&&a&&!N?o.jsx("div",{id:f,role:"tooltip","data-pyric-bucket-summary":"",style:{"--pyric-bucket-summary-x":(_.index+.5)/Math.max(x.length,1)},children:a(_)}):null,s&&o.jsx("div",{"data-pyric-brush":"","aria-hidden":"true",style:{"--pyric-brush-left":Kn(s.start,n),"--pyric-brush-right":1-Kn(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 vb({bucket:e,window:t,onBrush:n,onHover:r,onFocus:s,summaryId:i,selected:a}){const l=n!==void 0,c=`${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:!l,"aria-label":`${c}, ${u}`,"aria-describedby":i,"aria-pressed":l?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:l?()=>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 wb=e=>String(e);function xb({series:e,visible:t,onToggle:n,formatValue:r=wb,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,l)=>{const c=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":l,"data-pyric-metric-hidden":c?void 0:"",children:[o.jsx("input",{type:"checkbox",checked:c,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":l,children:u},a.key)})})}const jb=e=>String(e),kb=e=>new Date(e).toLocaleTimeString();function _b({points:e,series:t,visible:n,omitZeroSeries:r=!1,formatValue:s=jb,formatTime:i=kb,emptyState:a,className:l}){const[c,u]=h.useState(null);if(e.length===0)return o.jsx("div",{className:l,"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=c!=null?e[c]:null;return o.jsx("div",{className:l,"data-pyric-ui":"traffic-line-chart",children:o.jsxs("div",{"data-pyric-chart-svg":"",children:[o.jsx("svg",{viewBox:"0 0 100 100",preserveAspectRatio:"none",role:"img","aria-label":"metrics over time",children:t.map(b=>{const w=t.indexOf(b);if(!((!n||n.has(b.key))&&(!r||b.total>0)))return null;const k=b.values.map((j,_)=>`${_===0?"M":"L"}${y(_)},${g(j)}`).join(" ");return o.jsx("path",{"data-pyric-chart-line":"","data-pyric-series-key":b.key,"data-pyric-series-index":w,d:k,fill:"none",vectorEffect:"non-scaling-stroke"},b.key)})}),o.jsx("div",{"data-pyric-chart-hits":"",children:e.map((b,w)=>o.jsx("button",{type:"button","data-pyric-chart-hit":"","data-pyric-point-index":w,onMouseEnter:()=>u(w),onFocus:()=>u(w),onMouseLeave:()=>u(x=>x===w?null:x),onBlur:()=>u(x=>x===w?null:x),"aria-label":`${i(b.start)} to ${i(b.end)}`},b.index))}),v&&o.jsxs("div",{"data-pyric-chart-tooltip":"",style:{"--pyric-hover-x":y(v.index)},children:[o.jsxs("div",{"data-pyric-tooltip-time":"",children:[i(v.start)," – ",i(v.end)]}),d.map(b=>o.jsxs("div",{"data-pyric-tooltip-row":"","data-pyric-series-key":b.key,"data-pyric-series-index":t.indexOf(b),children:[o.jsx("span",{"data-pyric-tooltip-label":"",children:b.label}),o.jsx("span",{"data-pyric-tooltip-value":"",children:s(b.values[v.index])})]},b.key))]})]})})}const Sb={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},Po=h.createContext(Sb);function Eb(){return h.useContext(Po)}function $o({value:e,children:t}){return h.createElement(Po.Provider,{value:e},t)}function Cb(e,t){return[e.uid,e.email,e.displayName,e.phoneNumber].some(n=>n!=null&&n.toLowerCase().includes(t))}function rs(e){const{listUsers:t,subscribeUsers:n,createUser:r,updateUser:s,deleteUser:i,clearUsers:a}=Eb(),[l,c]=h.useState([]),[u,d]=h.useState(!0),[p,f]=h.useState(void 0),[m,y]=h.useState("");h.useEffect(()=>{let j=!1;d(!0),f(void 0);const _=D=>{j||(c(D),d(!1))},N=D=>{j||(c([]),f(D instanceof Error?D:new Error(String(D))),d(!1))},P=()=>{try{const D=t(e);D&&typeof D.then=="function"?D.then(_).catch(N):_(D)}catch(D){N(D)}};let I;try{P(),I=n(e,P)}catch(D){N(D)}return()=>{j=!0,I?.()}},[e,t,n]);const g=h.useMemo(()=>{const j=m.trim().toLowerCase();return j?l.filter(_=>Cb(_,j)):l},[l,m]),v=h.useCallback(j=>r(e,j),[e,r]),b=h.useCallback((j,_)=>s(e,j,_),[e,s]),w=h.useCallback(j=>i(e,j),[e,i]),x=h.useCallback(()=>a(e),[e,a]),k=h.useCallback(()=>{const j=t(e);j&&typeof j.then=="function"?j.then(_=>c(_)).catch(()=>{}):c(j)},[e,t]);return{users:g,totalCount:l.length,isLoading:u,error:p,filter:m,setFilter:y,createUser:v,updateUser:b,deleteUser:w,clearUsers:x,refresh:k}}const Nb=["iss","aud","sub","iat","exp","nbf","jti","nonce","azp","acr","amr","cnf","auth_time","firebase","at_hash","c_hash"],Rb=1e3;function Oo(e){const t=e.trim();if(!t)return{ok:!0,claims:void 0};if(t.length>Rb)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 Nb)if(r in n)return{ok:!1,message:`Custom claims must not have forbidden key: ${r}`};return{ok:!0,claims:n}}const Ab={email:"",password:"",displayName:"",phoneNumber:"",photoUrl:"",emailVerified:!1,disabled:!1,claimsText:"",providerIds:[]},Ib=new Set(["password","anonymous","phone"]),Db=/^[^@]+@[^@]+\.[^@]+$/,wi=6;function Pb(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=>!Ib.has(t))}:{...Ab}}function $b(e){const t=Pb(e);return{fields:t,initial:{...t}}}function Ob(e,t){switch(t.type){case"setField":return{...e,fields:{...e.fields,[t.field]:t.value}};case"reset":return{...e,fields:{...e.initial}}}}function Ub(e){const t={},n=e.email.trim(),r=e.password;n&&!Db.test(n)&&(t.email="Invalid email"),r&&r.length<wi&&(t.password=`Password should be at least ${wi} characters`),r&&!n&&(t.password="Email is required for password authentication");const s=Oo(e.claimsText);return s.ok||(t.claims=s.message),t}function Tb(e){const{fields:t,initial:n}=e;return Object.keys(t).some(r=>r==="providerIds"?!Uo(t.providerIds,n.providerIds):t[r]!==n[r])}function Uo(e,t){if(e.length!==t.length)return!1;const n=[...t].sort();return[...e].sort().every((r,s)=>r===n[s])}function To(e){const t=Oo(e.claimsText);return t.ok?t.claims:void 0}function Mb(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=To(t);return r&&(n.customClaims=r),t.providerIds.length&&(n.providerUserInfo=t.providerIds.map(s=>({providerId:s}))),n}function Bb(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=To(t)??{}),Uo(t.providerIds,n.providerIds)||(r.providerUserInfo=t.providerIds.map(s=>({providerId:s}))),r}function Mo(e={}){const[t,n]=h.useReducer(Ob,e.initial,$b),r=h.useMemo(()=>Ub(t.fields),[t.fields]),s=h.useMemo(()=>Tb(t),[t]),i=h.useCallback((l,c)=>n({type:"setField",field:l,value:c}),[]),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:()=>Mb(t),toUpdateRequest:()=>Bb(t),dispatch:n}}const Lb={"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 fn(e){return Lb[e]??e}function xi(e){return e.email??e.phoneNumber??(e.isAnonymous?"anonymous":e.uid)}function Fb(e){return e.isAnonymous&&e.providerUserInfo.length===0?o.jsx("span",{"data-pyric-provider-id":"anonymous",children:fn("anonymous")}):e.providerUserInfo.map(t=>o.jsx("span",{"data-pyric-provider-id":t.providerId,children:fn(t.providerId)},t.providerId))}function ji(e){if(!e)return"—";const t=new Date(e);return Number.isNaN(t.getTime())?"—":t.toLocaleDateString()}function Bo({users:e,isLoading:t,error:n,filter:r,onSelect:s,renderIdentifier:i,renderProviders:a,renderSelection:l,renderSelectionHeader:c,renderActions:u,renderActionsHeader:d,formatCreatedAt:p=ji,formatLastLoginAt:f=ji,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:[l?o.jsx("span",{role:"cell","data-pyric-user-cell":"selection",children:l(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):xi(j)}):(i??xi)(j)}),o.jsx("span",{role:"cell","data-pyric-user-cell":"providers",children:(a??Fb)(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":l?"":void 0,"data-pyric-actions":u?"":void 0,children:[o.jsxs("div",{role:"row","data-pyric-user-header":!0,children:[l?o.jsx("span",{role:"columnheader","data-pyric-user-cell":"selection","aria-label":"Selection",children:c}):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(ns,{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 Vb({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 qb({selected:e,onChange:t}){return o.jsx("div",{"data-pyric-provider-checklist":!0,children:vo.map(n=>o.jsxs("label",{"data-pyric-provider-option":n,children:[o.jsx("input",{type:"checkbox",checked:e.includes(n),onChange:r=>t(r.target.checked?[...e,n]:e.filter(s=>s!==n))}),o.jsx("span",{"data-pyric-provider-option-label":!0,children:fn(n)}),o.jsx("span",{"data-pyric-provider-option-id":!0,children:n})]},n))})}function Lo({initial:e,onSubmit:t,onCancel:n,submitLabel:r="Save",cancelLabel:s="Cancel",children:i,className:a,renderField:l}){const c=Mo({initial:e}),u=e?"edit":"create",d=c.isValid&&(u==="create"||c.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:c.fields.email,onChange:y=>c.setField("email",y.target.value)}),c.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:c.fields.password,onChange:y=>c.setField("password",y.target.value)}),c.errors.password??null),p("display-name","Display name","text",o.jsx("input",{type:"text","data-pyric-field":"display-name",placeholder:"Display name (optional)",value:c.fields.displayName,onChange:y=>c.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:c.fields.phoneNumber,onChange:y=>c.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:c.fields.photoUrl,onChange:y=>c.setField("photoUrl",y.target.value)})),...u==="create"?[p("providers","Sign-in providers","group",o.jsx(qb,{selected:c.fields.providerIds,onChange:y=>c.setField("providerIds",y)}))]:[],p("email-verified","Verified email","checkbox",o.jsx("input",{type:"checkbox","data-pyric-field":"email-verified",checked:c.fields.emailVerified,onChange:y=>c.setField("emailVerified",y.target.checked)})),p("disabled","Disabled (sign-in attempts are rejected)","checkbox",o.jsx("input",{type:"checkbox","data-pyric-field":"disabled",checked:c.fields.disabled,onChange:y=>c.setField("disabled",y.target.checked)}))],m=y=>{y.preventDefault(),d&&t(u==="edit"?{mode:u,uid:e.uid,request:c.toUpdateRequest()}:{mode:u,request:c.toCreateRequest()})};return o.jsxs("form",{className:a,"data-pyric-ui":"auth-user-form","data-pyric-mode":u,"data-pyric-is-dirty":c.isDirty?"":void 0,"data-pyric-is-valid":c.isValid?"":void 0,onSubmit:m,children:[f.map(y=>l?o.jsx(h.Fragment,{children:l(y)},y.name):y.defaultRender()),o.jsx(Vb,{value:c.fields.claimsText,onChange:y=>c.setField("claimsText",y),error:c.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 Wb({open:e,onOpenChange:t,title:n,body:r,destructive:s,confirmLabel:i="Confirm",cancelLabel:a="Cancel",onConfirm:l,className:c}){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:ts.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:c,"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:l,children:i})]})]})]}),document.body)}const Fo=h.createContext(null);function pt(){const e=h.useContext(Fo);if(!e)throw new Error("useConfirm: missing <ConfirmProvider> ancestor");return e}function ss({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]),l=h.useCallback(u=>{u||n&&(s.current||(s.current=!0,n.resolve(!1),r(null)))},[n]),c=h.useMemo(()=>i,[i]);return o.jsxs(Fo.Provider,{value:c,children:[e,n?o.jsx(Wb,{open:!0,onOpenChange:l,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 zb(e){return e.email??e.phoneNumber??e.displayName??e.uid}function Kb({user:e,onDelete:t,title:n="Delete user",body:r,confirmLabel:s="Delete",renderTrigger:i,className:a}){const l=pt(),c=async()=>{await l({title:n,body:r??`This will permanently delete ${zb(e)}.`,destructive:!0,confirmLabel:s})&&t(e.uid)};return i?o.jsx(o.Fragment,{children:i({onClick:c})}):o.jsx("button",{type:"button",className:a,"data-pyric-ui":"delete-user","data-pyric-destructive":!0,onClick:c,children:"Delete user"})}function Hb(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 Gb={addDoc:fa,collection:kt,deleteDoc:Zn,doc:Be,getDoc:va,getDocs:Zt,limit:an,onSnapshot:Hu,query:sn,setDoc:Qt,startAfter:Ku},Vo=h.createContext(Gb);function is(){return h.useContext(Vo)}function Jb({value:e,children:t}){return h.createElement(Vo.Provider,{value:e},t)}function Yb(e){const{onSnapshot:t}=is(),[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:Hb(i),isLoading:!1}))},[t,e]),n}function Nn(e){return e==null?"null":typeof e=="string"?"string":typeof e=="number"?"number":typeof e=="boolean"?"boolean":typeof e=="object"&&Ke(e)!==null?"vector":Array.isArray(e)?"array":e instanceof ct?"timestamp":e instanceof rt?"geopoint":e instanceof gn?"bytes":typeof e=="object"&&qo(e)?"timestamp":typeof e=="object"&&Wo(e)?"geopoint":typeof e=="object"&&Xb(e)?"reference":typeof e=="object"?"map":"null"}function qo(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 Wo(e){const t=e;return Object.keys(t).length===2&&typeof t.latitude=="number"&&typeof t.longitude=="number"}function Xb(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 Ke(e){if(e===null||typeof e!="object")return null;const t=e;if(t.typeName==="vector"&&Wt(t.value)||t.__type__==="__vector__"&&Wt(t.value))return zt(t.value);if(Wt(t._values))return zt(t._values);if(typeof t.toArray=="function")try{const n=t.toArray();if(Wt(n))return zt(n)}catch{}return null}function Wt(e){return Array.isArray(e)&&e.every(t=>typeof t=="number")}function zt(e){const t=e.slice();return{values:t,dimension:t.length}}const ki=4;function zo(e){const t=e.values.slice(0,ki).join(", "),n=e.values.length>ki?", …":"";return`vector · ${e.dimension} [${t}${n}]`}function hn(e){const t=Ke(e);if(t)return zo(t);if(Array.isArray(e))return e.map(hn);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]=hn(i);return r}}return e}function Ko(){return crypto.randomUUID()}function Qb(e){const t=Ko(),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))kr(n,t,r,s);return n}function kr(e,t,n,r){const s=Nn(r),i=Ko(),a={id:i,parentId:t,key:n,type:s,value:Zb(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[l,c]of Object.entries(r))kr(e,i,l,c);else if(s==="array"&&Array.isArray(r))for(const l of r)kr(e,i,null,l);return i}function Zb(e){return e==="map"||e==="array"}function Ho(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 Sr(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 Go(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 Jo(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 ct?void 0:"Expected a Timestamp";case"geopoint":return t instanceof rt?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 gn?void 0:"Expected a Bytes value";case"vector":return Ke(t)!==null?void 0:"Expected a vector value";case"map":case"array":return}}function Yo(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=Jo(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 l of i){const c=t[l];if(!c)continue;const u=c.key??"";u||(c.error||n++,t[l].error=t[l].error??"Field name is required");const d=a.get(u)??[];d.push(l),a.set(u,d)}for(const[l,c]of a)if(l&&c.length>1)for(const u of c)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 as(e){switch(e){case"string":return"";case"number":return 0;case"boolean":return!1;case"null":return null;case"timestamp":return ct.now();case"geopoint":return new rt(0,0);case"reference":return{path:"",id:"",firestore:{}};case"bytes":return gn.fromUint8Array(new Uint8Array);case"vector":return{__type__:"__vector__",value:[]};case"map":case"array":return}}function Er(e){if(e===null||typeof e!="object"||Ke(e)!==null)return e;if(qo(e)){const n=e;return new ct(n.seconds??n._seconds??0,n.nanoseconds??n._nanoseconds??0)}if(Wo(e)){const n=e;return new rt(n.latitude,n.longitude)}if(Array.isArray(e))return e.map(Er);const t=Object.getPrototypeOf(e);if(t===Object.prototype||t===null){const n={};for(const[r,s]of Object.entries(e))n[r]=Er(s);return n}return e}function Xo(e){const t=Qb(Er(e)),{tree:n,errorCount:r}=Yo(t);return{tree:n,initial:n,errorCount:r}}function eg(e,t){switch(t.type){case"setValue":return Ye(e,n=>ng(n,t.nodeId,t.value));case"setType":return Ye(e,n=>rg(n,t.nodeId,t.newType));case"setKey":return Ye(e,n=>sg(n,t.nodeId,t.key));case"addMapEntry":return Ye(e,n=>ig(n,t.parentId,t.key,t.childType));case"addArrayEntry":return Ye(e,n=>ag(n,t.parentId,t.childType));case"remove":return Ye(e,n=>og(n,t.nodeId));case"reset":return{tree:e.initial,initial:e.initial,errorCount:tg(e.initial)};case"replaceData":return Xo(t.data);case"touch":{const n=e.tree.nodes[t.nodeId];if(!n||n.touched)return e;const r=Sr(e.tree);return r.nodes[t.nodeId]={...r.nodes[t.nodeId],touched:!0},{...e,tree:r}}case"touchAll":{const n=Sr(e.tree);for(const r of Object.keys(n.nodes))n.nodes[r]={...n.nodes[r],touched:!0};return{...e,tree:n}}}}function Ye(e,t){const n=t(Sr(e.tree)),{tree:r,errorCount:s}=Yo(n);return{...e,tree:r,errorCount:s}}function tg(e){let t=0;for(const n of Object.values(e.nodes))n.error&&t++;return t}function ng(e,t,n){const r=e.nodes[t];return!r||r.type==="map"||r.type==="array"||(e.nodes[t]={...r,value:n}),e}function rg(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 l of Go(e,a))delete e.nodes[l],delete e.childIds[l];e.childIds[t]=[]}const s=n==="map"||n==="array"?void 0:as(n);return e.nodes[t]={...r,type:n,value:s},e}function sg(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 ig(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:as(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 ag(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:as(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 og(e,t){const n=e.nodes[t];if(!n||n.id===e.rootId)return e;const r=Go(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 Qo(e={}){const t=e.initial??{},n=h.useRef(null);n.current==null&&(n.current=Xo(t));const[r,s]=h.useReducer(eg,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}),[]),l=h.useCallback((w,x)=>s({type:"setKey",nodeId:w,key:x}),[]),c=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(()=>Ho(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:l,addMapEntry:c,addArrayEntry:u,remove:d,reset:p,replaceData:f,touch:m,touchAll:y,toData:g}),[r,v,b,i,a,l,c,u,d,p,f,m,y,g])}function lg({collection:e,query:t,pageSize:n=50,mode:r="paged"}){const[s,i]=h.useState([]),[a,l]=h.useState(!0),[c,u]=h.useState(void 0),[d,p]=h.useState(!1),[f,m]=h.useState(0),[y,g]=h.useState(n),v=h.useRef(0),[b,w]=h.useState(0),{addDoc:x,deleteDoc:k,doc:j,getDoc:_,getDocs:N,limit:P,onSnapshot:I,query:D,setDoc:C,startAfter:S}=is();h.useEffect(()=>{g(n)},[e,r,n,t]),h.useEffect(()=>{let A=!1;r==="paged"&&i([]),p(!1),l(!0),u(void 0);const O=t??e,U=r==="live"?y:n,$=D(O,P(U)),Y=ne=>{A||(i([...ne.docs]),p(ne.docs.length===U),l(!1))},se=ne=>{A||(u(ne instanceof Error?ne:new Error(String(ne))),l(!1))};if(r==="live"){const ne=++v.current,Wl=I($,zl=>{w(ne),Y(zl)},se);return()=>{A=!0,Wl()}}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"){l(!0),g($=>$+n);return}const A=s[s.length-1];if(!A)return;l(!0);const U=D(t??e,S(A),P(n));N(U).then($=>{i(Y=>[...Y,...$.docs]),p($.docs.length===n),l(!1)}).catch($=>{u($ instanceof Error?$:new Error(String($))),l(!1)})},[e,s,N,d,a,P,r,n,t,D,S]),R=h.useCallback(async(A,O,U)=>{if(A==null){const Y=await x(e,O);return r==="paged"&&m(se=>se+1),Y}const $=j(e,A);if(U?.onExisting==="fail"){const Y=await _($);if(typeof Y.exists=="function"?Y.exists():!!Y.exists){const ne=new Error(`Document "${A}" already exists.`);throw ne.code="already-exists",ne}}return await C($,O),r==="paged"&&m(Y=>Y+1),$},[x,e,j,_,r,C]),V=h.useCallback(async A=>{await k(A),r==="paged"&&m(O=>O+1)},[k,r]),G=h.useCallback(()=>m(A=>A+1),[]);return{documents:s,isLoading:a,error:c,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),[l,c]=h.useState(void 0),u=h.useRef(n);u.current=n;const d=t?.path;return h.useEffect(()=>{if(!t){s([]),a(!1),c(void 0);return}let p=!1;return a(!0),c(void 0),u.current(e,t).then(f=>{p||(s(f),a(!1))}).catch(f=>{p||(c(f instanceof Error?f:new Error(String(f))),a(!1))}),()=>{p=!0}},[e,d]),{subcollections:r,isLoading:i,error:l}}function _i(e){return typeof e=="object"&&e!==null&&"isEqual"in e&&typeof e.isEqual=="function"}function Si(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function pn(e,t){if(Object.is(e,t))return!0;if(_i(e))return e.isEqual(t);if(_i(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)=>pn(s,t[i]));if(!Si(e)||!Si(t))return!1;const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(s=>s in t&&pn(e[s],t[s]))}function ug({value:e,path:t}){return o.jsx("span",{"data-pyric-field-type":"string","data-pyric-field-path":t,children:e})}function dg({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 fg={type:"string",Display:ug,Edit:dg};function hg({value:e,path:t}){return o.jsx("span",{"data-pyric-field-type":"number","data-pyric-field-path":t,children:String(e)})}function pg({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 mg={type:"number",Display:hg,Edit:pg};function yg({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 bg({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 gg={type:"boolean",Display:yg,Edit:bg};function vg({path:e}){return o.jsx("span",{"data-pyric-field-type":"null","data-pyric-field-path":e,children:"null"})}function wg({path:e}){return o.jsx("span",{"data-pyric-field-type":"null","data-pyric-field-path":e,children:"null"})}const xg={type:"null",Display:vg,Edit:wg};function Zo(e){if(e instanceof ct)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 jg({value:e,path:t}){const n=Zo(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 kg({value:e,onChange:t,error:n,path:r}){const s=Zo(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:l=>{const c=l.target.value;if(!c)return;const u=new Date(c);t(ct.fromDate(u))},"aria-invalid":n?"true":void 0}),n?o.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const _g={type:"timestamp",Display:jg,Edit:kg};function Sg({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 Eg({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 rt(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 rt(e.latitude,i))}catch{}},"aria-label":"Longitude"})}),n?o.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const Cg={type:"geopoint",Display:Sg,Edit:Eg},el=h.createContext({});el.Provider;function Ng(){return h.useContext(el)}function Rg({value:e,path:t}){const{onReferenceClick:n}=Ng();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 Ag({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),l=a[a.length-1]??"",c=e.firestore??{};t({path:i,id:l,firestore:c,type:"document"})},"aria-invalid":n?"true":void 0}),n?o.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const Ig={type:"reference",Display:Rg,Edit:Ag};function Dg({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 Pg({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(gn.fromBase64String(s.target.value))}catch{}},"aria-invalid":n?"true":void 0}),n?o.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const $g={type:"bytes",Display:Dg,Edit:Pg};function Cr({value:e,path:t,fieldEditors:n}){const r=Nn(e),s=n[r];if(!s)return null;const{Display:i}=s;return o.jsx(i,{value:e,path:t,fieldEditors:n})}function tl({label:e,value:t,path:n,fieldEditors:r,kind:s}){const i=Nn(t),a=i==="map"||i==="array",[l,c]=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":l,onClick:()=>c(p=>!p),children:[o.jsx("span",{"data-pyric-tree-chevron":!0,"aria-hidden":"true",children:"›"}),o.jsx("span",{...u,children:e})]}),l?o.jsx(Cr,{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(Cr,{value:t,path:n,fieldEditors:r})]})}function Og({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(tl,{label:s,value:i,path:t?`${t}.${s}`:s,fieldEditors:n??{},kind:"key"},s))})}const Ug={type:"map",Display:Og};function Tg({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(tl,{label:String(s),value:r,path:t?`${t}[${s}]`:`[${s}]`,fieldEditors:n??{},kind:"index"},s))})}const Mg={type:"array",Display:Tg},Ei=4;function Bg(e){return e.length<=Ei?`[${e.join(", ")}]`:`[${e.slice(0,Ei).join(", ")}, …]`}function Lg({value:e,path:t}){const n=Ke(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:Bg(n.values)})]}):o.jsx("span",{"data-pyric-field-type":"vector","data-pyric-field-path":t})}function Fg(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 Vg({value:e,onChange:t,error:n,path:r}){const s=Ke(e),i=s?JSON.stringify(s.values):"[]",[a,l]=h.useState(i),[c,u]=h.useState(void 0),d=m=>{l(m);const y=Fg(m);if(!y.ok){u(y.error);return}u(void 0),t(y.value)},p=s?s.dimension:0,f=c??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 qg={type:"vector",Display:Lg,Edit:Vg},Ci={string:fg,number:mg,boolean:gg,null:xg,timestamp:_g,geopoint:Cg,reference:Ig,bytes:$g,map:Ug,array:Mg,vector:qg};function nl(e){return e?{...Ci,...e}:Ci}function Rn(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 l=new ResizeObserver(c=>{const u=c[0];if(!u)return;const d=u.contentRect.width;d<n?i("narrow"):d<r?i("medium"):i("wide")});return l.observe(a),()=>l.disconnect()},[n,r]),{ref:t,size:s}}const rl=h.createContext(null);function Oe(){const e=h.useContext(rl);if(!e)throw new Error("DocumentEditor.* components must render inside <DocumentEditor.Root>");return e}function Wg({initial:e,fieldEditors:t,onChange:n,children:r,className:s}){const i=Qo({initial:e}),a=nl(t),l=h.useRef(n);l.current=n,h.useEffect(()=>{l.current?.(i)},[i]);const{ref:c,size:u}=Rn();return o.jsx(rl.Provider,{value:{editor:i,fieldEditors:a},children:o.jsx("div",{ref:c,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 zg(){const{editor:e}=Oe(),t=e.tree.childIds[e.tree.rootId]??[];return o.jsxs("div",{"data-pyric-editor-fields":!0,children:[t.map(n=>o.jsx(os,{nodeId:n,path:Kg(e,n)},n)),o.jsx(sl,{parentId:e.tree.rootId})]})}function Kg(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 os({nodeId:e,path:t}){const{editor:n,fieldEditors:r}=Oe(),s=n.tree.nodes[e];if(!s)return null;if(s.type==="map")return o.jsx(Jg,{node:s,path:t});if(s.type==="array")return o.jsx(Yg,{node:s,path:t});const a=r[s.type]?.Edit;if(!a)return null;const l=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":l?"":void 0,onBlur:()=>n.touch(s.id),children:[o.jsx(ls,{node:s,path:t}),o.jsx(a,{value:s.value,path:t,error:l,onChange:c=>n.setValue(s.id,c)})]})}function ls({node:e,path:t}){const{editor:n}=Oe(),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(Gg,{node:e}),o.jsx("button",{type:"button",onClick:()=>n.remove(e.id),"data-pyric-remove":!0,"aria-label":"Remove field",children:"×"})]})}const Hg=["string","number","boolean","null","timestamp","geopoint","reference","bytes","vector","map","array"];function Gg({node:e}){const{editor:t}=Oe(),n=e.parentId!=null?t.tree.nodes[e.parentId]:null,r=Hg.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 Jg({node:e,path:t}){const{editor:n}=Oe(),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(ls,{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(os,{nodeId:s,path:a},s)})}),o.jsx(sl,{parentId:e.id})]})}function Yg({node:e,path:t}){const{editor:n}=Oe(),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(ls,{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(os,{nodeId:s,path:a})},s)})}),o.jsx(Xg,{parentId:e.id})]})}function sl({parentId:e}){const{editor:t}=Oe();return o.jsx("button",{type:"button","data-pyric-add-map-entry":!0,onClick:()=>t.addMapEntry(e,"","string"),children:"+ Add field"})}function Xg({parentId:e}){const{editor:t}=Oe();return o.jsx("button",{type:"button","data-pyric-add-array-entry":!0,onClick:()=>t.addArrayEntry(e,"string"),children:"+ Add item"})}const Ni={Root:Wg,Fields:zg};function Qg({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 wt=new Map;function cs({scope:e,entries:t,equals:n=Object.is,durationMs:r=1200,ready:s=!0}){const i=h.useRef(null),a=h.useRef(new Map),l=h.useRef(new Map),[c,u]=h.useState(wt);return h.useEffect(()=>{const d=i.current;if(!s){if(d&&d.scope!==e){i.current=null;for(const f of l.current.values())clearTimeout(f);l.current.clear(),a.current.clear(),u(wt)}return}if(!d||d.scope!==e){i.current={scope:e,entries:t};for(const f of l.current.values())clearTimeout(f);l.current.clear(),a.current.clear(),u(wt);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?wt:m:f});for(const[f,m]of p){const y=l.current.get(f);y&&clearTimeout(y);const g=setTimeout(()=>{l.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?wt:b})},r);l.current.set(f,g)}},[r,t,n,s,e]),h.useEffect(()=>()=>{for(const d of l.current.values())clearTimeout(d);l.current.clear()},[]),c}function xt(e){return e.ref}function Zg({documents:e,isLoading:t,error:n,hasMore:r,onSelect:s,onLoadMore:i,renderLabel:a,renderRowAction:l,emptyState:c,className:u,updateScope:d="document-list",virtualizeThreshold:p=100,rowHeight:f=36,virtualizedHeight:m="60vh"}){const y=h.useMemo(()=>new Map(e.map(b=>[xt(b).path,b.data()])),[e]),g=cs({scope:d,entries:y,equals:pn,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:c});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(ns,{items:e,estimateSize:f,height:m,getItemKey:b=>xt(b).path,renderItem:b=>{const w=g.get(xt(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?.(xt(b)),"data-pyric-document-select":!0,"data-pyric-update":w?.kind,"data-pyric-update-cycle":w?.cycle,children:a?a(b):b.id}),l?o.jsx("span",{"data-pyric-document-action":!0,children:l(b)}):null]})}}):o.jsx("ul",{"data-pyric-document-list-items":!0,children:e.map(b=>{const w=xt(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}),l?o.jsx("span",{"data-pyric-document-action":!0,children:l(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 ev=/^__.*__$/;function il(e){if(e.length===0)return"Cannot be empty";if(e.includes("/"))return'Cannot contain "/"';if(e==="."||e==="..")return'Cannot be "." or ".."';if(ev.test(e))return"Cannot match __.*__ (reserved)";if(nv(e)>1500)return"Cannot exceed 1500 bytes"}function tv(e){return il(e)}function nv(e){return new TextEncoder().encode(e).length}function rv(e){return il(e)}const Ri="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function sv(){let e="";for(let t=0;t<20;t++)e+=Ri.charAt(Math.floor(Math.random()*Ri.length));return e}const iv={ref:Nt,listAll:Zr,getMetadata:gh,getBlob:Im,uploadBytes:eo,uploadBytesResumable:Om,deleteObject:Qr},al=h.createContext(iv);function An(){return h.useContext(al)}function av({value:e,children:t}){return h.createElement(al.Provider,{value:e},t)}function Hn(e){return e.replace(/^\/+|\/+$/g,"")}function Nr(e,t){return e.fullPath<t.fullPath?-1:e.fullPath>t.fullPath?1:0}function Gn(e,t){return e.some(n=>n.fullPath===t.fullPath)?e:[...e,t].sort(Nr)}function ov(e,t){const{listAll:n,ref:r}=An(),s=Hn(t),[i,a]=h.useState(()=>({status:e==null?"idle":"loading",items:[],prefixes:[],error:void 0})),[l,c]=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(Nr),prefixes:[...g.prefixes].sort(Nr),error:void 0})}).catch(g=>{y||a({status:"error",items:[],prefixes:[],error:g instanceof Error?g:new Error(String(g))})}),()=>{y=!0}},[e,s,l]);const d=h.useCallback(()=>c(y=>y+1),[]),p=h.useCallback(y=>{if(e==null)return;const g=y.endsWith("/"),v=Hn(y),b=s===""?"":`${s}/`;if(!v.startsWith(b)||v===s)return;const w=v.slice(b.length),x=w.indexOf("/");a(k=>{if(k.status==="idle")return k;if(x===-1)return g?(u.current.set(v,k.prefixes.some(_=>_.fullPath===v)?null:v),{...k,prefixes:Gn(k.prefixes,r(e,v))}):(u.current.set(v,k.items.some(_=>_.fullPath===v)?null:v),{...k,items:Gn(k.items,r(e,v))});const j=`${b}${w.slice(0,x)}`;return u.current.set(v,k.prefixes.some(_=>_.fullPath===j)?null:j),{...k,prefixes:Gn(k.prefixes,r(e,j))}})},[e,s]),f=h.useCallback(y=>{const g=Hn(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 X(e){return e.split("/").filter(Boolean).join("/")}function lv(e={}){const{path:t,onPathChange:n,defaultPath:r=""}=e,s=t!==void 0,[i,a]=h.useState(()=>X(r)),l=s?X(t):i,c=h.useCallback(m=>{const y=X(m);s||a(y),n?.(y)},[s,n]),u=h.useMemo(()=>l===""?[]:l.split("/"),[l]),d=h.useCallback(m=>{const y=X(m);c(y.includes("/")||l===""?y:`${l}/${y}`)},[l,c]),p=h.useCallback(()=>{u.length!==0&&c(u.slice(0,-1).join("/"))},[u,c]),f=h.useCallback(m=>{c(m<0?"":u.slice(0,m+1).join("/"))},[u,c]);return{path:l,segments:u,setPath:c,enter:d,up:p,navigateToIndex:f}}const Ai={status:"idle",blob:void 0,url:void 0,error:void 0};function cv(e,t){const{getBlob:n,getMetadata:r,ref:s}=An(),i=t==null?null:X(t),a=e!=null&&i!=null&&i!=="",[l,c]=h.useState(()=>({status:a?"loading":"idle",metadata:void 0,error:void 0})),[u,d]=h.useState(Ai),[p,f]=h.useState(0),m=h.useRef(0);h.useEffect(()=>{if(m.current++,d(Ai),!a){c({status:"idle",metadata:void 0,error:void 0});return}let b=!1;return c({status:"loading",metadata:void 0,error:void 0}),r(s(e,i)).then(w=>{b||c({status:"success",metadata:w,error:void 0})}).catch(w=>{b||c({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:l.status,metadata:l.metadata,error:l.error,refresh:g,blobStatus:u.status,blob:u.blob,blobUrl:u.url,blobError:u.error,loadBlob:v}}function uv(){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])))},[]),l=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:l}}function dv(e,t){const n=Nt(e,t);return{storage:e,bucket:n.bucket,fullPath:`${n.fullPath}/`,name:"",parent:n,root:n.root,toString:()=>`${n.toString()}/`}}function fv(e){return{...e,fullPath:`${e.fullPath}/`,name:""}}function hv(e){return{async*start(t){const n=e??{listAll:Zr,deleteObject:Qr};let r=0;const s=[t],i=[];for(;s.length>0;){const a=s.pop();i.push(a);const l=await n.listAll(a);s.push(...l.prefixes);for(const c of l.items)await n.deleteObject(c),r++,yield{deletedCount:r,done:!1}}for(const a of i)try{await n.deleteObject(fv(a))}catch{}yield{deletedCount:r,done:!0}}}}function pv(e,t={}){const n=An(),[r,s]=h.useState(0),[i,a]=h.useState(!1),[l,c]=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),c(void 0);const y={deleted:[],failed:[]};if(e==null||f.length===0)return y;a(!0);const g=d.current.impl??hv(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&&c(x)}}return y}finally{m===u.current&&a(!1)}},[n,e]),progress:r,isRunning:i,error:l}}const mv=Object.freeze({read:!0,write:!0,delete:!0,upload:!0,reasons:Object.freeze({read:[],write:[]})});function yv(e,t={}){const{paths:n,rules:r,identity:s,writeResource:i}=t,a=e==null?null:e[wn],[l,c]=h.useState(()=>({status:e==null?"idle":"loading",rules:null,source:"none",error:void 0}));h.useEffect(()=>{if(a==null){c({status:"idle",rules:null,source:"none",error:void 0});return}if(r!=null){try{const w=typeof r=="string"?pr(r):r;c({status:"ready",rules:w,source:"option",error:void 0})}catch(w){c({status:"error",rules:null,source:"none",error:w instanceof Error?w:new Error(String(w))})}return}let b=!1;return c({status:"loading",rules:null,source:"none",error:void 0}),a.servicePromise.then(w=>{b||c({status:"ready",rules:w.rules,source:w.rules?"sandbox":"none",error:void 0})}).catch(w=>{b||c({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}=l,f=i?.size,m=i?.contentType,y=h.useCallback(b=>{if(d==null)return mv;const w=X(b),x=a?.bucket??"pyric-default",k=w===""?`b/${x}/o`:`b/${x}/o/${w}`,j=D=>Qa(d,{request:{auth:u,method:D,path:k,...D==="create"&&f!==void 0?{resource:{size:f,contentType:m}}:{}},resource:null}),_=j("read"),N=j("create"),P=j("delete"),I=N;return{read:_.allowed,write:I.allowed,delete:P.allowed,upload:N.allowed,reasons:{read:_.allowed?[]:_.reasons,write:I.allowed?[]:I.reasons}}},[d,a?.bucket,u,f,m]),g=typeof n=="string"?n:(n??[]).join(`
|
|
9
|
-
`),v=h.useMemo(()=>{const b=typeof n=="string"?[n]:n??[],w={};for(const x of b)w[X(x)]=y(x);return w},[g,y]);return{status:p,source:l.source,advisory:!1,identity:u,verdicts:v,verdictFor:y,error:l.error}}function Ii(e,t){return e===""?t:t===""?e:`${e}/${t}`}function bv(e){return e instanceof Blob?e.size:e.byteLength}function gv(e){if(e instanceof Blob){const t=e;return{path:t.webkitRelativePath||t.name,data:t}}return e}function vv(e,t={}){const{ref:n,uploadBytes:r}=An(),s=X(t.path??""),[i,a]=h.useState([]),l=h.useRef(t);l.current=t;const c=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=gv(g);return{task:{id:crypto.randomUUID(),fullPath:Ii(s,X(v.path)),status:"running",bytesTransferred:0,totalBytes:bv(v.data)},entry:v}});a(g=>[...g,...y.map(v=>v.task)]);for(const{task:g}of y)l.current.list?.insertItem(g.fullPath),l.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 c(w),l.current.onProgress?.(w),l.current.onComplete?.(w),w}catch(b){const w={...g,status:"error",error:b instanceof Error?b:new Error(String(b))};return l.current.list?.removeItem(g.fullPath),c(w),l.current.onError?.(w),w}}))},[e,s,c,n,r]),d=h.useCallback(async f=>{if(e==null)throw new Error("useObjectUpload: storage handle is null");const m=Ii(s,X(f));if(m==="")throw new Error("createFolder: folder name is empty");l.current.list?.insertItem(`${m}/`);try{await r(dv(e,m),new Blob([]),{contentType:"text/plain"})}catch(y){throw l.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 wv({path:e,onNavigate:t,rootLabel:n="/",separator:r="/",className:s}){const i=X(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((l,c)=>{const u=c===a.length-1,d=a.slice(0,c+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:l})]},d)})]})})}function xv({entries:e,status:t="success",error:n,onNavigate:r,onSelect:s,selectedPath:i,gate:a,renderEntry:l,renderRowAction:c,emptyState:u,className:d,virtualizeThreshold:p=100,rowHeight:f=36,virtualizedHeight:m="60vh"}){const{ref:y,size:g}=Rn();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:l?l(x):x.name}),c?o.jsx("span",{"data-pyric-storage-action":!0,children:c(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(ns,{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 ol(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,l)=>s.readEntries(a,l));if(i.length===0)break;for(const a of i)await ol(a,r,n)}}}async function jv(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 ol(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 kv({onFiles:e,children:t,disabled:n,disabledReason:r,className:s}){const[i,a]=h.useState(!1),l=h.useRef(0),c=h.useCallback(f=>{f.preventDefault(),!n&&(l.current+=1,a(!0))},[n]),u=h.useCallback(f=>{f.preventDefault()},[]),d=h.useCallback(f=>{f.preventDefault(),!n&&(l.current=Math.max(0,l.current-1),l.current===0&&a(!1))},[n]),p=h.useCallback(f=>{if(f.preventDefault(),l.current=0,a(!1),n)return;const m=f.dataTransfer;m&&jv(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:c,onDragOver:u,onDragLeave:d,onDrop:p,children:t})}function _v(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 Sv(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 Di(e,t){if(!t.has(e))return e;const{stem:n,ext:r}=_v(e),{base:s,counter:i}=Sv(n);let a=i===null?1:i+1;for(;;){const l=`${s} (${a})${r}`;if(!t.has(l))return l;a+=1}}function Ev(e,t){const n=new Set(t),r=new Map;return e.map(s=>{const i=s.indexOf("/");if(i===-1){const c=Di(s,n);return n.add(c),c}const a=s.slice(0,i);let l=r.get(a);return l===void 0&&(l=Di(a,n),n.add(l),r.set(a,l)),`${l}${s.slice(i)}`})}function Pi(e){const t=X(e);if(t==="")return[];const n=t.split("/");return n.map((r,s)=>n.slice(0,s+1).join("/"))}const ll=[];function Cv(e,t){switch(t.type){case"create":{const n=Pi(t.path).filter(r=>!e.includes(r));return n.length===0?e:[...e,...n].sort()}case"materialize":{const n=new Set(Pi(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=X(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:ll}}function Nv(e,t){const n=X(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 $i(e,t){return e.includes(X(t))}function Rv(e){const t=X(e);return t===""?"Enter a folder name.":t.split("/").some(r=>r==="."||r==="..")?'Folder names may not be "." or "..".':null}const Av=256*1024;function Rr(e){return(e.contentType??"").split(";")[0].trim().toLowerCase()}const Iv={id:"image",match:e=>Rr(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 Dv({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 Pv={id:"text",match:e=>{const t=Rr(e);return t.startsWith("text/")||t==="application/json"},needsBlob:!0,maxBytes:Av,render:({metadata:e,blob:t})=>t?o.jsx(Dv,{blob:t,isJson:Rr(e)==="application/json"}):null},$v=[Iv,Pv];function Ov(e,t){for(const n of[...t??[],...$v])if(n.match(e))return n}const Uv=[{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 Tv({metadata:e}){return o.jsxs("dl",{"data-pyric-object-metadata":!0,children:[Uv.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 Mv({storage:e,path:t,previews:n,renderMetadata:r,children:s,className:i}){const{ref:a,size:l}=Rn(),c=cv(e,t),{metadata:u,blobStatus:d,loadBlob:p}=c,f=u?Ov(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]),c.status==="idle")return o.jsx("div",{className:i,"data-pyric-ui":"object-inspector","data-pyric-idle":""});if(c.status==="loading")return o.jsx("div",{className:i,"data-pyric-ui":"object-inspector","data-pyric-loading":""});if(c.status==="error"||u===void 0)return o.jsx("div",{className:i,"data-pyric-ui":"object-inspector","data-pyric-error":"",role:"alert",children:c.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=c.blobError?.message):(!y||d==="success")&&(g=f.render({metadata:u,blob:c.blob,blobUrl:c.blobUrl})),o.jsxs("div",{ref:a,className:i,"data-pyric-ui":"object-inspector","data-size":l,children:[o.jsx("div",{"data-pyric-object-name":!0,children:u.name}),r?r(u):o.jsx(Tv,{metadata:u}),o.jsx("div",{"data-pyric-object-preview":!0,"data-pyric-preview":f?.id,...v,children:g}),s]})}const cl=h.createContext(null);function Bv(){const e=h.useContext(cl);if(!e)throw new Error("useToast: missing <ToastProvider> ancestor");return e}function Lv({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))},[]),l=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]),c=h.useMemo(()=>({toast:l,dismiss:a,toasts:s}),[l,a,s]);return o.jsxs(cl.Provider,{value:c,children:[e,o.jsx(Fv,{toasts:s,dismiss:a,className:n,regionLabel:r})]})}function Fv({toasts:e,dismiss:t,className:n,regionLabel:r}){const[s,i]=h.useState(!1);return h.useEffect(()=>i(!0),[]),!s||typeof document>"u"?null:ts.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 Vv({storage:e,entries:t,impl:n,list:r,gate:s,title:i,body:a,confirmLabel:l="Delete",onDeleted:c,onFailed:u,renderTrigger:d,className:p}){const f=pt(),{toast:m}=Bv(),{deleteEntries:y,isRunning:g,progress:v}=pv(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:l}))return;const _=await y(t);_.failed.length===0?(m({title:`Deleted ${_.deleted.length} ${_.deleted.length===1?"item":"items"}`,kind:"success"}),c?.(_)):(m({title:`Delete failed for ${_.failed.length} of ${t.length}`,kind:"error",body:o.jsx("ul",{"data-pyric-delete-selection-failures":!0,children:_.failed.map(N=>o.jsxs("li",{children:[N.fullPath,":"," ",N.error.code??N.error.message]},N.fullPath))})}),u?.(_))};return d?o.jsx(o.Fragment,{children:d({onClick:k,isRunning:g,progress:v,disabled:x,deniedReason:w})}):o.jsx("button",{type:"button",onClick:k,className:p,disabled:x,title:w,"data-pyric-ui":"delete-selection","data-pyric-destructive":"","data-pyric-running":g?"":void 0,"data-pyric-denied":w?"":void 0,"data-pyric-denied-reason":w,children:g?`Deleting… (${v})`:l})}function mn(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 ul(e){const t=e.indexOf("?");return Jr(t===-1?e:e.slice(0,t),t===-1?"":e.slice(t))}function qv(e){const{tab:t,rest:n,query:r}=ul(e),s=n.join("/");return t==="firestore"?{view:"firestore",path:mn(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 Wv(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 dl(e){const{tab:t,query:n}=ul(e),r=qv(e),s=t==="traffic"?n.inspect??null:null;return{target:r,selectedInspectId:s}}let Oi=null,Ar=dl("");function zv(){const e=po();return e!==Oi&&(Oi=e,Ar=dl(e)),Ar}function Kv(){return Ar}function Kt(e){ce(Wv(e))}function Hv(e){ce({tab:"traffic",query:{inspect:e}})}function In(){const e=h.useSyncExternalStore(Ut,zv,Kv),t=h.useCallback(s=>Kt(s),[]),n=h.useCallback(s=>{switch(s.kind){case"user":Kt({view:"auth",uid:s.uid});break;case"storage":Kt({view:"storage",kind:"object",path:s.objectPath});break;case"document":Kt({view:"firestore",path:mn(s.path)});break}},[]),r=h.useCallback(s=>Hv(s),[]);return h.useMemo(()=>({target:e.target,navigate:t,navigateRef:n,selectedInspectId:e.selectedInspectId,navigateInspect:r}),[e,t,n,r])}const Gv={narrowBreakpoint:640,mediumBreakpoint:920};function Jv(e){switch(e){case"narrow":return 1;case"medium":return 2;case"wide":return 3}}function Yv(e,t){const n=Jv(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 Jn({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 fl({mode:e,parentPath:t,onCreate:n,onClose:r}){const[s,i]=h.useState(""),[a,l]=h.useState(()=>sv()),[c,u]=h.useState(null),[d,p]=h.useState(null),[f,m]=h.useState(!1),y=h.useRef(null),g=e==="collection"&&s?tv(s):void 0,v=a?rv(a):void 0,w=!(e==="collection"&&(!s||g))&&!!a&&!v&&!f;h.useEffect(()=>{const j=_=>{_.key==="Escape"&&!f&&r()};return document.addEventListener("keydown",j),()=>document.removeEventListener("keydown",j)},[f,r]);const x=async()=>{if(!(!w||!c)){if(!c.isValid){c.touchAll();return}m(!0),p(null);try{await n({collectionId:e==="collection"?s:null,docId:a,data:Ho(c.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(Jn,{label:"Parent path",children:o.jsx("span",{className:"fs-modal__path",children:t})}),e==="collection"?o.jsx(Jn,{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(Jn,{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=>l(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(Ni.Root,{initial:{},onChange:u,children:o.jsx(Ni.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 hl({items:e,label:t="More actions"}){const[n,r]=h.useState(!1),[s,i]=h.useState(null),a=h.useRef(null),l=()=>{if(!n){const c=a.current?.getBoundingClientRect();c&&i({top:c.bottom+4,right:window.innerWidth-c.right})}r(c=>!c)};return h.useEffect(()=>{if(!n)return;const c=u=>{u.key==="Escape"&&(r(!1),a.current?.focus())};return document.addEventListener("keydown",c),()=>document.removeEventListener("keydown",c)},[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:l,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(c=>o.jsx("button",{type:"button",role:"menuitem",className:"fs-overflow__item","data-destructive":c.destructive?"":void 0,disabled:c.disabled,onClick:()=>{r(!1),c.onSelect()},children:c.label},c.label))})]}):null]})}function pl(e){return JSON.stringify(e)}function Xv(e,t){const n=new Map,r=(s,i)=>{const a=t(s),l=pl(i);if(a==="map"){const c=s,u=Object.keys(c).sort();n.set(l,[a,u]);for(const d of u)r(c[d],[...i,["field",d]]);return}if(a==="array"){const c=s;n.set(l,[a,c.map((u,d)=>String(d))]),c.forEach((u,d)=>r(u,[...i,["index",d]]));return}n.set(l,[a,s])};for(const[s,i]of Object.entries(e))r(i,[["field",s]]);return n}function ml(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 pl(n)}function Qv(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 Zv(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 Ui(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 ew=42;function tw(e,t,n,r=ew){const s=e.nodes[t],i=e.childIds[t]??[];let a;return s.type==="array"?a=`[${i.slice(0,3).map(c=>Ui(e.nodes[c],n.asVectorView,n.vectorPreview)).join(", ")}${i.length>3?", …":""}]`:a=`{${i.slice(0,2).map(c=>`"${e.nodes[c].key}": ${Ui(e.nodes[c],n.asVectorView,n.vectorPreview)}`).join(", ")}${i.length>2?", …":""}}`,a.length>r?`${a.slice(0,r-1)}…`:a}function nw(e,t,n){return t.parentId==null?!1:(e.childIds[t.parentId]??[]).some(s=>s!==t.id&&e.nodes[s]?.key===n)}function rw(e){return e.shiftKey===!0}const yl=["string","number","boolean","null","timestamp","geopoint","reference","bytes","vector"],sw=[...yl,"map","array"];function iw({snapshot:e,documentRef:t,onCommit:n,onDeleteDocument:r,onDeleteDocumentFields:s,fieldEditors:i,onReferenceClick:a,onStartCollection:l,firestore:c,listSubcollections:u,onSubcollectionClick:d}){const p=h.useMemo(()=>e?.data()??{},[e]),f=h.useMemo(()=>p,[]),m=Qo({initial:f}),y=m.replaceData,g=h.useMemo(()=>nl(i),[i]),v=pt(),[b,w]=h.useState(()=>new Set),[x,k]=h.useState(null),j=h.useRef(e),_=h.useRef(new Set),N=h.useRef(!1),[P,I]=h.useState(null),D=h.useMemo(()=>Xv(p,Nn),[p]),C=cs({scope:t.path,entries:D,equals:pn,ready:x===null});h.useEffect(()=>{N.current&&(N.current=!1,I(null),n(m.toData()).catch($=>{I($ instanceof Error?$:new Error(String($)))}))},[m.tree]),h.useEffect(()=>{!e||e===j.current||x!==null||(j.current=e,_.current.clear(),y(e.data()??{}))},[x,y,e]);const S=h.useCallback($=>{w(Y=>{const se=new Set(Y);return se.has($)?se.delete($):se.add($),se})},[]),[E,R]=h.useState(null),V=h.useCallback(($,Y)=>{if(Y==="map"?m.addMapEntry($,"","string"):m.addArrayEntry($,"string"),$!==m.tree.rootId){const se=ml(m.tree,$);w(ne=>new Set(ne).add(se))}R($)},[m]);h.useEffect(()=>{if(!E)return;const $=m.tree.childIds[E]??[],Y=$[$.length-1];Y&&!x&&(_.current.add(Y),k(Y),R(null))},[m.tree,E]);const G=h.useCallback($=>{m.remove($),_.current.delete($),N.current=!0,x===$&&k(null)},[m,x]),A=h.useCallback(async($,Y,se)=>{if(rw(se)){G($.id);return}await v({title:`Delete field "${Y}"?`,destructive:!0,confirmLabel:"Delete"})&&G($.id)},[v,G]),O=t.id,U=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(hl,{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:[l?o.jsx("li",{className:"fs-doctree__action-row",children:o.jsxs("button",{type:"button",className:"fs-doctree__action",onClick:l,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"]})}),U.map($=>o.jsx(bl,{nodeId:$,depth:0,editor:m,registry:g,expanded:b,onToggle:S,editingId:x,setEditingId:k,newIdsRef:_,onAdd:V,onDelete:A,onCommitNeeded:()=>{N.current=!0},onReferenceClick:a,updates:C},$))]}),c&&u?o.jsx(gl,{firestore:c,documentRef:t,listSubcollections:u,onSubcollectionClick:d}):null]})}function bl({nodeId:e,depth:t,editor:n,registry:r,expanded:s,onToggle:i,editingId:a,setEditingId:l,newIdsRef:c,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}=Zv(y,e),w=g.type==="map"||g.type==="array",x=Qv(y,e),k=ml(y,e),j=m.get(k),_=s.has(k),N=a===e,P=c.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(aw,{node:g,isNew:P,isArrayChild:b,tree:y,editor:n,registry:r,path:x,onCommitNeeded:p,onDone:()=>{c.current.delete(e),l(null)},onCancelNew:()=>{n.remove(e),c.current.delete(e),l(null)}})}):o.jsxs("li",{className:"fs-doctree__row","data-pyric-doctree-depth":t,"data-pyric-doctree-nested":w?"":void 0,style:{"--fs-depth":t},children:[o.jsxs("div",{className:"fs-doctree__line","data-pyric-update":j?.kind,"data-pyric-update-cycle":j?.cycle,children:[w?o.jsx("button",{type:"button",className:"fs-doctree__caret","aria-expanded":_,onClick:()=>i(k),children:o.jsx("span",{"aria-hidden":"true",children:_?"▼":"▶"})}):o.jsx("span",{className:"fs-doctree__caret fs-doctree__caret--empty","aria-hidden":"true"}),b?o.jsx("span",{className:"fs-doctree__chip",children:v}):o.jsx("span",{className:"fs-doctree__key",children:v}),w?_?null:o.jsx("span",{className:"fs-doctree__preview",children:tw(y,e,{asVectorView:Ke,vectorPreview:zo})}):o.jsx("span",{className:"fs-doctree__value",children:o.jsx(Cr,{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:()=>l(e),children:"✎"}),o.jsx("button",{type:"button",className:"fs-doctree__icon fs-doctree__icon--danger",title:"Delete (shift-click to skip confirmation)","aria-label":`Delete ${v||"field"} (shift-click to skip confirmation)`,onClick:I=>void d(g,v,{shiftKey:I.shiftKey}),children:"🗑"})]})]}),w&&_?o.jsxs("ul",{className:"fs-doctree__children",children:[(y.childIds[e]??[]).map(I=>o.jsx(bl,{nodeId:I,depth:t+1,editor:n,registry:r,expanded:s,onToggle:i,editingId:a,setEditingId:l,newIdsRef:c,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 aw({node:e,isNew:t,isArrayChild:n,tree:r,editor:s,registry:i,path:a,onCommitNeeded:l,onDone:c,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":nw(r,e,d)?"Field name must be unique":void 0,x=f==="map"||f==="array"?void 0:Jo(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),l(),c()},_=()=>{t?u():c()},P=i[f]?.Edit,I=f!=="map"&&f!=="array"&&P?o.jsx(P,{value:y,path:a,error:v?x:void 0,onChange:S=>g(S)}):f==="map"||f==="array"?o.jsxs("span",{className:"fs-doctree__editnote",children:["Saves as an empty ",f," — add its children afterward."]}):null,D=o.jsxs("span",{className:"fs-doctree__editactions",children:[o.jsx("button",{type:"button",className:"fs-doctree__editsave",onClick:j,"aria-label":"Save field",children:"✓"}),o.jsx("button",{type:"button",className:"fs-doctree__editcancel",onClick:_,"aria-label":"Cancel edit",children:"✕"})]}),C=o.jsx("select",{className:"fs-doctree__edittype",value:f,onChange:S=>{const E=S.target.value;m(E),E!=="map"&&E!=="array"&&E!==f&&g(ow(E))},"aria-label":"Field type",children:(t?sw:yl).map(S=>o.jsx("option",{value:S,children:S},S))});return o.jsxs("div",{className:"fs-doctree__editrow",onKeyDown:S=>{S.key==="Enter"&&!S.target.matches("textarea")?(S.preventDefault(),j()):S.key==="Escape"&&(S.preventDefault(),_())},children:[n?null:o.jsxs("div",{className:"fs-doctree__editline",children:[o.jsx("input",{type:"text",className:"fs-doctree__editkey",value:d,placeholder:"Field name",autoFocus:t,onChange:S=>p(S.target.value),onBlur:()=>b(!0),"aria-label":"Field name","aria-invalid":v&&w?"true":void 0}),C]}),o.jsxs("div",{className:"fs-doctree__editline",children:[n?C:null,I,D]}),v&&w?o.jsx("span",{className:"fs-doctree__editerr",children:w}):null]})}function ow(e){switch(e){case"string":return"";case"number":return 0;case"boolean":return!1;default:return null}}function gl({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 lw(e){return e.split("/").filter(Boolean).length%2===0}function vl(e,t){async function*n(s,i,a=!1){const l=await t.listSubcollections(s.path);for(const c of l)yield*r(e.collection(s,c),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 l of a){const c=l.path.split("/").pop();c&&(yield*n(e.doc(s,c),i,l.phantom===!0))}}return{async*start(s){const i={n:0};lw(s.path)?yield*n(s,i):yield*r(s,i),yield{deletedCount:i.n,done:!0}}}}async function wl(e,t){for await(const n of e.start(t))if(n.done)return}async function xl({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 wl(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 uw(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 dw(e){return{id:e.id,ref:e,data:()=>{},__pyricPhantom:!0}}function Ti(e){return e.__pyricPhantom===!0}function fw(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 hw({handles:e}){const{target:t,navigate:n}=In(),r=e.adminFirestore,s=is(),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]),l=(k,j)=>a(_=>[..._.slice(0,k+1),j]),[c,u]=h.useState(null),d=h.useCallback(async({collectionId:k,docId:j,data:_})=>{if(!c||!k)return;const N=c.parentDocPath,P=N?s.collection(s.doc(r,N),k):s.collection(r,k);await uw(s,P,j,_);const I=N?`${N}/${k}`:k;n({view:"firestore",path:mn(`${I}/${j}`)})},[s,r,c,n]),p=[o.jsx(yw,{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(bw,{api:s,firestore:r,handles:e,collectionPath:k.path,selectedId:i[j+1]?.id??null,onSelect:_=>l(j,{kind:"document",id:_.id,path:_.path}),onCollectionDeleted:()=>a(_=>_.slice(0,j))},k.path):o.jsx(gw,{api:s,firestore:r,handles:e,docPath:k.path,onOpenSubcollection:_=>l(j,{kind:"collection",id:_.id,path:_.path}),onReferenceClick:_=>n({view:"firestore",path:mn(_.path)}),onStartCollection:()=>u({parentDocPath:k.path}),onDeleted:()=>a(_=>_.slice(0,j))},k.path))],{ref:f,size:m}=Rn(Gv),{startIndex:y,visibleCount:g,emptySlots:v}=Yv(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(mw,{hint:j===0?w:null},`__empty_${j}__`))];return h.useEffect(()=>{if(m==="wide")return;const k=f.current;if(!k)return;const j=document.activeElement;if(j&&j!==document.body&&k.contains(j))return;const _=k.querySelector(".fs-columns > .fs-col:last-child");_&&(_.tabIndex=-1,_.focus({preventScroll:!0}))},[i.length,m]),o.jsx(ss,{children:o.jsxs("div",{ref:f,"data-pyric-ui":"fs-browser","data-fs-depth":i.length,"data-size":m,children:[o.jsx(pw,{path:i,onHome:()=>a([]),onJump:k=>a(j=>j.slice(0,k+1))}),o.jsx("div",{className:"fs-columns",children:x}),c?o.jsx(fl,{mode:"collection",parentPath:c.parentDocPath?`/${c.parentDocPath}`:"/",onCreate:d,onClose:()=>u(null)}):null]})})}function pw({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 mw({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 yw({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(Qg,{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 bw({api:e,firestore:t,handles:n,collectionPath:r,selectedId:s,onSelect:i,onCollectionDeleted:a}){const l=h.useMemo(()=>fw(e,t,r),[e,t,r]),{documents:c,isLoading:u,error:d,subscriptionGeneration:p,hasMore:f,loadMore:m,createDocument:y}=lg({collection:l,mode:"live"}),[g,v]=h.useState([]);h.useEffect(()=>{let C=!1;return Promise.resolve(n.listDocuments(r)).then(S=>{C||v(S.filter(E=>E.phantom).map(E=>E.path.split("/").pop()??""))}).catch(()=>{C||v([])}),()=>{C=!0}},[n,r,c]);const b=h.useMemo(()=>{const C=new Set(c.map(S=>S.id));return[...c,...g.filter(S=>S.length>0&&!C.has(S)).map(S=>dw(e.doc(t,`${r}/${S}`)))]},[c,g,e,t,r]),w=r.split("/").pop()??r,[x,k]=h.useState(null),[j,_]=h.useState(!1),N=pt(),P=h.useMemo(()=>vl(e,n),[e,n]),I=h.useCallback(async C=>{k(null);try{await xl({confirm:N,ref:C,api:e,recursiveImpl:P})}catch(S){k(S instanceof Error?S:new Error(String(S)))}},[e,N,P]),D=h.useCallback(async()=>{if(await N({title:`Delete collection "${w}"?`,body:"This deletes every document in it (and their subcollections).",destructive:!0,confirmLabel:"Delete collection"})){k(null);try{await wl(P,l),a()}catch(S){k(S instanceof Error?S:new Error(String(S)))}}},[N,P,l,w,a]);return o.jsxs("section",{"data-pyric-ui":"fs-documents",className:"fs-pane fs-col",children:[o.jsxs("div",{className:"fs-phead",children:[o.jsx("span",{className:"fs-phead-title",children:w}),o.jsx("span",{className:"fs-phead-actions",children:o.jsx("button",{type:"button",className:"fs-add",onClick:()=>_(!0),children:"+ New"})}),o.jsx(hl,{items:[{label:"Delete collection",onSelect:()=>void D(),destructive:!0}]})]}),j?o.jsx(fl,{mode:"document",parentPath:`/${r}`,onCreate:async({docId:C,data:S})=>{const E=await y(C,S,{onExisting:"fail"});i(E)},onClose:()=>_(!1)}):null,o.jsx(Zg,{documents:b,isLoading:u,error:d,updateScope:`${r}:${p}`,hasMore:f,onLoadMore:m,onSelect:i,renderLabel:C=>{const S=C.ref;return o.jsx("span",{"data-pyric-selected":s===S.id?"":void 0,style:{display:"contents"},children:Ti(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(Ti(C))return null;const S=C.ref;return o.jsx("button",{type:"button",className:"fs-doc-del",title:"Delete document","aria-label":`Delete ${S.id}`,onClick:E=>{E.stopPropagation(),I(S)},children:"×"})},emptyState:o.jsx("p",{className:"fs-empty",children:"No documents."})}),x?o.jsx("p",{className:"fs-empty fs-doc-del-err",children:x.message}):null]})}function gw({api:e,firestore:t,handles:n,docPath:r,onOpenSubcollection:s,onReferenceClick:i,onStartCollection:a,onDeleted:l}){const c=h.useMemo(()=>e.doc(t,r),[e,t,r]),{data:u,error:d,isLoading:p}=Yb(c),f=h.useCallback(async(k,j)=>(await n.listSubcollections(j.path)).map(N=>e.collection(j,N)),[n,e]),m=pt(),y=h.useMemo(()=>vl(e,n),[e,n]),[g,v]=h.useState(null),b=h.useCallback(async()=>{v(null);try{await xl({confirm:m,ref:c,api:e,recursiveImpl:y})&&l()}catch(k){v(k instanceof Error?k:new Error(String(k)))}},[e,m,y,c,l]),w=h.useCallback(async()=>{await e.setDoc(c,{})},[e,c]),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:c.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(iw,{snapshot:u,documentRef:c,firestore:t,listSubcollections:f,onReferenceClick:i,onSubcollectionClick:s,onStartCollection:a,onDeleteDocument:()=>void b(),onDeleteDocumentFields:w,onCommit:async k=>{await e.setDoc(c,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(gl,{firestore:t,documentRef:c,listSubcollections:f,onSubcollectionClick:s})]}),g?o.jsx("p",{className:"fs-empty fs-doc-del-err",children:g.message}):null]})}const vw="block w-full text-sm text-soft-white";function ww({auth:e,focusUid:t}){const{users:n,totalCount:r,isLoading:s,error:i,filter:a,setFilter:l,updateUser:c}=rs(e),[u,d]=h.useState(null);h.useEffect(()=>{t&&(d(t),l(t))},[t,l]);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=>l(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(Bo,{users:n,isLoading:s,error:i,filter:a,onSelect:f=>d(f.uid),className:vw,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(xw,{user:p,onSave:f=>c(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 xw({user:e,onSave:t}){const n=Mo({initial:e}),[r,s]=h.useState(null),[i,a]=h.useState(!1),l=()=>{s(null),a(!1);try{t(n.toUpdateRequest()),a(!0)}catch(c){s(c instanceof Error?c:new Error(String(c)))}};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:c=>n.setField("displayName",c.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:c=>n.setField("claimsText",c.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:c=>n.setField("disabled",c.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:l,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 Mi(e){const t=X(e),n=t.lastIndexOf("/");return n===-1?"":t.slice(0,n)}function Bi(e,t){return e===""?t:t===""?e:`${e}/${t}`}function Li(e){const t=e.lastIndexOf("/");return t===-1?e:e.slice(t+1)}const jw=[{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 kw(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"}),jw.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 _w(){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 Sw(){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 Ew(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(_w,{}):o.jsx(Sw,{})}),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 Cw({storage:e,focusTarget:t}){const n=In(),r=t.kind==="object"?X(t.path):null,s=t.kind==="prefix"?X(t.path):r?Mi(r):"",i=h.useCallback(C=>{const S=X(C);n.navigate(S?{view:"storage",kind:"prefix",path:S}:{view:"storage",kind:"root"})},[n.navigate]),a=lv({path:s,onPathChange:i}),l=C=>{n.navigate({view:"storage",kind:"object",path:X(C)})},c=ov(e,a.path),u=uv(),d=yv(e),[p,f]=h.useReducer(Cv,ll),m=vv(e,{path:a.path,list:c,onComplete:C=>f({type:"materialize",path:Mi(C.fullPath)})});h.useEffect(()=>{if(c.status==="success")for(const C of c.entries)C.kind==="folder"&&$i(p,C.fullPath)&&f({type:"materialize",path:C.fullPath})},[c.status,c.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=Nv(p,a.path).filter(R=>!c.entries.some(V=>V.kind==="folder"&&V.name===R));if(C.length===0)return c.entries;const S=C.map(R=>{const V=Bi(a.path,R);return{kind:"folder",name:R,fullPath:V,ref:{fullPath:V,name:R}}});return[...[...c.entries.filter(R=>R.kind==="folder"),...S].sort((R,V)=>R.name<V.name?-1:R.name>V.name?1:0),...c.entries.filter(R=>R.kind==="object")]},[c.entries,p,a.path]),_=j.length>0&&j.every(C=>u.isSelected(C.fullPath)),N=C=>{const S=new Set(j.map(R=>R.name)),E=Ev(C.map(R=>R.relativePath),S);m.upload(C.map((R,V)=>({path:E[V],data:R.file})))},P=C=>{C.preventDefault();const S=Rv(v);if(S){x(S);return}const E=Bi(a.path,X(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(Lv,{children:o.jsx(ss,{children:o.jsxs("div",{className:"storage",children:[o.jsxs("div",{className:"storage__sub",children:[o.jsx(wv,{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(Vv,{storage:e,entries:u.selected,list:c,gate:d,className:"studio-selection-delete",onDeleted:C=>{for(const S of u.selected)S.kind==="folder"&&C.deleted.includes(S.fullPath)&&f({type:"discard",path:S.fullPath});r&&u.selected.some(S=>S.kind==="object"?S.fullPath===r:r.startsWith(`${S.fullPath}/`))&&a.setPath(a.path),u.clear(),c.refresh()},onFailed:C=>{const S=new Set(C.failed.map(E=>E.fullPath));u.selectAll(u.selected.filter(E=>S.has(E.fullPath))),c.refresh()}}),o.jsx("button",{type:"button",className:"storage__action",onClick:u.clear,children:"Clear selection"})]}):o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:"storage__action","aria-expanded":y,onClick:()=>{g(C=>!C),x(null)},children:"New folder"}),o.jsx("button",{type:"button",className:"storage__action storage__action--upload",onClick:()=>k.current?.click(),children:"Upload files"}),o.jsx("input",{ref:k,type:"file",multiple:!0,hidden:!0,onChange:C=>{const S=Array.from(C.currentTarget.files??[]);S.length>0&&N(S.map(E=>({file:E,relativePath:E.name}))),C.currentTarget.value=""}})]})})]}),y?o.jsxs("form",{className:"storage__newfolder",onSubmit:P,children:[o.jsx("input",{autoFocus:!0,className:"storage__newfolder-input",placeholder:"folder or nested/path/of/folders","aria-label":"New folder name",value:v,onChange:C=>{b(C.currentTarget.value),x(null)},onKeyDown:C=>{C.key==="Escape"&&g(!1)}}),o.jsx("button",{type:"submit",className:"storage__newfolder-btn",children:"Create"}),w?o.jsx("span",{className:"storage__newfolder-err",role:"alert",children:w}):o.jsx("span",{className:"storage__newfolder-note",children:"Nested paths create the whole chain. Empty folders last this session only — upload a file to keep one."})]}):null,I.length>0?o.jsxs("p",{className:"storage__upload-err",role:"alert",children:[I.length===1?`Upload failed: ${Li(I[0].fullPath)} — ${I[0].error?.message??"error"}`:`${I.length} uploads failed: ${I.map(C=>Li(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(kv,{className:"storage__browser",onFiles:N,disabled:!D.upload,disabledReason:D.reasons.write.join("; "),children:[o.jsxs("div",{className:"storage__lhead",children:[o.jsx("label",{className:"storage__select-all",title:"Select all in this folder",children:o.jsx("input",{type:"checkbox","aria-label":"Select all in this folder",checked:_,onChange:C=>C.currentTarget.checked?u.selectAll(j):u.clear()})}),o.jsx("span",{children:"name"}),o.jsx("span",{children:"type"}),o.jsx("span",{children:"size"}),o.jsx("span",{children:"updated"})]}),o.jsx(xv,{entries:j,status:c.status,error:c.error,gate:d,selectedPath:r??void 0,renderEntry:Ew,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=>l(C.fullPath),emptyState:o.jsx("p",{className:"storage__empty",children:$i(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(Mv,{storage:e,path:r,renderMetadata:kw})]}):o.jsx("p",{className:"storage__inspector-hint",children:"Select an object to inspect its preview and metadata."})})]})]})})})}function Nw({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 jl({view:e}){const{target:t}=In(),n=$e(),r=n.status==="ready"?n.handles.auth:null;return o.jsx("div",{"data-pyric-ui":"data-feature",children:n.status!=="ready"||!r?o.jsx(Nw,{view:e}):n.authApi?o.jsx($o,{value:n.authApi,children:o.jsx(Fi,{view:e,handles:n.handles,auth:r,target:t,firestoreApi:n.firestoreApi,storageApi:n.storageApi})}):o.jsx(Fi,{view:e,handles:n.handles,auth:r,target:t,firestoreApi:n.firestoreApi,storageApi:n.storageApi})})}function Fi({view:e,handles:t,auth:n,target:r,firestoreApi:s,storageApi:i}){const{users:a}=rs(n),l=h.useMemo(()=>new Set(a.map(c=>c.uid)),[a]);switch(e){case"firestore":{const c=o.jsx(hw,{handles:t,knownUids:l});return s?o.jsx(Jb,{value:s,children:c}):c}case"auth":return o.jsx(ww,{auth:n,focusUid:r?.view==="auth"?r.uid:null});case"storage":{const c=o.jsx(Cw,{storage:t.storage,focusTarget:r?.view==="storage"?r:{kind:"root"}});return i?o.jsx(av,{value:i,children:c}):c}}}function Rw(){return o.jsx(jl,{view:"firestore"})}function Aw(){return o.jsx(jl,{view:"storage"})}function Iw(e,t){const n=new Set(t.map(r=>r.uid));return new Set([...e].filter(r=>n.has(r)))}async function Dw(e,t){const n=[];for(const r of e)try{await t(r.uid)}catch{n.push(r.uid)}return n}function Pw(e){const[t,n]=h.useState(()=>new Set);h.useEffect(()=>{n(s=>{const i=Iw(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 $w({users:e,filter:t,onDelete:n,onComplete:r}){const s=pt(),[i,a]=h.useState(!1),[l,c]=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),c(null);const f=await Dw(e,n);a(!1),c(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"}),l?o.jsx("span",{className:"auth-sub__error",children:l}):null]})}function kl(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 _l(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 Ow(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 Uw({auth:e}={}){const t=Pe(),n=$e(),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(Fw,{status:t.status})});const i=o.jsx(ss,{children:o.jsx(Tw,{auth:r})});return s?o.jsx($o,{value:s,children:i}):i}function Tw({auth:e}){const{users:t,totalCount:n,isLoading:r,error:s,filter:i,setFilter:a,createUser:l,updateUser:c,deleteUser:u}=rs(e),d=In(),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=Pw(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($w,{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(Bo,{users:t,isLoading:r,error:s,filter:i,onSelect:b=>{g(!1),f(b.uid)},renderIdentifier:Ow,formatCreatedAt:_l,formatLastLoginAt:kl,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(Mw,{onCancel:()=>g(!1),onCreate:async b=>{const w=await Promise.resolve(l(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(Lw,{user:m,onSave:b=>{b.mode==="edit"&&c(b.uid,b.request)},onProvidersChange:async b=>{await Promise.resolve(c(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 Mw({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(Lo,{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 Vi=[...vo];function Bw({user:e,onChange:t}){const[n,r]=h.useState(null),[s,i]=h.useState(""),a=e.providerUserInfo.map(m=>m.providerId),l=a.includes("password"),c=a.filter(m=>m!=="password"),u=c.filter(m=>!Vi.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?[...c,m]:c.filter(g=>g!==m))},f=()=>{const m=s.trim();m&&(i(""),!c.includes(m)&&d([...c,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:[...Vi,...u].map(m=>o.jsxs("label",{className:"auth-provider-row","data-pyric-provider-id":m,children:[o.jsx("input",{type:"checkbox",checked:c.includes(m),onChange:y=>p(m,y.target.checked)}),o.jsx("span",{className:"auth-provider-row__label",children:fn(m)}),o.jsx("span",{className:"auth-provider-row__id",children:m})]},m))}),l||e.isAnonymous?o.jsx("p",{className:"auth-providers-editor__derived",children:l?"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 Lw({user:e,onSave:t,onProvidersChange:n,onDelete:r}){const[s,i]=h.useState(null),[a,l]=h.useState(!1),c=p=>{i(null),l(!1);try{t(p),l(!0)}catch(f){i(f instanceof Error?f:new Error(String(f)))}},u=_l(e.createdAt),d=kl(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(Bw,{user:e,onChange:n}),o.jsxs(Lo,{initial:e,onSubmit:c,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(Kb,{user:e,onDelete:r,className:"auth-del"})})]})}function Fw({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 Vw(e){return e.operationContext.source.kind==="studio"}function qw(e,t){return t?e.filter(n=>!Vw(n)):[...e]}const Ww=["all","allow","deny","bypassed"];function Dn(e){return e.rulesDisposition.kind==="bypassed"?"bypassed":e.rulesDisposition.kind==="evaluated"?e.rulesDisposition.verdict:null}function zw(e,t){return t==="all"?[...e]:e.filter(n=>Dn(n)===t)}function Yn(e){return e.rulesDisposition.kind==="evaluated"}function qi(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 Ir="inspect";function Sl(e){const t=e[Ir];return t||null}function El(e,t){const{[Ir]:n,...r}=e;return t?{...r,[Ir]:t}:r}function Kw(e,t){return El(e,Sl(e)===t?null:t)}const Hw=h.lazy(()=>Ba(()=>import("./RulesCodeEditor.CzwHdCi9.js"),__vite__mapDeps([7,2,3])));function Cl(e){return o.jsx(h.Suspense,{fallback:o.jsx(Gw,{value:e.value,minHeightRem:e.minHeightRem}),children:o.jsx(Hw,{...e})})}function Gw({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 Nl({denial:e,rulesSource:t}){const n=Xm(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(jr,{kind:"allow",className:"rounded bg-primary/15 px-2 py-0.5 text-xs font-semibold uppercase text-primary",children:"allowed"}):o.jsx(jr,{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(Jw,{denial:e,exp:n,rulesSource:t}),o.jsx(Xw,{denial:e})]}),o.jsx(Zw,{denial:e})]})}function Jw({denial:e,exp:t,rulesSource:n}){const r=t.engine==="rtdb",s=t.engine==="storage";return r?o.jsx(nx,{denial:e,exp:t,rulesSource:n}):s?o.jsx(rx,{exp:t}):o.jsx(Yw,{denial:e,exp:t,rulesSource:n})}function Yw({denial:e,exp:t,rulesSource:n}){const r=e.evaluatedRule?.line,s=e.result==="allow",i=!!n&&n.trim().length>0;return o.jsx(Ae,{label:t.implicitDeny||!t.ruleNode?"matched rule":`matched rule — ${t.ruleNode}${r?` · line ${r}`:""}`,children:i?o.jsx(Cl,{value:n,readOnly:!0,markLine:r,markKind:s?"allow":"deny",minHeightRem:12,ariaLabel:`Deployed firestore.rules — the ${s?"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
|
|
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 Wi({eventId:e,onClose:t}){const r=cy().find(a=>a.id===e),s=r?.service??"firestore",i=by(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(Nl,{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 sx=new Intl.NumberFormat,ix={reads:"read operations",writes:"writes",deletes:"deletes"},ax={allows:"allowed requests",denies:"denied requests"};function zi(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 Ki(e){return e&&`${e[0].toUpperCase()}${e.slice(1)}`}function Dl(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=`${sx.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} ${zi(u)}.`:`${Ki(zi(u))} tied for the largest share of ${t.subject} in this window.`}}const l=s[0],c=Math.round(l.total/n*100);return{total:n,headline:i,finding:`${Ki(a(l))} accounted for ${c}% of ${t.subject} in this window.`}}function ox(e){return Dl(e,{labels:ix,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 lx(e){return Dl(e,{labels:ax,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 cx=new Intl.NumberFormat,ux=new Intl.DateTimeFormat(void 0,{hour:"numeric",minute:"2-digit"});function Hi(e){return cx.format(e)}function jt(e){return ux.format(e)}function dx(e){return Dn(e)==="bypassed"}function fx(e){return e.every(t=>t.total===0)}function Pl({eyebrow:e,story:t,series:n,points:r,window:s,emptyLabel:i,evidenceTitle:a,source:l,methodology:c}){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(xb,{series:n,visible:u,onToggle:p,formatValue:Hi,className:`traffic__metric-cards traffic__metric-cards--journal traffic__metric-cards--${n.length}`}),fx(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:[jt(s.start),"–",jt(s.end)]})]}),o.jsx(_b,{points:r,series:n,visible:u,omitZeroSeries:!0,formatValue:Hi,formatTime:jt,className:"traffic__chart traffic__chart--journal"}),o.jsxs("div",{className:"traffic__metric-axis","aria-hidden":"true",children:[o.jsx("span",{children:jt(s.start)}),o.jsx("span",{children:jt(s.end)})]})]}),o.jsxs("footer",{className:"traffic__metric-footer",children:[o.jsx("p",{className:"traffic__metric-source",children:l}),o.jsxs("details",{className:"traffic__metric-methodology",children:[o.jsx("summary",{children:"How this is counted"}),o.jsx("div",{children:c})]})]})]})}function hx({events:e,window:t}){const n=h.useMemo(()=>e.filter(i=>(i.service??"firestore")==="firestore"),[e]),r=tb({events:n,window:t,isAdmin:dx}),s=h.useMemo(()=>ox(r.series),[r.series]);return o.jsx("div",{className:"traffic__metrics","data-pyric-ui":"traffic-billable-view",children:o.jsx(Pl,{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 px({events:e,window:t}){const n=h.useMemo(()=>e.filter(a=>a.rulesDisposition.kind==="evaluated"),[e]),r=nb({events:n,window:t}),s=h.useMemo(()=>r.series.filter(a=>a.key==="allows"||a.key==="denies"),[r.series]),i=h.useMemo(()=>lx(s),[s]);return o.jsx("div",{className:"traffic__metrics","data-pyric-ui":"traffic-rules-view",children:o.jsx(Pl,{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 yx(e){return e==="billable"?"billable":e==="rules"||e==="subscriptions"?"rules":"timeline"}function bx(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 gx(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:bx(n.length,r)}}function vx(e,t){return e?.start===t.start&&e.end===t.end?null:t}function wx(){const{tab:e,query:t}=be();return e!=="traffic"?"timeline":yx(t.view)}function xx(){const e=h.useSyncExternalStore(Ut,wx,()=>"timeline"),t=h.useCallback(n=>{const r={...be().query,view:n==="timeline"?void 0:n};r.view===void 0&&delete r.view,ce({tab:"traffic",query:r})},[]);return[e,t]}function jx(){const e=h.useSyncExternalStore(Ut,()=>be().query.hide==="studio",()=>!1),t=h.useCallback(()=>{const n={...be().query};n.hide==="studio"?delete n.hide:n.hide="studio",ce({tab:"traffic",query:n})},[]);return[e,t]}function kx(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 Gi(e){return`${At(e.start)}–${At(e.end)}`}function _x({event:e}){const t=Dn(e);return t?o.jsx("span",{className:"traffic__verdict","data-verdict":t,children:t}):null}function Sx(){return h.useSyncExternalStore(Ut,()=>Sl(be().query),()=>null)}const Xn=100;function Ex(){const e=ly(),[t,n]=xx(),[r,s]=jx(),i=h.useMemo(()=>qw(e,r),[e,r]),a=e.length-i.length,[l,c]=h.useState("all"),[u,d]=h.useState(null),p=Sx(),[f,m]=h.useState(Xn),y=E=>{ce({tab:"traffic",query:Kw(be().query,E)})},g=()=>{ce({tab:"traffic",query:El(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?gx(i,u):null,[i,u]),x=w?.events??i,k=h.useMemo(()=>zw(x,l).sort((E,R)=>R.at-E.at),[x,l]),{items:j}=Fy({events:k}),_=j.slice(0,f),N=j.length-_.length,P=i.length>=un,I=i.filter(E=>E.result==="deny").length,D=E=>o.jsx(_x,{event:E}),C=E=>{if(Yn(E)){y(E.id);return}const R=qi(E);R&&ce(R)},S=p!=null&&_.some(E=>E.type!=="group"&&E.event.id===p);return o.jsxs("section",{"data-pyric-ui":"traffic-surface",className:"traffic",children:[o.jsxs("div",{className:"traffic__tabs",role:"tablist","aria-label":"Traffic views",children:[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(hx,{events:i,window:v}):t==="rules"?o.jsx(px,{events:i,window:v}):o.jsxs(o.Fragment,{children:[o.jsx(gb,{events:i,window:v,brush:u??void 0,onBrush:E=>{d(R=>vx(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 ${un})`:""]}),I>0?o.jsxs("button",{type:"button",className:"traffic__tl-deny","aria-pressed":l==="deny",onClick:()=>c(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:kx(E.start,b)}),o.jsx("span",{children:"now"})]}),renderBucketSummary:E=>o.jsxs("div",{className:"traffic__bucket-summary",children:[o.jsx("span",{children:Gi(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:Gi(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"}),Ww.map(E=>o.jsx("button",{type:"button",className:"traffic__filter","aria-pressed":l===E,onClick:()=>c(E),children:E},E))]}),p&&!S?o.jsx(Wi,{eventId:p,onClose:g},p):null,j.length===0?o.jsx("p",{className:"traffic__empty",children:w?l==="all"?"No requests occurred in the selected interval.":`No ${l} traffic occurred in the selected interval.`:l==="all"?"No requests yet. Reads, writes, and listeners against the sandbox stream in live.":`No ${l} traffic in this session.`}):o.jsxs("div",{className:"traffic__log","data-pyric-ui":"traffic-log","data-pyric-grouped":"","data-pyric-time-focused":w?"":void 0,children:[o.jsx("ul",{"data-pyric-traffic-log-items":"",children:_.map(E=>E.type==="group"?o.jsx("li",{"data-pyric-traffic-group-entry":"",children:o.jsx(yb,{group:E,onSelect:R=>{const V=R;if(Yn(V)){y(V.id);return}const G=qi(V);G&&ce(G)},renderClassification:R=>D(R),formatTime:At})},E.key):o.jsxs("li",{"data-pyric-traffic-entry":"","data-pyric-traffic-id":E.event.id,"data-verdict":Dn(E.event)??void 0,children:[o.jsx(Io,{event:E.event,selected:E.event.id===p,onSelect:R=>C(R),renderClassification:R=>D(R),formatTime:At}),E.event.id===p&&Yn(E.event)?o.jsx(Wi,{eventId:p,onClose:g},p):null]},E.event.id))}),N>0?o.jsxs("button",{type:"button",className:"traffic__show-more",onClick:()=>m(E=>E+Xn),children:["Show ",Math.min(N,Xn)," more (",N," hidden)"]}):null]})]})]})}const Ji=["amber","teal","coral","slate","olive","plum","rust","indigo","mint","sand","ash","jade"],Yi=["fox","owl","lynx","crane","otter","wren","ibex","hare","newt","moth","seal","vole"];function us(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`${Ji[t%Ji.length]}-${Yi[(t>>>4)%Yi.length]}`}function Cx(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 Nx(e){return e?{tab:"firestore",rest:e.split("/").filter(Boolean)}:null}function Rx(e){const{provenance:t,identity:n}=Cx(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:Nx(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 Ax(e,t=20){const n=[];for(let r=e.length-1;r>=0&&n.length<t;r--){const s=Rx(e[r]);s&&n.push(s)}return n}const Ix=20;function Dx(e){ce(e)}function ot({target:e,className:t,children:n,title:r}){return o.jsx("a",{className:t,href:kn(e),title:r,onClick:s=>{s.metaKey||s.ctrlKey||s.shiftKey||s.altKey||(s.preventDefault(),Dx(e))},children:n})}function Px(){const e=Pe(),t=En(),n=es();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(ot,{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(ot,{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"}),us(n)]},"instance")),o.jsx("div",{className:"studio-home__status","aria-label":"Sandbox status",children:s})}function $x(e){return new Date(e).toLocaleTimeString(void 0,{hour12:!1})}function Ox(){const e=Tt(),t=h.useMemo(()=>Ax(e,Ix),[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(ot,{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:$x(n.at)})]});return o.jsx("li",{children:n.target?o.jsx(ot,{className:"studio-home__feed-row",target:n.target,children:r}):o.jsx("span",{className:"studio-home__feed-row",children:r})},n.id)})})})]})}const Ux=["firestore","auth","rtdb","storage","traffic"];function Tx(){const e=$e(),t=Tt(),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:Ux.map(r=>{const s=We.find(i=>i.id===r);return s?o.jsxs(ot,{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 Mx(){const e=En(),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(ot,{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 Bx(){const e=$e(),t=Tt(),n=Pe(),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(Ro,{exposeFocus:Kp}),o.jsx(Px,{}),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(Mx,{}):o.jsxs(o.Fragment,{children:[o.jsx(Ox,{}),o.jsx(Tx,{})]})})]})}function te(e){const t=e.split("/").filter(Boolean);return t.length===0?"/":`/${t.join("/")}`}function ze(e){return te(e).split("/").filter(Boolean)}function Dr(e,t){return te([...ze(e),...t.split("/").filter(Boolean)].join("/"))}function $l(e,t){const n=ze(e),r=ze(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 Ol(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=Ol(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 Lx(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 ds(e){return e===null||typeof e!="object"?!1:Object.keys(e).length>0}function Ul(e){return e===null||typeof e!="object"?[]:Object.entries(e).sort(([t],[n])=>t.localeCompare(n,void 0,{numeric:!0}))}function Tl(e,t){let n=e??null;for(const r of ze(t)){if(n===null||typeof n!="object")return null;n=n[r]??null}return n}function Fx(e){return e==null?"null":Array.isArray(e)?"array":typeof e}function Pr(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,l)=>Pr(a,t[l]));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&&Pr(n[a],r[a]))}function Vx(e,t){const n=new Map,r=(s,i)=>{if(!ds(s)){n.set(i,["leaf",s??null]);return}const a=Ul(s);n.set(i,["parent",a.map(([l])=>l)]);for(const[l,c]of a)r(c,Dr(i,l))};return r(e,te(t)),n}function qx(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 Wx(e){const t=ze(e);return t.map((n,r)=>({label:n,path:`/${t.slice(0,r+1).join("/")}`}))}const zx=["string","number","boolean","json"];function Xi(e){switch(typeof e){case"string":return"string";case"number":return"number";case"boolean":return"boolean";default:return"json"}}function Kx(e,t){return t==="json"?JSON.stringify(e??null):e==null?"":String(e)}function Hx(e){if(e.trim().length===0)return"Enter a key.";const t=e.match(/[.$#[\]/]/);return t?`Keys can't contain "${t[0]}".`:null}function Gx(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 Ml(e){return{path:te(e),status:"loading",value:null,error:null,expanded:{},pages:{}}}function Bl(e,t){const n=$l(e.path,t);return n===null?null:Tl(e.value,n)}function Jx(e,t){const n=te(t);return n===e.path||e.expanded[n]===!0}function Yx(e,t,n){const r=Ul(Bl(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 Qi(e,t){const n={};let r=!1;for(const[s,i]of Object.entries(e)){const a=$l(t.path,s);a!==null&&ds(Tl(t.value,a))?n[s]=i:r=!0}return r?n:e}function Ll(e,t){switch(t.type){case"navigate":{const n=te(t.path);return n===e.path?e:Ml(n)}case"value":{if(te(t.path)!==e.path)return e;const n={...e,status:"live",value:Ol(t.value),error:null};return n.expanded=Qi(e.expanded,n),n.pages=Qi(e.pages,n),n}case"error":return te(t.path)!==e.path?e:{...e,status:"error",error:t.message};case"expand":{const n=te(t.path);return n===e.path||e.expanded[n]?e:{...e,expanded:{...e.expanded,[n]:!0}}}case"collapse":{const n=te(t.path);if(!e.expanded[n])return e;const r={...e.expanded};return delete r[n],{...e,expanded:r}}case"toggle":{const n=te(t.path);return Ll(e,{type:e.expanded[n]?"collapse":"expand",path:n})}case"show-more":{const n=te(t.path),r=e.pages[n]??t.pageSize;return{...e,pages:{...e.pages,[n]:r+t.pageSize}}}}}const Xx=50;function Qx(e,t,n={}){const r=n.pageSize??Xx,s=te(t),[i,a]=h.useReducer(Ll,s,Ml),l=h.useMemo(()=>Vx(i.value,i.path),[i.path,i.value]),c=cs({scope:i.path,entries:l,equals:Pr,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=>Bl(i,g),[i]),d=h.useCallback(g=>Jx(i,g),[i]),p=h.useCallback(g=>Yx(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=>c.get(te(g)),[c]);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 Zx({path:e,onNavigate:t,rootLabel:n="/",inputPrefix:r,className:s}){const i=te(e),[a,l]=h.useState(!1),c=h.useRef(null);h.useEffect(()=>{a&&c.current?.select()},[a]);const u=f=>{f.preventDefault(),t(qx(c.current?.value??"")),l(!1)},d=()=>l(!1),p=Wx(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:c,"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:()=>l(!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 ej({tree:e,api:t,onNavigate:n,rootLabel:r="/",className:s}){const{state:i}=e,a=ze(i.path),l=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(Fl,{tree:e,api:t,onNavigate:n,path:i.path,label:l,isViewRoot:!0})})}function Fl({tree:e,api:t,onNavigate:n,path:r,label:s,isViewRoot:i}){const a=e.valueAt(r),l=ds(a),c=e.isExpanded(r),u=e.updateAt(r),[d,p]=h.useState(!1),[f,m]=h.useState(!1),[y,g]=h.useState(!1),[v,b]=h.useState(null),w=async(j,_)=>{try{await j(),b(null),_()}catch(N){b(N instanceof Error?N.message:String(N))}},x=()=>{p(!0),g(!1),l&&!c&&e.toggle(r)},k=l&&c?e.childrenAt(r):null;return o.jsxs("div",{"data-rtdb-node":!0,"data-rtdb-kind":l?"parent":"leaf","data-rtdb-view-root":i?"":void 0,"data-rtdb-expanded":l&&c?"":void 0,children:[o.jsxs("div",{"data-rtdb-row":!0,"data-pyric-update":u?.kind,"data-pyric-update-cycle":u?.cycle,children:[l&&!i?o.jsx("button",{type:"button","data-rtdb-caret":!0,"aria-expanded":c,"aria-label":c?"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}),l?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":Fx(a),title:"Edit value",onClick:()=>{m(!0),g(!1)},children:Lx(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",l?" 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 ${Zi(r)}`,title:"Add child",onClick:x,children:"+"}),o.jsx("button",{type:"button","data-rtdb-action-delete":!0,"aria-label":`Delete ${Zi(r)}`,title:"Delete",onClick:()=>g(!0),children:"×"})]})})]}),v?o.jsx("p",{role:"alert","data-rtdb-error":!0,children:v}):null,f?o.jsx(ea,{initialType:Xi(a),initialText:Kx(a,Xi(a)),submitLabel:"Save",onCancel:()=>m(!1),onSubmit:j=>w(()=>t.set(r,j),()=>m(!1))}):null,d?o.jsx(ea,{withKey:!0,initialType:"string",initialText:"",submitLabel:"Add",onCancel:()=>p(!1),onSubmit:(j,_)=>w(()=>t.set(Dr(r,_),j),()=>p(!1))}):null,k?o.jsxs("ul",{"data-rtdb-children":!0,children:[k.entries.map(([j])=>o.jsx("li",{children:o.jsx(Fl,{tree:e,api:t,onNavigate:n,path:Dr(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 Zi(e){const t=ze(e);return t.length===0?"root":t[t.length-1]}function ea({withKey:e,initialType:t,initialText:n,submitLabel:r,onSubmit:s,onCancel:i}){const a=h.useRef(null),l=h.useRef(null),[c,u]=h.useState(t),[d,p]=h.useState(null),f=y=>{y.preventDefault();const g=a.current?.value??"";if(e){const b=Hx(g);if(b){p(b);return}}const v=Gx(c,l.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:c,onChange:y=>u(y.currentTarget.value),onKeyDown:m,children:zx.map(y=>o.jsx("option",{value:y,children:y},y))}),c==="boolean"?o.jsxs("select",{ref:l,"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:l,"data-rtdb-editor-value":!0,"aria-label":"Value",placeholder:c==="json"?'{ "key": "value" }':"value",autoFocus:!e,defaultValue:n,onKeyDown:m,spellCheck:!1}),o.jsx("button",{type:"submit","data-rtdb-editor-save":!0,children:r}),o.jsx("button",{type:"button","data-rtdb-editor-cancel":!0,onClick:i,children:"Cancel"}),d?o.jsx("span",{role:"alert","data-rtdb-editor-error":!0,children:d}):null]})}function tj(){const e=pe(),t=e.status==="ready"?e.env.live:void 0;return o.jsxs("section",{className:"studio-surface grid gap-4","aria-labelledby":"rtdb-title",children:[o.jsxs("div",{className:"studio-surface__intro",children:[o.jsx("p",{className:"studio-surface__eyebrow",children:"RTDB"}),o.jsx("h1",{id:"rtdb-title",className:"studio-surface__title",children:"RTDB"}),o.jsx("p",{className:"studio-surface__copy",children:"Browse and edit RTDB data in the shared sandbox."})]}),t?o.jsx(rj,{live:t}):o.jsx(nj,{})]})}function nj(){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 rj({live:e}){const[t,n]=h.useState("/"),r=us(es()),s=r?`${r}-sandbox`:"sandbox",i=h.useMemo(()=>({set:(l,c)=>e.setRtdbValue(l,c),remove:l=>e.deleteRtdbValue(l),subscribeValue:(l,c,u)=>e.subscribeRtdbValue(l,c,u)}),[e]),a=Qx(i,t);return o.jsxs("div",{className:"rtdb",children:[o.jsx(Zx,{className:"rtdb__pathbar",path:t,onNavigate:n,rootLabel:s,inputPrefix:s}),o.jsx(ej,{className:"rtdb__tree",tree:a,api:i,onNavigate:n,rootLabel:s})]})}function sj(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 Ht(e,t,n=`${t}s`){return`${e} ${e===1?t:n}`}function ij(e){if(e===null)return"measuring…";const t=[];return e.collections&&t.push(Ht(e.collections,"collection")),e.users&&t.push(Ht(e.users,"user")),e.objects&&t.push(Ht(e.objects,"file")),e.rtdbKeys&&t.push(Ht(e.rtdbKeys,"RTDB key")),t.length?t.join(" · "):"empty — no data yet"}function Pn(){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 aj(){return o.jsxs("svg",{...Pn(),children:[o.jsx("path",{d:"M12 4v10"}),o.jsx("path",{d:"M8 10l4 4 4-4"}),o.jsx("path",{d:"M4 19h16"})]})}function oj(){return o.jsxs("svg",{...Pn(),children:[o.jsx("path",{d:"M12 14V4"}),o.jsx("path",{d:"M8 8l4-4 4 4"}),o.jsx("path",{d:"M4 19h16"})]})}function lj(){return o.jsxs("svg",{...Pn(),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 cj(){return o.jsxs("svg",{...Pn(),children:[o.jsx("path",{d:"M4 5v5h5"}),o.jsx("path",{d:"M4.6 10a8 8 0 1 0 1.7-5.3"})]})}function Gt({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 uj(){const e=hy(),t=py(),n=my(),r=yy(),s=En(),i=h.useRef(null),a=us(es()),[l,c]=h.useState(!1),[u,d]=h.useState(!1),[p,f]=h.useState(!1),[m,y]=h.useState(!1),[g,v]=h.useState(""),b=No(),{ensure:w}=b;h.useEffect(()=>w(),[w]);const x=sj(b.entries),k=ij(x),j=s.status==="ready"?s.payload.persist?"persisted to disk":"ephemeral":"in-page · resets on reload",_=async()=>{const S=await t();if(!S||typeof document>"u")return;const E=URL.createObjectURL(new Blob([S],{type:"application/json"})),R=document.createElement("a");R.href=E,R.download=`pyric-sandbox-${a||"export"}.json`,R.click(),URL.revokeObjectURL(E)},N=async S=>{const E=S.target.files?.[0];if(S.target.value="",!!E&&!(typeof window<"u"&&!window.confirm("Import replaces all data in this sandbox. This cannot be undone. Continue?"))){d(!0);try{await n(await E.text())}finally{d(!1)}}},P=async()=>{f(!1),c(!0);try{await e()}finally{c(!1)}},I=async()=>{const S=g.trim();S&&(await r.save(S),v(""),y(!1))},D=async S=>{typeof window<"u"&&!window.confirm(`Switch to branch "${S}"? This replaces the current sandbox state.`)||await r.switchTo(S)},C=async S=>{typeof window<"u"&&!window.confirm(`Delete branch "${S}"?`)||await r.remove(S)};return o.jsxs("section",{className:"studio-surface studio-settings","aria-labelledby":"settings-title",children:[o.jsxs("div",{className:"studio-surface__intro",children:[o.jsx("p",{className:"studio-surface__eyebrow",children:"Settings"}),o.jsx("h1",{id:"settings-title",className:"studio-surface__title",children:"Configuration and maintenance."}),o.jsx("p",{className:"studio-surface__copy",children:"Global controls live here so service surfaces can stay focused on their primary work."})]}),o.jsx("div",{className:"studio-settings__grid",children:o.jsxs("section",{className:"studio-panel studio-settings__panel","aria-labelledby":"settings-sandbox-title",children:[o.jsx("h2",{id:"settings-sandbox-title",className:"studio-panel__title",children:"Sandbox"}),o.jsxs("div",{className:"studio-sandbox__live","aria-label":"Sandbox contents",children:[o.jsx("span",{className:"studio-sandbox__instance mono",children:a||"local"}),o.jsx("span",{className:"studio-sandbox__inventory",children:k}),o.jsx("span",{className:"studio-sandbox__persist",children:j})]}),o.jsxs("div",{className:"studio-sandbox__actions",children:[o.jsx(Gt,{glyph:o.jsx(aj,{}),name:"Export",caption:"Downloads all of this as one file.",onClick:()=>void _()}),o.jsx(Gt,{glyph:o.jsx(oj,{}),name:u?"Importing…":"Import",caption:"A chosen file replaces everything here.",disabled:u,onClick:()=>i.current?.click()}),o.jsx(Gt,{glyph:o.jsx(lj,{}),name:"Save branch",caption:"Keeps a copy you can return to.",onClick:()=>y(S=>!S)}),o.jsx(Gt,{glyph:o.jsx(cj,{}),name:l?"Resetting…":"Reset session",caption:"Everything returns to the seeded start.",disabled:l,danger:!0,onClick:()=>f(!0)})]}),o.jsx("input",{ref:i,type:"file",accept:"application/json,.json",className:"studio-settings__file",onChange:N}),m?o.jsxs("form",{className:"studio-sandbox__name-row",onSubmit:S=>{S.preventDefault(),I()},children:[o.jsx("input",{className:"studio-sandbox__name-input",type:"text",value:g,placeholder:"branch name","aria-label":"Branch name",autoFocus:!0,onChange:S=>v(S.target.value),onKeyDown:S=>{S.key==="Escape"&&(y(!1),v(""))}}),o.jsx("button",{type:"submit",className:"studio-button",disabled:!g.trim(),children:"Save"}),o.jsx("button",{type:"button",className:"studio-button",onClick:()=>{y(!1),v("")},children:"Cancel"})]}):null,p?o.jsxs("div",{className:"studio-sandbox__confirm",role:"alert",children:[o.jsx("span",{className:"studio-sandbox__confirm-copy",children:x&&k!=="empty — no data yet"?`This erases ${k}.`:"This erases everything in this sandbox."}),o.jsxs("span",{className:"studio-sandbox__confirm-actions",children:[o.jsx("button",{type:"button",className:"studio-button studio-button--danger",onClick:()=>void P(),children:"Erase and reseed"}),o.jsx("button",{type:"button",className:"studio-button",onClick:()=>f(!1),children:"Keep"})]})]}):null,r.branches.length>0?o.jsx("div",{className:"studio-settings__branches",children:r.branches.map(S=>o.jsxs("div",{className:"studio-settings__branch",children:[o.jsx("span",{className:"mono",children:S}),o.jsxs("span",{className:"studio-settings__branch-actions",children:[o.jsx("button",{type:"button",className:"studio-button",onClick:()=>void D(S),children:"Switch"}),o.jsx("button",{type:"button",className:"studio-button",onClick:()=>void C(S),children:"Delete"})]})]},S))}):o.jsx("p",{className:"studio-sandbox__branches-empty",children:"No branches yet — Save branch keeps this exact state to come back to."})]})})]})}function Jt(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}: ${Jt(n[a])} -> ${Jt(r[a])}`).join(", ")}return`${Jt(t.before)} -> ${Jt(t.after)}`}function fj(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 hj(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 pj="pyric:assurance-campaign",mj="pyric-assurance-v1",$r=new Set;let ta=!1,na;function ra(e){for(const t of $r)t(e)}function sa(e){return!!e&&typeof e=="object"&&e.schema==="pyric.assurance.visualization.v1"&&typeof e.campaignId=="string"}function yj(){if(!(ta||typeof document>"u")){ta=!0,globalThis.addEventListener(pj,e=>{const t=e.detail;sa(t)&&ra(t)});try{na=new BroadcastChannel(mj),na.onmessage=e=>{sa(e.data)&&ra(e.data)}}catch{}}}function bj(e){return yj(),$r.add(e),()=>$r.delete(e)}function Qn(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 gj=[Qn({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"}}),Qn({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"}),Qn({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"}}})],Lj=gj.map(e=>({...e,campaignId:"collaboration-local-v1-fixed",targetHash:"fnv1a32-a9f18f23",mutation:{...e.mutation,decision:"DENY",events:[]},stateDiff:void 0,classification:"no-counterexample"}));const Or="pyric:assurance:campaigns",Vl="pyric:assurance:campaign:";function vj(e){return!!e&&typeof e=="object"&&e.schema==="pyric.assurance.visualization.v1"&&typeof e.campaignId=="string"}function wj(){if(typeof sessionStorage>"u")return[];try{const e=JSON.parse(sessionStorage.getItem(Or)??"[]");if(!Array.isArray(e))return[];const t=e.map(n=>sessionStorage.getItem(`${Vl}${String(n)}`)).filter(n=>!!n).map(n=>JSON.parse(n)).filter(vj);return t.length,t}catch{return[]}}function xj(e){if(!(typeof sessionStorage>"u"))try{const t=JSON.parse(sessionStorage.getItem(Or)??"[]"),n=Array.isArray(t)?t.map(String):[];n.includes(e.campaignId)||n.push(e.campaignId),sessionStorage.setItem(Or,JSON.stringify(n)),sessionStorage.setItem(`${Vl}${e.campaignId}`,JSON.stringify(e))}catch{}}function jj(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 kj(){const[e,t]=h.useState(wj);return h.useEffect(()=>{const r=bj(s=>{xj(s),t(i=>jj(i,s))});return()=>{r()}},[]),e}function _j(e,t){return e!==t?"assurance-verdict--mismatch":t==="ALLOW"?"assurance-verdict--allow":"assurance-verdict--deny"}function Sj(e){return e.replaceAll("-"," ")}function ia({value:e}){return o.jsx("pre",{className:"assurance-evidence__json",children:JSON.stringify(e,null,2)})}function Ej(){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 aa({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 Cj({campaigns:e}){const t=kj(),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],l=h.useMemo(()=>a?.report?fj(a.report):[],[a]),[c,u]=h.useState(r.probe??l[0]?.id??"");if(h.useEffect(()=>{!s&&n[0]&&i(n[0].campaignId)},[s,n]),h.useEffect(()=>{l.some(x=>x.id===c)||u(l[0]?.id??"")},[l,c]),!a)return o.jsx(Ej,{});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(aa,{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=l.find(x=>x.id===c)??l[0],m=p.results.find(x=>x.probeId===f?.id),y=m?hj(m):null,g=a.verifications?.at(-1),v=g!==void 0&&g.summary.controlsPassed===g.summary.probes&&g.summary.noCounterexamples===g.summary.probes&&g.summary.localCounterexamples===0&&g.summary.engineGaps===0&&g.summary.invalidProbes===0;function b(x){i(x);const j=n.find(_=>_.campaignId===x)?.report?.results[0]?.probeId??"";u(j),ln({tab:"assurance",query:{campaign:x,probe:j||void 0}})}function w(x){u(x.id),ln({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(aa,{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"})]}),l.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 ${_j(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:Sj(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(ia,{value:m.stateDiff.before})]}),o.jsxs("div",{children:[o.jsx("span",{children:"After"}),o.jsx(ia,{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(Nl,{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 ql(){const e="/__pyric/ui/";return`${e.endsWith("/")?e:`${e}/`}docs`}function Nj(){const[e,t]=h.useState(!1);return h.useEffect(()=>{let n=!0;return fetch(`${ql()}/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 Rj({id:e}){const t=Qp(e),n=Pe(),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 Aj({id:e}){switch(e){case"home":return o.jsx(Bx,{});case"firestore":return o.jsx(Rw,{});case"auth":return o.jsx(Uw,{});case"storage":return o.jsx(Aw,{});case"rtdb":return o.jsx(tj,{});case"traffic":return o.jsx(Ex,{});case"assurance":return o.jsx(Cj,{});case"settings":return o.jsx(uj,{});default:return o.jsx(Rj,{id:e})}}function Ij(){const[e,t]=zp(Xp,"home"),n=l=>t(l),[r,s]=h.useState(!1),i=Nj(),a=e==="home";return h.useEffect(()=>{const l=c=>{if(Gp(c)){if(r){c.preventDefault(),s(!1);return}if(a){Hp()&&c.preventDefault();return}c.preventDefault(),s(!0)}};return window.addEventListener("keydown",l),()=>window.removeEventListener("keydown",l)},[a,r]),h.useEffect(()=>{a&&s(!1)},[a]),h.useEffect(()=>{document.querySelector('.studio__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:[We.map(l=>o.jsx("button",{type:"button",className:"studio__nav-tab","aria-current":l.id===e?"page":void 0,onClick:()=>n(l.id),children:l.label},l.id)),i?o.jsx("a",{className:"studio__nav-tab",href:ql(),children:"Docs"}):null]}),o.jsx(By,{})]})}),o.jsx("main",{className:"studio__content","data-surface":e,children:o.jsx("div",{className:"studio__surface-slot","data-active":"true",children:o.jsx(Aj,{id:e})})}),r?o.jsx(_y,{onClose:()=>s(!1)}):null]})}function Dj(){return o.jsx(Lp,{children:o.jsx(rd,{children:o.jsx(Op,{mode:"local",children:o.jsx(Ij,{})})})})}function Fj(){return o.jsx(h.StrictMode,{children:o.jsx(Dj,{})})}export{Fj as S,Bj as a,Sm as b,Nt as r,fe as s,eo as u};
|
|
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=l=>{r=l},a}function mi(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const sb=(e,t)=>Math.abs(e-t)<1.01,ib=(e,t,n)=>{let r;return function(...s){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,s),n)}},yi=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},ab=e=>e,ob=e=>{const t=Math.max(e.startIndex-e.overscan,0),n=Math.min(e.endIndex+e.overscan,e.count-1),r=[];for(let s=t;s<=n;s++)r.push(s);return r},lb=(e,t)=>{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;const s=a=>{const{width:l,height:c}=a;t({width:Math.round(l),height:Math.round(c)})};if(s(yi(n)),!r.ResizeObserver)return()=>{};const i=new r.ResizeObserver(a=>{const l=()=>{const c=a[0];if(c?.borderBoxSize){const u=c.borderBoxSize[0];if(u){s({width:u.inlineSize,height:u.blockSize});return}}s(yi(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(l):l()});return i.observe(n,{box:"border-box"}),()=>{i.unobserve(n)}},bi={passive:!0},gi=typeof window>"u"?!0:"onscrollend"in window,cb=(e,t)=>{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;let s=0;const i=e.options.useScrollendEvent&&gi?()=>{}:ib(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)},l=a(!0),c=a(!1);n.addEventListener("scroll",l,bi);const u=e.options.useScrollendEvent&&gi;return u&&n.addEventListener("scrollend",c,bi),()=>{n.removeEventListener("scroll",l),u&&n.removeEventListener("scrollend",c)}},ub=(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"]},db=(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 fb{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 l=i.target,c=this.indexFromElement(l);if(!l.isConnected){this.observer.unobserve(l);return}this.shouldMeasureDuringScroll(c)&&this.resizeItem(c,this.options.measureElement(l,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:ab,rangeExtractor:ob,onChange:()=>{},measureElement:ub,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=Je(()=>(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 l=n[a];if(s.has(l.lane))continue;const c=i.get(l.lane);if(c==null||l.end>c.end?i.set(l.lane,l):l.end<c.end&&s.set(l.lane,!0),s.size===this.options.lanes)break}return i.size===this.options.lanes?Array.from(i.values()).sort((a,l)=>a.end===l.end?a.index-l.index:a.end-l.end)[0]:void 0},this.getMeasurementOptions=Je(()=>[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,l,c)=>(this.prevLanes!==void 0&&this.prevLanes!==l&&(this.lanesChangedFlag=!0),this.prevLanes=l,this.pendingMeasuredCacheIndexes=[],{count:n,paddingStart:r,scrollMargin:s,getItemKey:i,enabled:a,lanes:l,laneAssignmentMode:c}),{key:!1}),this.getMeasurements=Je(()=>[this.getMeasurementOptions(),this.itemSizeCache],({count:n,paddingStart:r,scrollMargin:s,getItemKey:i,enabled:a,lanes:l,laneAssignmentMode:c},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(l).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=c==="estimate"||u.has(y);if(g!==void 0&&this.options.lanes>1){v=g;const _=f[v],N=_!==void 0?p[_]:void 0;b=N?N.end+this.options.gap:r+s}else{const _=this.options.lanes===1?p[m-1]:this.getFurthestMeasurement(p,m);b=_?_.end+this.options.gap:r+s,v=_?_.lane:m%this.options.lanes,this.options.lanes>1&&w&&this.laneAssignments.set(m,v)}const x=u.get(y),k=typeof x=="number"?x:this.options.estimateSize(m),j=b+k;p[m]={index:m,start:b,size:k,end:j,key:y,lane:v},f[v]=m}return this.measurementsCache=p,p},{key:!1,debug:()=>this.options.debug}),this.calculateRange=Je(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,s,i)=>this.range=n.length>0&&r>0?hb({measurements:n,outerSize:r,scrollOffset:s,lanes:i}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=Je(()=>{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),l=Math.min(this.options.count-1,s+i);return n>=a&&n<=l}return!0},this.measureElement=n=>{if(!n){this.elementsCache.forEach((a,l)=>{a.isConnected||(this.observer.unobserve(a),this.elementsCache.delete(l))});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,l=r-a;l!==0&&(((s=this.scrollState)==null?void 0:s.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(i,l,this):i.start<this.getScrollOffset()+this.scrollAdjustments)&&this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=l,behavior:void 0}),this.pendingMeasuredCacheIndexes.push(i.index),this.itemSizeCache=new Map(this.itemSizeCache.set(i.key,r)),this.notify(!1))},this.getVirtualItems=Je(()=>[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const s=[];for(let i=0,a=n.length;i<a;i++){const l=n[i],c=r[l];s.push(c)}return s},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length!==0)return mi(r[Do(0,r.length-1,s=>mi(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 l=this.getMaxScrollOffset();return Math.max(Math.min(l,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 l=r==="end"?a.end+this.options.scrollPaddingEnd:a.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(l,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,l]=i,c=this.now();this.scrollState={index:n,align:l,behavior:s,startedAt:c,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(l=>l===null);){const l=r[a];i[l.lane]===null&&(i[l.lane]=l.end),a--}s=Math.max(...i.filter(l=>l!==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&&sb(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 Do=(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 hb({measurements:e,outerSize:t,scrollOffset:n,lanes:r}){const s=e.length-1,i=c=>e[c].start;if(e.length<=r)return{startIndex:0,endIndex:s};let a=Do(0,s,i,n),l=a;if(r===1)for(;l<s&&e[l].end<n+t;)l++;else if(r>1){const c=Array(r).fill(0);for(;l<s&&c.some(d=>d<n+t);){const d=e[l];c[d.lane]=d.end,l++}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),l=Math.min(s,l+(r-1-l%r))}return{startIndex:a,endIndex:l}}const vi=typeof document<"u"?h.useLayoutEffect:h.useEffect;function pb({useFlushSync:e=!0,...t}){const n=h.useReducer(()=>({}),{})[1],r={...t,onChange:(i,a)=>{var l;e&&a?ts.flushSync(n):n(),(l=t.onChange)==null||l.call(t,i,a)}},[s]=h.useState(()=>new fb(r));return s.setOptions(r),vi(()=>s._didMount(),[]),vi(()=>s._willUpdate()),s}function mb(e){return pb({observeElementRect:lb,observeElementOffset:cb,scrollToFn:db,...e})}function ns({items:e,estimateSize:t,renderItem:n,overscan:r=5,className:s,height:i="100%",getItemKey:a}){const l=h.useRef(null),c=typeof t=="function"?t:()=>t,u=mb({count:e.length,getScrollElement:()=>l.current,estimateSize:c,overscan:r});return o.jsx("div",{ref:l,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 yb={batch:"batch write",transaction:"transaction","listener-run":"listener re-evals"};function bb({group:e,defaultExpanded:t=!1,onSelect:n,selectedId:r,renderClassification:s,formatTime:i,className:a}){const[l,c]=h.useState(t);return o.jsxs("div",{className:a,"data-pyric-traffic-group":"","data-pyric-group-kind":e.kind,"data-pyric-expanded":l?"":void 0,children:[o.jsxs("button",{type:"button",onClick:()=>c(u=>!u),"data-pyric-traffic-group-header":"","data-pyric-group-kind":e.kind,"aria-expanded":l,children:[o.jsx("span",{"data-pyric-group-kind-label":"",children:yb[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]}),l?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(Io,{event:u,selected:u.id===r,onSelect:n,renderClassification:s,formatTime:i})},u.id))}):null]})}function gb(e){return e<0?0:e>1?1:e}function Kn(e,t){const n=t.end-t.start;return n<=0?0:gb((e-t.start)/n)}function vb({events:e,buckets:t,window:n,bucketCount:r=30,brush:s,onBrush:i,renderBucketSummary:a,liveAt:l,header:c,axis:u,emptyState:d,className:p}){const f=h.useId(),[m,y]=h.useState(null),[g,v]=h.useState(null),b=Wy({events:e??[],window:n,bucketCount:r}),w=t??b,{buckets:x,total:k}=w,j=m??g,_=j===null?null:x.find(S=>S.index===j)??null,N=_!==null&&s?.start===_.start&&s.end===_.end;if(x.length===0)return o.jsx("div",{className:p,"data-pyric-ui":"traffic-timeline","data-pyric-empty":"",children:d});const P=k===0,I=l===void 0?n.end:l,D=I==null?null:Kn(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:[c!==void 0&&o.jsx("div",{"data-pyric-timeline-header":"",children:c}),o.jsxs("div",{"data-pyric-timeline-chart":"",children:[o.jsx("div",{"data-pyric-timeline-bars":"",role:i?"group":"img","aria-label":"request volume over time",children:x.map(S=>o.jsx(wb,{bucket:S,window:n,onBrush:i,onHover:a?y:void 0,onFocus:a?v:void 0,summaryId:a&&!N&&_?.index===S.index?f:void 0,selected:s?.start===S.start&&s.end===S.end},S.index))}),_&&a&&!N?o.jsx("div",{id:f,role:"tooltip","data-pyric-bucket-summary":"",style:{"--pyric-bucket-summary-x":(_.index+.5)/Math.max(x.length,1)},children:a(_)}):null,s&&o.jsx("div",{"data-pyric-brush":"","aria-hidden":"true",style:{"--pyric-brush-left":Kn(s.start,n),"--pyric-brush-right":1-Kn(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 wb({bucket:e,window:t,onBrush:n,onHover:r,onFocus:s,summaryId:i,selected:a}){const l=n!==void 0,c=`${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:!l,"aria-label":`${c}, ${u}`,"aria-describedby":i,"aria-pressed":l?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:l?()=>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 xb=e=>String(e);function jb({series:e,visible:t,onToggle:n,formatValue:r=xb,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,l)=>{const c=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":l,"data-pyric-metric-hidden":c?void 0:"",children:[o.jsx("input",{type:"checkbox",checked:c,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":l,children:u},a.key)})})}const kb=e=>String(e),_b=e=>new Date(e).toLocaleTimeString();function Sb({points:e,series:t,visible:n,omitZeroSeries:r=!1,formatValue:s=kb,formatTime:i=_b,emptyState:a,className:l}){const[c,u]=h.useState(null);if(e.length===0)return o.jsx("div",{className:l,"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=c!=null?e[c]:null;return o.jsx("div",{className:l,"data-pyric-ui":"traffic-line-chart",children:o.jsxs("div",{"data-pyric-chart-svg":"",children:[o.jsx("svg",{viewBox:"0 0 100 100",preserveAspectRatio:"none",role:"img","aria-label":"metrics over time",children:t.map(b=>{const w=t.indexOf(b);if(!((!n||n.has(b.key))&&(!r||b.total>0)))return null;const k=b.values.map((j,_)=>`${_===0?"M":"L"}${y(_)},${g(j)}`).join(" ");return o.jsx("path",{"data-pyric-chart-line":"","data-pyric-series-key":b.key,"data-pyric-series-index":w,d:k,fill:"none",vectorEffect:"non-scaling-stroke"},b.key)})}),o.jsx("div",{"data-pyric-chart-hits":"",children:e.map((b,w)=>o.jsx("button",{type:"button","data-pyric-chart-hit":"","data-pyric-point-index":w,onMouseEnter:()=>u(w),onFocus:()=>u(w),onMouseLeave:()=>u(x=>x===w?null:x),onBlur:()=>u(x=>x===w?null:x),"aria-label":`${i(b.start)} to ${i(b.end)}`},b.index))}),v&&o.jsxs("div",{"data-pyric-chart-tooltip":"",style:{"--pyric-hover-x":y(v.index)},children:[o.jsxs("div",{"data-pyric-tooltip-time":"",children:[i(v.start)," – ",i(v.end)]}),d.map(b=>o.jsxs("div",{"data-pyric-tooltip-row":"","data-pyric-series-key":b.key,"data-pyric-series-index":t.indexOf(b),children:[o.jsx("span",{"data-pyric-tooltip-label":"",children:b.label}),o.jsx("span",{"data-pyric-tooltip-value":"",children:s(b.values[v.index])})]},b.key))]})]})})}const Eb={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},Po=h.createContext(Eb);function Cb(){return h.useContext(Po)}function $o({value:e,children:t}){return h.createElement(Po.Provider,{value:e},t)}function Nb(e,t){return[e.uid,e.email,e.displayName,e.phoneNumber].some(n=>n!=null&&n.toLowerCase().includes(t))}function rs(e){const{listUsers:t,subscribeUsers:n,createUser:r,updateUser:s,deleteUser:i,clearUsers:a}=Cb(),[l,c]=h.useState([]),[u,d]=h.useState(!0),[p,f]=h.useState(void 0),[m,y]=h.useState("");h.useEffect(()=>{let j=!1;d(!0),f(void 0);const _=D=>{j||(c(D),d(!1))},N=D=>{j||(c([]),f(D instanceof Error?D:new Error(String(D))),d(!1))},P=()=>{try{const D=t(e);D&&typeof D.then=="function"?D.then(_).catch(N):_(D)}catch(D){N(D)}};let I;try{P(),I=n(e,P)}catch(D){N(D)}return()=>{j=!0,I?.()}},[e,t,n]);const g=h.useMemo(()=>{const j=m.trim().toLowerCase();return j?l.filter(_=>Nb(_,j)):l},[l,m]),v=h.useCallback(j=>r(e,j),[e,r]),b=h.useCallback((j,_)=>s(e,j,_),[e,s]),w=h.useCallback(j=>i(e,j),[e,i]),x=h.useCallback(()=>a(e),[e,a]),k=h.useCallback(()=>{const j=t(e);j&&typeof j.then=="function"?j.then(_=>c(_)).catch(()=>{}):c(j)},[e,t]);return{users:g,totalCount:l.length,isLoading:u,error:p,filter:m,setFilter:y,createUser:v,updateUser:b,deleteUser:w,clearUsers:x,refresh:k}}const Rb=["iss","aud","sub","iat","exp","nbf","jti","nonce","azp","acr","amr","cnf","auth_time","firebase","at_hash","c_hash"],Ab=1e3;function Oo(e){const t=e.trim();if(!t)return{ok:!0,claims:void 0};if(t.length>Ab)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 Rb)if(r in n)return{ok:!1,message:`Custom claims must not have forbidden key: ${r}`};return{ok:!0,claims:n}}const Ib={email:"",password:"",displayName:"",phoneNumber:"",photoUrl:"",emailVerified:!1,disabled:!1,claimsText:"",providerIds:[]},Db=new Set(["password","anonymous","phone"]),Pb=/^[^@]+@[^@]+\.[^@]+$/,wi=6;function $b(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=>!Db.has(t))}:{...Ib}}function Ob(e){const t=$b(e);return{fields:t,initial:{...t}}}function Ub(e,t){switch(t.type){case"setField":return{...e,fields:{...e.fields,[t.field]:t.value}};case"reset":return{...e,fields:{...e.initial}}}}function Mb(e){const t={},n=e.email.trim(),r=e.password;n&&!Pb.test(n)&&(t.email="Invalid email"),r&&r.length<wi&&(t.password=`Password should be at least ${wi} characters`),r&&!n&&(t.password="Email is required for password authentication");const s=Oo(e.claimsText);return s.ok||(t.claims=s.message),t}function Tb(e){const{fields:t,initial:n}=e;return Object.keys(t).some(r=>r==="providerIds"?!Uo(t.providerIds,n.providerIds):t[r]!==n[r])}function Uo(e,t){if(e.length!==t.length)return!1;const n=[...t].sort();return[...e].sort().every((r,s)=>r===n[s])}function Mo(e){const t=Oo(e.claimsText);return t.ok?t.claims:void 0}function Bb(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=Mo(t);return r&&(n.customClaims=r),t.providerIds.length&&(n.providerUserInfo=t.providerIds.map(s=>({providerId:s}))),n}function Lb(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=Mo(t)??{}),Uo(t.providerIds,n.providerIds)||(r.providerUserInfo=t.providerIds.map(s=>({providerId:s}))),r}function To(e={}){const[t,n]=h.useReducer(Ub,e.initial,Ob),r=h.useMemo(()=>Mb(t.fields),[t.fields]),s=h.useMemo(()=>Tb(t),[t]),i=h.useCallback((l,c)=>n({type:"setField",field:l,value:c}),[]),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:()=>Bb(t),toUpdateRequest:()=>Lb(t),dispatch:n}}const Fb={"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 fn(e){return Fb[e]??e}function xi(e){return e.email??e.phoneNumber??(e.isAnonymous?"anonymous":e.uid)}function Vb(e){return e.isAnonymous&&e.providerUserInfo.length===0?o.jsx("span",{"data-pyric-provider-id":"anonymous",children:fn("anonymous")}):e.providerUserInfo.map(t=>o.jsx("span",{"data-pyric-provider-id":t.providerId,children:fn(t.providerId)},t.providerId))}function ji(e){if(!e)return"—";const t=new Date(e);return Number.isNaN(t.getTime())?"—":t.toLocaleDateString()}function Bo({users:e,isLoading:t,error:n,filter:r,onSelect:s,renderIdentifier:i,renderProviders:a,renderSelection:l,renderSelectionHeader:c,renderActions:u,renderActionsHeader:d,formatCreatedAt:p=ji,formatLastLoginAt:f=ji,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:[l?o.jsx("span",{role:"cell","data-pyric-user-cell":"selection",children:l(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):xi(j)}):(i??xi)(j)}),o.jsx("span",{role:"cell","data-pyric-user-cell":"providers",children:(a??Vb)(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":l?"":void 0,"data-pyric-actions":u?"":void 0,children:[o.jsxs("div",{role:"row","data-pyric-user-header":!0,children:[l?o.jsx("span",{role:"columnheader","data-pyric-user-cell":"selection","aria-label":"Selection",children:c}):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(ns,{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 qb({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 Wb({selected:e,onChange:t}){return o.jsx("div",{"data-pyric-provider-checklist":!0,children:vo.map(n=>o.jsxs("label",{"data-pyric-provider-option":n,children:[o.jsx("input",{type:"checkbox",checked:e.includes(n),onChange:r=>t(r.target.checked?[...e,n]:e.filter(s=>s!==n))}),o.jsx("span",{"data-pyric-provider-option-label":!0,children:fn(n)}),o.jsx("span",{"data-pyric-provider-option-id":!0,children:n})]},n))})}function Lo({initial:e,onSubmit:t,onCancel:n,submitLabel:r="Save",cancelLabel:s="Cancel",children:i,className:a,renderField:l}){const c=To({initial:e}),u=e?"edit":"create",d=c.isValid&&(u==="create"||c.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:c.fields.email,onChange:y=>c.setField("email",y.target.value)}),c.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:c.fields.password,onChange:y=>c.setField("password",y.target.value)}),c.errors.password??null),p("display-name","Display name","text",o.jsx("input",{type:"text","data-pyric-field":"display-name",placeholder:"Display name (optional)",value:c.fields.displayName,onChange:y=>c.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:c.fields.phoneNumber,onChange:y=>c.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:c.fields.photoUrl,onChange:y=>c.setField("photoUrl",y.target.value)})),...u==="create"?[p("providers","Sign-in providers","group",o.jsx(Wb,{selected:c.fields.providerIds,onChange:y=>c.setField("providerIds",y)}))]:[],p("email-verified","Verified email","checkbox",o.jsx("input",{type:"checkbox","data-pyric-field":"email-verified",checked:c.fields.emailVerified,onChange:y=>c.setField("emailVerified",y.target.checked)})),p("disabled","Disabled (sign-in attempts are rejected)","checkbox",o.jsx("input",{type:"checkbox","data-pyric-field":"disabled",checked:c.fields.disabled,onChange:y=>c.setField("disabled",y.target.checked)}))],m=y=>{y.preventDefault(),d&&t(u==="edit"?{mode:u,uid:e.uid,request:c.toUpdateRequest()}:{mode:u,request:c.toCreateRequest()})};return o.jsxs("form",{className:a,"data-pyric-ui":"auth-user-form","data-pyric-mode":u,"data-pyric-is-dirty":c.isDirty?"":void 0,"data-pyric-is-valid":c.isValid?"":void 0,onSubmit:m,children:[f.map(y=>l?o.jsx(h.Fragment,{children:l(y)},y.name):y.defaultRender()),o.jsx(qb,{value:c.fields.claimsText,onChange:y=>c.setField("claimsText",y),error:c.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 zb({open:e,onOpenChange:t,title:n,body:r,destructive:s,confirmLabel:i="Confirm",cancelLabel:a="Cancel",onConfirm:l,className:c}){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:ts.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:c,"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:l,children:i})]})]})]}),document.body)}const Fo=h.createContext(null);function pt(){const e=h.useContext(Fo);if(!e)throw new Error("useConfirm: missing <ConfirmProvider> ancestor");return e}function ss({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]),l=h.useCallback(u=>{u||n&&(s.current||(s.current=!0,n.resolve(!1),r(null)))},[n]),c=h.useMemo(()=>i,[i]);return o.jsxs(Fo.Provider,{value:c,children:[e,n?o.jsx(zb,{open:!0,onOpenChange:l,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 Kb(e){return e.email??e.phoneNumber??e.displayName??e.uid}function Hb({user:e,onDelete:t,title:n="Delete user",body:r,confirmLabel:s="Delete",renderTrigger:i,className:a}){const l=pt(),c=async()=>{await l({title:n,body:r??`This will permanently delete ${Kb(e)}.`,destructive:!0,confirmLabel:s})&&t(e.uid)};return i?o.jsx(o.Fragment,{children:i({onClick:c})}):o.jsx("button",{type:"button",className:a,"data-pyric-ui":"delete-user","data-pyric-destructive":!0,onClick:c,children:"Delete user"})}function Gb(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 Jb={addDoc:fa,collection:kt,deleteDoc:Zn,doc:Be,getDoc:va,getDocs:Zt,limit:an,onSnapshot:Hu,query:sn,setDoc:Qt,startAfter:Ku},Vo=h.createContext(Jb);function is(){return h.useContext(Vo)}function Yb({value:e,children:t}){return h.createElement(Vo.Provider,{value:e},t)}function Xb(e){const{onSnapshot:t}=is(),[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:Gb(i),isLoading:!1}))},[t,e]),n}function Nn(e){return e==null?"null":typeof e=="string"?"string":typeof e=="number"?"number":typeof e=="boolean"?"boolean":typeof e=="object"&&Ke(e)!==null?"vector":Array.isArray(e)?"array":e instanceof ct?"timestamp":e instanceof rt?"geopoint":e instanceof gn?"bytes":typeof e=="object"&&qo(e)?"timestamp":typeof e=="object"&&Wo(e)?"geopoint":typeof e=="object"&&Qb(e)?"reference":typeof e=="object"?"map":"null"}function qo(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 Wo(e){const t=e;return Object.keys(t).length===2&&typeof t.latitude=="number"&&typeof t.longitude=="number"}function Qb(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 Ke(e){if(e===null||typeof e!="object")return null;const t=e;if(t.typeName==="vector"&&Wt(t.value)||t.__type__==="__vector__"&&Wt(t.value))return zt(t.value);if(Wt(t._values))return zt(t._values);if(typeof t.toArray=="function")try{const n=t.toArray();if(Wt(n))return zt(n)}catch{}return null}function Wt(e){return Array.isArray(e)&&e.every(t=>typeof t=="number")}function zt(e){const t=e.slice();return{values:t,dimension:t.length}}const ki=4;function zo(e){const t=e.values.slice(0,ki).join(", "),n=e.values.length>ki?", …":"";return`vector · ${e.dimension} [${t}${n}]`}function hn(e){const t=Ke(e);if(t)return zo(t);if(Array.isArray(e))return e.map(hn);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]=hn(i);return r}}return e}function Ko(){return crypto.randomUUID()}function Zb(e){const t=Ko(),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))kr(n,t,r,s);return n}function kr(e,t,n,r){const s=Nn(r),i=Ko(),a={id:i,parentId:t,key:n,type:s,value:eg(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[l,c]of Object.entries(r))kr(e,i,l,c);else if(s==="array"&&Array.isArray(r))for(const l of r)kr(e,i,null,l);return i}function eg(e){return e==="map"||e==="array"}function Ho(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 Sr(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 Go(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 Jo(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 ct?void 0:"Expected a Timestamp";case"geopoint":return t instanceof rt?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 gn?void 0:"Expected a Bytes value";case"vector":return Ke(t)!==null?void 0:"Expected a vector value";case"map":case"array":return}}function Yo(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=Jo(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 l of i){const c=t[l];if(!c)continue;const u=c.key??"";u||(c.error||n++,t[l].error=t[l].error??"Field name is required");const d=a.get(u)??[];d.push(l),a.set(u,d)}for(const[l,c]of a)if(l&&c.length>1)for(const u of c)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 as(e){switch(e){case"string":return"";case"number":return 0;case"boolean":return!1;case"null":return null;case"timestamp":return ct.now();case"geopoint":return new rt(0,0);case"reference":return{path:"",id:"",firestore:{}};case"bytes":return gn.fromUint8Array(new Uint8Array);case"vector":return{__type__:"__vector__",value:[]};case"map":case"array":return}}function Er(e){if(e===null||typeof e!="object"||Ke(e)!==null)return e;if(qo(e)){const n=e;return new ct(n.seconds??n._seconds??0,n.nanoseconds??n._nanoseconds??0)}if(Wo(e)){const n=e;return new rt(n.latitude,n.longitude)}if(Array.isArray(e))return e.map(Er);const t=Object.getPrototypeOf(e);if(t===Object.prototype||t===null){const n={};for(const[r,s]of Object.entries(e))n[r]=Er(s);return n}return e}function Xo(e){const t=Zb(Er(e)),{tree:n,errorCount:r}=Yo(t);return{tree:n,initial:n,errorCount:r}}function tg(e,t){switch(t.type){case"setValue":return Ye(e,n=>rg(n,t.nodeId,t.value));case"setType":return Ye(e,n=>sg(n,t.nodeId,t.newType));case"setKey":return Ye(e,n=>ig(n,t.nodeId,t.key));case"addMapEntry":return Ye(e,n=>ag(n,t.parentId,t.key,t.childType));case"addArrayEntry":return Ye(e,n=>og(n,t.parentId,t.childType));case"remove":return Ye(e,n=>lg(n,t.nodeId));case"reset":return{tree:e.initial,initial:e.initial,errorCount:ng(e.initial)};case"replaceData":return Xo(t.data);case"touch":{const n=e.tree.nodes[t.nodeId];if(!n||n.touched)return e;const r=Sr(e.tree);return r.nodes[t.nodeId]={...r.nodes[t.nodeId],touched:!0},{...e,tree:r}}case"touchAll":{const n=Sr(e.tree);for(const r of Object.keys(n.nodes))n.nodes[r]={...n.nodes[r],touched:!0};return{...e,tree:n}}}}function Ye(e,t){const n=t(Sr(e.tree)),{tree:r,errorCount:s}=Yo(n);return{...e,tree:r,errorCount:s}}function ng(e){let t=0;for(const n of Object.values(e.nodes))n.error&&t++;return t}function rg(e,t,n){const r=e.nodes[t];return!r||r.type==="map"||r.type==="array"||(e.nodes[t]={...r,value:n}),e}function sg(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 l of Go(e,a))delete e.nodes[l],delete e.childIds[l];e.childIds[t]=[]}const s=n==="map"||n==="array"?void 0:as(n);return e.nodes[t]={...r,type:n,value:s},e}function ig(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 ag(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:as(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 og(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:as(n);return e.nodes[s]={id:s,parentId:t,key:null,type:n,value:i},e.childIds[s]=[],e.childIds[t]=[...e.childIds[t]??[],s],e}function lg(e,t){const n=e.nodes[t];if(!n||n.id===e.rootId)return e;const r=Go(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 Qo(e={}){const t=e.initial??{},n=h.useRef(null);n.current==null&&(n.current=Xo(t));const[r,s]=h.useReducer(tg,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}),[]),l=h.useCallback((w,x)=>s({type:"setKey",nodeId:w,key:x}),[]),c=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(()=>Ho(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:l,addMapEntry:c,addArrayEntry:u,remove:d,reset:p,replaceData:f,touch:m,touchAll:y,toData:g}),[r,v,b,i,a,l,c,u,d,p,f,m,y,g])}function cg({collection:e,query:t,pageSize:n=50,mode:r="paged"}){const[s,i]=h.useState([]),[a,l]=h.useState(!0),[c,u]=h.useState(void 0),[d,p]=h.useState(!1),[f,m]=h.useState(0),[y,g]=h.useState(n),v=h.useRef(0),[b,w]=h.useState(0),{addDoc:x,deleteDoc:k,doc:j,getDoc:_,getDocs:N,limit:P,onSnapshot:I,query:D,setDoc:C,startAfter:S}=is();h.useEffect(()=>{g(n)},[e,r,n,t]),h.useEffect(()=>{let A=!1;r==="paged"&&i([]),p(!1),l(!0),u(void 0);const O=t??e,U=r==="live"?y:n,$=D(O,P(U)),Y=ne=>{A||(i([...ne.docs]),p(ne.docs.length===U),l(!1))},se=ne=>{A||(u(ne instanceof Error?ne:new Error(String(ne))),l(!1))};if(r==="live"){const ne=++v.current,Wl=I($,zl=>{w(ne),Y(zl)},se);return()=>{A=!0,Wl()}}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"){l(!0),g($=>$+n);return}const A=s[s.length-1];if(!A)return;l(!0);const U=D(t??e,S(A),P(n));N(U).then($=>{i(Y=>[...Y,...$.docs]),p($.docs.length===n),l(!1)}).catch($=>{u($ instanceof Error?$:new Error(String($))),l(!1)})},[e,s,N,d,a,P,r,n,t,D,S]),R=h.useCallback(async(A,O,U)=>{if(A==null){const Y=await x(e,O);return r==="paged"&&m(se=>se+1),Y}const $=j(e,A);if(U?.onExisting==="fail"){const Y=await _($);if(typeof Y.exists=="function"?Y.exists():!!Y.exists){const ne=new Error(`Document "${A}" already exists.`);throw ne.code="already-exists",ne}}return await C($,O),r==="paged"&&m(Y=>Y+1),$},[x,e,j,_,r,C]),V=h.useCallback(async A=>{await k(A),r==="paged"&&m(O=>O+1)},[k,r]),G=h.useCallback(()=>m(A=>A+1),[]);return{documents:s,isLoading:a,error:c,subscriptionGeneration:b,hasMore:d,loadMore:E,createDocument:R,deleteDocument:V,refresh:G}}function ug({firestore:e,documentRef:t,listSubcollections:n}){const[r,s]=h.useState([]),[i,a]=h.useState(!1),[l,c]=h.useState(void 0),u=h.useRef(n);u.current=n;const d=t?.path;return h.useEffect(()=>{if(!t){s([]),a(!1),c(void 0);return}let p=!1;return a(!0),c(void 0),u.current(e,t).then(f=>{p||(s(f),a(!1))}).catch(f=>{p||(c(f instanceof Error?f:new Error(String(f))),a(!1))}),()=>{p=!0}},[e,d]),{subcollections:r,isLoading:i,error:l}}function _i(e){return typeof e=="object"&&e!==null&&"isEqual"in e&&typeof e.isEqual=="function"}function Si(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function pn(e,t){if(Object.is(e,t))return!0;if(_i(e))return e.isEqual(t);if(_i(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)=>pn(s,t[i]));if(!Si(e)||!Si(t))return!1;const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(s=>s in t&&pn(e[s],t[s]))}function dg({value:e,path:t}){return o.jsx("span",{"data-pyric-field-type":"string","data-pyric-field-path":t,children:e})}function fg({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 hg={type:"string",Display:dg,Edit:fg};function pg({value:e,path:t}){return o.jsx("span",{"data-pyric-field-type":"number","data-pyric-field-path":t,children:String(e)})}function mg({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 yg={type:"number",Display:pg,Edit:mg};function bg({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 gg({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 vg={type:"boolean",Display:bg,Edit:gg};function wg({path:e}){return o.jsx("span",{"data-pyric-field-type":"null","data-pyric-field-path":e,children:"null"})}function xg({path:e}){return o.jsx("span",{"data-pyric-field-type":"null","data-pyric-field-path":e,children:"null"})}const jg={type:"null",Display:wg,Edit:xg};function Zo(e){if(e instanceof ct)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 kg({value:e,path:t}){const n=Zo(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 _g({value:e,onChange:t,error:n,path:r}){const s=Zo(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:l=>{const c=l.target.value;if(!c)return;const u=new Date(c);t(ct.fromDate(u))},"aria-invalid":n?"true":void 0}),n?o.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const Sg={type:"timestamp",Display:kg,Edit:_g};function Eg({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 Cg({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 rt(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 rt(e.latitude,i))}catch{}},"aria-label":"Longitude"})}),n?o.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const Ng={type:"geopoint",Display:Eg,Edit:Cg},el=h.createContext({});el.Provider;function Rg(){return h.useContext(el)}function Ag({value:e,path:t}){const{onReferenceClick:n}=Rg();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 Ig({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),l=a[a.length-1]??"",c=e.firestore??{};t({path:i,id:l,firestore:c,type:"document"})},"aria-invalid":n?"true":void 0}),n?o.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const Dg={type:"reference",Display:Ag,Edit:Ig};function Pg({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 $g({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(gn.fromBase64String(s.target.value))}catch{}},"aria-invalid":n?"true":void 0}),n?o.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const Og={type:"bytes",Display:Pg,Edit:$g};function Cr({value:e,path:t,fieldEditors:n}){const r=Nn(e),s=n[r];if(!s)return null;const{Display:i}=s;return o.jsx(i,{value:e,path:t,fieldEditors:n})}function tl({label:e,value:t,path:n,fieldEditors:r,kind:s}){const i=Nn(t),a=i==="map"||i==="array",[l,c]=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":l,onClick:()=>c(p=>!p),children:[o.jsx("span",{"data-pyric-tree-chevron":!0,"aria-hidden":"true",children:"›"}),o.jsx("span",{...u,children:e})]}),l?o.jsx(Cr,{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(Cr,{value:t,path:n,fieldEditors:r})]})}function Ug({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(tl,{label:s,value:i,path:t?`${t}.${s}`:s,fieldEditors:n??{},kind:"key"},s))})}const Mg={type:"map",Display:Ug};function Tg({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(tl,{label:String(s),value:r,path:t?`${t}[${s}]`:`[${s}]`,fieldEditors:n??{},kind:"index"},s))})}const Bg={type:"array",Display:Tg},Ei=4;function Lg(e){return e.length<=Ei?`[${e.join(", ")}]`:`[${e.slice(0,Ei).join(", ")}, …]`}function Fg({value:e,path:t}){const n=Ke(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:Lg(n.values)})]}):o.jsx("span",{"data-pyric-field-type":"vector","data-pyric-field-path":t})}function Vg(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 qg({value:e,onChange:t,error:n,path:r}){const s=Ke(e),i=s?JSON.stringify(s.values):"[]",[a,l]=h.useState(i),[c,u]=h.useState(void 0),d=m=>{l(m);const y=Vg(m);if(!y.ok){u(y.error);return}u(void 0),t(y.value)},p=s?s.dimension:0,f=c??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 Wg={type:"vector",Display:Fg,Edit:qg},Ci={string:hg,number:yg,boolean:vg,null:jg,timestamp:Sg,geopoint:Ng,reference:Dg,bytes:Og,map:Mg,array:Bg,vector:Wg};function nl(e){return e?{...Ci,...e}:Ci}function Rn(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 l=new ResizeObserver(c=>{const u=c[0];if(!u)return;const d=u.contentRect.width;d<n?i("narrow"):d<r?i("medium"):i("wide")});return l.observe(a),()=>l.disconnect()},[n,r]),{ref:t,size:s}}const rl=h.createContext(null);function Oe(){const e=h.useContext(rl);if(!e)throw new Error("DocumentEditor.* components must render inside <DocumentEditor.Root>");return e}function zg({initial:e,fieldEditors:t,onChange:n,children:r,className:s}){const i=Qo({initial:e}),a=nl(t),l=h.useRef(n);l.current=n,h.useEffect(()=>{l.current?.(i)},[i]);const{ref:c,size:u}=Rn();return o.jsx(rl.Provider,{value:{editor:i,fieldEditors:a},children:o.jsx("div",{ref:c,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 Kg(){const{editor:e}=Oe(),t=e.tree.childIds[e.tree.rootId]??[];return o.jsxs("div",{"data-pyric-editor-fields":!0,children:[t.map(n=>o.jsx(os,{nodeId:n,path:Hg(e,n)},n)),o.jsx(sl,{parentId:e.tree.rootId})]})}function Hg(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 os({nodeId:e,path:t}){const{editor:n,fieldEditors:r}=Oe(),s=n.tree.nodes[e];if(!s)return null;if(s.type==="map")return o.jsx(Yg,{node:s,path:t});if(s.type==="array")return o.jsx(Xg,{node:s,path:t});const a=r[s.type]?.Edit;if(!a)return null;const l=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":l?"":void 0,onBlur:()=>n.touch(s.id),children:[o.jsx(ls,{node:s,path:t}),o.jsx(a,{value:s.value,path:t,error:l,onChange:c=>n.setValue(s.id,c)})]})}function ls({node:e,path:t}){const{editor:n}=Oe(),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(Jg,{node:e}),o.jsx("button",{type:"button",onClick:()=>n.remove(e.id),"data-pyric-remove":!0,"aria-label":"Remove field",children:"×"})]})}const Gg=["string","number","boolean","null","timestamp","geopoint","reference","bytes","vector","map","array"];function Jg({node:e}){const{editor:t}=Oe(),n=e.parentId!=null?t.tree.nodes[e.parentId]:null,r=Gg.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 Yg({node:e,path:t}){const{editor:n}=Oe(),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(ls,{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(os,{nodeId:s,path:a},s)})}),o.jsx(sl,{parentId:e.id})]})}function Xg({node:e,path:t}){const{editor:n}=Oe(),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(ls,{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(os,{nodeId:s,path:a})},s)})}),o.jsx(Qg,{parentId:e.id})]})}function sl({parentId:e}){const{editor:t}=Oe();return o.jsx("button",{type:"button","data-pyric-add-map-entry":!0,onClick:()=>t.addMapEntry(e,"","string"),children:"+ Add field"})}function Qg({parentId:e}){const{editor:t}=Oe();return o.jsx("button",{type:"button","data-pyric-add-array-entry":!0,onClick:()=>t.addArrayEntry(e,"string"),children:"+ Add item"})}const Ni={Root:zg,Fields:Kg};function Zg({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 wt=new Map;function cs({scope:e,entries:t,equals:n=Object.is,durationMs:r=1200,ready:s=!0}){const i=h.useRef(null),a=h.useRef(new Map),l=h.useRef(new Map),[c,u]=h.useState(wt);return h.useEffect(()=>{const d=i.current;if(!s){if(d&&d.scope!==e){i.current=null;for(const f of l.current.values())clearTimeout(f);l.current.clear(),a.current.clear(),u(wt)}return}if(!d||d.scope!==e){i.current={scope:e,entries:t};for(const f of l.current.values())clearTimeout(f);l.current.clear(),a.current.clear(),u(wt);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?wt:m:f});for(const[f,m]of p){const y=l.current.get(f);y&&clearTimeout(y);const g=setTimeout(()=>{l.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?wt:b})},r);l.current.set(f,g)}},[r,t,n,s,e]),h.useEffect(()=>()=>{for(const d of l.current.values())clearTimeout(d);l.current.clear()},[]),c}function xt(e){return e.ref}function ev({documents:e,isLoading:t,error:n,hasMore:r,onSelect:s,onLoadMore:i,renderLabel:a,renderRowAction:l,emptyState:c,className:u,updateScope:d="document-list",virtualizeThreshold:p=100,rowHeight:f=36,virtualizedHeight:m="60vh"}){const y=h.useMemo(()=>new Map(e.map(b=>[xt(b).path,b.data()])),[e]),g=cs({scope:d,entries:y,equals:pn,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:c});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(ns,{items:e,estimateSize:f,height:m,getItemKey:b=>xt(b).path,renderItem:b=>{const w=g.get(xt(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?.(xt(b)),"data-pyric-document-select":!0,"data-pyric-update":w?.kind,"data-pyric-update-cycle":w?.cycle,children:a?a(b):b.id}),l?o.jsx("span",{"data-pyric-document-action":!0,children:l(b)}):null]})}}):o.jsx("ul",{"data-pyric-document-list-items":!0,children:e.map(b=>{const w=xt(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}),l?o.jsx("span",{"data-pyric-document-action":!0,children:l(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 tv=/^__.*__$/;function il(e){if(e.length===0)return"Cannot be empty";if(e.includes("/"))return'Cannot contain "/"';if(e==="."||e==="..")return'Cannot be "." or ".."';if(tv.test(e))return"Cannot match __.*__ (reserved)";if(rv(e)>1500)return"Cannot exceed 1500 bytes"}function nv(e){return il(e)}function rv(e){return new TextEncoder().encode(e).length}function sv(e){return il(e)}const Ri="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function iv(){let e="";for(let t=0;t<20;t++)e+=Ri.charAt(Math.floor(Math.random()*Ri.length));return e}const av={ref:Nt,listAll:Zr,getMetadata:gh,getBlob:Im,uploadBytes:eo,uploadBytesResumable:Om,deleteObject:Qr},al=h.createContext(av);function An(){return h.useContext(al)}function ov({value:e,children:t}){return h.createElement(al.Provider,{value:e},t)}function Hn(e){return e.replace(/^\/+|\/+$/g,"")}function Nr(e,t){return e.fullPath<t.fullPath?-1:e.fullPath>t.fullPath?1:0}function Gn(e,t){return e.some(n=>n.fullPath===t.fullPath)?e:[...e,t].sort(Nr)}function lv(e,t){const{listAll:n,ref:r}=An(),s=Hn(t),[i,a]=h.useState(()=>({status:e==null?"idle":"loading",items:[],prefixes:[],error:void 0})),[l,c]=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(Nr),prefixes:[...g.prefixes].sort(Nr),error:void 0})}).catch(g=>{y||a({status:"error",items:[],prefixes:[],error:g instanceof Error?g:new Error(String(g))})}),()=>{y=!0}},[e,s,l]);const d=h.useCallback(()=>c(y=>y+1),[]),p=h.useCallback(y=>{if(e==null)return;const g=y.endsWith("/"),v=Hn(y),b=s===""?"":`${s}/`;if(!v.startsWith(b)||v===s)return;const w=v.slice(b.length),x=w.indexOf("/");a(k=>{if(k.status==="idle")return k;if(x===-1)return g?(u.current.set(v,k.prefixes.some(_=>_.fullPath===v)?null:v),{...k,prefixes:Gn(k.prefixes,r(e,v))}):(u.current.set(v,k.items.some(_=>_.fullPath===v)?null:v),{...k,items:Gn(k.items,r(e,v))});const j=`${b}${w.slice(0,x)}`;return u.current.set(v,k.prefixes.some(_=>_.fullPath===j)?null:j),{...k,prefixes:Gn(k.prefixes,r(e,j))}})},[e,s]),f=h.useCallback(y=>{const g=Hn(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 X(e){return e.split("/").filter(Boolean).join("/")}function cv(e={}){const{path:t,onPathChange:n,defaultPath:r=""}=e,s=t!==void 0,[i,a]=h.useState(()=>X(r)),l=s?X(t):i,c=h.useCallback(m=>{const y=X(m);s||a(y),n?.(y)},[s,n]),u=h.useMemo(()=>l===""?[]:l.split("/"),[l]),d=h.useCallback(m=>{const y=X(m);c(y.includes("/")||l===""?y:`${l}/${y}`)},[l,c]),p=h.useCallback(()=>{u.length!==0&&c(u.slice(0,-1).join("/"))},[u,c]),f=h.useCallback(m=>{c(m<0?"":u.slice(0,m+1).join("/"))},[u,c]);return{path:l,segments:u,setPath:c,enter:d,up:p,navigateToIndex:f}}const Ai={status:"idle",blob:void 0,url:void 0,error:void 0};function uv(e,t){const{getBlob:n,getMetadata:r,ref:s}=An(),i=t==null?null:X(t),a=e!=null&&i!=null&&i!=="",[l,c]=h.useState(()=>({status:a?"loading":"idle",metadata:void 0,error:void 0})),[u,d]=h.useState(Ai),[p,f]=h.useState(0),m=h.useRef(0);h.useEffect(()=>{if(m.current++,d(Ai),!a){c({status:"idle",metadata:void 0,error:void 0});return}let b=!1;return c({status:"loading",metadata:void 0,error:void 0}),r(s(e,i)).then(w=>{b||c({status:"success",metadata:w,error:void 0})}).catch(w=>{b||c({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:l.status,metadata:l.metadata,error:l.error,refresh:g,blobStatus:u.status,blob:u.blob,blobUrl:u.url,blobError:u.error,loadBlob:v}}function dv(){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])))},[]),l=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:l}}function fv(e,t){const n=Nt(e,t);return{storage:e,bucket:n.bucket,fullPath:`${n.fullPath}/`,name:"",parent:n,root:n.root,toString:()=>`${n.toString()}/`}}function hv(e){return{...e,fullPath:`${e.fullPath}/`,name:""}}function pv(e){return{async*start(t){const n=e??{listAll:Zr,deleteObject:Qr};let r=0;const s=[t],i=[];for(;s.length>0;){const a=s.pop();i.push(a);const l=await n.listAll(a);s.push(...l.prefixes);for(const c of l.items)await n.deleteObject(c),r++,yield{deletedCount:r,done:!1}}for(const a of i)try{await n.deleteObject(hv(a))}catch{}yield{deletedCount:r,done:!0}}}}function mv(e,t={}){const n=An(),[r,s]=h.useState(0),[i,a]=h.useState(!1),[l,c]=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),c(void 0);const y={deleted:[],failed:[]};if(e==null||f.length===0)return y;a(!0);const g=d.current.impl??pv(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&&c(x)}}return y}finally{m===u.current&&a(!1)}},[n,e]),progress:r,isRunning:i,error:l}}const yv=Object.freeze({read:!0,write:!0,delete:!0,upload:!0,reasons:Object.freeze({read:[],write:[]})});function bv(e,t={}){const{paths:n,rules:r,identity:s,writeResource:i}=t,a=e==null?null:e[wn],[l,c]=h.useState(()=>({status:e==null?"idle":"loading",rules:null,source:"none",error:void 0}));h.useEffect(()=>{if(a==null){c({status:"idle",rules:null,source:"none",error:void 0});return}if(r!=null){try{const w=typeof r=="string"?pr(r):r;c({status:"ready",rules:w,source:"option",error:void 0})}catch(w){c({status:"error",rules:null,source:"none",error:w instanceof Error?w:new Error(String(w))})}return}let b=!1;return c({status:"loading",rules:null,source:"none",error:void 0}),a.servicePromise.then(w=>{b||c({status:"ready",rules:w.rules,source:w.rules?"sandbox":"none",error:void 0})}).catch(w=>{b||c({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}=l,f=i?.size,m=i?.contentType,y=h.useCallback(b=>{if(d==null)return yv;const w=X(b),x=a?.bucket??"pyric-default",k=w===""?`b/${x}/o`:`b/${x}/o/${w}`,j=D=>Qa(d,{request:{auth:u,method:D,path:k,...D==="create"&&f!==void 0?{resource:{size:f,contentType:m}}:{}},resource:null}),_=j("read"),N=j("create"),P=j("delete"),I=N;return{read:_.allowed,write:I.allowed,delete:P.allowed,upload:N.allowed,reasons:{read:_.allowed?[]:_.reasons,write:I.allowed?[]:I.reasons}}},[d,a?.bucket,u,f,m]),g=typeof n=="string"?n:(n??[]).join(`
|
|
9
|
+
`),v=h.useMemo(()=>{const b=typeof n=="string"?[n]:n??[],w={};for(const x of b)w[X(x)]=y(x);return w},[g,y]);return{status:p,source:l.source,advisory:!1,identity:u,verdicts:v,verdictFor:y,error:l.error}}function Ii(e,t){return e===""?t:t===""?e:`${e}/${t}`}function gv(e){return e instanceof Blob?e.size:e.byteLength}function vv(e){if(e instanceof Blob){const t=e;return{path:t.webkitRelativePath||t.name,data:t}}return e}function wv(e,t={}){const{ref:n,uploadBytes:r}=An(),s=X(t.path??""),[i,a]=h.useState([]),l=h.useRef(t);l.current=t;const c=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=vv(g);return{task:{id:crypto.randomUUID(),fullPath:Ii(s,X(v.path)),status:"running",bytesTransferred:0,totalBytes:gv(v.data)},entry:v}});a(g=>[...g,...y.map(v=>v.task)]);for(const{task:g}of y)l.current.list?.insertItem(g.fullPath),l.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 c(w),l.current.onProgress?.(w),l.current.onComplete?.(w),w}catch(b){const w={...g,status:"error",error:b instanceof Error?b:new Error(String(b))};return l.current.list?.removeItem(g.fullPath),c(w),l.current.onError?.(w),w}}))},[e,s,c,n,r]),d=h.useCallback(async f=>{if(e==null)throw new Error("useObjectUpload: storage handle is null");const m=Ii(s,X(f));if(m==="")throw new Error("createFolder: folder name is empty");l.current.list?.insertItem(`${m}/`);try{await r(fv(e,m),new Blob([]),{contentType:"text/plain"})}catch(y){throw l.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 xv({path:e,onNavigate:t,rootLabel:n="/",separator:r="/",className:s}){const i=X(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((l,c)=>{const u=c===a.length-1,d=a.slice(0,c+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:l})]},d)})]})})}function jv({entries:e,status:t="success",error:n,onNavigate:r,onSelect:s,selectedPath:i,gate:a,renderEntry:l,renderRowAction:c,emptyState:u,className:d,virtualizeThreshold:p=100,rowHeight:f=36,virtualizedHeight:m="60vh"}){const{ref:y,size:g}=Rn();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:l?l(x):x.name}),c?o.jsx("span",{"data-pyric-storage-action":!0,children:c(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(ns,{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 ol(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,l)=>s.readEntries(a,l));if(i.length===0)break;for(const a of i)await ol(a,r,n)}}}async function kv(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 ol(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 _v({onFiles:e,children:t,disabled:n,disabledReason:r,className:s}){const[i,a]=h.useState(!1),l=h.useRef(0),c=h.useCallback(f=>{f.preventDefault(),!n&&(l.current+=1,a(!0))},[n]),u=h.useCallback(f=>{f.preventDefault()},[]),d=h.useCallback(f=>{f.preventDefault(),!n&&(l.current=Math.max(0,l.current-1),l.current===0&&a(!1))},[n]),p=h.useCallback(f=>{if(f.preventDefault(),l.current=0,a(!1),n)return;const m=f.dataTransfer;m&&kv(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:c,onDragOver:u,onDragLeave:d,onDrop:p,children:t})}function Sv(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 Ev(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 Di(e,t){if(!t.has(e))return e;const{stem:n,ext:r}=Sv(e),{base:s,counter:i}=Ev(n);let a=i===null?1:i+1;for(;;){const l=`${s} (${a})${r}`;if(!t.has(l))return l;a+=1}}function Cv(e,t){const n=new Set(t),r=new Map;return e.map(s=>{const i=s.indexOf("/");if(i===-1){const c=Di(s,n);return n.add(c),c}const a=s.slice(0,i);let l=r.get(a);return l===void 0&&(l=Di(a,n),n.add(l),r.set(a,l)),`${l}${s.slice(i)}`})}function Pi(e){const t=X(e);if(t==="")return[];const n=t.split("/");return n.map((r,s)=>n.slice(0,s+1).join("/"))}const ll=[];function Nv(e,t){switch(t.type){case"create":{const n=Pi(t.path).filter(r=>!e.includes(r));return n.length===0?e:[...e,...n].sort()}case"materialize":{const n=new Set(Pi(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=X(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:ll}}function Rv(e,t){const n=X(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 $i(e,t){return e.includes(X(t))}function Av(e){const t=X(e);return t===""?"Enter a folder name.":t.split("/").some(r=>r==="."||r==="..")?'Folder names may not be "." or "..".':null}const Iv=256*1024;function Rr(e){return(e.contentType??"").split(";")[0].trim().toLowerCase()}const Dv={id:"image",match:e=>Rr(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 Pv({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 $v={id:"text",match:e=>{const t=Rr(e);return t.startsWith("text/")||t==="application/json"},needsBlob:!0,maxBytes:Iv,render:({metadata:e,blob:t})=>t?o.jsx(Pv,{blob:t,isJson:Rr(e)==="application/json"}):null},Ov=[Dv,$v];function Uv(e,t){for(const n of[...t??[],...Ov])if(n.match(e))return n}const Mv=[{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 Tv({metadata:e}){return o.jsxs("dl",{"data-pyric-object-metadata":!0,children:[Mv.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 Bv({storage:e,path:t,previews:n,renderMetadata:r,children:s,className:i}){const{ref:a,size:l}=Rn(),c=uv(e,t),{metadata:u,blobStatus:d,loadBlob:p}=c,f=u?Uv(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]),c.status==="idle")return o.jsx("div",{className:i,"data-pyric-ui":"object-inspector","data-pyric-idle":""});if(c.status==="loading")return o.jsx("div",{className:i,"data-pyric-ui":"object-inspector","data-pyric-loading":""});if(c.status==="error"||u===void 0)return o.jsx("div",{className:i,"data-pyric-ui":"object-inspector","data-pyric-error":"",role:"alert",children:c.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=c.blobError?.message):(!y||d==="success")&&(g=f.render({metadata:u,blob:c.blob,blobUrl:c.blobUrl})),o.jsxs("div",{ref:a,className:i,"data-pyric-ui":"object-inspector","data-size":l,children:[o.jsx("div",{"data-pyric-object-name":!0,children:u.name}),r?r(u):o.jsx(Tv,{metadata:u}),o.jsx("div",{"data-pyric-object-preview":!0,"data-pyric-preview":f?.id,...v,children:g}),s]})}const cl=h.createContext(null);function Lv(){const e=h.useContext(cl);if(!e)throw new Error("useToast: missing <ToastProvider> ancestor");return e}function Fv({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))},[]),l=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]),c=h.useMemo(()=>({toast:l,dismiss:a,toasts:s}),[l,a,s]);return o.jsxs(cl.Provider,{value:c,children:[e,o.jsx(Vv,{toasts:s,dismiss:a,className:n,regionLabel:r})]})}function Vv({toasts:e,dismiss:t,className:n,regionLabel:r}){const[s,i]=h.useState(!1);return h.useEffect(()=>i(!0),[]),!s||typeof document>"u"?null:ts.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 qv({storage:e,entries:t,impl:n,list:r,gate:s,title:i,body:a,confirmLabel:l="Delete",onDeleted:c,onFailed:u,renderTrigger:d,className:p}){const f=pt(),{toast:m}=Lv(),{deleteEntries:y,isRunning:g,progress:v}=mv(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:l}))return;const _=await y(t);_.failed.length===0?(m({title:`Deleted ${_.deleted.length} ${_.deleted.length===1?"item":"items"}`,kind:"success"}),c?.(_)):(m({title:`Delete failed for ${_.failed.length} of ${t.length}`,kind:"error",body:o.jsx("ul",{"data-pyric-delete-selection-failures":!0,children:_.failed.map(N=>o.jsxs("li",{children:[N.fullPath,":"," ",N.error.code??N.error.message]},N.fullPath))})}),u?.(_))};return d?o.jsx(o.Fragment,{children:d({onClick:k,isRunning:g,progress:v,disabled:x,deniedReason:w})}):o.jsx("button",{type:"button",onClick:k,className:p,disabled:x,title:w,"data-pyric-ui":"delete-selection","data-pyric-destructive":"","data-pyric-running":g?"":void 0,"data-pyric-denied":w?"":void 0,"data-pyric-denied-reason":w,children:g?`Deleting… (${v})`:l})}function mn(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 ul(e){const t=e.indexOf("?");return Jr(t===-1?e:e.slice(0,t),t===-1?"":e.slice(t))}function Wv(e){const{tab:t,rest:n,query:r}=ul(e),s=n.join("/");return t==="firestore"?{view:"firestore",path:mn(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 zv(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 dl(e){const{tab:t,query:n}=ul(e),r=Wv(e),s=t==="traffic"?n.inspect??null:null;return{target:r,selectedInspectId:s}}let Oi=null,Ar=dl("");function Kv(){const e=po();return e!==Oi&&(Oi=e,Ar=dl(e)),Ar}function Hv(){return Ar}function Kt(e){ce(zv(e))}function Gv(e){ce({tab:"traffic",query:{inspect:e}})}function In(){const e=h.useSyncExternalStore(Ut,Kv,Hv),t=h.useCallback(s=>Kt(s),[]),n=h.useCallback(s=>{switch(s.kind){case"user":Kt({view:"auth",uid:s.uid});break;case"storage":Kt({view:"storage",kind:"object",path:s.objectPath});break;case"document":Kt({view:"firestore",path:mn(s.path)});break}},[]),r=h.useCallback(s=>Gv(s),[]);return h.useMemo(()=>({target:e.target,navigate:t,navigateRef:n,selectedInspectId:e.selectedInspectId,navigateInspect:r}),[e,t,n,r])}const Jv={narrowBreakpoint:640,mediumBreakpoint:920};function Yv(e){switch(e){case"narrow":return 1;case"medium":return 2;case"wide":return 3}}function Xv(e,t){const n=Yv(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 Jn({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 fl({mode:e,parentPath:t,onCreate:n,onClose:r}){const[s,i]=h.useState(""),[a,l]=h.useState(()=>iv()),[c,u]=h.useState(null),[d,p]=h.useState(null),[f,m]=h.useState(!1),y=h.useRef(null),g=e==="collection"&&s?nv(s):void 0,v=a?sv(a):void 0,w=!(e==="collection"&&(!s||g))&&!!a&&!v&&!f;h.useEffect(()=>{const j=_=>{_.key==="Escape"&&!f&&r()};return document.addEventListener("keydown",j),()=>document.removeEventListener("keydown",j)},[f,r]);const x=async()=>{if(!(!w||!c)){if(!c.isValid){c.touchAll();return}m(!0),p(null);try{await n({collectionId:e==="collection"?s:null,docId:a,data:Ho(c.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(Jn,{label:"Parent path",children:o.jsx("span",{className:"fs-modal__path",children:t})}),e==="collection"?o.jsx(Jn,{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(Jn,{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=>l(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(Ni.Root,{initial:{},onChange:u,children:o.jsx(Ni.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 hl({items:e,label:t="More actions"}){const[n,r]=h.useState(!1),[s,i]=h.useState(null),a=h.useRef(null),l=()=>{if(!n){const c=a.current?.getBoundingClientRect();c&&i({top:c.bottom+4,right:window.innerWidth-c.right})}r(c=>!c)};return h.useEffect(()=>{if(!n)return;const c=u=>{u.key==="Escape"&&(r(!1),a.current?.focus())};return document.addEventListener("keydown",c),()=>document.removeEventListener("keydown",c)},[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:l,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(c=>o.jsx("button",{type:"button",role:"menuitem",className:"fs-overflow__item","data-destructive":c.destructive?"":void 0,disabled:c.disabled,onClick:()=>{r(!1),c.onSelect()},children:c.label},c.label))})]}):null]})}function pl(e){return JSON.stringify(e)}function Qv(e,t){const n=new Map,r=(s,i)=>{const a=t(s),l=pl(i);if(a==="map"){const c=s,u=Object.keys(c).sort();n.set(l,[a,u]);for(const d of u)r(c[d],[...i,["field",d]]);return}if(a==="array"){const c=s;n.set(l,[a,c.map((u,d)=>String(d))]),c.forEach((u,d)=>r(u,[...i,["index",d]]));return}n.set(l,[a,s])};for(const[s,i]of Object.entries(e))r(i,[["field",s]]);return n}function ml(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 pl(n)}function Zv(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 ew(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 Ui(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 tw=42;function nw(e,t,n,r=tw){const s=e.nodes[t],i=e.childIds[t]??[];let a;return s.type==="array"?a=`[${i.slice(0,3).map(c=>Ui(e.nodes[c],n.asVectorView,n.vectorPreview)).join(", ")}${i.length>3?", …":""}]`:a=`{${i.slice(0,2).map(c=>`"${e.nodes[c].key}": ${Ui(e.nodes[c],n.asVectorView,n.vectorPreview)}`).join(", ")}${i.length>2?", …":""}}`,a.length>r?`${a.slice(0,r-1)}…`:a}function rw(e,t,n){return t.parentId==null?!1:(e.childIds[t.parentId]??[]).some(s=>s!==t.id&&e.nodes[s]?.key===n)}function sw(e){return e.shiftKey===!0}const yl=["string","number","boolean","null","timestamp","geopoint","reference","bytes","vector"],iw=[...yl,"map","array"];function aw({snapshot:e,documentRef:t,onCommit:n,onDeleteDocument:r,onDeleteDocumentFields:s,fieldEditors:i,onReferenceClick:a,onStartCollection:l,firestore:c,listSubcollections:u,onSubcollectionClick:d}){const p=h.useMemo(()=>e?.data()??{},[e]),f=h.useMemo(()=>p,[]),m=Qo({initial:f}),y=m.replaceData,g=h.useMemo(()=>nl(i),[i]),v=pt(),[b,w]=h.useState(()=>new Set),[x,k]=h.useState(null),j=h.useRef(e),_=h.useRef(new Set),N=h.useRef(!1),[P,I]=h.useState(null),D=h.useMemo(()=>Qv(p,Nn),[p]),C=cs({scope:t.path,entries:D,equals:pn,ready:x===null});h.useEffect(()=>{N.current&&(N.current=!1,I(null),n(m.toData()).catch($=>{I($ instanceof Error?$:new Error(String($)))}))},[m.tree]),h.useEffect(()=>{!e||e===j.current||x!==null||(j.current=e,_.current.clear(),y(e.data()??{}))},[x,y,e]);const S=h.useCallback($=>{w(Y=>{const se=new Set(Y);return se.has($)?se.delete($):se.add($),se})},[]),[E,R]=h.useState(null),V=h.useCallback(($,Y)=>{if(Y==="map"?m.addMapEntry($,"","string"):m.addArrayEntry($,"string"),$!==m.tree.rootId){const se=ml(m.tree,$);w(ne=>new Set(ne).add(se))}R($)},[m]);h.useEffect(()=>{if(!E)return;const $=m.tree.childIds[E]??[],Y=$[$.length-1];Y&&!x&&(_.current.add(Y),k(Y),R(null))},[m.tree,E]);const G=h.useCallback($=>{m.remove($),_.current.delete($),N.current=!0,x===$&&k(null)},[m,x]),A=h.useCallback(async($,Y,se)=>{if(sw(se)){G($.id);return}await v({title:`Delete field "${Y}"?`,destructive:!0,confirmLabel:"Delete"})&&G($.id)},[v,G]),O=t.id,U=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(hl,{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:[l?o.jsx("li",{className:"fs-doctree__action-row",children:o.jsxs("button",{type:"button",className:"fs-doctree__action",onClick:l,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"]})}),U.map($=>o.jsx(bl,{nodeId:$,depth:0,editor:m,registry:g,expanded:b,onToggle:S,editingId:x,setEditingId:k,newIdsRef:_,onAdd:V,onDelete:A,onCommitNeeded:()=>{N.current=!0},onReferenceClick:a,updates:C},$))]}),c&&u?o.jsx(gl,{firestore:c,documentRef:t,listSubcollections:u,onSubcollectionClick:d}):null]})}function bl({nodeId:e,depth:t,editor:n,registry:r,expanded:s,onToggle:i,editingId:a,setEditingId:l,newIdsRef:c,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}=ew(y,e),w=g.type==="map"||g.type==="array",x=Zv(y,e),k=ml(y,e),j=m.get(k),_=s.has(k),N=a===e,P=c.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(ow,{node:g,isNew:P,isArrayChild:b,tree:y,editor:n,registry:r,path:x,onCommitNeeded:p,onDone:()=>{c.current.delete(e),l(null)},onCancelNew:()=>{n.remove(e),c.current.delete(e),l(null)}})}):o.jsxs("li",{className:"fs-doctree__row","data-pyric-doctree-depth":t,"data-pyric-doctree-nested":w?"":void 0,style:{"--fs-depth":t},children:[o.jsxs("div",{className:"fs-doctree__line","data-pyric-update":j?.kind,"data-pyric-update-cycle":j?.cycle,children:[w?o.jsx("button",{type:"button",className:"fs-doctree__caret","aria-expanded":_,onClick:()=>i(k),children:o.jsx("span",{"aria-hidden":"true",children:_?"▼":"▶"})}):o.jsx("span",{className:"fs-doctree__caret fs-doctree__caret--empty","aria-hidden":"true"}),b?o.jsx("span",{className:"fs-doctree__chip",children:v}):o.jsx("span",{className:"fs-doctree__key",children:v}),w?_?null:o.jsx("span",{className:"fs-doctree__preview",children:nw(y,e,{asVectorView:Ke,vectorPreview:zo})}):o.jsx("span",{className:"fs-doctree__value",children:o.jsx(Cr,{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:()=>l(e),children:"✎"}),o.jsx("button",{type:"button",className:"fs-doctree__icon fs-doctree__icon--danger",title:"Delete (shift-click to skip confirmation)","aria-label":`Delete ${v||"field"} (shift-click to skip confirmation)`,onClick:I=>void d(g,v,{shiftKey:I.shiftKey}),children:"🗑"})]})]}),w&&_?o.jsxs("ul",{className:"fs-doctree__children",children:[(y.childIds[e]??[]).map(I=>o.jsx(bl,{nodeId:I,depth:t+1,editor:n,registry:r,expanded:s,onToggle:i,editingId:a,setEditingId:l,newIdsRef:c,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 ow({node:e,isNew:t,isArrayChild:n,tree:r,editor:s,registry:i,path:a,onCommitNeeded:l,onDone:c,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":rw(r,e,d)?"Field name must be unique":void 0,x=f==="map"||f==="array"?void 0:Jo(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),l(),c()},_=()=>{t?u():c()},P=i[f]?.Edit,I=f!=="map"&&f!=="array"&&P?o.jsx(P,{value:y,path:a,error:v?x:void 0,onChange:S=>g(S)}):f==="map"||f==="array"?o.jsxs("span",{className:"fs-doctree__editnote",children:["Saves as an empty ",f," — add its children afterward."]}):null,D=o.jsxs("span",{className:"fs-doctree__editactions",children:[o.jsx("button",{type:"button",className:"fs-doctree__editsave",onClick:j,"aria-label":"Save field",children:"✓"}),o.jsx("button",{type:"button",className:"fs-doctree__editcancel",onClick:_,"aria-label":"Cancel edit",children:"✕"})]}),C=o.jsx("select",{className:"fs-doctree__edittype",value:f,onChange:S=>{const E=S.target.value;m(E),E!=="map"&&E!=="array"&&E!==f&&g(lw(E))},"aria-label":"Field type",children:(t?iw:yl).map(S=>o.jsx("option",{value:S,children:S},S))});return o.jsxs("div",{className:"fs-doctree__editrow",onKeyDown:S=>{S.key==="Enter"&&!S.target.matches("textarea")?(S.preventDefault(),j()):S.key==="Escape"&&(S.preventDefault(),_())},children:[n?null:o.jsxs("div",{className:"fs-doctree__editline",children:[o.jsx("input",{type:"text",className:"fs-doctree__editkey",value:d,placeholder:"Field name",autoFocus:t,onChange:S=>p(S.target.value),onBlur:()=>b(!0),"aria-label":"Field name","aria-invalid":v&&w?"true":void 0}),C]}),o.jsxs("div",{className:"fs-doctree__editline",children:[n?C:null,I,D]}),v&&w?o.jsx("span",{className:"fs-doctree__editerr",children:w}):null]})}function lw(e){switch(e){case"string":return"";case"number":return 0;case"boolean":return!1;default:return null}}function gl({firestore:e,documentRef:t,listSubcollections:n,onSubcollectionClick:r}){const{subcollections:s,isLoading:i}=ug({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 cw(e){return e.split("/").filter(Boolean).length%2===0}function vl(e,t){async function*n(s,i,a=!1){const l=await t.listSubcollections(s.path);for(const c of l)yield*r(e.collection(s,c),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 l of a){const c=l.path.split("/").pop();c&&(yield*n(e.doc(s,c),i,l.phantom===!0))}}return{async*start(s){const i={n:0};cw(s.path)?yield*n(s,i):yield*r(s,i),yield{deletedCount:i.n,done:!0}}}}async function wl(e,t){for await(const n of e.start(t))if(n.done)return}async function xl({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 wl(r,t):await n.deleteDoc(t),!0):!1}function uw(e){const t=e.exists;return typeof t=="function"?t.call(e):t}async function dw(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 fw(e){return{id:e.id,ref:e,data:()=>{},__pyricPhantom:!0}}function Mi(e){return e.__pyricPhantom===!0}function hw(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 pw({handles:e}){const{target:t,navigate:n}=In(),r=e.adminFirestore,s=is(),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]),l=(k,j)=>a(_=>[..._.slice(0,k+1),j]),[c,u]=h.useState(null),d=h.useCallback(async({collectionId:k,docId:j,data:_})=>{if(!c||!k)return;const N=c.parentDocPath,P=N?s.collection(s.doc(r,N),k):s.collection(r,k);await dw(s,P,j,_);const I=N?`${N}/${k}`:k;n({view:"firestore",path:mn(`${I}/${j}`)})},[s,r,c,n]),p=[o.jsx(bw,{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(gw,{api:s,firestore:r,handles:e,collectionPath:k.path,selectedId:i[j+1]?.id??null,onSelect:_=>l(j,{kind:"document",id:_.id,path:_.path}),onCollectionDeleted:()=>a(_=>_.slice(0,j))},k.path):o.jsx(vw,{api:s,firestore:r,handles:e,docPath:k.path,onOpenSubcollection:_=>l(j,{kind:"collection",id:_.id,path:_.path}),onReferenceClick:_=>n({view:"firestore",path:mn(_.path)}),onStartCollection:()=>u({parentDocPath:k.path}),onDeleted:()=>a(_=>_.slice(0,j))},k.path))],{ref:f,size:m}=Rn(Jv),{startIndex:y,visibleCount:g,emptySlots:v}=Xv(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(yw,{hint:j===0?w:null},`__empty_${j}__`))];return h.useEffect(()=>{if(m==="wide")return;const k=f.current;if(!k)return;const j=document.activeElement;if(j&&j!==document.body&&k.contains(j))return;const _=k.querySelector(".fs-columns > .fs-col:last-child");_&&(_.tabIndex=-1,_.focus({preventScroll:!0}))},[i.length,m]),o.jsx(ss,{children:o.jsxs("div",{ref:f,"data-pyric-ui":"fs-browser","data-fs-depth":i.length,"data-size":m,children:[o.jsx(mw,{path:i,onHome:()=>a([]),onJump:k=>a(j=>j.slice(0,k+1))}),o.jsx("div",{className:"fs-columns",children:x}),c?o.jsx(fl,{mode:"collection",parentPath:c.parentDocPath?`/${c.parentDocPath}`:"/",onCreate:d,onClose:()=>u(null)}):null]})})}function mw({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 yw({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 bw({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(Zg,{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 gw({api:e,firestore:t,handles:n,collectionPath:r,selectedId:s,onSelect:i,onCollectionDeleted:a}){const l=h.useMemo(()=>hw(e,t,r),[e,t,r]),{documents:c,isLoading:u,error:d,subscriptionGeneration:p,hasMore:f,loadMore:m,createDocument:y}=cg({collection:l,mode:"live"}),[g,v]=h.useState([]);h.useEffect(()=>{let C=!1;return Promise.resolve(n.listDocuments(r)).then(S=>{C||v(S.filter(E=>E.phantom).map(E=>E.path.split("/").pop()??""))}).catch(()=>{C||v([])}),()=>{C=!0}},[n,r,c]);const b=h.useMemo(()=>{const C=new Set(c.map(S=>S.id));return[...c,...g.filter(S=>S.length>0&&!C.has(S)).map(S=>fw(e.doc(t,`${r}/${S}`)))]},[c,g,e,t,r]),w=r.split("/").pop()??r,[x,k]=h.useState(null),[j,_]=h.useState(!1),N=pt(),P=h.useMemo(()=>vl(e,n),[e,n]),I=h.useCallback(async C=>{k(null);try{await xl({confirm:N,ref:C,api:e,recursiveImpl:P})}catch(S){k(S instanceof Error?S:new Error(String(S)))}},[e,N,P]),D=h.useCallback(async()=>{if(await N({title:`Delete collection "${w}"?`,body:"This deletes every document in it (and their subcollections).",destructive:!0,confirmLabel:"Delete collection"})){k(null);try{await wl(P,l),a()}catch(S){k(S instanceof Error?S:new Error(String(S)))}}},[N,P,l,w,a]);return o.jsxs("section",{"data-pyric-ui":"fs-documents",className:"fs-pane fs-col",children:[o.jsxs("div",{className:"fs-phead",children:[o.jsx("span",{className:"fs-phead-title",children:w}),o.jsx("span",{className:"fs-phead-actions",children:o.jsx("button",{type:"button",className:"fs-add",onClick:()=>_(!0),children:"+ New"})}),o.jsx(hl,{items:[{label:"Delete collection",onSelect:()=>void D(),destructive:!0}]})]}),j?o.jsx(fl,{mode:"document",parentPath:`/${r}`,onCreate:async({docId:C,data:S})=>{const E=await y(C,S,{onExisting:"fail"});i(E)},onClose:()=>_(!1)}):null,o.jsx(ev,{documents:b,isLoading:u,error:d,updateScope:`${r}:${p}`,hasMore:f,onLoadMore:m,onSelect:i,renderLabel:C=>{const S=C.ref;return o.jsx("span",{"data-pyric-selected":s===S.id?"":void 0,style:{display:"contents"},children:Mi(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(Mi(C))return null;const S=C.ref;return o.jsx("button",{type:"button",className:"fs-doc-del",title:"Delete document","aria-label":`Delete ${S.id}`,onClick:E=>{E.stopPropagation(),I(S)},children:"×"})},emptyState:o.jsx("p",{className:"fs-empty",children:"No documents."})}),x?o.jsx("p",{className:"fs-empty fs-doc-del-err",children:x.message}):null]})}function vw({api:e,firestore:t,handles:n,docPath:r,onOpenSubcollection:s,onReferenceClick:i,onStartCollection:a,onDeleted:l}){const c=h.useMemo(()=>e.doc(t,r),[e,t,r]),{data:u,error:d,isLoading:p}=Xb(c),f=h.useCallback(async(k,j)=>(await n.listSubcollections(j.path)).map(N=>e.collection(j,N)),[n,e]),m=pt(),y=h.useMemo(()=>vl(e,n),[e,n]),[g,v]=h.useState(null),b=h.useCallback(async()=>{v(null);try{await xl({confirm:m,ref:c,api:e,recursiveImpl:y})&&l()}catch(k){v(k instanceof Error?k:new Error(String(k)))}},[e,m,y,c,l]),w=h.useCallback(async()=>{await e.setDoc(c,{})},[e,c]),x=u!=null&&uw(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:c.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(aw,{snapshot:u,documentRef:c,firestore:t,listSubcollections:f,onReferenceClick:i,onSubcollectionClick:s,onStartCollection:a,onDeleteDocument:()=>void b(),onDeleteDocumentFields:w,onCommit:async k=>{await e.setDoc(c,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(gl,{firestore:t,documentRef:c,listSubcollections:f,onSubcollectionClick:s})]}),g?o.jsx("p",{className:"fs-empty fs-doc-del-err",children:g.message}):null]})}const ww="block w-full text-sm text-soft-white";function xw({auth:e,focusUid:t}){const{users:n,totalCount:r,isLoading:s,error:i,filter:a,setFilter:l,updateUser:c}=rs(e),[u,d]=h.useState(null);h.useEffect(()=>{t&&(d(t),l(t))},[t,l]);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=>l(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(Bo,{users:n,isLoading:s,error:i,filter:a,onSelect:f=>d(f.uid),className:ww,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(jw,{user:p,onSave:f=>c(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 jw({user:e,onSave:t}){const n=To({initial:e}),[r,s]=h.useState(null),[i,a]=h.useState(!1),l=()=>{s(null),a(!1);try{t(n.toUpdateRequest()),a(!0)}catch(c){s(c instanceof Error?c:new Error(String(c)))}};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:c=>n.setField("displayName",c.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:c=>n.setField("claimsText",c.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:c=>n.setField("disabled",c.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:l,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 Ti(e){const t=X(e),n=t.lastIndexOf("/");return n===-1?"":t.slice(0,n)}function Bi(e,t){return e===""?t:t===""?e:`${e}/${t}`}function Li(e){const t=e.lastIndexOf("/");return t===-1?e:e.slice(t+1)}const kw=[{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 _w(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"}),kw.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 Sw(){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 Ew(){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 Cw(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(Sw,{}):o.jsx(Ew,{})}),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 Nw({storage:e,focusTarget:t}){const n=In(),r=t.kind==="object"?X(t.path):null,s=t.kind==="prefix"?X(t.path):r?Ti(r):"",i=h.useCallback(C=>{const S=X(C);n.navigate(S?{view:"storage",kind:"prefix",path:S}:{view:"storage",kind:"root"})},[n.navigate]),a=cv({path:s,onPathChange:i}),l=C=>{n.navigate({view:"storage",kind:"object",path:X(C)})},c=lv(e,a.path),u=dv(),d=bv(e),[p,f]=h.useReducer(Nv,ll),m=wv(e,{path:a.path,list:c,onComplete:C=>f({type:"materialize",path:Ti(C.fullPath)})});h.useEffect(()=>{if(c.status==="success")for(const C of c.entries)C.kind==="folder"&&$i(p,C.fullPath)&&f({type:"materialize",path:C.fullPath})},[c.status,c.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=Rv(p,a.path).filter(R=>!c.entries.some(V=>V.kind==="folder"&&V.name===R));if(C.length===0)return c.entries;const S=C.map(R=>{const V=Bi(a.path,R);return{kind:"folder",name:R,fullPath:V,ref:{fullPath:V,name:R}}});return[...[...c.entries.filter(R=>R.kind==="folder"),...S].sort((R,V)=>R.name<V.name?-1:R.name>V.name?1:0),...c.entries.filter(R=>R.kind==="object")]},[c.entries,p,a.path]),_=j.length>0&&j.every(C=>u.isSelected(C.fullPath)),N=C=>{const S=new Set(j.map(R=>R.name)),E=Cv(C.map(R=>R.relativePath),S);m.upload(C.map((R,V)=>({path:E[V],data:R.file})))},P=C=>{C.preventDefault();const S=Av(v);if(S){x(S);return}const E=Bi(a.path,X(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(Fv,{children:o.jsx(ss,{children:o.jsxs("div",{className:"storage",children:[o.jsxs("div",{className:"storage__sub",children:[o.jsx(xv,{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(qv,{storage:e,entries:u.selected,list:c,gate:d,className:"studio-selection-delete",onDeleted:C=>{for(const S of u.selected)S.kind==="folder"&&C.deleted.includes(S.fullPath)&&f({type:"discard",path:S.fullPath});r&&u.selected.some(S=>S.kind==="object"?S.fullPath===r:r.startsWith(`${S.fullPath}/`))&&a.setPath(a.path),u.clear(),c.refresh()},onFailed:C=>{const S=new Set(C.failed.map(E=>E.fullPath));u.selectAll(u.selected.filter(E=>S.has(E.fullPath))),c.refresh()}}),o.jsx("button",{type:"button",className:"storage__action",onClick:u.clear,children:"Clear selection"})]}):o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:"storage__action","aria-expanded":y,onClick:()=>{g(C=>!C),x(null)},children:"New folder"}),o.jsx("button",{type:"button",className:"storage__action storage__action--upload",onClick:()=>k.current?.click(),children:"Upload files"}),o.jsx("input",{ref:k,type:"file",multiple:!0,hidden:!0,onChange:C=>{const S=Array.from(C.currentTarget.files??[]);S.length>0&&N(S.map(E=>({file:E,relativePath:E.name}))),C.currentTarget.value=""}})]})})]}),y?o.jsxs("form",{className:"storage__newfolder",onSubmit:P,children:[o.jsx("input",{autoFocus:!0,className:"storage__newfolder-input",placeholder:"folder or nested/path/of/folders","aria-label":"New folder name",value:v,onChange:C=>{b(C.currentTarget.value),x(null)},onKeyDown:C=>{C.key==="Escape"&&g(!1)}}),o.jsx("button",{type:"submit",className:"storage__newfolder-btn",children:"Create"}),w?o.jsx("span",{className:"storage__newfolder-err",role:"alert",children:w}):o.jsx("span",{className:"storage__newfolder-note",children:"Nested paths create the whole chain. Empty folders last this session only — upload a file to keep one."})]}):null,I.length>0?o.jsxs("p",{className:"storage__upload-err",role:"alert",children:[I.length===1?`Upload failed: ${Li(I[0].fullPath)} — ${I[0].error?.message??"error"}`:`${I.length} uploads failed: ${I.map(C=>Li(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(_v,{className:"storage__browser",onFiles:N,disabled:!D.upload,disabledReason:D.reasons.write.join("; "),children:[o.jsxs("div",{className:"storage__lhead",children:[o.jsx("label",{className:"storage__select-all",title:"Select all in this folder",children:o.jsx("input",{type:"checkbox","aria-label":"Select all in this folder",checked:_,onChange:C=>C.currentTarget.checked?u.selectAll(j):u.clear()})}),o.jsx("span",{children:"name"}),o.jsx("span",{children:"type"}),o.jsx("span",{children:"size"}),o.jsx("span",{children:"updated"})]}),o.jsx(jv,{entries:j,status:c.status,error:c.error,gate:d,selectedPath:r??void 0,renderEntry:Cw,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=>l(C.fullPath),emptyState:o.jsx("p",{className:"storage__empty",children:$i(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(Bv,{storage:e,path:r,renderMetadata:_w})]}):o.jsx("p",{className:"storage__inspector-hint",children:"Select an object to inspect its preview and metadata."})})]})]})})})}function Rw({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 jl({view:e}){const{target:t}=In(),n=$e(),r=n.status==="ready"?n.handles.auth:null;return o.jsx("div",{"data-pyric-ui":"data-feature",children:n.status!=="ready"||!r?o.jsx(Rw,{view:e}):n.authApi?o.jsx($o,{value:n.authApi,children:o.jsx(Fi,{view:e,handles:n.handles,auth:r,target:t,firestoreApi:n.firestoreApi,storageApi:n.storageApi})}):o.jsx(Fi,{view:e,handles:n.handles,auth:r,target:t,firestoreApi:n.firestoreApi,storageApi:n.storageApi})})}function Fi({view:e,handles:t,auth:n,target:r,firestoreApi:s,storageApi:i}){const{users:a}=rs(n),l=h.useMemo(()=>new Set(a.map(c=>c.uid)),[a]);switch(e){case"firestore":{const c=o.jsx(pw,{handles:t,knownUids:l});return s?o.jsx(Yb,{value:s,children:c}):c}case"auth":return o.jsx(xw,{auth:n,focusUid:r?.view==="auth"?r.uid:null});case"storage":{const c=o.jsx(Nw,{storage:t.storage,focusTarget:r?.view==="storage"?r:{kind:"root"}});return i?o.jsx(ov,{value:i,children:c}):c}}}function Aw(){return o.jsx(jl,{view:"firestore"})}function Iw(){return o.jsx(jl,{view:"storage"})}function Dw(e,t){const n=new Set(t.map(r=>r.uid));return new Set([...e].filter(r=>n.has(r)))}async function Pw(e,t){const n=[];for(const r of e)try{await t(r.uid)}catch{n.push(r.uid)}return n}function $w(e){const[t,n]=h.useState(()=>new Set);h.useEffect(()=>{n(s=>{const i=Dw(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 Ow({users:e,filter:t,onDelete:n,onComplete:r}){const s=pt(),[i,a]=h.useState(!1),[l,c]=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),c(null);const f=await Pw(e,n);a(!1),c(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"}),l?o.jsx("span",{className:"auth-sub__error",children:l}):null]})}function kl(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 _l(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 Uw(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 Mw({auth:e}={}){const t=Pe(),n=$e(),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(Vw,{status:t.status})});const i=o.jsx(ss,{children:o.jsx(Tw,{auth:r})});return s?o.jsx($o,{value:s,children:i}):i}function Tw({auth:e}){const{users:t,totalCount:n,isLoading:r,error:s,filter:i,setFilter:a,createUser:l,updateUser:c,deleteUser:u}=rs(e),d=In(),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=$w(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(Ow,{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(Bo,{users:t,isLoading:r,error:s,filter:i,onSelect:b=>{g(!1),f(b.uid)},renderIdentifier:Uw,formatCreatedAt:_l,formatLastLoginAt:kl,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(Bw,{onCancel:()=>g(!1),onCreate:async b=>{const w=await Promise.resolve(l(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(Fw,{user:m,onSave:b=>{b.mode==="edit"&&c(b.uid,b.request)},onProvidersChange:async b=>{await Promise.resolve(c(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 Bw({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(Lo,{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 Vi=[...vo];function Lw({user:e,onChange:t}){const[n,r]=h.useState(null),[s,i]=h.useState(""),a=e.providerUserInfo.map(m=>m.providerId),l=a.includes("password"),c=a.filter(m=>m!=="password"),u=c.filter(m=>!Vi.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?[...c,m]:c.filter(g=>g!==m))},f=()=>{const m=s.trim();m&&(i(""),!c.includes(m)&&d([...c,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:[...Vi,...u].map(m=>o.jsxs("label",{className:"auth-provider-row","data-pyric-provider-id":m,children:[o.jsx("input",{type:"checkbox",checked:c.includes(m),onChange:y=>p(m,y.target.checked)}),o.jsx("span",{className:"auth-provider-row__label",children:fn(m)}),o.jsx("span",{className:"auth-provider-row__id",children:m})]},m))}),l||e.isAnonymous?o.jsx("p",{className:"auth-providers-editor__derived",children:l?"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 Fw({user:e,onSave:t,onProvidersChange:n,onDelete:r}){const[s,i]=h.useState(null),[a,l]=h.useState(!1),c=p=>{i(null),l(!1);try{t(p),l(!0)}catch(f){i(f instanceof Error?f:new Error(String(f)))}},u=_l(e.createdAt),d=kl(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(Lw,{user:e,onChange:n}),o.jsxs(Lo,{initial:e,onSubmit:c,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(Hb,{user:e,onDelete:r,className:"auth-del"})})]})}function Vw({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 qw(e){return e.operationContext.source.kind==="studio"}function Ww(e,t){return t?e.filter(n=>!qw(n)):[...e]}const zw=["all","allow","deny","bypassed"];function Dn(e){return e.rulesDisposition.kind==="bypassed"?"bypassed":e.rulesDisposition.kind==="evaluated"?e.rulesDisposition.verdict:null}function Kw(e,t){return t==="all"?[...e]:e.filter(n=>Dn(n)===t)}function Yn(e){return e.rulesDisposition.kind==="evaluated"}function qi(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 Ir="inspect";function Sl(e){const t=e[Ir];return t||null}function El(e,t){const{[Ir]:n,...r}=e;return t?{...r,[Ir]:t}:r}function Hw(e,t){return El(e,Sl(e)===t?null:t)}const Gw=h.lazy(()=>Ba(()=>import("./RulesCodeEditor.CzwHdCi9.js"),__vite__mapDeps([7,2,3])));function Cl(e){return o.jsx(h.Suspense,{fallback:o.jsx(Jw,{value:e.value,minHeightRem:e.minHeightRem}),children:o.jsx(Gw,{...e})})}function Jw({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 Nl({denial:e,rulesSource:t}){const n=Xm(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(jr,{kind:"allow",className:"rounded bg-primary/15 px-2 py-0.5 text-xs font-semibold uppercase text-primary",children:"allowed"}):o.jsx(jr,{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(Yw,{denial:e,exp:n,rulesSource:t}),o.jsx(tx,{denial:e})]}),o.jsx(rx,{denial:e})]})}function Yw({denial:e,exp:t,rulesSource:n}){const r=t.engine==="rtdb",s=t.engine==="storage";return r?o.jsx(ax,{denial:e,exp:t,rulesSource:n}):s?o.jsx(ox,{exp:t}):o.jsx(ex,{denial:e,exp:t,rulesSource:n})}function Xw(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 Qw(e){const n=e.indexOf("// @pyric-source-map:");return n!==-1?e.slice(0,n).trimEnd():e}function Zw(e,t){if(e===void 0||t===void 0)return t;const s=Xw(e);if(s!==null){const a=s.find(c=>c.authoredLine===t);if(a!==void 0)return a.generatedLine}return t}function ex({denial:e,exp:t,rulesSource:n}){const r=e.evaluatedRule?.line,s=Zw(n,r),i=n!==void 0?Qw(n):void 0,a=e.result==="allow",l=!!(i&&i.trim().length>0);return o.jsx(Ae,{label:t.implicitDeny||!t.ruleNode?"matched rule":`matched rule — ${t.ruleNode}${r?` · line ${r}`:""}`,children:l?o.jsx(Cl,{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 tx({denial:e}){const t=ny(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(Rl,{step:n},r))})})}const nx={true:"✓",false:"✗",skipped:"⊘",error:"!",value:"·"};function Rl({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:`→ ${Al(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:nx[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(Rl,{step:r},s))]})}function Al(e){if(e===void 0)return"undefined";try{return JSON.stringify(hn(e))}catch{return String(e)}}function rx({denial:e}){const t=ry(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(sx,{variable:n},n.name))})})}function sx({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(Il,{value:e.value}):o.jsxs("span",{className:"font-mono text-xs italic text-slate-gray",children:["absent",e.absentNote?` — ${e.absentNote}`:""]})]})}function Il({value:e,depth:t=0}){const[n,r]=h.useState(t<2),s=hn(e);if(s===null||typeof s!="object")return o.jsx("span",{className:"font-mono text-xs text-soft-white",children:Al(s)});const i=Array.isArray(s)?s.map((a,l)=>[String(l),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,l])=>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(Il,{value:l,depth:t+1})]},a))}):null]})}function ix(e,t,n,r){if(!e||!n)return;const i=e.split(/\r?\n/),a=t!==void 0&&t.length>0;let l;a?l=`".${t}"`:l=null;const c=[];for(let m=0;m<i.length;m++){const y=i[m];!y.includes(n)||!(l===null||y.includes(l))||c.push(m+1)}if(c.length===1)return c[0];if(c.length===0)return;const d=(r??"").split("/").filter(Boolean);if(d.length===0)return c[0];let p=c[0],f=-1;for(const m of c){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 ax({denial:e,exp:t,rulesSource:n}){const r=ix(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 l;return s?l="Deployed database.rules.json — the allowing rule is marked":l="Deployed database.rules.json — the denying rule is marked",o.jsxs(o.Fragment,{children:[o.jsx(Ae,{label:a,children:i?o.jsx(Cl,{value:n,readOnly:!0,markLine:r,markKind:s?"allow":"deny",minHeightRem:12,ariaLabel:l}):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(([c,u])=>`${c.startsWith("$")?c:`$${c}`} → ${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 ox({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 Wi({eventId:e,onClose:t}){const r=uy().find(a=>a.id===e),s=r?.service??"firestore",i=gy(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(Nl,{denial:r,rulesSource:i})]}):o.jsxs("div",{"data-pyric-ui":"traffic-inspect-missing",className:"traffic__inspector",children:[o.jsx("p",{className:"traffic__inspector-missing",children:"This operation isn't in this session's traffic. It may be from an earlier session, or the event has aged out of the buffer."}),o.jsx("button",{type:"button",className:"traffic__inspector-close",onClick:t,children:"Back to the log"})]})}const lx=new Intl.NumberFormat,cx={reads:"read operations",writes:"writes",deletes:"deletes"},ux={allows:"allowed requests",denies:"denied requests"};function zi(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 Ki(e){return e&&`${e[0].toUpperCase()}${e.slice(1)}`}function Dl(e,t){const n=e.reduce((u,d)=>u+d.total,0);if(n===0)return{total:n,headline:t.emptyHeadline,finding:t.emptyFinding};const r=Math.max(...e.map(u=>u.total)),s=e.filter(u=>u.total===r),i=`${lx.format(n)} observed ${n===1?t.singular:t.plural}`,a=u=>t.labels[u.key]??u.label.toLowerCase();if(s.length>1){const u=s.map(a);return{total:n,headline:i,finding:s.length===e.length?`${t.evenSplitPrefix} ${zi(u)}.`:`${Ki(zi(u))} tied for the largest share of ${t.subject} in this window.`}}const l=s[0],c=Math.round(l.total/n*100);return{total:n,headline:i,finding:`${Ki(a(l))} accounted for ${c}% of ${t.subject} in this window.`}}function dx(e){return Dl(e,{labels:cx,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 fx(e){return Dl(e,{labels:ux,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 hx=new Intl.NumberFormat,px=new Intl.DateTimeFormat(void 0,{hour:"numeric",minute:"2-digit"});function Hi(e){return hx.format(e)}function jt(e){return px.format(e)}function mx(e){return Dn(e)==="bypassed"}function yx(e){return e.every(t=>t.total===0)}function Pl({eyebrow:e,story:t,series:n,points:r,window:s,emptyLabel:i,evidenceTitle:a,source:l,methodology:c}){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(jb,{series:n,visible:u,onToggle:p,formatValue:Hi,className:`traffic__metric-cards traffic__metric-cards--journal traffic__metric-cards--${n.length}`}),yx(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:[jt(s.start),"–",jt(s.end)]})]}),o.jsx(Sb,{points:r,series:n,visible:u,omitZeroSeries:!0,formatValue:Hi,formatTime:jt,className:"traffic__chart traffic__chart--journal"}),o.jsxs("div",{className:"traffic__metric-axis","aria-hidden":"true",children:[o.jsx("span",{children:jt(s.start)}),o.jsx("span",{children:jt(s.end)})]})]}),o.jsxs("footer",{className:"traffic__metric-footer",children:[o.jsx("p",{className:"traffic__metric-source",children:l}),o.jsxs("details",{className:"traffic__metric-methodology",children:[o.jsx("summary",{children:"How this is counted"}),o.jsx("div",{children:c})]})]})]})}function bx({events:e,window:t}){const n=h.useMemo(()=>e.filter(i=>(i.service??"firestore")==="firestore"),[e]),r=nb({events:n,window:t,isAdmin:mx}),s=h.useMemo(()=>dx(r.series),[r.series]);return o.jsx("div",{className:"traffic__metrics","data-pyric-ui":"traffic-billable-view",children:o.jsx(Pl,{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 gx({events:e,window:t}){const n=h.useMemo(()=>e.filter(a=>a.rulesDisposition.kind==="evaluated"),[e]),r=rb({events:n,window:t}),s=h.useMemo(()=>r.series.filter(a=>a.key==="allows"||a.key==="denies"),[r.series]),i=h.useMemo(()=>fx(s),[s]);return o.jsx("div",{className:"traffic__metrics","data-pyric-ui":"traffic-rules-view",children:o.jsx(Pl,{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 vx=[{id:"timeline",label:"Timeline"},{id:"billable",label:"Billable metrics"},{id:"rules",label:"Rules"}];function wx(e){return e==="billable"?"billable":e==="rules"||e==="subscriptions"?"rules":"timeline"}function xx(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 jx(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:xx(n.length,r)}}function kx(e,t){return e?.start===t.start&&e.end===t.end?null:t}function _x(){const{tab:e,query:t}=be();return e!=="traffic"?"timeline":wx(t.view)}function Sx(){const e=h.useSyncExternalStore(Ut,_x,()=>"timeline"),t=h.useCallback(n=>{const r={...be().query,view:n==="timeline"?void 0:n};r.view===void 0&&delete r.view,ce({tab:"traffic",query:r})},[]);return[e,t]}function Ex(){const e=h.useSyncExternalStore(Ut,()=>be().query.hide==="studio",()=>!1),t=h.useCallback(()=>{const n={...be().query};n.hide==="studio"?delete n.hide:n.hide="studio",ce({tab:"traffic",query:n})},[]);return[e,t]}function Cx(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 Gi(e){return`${At(e.start)}–${At(e.end)}`}function Nx({event:e}){const t=Dn(e);return t?o.jsx("span",{className:"traffic__verdict","data-verdict":t,children:t}):null}function Rx(){return h.useSyncExternalStore(Ut,()=>Sl(be().query),()=>null)}const Xn=100;function Ax(){const e=cy(),[t,n]=Sx(),[r,s]=Ex(),i=h.useMemo(()=>Ww(e,r),[e,r]),a=e.length-i.length,[l,c]=h.useState("all"),[u,d]=h.useState(null),p=Rx(),[f,m]=h.useState(Xn),y=E=>{ce({tab:"traffic",query:Hw(be().query,E)})},g=()=>{ce({tab:"traffic",query:El(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?jx(i,u):null,[i,u]),x=w?.events??i,k=h.useMemo(()=>Kw(x,l).sort((E,R)=>R.at-E.at),[x,l]),{items:j}=Vy({events:k}),_=j.slice(0,f),N=j.length-_.length,P=i.length>=un,I=i.filter(E=>E.result==="deny").length,D=E=>o.jsx(Nx,{event:E}),C=E=>{if(Yn(E)){y(E.id);return}const R=qi(E);R&&ce(R)},S=p!=null&&_.some(E=>E.type!=="group"&&E.event.id===p);return o.jsxs("section",{"data-pyric-ui":"traffic-surface",className:"traffic",children:[o.jsxs("div",{className:"traffic__tabs",role:"tablist","aria-label":"Traffic views",children:[vx.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(bx,{events:i,window:v}):t==="rules"?o.jsx(gx,{events:i,window:v}):o.jsxs(o.Fragment,{children:[o.jsx(vb,{events:i,window:v,brush:u??void 0,onBrush:E=>{d(R=>kx(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 ${un})`:""]}),I>0?o.jsxs("button",{type:"button",className:"traffic__tl-deny","aria-pressed":l==="deny",onClick:()=>c(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:Cx(E.start,b)}),o.jsx("span",{children:"now"})]}),renderBucketSummary:E=>o.jsxs("div",{className:"traffic__bucket-summary",children:[o.jsx("span",{children:Gi(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:Gi(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"}),zw.map(E=>o.jsx("button",{type:"button",className:"traffic__filter","aria-pressed":l===E,onClick:()=>c(E),children:E},E))]}),p&&!S?o.jsx(Wi,{eventId:p,onClose:g},p):null,j.length===0?o.jsx("p",{className:"traffic__empty",children:w?l==="all"?"No requests occurred in the selected interval.":`No ${l} traffic occurred in the selected interval.`:l==="all"?"No requests yet. Reads, writes, and listeners against the sandbox stream in live.":`No ${l} traffic in this session.`}):o.jsxs("div",{className:"traffic__log","data-pyric-ui":"traffic-log","data-pyric-grouped":"","data-pyric-time-focused":w?"":void 0,children:[o.jsx("ul",{"data-pyric-traffic-log-items":"",children:_.map(E=>E.type==="group"?o.jsx("li",{"data-pyric-traffic-group-entry":"",children:o.jsx(bb,{group:E,onSelect:R=>{const V=R;if(Yn(V)){y(V.id);return}const G=qi(V);G&&ce(G)},renderClassification:R=>D(R),formatTime:At})},E.key):o.jsxs("li",{"data-pyric-traffic-entry":"","data-pyric-traffic-id":E.event.id,"data-verdict":Dn(E.event)??void 0,children:[o.jsx(Io,{event:E.event,selected:E.event.id===p,onSelect:R=>C(R),renderClassification:R=>D(R),formatTime:At}),E.event.id===p&&Yn(E.event)?o.jsx(Wi,{eventId:p,onClose:g},p):null]},E.event.id))}),N>0?o.jsxs("button",{type:"button",className:"traffic__show-more",onClick:()=>m(E=>E+Xn),children:["Show ",Math.min(N,Xn)," more (",N," hidden)"]}):null]})]})]})}const Ji=["amber","teal","coral","slate","olive","plum","rust","indigo","mint","sand","ash","jade"],Yi=["fox","owl","lynx","crane","otter","wren","ibex","hare","newt","moth","seal","vole"];function us(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`${Ji[t%Ji.length]}-${Yi[(t>>>4)%Yi.length]}`}function Ix(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 Dx(e){return e?{tab:"firestore",rest:e.split("/").filter(Boolean)}:null}function Px(e){const{provenance:t,identity:n}=Ix(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:Dx(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 $x(e,t=20){const n=[];for(let r=e.length-1;r>=0&&n.length<t;r--){const s=Px(e[r]);s&&n.push(s)}return n}const Ox=20;function Ux(e){ce(e)}function ot({target:e,className:t,children:n,title:r}){return o.jsx("a",{className:t,href:kn(e),title:r,onClick:s=>{s.metaKey||s.ctrlKey||s.shiftKey||s.altKey||(s.preventDefault(),Ux(e))},children:n})}function Mx(){const e=Pe(),t=En(),n=es();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(ot,{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(ot,{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"}),us(n)]},"instance")),o.jsx("div",{className:"studio-home__status","aria-label":"Sandbox status",children:s})}function Tx(e){return new Date(e).toLocaleTimeString(void 0,{hour12:!1})}function Bx(){const e=Mt(),t=h.useMemo(()=>$x(e,Ox),[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(ot,{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:Tx(n.at)})]});return o.jsx("li",{children:n.target?o.jsx(ot,{className:"studio-home__feed-row",target:n.target,children:r}):o.jsx("span",{className:"studio-home__feed-row",children:r})},n.id)})})})]})}const Lx=["firestore","auth","rtdb","storage","traffic"];function Fx(){const e=$e(),t=Mt(),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:Lx.map(r=>{const s=We.find(i=>i.id===r);return s?o.jsxs(ot,{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 Vx(){const e=En(),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(ot,{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 qx(){const e=$e(),t=Mt(),n=Pe(),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(Ro,{exposeFocus:Kp}),o.jsx(Mx,{}),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(Vx,{}):o.jsxs(o.Fragment,{children:[o.jsx(Bx,{}),o.jsx(Fx,{})]})})]})}function te(e){const t=e.split("/").filter(Boolean);return t.length===0?"/":`/${t.join("/")}`}function ze(e){return te(e).split("/").filter(Boolean)}function Dr(e,t){return te([...ze(e),...t.split("/").filter(Boolean)].join("/"))}function $l(e,t){const n=ze(e),r=ze(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 Ol(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=Ol(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 Wx(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 ds(e){return e===null||typeof e!="object"?!1:Object.keys(e).length>0}function Ul(e){return e===null||typeof e!="object"?[]:Object.entries(e).sort(([t],[n])=>t.localeCompare(n,void 0,{numeric:!0}))}function Ml(e,t){let n=e??null;for(const r of ze(t)){if(n===null||typeof n!="object")return null;n=n[r]??null}return n}function zx(e){return e==null?"null":Array.isArray(e)?"array":typeof e}function Pr(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,l)=>Pr(a,t[l]));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&&Pr(n[a],r[a]))}function Kx(e,t){const n=new Map,r=(s,i)=>{if(!ds(s)){n.set(i,["leaf",s??null]);return}const a=Ul(s);n.set(i,["parent",a.map(([l])=>l)]);for(const[l,c]of a)r(c,Dr(i,l))};return r(e,te(t)),n}function Hx(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 Gx(e){const t=ze(e);return t.map((n,r)=>({label:n,path:`/${t.slice(0,r+1).join("/")}`}))}const Jx=["string","number","boolean","json"];function Xi(e){switch(typeof e){case"string":return"string";case"number":return"number";case"boolean":return"boolean";default:return"json"}}function Yx(e,t){return t==="json"?JSON.stringify(e??null):e==null?"":String(e)}function Xx(e){if(e.trim().length===0)return"Enter a key.";const t=e.match(/[.$#[\]/]/);return t?`Keys can't contain "${t[0]}".`:null}function Qx(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 Tl(e){return{path:te(e),status:"loading",value:null,error:null,expanded:{},pages:{}}}function Bl(e,t){const n=$l(e.path,t);return n===null?null:Ml(e.value,n)}function Zx(e,t){const n=te(t);return n===e.path||e.expanded[n]===!0}function ej(e,t,n){const r=Ul(Bl(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 Qi(e,t){const n={};let r=!1;for(const[s,i]of Object.entries(e)){const a=$l(t.path,s);a!==null&&ds(Ml(t.value,a))?n[s]=i:r=!0}return r?n:e}function Ll(e,t){switch(t.type){case"navigate":{const n=te(t.path);return n===e.path?e:Tl(n)}case"value":{if(te(t.path)!==e.path)return e;const n={...e,status:"live",value:Ol(t.value),error:null};return n.expanded=Qi(e.expanded,n),n.pages=Qi(e.pages,n),n}case"error":return te(t.path)!==e.path?e:{...e,status:"error",error:t.message};case"expand":{const n=te(t.path);return n===e.path||e.expanded[n]?e:{...e,expanded:{...e.expanded,[n]:!0}}}case"collapse":{const n=te(t.path);if(!e.expanded[n])return e;const r={...e.expanded};return delete r[n],{...e,expanded:r}}case"toggle":{const n=te(t.path);return Ll(e,{type:e.expanded[n]?"collapse":"expand",path:n})}case"show-more":{const n=te(t.path),r=e.pages[n]??t.pageSize;return{...e,pages:{...e.pages,[n]:r+t.pageSize}}}}}const tj=50;function nj(e,t,n={}){const r=n.pageSize??tj,s=te(t),[i,a]=h.useReducer(Ll,s,Tl),l=h.useMemo(()=>Kx(i.value,i.path),[i.path,i.value]),c=cs({scope:i.path,entries:l,equals:Pr,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=>Bl(i,g),[i]),d=h.useCallback(g=>Zx(i,g),[i]),p=h.useCallback(g=>ej(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=>c.get(te(g)),[c]);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 rj({path:e,onNavigate:t,rootLabel:n="/",inputPrefix:r,className:s}){const i=te(e),[a,l]=h.useState(!1),c=h.useRef(null);h.useEffect(()=>{a&&c.current?.select()},[a]);const u=f=>{f.preventDefault(),t(Hx(c.current?.value??"")),l(!1)},d=()=>l(!1),p=Gx(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:c,"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:()=>l(!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 sj({tree:e,api:t,onNavigate:n,rootLabel:r="/",className:s}){const{state:i}=e,a=ze(i.path),l=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(Fl,{tree:e,api:t,onNavigate:n,path:i.path,label:l,isViewRoot:!0})})}function Fl({tree:e,api:t,onNavigate:n,path:r,label:s,isViewRoot:i}){const a=e.valueAt(r),l=ds(a),c=e.isExpanded(r),u=e.updateAt(r),[d,p]=h.useState(!1),[f,m]=h.useState(!1),[y,g]=h.useState(!1),[v,b]=h.useState(null),w=async(j,_)=>{try{await j(),b(null),_()}catch(N){b(N instanceof Error?N.message:String(N))}},x=()=>{p(!0),g(!1),l&&!c&&e.toggle(r)},k=l&&c?e.childrenAt(r):null;return o.jsxs("div",{"data-rtdb-node":!0,"data-rtdb-kind":l?"parent":"leaf","data-rtdb-view-root":i?"":void 0,"data-rtdb-expanded":l&&c?"":void 0,children:[o.jsxs("div",{"data-rtdb-row":!0,"data-pyric-update":u?.kind,"data-pyric-update-cycle":u?.cycle,children:[l&&!i?o.jsx("button",{type:"button","data-rtdb-caret":!0,"aria-expanded":c,"aria-label":c?"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}),l?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":zx(a),title:"Edit value",onClick:()=>{m(!0),g(!1)},children:Wx(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",l?" 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 ${Zi(r)}`,title:"Add child",onClick:x,children:"+"}),o.jsx("button",{type:"button","data-rtdb-action-delete":!0,"aria-label":`Delete ${Zi(r)}`,title:"Delete",onClick:()=>g(!0),children:"×"})]})})]}),v?o.jsx("p",{role:"alert","data-rtdb-error":!0,children:v}):null,f?o.jsx(ea,{initialType:Xi(a),initialText:Yx(a,Xi(a)),submitLabel:"Save",onCancel:()=>m(!1),onSubmit:j=>w(()=>t.set(r,j),()=>m(!1))}):null,d?o.jsx(ea,{withKey:!0,initialType:"string",initialText:"",submitLabel:"Add",onCancel:()=>p(!1),onSubmit:(j,_)=>w(()=>t.set(Dr(r,_),j),()=>p(!1))}):null,k?o.jsxs("ul",{"data-rtdb-children":!0,children:[k.entries.map(([j])=>o.jsx("li",{children:o.jsx(Fl,{tree:e,api:t,onNavigate:n,path:Dr(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 Zi(e){const t=ze(e);return t.length===0?"root":t[t.length-1]}function ea({withKey:e,initialType:t,initialText:n,submitLabel:r,onSubmit:s,onCancel:i}){const a=h.useRef(null),l=h.useRef(null),[c,u]=h.useState(t),[d,p]=h.useState(null),f=y=>{y.preventDefault();const g=a.current?.value??"";if(e){const b=Xx(g);if(b){p(b);return}}const v=Qx(c,l.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:c,onChange:y=>u(y.currentTarget.value),onKeyDown:m,children:Jx.map(y=>o.jsx("option",{value:y,children:y},y))}),c==="boolean"?o.jsxs("select",{ref:l,"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:l,"data-rtdb-editor-value":!0,"aria-label":"Value",placeholder:c==="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 ij(){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(oj,{live:t}):o.jsx(aj,{})]})}function aj(){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 oj({live:e}){const[t,n]=h.useState("/"),r=us(es()),s=r?`${r}-sandbox`:"sandbox",i=h.useMemo(()=>({set:(l,c)=>e.setRtdbValue(l,c),remove:l=>e.deleteRtdbValue(l),subscribeValue:(l,c,u)=>e.subscribeRtdbValue(l,c,u)}),[e]),a=nj(i,t);return o.jsxs("div",{className:"rtdb",children:[o.jsx(rj,{className:"rtdb__pathbar",path:t,onNavigate:n,rootLabel:s,inputPrefix:s}),o.jsx(sj,{className:"rtdb__tree",tree:a,api:i,onNavigate:n,rootLabel:s})]})}function lj(e){if(e===null)return null;const t={collections:0,users:0,objects:0,rtdbKeys:0};for(const n of e)n.kind==="collection"?t.collections++:n.kind==="user"?t.users++:n.kind==="object"?t.objects++:n.kind==="rtdb-key"&&t.rtdbKeys++;return t}function Ht(e,t,n=`${t}s`){return`${e} ${e===1?t:n}`}function cj(e){if(e===null)return"measuring…";const t=[];return e.collections&&t.push(Ht(e.collections,"collection")),e.users&&t.push(Ht(e.users,"user")),e.objects&&t.push(Ht(e.objects,"file")),e.rtdbKeys&&t.push(Ht(e.rtdbKeys,"RTDB key")),t.length?t.join(" · "):"empty — no data yet"}function Pn(){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 uj(){return o.jsxs("svg",{...Pn(),children:[o.jsx("path",{d:"M12 4v10"}),o.jsx("path",{d:"M8 10l4 4 4-4"}),o.jsx("path",{d:"M4 19h16"})]})}function dj(){return o.jsxs("svg",{...Pn(),children:[o.jsx("path",{d:"M12 14V4"}),o.jsx("path",{d:"M8 8l4-4 4 4"}),o.jsx("path",{d:"M4 19h16"})]})}function fj(){return o.jsxs("svg",{...Pn(),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 hj(){return o.jsxs("svg",{...Pn(),children:[o.jsx("path",{d:"M4 5v5h5"}),o.jsx("path",{d:"M4.6 10a8 8 0 1 0 1.7-5.3"})]})}function Gt({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 pj(){const e=py(),t=my(),n=yy(),r=by(),s=En(),i=h.useRef(null),a=us(es()),[l,c]=h.useState(!1),[u,d]=h.useState(!1),[p,f]=h.useState(!1),[m,y]=h.useState(!1),[g,v]=h.useState(""),b=No(),{ensure:w}=b;h.useEffect(()=>w(),[w]);const x=lj(b.entries),k=cj(x),j=s.status==="ready"?s.payload.persist?"persisted to disk":"ephemeral":"in-page · resets on reload",_=async()=>{const S=await t();if(!S||typeof document>"u")return;const E=URL.createObjectURL(new Blob([S],{type:"application/json"})),R=document.createElement("a");R.href=E,R.download=`pyric-sandbox-${a||"export"}.json`,R.click(),URL.revokeObjectURL(E)},N=async S=>{const E=S.target.files?.[0];if(S.target.value="",!!E&&!(typeof window<"u"&&!window.confirm("Import replaces all data in this sandbox. This cannot be undone. Continue?"))){d(!0);try{await n(await E.text())}finally{d(!1)}}},P=async()=>{f(!1),c(!0);try{await e()}finally{c(!1)}},I=async()=>{const S=g.trim();S&&(await r.save(S),v(""),y(!1))},D=async S=>{typeof window<"u"&&!window.confirm(`Switch to branch "${S}"? This replaces the current sandbox state.`)||await r.switchTo(S)},C=async S=>{typeof window<"u"&&!window.confirm(`Delete branch "${S}"?`)||await r.remove(S)};return o.jsxs("section",{className:"studio-surface studio-settings","aria-labelledby":"settings-title",children:[o.jsxs("div",{className:"studio-surface__intro",children:[o.jsx("p",{className:"studio-surface__eyebrow",children:"Settings"}),o.jsx("h1",{id:"settings-title",className:"studio-surface__title",children:"Configuration and maintenance."}),o.jsx("p",{className:"studio-surface__copy",children:"Global controls live here so service surfaces can stay focused on their primary work."})]}),o.jsx("div",{className:"studio-settings__grid",children:o.jsxs("section",{className:"studio-panel studio-settings__panel","aria-labelledby":"settings-sandbox-title",children:[o.jsx("h2",{id:"settings-sandbox-title",className:"studio-panel__title",children:"Sandbox"}),o.jsxs("div",{className:"studio-sandbox__live","aria-label":"Sandbox contents",children:[o.jsx("span",{className:"studio-sandbox__instance mono",children:a||"local"}),o.jsx("span",{className:"studio-sandbox__inventory",children:k}),o.jsx("span",{className:"studio-sandbox__persist",children:j})]}),o.jsxs("div",{className:"studio-sandbox__actions",children:[o.jsx(Gt,{glyph:o.jsx(uj,{}),name:"Export",caption:"Downloads all of this as one file.",onClick:()=>void _()}),o.jsx(Gt,{glyph:o.jsx(dj,{}),name:u?"Importing…":"Import",caption:"A chosen file replaces everything here.",disabled:u,onClick:()=>i.current?.click()}),o.jsx(Gt,{glyph:o.jsx(fj,{}),name:"Save branch",caption:"Keeps a copy you can return to.",onClick:()=>y(S=>!S)}),o.jsx(Gt,{glyph:o.jsx(hj,{}),name:l?"Resetting…":"Reset session",caption:"Everything returns to the seeded start.",disabled:l,danger:!0,onClick:()=>f(!0)})]}),o.jsx("input",{ref:i,type:"file",accept:"application/json,.json",className:"studio-settings__file",onChange:N}),m?o.jsxs("form",{className:"studio-sandbox__name-row",onSubmit:S=>{S.preventDefault(),I()},children:[o.jsx("input",{className:"studio-sandbox__name-input",type:"text",value:g,placeholder:"branch name","aria-label":"Branch name",autoFocus:!0,onChange:S=>v(S.target.value),onKeyDown:S=>{S.key==="Escape"&&(y(!1),v(""))}}),o.jsx("button",{type:"submit",className:"studio-button",disabled:!g.trim(),children:"Save"}),o.jsx("button",{type:"button",className:"studio-button",onClick:()=>{y(!1),v("")},children:"Cancel"})]}):null,p?o.jsxs("div",{className:"studio-sandbox__confirm",role:"alert",children:[o.jsx("span",{className:"studio-sandbox__confirm-copy",children:x&&k!=="empty — no data yet"?`This erases ${k}.`:"This erases everything in this sandbox."}),o.jsxs("span",{className:"studio-sandbox__confirm-actions",children:[o.jsx("button",{type:"button",className:"studio-button studio-button--danger",onClick:()=>void P(),children:"Erase and reseed"}),o.jsx("button",{type:"button",className:"studio-button",onClick:()=>f(!1),children:"Keep"})]})]}):null,r.branches.length>0?o.jsx("div",{className:"studio-settings__branches",children:r.branches.map(S=>o.jsxs("div",{className:"studio-settings__branch",children:[o.jsx("span",{className:"mono",children:S}),o.jsxs("span",{className:"studio-settings__branch-actions",children:[o.jsx("button",{type:"button",className:"studio-button",onClick:()=>void D(S),children:"Switch"}),o.jsx("button",{type:"button",className:"studio-button",onClick:()=>void C(S),children:"Delete"})]})]},S))}):o.jsx("p",{className:"studio-sandbox__branches-empty",children:"No branches yet — Save branch keeps this exact state to come back to."})]})})]})}function Jt(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 mj(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}: ${Jt(n[a])} -> ${Jt(r[a])}`).join(", ")}return`${Jt(t.before)} -> ${Jt(t.after)}`}function yj(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:mj(t),supported:t.qualification.supported}))}function bj(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 gj="pyric:assurance-campaign",vj="pyric-assurance-v1",$r=new Set;let ta=!1,na;function ra(e){for(const t of $r)t(e)}function sa(e){return!!e&&typeof e=="object"&&e.schema==="pyric.assurance.visualization.v1"&&typeof e.campaignId=="string"}function wj(){if(!(ta||typeof document>"u")){ta=!0,globalThis.addEventListener(gj,e=>{const t=e.detail;sa(t)&&ra(t)});try{na=new BroadcastChannel(vj),na.onmessage=e=>{sa(e.data)&&ra(e.data)}}catch{}}}function xj(e){return wj(),$r.add(e),()=>$r.delete(e)}function Qn(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 jj=[Qn({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"}}),Qn({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"}),Qn({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"}}})],Wj=jj.map(e=>({...e,campaignId:"collaboration-local-v1-fixed",targetHash:"fnv1a32-a9f18f23",mutation:{...e.mutation,decision:"DENY",events:[]},stateDiff:void 0,classification:"no-counterexample"}));const Or="pyric:assurance:campaigns",Vl="pyric:assurance:campaign:";function kj(e){return!!e&&typeof e=="object"&&e.schema==="pyric.assurance.visualization.v1"&&typeof e.campaignId=="string"}function _j(){if(typeof sessionStorage>"u")return[];try{const e=JSON.parse(sessionStorage.getItem(Or)??"[]");if(!Array.isArray(e))return[];const t=e.map(n=>sessionStorage.getItem(`${Vl}${String(n)}`)).filter(n=>!!n).map(n=>JSON.parse(n)).filter(kj);return t.length,t}catch{return[]}}function Sj(e){if(!(typeof sessionStorage>"u"))try{const t=JSON.parse(sessionStorage.getItem(Or)??"[]"),n=Array.isArray(t)?t.map(String):[];n.includes(e.campaignId)||n.push(e.campaignId),sessionStorage.setItem(Or,JSON.stringify(n)),sessionStorage.setItem(`${Vl}${e.campaignId}`,JSON.stringify(e))}catch{}}function Ej(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 Cj(){const[e,t]=h.useState(_j);return h.useEffect(()=>{const r=xj(s=>{Sj(s),t(i=>Ej(i,s))});return()=>{r()}},[]),e}function Nj(e,t){return e!==t?"assurance-verdict--mismatch":t==="ALLOW"?"assurance-verdict--allow":"assurance-verdict--deny"}function Rj(e){return e.replaceAll("-"," ")}function ia({value:e}){return o.jsx("pre",{className:"assurance-evidence__json",children:JSON.stringify(e,null,2)})}function Aj(){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 aa({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 Ij({campaigns:e}){const t=Cj(),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],l=h.useMemo(()=>a?.report?yj(a.report):[],[a]),[c,u]=h.useState(r.probe??l[0]?.id??"");if(h.useEffect(()=>{!s&&n[0]&&i(n[0].campaignId)},[s,n]),h.useEffect(()=>{l.some(x=>x.id===c)||u(l[0]?.id??"")},[l,c]),!a)return o.jsx(Aj,{});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(aa,{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=l.find(x=>x.id===c)??l[0],m=p.results.find(x=>x.probeId===f?.id),y=m?bj(m):null,g=a.verifications?.at(-1),v=g!==void 0&&g.summary.controlsPassed===g.summary.probes&&g.summary.noCounterexamples===g.summary.probes&&g.summary.localCounterexamples===0&&g.summary.engineGaps===0&&g.summary.invalidProbes===0;function b(x){i(x);const j=n.find(_=>_.campaignId===x)?.report?.results[0]?.probeId??"";u(j),ln({tab:"assurance",query:{campaign:x,probe:j||void 0}})}function w(x){u(x.id),ln({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(aa,{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"})]}),l.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 ${Nj(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:Rj(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(ia,{value:m.stateDiff.before})]}),o.jsxs("div",{children:[o.jsx("span",{children:"After"}),o.jsx(ia,{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(Nl,{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 ql(){const e="/__pyric/ui/";return`${e.endsWith("/")?e:`${e}/`}docs`}function Dj(){const[e,t]=h.useState(!1);return h.useEffect(()=>{let n=!0;return fetch(`${ql()}/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 Pj({id:e}){const t=Qp(e),n=Pe(),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 $j({id:e}){switch(e){case"home":return o.jsx(qx,{});case"firestore":return o.jsx(Aw,{});case"auth":return o.jsx(Mw,{});case"storage":return o.jsx(Iw,{});case"rtdb":return o.jsx(ij,{});case"traffic":return o.jsx(Ax,{});case"assurance":return o.jsx(Ij,{});case"settings":return o.jsx(pj,{});default:return o.jsx(Pj,{id:e})}}function Oj(){const[e,t]=zp(Xp,"home"),n=l=>t(l),[r,s]=h.useState(!1),i=Dj(),a=e==="home";return h.useEffect(()=>{const l=c=>{if(Gp(c)){if(r){c.preventDefault(),s(!1);return}if(a){Hp()&&c.preventDefault();return}c.preventDefault(),s(!0)}};return window.addEventListener("keydown",l),()=>window.removeEventListener("keydown",l)},[a,r]),h.useEffect(()=>{a&&s(!1)},[a]),h.useEffect(()=>{document.querySelector('.studio__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:[We.map(l=>o.jsx("button",{type:"button",className:"studio__nav-tab","aria-current":l.id===e?"page":void 0,onClick:()=>n(l.id),children:l.label},l.id)),i?o.jsx("a",{className:"studio__nav-tab",href:ql(),children:"Docs"}):null]}),o.jsx(Ly,{})]})}),o.jsx("main",{className:"studio__content","data-surface":e,children:o.jsx("div",{className:"studio__surface-slot","data-active":"true",children:o.jsx($j,{id:e})})}),r?o.jsx(Sy,{onClose:()=>s(!1)}):null]})}function Uj(){return o.jsx(Lp,{children:o.jsx(rd,{children:o.jsx(Op,{mode:"local",children:o.jsx(Oj,{})})})})}function zj(){return o.jsx(h.StrictMode,{children:o.jsx(Uj,{})})}export{zj as S,qj as a,Sm as b,Nt as r,fe as s,eo as u};
|