@pyric/cli 0.1.0-alpha.10 → 0.1.0-alpha.11
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.orig +2 -2
- package/dist/assurance/.generated/conformance-verdicts.d.ts +16 -0
- package/dist/assurance/.generated/conformance-verdicts.d.ts.map +1 -1
- package/dist/assurance/.generated/conformance-verdicts.js +16 -0
- package/dist/assurance/.generated/conformance-verdicts.js.map +1 -1
- package/dist/bridge/server/peer.d.ts +1 -1
- package/dist/bridge/server.d.ts +1 -1
- package/dist/bridge/server.js +1 -1
- package/dist/cli/index.d.ts +11 -0
- package/dist/cli/index.d.ts.map +1 -1
- package/dist/cli/index.js +13 -1
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/init.d.ts +3 -3
- package/dist/cli/init.d.ts.map +1 -1
- package/dist/cli/init.js +5 -5
- package/dist/cli/init.js.map +1 -1
- package/dist/cli/serve.d.ts.map +1 -1
- package/dist/cli/serve.js +8 -2
- package/dist/cli/serve.js.map +1 -1
- package/dist/conformance/.generated/can-i-use-browser.d.ts.map +1 -1
- package/dist/conformance/.generated/can-i-use-browser.js +1 -1
- package/dist/conformance/.generated/can-i-use-browser.js.map +1 -1
- package/dist/conformance/.generated/can-i-use.d.ts.map +1 -1
- package/dist/conformance/.generated/can-i-use.js +1 -1
- package/dist/conformance/.generated/can-i-use.js.map +1 -1
- package/dist/conformance/.generated/conformance-docs.d.ts +12 -0
- package/dist/conformance/.generated/conformance-docs.d.ts.map +1 -0
- package/dist/conformance/.generated/conformance-docs.js +2 -0
- package/dist/conformance/.generated/conformance-docs.js.map +1 -0
- package/dist/conformance/docs.d.ts +6 -0
- package/dist/conformance/docs.d.ts.map +1 -0
- package/dist/conformance/docs.js +6 -0
- package/dist/conformance/docs.js.map +1 -0
- package/dist/remote/index.d.ts.map +1 -1
- package/dist/remote/index.js +1 -0
- package/dist/remote/index.js.map +1 -1
- package/dist/serve/activity-guard.d.ts +4 -0
- package/dist/serve/activity-guard.d.ts.map +1 -0
- package/dist/serve/activity-guard.js +22 -0
- package/dist/serve/activity-guard.js.map +1 -0
- package/dist/serve/activity-route.d.ts +4 -0
- package/dist/serve/activity-route.d.ts.map +1 -0
- package/dist/serve/activity-route.js +157 -0
- package/dist/serve/activity-route.js.map +1 -0
- package/dist/serve/activity-warning.d.ts +4 -0
- package/dist/serve/activity-warning.d.ts.map +1 -0
- package/dist/serve/activity-warning.js +21 -0
- package/dist/serve/activity-warning.js.map +1 -0
- package/dist/serve/bridge-mount.d.ts +5 -0
- package/dist/serve/bridge-mount.d.ts.map +1 -1
- package/dist/serve/bridge-mount.js +1 -0
- package/dist/serve/bridge-mount.js.map +1 -1
- package/dist/serve/docs-ui/404.html +3 -0
- package/dist/serve/docs-ui/_astro/{_slug_.DPUwShm2.css → _slug_.CXh9yTP1.css} +1 -1
- package/dist/serve/docs-ui/_astro/_slug_.DUci-duz.css +1 -0
- package/dist/serve/docs-ui/docs/_rhythm/index.html +2 -1
- package/dist/serve/docs-ui/docs/agent/set-up-your-agent/index.html +3 -2
- package/dist/serve/docs-ui/docs/agent/set-up-your-agent.md +1 -1
- package/dist/serve/docs-ui/docs/agent/watch-and-review/index.html +2 -1
- package/dist/serve/docs-ui/docs/agent/work-with-an-agent/index.html +2 -1
- package/dist/serve/docs-ui/docs/ai-compat/index.html +2 -1
- package/dist/serve/docs-ui/docs/api-reference/index.html +51 -49
- package/dist/serve/docs-ui/docs/api-reference.md +2 -2
- package/dist/serve/docs-ui/docs/app-compat/index.html +2 -1
- package/dist/serve/docs-ui/docs/auth-compat/index.html +2 -1
- package/dist/serve/docs-ui/docs/build/ai-logic/index.html +18 -3
- package/dist/serve/docs-ui/docs/build/ai-logic.md +30 -2
- package/dist/serve/docs-ui/docs/build/authentication/index.html +2 -1
- package/dist/serve/docs-ui/docs/build/authentication.md +1 -1
- package/dist/serve/docs-ui/docs/build/cloud-firestore/index.html +2 -1
- package/dist/serve/docs-ui/docs/build/cloud-messaging/index.html +46 -2
- package/dist/serve/docs-ui/docs/build/cloud-messaging.md +56 -1
- package/dist/serve/docs-ui/docs/build/cloud-storage/index.html +2 -1
- package/dist/serve/docs-ui/docs/build/cloud-storage.md +1 -1
- package/dist/serve/docs-ui/docs/build/realtime-database/index.html +21 -3
- package/dist/serve/docs-ui/docs/build/realtime-database.md +25 -1
- package/dist/serve/docs-ui/docs/conformance-scores/index.html +2 -1
- package/dist/serve/docs-ui/docs/create-pyric-reference-api/index.html +61 -28
- package/dist/serve/docs-ui/docs/create-pyric-reference-api.md +65 -20
- package/dist/serve/docs-ui/docs/database-compat/index.html +2 -1
- package/dist/serve/docs-ui/docs/firestore-compat/index.html +6 -5
- package/dist/serve/docs-ui/docs/firestore-compat.md +4 -4
- package/dist/serve/docs-ui/docs/functions-rtdb-compat/index.html +2 -1
- package/dist/serve/docs-ui/docs/get-started/how-the-swap-works/index.html +2 -1
- package/dist/serve/docs-ui/docs/get-started/start-building/index.html +4 -3
- package/dist/serve/docs-ui/docs/get-started/start-building.md +2 -2
- package/dist/serve/docs-ui/docs/index.json +800 -575
- package/dist/serve/docs-ui/docs/messaging-compat/index.html +2 -1
- package/dist/serve/docs-ui/docs/observe/see-whats-happening/index.html +2 -1
- package/dist/serve/docs-ui/docs/observe/shape-your-data/index.html +2 -1
- package/dist/serve/docs-ui/docs/overview/index.html +2 -1
- package/dist/serve/docs-ui/docs/pyric-admin-app-reference-api/index.html +5 -4
- package/dist/serve/docs-ui/docs/pyric-admin-app-reference-api.md +3 -4
- package/dist/serve/docs-ui/docs/pyric-admin-auth-reference-api/index.html +5 -4
- package/dist/serve/docs-ui/docs/pyric-admin-auth-reference-api.md +3 -4
- package/dist/serve/docs-ui/docs/pyric-admin-database-reference-api/index.html +5 -4
- package/dist/serve/docs-ui/docs/pyric-admin-database-reference-api.md +3 -4
- package/dist/serve/docs-ui/docs/pyric-admin-firestore-reference-api/index.html +2503 -12
- package/dist/serve/docs-ui/docs/pyric-admin-firestore-reference-api.md +2219 -8
- package/dist/serve/docs-ui/docs/pyric-admin-storage-reference-api/index.html +4 -3
- package/dist/serve/docs-ui/docs/pyric-admin-storage-reference-api.md +2 -3
- package/dist/serve/docs-ui/docs/pyric-ai-reference-api/index.html +16 -11
- package/dist/serve/docs-ui/docs/pyric-ai-reference-api.md +14 -13
- package/dist/serve/docs-ui/docs/pyric-ai-scripting-reference-api/index.html +4 -3
- package/dist/serve/docs-ui/docs/pyric-ai-scripting-reference-api.md +2 -3
- package/dist/serve/docs-ui/docs/pyric-app-reference-api/index.html +7 -2
- package/dist/serve/docs-ui/docs/pyric-app-reference-api.md +5 -2
- package/dist/serve/docs-ui/docs/pyric-auth-reference-api/index.html +23 -12
- package/dist/serve/docs-ui/docs/pyric-auth-reference-api.md +15 -12
- package/dist/serve/docs-ui/docs/pyric-cli-assurance-browser-reference-api/index.html +10 -48
- package/dist/serve/docs-ui/docs/pyric-cli-assurance-browser-reference-api.md +11 -24
- package/dist/serve/docs-ui/docs/pyric-cli-assurance-reference-api/index.html +87 -97
- package/dist/serve/docs-ui/docs/pyric-cli-assurance-reference-api.md +53 -65
- package/dist/serve/docs-ui/docs/pyric-cli-bridge-client-reference-api/index.html +14 -15
- package/dist/serve/docs-ui/docs/pyric-cli-bridge-client-reference-api.md +19 -28
- package/dist/serve/docs-ui/docs/pyric-cli-bridge-reference-api/index.html +4 -3
- package/dist/serve/docs-ui/docs/pyric-cli-bridge-reference-api.md +2 -3
- package/dist/serve/docs-ui/docs/pyric-cli-conformance-browser-reference-api/index.html +3 -2
- package/dist/serve/docs-ui/docs/pyric-cli-conformance-browser-reference-api.md +1 -2
- package/dist/serve/docs-ui/docs/pyric-cli-conformance-docs-reference-api/index.html +51 -0
- package/dist/serve/docs-ui/docs/pyric-cli-conformance-docs-reference-api.md +36 -0
- package/dist/serve/docs-ui/docs/pyric-cli-conformance-reference-api/index.html +3 -2
- package/dist/serve/docs-ui/docs/pyric-cli-conformance-reference-api.md +1 -2
- package/dist/serve/docs-ui/docs/pyric-cli-credentials-node-reference-api/index.html +3 -2
- package/dist/serve/docs-ui/docs/pyric-cli-credentials-node-reference-api.md +1 -2
- package/dist/serve/docs-ui/docs/pyric-cli-discover-reference-api/index.html +3 -2
- package/dist/serve/docs-ui/docs/pyric-cli-discover-reference-api.md +1 -2
- package/dist/serve/docs-ui/docs/pyric-cli-register-reference-api/index.html +3 -2
- package/dist/serve/docs-ui/docs/pyric-cli-register-reference-api.md +1 -2
- package/dist/serve/docs-ui/docs/pyric-cli-remote-reference-api/index.html +1067 -83
- package/dist/serve/docs-ui/docs/pyric-cli-remote-reference-api.md +1291 -160
- package/dist/serve/docs-ui/docs/pyric-cli-serve-worker-reference-api/index.html +123 -92
- package/dist/serve/docs-ui/docs/pyric-cli-serve-worker-reference-api.md +49 -20
- package/dist/serve/docs-ui/docs/pyric-cli-verify-reference-api/index.html +72 -7
- package/dist/serve/docs-ui/docs/pyric-cli-verify-reference-api.md +22 -7
- package/dist/serve/docs-ui/docs/pyric-cli-vite-reference-api/index.html +33 -12
- package/dist/serve/docs-ui/docs/pyric-cli-vite-reference-api.md +15 -12
- package/dist/serve/docs-ui/docs/pyric-database-reference-api/index.html +18 -17
- package/dist/serve/docs-ui/docs/pyric-database-reference-api.md +19 -22
- package/dist/serve/docs-ui/docs/pyric-firestore-reference-api/index.html +1512 -545
- package/dist/serve/docs-ui/docs/pyric-firestore-reference-api.md +1311 -316
- package/dist/serve/docs-ui/docs/pyric-firestore-values-reference-api/index.html +3 -2
- package/dist/serve/docs-ui/docs/pyric-firestore-values-reference-api.md +1 -2
- package/dist/serve/docs-ui/docs/pyric-messaging-reference-api/index.html +5 -4
- package/dist/serve/docs-ui/docs/pyric-messaging-reference-api.md +3 -4
- package/dist/serve/docs-ui/docs/pyric-messaging-sw-reference-api/index.html +69 -369
- package/dist/serve/docs-ui/docs/pyric-messaging-sw-reference-api.md +103 -216
- package/dist/serve/docs-ui/docs/pyric-rules-reference-api/index.html +10 -9
- package/dist/serve/docs-ui/docs/pyric-rules-reference-api.md +9 -10
- package/dist/serve/docs-ui/docs/pyric-sandbox-database-reference-api/index.html +8 -7
- package/dist/serve/docs-ui/docs/pyric-sandbox-database-reference-api.md +6 -7
- package/dist/serve/docs-ui/docs/pyric-sandbox-firestore-reference-api/index.html +10 -9
- package/dist/serve/docs-ui/docs/pyric-sandbox-firestore-reference-api.md +9 -10
- package/dist/serve/docs-ui/docs/pyric-sandbox-reference-api/index.html +374 -910
- package/dist/serve/docs-ui/docs/pyric-sandbox-reference-api.md +377 -911
- package/dist/serve/docs-ui/docs/pyric-storage-reference-api/index.html +25 -17
- package/dist/serve/docs-ui/docs/pyric-storage-reference-api.md +21 -19
- package/dist/serve/docs-ui/docs/pyric-ui-agents-reference-api/index.html +3 -2
- package/dist/serve/docs-ui/docs/pyric-ui-agents-reference-api.md +1 -2
- package/dist/serve/docs-ui/docs/pyric-ui-auth-hooks-reference-api/index.html +63 -776
- package/dist/serve/docs-ui/docs/pyric-ui-auth-hooks-reference-api.md +69 -510
- package/dist/serve/docs-ui/docs/pyric-ui-auth-reference-api/index.html +22 -21
- package/dist/serve/docs-ui/docs/pyric-ui-auth-reference-api.md +29 -30
- package/dist/serve/docs-ui/docs/pyric-ui-events-hooks-reference-api/index.html +15 -168
- package/dist/serve/docs-ui/docs/pyric-ui-events-hooks-reference-api.md +17 -87
- package/dist/serve/docs-ui/docs/pyric-ui-events-reference-api/index.html +6 -5
- package/dist/serve/docs-ui/docs/pyric-ui-events-reference-api.md +5 -6
- package/dist/serve/docs-ui/docs/pyric-ui-firestore-hooks-reference-api/index.html +82 -970
- package/dist/serve/docs-ui/docs/pyric-ui-firestore-hooks-reference-api.md +104 -479
- package/dist/serve/docs-ui/docs/pyric-ui-firestore-reference-api/index.html +30 -29
- package/dist/serve/docs-ui/docs/pyric-ui-firestore-reference-api.md +54 -55
- package/dist/serve/docs-ui/docs/pyric-ui-primitives-reference-api/index.html +3 -2
- package/dist/serve/docs-ui/docs/pyric-ui-primitives-reference-api.md +1 -2
- package/dist/serve/docs-ui/docs/pyric-ui-rtdb-reference-api/index.html +5 -4
- package/dist/serve/docs-ui/docs/pyric-ui-rtdb-reference-api.md +3 -4
- package/dist/serve/docs-ui/docs/pyric-ui-rules-hooks-reference-api/index.html +9 -124
- package/dist/serve/docs-ui/docs/pyric-ui-rules-hooks-reference-api.md +7 -58
- package/dist/serve/docs-ui/docs/pyric-ui-rules-reference-api/index.html +24 -23
- package/dist/serve/docs-ui/docs/pyric-ui-rules-reference-api.md +31 -34
- package/dist/serve/docs-ui/docs/pyric-ui-storage-hooks-reference-api/index.html +104 -1385
- package/dist/serve/docs-ui/docs/pyric-ui-storage-hooks-reference-api.md +133 -817
- package/dist/serve/docs-ui/docs/pyric-ui-storage-reference-api/index.html +34 -33
- package/dist/serve/docs-ui/docs/pyric-ui-storage-reference-api.md +37 -38
- package/dist/serve/docs-ui/docs/pyric-ui-traffic-hooks-reference-api/index.html +116 -1169
- package/dist/serve/docs-ui/docs/pyric-ui-traffic-hooks-reference-api.md +142 -590
- package/dist/serve/docs-ui/docs/pyric-ui-traffic-reference-api/index.html +4 -3
- package/dist/serve/docs-ui/docs/pyric-ui-traffic-reference-api.md +3 -4
- package/dist/serve/docs-ui/docs/rules-compat/index.html +34 -1
- package/dist/serve/docs-ui/docs/rules-compat.md +32 -0
- package/dist/serve/docs-ui/docs/secure/audit-your-rules/index.html +19 -2
- package/dist/serve/docs-ui/docs/secure/audit-your-rules.md +32 -0
- package/dist/serve/docs-ui/docs/secure/firestore-rules-limits/index.html +2 -1
- package/dist/serve/docs-ui/docs/secure/read-a-denial/index.html +2 -1
- package/dist/serve/docs-ui/docs/secure/rtdb-rules-in-typescript/index.html +2 -1
- package/dist/serve/docs-ui/docs/secure/rtdb-rules-in-typescript.md +1 -1
- package/dist/serve/docs-ui/docs/secure/rules-standard-library/index.html +2 -1
- package/dist/serve/docs-ui/docs/secure/secure-it-with-rules/index.html +2 -1
- package/dist/serve/docs-ui/docs/secure/simulate-and-lint/index.html +2 -1
- package/dist/serve/docs-ui/docs/secure/write-a-rules-test-suite/index.html +2 -1
- package/dist/serve/docs-ui/docs/ship/ship-to-production/index.html +2 -1
- package/dist/serve/docs-ui/docs/ship/test-in-node/index.html +2 -1
- package/dist/serve/docs-ui/docs/storage-compat/index.html +2 -1
- package/dist/serve/docs-ui/docs/trust/how-we-know-it-matches-firebase/index.html +2 -1
- package/dist/serve/docs-ui/docs/trust/versioning-and-compatibility/index.html +2 -1
- package/dist/serve/docs-ui/llms.txt +1 -0
- package/dist/serve/entries/ai.d.ts.map +1 -1
- package/dist/serve/entries/ai.js +39 -1
- package/dist/serve/entries/ai.js.map +1 -1
- package/dist/serve/entries/messaging-sw.d.ts.map +1 -1
- package/dist/serve/entries/messaging-sw.js +5 -1
- package/dist/serve/entries/messaging-sw.js.map +1 -1
- package/dist/serve/entries/messaging.d.ts.map +1 -1
- package/dist/serve/entries/messaging.js +7 -1
- package/dist/serve/entries/messaging.js.map +1 -1
- package/dist/serve/entries/runtime.d.ts.map +1 -1
- package/dist/serve/entries/runtime.js +20 -1
- package/dist/serve/entries/runtime.js.map +1 -1
- package/dist/serve/init-payload.d.ts +25 -0
- package/dist/serve/init-payload.d.ts.map +1 -1
- package/dist/serve/namespace.d.ts +39 -0
- package/dist/serve/namespace.d.ts.map +1 -1
- package/dist/serve/namespace.js +80 -1
- package/dist/serve/namespace.js.map +1 -1
- package/dist/serve/standalone-assets.d.ts +11 -9
- package/dist/serve/standalone-assets.d.ts.map +1 -1
- package/dist/serve/standalone-assets.js +6 -5
- package/dist/serve/standalone-assets.js.map +1 -1
- package/dist/serve/studio-ui/assets/{RulesCodeEditor-CXdSLKhO.js → RulesCodeEditor-CxVYcZXw.js} +1 -1
- package/dist/serve/studio-ui/assets/index-cpSfgQ7H.js +1218 -0
- package/dist/serve/studio-ui/assets/seed-DeuFKi4J.js +20 -0
- package/dist/serve/studio-ui/index.html +1 -1
- package/dist/serve/vite-plugin.d.ts +92 -15
- package/dist/serve/vite-plugin.d.ts.map +1 -1
- package/dist/serve/vite-plugin.js +281 -11
- package/dist/serve/vite-plugin.js.map +1 -1
- package/dist/serve/worker/activity-bootstrap.d.ts +8 -0
- package/dist/serve/worker/activity-bootstrap.d.ts.map +1 -0
- package/dist/serve/worker/activity-bootstrap.js +11 -0
- package/dist/serve/worker/activity-bootstrap.js.map +1 -0
- package/dist/serve/worker/client/connection.d.ts.map +1 -1
- package/dist/serve/worker/client/connection.js +17 -5
- package/dist/serve/worker/client/connection.js.map +1 -1
- package/dist/serve/worker/client/core.d.ts +2 -2
- package/dist/serve/worker/client/core.d.ts.map +1 -1
- package/dist/serve/worker/client/core.js +33 -5
- package/dist/serve/worker/client/core.js.map +1 -1
- package/dist/serve/worker/client/firestore-writes.d.ts.map +1 -1
- package/dist/serve/worker/client/firestore-writes.js +1 -0
- package/dist/serve/worker/client/firestore-writes.js.map +1 -1
- package/dist/serve/worker/client/messaging.d.ts +9 -1
- package/dist/serve/worker/client/messaging.d.ts.map +1 -1
- package/dist/serve/worker/client/messaging.js +15 -0
- package/dist/serve/worker/client/messaging.js.map +1 -1
- package/dist/serve/worker/client/studio.d.ts +10 -0
- package/dist/serve/worker/client/studio.d.ts.map +1 -1
- package/dist/serve/worker/client/studio.js +11 -0
- package/dist/serve/worker/client/studio.js.map +1 -1
- package/dist/serve/worker/durable-persistence.d.ts +12 -0
- package/dist/serve/worker/durable-persistence.d.ts.map +1 -0
- package/dist/serve/worker/durable-persistence.js +118 -0
- package/dist/serve/worker/durable-persistence.js.map +1 -0
- package/dist/serve/worker/entry.d.ts +7 -3
- package/dist/serve/worker/entry.d.ts.map +1 -1
- package/dist/serve/worker/entry.js +7 -3
- package/dist/serve/worker/entry.js.map +1 -1
- package/dist/serve/worker/host/core.d.ts +9 -5
- package/dist/serve/worker/host/core.d.ts.map +1 -1
- package/dist/serve/worker/host/core.js +33 -8
- package/dist/serve/worker/host/core.js.map +1 -1
- package/dist/serve/worker/host/dispatch.d.ts.map +1 -1
- package/dist/serve/worker/host/dispatch.js +9 -2
- package/dist/serve/worker/host/dispatch.js.map +1 -1
- package/dist/serve/worker/host/studio.d.ts +1 -1
- package/dist/serve/worker/host/studio.d.ts.map +1 -1
- package/dist/serve/worker/host/studio.js +36 -1
- package/dist/serve/worker/host/studio.js.map +1 -1
- package/dist/serve/worker/host/subscriptions.d.ts.map +1 -1
- package/dist/serve/worker/host/subscriptions.js +27 -7
- package/dist/serve/worker/host/subscriptions.js.map +1 -1
- package/dist/serve/worker/host-context.d.ts +15 -0
- package/dist/serve/worker/host-context.d.ts.map +1 -1
- package/dist/serve/worker/host-context.js +10 -0
- package/dist/serve/worker/host-context.js.map +1 -1
- package/dist/serve/worker/host-messaging.d.ts.map +1 -1
- package/dist/serve/worker/host-messaging.js +9 -2
- package/dist/serve/worker/host-messaging.js.map +1 -1
- package/dist/serve/worker/index.d.ts +1 -1
- package/dist/serve/worker/index.d.ts.map +1 -1
- package/dist/serve/worker/index.js +2 -0
- package/dist/serve/worker/index.js.map +1 -1
- package/dist/serve/worker/protocol.d.ts +25 -3
- package/dist/serve/worker/protocol.d.ts.map +1 -1
- package/dist/serve/worker/protocol.js.map +1 -1
- package/dist/serve/worker/serve-init.d.ts +23 -37
- package/dist/serve/worker/serve-init.d.ts.map +1 -1
- package/dist/serve/worker/serve-init.js +95 -172
- package/dist/serve/worker/serve-init.js.map +1 -1
- package/dist/vite.d.ts +4 -4
- package/dist/vite.d.ts.map +1 -1
- package/dist/vite.js +3 -3
- package/dist/vite.js.map +1 -1
- package/package.json +8 -4
- package/dist/serve/studio-ui/assets/index-BvtQIpGn.js +0 -1211
- package/dist/serve/studio-ui/assets/seed-3DMedLL3.js +0 -2
|
@@ -1,1211 +0,0 @@
|
|
|
1
|
-
var kN=Object.defineProperty;var CN=(t,e,n)=>e in t?kN(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var G=(t,e,n)=>CN(t,typeof e!="symbol"?e+"":e,n);(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const o of s)if(o.type==="childList")for(const c of o.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&r(c)}).observe(document,{childList:!0,subtree:!0});function n(s){const o={};return s.integrity&&(o.integrity=s.integrity),s.referrerPolicy&&(o.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?o.credentials="include":s.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function r(s){if(s.ep)return;s.ep=!0;const o=n(s);fetch(s.href,o)}})();var H_=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function NN(t){if(Object.prototype.hasOwnProperty.call(t,"__esModule"))return t;var e=t.default;if(typeof e=="function"){var n=function r(){return this instanceof r?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};n.prototype=e.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(t).forEach(function(r){var s=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(n,r,s.get?s:{enumerable:!0,get:function(){return t[r]}})}),n}var gp={exports:{}},rl={};/**
|
|
2
|
-
* @license React
|
|
3
|
-
* react-jsx-runtime.production.js
|
|
4
|
-
*
|
|
5
|
-
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
6
|
-
*
|
|
7
|
-
* This source code is licensed under the MIT license found in the
|
|
8
|
-
* LICENSE file in the root directory of this source tree.
|
|
9
|
-
*/var Nx;function ON(){if(Nx)return rl;Nx=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function n(r,s,o){var c=null;if(o!==void 0&&(c=""+o),s.key!==void 0&&(c=""+s.key),"key"in s){o={};for(var d in s)d!=="key"&&(o[d]=s[d])}else o=s;return s=o.ref,{$$typeof:t,type:r,key:c,ref:s!==void 0?s:null,props:o}}return rl.Fragment=e,rl.jsx=n,rl.jsxs=n,rl}var Ox;function TN(){return Ox||(Ox=1,gp.exports=ON()),gp.exports}var h=TN(),bp={exports:{}},ve={};/**
|
|
10
|
-
* @license React
|
|
11
|
-
* react.production.js
|
|
12
|
-
*
|
|
13
|
-
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
14
|
-
*
|
|
15
|
-
* This source code is licensed under the MIT license found in the
|
|
16
|
-
* LICENSE file in the root directory of this source tree.
|
|
17
|
-
*/var Tx;function RN(){if(Tx)return ve;Tx=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),s=Symbol.for("react.profiler"),o=Symbol.for("react.consumer"),c=Symbol.for("react.context"),d=Symbol.for("react.forward_ref"),f=Symbol.for("react.suspense"),p=Symbol.for("react.memo"),g=Symbol.for("react.lazy"),b=Symbol.for("react.activity"),v=Symbol.iterator;function x(B){return B===null||typeof B!="object"?null:(B=v&&B[v]||B["@@iterator"],typeof B=="function"?B:null)}var _={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},k=Object.assign,R={};function C(B,ee,ae){this.props=B,this.context=ee,this.refs=R,this.updater=ae||_}C.prototype.isReactComponent={},C.prototype.setState=function(B,ee){if(typeof B!="object"&&typeof B!="function"&&B!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,B,ee,"setState")},C.prototype.forceUpdate=function(B){this.updater.enqueueForceUpdate(this,B,"forceUpdate")};function T(){}T.prototype=C.prototype;function U(B,ee,ae){this.props=B,this.context=ee,this.refs=R,this.updater=ae||_}var q=U.prototype=new T;q.constructor=U,k(q,C.prototype),q.isPureReactComponent=!0;var I=Array.isArray;function N(){}var M={H:null,A:null,T:null,S:null},L=Object.prototype.hasOwnProperty;function H(B,ee,ae){var le=ae.ref;return{$$typeof:t,type:B,key:ee,ref:le!==void 0?le:null,props:ae}}function P(B,ee){return H(B.type,ee,B.props)}function F(B){return typeof B=="object"&&B!==null&&B.$$typeof===t}function w(B){var ee={"=":"=0",":":"=2"};return"$"+B.replace(/[=:]/g,function(ae){return ee[ae]})}var E=/\/+/g;function O(B,ee){return typeof B=="object"&&B!==null&&B.key!=null?w(""+B.key):ee.toString(36)}function D(B){switch(B.status){case"fulfilled":return B.value;case"rejected":throw B.reason;default:switch(typeof B.status=="string"?B.then(N,N):(B.status="pending",B.then(function(ee){B.status==="pending"&&(B.status="fulfilled",B.value=ee)},function(ee){B.status==="pending"&&(B.status="rejected",B.reason=ee)})),B.status){case"fulfilled":return B.value;case"rejected":throw B.reason}}throw B}function z(B,ee,ae,le,ye){var je=typeof B;(je==="undefined"||je==="boolean")&&(B=null);var qe=!1;if(B===null)qe=!0;else switch(je){case"bigint":case"string":case"number":qe=!0;break;case"object":switch(B.$$typeof){case t:case e:qe=!0;break;case g:return qe=B._init,z(qe(B._payload),ee,ae,le,ye)}}if(qe)return ye=ye(B),qe=le===""?"."+O(B,0):le,I(ye)?(ae="",qe!=null&&(ae=qe.replace(E,"$&/")+"/"),z(ye,ee,ae,"",function(co){return co})):ye!=null&&(F(ye)&&(ye=P(ye,ae+(ye.key==null||B&&B.key===ye.key?"":(""+ye.key).replace(E,"$&/")+"/")+qe)),ee.push(ye)),1;qe=0;var Qt=le===""?".":le+":";if(I(B))for(var mt=0;mt<B.length;mt++)le=B[mt],je=Qt+O(le,mt),qe+=z(le,ee,ae,je,ye);else if(mt=x(B),typeof mt=="function")for(B=mt.call(B),mt=0;!(le=B.next()).done;)le=le.value,je=Qt+O(le,mt++),qe+=z(le,ee,ae,je,ye);else if(je==="object"){if(typeof B.then=="function")return z(D(B),ee,ae,le,ye);throw ee=String(B),Error("Objects are not valid as a React child (found: "+(ee==="[object Object]"?"object with keys {"+Object.keys(B).join(", ")+"}":ee)+"). If you meant to render a collection of children, use an array instead.")}return qe}function $(B,ee,ae){if(B==null)return B;var le=[],ye=0;return z(B,le,"","",function(je){return ee.call(ae,je,ye++)}),le}function K(B){if(B._status===-1){var ee=B._result;ee=ee(),ee.then(function(ae){(B._status===0||B._status===-1)&&(B._status=1,B._result=ae)},function(ae){(B._status===0||B._status===-1)&&(B._status=2,B._result=ae)}),B._status===-1&&(B._status=0,B._result=ee)}if(B._status===1)return B._result.default;throw B._result}var W=typeof reportError=="function"?reportError:function(B){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var ee=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof B=="object"&&B!==null&&typeof B.message=="string"?String(B.message):String(B),error:B});if(!window.dispatchEvent(ee))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",B);return}console.error(B)},se={map:$,forEach:function(B,ee,ae){$(B,function(){ee.apply(this,arguments)},ae)},count:function(B){var ee=0;return $(B,function(){ee++}),ee},toArray:function(B){return $(B,function(ee){return ee})||[]},only:function(B){if(!F(B))throw Error("React.Children.only expected to receive a single React element child.");return B}};return ve.Activity=b,ve.Children=se,ve.Component=C,ve.Fragment=n,ve.Profiler=s,ve.PureComponent=U,ve.StrictMode=r,ve.Suspense=f,ve.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=M,ve.__COMPILER_RUNTIME={__proto__:null,c:function(B){return M.H.useMemoCache(B)}},ve.cache=function(B){return function(){return B.apply(null,arguments)}},ve.cacheSignal=function(){return null},ve.cloneElement=function(B,ee,ae){if(B==null)throw Error("The argument must be a React element, but you passed "+B+".");var le=k({},B.props),ye=B.key;if(ee!=null)for(je in ee.key!==void 0&&(ye=""+ee.key),ee)!L.call(ee,je)||je==="key"||je==="__self"||je==="__source"||je==="ref"&&ee.ref===void 0||(le[je]=ee[je]);var je=arguments.length-2;if(je===1)le.children=ae;else if(1<je){for(var qe=Array(je),Qt=0;Qt<je;Qt++)qe[Qt]=arguments[Qt+2];le.children=qe}return H(B.type,ye,le)},ve.createContext=function(B){return B={$$typeof:c,_currentValue:B,_currentValue2:B,_threadCount:0,Provider:null,Consumer:null},B.Provider=B,B.Consumer={$$typeof:o,_context:B},B},ve.createElement=function(B,ee,ae){var le,ye={},je=null;if(ee!=null)for(le in ee.key!==void 0&&(je=""+ee.key),ee)L.call(ee,le)&&le!=="key"&&le!=="__self"&&le!=="__source"&&(ye[le]=ee[le]);var qe=arguments.length-2;if(qe===1)ye.children=ae;else if(1<qe){for(var Qt=Array(qe),mt=0;mt<qe;mt++)Qt[mt]=arguments[mt+2];ye.children=Qt}if(B&&B.defaultProps)for(le in qe=B.defaultProps,qe)ye[le]===void 0&&(ye[le]=qe[le]);return H(B,je,ye)},ve.createRef=function(){return{current:null}},ve.forwardRef=function(B){return{$$typeof:d,render:B}},ve.isValidElement=F,ve.lazy=function(B){return{$$typeof:g,_payload:{_status:-1,_result:B},_init:K}},ve.memo=function(B,ee){return{$$typeof:p,type:B,compare:ee===void 0?null:ee}},ve.startTransition=function(B){var ee=M.T,ae={};M.T=ae;try{var le=B(),ye=M.S;ye!==null&&ye(ae,le),typeof le=="object"&&le!==null&&typeof le.then=="function"&&le.then(N,W)}catch(je){W(je)}finally{ee!==null&&ae.types!==null&&(ee.types=ae.types),M.T=ee}},ve.unstable_useCacheRefresh=function(){return M.H.useCacheRefresh()},ve.use=function(B){return M.H.use(B)},ve.useActionState=function(B,ee,ae){return M.H.useActionState(B,ee,ae)},ve.useCallback=function(B,ee){return M.H.useCallback(B,ee)},ve.useContext=function(B){return M.H.useContext(B)},ve.useDebugValue=function(){},ve.useDeferredValue=function(B,ee){return M.H.useDeferredValue(B,ee)},ve.useEffect=function(B,ee){return M.H.useEffect(B,ee)},ve.useEffectEvent=function(B){return M.H.useEffectEvent(B)},ve.useId=function(){return M.H.useId()},ve.useImperativeHandle=function(B,ee,ae){return M.H.useImperativeHandle(B,ee,ae)},ve.useInsertionEffect=function(B,ee){return M.H.useInsertionEffect(B,ee)},ve.useLayoutEffect=function(B,ee){return M.H.useLayoutEffect(B,ee)},ve.useMemo=function(B,ee){return M.H.useMemo(B,ee)},ve.useOptimistic=function(B,ee){return M.H.useOptimistic(B,ee)},ve.useReducer=function(B,ee,ae){return M.H.useReducer(B,ee,ae)},ve.useRef=function(B){return M.H.useRef(B)},ve.useState=function(B){return M.H.useState(B)},ve.useSyncExternalStore=function(B,ee,ae){return M.H.useSyncExternalStore(B,ee,ae)},ve.useTransition=function(){return M.H.useTransition()},ve.version="19.2.7",ve}var Rx;function Cy(){return Rx||(Rx=1,bp.exports=RN()),bp.exports}var A=Cy(),vp={exports:{}},sl={},xp={exports:{}},wp={};/**
|
|
18
|
-
* @license React
|
|
19
|
-
* scheduler.production.js
|
|
20
|
-
*
|
|
21
|
-
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
22
|
-
*
|
|
23
|
-
* This source code is licensed under the MIT license found in the
|
|
24
|
-
* LICENSE file in the root directory of this source tree.
|
|
25
|
-
*/var Dx;function DN(){return Dx||(Dx=1,(function(t){function e(z,$){var K=z.length;z.push($);e:for(;0<K;){var W=K-1>>>1,se=z[W];if(0<s(se,$))z[W]=$,z[K]=se,K=W;else break e}}function n(z){return z.length===0?null:z[0]}function r(z){if(z.length===0)return null;var $=z[0],K=z.pop();if(K!==$){z[0]=K;e:for(var W=0,se=z.length,B=se>>>1;W<B;){var ee=2*(W+1)-1,ae=z[ee],le=ee+1,ye=z[le];if(0>s(ae,K))le<se&&0>s(ye,ae)?(z[W]=ye,z[le]=K,W=le):(z[W]=ae,z[ee]=K,W=ee);else if(le<se&&0>s(ye,K))z[W]=ye,z[le]=K,W=le;else break e}}return $}function s(z,$){var K=z.sortIndex-$.sortIndex;return K!==0?K:z.id-$.id}if(t.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var o=performance;t.unstable_now=function(){return o.now()}}else{var c=Date,d=c.now();t.unstable_now=function(){return c.now()-d}}var f=[],p=[],g=1,b=null,v=3,x=!1,_=!1,k=!1,R=!1,C=typeof setTimeout=="function"?setTimeout:null,T=typeof clearTimeout=="function"?clearTimeout:null,U=typeof setImmediate<"u"?setImmediate:null;function q(z){for(var $=n(p);$!==null;){if($.callback===null)r(p);else if($.startTime<=z)r(p),$.sortIndex=$.expirationTime,e(f,$);else break;$=n(p)}}function I(z){if(k=!1,q(z),!_)if(n(f)!==null)_=!0,N||(N=!0,w());else{var $=n(p);$!==null&&D(I,$.startTime-z)}}var N=!1,M=-1,L=5,H=-1;function P(){return R?!0:!(t.unstable_now()-H<L)}function F(){if(R=!1,N){var z=t.unstable_now();H=z;var $=!0;try{e:{_=!1,k&&(k=!1,T(M),M=-1),x=!0;var K=v;try{t:{for(q(z),b=n(f);b!==null&&!(b.expirationTime>z&&P());){var W=b.callback;if(typeof W=="function"){b.callback=null,v=b.priorityLevel;var se=W(b.expirationTime<=z);if(z=t.unstable_now(),typeof se=="function"){b.callback=se,q(z),$=!0;break t}b===n(f)&&r(f),q(z)}else r(f);b=n(f)}if(b!==null)$=!0;else{var B=n(p);B!==null&&D(I,B.startTime-z),$=!1}}break e}finally{b=null,v=K,x=!1}$=void 0}}finally{$?w():N=!1}}}var w;if(typeof U=="function")w=function(){U(F)};else if(typeof MessageChannel<"u"){var E=new MessageChannel,O=E.port2;E.port1.onmessage=F,w=function(){O.postMessage(null)}}else w=function(){C(F,0)};function D(z,$){M=C(function(){z(t.unstable_now())},$)}t.unstable_IdlePriority=5,t.unstable_ImmediatePriority=1,t.unstable_LowPriority=4,t.unstable_NormalPriority=3,t.unstable_Profiling=null,t.unstable_UserBlockingPriority=2,t.unstable_cancelCallback=function(z){z.callback=null},t.unstable_forceFrameRate=function(z){0>z||125<z?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):L=0<z?Math.floor(1e3/z):5},t.unstable_getCurrentPriorityLevel=function(){return v},t.unstable_next=function(z){switch(v){case 1:case 2:case 3:var $=3;break;default:$=v}var K=v;v=$;try{return z()}finally{v=K}},t.unstable_requestPaint=function(){R=!0},t.unstable_runWithPriority=function(z,$){switch(z){case 1:case 2:case 3:case 4:case 5:break;default:z=3}var K=v;v=z;try{return $()}finally{v=K}},t.unstable_scheduleCallback=function(z,$,K){var W=t.unstable_now();switch(typeof K=="object"&&K!==null?(K=K.delay,K=typeof K=="number"&&0<K?W+K:W):K=W,z){case 1:var se=-1;break;case 2:se=250;break;case 5:se=1073741823;break;case 4:se=1e4;break;default:se=5e3}return se=K+se,z={id:g++,callback:$,priorityLevel:z,startTime:K,expirationTime:se,sortIndex:-1},K>W?(z.sortIndex=K,e(p,z),n(f)===null&&z===n(p)&&(k?(T(M),M=-1):k=!0,D(I,K-W))):(z.sortIndex=se,e(f,z),_||x||(_=!0,N||(N=!0,w()))),z},t.unstable_shouldYield=P,t.unstable_wrapCallback=function(z){var $=v;return function(){var K=v;v=$;try{return z.apply(this,arguments)}finally{v=K}}}})(wp)),wp}var Ix;function IN(){return Ix||(Ix=1,xp.exports=DN()),xp.exports}var Sp={exports:{}},Ht={};/**
|
|
26
|
-
* @license React
|
|
27
|
-
* react-dom.production.js
|
|
28
|
-
*
|
|
29
|
-
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
30
|
-
*
|
|
31
|
-
* This source code is licensed under the MIT license found in the
|
|
32
|
-
* LICENSE file in the root directory of this source tree.
|
|
33
|
-
*/var Mx;function MN(){if(Mx)return Ht;Mx=1;var t=Cy();function e(f){var p="https://react.dev/errors/"+f;if(1<arguments.length){p+="?args[]="+encodeURIComponent(arguments[1]);for(var g=2;g<arguments.length;g++)p+="&args[]="+encodeURIComponent(arguments[g])}return"Minified React error #"+f+"; visit "+p+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function n(){}var r={d:{f:n,r:function(){throw Error(e(522))},D:n,C:n,L:n,m:n,X:n,S:n,M:n},p:0,findDOMNode:null},s=Symbol.for("react.portal");function o(f,p,g){var b=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:s,key:b==null?null:""+b,children:f,containerInfo:p,implementation:g}}var c=t.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function d(f,p){if(f==="font")return"";if(typeof p=="string")return p==="use-credentials"?p:""}return Ht.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=r,Ht.createPortal=function(f,p){var g=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!p||p.nodeType!==1&&p.nodeType!==9&&p.nodeType!==11)throw Error(e(299));return o(f,p,null,g)},Ht.flushSync=function(f){var p=c.T,g=r.p;try{if(c.T=null,r.p=2,f)return f()}finally{c.T=p,r.p=g,r.d.f()}},Ht.preconnect=function(f,p){typeof f=="string"&&(p?(p=p.crossOrigin,p=typeof p=="string"?p==="use-credentials"?p:"":void 0):p=null,r.d.C(f,p))},Ht.prefetchDNS=function(f){typeof f=="string"&&r.d.D(f)},Ht.preinit=function(f,p){if(typeof f=="string"&&p&&typeof p.as=="string"){var g=p.as,b=d(g,p.crossOrigin),v=typeof p.integrity=="string"?p.integrity:void 0,x=typeof p.fetchPriority=="string"?p.fetchPriority:void 0;g==="style"?r.d.S(f,typeof p.precedence=="string"?p.precedence:void 0,{crossOrigin:b,integrity:v,fetchPriority:x}):g==="script"&&r.d.X(f,{crossOrigin:b,integrity:v,fetchPriority:x,nonce:typeof p.nonce=="string"?p.nonce:void 0})}},Ht.preinitModule=function(f,p){if(typeof f=="string")if(typeof p=="object"&&p!==null){if(p.as==null||p.as==="script"){var g=d(p.as,p.crossOrigin);r.d.M(f,{crossOrigin:g,integrity:typeof p.integrity=="string"?p.integrity:void 0,nonce:typeof p.nonce=="string"?p.nonce:void 0})}}else p==null&&r.d.M(f)},Ht.preload=function(f,p){if(typeof f=="string"&&typeof p=="object"&&p!==null&&typeof p.as=="string"){var g=p.as,b=d(g,p.crossOrigin);r.d.L(f,g,{crossOrigin:b,integrity:typeof p.integrity=="string"?p.integrity:void 0,nonce:typeof p.nonce=="string"?p.nonce:void 0,type:typeof p.type=="string"?p.type:void 0,fetchPriority:typeof p.fetchPriority=="string"?p.fetchPriority:void 0,referrerPolicy:typeof p.referrerPolicy=="string"?p.referrerPolicy:void 0,imageSrcSet:typeof p.imageSrcSet=="string"?p.imageSrcSet:void 0,imageSizes:typeof p.imageSizes=="string"?p.imageSizes:void 0,media:typeof p.media=="string"?p.media:void 0})}},Ht.preloadModule=function(f,p){if(typeof f=="string")if(p){var g=d(p.as,p.crossOrigin);r.d.m(f,{as:typeof p.as=="string"&&p.as!=="script"?p.as:void 0,crossOrigin:g,integrity:typeof p.integrity=="string"?p.integrity:void 0})}else r.d.m(f)},Ht.requestFormReset=function(f){r.d.r(f)},Ht.unstable_batchedUpdates=function(f,p){return f(p)},Ht.useFormState=function(f,p,g){return c.H.useFormState(f,p,g)},Ht.useFormStatus=function(){return c.H.useHostTransitionStatus()},Ht.version="19.2.7",Ht}var Lx;function G_(){if(Lx)return Sp.exports;Lx=1;function t(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(t)}catch(e){console.error(e)}}return t(),Sp.exports=MN(),Sp.exports}/**
|
|
34
|
-
* @license React
|
|
35
|
-
* react-dom-client.production.js
|
|
36
|
-
*
|
|
37
|
-
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
38
|
-
*
|
|
39
|
-
* This source code is licensed under the MIT license found in the
|
|
40
|
-
* LICENSE file in the root directory of this source tree.
|
|
41
|
-
*/var Ux;function LN(){if(Ux)return sl;Ux=1;var t=IN(),e=Cy(),n=G_();function r(i){var a="https://react.dev/errors/"+i;if(1<arguments.length){a+="?args[]="+encodeURIComponent(arguments[1]);for(var l=2;l<arguments.length;l++)a+="&args[]="+encodeURIComponent(arguments[l])}return"Minified React error #"+i+"; visit "+a+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function s(i){return!(!i||i.nodeType!==1&&i.nodeType!==9&&i.nodeType!==11)}function o(i){var a=i,l=i;if(i.alternate)for(;a.return;)a=a.return;else{i=a;do a=i,(a.flags&4098)!==0&&(l=a.return),i=a.return;while(i)}return a.tag===3?l:null}function c(i){if(i.tag===13){var a=i.memoizedState;if(a===null&&(i=i.alternate,i!==null&&(a=i.memoizedState)),a!==null)return a.dehydrated}return null}function d(i){if(i.tag===31){var a=i.memoizedState;if(a===null&&(i=i.alternate,i!==null&&(a=i.memoizedState)),a!==null)return a.dehydrated}return null}function f(i){if(o(i)!==i)throw Error(r(188))}function p(i){var a=i.alternate;if(!a){if(a=o(i),a===null)throw Error(r(188));return a!==i?null:i}for(var l=i,u=a;;){var m=l.return;if(m===null)break;var y=m.alternate;if(y===null){if(u=m.return,u!==null){l=u;continue}break}if(m.child===y.child){for(y=m.child;y;){if(y===l)return f(m),i;if(y===u)return f(m),a;y=y.sibling}throw Error(r(188))}if(l.return!==u.return)l=m,u=y;else{for(var S=!1,j=m.child;j;){if(j===l){S=!0,l=m,u=y;break}if(j===u){S=!0,u=m,l=y;break}j=j.sibling}if(!S){for(j=y.child;j;){if(j===l){S=!0,l=y,u=m;break}if(j===u){S=!0,u=y,l=m;break}j=j.sibling}if(!S)throw Error(r(189))}}if(l.alternate!==u)throw Error(r(190))}if(l.tag!==3)throw Error(r(188));return l.stateNode.current===l?i:a}function g(i){var a=i.tag;if(a===5||a===26||a===27||a===6)return i;for(i=i.child;i!==null;){if(a=g(i),a!==null)return a;i=i.sibling}return null}var b=Object.assign,v=Symbol.for("react.element"),x=Symbol.for("react.transitional.element"),_=Symbol.for("react.portal"),k=Symbol.for("react.fragment"),R=Symbol.for("react.strict_mode"),C=Symbol.for("react.profiler"),T=Symbol.for("react.consumer"),U=Symbol.for("react.context"),q=Symbol.for("react.forward_ref"),I=Symbol.for("react.suspense"),N=Symbol.for("react.suspense_list"),M=Symbol.for("react.memo"),L=Symbol.for("react.lazy"),H=Symbol.for("react.activity"),P=Symbol.for("react.memo_cache_sentinel"),F=Symbol.iterator;function w(i){return i===null||typeof i!="object"?null:(i=F&&i[F]||i["@@iterator"],typeof i=="function"?i:null)}var E=Symbol.for("react.client.reference");function O(i){if(i==null)return null;if(typeof i=="function")return i.$$typeof===E?null:i.displayName||i.name||null;if(typeof i=="string")return i;switch(i){case k:return"Fragment";case C:return"Profiler";case R:return"StrictMode";case I:return"Suspense";case N:return"SuspenseList";case H:return"Activity"}if(typeof i=="object")switch(i.$$typeof){case _:return"Portal";case U:return i.displayName||"Context";case T:return(i._context.displayName||"Context")+".Consumer";case q:var a=i.render;return i=i.displayName,i||(i=a.displayName||a.name||"",i=i!==""?"ForwardRef("+i+")":"ForwardRef"),i;case M:return a=i.displayName||null,a!==null?a:O(i.type)||"Memo";case L:a=i._payload,i=i._init;try{return O(i(a))}catch{}}return null}var D=Array.isArray,z=e.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,$=n.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,K={pending:!1,data:null,method:null,action:null},W=[],se=-1;function B(i){return{current:i}}function ee(i){0>se||(i.current=W[se],W[se]=null,se--)}function ae(i,a){se++,W[se]=i.current,i.current=a}var le=B(null),ye=B(null),je=B(null),qe=B(null);function Qt(i,a){switch(ae(je,a),ae(ye,i),ae(le,null),a.nodeType){case 9:case 11:i=(i=a.documentElement)&&(i=i.namespaceURI)?Q0(i):0;break;default:if(i=a.tagName,a=a.namespaceURI)a=Q0(a),i=X0(a,i);else switch(i){case"svg":i=1;break;case"math":i=2;break;default:i=0}}ee(le),ae(le,i)}function mt(){ee(le),ee(ye),ee(je)}function co(i){i.memoizedState!==null&&ae(qe,i);var a=le.current,l=X0(a,i.type);a!==l&&(ae(ye,i),ae(le,l))}function Zl(i){ye.current===i&&(ee(le),ee(ye)),qe.current===i&&(ee(qe),Xo._currentValue=K)}var Qd,Cg;function ti(i){if(Qd===void 0)try{throw Error()}catch(l){var a=l.stack.trim().match(/\n( *(at )?)/);Qd=a&&a[1]||"",Cg=-1<l.stack.indexOf(`
|
|
42
|
-
at`)?" (<anonymous>)":-1<l.stack.indexOf("@")?"@unknown:0:0":""}return`
|
|
43
|
-
`+Qd+i+Cg}var Xd=!1;function ef(i,a){if(!i||Xd)return"";Xd=!0;var l=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var u={DetermineComponentFrameRoot:function(){try{if(a){var ie=function(){throw Error()};if(Object.defineProperty(ie.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(ie,[])}catch(te){var X=te}Reflect.construct(i,[],ie)}else{try{ie.call()}catch(te){X=te}i.call(ie.prototype)}}else{try{throw Error()}catch(te){X=te}(ie=i())&&typeof ie.catch=="function"&&ie.catch(function(){})}}catch(te){if(te&&X&&typeof te.stack=="string")return[te.stack,X.stack]}return[null,null]}};u.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var m=Object.getOwnPropertyDescriptor(u.DetermineComponentFrameRoot,"name");m&&m.configurable&&Object.defineProperty(u.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var y=u.DetermineComponentFrameRoot(),S=y[0],j=y[1];if(S&&j){var V=S.split(`
|
|
44
|
-
`),Q=j.split(`
|
|
45
|
-
`);for(m=u=0;u<V.length&&!V[u].includes("DetermineComponentFrameRoot");)u++;for(;m<Q.length&&!Q[m].includes("DetermineComponentFrameRoot");)m++;if(u===V.length||m===Q.length)for(u=V.length-1,m=Q.length-1;1<=u&&0<=m&&V[u]!==Q[m];)m--;for(;1<=u&&0<=m;u--,m--)if(V[u]!==Q[m]){if(u!==1||m!==1)do if(u--,m--,0>m||V[u]!==Q[m]){var ne=`
|
|
46
|
-
`+V[u].replace(" at new "," at ");return i.displayName&&ne.includes("<anonymous>")&&(ne=ne.replace("<anonymous>",i.displayName)),ne}while(1<=u&&0<=m);break}}}finally{Xd=!1,Error.prepareStackTrace=l}return(l=i?i.displayName||i.name:"")?ti(l):""}function sk(i,a){switch(i.tag){case 26:case 27:case 5:return ti(i.type);case 16:return ti("Lazy");case 13:return i.child!==a&&a!==null?ti("Suspense Fallback"):ti("Suspense");case 19:return ti("SuspenseList");case 0:case 15:return ef(i.type,!1);case 11:return ef(i.type.render,!1);case 1:return ef(i.type,!0);case 31:return ti("Activity");default:return""}}function Ng(i){try{var a="",l=null;do a+=sk(i,l),l=i,i=i.return;while(i);return a}catch(u){return`
|
|
47
|
-
Error generating stack: `+u.message+`
|
|
48
|
-
`+u.stack}}var tf=Object.prototype.hasOwnProperty,nf=t.unstable_scheduleCallback,rf=t.unstable_cancelCallback,ik=t.unstable_shouldYield,ak=t.unstable_requestPaint,wn=t.unstable_now,ok=t.unstable_getCurrentPriorityLevel,Og=t.unstable_ImmediatePriority,Tg=t.unstable_UserBlockingPriority,Wl=t.unstable_NormalPriority,lk=t.unstable_LowPriority,Rg=t.unstable_IdlePriority,ck=t.log,uk=t.unstable_setDisableYieldValue,uo=null,Sn=null;function ls(i){if(typeof ck=="function"&&uk(i),Sn&&typeof Sn.setStrictMode=="function")try{Sn.setStrictMode(uo,i)}catch{}}var _n=Math.clz32?Math.clz32:hk,dk=Math.log,fk=Math.LN2;function hk(i){return i>>>=0,i===0?32:31-(dk(i)/fk|0)|0}var Jl=256,Ql=262144,Xl=4194304;function ni(i){var a=i&42;if(a!==0)return a;switch(i&-i){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return i&261888;case 262144:case 524288:case 1048576:case 2097152:return i&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return i&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return i}}function ec(i,a,l){var u=i.pendingLanes;if(u===0)return 0;var m=0,y=i.suspendedLanes,S=i.pingedLanes;i=i.warmLanes;var j=u&134217727;return j!==0?(u=j&~y,u!==0?m=ni(u):(S&=j,S!==0?m=ni(S):l||(l=j&~i,l!==0&&(m=ni(l))))):(j=u&~y,j!==0?m=ni(j):S!==0?m=ni(S):l||(l=u&~i,l!==0&&(m=ni(l)))),m===0?0:a!==0&&a!==m&&(a&y)===0&&(y=m&-m,l=a&-a,y>=l||y===32&&(l&4194048)!==0)?a:m}function fo(i,a){return(i.pendingLanes&~(i.suspendedLanes&~i.pingedLanes)&a)===0}function pk(i,a){switch(i){case 1:case 2:case 4:case 8:case 64:return a+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function Dg(){var i=Xl;return Xl<<=1,(Xl&62914560)===0&&(Xl=4194304),i}function sf(i){for(var a=[],l=0;31>l;l++)a.push(i);return a}function ho(i,a){i.pendingLanes|=a,a!==268435456&&(i.suspendedLanes=0,i.pingedLanes=0,i.warmLanes=0)}function mk(i,a,l,u,m,y){var S=i.pendingLanes;i.pendingLanes=l,i.suspendedLanes=0,i.pingedLanes=0,i.warmLanes=0,i.expiredLanes&=l,i.entangledLanes&=l,i.errorRecoveryDisabledLanes&=l,i.shellSuspendCounter=0;var j=i.entanglements,V=i.expirationTimes,Q=i.hiddenUpdates;for(l=S&~l;0<l;){var ne=31-_n(l),ie=1<<ne;j[ne]=0,V[ne]=-1;var X=Q[ne];if(X!==null)for(Q[ne]=null,ne=0;ne<X.length;ne++){var te=X[ne];te!==null&&(te.lane&=-536870913)}l&=~ie}u!==0&&Ig(i,u,0),y!==0&&m===0&&i.tag!==0&&(i.suspendedLanes|=y&~(S&~a))}function Ig(i,a,l){i.pendingLanes|=a,i.suspendedLanes&=~a;var u=31-_n(a);i.entangledLanes|=a,i.entanglements[u]=i.entanglements[u]|1073741824|l&261930}function Mg(i,a){var l=i.entangledLanes|=a;for(i=i.entanglements;l;){var u=31-_n(l),m=1<<u;m&a|i[u]&a&&(i[u]|=a),l&=~m}}function Lg(i,a){var l=a&-a;return l=(l&42)!==0?1:af(l),(l&(i.suspendedLanes|a))!==0?0:l}function af(i){switch(i){case 2:i=1;break;case 8:i=4;break;case 32:i=16;break;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:i=128;break;case 268435456:i=134217728;break;default:i=0}return i}function of(i){return i&=-i,2<i?8<i?(i&134217727)!==0?32:268435456:8:2}function Ug(){var i=$.p;return i!==0?i:(i=window.event,i===void 0?32:Sx(i.type))}function $g(i,a){var l=$.p;try{return $.p=i,a()}finally{$.p=l}}var cs=Math.random().toString(36).slice(2),Mt="__reactFiber$"+cs,cn="__reactProps$"+cs,Yi="__reactContainer$"+cs,lf="__reactEvents$"+cs,yk="__reactListeners$"+cs,gk="__reactHandles$"+cs,Bg="__reactResources$"+cs,po="__reactMarker$"+cs;function cf(i){delete i[Mt],delete i[cn],delete i[lf],delete i[yk],delete i[gk]}function Zi(i){var a=i[Mt];if(a)return a;for(var l=i.parentNode;l;){if(a=l[Yi]||l[Mt]){if(l=a.alternate,a.child!==null||l!==null&&l.child!==null)for(i=ax(i);i!==null;){if(l=i[Mt])return l;i=ax(i)}return a}i=l,l=i.parentNode}return null}function Wi(i){if(i=i[Mt]||i[Yi]){var a=i.tag;if(a===5||a===6||a===13||a===31||a===26||a===27||a===3)return i}return null}function mo(i){var a=i.tag;if(a===5||a===26||a===27||a===6)return i.stateNode;throw Error(r(33))}function Ji(i){var a=i[Bg];return a||(a=i[Bg]={hoistableStyles:new Map,hoistableScripts:new Map}),a}function Tt(i){i[po]=!0}var Fg=new Set,Pg={};function ri(i,a){Qi(i,a),Qi(i+"Capture",a)}function Qi(i,a){for(Pg[i]=a,i=0;i<a.length;i++)Fg.add(a[i])}var bk=RegExp("^[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD][:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$"),qg={},zg={};function vk(i){return tf.call(zg,i)?!0:tf.call(qg,i)?!1:bk.test(i)?zg[i]=!0:(qg[i]=!0,!1)}function tc(i,a,l){if(vk(a))if(l===null)i.removeAttribute(a);else{switch(typeof l){case"undefined":case"function":case"symbol":i.removeAttribute(a);return;case"boolean":var u=a.toLowerCase().slice(0,5);if(u!=="data-"&&u!=="aria-"){i.removeAttribute(a);return}}i.setAttribute(a,""+l)}}function nc(i,a,l){if(l===null)i.removeAttribute(a);else{switch(typeof l){case"undefined":case"function":case"symbol":case"boolean":i.removeAttribute(a);return}i.setAttribute(a,""+l)}}function Tr(i,a,l,u){if(u===null)i.removeAttribute(l);else{switch(typeof u){case"undefined":case"function":case"symbol":case"boolean":i.removeAttribute(l);return}i.setAttributeNS(a,l,""+u)}}function Ln(i){switch(typeof i){case"bigint":case"boolean":case"number":case"string":case"undefined":return i;case"object":return i;default:return""}}function Vg(i){var a=i.type;return(i=i.nodeName)&&i.toLowerCase()==="input"&&(a==="checkbox"||a==="radio")}function xk(i,a,l){var u=Object.getOwnPropertyDescriptor(i.constructor.prototype,a);if(!i.hasOwnProperty(a)&&typeof u<"u"&&typeof u.get=="function"&&typeof u.set=="function"){var m=u.get,y=u.set;return Object.defineProperty(i,a,{configurable:!0,get:function(){return m.call(this)},set:function(S){l=""+S,y.call(this,S)}}),Object.defineProperty(i,a,{enumerable:u.enumerable}),{getValue:function(){return l},setValue:function(S){l=""+S},stopTracking:function(){i._valueTracker=null,delete i[a]}}}}function uf(i){if(!i._valueTracker){var a=Vg(i)?"checked":"value";i._valueTracker=xk(i,a,""+i[a])}}function Hg(i){if(!i)return!1;var a=i._valueTracker;if(!a)return!0;var l=a.getValue(),u="";return i&&(u=Vg(i)?i.checked?"true":"false":i.value),i=u,i!==l?(a.setValue(i),!0):!1}function rc(i){if(i=i||(typeof document<"u"?document:void 0),typeof i>"u")return null;try{return i.activeElement||i.body}catch{return i.body}}var wk=/[\n"\\]/g;function Un(i){return i.replace(wk,function(a){return"\\"+a.charCodeAt(0).toString(16)+" "})}function df(i,a,l,u,m,y,S,j){i.name="",S!=null&&typeof S!="function"&&typeof S!="symbol"&&typeof S!="boolean"?i.type=S:i.removeAttribute("type"),a!=null?S==="number"?(a===0&&i.value===""||i.value!=a)&&(i.value=""+Ln(a)):i.value!==""+Ln(a)&&(i.value=""+Ln(a)):S!=="submit"&&S!=="reset"||i.removeAttribute("value"),a!=null?ff(i,S,Ln(a)):l!=null?ff(i,S,Ln(l)):u!=null&&i.removeAttribute("value"),m==null&&y!=null&&(i.defaultChecked=!!y),m!=null&&(i.checked=m&&typeof m!="function"&&typeof m!="symbol"),j!=null&&typeof j!="function"&&typeof j!="symbol"&&typeof j!="boolean"?i.name=""+Ln(j):i.removeAttribute("name")}function Gg(i,a,l,u,m,y,S,j){if(y!=null&&typeof y!="function"&&typeof y!="symbol"&&typeof y!="boolean"&&(i.type=y),a!=null||l!=null){if(!(y!=="submit"&&y!=="reset"||a!=null)){uf(i);return}l=l!=null?""+Ln(l):"",a=a!=null?""+Ln(a):l,j||a===i.value||(i.value=a),i.defaultValue=a}u=u??m,u=typeof u!="function"&&typeof u!="symbol"&&!!u,i.checked=j?i.checked:!!u,i.defaultChecked=!!u,S!=null&&typeof S!="function"&&typeof S!="symbol"&&typeof S!="boolean"&&(i.name=S),uf(i)}function ff(i,a,l){a==="number"&&rc(i.ownerDocument)===i||i.defaultValue===""+l||(i.defaultValue=""+l)}function Xi(i,a,l,u){if(i=i.options,a){a={};for(var m=0;m<l.length;m++)a["$"+l[m]]=!0;for(l=0;l<i.length;l++)m=a.hasOwnProperty("$"+i[l].value),i[l].selected!==m&&(i[l].selected=m),m&&u&&(i[l].defaultSelected=!0)}else{for(l=""+Ln(l),a=null,m=0;m<i.length;m++){if(i[m].value===l){i[m].selected=!0,u&&(i[m].defaultSelected=!0);return}a!==null||i[m].disabled||(a=i[m])}a!==null&&(a.selected=!0)}}function Kg(i,a,l){if(a!=null&&(a=""+Ln(a),a!==i.value&&(i.value=a),l==null)){i.defaultValue!==a&&(i.defaultValue=a);return}i.defaultValue=l!=null?""+Ln(l):""}function Yg(i,a,l,u){if(a==null){if(u!=null){if(l!=null)throw Error(r(92));if(D(u)){if(1<u.length)throw Error(r(93));u=u[0]}l=u}l==null&&(l=""),a=l}l=Ln(a),i.defaultValue=l,u=i.textContent,u===l&&u!==""&&u!==null&&(i.value=u),uf(i)}function ea(i,a){if(a){var l=i.firstChild;if(l&&l===i.lastChild&&l.nodeType===3){l.nodeValue=a;return}}i.textContent=a}var Sk=new Set("animationIterationCount aspectRatio borderImageOutset borderImageSlice borderImageWidth boxFlex boxFlexGroup boxOrdinalGroup columnCount columns flex flexGrow flexPositive flexShrink flexNegative flexOrder gridArea gridRow gridRowEnd gridRowSpan gridRowStart gridColumn gridColumnEnd gridColumnSpan gridColumnStart fontWeight lineClamp lineHeight opacity order orphans scale tabSize widows zIndex zoom fillOpacity floodOpacity stopOpacity strokeDasharray strokeDashoffset strokeMiterlimit strokeOpacity strokeWidth MozAnimationIterationCount MozBoxFlex MozBoxFlexGroup MozLineClamp msAnimationIterationCount msFlex msZoom msFlexGrow msFlexNegative msFlexOrder msFlexPositive msFlexShrink msGridColumn msGridColumnSpan msGridRow msGridRowSpan WebkitAnimationIterationCount WebkitBoxFlex WebKitBoxFlexGroup WebkitBoxOrdinalGroup WebkitColumnCount WebkitColumns WebkitFlex WebkitFlexGrow WebkitFlexPositive WebkitFlexShrink WebkitLineClamp".split(" "));function Zg(i,a,l){var u=a.indexOf("--")===0;l==null||typeof l=="boolean"||l===""?u?i.setProperty(a,""):a==="float"?i.cssFloat="":i[a]="":u?i.setProperty(a,l):typeof l!="number"||l===0||Sk.has(a)?a==="float"?i.cssFloat=l:i[a]=(""+l).trim():i[a]=l+"px"}function Wg(i,a,l){if(a!=null&&typeof a!="object")throw Error(r(62));if(i=i.style,l!=null){for(var u in l)!l.hasOwnProperty(u)||a!=null&&a.hasOwnProperty(u)||(u.indexOf("--")===0?i.setProperty(u,""):u==="float"?i.cssFloat="":i[u]="");for(var m in a)u=a[m],a.hasOwnProperty(m)&&l[m]!==u&&Zg(i,m,u)}else for(var y in a)a.hasOwnProperty(y)&&Zg(i,y,a[y])}function hf(i){if(i.indexOf("-")===-1)return!1;switch(i){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var _k=new Map([["acceptCharset","accept-charset"],["htmlFor","for"],["httpEquiv","http-equiv"],["crossOrigin","crossorigin"],["accentHeight","accent-height"],["alignmentBaseline","alignment-baseline"],["arabicForm","arabic-form"],["baselineShift","baseline-shift"],["capHeight","cap-height"],["clipPath","clip-path"],["clipRule","clip-rule"],["colorInterpolation","color-interpolation"],["colorInterpolationFilters","color-interpolation-filters"],["colorProfile","color-profile"],["colorRendering","color-rendering"],["dominantBaseline","dominant-baseline"],["enableBackground","enable-background"],["fillOpacity","fill-opacity"],["fillRule","fill-rule"],["floodColor","flood-color"],["floodOpacity","flood-opacity"],["fontFamily","font-family"],["fontSize","font-size"],["fontSizeAdjust","font-size-adjust"],["fontStretch","font-stretch"],["fontStyle","font-style"],["fontVariant","font-variant"],["fontWeight","font-weight"],["glyphName","glyph-name"],["glyphOrientationHorizontal","glyph-orientation-horizontal"],["glyphOrientationVertical","glyph-orientation-vertical"],["horizAdvX","horiz-adv-x"],["horizOriginX","horiz-origin-x"],["imageRendering","image-rendering"],["letterSpacing","letter-spacing"],["lightingColor","lighting-color"],["markerEnd","marker-end"],["markerMid","marker-mid"],["markerStart","marker-start"],["overlinePosition","overline-position"],["overlineThickness","overline-thickness"],["paintOrder","paint-order"],["panose-1","panose-1"],["pointerEvents","pointer-events"],["renderingIntent","rendering-intent"],["shapeRendering","shape-rendering"],["stopColor","stop-color"],["stopOpacity","stop-opacity"],["strikethroughPosition","strikethrough-position"],["strikethroughThickness","strikethrough-thickness"],["strokeDasharray","stroke-dasharray"],["strokeDashoffset","stroke-dashoffset"],["strokeLinecap","stroke-linecap"],["strokeLinejoin","stroke-linejoin"],["strokeMiterlimit","stroke-miterlimit"],["strokeOpacity","stroke-opacity"],["strokeWidth","stroke-width"],["textAnchor","text-anchor"],["textDecoration","text-decoration"],["textRendering","text-rendering"],["transformOrigin","transform-origin"],["underlinePosition","underline-position"],["underlineThickness","underline-thickness"],["unicodeBidi","unicode-bidi"],["unicodeRange","unicode-range"],["unitsPerEm","units-per-em"],["vAlphabetic","v-alphabetic"],["vHanging","v-hanging"],["vIdeographic","v-ideographic"],["vMathematical","v-mathematical"],["vectorEffect","vector-effect"],["vertAdvY","vert-adv-y"],["vertOriginX","vert-origin-x"],["vertOriginY","vert-origin-y"],["wordSpacing","word-spacing"],["writingMode","writing-mode"],["xmlnsXlink","xmlns:xlink"],["xHeight","x-height"]]),Ek=/^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*:/i;function sc(i){return Ek.test(""+i)?"javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')":i}function Rr(){}var pf=null;function mf(i){return i=i.target||i.srcElement||window,i.correspondingUseElement&&(i=i.correspondingUseElement),i.nodeType===3?i.parentNode:i}var ta=null,na=null;function Jg(i){var a=Wi(i);if(a&&(i=a.stateNode)){var l=i[cn]||null;e:switch(i=a.stateNode,a.type){case"input":if(df(i,l.value,l.defaultValue,l.defaultValue,l.checked,l.defaultChecked,l.type,l.name),a=l.name,l.type==="radio"&&a!=null){for(l=i;l.parentNode;)l=l.parentNode;for(l=l.querySelectorAll('input[name="'+Un(""+a)+'"][type="radio"]'),a=0;a<l.length;a++){var u=l[a];if(u!==i&&u.form===i.form){var m=u[cn]||null;if(!m)throw Error(r(90));df(u,m.value,m.defaultValue,m.defaultValue,m.checked,m.defaultChecked,m.type,m.name)}}for(a=0;a<l.length;a++)u=l[a],u.form===i.form&&Hg(u)}break e;case"textarea":Kg(i,l.value,l.defaultValue);break e;case"select":a=l.value,a!=null&&Xi(i,!!l.multiple,a,!1)}}}var yf=!1;function Qg(i,a,l){if(yf)return i(a,l);yf=!0;try{var u=i(a);return u}finally{if(yf=!1,(ta!==null||na!==null)&&(Hc(),ta&&(a=ta,i=na,na=ta=null,Jg(a),i)))for(a=0;a<i.length;a++)Jg(i[a])}}function yo(i,a){var l=i.stateNode;if(l===null)return null;var u=l[cn]||null;if(u===null)return null;l=u[a];e:switch(a){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(u=!u.disabled)||(i=i.type,u=!(i==="button"||i==="input"||i==="select"||i==="textarea")),i=!u;break e;default:i=!1}if(i)return null;if(l&&typeof l!="function")throw Error(r(231,a,typeof l));return l}var Dr=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),gf=!1;if(Dr)try{var go={};Object.defineProperty(go,"passive",{get:function(){gf=!0}}),window.addEventListener("test",go,go),window.removeEventListener("test",go,go)}catch{gf=!1}var us=null,bf=null,ic=null;function Xg(){if(ic)return ic;var i,a=bf,l=a.length,u,m="value"in us?us.value:us.textContent,y=m.length;for(i=0;i<l&&a[i]===m[i];i++);var S=l-i;for(u=1;u<=S&&a[l-u]===m[y-u];u++);return ic=m.slice(i,1<u?1-u:void 0)}function ac(i){var a=i.keyCode;return"charCode"in i?(i=i.charCode,i===0&&a===13&&(i=13)):i=a,i===10&&(i=13),32<=i||i===13?i:0}function oc(){return!0}function eb(){return!1}function un(i){function a(l,u,m,y,S){this._reactName=l,this._targetInst=m,this.type=u,this.nativeEvent=y,this.target=S,this.currentTarget=null;for(var j in i)i.hasOwnProperty(j)&&(l=i[j],this[j]=l?l(y):y[j]);return this.isDefaultPrevented=(y.defaultPrevented!=null?y.defaultPrevented:y.returnValue===!1)?oc:eb,this.isPropagationStopped=eb,this}return b(a.prototype,{preventDefault:function(){this.defaultPrevented=!0;var l=this.nativeEvent;l&&(l.preventDefault?l.preventDefault():typeof l.returnValue!="unknown"&&(l.returnValue=!1),this.isDefaultPrevented=oc)},stopPropagation:function(){var l=this.nativeEvent;l&&(l.stopPropagation?l.stopPropagation():typeof l.cancelBubble!="unknown"&&(l.cancelBubble=!0),this.isPropagationStopped=oc)},persist:function(){},isPersistent:oc}),a}var si={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(i){return i.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},lc=un(si),bo=b({},si,{view:0,detail:0}),Ak=un(bo),vf,xf,vo,cc=b({},bo,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:Sf,button:0,buttons:0,relatedTarget:function(i){return i.relatedTarget===void 0?i.fromElement===i.srcElement?i.toElement:i.fromElement:i.relatedTarget},movementX:function(i){return"movementX"in i?i.movementX:(i!==vo&&(vo&&i.type==="mousemove"?(vf=i.screenX-vo.screenX,xf=i.screenY-vo.screenY):xf=vf=0,vo=i),vf)},movementY:function(i){return"movementY"in i?i.movementY:xf}}),tb=un(cc),jk=b({},cc,{dataTransfer:0}),kk=un(jk),Ck=b({},bo,{relatedTarget:0}),wf=un(Ck),Nk=b({},si,{animationName:0,elapsedTime:0,pseudoElement:0}),Ok=un(Nk),Tk=b({},si,{clipboardData:function(i){return"clipboardData"in i?i.clipboardData:window.clipboardData}}),Rk=un(Tk),Dk=b({},si,{data:0}),nb=un(Dk),Ik={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},Mk={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},Lk={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function Uk(i){var a=this.nativeEvent;return a.getModifierState?a.getModifierState(i):(i=Lk[i])?!!a[i]:!1}function Sf(){return Uk}var $k=b({},bo,{key:function(i){if(i.key){var a=Ik[i.key]||i.key;if(a!=="Unidentified")return a}return i.type==="keypress"?(i=ac(i),i===13?"Enter":String.fromCharCode(i)):i.type==="keydown"||i.type==="keyup"?Mk[i.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:Sf,charCode:function(i){return i.type==="keypress"?ac(i):0},keyCode:function(i){return i.type==="keydown"||i.type==="keyup"?i.keyCode:0},which:function(i){return i.type==="keypress"?ac(i):i.type==="keydown"||i.type==="keyup"?i.keyCode:0}}),Bk=un($k),Fk=b({},cc,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),rb=un(Fk),Pk=b({},bo,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:Sf}),qk=un(Pk),zk=b({},si,{propertyName:0,elapsedTime:0,pseudoElement:0}),Vk=un(zk),Hk=b({},cc,{deltaX:function(i){return"deltaX"in i?i.deltaX:"wheelDeltaX"in i?-i.wheelDeltaX:0},deltaY:function(i){return"deltaY"in i?i.deltaY:"wheelDeltaY"in i?-i.wheelDeltaY:"wheelDelta"in i?-i.wheelDelta:0},deltaZ:0,deltaMode:0}),Gk=un(Hk),Kk=b({},si,{newState:0,oldState:0}),Yk=un(Kk),Zk=[9,13,27,32],_f=Dr&&"CompositionEvent"in window,xo=null;Dr&&"documentMode"in document&&(xo=document.documentMode);var Wk=Dr&&"TextEvent"in window&&!xo,sb=Dr&&(!_f||xo&&8<xo&&11>=xo),ib=" ",ab=!1;function ob(i,a){switch(i){case"keyup":return Zk.indexOf(a.keyCode)!==-1;case"keydown":return a.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function lb(i){return i=i.detail,typeof i=="object"&&"data"in i?i.data:null}var ra=!1;function Jk(i,a){switch(i){case"compositionend":return lb(a);case"keypress":return a.which!==32?null:(ab=!0,ib);case"textInput":return i=a.data,i===ib&&ab?null:i;default:return null}}function Qk(i,a){if(ra)return i==="compositionend"||!_f&&ob(i,a)?(i=Xg(),ic=bf=us=null,ra=!1,i):null;switch(i){case"paste":return null;case"keypress":if(!(a.ctrlKey||a.altKey||a.metaKey)||a.ctrlKey&&a.altKey){if(a.char&&1<a.char.length)return a.char;if(a.which)return String.fromCharCode(a.which)}return null;case"compositionend":return sb&&a.locale!=="ko"?null:a.data;default:return null}}var Xk={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function cb(i){var a=i&&i.nodeName&&i.nodeName.toLowerCase();return a==="input"?!!Xk[i.type]:a==="textarea"}function ub(i,a,l,u){ta?na?na.push(u):na=[u]:ta=u,a=Qc(a,"onChange"),0<a.length&&(l=new lc("onChange","change",null,l,u),i.push({event:l,listeners:a}))}var wo=null,So=null;function eC(i){G0(i,0)}function uc(i){var a=mo(i);if(Hg(a))return i}function db(i,a){if(i==="change")return a}var fb=!1;if(Dr){var Ef;if(Dr){var Af="oninput"in document;if(!Af){var hb=document.createElement("div");hb.setAttribute("oninput","return;"),Af=typeof hb.oninput=="function"}Ef=Af}else Ef=!1;fb=Ef&&(!document.documentMode||9<document.documentMode)}function pb(){wo&&(wo.detachEvent("onpropertychange",mb),So=wo=null)}function mb(i){if(i.propertyName==="value"&&uc(So)){var a=[];ub(a,So,i,mf(i)),Qg(eC,a)}}function tC(i,a,l){i==="focusin"?(pb(),wo=a,So=l,wo.attachEvent("onpropertychange",mb)):i==="focusout"&&pb()}function nC(i){if(i==="selectionchange"||i==="keyup"||i==="keydown")return uc(So)}function rC(i,a){if(i==="click")return uc(a)}function sC(i,a){if(i==="input"||i==="change")return uc(a)}function iC(i,a){return i===a&&(i!==0||1/i===1/a)||i!==i&&a!==a}var En=typeof Object.is=="function"?Object.is:iC;function _o(i,a){if(En(i,a))return!0;if(typeof i!="object"||i===null||typeof a!="object"||a===null)return!1;var l=Object.keys(i),u=Object.keys(a);if(l.length!==u.length)return!1;for(u=0;u<l.length;u++){var m=l[u];if(!tf.call(a,m)||!En(i[m],a[m]))return!1}return!0}function yb(i){for(;i&&i.firstChild;)i=i.firstChild;return i}function gb(i,a){var l=yb(i);i=0;for(var u;l;){if(l.nodeType===3){if(u=i+l.textContent.length,i<=a&&u>=a)return{node:l,offset:a-i};i=u}e:{for(;l;){if(l.nextSibling){l=l.nextSibling;break e}l=l.parentNode}l=void 0}l=yb(l)}}function bb(i,a){return i&&a?i===a?!0:i&&i.nodeType===3?!1:a&&a.nodeType===3?bb(i,a.parentNode):"contains"in i?i.contains(a):i.compareDocumentPosition?!!(i.compareDocumentPosition(a)&16):!1:!1}function vb(i){i=i!=null&&i.ownerDocument!=null&&i.ownerDocument.defaultView!=null?i.ownerDocument.defaultView:window;for(var a=rc(i.document);a instanceof i.HTMLIFrameElement;){try{var l=typeof a.contentWindow.location.href=="string"}catch{l=!1}if(l)i=a.contentWindow;else break;a=rc(i.document)}return a}function jf(i){var a=i&&i.nodeName&&i.nodeName.toLowerCase();return a&&(a==="input"&&(i.type==="text"||i.type==="search"||i.type==="tel"||i.type==="url"||i.type==="password")||a==="textarea"||i.contentEditable==="true")}var aC=Dr&&"documentMode"in document&&11>=document.documentMode,sa=null,kf=null,Eo=null,Cf=!1;function xb(i,a,l){var u=l.window===l?l.document:l.nodeType===9?l:l.ownerDocument;Cf||sa==null||sa!==rc(u)||(u=sa,"selectionStart"in u&&jf(u)?u={start:u.selectionStart,end:u.selectionEnd}:(u=(u.ownerDocument&&u.ownerDocument.defaultView||window).getSelection(),u={anchorNode:u.anchorNode,anchorOffset:u.anchorOffset,focusNode:u.focusNode,focusOffset:u.focusOffset}),Eo&&_o(Eo,u)||(Eo=u,u=Qc(kf,"onSelect"),0<u.length&&(a=new lc("onSelect","select",null,a,l),i.push({event:a,listeners:u}),a.target=sa)))}function ii(i,a){var l={};return l[i.toLowerCase()]=a.toLowerCase(),l["Webkit"+i]="webkit"+a,l["Moz"+i]="moz"+a,l}var ia={animationend:ii("Animation","AnimationEnd"),animationiteration:ii("Animation","AnimationIteration"),animationstart:ii("Animation","AnimationStart"),transitionrun:ii("Transition","TransitionRun"),transitionstart:ii("Transition","TransitionStart"),transitioncancel:ii("Transition","TransitionCancel"),transitionend:ii("Transition","TransitionEnd")},Nf={},wb={};Dr&&(wb=document.createElement("div").style,"AnimationEvent"in window||(delete ia.animationend.animation,delete ia.animationiteration.animation,delete ia.animationstart.animation),"TransitionEvent"in window||delete ia.transitionend.transition);function ai(i){if(Nf[i])return Nf[i];if(!ia[i])return i;var a=ia[i],l;for(l in a)if(a.hasOwnProperty(l)&&l in wb)return Nf[i]=a[l];return i}var Sb=ai("animationend"),_b=ai("animationiteration"),Eb=ai("animationstart"),oC=ai("transitionrun"),lC=ai("transitionstart"),cC=ai("transitioncancel"),Ab=ai("transitionend"),jb=new Map,Of="abort auxClick beforeToggle cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");Of.push("scrollEnd");function nr(i,a){jb.set(i,a),ri(a,[i])}var dc=typeof reportError=="function"?reportError:function(i){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var a=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof i=="object"&&i!==null&&typeof i.message=="string"?String(i.message):String(i),error:i});if(!window.dispatchEvent(a))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",i);return}console.error(i)},$n=[],aa=0,Tf=0;function fc(){for(var i=aa,a=Tf=aa=0;a<i;){var l=$n[a];$n[a++]=null;var u=$n[a];$n[a++]=null;var m=$n[a];$n[a++]=null;var y=$n[a];if($n[a++]=null,u!==null&&m!==null){var S=u.pending;S===null?m.next=m:(m.next=S.next,S.next=m),u.pending=m}y!==0&&kb(l,m,y)}}function hc(i,a,l,u){$n[aa++]=i,$n[aa++]=a,$n[aa++]=l,$n[aa++]=u,Tf|=u,i.lanes|=u,i=i.alternate,i!==null&&(i.lanes|=u)}function Rf(i,a,l,u){return hc(i,a,l,u),pc(i)}function oi(i,a){return hc(i,null,null,a),pc(i)}function kb(i,a,l){i.lanes|=l;var u=i.alternate;u!==null&&(u.lanes|=l);for(var m=!1,y=i.return;y!==null;)y.childLanes|=l,u=y.alternate,u!==null&&(u.childLanes|=l),y.tag===22&&(i=y.stateNode,i===null||i._visibility&1||(m=!0)),i=y,y=y.return;return i.tag===3?(y=i.stateNode,m&&a!==null&&(m=31-_n(l),i=y.hiddenUpdates,u=i[m],u===null?i[m]=[a]:u.push(a),a.lane=l|536870912),y):null}function pc(i){if(50<Go)throw Go=0,Ph=null,Error(r(185));for(var a=i.return;a!==null;)i=a,a=i.return;return i.tag===3?i.stateNode:null}var oa={};function uC(i,a,l,u){this.tag=i,this.key=l,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.refCleanup=this.ref=null,this.pendingProps=a,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=u,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function An(i,a,l,u){return new uC(i,a,l,u)}function Df(i){return i=i.prototype,!(!i||!i.isReactComponent)}function Ir(i,a){var l=i.alternate;return l===null?(l=An(i.tag,a,i.key,i.mode),l.elementType=i.elementType,l.type=i.type,l.stateNode=i.stateNode,l.alternate=i,i.alternate=l):(l.pendingProps=a,l.type=i.type,l.flags=0,l.subtreeFlags=0,l.deletions=null),l.flags=i.flags&65011712,l.childLanes=i.childLanes,l.lanes=i.lanes,l.child=i.child,l.memoizedProps=i.memoizedProps,l.memoizedState=i.memoizedState,l.updateQueue=i.updateQueue,a=i.dependencies,l.dependencies=a===null?null:{lanes:a.lanes,firstContext:a.firstContext},l.sibling=i.sibling,l.index=i.index,l.ref=i.ref,l.refCleanup=i.refCleanup,l}function Cb(i,a){i.flags&=65011714;var l=i.alternate;return l===null?(i.childLanes=0,i.lanes=a,i.child=null,i.subtreeFlags=0,i.memoizedProps=null,i.memoizedState=null,i.updateQueue=null,i.dependencies=null,i.stateNode=null):(i.childLanes=l.childLanes,i.lanes=l.lanes,i.child=l.child,i.subtreeFlags=0,i.deletions=null,i.memoizedProps=l.memoizedProps,i.memoizedState=l.memoizedState,i.updateQueue=l.updateQueue,i.type=l.type,a=l.dependencies,i.dependencies=a===null?null:{lanes:a.lanes,firstContext:a.firstContext}),i}function mc(i,a,l,u,m,y){var S=0;if(u=i,typeof i=="function")Df(i)&&(S=1);else if(typeof i=="string")S=mN(i,l,le.current)?26:i==="html"||i==="head"||i==="body"?27:5;else e:switch(i){case H:return i=An(31,l,a,m),i.elementType=H,i.lanes=y,i;case k:return li(l.children,m,y,a);case R:S=8,m|=24;break;case C:return i=An(12,l,a,m|2),i.elementType=C,i.lanes=y,i;case I:return i=An(13,l,a,m),i.elementType=I,i.lanes=y,i;case N:return i=An(19,l,a,m),i.elementType=N,i.lanes=y,i;default:if(typeof i=="object"&&i!==null)switch(i.$$typeof){case U:S=10;break e;case T:S=9;break e;case q:S=11;break e;case M:S=14;break e;case L:S=16,u=null;break e}S=29,l=Error(r(130,i===null?"null":typeof i,"")),u=null}return a=An(S,l,a,m),a.elementType=i,a.type=u,a.lanes=y,a}function li(i,a,l,u){return i=An(7,i,u,a),i.lanes=l,i}function If(i,a,l){return i=An(6,i,null,a),i.lanes=l,i}function Nb(i){var a=An(18,null,null,0);return a.stateNode=i,a}function Mf(i,a,l){return a=An(4,i.children!==null?i.children:[],i.key,a),a.lanes=l,a.stateNode={containerInfo:i.containerInfo,pendingChildren:null,implementation:i.implementation},a}var Ob=new WeakMap;function Bn(i,a){if(typeof i=="object"&&i!==null){var l=Ob.get(i);return l!==void 0?l:(a={value:i,source:a,stack:Ng(a)},Ob.set(i,a),a)}return{value:i,source:a,stack:Ng(a)}}var la=[],ca=0,yc=null,Ao=0,Fn=[],Pn=0,ds=null,fr=1,hr="";function Mr(i,a){la[ca++]=Ao,la[ca++]=yc,yc=i,Ao=a}function Tb(i,a,l){Fn[Pn++]=fr,Fn[Pn++]=hr,Fn[Pn++]=ds,ds=i;var u=fr;i=hr;var m=32-_n(u)-1;u&=~(1<<m),l+=1;var y=32-_n(a)+m;if(30<y){var S=m-m%5;y=(u&(1<<S)-1).toString(32),u>>=S,m-=S,fr=1<<32-_n(a)+m|l<<m|u,hr=y+i}else fr=1<<y|l<<m|u,hr=i}function Lf(i){i.return!==null&&(Mr(i,1),Tb(i,1,0))}function Uf(i){for(;i===yc;)yc=la[--ca],la[ca]=null,Ao=la[--ca],la[ca]=null;for(;i===ds;)ds=Fn[--Pn],Fn[Pn]=null,hr=Fn[--Pn],Fn[Pn]=null,fr=Fn[--Pn],Fn[Pn]=null}function Rb(i,a){Fn[Pn++]=fr,Fn[Pn++]=hr,Fn[Pn++]=ds,fr=a.id,hr=a.overflow,ds=i}var Lt=null,Xe=null,De=!1,fs=null,qn=!1,$f=Error(r(519));function hs(i){var a=Error(r(418,1<arguments.length&&arguments[1]!==void 0&&arguments[1]?"text":"HTML",""));throw jo(Bn(a,i)),$f}function Db(i){var a=i.stateNode,l=i.type,u=i.memoizedProps;switch(a[Mt]=i,a[cn]=u,l){case"dialog":Ce("cancel",a),Ce("close",a);break;case"iframe":case"object":case"embed":Ce("load",a);break;case"video":case"audio":for(l=0;l<Yo.length;l++)Ce(Yo[l],a);break;case"source":Ce("error",a);break;case"img":case"image":case"link":Ce("error",a),Ce("load",a);break;case"details":Ce("toggle",a);break;case"input":Ce("invalid",a),Gg(a,u.value,u.defaultValue,u.checked,u.defaultChecked,u.type,u.name,!0);break;case"select":Ce("invalid",a);break;case"textarea":Ce("invalid",a),Yg(a,u.value,u.defaultValue,u.children)}l=u.children,typeof l!="string"&&typeof l!="number"&&typeof l!="bigint"||a.textContent===""+l||u.suppressHydrationWarning===!0||W0(a.textContent,l)?(u.popover!=null&&(Ce("beforetoggle",a),Ce("toggle",a)),u.onScroll!=null&&Ce("scroll",a),u.onScrollEnd!=null&&Ce("scrollend",a),u.onClick!=null&&(a.onclick=Rr),a=!0):a=!1,a||hs(i,!0)}function Ib(i){for(Lt=i.return;Lt;)switch(Lt.tag){case 5:case 31:case 13:qn=!1;return;case 27:case 3:qn=!0;return;default:Lt=Lt.return}}function ua(i){if(i!==Lt)return!1;if(!De)return Ib(i),De=!0,!1;var a=i.tag,l;if((l=a!==3&&a!==27)&&((l=a===5)&&(l=i.type,l=!(l!=="form"&&l!=="button")||np(i.type,i.memoizedProps)),l=!l),l&&Xe&&hs(i),Ib(i),a===13){if(i=i.memoizedState,i=i!==null?i.dehydrated:null,!i)throw Error(r(317));Xe=ix(i)}else if(a===31){if(i=i.memoizedState,i=i!==null?i.dehydrated:null,!i)throw Error(r(317));Xe=ix(i)}else a===27?(a=Xe,ks(i.type)?(i=op,op=null,Xe=i):Xe=a):Xe=Lt?Vn(i.stateNode.nextSibling):null;return!0}function ci(){Xe=Lt=null,De=!1}function Bf(){var i=fs;return i!==null&&(pn===null?pn=i:pn.push.apply(pn,i),fs=null),i}function jo(i){fs===null?fs=[i]:fs.push(i)}var Ff=B(null),ui=null,Lr=null;function ps(i,a,l){ae(Ff,a._currentValue),a._currentValue=l}function Ur(i){i._currentValue=Ff.current,ee(Ff)}function Pf(i,a,l){for(;i!==null;){var u=i.alternate;if((i.childLanes&a)!==a?(i.childLanes|=a,u!==null&&(u.childLanes|=a)):u!==null&&(u.childLanes&a)!==a&&(u.childLanes|=a),i===l)break;i=i.return}}function qf(i,a,l,u){var m=i.child;for(m!==null&&(m.return=i);m!==null;){var y=m.dependencies;if(y!==null){var S=m.child;y=y.firstContext;e:for(;y!==null;){var j=y;y=m;for(var V=0;V<a.length;V++)if(j.context===a[V]){y.lanes|=l,j=y.alternate,j!==null&&(j.lanes|=l),Pf(y.return,l,i),u||(S=null);break e}y=j.next}}else if(m.tag===18){if(S=m.return,S===null)throw Error(r(341));S.lanes|=l,y=S.alternate,y!==null&&(y.lanes|=l),Pf(S,l,i),S=null}else S=m.child;if(S!==null)S.return=m;else for(S=m;S!==null;){if(S===i){S=null;break}if(m=S.sibling,m!==null){m.return=S.return,S=m;break}S=S.return}m=S}}function da(i,a,l,u){i=null;for(var m=a,y=!1;m!==null;){if(!y){if((m.flags&524288)!==0)y=!0;else if((m.flags&262144)!==0)break}if(m.tag===10){var S=m.alternate;if(S===null)throw Error(r(387));if(S=S.memoizedProps,S!==null){var j=m.type;En(m.pendingProps.value,S.value)||(i!==null?i.push(j):i=[j])}}else if(m===qe.current){if(S=m.alternate,S===null)throw Error(r(387));S.memoizedState.memoizedState!==m.memoizedState.memoizedState&&(i!==null?i.push(Xo):i=[Xo])}m=m.return}i!==null&&qf(a,i,l,u),a.flags|=262144}function gc(i){for(i=i.firstContext;i!==null;){if(!En(i.context._currentValue,i.memoizedValue))return!0;i=i.next}return!1}function di(i){ui=i,Lr=null,i=i.dependencies,i!==null&&(i.firstContext=null)}function Ut(i){return Mb(ui,i)}function bc(i,a){return ui===null&&di(i),Mb(i,a)}function Mb(i,a){var l=a._currentValue;if(a={context:a,memoizedValue:l,next:null},Lr===null){if(i===null)throw Error(r(308));Lr=a,i.dependencies={lanes:0,firstContext:a},i.flags|=524288}else Lr=Lr.next=a;return l}var dC=typeof AbortController<"u"?AbortController:function(){var i=[],a=this.signal={aborted:!1,addEventListener:function(l,u){i.push(u)}};this.abort=function(){a.aborted=!0,i.forEach(function(l){return l()})}},fC=t.unstable_scheduleCallback,hC=t.unstable_NormalPriority,vt={$$typeof:U,Consumer:null,Provider:null,_currentValue:null,_currentValue2:null,_threadCount:0};function zf(){return{controller:new dC,data:new Map,refCount:0}}function ko(i){i.refCount--,i.refCount===0&&fC(hC,function(){i.controller.abort()})}var Co=null,Vf=0,fa=0,ha=null;function pC(i,a){if(Co===null){var l=Co=[];Vf=0,fa=Kh(),ha={status:"pending",value:void 0,then:function(u){l.push(u)}}}return Vf++,a.then(Lb,Lb),a}function Lb(){if(--Vf===0&&Co!==null){ha!==null&&(ha.status="fulfilled");var i=Co;Co=null,fa=0,ha=null;for(var a=0;a<i.length;a++)(0,i[a])()}}function mC(i,a){var l=[],u={status:"pending",value:null,reason:null,then:function(m){l.push(m)}};return i.then(function(){u.status="fulfilled",u.value=a;for(var m=0;m<l.length;m++)(0,l[m])(a)},function(m){for(u.status="rejected",u.reason=m,m=0;m<l.length;m++)(0,l[m])(void 0)}),u}var Ub=z.S;z.S=function(i,a){x0=wn(),typeof a=="object"&&a!==null&&typeof a.then=="function"&&pC(i,a),Ub!==null&&Ub(i,a)};var fi=B(null);function Hf(){var i=fi.current;return i!==null?i:We.pooledCache}function vc(i,a){a===null?ae(fi,fi.current):ae(fi,a.pool)}function $b(){var i=Hf();return i===null?null:{parent:vt._currentValue,pool:i}}var pa=Error(r(460)),Gf=Error(r(474)),xc=Error(r(542)),wc={then:function(){}};function Bb(i){return i=i.status,i==="fulfilled"||i==="rejected"}function Fb(i,a,l){switch(l=i[l],l===void 0?i.push(a):l!==a&&(a.then(Rr,Rr),a=l),a.status){case"fulfilled":return a.value;case"rejected":throw i=a.reason,qb(i),i;default:if(typeof a.status=="string")a.then(Rr,Rr);else{if(i=We,i!==null&&100<i.shellSuspendCounter)throw Error(r(482));i=a,i.status="pending",i.then(function(u){if(a.status==="pending"){var m=a;m.status="fulfilled",m.value=u}},function(u){if(a.status==="pending"){var m=a;m.status="rejected",m.reason=u}})}switch(a.status){case"fulfilled":return a.value;case"rejected":throw i=a.reason,qb(i),i}throw pi=a,pa}}function hi(i){try{var a=i._init;return a(i._payload)}catch(l){throw l!==null&&typeof l=="object"&&typeof l.then=="function"?(pi=l,pa):l}}var pi=null;function Pb(){if(pi===null)throw Error(r(459));var i=pi;return pi=null,i}function qb(i){if(i===pa||i===xc)throw Error(r(483))}var ma=null,No=0;function Sc(i){var a=No;return No+=1,ma===null&&(ma=[]),Fb(ma,i,a)}function Oo(i,a){a=a.props.ref,i.ref=a!==void 0?a:null}function _c(i,a){throw a.$$typeof===v?Error(r(525)):(i=Object.prototype.toString.call(a),Error(r(31,i==="[object Object]"?"object with keys {"+Object.keys(a).join(", ")+"}":i)))}function zb(i){function a(Z,Y){if(i){var J=Z.deletions;J===null?(Z.deletions=[Y],Z.flags|=16):J.push(Y)}}function l(Z,Y){if(!i)return null;for(;Y!==null;)a(Z,Y),Y=Y.sibling;return null}function u(Z){for(var Y=new Map;Z!==null;)Z.key!==null?Y.set(Z.key,Z):Y.set(Z.index,Z),Z=Z.sibling;return Y}function m(Z,Y){return Z=Ir(Z,Y),Z.index=0,Z.sibling=null,Z}function y(Z,Y,J){return Z.index=J,i?(J=Z.alternate,J!==null?(J=J.index,J<Y?(Z.flags|=67108866,Y):J):(Z.flags|=67108866,Y)):(Z.flags|=1048576,Y)}function S(Z){return i&&Z.alternate===null&&(Z.flags|=67108866),Z}function j(Z,Y,J,re){return Y===null||Y.tag!==6?(Y=If(J,Z.mode,re),Y.return=Z,Y):(Y=m(Y,J),Y.return=Z,Y)}function V(Z,Y,J,re){var pe=J.type;return pe===k?ne(Z,Y,J.props.children,re,J.key):Y!==null&&(Y.elementType===pe||typeof pe=="object"&&pe!==null&&pe.$$typeof===L&&hi(pe)===Y.type)?(Y=m(Y,J.props),Oo(Y,J),Y.return=Z,Y):(Y=mc(J.type,J.key,J.props,null,Z.mode,re),Oo(Y,J),Y.return=Z,Y)}function Q(Z,Y,J,re){return Y===null||Y.tag!==4||Y.stateNode.containerInfo!==J.containerInfo||Y.stateNode.implementation!==J.implementation?(Y=Mf(J,Z.mode,re),Y.return=Z,Y):(Y=m(Y,J.children||[]),Y.return=Z,Y)}function ne(Z,Y,J,re,pe){return Y===null||Y.tag!==7?(Y=li(J,Z.mode,re,pe),Y.return=Z,Y):(Y=m(Y,J),Y.return=Z,Y)}function ie(Z,Y,J){if(typeof Y=="string"&&Y!==""||typeof Y=="number"||typeof Y=="bigint")return Y=If(""+Y,Z.mode,J),Y.return=Z,Y;if(typeof Y=="object"&&Y!==null){switch(Y.$$typeof){case x:return J=mc(Y.type,Y.key,Y.props,null,Z.mode,J),Oo(J,Y),J.return=Z,J;case _:return Y=Mf(Y,Z.mode,J),Y.return=Z,Y;case L:return Y=hi(Y),ie(Z,Y,J)}if(D(Y)||w(Y))return Y=li(Y,Z.mode,J,null),Y.return=Z,Y;if(typeof Y.then=="function")return ie(Z,Sc(Y),J);if(Y.$$typeof===U)return ie(Z,bc(Z,Y),J);_c(Z,Y)}return null}function X(Z,Y,J,re){var pe=Y!==null?Y.key:null;if(typeof J=="string"&&J!==""||typeof J=="number"||typeof J=="bigint")return pe!==null?null:j(Z,Y,""+J,re);if(typeof J=="object"&&J!==null){switch(J.$$typeof){case x:return J.key===pe?V(Z,Y,J,re):null;case _:return J.key===pe?Q(Z,Y,J,re):null;case L:return J=hi(J),X(Z,Y,J,re)}if(D(J)||w(J))return pe!==null?null:ne(Z,Y,J,re,null);if(typeof J.then=="function")return X(Z,Y,Sc(J),re);if(J.$$typeof===U)return X(Z,Y,bc(Z,J),re);_c(Z,J)}return null}function te(Z,Y,J,re,pe){if(typeof re=="string"&&re!==""||typeof re=="number"||typeof re=="bigint")return Z=Z.get(J)||null,j(Y,Z,""+re,pe);if(typeof re=="object"&&re!==null){switch(re.$$typeof){case x:return Z=Z.get(re.key===null?J:re.key)||null,V(Y,Z,re,pe);case _:return Z=Z.get(re.key===null?J:re.key)||null,Q(Y,Z,re,pe);case L:return re=hi(re),te(Z,Y,J,re,pe)}if(D(re)||w(re))return Z=Z.get(J)||null,ne(Y,Z,re,pe,null);if(typeof re.then=="function")return te(Z,Y,J,Sc(re),pe);if(re.$$typeof===U)return te(Z,Y,J,bc(Y,re),pe);_c(Y,re)}return null}function de(Z,Y,J,re){for(var pe=null,Ue=null,fe=Y,Se=Y=0,Oe=null;fe!==null&&Se<J.length;Se++){fe.index>Se?(Oe=fe,fe=null):Oe=fe.sibling;var $e=X(Z,fe,J[Se],re);if($e===null){fe===null&&(fe=Oe);break}i&&fe&&$e.alternate===null&&a(Z,fe),Y=y($e,Y,Se),Ue===null?pe=$e:Ue.sibling=$e,Ue=$e,fe=Oe}if(Se===J.length)return l(Z,fe),De&&Mr(Z,Se),pe;if(fe===null){for(;Se<J.length;Se++)fe=ie(Z,J[Se],re),fe!==null&&(Y=y(fe,Y,Se),Ue===null?pe=fe:Ue.sibling=fe,Ue=fe);return De&&Mr(Z,Se),pe}for(fe=u(fe);Se<J.length;Se++)Oe=te(fe,Z,Se,J[Se],re),Oe!==null&&(i&&Oe.alternate!==null&&fe.delete(Oe.key===null?Se:Oe.key),Y=y(Oe,Y,Se),Ue===null?pe=Oe:Ue.sibling=Oe,Ue=Oe);return i&&fe.forEach(function(Rs){return a(Z,Rs)}),De&&Mr(Z,Se),pe}function me(Z,Y,J,re){if(J==null)throw Error(r(151));for(var pe=null,Ue=null,fe=Y,Se=Y=0,Oe=null,$e=J.next();fe!==null&&!$e.done;Se++,$e=J.next()){fe.index>Se?(Oe=fe,fe=null):Oe=fe.sibling;var Rs=X(Z,fe,$e.value,re);if(Rs===null){fe===null&&(fe=Oe);break}i&&fe&&Rs.alternate===null&&a(Z,fe),Y=y(Rs,Y,Se),Ue===null?pe=Rs:Ue.sibling=Rs,Ue=Rs,fe=Oe}if($e.done)return l(Z,fe),De&&Mr(Z,Se),pe;if(fe===null){for(;!$e.done;Se++,$e=J.next())$e=ie(Z,$e.value,re),$e!==null&&(Y=y($e,Y,Se),Ue===null?pe=$e:Ue.sibling=$e,Ue=$e);return De&&Mr(Z,Se),pe}for(fe=u(fe);!$e.done;Se++,$e=J.next())$e=te(fe,Z,Se,$e.value,re),$e!==null&&(i&&$e.alternate!==null&&fe.delete($e.key===null?Se:$e.key),Y=y($e,Y,Se),Ue===null?pe=$e:Ue.sibling=$e,Ue=$e);return i&&fe.forEach(function(jN){return a(Z,jN)}),De&&Mr(Z,Se),pe}function Ye(Z,Y,J,re){if(typeof J=="object"&&J!==null&&J.type===k&&J.key===null&&(J=J.props.children),typeof J=="object"&&J!==null){switch(J.$$typeof){case x:e:{for(var pe=J.key;Y!==null;){if(Y.key===pe){if(pe=J.type,pe===k){if(Y.tag===7){l(Z,Y.sibling),re=m(Y,J.props.children),re.return=Z,Z=re;break e}}else if(Y.elementType===pe||typeof pe=="object"&&pe!==null&&pe.$$typeof===L&&hi(pe)===Y.type){l(Z,Y.sibling),re=m(Y,J.props),Oo(re,J),re.return=Z,Z=re;break e}l(Z,Y);break}else a(Z,Y);Y=Y.sibling}J.type===k?(re=li(J.props.children,Z.mode,re,J.key),re.return=Z,Z=re):(re=mc(J.type,J.key,J.props,null,Z.mode,re),Oo(re,J),re.return=Z,Z=re)}return S(Z);case _:e:{for(pe=J.key;Y!==null;){if(Y.key===pe)if(Y.tag===4&&Y.stateNode.containerInfo===J.containerInfo&&Y.stateNode.implementation===J.implementation){l(Z,Y.sibling),re=m(Y,J.children||[]),re.return=Z,Z=re;break e}else{l(Z,Y);break}else a(Z,Y);Y=Y.sibling}re=Mf(J,Z.mode,re),re.return=Z,Z=re}return S(Z);case L:return J=hi(J),Ye(Z,Y,J,re)}if(D(J))return de(Z,Y,J,re);if(w(J)){if(pe=w(J),typeof pe!="function")throw Error(r(150));return J=pe.call(J),me(Z,Y,J,re)}if(typeof J.then=="function")return Ye(Z,Y,Sc(J),re);if(J.$$typeof===U)return Ye(Z,Y,bc(Z,J),re);_c(Z,J)}return typeof J=="string"&&J!==""||typeof J=="number"||typeof J=="bigint"?(J=""+J,Y!==null&&Y.tag===6?(l(Z,Y.sibling),re=m(Y,J),re.return=Z,Z=re):(l(Z,Y),re=If(J,Z.mode,re),re.return=Z,Z=re),S(Z)):l(Z,Y)}return function(Z,Y,J,re){try{No=0;var pe=Ye(Z,Y,J,re);return ma=null,pe}catch(fe){if(fe===pa||fe===xc)throw fe;var Ue=An(29,fe,null,Z.mode);return Ue.lanes=re,Ue.return=Z,Ue}finally{}}}var mi=zb(!0),Vb=zb(!1),ms=!1;function Kf(i){i.updateQueue={baseState:i.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Yf(i,a){i=i.updateQueue,a.updateQueue===i&&(a.updateQueue={baseState:i.baseState,firstBaseUpdate:i.firstBaseUpdate,lastBaseUpdate:i.lastBaseUpdate,shared:i.shared,callbacks:null})}function ys(i){return{lane:i,tag:0,payload:null,callback:null,next:null}}function gs(i,a,l){var u=i.updateQueue;if(u===null)return null;if(u=u.shared,(Fe&2)!==0){var m=u.pending;return m===null?a.next=a:(a.next=m.next,m.next=a),u.pending=a,a=pc(i),kb(i,null,l),a}return hc(i,u,a,l),pc(i)}function To(i,a,l){if(a=a.updateQueue,a!==null&&(a=a.shared,(l&4194048)!==0)){var u=a.lanes;u&=i.pendingLanes,l|=u,a.lanes=l,Mg(i,l)}}function Zf(i,a){var l=i.updateQueue,u=i.alternate;if(u!==null&&(u=u.updateQueue,l===u)){var m=null,y=null;if(l=l.firstBaseUpdate,l!==null){do{var S={lane:l.lane,tag:l.tag,payload:l.payload,callback:null,next:null};y===null?m=y=S:y=y.next=S,l=l.next}while(l!==null);y===null?m=y=a:y=y.next=a}else m=y=a;l={baseState:u.baseState,firstBaseUpdate:m,lastBaseUpdate:y,shared:u.shared,callbacks:u.callbacks},i.updateQueue=l;return}i=l.lastBaseUpdate,i===null?l.firstBaseUpdate=a:i.next=a,l.lastBaseUpdate=a}var Wf=!1;function Ro(){if(Wf){var i=ha;if(i!==null)throw i}}function Do(i,a,l,u){Wf=!1;var m=i.updateQueue;ms=!1;var y=m.firstBaseUpdate,S=m.lastBaseUpdate,j=m.shared.pending;if(j!==null){m.shared.pending=null;var V=j,Q=V.next;V.next=null,S===null?y=Q:S.next=Q,S=V;var ne=i.alternate;ne!==null&&(ne=ne.updateQueue,j=ne.lastBaseUpdate,j!==S&&(j===null?ne.firstBaseUpdate=Q:j.next=Q,ne.lastBaseUpdate=V))}if(y!==null){var ie=m.baseState;S=0,ne=Q=V=null,j=y;do{var X=j.lane&-536870913,te=X!==j.lane;if(te?(Ne&X)===X:(u&X)===X){X!==0&&X===fa&&(Wf=!0),ne!==null&&(ne=ne.next={lane:0,tag:j.tag,payload:j.payload,callback:null,next:null});e:{var de=i,me=j;X=a;var Ye=l;switch(me.tag){case 1:if(de=me.payload,typeof de=="function"){ie=de.call(Ye,ie,X);break e}ie=de;break e;case 3:de.flags=de.flags&-65537|128;case 0:if(de=me.payload,X=typeof de=="function"?de.call(Ye,ie,X):de,X==null)break e;ie=b({},ie,X);break e;case 2:ms=!0}}X=j.callback,X!==null&&(i.flags|=64,te&&(i.flags|=8192),te=m.callbacks,te===null?m.callbacks=[X]:te.push(X))}else te={lane:X,tag:j.tag,payload:j.payload,callback:j.callback,next:null},ne===null?(Q=ne=te,V=ie):ne=ne.next=te,S|=X;if(j=j.next,j===null){if(j=m.shared.pending,j===null)break;te=j,j=te.next,te.next=null,m.lastBaseUpdate=te,m.shared.pending=null}}while(!0);ne===null&&(V=ie),m.baseState=V,m.firstBaseUpdate=Q,m.lastBaseUpdate=ne,y===null&&(m.shared.lanes=0),Ss|=S,i.lanes=S,i.memoizedState=ie}}function Hb(i,a){if(typeof i!="function")throw Error(r(191,i));i.call(a)}function Gb(i,a){var l=i.callbacks;if(l!==null)for(i.callbacks=null,i=0;i<l.length;i++)Hb(l[i],a)}var ya=B(null),Ec=B(0);function Kb(i,a){i=Gr,ae(Ec,i),ae(ya,a),Gr=i|a.baseLanes}function Jf(){ae(Ec,Gr),ae(ya,ya.current)}function Qf(){Gr=Ec.current,ee(ya),ee(Ec)}var jn=B(null),zn=null;function bs(i){var a=i.alternate;ae(yt,yt.current&1),ae(jn,i),zn===null&&(a===null||ya.current!==null||a.memoizedState!==null)&&(zn=i)}function Xf(i){ae(yt,yt.current),ae(jn,i),zn===null&&(zn=i)}function Yb(i){i.tag===22?(ae(yt,yt.current),ae(jn,i),zn===null&&(zn=i)):vs()}function vs(){ae(yt,yt.current),ae(jn,jn.current)}function kn(i){ee(jn),zn===i&&(zn=null),ee(yt)}var yt=B(0);function Ac(i){for(var a=i;a!==null;){if(a.tag===13){var l=a.memoizedState;if(l!==null&&(l=l.dehydrated,l===null||ip(l)||ap(l)))return a}else if(a.tag===19&&(a.memoizedProps.revealOrder==="forwards"||a.memoizedProps.revealOrder==="backwards"||a.memoizedProps.revealOrder==="unstable_legacy-backwards"||a.memoizedProps.revealOrder==="together")){if((a.flags&128)!==0)return a}else if(a.child!==null){a.child.return=a,a=a.child;continue}if(a===i)break;for(;a.sibling===null;){if(a.return===null||a.return===i)return null;a=a.return}a.sibling.return=a.return,a=a.sibling}return null}var $r=0,we=null,Ge=null,xt=null,jc=!1,ga=!1,yi=!1,kc=0,Io=0,ba=null,yC=0;function ot(){throw Error(r(321))}function eh(i,a){if(a===null)return!1;for(var l=0;l<a.length&&l<i.length;l++)if(!En(i[l],a[l]))return!1;return!0}function th(i,a,l,u,m,y){return $r=y,we=a,a.memoizedState=null,a.updateQueue=null,a.lanes=0,z.H=i===null||i.memoizedState===null?Tv:yh,yi=!1,y=l(u,m),yi=!1,ga&&(y=Wb(a,l,u,m)),Zb(i),y}function Zb(i){z.H=Uo;var a=Ge!==null&&Ge.next!==null;if($r=0,xt=Ge=we=null,jc=!1,Io=0,ba=null,a)throw Error(r(300));i===null||wt||(i=i.dependencies,i!==null&&gc(i)&&(wt=!0))}function Wb(i,a,l,u){we=i;var m=0;do{if(ga&&(ba=null),Io=0,ga=!1,25<=m)throw Error(r(301));if(m+=1,xt=Ge=null,i.updateQueue!=null){var y=i.updateQueue;y.lastEffect=null,y.events=null,y.stores=null,y.memoCache!=null&&(y.memoCache.index=0)}z.H=Rv,y=a(l,u)}while(ga);return y}function gC(){var i=z.H,a=i.useState()[0];return a=typeof a.then=="function"?Mo(a):a,i=i.useState()[0],(Ge!==null?Ge.memoizedState:null)!==i&&(we.flags|=1024),a}function nh(){var i=kc!==0;return kc=0,i}function rh(i,a,l){a.updateQueue=i.updateQueue,a.flags&=-2053,i.lanes&=~l}function sh(i){if(jc){for(i=i.memoizedState;i!==null;){var a=i.queue;a!==null&&(a.pending=null),i=i.next}jc=!1}$r=0,xt=Ge=we=null,ga=!1,Io=kc=0,ba=null}function Xt(){var i={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return xt===null?we.memoizedState=xt=i:xt=xt.next=i,xt}function gt(){if(Ge===null){var i=we.alternate;i=i!==null?i.memoizedState:null}else i=Ge.next;var a=xt===null?we.memoizedState:xt.next;if(a!==null)xt=a,Ge=i;else{if(i===null)throw we.alternate===null?Error(r(467)):Error(r(310));Ge=i,i={memoizedState:Ge.memoizedState,baseState:Ge.baseState,baseQueue:Ge.baseQueue,queue:Ge.queue,next:null},xt===null?we.memoizedState=xt=i:xt=xt.next=i}return xt}function Cc(){return{lastEffect:null,events:null,stores:null,memoCache:null}}function Mo(i){var a=Io;return Io+=1,ba===null&&(ba=[]),i=Fb(ba,i,a),a=we,(xt===null?a.memoizedState:xt.next)===null&&(a=a.alternate,z.H=a===null||a.memoizedState===null?Tv:yh),i}function Nc(i){if(i!==null&&typeof i=="object"){if(typeof i.then=="function")return Mo(i);if(i.$$typeof===U)return Ut(i)}throw Error(r(438,String(i)))}function ih(i){var a=null,l=we.updateQueue;if(l!==null&&(a=l.memoCache),a==null){var u=we.alternate;u!==null&&(u=u.updateQueue,u!==null&&(u=u.memoCache,u!=null&&(a={data:u.data.map(function(m){return m.slice()}),index:0})))}if(a==null&&(a={data:[],index:0}),l===null&&(l=Cc(),we.updateQueue=l),l.memoCache=a,l=a.data[a.index],l===void 0)for(l=a.data[a.index]=Array(i),u=0;u<i;u++)l[u]=P;return a.index++,l}function Br(i,a){return typeof a=="function"?a(i):a}function Oc(i){var a=gt();return ah(a,Ge,i)}function ah(i,a,l){var u=i.queue;if(u===null)throw Error(r(311));u.lastRenderedReducer=l;var m=i.baseQueue,y=u.pending;if(y!==null){if(m!==null){var S=m.next;m.next=y.next,y.next=S}a.baseQueue=m=y,u.pending=null}if(y=i.baseState,m===null)i.memoizedState=y;else{a=m.next;var j=S=null,V=null,Q=a,ne=!1;do{var ie=Q.lane&-536870913;if(ie!==Q.lane?(Ne&ie)===ie:($r&ie)===ie){var X=Q.revertLane;if(X===0)V!==null&&(V=V.next={lane:0,revertLane:0,gesture:null,action:Q.action,hasEagerState:Q.hasEagerState,eagerState:Q.eagerState,next:null}),ie===fa&&(ne=!0);else if(($r&X)===X){Q=Q.next,X===fa&&(ne=!0);continue}else ie={lane:0,revertLane:Q.revertLane,gesture:null,action:Q.action,hasEagerState:Q.hasEagerState,eagerState:Q.eagerState,next:null},V===null?(j=V=ie,S=y):V=V.next=ie,we.lanes|=X,Ss|=X;ie=Q.action,yi&&l(y,ie),y=Q.hasEagerState?Q.eagerState:l(y,ie)}else X={lane:ie,revertLane:Q.revertLane,gesture:Q.gesture,action:Q.action,hasEagerState:Q.hasEagerState,eagerState:Q.eagerState,next:null},V===null?(j=V=X,S=y):V=V.next=X,we.lanes|=ie,Ss|=ie;Q=Q.next}while(Q!==null&&Q!==a);if(V===null?S=y:V.next=j,!En(y,i.memoizedState)&&(wt=!0,ne&&(l=ha,l!==null)))throw l;i.memoizedState=y,i.baseState=S,i.baseQueue=V,u.lastRenderedState=y}return m===null&&(u.lanes=0),[i.memoizedState,u.dispatch]}function oh(i){var a=gt(),l=a.queue;if(l===null)throw Error(r(311));l.lastRenderedReducer=i;var u=l.dispatch,m=l.pending,y=a.memoizedState;if(m!==null){l.pending=null;var S=m=m.next;do y=i(y,S.action),S=S.next;while(S!==m);En(y,a.memoizedState)||(wt=!0),a.memoizedState=y,a.baseQueue===null&&(a.baseState=y),l.lastRenderedState=y}return[y,u]}function Jb(i,a,l){var u=we,m=gt(),y=De;if(y){if(l===void 0)throw Error(r(407));l=l()}else l=a();var S=!En((Ge||m).memoizedState,l);if(S&&(m.memoizedState=l,wt=!0),m=m.queue,uh(ev.bind(null,u,m,i),[i]),m.getSnapshot!==a||S||xt!==null&&xt.memoizedState.tag&1){if(u.flags|=2048,va(9,{destroy:void 0},Xb.bind(null,u,m,l,a),null),We===null)throw Error(r(349));y||($r&127)!==0||Qb(u,a,l)}return l}function Qb(i,a,l){i.flags|=16384,i={getSnapshot:a,value:l},a=we.updateQueue,a===null?(a=Cc(),we.updateQueue=a,a.stores=[i]):(l=a.stores,l===null?a.stores=[i]:l.push(i))}function Xb(i,a,l,u){a.value=l,a.getSnapshot=u,tv(a)&&nv(i)}function ev(i,a,l){return l(function(){tv(a)&&nv(i)})}function tv(i){var a=i.getSnapshot;i=i.value;try{var l=a();return!En(i,l)}catch{return!0}}function nv(i){var a=oi(i,2);a!==null&&mn(a,i,2)}function lh(i){var a=Xt();if(typeof i=="function"){var l=i;if(i=l(),yi){ls(!0);try{l()}finally{ls(!1)}}}return a.memoizedState=a.baseState=i,a.queue={pending:null,lanes:0,dispatch:null,lastRenderedReducer:Br,lastRenderedState:i},a}function rv(i,a,l,u){return i.baseState=l,ah(i,Ge,typeof u=="function"?u:Br)}function bC(i,a,l,u,m){if(Dc(i))throw Error(r(485));if(i=a.action,i!==null){var y={payload:m,action:i,next:null,isTransition:!0,status:"pending",value:null,reason:null,listeners:[],then:function(S){y.listeners.push(S)}};z.T!==null?l(!0):y.isTransition=!1,u(y),l=a.pending,l===null?(y.next=a.pending=y,sv(a,y)):(y.next=l.next,a.pending=l.next=y)}}function sv(i,a){var l=a.action,u=a.payload,m=i.state;if(a.isTransition){var y=z.T,S={};z.T=S;try{var j=l(m,u),V=z.S;V!==null&&V(S,j),iv(i,a,j)}catch(Q){ch(i,a,Q)}finally{y!==null&&S.types!==null&&(y.types=S.types),z.T=y}}else try{y=l(m,u),iv(i,a,y)}catch(Q){ch(i,a,Q)}}function iv(i,a,l){l!==null&&typeof l=="object"&&typeof l.then=="function"?l.then(function(u){av(i,a,u)},function(u){return ch(i,a,u)}):av(i,a,l)}function av(i,a,l){a.status="fulfilled",a.value=l,ov(a),i.state=l,a=i.pending,a!==null&&(l=a.next,l===a?i.pending=null:(l=l.next,a.next=l,sv(i,l)))}function ch(i,a,l){var u=i.pending;if(i.pending=null,u!==null){u=u.next;do a.status="rejected",a.reason=l,ov(a),a=a.next;while(a!==u)}i.action=null}function ov(i){i=i.listeners;for(var a=0;a<i.length;a++)(0,i[a])()}function lv(i,a){return a}function cv(i,a){if(De){var l=We.formState;if(l!==null){e:{var u=we;if(De){if(Xe){t:{for(var m=Xe,y=qn;m.nodeType!==8;){if(!y){m=null;break t}if(m=Vn(m.nextSibling),m===null){m=null;break t}}y=m.data,m=y==="F!"||y==="F"?m:null}if(m){Xe=Vn(m.nextSibling),u=m.data==="F!";break e}}hs(u)}u=!1}u&&(a=l[0])}}return l=Xt(),l.memoizedState=l.baseState=a,u={pending:null,lanes:0,dispatch:null,lastRenderedReducer:lv,lastRenderedState:a},l.queue=u,l=Cv.bind(null,we,u),u.dispatch=l,u=lh(!1),y=mh.bind(null,we,!1,u.queue),u=Xt(),m={state:a,dispatch:null,action:i,pending:null},u.queue=m,l=bC.bind(null,we,m,y,l),m.dispatch=l,u.memoizedState=i,[a,l,!1]}function uv(i){var a=gt();return dv(a,Ge,i)}function dv(i,a,l){if(a=ah(i,a,lv)[0],i=Oc(Br)[0],typeof a=="object"&&a!==null&&typeof a.then=="function")try{var u=Mo(a)}catch(S){throw S===pa?xc:S}else u=a;a=gt();var m=a.queue,y=m.dispatch;return l!==a.memoizedState&&(we.flags|=2048,va(9,{destroy:void 0},vC.bind(null,m,l),null)),[u,y,i]}function vC(i,a){i.action=a}function fv(i){var a=gt(),l=Ge;if(l!==null)return dv(a,l,i);gt(),a=a.memoizedState,l=gt();var u=l.queue.dispatch;return l.memoizedState=i,[a,u,!1]}function va(i,a,l,u){return i={tag:i,create:l,deps:u,inst:a,next:null},a=we.updateQueue,a===null&&(a=Cc(),we.updateQueue=a),l=a.lastEffect,l===null?a.lastEffect=i.next=i:(u=l.next,l.next=i,i.next=u,a.lastEffect=i),i}function hv(){return gt().memoizedState}function Tc(i,a,l,u){var m=Xt();we.flags|=i,m.memoizedState=va(1|a,{destroy:void 0},l,u===void 0?null:u)}function Rc(i,a,l,u){var m=gt();u=u===void 0?null:u;var y=m.memoizedState.inst;Ge!==null&&u!==null&&eh(u,Ge.memoizedState.deps)?m.memoizedState=va(a,y,l,u):(we.flags|=i,m.memoizedState=va(1|a,y,l,u))}function pv(i,a){Tc(8390656,8,i,a)}function uh(i,a){Rc(2048,8,i,a)}function xC(i){we.flags|=4;var a=we.updateQueue;if(a===null)a=Cc(),we.updateQueue=a,a.events=[i];else{var l=a.events;l===null?a.events=[i]:l.push(i)}}function mv(i){var a=gt().memoizedState;return xC({ref:a,nextImpl:i}),function(){if((Fe&2)!==0)throw Error(r(440));return a.impl.apply(void 0,arguments)}}function yv(i,a){return Rc(4,2,i,a)}function gv(i,a){return Rc(4,4,i,a)}function bv(i,a){if(typeof a=="function"){i=i();var l=a(i);return function(){typeof l=="function"?l():a(null)}}if(a!=null)return i=i(),a.current=i,function(){a.current=null}}function vv(i,a,l){l=l!=null?l.concat([i]):null,Rc(4,4,bv.bind(null,a,i),l)}function dh(){}function xv(i,a){var l=gt();a=a===void 0?null:a;var u=l.memoizedState;return a!==null&&eh(a,u[1])?u[0]:(l.memoizedState=[i,a],i)}function wv(i,a){var l=gt();a=a===void 0?null:a;var u=l.memoizedState;if(a!==null&&eh(a,u[1]))return u[0];if(u=i(),yi){ls(!0);try{i()}finally{ls(!1)}}return l.memoizedState=[u,a],u}function fh(i,a,l){return l===void 0||($r&1073741824)!==0&&(Ne&261930)===0?i.memoizedState=a:(i.memoizedState=l,i=S0(),we.lanes|=i,Ss|=i,l)}function Sv(i,a,l,u){return En(l,a)?l:ya.current!==null?(i=fh(i,l,u),En(i,a)||(wt=!0),i):($r&42)===0||($r&1073741824)!==0&&(Ne&261930)===0?(wt=!0,i.memoizedState=l):(i=S0(),we.lanes|=i,Ss|=i,a)}function _v(i,a,l,u,m){var y=$.p;$.p=y!==0&&8>y?y:8;var S=z.T,j={};z.T=j,mh(i,!1,a,l);try{var V=m(),Q=z.S;if(Q!==null&&Q(j,V),V!==null&&typeof V=="object"&&typeof V.then=="function"){var ne=mC(V,u);Lo(i,a,ne,On(i))}else Lo(i,a,u,On(i))}catch(ie){Lo(i,a,{then:function(){},status:"rejected",reason:ie},On())}finally{$.p=y,S!==null&&j.types!==null&&(S.types=j.types),z.T=S}}function wC(){}function hh(i,a,l,u){if(i.tag!==5)throw Error(r(476));var m=Ev(i).queue;_v(i,m,a,K,l===null?wC:function(){return Av(i),l(u)})}function Ev(i){var a=i.memoizedState;if(a!==null)return a;a={memoizedState:K,baseState:K,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Br,lastRenderedState:K},next:null};var l={};return a.next={memoizedState:l,baseState:l,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Br,lastRenderedState:l},next:null},i.memoizedState=a,i=i.alternate,i!==null&&(i.memoizedState=a),a}function Av(i){var a=Ev(i);a.next===null&&(a=i.alternate.memoizedState),Lo(i,a.next.queue,{},On())}function ph(){return Ut(Xo)}function jv(){return gt().memoizedState}function kv(){return gt().memoizedState}function SC(i){for(var a=i.return;a!==null;){switch(a.tag){case 24:case 3:var l=On();i=ys(l);var u=gs(a,i,l);u!==null&&(mn(u,a,l),To(u,a,l)),a={cache:zf()},i.payload=a;return}a=a.return}}function _C(i,a,l){var u=On();l={lane:u,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null},Dc(i)?Nv(a,l):(l=Rf(i,a,l,u),l!==null&&(mn(l,i,u),Ov(l,a,u)))}function Cv(i,a,l){var u=On();Lo(i,a,l,u)}function Lo(i,a,l,u){var m={lane:u,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null};if(Dc(i))Nv(a,m);else{var y=i.alternate;if(i.lanes===0&&(y===null||y.lanes===0)&&(y=a.lastRenderedReducer,y!==null))try{var S=a.lastRenderedState,j=y(S,l);if(m.hasEagerState=!0,m.eagerState=j,En(j,S))return hc(i,a,m,0),We===null&&fc(),!1}catch{}finally{}if(l=Rf(i,a,m,u),l!==null)return mn(l,i,u),Ov(l,a,u),!0}return!1}function mh(i,a,l,u){if(u={lane:2,revertLane:Kh(),gesture:null,action:u,hasEagerState:!1,eagerState:null,next:null},Dc(i)){if(a)throw Error(r(479))}else a=Rf(i,l,u,2),a!==null&&mn(a,i,2)}function Dc(i){var a=i.alternate;return i===we||a!==null&&a===we}function Nv(i,a){ga=jc=!0;var l=i.pending;l===null?a.next=a:(a.next=l.next,l.next=a),i.pending=a}function Ov(i,a,l){if((l&4194048)!==0){var u=a.lanes;u&=i.pendingLanes,l|=u,a.lanes=l,Mg(i,l)}}var Uo={readContext:Ut,use:Nc,useCallback:ot,useContext:ot,useEffect:ot,useImperativeHandle:ot,useLayoutEffect:ot,useInsertionEffect:ot,useMemo:ot,useReducer:ot,useRef:ot,useState:ot,useDebugValue:ot,useDeferredValue:ot,useTransition:ot,useSyncExternalStore:ot,useId:ot,useHostTransitionStatus:ot,useFormState:ot,useActionState:ot,useOptimistic:ot,useMemoCache:ot,useCacheRefresh:ot};Uo.useEffectEvent=ot;var Tv={readContext:Ut,use:Nc,useCallback:function(i,a){return Xt().memoizedState=[i,a===void 0?null:a],i},useContext:Ut,useEffect:pv,useImperativeHandle:function(i,a,l){l=l!=null?l.concat([i]):null,Tc(4194308,4,bv.bind(null,a,i),l)},useLayoutEffect:function(i,a){return Tc(4194308,4,i,a)},useInsertionEffect:function(i,a){Tc(4,2,i,a)},useMemo:function(i,a){var l=Xt();a=a===void 0?null:a;var u=i();if(yi){ls(!0);try{i()}finally{ls(!1)}}return l.memoizedState=[u,a],u},useReducer:function(i,a,l){var u=Xt();if(l!==void 0){var m=l(a);if(yi){ls(!0);try{l(a)}finally{ls(!1)}}}else m=a;return u.memoizedState=u.baseState=m,i={pending:null,lanes:0,dispatch:null,lastRenderedReducer:i,lastRenderedState:m},u.queue=i,i=i.dispatch=_C.bind(null,we,i),[u.memoizedState,i]},useRef:function(i){var a=Xt();return i={current:i},a.memoizedState=i},useState:function(i){i=lh(i);var a=i.queue,l=Cv.bind(null,we,a);return a.dispatch=l,[i.memoizedState,l]},useDebugValue:dh,useDeferredValue:function(i,a){var l=Xt();return fh(l,i,a)},useTransition:function(){var i=lh(!1);return i=_v.bind(null,we,i.queue,!0,!1),Xt().memoizedState=i,[!1,i]},useSyncExternalStore:function(i,a,l){var u=we,m=Xt();if(De){if(l===void 0)throw Error(r(407));l=l()}else{if(l=a(),We===null)throw Error(r(349));(Ne&127)!==0||Qb(u,a,l)}m.memoizedState=l;var y={value:l,getSnapshot:a};return m.queue=y,pv(ev.bind(null,u,y,i),[i]),u.flags|=2048,va(9,{destroy:void 0},Xb.bind(null,u,y,l,a),null),l},useId:function(){var i=Xt(),a=We.identifierPrefix;if(De){var l=hr,u=fr;l=(u&~(1<<32-_n(u)-1)).toString(32)+l,a="_"+a+"R_"+l,l=kc++,0<l&&(a+="H"+l.toString(32)),a+="_"}else l=yC++,a="_"+a+"r_"+l.toString(32)+"_";return i.memoizedState=a},useHostTransitionStatus:ph,useFormState:cv,useActionState:cv,useOptimistic:function(i){var a=Xt();a.memoizedState=a.baseState=i;var l={pending:null,lanes:0,dispatch:null,lastRenderedReducer:null,lastRenderedState:null};return a.queue=l,a=mh.bind(null,we,!0,l),l.dispatch=a,[i,a]},useMemoCache:ih,useCacheRefresh:function(){return Xt().memoizedState=SC.bind(null,we)},useEffectEvent:function(i){var a=Xt(),l={impl:i};return a.memoizedState=l,function(){if((Fe&2)!==0)throw Error(r(440));return l.impl.apply(void 0,arguments)}}},yh={readContext:Ut,use:Nc,useCallback:xv,useContext:Ut,useEffect:uh,useImperativeHandle:vv,useInsertionEffect:yv,useLayoutEffect:gv,useMemo:wv,useReducer:Oc,useRef:hv,useState:function(){return Oc(Br)},useDebugValue:dh,useDeferredValue:function(i,a){var l=gt();return Sv(l,Ge.memoizedState,i,a)},useTransition:function(){var i=Oc(Br)[0],a=gt().memoizedState;return[typeof i=="boolean"?i:Mo(i),a]},useSyncExternalStore:Jb,useId:jv,useHostTransitionStatus:ph,useFormState:uv,useActionState:uv,useOptimistic:function(i,a){var l=gt();return rv(l,Ge,i,a)},useMemoCache:ih,useCacheRefresh:kv};yh.useEffectEvent=mv;var Rv={readContext:Ut,use:Nc,useCallback:xv,useContext:Ut,useEffect:uh,useImperativeHandle:vv,useInsertionEffect:yv,useLayoutEffect:gv,useMemo:wv,useReducer:oh,useRef:hv,useState:function(){return oh(Br)},useDebugValue:dh,useDeferredValue:function(i,a){var l=gt();return Ge===null?fh(l,i,a):Sv(l,Ge.memoizedState,i,a)},useTransition:function(){var i=oh(Br)[0],a=gt().memoizedState;return[typeof i=="boolean"?i:Mo(i),a]},useSyncExternalStore:Jb,useId:jv,useHostTransitionStatus:ph,useFormState:fv,useActionState:fv,useOptimistic:function(i,a){var l=gt();return Ge!==null?rv(l,Ge,i,a):(l.baseState=i,[i,l.queue.dispatch])},useMemoCache:ih,useCacheRefresh:kv};Rv.useEffectEvent=mv;function gh(i,a,l,u){a=i.memoizedState,l=l(u,a),l=l==null?a:b({},a,l),i.memoizedState=l,i.lanes===0&&(i.updateQueue.baseState=l)}var bh={enqueueSetState:function(i,a,l){i=i._reactInternals;var u=On(),m=ys(u);m.payload=a,l!=null&&(m.callback=l),a=gs(i,m,u),a!==null&&(mn(a,i,u),To(a,i,u))},enqueueReplaceState:function(i,a,l){i=i._reactInternals;var u=On(),m=ys(u);m.tag=1,m.payload=a,l!=null&&(m.callback=l),a=gs(i,m,u),a!==null&&(mn(a,i,u),To(a,i,u))},enqueueForceUpdate:function(i,a){i=i._reactInternals;var l=On(),u=ys(l);u.tag=2,a!=null&&(u.callback=a),a=gs(i,u,l),a!==null&&(mn(a,i,l),To(a,i,l))}};function Dv(i,a,l,u,m,y,S){return i=i.stateNode,typeof i.shouldComponentUpdate=="function"?i.shouldComponentUpdate(u,y,S):a.prototype&&a.prototype.isPureReactComponent?!_o(l,u)||!_o(m,y):!0}function Iv(i,a,l,u){i=a.state,typeof a.componentWillReceiveProps=="function"&&a.componentWillReceiveProps(l,u),typeof a.UNSAFE_componentWillReceiveProps=="function"&&a.UNSAFE_componentWillReceiveProps(l,u),a.state!==i&&bh.enqueueReplaceState(a,a.state,null)}function gi(i,a){var l=a;if("ref"in a){l={};for(var u in a)u!=="ref"&&(l[u]=a[u])}if(i=i.defaultProps){l===a&&(l=b({},l));for(var m in i)l[m]===void 0&&(l[m]=i[m])}return l}function Mv(i){dc(i)}function Lv(i){console.error(i)}function Uv(i){dc(i)}function Ic(i,a){try{var l=i.onUncaughtError;l(a.value,{componentStack:a.stack})}catch(u){setTimeout(function(){throw u})}}function $v(i,a,l){try{var u=i.onCaughtError;u(l.value,{componentStack:l.stack,errorBoundary:a.tag===1?a.stateNode:null})}catch(m){setTimeout(function(){throw m})}}function vh(i,a,l){return l=ys(l),l.tag=3,l.payload={element:null},l.callback=function(){Ic(i,a)},l}function Bv(i){return i=ys(i),i.tag=3,i}function Fv(i,a,l,u){var m=l.type.getDerivedStateFromError;if(typeof m=="function"){var y=u.value;i.payload=function(){return m(y)},i.callback=function(){$v(a,l,u)}}var S=l.stateNode;S!==null&&typeof S.componentDidCatch=="function"&&(i.callback=function(){$v(a,l,u),typeof m!="function"&&(_s===null?_s=new Set([this]):_s.add(this));var j=u.stack;this.componentDidCatch(u.value,{componentStack:j!==null?j:""})})}function EC(i,a,l,u,m){if(l.flags|=32768,u!==null&&typeof u=="object"&&typeof u.then=="function"){if(a=l.alternate,a!==null&&da(a,l,m,!0),l=jn.current,l!==null){switch(l.tag){case 31:case 13:return zn===null?Gc():l.alternate===null&<===0&&(lt=3),l.flags&=-257,l.flags|=65536,l.lanes=m,u===wc?l.flags|=16384:(a=l.updateQueue,a===null?l.updateQueue=new Set([u]):a.add(u),Vh(i,u,m)),!1;case 22:return l.flags|=65536,u===wc?l.flags|=16384:(a=l.updateQueue,a===null?(a={transitions:null,markerInstances:null,retryQueue:new Set([u])},l.updateQueue=a):(l=a.retryQueue,l===null?a.retryQueue=new Set([u]):l.add(u)),Vh(i,u,m)),!1}throw Error(r(435,l.tag))}return Vh(i,u,m),Gc(),!1}if(De)return a=jn.current,a!==null?((a.flags&65536)===0&&(a.flags|=256),a.flags|=65536,a.lanes=m,u!==$f&&(i=Error(r(422),{cause:u}),jo(Bn(i,l)))):(u!==$f&&(a=Error(r(423),{cause:u}),jo(Bn(a,l))),i=i.current.alternate,i.flags|=65536,m&=-m,i.lanes|=m,u=Bn(u,l),m=vh(i.stateNode,u,m),Zf(i,m),lt!==4&&(lt=2)),!1;var y=Error(r(520),{cause:u});if(y=Bn(y,l),Ho===null?Ho=[y]:Ho.push(y),lt!==4&&(lt=2),a===null)return!0;u=Bn(u,l),l=a;do{switch(l.tag){case 3:return l.flags|=65536,i=m&-m,l.lanes|=i,i=vh(l.stateNode,u,i),Zf(l,i),!1;case 1:if(a=l.type,y=l.stateNode,(l.flags&128)===0&&(typeof a.getDerivedStateFromError=="function"||y!==null&&typeof y.componentDidCatch=="function"&&(_s===null||!_s.has(y))))return l.flags|=65536,m&=-m,l.lanes|=m,m=Bv(m),Fv(m,i,l,u),Zf(l,m),!1}l=l.return}while(l!==null);return!1}var xh=Error(r(461)),wt=!1;function $t(i,a,l,u){a.child=i===null?Vb(a,null,l,u):mi(a,i.child,l,u)}function Pv(i,a,l,u,m){l=l.render;var y=a.ref;if("ref"in u){var S={};for(var j in u)j!=="ref"&&(S[j]=u[j])}else S=u;return di(a),u=th(i,a,l,S,y,m),j=nh(),i!==null&&!wt?(rh(i,a,m),Fr(i,a,m)):(De&&j&&Lf(a),a.flags|=1,$t(i,a,u,m),a.child)}function qv(i,a,l,u,m){if(i===null){var y=l.type;return typeof y=="function"&&!Df(y)&&y.defaultProps===void 0&&l.compare===null?(a.tag=15,a.type=y,zv(i,a,y,u,m)):(i=mc(l.type,null,u,a,a.mode,m),i.ref=a.ref,i.return=a,a.child=i)}if(y=i.child,!Ch(i,m)){var S=y.memoizedProps;if(l=l.compare,l=l!==null?l:_o,l(S,u)&&i.ref===a.ref)return Fr(i,a,m)}return a.flags|=1,i=Ir(y,u),i.ref=a.ref,i.return=a,a.child=i}function zv(i,a,l,u,m){if(i!==null){var y=i.memoizedProps;if(_o(y,u)&&i.ref===a.ref)if(wt=!1,a.pendingProps=u=y,Ch(i,m))(i.flags&131072)!==0&&(wt=!0);else return a.lanes=i.lanes,Fr(i,a,m)}return wh(i,a,l,u,m)}function Vv(i,a,l,u){var m=u.children,y=i!==null?i.memoizedState:null;if(i===null&&a.stateNode===null&&(a.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),u.mode==="hidden"){if((a.flags&128)!==0){if(y=y!==null?y.baseLanes|l:l,i!==null){for(u=a.child=i.child,m=0;u!==null;)m=m|u.lanes|u.childLanes,u=u.sibling;u=m&~y}else u=0,a.child=null;return Hv(i,a,y,l,u)}if((l&536870912)!==0)a.memoizedState={baseLanes:0,cachePool:null},i!==null&&vc(a,y!==null?y.cachePool:null),y!==null?Kb(a,y):Jf(),Yb(a);else return u=a.lanes=536870912,Hv(i,a,y!==null?y.baseLanes|l:l,l,u)}else y!==null?(vc(a,y.cachePool),Kb(a,y),vs(),a.memoizedState=null):(i!==null&&vc(a,null),Jf(),vs());return $t(i,a,m,l),a.child}function $o(i,a){return i!==null&&i.tag===22||a.stateNode!==null||(a.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),a.sibling}function Hv(i,a,l,u,m){var y=Hf();return y=y===null?null:{parent:vt._currentValue,pool:y},a.memoizedState={baseLanes:l,cachePool:y},i!==null&&vc(a,null),Jf(),Yb(a),i!==null&&da(i,a,u,!0),a.childLanes=m,null}function Mc(i,a){return a=Uc({mode:a.mode,children:a.children},i.mode),a.ref=i.ref,i.child=a,a.return=i,a}function Gv(i,a,l){return mi(a,i.child,null,l),i=Mc(a,a.pendingProps),i.flags|=2,kn(a),a.memoizedState=null,i}function AC(i,a,l){var u=a.pendingProps,m=(a.flags&128)!==0;if(a.flags&=-129,i===null){if(De){if(u.mode==="hidden")return i=Mc(a,u),a.lanes=536870912,$o(null,i);if(Xf(a),(i=Xe)?(i=sx(i,qn),i=i!==null&&i.data==="&"?i:null,i!==null&&(a.memoizedState={dehydrated:i,treeContext:ds!==null?{id:fr,overflow:hr}:null,retryLane:536870912,hydrationErrors:null},l=Nb(i),l.return=a,a.child=l,Lt=a,Xe=null)):i=null,i===null)throw hs(a);return a.lanes=536870912,null}return Mc(a,u)}var y=i.memoizedState;if(y!==null){var S=y.dehydrated;if(Xf(a),m)if(a.flags&256)a.flags&=-257,a=Gv(i,a,l);else if(a.memoizedState!==null)a.child=i.child,a.flags|=128,a=null;else throw Error(r(558));else if(wt||da(i,a,l,!1),m=(l&i.childLanes)!==0,wt||m){if(u=We,u!==null&&(S=Lg(u,l),S!==0&&S!==y.retryLane))throw y.retryLane=S,oi(i,S),mn(u,i,S),xh;Gc(),a=Gv(i,a,l)}else i=y.treeContext,Xe=Vn(S.nextSibling),Lt=a,De=!0,fs=null,qn=!1,i!==null&&Rb(a,i),a=Mc(a,u),a.flags|=4096;return a}return i=Ir(i.child,{mode:u.mode,children:u.children}),i.ref=a.ref,a.child=i,i.return=a,i}function Lc(i,a){var l=a.ref;if(l===null)i!==null&&i.ref!==null&&(a.flags|=4194816);else{if(typeof l!="function"&&typeof l!="object")throw Error(r(284));(i===null||i.ref!==l)&&(a.flags|=4194816)}}function wh(i,a,l,u,m){return di(a),l=th(i,a,l,u,void 0,m),u=nh(),i!==null&&!wt?(rh(i,a,m),Fr(i,a,m)):(De&&u&&Lf(a),a.flags|=1,$t(i,a,l,m),a.child)}function Kv(i,a,l,u,m,y){return di(a),a.updateQueue=null,l=Wb(a,u,l,m),Zb(i),u=nh(),i!==null&&!wt?(rh(i,a,y),Fr(i,a,y)):(De&&u&&Lf(a),a.flags|=1,$t(i,a,l,y),a.child)}function Yv(i,a,l,u,m){if(di(a),a.stateNode===null){var y=oa,S=l.contextType;typeof S=="object"&&S!==null&&(y=Ut(S)),y=new l(u,y),a.memoizedState=y.state!==null&&y.state!==void 0?y.state:null,y.updater=bh,a.stateNode=y,y._reactInternals=a,y=a.stateNode,y.props=u,y.state=a.memoizedState,y.refs={},Kf(a),S=l.contextType,y.context=typeof S=="object"&&S!==null?Ut(S):oa,y.state=a.memoizedState,S=l.getDerivedStateFromProps,typeof S=="function"&&(gh(a,l,S,u),y.state=a.memoizedState),typeof l.getDerivedStateFromProps=="function"||typeof y.getSnapshotBeforeUpdate=="function"||typeof y.UNSAFE_componentWillMount!="function"&&typeof y.componentWillMount!="function"||(S=y.state,typeof y.componentWillMount=="function"&&y.componentWillMount(),typeof y.UNSAFE_componentWillMount=="function"&&y.UNSAFE_componentWillMount(),S!==y.state&&bh.enqueueReplaceState(y,y.state,null),Do(a,u,y,m),Ro(),y.state=a.memoizedState),typeof y.componentDidMount=="function"&&(a.flags|=4194308),u=!0}else if(i===null){y=a.stateNode;var j=a.memoizedProps,V=gi(l,j);y.props=V;var Q=y.context,ne=l.contextType;S=oa,typeof ne=="object"&&ne!==null&&(S=Ut(ne));var ie=l.getDerivedStateFromProps;ne=typeof ie=="function"||typeof y.getSnapshotBeforeUpdate=="function",j=a.pendingProps!==j,ne||typeof y.UNSAFE_componentWillReceiveProps!="function"&&typeof y.componentWillReceiveProps!="function"||(j||Q!==S)&&Iv(a,y,u,S),ms=!1;var X=a.memoizedState;y.state=X,Do(a,u,y,m),Ro(),Q=a.memoizedState,j||X!==Q||ms?(typeof ie=="function"&&(gh(a,l,ie,u),Q=a.memoizedState),(V=ms||Dv(a,l,V,u,X,Q,S))?(ne||typeof y.UNSAFE_componentWillMount!="function"&&typeof y.componentWillMount!="function"||(typeof y.componentWillMount=="function"&&y.componentWillMount(),typeof y.UNSAFE_componentWillMount=="function"&&y.UNSAFE_componentWillMount()),typeof y.componentDidMount=="function"&&(a.flags|=4194308)):(typeof y.componentDidMount=="function"&&(a.flags|=4194308),a.memoizedProps=u,a.memoizedState=Q),y.props=u,y.state=Q,y.context=S,u=V):(typeof y.componentDidMount=="function"&&(a.flags|=4194308),u=!1)}else{y=a.stateNode,Yf(i,a),S=a.memoizedProps,ne=gi(l,S),y.props=ne,ie=a.pendingProps,X=y.context,Q=l.contextType,V=oa,typeof Q=="object"&&Q!==null&&(V=Ut(Q)),j=l.getDerivedStateFromProps,(Q=typeof j=="function"||typeof y.getSnapshotBeforeUpdate=="function")||typeof y.UNSAFE_componentWillReceiveProps!="function"&&typeof y.componentWillReceiveProps!="function"||(S!==ie||X!==V)&&Iv(a,y,u,V),ms=!1,X=a.memoizedState,y.state=X,Do(a,u,y,m),Ro();var te=a.memoizedState;S!==ie||X!==te||ms||i!==null&&i.dependencies!==null&&gc(i.dependencies)?(typeof j=="function"&&(gh(a,l,j,u),te=a.memoizedState),(ne=ms||Dv(a,l,ne,u,X,te,V)||i!==null&&i.dependencies!==null&&gc(i.dependencies))?(Q||typeof y.UNSAFE_componentWillUpdate!="function"&&typeof y.componentWillUpdate!="function"||(typeof y.componentWillUpdate=="function"&&y.componentWillUpdate(u,te,V),typeof y.UNSAFE_componentWillUpdate=="function"&&y.UNSAFE_componentWillUpdate(u,te,V)),typeof y.componentDidUpdate=="function"&&(a.flags|=4),typeof y.getSnapshotBeforeUpdate=="function"&&(a.flags|=1024)):(typeof y.componentDidUpdate!="function"||S===i.memoizedProps&&X===i.memoizedState||(a.flags|=4),typeof y.getSnapshotBeforeUpdate!="function"||S===i.memoizedProps&&X===i.memoizedState||(a.flags|=1024),a.memoizedProps=u,a.memoizedState=te),y.props=u,y.state=te,y.context=V,u=ne):(typeof y.componentDidUpdate!="function"||S===i.memoizedProps&&X===i.memoizedState||(a.flags|=4),typeof y.getSnapshotBeforeUpdate!="function"||S===i.memoizedProps&&X===i.memoizedState||(a.flags|=1024),u=!1)}return y=u,Lc(i,a),u=(a.flags&128)!==0,y||u?(y=a.stateNode,l=u&&typeof l.getDerivedStateFromError!="function"?null:y.render(),a.flags|=1,i!==null&&u?(a.child=mi(a,i.child,null,m),a.child=mi(a,null,l,m)):$t(i,a,l,m),a.memoizedState=y.state,i=a.child):i=Fr(i,a,m),i}function Zv(i,a,l,u){return ci(),a.flags|=256,$t(i,a,l,u),a.child}var Sh={dehydrated:null,treeContext:null,retryLane:0,hydrationErrors:null};function _h(i){return{baseLanes:i,cachePool:$b()}}function Eh(i,a,l){return i=i!==null?i.childLanes&~l:0,a&&(i|=Nn),i}function Wv(i,a,l){var u=a.pendingProps,m=!1,y=(a.flags&128)!==0,S;if((S=y)||(S=i!==null&&i.memoizedState===null?!1:(yt.current&2)!==0),S&&(m=!0,a.flags&=-129),S=(a.flags&32)!==0,a.flags&=-33,i===null){if(De){if(m?bs(a):vs(),(i=Xe)?(i=sx(i,qn),i=i!==null&&i.data!=="&"?i:null,i!==null&&(a.memoizedState={dehydrated:i,treeContext:ds!==null?{id:fr,overflow:hr}:null,retryLane:536870912,hydrationErrors:null},l=Nb(i),l.return=a,a.child=l,Lt=a,Xe=null)):i=null,i===null)throw hs(a);return ap(i)?a.lanes=32:a.lanes=536870912,null}var j=u.children;return u=u.fallback,m?(vs(),m=a.mode,j=Uc({mode:"hidden",children:j},m),u=li(u,m,l,null),j.return=a,u.return=a,j.sibling=u,a.child=j,u=a.child,u.memoizedState=_h(l),u.childLanes=Eh(i,S,l),a.memoizedState=Sh,$o(null,u)):(bs(a),Ah(a,j))}var V=i.memoizedState;if(V!==null&&(j=V.dehydrated,j!==null)){if(y)a.flags&256?(bs(a),a.flags&=-257,a=jh(i,a,l)):a.memoizedState!==null?(vs(),a.child=i.child,a.flags|=128,a=null):(vs(),j=u.fallback,m=a.mode,u=Uc({mode:"visible",children:u.children},m),j=li(j,m,l,null),j.flags|=2,u.return=a,j.return=a,u.sibling=j,a.child=u,mi(a,i.child,null,l),u=a.child,u.memoizedState=_h(l),u.childLanes=Eh(i,S,l),a.memoizedState=Sh,a=$o(null,u));else if(bs(a),ap(j)){if(S=j.nextSibling&&j.nextSibling.dataset,S)var Q=S.dgst;S=Q,u=Error(r(419)),u.stack="",u.digest=S,jo({value:u,source:null,stack:null}),a=jh(i,a,l)}else if(wt||da(i,a,l,!1),S=(l&i.childLanes)!==0,wt||S){if(S=We,S!==null&&(u=Lg(S,l),u!==0&&u!==V.retryLane))throw V.retryLane=u,oi(i,u),mn(S,i,u),xh;ip(j)||Gc(),a=jh(i,a,l)}else ip(j)?(a.flags|=192,a.child=i.child,a=null):(i=V.treeContext,Xe=Vn(j.nextSibling),Lt=a,De=!0,fs=null,qn=!1,i!==null&&Rb(a,i),a=Ah(a,u.children),a.flags|=4096);return a}return m?(vs(),j=u.fallback,m=a.mode,V=i.child,Q=V.sibling,u=Ir(V,{mode:"hidden",children:u.children}),u.subtreeFlags=V.subtreeFlags&65011712,Q!==null?j=Ir(Q,j):(j=li(j,m,l,null),j.flags|=2),j.return=a,u.return=a,u.sibling=j,a.child=u,$o(null,u),u=a.child,j=i.child.memoizedState,j===null?j=_h(l):(m=j.cachePool,m!==null?(V=vt._currentValue,m=m.parent!==V?{parent:V,pool:V}:m):m=$b(),j={baseLanes:j.baseLanes|l,cachePool:m}),u.memoizedState=j,u.childLanes=Eh(i,S,l),a.memoizedState=Sh,$o(i.child,u)):(bs(a),l=i.child,i=l.sibling,l=Ir(l,{mode:"visible",children:u.children}),l.return=a,l.sibling=null,i!==null&&(S=a.deletions,S===null?(a.deletions=[i],a.flags|=16):S.push(i)),a.child=l,a.memoizedState=null,l)}function Ah(i,a){return a=Uc({mode:"visible",children:a},i.mode),a.return=i,i.child=a}function Uc(i,a){return i=An(22,i,null,a),i.lanes=0,i}function jh(i,a,l){return mi(a,i.child,null,l),i=Ah(a,a.pendingProps.children),i.flags|=2,a.memoizedState=null,i}function Jv(i,a,l){i.lanes|=a;var u=i.alternate;u!==null&&(u.lanes|=a),Pf(i.return,a,l)}function kh(i,a,l,u,m,y){var S=i.memoizedState;S===null?i.memoizedState={isBackwards:a,rendering:null,renderingStartTime:0,last:u,tail:l,tailMode:m,treeForkCount:y}:(S.isBackwards=a,S.rendering=null,S.renderingStartTime=0,S.last=u,S.tail=l,S.tailMode=m,S.treeForkCount=y)}function Qv(i,a,l){var u=a.pendingProps,m=u.revealOrder,y=u.tail;u=u.children;var S=yt.current,j=(S&2)!==0;if(j?(S=S&1|2,a.flags|=128):S&=1,ae(yt,S),$t(i,a,u,l),u=De?Ao:0,!j&&i!==null&&(i.flags&128)!==0)e:for(i=a.child;i!==null;){if(i.tag===13)i.memoizedState!==null&&Jv(i,l,a);else if(i.tag===19)Jv(i,l,a);else if(i.child!==null){i.child.return=i,i=i.child;continue}if(i===a)break e;for(;i.sibling===null;){if(i.return===null||i.return===a)break e;i=i.return}i.sibling.return=i.return,i=i.sibling}switch(m){case"forwards":for(l=a.child,m=null;l!==null;)i=l.alternate,i!==null&&Ac(i)===null&&(m=l),l=l.sibling;l=m,l===null?(m=a.child,a.child=null):(m=l.sibling,l.sibling=null),kh(a,!1,m,l,y,u);break;case"backwards":case"unstable_legacy-backwards":for(l=null,m=a.child,a.child=null;m!==null;){if(i=m.alternate,i!==null&&Ac(i)===null){a.child=m;break}i=m.sibling,m.sibling=l,l=m,m=i}kh(a,!0,l,null,y,u);break;case"together":kh(a,!1,null,null,void 0,u);break;default:a.memoizedState=null}return a.child}function Fr(i,a,l){if(i!==null&&(a.dependencies=i.dependencies),Ss|=a.lanes,(l&a.childLanes)===0)if(i!==null){if(da(i,a,l,!1),(l&a.childLanes)===0)return null}else return null;if(i!==null&&a.child!==i.child)throw Error(r(153));if(a.child!==null){for(i=a.child,l=Ir(i,i.pendingProps),a.child=l,l.return=a;i.sibling!==null;)i=i.sibling,l=l.sibling=Ir(i,i.pendingProps),l.return=a;l.sibling=null}return a.child}function Ch(i,a){return(i.lanes&a)!==0?!0:(i=i.dependencies,!!(i!==null&&gc(i)))}function jC(i,a,l){switch(a.tag){case 3:Qt(a,a.stateNode.containerInfo),ps(a,vt,i.memoizedState.cache),ci();break;case 27:case 5:co(a);break;case 4:Qt(a,a.stateNode.containerInfo);break;case 10:ps(a,a.type,a.memoizedProps.value);break;case 31:if(a.memoizedState!==null)return a.flags|=128,Xf(a),null;break;case 13:var u=a.memoizedState;if(u!==null)return u.dehydrated!==null?(bs(a),a.flags|=128,null):(l&a.child.childLanes)!==0?Wv(i,a,l):(bs(a),i=Fr(i,a,l),i!==null?i.sibling:null);bs(a);break;case 19:var m=(i.flags&128)!==0;if(u=(l&a.childLanes)!==0,u||(da(i,a,l,!1),u=(l&a.childLanes)!==0),m){if(u)return Qv(i,a,l);a.flags|=128}if(m=a.memoizedState,m!==null&&(m.rendering=null,m.tail=null,m.lastEffect=null),ae(yt,yt.current),u)break;return null;case 22:return a.lanes=0,Vv(i,a,l,a.pendingProps);case 24:ps(a,vt,i.memoizedState.cache)}return Fr(i,a,l)}function Xv(i,a,l){if(i!==null)if(i.memoizedProps!==a.pendingProps)wt=!0;else{if(!Ch(i,l)&&(a.flags&128)===0)return wt=!1,jC(i,a,l);wt=(i.flags&131072)!==0}else wt=!1,De&&(a.flags&1048576)!==0&&Tb(a,Ao,a.index);switch(a.lanes=0,a.tag){case 16:e:{var u=a.pendingProps;if(i=hi(a.elementType),a.type=i,typeof i=="function")Df(i)?(u=gi(i,u),a.tag=1,a=Yv(null,a,i,u,l)):(a.tag=0,a=wh(null,a,i,u,l));else{if(i!=null){var m=i.$$typeof;if(m===q){a.tag=11,a=Pv(null,a,i,u,l);break e}else if(m===M){a.tag=14,a=qv(null,a,i,u,l);break e}}throw a=O(i)||i,Error(r(306,a,""))}}return a;case 0:return wh(i,a,a.type,a.pendingProps,l);case 1:return u=a.type,m=gi(u,a.pendingProps),Yv(i,a,u,m,l);case 3:e:{if(Qt(a,a.stateNode.containerInfo),i===null)throw Error(r(387));u=a.pendingProps;var y=a.memoizedState;m=y.element,Yf(i,a),Do(a,u,null,l);var S=a.memoizedState;if(u=S.cache,ps(a,vt,u),u!==y.cache&&qf(a,[vt],l,!0),Ro(),u=S.element,y.isDehydrated)if(y={element:u,isDehydrated:!1,cache:S.cache},a.updateQueue.baseState=y,a.memoizedState=y,a.flags&256){a=Zv(i,a,u,l);break e}else if(u!==m){m=Bn(Error(r(424)),a),jo(m),a=Zv(i,a,u,l);break e}else{switch(i=a.stateNode.containerInfo,i.nodeType){case 9:i=i.body;break;default:i=i.nodeName==="HTML"?i.ownerDocument.body:i}for(Xe=Vn(i.firstChild),Lt=a,De=!0,fs=null,qn=!0,l=Vb(a,null,u,l),a.child=l;l;)l.flags=l.flags&-3|4096,l=l.sibling}else{if(ci(),u===m){a=Fr(i,a,l);break e}$t(i,a,u,l)}a=a.child}return a;case 26:return Lc(i,a),i===null?(l=ux(a.type,null,a.pendingProps,null))?a.memoizedState=l:De||(l=a.type,i=a.pendingProps,u=Xc(je.current).createElement(l),u[Mt]=a,u[cn]=i,Bt(u,l,i),Tt(u),a.stateNode=u):a.memoizedState=ux(a.type,i.memoizedProps,a.pendingProps,i.memoizedState),null;case 27:return co(a),i===null&&De&&(u=a.stateNode=ox(a.type,a.pendingProps,je.current),Lt=a,qn=!0,m=Xe,ks(a.type)?(op=m,Xe=Vn(u.firstChild)):Xe=m),$t(i,a,a.pendingProps.children,l),Lc(i,a),i===null&&(a.flags|=4194304),a.child;case 5:return i===null&&De&&((m=u=Xe)&&(u=nN(u,a.type,a.pendingProps,qn),u!==null?(a.stateNode=u,Lt=a,Xe=Vn(u.firstChild),qn=!1,m=!0):m=!1),m||hs(a)),co(a),m=a.type,y=a.pendingProps,S=i!==null?i.memoizedProps:null,u=y.children,np(m,y)?u=null:S!==null&&np(m,S)&&(a.flags|=32),a.memoizedState!==null&&(m=th(i,a,gC,null,null,l),Xo._currentValue=m),Lc(i,a),$t(i,a,u,l),a.child;case 6:return i===null&&De&&((i=l=Xe)&&(l=rN(l,a.pendingProps,qn),l!==null?(a.stateNode=l,Lt=a,Xe=null,i=!0):i=!1),i||hs(a)),null;case 13:return Wv(i,a,l);case 4:return Qt(a,a.stateNode.containerInfo),u=a.pendingProps,i===null?a.child=mi(a,null,u,l):$t(i,a,u,l),a.child;case 11:return Pv(i,a,a.type,a.pendingProps,l);case 7:return $t(i,a,a.pendingProps,l),a.child;case 8:return $t(i,a,a.pendingProps.children,l),a.child;case 12:return $t(i,a,a.pendingProps.children,l),a.child;case 10:return u=a.pendingProps,ps(a,a.type,u.value),$t(i,a,u.children,l),a.child;case 9:return m=a.type._context,u=a.pendingProps.children,di(a),m=Ut(m),u=u(m),a.flags|=1,$t(i,a,u,l),a.child;case 14:return qv(i,a,a.type,a.pendingProps,l);case 15:return zv(i,a,a.type,a.pendingProps,l);case 19:return Qv(i,a,l);case 31:return AC(i,a,l);case 22:return Vv(i,a,l,a.pendingProps);case 24:return di(a),u=Ut(vt),i===null?(m=Hf(),m===null&&(m=We,y=zf(),m.pooledCache=y,y.refCount++,y!==null&&(m.pooledCacheLanes|=l),m=y),a.memoizedState={parent:u,cache:m},Kf(a),ps(a,vt,m)):((i.lanes&l)!==0&&(Yf(i,a),Do(a,null,null,l),Ro()),m=i.memoizedState,y=a.memoizedState,m.parent!==u?(m={parent:u,cache:u},a.memoizedState=m,a.lanes===0&&(a.memoizedState=a.updateQueue.baseState=m),ps(a,vt,u)):(u=y.cache,ps(a,vt,u),u!==m.cache&&qf(a,[vt],l,!0))),$t(i,a,a.pendingProps.children,l),a.child;case 29:throw a.pendingProps}throw Error(r(156,a.tag))}function Pr(i){i.flags|=4}function Nh(i,a,l,u,m){if((a=(i.mode&32)!==0)&&(a=!1),a){if(i.flags|=16777216,(m&335544128)===m)if(i.stateNode.complete)i.flags|=8192;else if(j0())i.flags|=8192;else throw pi=wc,Gf}else i.flags&=-16777217}function e0(i,a){if(a.type!=="stylesheet"||(a.state.loading&4)!==0)i.flags&=-16777217;else if(i.flags|=16777216,!mx(a))if(j0())i.flags|=8192;else throw pi=wc,Gf}function $c(i,a){a!==null&&(i.flags|=4),i.flags&16384&&(a=i.tag!==22?Dg():536870912,i.lanes|=a,_a|=a)}function Bo(i,a){if(!De)switch(i.tailMode){case"hidden":a=i.tail;for(var l=null;a!==null;)a.alternate!==null&&(l=a),a=a.sibling;l===null?i.tail=null:l.sibling=null;break;case"collapsed":l=i.tail;for(var u=null;l!==null;)l.alternate!==null&&(u=l),l=l.sibling;u===null?a||i.tail===null?i.tail=null:i.tail.sibling=null:u.sibling=null}}function et(i){var a=i.alternate!==null&&i.alternate.child===i.child,l=0,u=0;if(a)for(var m=i.child;m!==null;)l|=m.lanes|m.childLanes,u|=m.subtreeFlags&65011712,u|=m.flags&65011712,m.return=i,m=m.sibling;else for(m=i.child;m!==null;)l|=m.lanes|m.childLanes,u|=m.subtreeFlags,u|=m.flags,m.return=i,m=m.sibling;return i.subtreeFlags|=u,i.childLanes=l,a}function kC(i,a,l){var u=a.pendingProps;switch(Uf(a),a.tag){case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return et(a),null;case 1:return et(a),null;case 3:return l=a.stateNode,u=null,i!==null&&(u=i.memoizedState.cache),a.memoizedState.cache!==u&&(a.flags|=2048),Ur(vt),mt(),l.pendingContext&&(l.context=l.pendingContext,l.pendingContext=null),(i===null||i.child===null)&&(ua(a)?Pr(a):i===null||i.memoizedState.isDehydrated&&(a.flags&256)===0||(a.flags|=1024,Bf())),et(a),null;case 26:var m=a.type,y=a.memoizedState;return i===null?(Pr(a),y!==null?(et(a),e0(a,y)):(et(a),Nh(a,m,null,u,l))):y?y!==i.memoizedState?(Pr(a),et(a),e0(a,y)):(et(a),a.flags&=-16777217):(i=i.memoizedProps,i!==u&&Pr(a),et(a),Nh(a,m,i,u,l)),null;case 27:if(Zl(a),l=je.current,m=a.type,i!==null&&a.stateNode!=null)i.memoizedProps!==u&&Pr(a);else{if(!u){if(a.stateNode===null)throw Error(r(166));return et(a),null}i=le.current,ua(a)?Db(a):(i=ox(m,u,l),a.stateNode=i,Pr(a))}return et(a),null;case 5:if(Zl(a),m=a.type,i!==null&&a.stateNode!=null)i.memoizedProps!==u&&Pr(a);else{if(!u){if(a.stateNode===null)throw Error(r(166));return et(a),null}if(y=le.current,ua(a))Db(a);else{var S=Xc(je.current);switch(y){case 1:y=S.createElementNS("http://www.w3.org/2000/svg",m);break;case 2:y=S.createElementNS("http://www.w3.org/1998/Math/MathML",m);break;default:switch(m){case"svg":y=S.createElementNS("http://www.w3.org/2000/svg",m);break;case"math":y=S.createElementNS("http://www.w3.org/1998/Math/MathML",m);break;case"script":y=S.createElement("div"),y.innerHTML="<script><\/script>",y=y.removeChild(y.firstChild);break;case"select":y=typeof u.is=="string"?S.createElement("select",{is:u.is}):S.createElement("select"),u.multiple?y.multiple=!0:u.size&&(y.size=u.size);break;default:y=typeof u.is=="string"?S.createElement(m,{is:u.is}):S.createElement(m)}}y[Mt]=a,y[cn]=u;e:for(S=a.child;S!==null;){if(S.tag===5||S.tag===6)y.appendChild(S.stateNode);else if(S.tag!==4&&S.tag!==27&&S.child!==null){S.child.return=S,S=S.child;continue}if(S===a)break e;for(;S.sibling===null;){if(S.return===null||S.return===a)break e;S=S.return}S.sibling.return=S.return,S=S.sibling}a.stateNode=y;e:switch(Bt(y,m,u),m){case"button":case"input":case"select":case"textarea":u=!!u.autoFocus;break e;case"img":u=!0;break e;default:u=!1}u&&Pr(a)}}return et(a),Nh(a,a.type,i===null?null:i.memoizedProps,a.pendingProps,l),null;case 6:if(i&&a.stateNode!=null)i.memoizedProps!==u&&Pr(a);else{if(typeof u!="string"&&a.stateNode===null)throw Error(r(166));if(i=je.current,ua(a)){if(i=a.stateNode,l=a.memoizedProps,u=null,m=Lt,m!==null)switch(m.tag){case 27:case 5:u=m.memoizedProps}i[Mt]=a,i=!!(i.nodeValue===l||u!==null&&u.suppressHydrationWarning===!0||W0(i.nodeValue,l)),i||hs(a,!0)}else i=Xc(i).createTextNode(u),i[Mt]=a,a.stateNode=i}return et(a),null;case 31:if(l=a.memoizedState,i===null||i.memoizedState!==null){if(u=ua(a),l!==null){if(i===null){if(!u)throw Error(r(318));if(i=a.memoizedState,i=i!==null?i.dehydrated:null,!i)throw Error(r(557));i[Mt]=a}else ci(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;et(a),i=!1}else l=Bf(),i!==null&&i.memoizedState!==null&&(i.memoizedState.hydrationErrors=l),i=!0;if(!i)return a.flags&256?(kn(a),a):(kn(a),null);if((a.flags&128)!==0)throw Error(r(558))}return et(a),null;case 13:if(u=a.memoizedState,i===null||i.memoizedState!==null&&i.memoizedState.dehydrated!==null){if(m=ua(a),u!==null&&u.dehydrated!==null){if(i===null){if(!m)throw Error(r(318));if(m=a.memoizedState,m=m!==null?m.dehydrated:null,!m)throw Error(r(317));m[Mt]=a}else ci(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;et(a),m=!1}else m=Bf(),i!==null&&i.memoizedState!==null&&(i.memoizedState.hydrationErrors=m),m=!0;if(!m)return a.flags&256?(kn(a),a):(kn(a),null)}return kn(a),(a.flags&128)!==0?(a.lanes=l,a):(l=u!==null,i=i!==null&&i.memoizedState!==null,l&&(u=a.child,m=null,u.alternate!==null&&u.alternate.memoizedState!==null&&u.alternate.memoizedState.cachePool!==null&&(m=u.alternate.memoizedState.cachePool.pool),y=null,u.memoizedState!==null&&u.memoizedState.cachePool!==null&&(y=u.memoizedState.cachePool.pool),y!==m&&(u.flags|=2048)),l!==i&&l&&(a.child.flags|=8192),$c(a,a.updateQueue),et(a),null);case 4:return mt(),i===null&&Jh(a.stateNode.containerInfo),et(a),null;case 10:return Ur(a.type),et(a),null;case 19:if(ee(yt),u=a.memoizedState,u===null)return et(a),null;if(m=(a.flags&128)!==0,y=u.rendering,y===null)if(m)Bo(u,!1);else{if(lt!==0||i!==null&&(i.flags&128)!==0)for(i=a.child;i!==null;){if(y=Ac(i),y!==null){for(a.flags|=128,Bo(u,!1),i=y.updateQueue,a.updateQueue=i,$c(a,i),a.subtreeFlags=0,i=l,l=a.child;l!==null;)Cb(l,i),l=l.sibling;return ae(yt,yt.current&1|2),De&&Mr(a,u.treeForkCount),a.child}i=i.sibling}u.tail!==null&&wn()>zc&&(a.flags|=128,m=!0,Bo(u,!1),a.lanes=4194304)}else{if(!m)if(i=Ac(y),i!==null){if(a.flags|=128,m=!0,i=i.updateQueue,a.updateQueue=i,$c(a,i),Bo(u,!0),u.tail===null&&u.tailMode==="hidden"&&!y.alternate&&!De)return et(a),null}else 2*wn()-u.renderingStartTime>zc&&l!==536870912&&(a.flags|=128,m=!0,Bo(u,!1),a.lanes=4194304);u.isBackwards?(y.sibling=a.child,a.child=y):(i=u.last,i!==null?i.sibling=y:a.child=y,u.last=y)}return u.tail!==null?(i=u.tail,u.rendering=i,u.tail=i.sibling,u.renderingStartTime=wn(),i.sibling=null,l=yt.current,ae(yt,m?l&1|2:l&1),De&&Mr(a,u.treeForkCount),i):(et(a),null);case 22:case 23:return kn(a),Qf(),u=a.memoizedState!==null,i!==null?i.memoizedState!==null!==u&&(a.flags|=8192):u&&(a.flags|=8192),u?(l&536870912)!==0&&(a.flags&128)===0&&(et(a),a.subtreeFlags&6&&(a.flags|=8192)):et(a),l=a.updateQueue,l!==null&&$c(a,l.retryQueue),l=null,i!==null&&i.memoizedState!==null&&i.memoizedState.cachePool!==null&&(l=i.memoizedState.cachePool.pool),u=null,a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(u=a.memoizedState.cachePool.pool),u!==l&&(a.flags|=2048),i!==null&&ee(fi),null;case 24:return l=null,i!==null&&(l=i.memoizedState.cache),a.memoizedState.cache!==l&&(a.flags|=2048),Ur(vt),et(a),null;case 25:return null;case 30:return null}throw Error(r(156,a.tag))}function CC(i,a){switch(Uf(a),a.tag){case 1:return i=a.flags,i&65536?(a.flags=i&-65537|128,a):null;case 3:return Ur(vt),mt(),i=a.flags,(i&65536)!==0&&(i&128)===0?(a.flags=i&-65537|128,a):null;case 26:case 27:case 5:return Zl(a),null;case 31:if(a.memoizedState!==null){if(kn(a),a.alternate===null)throw Error(r(340));ci()}return i=a.flags,i&65536?(a.flags=i&-65537|128,a):null;case 13:if(kn(a),i=a.memoizedState,i!==null&&i.dehydrated!==null){if(a.alternate===null)throw Error(r(340));ci()}return i=a.flags,i&65536?(a.flags=i&-65537|128,a):null;case 19:return ee(yt),null;case 4:return mt(),null;case 10:return Ur(a.type),null;case 22:case 23:return kn(a),Qf(),i!==null&&ee(fi),i=a.flags,i&65536?(a.flags=i&-65537|128,a):null;case 24:return Ur(vt),null;case 25:return null;default:return null}}function t0(i,a){switch(Uf(a),a.tag){case 3:Ur(vt),mt();break;case 26:case 27:case 5:Zl(a);break;case 4:mt();break;case 31:a.memoizedState!==null&&kn(a);break;case 13:kn(a);break;case 19:ee(yt);break;case 10:Ur(a.type);break;case 22:case 23:kn(a),Qf(),i!==null&&ee(fi);break;case 24:Ur(vt)}}function Fo(i,a){try{var l=a.updateQueue,u=l!==null?l.lastEffect:null;if(u!==null){var m=u.next;l=m;do{if((l.tag&i)===i){u=void 0;var y=l.create,S=l.inst;u=y(),S.destroy=u}l=l.next}while(l!==m)}}catch(j){Ve(a,a.return,j)}}function xs(i,a,l){try{var u=a.updateQueue,m=u!==null?u.lastEffect:null;if(m!==null){var y=m.next;u=y;do{if((u.tag&i)===i){var S=u.inst,j=S.destroy;if(j!==void 0){S.destroy=void 0,m=a;var V=l,Q=j;try{Q()}catch(ne){Ve(m,V,ne)}}}u=u.next}while(u!==y)}}catch(ne){Ve(a,a.return,ne)}}function n0(i){var a=i.updateQueue;if(a!==null){var l=i.stateNode;try{Gb(a,l)}catch(u){Ve(i,i.return,u)}}}function r0(i,a,l){l.props=gi(i.type,i.memoizedProps),l.state=i.memoizedState;try{l.componentWillUnmount()}catch(u){Ve(i,a,u)}}function Po(i,a){try{var l=i.ref;if(l!==null){switch(i.tag){case 26:case 27:case 5:var u=i.stateNode;break;case 30:u=i.stateNode;break;default:u=i.stateNode}typeof l=="function"?i.refCleanup=l(u):l.current=u}}catch(m){Ve(i,a,m)}}function pr(i,a){var l=i.ref,u=i.refCleanup;if(l!==null)if(typeof u=="function")try{u()}catch(m){Ve(i,a,m)}finally{i.refCleanup=null,i=i.alternate,i!=null&&(i.refCleanup=null)}else if(typeof l=="function")try{l(null)}catch(m){Ve(i,a,m)}else l.current=null}function s0(i){var a=i.type,l=i.memoizedProps,u=i.stateNode;try{e:switch(a){case"button":case"input":case"select":case"textarea":l.autoFocus&&u.focus();break e;case"img":l.src?u.src=l.src:l.srcSet&&(u.srcset=l.srcSet)}}catch(m){Ve(i,i.return,m)}}function Oh(i,a,l){try{var u=i.stateNode;WC(u,i.type,l,a),u[cn]=a}catch(m){Ve(i,i.return,m)}}function i0(i){return i.tag===5||i.tag===3||i.tag===26||i.tag===27&&ks(i.type)||i.tag===4}function Th(i){e:for(;;){for(;i.sibling===null;){if(i.return===null||i0(i.return))return null;i=i.return}for(i.sibling.return=i.return,i=i.sibling;i.tag!==5&&i.tag!==6&&i.tag!==18;){if(i.tag===27&&ks(i.type)||i.flags&2||i.child===null||i.tag===4)continue e;i.child.return=i,i=i.child}if(!(i.flags&2))return i.stateNode}}function Rh(i,a,l){var u=i.tag;if(u===5||u===6)i=i.stateNode,a?(l.nodeType===9?l.body:l.nodeName==="HTML"?l.ownerDocument.body:l).insertBefore(i,a):(a=l.nodeType===9?l.body:l.nodeName==="HTML"?l.ownerDocument.body:l,a.appendChild(i),l=l._reactRootContainer,l!=null||a.onclick!==null||(a.onclick=Rr));else if(u!==4&&(u===27&&ks(i.type)&&(l=i.stateNode,a=null),i=i.child,i!==null))for(Rh(i,a,l),i=i.sibling;i!==null;)Rh(i,a,l),i=i.sibling}function Bc(i,a,l){var u=i.tag;if(u===5||u===6)i=i.stateNode,a?l.insertBefore(i,a):l.appendChild(i);else if(u!==4&&(u===27&&ks(i.type)&&(l=i.stateNode),i=i.child,i!==null))for(Bc(i,a,l),i=i.sibling;i!==null;)Bc(i,a,l),i=i.sibling}function a0(i){var a=i.stateNode,l=i.memoizedProps;try{for(var u=i.type,m=a.attributes;m.length;)a.removeAttributeNode(m[0]);Bt(a,u,l),a[Mt]=i,a[cn]=l}catch(y){Ve(i,i.return,y)}}var qr=!1,St=!1,Dh=!1,o0=typeof WeakSet=="function"?WeakSet:Set,Rt=null;function NC(i,a){if(i=i.containerInfo,ep=au,i=vb(i),jf(i)){if("selectionStart"in i)var l={start:i.selectionStart,end:i.selectionEnd};else e:{l=(l=i.ownerDocument)&&l.defaultView||window;var u=l.getSelection&&l.getSelection();if(u&&u.rangeCount!==0){l=u.anchorNode;var m=u.anchorOffset,y=u.focusNode;u=u.focusOffset;try{l.nodeType,y.nodeType}catch{l=null;break e}var S=0,j=-1,V=-1,Q=0,ne=0,ie=i,X=null;t:for(;;){for(var te;ie!==l||m!==0&&ie.nodeType!==3||(j=S+m),ie!==y||u!==0&&ie.nodeType!==3||(V=S+u),ie.nodeType===3&&(S+=ie.nodeValue.length),(te=ie.firstChild)!==null;)X=ie,ie=te;for(;;){if(ie===i)break t;if(X===l&&++Q===m&&(j=S),X===y&&++ne===u&&(V=S),(te=ie.nextSibling)!==null)break;ie=X,X=ie.parentNode}ie=te}l=j===-1||V===-1?null:{start:j,end:V}}else l=null}l=l||{start:0,end:0}}else l=null;for(tp={focusedElem:i,selectionRange:l},au=!1,Rt=a;Rt!==null;)if(a=Rt,i=a.child,(a.subtreeFlags&1028)!==0&&i!==null)i.return=a,Rt=i;else for(;Rt!==null;){switch(a=Rt,y=a.alternate,i=a.flags,a.tag){case 0:if((i&4)!==0&&(i=a.updateQueue,i=i!==null?i.events:null,i!==null))for(l=0;l<i.length;l++)m=i[l],m.ref.impl=m.nextImpl;break;case 11:case 15:break;case 1:if((i&1024)!==0&&y!==null){i=void 0,l=a,m=y.memoizedProps,y=y.memoizedState,u=l.stateNode;try{var de=gi(l.type,m);i=u.getSnapshotBeforeUpdate(de,y),u.__reactInternalSnapshotBeforeUpdate=i}catch(me){Ve(l,l.return,me)}}break;case 3:if((i&1024)!==0){if(i=a.stateNode.containerInfo,l=i.nodeType,l===9)sp(i);else if(l===1)switch(i.nodeName){case"HEAD":case"HTML":case"BODY":sp(i);break;default:i.textContent=""}}break;case 5:case 26:case 27:case 6:case 4:case 17:break;default:if((i&1024)!==0)throw Error(r(163))}if(i=a.sibling,i!==null){i.return=a.return,Rt=i;break}Rt=a.return}}function l0(i,a,l){var u=l.flags;switch(l.tag){case 0:case 11:case 15:Vr(i,l),u&4&&Fo(5,l);break;case 1:if(Vr(i,l),u&4)if(i=l.stateNode,a===null)try{i.componentDidMount()}catch(S){Ve(l,l.return,S)}else{var m=gi(l.type,a.memoizedProps);a=a.memoizedState;try{i.componentDidUpdate(m,a,i.__reactInternalSnapshotBeforeUpdate)}catch(S){Ve(l,l.return,S)}}u&64&&n0(l),u&512&&Po(l,l.return);break;case 3:if(Vr(i,l),u&64&&(i=l.updateQueue,i!==null)){if(a=null,l.child!==null)switch(l.child.tag){case 27:case 5:a=l.child.stateNode;break;case 1:a=l.child.stateNode}try{Gb(i,a)}catch(S){Ve(l,l.return,S)}}break;case 27:a===null&&u&4&&a0(l);case 26:case 5:Vr(i,l),a===null&&u&4&&s0(l),u&512&&Po(l,l.return);break;case 12:Vr(i,l);break;case 31:Vr(i,l),u&4&&d0(i,l);break;case 13:Vr(i,l),u&4&&f0(i,l),u&64&&(i=l.memoizedState,i!==null&&(i=i.dehydrated,i!==null&&(l=$C.bind(null,l),sN(i,l))));break;case 22:if(u=l.memoizedState!==null||qr,!u){a=a!==null&&a.memoizedState!==null||St,m=qr;var y=St;qr=u,(St=a)&&!y?Hr(i,l,(l.subtreeFlags&8772)!==0):Vr(i,l),qr=m,St=y}break;case 30:break;default:Vr(i,l)}}function c0(i){var a=i.alternate;a!==null&&(i.alternate=null,c0(a)),i.child=null,i.deletions=null,i.sibling=null,i.tag===5&&(a=i.stateNode,a!==null&&cf(a)),i.stateNode=null,i.return=null,i.dependencies=null,i.memoizedProps=null,i.memoizedState=null,i.pendingProps=null,i.stateNode=null,i.updateQueue=null}var st=null,dn=!1;function zr(i,a,l){for(l=l.child;l!==null;)u0(i,a,l),l=l.sibling}function u0(i,a,l){if(Sn&&typeof Sn.onCommitFiberUnmount=="function")try{Sn.onCommitFiberUnmount(uo,l)}catch{}switch(l.tag){case 26:St||pr(l,a),zr(i,a,l),l.memoizedState?l.memoizedState.count--:l.stateNode&&(l=l.stateNode,l.parentNode.removeChild(l));break;case 27:St||pr(l,a);var u=st,m=dn;ks(l.type)&&(st=l.stateNode,dn=!1),zr(i,a,l),Wo(l.stateNode),st=u,dn=m;break;case 5:St||pr(l,a);case 6:if(u=st,m=dn,st=null,zr(i,a,l),st=u,dn=m,st!==null)if(dn)try{(st.nodeType===9?st.body:st.nodeName==="HTML"?st.ownerDocument.body:st).removeChild(l.stateNode)}catch(y){Ve(l,a,y)}else try{st.removeChild(l.stateNode)}catch(y){Ve(l,a,y)}break;case 18:st!==null&&(dn?(i=st,nx(i.nodeType===9?i.body:i.nodeName==="HTML"?i.ownerDocument.body:i,l.stateNode),Ta(i)):nx(st,l.stateNode));break;case 4:u=st,m=dn,st=l.stateNode.containerInfo,dn=!0,zr(i,a,l),st=u,dn=m;break;case 0:case 11:case 14:case 15:xs(2,l,a),St||xs(4,l,a),zr(i,a,l);break;case 1:St||(pr(l,a),u=l.stateNode,typeof u.componentWillUnmount=="function"&&r0(l,a,u)),zr(i,a,l);break;case 21:zr(i,a,l);break;case 22:St=(u=St)||l.memoizedState!==null,zr(i,a,l),St=u;break;default:zr(i,a,l)}}function d0(i,a){if(a.memoizedState===null&&(i=a.alternate,i!==null&&(i=i.memoizedState,i!==null))){i=i.dehydrated;try{Ta(i)}catch(l){Ve(a,a.return,l)}}}function f0(i,a){if(a.memoizedState===null&&(i=a.alternate,i!==null&&(i=i.memoizedState,i!==null&&(i=i.dehydrated,i!==null))))try{Ta(i)}catch(l){Ve(a,a.return,l)}}function OC(i){switch(i.tag){case 31:case 13:case 19:var a=i.stateNode;return a===null&&(a=i.stateNode=new o0),a;case 22:return i=i.stateNode,a=i._retryCache,a===null&&(a=i._retryCache=new o0),a;default:throw Error(r(435,i.tag))}}function Fc(i,a){var l=OC(i);a.forEach(function(u){if(!l.has(u)){l.add(u);var m=BC.bind(null,i,u);u.then(m,m)}})}function fn(i,a){var l=a.deletions;if(l!==null)for(var u=0;u<l.length;u++){var m=l[u],y=i,S=a,j=S;e:for(;j!==null;){switch(j.tag){case 27:if(ks(j.type)){st=j.stateNode,dn=!1;break e}break;case 5:st=j.stateNode,dn=!1;break e;case 3:case 4:st=j.stateNode.containerInfo,dn=!0;break e}j=j.return}if(st===null)throw Error(r(160));u0(y,S,m),st=null,dn=!1,y=m.alternate,y!==null&&(y.return=null),m.return=null}if(a.subtreeFlags&13886)for(a=a.child;a!==null;)h0(a,i),a=a.sibling}var rr=null;function h0(i,a){var l=i.alternate,u=i.flags;switch(i.tag){case 0:case 11:case 14:case 15:fn(a,i),hn(i),u&4&&(xs(3,i,i.return),Fo(3,i),xs(5,i,i.return));break;case 1:fn(a,i),hn(i),u&512&&(St||l===null||pr(l,l.return)),u&64&&qr&&(i=i.updateQueue,i!==null&&(u=i.callbacks,u!==null&&(l=i.shared.hiddenCallbacks,i.shared.hiddenCallbacks=l===null?u:l.concat(u))));break;case 26:var m=rr;if(fn(a,i),hn(i),u&512&&(St||l===null||pr(l,l.return)),u&4){var y=l!==null?l.memoizedState:null;if(u=i.memoizedState,l===null)if(u===null)if(i.stateNode===null){e:{u=i.type,l=i.memoizedProps,m=m.ownerDocument||m;t:switch(u){case"title":y=m.getElementsByTagName("title")[0],(!y||y[po]||y[Mt]||y.namespaceURI==="http://www.w3.org/2000/svg"||y.hasAttribute("itemprop"))&&(y=m.createElement(u),m.head.insertBefore(y,m.querySelector("head > title"))),Bt(y,u,l),y[Mt]=i,Tt(y),u=y;break e;case"link":var S=hx("link","href",m).get(u+(l.href||""));if(S){for(var j=0;j<S.length;j++)if(y=S[j],y.getAttribute("href")===(l.href==null||l.href===""?null:l.href)&&y.getAttribute("rel")===(l.rel==null?null:l.rel)&&y.getAttribute("title")===(l.title==null?null:l.title)&&y.getAttribute("crossorigin")===(l.crossOrigin==null?null:l.crossOrigin)){S.splice(j,1);break t}}y=m.createElement(u),Bt(y,u,l),m.head.appendChild(y);break;case"meta":if(S=hx("meta","content",m).get(u+(l.content||""))){for(j=0;j<S.length;j++)if(y=S[j],y.getAttribute("content")===(l.content==null?null:""+l.content)&&y.getAttribute("name")===(l.name==null?null:l.name)&&y.getAttribute("property")===(l.property==null?null:l.property)&&y.getAttribute("http-equiv")===(l.httpEquiv==null?null:l.httpEquiv)&&y.getAttribute("charset")===(l.charSet==null?null:l.charSet)){S.splice(j,1);break t}}y=m.createElement(u),Bt(y,u,l),m.head.appendChild(y);break;default:throw Error(r(468,u))}y[Mt]=i,Tt(y),u=y}i.stateNode=u}else px(m,i.type,i.stateNode);else i.stateNode=fx(m,u,i.memoizedProps);else y!==u?(y===null?l.stateNode!==null&&(l=l.stateNode,l.parentNode.removeChild(l)):y.count--,u===null?px(m,i.type,i.stateNode):fx(m,u,i.memoizedProps)):u===null&&i.stateNode!==null&&Oh(i,i.memoizedProps,l.memoizedProps)}break;case 27:fn(a,i),hn(i),u&512&&(St||l===null||pr(l,l.return)),l!==null&&u&4&&Oh(i,i.memoizedProps,l.memoizedProps);break;case 5:if(fn(a,i),hn(i),u&512&&(St||l===null||pr(l,l.return)),i.flags&32){m=i.stateNode;try{ea(m,"")}catch(de){Ve(i,i.return,de)}}u&4&&i.stateNode!=null&&(m=i.memoizedProps,Oh(i,m,l!==null?l.memoizedProps:m)),u&1024&&(Dh=!0);break;case 6:if(fn(a,i),hn(i),u&4){if(i.stateNode===null)throw Error(r(162));u=i.memoizedProps,l=i.stateNode;try{l.nodeValue=u}catch(de){Ve(i,i.return,de)}}break;case 3:if(nu=null,m=rr,rr=eu(a.containerInfo),fn(a,i),rr=m,hn(i),u&4&&l!==null&&l.memoizedState.isDehydrated)try{Ta(a.containerInfo)}catch(de){Ve(i,i.return,de)}Dh&&(Dh=!1,p0(i));break;case 4:u=rr,rr=eu(i.stateNode.containerInfo),fn(a,i),hn(i),rr=u;break;case 12:fn(a,i),hn(i);break;case 31:fn(a,i),hn(i),u&4&&(u=i.updateQueue,u!==null&&(i.updateQueue=null,Fc(i,u)));break;case 13:fn(a,i),hn(i),i.child.flags&8192&&i.memoizedState!==null!=(l!==null&&l.memoizedState!==null)&&(qc=wn()),u&4&&(u=i.updateQueue,u!==null&&(i.updateQueue=null,Fc(i,u)));break;case 22:m=i.memoizedState!==null;var V=l!==null&&l.memoizedState!==null,Q=qr,ne=St;if(qr=Q||m,St=ne||V,fn(a,i),St=ne,qr=Q,hn(i),u&8192)e:for(a=i.stateNode,a._visibility=m?a._visibility&-2:a._visibility|1,m&&(l===null||V||qr||St||bi(i)),l=null,a=i;;){if(a.tag===5||a.tag===26){if(l===null){V=l=a;try{if(y=V.stateNode,m)S=y.style,typeof S.setProperty=="function"?S.setProperty("display","none","important"):S.display="none";else{j=V.stateNode;var ie=V.memoizedProps.style,X=ie!=null&&ie.hasOwnProperty("display")?ie.display:null;j.style.display=X==null||typeof X=="boolean"?"":(""+X).trim()}}catch(de){Ve(V,V.return,de)}}}else if(a.tag===6){if(l===null){V=a;try{V.stateNode.nodeValue=m?"":V.memoizedProps}catch(de){Ve(V,V.return,de)}}}else if(a.tag===18){if(l===null){V=a;try{var te=V.stateNode;m?rx(te,!0):rx(V.stateNode,!1)}catch(de){Ve(V,V.return,de)}}}else if((a.tag!==22&&a.tag!==23||a.memoizedState===null||a===i)&&a.child!==null){a.child.return=a,a=a.child;continue}if(a===i)break e;for(;a.sibling===null;){if(a.return===null||a.return===i)break e;l===a&&(l=null),a=a.return}l===a&&(l=null),a.sibling.return=a.return,a=a.sibling}u&4&&(u=i.updateQueue,u!==null&&(l=u.retryQueue,l!==null&&(u.retryQueue=null,Fc(i,l))));break;case 19:fn(a,i),hn(i),u&4&&(u=i.updateQueue,u!==null&&(i.updateQueue=null,Fc(i,u)));break;case 30:break;case 21:break;default:fn(a,i),hn(i)}}function hn(i){var a=i.flags;if(a&2){try{for(var l,u=i.return;u!==null;){if(i0(u)){l=u;break}u=u.return}if(l==null)throw Error(r(160));switch(l.tag){case 27:var m=l.stateNode,y=Th(i);Bc(i,y,m);break;case 5:var S=l.stateNode;l.flags&32&&(ea(S,""),l.flags&=-33);var j=Th(i);Bc(i,j,S);break;case 3:case 4:var V=l.stateNode.containerInfo,Q=Th(i);Rh(i,Q,V);break;default:throw Error(r(161))}}catch(ne){Ve(i,i.return,ne)}i.flags&=-3}a&4096&&(i.flags&=-4097)}function p0(i){if(i.subtreeFlags&1024)for(i=i.child;i!==null;){var a=i;p0(a),a.tag===5&&a.flags&1024&&a.stateNode.reset(),i=i.sibling}}function Vr(i,a){if(a.subtreeFlags&8772)for(a=a.child;a!==null;)l0(i,a.alternate,a),a=a.sibling}function bi(i){for(i=i.child;i!==null;){var a=i;switch(a.tag){case 0:case 11:case 14:case 15:xs(4,a,a.return),bi(a);break;case 1:pr(a,a.return);var l=a.stateNode;typeof l.componentWillUnmount=="function"&&r0(a,a.return,l),bi(a);break;case 27:Wo(a.stateNode);case 26:case 5:pr(a,a.return),bi(a);break;case 22:a.memoizedState===null&&bi(a);break;case 30:bi(a);break;default:bi(a)}i=i.sibling}}function Hr(i,a,l){for(l=l&&(a.subtreeFlags&8772)!==0,a=a.child;a!==null;){var u=a.alternate,m=i,y=a,S=y.flags;switch(y.tag){case 0:case 11:case 15:Hr(m,y,l),Fo(4,y);break;case 1:if(Hr(m,y,l),u=y,m=u.stateNode,typeof m.componentDidMount=="function")try{m.componentDidMount()}catch(Q){Ve(u,u.return,Q)}if(u=y,m=u.updateQueue,m!==null){var j=u.stateNode;try{var V=m.shared.hiddenCallbacks;if(V!==null)for(m.shared.hiddenCallbacks=null,m=0;m<V.length;m++)Hb(V[m],j)}catch(Q){Ve(u,u.return,Q)}}l&&S&64&&n0(y),Po(y,y.return);break;case 27:a0(y);case 26:case 5:Hr(m,y,l),l&&u===null&&S&4&&s0(y),Po(y,y.return);break;case 12:Hr(m,y,l);break;case 31:Hr(m,y,l),l&&S&4&&d0(m,y);break;case 13:Hr(m,y,l),l&&S&4&&f0(m,y);break;case 22:y.memoizedState===null&&Hr(m,y,l),Po(y,y.return);break;case 30:break;default:Hr(m,y,l)}a=a.sibling}}function Ih(i,a){var l=null;i!==null&&i.memoizedState!==null&&i.memoizedState.cachePool!==null&&(l=i.memoizedState.cachePool.pool),i=null,a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(i=a.memoizedState.cachePool.pool),i!==l&&(i!=null&&i.refCount++,l!=null&&ko(l))}function Mh(i,a){i=null,a.alternate!==null&&(i=a.alternate.memoizedState.cache),a=a.memoizedState.cache,a!==i&&(a.refCount++,i!=null&&ko(i))}function sr(i,a,l,u){if(a.subtreeFlags&10256)for(a=a.child;a!==null;)m0(i,a,l,u),a=a.sibling}function m0(i,a,l,u){var m=a.flags;switch(a.tag){case 0:case 11:case 15:sr(i,a,l,u),m&2048&&Fo(9,a);break;case 1:sr(i,a,l,u);break;case 3:sr(i,a,l,u),m&2048&&(i=null,a.alternate!==null&&(i=a.alternate.memoizedState.cache),a=a.memoizedState.cache,a!==i&&(a.refCount++,i!=null&&ko(i)));break;case 12:if(m&2048){sr(i,a,l,u),i=a.stateNode;try{var y=a.memoizedProps,S=y.id,j=y.onPostCommit;typeof j=="function"&&j(S,a.alternate===null?"mount":"update",i.passiveEffectDuration,-0)}catch(V){Ve(a,a.return,V)}}else sr(i,a,l,u);break;case 31:sr(i,a,l,u);break;case 13:sr(i,a,l,u);break;case 23:break;case 22:y=a.stateNode,S=a.alternate,a.memoizedState!==null?y._visibility&2?sr(i,a,l,u):qo(i,a):y._visibility&2?sr(i,a,l,u):(y._visibility|=2,xa(i,a,l,u,(a.subtreeFlags&10256)!==0||!1)),m&2048&&Ih(S,a);break;case 24:sr(i,a,l,u),m&2048&&Mh(a.alternate,a);break;default:sr(i,a,l,u)}}function xa(i,a,l,u,m){for(m=m&&((a.subtreeFlags&10256)!==0||!1),a=a.child;a!==null;){var y=i,S=a,j=l,V=u,Q=S.flags;switch(S.tag){case 0:case 11:case 15:xa(y,S,j,V,m),Fo(8,S);break;case 23:break;case 22:var ne=S.stateNode;S.memoizedState!==null?ne._visibility&2?xa(y,S,j,V,m):qo(y,S):(ne._visibility|=2,xa(y,S,j,V,m)),m&&Q&2048&&Ih(S.alternate,S);break;case 24:xa(y,S,j,V,m),m&&Q&2048&&Mh(S.alternate,S);break;default:xa(y,S,j,V,m)}a=a.sibling}}function qo(i,a){if(a.subtreeFlags&10256)for(a=a.child;a!==null;){var l=i,u=a,m=u.flags;switch(u.tag){case 22:qo(l,u),m&2048&&Ih(u.alternate,u);break;case 24:qo(l,u),m&2048&&Mh(u.alternate,u);break;default:qo(l,u)}a=a.sibling}}var zo=8192;function wa(i,a,l){if(i.subtreeFlags&zo)for(i=i.child;i!==null;)y0(i,a,l),i=i.sibling}function y0(i,a,l){switch(i.tag){case 26:wa(i,a,l),i.flags&zo&&i.memoizedState!==null&&yN(l,rr,i.memoizedState,i.memoizedProps);break;case 5:wa(i,a,l);break;case 3:case 4:var u=rr;rr=eu(i.stateNode.containerInfo),wa(i,a,l),rr=u;break;case 22:i.memoizedState===null&&(u=i.alternate,u!==null&&u.memoizedState!==null?(u=zo,zo=16777216,wa(i,a,l),zo=u):wa(i,a,l));break;default:wa(i,a,l)}}function g0(i){var a=i.alternate;if(a!==null&&(i=a.child,i!==null)){a.child=null;do a=i.sibling,i.sibling=null,i=a;while(i!==null)}}function Vo(i){var a=i.deletions;if((i.flags&16)!==0){if(a!==null)for(var l=0;l<a.length;l++){var u=a[l];Rt=u,v0(u,i)}g0(i)}if(i.subtreeFlags&10256)for(i=i.child;i!==null;)b0(i),i=i.sibling}function b0(i){switch(i.tag){case 0:case 11:case 15:Vo(i),i.flags&2048&&xs(9,i,i.return);break;case 3:Vo(i);break;case 12:Vo(i);break;case 22:var a=i.stateNode;i.memoizedState!==null&&a._visibility&2&&(i.return===null||i.return.tag!==13)?(a._visibility&=-3,Pc(i)):Vo(i);break;default:Vo(i)}}function Pc(i){var a=i.deletions;if((i.flags&16)!==0){if(a!==null)for(var l=0;l<a.length;l++){var u=a[l];Rt=u,v0(u,i)}g0(i)}for(i=i.child;i!==null;){switch(a=i,a.tag){case 0:case 11:case 15:xs(8,a,a.return),Pc(a);break;case 22:l=a.stateNode,l._visibility&2&&(l._visibility&=-3,Pc(a));break;default:Pc(a)}i=i.sibling}}function v0(i,a){for(;Rt!==null;){var l=Rt;switch(l.tag){case 0:case 11:case 15:xs(8,l,a);break;case 23:case 22:if(l.memoizedState!==null&&l.memoizedState.cachePool!==null){var u=l.memoizedState.cachePool.pool;u!=null&&u.refCount++}break;case 24:ko(l.memoizedState.cache)}if(u=l.child,u!==null)u.return=l,Rt=u;else e:for(l=i;Rt!==null;){u=Rt;var m=u.sibling,y=u.return;if(c0(u),u===l){Rt=null;break e}if(m!==null){m.return=y,Rt=m;break e}Rt=y}}}var TC={getCacheForType:function(i){var a=Ut(vt),l=a.data.get(i);return l===void 0&&(l=i(),a.data.set(i,l)),l},cacheSignal:function(){return Ut(vt).controller.signal}},RC=typeof WeakMap=="function"?WeakMap:Map,Fe=0,We=null,ke=null,Ne=0,ze=0,Cn=null,ws=!1,Sa=!1,Lh=!1,Gr=0,lt=0,Ss=0,vi=0,Uh=0,Nn=0,_a=0,Ho=null,pn=null,$h=!1,qc=0,x0=0,zc=1/0,Vc=null,_s=null,Ct=0,Es=null,Ea=null,Kr=0,Bh=0,Fh=null,w0=null,Go=0,Ph=null;function On(){return(Fe&2)!==0&&Ne!==0?Ne&-Ne:z.T!==null?Kh():Ug()}function S0(){if(Nn===0)if((Ne&536870912)===0||De){var i=Ql;Ql<<=1,(Ql&3932160)===0&&(Ql=262144),Nn=i}else Nn=536870912;return i=jn.current,i!==null&&(i.flags|=32),Nn}function mn(i,a,l){(i===We&&(ze===2||ze===9)||i.cancelPendingCommit!==null)&&(Aa(i,0),As(i,Ne,Nn,!1)),ho(i,l),((Fe&2)===0||i!==We)&&(i===We&&((Fe&2)===0&&(vi|=l),lt===4&&As(i,Ne,Nn,!1)),mr(i))}function _0(i,a,l){if((Fe&6)!==0)throw Error(r(327));var u=!l&&(a&127)===0&&(a&i.expiredLanes)===0||fo(i,a),m=u?MC(i,a):zh(i,a,!0),y=u;do{if(m===0){Sa&&!u&&As(i,a,0,!1);break}else{if(l=i.current.alternate,y&&!DC(l)){m=zh(i,a,!1),y=!1;continue}if(m===2){if(y=a,i.errorRecoveryDisabledLanes&y)var S=0;else S=i.pendingLanes&-536870913,S=S!==0?S:S&536870912?536870912:0;if(S!==0){a=S;e:{var j=i;m=Ho;var V=j.current.memoizedState.isDehydrated;if(V&&(Aa(j,S).flags|=256),S=zh(j,S,!1),S!==2){if(Lh&&!V){j.errorRecoveryDisabledLanes|=y,vi|=y,m=4;break e}y=pn,pn=m,y!==null&&(pn===null?pn=y:pn.push.apply(pn,y))}m=S}if(y=!1,m!==2)continue}}if(m===1){Aa(i,0),As(i,a,0,!0);break}e:{switch(u=i,y=m,y){case 0:case 1:throw Error(r(345));case 4:if((a&4194048)!==a)break;case 6:As(u,a,Nn,!ws);break e;case 2:pn=null;break;case 3:case 5:break;default:throw Error(r(329))}if((a&62914560)===a&&(m=qc+300-wn(),10<m)){if(As(u,a,Nn,!ws),ec(u,0,!0)!==0)break e;Kr=a,u.timeoutHandle=ex(E0.bind(null,u,l,pn,Vc,$h,a,Nn,vi,_a,ws,y,"Throttled",-0,0),m);break e}E0(u,l,pn,Vc,$h,a,Nn,vi,_a,ws,y,null,-0,0)}}break}while(!0);mr(i)}function E0(i,a,l,u,m,y,S,j,V,Q,ne,ie,X,te){if(i.timeoutHandle=-1,ie=a.subtreeFlags,ie&8192||(ie&16785408)===16785408){ie={stylesheets:null,count:0,imgCount:0,imgBytes:0,suspenseyImages:[],waitingForImages:!0,waitingForViewTransition:!1,unsuspend:Rr},y0(a,y,ie);var de=(y&62914560)===y?qc-wn():(y&4194048)===y?x0-wn():0;if(de=gN(ie,de),de!==null){Kr=y,i.cancelPendingCommit=de(R0.bind(null,i,a,y,l,u,m,S,j,V,ne,ie,null,X,te)),As(i,y,S,!Q);return}}R0(i,a,y,l,u,m,S,j,V)}function DC(i){for(var a=i;;){var l=a.tag;if((l===0||l===11||l===15)&&a.flags&16384&&(l=a.updateQueue,l!==null&&(l=l.stores,l!==null)))for(var u=0;u<l.length;u++){var m=l[u],y=m.getSnapshot;m=m.value;try{if(!En(y(),m))return!1}catch{return!1}}if(l=a.child,a.subtreeFlags&16384&&l!==null)l.return=a,a=l;else{if(a===i)break;for(;a.sibling===null;){if(a.return===null||a.return===i)return!0;a=a.return}a.sibling.return=a.return,a=a.sibling}}return!0}function As(i,a,l,u){a&=~Uh,a&=~vi,i.suspendedLanes|=a,i.pingedLanes&=~a,u&&(i.warmLanes|=a),u=i.expirationTimes;for(var m=a;0<m;){var y=31-_n(m),S=1<<y;u[y]=-1,m&=~S}l!==0&&Ig(i,l,a)}function Hc(){return(Fe&6)===0?(Ko(0),!1):!0}function qh(){if(ke!==null){if(ze===0)var i=ke.return;else i=ke,Lr=ui=null,sh(i),ma=null,No=0,i=ke;for(;i!==null;)t0(i.alternate,i),i=i.return;ke=null}}function Aa(i,a){var l=i.timeoutHandle;l!==-1&&(i.timeoutHandle=-1,XC(l)),l=i.cancelPendingCommit,l!==null&&(i.cancelPendingCommit=null,l()),Kr=0,qh(),We=i,ke=l=Ir(i.current,null),Ne=a,ze=0,Cn=null,ws=!1,Sa=fo(i,a),Lh=!1,_a=Nn=Uh=vi=Ss=lt=0,pn=Ho=null,$h=!1,(a&8)!==0&&(a|=a&32);var u=i.entangledLanes;if(u!==0)for(i=i.entanglements,u&=a;0<u;){var m=31-_n(u),y=1<<m;a|=i[m],u&=~y}return Gr=a,fc(),l}function A0(i,a){we=null,z.H=Uo,a===pa||a===xc?(a=Pb(),ze=3):a===Gf?(a=Pb(),ze=4):ze=a===xh?8:a!==null&&typeof a=="object"&&typeof a.then=="function"?6:1,Cn=a,ke===null&&(lt=1,Ic(i,Bn(a,i.current)))}function j0(){var i=jn.current;return i===null?!0:(Ne&4194048)===Ne?zn===null:(Ne&62914560)===Ne||(Ne&536870912)!==0?i===zn:!1}function k0(){var i=z.H;return z.H=Uo,i===null?Uo:i}function C0(){var i=z.A;return z.A=TC,i}function Gc(){lt=4,ws||(Ne&4194048)!==Ne&&jn.current!==null||(Sa=!0),(Ss&134217727)===0&&(vi&134217727)===0||We===null||As(We,Ne,Nn,!1)}function zh(i,a,l){var u=Fe;Fe|=2;var m=k0(),y=C0();(We!==i||Ne!==a)&&(Vc=null,Aa(i,a)),a=!1;var S=lt;e:do try{if(ze!==0&&ke!==null){var j=ke,V=Cn;switch(ze){case 8:qh(),S=6;break e;case 3:case 2:case 9:case 6:jn.current===null&&(a=!0);var Q=ze;if(ze=0,Cn=null,ja(i,j,V,Q),l&&Sa){S=0;break e}break;default:Q=ze,ze=0,Cn=null,ja(i,j,V,Q)}}IC(),S=lt;break}catch(ne){A0(i,ne)}while(!0);return a&&i.shellSuspendCounter++,Lr=ui=null,Fe=u,z.H=m,z.A=y,ke===null&&(We=null,Ne=0,fc()),S}function IC(){for(;ke!==null;)N0(ke)}function MC(i,a){var l=Fe;Fe|=2;var u=k0(),m=C0();We!==i||Ne!==a?(Vc=null,zc=wn()+500,Aa(i,a)):Sa=fo(i,a);e:do try{if(ze!==0&&ke!==null){a=ke;var y=Cn;t:switch(ze){case 1:ze=0,Cn=null,ja(i,a,y,1);break;case 2:case 9:if(Bb(y)){ze=0,Cn=null,O0(a);break}a=function(){ze!==2&&ze!==9||We!==i||(ze=7),mr(i)},y.then(a,a);break e;case 3:ze=7;break e;case 4:ze=5;break e;case 7:Bb(y)?(ze=0,Cn=null,O0(a)):(ze=0,Cn=null,ja(i,a,y,7));break;case 5:var S=null;switch(ke.tag){case 26:S=ke.memoizedState;case 5:case 27:var j=ke;if(S?mx(S):j.stateNode.complete){ze=0,Cn=null;var V=j.sibling;if(V!==null)ke=V;else{var Q=j.return;Q!==null?(ke=Q,Kc(Q)):ke=null}break t}}ze=0,Cn=null,ja(i,a,y,5);break;case 6:ze=0,Cn=null,ja(i,a,y,6);break;case 8:qh(),lt=6;break e;default:throw Error(r(462))}}LC();break}catch(ne){A0(i,ne)}while(!0);return Lr=ui=null,z.H=u,z.A=m,Fe=l,ke!==null?0:(We=null,Ne=0,fc(),lt)}function LC(){for(;ke!==null&&!ik();)N0(ke)}function N0(i){var a=Xv(i.alternate,i,Gr);i.memoizedProps=i.pendingProps,a===null?Kc(i):ke=a}function O0(i){var a=i,l=a.alternate;switch(a.tag){case 15:case 0:a=Kv(l,a,a.pendingProps,a.type,void 0,Ne);break;case 11:a=Kv(l,a,a.pendingProps,a.type.render,a.ref,Ne);break;case 5:sh(a);default:t0(l,a),a=ke=Cb(a,Gr),a=Xv(l,a,Gr)}i.memoizedProps=i.pendingProps,a===null?Kc(i):ke=a}function ja(i,a,l,u){Lr=ui=null,sh(a),ma=null,No=0;var m=a.return;try{if(EC(i,m,a,l,Ne)){lt=1,Ic(i,Bn(l,i.current)),ke=null;return}}catch(y){if(m!==null)throw ke=m,y;lt=1,Ic(i,Bn(l,i.current)),ke=null;return}a.flags&32768?(De||u===1?i=!0:Sa||(Ne&536870912)!==0?i=!1:(ws=i=!0,(u===2||u===9||u===3||u===6)&&(u=jn.current,u!==null&&u.tag===13&&(u.flags|=16384))),T0(a,i)):Kc(a)}function Kc(i){var a=i;do{if((a.flags&32768)!==0){T0(a,ws);return}i=a.return;var l=kC(a.alternate,a,Gr);if(l!==null){ke=l;return}if(a=a.sibling,a!==null){ke=a;return}ke=a=i}while(a!==null);lt===0&&(lt=5)}function T0(i,a){do{var l=CC(i.alternate,i);if(l!==null){l.flags&=32767,ke=l;return}if(l=i.return,l!==null&&(l.flags|=32768,l.subtreeFlags=0,l.deletions=null),!a&&(i=i.sibling,i!==null)){ke=i;return}ke=i=l}while(i!==null);lt=6,ke=null}function R0(i,a,l,u,m,y,S,j,V){i.cancelPendingCommit=null;do Yc();while(Ct!==0);if((Fe&6)!==0)throw Error(r(327));if(a!==null){if(a===i.current)throw Error(r(177));if(y=a.lanes|a.childLanes,y|=Tf,mk(i,l,y,S,j,V),i===We&&(ke=We=null,Ne=0),Ea=a,Es=i,Kr=l,Bh=y,Fh=m,w0=u,(a.subtreeFlags&10256)!==0||(a.flags&10256)!==0?(i.callbackNode=null,i.callbackPriority=0,FC(Wl,function(){return U0(),null})):(i.callbackNode=null,i.callbackPriority=0),u=(a.flags&13878)!==0,(a.subtreeFlags&13878)!==0||u){u=z.T,z.T=null,m=$.p,$.p=2,S=Fe,Fe|=4;try{NC(i,a,l)}finally{Fe=S,$.p=m,z.T=u}}Ct=1,D0(),I0(),M0()}}function D0(){if(Ct===1){Ct=0;var i=Es,a=Ea,l=(a.flags&13878)!==0;if((a.subtreeFlags&13878)!==0||l){l=z.T,z.T=null;var u=$.p;$.p=2;var m=Fe;Fe|=4;try{h0(a,i);var y=tp,S=vb(i.containerInfo),j=y.focusedElem,V=y.selectionRange;if(S!==j&&j&&j.ownerDocument&&bb(j.ownerDocument.documentElement,j)){if(V!==null&&jf(j)){var Q=V.start,ne=V.end;if(ne===void 0&&(ne=Q),"selectionStart"in j)j.selectionStart=Q,j.selectionEnd=Math.min(ne,j.value.length);else{var ie=j.ownerDocument||document,X=ie&&ie.defaultView||window;if(X.getSelection){var te=X.getSelection(),de=j.textContent.length,me=Math.min(V.start,de),Ye=V.end===void 0?me:Math.min(V.end,de);!te.extend&&me>Ye&&(S=Ye,Ye=me,me=S);var Z=gb(j,me),Y=gb(j,Ye);if(Z&&Y&&(te.rangeCount!==1||te.anchorNode!==Z.node||te.anchorOffset!==Z.offset||te.focusNode!==Y.node||te.focusOffset!==Y.offset)){var J=ie.createRange();J.setStart(Z.node,Z.offset),te.removeAllRanges(),me>Ye?(te.addRange(J),te.extend(Y.node,Y.offset)):(J.setEnd(Y.node,Y.offset),te.addRange(J))}}}}for(ie=[],te=j;te=te.parentNode;)te.nodeType===1&&ie.push({element:te,left:te.scrollLeft,top:te.scrollTop});for(typeof j.focus=="function"&&j.focus(),j=0;j<ie.length;j++){var re=ie[j];re.element.scrollLeft=re.left,re.element.scrollTop=re.top}}au=!!ep,tp=ep=null}finally{Fe=m,$.p=u,z.T=l}}i.current=a,Ct=2}}function I0(){if(Ct===2){Ct=0;var i=Es,a=Ea,l=(a.flags&8772)!==0;if((a.subtreeFlags&8772)!==0||l){l=z.T,z.T=null;var u=$.p;$.p=2;var m=Fe;Fe|=4;try{l0(i,a.alternate,a)}finally{Fe=m,$.p=u,z.T=l}}Ct=3}}function M0(){if(Ct===4||Ct===3){Ct=0,ak();var i=Es,a=Ea,l=Kr,u=w0;(a.subtreeFlags&10256)!==0||(a.flags&10256)!==0?Ct=5:(Ct=0,Ea=Es=null,L0(i,i.pendingLanes));var m=i.pendingLanes;if(m===0&&(_s=null),of(l),a=a.stateNode,Sn&&typeof Sn.onCommitFiberRoot=="function")try{Sn.onCommitFiberRoot(uo,a,void 0,(a.current.flags&128)===128)}catch{}if(u!==null){a=z.T,m=$.p,$.p=2,z.T=null;try{for(var y=i.onRecoverableError,S=0;S<u.length;S++){var j=u[S];y(j.value,{componentStack:j.stack})}}finally{z.T=a,$.p=m}}(Kr&3)!==0&&Yc(),mr(i),m=i.pendingLanes,(l&261930)!==0&&(m&42)!==0?i===Ph?Go++:(Go=0,Ph=i):Go=0,Ko(0)}}function L0(i,a){(i.pooledCacheLanes&=a)===0&&(a=i.pooledCache,a!=null&&(i.pooledCache=null,ko(a)))}function Yc(){return D0(),I0(),M0(),U0()}function U0(){if(Ct!==5)return!1;var i=Es,a=Bh;Bh=0;var l=of(Kr),u=z.T,m=$.p;try{$.p=32>l?32:l,z.T=null,l=Fh,Fh=null;var y=Es,S=Kr;if(Ct=0,Ea=Es=null,Kr=0,(Fe&6)!==0)throw Error(r(331));var j=Fe;if(Fe|=4,b0(y.current),m0(y,y.current,S,l),Fe=j,Ko(0,!1),Sn&&typeof Sn.onPostCommitFiberRoot=="function")try{Sn.onPostCommitFiberRoot(uo,y)}catch{}return!0}finally{$.p=m,z.T=u,L0(i,a)}}function $0(i,a,l){a=Bn(l,a),a=vh(i.stateNode,a,2),i=gs(i,a,2),i!==null&&(ho(i,2),mr(i))}function Ve(i,a,l){if(i.tag===3)$0(i,i,l);else for(;a!==null;){if(a.tag===3){$0(a,i,l);break}else if(a.tag===1){var u=a.stateNode;if(typeof a.type.getDerivedStateFromError=="function"||typeof u.componentDidCatch=="function"&&(_s===null||!_s.has(u))){i=Bn(l,i),l=Bv(2),u=gs(a,l,2),u!==null&&(Fv(l,u,a,i),ho(u,2),mr(u));break}}a=a.return}}function Vh(i,a,l){var u=i.pingCache;if(u===null){u=i.pingCache=new RC;var m=new Set;u.set(a,m)}else m=u.get(a),m===void 0&&(m=new Set,u.set(a,m));m.has(l)||(Lh=!0,m.add(l),i=UC.bind(null,i,a,l),a.then(i,i))}function UC(i,a,l){var u=i.pingCache;u!==null&&u.delete(a),i.pingedLanes|=i.suspendedLanes&l,i.warmLanes&=~l,We===i&&(Ne&l)===l&&(lt===4||lt===3&&(Ne&62914560)===Ne&&300>wn()-qc?(Fe&2)===0&&Aa(i,0):Uh|=l,_a===Ne&&(_a=0)),mr(i)}function B0(i,a){a===0&&(a=Dg()),i=oi(i,a),i!==null&&(ho(i,a),mr(i))}function $C(i){var a=i.memoizedState,l=0;a!==null&&(l=a.retryLane),B0(i,l)}function BC(i,a){var l=0;switch(i.tag){case 31:case 13:var u=i.stateNode,m=i.memoizedState;m!==null&&(l=m.retryLane);break;case 19:u=i.stateNode;break;case 22:u=i.stateNode._retryCache;break;default:throw Error(r(314))}u!==null&&u.delete(a),B0(i,l)}function FC(i,a){return nf(i,a)}var Zc=null,ka=null,Hh=!1,Wc=!1,Gh=!1,js=0;function mr(i){i!==ka&&i.next===null&&(ka===null?Zc=ka=i:ka=ka.next=i),Wc=!0,Hh||(Hh=!0,qC())}function Ko(i,a){if(!Gh&&Wc){Gh=!0;do for(var l=!1,u=Zc;u!==null;){if(i!==0){var m=u.pendingLanes;if(m===0)var y=0;else{var S=u.suspendedLanes,j=u.pingedLanes;y=(1<<31-_n(42|i)+1)-1,y&=m&~(S&~j),y=y&201326741?y&201326741|1:y?y|2:0}y!==0&&(l=!0,z0(u,y))}else y=Ne,y=ec(u,u===We?y:0,u.cancelPendingCommit!==null||u.timeoutHandle!==-1),(y&3)===0||fo(u,y)||(l=!0,z0(u,y));u=u.next}while(l);Gh=!1}}function PC(){F0()}function F0(){Wc=Hh=!1;var i=0;js!==0&&QC()&&(i=js);for(var a=wn(),l=null,u=Zc;u!==null;){var m=u.next,y=P0(u,a);y===0?(u.next=null,l===null?Zc=m:l.next=m,m===null&&(ka=l)):(l=u,(i!==0||(y&3)!==0)&&(Wc=!0)),u=m}Ct!==0&&Ct!==5||Ko(i),js!==0&&(js=0)}function P0(i,a){for(var l=i.suspendedLanes,u=i.pingedLanes,m=i.expirationTimes,y=i.pendingLanes&-62914561;0<y;){var S=31-_n(y),j=1<<S,V=m[S];V===-1?((j&l)===0||(j&u)!==0)&&(m[S]=pk(j,a)):V<=a&&(i.expiredLanes|=j),y&=~j}if(a=We,l=Ne,l=ec(i,i===a?l:0,i.cancelPendingCommit!==null||i.timeoutHandle!==-1),u=i.callbackNode,l===0||i===a&&(ze===2||ze===9)||i.cancelPendingCommit!==null)return u!==null&&u!==null&&rf(u),i.callbackNode=null,i.callbackPriority=0;if((l&3)===0||fo(i,l)){if(a=l&-l,a===i.callbackPriority)return a;switch(u!==null&&rf(u),of(l)){case 2:case 8:l=Tg;break;case 32:l=Wl;break;case 268435456:l=Rg;break;default:l=Wl}return u=q0.bind(null,i),l=nf(l,u),i.callbackPriority=a,i.callbackNode=l,a}return u!==null&&u!==null&&rf(u),i.callbackPriority=2,i.callbackNode=null,2}function q0(i,a){if(Ct!==0&&Ct!==5)return i.callbackNode=null,i.callbackPriority=0,null;var l=i.callbackNode;if(Yc()&&i.callbackNode!==l)return null;var u=Ne;return u=ec(i,i===We?u:0,i.cancelPendingCommit!==null||i.timeoutHandle!==-1),u===0?null:(_0(i,u,a),P0(i,wn()),i.callbackNode!=null&&i.callbackNode===l?q0.bind(null,i):null)}function z0(i,a){if(Yc())return null;_0(i,a,!0)}function qC(){eN(function(){(Fe&6)!==0?nf(Og,PC):F0()})}function Kh(){if(js===0){var i=fa;i===0&&(i=Jl,Jl<<=1,(Jl&261888)===0&&(Jl=256)),js=i}return js}function V0(i){return i==null||typeof i=="symbol"||typeof i=="boolean"?null:typeof i=="function"?i:sc(""+i)}function H0(i,a){var l=a.ownerDocument.createElement("input");return l.name=a.name,l.value=a.value,i.id&&l.setAttribute("form",i.id),a.parentNode.insertBefore(l,a),i=new FormData(i),l.parentNode.removeChild(l),i}function zC(i,a,l,u,m){if(a==="submit"&&l&&l.stateNode===m){var y=V0((m[cn]||null).action),S=u.submitter;S&&(a=(a=S[cn]||null)?V0(a.formAction):S.getAttribute("formAction"),a!==null&&(y=a,S=null));var j=new lc("action","action",null,u,m);i.push({event:j,listeners:[{instance:null,listener:function(){if(u.defaultPrevented){if(js!==0){var V=S?H0(m,S):new FormData(m);hh(l,{pending:!0,data:V,method:m.method,action:y},null,V)}}else typeof y=="function"&&(j.preventDefault(),V=S?H0(m,S):new FormData(m),hh(l,{pending:!0,data:V,method:m.method,action:y},y,V))},currentTarget:m}]})}}for(var Yh=0;Yh<Of.length;Yh++){var Zh=Of[Yh],VC=Zh.toLowerCase(),HC=Zh[0].toUpperCase()+Zh.slice(1);nr(VC,"on"+HC)}nr(Sb,"onAnimationEnd"),nr(_b,"onAnimationIteration"),nr(Eb,"onAnimationStart"),nr("dblclick","onDoubleClick"),nr("focusin","onFocus"),nr("focusout","onBlur"),nr(oC,"onTransitionRun"),nr(lC,"onTransitionStart"),nr(cC,"onTransitionCancel"),nr(Ab,"onTransitionEnd"),Qi("onMouseEnter",["mouseout","mouseover"]),Qi("onMouseLeave",["mouseout","mouseover"]),Qi("onPointerEnter",["pointerout","pointerover"]),Qi("onPointerLeave",["pointerout","pointerover"]),ri("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),ri("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),ri("onBeforeInput",["compositionend","keypress","textInput","paste"]),ri("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),ri("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),ri("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var Yo="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),GC=new Set("beforetoggle cancel close invalid load scroll scrollend toggle".split(" ").concat(Yo));function G0(i,a){a=(a&4)!==0;for(var l=0;l<i.length;l++){var u=i[l],m=u.event;u=u.listeners;e:{var y=void 0;if(a)for(var S=u.length-1;0<=S;S--){var j=u[S],V=j.instance,Q=j.currentTarget;if(j=j.listener,V!==y&&m.isPropagationStopped())break e;y=j,m.currentTarget=Q;try{y(m)}catch(ne){dc(ne)}m.currentTarget=null,y=V}else for(S=0;S<u.length;S++){if(j=u[S],V=j.instance,Q=j.currentTarget,j=j.listener,V!==y&&m.isPropagationStopped())break e;y=j,m.currentTarget=Q;try{y(m)}catch(ne){dc(ne)}m.currentTarget=null,y=V}}}}function Ce(i,a){var l=a[lf];l===void 0&&(l=a[lf]=new Set);var u=i+"__bubble";l.has(u)||(K0(a,i,2,!1),l.add(u))}function Wh(i,a,l){var u=0;a&&(u|=4),K0(l,i,u,a)}var Jc="_reactListening"+Math.random().toString(36).slice(2);function Jh(i){if(!i[Jc]){i[Jc]=!0,Fg.forEach(function(l){l!=="selectionchange"&&(GC.has(l)||Wh(l,!1,i),Wh(l,!0,i))});var a=i.nodeType===9?i:i.ownerDocument;a===null||a[Jc]||(a[Jc]=!0,Wh("selectionchange",!1,a))}}function K0(i,a,l,u){switch(Sx(a)){case 2:var m=xN;break;case 8:m=wN;break;default:m=fp}l=m.bind(null,a,l,i),m=void 0,!gf||a!=="touchstart"&&a!=="touchmove"&&a!=="wheel"||(m=!0),u?m!==void 0?i.addEventListener(a,l,{capture:!0,passive:m}):i.addEventListener(a,l,!0):m!==void 0?i.addEventListener(a,l,{passive:m}):i.addEventListener(a,l,!1)}function Qh(i,a,l,u,m){var y=u;if((a&1)===0&&(a&2)===0&&u!==null)e:for(;;){if(u===null)return;var S=u.tag;if(S===3||S===4){var j=u.stateNode.containerInfo;if(j===m)break;if(S===4)for(S=u.return;S!==null;){var V=S.tag;if((V===3||V===4)&&S.stateNode.containerInfo===m)return;S=S.return}for(;j!==null;){if(S=Zi(j),S===null)return;if(V=S.tag,V===5||V===6||V===26||V===27){u=y=S;continue e}j=j.parentNode}}u=u.return}Qg(function(){var Q=y,ne=mf(l),ie=[];e:{var X=jb.get(i);if(X!==void 0){var te=lc,de=i;switch(i){case"keypress":if(ac(l)===0)break e;case"keydown":case"keyup":te=Bk;break;case"focusin":de="focus",te=wf;break;case"focusout":de="blur",te=wf;break;case"beforeblur":case"afterblur":te=wf;break;case"click":if(l.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":te=tb;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":te=kk;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":te=qk;break;case Sb:case _b:case Eb:te=Ok;break;case Ab:te=Vk;break;case"scroll":case"scrollend":te=Ak;break;case"wheel":te=Gk;break;case"copy":case"cut":case"paste":te=Rk;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":te=rb;break;case"toggle":case"beforetoggle":te=Yk}var me=(a&4)!==0,Ye=!me&&(i==="scroll"||i==="scrollend"),Z=me?X!==null?X+"Capture":null:X;me=[];for(var Y=Q,J;Y!==null;){var re=Y;if(J=re.stateNode,re=re.tag,re!==5&&re!==26&&re!==27||J===null||Z===null||(re=yo(Y,Z),re!=null&&me.push(Zo(Y,re,J))),Ye)break;Y=Y.return}0<me.length&&(X=new te(X,de,null,l,ne),ie.push({event:X,listeners:me}))}}if((a&7)===0){e:{if(X=i==="mouseover"||i==="pointerover",te=i==="mouseout"||i==="pointerout",X&&l!==pf&&(de=l.relatedTarget||l.fromElement)&&(Zi(de)||de[Yi]))break e;if((te||X)&&(X=ne.window===ne?ne:(X=ne.ownerDocument)?X.defaultView||X.parentWindow:window,te?(de=l.relatedTarget||l.toElement,te=Q,de=de?Zi(de):null,de!==null&&(Ye=o(de),me=de.tag,de!==Ye||me!==5&&me!==27&&me!==6)&&(de=null)):(te=null,de=Q),te!==de)){if(me=tb,re="onMouseLeave",Z="onMouseEnter",Y="mouse",(i==="pointerout"||i==="pointerover")&&(me=rb,re="onPointerLeave",Z="onPointerEnter",Y="pointer"),Ye=te==null?X:mo(te),J=de==null?X:mo(de),X=new me(re,Y+"leave",te,l,ne),X.target=Ye,X.relatedTarget=J,re=null,Zi(ne)===Q&&(me=new me(Z,Y+"enter",de,l,ne),me.target=J,me.relatedTarget=Ye,re=me),Ye=re,te&&de)t:{for(me=KC,Z=te,Y=de,J=0,re=Z;re;re=me(re))J++;re=0;for(var pe=Y;pe;pe=me(pe))re++;for(;0<J-re;)Z=me(Z),J--;for(;0<re-J;)Y=me(Y),re--;for(;J--;){if(Z===Y||Y!==null&&Z===Y.alternate){me=Z;break t}Z=me(Z),Y=me(Y)}me=null}else me=null;te!==null&&Y0(ie,X,te,me,!1),de!==null&&Ye!==null&&Y0(ie,Ye,de,me,!0)}}e:{if(X=Q?mo(Q):window,te=X.nodeName&&X.nodeName.toLowerCase(),te==="select"||te==="input"&&X.type==="file")var Ue=db;else if(cb(X))if(fb)Ue=sC;else{Ue=nC;var fe=tC}else te=X.nodeName,!te||te.toLowerCase()!=="input"||X.type!=="checkbox"&&X.type!=="radio"?Q&&hf(Q.elementType)&&(Ue=db):Ue=rC;if(Ue&&(Ue=Ue(i,Q))){ub(ie,Ue,l,ne);break e}fe&&fe(i,X,Q),i==="focusout"&&Q&&X.type==="number"&&Q.memoizedProps.value!=null&&ff(X,"number",X.value)}switch(fe=Q?mo(Q):window,i){case"focusin":(cb(fe)||fe.contentEditable==="true")&&(sa=fe,kf=Q,Eo=null);break;case"focusout":Eo=kf=sa=null;break;case"mousedown":Cf=!0;break;case"contextmenu":case"mouseup":case"dragend":Cf=!1,xb(ie,l,ne);break;case"selectionchange":if(aC)break;case"keydown":case"keyup":xb(ie,l,ne)}var Se;if(_f)e:{switch(i){case"compositionstart":var Oe="onCompositionStart";break e;case"compositionend":Oe="onCompositionEnd";break e;case"compositionupdate":Oe="onCompositionUpdate";break e}Oe=void 0}else ra?ob(i,l)&&(Oe="onCompositionEnd"):i==="keydown"&&l.keyCode===229&&(Oe="onCompositionStart");Oe&&(sb&&l.locale!=="ko"&&(ra||Oe!=="onCompositionStart"?Oe==="onCompositionEnd"&&ra&&(Se=Xg()):(us=ne,bf="value"in us?us.value:us.textContent,ra=!0)),fe=Qc(Q,Oe),0<fe.length&&(Oe=new nb(Oe,i,null,l,ne),ie.push({event:Oe,listeners:fe}),Se?Oe.data=Se:(Se=lb(l),Se!==null&&(Oe.data=Se)))),(Se=Wk?Jk(i,l):Qk(i,l))&&(Oe=Qc(Q,"onBeforeInput"),0<Oe.length&&(fe=new nb("onBeforeInput","beforeinput",null,l,ne),ie.push({event:fe,listeners:Oe}),fe.data=Se)),zC(ie,i,Q,l,ne)}G0(ie,a)})}function Zo(i,a,l){return{instance:i,listener:a,currentTarget:l}}function Qc(i,a){for(var l=a+"Capture",u=[];i!==null;){var m=i,y=m.stateNode;if(m=m.tag,m!==5&&m!==26&&m!==27||y===null||(m=yo(i,l),m!=null&&u.unshift(Zo(i,m,y)),m=yo(i,a),m!=null&&u.push(Zo(i,m,y))),i.tag===3)return u;i=i.return}return[]}function KC(i){if(i===null)return null;do i=i.return;while(i&&i.tag!==5&&i.tag!==27);return i||null}function Y0(i,a,l,u,m){for(var y=a._reactName,S=[];l!==null&&l!==u;){var j=l,V=j.alternate,Q=j.stateNode;if(j=j.tag,V!==null&&V===u)break;j!==5&&j!==26&&j!==27||Q===null||(V=Q,m?(Q=yo(l,y),Q!=null&&S.unshift(Zo(l,Q,V))):m||(Q=yo(l,y),Q!=null&&S.push(Zo(l,Q,V)))),l=l.return}S.length!==0&&i.push({event:a,listeners:S})}var YC=/\r\n?/g,ZC=/\u0000|\uFFFD/g;function Z0(i){return(typeof i=="string"?i:""+i).replace(YC,`
|
|
49
|
-
`).replace(ZC,"")}function W0(i,a){return a=Z0(a),Z0(i)===a}function Ke(i,a,l,u,m,y){switch(l){case"children":typeof u=="string"?a==="body"||a==="textarea"&&u===""||ea(i,u):(typeof u=="number"||typeof u=="bigint")&&a!=="body"&&ea(i,""+u);break;case"className":nc(i,"class",u);break;case"tabIndex":nc(i,"tabindex",u);break;case"dir":case"role":case"viewBox":case"width":case"height":nc(i,l,u);break;case"style":Wg(i,u,y);break;case"data":if(a!=="object"){nc(i,"data",u);break}case"src":case"href":if(u===""&&(a!=="a"||l!=="href")){i.removeAttribute(l);break}if(u==null||typeof u=="function"||typeof u=="symbol"||typeof u=="boolean"){i.removeAttribute(l);break}u=sc(""+u),i.setAttribute(l,u);break;case"action":case"formAction":if(typeof u=="function"){i.setAttribute(l,"javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')");break}else typeof y=="function"&&(l==="formAction"?(a!=="input"&&Ke(i,a,"name",m.name,m,null),Ke(i,a,"formEncType",m.formEncType,m,null),Ke(i,a,"formMethod",m.formMethod,m,null),Ke(i,a,"formTarget",m.formTarget,m,null)):(Ke(i,a,"encType",m.encType,m,null),Ke(i,a,"method",m.method,m,null),Ke(i,a,"target",m.target,m,null)));if(u==null||typeof u=="symbol"||typeof u=="boolean"){i.removeAttribute(l);break}u=sc(""+u),i.setAttribute(l,u);break;case"onClick":u!=null&&(i.onclick=Rr);break;case"onScroll":u!=null&&Ce("scroll",i);break;case"onScrollEnd":u!=null&&Ce("scrollend",i);break;case"dangerouslySetInnerHTML":if(u!=null){if(typeof u!="object"||!("__html"in u))throw Error(r(61));if(l=u.__html,l!=null){if(m.children!=null)throw Error(r(60));i.innerHTML=l}}break;case"multiple":i.multiple=u&&typeof u!="function"&&typeof u!="symbol";break;case"muted":i.muted=u&&typeof u!="function"&&typeof u!="symbol";break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"defaultValue":case"defaultChecked":case"innerHTML":case"ref":break;case"autoFocus":break;case"xlinkHref":if(u==null||typeof u=="function"||typeof u=="boolean"||typeof u=="symbol"){i.removeAttribute("xlink:href");break}l=sc(""+u),i.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",l);break;case"contentEditable":case"spellCheck":case"draggable":case"value":case"autoReverse":case"externalResourcesRequired":case"focusable":case"preserveAlpha":u!=null&&typeof u!="function"&&typeof u!="symbol"?i.setAttribute(l,""+u):i.removeAttribute(l);break;case"inert":case"allowFullScreen":case"async":case"autoPlay":case"controls":case"default":case"defer":case"disabled":case"disablePictureInPicture":case"disableRemotePlayback":case"formNoValidate":case"hidden":case"loop":case"noModule":case"noValidate":case"open":case"playsInline":case"readOnly":case"required":case"reversed":case"scoped":case"seamless":case"itemScope":u&&typeof u!="function"&&typeof u!="symbol"?i.setAttribute(l,""):i.removeAttribute(l);break;case"capture":case"download":u===!0?i.setAttribute(l,""):u!==!1&&u!=null&&typeof u!="function"&&typeof u!="symbol"?i.setAttribute(l,u):i.removeAttribute(l);break;case"cols":case"rows":case"size":case"span":u!=null&&typeof u!="function"&&typeof u!="symbol"&&!isNaN(u)&&1<=u?i.setAttribute(l,u):i.removeAttribute(l);break;case"rowSpan":case"start":u==null||typeof u=="function"||typeof u=="symbol"||isNaN(u)?i.removeAttribute(l):i.setAttribute(l,u);break;case"popover":Ce("beforetoggle",i),Ce("toggle",i),tc(i,"popover",u);break;case"xlinkActuate":Tr(i,"http://www.w3.org/1999/xlink","xlink:actuate",u);break;case"xlinkArcrole":Tr(i,"http://www.w3.org/1999/xlink","xlink:arcrole",u);break;case"xlinkRole":Tr(i,"http://www.w3.org/1999/xlink","xlink:role",u);break;case"xlinkShow":Tr(i,"http://www.w3.org/1999/xlink","xlink:show",u);break;case"xlinkTitle":Tr(i,"http://www.w3.org/1999/xlink","xlink:title",u);break;case"xlinkType":Tr(i,"http://www.w3.org/1999/xlink","xlink:type",u);break;case"xmlBase":Tr(i,"http://www.w3.org/XML/1998/namespace","xml:base",u);break;case"xmlLang":Tr(i,"http://www.w3.org/XML/1998/namespace","xml:lang",u);break;case"xmlSpace":Tr(i,"http://www.w3.org/XML/1998/namespace","xml:space",u);break;case"is":tc(i,"is",u);break;case"innerText":case"textContent":break;default:(!(2<l.length)||l[0]!=="o"&&l[0]!=="O"||l[1]!=="n"&&l[1]!=="N")&&(l=_k.get(l)||l,tc(i,l,u))}}function Xh(i,a,l,u,m,y){switch(l){case"style":Wg(i,u,y);break;case"dangerouslySetInnerHTML":if(u!=null){if(typeof u!="object"||!("__html"in u))throw Error(r(61));if(l=u.__html,l!=null){if(m.children!=null)throw Error(r(60));i.innerHTML=l}}break;case"children":typeof u=="string"?ea(i,u):(typeof u=="number"||typeof u=="bigint")&&ea(i,""+u);break;case"onScroll":u!=null&&Ce("scroll",i);break;case"onScrollEnd":u!=null&&Ce("scrollend",i);break;case"onClick":u!=null&&(i.onclick=Rr);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"innerHTML":case"ref":break;case"innerText":case"textContent":break;default:if(!Pg.hasOwnProperty(l))e:{if(l[0]==="o"&&l[1]==="n"&&(m=l.endsWith("Capture"),a=l.slice(2,m?l.length-7:void 0),y=i[cn]||null,y=y!=null?y[l]:null,typeof y=="function"&&i.removeEventListener(a,y,m),typeof u=="function")){typeof y!="function"&&y!==null&&(l in i?i[l]=null:i.hasAttribute(l)&&i.removeAttribute(l)),i.addEventListener(a,u,m);break e}l in i?i[l]=u:u===!0?i.setAttribute(l,""):tc(i,l,u)}}}function Bt(i,a,l){switch(a){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"img":Ce("error",i),Ce("load",i);var u=!1,m=!1,y;for(y in l)if(l.hasOwnProperty(y)){var S=l[y];if(S!=null)switch(y){case"src":u=!0;break;case"srcSet":m=!0;break;case"children":case"dangerouslySetInnerHTML":throw Error(r(137,a));default:Ke(i,a,y,S,l,null)}}m&&Ke(i,a,"srcSet",l.srcSet,l,null),u&&Ke(i,a,"src",l.src,l,null);return;case"input":Ce("invalid",i);var j=y=S=m=null,V=null,Q=null;for(u in l)if(l.hasOwnProperty(u)){var ne=l[u];if(ne!=null)switch(u){case"name":m=ne;break;case"type":S=ne;break;case"checked":V=ne;break;case"defaultChecked":Q=ne;break;case"value":y=ne;break;case"defaultValue":j=ne;break;case"children":case"dangerouslySetInnerHTML":if(ne!=null)throw Error(r(137,a));break;default:Ke(i,a,u,ne,l,null)}}Gg(i,y,j,V,Q,S,m,!1);return;case"select":Ce("invalid",i),u=S=y=null;for(m in l)if(l.hasOwnProperty(m)&&(j=l[m],j!=null))switch(m){case"value":y=j;break;case"defaultValue":S=j;break;case"multiple":u=j;default:Ke(i,a,m,j,l,null)}a=y,l=S,i.multiple=!!u,a!=null?Xi(i,!!u,a,!1):l!=null&&Xi(i,!!u,l,!0);return;case"textarea":Ce("invalid",i),y=m=u=null;for(S in l)if(l.hasOwnProperty(S)&&(j=l[S],j!=null))switch(S){case"value":u=j;break;case"defaultValue":m=j;break;case"children":y=j;break;case"dangerouslySetInnerHTML":if(j!=null)throw Error(r(91));break;default:Ke(i,a,S,j,l,null)}Yg(i,u,m,y);return;case"option":for(V in l)if(l.hasOwnProperty(V)&&(u=l[V],u!=null))switch(V){case"selected":i.selected=u&&typeof u!="function"&&typeof u!="symbol";break;default:Ke(i,a,V,u,l,null)}return;case"dialog":Ce("beforetoggle",i),Ce("toggle",i),Ce("cancel",i),Ce("close",i);break;case"iframe":case"object":Ce("load",i);break;case"video":case"audio":for(u=0;u<Yo.length;u++)Ce(Yo[u],i);break;case"image":Ce("error",i),Ce("load",i);break;case"details":Ce("toggle",i);break;case"embed":case"source":case"link":Ce("error",i),Ce("load",i);case"area":case"base":case"br":case"col":case"hr":case"keygen":case"meta":case"param":case"track":case"wbr":case"menuitem":for(Q in l)if(l.hasOwnProperty(Q)&&(u=l[Q],u!=null))switch(Q){case"children":case"dangerouslySetInnerHTML":throw Error(r(137,a));default:Ke(i,a,Q,u,l,null)}return;default:if(hf(a)){for(ne in l)l.hasOwnProperty(ne)&&(u=l[ne],u!==void 0&&Xh(i,a,ne,u,l,void 0));return}}for(j in l)l.hasOwnProperty(j)&&(u=l[j],u!=null&&Ke(i,a,j,u,l,null))}function WC(i,a,l,u){switch(a){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"input":var m=null,y=null,S=null,j=null,V=null,Q=null,ne=null;for(te in l){var ie=l[te];if(l.hasOwnProperty(te)&&ie!=null)switch(te){case"checked":break;case"value":break;case"defaultValue":V=ie;default:u.hasOwnProperty(te)||Ke(i,a,te,null,u,ie)}}for(var X in u){var te=u[X];if(ie=l[X],u.hasOwnProperty(X)&&(te!=null||ie!=null))switch(X){case"type":y=te;break;case"name":m=te;break;case"checked":Q=te;break;case"defaultChecked":ne=te;break;case"value":S=te;break;case"defaultValue":j=te;break;case"children":case"dangerouslySetInnerHTML":if(te!=null)throw Error(r(137,a));break;default:te!==ie&&Ke(i,a,X,te,u,ie)}}df(i,S,j,V,Q,ne,y,m);return;case"select":te=S=j=X=null;for(y in l)if(V=l[y],l.hasOwnProperty(y)&&V!=null)switch(y){case"value":break;case"multiple":te=V;default:u.hasOwnProperty(y)||Ke(i,a,y,null,u,V)}for(m in u)if(y=u[m],V=l[m],u.hasOwnProperty(m)&&(y!=null||V!=null))switch(m){case"value":X=y;break;case"defaultValue":j=y;break;case"multiple":S=y;default:y!==V&&Ke(i,a,m,y,u,V)}a=j,l=S,u=te,X!=null?Xi(i,!!l,X,!1):!!u!=!!l&&(a!=null?Xi(i,!!l,a,!0):Xi(i,!!l,l?[]:"",!1));return;case"textarea":te=X=null;for(j in l)if(m=l[j],l.hasOwnProperty(j)&&m!=null&&!u.hasOwnProperty(j))switch(j){case"value":break;case"children":break;default:Ke(i,a,j,null,u,m)}for(S in u)if(m=u[S],y=l[S],u.hasOwnProperty(S)&&(m!=null||y!=null))switch(S){case"value":X=m;break;case"defaultValue":te=m;break;case"children":break;case"dangerouslySetInnerHTML":if(m!=null)throw Error(r(91));break;default:m!==y&&Ke(i,a,S,m,u,y)}Kg(i,X,te);return;case"option":for(var de in l)if(X=l[de],l.hasOwnProperty(de)&&X!=null&&!u.hasOwnProperty(de))switch(de){case"selected":i.selected=!1;break;default:Ke(i,a,de,null,u,X)}for(V in u)if(X=u[V],te=l[V],u.hasOwnProperty(V)&&X!==te&&(X!=null||te!=null))switch(V){case"selected":i.selected=X&&typeof X!="function"&&typeof X!="symbol";break;default:Ke(i,a,V,X,u,te)}return;case"img":case"link":case"area":case"base":case"br":case"col":case"embed":case"hr":case"keygen":case"meta":case"param":case"source":case"track":case"wbr":case"menuitem":for(var me in l)X=l[me],l.hasOwnProperty(me)&&X!=null&&!u.hasOwnProperty(me)&&Ke(i,a,me,null,u,X);for(Q in u)if(X=u[Q],te=l[Q],u.hasOwnProperty(Q)&&X!==te&&(X!=null||te!=null))switch(Q){case"children":case"dangerouslySetInnerHTML":if(X!=null)throw Error(r(137,a));break;default:Ke(i,a,Q,X,u,te)}return;default:if(hf(a)){for(var Ye in l)X=l[Ye],l.hasOwnProperty(Ye)&&X!==void 0&&!u.hasOwnProperty(Ye)&&Xh(i,a,Ye,void 0,u,X);for(ne in u)X=u[ne],te=l[ne],!u.hasOwnProperty(ne)||X===te||X===void 0&&te===void 0||Xh(i,a,ne,X,u,te);return}}for(var Z in l)X=l[Z],l.hasOwnProperty(Z)&&X!=null&&!u.hasOwnProperty(Z)&&Ke(i,a,Z,null,u,X);for(ie in u)X=u[ie],te=l[ie],!u.hasOwnProperty(ie)||X===te||X==null&&te==null||Ke(i,a,ie,X,u,te)}function J0(i){switch(i){case"css":case"script":case"font":case"img":case"image":case"input":case"link":return!0;default:return!1}}function JC(){if(typeof performance.getEntriesByType=="function"){for(var i=0,a=0,l=performance.getEntriesByType("resource"),u=0;u<l.length;u++){var m=l[u],y=m.transferSize,S=m.initiatorType,j=m.duration;if(y&&j&&J0(S)){for(S=0,j=m.responseEnd,u+=1;u<l.length;u++){var V=l[u],Q=V.startTime;if(Q>j)break;var ne=V.transferSize,ie=V.initiatorType;ne&&J0(ie)&&(V=V.responseEnd,S+=ne*(V<j?1:(j-Q)/(V-Q)))}if(--u,a+=8*(y+S)/(m.duration/1e3),i++,10<i)break}}if(0<i)return a/i/1e6}return navigator.connection&&(i=navigator.connection.downlink,typeof i=="number")?i:5}var ep=null,tp=null;function Xc(i){return i.nodeType===9?i:i.ownerDocument}function Q0(i){switch(i){case"http://www.w3.org/2000/svg":return 1;case"http://www.w3.org/1998/Math/MathML":return 2;default:return 0}}function X0(i,a){if(i===0)switch(a){case"svg":return 1;case"math":return 2;default:return 0}return i===1&&a==="foreignObject"?0:i}function np(i,a){return i==="textarea"||i==="noscript"||typeof a.children=="string"||typeof a.children=="number"||typeof a.children=="bigint"||typeof a.dangerouslySetInnerHTML=="object"&&a.dangerouslySetInnerHTML!==null&&a.dangerouslySetInnerHTML.__html!=null}var rp=null;function QC(){var i=window.event;return i&&i.type==="popstate"?i===rp?!1:(rp=i,!0):(rp=null,!1)}var ex=typeof setTimeout=="function"?setTimeout:void 0,XC=typeof clearTimeout=="function"?clearTimeout:void 0,tx=typeof Promise=="function"?Promise:void 0,eN=typeof queueMicrotask=="function"?queueMicrotask:typeof tx<"u"?function(i){return tx.resolve(null).then(i).catch(tN)}:ex;function tN(i){setTimeout(function(){throw i})}function ks(i){return i==="head"}function nx(i,a){var l=a,u=0;do{var m=l.nextSibling;if(i.removeChild(l),m&&m.nodeType===8)if(l=m.data,l==="/$"||l==="/&"){if(u===0){i.removeChild(m),Ta(a);return}u--}else if(l==="$"||l==="$?"||l==="$~"||l==="$!"||l==="&")u++;else if(l==="html")Wo(i.ownerDocument.documentElement);else if(l==="head"){l=i.ownerDocument.head,Wo(l);for(var y=l.firstChild;y;){var S=y.nextSibling,j=y.nodeName;y[po]||j==="SCRIPT"||j==="STYLE"||j==="LINK"&&y.rel.toLowerCase()==="stylesheet"||l.removeChild(y),y=S}}else l==="body"&&Wo(i.ownerDocument.body);l=m}while(l);Ta(a)}function rx(i,a){var l=i;i=0;do{var u=l.nextSibling;if(l.nodeType===1?a?(l._stashedDisplay=l.style.display,l.style.display="none"):(l.style.display=l._stashedDisplay||"",l.getAttribute("style")===""&&l.removeAttribute("style")):l.nodeType===3&&(a?(l._stashedText=l.nodeValue,l.nodeValue=""):l.nodeValue=l._stashedText||""),u&&u.nodeType===8)if(l=u.data,l==="/$"){if(i===0)break;i--}else l!=="$"&&l!=="$?"&&l!=="$~"&&l!=="$!"||i++;l=u}while(l)}function sp(i){var a=i.firstChild;for(a&&a.nodeType===10&&(a=a.nextSibling);a;){var l=a;switch(a=a.nextSibling,l.nodeName){case"HTML":case"HEAD":case"BODY":sp(l),cf(l);continue;case"SCRIPT":case"STYLE":continue;case"LINK":if(l.rel.toLowerCase()==="stylesheet")continue}i.removeChild(l)}}function nN(i,a,l,u){for(;i.nodeType===1;){var m=l;if(i.nodeName.toLowerCase()!==a.toLowerCase()){if(!u&&(i.nodeName!=="INPUT"||i.type!=="hidden"))break}else if(u){if(!i[po])switch(a){case"meta":if(!i.hasAttribute("itemprop"))break;return i;case"link":if(y=i.getAttribute("rel"),y==="stylesheet"&&i.hasAttribute("data-precedence"))break;if(y!==m.rel||i.getAttribute("href")!==(m.href==null||m.href===""?null:m.href)||i.getAttribute("crossorigin")!==(m.crossOrigin==null?null:m.crossOrigin)||i.getAttribute("title")!==(m.title==null?null:m.title))break;return i;case"style":if(i.hasAttribute("data-precedence"))break;return i;case"script":if(y=i.getAttribute("src"),(y!==(m.src==null?null:m.src)||i.getAttribute("type")!==(m.type==null?null:m.type)||i.getAttribute("crossorigin")!==(m.crossOrigin==null?null:m.crossOrigin))&&y&&i.hasAttribute("async")&&!i.hasAttribute("itemprop"))break;return i;default:return i}}else if(a==="input"&&i.type==="hidden"){var y=m.name==null?null:""+m.name;if(m.type==="hidden"&&i.getAttribute("name")===y)return i}else return i;if(i=Vn(i.nextSibling),i===null)break}return null}function rN(i,a,l){if(a==="")return null;for(;i.nodeType!==3;)if((i.nodeType!==1||i.nodeName!=="INPUT"||i.type!=="hidden")&&!l||(i=Vn(i.nextSibling),i===null))return null;return i}function sx(i,a){for(;i.nodeType!==8;)if((i.nodeType!==1||i.nodeName!=="INPUT"||i.type!=="hidden")&&!a||(i=Vn(i.nextSibling),i===null))return null;return i}function ip(i){return i.data==="$?"||i.data==="$~"}function ap(i){return i.data==="$!"||i.data==="$?"&&i.ownerDocument.readyState!=="loading"}function sN(i,a){var l=i.ownerDocument;if(i.data==="$~")i._reactRetry=a;else if(i.data!=="$?"||l.readyState!=="loading")a();else{var u=function(){a(),l.removeEventListener("DOMContentLoaded",u)};l.addEventListener("DOMContentLoaded",u),i._reactRetry=u}}function Vn(i){for(;i!=null;i=i.nextSibling){var a=i.nodeType;if(a===1||a===3)break;if(a===8){if(a=i.data,a==="$"||a==="$!"||a==="$?"||a==="$~"||a==="&"||a==="F!"||a==="F")break;if(a==="/$"||a==="/&")return null}}return i}var op=null;function ix(i){i=i.nextSibling;for(var a=0;i;){if(i.nodeType===8){var l=i.data;if(l==="/$"||l==="/&"){if(a===0)return Vn(i.nextSibling);a--}else l!=="$"&&l!=="$!"&&l!=="$?"&&l!=="$~"&&l!=="&"||a++}i=i.nextSibling}return null}function ax(i){i=i.previousSibling;for(var a=0;i;){if(i.nodeType===8){var l=i.data;if(l==="$"||l==="$!"||l==="$?"||l==="$~"||l==="&"){if(a===0)return i;a--}else l!=="/$"&&l!=="/&"||a++}i=i.previousSibling}return null}function ox(i,a,l){switch(a=Xc(l),i){case"html":if(i=a.documentElement,!i)throw Error(r(452));return i;case"head":if(i=a.head,!i)throw Error(r(453));return i;case"body":if(i=a.body,!i)throw Error(r(454));return i;default:throw Error(r(451))}}function Wo(i){for(var a=i.attributes;a.length;)i.removeAttributeNode(a[0]);cf(i)}var Hn=new Map,lx=new Set;function eu(i){return typeof i.getRootNode=="function"?i.getRootNode():i.nodeType===9?i:i.ownerDocument}var Yr=$.d;$.d={f:iN,r:aN,D:oN,C:lN,L:cN,m:uN,X:fN,S:dN,M:hN};function iN(){var i=Yr.f(),a=Hc();return i||a}function aN(i){var a=Wi(i);a!==null&&a.tag===5&&a.type==="form"?Av(a):Yr.r(i)}var Ca=typeof document>"u"?null:document;function cx(i,a,l){var u=Ca;if(u&&typeof a=="string"&&a){var m=Un(a);m='link[rel="'+i+'"][href="'+m+'"]',typeof l=="string"&&(m+='[crossorigin="'+l+'"]'),lx.has(m)||(lx.add(m),i={rel:i,crossOrigin:l,href:a},u.querySelector(m)===null&&(a=u.createElement("link"),Bt(a,"link",i),Tt(a),u.head.appendChild(a)))}}function oN(i){Yr.D(i),cx("dns-prefetch",i,null)}function lN(i,a){Yr.C(i,a),cx("preconnect",i,a)}function cN(i,a,l){Yr.L(i,a,l);var u=Ca;if(u&&i&&a){var m='link[rel="preload"][as="'+Un(a)+'"]';a==="image"&&l&&l.imageSrcSet?(m+='[imagesrcset="'+Un(l.imageSrcSet)+'"]',typeof l.imageSizes=="string"&&(m+='[imagesizes="'+Un(l.imageSizes)+'"]')):m+='[href="'+Un(i)+'"]';var y=m;switch(a){case"style":y=Na(i);break;case"script":y=Oa(i)}Hn.has(y)||(i=b({rel:"preload",href:a==="image"&&l&&l.imageSrcSet?void 0:i,as:a},l),Hn.set(y,i),u.querySelector(m)!==null||a==="style"&&u.querySelector(Jo(y))||a==="script"&&u.querySelector(Qo(y))||(a=u.createElement("link"),Bt(a,"link",i),Tt(a),u.head.appendChild(a)))}}function uN(i,a){Yr.m(i,a);var l=Ca;if(l&&i){var u=a&&typeof a.as=="string"?a.as:"script",m='link[rel="modulepreload"][as="'+Un(u)+'"][href="'+Un(i)+'"]',y=m;switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":y=Oa(i)}if(!Hn.has(y)&&(i=b({rel:"modulepreload",href:i},a),Hn.set(y,i),l.querySelector(m)===null)){switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(l.querySelector(Qo(y)))return}u=l.createElement("link"),Bt(u,"link",i),Tt(u),l.head.appendChild(u)}}}function dN(i,a,l){Yr.S(i,a,l);var u=Ca;if(u&&i){var m=Ji(u).hoistableStyles,y=Na(i);a=a||"default";var S=m.get(y);if(!S){var j={loading:0,preload:null};if(S=u.querySelector(Jo(y)))j.loading=5;else{i=b({rel:"stylesheet",href:i,"data-precedence":a},l),(l=Hn.get(y))&&lp(i,l);var V=S=u.createElement("link");Tt(V),Bt(V,"link",i),V._p=new Promise(function(Q,ne){V.onload=Q,V.onerror=ne}),V.addEventListener("load",function(){j.loading|=1}),V.addEventListener("error",function(){j.loading|=2}),j.loading|=4,tu(S,a,u)}S={type:"stylesheet",instance:S,count:1,state:j},m.set(y,S)}}}function fN(i,a){Yr.X(i,a);var l=Ca;if(l&&i){var u=Ji(l).hoistableScripts,m=Oa(i),y=u.get(m);y||(y=l.querySelector(Qo(m)),y||(i=b({src:i,async:!0},a),(a=Hn.get(m))&&cp(i,a),y=l.createElement("script"),Tt(y),Bt(y,"link",i),l.head.appendChild(y)),y={type:"script",instance:y,count:1,state:null},u.set(m,y))}}function hN(i,a){Yr.M(i,a);var l=Ca;if(l&&i){var u=Ji(l).hoistableScripts,m=Oa(i),y=u.get(m);y||(y=l.querySelector(Qo(m)),y||(i=b({src:i,async:!0,type:"module"},a),(a=Hn.get(m))&&cp(i,a),y=l.createElement("script"),Tt(y),Bt(y,"link",i),l.head.appendChild(y)),y={type:"script",instance:y,count:1,state:null},u.set(m,y))}}function ux(i,a,l,u){var m=(m=je.current)?eu(m):null;if(!m)throw Error(r(446));switch(i){case"meta":case"title":return null;case"style":return typeof l.precedence=="string"&&typeof l.href=="string"?(a=Na(l.href),l=Ji(m).hoistableStyles,u=l.get(a),u||(u={type:"style",instance:null,count:0,state:null},l.set(a,u)),u):{type:"void",instance:null,count:0,state:null};case"link":if(l.rel==="stylesheet"&&typeof l.href=="string"&&typeof l.precedence=="string"){i=Na(l.href);var y=Ji(m).hoistableStyles,S=y.get(i);if(S||(m=m.ownerDocument||m,S={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},y.set(i,S),(y=m.querySelector(Jo(i)))&&!y._p&&(S.instance=y,S.state.loading=5),Hn.has(i)||(l={rel:"preload",as:"style",href:l.href,crossOrigin:l.crossOrigin,integrity:l.integrity,media:l.media,hrefLang:l.hrefLang,referrerPolicy:l.referrerPolicy},Hn.set(i,l),y||pN(m,i,l,S.state))),a&&u===null)throw Error(r(528,""));return S}if(a&&u!==null)throw Error(r(529,""));return null;case"script":return a=l.async,l=l.src,typeof l=="string"&&a&&typeof a!="function"&&typeof a!="symbol"?(a=Oa(l),l=Ji(m).hoistableScripts,u=l.get(a),u||(u={type:"script",instance:null,count:0,state:null},l.set(a,u)),u):{type:"void",instance:null,count:0,state:null};default:throw Error(r(444,i))}}function Na(i){return'href="'+Un(i)+'"'}function Jo(i){return'link[rel="stylesheet"]['+i+"]"}function dx(i){return b({},i,{"data-precedence":i.precedence,precedence:null})}function pN(i,a,l,u){i.querySelector('link[rel="preload"][as="style"]['+a+"]")?u.loading=1:(a=i.createElement("link"),u.preload=a,a.addEventListener("load",function(){return u.loading|=1}),a.addEventListener("error",function(){return u.loading|=2}),Bt(a,"link",l),Tt(a),i.head.appendChild(a))}function Oa(i){return'[src="'+Un(i)+'"]'}function Qo(i){return"script[async]"+i}function fx(i,a,l){if(a.count++,a.instance===null)switch(a.type){case"style":var u=i.querySelector('style[data-href~="'+Un(l.href)+'"]');if(u)return a.instance=u,Tt(u),u;var m=b({},l,{"data-href":l.href,"data-precedence":l.precedence,href:null,precedence:null});return u=(i.ownerDocument||i).createElement("style"),Tt(u),Bt(u,"style",m),tu(u,l.precedence,i),a.instance=u;case"stylesheet":m=Na(l.href);var y=i.querySelector(Jo(m));if(y)return a.state.loading|=4,a.instance=y,Tt(y),y;u=dx(l),(m=Hn.get(m))&&lp(u,m),y=(i.ownerDocument||i).createElement("link"),Tt(y);var S=y;return S._p=new Promise(function(j,V){S.onload=j,S.onerror=V}),Bt(y,"link",u),a.state.loading|=4,tu(y,l.precedence,i),a.instance=y;case"script":return y=Oa(l.src),(m=i.querySelector(Qo(y)))?(a.instance=m,Tt(m),m):(u=l,(m=Hn.get(y))&&(u=b({},l),cp(u,m)),i=i.ownerDocument||i,m=i.createElement("script"),Tt(m),Bt(m,"link",u),i.head.appendChild(m),a.instance=m);case"void":return null;default:throw Error(r(443,a.type))}else a.type==="stylesheet"&&(a.state.loading&4)===0&&(u=a.instance,a.state.loading|=4,tu(u,l.precedence,i));return a.instance}function tu(i,a,l){for(var u=l.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),m=u.length?u[u.length-1]:null,y=m,S=0;S<u.length;S++){var j=u[S];if(j.dataset.precedence===a)y=j;else if(y!==m)break}y?y.parentNode.insertBefore(i,y.nextSibling):(a=l.nodeType===9?l.head:l,a.insertBefore(i,a.firstChild))}function lp(i,a){i.crossOrigin==null&&(i.crossOrigin=a.crossOrigin),i.referrerPolicy==null&&(i.referrerPolicy=a.referrerPolicy),i.title==null&&(i.title=a.title)}function cp(i,a){i.crossOrigin==null&&(i.crossOrigin=a.crossOrigin),i.referrerPolicy==null&&(i.referrerPolicy=a.referrerPolicy),i.integrity==null&&(i.integrity=a.integrity)}var nu=null;function hx(i,a,l){if(nu===null){var u=new Map,m=nu=new Map;m.set(l,u)}else m=nu,u=m.get(l),u||(u=new Map,m.set(l,u));if(u.has(i))return u;for(u.set(i,null),l=l.getElementsByTagName(i),m=0;m<l.length;m++){var y=l[m];if(!(y[po]||y[Mt]||i==="link"&&y.getAttribute("rel")==="stylesheet")&&y.namespaceURI!=="http://www.w3.org/2000/svg"){var S=y.getAttribute(a)||"";S=i+S;var j=u.get(S);j?j.push(y):u.set(S,[y])}}return u}function px(i,a,l){i=i.ownerDocument||i,i.head.insertBefore(l,a==="title"?i.querySelector("head > title"):null)}function mN(i,a,l){if(l===1||a.itemProp!=null)return!1;switch(i){case"meta":case"title":return!0;case"style":if(typeof a.precedence!="string"||typeof a.href!="string"||a.href==="")break;return!0;case"link":if(typeof a.rel!="string"||typeof a.href!="string"||a.href===""||a.onLoad||a.onError)break;switch(a.rel){case"stylesheet":return i=a.disabled,typeof a.precedence=="string"&&i==null;default:return!0}case"script":if(a.async&&typeof a.async!="function"&&typeof a.async!="symbol"&&!a.onLoad&&!a.onError&&a.src&&typeof a.src=="string")return!0}return!1}function mx(i){return!(i.type==="stylesheet"&&(i.state.loading&3)===0)}function yN(i,a,l,u){if(l.type==="stylesheet"&&(typeof u.media!="string"||matchMedia(u.media).matches!==!1)&&(l.state.loading&4)===0){if(l.instance===null){var m=Na(u.href),y=a.querySelector(Jo(m));if(y){a=y._p,a!==null&&typeof a=="object"&&typeof a.then=="function"&&(i.count++,i=ru.bind(i),a.then(i,i)),l.state.loading|=4,l.instance=y,Tt(y);return}y=a.ownerDocument||a,u=dx(u),(m=Hn.get(m))&&lp(u,m),y=y.createElement("link"),Tt(y);var S=y;S._p=new Promise(function(j,V){S.onload=j,S.onerror=V}),Bt(y,"link",u),l.instance=y}i.stylesheets===null&&(i.stylesheets=new Map),i.stylesheets.set(l,a),(a=l.state.preload)&&(l.state.loading&3)===0&&(i.count++,l=ru.bind(i),a.addEventListener("load",l),a.addEventListener("error",l))}}var up=0;function gN(i,a){return i.stylesheets&&i.count===0&&iu(i,i.stylesheets),0<i.count||0<i.imgCount?function(l){var u=setTimeout(function(){if(i.stylesheets&&iu(i,i.stylesheets),i.unsuspend){var y=i.unsuspend;i.unsuspend=null,y()}},6e4+a);0<i.imgBytes&&up===0&&(up=62500*JC());var m=setTimeout(function(){if(i.waitingForImages=!1,i.count===0&&(i.stylesheets&&iu(i,i.stylesheets),i.unsuspend)){var y=i.unsuspend;i.unsuspend=null,y()}},(i.imgBytes>up?50:800)+a);return i.unsuspend=l,function(){i.unsuspend=null,clearTimeout(u),clearTimeout(m)}}:null}function ru(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)iu(this,this.stylesheets);else if(this.unsuspend){var i=this.unsuspend;this.unsuspend=null,i()}}}var su=null;function iu(i,a){i.stylesheets=null,i.unsuspend!==null&&(i.count++,su=new Map,a.forEach(bN,i),su=null,ru.call(i))}function bN(i,a){if(!(a.state.loading&4)){var l=su.get(i);if(l)var u=l.get(null);else{l=new Map,su.set(i,l);for(var m=i.querySelectorAll("link[data-precedence],style[data-precedence]"),y=0;y<m.length;y++){var S=m[y];(S.nodeName==="LINK"||S.getAttribute("media")!=="not all")&&(l.set(S.dataset.precedence,S),u=S)}u&&l.set(null,u)}m=a.instance,S=m.getAttribute("data-precedence"),y=l.get(S)||u,y===u&&l.set(null,m),l.set(S,m),this.count++,u=ru.bind(this),m.addEventListener("load",u),m.addEventListener("error",u),y?y.parentNode.insertBefore(m,y.nextSibling):(i=i.nodeType===9?i.head:i,i.insertBefore(m,i.firstChild)),a.state.loading|=4}}var Xo={$$typeof:U,Provider:null,Consumer:null,_currentValue:K,_currentValue2:K,_threadCount:0};function vN(i,a,l,u,m,y,S,j,V){this.tag=1,this.containerInfo=i,this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.next=this.pendingContext=this.context=this.cancelPendingCommit=null,this.callbackPriority=0,this.expirationTimes=sf(-1),this.entangledLanes=this.shellSuspendCounter=this.errorRecoveryDisabledLanes=this.expiredLanes=this.warmLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=sf(0),this.hiddenUpdates=sf(null),this.identifierPrefix=u,this.onUncaughtError=m,this.onCaughtError=y,this.onRecoverableError=S,this.pooledCache=null,this.pooledCacheLanes=0,this.formState=V,this.incompleteTransitions=new Map}function yx(i,a,l,u,m,y,S,j,V,Q,ne,ie){return i=new vN(i,a,l,S,V,Q,ne,ie,j),a=1,y===!0&&(a|=24),y=An(3,null,null,a),i.current=y,y.stateNode=i,a=zf(),a.refCount++,i.pooledCache=a,a.refCount++,y.memoizedState={element:u,isDehydrated:l,cache:a},Kf(y),i}function gx(i){return i?(i=oa,i):oa}function bx(i,a,l,u,m,y){m=gx(m),u.context===null?u.context=m:u.pendingContext=m,u=ys(a),u.payload={element:l},y=y===void 0?null:y,y!==null&&(u.callback=y),l=gs(i,u,a),l!==null&&(mn(l,i,a),To(l,i,a))}function vx(i,a){if(i=i.memoizedState,i!==null&&i.dehydrated!==null){var l=i.retryLane;i.retryLane=l!==0&&l<a?l:a}}function dp(i,a){vx(i,a),(i=i.alternate)&&vx(i,a)}function xx(i){if(i.tag===13||i.tag===31){var a=oi(i,67108864);a!==null&&mn(a,i,67108864),dp(i,67108864)}}function wx(i){if(i.tag===13||i.tag===31){var a=On();a=af(a);var l=oi(i,a);l!==null&&mn(l,i,a),dp(i,a)}}var au=!0;function xN(i,a,l,u){var m=z.T;z.T=null;var y=$.p;try{$.p=2,fp(i,a,l,u)}finally{$.p=y,z.T=m}}function wN(i,a,l,u){var m=z.T;z.T=null;var y=$.p;try{$.p=8,fp(i,a,l,u)}finally{$.p=y,z.T=m}}function fp(i,a,l,u){if(au){var m=hp(u);if(m===null)Qh(i,a,u,ou,l),_x(i,u);else if(_N(m,i,a,l,u))u.stopPropagation();else if(_x(i,u),a&4&&-1<SN.indexOf(i)){for(;m!==null;){var y=Wi(m);if(y!==null)switch(y.tag){case 3:if(y=y.stateNode,y.current.memoizedState.isDehydrated){var S=ni(y.pendingLanes);if(S!==0){var j=y;for(j.pendingLanes|=2,j.entangledLanes|=2;S;){var V=1<<31-_n(S);j.entanglements[1]|=V,S&=~V}mr(y),(Fe&6)===0&&(zc=wn()+500,Ko(0))}}break;case 31:case 13:j=oi(y,2),j!==null&&mn(j,y,2),Hc(),dp(y,2)}if(y=hp(u),y===null&&Qh(i,a,u,ou,l),y===m)break;m=y}m!==null&&u.stopPropagation()}else Qh(i,a,u,null,l)}}function hp(i){return i=mf(i),pp(i)}var ou=null;function pp(i){if(ou=null,i=Zi(i),i!==null){var a=o(i);if(a===null)i=null;else{var l=a.tag;if(l===13){if(i=c(a),i!==null)return i;i=null}else if(l===31){if(i=d(a),i!==null)return i;i=null}else if(l===3){if(a.stateNode.current.memoizedState.isDehydrated)return a.tag===3?a.stateNode.containerInfo:null;i=null}else a!==i&&(i=null)}}return ou=i,null}function Sx(i){switch(i){case"beforetoggle":case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"toggle":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 2;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 8;case"message":switch(ok()){case Og:return 2;case Tg:return 8;case Wl:case lk:return 32;case Rg:return 268435456;default:return 32}default:return 32}}var mp=!1,Cs=null,Ns=null,Os=null,el=new Map,tl=new Map,Ts=[],SN="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset".split(" ");function _x(i,a){switch(i){case"focusin":case"focusout":Cs=null;break;case"dragenter":case"dragleave":Ns=null;break;case"mouseover":case"mouseout":Os=null;break;case"pointerover":case"pointerout":el.delete(a.pointerId);break;case"gotpointercapture":case"lostpointercapture":tl.delete(a.pointerId)}}function nl(i,a,l,u,m,y){return i===null||i.nativeEvent!==y?(i={blockedOn:a,domEventName:l,eventSystemFlags:u,nativeEvent:y,targetContainers:[m]},a!==null&&(a=Wi(a),a!==null&&xx(a)),i):(i.eventSystemFlags|=u,a=i.targetContainers,m!==null&&a.indexOf(m)===-1&&a.push(m),i)}function _N(i,a,l,u,m){switch(a){case"focusin":return Cs=nl(Cs,i,a,l,u,m),!0;case"dragenter":return Ns=nl(Ns,i,a,l,u,m),!0;case"mouseover":return Os=nl(Os,i,a,l,u,m),!0;case"pointerover":var y=m.pointerId;return el.set(y,nl(el.get(y)||null,i,a,l,u,m)),!0;case"gotpointercapture":return y=m.pointerId,tl.set(y,nl(tl.get(y)||null,i,a,l,u,m)),!0}return!1}function Ex(i){var a=Zi(i.target);if(a!==null){var l=o(a);if(l!==null){if(a=l.tag,a===13){if(a=c(l),a!==null){i.blockedOn=a,$g(i.priority,function(){wx(l)});return}}else if(a===31){if(a=d(l),a!==null){i.blockedOn=a,$g(i.priority,function(){wx(l)});return}}else if(a===3&&l.stateNode.current.memoizedState.isDehydrated){i.blockedOn=l.tag===3?l.stateNode.containerInfo:null;return}}}i.blockedOn=null}function lu(i){if(i.blockedOn!==null)return!1;for(var a=i.targetContainers;0<a.length;){var l=hp(i.nativeEvent);if(l===null){l=i.nativeEvent;var u=new l.constructor(l.type,l);pf=u,l.target.dispatchEvent(u),pf=null}else return a=Wi(l),a!==null&&xx(a),i.blockedOn=l,!1;a.shift()}return!0}function Ax(i,a,l){lu(i)&&l.delete(a)}function EN(){mp=!1,Cs!==null&&lu(Cs)&&(Cs=null),Ns!==null&&lu(Ns)&&(Ns=null),Os!==null&&lu(Os)&&(Os=null),el.forEach(Ax),tl.forEach(Ax)}function cu(i,a){i.blockedOn===a&&(i.blockedOn=null,mp||(mp=!0,t.unstable_scheduleCallback(t.unstable_NormalPriority,EN)))}var uu=null;function jx(i){uu!==i&&(uu=i,t.unstable_scheduleCallback(t.unstable_NormalPriority,function(){uu===i&&(uu=null);for(var a=0;a<i.length;a+=3){var l=i[a],u=i[a+1],m=i[a+2];if(typeof u!="function"){if(pp(u||l)===null)continue;break}var y=Wi(l);y!==null&&(i.splice(a,3),a-=3,hh(y,{pending:!0,data:m,method:l.method,action:u},u,m))}}))}function Ta(i){function a(V){return cu(V,i)}Cs!==null&&cu(Cs,i),Ns!==null&&cu(Ns,i),Os!==null&&cu(Os,i),el.forEach(a),tl.forEach(a);for(var l=0;l<Ts.length;l++){var u=Ts[l];u.blockedOn===i&&(u.blockedOn=null)}for(;0<Ts.length&&(l=Ts[0],l.blockedOn===null);)Ex(l),l.blockedOn===null&&Ts.shift();if(l=(i.ownerDocument||i).$$reactFormReplay,l!=null)for(u=0;u<l.length;u+=3){var m=l[u],y=l[u+1],S=m[cn]||null;if(typeof y=="function")S||jx(l);else if(S){var j=null;if(y&&y.hasAttribute("formAction")){if(m=y,S=y[cn]||null)j=S.formAction;else if(pp(m)!==null)continue}else j=S.action;typeof j=="function"?l[u+1]=j:(l.splice(u,3),u-=3),jx(l)}}}function kx(){function i(y){y.canIntercept&&y.info==="react-transition"&&y.intercept({handler:function(){return new Promise(function(S){return m=S})},focusReset:"manual",scroll:"manual"})}function a(){m!==null&&(m(),m=null),u||setTimeout(l,20)}function l(){if(!u&&!navigation.transition){var y=navigation.currentEntry;y&&y.url!=null&&navigation.navigate(y.url,{state:y.getState(),info:"react-transition",history:"replace"})}}if(typeof navigation=="object"){var u=!1,m=null;return navigation.addEventListener("navigate",i),navigation.addEventListener("navigatesuccess",a),navigation.addEventListener("navigateerror",a),setTimeout(l,100),function(){u=!0,navigation.removeEventListener("navigate",i),navigation.removeEventListener("navigatesuccess",a),navigation.removeEventListener("navigateerror",a),m!==null&&(m(),m=null)}}}function yp(i){this._internalRoot=i}du.prototype.render=yp.prototype.render=function(i){var a=this._internalRoot;if(a===null)throw Error(r(409));var l=a.current,u=On();bx(l,u,i,a,null,null)},du.prototype.unmount=yp.prototype.unmount=function(){var i=this._internalRoot;if(i!==null){this._internalRoot=null;var a=i.containerInfo;bx(i.current,2,null,i,null,null),Hc(),a[Yi]=null}};function du(i){this._internalRoot=i}du.prototype.unstable_scheduleHydration=function(i){if(i){var a=Ug();i={blockedOn:null,target:i,priority:a};for(var l=0;l<Ts.length&&a!==0&&a<Ts[l].priority;l++);Ts.splice(l,0,i),l===0&&Ex(i)}};var Cx=e.version;if(Cx!=="19.2.7")throw Error(r(527,Cx,"19.2.7"));$.findDOMNode=function(i){var a=i._reactInternals;if(a===void 0)throw typeof i.render=="function"?Error(r(188)):(i=Object.keys(i).join(","),Error(r(268,i)));return i=p(a),i=i!==null?g(i):null,i=i===null?null:i.stateNode,i};var AN={bundleType:0,version:"19.2.7",rendererPackageName:"react-dom",currentDispatcherRef:z,reconcilerVersion:"19.2.7"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var fu=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!fu.isDisabled&&fu.supportsFiber)try{uo=fu.inject(AN),Sn=fu}catch{}}return sl.createRoot=function(i,a){if(!s(i))throw Error(r(299));var l=!1,u="",m=Mv,y=Lv,S=Uv;return a!=null&&(a.unstable_strictMode===!0&&(l=!0),a.identifierPrefix!==void 0&&(u=a.identifierPrefix),a.onUncaughtError!==void 0&&(m=a.onUncaughtError),a.onCaughtError!==void 0&&(y=a.onCaughtError),a.onRecoverableError!==void 0&&(S=a.onRecoverableError)),a=yx(i,1,!1,null,null,l,u,null,m,y,S,kx),i[Yi]=a.current,Jh(i),new yp(a)},sl.hydrateRoot=function(i,a,l){if(!s(i))throw Error(r(299));var u=!1,m="",y=Mv,S=Lv,j=Uv,V=null;return l!=null&&(l.unstable_strictMode===!0&&(u=!0),l.identifierPrefix!==void 0&&(m=l.identifierPrefix),l.onUncaughtError!==void 0&&(y=l.onUncaughtError),l.onCaughtError!==void 0&&(S=l.onCaughtError),l.onRecoverableError!==void 0&&(j=l.onRecoverableError),l.formState!==void 0&&(V=l.formState)),a=yx(i,1,!0,a,l??null,u,m,V,y,S,j,kx),a.context=gx(null),l=a.current,u=On(),u=af(u),m=ys(u),m.callback=null,gs(l,m,u),l=u,a.current.lanes=l,ho(a,l),mr(a),i[Yi]=a.current,Jh(i),new du(a)},sl.version="19.2.7",sl}var $x;function UN(){if($x)return vp.exports;$x=1;function t(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(t)}catch(e){console.error(e)}}return t(),vp.exports=LN(),vp.exports}var $N=UN();const BN="modulepreload",FN=function(t){return"/__pyric/ui/"+t},Bx={},K_=function(e,n,r){let s=Promise.resolve();if(n&&n.length>0){let c=function(p){return Promise.all(p.map(g=>Promise.resolve(g).then(b=>({status:"fulfilled",value:b}),b=>({status:"rejected",reason:b}))))};document.getElementsByTagName("link");const d=document.querySelector("meta[property=csp-nonce]"),f=(d==null?void 0:d.nonce)||(d==null?void 0:d.getAttribute("nonce"));s=c(n.map(p=>{if(p=FN(p),p in Bx)return;Bx[p]=!0;const g=p.endsWith(".css"),b=g?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${p}"]${b}`))return;const v=document.createElement("link");if(v.rel=g?"stylesheet":BN,g||(v.as="script"),v.crossOrigin="",v.href=p,f&&v.setAttribute("nonce",f),document.head.appendChild(v),g)return new Promise((x,_)=>{v.addEventListener("load",x),v.addEventListener("error",()=>_(new Error(`Unable to preload CSS for ${p}`)))})}))}function o(c){const d=new Event("vite:preloadError",{cancelable:!0});if(d.payload=c,window.dispatchEvent(d),!d.defaultPrevented)throw c}return s.then(c=>{for(const d of c||[])d.status==="rejected"&&o(d.reason);return e().catch(o)})},Y_=A.createContext(null),Z_={status:"disabled",handles:null,events:[]};function PN({children:t}){return h.jsx(Y_.Provider,{value:Z_,children:t})}function as(){return A.useContext(Y_)??Z_}function an(t){const e=t||"";return function(){throw new Error("this method "+e+" is abstract! (it has no implementation in class "+this.constructor.name+")")}}function Js(t,e){if(!t)throw new Error(e||"Assertion failed")}function am(t,e,n){let r;Object.defineProperty(t,e,{get(){return r||(r=n.call(this)),r}})}function W_(t,e){const n=[];for(;e-- >0;)n.push(t());return n}function J_(t,e){return new Array(e+1).join(t)}function Sd(t,e){return W_(()=>t,e)}function om(t){const e=[];for(let n=0;n<t.length;n++){const r=t[n];t.lastIndexOf(r)!==n&&e.indexOf(r)<0&&e.push(r)}return e}function Q_(t){const e=[];return t.forEach(n=>{e.indexOf(n)<0&&e.push(n)}),e}function Ci(t){const e=t[0];return e===e.toUpperCase()}function X_(t){return!Ci(t)}function e1(t,e,n){return t.length<e?J_(" ",e-t.length)+t:t}function Fi(){this.strings=[]}Fi.prototype.append=function(t){this.strings.push(t)};Fi.prototype.contents=function(){return this.strings.join("")};const _p=t=>String.fromCodePoint(parseInt(t,16));function t1(t){if(t.charAt(0)==="\\")switch(t.charAt(1)){case"b":return"\b";case"f":return"\f";case"n":return`
|
|
50
|
-
`;case"r":return"\r";case"t":return" ";case"v":return"\v";case"x":return _p(t.slice(2,4));case"u":return t.charAt(2)==="{"?_p(t.slice(3,-1)):_p(t.slice(2,6));default:return t.charAt(1)}else return t}function Ny(t){if(t==null)return String(t);const e=Object.prototype.toString.call(t);try{let n;return t.constructor&&t.constructor.name?n=t.constructor.name:e.indexOf("[object ")===0?n=e.slice(8,-1):n=typeof t,n+": "+JSON.stringify(String(t))}catch{return e}}function n1(t,e="unexpected null value"){if(t==null)throw new Error(e);return t}const qN=Object.freeze(Object.defineProperty({__proto__:null,StringBuffer:Fi,abstract:an,assert:Js,checkNotNull:n1,copyWithoutDuplicates:Q_,defineLazyProperty:am,getDuplicates:om,isLexical:X_,isSyntactic:Ci,padLeft:e1,repeat:Sd,repeatFn:W_,repeatStr:J_,unescapeCodePoint:t1,unexpectedObjToString:Ny},Symbol.toStringTag,{value:"Module"})),r1=t=>new RegExp(String.raw`\p{${t}}`,"u"),lm=Object.fromEntries(["Cc","Cf","Cn","Co","Cs","Ll","Lm","Lo","Lt","Lu","Mc","Me","Mn","Nd","Nl","No","Pc","Pd","Pe","Pf","Pi","Po","Ps","Sc","Sk","Sm","So","Zl","Zp","Zs"].map(t=>[t,r1(t)]));lm.Ltmo=new RegExp("\\p{Lt}|\\p{Lm}|\\p{Lo}","u");const Fx=Object.fromEntries(["XID_Start","XID_Continue","White_Space"].map(t=>[t,r1(t)]));class xe{constructor(){if(this.constructor===xe)throw new Error("PExpr cannot be instantiated -- it's abstract")}withSource(e){return e&&(this.source=e.trimmed()),this}}const Yt=Object.create(xe.prototype),Zt=Object.create(xe.prototype);class Vt extends xe{constructor(e){super(),this.obj=e}}class Wt extends xe{constructor(e,n){super(),this.from=e,this.to=n,this.matchCodePoint=e.length>1||n.length>1}}class Jt extends xe{constructor(e){super(),this.index=e}}class Ot extends xe{constructor(e){super(),this.terms=e}}class _d extends Ot{constructor(e,n,r){const s=e.rules[n].body;super([r,s]),this.superGrammar=e,this.name=n,this.body=r}}class Ed extends Ot{constructor(e,n,r,s){const o=e.rules[n].body;super([...r,o,...s]),this.superGrammar=e,this.ruleName=n,this.expansionPos=r.length}}class It extends xe{constructor(e){super(),this.factors=e}}class on extends xe{constructor(e){super(),this.expr=e}}class Pi extends on{}class to extends on{}class os extends on{}Pi.prototype.operator="*";to.prototype.operator="+";os.prototype.operator="?";Pi.prototype.minNumMatches=0;to.prototype.minNumMatches=1;os.prototype.minNumMatches=0;Pi.prototype.maxNumMatches=Number.POSITIVE_INFINITY;to.prototype.maxNumMatches=Number.POSITIVE_INFINITY;os.prototype.maxNumMatches=1;class qt extends xe{constructor(e){super(),this.expr=e}}class ln extends xe{constructor(e){super(),this.expr=e}}class vn extends xe{constructor(e){super(),this.expr=e}}class He extends xe{constructor(e,n=[]){super(),this.ruleName=e,this.args=n}isSyntactic(){return Ci(this.ruleName)}toMemoKey(){return this._memoKey||Object.defineProperty(this,"_memoKey",{value:this.toString()}),this._memoKey}}class zt extends xe{constructor(e){if(super(),this.categoryOrProp=e,e in lm)this.pattern=lm[e];else if(e in Fx)this.pattern=Fx[e];else throw new Error(`Invalid Unicode category or property name: ${JSON.stringify(e)}`)}}function pt(t,e){let n;return e?(n=new Error(e.getLineAndColumnMessage()+t),n.shortMessage=t,n.interval=e):n=new Error(t),n}function cm(){return pt("Interval sources don't match")}function zN(t){const e=new Error;return Object.defineProperty(e,"message",{enumerable:!0,get(){return t.message}}),Object.defineProperty(e,"shortMessage",{enumerable:!0,get(){return"Expected "+t.getExpectedText()}}),e.interval=t.getInterval(),e}function VN(t,e,n){const r=e?`Grammar ${t} is not declared in namespace '${e}'`:"Undeclared grammar "+t;return pt(r,n)}function HN(t,e){return pt("Grammar "+t.name+" is already declared in this namespace")}function GN(t){return pt(`Grammar '${t.name}' does not support incremental parsing`)}function s1(t,e,n){return pt("Rule "+t+" is not declared in grammar "+e,n)}function KN(t,e,n){return pt("Cannot override rule "+t+" because it is not declared in "+e,n)}function YN(t,e,n){return pt("Cannot extend rule "+t+" because it is not declared in "+e,n)}function Px(t,e,n,r){let s="Duplicate declaration for rule '"+t+"' in grammar '"+e+"'";return e!==n&&(s+=" (originally declared in '"+n+"')"),pt(s,r)}function i1(t,e,n,r){return pt("Wrong number of parameters for rule "+t+" (expected "+e+", got "+n+")",r)}function ZN(t,e,n,r){return pt("Wrong number of arguments for rule "+t+" (expected "+e+", got "+n+")",r)}function qx(t,e,n){return pt("Duplicate parameter names in rule "+t+": "+e.join(", "),n)}function WN(t,e){return pt("Invalid parameter to rule "+t+": "+e+" has arity "+e.getArity()+", but parameter expressions must have arity 1",e.source)}const JN="NOTE: A _syntactic rule_ is a rule whose name begins with a capital letter. See https://ohmjs.org/d/svl for more details.";function QN(t,e){return pt("Cannot apply syntactic rule "+t+" from here (inside a lexical context)",e.source)}function XN(t){const{ruleName:e}=t;return pt(`applySyntactic is for syntactic rules, but '${e}' is a lexical rule. `+JN,t.source)}function eO(t){return pt("applySyntactic is not required here (in a syntactic context)",t.source)}function zx(t,e){return pt("Incorrect argument type: expected "+t,e.source)}function tO(t){return pt("'...' can appear at most once in a rule body",t.source)}function nO(t){const e=t._node;Js(e&&e.isNonterminal()&&e.ctorName==="escapeChar_unicodeCodePoint");const n=t.children.slice(1,-1).map(s=>s.source),r=n[0].coverageWith(...n.slice(1));return pt(`U+${r.contents} is not a valid Unicode code point`,r)}function a1(t,e){const n=e.length>0?e[e.length-1].args:[];let s="Nullable expression "+t.expr.substituteParams(n)+" is not allowed inside '"+t.operator+"' (possible infinite loop)";if(e.length>0){const o=e.map(c=>new He(c.ruleName,c.args)).join(`
|
|
51
|
-
`);s+=`
|
|
52
|
-
Application stack (most recent application last):
|
|
53
|
-
`+o}return pt(s,t.expr.source)}function o1(t,e,n,r){return pt("Rule "+t+" involves an alternation which has inconsistent arity (expected "+e+", got "+n+")",r.source)}function rO(t){const e=t.map(n=>n.message);return pt(["Errors:"].concat(e).join(`
|
|
54
|
-
- `),t[0].interval)}function sO(t,e,n,r){let s=r.slice(0,-1).map(f=>{const p=" "+f[0].name+" > "+f[1];return f.length===3?p+" for '"+f[2]+"'":p}).join(`
|
|
55
|
-
`);s+=`
|
|
56
|
-
`+e+" > "+t;let o="";t==="_iter"&&(o=[`
|
|
57
|
-
NOTE: as of Ohm v16, there is no default action for iteration nodes — see `," https://ohmjs.org/d/dsa for details."].join(`
|
|
58
|
-
`));const c=[`Missing semantic action for '${t}' in ${n} '${e}'.${o}`,"Action stack (most recent call last):",s].join(`
|
|
59
|
-
`),d=pt(c);return d.name="missingSemanticAction",d}function iO(t){if(t.length===1)throw t[0];if(t.length>1)throw rO(t)}function aO(t){let e=0;return t.map(r=>{const s=r.toString();return e=Math.max(e,s.length),s}).map(r=>e1(r,e))}function Vx(t,e,n){const r=t.length,s=t.slice(0,n),o=t.slice(n+e.length);return(s+e+o).substr(0,r)}function oO(...t){const e=this,{offset:n}=e,{repeatStr:r}=qN,s=new Fi;s.append("Line "+e.lineNum+", col "+e.colNum+`:
|
|
60
|
-
`);const o=aO([e.prevLine==null?0:e.lineNum-1,e.lineNum,e.nextLine==null?0:e.lineNum+1]),c=(g,b,v)=>{s.append(v+o[g]+" | "+b+`
|
|
61
|
-
`)};e.prevLine!=null&&c(0,e.prevLine," "),c(1,e.line,"> ");const d=e.line.length;let f=r(" ",d+1);for(let g=0;g<t.length;++g){let b=t[g][0],v=t[g][1];Js(b>=0&&b<=v,"range start must be >= 0 and <= end");const x=n-e.colNum+1;b=Math.max(0,b-x),v=Math.min(v-x,d),f=Vx(f,r("~",v-b),b)}const p=2+o[1].length+3;return s.append(r(" ",p)),f=Vx(f,"^",e.colNum-1),s.append(f.replace(/ +$/,"")+`
|
|
62
|
-
`),e.nextLine!=null&&c(2,e.nextLine," "),s.contents()}let um=[];function l1(t){um.push(t)}function lO(t){um.forEach(e=>{e(t)}),um=null}function Oy(t,e){let n=1,r=1,s=0,o=0,c=null,d=null,f=-1;for(;s<e;){const b=t.charAt(s++);b===`
|
|
63
|
-
`?(n++,r=1,f=o,o=s):b!=="\r"&&r++}let p=t.indexOf(`
|
|
64
|
-
`,o);if(p===-1)p=t.length;else{const b=t.indexOf(`
|
|
65
|
-
`,p+1);c=b===-1?t.slice(p):t.slice(p,b),c=c.replace(/^\r?\n/,"").replace(/\r$/,"")}f>=0&&(d=t.slice(f,o).replace(/\r?\n$/,""));const g=t.slice(o,p).replace(/\r$/,"");return{offset:e,lineNum:n,colNum:r,line:g,prevLine:d,nextLine:c,toString:oO}}function Ty(t,e,...n){return Oy(t,e).toString(...n)}const Hx=(()=>{let t=0;return e=>""+e+t++})();class Gt{constructor(e,n,r){Object.defineProperty(this,"_sourceString",{value:e,configurable:!1,enumerable:!1,writable:!1}),this.startIdx=n,this.endIdx=r}get sourceString(){return this._sourceString}get contents(){return this._contents===void 0&&(this._contents=this.sourceString.slice(this.startIdx,this.endIdx)),this._contents}get length(){return this.endIdx-this.startIdx}coverageWith(...e){return Gt.coverage(...e,this)}collapsedLeft(){return new Gt(this.sourceString,this.startIdx,this.startIdx)}collapsedRight(){return new Gt(this.sourceString,this.endIdx,this.endIdx)}getLineAndColumn(){return Oy(this.sourceString,this.startIdx)}getLineAndColumnMessage(){const e=[this.startIdx,this.endIdx];return Ty(this.sourceString,this.startIdx,e)}minus(e){if(this.sourceString!==e.sourceString)throw cm();return this.startIdx===e.startIdx&&this.endIdx===e.endIdx?[]:this.startIdx<e.startIdx&&e.endIdx<this.endIdx?[new Gt(this.sourceString,this.startIdx,e.startIdx),new Gt(this.sourceString,e.endIdx,this.endIdx)]:this.startIdx<e.endIdx&&e.endIdx<this.endIdx?[new Gt(this.sourceString,e.endIdx,this.endIdx)]:this.startIdx<e.startIdx&&e.startIdx<this.endIdx?[new Gt(this.sourceString,this.startIdx,e.startIdx)]:[this]}relativeTo(e){if(this.sourceString!==e.sourceString)throw cm();return Js(this.startIdx>=e.startIdx&&this.endIdx<=e.endIdx,"other interval does not cover this one"),new Gt(this.sourceString,this.startIdx-e.startIdx,this.endIdx-e.startIdx)}trimmed(){const{contents:e}=this,n=this.startIdx+e.match(/^\s*/)[0].length,r=this.endIdx-e.match(/\s*$/)[0].length;return new Gt(this.sourceString,n,r)}subInterval(e,n){const r=this.startIdx+e;return new Gt(this.sourceString,r,r+n)}}Gt.coverage=function(t,...e){let{startIdx:n,endIdx:r}=t;for(const s of e){if(s.sourceString!==t.sourceString)throw cm();n=Math.min(n,s.startIdx),r=Math.max(r,s.endIdx)}return new Gt(t.sourceString,n,r)};const cO=65535,uO=1114111;class Ad{constructor(e){this.source=e,this.pos=0,this.examinedLength=0}atEnd(){const e=this.pos>=this.source.length;return this.examinedLength=Math.max(this.examinedLength,this.pos+1),e}next(){const e=this.source[this.pos++];return this.examinedLength=Math.max(this.examinedLength,this.pos),e}nextCharCode(){const e=this.next();return e&&e.charCodeAt(0)}nextCodePoint(){const e=this.source.slice(this.pos++).codePointAt(0);return e>cO&&(this.pos+=1),this.examinedLength=Math.max(this.examinedLength,this.pos),e}matchString(e,n){let r;if(n){for(r=0;r<e.length;r++){const s=this.next(),o=e[r];if(s==null||s.toUpperCase()!==o.toUpperCase())return!1}return!0}for(r=0;r<e.length;r++)if(this.next()!==e[r])return!1;return!0}sourceSlice(e,n){return this.source.slice(e,n)}interval(e,n){return new Gt(this.source,e,n||this.pos)}}class c1{constructor(e,n,r,s,o,c,d){this.matcher=e,this.input=n,this.startExpr=r,this._cst=s,this._cstOffset=o,this._rightmostFailurePosition=c,this._rightmostFailures=d,this.failed()&&(am(this,"message",function(){const f="Expected "+this.getExpectedText();return Ty(this.input,this.getRightmostFailurePosition())+f}),am(this,"shortMessage",function(){const f="expected "+this.getExpectedText(),p=Oy(this.input,this.getRightmostFailurePosition());return"Line "+p.lineNum+", col "+p.colNum+": "+f}))}succeeded(){return!!this._cst}failed(){return!this.succeeded()}getRightmostFailurePosition(){return this._rightmostFailurePosition}getRightmostFailures(){if(!this._rightmostFailures){this.matcher.setInput(this.input);const e=this.matcher._match(this.startExpr,{tracing:!1,positionToRecordFailures:this.getRightmostFailurePosition()});this._rightmostFailures=e.getRightmostFailures()}return this._rightmostFailures}toString(){return this.succeeded()?"[match succeeded]":"[match failed at position "+this.getRightmostFailurePosition()+"]"}getExpectedText(){if(this.succeeded())throw new Error("cannot get expected text of a successful MatchResult");const e=new Fi;let n=this.getRightmostFailures();n=n.filter(r=>!r.isFluffy());for(let r=0;r<n.length;r++)r>0&&(r===n.length-1?e.append(n.length>2?", or ":" or "):e.append(", ")),e.append(n[r].toString());return e.contents()}getInterval(){const e=this.getRightmostFailurePosition();return new Gt(this.input,e,e)}}class dO{constructor(){this.applicationMemoKeyStack=[],this.memo={},this.maxExaminedLength=0,this.maxRightmostFailureOffset=-1,this.currentLeftRecursion=void 0}isActive(e){return this.applicationMemoKeyStack.indexOf(e.toMemoKey())>=0}enter(e){this.applicationMemoKeyStack.push(e.toMemoKey())}exit(){this.applicationMemoKeyStack.pop()}startLeftRecursion(e,n){n.isLeftRecursion=!0,n.headApplication=e,n.nextLeftRecursion=this.currentLeftRecursion,this.currentLeftRecursion=n;const{applicationMemoKeyStack:r}=this,s=r.indexOf(e.toMemoKey())+1,o=r.slice(s);n.isInvolved=function(c){return o.indexOf(c)>=0},n.updateInvolvedApplicationMemoKeys=function(){for(let c=s;c<r.length;c++){const d=r[c];this.isInvolved(d)||o.push(d)}}}endLeftRecursion(){this.currentLeftRecursion=this.currentLeftRecursion.nextLeftRecursion}shouldUseMemoizedResult(e){if(!e.isLeftRecursion)return!0;const{applicationMemoKeyStack:n}=this;for(let r=0;r<n.length;r++){const s=n[r];if(e.isInvolved(s))return!1}return!0}memoize(e,n){return this.memo[e]=n,this.maxExaminedLength=Math.max(this.maxExaminedLength,n.examinedLength),this.maxRightmostFailureOffset=Math.max(this.maxRightmostFailureOffset,n.rightmostFailureOffset),n}clearObsoleteEntries(e,n){if(e+this.maxExaminedLength<=n)return;const{memo:r}=this;this.maxExaminedLength=0,this.maxRightmostFailureOffset=-1,Object.keys(r).forEach(s=>{const o=r[s];e+o.examinedLength>n?delete r[s]:(this.maxExaminedLength=Math.max(this.maxExaminedLength,o.examinedLength),this.maxRightmostFailureOffset=Math.max(this.maxRightmostFailureOffset,o.rightmostFailureOffset))})}}const fO="✗",hO="✓",pO="⋅",mO="⇒",yO="␉",gO="␊",bO="␍",dm={succeeded:1,isRootNode:2,isImplicitSpaces:4,isMemoized:8,isHeadOfLeftRecursion:16,terminatesLR:32};function vO(t){return Sd(" ",t).join("")}function xO(t,e,n){const r=u1(t.slice(e,e+n));return r.length<n?r+Sd(" ",n-r.length).join(""):r}function u1(t){return typeof t=="string"?t.replace(/ /g,pO).replace(/\t/g,yO).replace(/\n/g,gO).replace(/\r/g,bO):String(t)}class zs{constructor(e,n,r,s,o,c,d){this.input=e,this.pos=this.pos1=n,this.pos2=r,this.source=new Gt(e,n,r),this.expr=s,this.bindings=c,this.children=d||[],this.terminatingLREntry=null,this._flags=o?dm.succeeded:0}get displayString(){return this.expr.toDisplayString()}clone(){return this.cloneWithExpr(this.expr)}cloneWithExpr(e){const n=new zs(this.input,this.pos,this.pos2,e,this.succeeded,this.bindings,this.children);return n.isHeadOfLeftRecursion=this.isHeadOfLeftRecursion,n.isImplicitSpaces=this.isImplicitSpaces,n.isMemoized=this.isMemoized,n.isRootNode=this.isRootNode,n.terminatesLR=this.terminatesLR,n.terminatingLREntry=this.terminatingLREntry,n}recordLRTermination(e,n){this.terminatingLREntry=new zs(this.input,this.pos,this.pos2,this.expr,!1,[n],[e]),this.terminatingLREntry.terminatesLR=!0}walk(e,n){let r=e;typeof r=="function"&&(r={enter:r});function s(o,c,d){let f=!0;r.enter&&r.enter.call(n,o,c,d)===zs.prototype.SKIP&&(f=!1),f&&(o.children.forEach(p=>{s(p,o,d+1)}),r.exit&&r.exit.call(n,o,c,d))}this.isRootNode?this.children.forEach(o=>{s(o,null,0)}):s(this,null,0)}toString(){const e=new Fi;return this.walk((n,r,s)=>{if(!n)return this.SKIP;if(n.expr.constructor.name!=="Alt"){if(e.append(xO(n.input,n.pos,10)+vO(s*2+1)),e.append((n.succeeded?hO:fO)+" "+n.displayString),n.isHeadOfLeftRecursion&&e.append(" (LR)"),n.succeeded){const c=u1(n.source.contents);e.append(" "+mO+" "),e.append(typeof c=="string"?'"'+c+'"':c)}e.append(`
|
|
66
|
-
`)}}),e.contents()}}zs.prototype.SKIP={};Object.keys(dm).forEach(t=>{const e=dm[t];Object.defineProperty(zs.prototype,t,{get(){return(this._flags&e)!==0},set(n){n?this._flags|=e:this._flags&=~e}})});xe.prototype.allowsSkippingPrecedingSpace=an("allowsSkippingPrecedingSpace");Yt.allowsSkippingPrecedingSpace=Zt.allowsSkippingPrecedingSpace=He.prototype.allowsSkippingPrecedingSpace=Vt.prototype.allowsSkippingPrecedingSpace=Wt.prototype.allowsSkippingPrecedingSpace=zt.prototype.allowsSkippingPrecedingSpace=function(){return!0};Ot.prototype.allowsSkippingPrecedingSpace=on.prototype.allowsSkippingPrecedingSpace=vn.prototype.allowsSkippingPrecedingSpace=ln.prototype.allowsSkippingPrecedingSpace=qt.prototype.allowsSkippingPrecedingSpace=Jt.prototype.allowsSkippingPrecedingSpace=It.prototype.allowsSkippingPrecedingSpace=function(){return!1};let dl;l1(t=>{dl=t});let Lu;xe.prototype.assertAllApplicationsAreValid=function(t,e){Lu=0,this._assertAllApplicationsAreValid(t,e)};xe.prototype._assertAllApplicationsAreValid=an("_assertAllApplicationsAreValid");Yt._assertAllApplicationsAreValid=Zt._assertAllApplicationsAreValid=Vt.prototype._assertAllApplicationsAreValid=Wt.prototype._assertAllApplicationsAreValid=Jt.prototype._assertAllApplicationsAreValid=zt.prototype._assertAllApplicationsAreValid=function(t,e){};vn.prototype._assertAllApplicationsAreValid=function(t,e){Lu++,this.expr._assertAllApplicationsAreValid(t,e),Lu--};Ot.prototype._assertAllApplicationsAreValid=function(t,e){for(let n=0;n<this.terms.length;n++)this.terms[n]._assertAllApplicationsAreValid(t,e)};It.prototype._assertAllApplicationsAreValid=function(t,e){for(let n=0;n<this.factors.length;n++)this.factors[n]._assertAllApplicationsAreValid(t,e)};on.prototype._assertAllApplicationsAreValid=qt.prototype._assertAllApplicationsAreValid=ln.prototype._assertAllApplicationsAreValid=function(t,e){this.expr._assertAllApplicationsAreValid(t,e)};He.prototype._assertAllApplicationsAreValid=function(t,e,n=!1){const r=e.rules[this.ruleName],s=Ci(t)&&Lu===0;if(!r)throw s1(this.ruleName,e.name,this.source);if(!n&&Ci(this.ruleName)&&!s)throw QN(this.ruleName,this);const o=this.args.length,c=r.formals.length;if(o!==c)throw ZN(this.ruleName,c,o,this.source);const d=dl&&r===dl.rules.applySyntactic;if(dl&&r===dl.rules.caseInsensitive&&!(this.args[0]instanceof Vt))throw zx('a Terminal (e.g. "abc")',this.args[0]);if(d){const p=this.args[0];if(!(p instanceof He))throw zx("a syntactic rule application",p);if(!Ci(p.ruleName))throw XN(p);if(s)throw eO(this)}this.args.forEach(p=>{if(p._assertAllApplicationsAreValid(t,e,d),p.getArity()!==1)throw WN(this.ruleName,p)})};xe.prototype.assertChoicesHaveUniformArity=an("assertChoicesHaveUniformArity");Yt.assertChoicesHaveUniformArity=Zt.assertChoicesHaveUniformArity=Vt.prototype.assertChoicesHaveUniformArity=Wt.prototype.assertChoicesHaveUniformArity=Jt.prototype.assertChoicesHaveUniformArity=vn.prototype.assertChoicesHaveUniformArity=zt.prototype.assertChoicesHaveUniformArity=function(t){};Ot.prototype.assertChoicesHaveUniformArity=function(t){if(this.terms.length===0)return;const e=this.terms[0].getArity();for(let n=0;n<this.terms.length;n++){const r=this.terms[n];r.assertChoicesHaveUniformArity();const s=r.getArity();if(e!==s)throw o1(t,e,s,r)}};_d.prototype.assertChoicesHaveUniformArity=function(t){const e=this.terms[0].getArity(),n=this.terms[1].getArity();if(e!==n)throw o1(t,n,e,this.terms[0])};It.prototype.assertChoicesHaveUniformArity=function(t){for(let e=0;e<this.factors.length;e++)this.factors[e].assertChoicesHaveUniformArity(t)};on.prototype.assertChoicesHaveUniformArity=function(t){this.expr.assertChoicesHaveUniformArity(t)};qt.prototype.assertChoicesHaveUniformArity=function(t){};ln.prototype.assertChoicesHaveUniformArity=function(t){this.expr.assertChoicesHaveUniformArity(t)};He.prototype.assertChoicesHaveUniformArity=function(t){};xe.prototype.assertIteratedExprsAreNotNullable=an("assertIteratedExprsAreNotNullable");Yt.assertIteratedExprsAreNotNullable=Zt.assertIteratedExprsAreNotNullable=Vt.prototype.assertIteratedExprsAreNotNullable=Wt.prototype.assertIteratedExprsAreNotNullable=Jt.prototype.assertIteratedExprsAreNotNullable=zt.prototype.assertIteratedExprsAreNotNullable=function(t){};Ot.prototype.assertIteratedExprsAreNotNullable=function(t){for(let e=0;e<this.terms.length;e++)this.terms[e].assertIteratedExprsAreNotNullable(t)};It.prototype.assertIteratedExprsAreNotNullable=function(t){for(let e=0;e<this.factors.length;e++)this.factors[e].assertIteratedExprsAreNotNullable(t)};on.prototype.assertIteratedExprsAreNotNullable=function(t){if(this.expr.assertIteratedExprsAreNotNullable(t),this.expr.isNullable(t))throw a1(this,[])};os.prototype.assertIteratedExprsAreNotNullable=qt.prototype.assertIteratedExprsAreNotNullable=ln.prototype.assertIteratedExprsAreNotNullable=vn.prototype.assertIteratedExprsAreNotNullable=function(t){this.expr.assertIteratedExprsAreNotNullable(t)};He.prototype.assertIteratedExprsAreNotNullable=function(t){this.args.forEach(e=>{e.assertIteratedExprsAreNotNullable(t)})};let Ry=class{constructor(e){this.matchLength=e}get ctorName(){throw new Error("subclass responsibility")}numChildren(){return this.children?this.children.length:0}childAt(e){if(this.children)return this.children[e]}indexOfChild(e){return this.children.indexOf(e)}hasChildren(){return this.numChildren()>0}hasNoChildren(){return!this.hasChildren()}onlyChild(){if(this.numChildren()!==1)throw new Error("cannot get only child of a node of type "+this.ctorName+" (it has "+this.numChildren()+" children)");return this.firstChild()}firstChild(){if(this.hasNoChildren())throw new Error("cannot get first child of a "+this.ctorName+" node, which has no children");return this.childAt(0)}lastChild(){if(this.hasNoChildren())throw new Error("cannot get last child of a "+this.ctorName+" node, which has no children");return this.childAt(this.numChildren()-1)}childBefore(e){const n=this.indexOfChild(e);if(n<0)throw new Error("Node.childBefore() called w/ an argument that is not a child");if(n===0)throw new Error("cannot get child before first child");return this.childAt(n-1)}childAfter(e){const n=this.indexOfChild(e);if(n<0)throw new Error("Node.childAfter() called w/ an argument that is not a child");if(n===this.numChildren()-1)throw new Error("cannot get child after last child");return this.childAt(n+1)}isTerminal(){return!1}isNonterminal(){return!1}isIteration(){return!1}isOptional(){return!1}};class qi extends Ry{get ctorName(){return"_terminal"}isTerminal(){return!0}get primitiveValue(){throw new Error("The `primitiveValue` property was removed in Ohm v17.")}}class wO extends Ry{constructor(e,n,r,s){super(s),this.ruleName=e,this.children=n,this.childOffsets=r}get ctorName(){return this.ruleName}isNonterminal(){return!0}isLexical(){return X_(this.ctorName)}isSyntactic(){return Ci(this.ctorName)}}class d1 extends Ry{constructor(e,n,r,s){super(r),this.children=e,this.childOffsets=n,this.optional=s}get ctorName(){return"_iter"}isIteration(){return!0}isOptional(){return this.optional}}xe.prototype.eval=an("eval");Yt.eval=function(t){const{inputStream:e}=t,n=e.pos,r=e.nextCodePoint();return r!==void 0?(t.pushBinding(new qi(String.fromCodePoint(r).length),n),!0):(t.processFailure(n,this),!1)};Zt.eval=function(t){const{inputStream:e}=t,n=e.pos;return e.atEnd()?(t.pushBinding(new qi(0),n),!0):(t.processFailure(n,this),!1)};Vt.prototype.eval=function(t){const{inputStream:e}=t,n=e.pos;return e.matchString(this.obj)?(t.pushBinding(new qi(this.obj.length),n),!0):(t.processFailure(n,this),!1)};Wt.prototype.eval=function(t){const{inputStream:e}=t,n=e.pos,r=this.matchCodePoint?e.nextCodePoint():e.nextCharCode();return r!==void 0&&this.from.codePointAt(0)<=r&&r<=this.to.codePointAt(0)?(t.pushBinding(new qi(String.fromCodePoint(r).length),n),!0):(t.processFailure(n,this),!1)};Jt.prototype.eval=function(t){return t.eval(t.currentApplication().args[this.index])};vn.prototype.eval=function(t){t.enterLexifiedContext();const e=t.eval(this.expr);return t.exitLexifiedContext(),e};Ot.prototype.eval=function(t){for(let e=0;e<this.terms.length;e++)if(t.eval(this.terms[e]))return!0;return!1};It.prototype.eval=function(t){for(let e=0;e<this.factors.length;e++){const n=this.factors[e];if(!t.eval(n))return!1}return!0};on.prototype.eval=function(t){const{inputStream:e}=t,n=e.pos,r=this.getArity(),s=[],o=[];for(;s.length<r;)s.push([]),o.push([]);let c=0,d=n,f;for(;c<this.maxNumMatches&&t.eval(this.expr);){if(e.pos===d)throw a1(this,t._applicationStack);d=e.pos,c++;const v=t._bindings.splice(t._bindings.length-r,r),x=t._bindingOffsets.splice(t._bindingOffsets.length-r,r);for(f=0;f<v.length;f++)s[f].push(v[f]),o[f].push(x[f])}if(c<this.minNumMatches)return!1;let p=t.posToOffset(n),g=0;if(c>0){const v=s[r-1],x=o[r-1],_=x[x.length-1]+v[v.length-1].matchLength;p=o[0][0],g=_-p}const b=this instanceof os;for(f=0;f<s.length;f++)t._bindings.push(new d1(s[f],o[f],g,b)),t._bindingOffsets.push(p);return!0};qt.prototype.eval=function(t){const{inputStream:e}=t,n=e.pos;t.pushFailuresInfo();const r=t.eval(this.expr);return t.popFailuresInfo(),r?(t.processFailure(n,this),!1):(e.pos=n,!0)};ln.prototype.eval=function(t){const{inputStream:e}=t,n=e.pos;return t.eval(this.expr)?(e.pos=n,!0):!1};He.prototype.eval=function(t){const e=t.currentApplication(),n=e?e.args:[],r=this.substituteParams(n),s=t.getCurrentPosInfo();if(s.isActive(r))return r.handleCycle(t);const o=r.toMemoKey(),c=s.memo[o];if(c&&s.shouldUseMemoizedResult(c)){if(t.hasNecessaryInfo(c))return t.useMemoizedResult(t.inputStream.pos,c);delete s.memo[o]}return r.reallyEval(t)};He.prototype.handleCycle=function(t){const e=t.getCurrentPosInfo(),{currentLeftRecursion:n}=e,r=this.toMemoKey();let s=e.memo[r];return n&&n.headApplication.toMemoKey()===r?s.updateInvolvedApplicationMemoKeys():s||(s=e.memoize(r,{matchLength:0,examinedLength:0,value:!1,rightmostFailureOffset:-1}),e.startLeftRecursion(this,s)),t.useMemoizedResult(t.inputStream.pos,s)};He.prototype.reallyEval=function(t){const{inputStream:e}=t,n=e.pos,r=t.getCurrentPosInfo(),s=t.grammar.rules[this.ruleName],{body:o}=s,{description:c}=s;t.enterApplication(r,this),c&&t.pushFailuresInfo();const d=e.examinedLength;e.examinedLength=0;let f=this.evalOnce(o,t);const p=r.currentLeftRecursion,g=this.toMemoKey(),b=p&&p.headApplication.toMemoKey()===g;let v;t.doNotMemoize?t.doNotMemoize=!1:b?(f=this.growSeedResult(o,t,n,p,f),r.endLeftRecursion(),v=p,v.examinedLength=e.examinedLength-n,v.rightmostFailureOffset=t._getRightmostFailureOffset(),r.memoize(g,v)):(!p||!p.isInvolved(g))&&(v=r.memoize(g,{matchLength:e.pos-n,examinedLength:e.examinedLength-n,value:f,failuresAtRightmostPosition:t.cloneRecordedFailures(),rightmostFailureOffset:t._getRightmostFailureOffset()}));const x=!!f;if(c&&(t.popFailuresInfo(),x||t.processFailure(n,this),v&&(v.failuresAtRightmostPosition=t.cloneRecordedFailures(),v.rightmostFailureOffset=t._getRightmostFailureOffset())),t.isTracing()&&v){const _=t.getTraceEntry(n,this,x,x?[f]:[]);b&&(Js(_.terminatingLREntry!=null||!x),_.isHeadOfLeftRecursion=!0),v.traceEntry=_}return e.examinedLength=Math.max(e.examinedLength,d),t.exitApplication(r,f),x};He.prototype.evalOnce=function(t,e){const{inputStream:n}=e,r=n.pos;if(e.eval(t)){const s=t.getArity(),o=e._bindings.splice(e._bindings.length-s,s),c=e._bindingOffsets.splice(e._bindingOffsets.length-s,s),d=n.pos-r;return new wO(this.ruleName,o,c,d)}else return!1};He.prototype.growSeedResult=function(t,e,n,r,s){if(!s)return!1;const{inputStream:o}=e;for(;;){if(r.matchLength=o.pos-n,r.value=s,r.failuresAtRightmostPosition=e.cloneRecordedFailures(),e.isTracing()){const c=e.trace[e.trace.length-1];r.traceEntry=new zs(e.input,n,o.pos,this,!0,[s],[c.clone()])}if(o.pos=n,s=this.evalOnce(t,e),o.pos-n<=r.matchLength)break;e.isTracing()&&e.trace.splice(-2,1)}return e.isTracing()&&r.traceEntry.recordLRTermination(e.trace.pop(),s),o.pos=n+r.matchLength,r.value};zt.prototype.eval=function(t){const{inputStream:e}=t,n=e.pos,r=e.nextCodePoint();if(r!==void 0&&r<=uO){const s=String.fromCodePoint(r);if(this.pattern.test(s))return t.pushBinding(new qi(s.length),n),!0}return t.processFailure(n,this),!1};xe.prototype.getArity=an("getArity");Yt.getArity=Zt.getArity=Vt.prototype.getArity=Wt.prototype.getArity=Jt.prototype.getArity=He.prototype.getArity=zt.prototype.getArity=function(){return 1};Ot.prototype.getArity=function(){return this.terms.length===0?0:this.terms[0].getArity()};It.prototype.getArity=function(){let t=0;for(let e=0;e<this.factors.length;e++)t+=this.factors[e].getArity();return t};on.prototype.getArity=function(){return this.expr.getArity()};qt.prototype.getArity=function(){return 0};ln.prototype.getArity=vn.prototype.getArity=function(){return this.expr.getArity()};function ur(t,e){const n={};if(t.source&&e){const r=t.source.relativeTo(e);n.sourceInterval=[r.startIdx,r.endIdx]}return n}xe.prototype.outputRecipe=an("outputRecipe");Yt.outputRecipe=function(t,e){return["any",ur(this,e)]};Zt.outputRecipe=function(t,e){return["end",ur(this,e)]};Vt.prototype.outputRecipe=function(t,e){return["terminal",ur(this,e),this.obj]};Wt.prototype.outputRecipe=function(t,e){return["range",ur(this,e),this.from,this.to]};Jt.prototype.outputRecipe=function(t,e){return["param",ur(this,e),this.index]};Ot.prototype.outputRecipe=function(t,e){return["alt",ur(this,e)].concat(this.terms.map(n=>n.outputRecipe(t,e)))};_d.prototype.outputRecipe=function(t,e){return this.terms[0].outputRecipe(t,e)};Ed.prototype.outputRecipe=function(t,e){const n=this.terms.slice(0,this.expansionPos),r=this.terms.slice(this.expansionPos+1);return["splice",ur(this,e),n.map(s=>s.outputRecipe(t,e)),r.map(s=>s.outputRecipe(t,e))]};It.prototype.outputRecipe=function(t,e){return["seq",ur(this,e)].concat(this.factors.map(n=>n.outputRecipe(t,e)))};Pi.prototype.outputRecipe=to.prototype.outputRecipe=os.prototype.outputRecipe=qt.prototype.outputRecipe=ln.prototype.outputRecipe=vn.prototype.outputRecipe=function(t,e){return[this.constructor.name.toLowerCase(),ur(this,e),this.expr.outputRecipe(t,e)]};He.prototype.outputRecipe=function(t,e){return["app",ur(this,e),this.ruleName,this.args.map(n=>n.outputRecipe(t,e))]};zt.prototype.outputRecipe=function(t,e){return["unicodeChar",ur(this,e),this.categoryOrProp]};xe.prototype.introduceParams=an("introduceParams");Yt.introduceParams=Zt.introduceParams=Vt.prototype.introduceParams=Wt.prototype.introduceParams=Jt.prototype.introduceParams=zt.prototype.introduceParams=function(t){return this};Ot.prototype.introduceParams=function(t){return this.terms.forEach((e,n,r)=>{r[n]=e.introduceParams(t)}),this};It.prototype.introduceParams=function(t){return this.factors.forEach((e,n,r)=>{r[n]=e.introduceParams(t)}),this};on.prototype.introduceParams=qt.prototype.introduceParams=ln.prototype.introduceParams=vn.prototype.introduceParams=function(t){return this.expr=this.expr.introduceParams(t),this};He.prototype.introduceParams=function(t){const e=t.indexOf(this.ruleName);if(e>=0){if(this.args.length>0)throw new Error("Parameterized rules cannot be passed as arguments to another rule.");return new Jt(e).withSource(this.source)}else return this.args.forEach((n,r,s)=>{s[r]=n.introduceParams(t)}),this};xe.prototype.isNullable=function(t){return this._isNullable(t,Object.create(null))};xe.prototype._isNullable=an("_isNullable");Yt._isNullable=Wt.prototype._isNullable=Jt.prototype._isNullable=to.prototype._isNullable=zt.prototype._isNullable=function(t,e){return!1};Zt._isNullable=function(t,e){return!0};Vt.prototype._isNullable=function(t,e){return typeof this.obj=="string"?this.obj==="":!1};Ot.prototype._isNullable=function(t,e){return this.terms.length===0||this.terms.some(n=>n._isNullable(t,e))};It.prototype._isNullable=function(t,e){return this.factors.every(n=>n._isNullable(t,e))};Pi.prototype._isNullable=os.prototype._isNullable=qt.prototype._isNullable=ln.prototype._isNullable=function(t,e){return!0};vn.prototype._isNullable=function(t,e){return this.expr._isNullable(t,e)};He.prototype._isNullable=function(t,e){const n=this.toMemoKey();if(!Object.prototype.hasOwnProperty.call(e,n)){const{body:r}=t.rules[this.ruleName],s=r.substituteParams(this.args);e[n]=!1,e[n]=s._isNullable(t,e)}return e[n]};xe.prototype.substituteParams=an("substituteParams");Yt.substituteParams=Zt.substituteParams=Vt.prototype.substituteParams=Wt.prototype.substituteParams=zt.prototype.substituteParams=function(t){return this};Jt.prototype.substituteParams=function(t){return n1(t[this.index])};Ot.prototype.substituteParams=function(t){return new Ot(this.terms.map(e=>e.substituteParams(t)))};It.prototype.substituteParams=function(t){return new It(this.factors.map(e=>e.substituteParams(t)))};on.prototype.substituteParams=qt.prototype.substituteParams=ln.prototype.substituteParams=vn.prototype.substituteParams=function(t){return new this.constructor(this.expr.substituteParams(t))};He.prototype.substituteParams=function(t){if(this.args.length===0)return this;{const e=this.args.map(n=>n.substituteParams(t));return new He(this.ruleName,e)}};function Gx(t){return/^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(t)}function Dy(t){const e=Object.create(null);t.forEach(n=>{e[n]=(e[n]||0)+1}),Object.keys(e).forEach(n=>{if(e[n]<=1)return;let r=1;t.forEach((s,o)=>{s===n&&(t[o]=s+"_"+r++)})})}xe.prototype.toArgumentNameList=an("toArgumentNameList");Yt.toArgumentNameList=function(t,e){return["any"]};Zt.toArgumentNameList=function(t,e){return["end"]};Vt.prototype.toArgumentNameList=function(t,e){return typeof this.obj=="string"&&/^[_a-zA-Z0-9]+$/.test(this.obj)?["_"+this.obj]:["$"+t]};Wt.prototype.toArgumentNameList=function(t,e){let n=this.from+"_to_"+this.to;return Gx(n)||(n="_"+n),Gx(n)||(n="$"+t),[n]};Ot.prototype.toArgumentNameList=function(t,e){const n=this.terms.map(o=>o.toArgumentNameList(t,!0)),r=[],s=n[0].length;for(let o=0;o<s;o++){const c=[];for(let f=0;f<this.terms.length;f++)c.push(n[f][o]);const d=Q_(c);r.push(d.join("_or_"))}return e||Dy(r),r};It.prototype.toArgumentNameList=function(t,e){let n=[];return this.factors.forEach(r=>{const s=r.toArgumentNameList(t,!0);n=n.concat(s),t+=s.length}),e||Dy(n),n};on.prototype.toArgumentNameList=function(t,e){const n=this.expr.toArgumentNameList(t,e).map(r=>r[r.length-1]==="s"?r+"es":r+"s");return e||Dy(n),n};os.prototype.toArgumentNameList=function(t,e){return this.expr.toArgumentNameList(t,e).map(n=>"opt"+n[0].toUpperCase()+n.slice(1))};qt.prototype.toArgumentNameList=function(t,e){return[]};ln.prototype.toArgumentNameList=vn.prototype.toArgumentNameList=function(t,e){return this.expr.toArgumentNameList(t,e)};He.prototype.toArgumentNameList=function(t,e){return[this.ruleName]};zt.prototype.toArgumentNameList=function(t,e){return["$"+t]};Jt.prototype.toArgumentNameList=function(t,e){return["param"+this.index]};xe.prototype.toDisplayString=an("toDisplayString");Ot.prototype.toDisplayString=It.prototype.toDisplayString=function(){return this.source?this.source.trimmed().contents:"["+this.constructor.name+"]"};Yt.toDisplayString=Zt.toDisplayString=on.prototype.toDisplayString=qt.prototype.toDisplayString=ln.prototype.toDisplayString=vn.prototype.toDisplayString=Vt.prototype.toDisplayString=Wt.prototype.toDisplayString=Jt.prototype.toDisplayString=function(){return this.toString()};He.prototype.toDisplayString=function(){if(this.args.length>0){const t=this.args.map(e=>e.toDisplayString());return this.ruleName+"<"+t.join(",")+">"}else return this.ruleName};zt.prototype.toDisplayString=function(){return"Unicode ["+this.categoryOrProp+"] character"};function SO(t){return t==="description"||t==="string"||t==="code"}class xn{constructor(e,n,r){if(!SO(r))throw new Error("invalid Failure type: "+r);this.pexpr=e,this.text=n,this.type=r,this.fluffy=!1}getPExpr(){return this.pexpr}getText(){return this.text}getType(){return this.type}isDescription(){return this.type==="description"}isStringTerminal(){return this.type==="string"}isCode(){return this.type==="code"}isFluffy(){return this.fluffy}makeFluffy(){this.fluffy=!0}clearFluffy(){this.fluffy=!1}subsumes(e){return this.getText()===e.getText()&&this.type===e.type&&(!this.isFluffy()||this.isFluffy()&&e.isFluffy())}toString(){return this.type==="string"?JSON.stringify(this.getText()):this.getText()}clone(){const e=new xn(this.pexpr,this.text,this.type);return this.isFluffy()&&e.makeFluffy(),e}toKey(){return this.toString()+"#"+this.type}}xe.prototype.toFailure=an("toFailure");Yt.toFailure=function(t){return new xn(this,"any object","description")};Zt.toFailure=function(t){return new xn(this,"end of input","description")};Vt.prototype.toFailure=function(t){return new xn(this,this.obj,"string")};Wt.prototype.toFailure=function(t){return new xn(this,JSON.stringify(this.from)+".."+JSON.stringify(this.to),"code")};qt.prototype.toFailure=function(t){const e=this.expr===Yt?"nothing":"not "+this.expr.toFailure(t);return new xn(this,e,"description")};ln.prototype.toFailure=function(t){return this.expr.toFailure(t)};He.prototype.toFailure=function(t){let{description:e}=t.rules[this.ruleName];return e||(e=(/^[aeiouAEIOU]/.test(this.ruleName)?"an":"a")+" "+this.ruleName),new xn(this,e,"description")};zt.prototype.toFailure=function(t){return new xn(this,"a Unicode ["+this.categoryOrProp+"] character","description")};Ot.prototype.toFailure=function(t){const n="("+this.terms.map(r=>r.toFailure(t)).join(" or ")+")";return new xn(this,n,"description")};It.prototype.toFailure=function(t){const n="("+this.factors.map(r=>r.toFailure(t)).join(" ")+")";return new xn(this,n,"description")};on.prototype.toFailure=function(t){const e="("+this.expr.toFailure(t)+this.operator+")";return new xn(this,e,"description")};xe.prototype.toString=an("toString");Yt.toString=function(){return"any"};Zt.toString=function(){return"end"};Vt.prototype.toString=function(){return JSON.stringify(this.obj)};Wt.prototype.toString=function(){return JSON.stringify(this.from)+".."+JSON.stringify(this.to)};Jt.prototype.toString=function(){return"$"+this.index};vn.prototype.toString=function(){return"#("+this.expr.toString()+")"};Ot.prototype.toString=function(){return this.terms.length===1?this.terms[0].toString():"("+this.terms.map(t=>t.toString()).join(" | ")+")"};It.prototype.toString=function(){return this.factors.length===1?this.factors[0].toString():"("+this.factors.map(t=>t.toString()).join(" ")+")"};on.prototype.toString=function(){return this.expr+this.operator};qt.prototype.toString=function(){return"~"+this.expr};ln.prototype.toString=function(){return"&"+this.expr};He.prototype.toString=function(){if(this.args.length>0){const t=this.args.map(e=>e.toString());return this.ruleName+"<"+t.join(",")+">"}else return this.ruleName};zt.prototype.toString=function(){return"\\p{"+this.categoryOrProp+"}"};class Iy extends xe{constructor(e){super(),this.obj=e}_getString(e){const n=e.currentApplication().args[this.obj.index];return Js(n instanceof Vt,"expected a Terminal expression"),n.obj}allowsSkippingPrecedingSpace(){return!0}eval(e){const{inputStream:n}=e,r=n.pos,s=this._getString(e);return n.matchString(s,!0)?(e.pushBinding(new qi(s.length),r),!0):(e.processFailure(r,this),!1)}getArity(){return 1}substituteParams(e){return new Iy(this.obj.substituteParams(e))}toDisplayString(){return this.obj.toDisplayString()+" (case-insensitive)"}toFailure(e){return new xn(this,this.obj.toFailure(e)+" (case-insensitive)","description")}_isNullable(e,n){return this.obj._isNullable(e,n)}}let f1;l1(t=>{f1=t.rules.applySyntactic.body});const Ep=new He("spaces");class _O{constructor(e,n,r){this.matcher=e,this.startExpr=n,this.grammar=e.grammar,this.input=e.getInput(),this.inputStream=new Ad(this.input),this.memoTable=e._memoTable,this.userData=void 0,this.doNotMemoize=!1,this._bindings=[],this._bindingOffsets=[],this._applicationStack=[],this._posStack=[0],this.inLexifiedContextStack=[!1],this.rightmostFailurePosition=-1,this._rightmostFailurePositionStack=[],this._recordedFailuresStack=[],r!==void 0&&(this.positionToRecordFailures=r,this.recordedFailures=Object.create(null))}posToOffset(e){return e-this._posStack[this._posStack.length-1]}enterApplication(e,n){this._posStack.push(this.inputStream.pos),this._applicationStack.push(n),this.inLexifiedContextStack.push(!1),e.enter(n),this._rightmostFailurePositionStack.push(this.rightmostFailurePosition),this.rightmostFailurePosition=-1}exitApplication(e,n){const r=this._posStack.pop();this._applicationStack.pop(),this.inLexifiedContextStack.pop(),e.exit(),this.rightmostFailurePosition=Math.max(this.rightmostFailurePosition,this._rightmostFailurePositionStack.pop()),n&&this.pushBinding(n,r)}enterLexifiedContext(){this.inLexifiedContextStack.push(!0)}exitLexifiedContext(){this.inLexifiedContextStack.pop()}currentApplication(){return this._applicationStack[this._applicationStack.length-1]}inSyntacticContext(){const e=this.currentApplication();return e?e.isSyntactic()&&!this.inLexifiedContext():this.startExpr.factors[0].isSyntactic()}inLexifiedContext(){return this.inLexifiedContextStack[this.inLexifiedContextStack.length-1]}skipSpaces(){return this.pushFailuresInfo(),this.eval(Ep),this.popBinding(),this.popFailuresInfo(),this.inputStream.pos}skipSpacesIfInSyntacticContext(){return this.inSyntacticContext()?this.skipSpaces():this.inputStream.pos}maybeSkipSpacesBefore(e){return e.allowsSkippingPrecedingSpace()&&e!==Ep?this.skipSpacesIfInSyntacticContext():this.inputStream.pos}pushBinding(e,n){this._bindings.push(e),this._bindingOffsets.push(this.posToOffset(n))}popBinding(){this._bindings.pop(),this._bindingOffsets.pop()}numBindings(){return this._bindings.length}truncateBindings(e){for(;this._bindings.length>e;)this.popBinding()}getCurrentPosInfo(){return this.getPosInfo(this.inputStream.pos)}getPosInfo(e){let n=this.memoTable[e];return n||(n=this.memoTable[e]=new dO),n}processFailure(e,n){if(this.rightmostFailurePosition=Math.max(this.rightmostFailurePosition,e),this.recordedFailures&&e===this.positionToRecordFailures){const r=this.currentApplication();r&&(n=n.substituteParams(r.args)),this.recordFailure(n.toFailure(this.grammar),!1)}}recordFailure(e,n){const r=e.toKey();this.recordedFailures[r]?this.recordedFailures[r].isFluffy()&&!e.isFluffy()&&this.recordedFailures[r].clearFluffy():this.recordedFailures[r]=n?e.clone():e}recordFailures(e,n){Object.keys(e).forEach(r=>{this.recordFailure(e[r],n)})}cloneRecordedFailures(){if(!this.recordedFailures)return;const e=Object.create(null);return Object.keys(this.recordedFailures).forEach(n=>{e[n]=this.recordedFailures[n].clone()}),e}getRightmostFailurePosition(){return this.rightmostFailurePosition}_getRightmostFailureOffset(){return this.rightmostFailurePosition>=0?this.posToOffset(this.rightmostFailurePosition):-1}getMemoizedTraceEntry(e,n){const r=this.memoTable[e];if(r&&n instanceof He){const s=r.memo[n.toMemoKey()];if(s&&s.traceEntry){const o=s.traceEntry.cloneWithExpr(n);return o.isMemoized=!0,o}}return null}getTraceEntry(e,n,r,s){if(n instanceof He){const o=this.currentApplication(),c=o?o.args:[];n=n.substituteParams(c)}return this.getMemoizedTraceEntry(e,n)||new zs(this.input,e,this.inputStream.pos,n,r,s,this.trace)}isTracing(){return!!this.trace}hasNecessaryInfo(e){return this.trace&&!e.traceEntry?!1:this.recordedFailures&&this.inputStream.pos+e.rightmostFailureOffset===this.positionToRecordFailures?!!e.failuresAtRightmostPosition:!0}useMemoizedResult(e,n){this.trace&&this.trace.push(n.traceEntry);const r=this.inputStream.pos+n.rightmostFailureOffset;return this.rightmostFailurePosition=Math.max(this.rightmostFailurePosition,r),this.recordedFailures&&this.positionToRecordFailures===r&&n.failuresAtRightmostPosition&&this.recordFailures(n.failuresAtRightmostPosition,!0),this.inputStream.examinedLength=Math.max(this.inputStream.examinedLength,n.examinedLength+e),n.value?(this.inputStream.pos+=n.matchLength,this.pushBinding(n.value,e),!0):!1}eval(e){const{inputStream:n}=this,r=this._bindings.length,s=this.userData;let o;this.recordedFailures&&(o=this.recordedFailures,this.recordedFailures=Object.create(null));const c=n.pos,d=this.maybeSkipSpacesBefore(e);let f;this.trace&&(f=this.trace,this.trace=[]);const p=e.eval(this);if(this.trace){const g=this._bindings.slice(r),b=this.getTraceEntry(d,e,p,g);b.isImplicitSpaces=e===Ep,b.isRootNode=e===this.startExpr,f.push(b),this.trace=f}return p?this.recordedFailures&&n.pos===this.positionToRecordFailures&&Object.keys(this.recordedFailures).forEach(g=>{this.recordedFailures[g].makeFluffy()}):(n.pos=c,this.truncateBindings(r),this.userData=s),this.recordedFailures&&this.recordFailures(o,!1),e===f1&&this.skipSpaces(),p}getMatchResult(){this.grammar._setUpMatchState(this),this.eval(this.startExpr);let e;this.recordedFailures&&(e=Object.keys(this.recordedFailures).map(r=>this.recordedFailures[r]));const n=this._bindings[0];return n&&(n.grammar=this.grammar),new c1(this.matcher,this.input,this.startExpr,n,this._bindingOffsets[0],this.rightmostFailurePosition,e)}getTrace(){this.trace=[];const e=this.getMatchResult(),n=this.trace[this.trace.length-1];return n.result=e,n}pushFailuresInfo(){this._rightmostFailurePositionStack.push(this.rightmostFailurePosition),this._recordedFailuresStack.push(this.recordedFailures)}popFailuresInfo(){this.rightmostFailurePosition=this._rightmostFailurePositionStack.pop(),this.recordedFailures=this._recordedFailuresStack.pop()}}class EO{constructor(e){this.grammar=e,this._memoTable=[],this._input="",this._isMemoTableStale=!1}_resetMemoTable(){this._memoTable=[],this._isMemoTableStale=!1}getInput(){return this._input}setInput(e){return this._input!==e&&this.replaceInputRange(0,this._input.length,e),this}replaceInputRange(e,n,r){const s=this._input,o=this._memoTable;if(e<0||e>s.length||n<0||n>s.length||e>n)throw new Error("Invalid indices: "+e+" and "+n);this._input=s.slice(0,e)+r+s.slice(n),this._input!==s&&o.length>0&&(this._isMemoTableStale=!0);const c=o.slice(n);o.length=e;for(let d=0;d<r.length;d++)o.push(void 0);for(const d of c)o.push(d);for(let d=0;d<e;d++){const f=o[d];f&&f.clearObsoleteEntries(d,e)}return this}match(e,n={incremental:!0}){return this._match(this._getStartExpr(e),{incremental:n.incremental,tracing:!1})}trace(e,n={incremental:!0}){return this._match(this._getStartExpr(e),{incremental:n.incremental,tracing:!0})}_match(e,n={}){const r={tracing:!1,incremental:!0,positionToRecordFailures:void 0,...n};if(!r.incremental)this._resetMemoTable();else if(this._isMemoTableStale&&!this.grammar.supportsIncrementalParsing)throw GN(this.grammar);const s=new _O(this,e,r.positionToRecordFailures);return r.tracing?s.getTrace():s.getMatchResult()}_getStartExpr(e){const n=e||this.grammar.defaultStartRule;if(!n)throw new Error("Missing start rule argument -- the grammar has no default start rule.");const r=this.grammar.parseApplication(n);return new It([r,Zt])}}const fl=[],fm=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);class Kx{constructor(e,n,r){this._node=e,this.source=n,this._baseInterval=r,e.isNonterminal()&&Js(n===r),this._childWrappers=[]}_forgetMemoizedResultFor(e){delete this._node[this._semantics.attributeKeys[e]],this.children.forEach(n=>{n._forgetMemoizedResultFor(e)})}child(e){if(!(0<=e&&e<this._node.numChildren()))return;let n=this._childWrappers[e];if(!n){const r=this._node.childAt(e),s=this._node.childOffsets[e],o=this._baseInterval.subInterval(s,r.matchLength),c=r.isNonterminal()?o:this._baseInterval;n=this._childWrappers[e]=this._semantics.wrap(r,o,c)}return n}_children(){for(let e=0;e<this._node.numChildren();e++)this.child(e);return this._childWrappers}isIteration(){return this._node.isIteration()}isTerminal(){return this._node.isTerminal()}isNonterminal(){return this._node.isNonterminal()}isSyntactic(){return this.isNonterminal()&&this._node.isSyntactic()}isLexical(){return this.isNonterminal()&&this._node.isLexical()}isOptional(){return this._node.isOptional()}iteration(e){const n=e||[],r=n.map(c=>c._node),s=new d1(r,[],-1,!1),o=this._semantics.wrap(s,null,null);return o._childWrappers=n,o}get children(){return this._children()}get ctorName(){return this._node.ctorName}get numChildren(){return this._node.numChildren()}get sourceString(){return this.source.contents}}class bn{constructor(e,n){const r=this;if(this.grammar=e,this.checkedActionDicts=!1,this.Wrapper=class extends(n?n.Wrapper:Kx){constructor(s,o,c){super(s,o,c),r.checkActionDictsIfHaventAlready(),this._semantics=r}toString(){return"[semantics wrapper for "+r.grammar.name+"]"}},this.super=n,n){if(!(e.equals(this.super.grammar)||e._inheritsFrom(this.super.grammar)))throw new Error("Cannot extend a semantics for grammar '"+this.super.grammar.name+"' for use with grammar '"+e.name+"' (not a sub-grammar)");this.operations=Object.create(this.super.operations),this.attributes=Object.create(this.super.attributes),this.attributeKeys=Object.create(null);for(const s in this.attributes)Object.defineProperty(this.attributeKeys,s,{value:Hx(s)})}else this.operations=Object.create(null),this.attributes=Object.create(null),this.attributeKeys=Object.create(null)}toString(){return"[semantics for "+this.grammar.name+"]"}checkActionDictsIfHaventAlready(){this.checkedActionDicts||(this.checkActionDicts(),this.checkedActionDicts=!0)}checkActionDicts(){let e;for(e in this.operations)this.operations[e].checkActionDict(this.grammar);for(e in this.attributes)this.attributes[e].checkActionDict(this.grammar)}toRecipe(e){function n(s){return s.super!==bn.BuiltInSemantics._getSemantics()}let r=`(function(g) {
|
|
67
|
-
`;if(n(this)){r+=" var semantics = "+this.super.toRecipe(!0)+"(g";const s=this.super.grammar;let o=this.grammar;for(;o!==s;)r+=".superGrammar",o=o.superGrammar;r+=`);
|
|
68
|
-
`,r+=" return g.extendSemantics(semantics)"}else r+=" return g.createSemantics()";return["Operation","Attribute"].forEach(s=>{const o=this[s.toLowerCase()+"s"];Object.keys(o).forEach(c=>{const{actionDict:d,formals:f,builtInDefault:p}=o[c];let g=c;f.length>0&&(g+="("+f.join(", ")+")");let b;n(this)&&this.super[s.toLowerCase()+"s"][c]?b="extend"+s:b="add"+s,r+=`
|
|
69
|
-
.`+b+"("+JSON.stringify(g)+", {";const v=[];Object.keys(d).forEach(x=>{if(d[x]!==p){let _=d[x].toString().trim();_=_.replace(/^.*\(/,"function("),v.push(`
|
|
70
|
-
`+JSON.stringify(x)+": "+_)}}),r+=v.join(",")+`
|
|
71
|
-
})`})}),r+=`;
|
|
72
|
-
})`,e||(r=`(function() {
|
|
73
|
-
var grammar = this.fromRecipe(`+this.grammar.toRecipe()+`);
|
|
74
|
-
var semantics = `+r+`(grammar);
|
|
75
|
-
return semantics;
|
|
76
|
-
});
|
|
77
|
-
`),r}addOperationOrAttribute(e,n,r){const s=e+"s",o=Yx(n,e),{name:c}=o,{formals:d}=o;this.assertNewName(c,e);const f=AO(e,c,b),p={_default:f};Object.keys(r).forEach(v=>{p[v]=r[v]});const g=e==="operation"?new _l(c,d,p,f):new hm(c,p,f);g.checkActionDict(this.grammar),this[s][c]=g;function b(...v){const x=this._semantics[s][c];if(arguments.length!==x.formals.length)throw new Error("Invalid number of arguments passed to "+c+" "+e+" (expected "+x.formals.length+", got "+arguments.length+")");const _=Object.create(null);for(const[C,T]of Object.entries(v)){const U=x.formals[C];_[U]=T}const k=this.args;this.args=_;const R=x.execute(this._semantics,this);return this.args=k,R}e==="operation"?(this.Wrapper.prototype[c]=b,this.Wrapper.prototype[c].toString=function(){return"["+c+" operation]"}):(Object.defineProperty(this.Wrapper.prototype,c,{get:b,configurable:!0}),Object.defineProperty(this.attributeKeys,c,{value:Hx(c)}))}extendOperationOrAttribute(e,n,r){const s=e+"s";if(Yx(n,"attribute"),!(this.super&&n in this.super[s]))throw new Error("Cannot extend "+e+" '"+n+"': did not inherit an "+e+" with that name");if(fm(this[s],n))throw new Error("Cannot extend "+e+" '"+n+"' again");const o=this[s][n].formals,c=this[s][n].actionDict,d=Object.create(c);Object.keys(r).forEach(f=>{d[f]=r[f]}),this[s][n]=e==="operation"?new _l(n,o,d):new hm(n,d),this[s][n].checkActionDict(this.grammar)}assertNewName(e,n){if(fm(Kx.prototype,e))throw new Error("Cannot add "+n+" '"+e+"': that's a reserved name");if(e in this.operations)throw new Error("Cannot add "+n+" '"+e+"': an operation with that name already exists");if(e in this.attributes)throw new Error("Cannot add "+n+" '"+e+"': an attribute with that name already exists")}wrap(e,n,r){const s=r||n;return e instanceof this.Wrapper?e:new this.Wrapper(e,n,s)}}function Yx(t,e){if(!bn.prototypeGrammar)return Js(t.indexOf("(")===-1),{name:t,formals:[]};const n=bn.prototypeGrammar.match(t,e==="operation"?"OperationSignature":"AttributeSignature");if(n.failed())throw new Error(n.message);return bn.prototypeGrammarSemantics(n).parse()}function AO(t,e,n){return function(...r){const o=(this._semantics.operations[e]||this._semantics.attributes[e]).formals.map(c=>this.args[c]);if(!this.isIteration()&&r.length===1)return n.apply(r[0],o);throw sO(this.ctorName,e,t,fl)}}bn.createSemantics=function(t,e){const n=new bn(t,e!==void 0?e:bn.BuiltInSemantics._getSemantics()),r=function(o){if(!(o instanceof c1))throw new TypeError("Semantics expected a MatchResult, but got "+Ny(o));if(o.failed())throw new TypeError("cannot apply Semantics to "+o.toString());const c=o._cst;if(c.grammar!==t)throw new Error("Cannot use a MatchResult from grammar '"+c.grammar.name+"' with a semantics for '"+t.name+"'");const d=new Ad(o.input);return n.wrap(c,d.interval(o._cstOffset,o.input.length))};return r.addOperation=function(s,o){return n.addOperationOrAttribute("operation",s,o),r},r.extendOperation=function(s,o){return n.extendOperationOrAttribute("operation",s,o),r},r.addAttribute=function(s,o){return n.addOperationOrAttribute("attribute",s,o),r},r.extendAttribute=function(s,o){return n.extendOperationOrAttribute("attribute",s,o),r},r._getActionDict=function(s){const o=n.operations[s]||n.attributes[s];if(!o)throw new Error('"'+s+'" is not a valid operation or attribute name in this semantics for "'+t.name+'"');return o.actionDict},r._remove=function(s){let o;return s in n.operations?(o=n.operations[s],delete n.operations[s]):s in n.attributes&&(o=n.attributes[s],delete n.attributes[s]),delete n.Wrapper.prototype[s],o},r.getOperationNames=function(){return Object.keys(n.operations)},r.getAttributeNames=function(){return Object.keys(n.attributes)},r.getGrammar=function(){return n.grammar},r.toRecipe=function(s){return n.toRecipe(s)},r.toString=n.toString.bind(n),r._getSemantics=function(){return n},r};class _l{constructor(e,n,r,s){this.name=e,this.formals=n,this.actionDict=r,this.builtInDefault=s}checkActionDict(e){e._checkTopDownActionDict(this.typeName,this.name,this.actionDict)}execute(e,n){try{const{ctorName:r}=n._node;let s=this.actionDict[r];return s?(fl.push([this,r]),s.apply(n,n._children())):n.isNonterminal()&&(s=this.actionDict._nonterminal,s)?(fl.push([this,"_nonterminal",r]),s.apply(n,n._children())):(fl.push([this,"default action",r]),this.actionDict._default.apply(n,n._children()))}finally{fl.pop()}}}_l.prototype.typeName="operation";class hm extends _l{constructor(e,n,r){super(e,[],n,r)}execute(e,n){const r=n._node,s=e.attributeKeys[this.name];return fm(r,s)||(r[s]=_l.prototype.execute.call(this,e,n)),r[s]}}hm.prototype.typeName="attribute";const Zx=["_iter","_terminal","_nonterminal","_default"];function Wx(t){return Object.keys(t.rules).sort().map(e=>t.rules[e])}const jO=t=>t.replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029");let h1,p1;class rn{constructor(e,n,r,s){if(this.name=e,this.superGrammar=n,this.rules=r,s){if(!(s in r))throw new Error("Invalid start rule: '"+s+"' is not a rule in grammar '"+e+"'");this.defaultStartRule=s}this._matchStateInitializer=void 0,this.supportsIncrementalParsing=!0}matcher(){return new EO(this)}isBuiltIn(){return this===rn.ProtoBuiltInRules||this===rn.BuiltInRules}equals(e){if(this===e)return!0;if(e==null||this.name!==e.name||this.defaultStartRule!==e.defaultStartRule||!(this.superGrammar===e.superGrammar||this.superGrammar.equals(e.superGrammar)))return!1;const n=Wx(this),r=Wx(e);return n.length===r.length&&n.every((s,o)=>s.description===r[o].description&&s.formals.join(",")===r[o].formals.join(",")&&s.body.toString()===r[o].body.toString())}match(e,n){const r=this.matcher();return r.replaceInputRange(0,0,e),r.match(n)}trace(e,n){const r=this.matcher();return r.replaceInputRange(0,0,e),r.trace(n)}createSemantics(){return bn.createSemantics(this)}extendSemantics(e){return bn.createSemantics(this,e._getSemantics())}_checkTopDownActionDict(e,n,r){const s=[];for(const o in r){const c=r[o];if(!Zx.includes(o)&&!(o in this.rules)){s.push(`'${o}' is not a valid semantic action for '${this.name}'`);continue}if(typeof c!="function"){s.push(`'${o}' must be a function in an action dictionary for '${this.name}'`);continue}const f=c.length,p=this._topDownActionArity(o);if(f!==p){let g;o==="_iter"||o==="_nonterminal"?g=`it should use a rest parameter, e.g. \`${o}(...children) {}\`. NOTE: this is new in Ohm v16 — see https://ohmjs.org/d/ati for details.`:g=`expected ${p}, got ${f}`,s.push(`Semantic action '${o}' has the wrong arity: ${g}`)}}if(s.length>0){const o=s.map(d=>"- "+d),c=new Error([`Found errors in the action dictionary of the '${n}' ${e}:`,...o].join(`
|
|
78
|
-
`));throw c.problems=s,c}}_topDownActionArity(e){return Zx.includes(e)?0:this.rules[e].body.getArity()}_inheritsFrom(e){let n=this.superGrammar;for(;n;){if(n.equals(e,!0))return!0;n=n.superGrammar}return!1}toRecipe(e=void 0){const n={};this.source&&(n.source=this.source.contents);let r=null;this.defaultStartRule&&(r=this.defaultStartRule);const s={};Object.keys(this.rules).forEach(d=>{const f=this.rules[d],{body:p}=f,g=!this.superGrammar||!this.superGrammar.rules[d];let b;g?b="define":b=p instanceof _d?"extend":"override";const v={};if(f.source&&this.source){const k=f.source.relativeTo(this.source);v.sourceInterval=[k.startIdx,k.endIdx]}const x=g?f.description:null,_=p.outputRecipe(f.formals,this.source);s[d]=[b,v,x,f.formals,_]});let o="null";e?o=e:this.superGrammar&&!this.superGrammar.isBuiltIn()&&(o=this.superGrammar.toRecipe());const c=[...["grammar",n,this.name].map(JSON.stringify),o,...[r,s].map(JSON.stringify)];return jO(`[${c.join(",")}]`)}toOperationActionDictionaryTemplate(){return this._toOperationOrAttributeActionDictionaryTemplate()}toAttributeActionDictionaryTemplate(){return this._toOperationOrAttributeActionDictionaryTemplate()}_toOperationOrAttributeActionDictionaryTemplate(){const e=new Fi;e.append("{");let n=!0;for(const r in this.rules){const{body:s}=this.rules[r];n?n=!1:e.append(","),e.append(`
|
|
79
|
-
`),e.append(" "),this.addSemanticActionTemplate(r,s,e)}return e.append(`
|
|
80
|
-
}`),e.contents()}addSemanticActionTemplate(e,n,r){r.append(e),r.append(": function(");const s=this._topDownActionArity(e);r.append(Sd("_",s).join(", ")),r.append(`) {
|
|
81
|
-
`),r.append(" }")}parseApplication(e){let n;if(e.indexOf("<")===-1)n=new He(e);else{const s=h1.match(e,"Base_application");n=p1(s,{})}if(!(n.ruleName in this.rules))throw s1(n.ruleName,this.name);const{formals:r}=this.rules[n.ruleName];if(r.length!==n.args.length){const{source:s}=this.rules[n.ruleName];throw i1(n.ruleName,r.length,n.args.length,s)}return n}_setUpMatchState(e){this._matchStateInitializer&&this._matchStateInitializer(e)}}rn.ProtoBuiltInRules=new rn("ProtoBuiltInRules",void 0,{any:{body:Yt,formals:[],description:"any character",primitive:!0},end:{body:Zt,formals:[],description:"end of input",primitive:!0},caseInsensitive:{body:new Iy(new Jt(0)),formals:["str"],primitive:!0},lower:{body:new zt("Ll"),formals:[],description:"a lowercase letter",primitive:!0},upper:{body:new zt("Lu"),formals:[],description:"an uppercase letter",primitive:!0},unicodeLtmo:{body:new zt("Ltmo"),formals:[],description:"a Unicode character in Lt, Lm, or Lo",primitive:!0},spaces:{body:new Pi(new He("space")),formals:[]},space:{body:new Wt("\0"," "),formals:[],description:"a space"}});rn.initApplicationParser=function(t,e){h1=t,p1=e};class Jx{constructor(e){this.name=e}sourceInterval(e,n){return this.source.subInterval(e,n-e)}ensureSuperGrammar(){return this.superGrammar||this.withSuperGrammar(this.name==="BuiltInRules"?rn.ProtoBuiltInRules:rn.BuiltInRules),this.superGrammar}ensureSuperGrammarRuleForOverriding(e,n){const r=this.ensureSuperGrammar().rules[e];if(!r)throw KN(e,this.superGrammar.name,n);return r}installOverriddenOrExtendedRule(e,n,r,s){const o=om(n);if(o.length>0)throw qx(e,o,s);const c=this.ensureSuperGrammar().rules[e],d=c.formals,f=d?d.length:0;if(n.length!==f)throw i1(e,f,n.length,s);return this.install(e,n,r,c.description,s)}install(e,n,r,s,o,c=!1){return this.rules[e]={body:r.introduceParams(n),formals:n,description:s,source:o,primitive:c},this}withSuperGrammar(e){if(this.superGrammar)throw new Error("the super grammar of a GrammarDecl cannot be set more than once");return this.superGrammar=e,this.rules=Object.create(e.rules),e.isBuiltIn()||(this.defaultStartRule=e.defaultStartRule),this}withDefaultStartRule(e){return this.defaultStartRule=e,this}withSource(e){return this.source=new Ad(e).interval(0,e.length),this}build(){const e=new rn(this.name,this.ensureSuperGrammar(),this.rules,this.defaultStartRule);e._matchStateInitializer=e.superGrammar._matchStateInitializer,e.supportsIncrementalParsing=e.superGrammar.supportsIncrementalParsing;const n=[];let r=!1;return Object.keys(e.rules).forEach(s=>{const{body:o}=e.rules[s];try{o.assertChoicesHaveUniformArity(s)}catch(c){n.push(c)}try{o.assertAllApplicationsAreValid(s,e)}catch(c){n.push(c),r=!0}}),r||Object.keys(e.rules).forEach(s=>{const{body:o}=e.rules[s];try{o.assertIteratedExprsAreNotNullable(e,[])}catch(c){n.push(c)}}),n.length>0&&iO(n),this.source&&(e.source=this.source),e}define(e,n,r,s,o,c){if(this.ensureSuperGrammar(),this.superGrammar.rules[e])throw Px(e,this.name,this.superGrammar.name,o);if(this.rules[e])throw Px(e,this.name,this.name,o);const d=om(n);if(d.length>0)throw qx(e,d,o);return this.install(e,n,r,s,o,c)}override(e,n,r,s,o){return this.ensureSuperGrammarRuleForOverriding(e,o),this.installOverriddenOrExtendedRule(e,n,r,o),this}extend(e,n,r,s,o){if(!this.ensureSuperGrammar().rules[e])throw YN(e,this.superGrammar.name,o);const d=new _d(this.superGrammar,e,r);return d.source=r.source,this.installOverriddenOrExtendedRule(e,n,d,o),this}}class Uu{constructor(e){this.currentDecl=null,this.currentRuleName=null,this.options=e||{}}newGrammar(e){return new Jx(e)}grammar(e,n,r,s,o){const c=new Jx(n);return r&&c.withSuperGrammar(r instanceof rn?r:this.fromRecipe(r)),s&&c.withDefaultStartRule(s),e&&e.source&&c.withSource(e.source),this.currentDecl=c,Object.keys(o).forEach(d=>{this.currentRuleName=d;const f=o[d],p=f[0],g=f[1],b=f[2],v=f[3],x=this.fromRecipe(f[4]);let _;c.source&&g&&g.sourceInterval&&(_=c.source.subInterval(g.sourceInterval[0],g.sourceInterval[1]-g.sourceInterval[0])),c[p](d,v,x,b,_)}),this.currentRuleName=this.currentDecl=null,c.build()}terminal(e){return new Vt(e)}range(e,n){return new Wt(e,n)}param(e){return new Jt(e)}alt(...e){let n=[];for(let r of e)r instanceof xe||(r=this.fromRecipe(r)),r instanceof Ot?n=n.concat(r.terms):n.push(r);return n.length===1?n[0]:new Ot(n)}seq(...e){let n=[];for(let r of e)r instanceof xe||(r=this.fromRecipe(r)),r instanceof It?n=n.concat(r.factors):n.push(r);return n.length===1?n[0]:new It(n)}star(e){return e instanceof xe||(e=this.fromRecipe(e)),new Pi(e)}plus(e){return e instanceof xe||(e=this.fromRecipe(e)),new to(e)}opt(e){return e instanceof xe||(e=this.fromRecipe(e)),new os(e)}not(e){return e instanceof xe||(e=this.fromRecipe(e)),new qt(e)}lookahead(e){return e instanceof xe||(e=this.fromRecipe(e)),this.options.eliminateLookaheads?new qt(new qt(e)):new ln(e)}lex(e){return e instanceof xe||(e=this.fromRecipe(e)),new vn(e)}app(e,n){return n&&n.length>0&&(n=n.map(function(r){return r instanceof xe?r:this.fromRecipe(r)},this)),new He(e,n)}splice(e,n){return new Ed(this.currentDecl.superGrammar,this.currentRuleName,e.map(r=>this.fromRecipe(r)),n.map(r=>this.fromRecipe(r)))}fromRecipe(e){const n=e[0]==="grammar"?e.slice(1):e.slice(2),r=this[e[0]](...n),s=e[1];return s&&s.sourceInterval&&this.currentDecl&&r.withSource(this.currentDecl.sourceInterval(...s.sourceInterval)),r}}function My(t){return typeof t=="function"?t.call(new Uu):(typeof t=="string"&&(t=JSON.parse(t)),new Uu().fromRecipe(t))}const Ly=My(["grammar",{source:`BuiltInRules {
|
|
82
|
-
|
|
83
|
-
alnum (an alpha-numeric character)
|
|
84
|
-
= letter
|
|
85
|
-
| digit
|
|
86
|
-
|
|
87
|
-
letter (a letter)
|
|
88
|
-
= lower
|
|
89
|
-
| upper
|
|
90
|
-
| unicodeLtmo
|
|
91
|
-
|
|
92
|
-
digit (a digit)
|
|
93
|
-
= "0".."9"
|
|
94
|
-
|
|
95
|
-
hexDigit (a hexadecimal digit)
|
|
96
|
-
= digit
|
|
97
|
-
| "a".."f"
|
|
98
|
-
| "A".."F"
|
|
99
|
-
|
|
100
|
-
ListOf<elem, sep>
|
|
101
|
-
= NonemptyListOf<elem, sep>
|
|
102
|
-
| EmptyListOf<elem, sep>
|
|
103
|
-
|
|
104
|
-
NonemptyListOf<elem, sep>
|
|
105
|
-
= elem (sep elem)*
|
|
106
|
-
|
|
107
|
-
EmptyListOf<elem, sep>
|
|
108
|
-
= /* nothing */
|
|
109
|
-
|
|
110
|
-
listOf<elem, sep>
|
|
111
|
-
= nonemptyListOf<elem, sep>
|
|
112
|
-
| emptyListOf<elem, sep>
|
|
113
|
-
|
|
114
|
-
nonemptyListOf<elem, sep>
|
|
115
|
-
= elem (sep elem)*
|
|
116
|
-
|
|
117
|
-
emptyListOf<elem, sep>
|
|
118
|
-
= /* nothing */
|
|
119
|
-
|
|
120
|
-
// Allows a syntactic rule application within a lexical context.
|
|
121
|
-
applySyntactic<app> = app
|
|
122
|
-
}`},"BuiltInRules",null,null,{alnum:["define",{sourceInterval:[18,78]},"an alpha-numeric character",[],["alt",{sourceInterval:[60,78]},["app",{sourceInterval:[60,66]},"letter",[]],["app",{sourceInterval:[73,78]},"digit",[]]]],letter:["define",{sourceInterval:[82,142]},"a letter",[],["alt",{sourceInterval:[107,142]},["app",{sourceInterval:[107,112]},"lower",[]],["app",{sourceInterval:[119,124]},"upper",[]],["app",{sourceInterval:[131,142]},"unicodeLtmo",[]]]],digit:["define",{sourceInterval:[146,177]},"a digit",[],["range",{sourceInterval:[169,177]},"0","9"]],hexDigit:["define",{sourceInterval:[181,254]},"a hexadecimal digit",[],["alt",{sourceInterval:[219,254]},["app",{sourceInterval:[219,224]},"digit",[]],["range",{sourceInterval:[231,239]},"a","f"],["range",{sourceInterval:[246,254]},"A","F"]]],ListOf:["define",{sourceInterval:[258,336]},null,["elem","sep"],["alt",{sourceInterval:[282,336]},["app",{sourceInterval:[282,307]},"NonemptyListOf",[["param",{sourceInterval:[297,301]},0],["param",{sourceInterval:[303,306]},1]]],["app",{sourceInterval:[314,336]},"EmptyListOf",[["param",{sourceInterval:[326,330]},0],["param",{sourceInterval:[332,335]},1]]]]],NonemptyListOf:["define",{sourceInterval:[340,388]},null,["elem","sep"],["seq",{sourceInterval:[372,388]},["param",{sourceInterval:[372,376]},0],["star",{sourceInterval:[377,388]},["seq",{sourceInterval:[378,386]},["param",{sourceInterval:[378,381]},1],["param",{sourceInterval:[382,386]},0]]]]],EmptyListOf:["define",{sourceInterval:[392,434]},null,["elem","sep"],["seq",{sourceInterval:[438,438]}]],listOf:["define",{sourceInterval:[438,516]},null,["elem","sep"],["alt",{sourceInterval:[462,516]},["app",{sourceInterval:[462,487]},"nonemptyListOf",[["param",{sourceInterval:[477,481]},0],["param",{sourceInterval:[483,486]},1]]],["app",{sourceInterval:[494,516]},"emptyListOf",[["param",{sourceInterval:[506,510]},0],["param",{sourceInterval:[512,515]},1]]]]],nonemptyListOf:["define",{sourceInterval:[520,568]},null,["elem","sep"],["seq",{sourceInterval:[552,568]},["param",{sourceInterval:[552,556]},0],["star",{sourceInterval:[557,568]},["seq",{sourceInterval:[558,566]},["param",{sourceInterval:[558,561]},1],["param",{sourceInterval:[562,566]},0]]]]],emptyListOf:["define",{sourceInterval:[572,682]},null,["elem","sep"],["seq",{sourceInterval:[685,685]}]],applySyntactic:["define",{sourceInterval:[685,710]},null,["app"],["param",{sourceInterval:[707,710]},0]]}]);rn.BuiltInRules=Ly;lO(rn.BuiltInRules);const Uy=My(["grammar",{source:`Ohm {
|
|
123
|
-
|
|
124
|
-
Grammars
|
|
125
|
-
= Grammar*
|
|
126
|
-
|
|
127
|
-
Grammar
|
|
128
|
-
= ident SuperGrammar? "{" Rule* "}"
|
|
129
|
-
|
|
130
|
-
SuperGrammar
|
|
131
|
-
= "<:" ident
|
|
132
|
-
|
|
133
|
-
Rule
|
|
134
|
-
= ident Formals? ruleDescr? "=" RuleBody -- define
|
|
135
|
-
| ident Formals? ":=" OverrideRuleBody -- override
|
|
136
|
-
| ident Formals? "+=" RuleBody -- extend
|
|
137
|
-
|
|
138
|
-
RuleBody
|
|
139
|
-
= "|"? NonemptyListOf<TopLevelTerm, "|">
|
|
140
|
-
|
|
141
|
-
TopLevelTerm
|
|
142
|
-
= Seq caseName -- inline
|
|
143
|
-
| Seq
|
|
144
|
-
|
|
145
|
-
OverrideRuleBody
|
|
146
|
-
= "|"? NonemptyListOf<OverrideTopLevelTerm, "|">
|
|
147
|
-
|
|
148
|
-
OverrideTopLevelTerm
|
|
149
|
-
= "..." -- superSplice
|
|
150
|
-
| TopLevelTerm
|
|
151
|
-
|
|
152
|
-
Formals
|
|
153
|
-
= "<" ListOf<ident, ","> ">"
|
|
154
|
-
|
|
155
|
-
Params
|
|
156
|
-
= "<" ListOf<Seq, ","> ">"
|
|
157
|
-
|
|
158
|
-
Alt
|
|
159
|
-
= NonemptyListOf<Seq, "|">
|
|
160
|
-
|
|
161
|
-
Seq
|
|
162
|
-
= Iter*
|
|
163
|
-
|
|
164
|
-
Iter
|
|
165
|
-
= Pred "*" -- star
|
|
166
|
-
| Pred "+" -- plus
|
|
167
|
-
| Pred "?" -- opt
|
|
168
|
-
| Pred
|
|
169
|
-
|
|
170
|
-
Pred
|
|
171
|
-
= "~" Lex -- not
|
|
172
|
-
| "&" Lex -- lookahead
|
|
173
|
-
| Lex
|
|
174
|
-
|
|
175
|
-
Lex
|
|
176
|
-
= "#" Base -- lex
|
|
177
|
-
| Base
|
|
178
|
-
|
|
179
|
-
Base
|
|
180
|
-
= ident Params? ~(ruleDescr? "=" | ":=" | "+=") -- application
|
|
181
|
-
| oneCharTerminal ".." oneCharTerminal -- range
|
|
182
|
-
| terminal -- terminal
|
|
183
|
-
| "(" Alt ")" -- paren
|
|
184
|
-
|
|
185
|
-
ruleDescr (a rule description)
|
|
186
|
-
= "(" ruleDescrText ")"
|
|
187
|
-
|
|
188
|
-
ruleDescrText
|
|
189
|
-
= (~")" any)*
|
|
190
|
-
|
|
191
|
-
caseName
|
|
192
|
-
= "--" (~"\\n" space)* name (~"\\n" space)* ("\\n" | &"}")
|
|
193
|
-
|
|
194
|
-
name (a name)
|
|
195
|
-
= nameFirst nameRest*
|
|
196
|
-
|
|
197
|
-
nameFirst
|
|
198
|
-
= "_"
|
|
199
|
-
| letter
|
|
200
|
-
|
|
201
|
-
nameRest
|
|
202
|
-
= "_"
|
|
203
|
-
| alnum
|
|
204
|
-
|
|
205
|
-
ident (an identifier)
|
|
206
|
-
= name
|
|
207
|
-
|
|
208
|
-
terminal
|
|
209
|
-
= "\\"" terminalChar* "\\""
|
|
210
|
-
|
|
211
|
-
oneCharTerminal
|
|
212
|
-
= "\\"" terminalChar "\\""
|
|
213
|
-
|
|
214
|
-
terminalChar
|
|
215
|
-
= escapeChar
|
|
216
|
-
| ~"\\\\" ~"\\"" ~"\\n" "\\u{0}".."\\u{10FFFF}"
|
|
217
|
-
|
|
218
|
-
escapeChar (an escape sequence)
|
|
219
|
-
= "\\\\\\\\" -- backslash
|
|
220
|
-
| "\\\\\\"" -- doubleQuote
|
|
221
|
-
| "\\\\\\'" -- singleQuote
|
|
222
|
-
| "\\\\b" -- backspace
|
|
223
|
-
| "\\\\n" -- lineFeed
|
|
224
|
-
| "\\\\r" -- carriageReturn
|
|
225
|
-
| "\\\\t" -- tab
|
|
226
|
-
| "\\\\u{" hexDigit hexDigit? hexDigit?
|
|
227
|
-
hexDigit? hexDigit? hexDigit? "}" -- unicodeCodePoint
|
|
228
|
-
| "\\\\u" hexDigit hexDigit hexDigit hexDigit -- unicodeEscape
|
|
229
|
-
| "\\\\x" hexDigit hexDigit -- hexEscape
|
|
230
|
-
|
|
231
|
-
space
|
|
232
|
-
+= comment
|
|
233
|
-
|
|
234
|
-
comment
|
|
235
|
-
= "//" (~"\\n" any)* &("\\n" | end) -- singleLine
|
|
236
|
-
| "/*" (~"*/" any)* "*/" -- multiLine
|
|
237
|
-
|
|
238
|
-
tokens = token*
|
|
239
|
-
|
|
240
|
-
token = caseName | comment | ident | operator | punctuation | terminal | any
|
|
241
|
-
|
|
242
|
-
operator = "<:" | "=" | ":=" | "+=" | "*" | "+" | "?" | "~" | "&"
|
|
243
|
-
|
|
244
|
-
punctuation = "<" | ">" | "," | "--"
|
|
245
|
-
}`},"Ohm",null,"Grammars",{Grammars:["define",{sourceInterval:[9,32]},null,[],["star",{sourceInterval:[24,32]},["app",{sourceInterval:[24,31]},"Grammar",[]]]],Grammar:["define",{sourceInterval:[36,83]},null,[],["seq",{sourceInterval:[50,83]},["app",{sourceInterval:[50,55]},"ident",[]],["opt",{sourceInterval:[56,69]},["app",{sourceInterval:[56,68]},"SuperGrammar",[]]],["terminal",{sourceInterval:[70,73]},"{"],["star",{sourceInterval:[74,79]},["app",{sourceInterval:[74,78]},"Rule",[]]],["terminal",{sourceInterval:[80,83]},"}"]]],SuperGrammar:["define",{sourceInterval:[87,116]},null,[],["seq",{sourceInterval:[106,116]},["terminal",{sourceInterval:[106,110]},"<:"],["app",{sourceInterval:[111,116]},"ident",[]]]],Rule_define:["define",{sourceInterval:[131,181]},null,[],["seq",{sourceInterval:[131,170]},["app",{sourceInterval:[131,136]},"ident",[]],["opt",{sourceInterval:[137,145]},["app",{sourceInterval:[137,144]},"Formals",[]]],["opt",{sourceInterval:[146,156]},["app",{sourceInterval:[146,155]},"ruleDescr",[]]],["terminal",{sourceInterval:[157,160]},"="],["app",{sourceInterval:[162,170]},"RuleBody",[]]]],Rule_override:["define",{sourceInterval:[188,248]},null,[],["seq",{sourceInterval:[188,235]},["app",{sourceInterval:[188,193]},"ident",[]],["opt",{sourceInterval:[194,202]},["app",{sourceInterval:[194,201]},"Formals",[]]],["terminal",{sourceInterval:[214,218]},":="],["app",{sourceInterval:[219,235]},"OverrideRuleBody",[]]]],Rule_extend:["define",{sourceInterval:[255,305]},null,[],["seq",{sourceInterval:[255,294]},["app",{sourceInterval:[255,260]},"ident",[]],["opt",{sourceInterval:[261,269]},["app",{sourceInterval:[261,268]},"Formals",[]]],["terminal",{sourceInterval:[281,285]},"+="],["app",{sourceInterval:[286,294]},"RuleBody",[]]]],Rule:["define",{sourceInterval:[120,305]},null,[],["alt",{sourceInterval:[131,305]},["app",{sourceInterval:[131,170]},"Rule_define",[]],["app",{sourceInterval:[188,235]},"Rule_override",[]],["app",{sourceInterval:[255,294]},"Rule_extend",[]]]],RuleBody:["define",{sourceInterval:[309,362]},null,[],["seq",{sourceInterval:[324,362]},["opt",{sourceInterval:[324,328]},["terminal",{sourceInterval:[324,327]},"|"]],["app",{sourceInterval:[329,362]},"NonemptyListOf",[["app",{sourceInterval:[344,356]},"TopLevelTerm",[]],["terminal",{sourceInterval:[358,361]},"|"]]]]],TopLevelTerm_inline:["define",{sourceInterval:[385,408]},null,[],["seq",{sourceInterval:[385,397]},["app",{sourceInterval:[385,388]},"Seq",[]],["app",{sourceInterval:[389,397]},"caseName",[]]]],TopLevelTerm:["define",{sourceInterval:[366,418]},null,[],["alt",{sourceInterval:[385,418]},["app",{sourceInterval:[385,397]},"TopLevelTerm_inline",[]],["app",{sourceInterval:[415,418]},"Seq",[]]]],OverrideRuleBody:["define",{sourceInterval:[422,491]},null,[],["seq",{sourceInterval:[445,491]},["opt",{sourceInterval:[445,449]},["terminal",{sourceInterval:[445,448]},"|"]],["app",{sourceInterval:[450,491]},"NonemptyListOf",[["app",{sourceInterval:[465,485]},"OverrideTopLevelTerm",[]],["terminal",{sourceInterval:[487,490]},"|"]]]]],OverrideTopLevelTerm_superSplice:["define",{sourceInterval:[522,543]},null,[],["terminal",{sourceInterval:[522,527]},"..."]],OverrideTopLevelTerm:["define",{sourceInterval:[495,562]},null,[],["alt",{sourceInterval:[522,562]},["app",{sourceInterval:[522,527]},"OverrideTopLevelTerm_superSplice",[]],["app",{sourceInterval:[550,562]},"TopLevelTerm",[]]]],Formals:["define",{sourceInterval:[566,606]},null,[],["seq",{sourceInterval:[580,606]},["terminal",{sourceInterval:[580,583]},"<"],["app",{sourceInterval:[584,602]},"ListOf",[["app",{sourceInterval:[591,596]},"ident",[]],["terminal",{sourceInterval:[598,601]},","]]],["terminal",{sourceInterval:[603,606]},">"]]],Params:["define",{sourceInterval:[610,647]},null,[],["seq",{sourceInterval:[623,647]},["terminal",{sourceInterval:[623,626]},"<"],["app",{sourceInterval:[627,643]},"ListOf",[["app",{sourceInterval:[634,637]},"Seq",[]],["terminal",{sourceInterval:[639,642]},","]]],["terminal",{sourceInterval:[644,647]},">"]]],Alt:["define",{sourceInterval:[651,685]},null,[],["app",{sourceInterval:[661,685]},"NonemptyListOf",[["app",{sourceInterval:[676,679]},"Seq",[]],["terminal",{sourceInterval:[681,684]},"|"]]]],Seq:["define",{sourceInterval:[689,704]},null,[],["star",{sourceInterval:[699,704]},["app",{sourceInterval:[699,703]},"Iter",[]]]],Iter_star:["define",{sourceInterval:[719,736]},null,[],["seq",{sourceInterval:[719,727]},["app",{sourceInterval:[719,723]},"Pred",[]],["terminal",{sourceInterval:[724,727]},"*"]]],Iter_plus:["define",{sourceInterval:[743,760]},null,[],["seq",{sourceInterval:[743,751]},["app",{sourceInterval:[743,747]},"Pred",[]],["terminal",{sourceInterval:[748,751]},"+"]]],Iter_opt:["define",{sourceInterval:[767,783]},null,[],["seq",{sourceInterval:[767,775]},["app",{sourceInterval:[767,771]},"Pred",[]],["terminal",{sourceInterval:[772,775]},"?"]]],Iter:["define",{sourceInterval:[708,794]},null,[],["alt",{sourceInterval:[719,794]},["app",{sourceInterval:[719,727]},"Iter_star",[]],["app",{sourceInterval:[743,751]},"Iter_plus",[]],["app",{sourceInterval:[767,775]},"Iter_opt",[]],["app",{sourceInterval:[790,794]},"Pred",[]]]],Pred_not:["define",{sourceInterval:[809,824]},null,[],["seq",{sourceInterval:[809,816]},["terminal",{sourceInterval:[809,812]},"~"],["app",{sourceInterval:[813,816]},"Lex",[]]]],Pred_lookahead:["define",{sourceInterval:[831,852]},null,[],["seq",{sourceInterval:[831,838]},["terminal",{sourceInterval:[831,834]},"&"],["app",{sourceInterval:[835,838]},"Lex",[]]]],Pred:["define",{sourceInterval:[798,862]},null,[],["alt",{sourceInterval:[809,862]},["app",{sourceInterval:[809,816]},"Pred_not",[]],["app",{sourceInterval:[831,838]},"Pred_lookahead",[]],["app",{sourceInterval:[859,862]},"Lex",[]]]],Lex_lex:["define",{sourceInterval:[876,892]},null,[],["seq",{sourceInterval:[876,884]},["terminal",{sourceInterval:[876,879]},"#"],["app",{sourceInterval:[880,884]},"Base",[]]]],Lex:["define",{sourceInterval:[866,903]},null,[],["alt",{sourceInterval:[876,903]},["app",{sourceInterval:[876,884]},"Lex_lex",[]],["app",{sourceInterval:[899,903]},"Base",[]]]],Base_application:["define",{sourceInterval:[918,979]},null,[],["seq",{sourceInterval:[918,963]},["app",{sourceInterval:[918,923]},"ident",[]],["opt",{sourceInterval:[924,931]},["app",{sourceInterval:[924,930]},"Params",[]]],["not",{sourceInterval:[932,963]},["alt",{sourceInterval:[934,962]},["seq",{sourceInterval:[934,948]},["opt",{sourceInterval:[934,944]},["app",{sourceInterval:[934,943]},"ruleDescr",[]]],["terminal",{sourceInterval:[945,948]},"="]],["terminal",{sourceInterval:[951,955]},":="],["terminal",{sourceInterval:[958,962]},"+="]]]]],Base_range:["define",{sourceInterval:[986,1041]},null,[],["seq",{sourceInterval:[986,1022]},["app",{sourceInterval:[986,1001]},"oneCharTerminal",[]],["terminal",{sourceInterval:[1002,1006]},".."],["app",{sourceInterval:[1007,1022]},"oneCharTerminal",[]]]],Base_terminal:["define",{sourceInterval:[1048,1106]},null,[],["app",{sourceInterval:[1048,1056]},"terminal",[]]],Base_paren:["define",{sourceInterval:[1113,1168]},null,[],["seq",{sourceInterval:[1113,1124]},["terminal",{sourceInterval:[1113,1116]},"("],["app",{sourceInterval:[1117,1120]},"Alt",[]],["terminal",{sourceInterval:[1121,1124]},")"]]],Base:["define",{sourceInterval:[907,1168]},null,[],["alt",{sourceInterval:[918,1168]},["app",{sourceInterval:[918,963]},"Base_application",[]],["app",{sourceInterval:[986,1022]},"Base_range",[]],["app",{sourceInterval:[1048,1056]},"Base_terminal",[]],["app",{sourceInterval:[1113,1124]},"Base_paren",[]]]],ruleDescr:["define",{sourceInterval:[1172,1231]},"a rule description",[],["seq",{sourceInterval:[1210,1231]},["terminal",{sourceInterval:[1210,1213]},"("],["app",{sourceInterval:[1214,1227]},"ruleDescrText",[]],["terminal",{sourceInterval:[1228,1231]},")"]]],ruleDescrText:["define",{sourceInterval:[1235,1266]},null,[],["star",{sourceInterval:[1255,1266]},["seq",{sourceInterval:[1256,1264]},["not",{sourceInterval:[1256,1260]},["terminal",{sourceInterval:[1257,1260]},")"]],["app",{sourceInterval:[1261,1264]},"any",[]]]]],caseName:["define",{sourceInterval:[1270,1338]},null,[],["seq",{sourceInterval:[1285,1338]},["terminal",{sourceInterval:[1285,1289]},"--"],["star",{sourceInterval:[1290,1304]},["seq",{sourceInterval:[1291,1302]},["not",{sourceInterval:[1291,1296]},["terminal",{sourceInterval:[1292,1296]},`
|
|
246
|
-
`]],["app",{sourceInterval:[1297,1302]},"space",[]]]],["app",{sourceInterval:[1305,1309]},"name",[]],["star",{sourceInterval:[1310,1324]},["seq",{sourceInterval:[1311,1322]},["not",{sourceInterval:[1311,1316]},["terminal",{sourceInterval:[1312,1316]},`
|
|
247
|
-
`]],["app",{sourceInterval:[1317,1322]},"space",[]]]],["alt",{sourceInterval:[1326,1337]},["terminal",{sourceInterval:[1326,1330]},`
|
|
248
|
-
`],["lookahead",{sourceInterval:[1333,1337]},["terminal",{sourceInterval:[1334,1337]},"}"]]]]],name:["define",{sourceInterval:[1342,1382]},"a name",[],["seq",{sourceInterval:[1363,1382]},["app",{sourceInterval:[1363,1372]},"nameFirst",[]],["star",{sourceInterval:[1373,1382]},["app",{sourceInterval:[1373,1381]},"nameRest",[]]]]],nameFirst:["define",{sourceInterval:[1386,1418]},null,[],["alt",{sourceInterval:[1402,1418]},["terminal",{sourceInterval:[1402,1405]},"_"],["app",{sourceInterval:[1412,1418]},"letter",[]]]],nameRest:["define",{sourceInterval:[1422,1452]},null,[],["alt",{sourceInterval:[1437,1452]},["terminal",{sourceInterval:[1437,1440]},"_"],["app",{sourceInterval:[1447,1452]},"alnum",[]]]],ident:["define",{sourceInterval:[1456,1489]},"an identifier",[],["app",{sourceInterval:[1485,1489]},"name",[]]],terminal:["define",{sourceInterval:[1493,1531]},null,[],["seq",{sourceInterval:[1508,1531]},["terminal",{sourceInterval:[1508,1512]},'"'],["star",{sourceInterval:[1513,1526]},["app",{sourceInterval:[1513,1525]},"terminalChar",[]]],["terminal",{sourceInterval:[1527,1531]},'"']]],oneCharTerminal:["define",{sourceInterval:[1535,1579]},null,[],["seq",{sourceInterval:[1557,1579]},["terminal",{sourceInterval:[1557,1561]},'"'],["app",{sourceInterval:[1562,1574]},"terminalChar",[]],["terminal",{sourceInterval:[1575,1579]},'"']]],terminalChar:["define",{sourceInterval:[1583,1660]},null,[],["alt",{sourceInterval:[1602,1660]},["app",{sourceInterval:[1602,1612]},"escapeChar",[]],["seq",{sourceInterval:[1621,1660]},["not",{sourceInterval:[1621,1626]},["terminal",{sourceInterval:[1622,1626]},"\\"]],["not",{sourceInterval:[1627,1632]},["terminal",{sourceInterval:[1628,1632]},'"']],["not",{sourceInterval:[1633,1638]},["terminal",{sourceInterval:[1634,1638]},`
|
|
249
|
-
`]],["range",{sourceInterval:[1639,1660]},"\0",""]]]],escapeChar_backslash:["define",{sourceInterval:[1703,1758]},null,[],["terminal",{sourceInterval:[1703,1709]},"\\\\"]],escapeChar_doubleQuote:["define",{sourceInterval:[1765,1822]},null,[],["terminal",{sourceInterval:[1765,1771]},'\\"']],escapeChar_singleQuote:["define",{sourceInterval:[1829,1886]},null,[],["terminal",{sourceInterval:[1829,1835]},"\\'"]],escapeChar_backspace:["define",{sourceInterval:[1893,1948]},null,[],["terminal",{sourceInterval:[1893,1898]},"\\b"]],escapeChar_lineFeed:["define",{sourceInterval:[1955,2009]},null,[],["terminal",{sourceInterval:[1955,1960]},"\\n"]],escapeChar_carriageReturn:["define",{sourceInterval:[2016,2076]},null,[],["terminal",{sourceInterval:[2016,2021]},"\\r"]],escapeChar_tab:["define",{sourceInterval:[2083,2132]},null,[],["terminal",{sourceInterval:[2083,2088]},"\\t"]],escapeChar_unicodeCodePoint:["define",{sourceInterval:[2139,2243]},null,[],["seq",{sourceInterval:[2139,2221]},["terminal",{sourceInterval:[2139,2145]},"\\u{"],["app",{sourceInterval:[2146,2154]},"hexDigit",[]],["opt",{sourceInterval:[2155,2164]},["app",{sourceInterval:[2155,2163]},"hexDigit",[]]],["opt",{sourceInterval:[2165,2174]},["app",{sourceInterval:[2165,2173]},"hexDigit",[]]],["opt",{sourceInterval:[2188,2197]},["app",{sourceInterval:[2188,2196]},"hexDigit",[]]],["opt",{sourceInterval:[2198,2207]},["app",{sourceInterval:[2198,2206]},"hexDigit",[]]],["opt",{sourceInterval:[2208,2217]},["app",{sourceInterval:[2208,2216]},"hexDigit",[]]],["terminal",{sourceInterval:[2218,2221]},"}"]]],escapeChar_unicodeEscape:["define",{sourceInterval:[2250,2309]},null,[],["seq",{sourceInterval:[2250,2291]},["terminal",{sourceInterval:[2250,2255]},"\\u"],["app",{sourceInterval:[2256,2264]},"hexDigit",[]],["app",{sourceInterval:[2265,2273]},"hexDigit",[]],["app",{sourceInterval:[2274,2282]},"hexDigit",[]],["app",{sourceInterval:[2283,2291]},"hexDigit",[]]]],escapeChar_hexEscape:["define",{sourceInterval:[2316,2371]},null,[],["seq",{sourceInterval:[2316,2339]},["terminal",{sourceInterval:[2316,2321]},"\\x"],["app",{sourceInterval:[2322,2330]},"hexDigit",[]],["app",{sourceInterval:[2331,2339]},"hexDigit",[]]]],escapeChar:["define",{sourceInterval:[1664,2371]},"an escape sequence",[],["alt",{sourceInterval:[1703,2371]},["app",{sourceInterval:[1703,1709]},"escapeChar_backslash",[]],["app",{sourceInterval:[1765,1771]},"escapeChar_doubleQuote",[]],["app",{sourceInterval:[1829,1835]},"escapeChar_singleQuote",[]],["app",{sourceInterval:[1893,1898]},"escapeChar_backspace",[]],["app",{sourceInterval:[1955,1960]},"escapeChar_lineFeed",[]],["app",{sourceInterval:[2016,2021]},"escapeChar_carriageReturn",[]],["app",{sourceInterval:[2083,2088]},"escapeChar_tab",[]],["app",{sourceInterval:[2139,2221]},"escapeChar_unicodeCodePoint",[]],["app",{sourceInterval:[2250,2291]},"escapeChar_unicodeEscape",[]],["app",{sourceInterval:[2316,2339]},"escapeChar_hexEscape",[]]]],space:["extend",{sourceInterval:[2375,2394]},null,[],["app",{sourceInterval:[2387,2394]},"comment",[]]],comment_singleLine:["define",{sourceInterval:[2412,2458]},null,[],["seq",{sourceInterval:[2412,2443]},["terminal",{sourceInterval:[2412,2416]},"//"],["star",{sourceInterval:[2417,2429]},["seq",{sourceInterval:[2418,2427]},["not",{sourceInterval:[2418,2423]},["terminal",{sourceInterval:[2419,2423]},`
|
|
250
|
-
`]],["app",{sourceInterval:[2424,2427]},"any",[]]]],["lookahead",{sourceInterval:[2430,2443]},["alt",{sourceInterval:[2432,2442]},["terminal",{sourceInterval:[2432,2436]},`
|
|
251
|
-
`],["app",{sourceInterval:[2439,2442]},"end",[]]]]]],comment_multiLine:["define",{sourceInterval:[2465,2501]},null,[],["seq",{sourceInterval:[2465,2487]},["terminal",{sourceInterval:[2465,2469]},"/*"],["star",{sourceInterval:[2470,2482]},["seq",{sourceInterval:[2471,2480]},["not",{sourceInterval:[2471,2476]},["terminal",{sourceInterval:[2472,2476]},"*/"]],["app",{sourceInterval:[2477,2480]},"any",[]]]],["terminal",{sourceInterval:[2483,2487]},"*/"]]],comment:["define",{sourceInterval:[2398,2501]},null,[],["alt",{sourceInterval:[2412,2501]},["app",{sourceInterval:[2412,2443]},"comment_singleLine",[]],["app",{sourceInterval:[2465,2487]},"comment_multiLine",[]]]],tokens:["define",{sourceInterval:[2505,2520]},null,[],["star",{sourceInterval:[2514,2520]},["app",{sourceInterval:[2514,2519]},"token",[]]]],token:["define",{sourceInterval:[2524,2600]},null,[],["alt",{sourceInterval:[2532,2600]},["app",{sourceInterval:[2532,2540]},"caseName",[]],["app",{sourceInterval:[2543,2550]},"comment",[]],["app",{sourceInterval:[2553,2558]},"ident",[]],["app",{sourceInterval:[2561,2569]},"operator",[]],["app",{sourceInterval:[2572,2583]},"punctuation",[]],["app",{sourceInterval:[2586,2594]},"terminal",[]],["app",{sourceInterval:[2597,2600]},"any",[]]]],operator:["define",{sourceInterval:[2604,2669]},null,[],["alt",{sourceInterval:[2615,2669]},["terminal",{sourceInterval:[2615,2619]},"<:"],["terminal",{sourceInterval:[2622,2625]},"="],["terminal",{sourceInterval:[2628,2632]},":="],["terminal",{sourceInterval:[2635,2639]},"+="],["terminal",{sourceInterval:[2642,2645]},"*"],["terminal",{sourceInterval:[2648,2651]},"+"],["terminal",{sourceInterval:[2654,2657]},"?"],["terminal",{sourceInterval:[2660,2663]},"~"],["terminal",{sourceInterval:[2666,2669]},"&"]]],punctuation:["define",{sourceInterval:[2673,2709]},null,[],["alt",{sourceInterval:[2687,2709]},["terminal",{sourceInterval:[2687,2690]},"<"],["terminal",{sourceInterval:[2693,2696]},">"],["terminal",{sourceInterval:[2699,2702]},","],["terminal",{sourceInterval:[2705,2709]},"--"]]]}]),Ap=Object.create(xe.prototype);function Qx(t,e){for(const n in t)if(n===e)return!0;return!1}function m1(t,e,n,r){const s=new Uu(r);let o,c,d,f=!1;return(n||Uy).createSemantics().addOperation("visit",{Grammars(b){return b.children.map(v=>v.visit())},Grammar(b,v,x,_,k){const R=b.visit();o=s.newGrammar(R),v.child(0)&&v.child(0).visit(),_.children.map(T=>T.visit());const C=o.build();if(C.source=this.source.trimmed(),Qx(e,R))throw HN(C);return e[R]=C,C},SuperGrammar(b,v){const x=v.visit();if(x==="null")o.withSuperGrammar(null);else{if(!e||!Qx(e,x))throw VN(x,e,v.source);o.withSuperGrammar(e[x])}},Rule_define(b,v,x,_,k){c=b.visit(),d=v.children.map(U=>U.visit())[0]||[],!o.defaultStartRule&&o.ensureSuperGrammar()!==rn.ProtoBuiltInRules&&o.withDefaultStartRule(c);const R=k.visit(),C=x.children.map(U=>U.visit())[0],T=this.source.trimmed();return o.define(c,d,R,C,T)},Rule_override(b,v,x,_){c=b.visit(),d=v.children.map(C=>C.visit())[0]||[];const k=this.source.trimmed();o.ensureSuperGrammarRuleForOverriding(c,k),f=!0;const R=_.visit();return f=!1,o.override(c,d,R,null,k)},Rule_extend(b,v,x,_){c=b.visit(),d=v.children.map(C=>C.visit())[0]||[];const k=_.visit(),R=this.source.trimmed();return o.extend(c,d,k,null,R)},RuleBody(b,v){return s.alt(...v.visit()).withSource(this.source)},OverrideRuleBody(b,v){const x=v.visit(),_=x.indexOf(Ap);if(_>=0){const k=x.slice(0,_),R=x.slice(_+1);return R.forEach(C=>{if(C===Ap)throw tO(C)}),new Ed(o.superGrammar,c,k,R).withSource(this.source)}else return s.alt(...x).withSource(this.source)},Formals(b,v,x){return v.visit()},Params(b,v,x){return v.visit()},Alt(b){return s.alt(...b.visit()).withSource(this.source)},TopLevelTerm_inline(b,v){const x=c+"_"+v.visit(),_=b.visit(),k=this.source.trimmed(),R=!(o.superGrammar&&o.superGrammar.rules[x]);f&&!R?o.override(x,d,_,null,k):o.define(x,d,_,null,k);const C=d.map(T=>s.app(T));return s.app(x,C).withSource(_.source)},OverrideTopLevelTerm_superSplice(b){return Ap},Seq(b){return s.seq(...b.children.map(v=>v.visit())).withSource(this.source)},Iter_star(b,v){return s.star(b.visit()).withSource(this.source)},Iter_plus(b,v){return s.plus(b.visit()).withSource(this.source)},Iter_opt(b,v){return s.opt(b.visit()).withSource(this.source)},Pred_not(b,v){return s.not(v.visit()).withSource(this.source)},Pred_lookahead(b,v){return s.lookahead(v.visit()).withSource(this.source)},Lex_lex(b,v){return s.lex(v.visit()).withSource(this.source)},Base_application(b,v){const x=v.children.map(_=>_.visit())[0]||[];return s.app(b.visit(),x).withSource(this.source)},Base_range(b,v,x){return s.range(b.visit(),x.visit()).withSource(this.source)},Base_terminal(b){return s.terminal(b.visit()).withSource(this.source)},Base_paren(b,v,x){return v.visit()},ruleDescr(b,v,x){return v.visit()},ruleDescrText(b){return this.sourceString.trim()},caseName(b,v,x,_,k){return x.visit()},name(b,v){return this.sourceString},nameFirst(b){},nameRest(b){},terminal(b,v,x){return v.children.map(_=>_.visit()).join("")},oneCharTerminal(b,v,x){return v.visit()},escapeChar(b){try{return t1(this.sourceString)}catch(v){throw v instanceof RangeError&&v.message.startsWith("Invalid code point ")?nO(b):v}},NonemptyListOf(b,v,x){return[b.visit()].concat(x.children.map(_=>_.visit()))},EmptyListOf(){return[]},_terminal(){return this.sourceString}})(t).visit()}const kO=My(["grammar",{source:`OperationsAndAttributes {
|
|
252
|
-
|
|
253
|
-
AttributeSignature =
|
|
254
|
-
name
|
|
255
|
-
|
|
256
|
-
OperationSignature =
|
|
257
|
-
name Formals?
|
|
258
|
-
|
|
259
|
-
Formals
|
|
260
|
-
= "(" ListOf<name, ","> ")"
|
|
261
|
-
|
|
262
|
-
name (a name)
|
|
263
|
-
= nameFirst nameRest*
|
|
264
|
-
|
|
265
|
-
nameFirst
|
|
266
|
-
= "_"
|
|
267
|
-
| letter
|
|
268
|
-
|
|
269
|
-
nameRest
|
|
270
|
-
= "_"
|
|
271
|
-
| alnum
|
|
272
|
-
|
|
273
|
-
}`},"OperationsAndAttributes",null,"AttributeSignature",{AttributeSignature:["define",{sourceInterval:[29,58]},null,[],["app",{sourceInterval:[54,58]},"name",[]]],OperationSignature:["define",{sourceInterval:[62,100]},null,[],["seq",{sourceInterval:[87,100]},["app",{sourceInterval:[87,91]},"name",[]],["opt",{sourceInterval:[92,100]},["app",{sourceInterval:[92,99]},"Formals",[]]]]],Formals:["define",{sourceInterval:[104,143]},null,[],["seq",{sourceInterval:[118,143]},["terminal",{sourceInterval:[118,121]},"("],["app",{sourceInterval:[122,139]},"ListOf",[["app",{sourceInterval:[129,133]},"name",[]],["terminal",{sourceInterval:[135,138]},","]]],["terminal",{sourceInterval:[140,143]},")"]]],name:["define",{sourceInterval:[147,187]},"a name",[],["seq",{sourceInterval:[168,187]},["app",{sourceInterval:[168,177]},"nameFirst",[]],["star",{sourceInterval:[178,187]},["app",{sourceInterval:[178,186]},"nameRest",[]]]]],nameFirst:["define",{sourceInterval:[191,223]},null,[],["alt",{sourceInterval:[207,223]},["terminal",{sourceInterval:[207,210]},"_"],["app",{sourceInterval:[217,223]},"letter",[]]]],nameRest:["define",{sourceInterval:[227,257]},null,[],["alt",{sourceInterval:[242,257]},["terminal",{sourceInterval:[242,245]},"_"],["app",{sourceInterval:[252,257]},"alnum",[]]]]}]);CO(rn.BuiltInRules);NO(kO);function CO(t){const e={empty(){return this.iteration()},nonEmpty(n,r,s){return this.iteration([n].concat(s.children))},self(...n){return this}};bn.BuiltInSemantics=bn.createSemantics(t,null).addOperation("asIteration",{emptyListOf:e.empty,nonemptyListOf:e.nonEmpty,EmptyListOf:e.empty,NonemptyListOf:e.nonEmpty,_iter:e.self})}function NO(t){bn.prototypeGrammarSemantics=t.createSemantics().addOperation("parse",{AttributeSignature(e){return{name:e.parse(),formals:[]}},OperationSignature(e,n){return{name:e.parse(),formals:n.children.map(r=>r.parse())[0]||[]}},Formals(e,n,r){return n.asIteration().children.map(s=>s.parse())},name(e,n){return this.sourceString}}),bn.prototypeGrammar=t}function OO(t){let e=0;const n=[0],r=()=>n[n.length-1],s={},o=/( *).*(?:$|\r?\n|\r)/g;let c;for(;(c=o.exec(t))!=null;){const[d,f]=c;if(d.length===0)break;const p=f.length,g=r(),b=e+p;if(p>g)n.push(p),s[b]=1;else if(p<g){const v=n.length;for(;r()!==p;)n.pop();s[b]=-1*(v-n.length)}e+=d.length}return n.length>1&&(s[e]=1-n.length),s}const y1="an indented block",g1="a dedent",Xx=1114112;class TO extends Ad{constructor(e){super(e.input),this.state=e}_indentationAt(e){return this.state.userData[e]||0}atEnd(){return super.atEnd()&&this._indentationAt(this.pos)===0}next(){if(this._indentationAt(this.pos)!==0){this.examinedLength=Math.max(this.examinedLength,this.pos);return}return super.next()}nextCharCode(){return this._indentationAt(this.pos)!==0?(this.examinedLength=Math.max(this.examinedLength,this.pos),Xx):super.nextCharCode()}nextCodePoint(){return this._indentationAt(this.pos)!==0?(this.examinedLength=Math.max(this.examinedLength,this.pos),Xx):super.nextCodePoint()}}class ew extends xe{constructor(e=!0){super(),this.isIndent=e}allowsSkippingPrecedingSpace(){return!0}eval(e){const{inputStream:n}=e,r=e.userData;e.doNotMemoize=!0;const s=n.pos,o=this.isIndent?1:-1;return(r[s]||0)*o>0?(e.userData=Object.create(r),e.userData[s]-=o,e.pushBinding(new qi(0),s),!0):(e.processFailure(s,this),!1)}getArity(){return 1}_assertAllApplicationsAreValid(e,n){}_isNullable(e,n){return!1}assertChoicesHaveUniformArity(e){}assertIteratedExprsAreNotNullable(e){}introduceParams(e){return this}substituteParams(e){return this}toString(){return this.isIndent?"indent":"dedent"}toDisplayString(){return this.toString()}toFailure(e){const n=this.isIndent?y1:g1;return new xn(this,n,"description")}}const RO=new He("indent"),DO=new He("dedent"),IO=new Ed(Ly,"any",[RO,DO],[]),MO=new Uu().newGrammar("IndentationSensitive").withSuperGrammar(Ly).define("indent",[],new ew(!0),y1,void 0,!0).define("dedent",[],new ew(!1),g1,void 0,!0).extend("any",[],IO,"any character",void 0).build();Object.assign(MO,{_matchStateInitializer(t){t.userData=OO(t.input),t.inputStream=new TO(t)},supportsIncrementalParsing:!1});rn.initApplicationParser(Uy,m1);const LO=t=>!!t.constructor&&typeof t.constructor.isBuffer=="function"&&t.constructor.isBuffer(t);function UO(t,e,n){const r=Uy.match(t,"Grammars");if(r.failed())throw zN(r);return m1(r,e,void 0,n)}function $O(t,e,n){const r=BO(t,e,n),s=Object.keys(r);if(s.length===0)throw new Error("Missing grammar definition");if(s.length>1){const c=r[s[1]].source;throw new Error(Ty(c.sourceString,c.startIdx)+"Found more than one grammar definition -- use ohm.grammars() instead.")}return r[s[0]]}function BO(t,e,n){const r=Object.create({});if(typeof t!="string")if(LO(t))t=t.toString();else throw new TypeError("Expected string as first argument, got "+Ny(t));return UO(t,r,n),r}function b1(t,e){return $O(t,e)}const FO=`FirestoreRules {
|
|
274
|
-
// === Top-level ===
|
|
275
|
-
// Syntactic rules (capitalized) auto-skip spaces between terms.
|
|
276
|
-
// Lexical rules (lowercase) do NOT skip spaces.
|
|
277
|
-
|
|
278
|
-
// Two accepted orderings. Real \`firestore.rules\` files put
|
|
279
|
-
// \`rules_version\` at line 1 (Firebase convention), so the
|
|
280
|
-
// \`versionFirst\` branch matches that natural shape. The
|
|
281
|
-
// \`importsFirst\` branch keeps legacy samples that put \`import\`
|
|
282
|
-
// declarations above the version line working. The semantic
|
|
283
|
-
// action below normalizes both into the same AST shape, so
|
|
284
|
-
// downstream code doesn't have to care which path matched.
|
|
285
|
-
RulesFile = RulesVersion ImportDecl* ServiceBlock -- versionFirst
|
|
286
|
-
| ImportDecl* RulesVersion ServiceBlock -- importsFirst
|
|
287
|
-
|
|
288
|
-
ImportDecl = "import" "{" ListOf<ident, ","> ","? "}" "from" string ";"
|
|
289
|
-
|
|
290
|
-
RulesVersion = "rules_version" "=" string ";"
|
|
291
|
-
|
|
292
|
-
ServiceBlock = "service" serviceName "{" DocumentsMatch "}"
|
|
293
|
-
|
|
294
|
-
DocumentsMatch = "match" matchPath "{" MatchBody "}"
|
|
295
|
-
|
|
296
|
-
MatchBody = MatchBodyItem*
|
|
297
|
-
|
|
298
|
-
MatchBodyItem
|
|
299
|
-
= FunctionDef
|
|
300
|
-
| MatchBlock
|
|
301
|
-
| AllowStatement
|
|
302
|
-
|
|
303
|
-
MatchBlock = "match" matchPath "{" MatchBody "}"
|
|
304
|
-
|
|
305
|
-
// === Statements ===
|
|
306
|
-
|
|
307
|
-
AllowStatement = "allow" OperationList ":" "if" Expr ";"
|
|
308
|
-
|
|
309
|
-
OperationList = Operation ("," Operation)*
|
|
310
|
-
|
|
311
|
-
FunctionDef = "export"? "function" ident "(" ParameterList ")" "{" FunctionBody "}"
|
|
312
|
-
|
|
313
|
-
ParameterList = ListOf<ident, ",">
|
|
314
|
-
|
|
315
|
-
FunctionBody = LetBinding* ReturnStatement
|
|
316
|
-
|
|
317
|
-
LetBinding = "let" ident "=" Expr ";"
|
|
318
|
-
|
|
319
|
-
ReturnStatement = "return" Expr ";"
|
|
320
|
-
|
|
321
|
-
// === Lexical: operations and service name ===
|
|
322
|
-
|
|
323
|
-
Operation
|
|
324
|
-
= "read" ~identChar
|
|
325
|
-
| "write" ~identChar
|
|
326
|
-
| "get" ~identChar
|
|
327
|
-
| "list" ~identChar
|
|
328
|
-
| "create" ~identChar
|
|
329
|
-
| "update" ~identChar
|
|
330
|
-
| "delete" ~identChar
|
|
331
|
-
|
|
332
|
-
serviceName = letter (letter | ".")*
|
|
333
|
-
|
|
334
|
-
// === Lexical: match paths ===
|
|
335
|
-
|
|
336
|
-
matchPath = "/" matchPathSegment ("/" matchPathSegment)*
|
|
337
|
-
|
|
338
|
-
matchPathSegment
|
|
339
|
-
= "{" matchWildcard "}" -- wildcard
|
|
340
|
-
| pathIdent -- literal
|
|
341
|
-
|
|
342
|
-
matchWildcard
|
|
343
|
-
= identStart identChar* "=" "**" -- recursive
|
|
344
|
-
| identStart identChar* -- single
|
|
345
|
-
|
|
346
|
-
pathIdent = (letter | digit | "_" | "-" | ".")+
|
|
347
|
-
|
|
348
|
-
// === Expressions ===
|
|
349
|
-
|
|
350
|
-
Expr = Ternary
|
|
351
|
-
|
|
352
|
-
Ternary
|
|
353
|
-
= LogicalOr "?" Ternary ":" Ternary -- ternary
|
|
354
|
-
| LogicalOr
|
|
355
|
-
|
|
356
|
-
LogicalOr
|
|
357
|
-
= LogicalOr "||" LogicalAnd -- or
|
|
358
|
-
| LogicalAnd
|
|
359
|
-
|
|
360
|
-
LogicalAnd
|
|
361
|
-
= LogicalAnd "&&" InIsExpr -- and
|
|
362
|
-
| InIsExpr
|
|
363
|
-
|
|
364
|
-
InIsExpr
|
|
365
|
-
= Equality in Equality -- in
|
|
366
|
-
| Equality is typeName -- is
|
|
367
|
-
| Equality
|
|
368
|
-
|
|
369
|
-
in = "in" ~identChar
|
|
370
|
-
is = "is" ~identChar
|
|
371
|
-
|
|
372
|
-
Equality
|
|
373
|
-
= Equality "==" Comparison -- eq
|
|
374
|
-
| Equality "!=" Comparison -- neq
|
|
375
|
-
| Comparison
|
|
376
|
-
|
|
377
|
-
Comparison
|
|
378
|
-
= Comparison ">=" Additive -- gte
|
|
379
|
-
| Comparison "<=" Additive -- lte
|
|
380
|
-
| Comparison ">" Additive -- gt
|
|
381
|
-
| Comparison "<" Additive -- lt
|
|
382
|
-
| Additive
|
|
383
|
-
|
|
384
|
-
Additive
|
|
385
|
-
= Additive "+" Multiplicative -- add
|
|
386
|
-
| Additive "-" Multiplicative -- sub
|
|
387
|
-
| Multiplicative
|
|
388
|
-
|
|
389
|
-
Multiplicative
|
|
390
|
-
= Multiplicative "*" UnaryExpr -- mul
|
|
391
|
-
| Multiplicative "/" UnaryExpr -- div
|
|
392
|
-
| Multiplicative "%" UnaryExpr -- mod
|
|
393
|
-
| UnaryExpr
|
|
394
|
-
|
|
395
|
-
UnaryExpr
|
|
396
|
-
= "!" UnaryExpr -- not
|
|
397
|
-
| "-" UnaryExpr -- neg
|
|
398
|
-
| PostfixExpr
|
|
399
|
-
|
|
400
|
-
PostfixExpr
|
|
401
|
-
= PostfixExpr "." memberName "(" ListOf<Expr, ","> ")" -- methodCall
|
|
402
|
-
| PostfixExpr "." memberName -- memberAccess
|
|
403
|
-
| PostfixExpr "[" Expr ":" Expr "]" -- sliceAccess
|
|
404
|
-
| PostfixExpr "[" Expr "]" -- bracketAccess
|
|
405
|
-
| Primary
|
|
406
|
-
|
|
407
|
-
memberName = identStart identChar*
|
|
408
|
-
|
|
409
|
-
Primary
|
|
410
|
-
= "(" Expr ")" -- paren
|
|
411
|
-
| PathLiteral -- path
|
|
412
|
-
| ListLiteral -- list
|
|
413
|
-
| MapLiteral -- map
|
|
414
|
-
| ident "(" ListOf<Expr, ","> ")" -- functionCall
|
|
415
|
-
| literal
|
|
416
|
-
| ident
|
|
417
|
-
|
|
418
|
-
// === Path literals ===
|
|
419
|
-
|
|
420
|
-
PathLiteral = "/" PathLitSegment ("/" PathLitSegment)*
|
|
421
|
-
|
|
422
|
-
PathLitSegment
|
|
423
|
-
= "$(" Expr ")" -- interpolation
|
|
424
|
-
| "{" ident "}" -- captureRef
|
|
425
|
-
| pathIdent -- literal
|
|
426
|
-
|
|
427
|
-
// === Literals ===
|
|
428
|
-
|
|
429
|
-
literal
|
|
430
|
-
= number
|
|
431
|
-
| string
|
|
432
|
-
| bool
|
|
433
|
-
| null
|
|
434
|
-
|
|
435
|
-
number
|
|
436
|
-
= digit+ "." digit+ -- float
|
|
437
|
-
| digit+ -- int
|
|
438
|
-
|
|
439
|
-
string
|
|
440
|
-
= "'" singleStringChar* "'" -- single
|
|
441
|
-
| "\\"" doubleStringChar* "\\"" -- double
|
|
442
|
-
|
|
443
|
-
singleStringChar
|
|
444
|
-
= "\\\\" stringEscapeChar -- escape
|
|
445
|
-
| ~"\\\\" ~"'" any -- char
|
|
446
|
-
|
|
447
|
-
doubleStringChar
|
|
448
|
-
= "\\\\" stringEscapeChar -- escape
|
|
449
|
-
| ~"\\\\" ~"\\"" any -- char
|
|
450
|
-
|
|
451
|
-
// Valid escape characters following a backslash. Anything else is rejected
|
|
452
|
-
// at parse time to match production semantics — production Firestore Rules
|
|
453
|
-
// raises a syntax error on unknown escapes (e.g. \`\\d\`, \`\\.\`). Keeping the
|
|
454
|
-
// sim strict here prevents over-permissive acceptance that masks model
|
|
455
|
-
// output that would crash at deploy.
|
|
456
|
-
stringEscapeChar = "\\\\" | "'" | "\\"" | "n" | "r" | "t" | "/"
|
|
457
|
-
|
|
458
|
-
ListLiteral = "[" ListOf<Expr, ","> ","? "]"
|
|
459
|
-
|
|
460
|
-
MapLiteral = "{" ListOf<MapEntry, ","> ","? "}"
|
|
461
|
-
|
|
462
|
-
MapEntry = (string | ident) ":" Expr
|
|
463
|
-
|
|
464
|
-
bool
|
|
465
|
-
= "true" ~identChar -- true
|
|
466
|
-
| "false" ~identChar -- false
|
|
467
|
-
|
|
468
|
-
null = "null" ~identChar
|
|
469
|
-
|
|
470
|
-
typeName
|
|
471
|
-
= "string" ~identChar
|
|
472
|
-
| "int" ~identChar
|
|
473
|
-
| "float" ~identChar
|
|
474
|
-
| "number" ~identChar
|
|
475
|
-
| "bool" ~identChar
|
|
476
|
-
| "list" ~identChar
|
|
477
|
-
| "map" ~identChar
|
|
478
|
-
| "timestamp" ~identChar
|
|
479
|
-
| "path" ~identChar
|
|
480
|
-
| "bytes" ~identChar
|
|
481
|
-
| "duration" ~identChar
|
|
482
|
-
| "latlng" ~identChar
|
|
483
|
-
| "reference" ~identChar
|
|
484
|
-
|
|
485
|
-
ident = ~keyword identStart identChar*
|
|
486
|
-
|
|
487
|
-
keyword
|
|
488
|
-
= ("true" | "false" | "null" | "in" | "is" | "if" | "return" | "let") ~identChar
|
|
489
|
-
|
|
490
|
-
identStart = letter | "_"
|
|
491
|
-
|
|
492
|
-
identChar = alnum | "_"
|
|
493
|
-
|
|
494
|
-
// === Whitespace and comments ===
|
|
495
|
-
|
|
496
|
-
space += comment
|
|
497
|
-
|
|
498
|
-
comment
|
|
499
|
-
= "//" (~"\\n" any)* &("\\n" | end) -- singleLine
|
|
500
|
-
| "/*" (~"*/" any)* "*/" -- multiLine
|
|
501
|
-
}
|
|
502
|
-
`,v1=b1(FO),x1=v1.createSemantics();x1.addOperation("toAST",{RulesFile_versionFirst(t,e,n){return{imports:e.children.map(r=>r.toAST()),version:t.toAST(),service:n.toAST()}},RulesFile_importsFirst(t,e,n){return{imports:t.children.map(r=>r.toAST()),version:e.toAST(),service:n.toAST()}},ImportDecl(t,e,n,r,s,o,c,d){return{functions:n.asIteration().children.map(f=>f.sourceString),module:c.toAST().value}},RulesVersion(t,e,n,r){return n.toAST().value},ServiceBlock(t,e,n,r,s){return{name:e.sourceString,match:r.toAST()}},DocumentsMatch(t,e,n,r,s){const{lineNum:o,colNum:c}=t.source.getLineAndColumn();return{...r.toAST(),path:nw(e.sourceString),loc:{line:o,col:c}}},MatchBody(t){const e=[],n=[],r=[];for(const s of t.children){const o=s.toAST();o._kind==="function"?e.push(o):o._kind==="allow"?n.push(o):o._kind==="match"&&r.push(o)}return{functions:e,allows:n,children:r}},MatchBodyItem(t){return t.toAST()},MatchBlock(t,e,n,r,s){const{functions:o,allows:c,children:d}=r.toAST(),{lineNum:f,colNum:p}=t.source.getLineAndColumn();return{_kind:"match",path:nw(e.sourceString),functions:o,allows:c,children:d,loc:{line:f,col:p}}},AllowStatement(t,e,n,r,s,o){const{lineNum:c,colNum:d}=t.source.getLineAndColumn();return{_kind:"allow",operations:e.toAST(),condition:s.toAST(),loc:{line:c,col:d}}},OperationList(t,e,n){return[t.toAST(),...n.children.map(r=>r.toAST())]},Operation(t){return t.sourceString},FunctionDef(t,e,n,r,s,o,c,d,f){const{lets:p,expr:g}=d.toAST();return{_kind:"function",name:n.sourceString,parameters:s.toAST(),exported:t.sourceString.trim()==="export",lets:p,body:g}},ParameterList(t){return t.asIteration().children.map(e=>e.sourceString)},FunctionBody(t,e){return{lets:t.children.map(n=>n.toAST()),expr:e.toAST()}},LetBinding(t,e,n,r,s){return{name:e.sourceString,value:r.toAST()}},ReturnStatement(t,e,n){return e.toAST()},Expr(t){return t.toAST()},Ternary_ternary(t,e,n,r,s){return{type:"ternary",condition:t.toAST(),consequent:n.toAST(),alternate:s.toAST()}},LogicalOr_or(t,e,n){return{type:"binaryOp",op:"||",left:t.toAST(),right:n.toAST()}},LogicalAnd_and(t,e,n){return{type:"binaryOp",op:"&&",left:t.toAST(),right:n.toAST()}},InIsExpr_in(t,e,n){return{type:"inExpr",element:t.toAST(),collection:n.toAST()}},InIsExpr_is(t,e,n){return{type:"isExpr",value:t.toAST(),typeName:n.sourceString}},Equality_eq(t,e,n){return{type:"binaryOp",op:"==",left:t.toAST(),right:n.toAST()}},Equality_neq(t,e,n){return{type:"binaryOp",op:"!=",left:t.toAST(),right:n.toAST()}},Comparison_gte(t,e,n){return{type:"binaryOp",op:">=",left:t.toAST(),right:n.toAST()}},Comparison_lte(t,e,n){return{type:"binaryOp",op:"<=",left:t.toAST(),right:n.toAST()}},Comparison_gt(t,e,n){return{type:"binaryOp",op:">",left:t.toAST(),right:n.toAST()}},Comparison_lt(t,e,n){return{type:"binaryOp",op:"<",left:t.toAST(),right:n.toAST()}},Additive_add(t,e,n){return{type:"binaryOp",op:"+",left:t.toAST(),right:n.toAST()}},Additive_sub(t,e,n){return{type:"binaryOp",op:"-",left:t.toAST(),right:n.toAST()}},Multiplicative_mul(t,e,n){return{type:"binaryOp",op:"*",left:t.toAST(),right:n.toAST()}},Multiplicative_div(t,e,n){return{type:"binaryOp",op:"/",left:t.toAST(),right:n.toAST()}},Multiplicative_mod(t,e,n){return{type:"binaryOp",op:"%",left:t.toAST(),right:n.toAST()}},UnaryExpr_not(t,e){return{type:"unaryOp",op:"!",operand:e.toAST()}},UnaryExpr_neg(t,e){return{type:"unaryOp",op:"-",operand:e.toAST()}},PostfixExpr_methodCall(t,e,n,r,s,o){return{type:"methodCall",object:t.toAST(),method:n.sourceString,args:s.asIteration().children.map(c=>c.toAST())}},PostfixExpr_memberAccess(t,e,n){return{type:"memberAccess",object:t.toAST(),property:n.sourceString}},PostfixExpr_bracketAccess(t,e,n,r){return{type:"bracketAccess",object:t.toAST(),index:n.toAST()}},PostfixExpr_sliceAccess(t,e,n,r,s,o){return{type:"sliceAccess",object:t.toAST(),start:n.toAST(),end:s.toAST()}},Primary_paren(t,e,n){return e.toAST()},Primary_path(t){return t.toAST()},Primary_list(t){return t.toAST()},Primary_map(t){return t.toAST()},Primary_functionCall(t,e,n,r){return{type:"functionCall",name:t.sourceString,args:n.asIteration().children.map(s=>s.toAST())}},PathLiteral(t,e,n,r){const s=[e.toAST()];for(const o of r.children)s.push(o.toAST());return{type:"pathLiteral",raw:this.sourceString,segments:s}},PathLitSegment_interpolation(t,e,n){return e.toAST()},PathLitSegment_captureRef(t,e,n){return`{${e.sourceString}}`},PathLitSegment_literal(t){return t.sourceString},ListLiteral(t,e,n,r){return{type:"listLiteral",elements:e.asIteration().children.map(s=>s.toAST())}},MapLiteral(t,e,n,r){return{type:"mapLiteral",entries:e.asIteration().children.map(s=>s.toAST())}},MapEntry(t,e,n){return{key:t.toAST(),value:n.toAST()}},literal(t){return t.toAST()},number_float(t,e,n){return{type:"literal",value:parseFloat(this.sourceString),raw:this.sourceString}},number_int(t){return{type:"literal",value:parseInt(this.sourceString,10),raw:this.sourceString}},string_single(t,e,n){return{type:"literal",value:tw(e.sourceString),raw:this.sourceString}},string_double(t,e,n){return{type:"literal",value:tw(e.sourceString),raw:this.sourceString}},bool_true(t){return{type:"literal",value:!0,raw:"true"}},bool_false(t){return{type:"literal",value:!1,raw:"false"}},null(t){return{type:"literal",value:null,raw:"null"}},ident(t,e){return{type:"identifier",name:this.sourceString}},_nonterminal(...t){return t.length===1?t[0].toAST():t.map(e=>e.toAST())},_terminal(){return this.sourceString}});function tw(t){let e="";for(let n=0;n<t.length;n++){const r=t[n];if(r!=="\\"||n===t.length-1){e+=r;continue}switch(t[n+1]){case"\\":e+="\\",n++;break;case"'":e+="'",n++;break;case'"':e+='"',n++;break;case"n":e+=`
|
|
503
|
-
`,n++;break;case"r":e+="\r",n++;break;case"t":e+=" ",n++;break;case"/":e+="/",n++;break;default:e+=r}}return e}function nw(t){const e=[],n=t.split("/").filter(Boolean);for(const r of n)if(r.startsWith("{")&&r.endsWith("}")){const s=r.slice(1,-1);s.endsWith("=**")?e.push({type:"recursive",name:s.slice(0,-3)}):e.push({type:"wildcard",name:s})}else e.push({type:"literal",value:r});return{raw:t,segments:e}}function PO(t,e){var p,g;const n=((p=t.getRightmostFailurePosition)==null?void 0:p.call(t))??0,r=((g=t.getExpectedText)==null?void 0:g.call(t))??"";let s=1,o=-1;for(let b=0;b<n&&b<e.length;b++)e.charCodeAt(b)===10&&(s++,o=b);const c=n-o;let d=e.indexOf(`
|
|
504
|
-
`,n);d===-1&&(d=e.length);const f=e.slice(n,Math.min(d,n+40));return{line:s,column:c,offset:n,expected:r,actual:f,message:t.message??"Parse error"}}function $y(t){const e=$u(t);return e.ok?e.ast:null}function $u(t){const e=t.trim();if(!e)return{ok:!1,error:{line:1,column:1,offset:0,expected:"",actual:"",message:"Empty rules file"}};const n=v1.match(e);if(!n.succeeded())return{ok:!1,error:PO(n,e)};const r=x1(n).toAST(),s=t.length-t.trimStart().length;let o=0;for(let c=0;c<s;c++)t.charCodeAt(c)===10&&o++;return o>0&&qO(r,o),{ok:!0,ast:r}}function qO(t,e){const n=[t.service.match];for(;n.length>0;){const r=n.pop();r.loc&&(r.loc.line+=e);for(const s of r.allows)s.loc&&(s.loc.line+=e);for(const s of r.children)n.push(s)}}function zO(t){const e=`rules_version = '2';
|
|
505
|
-
service cloud.firestore {
|
|
506
|
-
match /databases/{db}/documents {
|
|
507
|
-
${t}
|
|
508
|
-
}
|
|
509
|
-
}`,n=$y(e);return n?n.service.match.functions:null}const w1={"||":2,"&&":3,"==":5,"!=":5,">":6,"<":6,">=":6,"<=":6,"+":7,"-":7,"*":8,"/":8,"%":8};function VO(t){switch(t.type){case"ternary":return 1;case"binaryOp":return w1[t.op]??0;case"inExpr":return 4;case"isExpr":return 4;case"unaryOp":return 9;default:return 100}}function HO(t){switch(t.type){case"literal":return typeof t.value=="string"&&t.raw.startsWith('"')&&t.raw.endsWith('"')?`'${t.raw.slice(1,-1)}'`:t.raw;case"identifier":return t.name;case"memberAccess":return`${Gn(t.object,10)}.${t.property}`;case"methodCall":return`${Gn(t.object,10)}.${t.method}(${t.args.map(e=>Ft(e)).join(", ")})`;case"bracketAccess":return`${Gn(t.object,10)}[${Ft(t.index)}]`;case"sliceAccess":return`${Gn(t.object,10)}[${Ft(t.start)}:${Ft(t.end)}]`;case"binaryOp":{const e=w1[t.op]??0,n=Gn(t.left,e),r=Gn(t.right,e+1);return`${n} ${t.op} ${r}`}case"unaryOp":return`${t.op}${Gn(t.operand,9)}`;case"ternary":return`${Gn(t.condition,2)} ? ${Ft(t.consequent)} : ${Ft(t.alternate)}`;case"inExpr":return`${Gn(t.element,5)} in ${Gn(t.collection,5)}`;case"isExpr":return`${Gn(t.value,5)} is ${t.typeName}`;case"listLiteral":return t.elements.length===0?"[]":`[${t.elements.map(e=>Ft(e)).join(", ")}]`;case"mapLiteral":return t.entries.length===0?"{}":`{${t.entries.map(e=>`${Ft(e.key)}: ${Ft(e.value)}`).join(", ")}}`;case"pathLiteral":return"/"+t.segments.map(e=>typeof e=="string"?e:`$(${Ft(e)})`).join("/");case"functionCall":return`${t.name}(${t.args.map(e=>Ft(e)).join(", ")})`}}function Gn(t,e){const n=HO(t);return VO(t)<e?`(${n})`:n}function Ft(t){return Gn(t,0)}function S1(t){return"/"+t.segments.map(e=>{switch(e.type){case"literal":return e.value;case"wildcard":return`{${e.name}}`;case"recursive":return`{${e.name}=**}`}}).join("/")}function El(t){return" ".repeat(t)}function _1(t,e){const n=El(e),r=El(e+2),s=t.parameters.join(", "),o=[],c=t.exported?"export ":"";o.push(`${n}${c}function ${t.name}(${s}) {`);for(const d of t.lets)o.push(`${r}let ${d.name} = ${Ft(d.value)};`);return o.push(`${r}return ${Ft(t.body)};`),o.push(`${n}}`),o.join(`
|
|
510
|
-
`)}function E1(t,e){const n=El(e),r=t.operations.join(", ");return`${n}allow ${r}: if ${Ft(t.condition)};`}function A1(t,e=0){const n=El(e),r=e+2,s=[];s.push(`${n}match ${S1(t.path)} {`);for(const o of t.functions)s.push(_1(o,r));for(const o of t.allows)s.push(E1(o,r));for(const o of t.children)s.push(A1(o,r));return s.push(`${n}}`),s.join(`
|
|
511
|
-
`)}function rw(t){const e=[];for(const o of t.imports)e.push(`import { ${o.functions.join(", ")} } from '${o.module}';`);e.push(`rules_version = '${t.version}';`),e.push(`service ${t.service.name} {`);const n=t.service.match,r=El(2),s=4;e.push(`${r}match ${S1(n.path)} {`);for(const o of n.functions)e.push(_1(o,s));for(const o of n.allows)e.push(E1(o,s));for(const o of n.children)e.push(A1(o,s));return e.push(`${r}}`),e.push("}"),e.push(""),e.join(`
|
|
512
|
-
`)}function Bu(t,e){return t.type!=="binaryOp"||t.op!==e?0:1+Bu(t.right,e)}function pm(t){let e={op:"",depth:0};function n(s){if(s.type==="binaryOp"){const o=Bu(s,"&&"),c=Bu(s,"||");o>e.depth&&(e={op:"&&",depth:o}),c>e.depth&&(e={op:"||",depth:c}),n(s.left),n(s.right)}else r(s)}function r(s){switch(s.type){case"unaryOp":n(s.operand);break;case"methodCall":n(s.object),s.args.forEach(n);break;case"memberAccess":n(s.object);break;case"bracketAccess":n(s.object),n(s.index);break;case"ternary":n(s.condition),n(s.consequent),n(s.alternate);break;case"inExpr":n(s.element),n(s.collection);break;case"isExpr":n(s.value);break;case"listLiteral":s.elements.forEach(n);break;case"mapLiteral":s.entries.forEach(o=>{n(o.key),n(o.value)});break;case"functionCall":s.args.forEach(n);break}}return n(t),e}function ut(t){let e=1;switch(t.type){case"binaryOp":e+=ut(t.left)+ut(t.right);break;case"unaryOp":e+=ut(t.operand);break;case"methodCall":e+=ut(t.object);for(const n of t.args)e+=ut(n);break;case"memberAccess":e+=ut(t.object);break;case"bracketAccess":e+=ut(t.object)+ut(t.index);break;case"ternary":e+=ut(t.condition)+ut(t.consequent)+ut(t.alternate);break;case"inExpr":e+=ut(t.element)+ut(t.collection);break;case"isExpr":e+=ut(t.value);break;case"listLiteral":for(const n of t.elements)e+=ut(n);break;case"mapLiteral":for(const n of t.entries)e+=ut(n.key)+ut(n.value);break;case"functionCall":for(const n of t.args)e+=ut(n);break;case"pathLiteral":for(const n of t.segments)typeof n!="string"&&(e+=ut(n));break}return e}function ct(t){switch(t.type){case"literal":return`L:${t.raw}`;case"identifier":return`I:${t.name}`;case"memberAccess":return`M:${ct(t.object)}.${t.property}`;case"methodCall":return`MC:${ct(t.object)}.${t.method}(${t.args.map(ct).join(",")})`;case"bracketAccess":return`B:${ct(t.object)}[${ct(t.index)}]`;case"binaryOp":return`BO:${ct(t.left)}${t.op}${ct(t.right)}`;case"unaryOp":return`UO:${t.op}${ct(t.operand)}`;case"ternary":return`T:${ct(t.condition)}?${ct(t.consequent)}:${ct(t.alternate)}`;case"inExpr":return`IN:${ct(t.element)}in${ct(t.collection)}`;case"isExpr":return`IS:${ct(t.value)}is${t.typeName}`;case"listLiteral":return`LL:[${t.elements.map(ct).join(",")}]`;case"mapLiteral":return`ML:{${t.entries.map(e=>ct(e.key)+":"+ct(e.value)).join(",")}}`;case"functionCall":return`FC:${t.name}(${t.args.map(ct).join(",")})`;case"pathLiteral":return`PL:${t.raw}`;case"sliceAccess":return`SL:${ct(t.object)}[${ct(t.start)}:${ct(t.end)}]`;default:{const e=t;throw new Error(`expressionFingerprint: unhandled type ${e.type}`)}}}function j1(t){return t.type==="binaryOp"&&t.op==="&&"?j1(t.left):t}function k1(t){const e=new Map,n=new Set(t.map(o=>o.name)),r=new Set(["get","exists","getAfter","debug"]);function s(o){const c=[],d=f=>{switch(f.type){case"functionCall":n.has(f.name)&&!r.has(f.name)&&c.push(f.name),f.args.forEach(d);break;case"binaryOp":d(f.left),d(f.right);break;case"unaryOp":d(f.operand);break;case"methodCall":d(f.object),f.args.forEach(d);break;case"memberAccess":d(f.object);break;case"bracketAccess":d(f.object),d(f.index);break;case"ternary":d(f.condition),d(f.consequent),d(f.alternate);break;case"inExpr":d(f.element),d(f.collection);break;case"isExpr":d(f.value);break;case"listLiteral":f.elements.forEach(d);break;case"mapLiteral":f.entries.forEach(p=>{d(p.key),d(p.value)});break}};return d(o),[...new Set(c)]}for(const o of t){const c=[];c.push(...s(o.body));for(const d of o.lets)c.push(...s(d.value));e.set(o.name,[...new Set(c)])}return e}function By(t,e,n=new Set){if(n.has(t))return 0;n.add(t);const r=e.get(t)||[];if(r.length===0)return 1;let s=0;for(const o of r)s=Math.max(s,By(o,e,new Set(n)));return 1+s}function C1(t,e,n=new Set){let r=0;const s=o=>{switch(o.type){case"functionCall":if(o.name==="get"||o.name==="exists")r++;else if(e.has(o.name)&&!n.has(o.name)){n.add(o.name);const c=e.get(o.name);s(c.body);for(const d of c.lets)s(d.value)}o.args.forEach(s);break;case"binaryOp":s(o.left),s(o.right);break;case"unaryOp":s(o.operand);break;case"methodCall":s(o.object),o.args.forEach(s);break;case"memberAccess":s(o.object);break;case"bracketAccess":s(o.object),s(o.index);break;case"ternary":s(o.condition),s(o.consequent),s(o.alternate);break;case"inExpr":s(o.element),s(o.collection);break;case"isExpr":s(o.value);break;case"listLiteral":o.elements.forEach(s);break;case"mapLiteral":o.entries.forEach(c=>{s(c.key),s(c.value)});break}};return s(t),r}function GO(t,e){const n=new Map,r=s=>{switch(s.type){case"functionCall":e.has(s.name)&&n.set(s.name,(n.get(s.name)??0)+1),s.args.forEach(r);break;case"binaryOp":r(s.left),r(s.right);break;case"unaryOp":r(s.operand);break;case"methodCall":r(s.object),s.args.forEach(r);break;case"memberAccess":r(s.object);break;case"bracketAccess":r(s.object),r(s.index);break;case"ternary":r(s.condition),r(s.consequent),r(s.alternate);break;case"inExpr":r(s.element),r(s.collection);break;case"isExpr":r(s.value);break;case"listLiteral":s.elements.forEach(r);break;case"mapLiteral":s.entries.forEach(o=>{r(o.key),r(o.value)});break}};return r(t),n}function N1(t,e,n=new Set){if(n.has(t))return!1;n.add(t);const r=e.get(t);if(!r)return!1;const s=o=>{switch(o.type){case"functionCall":return o.name==="get"||o.name==="exists"?!0:e.has(o.name)?N1(o.name,e,n):o.args.some(s);case"binaryOp":return s(o.left)||s(o.right);case"unaryOp":return s(o.operand);case"methodCall":return s(o.object)||o.args.some(s);case"memberAccess":return s(o.object);case"bracketAccess":return s(o.object)||s(o.index);case"ternary":return s(o.condition)||s(o.consequent)||s(o.alternate);case"inExpr":return s(o.element)||s(o.collection);case"isExpr":return s(o.value);case"listLiteral":return o.elements.some(s);case"mapLiteral":return o.entries.some(c=>s(c.key)||s(c.value));default:return!1}};return s(r.body)||r.lets.some(o=>s(o.value))}function mm(t,e,n=new Set){const r=s=>{switch(s.type){case"memberAccess":return s.property==="time"&&s.object.type==="identifier"&&s.object.name==="request"?!0:r(s.object);case"bracketAccess":return s.object.type==="identifier"&&s.object.name==="request"&&s.index.type==="literal"&&s.index.value==="time"?!0:r(s.object)||r(s.index);case"functionCall":if(e.has(s.name)&&!n.has(s.name)){n.add(s.name);const o=e.get(s.name);if(mm(o.body,e,n)||o.lets.some(c=>mm(c.value,e,n)))return!0}return s.args.some(r);case"binaryOp":return r(s.left)||r(s.right);case"unaryOp":return r(s.operand);case"methodCall":return r(s.object)||s.args.some(r);case"ternary":return r(s.condition)||r(s.consequent)||r(s.alternate);case"inExpr":return r(s.element)||r(s.collection);case"isExpr":return r(s.value);case"listLiteral":return s.elements.some(r);case"mapLiteral":return s.entries.some(o=>r(o.key)||r(o.value));default:return!1}};return r(t)}function O1(t){const e=[...t.functions];for(const n of t.children)e.push(...O1(n));return e}function T1(t){const e=[];for(const n of t.allows)e.push({rule:n,path:t.path.raw,matchFunctions:t.functions});for(const n of t.children){const r=T1(n);for(const s of r)s.matchFunctions=[...t.functions,...s.matchFunctions];e.push(...r)}return e}const jp={where:"No equivalent in rules — restructure logic instead of filtering a list",filter:"No equivalent in rules — restructure logic instead of filtering a list",find:"No equivalent in rules",findIndex:"No equivalent in rules",map:"No equivalent in rules — lists are not transformable",reduce:"No equivalent in rules",forEach:"No equivalent in rules",every:'Use `list.hasAll([...])` for "all elements present"',some:'Use `list.hasAny([...])` for "any element present"',includes:"Use `x in list` instead of `list.includes(x)`",indexOf:"No equivalent in rules",push:"Lists are immutable in rules",pop:"Lists are immutable in rules",shift:"Lists are immutable in rules",unshift:"Lists are immutable in rules",splice:"Lists are immutable in rules",slice:"No equivalent in rules",sort:"Lists are immutable in rules",reverse:"Lists are immutable in rules",flat:"No equivalent in rules",flatMap:"No equivalent in rules",toLowerCase:"Use `.lower()` instead of `.toLowerCase()`",toUpperCase:"Use `.upper()` instead of `.toUpperCase()`",charAt:'No equivalent in rules — use `.split("")` and index',charCodeAt:"No equivalent in rules",substring:"No `.substring()` — use `.split()` and reassembly",substr:"No `.substr()` — use `.split()` and reassembly",padStart:"No equivalent in rules",padEnd:"No equivalent in rules",trimStart:"Use `.trim()` (trims both ends)",trimEnd:"Use `.trim()` (trims both ends)",toString:"Use the `string(x)` cast instead of `.toString()`"},Zr={Object:"No `Object` in rules — use `data.keys()` / `data.values()` directly",Array:"No `Array` in rules — test list type with `x is list`",JSON:"No `JSON` in rules — rules cannot parse or serialize JSON",Math:"No `Math` in rules — inline arithmetic or ternaries",Date:"No `Date` in rules — use `request.time` (a Timestamp)",String:"Use lowercase `string(x)` for casting",Number:"Use lowercase `int(x)` or `float(x)` for casting",Boolean:"Use lowercase `bool(x)` for casting",parseInt:"Use `int(x)` instead",parseFloat:"Use `float(x)` instead",isNaN:"No equivalent in rules",isFinite:"No equivalent in rules",Promise:"Rules are synchronous — no Promise support",undefined:"`undefined` does not exist in rules — use `null`"},KO=[{receiver:"request",property:"data",suggestion:"Use `request.resource.data` (the incoming write payload)"},{receiver:"request",property:"uid",suggestion:"Use `request.auth.uid`"},{receiver:"request",property:"token",suggestion:"Use `request.auth.token`"},{receiver:"request",property:"user",suggestion:"Use `request.auth` (or `request.auth.uid` for the user id)"},{receiver:"resource",property:"path",suggestion:"`resource.path` is not available — bind path captures in the match pattern"},{receiver:"resource",property:"exists",suggestion:"Use `resource != null` (or `exists()` for cross-document checks)"},{receiver:"resource",property:"id",suggestion:"`resource.id` is not available — capture the document id with `/{docId}` in the match path"}],YO=new Set(["size","keys","values","lower","upper","trim","hasAll","hasAny","hasOnly","toSet","toUtf8"]),ZO=[{pattern:/===/,message:"Strict equality `===` is not supported in Firestore rules — use `==`."},{pattern:/!==/,message:"Strict inequality `!==` is not supported in Firestore rules — use `!=`."},{pattern:/\?\./,message:"Optional chaining `?.` is not supported — use `'field' in obj && obj.field`."},{pattern:/\?\?/,message:"Nullish coalescing `??` is not supported — use a ternary `cond ? a : b`."},{pattern:/=>/,message:"Arrow functions `=>` are not supported — define functions with `function name() { return ...; }`."},{pattern:/`[^`]*`/,message:"Backtick strings are not supported — use single or double quoted strings with `+` for concatenation."}];function WO(t){const e=[],n=t.replace(/\/\/[^\n]*/g,"").replace(/\/\*[\s\S]*?\*\//g,"");for(const r of ZO)r.pattern.test(n)&&e.push({rule:"INVALID_OPERATOR",severity:"error",message:r.message});return e}function R1(t,e){const n=t.path.raw;for(const r of t.functions){const s={matchPath:n,functionName:r.name};bt(r.body,s,e);for(const o of r.lets)bt(o.value,s,e)}for(let r=0;r<t.allows.length;r++)bt(t.allows[r].condition,{matchPath:n,ruleIndex:r},e);for(const r of t.children)R1(r,e)}function bt(t,e,n){switch(n(t,e),t.type){case"binaryOp":bt(t.left,e,n),bt(t.right,e,n);break;case"unaryOp":bt(t.operand,e,n);break;case"methodCall":bt(t.object,e,n),t.args.forEach(r=>bt(r,e,n));break;case"memberAccess":bt(t.object,e,n);break;case"bracketAccess":bt(t.object,e,n),bt(t.index,e,n);break;case"ternary":bt(t.condition,e,n),bt(t.consequent,e,n),bt(t.alternate,e,n);break;case"inExpr":bt(t.element,e,n),bt(t.collection,e,n);break;case"isExpr":bt(t.value,e,n);break;case"listLiteral":t.elements.forEach(r=>bt(r,e,n));break;case"mapLiteral":t.entries.forEach(r=>{bt(r.key,e,n),bt(r.value,e,n)});break;case"functionCall":t.args.forEach(r=>bt(r,e,n));break}}function JO(t){const e=[],n=new Set;function r(s,o,c,d){const f=`${s}|${o}|${c.matchPath||""}|${c.functionName||""}|${c.ruleIndex??""}`;n.has(f)||(n.add(f),e.push(d))}return R1(t.service.match,(s,o)=>{if(s.type==="methodCall"&&jp[s.method]&&r("HALLUCINATED_METHOD",s.method,o,{rule:"HALLUCINATED_METHOD",severity:"error",message:`\`.${s.method}()\` does not exist in Firestore rules. ${jp[s.method]}`,location:o,fix:jp[s.method]}),s.type==="methodCall"&&s.object.type==="identifier"&&Zr[s.object.name]){const c=s.object.name;r("HALLUCINATED_GLOBAL",`${c}.${s.method}`,o,{rule:"HALLUCINATED_GLOBAL",severity:"error",message:`\`${c}.${s.method}()\` does not exist in Firestore rules. ${Zr[c]}`,location:o,fix:Zr[c]})}if(s.type==="functionCall"&&Zr[s.name]&&r("HALLUCINATED_GLOBAL",s.name,o,{rule:"HALLUCINATED_GLOBAL",severity:"error",message:`\`${s.name}()\` does not exist in Firestore rules. ${Zr[s.name]}`,location:o,fix:Zr[s.name]}),s.type==="identifier"&&Zr[s.name]&&r("HALLUCINATED_GLOBAL",`ref:${s.name}`,o,{rule:"HALLUCINATED_GLOBAL",severity:"error",message:`\`${s.name}\` is not a Firestore rules identifier. ${Zr[s.name]}`,location:o,fix:Zr[s.name]}),s.type==="memberAccess"&&s.object.type==="identifier"){const c=s.object.name,d=s.property,f=KO.find(p=>p.receiver===c&&p.property===d);f&&r("WRONG_CONTEXT_PATH",`${c}.${d}`,o,{rule:"WRONG_CONTEXT_PATH",severity:"error",message:`\`${c}.${d}\` is not a valid Firestore rules path. ${f.suggestion}`,location:o,fix:f.suggestion})}if(s.type==="memberAccess"&&s.property==="length"&&s.object.type==="methodCall"&&r("LENGTH_PROPERTY","",o,{rule:"LENGTH_PROPERTY",severity:"error",message:"`.length` is not a valid property in Firestore rules — use `.size()` (a method, with parentheses).",location:o,fix:"Replace `.length` with `.size()`."}),s.type==="pathLiteral")for(const c of s.segments){if(typeof c!="string")continue;const d=c.match(/^\{([A-Za-z_][A-Za-z0-9_]*)\}$/);if(!d)continue;const f=d[1];r("INVALID_PATH_INTERPOLATION",`${s.raw}|${f}`,o,{rule:"INVALID_PATH_INTERPOLATION",severity:"error",message:`\`{${f}}\` is not valid inside a path literal — Firestore rejects this at deploy. The \`{var}\` syntax is for match statement wildcards (e.g. \`match /users/{userId}\`); path interpolation in get()/exists()/getAfter()/existsAfter() requires \`$(var)\`. Replace \`{${f}}\` with \`$(${f})\` in path \`${s.raw}\`.`,location:o,fix:`Replace \`{${f}}\` with \`$(${f})\` inside the path argument.`})}s.type==="memberAccess"&&YO.has(s.property)&&(s.object.type==="identifier"&&(s.object.name==="request"||s.object.name==="resource")||s.object.type==="memberAccess"||s.object.type==="methodCall"||s.object.type==="bracketAccess")&&r("METHOD_MISSING_PARENS",s.property,o,{rule:"METHOD_MISSING_PARENS",severity:"warning",message:`\`.${s.property}\` looks like a built-in method called without parentheses. Use \`.${s.property}()\` if you meant to invoke it (otherwise this is a field access).`,location:o,fix:`Add parentheses: \`.${s.property}()\`.`})}),e}const kt={SOURCE_SIZE:256*1024,CHAIN_DEPTH_ERROR:95,CHAIN_DEPTH_WARN:85,CHAIN_DEPTH_LIMIT:98,LET_LIMIT:11,RUNTIME_BUDGET:{low:{calls:2,warn:100},mid:{calls:4,warn:60},high:{warn:40}},CALL_DEPTH_WARN:6,CALL_DEPTH_ERROR:10,GET_COUNT_WARN:5,GET_COUNT_ERROR:10};function QO(t,e){t.length>kt.SOURCE_SIZE&&e.push({rule:"SOURCE_SIZE",severity:"error",message:`Rules source is ${(t.length/1024).toFixed(0)} KB, exceeding the 256 KB limit.`,fix:"Reduce string literals, remove comments, or split into smaller match blocks."})}function XO(t,e){for(const n of t)n.lets.length>kt.LET_LIMIT&&e.push({rule:"LET_LIMIT",severity:"error",message:`Function '${n.name}' has ${n.lets.length} let bindings. Limit is ${kt.LET_LIMIT}.`,location:{functionName:n.name},fix:"Inline some let expressions into the return statement, or split the function."})}function eT(t,e){for(const n of t){const r=pm(n.body);for(const s of n.lets){const o=pm(s.value);o.depth>r.depth&&(r.depth=o.depth,r.op=o.op)}r.depth>=kt.CHAIN_DEPTH_LIMIT?e.push({rule:"CHAIN_DEPTH",severity:"error",message:`Function '${n.name}' has a ${r.op} chain of depth ${r.depth}. Limit is ${kt.CHAIN_DEPTH_LIMIT}.`,location:{functionName:n.name},fix:"Split into nested groups: 'a && b && c && d' → '(a && b) && (c && d)' to halve chain depth."}):r.depth>=kt.CHAIN_DEPTH_ERROR?e.push({rule:"CHAIN_DEPTH",severity:"error",message:`Function '${n.name}' has a ${r.op} chain of depth ${r.depth}. Limit is ${kt.CHAIN_DEPTH_LIMIT}. Approaching failure.`,location:{functionName:n.name},fix:"Split the chain into nested groups to reduce depth."}):r.depth>=kt.CHAIN_DEPTH_WARN&&e.push({rule:"CHAIN_DEPTH",severity:"warning",message:`Function '${n.name}' has a ${r.op} chain of depth ${r.depth}. Limit is ${kt.CHAIN_DEPTH_LIMIT}.`,location:{functionName:n.name}})}}function tT(t,e){const n=new Map;for(let r=0;r<t.length;r++){const s=t[r];if(!s.rule.operations.some(d=>d==="update"||d==="write"))continue;const o=ct(j1(s.rule.condition)),c=s.path;n.has(c)||n.set(c,[]),n.get(c).push({index:r,gate:o,ops:s.rule.operations})}for(const[r,s]of n){const o=new Map;for(const c of s)o.has(c.gate)||o.set(c.gate,[]),o.get(c.gate).push(c.index);for(const[c,d]of o)d.length>=2&&e.push({rule:"SHARED_GATE",severity:"warning",message:`${d.length} allow rules in '${r}' share the same gate expression. This may cause cross-rule budget exhaustion. Rules: ${d.join(", ")}.`,location:{matchPath:r},fix:"Assign unique moveType or discriminator values so each rule has a unique first expression."})}}function nT(t,e){let n=ut(t);const r=new Set;function s(o){if(o.type==="functionCall"&&e.has(o.name)&&!r.has(o.name)){r.add(o.name);const c=e.get(o.name);n+=ut(c.body);for(const d of c.lets)n+=ut(d.value);s(c.body);for(const d of c.lets)s(d.value)}switch(o.type){case"binaryOp":s(o.left),s(o.right);break;case"unaryOp":s(o.operand);break;case"methodCall":s(o.object),o.args.forEach(s);break;case"memberAccess":s(o.object);break;case"bracketAccess":s(o.object),s(o.index);break;case"ternary":s(o.condition),s(o.consequent),s(o.alternate);break;case"inExpr":s(o.element),s(o.collection);break;case"isExpr":s(o.value);break;case"listLiteral":o.elements.forEach(s);break;case"mapLiteral":o.entries.forEach(c=>{s(c.key),s(c.value)});break;case"functionCall":o.args.forEach(s);break}}return s(t),{totalExprs:n,callCount:r.size}}function rT(t,e,n){const r=new Map;for(const s of e)r.set(s.name,s);for(let s=0;s<t.length;s++){const{totalExprs:o,callCount:c}=nT(t[s].rule.condition,r),d=Bu(t[s].rule.condition,"||"),f=d>5?.3:d>2?.5:1,p=Math.round(o*f),g=c<=kt.RUNTIME_BUDGET.low.calls?kt.RUNTIME_BUDGET.low:c<=kt.RUNTIME_BUDGET.mid.calls?kt.RUNTIME_BUDGET.mid:kt.RUNTIME_BUDGET.high;p>=g.warn&&n.push({rule:"EXPRESSION_BUDGET",severity:"warning",message:`Rule #${s} has ~${o} expression nodes across ${c} function calls. Runtime budget is non-deterministic; actual evaluation depends on short-circuit behavior.`,location:{ruleIndex:s},fix:"If this rule fails at runtime (403), reduce function calls or expression count."})}}function sT(t,e,n){const r=k1(e),s=new Map;for(const o of e)s.set(o.name,o);for(let o=0;o<t.length;o++){let c=0;const d=f=>{if(f.type==="functionCall"&&s.has(f.name)){const p=By(f.name,r);p>c&&(c=p)}switch(f.type){case"binaryOp":d(f.left),d(f.right);break;case"unaryOp":d(f.operand);break;case"methodCall":d(f.object),f.args.forEach(d);break;case"memberAccess":d(f.object);break;case"bracketAccess":d(f.object),d(f.index);break;case"ternary":d(f.condition),d(f.consequent),d(f.alternate);break;case"inExpr":d(f.element),d(f.collection);break;case"functionCall":f.args.forEach(d);break}};d(t[o].rule.condition),c>=kt.CALL_DEPTH_ERROR?n.push({rule:"CALL_DEPTH",severity:"error",message:`Rule #${o} has a function call chain of depth ${c}. May exceed call budget.`,location:{ruleIndex:o},fix:"Inline intermediate functions to reduce call depth."}):c>=kt.CALL_DEPTH_WARN&&n.push({rule:"CALL_DEPTH",severity:"warning",message:`Rule #${o} has a function call chain of depth ${c}.`,location:{ruleIndex:o}})}}function iT(t,e,n){const r=new Map;for(const s of e)r.set(s.name,s);for(let s=0;s<t.length;s++){const o=C1(t[s].rule.condition,r);o>=kt.GET_COUNT_ERROR?n.push({rule:"GET_COUNT",severity:"error",message:`Rule #${s} may invoke ${o} get()/exists() calls. Limit is ${kt.GET_COUNT_ERROR}.`,location:{ruleIndex:s},fix:"Cache get() results via a config() wrapper function. Same-path calls are cached by Firestore."}):o>=kt.GET_COUNT_WARN&&n.push({rule:"GET_COUNT",severity:"warning",message:`Rule #${s} invokes ${o} get()/exists() calls. Limit is ${kt.GET_COUNT_ERROR}.`,location:{ruleIndex:s}})}}function aT(t,e,n){const r=new Map;for(const o of e)r.set(o.name,o);const s=new Set(e.map(o=>o.name));for(let o=0;o<t.length;o++){const c=GO(t[o].rule.condition,s);for(const[d,f]of c)f>=2&&N1(d,r)&&n.push({rule:"GET_DUPLICATION",severity:"warning",message:`Function '${d}' (contains get/exists) is called ${f} times in rule #${o}. Cache the result with a let binding in a wrapper function to reduce get() calls from ${f} to 1.`,location:{ruleIndex:o},fix:`Create a wrapper: function verifyAll(ret) { let c = ${d}(); return verify1(ret, c) && verify2(ret, c) && ...; }`})}}function oT(t,e,n,r){const s=new Map;for(const d of e)s.set(d.name,d);const o=new Set;for(let d=0;d<t.length;d++)mm(t[d].rule.condition,s)&&o.add(d);if(o.size===0)return;function c(d,f){const p=d.split("/").filter(Boolean),g=f.split("/").filter(Boolean);if(p.length!==g.length)return!1;for(let b=0;b<p.length;b++){const v=p[b];if(!(v.startsWith("{")&&v.endsWith("}"))&&v!==g[b])return!1}return!0}for(const d of n)if(!d.requestTime)for(const f of o)c(t[f].path,d.path)&&r.push({rule:"REQUEST_TIME_NOT_PINNED",severity:"warning",message:`Test case "${d.description}" targets rule #${f} (path '${t[f].path}') which reads request.time, but does not set requestTime. Result is non-deterministic across runs.`,location:{ruleIndex:f,matchPath:t[f].path,testCaseDescription:d.description},fix:"Set requestTime on this TestCase to an ISO-8601 timestamp so the rule evaluates deterministically."})}function gl(t){if(t.type==="literal"&&typeof t.value=="boolean")return t.value;if(t.type==="binaryOp"){const e=gl(t.left),n=gl(t.right);if(t.op==="&&")return e===!1||n===!1?!1:e===!0&&n===!0?!0:null;if(t.op==="||")return e===!0||n===!0?!0:e===!1&&n===!1?!1:null}if(t.type==="unaryOp"&&t.op==="!"){const e=gl(t.operand);return e===null?null:!e}return null}const lT=new Set(["write","create","update","delete"]);function cT(t,e){for(let n=0;n<t.length;n++){const r=t[n];if(gl(r.rule.condition)!==!0||!r.rule.operations.some(c=>lT.has(c)))continue;const o=r.rule.operations.join(", ");e.push({rule:"PERMISSIVE_RULE",severity:"warning",message:`allow ${o} at ${r.path} resolves to a constant true predicate — this disables write security for the matched paths. If you reached for \`if true\` to escape a denial you don't understand, narrow the predicate to the specific request shape instead (auth identity, affected fields via diff, status transitions).`,location:{ruleIndex:n,matchPath:r.path},fix:"Replace the always-true predicate with a request-shape check (e.g. request.auth != null && request.resource.data.ownerId == request.auth.uid)."})}}function D1(t,e){if(t.path.segments.some(r=>r.type==="recursive"))for(let r=0;r<t.allows.length;r++)gl(t.allows[r].condition)===!0&&e.push({rule:"RECURSIVE_WILDCARD_OPEN",severity:"error",message:`Recursive wildcard match (${t.path.raw}) with an always-true predicate exposes every document under this prefix. This is the Firebase open-rules anti-pattern — never ship it.`,location:{ruleIndex:r,matchPath:t.path.raw},fix:"Either narrow the match path to specific collections, or replace `if true` with a real predicate (auth identity, ownership, role)."});for(const r of t.children)D1(r,e)}function uT(t){return t.type==="literal"?t.value??"":t.type==="wildcard"?"{*}":t.type==="recursive"?"{**}":""}function dT(t){return t.map(uT).join("/")}function ym(t,e){const n=dT(t.path.segments),r=e?`${e}/${n}`:n,s=[{block:t,normalizedPath:r}];for(const o of t.children)s.push(...ym(o,r));return s}function at(t){switch(t.type){case"literal":return t.raw;case"identifier":return t.name;case"memberAccess":return`${at(t.object)}.${t.property}`;case"methodCall":return`${at(t.object)}.${t.method}(${t.args.map(at).join(",")})`;case"bracketAccess":return`${at(t.object)}[${at(t.index)}]`;case"sliceAccess":return`${at(t.object)}[${at(t.start)}:${at(t.end)}]`;case"binaryOp":return`(${at(t.left)}${t.op}${at(t.right)})`;case"unaryOp":return`(${t.op}${at(t.operand)})`;case"ternary":return`(${at(t.condition)}?${at(t.consequent)}:${at(t.alternate)})`;case"inExpr":return`(${at(t.element)} in ${at(t.collection)})`;case"isExpr":return`(${at(t.value)} is ${t.typeName})`;case"listLiteral":return`[${t.elements.map(at).join(",")}]`;case"mapLiteral":return`{${t.entries.map(e=>`${at(e.key)}:${at(e.value)}`).join(",")}}`;case"pathLiteral":return t.raw;case"functionCall":return`${t.name}(${t.args.map(at).join(",")})`}}function Fu(t){return t.type==="binaryOp"&&t.op==="&&"?[...Fu(t.left),...Fu(t.right)]:[t]}function fT(t,e,n){const r=ym(t,""),s=ym(e,""),o=new Map;for(const{block:c,normalizedPath:d}of r)o.has(d)||o.set(d,c);for(const{block:c,normalizedPath:d}of s){const f=o.get(d);if(!f){c.allows.length>0&&n.push({rule:"RULES_WEAKENED",severity:"warning",message:`Match block removed: ${d}`,location:{matchPath:d}});continue}for(const p of c.allows){const g=[...p.operations].sort().join(","),b=f.allows.find(k=>[...k.operations].sort().join(",")===g),v=p.operations.join(", ");if(!b){n.push({rule:"RULES_WEAKENED",severity:"warning",message:`Allow rule removed: ${d} allow ${v}`,location:{matchPath:d}});continue}const x=Fu(p.condition).map(at),_=new Set(Fu(b.condition).map(at));for(const k of x)_.has(k)||n.push({rule:"RULES_WEAKENED",severity:"warning",message:`Predicate removed from ${d} allow ${v}: ${k}`,location:{matchPath:d}})}}}function Pu(t,e={}){const n=[];n.push(...WO(t)),QO(t,n);const r=$u(t);if(!r.ok)return{warnings:n,metrics:{sourceSize:t.length,functionCount:0,allowRuleCount:0,maxChainDepth:0,maxChainOp:"",maxLetBindings:0,maxLetBindingsFunction:"",maxCallDepth:0,maxEstimatedExpressions:0,getCallCount:0},parseError:r.error};const s=r.ast,o=O1(s.service.match),c=T1(s.service.match);if(eT(o,n),XO(o,n),tT(c,n),rT(c,o,n),sT(c,o,n),iT(c,o,n),aT(c,o,n),n.push(...JO(s)),cT(c,n),D1(s.service.match,n),e.testCases&&e.testCases.length>0&&oT(c,o,e.testCases,n),e.previousSource){const _=$u(e.previousSource);_.ok&&fT(s.service.match,_.ast.service.match,n)}let d={depth:0,op:""},f={count:0,fn:""};for(const _ of o){const k=pm(_.body);k.depth>d.depth&&(d={depth:k.depth,op:k.op}),_.lets.length>f.count&&(f={count:_.lets.length,fn:_.name})}const p=k1(o);let g=0;for(const _ of o){const k=By(_.name,p);k>g&&(g=k)}const b=new Map;for(const _ of o)b.set(_.name,_);let v=0,x=0;for(const _ of c){const k=C1(_.rule.condition,b);k>x&&(x=k)}return{warnings:n,metrics:{sourceSize:t.length,functionCount:o.length,allowRuleCount:c.length,maxChainDepth:d.depth,maxChainOp:d.op,maxLetBindings:f.count,maxLetBindingsFunction:f.fn,maxCallDepth:g,maxEstimatedExpressions:v,getCallCount:x}}}class it{constructor(e){G(this,"items");this.items=new Set(e)}hasOnly(e){const n=e instanceof it?e.toArray():e;for(const r of this.items)if(!n.includes(r))return!1;return!0}equals(e){if(!(e instanceof it)||e.items.size!==this.items.size)return!1;for(const n of this.items)if(!e.items.has(n))return!1;return!0}hasAll(e){const n=e instanceof it?e.toArray():e;for(const r of n)if(!this.items.has(r))return!1;return!0}hasAny(e){const n=e instanceof it?e.toArray():e;for(const r of n)if(this.items.has(r))return!0;return!1}size(){return this.items.size}toArray(){return[...this.items]}difference(e){const n=new Set(e instanceof it?e.toArray():e),r=[];for(const s of this.items)n.has(s)||r.push(s);return new it(r)}union(e){const n=e instanceof it?e.toArray():e,r=new Set(this.items);for(const s of n)r.add(s);return new it(r)}intersection(e){const n=new Set(e instanceof it?e.toArray():e),r=[];for(const s of this.items)n.has(s)&&r.push(s);return new it(r)}}const ht=Symbol.for("pyric.RulesValue.NO_OP");class Qe{field(e){return null}callMethod(e,n){return ht}binaryOp(e,n){return ht}}function Zn(t,e){if(Object.is(t,e))return!0;if(t instanceof Qe)return t.equals(e);if(e instanceof Qe)return e.equals(t);if(t instanceof it||e instanceof it)return t instanceof it&&t.equals(e);if(Array.isArray(t)||Array.isArray(e))return!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length?!1:t.every((s,o)=>Zn(s,e[o]));if(!sw(t)||!sw(e))return!1;const n=Object.keys(t),r=Object.keys(e);return n.length!==r.length?!1:n.every(s=>s in e&&Zn(t[s],e[s]))}function sw(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}class bl{constructor(e,n){G(this,"before");G(this,"after");this.before=e,this.after=n}addedKeys(){const e=[];for(const n of Object.keys(this.after))n in this.before||e.push(n);return new it(e)}removedKeys(){const e=[];for(const n of Object.keys(this.before))n in this.after||e.push(n);return new it(e)}changedKeys(){const e=[];for(const n of Object.keys(this.after))n in this.before&&!Zn(this.before[n],this.after[n])&&e.push(n);return new it(e)}affectedKeys(){const e=[],n=new Set([...Object.keys(this.before),...Object.keys(this.after)]);for(const r of n)(!(r in this.before)||!(r in this.after)||!Zn(this.before[r],this.after[r]))&&e.push(r);return new it(e)}unchangedKeys(){const e=[];for(const n of Object.keys(this.before))n in this.after&&Zn(this.before[n],this.after[n])&&e.push(n);return new it(e)}}function hT(t,e,n,r){const o=v=>v*Math.PI/180,c=o(t),d=o(n),f=o(n-t),p=o(r-e),g=Math.sin(f/2)**2+Math.cos(c)*Math.cos(d)*Math.sin(p/2)**2;return 6371e3*(2*Math.atan2(Math.sqrt(g),Math.sqrt(1-g)))}class jr extends Qe{constructor(n,r){super();G(this,"typeName","latlng");G(this,"lat");G(this,"lng");this.lat=n,this.lng=r}valueOf(){return NaN}toString(){return`${this.lat},${this.lng}`}toJSON(){return{__type:"latlng",lat:this.lat,lng:this.lng}}equals(n){return n instanceof jr&&this.lat===n.lat&&this.lng===n.lng}callMethod(n,r){switch(n){case"latitude":return this.lat;case"longitude":return this.lng;case"distance":{const s=r[0];if(!(s instanceof jr))throw new TypeError(`latlng.distance() requires a LatLng argument, got ${typeof s}`);return hT(this.lat,this.lng,s.lat,s.lng)}default:return ht}}}const Fa=1e9,iw={w:10080*60,d:1440*60,h:3600,m:60,s:1};function pT(t,e){let n=t+Math.trunc(e/Fa),r=e%Fa;return n>0&&r<0?(n-=1,r+=Fa):n<0&&r>0&&(n+=1,r-=Fa),{seconds:n,nanos:r}}class Dt extends Qe{constructor(n,r){super();G(this,"typeName","duration");G(this,"seconds");G(this,"nanos");const s=pT(n,r);this.seconds=s.seconds,this.nanos=s.nanos}static fromValue(n,r){if(r in iw)return new Dt(n*iw[r],0);if(r==="ms"){const s=Math.trunc(n/1e3),o=n-s*1e3;return new Dt(s,o*1e6)}if(r==="ns"){const s=Math.trunc(n/Fa),o=n-s*Fa;return new Dt(s,o)}throw new Error(`Unknown duration unit '${r}' (expected one of: w, d, h, m, s, ms, ns)`)}static fromTime(n,r,s,o){return new Dt(n*3600+r*60+s,o)}static abs(n){return new Dt(Math.abs(n.seconds),Math.abs(n.nanos))}valueOf(){return this.seconds*1e3+Math.round(this.nanos/1e6)}toString(){const n=this.seconds<0||this.nanos<0,r=Math.abs(this.seconds),s=Math.abs(this.nanos);return`${n?"-":""}${r}.${s.toString().padStart(9,"0")}s`}toJSON(){return{__type:"duration",seconds:this.seconds,nanos:this.nanos}}equals(n){return n instanceof Dt&&this.seconds===n.seconds&&this.nanos===n.nanos}callMethod(n,r){switch(n){case"seconds":return this.seconds;case"nanos":return this.nanos;default:return ht}}binaryOp(n,r){if(!(r instanceof Dt))return ht;switch(n){case"+":return new Dt(this.seconds+r.seconds,this.nanos+r.nanos);case"-":return new Dt(this.seconds-r.seconds,this.nanos-r.nanos);case"<":return this.compareTo(r)<0;case"<=":return this.compareTo(r)<=0;case">":return this.compareTo(r)>0;case">=":return this.compareTo(r)>=0;default:return ht}}compareTo(n){return this.seconds!==n.seconds?this.seconds-n.seconds:this.nanos-n.nanos}}const aw=1e9,mT=864e5,kp=86400;function yT(t,e){const n=Math.floor(e/aw);return{seconds:t+n,nanos:e-n*aw}}let Nt=class Jr extends Qe{constructor(n,r){super();G(this,"typeName","timestamp");G(this,"seconds");G(this,"nanos");const s=yT(n,r);this.seconds=s.seconds,this.nanos=s.nanos}static fromMillis(n){const r=Math.floor(n/1e3),s=n-r*1e3;return new Jr(r,s*1e6)}static fromYMD(n,r,s){return Jr.fromMillis(Date.UTC(n,r-1,s))}static fromIsoString(n){return Jr.fromMillis(Date.parse(n))}toMillis(){return this.seconds*1e3+Math.floor(this.nanos/1e6)}toDate(){return new Date(this.toMillis())}valueOf(){return this.toMillis()}toString(){const n=new Date(this.toMillis()).toISOString(),r=this.nanos.toString().padStart(9,"0");return n.replace(/\.\d{3}Z$/,`.${r}Z`)}toJSON(){return{__type:"timestamp",seconds:this.seconds,nanos:this.nanos}}equals(n){return n instanceof Jr&&this.seconds===n.seconds&&this.nanos===n.nanos}callMethod(n,r){switch(n){case"seconds":return this.seconds;case"nanos":return this.nanos;case"toMillis":return this.toMillis();case"year":return this.asDate().getUTCFullYear();case"month":return this.asDate().getUTCMonth()+1;case"day":return this.asDate().getUTCDate();case"hours":return this.asDate().getUTCHours();case"minutes":return this.asDate().getUTCMinutes();case"dayOfWeek":{const s=this.asDate().getUTCDay();return s===0?7:s}case"dayOfYear":{const s=this.asDate(),o=Date.UTC(s.getUTCFullYear(),0,1);return Math.floor((this.toMillis()-o)/mT)+1}case"date":return Jr.fromYMD(this.asDate().getUTCFullYear(),this.asDate().getUTCMonth()+1,this.asDate().getUTCDate());case"time":{const s=(this.seconds%kp+kp)%kp,o=Math.floor(s/3600),c=Math.floor(s%3600/60),d=s%60;return Dt.fromTime(o,c,d,this.nanos)}default:return ht}}asDate(){return new Date(this.toMillis())}binaryOp(n,r){if(r instanceof Jr)switch(n){case"-":return new Dt(this.seconds-r.seconds,this.nanos-r.nanos);case"<":return this.compareTo(r)<0;case"<=":return this.compareTo(r)<=0;case">":return this.compareTo(r)>0;case">=":return this.compareTo(r)>=0;default:return ht}if(r instanceof Dt)switch(n){case"+":return new Jr(this.seconds+r.seconds,this.nanos+r.nanos);case"-":return new Jr(this.seconds-r.seconds,this.nanos-r.nanos);default:return ht}return ht}compareTo(n){return this.seconds!==n.seconds?this.seconds-n.seconds:this.nanos-n.nanos}};const ow="0123456789abcdef";function gT(t){let e="";for(let n=0;n<t.length;n++){const r=t[n];e+=ow[r>>>4]+ow[r&15]}return e}function bT(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function vT(t,e){const n=Math.min(t.length,e.length);for(let r=0;r<n;r++)if(t[r]!==e[r])return t[r]<e[r]?-1:1;return t.length===e.length?0:t.length<e.length?-1:1}let Tn=class hl extends Qe{constructor(n){super();G(this,"typeName","bytes");G(this,"data");this.data=n}static fromUtf8(n){return new hl(new TextEncoder().encode(n))}static fromHex(n){if(n.length%2!==0)throw new Error(`Invalid hex string length: ${n.length}`);const r=new Uint8Array(n.length/2);for(let s=0;s<r.length;s++)r[s]=parseInt(n.substr(s*2,2),16);return new hl(r)}size(){return this.data.length}toBase64(){return bT(this.data)}toHexString(){return gT(this.data)}valueOf(){return this.data.length}toString(){return this.toBase64()}toJSON(){return{__type:"bytes",base64:this.toBase64()}}equals(n){if(!(n instanceof hl)||this.data.length!==n.data.length)return!1;for(let r=0;r<this.data.length;r++)if(this.data[r]!==n.data[r])return!1;return!0}callMethod(n,r){switch(n){case"size":return this.size();case"toBase64":return this.toBase64();case"toHexString":return this.toHexString()}return ht}binaryOp(n,r){if(!(r instanceof hl))return ht;const s=vT(this.data,r.data);switch(n){case"<":return s<0;case"<=":return s<=0;case">":return s>0;case">=":return s>=0}return ht}};const xT=/^\{([A-Za-z_][A-Za-z0-9_]*)\}$/;class lr extends Qe{constructor(n,r={}){super();G(this,"typeName","path");G(this,"segments");G(this,"bindings");this.segments=n,this.bindings=r}static fromString(n){const r=n.startsWith("/")?n.slice(1):n;return r.length===0?new lr([]):new lr(r.split("/"))}bind(n){const r=[],s={...this.bindings};for(const o of this.segments){const c=o.match(xT);if(!c){r.push(o);continue}const d=c[1];if(d in n){const f=n[d];if(f==null)throw new TypeError(`Path.bind(): binding '${d}' must not be null`);const p=String(f);r.push(p),s[d]=p}else r.push(o)}return new lr(r,s)}valueOf(){return NaN}toString(){return"/"+this.segments.join("/")}toJSON(){return{__type:"path",segments:[...this.segments]}}equals(n){if(!(n instanceof lr)||this.segments.length!==n.segments.length)return!1;for(let r=0;r<this.segments.length;r++)if(this.segments[r]!==n.segments[r])return!1;return!0}field(n){if(/^\d+$/.test(n)){const r=Number(n);return r<0||r>=this.segments.length?null:this.segments[r]}return n in this.bindings?this.bindings[n]:null}callMethod(n,r){switch(n){case"bind":{const s=r[0];if(s==null||typeof s!="object"||Array.isArray(s)||s instanceof Qe)throw new TypeError(`Path.bind() requires a Map argument, got ${s===null?"null":typeof s}`);return this.bind(s)}default:return ht}}}class At extends Qe{constructor(n){super();G(this,"typeName","float");G(this,"value");this.value=n}valueOf(){return this.value}toString(){return Number.isInteger(this.value)?`${this.value}.0`:String(this.value)}toJSON(){return{__type:"float",value:this.value}}equals(n){return n instanceof At?this.value===n.value:typeof n=="number"?this.value===n:!1}binaryOp(n,r){const s=r instanceof At?r.value:typeof r=="number"?r:void 0;if(s===void 0)return ht;const o=this.value;switch(n){case"+":return new At(o+s);case"-":return new At(o-s);case"*":return new At(o*s);case"/":return new At(o/s);case"%":return new At(o%s);case"<":return o<s;case"<=":return o<=s;case">":return o>s;case">=":return o>=s;default:return ht}}}var Cp={exports:{}};const wT={},ST=Object.freeze(Object.defineProperty({__proto__:null,default:wT},Symbol.toStringTag,{value:"Module"})),qu=NN(ST);/**
|
|
513
|
-
* [js-md5]{@link https://github.com/emn178/js-md5}
|
|
514
|
-
*
|
|
515
|
-
* @namespace md5
|
|
516
|
-
* @version 0.8.3
|
|
517
|
-
* @author Chen, Yi-Cyuan [emn178@gmail.com]
|
|
518
|
-
* @copyright Chen, Yi-Cyuan 2014-2023
|
|
519
|
-
* @license MIT
|
|
520
|
-
*/var lw;function _T(){return lw||(lw=1,(function(t){(function(){var e="input is invalid type",n="finalize already called",r=typeof window=="object",s=r?window:{};s.JS_MD5_NO_WINDOW&&(r=!1);var o=!r&&typeof self=="object",c=!s.JS_MD5_NO_NODE_JS&&typeof process=="object"&&process.versions&&process.versions.node;c?s=H_:o&&(s=self);var d=!s.JS_MD5_NO_COMMON_JS&&!0&&t.exports,f=!s.JS_MD5_NO_ARRAY_BUFFER&&typeof ArrayBuffer<"u",p="0123456789abcdef".split(""),g=[128,32768,8388608,-2147483648],b=[0,8,16,24],v=["hex","array","digest","buffer","arrayBuffer","base64"],x="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),_=[],k;if(f){var R=new ArrayBuffer(68);k=new Uint8Array(R),_=new Uint32Array(R)}var C=Array.isArray;(s.JS_MD5_NO_NODE_JS||!C)&&(C=function(w){return Object.prototype.toString.call(w)==="[object Array]"});var T=ArrayBuffer.isView;f&&(s.JS_MD5_NO_ARRAY_BUFFER_IS_VIEW||!T)&&(T=function(w){return typeof w=="object"&&w.buffer&&w.buffer.constructor===ArrayBuffer});var U=function(w){var E=typeof w;if(E==="string")return[w,!0];if(E!=="object"||w===null)throw new Error(e);if(f&&w.constructor===ArrayBuffer)return[new Uint8Array(w),!1];if(!C(w)&&!T(w))throw new Error(e);return[w,!1]},q=function(w){return function(E){return new H(!0).update(E)[w]()}},I=function(){var w=q("hex");c&&(w=N(w)),w.create=function(){return new H},w.update=function(D){return w.create().update(D)};for(var E=0;E<v.length;++E){var O=v[E];w[O]=q(O)}return w},N=function(w){var E=qu,O=qu.Buffer,D;O.from&&!s.JS_MD5_NO_BUFFER_FROM?D=O.from:D=function($){return new O($)};var z=function($){if(typeof $=="string")return E.createHash("md5").update($,"utf8").digest("hex");if($==null)throw new Error(e);return $.constructor===ArrayBuffer&&($=new Uint8Array($)),C($)||T($)||$.constructor===O?E.createHash("md5").update(D($)).digest("hex"):w($)};return z},M=function(w){return function(E,O){return new P(E,!0).update(O)[w]()}},L=function(){var w=M("hex");w.create=function(D){return new P(D)},w.update=function(D,z){return w.create(D).update(z)};for(var E=0;E<v.length;++E){var O=v[E];w[O]=M(O)}return w};function H(w){if(w)_[0]=_[16]=_[1]=_[2]=_[3]=_[4]=_[5]=_[6]=_[7]=_[8]=_[9]=_[10]=_[11]=_[12]=_[13]=_[14]=_[15]=0,this.blocks=_,this.buffer8=k;else if(f){var E=new ArrayBuffer(68);this.buffer8=new Uint8Array(E),this.blocks=new Uint32Array(E)}else this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];this.h0=this.h1=this.h2=this.h3=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0}H.prototype.update=function(w){if(this.finalized)throw new Error(n);var E=U(w);w=E[0];for(var O=E[1],D,z=0,$,K=w.length,W=this.blocks,se=this.buffer8;z<K;){if(this.hashed&&(this.hashed=!1,W[0]=W[16],W[16]=W[1]=W[2]=W[3]=W[4]=W[5]=W[6]=W[7]=W[8]=W[9]=W[10]=W[11]=W[12]=W[13]=W[14]=W[15]=0),O)if(f)for($=this.start;z<K&&$<64;++z)D=w.charCodeAt(z),D<128?se[$++]=D:D<2048?(se[$++]=192|D>>>6,se[$++]=128|D&63):D<55296||D>=57344?(se[$++]=224|D>>>12,se[$++]=128|D>>>6&63,se[$++]=128|D&63):(D=65536+((D&1023)<<10|w.charCodeAt(++z)&1023),se[$++]=240|D>>>18,se[$++]=128|D>>>12&63,se[$++]=128|D>>>6&63,se[$++]=128|D&63);else for($=this.start;z<K&&$<64;++z)D=w.charCodeAt(z),D<128?W[$>>>2]|=D<<b[$++&3]:D<2048?(W[$>>>2]|=(192|D>>>6)<<b[$++&3],W[$>>>2]|=(128|D&63)<<b[$++&3]):D<55296||D>=57344?(W[$>>>2]|=(224|D>>>12)<<b[$++&3],W[$>>>2]|=(128|D>>>6&63)<<b[$++&3],W[$>>>2]|=(128|D&63)<<b[$++&3]):(D=65536+((D&1023)<<10|w.charCodeAt(++z)&1023),W[$>>>2]|=(240|D>>>18)<<b[$++&3],W[$>>>2]|=(128|D>>>12&63)<<b[$++&3],W[$>>>2]|=(128|D>>>6&63)<<b[$++&3],W[$>>>2]|=(128|D&63)<<b[$++&3]);else if(f)for($=this.start;z<K&&$<64;++z)se[$++]=w[z];else for($=this.start;z<K&&$<64;++z)W[$>>>2]|=w[z]<<b[$++&3];this.lastByteIndex=$,this.bytes+=$-this.start,$>=64?(this.start=$-64,this.hash(),this.hashed=!0):this.start=$}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this},H.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var w=this.blocks,E=this.lastByteIndex;w[E>>>2]|=g[E&3],E>=56&&(this.hashed||this.hash(),w[0]=w[16],w[16]=w[1]=w[2]=w[3]=w[4]=w[5]=w[6]=w[7]=w[8]=w[9]=w[10]=w[11]=w[12]=w[13]=w[14]=w[15]=0),w[14]=this.bytes<<3,w[15]=this.hBytes<<3|this.bytes>>>29,this.hash()}},H.prototype.hash=function(){var w,E,O,D,z,$,K=this.blocks;this.first?(w=K[0]-680876937,w=(w<<7|w>>>25)-271733879<<0,D=(-1732584194^w&2004318071)+K[1]-117830708,D=(D<<12|D>>>20)+w<<0,O=(-271733879^D&(w^-271733879))+K[2]-1126478375,O=(O<<17|O>>>15)+D<<0,E=(w^O&(D^w))+K[3]-1316259209,E=(E<<22|E>>>10)+O<<0):(w=this.h0,E=this.h1,O=this.h2,D=this.h3,w+=(D^E&(O^D))+K[0]-680876936,w=(w<<7|w>>>25)+E<<0,D+=(O^w&(E^O))+K[1]-389564586,D=(D<<12|D>>>20)+w<<0,O+=(E^D&(w^E))+K[2]+606105819,O=(O<<17|O>>>15)+D<<0,E+=(w^O&(D^w))+K[3]-1044525330,E=(E<<22|E>>>10)+O<<0),w+=(D^E&(O^D))+K[4]-176418897,w=(w<<7|w>>>25)+E<<0,D+=(O^w&(E^O))+K[5]+1200080426,D=(D<<12|D>>>20)+w<<0,O+=(E^D&(w^E))+K[6]-1473231341,O=(O<<17|O>>>15)+D<<0,E+=(w^O&(D^w))+K[7]-45705983,E=(E<<22|E>>>10)+O<<0,w+=(D^E&(O^D))+K[8]+1770035416,w=(w<<7|w>>>25)+E<<0,D+=(O^w&(E^O))+K[9]-1958414417,D=(D<<12|D>>>20)+w<<0,O+=(E^D&(w^E))+K[10]-42063,O=(O<<17|O>>>15)+D<<0,E+=(w^O&(D^w))+K[11]-1990404162,E=(E<<22|E>>>10)+O<<0,w+=(D^E&(O^D))+K[12]+1804603682,w=(w<<7|w>>>25)+E<<0,D+=(O^w&(E^O))+K[13]-40341101,D=(D<<12|D>>>20)+w<<0,O+=(E^D&(w^E))+K[14]-1502002290,O=(O<<17|O>>>15)+D<<0,E+=(w^O&(D^w))+K[15]+1236535329,E=(E<<22|E>>>10)+O<<0,w+=(O^D&(E^O))+K[1]-165796510,w=(w<<5|w>>>27)+E<<0,D+=(E^O&(w^E))+K[6]-1069501632,D=(D<<9|D>>>23)+w<<0,O+=(w^E&(D^w))+K[11]+643717713,O=(O<<14|O>>>18)+D<<0,E+=(D^w&(O^D))+K[0]-373897302,E=(E<<20|E>>>12)+O<<0,w+=(O^D&(E^O))+K[5]-701558691,w=(w<<5|w>>>27)+E<<0,D+=(E^O&(w^E))+K[10]+38016083,D=(D<<9|D>>>23)+w<<0,O+=(w^E&(D^w))+K[15]-660478335,O=(O<<14|O>>>18)+D<<0,E+=(D^w&(O^D))+K[4]-405537848,E=(E<<20|E>>>12)+O<<0,w+=(O^D&(E^O))+K[9]+568446438,w=(w<<5|w>>>27)+E<<0,D+=(E^O&(w^E))+K[14]-1019803690,D=(D<<9|D>>>23)+w<<0,O+=(w^E&(D^w))+K[3]-187363961,O=(O<<14|O>>>18)+D<<0,E+=(D^w&(O^D))+K[8]+1163531501,E=(E<<20|E>>>12)+O<<0,w+=(O^D&(E^O))+K[13]-1444681467,w=(w<<5|w>>>27)+E<<0,D+=(E^O&(w^E))+K[2]-51403784,D=(D<<9|D>>>23)+w<<0,O+=(w^E&(D^w))+K[7]+1735328473,O=(O<<14|O>>>18)+D<<0,E+=(D^w&(O^D))+K[12]-1926607734,E=(E<<20|E>>>12)+O<<0,z=E^O,w+=(z^D)+K[5]-378558,w=(w<<4|w>>>28)+E<<0,D+=(z^w)+K[8]-2022574463,D=(D<<11|D>>>21)+w<<0,$=D^w,O+=($^E)+K[11]+1839030562,O=(O<<16|O>>>16)+D<<0,E+=($^O)+K[14]-35309556,E=(E<<23|E>>>9)+O<<0,z=E^O,w+=(z^D)+K[1]-1530992060,w=(w<<4|w>>>28)+E<<0,D+=(z^w)+K[4]+1272893353,D=(D<<11|D>>>21)+w<<0,$=D^w,O+=($^E)+K[7]-155497632,O=(O<<16|O>>>16)+D<<0,E+=($^O)+K[10]-1094730640,E=(E<<23|E>>>9)+O<<0,z=E^O,w+=(z^D)+K[13]+681279174,w=(w<<4|w>>>28)+E<<0,D+=(z^w)+K[0]-358537222,D=(D<<11|D>>>21)+w<<0,$=D^w,O+=($^E)+K[3]-722521979,O=(O<<16|O>>>16)+D<<0,E+=($^O)+K[6]+76029189,E=(E<<23|E>>>9)+O<<0,z=E^O,w+=(z^D)+K[9]-640364487,w=(w<<4|w>>>28)+E<<0,D+=(z^w)+K[12]-421815835,D=(D<<11|D>>>21)+w<<0,$=D^w,O+=($^E)+K[15]+530742520,O=(O<<16|O>>>16)+D<<0,E+=($^O)+K[2]-995338651,E=(E<<23|E>>>9)+O<<0,w+=(O^(E|~D))+K[0]-198630844,w=(w<<6|w>>>26)+E<<0,D+=(E^(w|~O))+K[7]+1126891415,D=(D<<10|D>>>22)+w<<0,O+=(w^(D|~E))+K[14]-1416354905,O=(O<<15|O>>>17)+D<<0,E+=(D^(O|~w))+K[5]-57434055,E=(E<<21|E>>>11)+O<<0,w+=(O^(E|~D))+K[12]+1700485571,w=(w<<6|w>>>26)+E<<0,D+=(E^(w|~O))+K[3]-1894986606,D=(D<<10|D>>>22)+w<<0,O+=(w^(D|~E))+K[10]-1051523,O=(O<<15|O>>>17)+D<<0,E+=(D^(O|~w))+K[1]-2054922799,E=(E<<21|E>>>11)+O<<0,w+=(O^(E|~D))+K[8]+1873313359,w=(w<<6|w>>>26)+E<<0,D+=(E^(w|~O))+K[15]-30611744,D=(D<<10|D>>>22)+w<<0,O+=(w^(D|~E))+K[6]-1560198380,O=(O<<15|O>>>17)+D<<0,E+=(D^(O|~w))+K[13]+1309151649,E=(E<<21|E>>>11)+O<<0,w+=(O^(E|~D))+K[4]-145523070,w=(w<<6|w>>>26)+E<<0,D+=(E^(w|~O))+K[11]-1120210379,D=(D<<10|D>>>22)+w<<0,O+=(w^(D|~E))+K[2]+718787259,O=(O<<15|O>>>17)+D<<0,E+=(D^(O|~w))+K[9]-343485551,E=(E<<21|E>>>11)+O<<0,this.first?(this.h0=w+1732584193<<0,this.h1=E-271733879<<0,this.h2=O-1732584194<<0,this.h3=D+271733878<<0,this.first=!1):(this.h0=this.h0+w<<0,this.h1=this.h1+E<<0,this.h2=this.h2+O<<0,this.h3=this.h3+D<<0)},H.prototype.hex=function(){this.finalize();var w=this.h0,E=this.h1,O=this.h2,D=this.h3;return p[w>>>4&15]+p[w&15]+p[w>>>12&15]+p[w>>>8&15]+p[w>>>20&15]+p[w>>>16&15]+p[w>>>28&15]+p[w>>>24&15]+p[E>>>4&15]+p[E&15]+p[E>>>12&15]+p[E>>>8&15]+p[E>>>20&15]+p[E>>>16&15]+p[E>>>28&15]+p[E>>>24&15]+p[O>>>4&15]+p[O&15]+p[O>>>12&15]+p[O>>>8&15]+p[O>>>20&15]+p[O>>>16&15]+p[O>>>28&15]+p[O>>>24&15]+p[D>>>4&15]+p[D&15]+p[D>>>12&15]+p[D>>>8&15]+p[D>>>20&15]+p[D>>>16&15]+p[D>>>28&15]+p[D>>>24&15]},H.prototype.toString=H.prototype.hex,H.prototype.digest=function(){this.finalize();var w=this.h0,E=this.h1,O=this.h2,D=this.h3;return[w&255,w>>>8&255,w>>>16&255,w>>>24&255,E&255,E>>>8&255,E>>>16&255,E>>>24&255,O&255,O>>>8&255,O>>>16&255,O>>>24&255,D&255,D>>>8&255,D>>>16&255,D>>>24&255]},H.prototype.array=H.prototype.digest,H.prototype.arrayBuffer=function(){this.finalize();var w=new ArrayBuffer(16),E=new Uint32Array(w);return E[0]=this.h0,E[1]=this.h1,E[2]=this.h2,E[3]=this.h3,w},H.prototype.buffer=H.prototype.arrayBuffer,H.prototype.base64=function(){for(var w,E,O,D="",z=this.array(),$=0;$<15;)w=z[$++],E=z[$++],O=z[$++],D+=x[w>>>2]+x[(w<<4|E>>>4)&63]+x[(E<<2|O>>>6)&63]+x[O&63];return w=z[$],D+=x[w>>>2]+x[w<<4&63]+"==",D};function P(w,E){var O,D=U(w);if(w=D[0],D[1]){var z=[],$=w.length,K=0,W;for(O=0;O<$;++O)W=w.charCodeAt(O),W<128?z[K++]=W:W<2048?(z[K++]=192|W>>>6,z[K++]=128|W&63):W<55296||W>=57344?(z[K++]=224|W>>>12,z[K++]=128|W>>>6&63,z[K++]=128|W&63):(W=65536+((W&1023)<<10|w.charCodeAt(++O)&1023),z[K++]=240|W>>>18,z[K++]=128|W>>>12&63,z[K++]=128|W>>>6&63,z[K++]=128|W&63);w=z}w.length>64&&(w=new H(!0).update(w).array());var se=[],B=[];for(O=0;O<64;++O){var ee=w[O]||0;se[O]=92^ee,B[O]=54^ee}H.call(this,E),this.update(B),this.oKeyPad=se,this.inner=!0,this.sharedMemory=E}P.prototype=new H,P.prototype.finalize=function(){if(H.prototype.finalize.call(this),this.inner){this.inner=!1;var w=this.array();H.call(this,this.sharedMemory),this.update(this.oKeyPad),this.update(w),H.prototype.finalize.call(this)}};var F=I();F.md5=F,F.md5.hmac=L(),d?t.exports=F:s.md5=F})()})(Cp)),Cp.exports}var ET=_T(),Np={exports:{}};/**
|
|
521
|
-
* [js-sha256]{@link https://github.com/emn178/js-sha256}
|
|
522
|
-
*
|
|
523
|
-
* @version 0.11.1
|
|
524
|
-
* @author Chen, Yi-Cyuan [emn178@gmail.com]
|
|
525
|
-
* @copyright Chen, Yi-Cyuan 2014-2025
|
|
526
|
-
* @license MIT
|
|
527
|
-
*/var cw;function AT(){return cw||(cw=1,(function(t){(function(){var e="input is invalid type",n=typeof window=="object",r=n?window:{};r.JS_SHA256_NO_WINDOW&&(n=!1);var s=!n&&typeof self=="object",o=!r.JS_SHA256_NO_NODE_JS&&typeof process=="object"&&process.versions&&process.versions.node&&process.type!="renderer";o?r=H_:s&&(r=self);var c=!r.JS_SHA256_NO_COMMON_JS&&!0&&t.exports,d=!r.JS_SHA256_NO_ARRAY_BUFFER&&typeof ArrayBuffer<"u",f="0123456789abcdef".split(""),p=[-2147483648,8388608,32768,128],g=[24,16,8,0],b=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],v=["hex","array","digest","arrayBuffer"],x=[];(r.JS_SHA256_NO_NODE_JS||!Array.isArray)&&(Array.isArray=function(N){return Object.prototype.toString.call(N)==="[object Array]"}),d&&(r.JS_SHA256_NO_ARRAY_BUFFER_IS_VIEW||!ArrayBuffer.isView)&&(ArrayBuffer.isView=function(N){return typeof N=="object"&&N.buffer&&N.buffer.constructor===ArrayBuffer});var _=function(N,M){return function(L){return new U(M,!0).update(L)[N]()}},k=function(N){var M=_("hex",N);o&&(M=R(M,N)),M.create=function(){return new U(N)},M.update=function(P){return M.create().update(P)};for(var L=0;L<v.length;++L){var H=v[L];M[H]=_(H,N)}return M},R=function(N,M){var L=qu,H=qu.Buffer,P=M?"sha224":"sha256",F;H.from&&!r.JS_SHA256_NO_BUFFER_FROM?F=H.from:F=function(E){return new H(E)};var w=function(E){if(typeof E=="string")return L.createHash(P).update(E,"utf8").digest("hex");if(E==null)throw new Error(e);return E.constructor===ArrayBuffer&&(E=new Uint8Array(E)),Array.isArray(E)||ArrayBuffer.isView(E)||E.constructor===H?L.createHash(P).update(F(E)).digest("hex"):N(E)};return w},C=function(N,M){return function(L,H){return new q(L,M,!0).update(H)[N]()}},T=function(N){var M=C("hex",N);M.create=function(P){return new q(P,N)},M.update=function(P,F){return M.create(P).update(F)};for(var L=0;L<v.length;++L){var H=v[L];M[H]=C(H,N)}return M};function U(N,M){M?(x[0]=x[16]=x[1]=x[2]=x[3]=x[4]=x[5]=x[6]=x[7]=x[8]=x[9]=x[10]=x[11]=x[12]=x[13]=x[14]=x[15]=0,this.blocks=x):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],N?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=N}U.prototype.update=function(N){if(!this.finalized){var M,L=typeof N;if(L!=="string"){if(L==="object"){if(N===null)throw new Error(e);if(d&&N.constructor===ArrayBuffer)N=new Uint8Array(N);else if(!Array.isArray(N)&&(!d||!ArrayBuffer.isView(N)))throw new Error(e)}else throw new Error(e);M=!0}for(var H,P=0,F,w=N.length,E=this.blocks;P<w;){if(this.hashed&&(this.hashed=!1,E[0]=this.block,this.block=E[16]=E[1]=E[2]=E[3]=E[4]=E[5]=E[6]=E[7]=E[8]=E[9]=E[10]=E[11]=E[12]=E[13]=E[14]=E[15]=0),M)for(F=this.start;P<w&&F<64;++P)E[F>>>2]|=N[P]<<g[F++&3];else for(F=this.start;P<w&&F<64;++P)H=N.charCodeAt(P),H<128?E[F>>>2]|=H<<g[F++&3]:H<2048?(E[F>>>2]|=(192|H>>>6)<<g[F++&3],E[F>>>2]|=(128|H&63)<<g[F++&3]):H<55296||H>=57344?(E[F>>>2]|=(224|H>>>12)<<g[F++&3],E[F>>>2]|=(128|H>>>6&63)<<g[F++&3],E[F>>>2]|=(128|H&63)<<g[F++&3]):(H=65536+((H&1023)<<10|N.charCodeAt(++P)&1023),E[F>>>2]|=(240|H>>>18)<<g[F++&3],E[F>>>2]|=(128|H>>>12&63)<<g[F++&3],E[F>>>2]|=(128|H>>>6&63)<<g[F++&3],E[F>>>2]|=(128|H&63)<<g[F++&3]);this.lastByteIndex=F,this.bytes+=F-this.start,F>=64?(this.block=E[16],this.start=F-64,this.hash(),this.hashed=!0):this.start=F}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}},U.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var N=this.blocks,M=this.lastByteIndex;N[16]=this.block,N[M>>>2]|=p[M&3],this.block=N[16],M>=56&&(this.hashed||this.hash(),N[0]=this.block,N[16]=N[1]=N[2]=N[3]=N[4]=N[5]=N[6]=N[7]=N[8]=N[9]=N[10]=N[11]=N[12]=N[13]=N[14]=N[15]=0),N[14]=this.hBytes<<3|this.bytes>>>29,N[15]=this.bytes<<3,this.hash()}},U.prototype.hash=function(){var N=this.h0,M=this.h1,L=this.h2,H=this.h3,P=this.h4,F=this.h5,w=this.h6,E=this.h7,O=this.blocks,D,z,$,K,W,se,B,ee,ae,le,ye;for(D=16;D<64;++D)W=O[D-15],z=(W>>>7|W<<25)^(W>>>18|W<<14)^W>>>3,W=O[D-2],$=(W>>>17|W<<15)^(W>>>19|W<<13)^W>>>10,O[D]=O[D-16]+z+O[D-7]+$<<0;for(ye=M&L,D=0;D<64;D+=4)this.first?(this.is224?(ee=300032,W=O[0]-1413257819,E=W-150054599<<0,H=W+24177077<<0):(ee=704751109,W=O[0]-210244248,E=W-1521486534<<0,H=W+143694565<<0),this.first=!1):(z=(N>>>2|N<<30)^(N>>>13|N<<19)^(N>>>22|N<<10),$=(P>>>6|P<<26)^(P>>>11|P<<21)^(P>>>25|P<<7),ee=N&M,K=ee^N&L^ye,B=P&F^~P&w,W=E+$+B+b[D]+O[D],se=z+K,E=H+W<<0,H=W+se<<0),z=(H>>>2|H<<30)^(H>>>13|H<<19)^(H>>>22|H<<10),$=(E>>>6|E<<26)^(E>>>11|E<<21)^(E>>>25|E<<7),ae=H&N,K=ae^H&M^ee,B=E&P^~E&F,W=w+$+B+b[D+1]+O[D+1],se=z+K,w=L+W<<0,L=W+se<<0,z=(L>>>2|L<<30)^(L>>>13|L<<19)^(L>>>22|L<<10),$=(w>>>6|w<<26)^(w>>>11|w<<21)^(w>>>25|w<<7),le=L&H,K=le^L&N^ae,B=w&E^~w&P,W=F+$+B+b[D+2]+O[D+2],se=z+K,F=M+W<<0,M=W+se<<0,z=(M>>>2|M<<30)^(M>>>13|M<<19)^(M>>>22|M<<10),$=(F>>>6|F<<26)^(F>>>11|F<<21)^(F>>>25|F<<7),ye=M&L,K=ye^M&H^le,B=F&w^~F&E,W=P+$+B+b[D+3]+O[D+3],se=z+K,P=N+W<<0,N=W+se<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+N<<0,this.h1=this.h1+M<<0,this.h2=this.h2+L<<0,this.h3=this.h3+H<<0,this.h4=this.h4+P<<0,this.h5=this.h5+F<<0,this.h6=this.h6+w<<0,this.h7=this.h7+E<<0},U.prototype.hex=function(){this.finalize();var N=this.h0,M=this.h1,L=this.h2,H=this.h3,P=this.h4,F=this.h5,w=this.h6,E=this.h7,O=f[N>>>28&15]+f[N>>>24&15]+f[N>>>20&15]+f[N>>>16&15]+f[N>>>12&15]+f[N>>>8&15]+f[N>>>4&15]+f[N&15]+f[M>>>28&15]+f[M>>>24&15]+f[M>>>20&15]+f[M>>>16&15]+f[M>>>12&15]+f[M>>>8&15]+f[M>>>4&15]+f[M&15]+f[L>>>28&15]+f[L>>>24&15]+f[L>>>20&15]+f[L>>>16&15]+f[L>>>12&15]+f[L>>>8&15]+f[L>>>4&15]+f[L&15]+f[H>>>28&15]+f[H>>>24&15]+f[H>>>20&15]+f[H>>>16&15]+f[H>>>12&15]+f[H>>>8&15]+f[H>>>4&15]+f[H&15]+f[P>>>28&15]+f[P>>>24&15]+f[P>>>20&15]+f[P>>>16&15]+f[P>>>12&15]+f[P>>>8&15]+f[P>>>4&15]+f[P&15]+f[F>>>28&15]+f[F>>>24&15]+f[F>>>20&15]+f[F>>>16&15]+f[F>>>12&15]+f[F>>>8&15]+f[F>>>4&15]+f[F&15]+f[w>>>28&15]+f[w>>>24&15]+f[w>>>20&15]+f[w>>>16&15]+f[w>>>12&15]+f[w>>>8&15]+f[w>>>4&15]+f[w&15];return this.is224||(O+=f[E>>>28&15]+f[E>>>24&15]+f[E>>>20&15]+f[E>>>16&15]+f[E>>>12&15]+f[E>>>8&15]+f[E>>>4&15]+f[E&15]),O},U.prototype.toString=U.prototype.hex,U.prototype.digest=function(){this.finalize();var N=this.h0,M=this.h1,L=this.h2,H=this.h3,P=this.h4,F=this.h5,w=this.h6,E=this.h7,O=[N>>>24&255,N>>>16&255,N>>>8&255,N&255,M>>>24&255,M>>>16&255,M>>>8&255,M&255,L>>>24&255,L>>>16&255,L>>>8&255,L&255,H>>>24&255,H>>>16&255,H>>>8&255,H&255,P>>>24&255,P>>>16&255,P>>>8&255,P&255,F>>>24&255,F>>>16&255,F>>>8&255,F&255,w>>>24&255,w>>>16&255,w>>>8&255,w&255];return this.is224||O.push(E>>>24&255,E>>>16&255,E>>>8&255,E&255),O},U.prototype.array=U.prototype.digest,U.prototype.arrayBuffer=function(){this.finalize();var N=new ArrayBuffer(this.is224?28:32),M=new DataView(N);return M.setUint32(0,this.h0),M.setUint32(4,this.h1),M.setUint32(8,this.h2),M.setUint32(12,this.h3),M.setUint32(16,this.h4),M.setUint32(20,this.h5),M.setUint32(24,this.h6),this.is224||M.setUint32(28,this.h7),N};function q(N,M,L){var H,P=typeof N;if(P==="string"){var F=[],w=N.length,E=0,O;for(H=0;H<w;++H)O=N.charCodeAt(H),O<128?F[E++]=O:O<2048?(F[E++]=192|O>>>6,F[E++]=128|O&63):O<55296||O>=57344?(F[E++]=224|O>>>12,F[E++]=128|O>>>6&63,F[E++]=128|O&63):(O=65536+((O&1023)<<10|N.charCodeAt(++H)&1023),F[E++]=240|O>>>18,F[E++]=128|O>>>12&63,F[E++]=128|O>>>6&63,F[E++]=128|O&63);N=F}else if(P==="object"){if(N===null)throw new Error(e);if(d&&N.constructor===ArrayBuffer)N=new Uint8Array(N);else if(!Array.isArray(N)&&(!d||!ArrayBuffer.isView(N)))throw new Error(e)}else throw new Error(e);N.length>64&&(N=new U(M,!0).update(N).array());var D=[],z=[];for(H=0;H<64;++H){var $=N[H]||0;D[H]=92^$,z[H]=54^$}U.call(this,M,L),this.update(z),this.oKeyPad=D,this.inner=!0,this.sharedMemory=L}q.prototype=new U,q.prototype.finalize=function(){if(U.prototype.finalize.call(this),this.inner){this.inner=!1;var N=this.array();U.call(this,this.is224,this.sharedMemory),this.update(this.oKeyPad),this.update(N),U.prototype.finalize.call(this)}};var I=k();I.sha256=I,I.sha224=k(!0),I.sha256.hmac=T(),I.sha224.hmac=T(!0),c?t.exports=I:(r.sha256=I.sha256,r.sha224=I.sha224)})()})(Np)),Np.exports}var jT=AT();let Ie=class extends Error{constructor(n,r){super(n);G(this,"expr");this.expr=r,this.name="EvalError"}};class Wn extends Ie{constructor(e,n){super(e,n),this.name="UnsupportedError"}}class kT{constructor(){G(this,"entries",[]);G(this,"parents",[]);G(this,"frames",[])}capture(e,n){const r=this.entries.length,s=this.parents.length>0?this.parents[this.parents.length-1]:null,o={source:Ft(e),kind:e.type,parent:s};this.stampFrame(o),this.entries.push(o),this.parents.push(r);try{const c=n();return this.entries[r].value=c,c}catch(c){throw this.entries[r].error=c instanceof Error?c.message:String(c),c}finally{this.parents.pop()}}skip(e){const n=this.parents.length>0?this.parents[this.parents.length-1]:null,r={source:Ft(e),kind:e.type,parent:n,skipped:!0};this.stampFrame(r),this.entries.push(r)}enterFrame(e){this.frames.push(e)}exitFrame(){this.frames.pop()}stampFrame(e){this.frames.length!==0&&(e.inlinedFrom={name:this.frames[this.frames.length-1]})}markEntryAsLetBinding(e,n){e<0||e>=this.entries.length||(this.entries[e].letBinding={name:n})}}function _e(t,e,n={}){return e.trace?e.trace.capture(t,()=>uw(t,e,n)):uw(t,e,n)}function uw(t,e,n){switch(t.type){case"literal":return typeof t.value=="number"&&t.raw.includes(".")?new At(t.value):t.value;case"identifier":return CT(t.name,e,n);case"binaryOp":return OT(t.op,t.left,t.right,e,n);case"unaryOp":{if(t.op==="!")return!_e(t.operand,e,n);if(t.op==="-"){const r=_e(t.operand,e,n);return r instanceof At?new At(-r.value):-r}throw new Ie(`Unknown unary op: ${t.op}`,t)}case"ternary":{const r=_e(t.condition,e,n);return _e(r?t.consequent:t.alternate,e,n)}case"memberAccess":{const r=_e(t.object,e,n);if(r==null)throw new Ie(`Property '${t.property}' accessed on ${r===null?"null":"undefined"} value`,t);if(r instanceof Qe)return r.field(t.property);if(r instanceof bl)switch(t.property){case"addedKeys":return()=>r.addedKeys();case"removedKeys":return()=>r.removedKeys();case"changedKeys":return()=>r.changedKeys();case"affectedKeys":return()=>r.affectedKeys();case"unchangedKeys":return()=>r.unchangedKeys()}if(r instanceof it)switch(t.property){case"size":return()=>r.size()}if(Object.hasOwn(r,t.property))return r[t.property];throw new Ie(`No field '${t.property}' on map (use 'in' or .get() to read a possibly-absent field)`,t)}case"bracketAccess":{const r=_e(t.object,e,n),s=_e(t.index,e,n);if(r==null)throw new Ie(`Index access on ${r===null?"null":"undefined"} value`,t);if(r instanceof Qe)return r.field(String(s));const o=String(s);return Object.hasOwn(r,o)?r[o]:null}case"sliceAccess":{const r=_e(t.object,e,n),s=_e(t.start,e,n),o=_e(t.end,e,n);if(r==null)return null;if(typeof s!="number"||!Number.isInteger(s))throw new Ie(`Slice start must be an integer, got ${typeof s}`);if(typeof o!="number"||!Number.isInteger(o))throw new Ie(`Slice end must be an integer, got ${typeof o}`);if(s<0||o<0)throw new Ie(`Slice indices must be non-negative, got [${s}:${o}]`);if(typeof r=="string"||Array.isArray(r))return r.slice(s,o);throw new Ie(`Slice not supported on ${typeof r}`)}case"inExpr":{const r=_e(t.element,e,n),s=_e(t.collection,e,n);return s==null?!1:Array.isArray(s)?s.some(o=>Zn(o,r)):typeof s=="object"?Object.hasOwn(s,String(r)):!1}case"isExpr":{const r=_e(t.value,e,n);switch(t.typeName){case"string":return typeof r=="string";case"int":return r instanceof Qe?!1:typeof r=="number";case"float":return r instanceof At;case"number":return r instanceof At?!0:r instanceof Qe?!1:typeof r=="number";case"bool":return typeof r=="boolean";case"null":return r===null;case"list":return Array.isArray(r);case"map":return r instanceof Qe||r instanceof bl||r instanceof it?!1:typeof r=="object"&&r!==null&&!Array.isArray(r);default:return r instanceof Qe?r.typeName===t.typeName:!1}}case"listLiteral":return t.elements.map(r=>_e(r,e,n));case"mapLiteral":{const r={};for(const s of t.entries){const o=String(_e(s.key,e,n));r[o]=_e(s.value,e,n)}return r}case"functionCall":return IT(t.name,t.args,e,n);case"methodCall":return MT(t.object,t.method,t.args,e,n);case"pathLiteral":{const r=[];for(const s of t.segments)typeof s=="string"?r.push(s):r.push(String(_e(s,e,n)));return new lr(r)}default:throw new Ie(`Unknown expression type: ${t.type}`,t)}}function CT(t,e,n){if(t in n)return n[t];if(t in e.pathVariables)return e.pathVariables[t];switch(t){case"request":return e.request;case"resource":if(e.resource===null)throw new Ie("Null value error.");return e.resource;case"true":return!0;case"false":return!1;case"null":return null}throw new Ie(`Undefined variable '${t}'`)}function NT(t){return t==="request"||t==="resource"||t==="true"||t==="false"||t==="null"}function OT(t,e,n,r,s){var d,f;if(t==="&&"){let p,g;try{p=_e(e,r,s)}catch(x){g=x}if(g===void 0&&!p)return(d=r.trace)==null||d.skip(n),!1;let b,v;try{b=_e(n,r,s)}catch(x){v=x}if(v===void 0&&!b)return!1;if(g!==void 0)throw g;if(v!==void 0)throw v;return!!b}if(t==="||"){let p,g;try{p=_e(e,r,s)}catch(x){g=x}if(g===void 0&&p)return(f=r.trace)==null||f.skip(n),!0;let b,v;try{b=_e(n,r,s)}catch(x){v=x}if(v===void 0&&b)return!0;if(g!==void 0)throw g;if(v!==void 0)throw v;return!!b}const o=_e(e,r,s),c=_e(n,r,s);if(t!=="=="&&t!=="!="){if(o instanceof Qe){const p=o.binaryOp(t,c);if(p!==ht)return p}if(typeof o=="number"&&c instanceof At){const p=new At(o).binaryOp(t,c);if(p!==ht)return p}if(c instanceof Qe&&(t==="+"||t==="*")){const p=c.binaryOp(t,o);if(p!==ht)return p}if((t!=="+"||typeof o!="string"&&typeof c!="string")&&(o instanceof Qe||c instanceof Qe)){const p=o instanceof Qe?o.typeName:typeof o,g=c instanceof Qe?c.typeName:typeof c;throw new Ie(`Operator '${t}' is not defined between ${p} and ${g}`)}}if((t==="<"||t===">"||t==="<="||t===">=")&&!(typeof o=="number"&&typeof c=="number"||typeof o=="string"&&typeof c=="string"))throw new Ie(`Operator '${t}' is not defined between ${typeof o} and ${typeof c}`);switch(t){case"==":return o===c||Zn(o,c);case"!=":return!(o===c||Zn(o,c));case"<":return o<c;case">":return o>c;case"<=":return o<=c;case">=":return o>=c;case"+":{if(Array.isArray(o)&&Array.isArray(c))return[...o,...c];if(typeof o=="string"&&typeof c=="string"||typeof o=="number"&&typeof c=="number")return o+c;if(typeof o=="string"&&c instanceof Qe)return o+String(c);throw new Ie(`Operator '+' is not defined between ${Array.isArray(o)?"list":typeof o} and ${Array.isArray(c)?"list":typeof c}`)}case"-":return o-c;case"*":return o*c;case"/":if(c===0)throw new Ie("Division by zero");return Math.trunc(o/c);case"%":if(c===0)throw new Ie("Modulo by zero");return o%c;default:throw new Ie(`Unknown binary op: ${t}`)}}function TT(t){if(typeof t=="number")return Math.trunc(t);if(t instanceof At)return Math.trunc(t.value);if(typeof t=="boolean")return t?1:0;if(typeof t=="string"){if(/^[+-]?\d+$/.test(t.trim()))return parseInt(t.trim(),10);throw new Ie(`int() cannot convert string '${t}' to an integer`)}throw new Ie(`int() cannot convert ${typeof t} to an integer`)}function RT(t){if(t instanceof At)return t;if(typeof t=="number")return new At(t);if(typeof t=="string"){const e=t.trim();if(/^[+-]?(\d+\.?\d*|\.\d+)$/.test(e))return new At(parseFloat(e));throw new Ie(`float() cannot convert string '${t}' to a float`)}throw new Ie(`float() cannot convert ${typeof t} to a float`)}function DT(t){if(typeof t=="boolean")return t;if(typeof t=="string"){if(t==="true")return!0;if(t==="false")return!1;throw new Ie(`bool() cannot convert string '${t}' to a boolean`)}throw new Ie(`bool() cannot convert ${typeof t} to a boolean`)}function IT(t,e,n,r){var c,d,f,p,g;switch(t){case"get":{const b=String(_e(e[0],n,r));return hw(b,n)}case"exists":{const b=String(_e(e[0],n,r));return pw(b,n)}case"getAfter":{const b=_e(e[0],n,r),v=String(b);if(v===n.afterStatePath.toString()){if(n.afterState===null)throw new Ie(`getAfter() of non-existent document '${v}' (guard with existsAfter() first)`);return gm(vl(v),n.afterState)}const x=vl(v);if((c=n.batchProjection)!=null&&c.has(x)){const _=n.batchProjection.get(x);if(_===null)throw new Ie(`getAfter() of non-existent document '${v}' (guard with existsAfter() first)`);return gm(x,_)}return hw(v,n)}case"existsAfter":{const b=_e(e[0],n,r),v=String(b);if(v===n.afterStatePath.toString())return n.existsAfter;const x=vl(v);return(d=n.batchProjection)!=null&&d.has(x)?n.batchProjection.get(x)!==null:pw(v,n)}case"debug":return _e(e[0],n,r);case"string":return String(_e(e[0],n,r));case"int":return TT(_e(e[0],n,r));case"float":return RT(_e(e[0],n,r));case"bool":return DT(_e(e[0],n,r));case"path":{const b=_e(e[0],n,r);if(b instanceof lr)return b;if(typeof b=="string")return lr.fromString(b);throw new Ie(`path() requires a string argument, got ${typeof b}`)}}const s=n.functions.get(t);if(!s)throw new Wn(`Unknown function: ${t}`);const o={...r};for(let b=0;b<s.parameters.length;b++)o[s.parameters[b]]=_e(e[b],n,r);(f=n.trace)==null||f.enterFrame(t);try{for(const b of s.lets){const v=n.trace?n.trace.entries.length:-1;o[b.name]=_e(b.value,n,o),v>=0&&((p=n.trace)==null||p.markEntryAsLetBinding(v,b.name))}return _e(s.body,n,o)}finally{(g=n.trace)==null||g.exitFrame()}}function MT(t,e,n,r,s){if(t.type==="identifier"){const d=t.name;if(dw(d)&&!(d in s)&&!(d in r.pathVariables)){const f=n.map(p=>_e(p,r,s));return UT(d,e,f)}if(!dw(d)&&!(d in s)&&!(d in r.pathVariables)&&!NT(d))throw new Wn(`Unknown namespace or method '${d}.${e}()'`)}const o=_e(t,r,s),c=n.map(d=>_e(d,r,s));if(o instanceof Qe){const d=o.callMethod(e,c);if(d===ht)throw new Wn(`Unknown method '${e}' on ${o.typeName}`);return d}if(e==="diff"&&typeof o=="object"&&o!==null&&!Array.isArray(o)){const d=c[0];if(typeof d=="object"&&d!==null)return new bl(d,o);throw new Ie("diff() requires a map argument")}if(typeof o=="function")return o(...c);if(o instanceof it)switch(e){case"hasOnly":return o.hasOnly(c[0]);case"hasAll":return o.hasAll(c[0]);case"hasAny":return o.hasAny(c[0]);case"size":return o.size();case"difference":case"union":case"intersection":throw new Wn(`Set.${e}() is not faithfully modeled by the simulator (oracle capture shows production denies calls that reach it) — abstaining rather than guessing`)}if(o instanceof bl)switch(e){case"addedKeys":return o.addedKeys();case"removedKeys":return o.removedKeys();case"changedKeys":return o.changedKeys();case"affectedKeys":return o.affectedKeys();case"unchangedKeys":return o.unchangedKeys()}if(typeof o=="object"&&o!==null&&!Array.isArray(o)){const d=o;switch(e){case"keys":return new it(Object.keys(d));case"values":return Object.values(d);case"size":return Object.keys(d).length;case"hasAll":return c[0].every(f=>Object.hasOwn(d,f));case"hasAny":return c[0].some(f=>Object.hasOwn(d,f));case"hasOnly":return Object.keys(d).every(f=>c[0].includes(f));case"diff":{const f=c[0];return new bl(f,d)}case"get":{const f=c[0],p=c[1];if(Array.isArray(f)){let b=d;for(const v of f){if(b==null||typeof b!="object"||Array.isArray(b)||b instanceof Qe)return p;const x=String(v);if(!Object.hasOwn(b,x))return p;b=b[x]}return b}const g=String(f);return Object.hasOwn(d,g)?d[g]:p}}}if(Array.isArray(o))switch(e){case"size":return o.length;case"hasAll":return c[0].every(d=>o.some(f=>Zn(f,d)));case"hasAny":return c[0].some(d=>o.some(f=>Zn(f,d)));case"hasOnly":{const d=c[0];return o.every(f=>d.some(p=>Zn(p,f)))}case"join":return o.join(String(c[0]??","));case"concat":{const d=c[0];if(!Array.isArray(d))throw new Ie(`List.concat requires a list argument, got ${typeof d}`);return[...o,...d]}case"removeAll":{const d=c[0];if(!Array.isArray(d))throw new Ie(`List.removeAll requires a list argument, got ${typeof d}`);return o.filter(f=>!d.some(p=>Zn(f,p)))}case"toSet":return new it(o.map(d=>String(d)))}if(typeof o=="string")switch(e){case"size":return o.length;case"lower":return o.toLowerCase();case"upper":return o.toUpperCase();case"trim":return o.trim();case"split":return o.split(Op(String(c[0]),"g"));case"matches":return Op(`^(?:${String(c[0])})$`).test(o);case"replace":return o.replace(Op(String(c[0]),"g"),String(c[1]));case"toUtf8":return Tn.fromUtf8(o)}throw new Wn(`Unknown method '${e}' on ${typeof o}`)}function Op(t,e=""){try{return new RegExp(t,e)}catch(n){throw new Ie(`Invalid regex '${t}': ${n.message}`)}}const LT=new Set(["math","timestamp","duration","latlng","hashing"]);function dw(t){return LT.has(t)}function UT(t,e,n){const r=t==="hashing"?n:n.map($T);switch(t){case"math":return GT(e,r);case"timestamp":return KT(e,r);case"duration":return YT(e,r);case"latlng":return HT(e,r);case"hashing":return FT(e,n)}throw new Wn(`Unknown namespace '${t}'`)}function $T(t){return t instanceof At?t.value:t}function BT(t){if(t instanceof Tn)return t;if(typeof t=="string")return Tn.fromUtf8(t);throw new Ie(`hashing.* requires Bytes or String, got ${typeof t}`)}function FT(t,e){const n=BT(e[0]);switch(t){case"md5":return new Tn(new Uint8Array(ET.md5.arrayBuffer(n.data)));case"sha256":return new Tn(new Uint8Array(jT.sha256.arrayBuffer(n.data)));case"crc32":{const r=qT(n.data);return new Tn(fw(r))}case"crc32c":{const r=VT(n.data);return new Tn(fw(r))}}throw new Wn(`Unknown hashing method '${t}'`)}function fw(t){return new Uint8Array([t>>>24&255,t>>>16&255,t>>>8&255,t&255])}const PT=(()=>{const t=new Uint32Array(256);for(let e=0;e<256;e++){let n=e;for(let r=0;r<8;r++)n=n&1?3988292384^n>>>1:n>>>1;t[e]=n>>>0}return t})();function qT(t){let e=4294967295;for(let n=0;n<t.length;n++)e=PT[(e^t[n])&255]^e>>>8;return(e^4294967295)>>>0}const zT=(()=>{const t=new Uint32Array(256);for(let e=0;e<256;e++){let n=e;for(let r=0;r<8;r++)n=n&1?2197175160^n>>>1:n>>>1;t[e]=n>>>0}return t})();function VT(t){let e=4294967295;for(let n=0;n<t.length;n++)e=zT[(e^t[n])&255]^e>>>8;return(e^4294967295)>>>0}function HT(t,e){switch(t){case"value":{const[n,r]=e;return new jr(n,r)}}throw new Wn(`Unknown latlng method '${t}'`)}function GT(t,e){switch(t){case"abs":return Math.abs(e[0]);case"ceil":return Math.ceil(e[0]);case"floor":return Math.floor(e[0]);case"round":return Math.round(e[0]);case"sqrt":return Math.sqrt(e[0]);case"pow":return Math.pow(e[0],e[1]);case"isInfinite":{const n=e[0];return Number.isFinite(n)===!1&&Number.isNaN(n)===!1}case"isNaN":return Number.isNaN(e[0])}throw new Wn(`Unknown math method '${t}'`)}function KT(t,e){switch(t){case"date":{const[n,r,s]=e;return Nt.fromYMD(n,r,s)}case"value":return Nt.fromMillis(e[0])}throw new Wn(`Unknown timestamp method '${t}'`)}function YT(t,e){switch(t){case"value":try{return Dt.fromValue(e[0],e[1])}catch(n){throw new Ie(n.message)}case"time":{const[n,r,s,o]=e;return Dt.fromTime(n,r,s,o)}case"abs":{const n=e[0];if(!(n instanceof Dt))throw new Ie(`duration.abs() requires a Duration argument, got ${typeof n}`);return Dt.abs(n)}}throw new Wn(`Unknown duration method '${t}'`)}function vl(t,e){return t.replace(/\$\(database\)/g,"(default)").replace(/^\/databases\/\(default\)\/documents\//,"")}function gm(t,e){const n=t.split("/").filter(Boolean),r=n.length>0?n[n.length-1]:"",s=["databases","(default)","documents",...n];return{data:e,id:r,__name__:new lr(s)}}function hw(t,e){const n=vl(t);let r=e.mockDocuments.get(n);if(!r&&e.getDoc){const s=e.getDoc(n);s&&(e.mockDocuments.set(n,s),r=s)}if(r)return gm(n,r);throw new Ie(`get() of non-existent document '${n}' (guard with exists() first)`)}function pw(t,e){const n=vl(t);if(e.mockDocuments.has(n))return!0;if(e.getDoc){const r=e.getDoc(n);if(r)return e.mockDocuments.set(n,r),!0}return!1}const ZT=new Set(["__proto__","prototype","constructor"]);function zu(t){if(ZT.has(t))throw new Error(`Invalid field-path segment '${t}': the keys __proto__, prototype, and constructor are reserved and cannot appear in a field path.`)}function I1(t,e){const n={...t};for(const[r,s]of Object.entries(e)){zu(r);const o=Object.hasOwn(n,r)?n[r]:void 0;s!==null&&typeof s=="object"&&!Array.isArray(s)&&o!==null&&typeof o=="object"&&!Array.isArray(o)?n[r]=I1(o,s):n[r]=s}return n}function WT(t,e,n){let r=t;for(let o=0;o<e.length-1;o++){const c=e[o];zu(c);const d=Object.hasOwn(r,c)?r[c]:void 0;(d===null||typeof d!="object"||Array.isArray(d))&&(r[c]={}),r=r[c]}const s=e[e.length-1];zu(s),r[s]=n}function JT(t,e){const n={...t};for(const[r,s]of Object.entries(e))r.includes(".")?WT(n,r.split("."),s):(zu(r),n[r]=s);return n}function QT(t,e,n){switch(t.kind){case"create":return n;case"set":return t.merge?I1(e??{},n):n;case"update":return JT(e??{},n);case"delete":return null}}class XT{constructor(){G(this,"attempts",[])}push(e){this.attempts.push(e)}}function Ou(t){return"/"+t.path.segments.map(n=>n.type==="literal"?n.value:n.type==="wildcard"?`{${n.name}}`:`{${n.name}=**}`).join("/")}function bm(t,e,n,r){const s=[...n,...t.functions],o=t.path.segments,c={};let d=0,f;for(const b of o)if(b.type==="literal"){if(d>=e.length){f="request-shorter";break}if(e[d]!==b.value){f="literal-mismatch";break}d++}else if(b.type==="wildcard"){if(d>=e.length){f="request-shorter";break}c[b.name]=e[d],d++}else b.type==="recursive"&&(c[b.name]=e.slice(d).join("/"),d=e.length);if(f!==void 0)return r==null||r.push({...t.loc?{line:t.loc.line}:{},blockPath:Ou(t),matchedSegments:d,totalSegments:o.length,bindings:c,matched:!1,reason:f}),[];const p=e.slice(d);if(p.length===0)return r==null||r.push({...t.loc?{line:t.loc.line}:{},blockPath:Ou(t),matchedSegments:d,totalSegments:o.length,bindings:c,matched:!0}),[{block:t,pathVariables:c,parentFunctions:s}];const g=[];for(const b of t.children)for(const v of bm(b,p,s,r))v.pathVariables={...c,...v.pathVariables},g.push(v);return r==null||r.push({...t.loc?{line:t.loc.line}:{},blockPath:Ou(t),matchedSegments:d,totalSegments:o.length,bindings:c,...g.length>0?{matched:!0}:{matched:!1,reason:"no-matching-child"}}),g}function eR(t){switch(t){case"get":return["get","read"];case"list":return["list","read"];case"create":return["create","write"];case"update":return["update","write"];case"delete":return["delete","write"];default:return[t]}}function tR(t,e,n){const r=eR(e),s=[],o=[],c=[];for(let p=0;p<t.allows.length;p++){const g=t.allows[p];g.operations.some(b=>r.includes(b))&&c.push({rule:g,index:p})}if(c.length===0)return o.push(`No allow rules found for operation '${e}'`),{decision:"DENY",trace:s,notes:o};let d=!1;const f=n.trace;for(const{rule:p,index:g}of c){const b=nR(p,g),v=new kT;n.trace=v;try{const x=_e(p.condition,n);if(b.expressionTrace=v.entries,x)return b.verdict="ALLOW",s.push(b),n.trace=f,{decision:"ALLOW",trace:s,notes:o};b.verdict="DENY",s.push(b)}catch(x){b.expressionTrace=v.entries,x instanceof Wn?(d=!0,b.verdict="UNSUPPORTED",b.message=x.message):(b.verdict="ERROR",b.message=x instanceof Error?x.message:String(x)),s.push(b)}}return n.trace=f,{decision:d?"UNSUPPORTED":"DENY",trace:s,notes:o}}function nR(t,e){const n={ruleIndex:e,operations:[...t.operations],verdict:"DENY",conditionText:Ft(t.condition)};return t.loc&&(n.line=t.loc.line),n}function rR(t){return typeof t=="object"&&t!==null&&t.__type==="serverTimestamp"}function M1(t,e){const n={};for(const[r,s]of Object.entries(t))rR(s)?n[r]=e:sR(s)?n[r]=M1(s,e):n[r]=s;return n}function sR(t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function iR(t){var e,n,r;return t.method!=="list"?{}:{limit:((e=t.query)==null?void 0:e.limit)??null,offset:((n=t.query)==null?void 0:n.offset)??null,orderBy:((r=t.query)==null?void 0:r.orderBy)??null}}function aR(t,e,n,r,s){const o=new Map;for(const C of e)o.set(C.name,C);const c=new Map;if(t.functionMocks)for(const C of t.functionMocks)C.function==="get"&&typeof C.result=="object"&&C.result!==null?c.set(C.path,C.result):C.function==="exists"&&C.result===!0&&c.set(C.path,{});const d=t.requestTime?Nt.fromIsoString(t.requestTime):Nt.fromMillis(Date.now()),p=["databases","(default)","documents",...(t.path.startsWith("/")?t.path.slice(1):t.path).split("/").filter(Boolean)],g=new lr(p,n),b=t.data??{},v=t.resource??null;let x,_;if(t.writeMode)x=QT(t.writeMode,v,b),_=x!==null;else switch(t.method){case"create":case"update":x=b,_=!0;break;case"delete":x=null,_=!1;break;case"get":case"list":default:x=v,_=v!==null;break}const k=x!==null?M1(x,d):null,R=k??{};return{request:{auth:t.auth?{uid:t.auth.uid,token:t.auth.token??{}}:null,resource:{data:R},method:t.method,path:g,query:iR(t),time:d},resource:t.method==="create"||v===null?null:{data:v},mockDocuments:c,getDoc:r,pathVariables:n,functions:o,database:"(default)",afterStatePath:g,afterState:k,existsAfter:_,...s?{batchProjection:s}:{}}}class oR{simulate(e,n,r){if(!e||e.trim().length===0)return{success:!1,error:{code:"PARSE_FAILED",message:"Empty rules source — call setRules(sandbox, rules) from pyric/sandbox/firestore before operating, or initialize without rules to use the open-by-default ruleset. See pyric/sandbox docs.",recoverable:!0}};const s=$y(e);if(!s)return{success:!1,error:{code:"PARSE_FAILED",message:"Failed to parse rules source",recoverable:!0}};const o=[];let c=0,d=0,f=0;const p={database:"(default)"};for(const g of s.service.match.path.segments)g.type==="wildcard"&&(p[g.name]="(default)");for(const g of n){const b=g.path.split("/").filter(Boolean),v=s.service.match.functions;let x=[];const _=new XT;for(const M of s.service.match.children)x.push(...bm(M,b,v,_));let k=!1;if(x.length===0&&g.method==="list"){const M=[...b,"__hypothetical_doc__"];for(const L of s.service.match.children)x.push(...bm(L,M,v,_));x.length>0&&(k=!0)}const R={requestPath:g.path,attempts:_.attempts};if(x.length===0){const M=g.expectation==="DENY"?"PASSED":"FAILED";M==="PASSED"?c++:d++,o.push({description:g.description,expectation:g.expectation,state:M,decision:"DENY",trace:[],notes:[`No match block found for path '${g.path}'`],pathResolution:R});continue}let C="DENY";const T=[],U=[];let q=!1,I;for(const M of x){const L=[...M.parentFunctions,...M.block.functions],H={...p,...M.pathVariables},P=aR(g,L,H,r==null?void 0:r.getDoc,r==null?void 0:r.batchProjection),F=Ou(M.block),w=tR(M.block,g.method,P);for(const E of w.trace)E.matchPath=F;if(T.push(...w.trace),U.push(...w.notes),w.decision==="ALLOW"){C="ALLOW",I=F;break}w.decision==="UNSUPPORTED"&&(q=!0)}C!=="ALLOW"&&q&&(C="UNSUPPORTED"),C==="ALLOW"&&I&&U.push(`Allowed by match block '${I}'`),k&&U.push(`list on collection path '${g.path}' evaluated against the document-level match block (document wildcard hypothetical, resource undefined) — emulator-faithful`);let N;C==="UNSUPPORTED"?(N="UNSUPPORTED",f++):C===g.expectation?(N="PASSED",c++):(N="FAILED",d++),o.push({description:g.description,expectation:g.expectation,state:N,decision:C,trace:T,notes:U,pathResolution:R})}return{success:!0,data:{passed:c,failed:d,unsupported:f,results:o}}}}const Ni={maxExpressionLength:256,maxStringLiteralLength:1024,maxAstDepth:16},lR=["serverTimestamp","increment","arrayUnion","arrayRemove","deleteField"],cR={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 uR(t){return lR.includes(t)}class jt extends Error{constructor(n,r){super(n);G(this,"code","invalid-argument");G(this,"pos");this.name="ExpressionLexError",this.pos=r}}class vr extends Error{constructor(n,r){super(n);G(this,"code","invalid-argument");G(this,"pos");this.name="ExpressionParseError",this.pos=r}}const dR={"(":"lparen",")":"rparen","[":"lbracket","]":"rbracket",",":"comma",".":"dot","?":"question",":":"colon","+":"plus","-":"minus","*":"star","/":"slash","%":"percent"},fR={true:"true",false:"false",null:"null"};function hR(t){if(t.length>Ni.maxExpressionLength)throw new jt(`expression exceeds ${Ni.maxExpressionLength}-character cap (got ${t.length})`,Me(Ni.maxExpressionLength));const e=[];let n=0;for(;n<t.length;){const r=n,s=t[n];if(s===" "||s===" "||s==="\r"||s===`
|
|
528
|
-
`){n+=1;continue}if(s==='"'||s==="'"){const{token:c,next:d}=yR(t,n,s);if(e.push(c),n=d,n<=r)throw new jt("lexer stalled on string",Me(r));continue}if(s>="0"&&s<="9"){const{token:c,next:d}=mR(t,n);if(e.push(c),n=d,n<=r)throw new jt("lexer stalled on number",Me(r));continue}if(jd(s)){const{token:c,next:d}=pR(t,n);e.push(c),n=d;continue}if(s==="$"){const{token:c,next:d}=mw(t,n,"$","reference");e.push(c),n=d;continue}if(s==="@"){const{token:c,next:d}=mw(t,n,"@","sentinel");e.push(c),n=d;continue}if(s==="="&&t[n+1]==="="){e.push({kind:"eq",pos:Me(n)}),n+=2;continue}if(s==="!"&&t[n+1]==="="){e.push({kind:"neq",pos:Me(n)}),n+=2;continue}if(s==="<"){t[n+1]==="="?(e.push({kind:"lte",pos:Me(n)}),n+=2):(e.push({kind:"lt",pos:Me(n)}),n+=1);continue}if(s===">"){t[n+1]==="="?(e.push({kind:"gte",pos:Me(n)}),n+=2):(e.push({kind:"gt",pos:Me(n)}),n+=1);continue}if(s==="&"){if(t[n+1]!=="&")throw new jt("unexpected '&' (did you mean '&&'?)",Me(n));e.push({kind:"and",pos:Me(n)}),n+=2;continue}if(s==="|"){if(t[n+1]!=="|")throw new jt("unexpected '|' (did you mean '||'?)",Me(n));e.push({kind:"or",pos:Me(n)}),n+=2;continue}if(s==="!"){e.push({kind:"bang",pos:Me(n)}),n+=1;continue}if(s==="=")throw new jt("unexpected '=' (did you mean '=='?)",Me(n));const o=dR[s];if(o){e.push({kind:o,pos:Me(n)}),n+=1;continue}throw new jt(`unexpected character ${JSON.stringify(s)}`,Me(n))}return e.push({kind:"eof",pos:Me(t.length)}),e}function Me(t){return{offset:t,column:t+1}}function jd(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"}function L1(t){return jd(t)||t>="0"&&t<="9"}function pR(t,e){let n=e+1;for(;n<t.length&&L1(t[n]);)n+=1;const r=t.slice(e,n),s=fR[r];return s?{token:{kind:s,pos:Me(e)},next:n}:{token:{kind:"identifier",pos:Me(e),value:r},next:n}}function mw(t,e,n,r){const s=e+1;if(s>=t.length||!jd(t[s]))throw new jt(`expected identifier after '${n}'`,Me(e));let o=s+1;for(;o<t.length&&L1(t[o]);)o+=1;const c=t.slice(s,o);return{token:{kind:r,pos:Me(e),value:c},next:o}}function mR(t,e){let n=e;const r=t[n];if(n+=1,r==="0"){if(n<t.length&&t[n]>="0"&&t[n]<="9")throw new jt("leading zeros are not allowed in number literals",Me(e))}else for(;n<t.length&&t[n]>="0"&&t[n]<="9";)n+=1;let s=!1;if(n<t.length&&t[n]==="."){const d=t[n+1];if(d!==void 0&&d>="0"&&d<="9")for(s=!0,n+=1;n<t.length&&t[n]>="0"&&t[n]<="9";)n+=1;else if(!(d!==void 0&&jd(d)))throw new jt("expected digit after '.' in number literal",Me(n))}const o=t.slice(e,n),c=Number.parseFloat(o);if(!Number.isFinite(c))throw new jt(`numeric literal '${o}' is not finite`,Me(e));if(!s&&!Number.isSafeInteger(c))throw new jt(`integer literal '${o}' exceeds safe integer range`,Me(e));return{token:{kind:"number",pos:Me(e),value:c},next:n}}function yR(t,e,n){let r=e+1,s="";for(;r<t.length;){const o=t[r];if(o===n)return{token:{kind:"string",pos:Me(e),value:s},next:r+1};if(o==="\\"){const c=t[r+1];if(c===void 0)throw new jt("unterminated escape sequence in string literal",Me(r));switch(c){case'"':s+='"';break;case"'":s+="'";break;case"\\":s+="\\";break;case"n":s+=`
|
|
529
|
-
`;break;case"t":s+=" ";break;default:throw new jt(`invalid escape sequence '\\${c}' (only \\", \\', \\\\, \\n, \\t are allowed)`,Me(r))}r+=2}else{if(o===`
|
|
530
|
-
`||o==="\r")throw new jt("unterminated string literal (newline before closing quote)",Me(e));s+=o,r+=1}if(s.length>Ni.maxStringLiteralLength)throw new jt(`string literal exceeds ${Ni.maxStringLiteralLength}-character cap`,Me(e))}throw new jt("unterminated string literal",Me(e))}function gR(t){const e=new bR(t),n=e.parseExpression();return e.expect("eof","unexpected trailing tokens"),wR(n),n}let bR=class{constructor(e){G(this,"tokens");G(this,"cursor",0);this.tokens=e}parseExpression(){return this.parseTernary()}parseTernary(){const e=this.parseLogicalOr();if(this.peek().kind!=="question")return e;const n=this.consume(),r=this.parseExpression();this.expect("colon","expected ':' in ternary");const s=this.parseExpression();return{kind:"ternary",cond:e,whenTrue:r,whenFalse:s,pos:n.pos}}parseLogicalOr(){let e=this.parseLogicalAnd();for(;this.peek().kind==="or";){const n=this.consume(),r=this.parseLogicalAnd();e={kind:"logical",op:"||",left:e,right:r,pos:n.pos}}return e}parseLogicalAnd(){let e=this.parseComparison();for(;this.peek().kind==="and";){const n=this.consume(),r=this.parseComparison();e={kind:"logical",op:"&&",left:e,right:r,pos:n.pos}}return e}parseComparison(){let e=this.parseSum();for(;;){const n=vR(this.peek().kind);if(!n)break;const r=this.consume(),s=this.parseSum();e={kind:"binary",op:n,left:e,right:s,pos:r.pos}}return e}parseSum(){let e=this.parseProduct();for(;;){const n=this.peek().kind;if(n!=="plus"&&n!=="minus")break;const r=this.consume(),s=this.parseProduct();e={kind:"binary",op:n==="plus"?"+":"-",left:e,right:s,pos:r.pos}}return e}parseProduct(){let e=this.parseUnary();for(;;){const n=this.peek().kind;if(n!=="star"&&n!=="slash"&&n!=="percent")break;const r=this.consume(),s=this.parseUnary();e={kind:"binary",op:n==="star"?"*":n==="slash"?"/":"%",left:e,right:s,pos:r.pos}}return e}parseUnary(){const e=this.peek().kind;if(e==="minus"||e==="bang"){const n=this.consume(),r=this.parseUnary();return{kind:"unary",op:e==="minus"?"-":"!",operand:r,pos:n.pos}}return this.parsePostfix()}parsePostfix(){let e=this.parsePrimary();for(;;){const n=this.peek().kind;if(n==="dot"){const r=this.consume(),s=this.expect("identifier","expected identifier after '.'");e={kind:"fieldAccess",target:e,field:s.value,pos:r.pos}}else if(n==="lbracket"){const r=this.consume(),s=this.parseExpression();this.expect("rbracket","expected ']'"),e={kind:"indexAccess",target:e,index:s,pos:r.pos}}else break}return e}parsePrimary(){const e=this.peek();switch(e.kind){case"number":return this.consume(),{kind:"literal",value:e.value,pos:e.pos};case"string":return this.consume(),{kind:"literal",value:e.value,pos:e.pos};case"true":return this.consume(),{kind:"literal",value:!0,pos:e.pos};case"false":return this.consume(),{kind:"literal",value:!1,pos:e.pos};case"null":return this.consume(),{kind:"literal",value:null,pos:e.pos};case"reference":return this.consume(),{kind:"reference",alias:e.value,pos:e.pos};case"sentinel":return this.parseSentinelCall();case"lparen":{this.consume();const n=this.parseExpression();return this.expect("rparen","expected ')'"),n}case"identifier":throw new vr(`bare identifier '${e.value}' is not a value (did you mean '$${e.value}' or '@${e.value}'?)`,e.pos);case"eof":throw new vr("unexpected end of expression",e.pos);default:throw new vr("unexpected token",e.pos)}}parseSentinelCall(){const e=this.consume(),n=e.value;if(!uR(n))throw new vr(`unknown sentinel '@${n}' (allowed: serverTimestamp, increment, arrayUnion, arrayRemove, deleteField)`,e.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=cR[n];if(r.length<s.min||r.length>s.max){const o=s.max===1/0?`at least ${s.min}`:s.min===s.max?`exactly ${s.min}`:`${s.min}..${s.max}`;throw new vr(`sentinel '@${n}' expects ${o} argument(s), got ${r.length}`,e.pos)}return{kind:"sentinel",name:n,args:r,pos:e.pos}}peek(){return this.tokens[this.cursor]}consume(){const e=this.tokens[this.cursor];return this.cursor+=1,e}expect(e,n){const r=this.peek();if(r.kind!==e)throw new vr(`${n} (got ${xR(r)})`,r.pos);return this.consume()}};function vR(t){switch(t){case"eq":return"==";case"neq":return"!=";case"lt":return"<";case"lte":return"<=";case"gt":return">";case"gte":return">=";default:return null}}function xR(t){return t.kind==="eof"?"end of expression":t.value!==void 0?`${t.kind} ${JSON.stringify(t.value)}`:t.kind}function wR(t){e(t);function e(n){let r=0;switch(n.kind){case"literal":case"reference":r=0;break;case"unary":r=e(n.operand);break;case"binary":case"logical":r=Math.max(e(n.left),e(n.right));break;case"ternary":r=Math.max(e(n.cond),e(n.whenTrue),e(n.whenFalse));break;case"fieldAccess":r=e(n.target);break;case"indexAccess":r=Math.max(e(n.target),e(n.index));break;case"sentinel":r=n.args.length===0?0:Math.max(...n.args.map(e));break}const s=r+1;if(s>Ni.maxAstDepth)throw new vr(`expression AST exceeds depth cap of ${Ni.maxAstDepth}`,n.pos);return s}}class Ha extends Qe{constructor(n){super();G(this,"typeName","reference");G(this,"path");this.path=SR(n)}static fromResourceName(n){return new Ha(U1(n))}get id(){const n=this.path.lastIndexOf("/");return n===-1?this.path:this.path.slice(n+1)}get parent(){const n=this.path.lastIndexOf("/");return n===-1?"":this.path.slice(0,n)}valueOf(){return NaN}toString(){return this.path}toJSON(){return{__type:"reference",path:this.path}}equals(n){return n instanceof Ha?this.path===n.path:!1}field(n){switch(n){case"path":return this.path;case"id":return this.id;case"parent":return this.parent;default:return null}}callMethod(n,r){return ht}}function SR(t){let e=U1(t);return e.startsWith("/")&&(e=e.slice(1)),e.endsWith("/")&&(e=e.slice(0,-1)),e}function U1(t){const e="/documents/",n=t.indexOf(e);return n===-1?t:t.slice(n+e.length)}class no extends Qe{constructor(n){super();G(this,"typeName","vector");G(this,"value");if(!Array.isArray(n))throw new TypeError("Vector: value must be a number[]");for(let r=0;r<n.length;r++)if(typeof n[r]!="number")throw new TypeError(`Vector: element at index ${r} is not a number (got ${typeof n[r]})`);this.value=Object.freeze(n.slice())}get dimension(){return this.value.length}valueOf(){return NaN}toString(){return`[${this.value.join(", ")}]`}toJSON(){return{__type__:"__vector__",value:this.value.slice()}}equals(n){if(!(n instanceof no)||n.value.length!==this.value.length)return!1;for(let r=0;r<this.value.length;r++)if(n.value[r]!==this.value[r])return!1;return!0}callMethod(n,r){return ht}}var Le;(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function n(s){throw new Error}t.assertNever=n,t.arrayToEnum=s=>{const o={};for(const c of s)o[c]=c;return o},t.getValidEnumValues=s=>{const o=t.objectKeys(s).filter(d=>typeof s[s[d]]!="number"),c={};for(const d of o)c[d]=s[d];return t.objectValues(c)},t.objectValues=s=>t.objectKeys(s).map(function(o){return s[o]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const o=[];for(const c in s)Object.prototype.hasOwnProperty.call(s,c)&&o.push(c);return o},t.find=(s,o)=>{for(const c of s)if(o(c))return c},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,o=" | "){return s.map(c=>typeof c=="string"?`'${c}'`:c).join(o)}t.joinValues=r,t.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(Le||(Le={}));var yw;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(yw||(yw={}));const ue=Le.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ls=t=>{switch(typeof t){case"undefined":return ue.undefined;case"string":return ue.string;case"number":return Number.isNaN(t)?ue.nan:ue.number;case"boolean":return ue.boolean;case"function":return ue.function;case"bigint":return ue.bigint;case"symbol":return ue.symbol;case"object":return Array.isArray(t)?ue.array:t===null?ue.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?ue.promise:typeof Map<"u"&&t instanceof Map?ue.map:typeof Set<"u"&&t instanceof Set?ue.set:typeof Date<"u"&&t instanceof Date?ue.date:ue.object;default:return ue.unknown}},oe=Le.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class rs extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){const n=e||function(o){return o.message},r={_errors:[]},s=o=>{for(const c of o.issues)if(c.code==="invalid_union")c.unionErrors.map(s);else if(c.code==="invalid_return_type")s(c.returnTypeError);else if(c.code==="invalid_arguments")s(c.argumentsError);else if(c.path.length===0)r._errors.push(n(c));else{let d=r,f=0;for(;f<c.path.length;){const p=c.path[f];f===c.path.length-1?(d[p]=d[p]||{_errors:[]},d[p]._errors.push(n(c))):d[p]=d[p]||{_errors:[]},d=d[p],f++}}};return s(this),r}static assert(e){if(!(e instanceof rs))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Le.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){const n={},r=[];for(const s of this.issues)if(s.path.length>0){const o=s.path[0];n[o]=n[o]||[],n[o].push(e(s))}else r.push(e(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}rs.create=t=>new rs(t);const vm=(t,e)=>{let n;switch(t.code){case oe.invalid_type:t.received===ue.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case oe.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,Le.jsonStringifyReplacer)}`;break;case oe.unrecognized_keys:n=`Unrecognized key(s) in object: ${Le.joinValues(t.keys,", ")}`;break;case oe.invalid_union:n="Invalid input";break;case oe.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${Le.joinValues(t.options)}`;break;case oe.invalid_enum_value:n=`Invalid enum value. Expected ${Le.joinValues(t.options)}, received '${t.received}'`;break;case oe.invalid_arguments:n="Invalid function arguments";break;case oe.invalid_return_type:n="Invalid function return type";break;case oe.invalid_date:n="Invalid date";break;case oe.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:Le.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case oe.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case oe.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case oe.custom:n="Invalid input";break;case oe.invalid_intersection_types:n="Intersection results could not be merged";break;case oe.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case oe.not_finite:n="Number must be finite";break;default:n=e.defaultError,Le.assertNever(t)}return{message:n}};let _R=vm;function ER(){return _R}const AR=t=>{const{data:e,path:n,errorMaps:r,issueData:s}=t,o=[...n,...s.path||[]],c={...s,path:o};if(s.message!==void 0)return{...s,path:o,message:s.message};let d="";const f=r.filter(p=>!!p).slice().reverse();for(const p of f)d=p(c,{data:e,defaultError:d}).message;return{...s,path:o,message:d}};function ce(t,e){const n=ER(),r=AR({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===vm?void 0:vm].filter(s=>!!s)});t.common.issues.push(r)}class sn{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){const r=[];for(const s of n){if(s.status==="aborted")return ge;s.status==="dirty"&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){const r=[];for(const s of n){const o=await s.key,c=await s.value;r.push({key:o,value:c})}return sn.mergeObjectSync(e,r)}static mergeObjectSync(e,n){const r={};for(const s of n){const{key:o,value:c}=s;if(o.status==="aborted"||c.status==="aborted")return ge;o.status==="dirty"&&e.dirty(),c.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof c.value<"u"||s.alwaysSet)&&(r[o.value]=c.value)}return{status:e.value,value:r}}}const ge=Object.freeze({status:"aborted"}),pl=t=>({status:"dirty",value:t}),Xn=t=>({status:"valid",value:t}),gw=t=>t.status==="aborted",bw=t=>t.status==="dirty",Ga=t=>t.status==="valid",Vu=t=>typeof Promise<"u"&&t instanceof Promise;var he;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(he||(he={}));class kr{constructor(e,n,r,s){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const vw=(t,e)=>{if(Ga(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new rs(t.common.issues);return this._error=n,this._error}}};function Ee(t){if(!t)return{};const{errorMap:e,invalid_type_error:n,required_error:r,description:s}=t;if(e&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(c,d)=>{const{message:f}=t;return c.code==="invalid_enum_value"?{message:f??d.defaultError}:typeof d.data>"u"?{message:f??r??d.defaultError}:c.code!=="invalid_type"?{message:d.defaultError}:{message:f??n??d.defaultError}},description:s}}class Re{get description(){return this._def.description}_getType(e){return Ls(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:Ls(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new sn,ctx:{common:e.parent.common,data:e.data,parsedType:Ls(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const n=this._parse(e);if(Vu(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){const n=this._parse(e);return Promise.resolve(n)}parse(e,n){const r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){const r={common:{issues:[],async:(n==null?void 0:n.async)??!1,contextualErrorMap:n==null?void 0:n.errorMap},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ls(e)},s=this._parseSync({data:e,path:r.path,parent:r});return vw(r,s)}"~validate"(e){var r,s;const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ls(e)};if(!this["~standard"].async)try{const o=this._parseSync({data:e,path:[],parent:n});return Ga(o)?{value:o.value}:{issues:n.common.issues}}catch(o){(s=(r=o==null?void 0:o.message)==null?void 0:r.toLowerCase())!=null&&s.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(o=>Ga(o)?{value:o.value}:{issues:n.common.issues})}async parseAsync(e,n){const r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){const r={common:{issues:[],contextualErrorMap:n==null?void 0:n.errorMap,async:!0},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ls(e)},s=this._parse({data:e,path:r.path,parent:r}),o=await(Vu(s)?s:Promise.resolve(s));return vw(r,o)}refine(e,n){const r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,o)=>{const c=e(s),d=()=>o.addIssue({code:oe.custom,...r(s)});return typeof Promise<"u"&&c instanceof Promise?c.then(f=>f?!0:(d(),!1)):c?!0:(d(),!1)})}refinement(e,n){return this._refinement((r,s)=>e(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(e){return new Ii({schema:this,typeName:be.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return Er.create(this,this._def)}nullable(){return Mi.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return _r.create(this)}promise(){return Wu.create(this,this._def)}or(e){return jl.create([this,e],this._def)}and(e){return Yu.create(this,e,this._def)}transform(e){return new Ii({...Ee(this._def),schema:this,typeName:be.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const n=typeof e=="function"?e:()=>e;return new Ju({...Ee(this._def),innerType:this,defaultValue:n,typeName:be.ZodDefault})}brand(){return new P1({typeName:be.ZodBranded,type:this,...Ee(this._def)})}catch(e){const n=typeof e=="function"?e:()=>e;return new Qu({...Ee(this._def),innerType:this,catchValue:n,typeName:be.ZodCatch})}describe(e){const n=this.constructor;return new n({...this._def,description:e})}pipe(e){return Py.create(this,e)}readonly(){return Xu.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const jR=/^c[^\s-]{8,}$/i,kR=/^[0-9a-z]+$/,CR=/^[0-9A-HJKMNP-TV-Z]{26}$/i,NR=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,OR=/^[a-z0-9_-]{21}$/i,TR=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,RR=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,DR=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,IR="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Tp;const MR=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,LR=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,UR=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,$R=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,BR=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,FR=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,$1="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",PR=new RegExp(`^${$1}$`);function B1(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);const n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function qR(t){return new RegExp(`^${B1(t)}$`)}function zR(t){let e=`${$1}T${B1(t)}`;const n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function VR(t,e){return!!((e==="v4"||!e)&&MR.test(t)||(e==="v6"||!e)&&UR.test(t))}function HR(t,e){if(!TR.test(t))return!1;try{const[n]=t.split(".");if(!n)return!1;const r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&(s==null?void 0:s.typ)!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function GR(t,e){return!!((e==="v4"||!e)&&LR.test(t)||(e==="v6"||!e)&&$R.test(t))}class wr extends Re{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==ue.string){const o=this._getOrReturnCtx(e);return ce(o,{code:oe.invalid_type,expected:ue.string,received:o.parsedType}),ge}const r=new sn;let s;for(const o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(s=this._getOrReturnCtx(e,s),ce(s,{code:oe.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="max")e.data.length>o.value&&(s=this._getOrReturnCtx(e,s),ce(s,{code:oe.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="length"){const c=e.data.length>o.value,d=e.data.length<o.value;(c||d)&&(s=this._getOrReturnCtx(e,s),c?ce(s,{code:oe.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):d&&ce(s,{code:oe.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),r.dirty())}else if(o.kind==="email")DR.test(e.data)||(s=this._getOrReturnCtx(e,s),ce(s,{validation:"email",code:oe.invalid_string,message:o.message}),r.dirty());else if(o.kind==="emoji")Tp||(Tp=new RegExp(IR,"u")),Tp.test(e.data)||(s=this._getOrReturnCtx(e,s),ce(s,{validation:"emoji",code:oe.invalid_string,message:o.message}),r.dirty());else if(o.kind==="uuid")NR.test(e.data)||(s=this._getOrReturnCtx(e,s),ce(s,{validation:"uuid",code:oe.invalid_string,message:o.message}),r.dirty());else if(o.kind==="nanoid")OR.test(e.data)||(s=this._getOrReturnCtx(e,s),ce(s,{validation:"nanoid",code:oe.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid")jR.test(e.data)||(s=this._getOrReturnCtx(e,s),ce(s,{validation:"cuid",code:oe.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid2")kR.test(e.data)||(s=this._getOrReturnCtx(e,s),ce(s,{validation:"cuid2",code:oe.invalid_string,message:o.message}),r.dirty());else if(o.kind==="ulid")CR.test(e.data)||(s=this._getOrReturnCtx(e,s),ce(s,{validation:"ulid",code:oe.invalid_string,message:o.message}),r.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),ce(s,{validation:"url",code:oe.invalid_string,message:o.message}),r.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),ce(s,{validation:"regex",code:oe.invalid_string,message:o.message}),r.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(s=this._getOrReturnCtx(e,s),ce(s,{code:oe.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),r.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(s=this._getOrReturnCtx(e,s),ce(s,{code:oe.invalid_string,validation:{startsWith:o.value},message:o.message}),r.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(s=this._getOrReturnCtx(e,s),ce(s,{code:oe.invalid_string,validation:{endsWith:o.value},message:o.message}),r.dirty()):o.kind==="datetime"?zR(o).test(e.data)||(s=this._getOrReturnCtx(e,s),ce(s,{code:oe.invalid_string,validation:"datetime",message:o.message}),r.dirty()):o.kind==="date"?PR.test(e.data)||(s=this._getOrReturnCtx(e,s),ce(s,{code:oe.invalid_string,validation:"date",message:o.message}),r.dirty()):o.kind==="time"?qR(o).test(e.data)||(s=this._getOrReturnCtx(e,s),ce(s,{code:oe.invalid_string,validation:"time",message:o.message}),r.dirty()):o.kind==="duration"?RR.test(e.data)||(s=this._getOrReturnCtx(e,s),ce(s,{validation:"duration",code:oe.invalid_string,message:o.message}),r.dirty()):o.kind==="ip"?VR(e.data,o.version)||(s=this._getOrReturnCtx(e,s),ce(s,{validation:"ip",code:oe.invalid_string,message:o.message}),r.dirty()):o.kind==="jwt"?HR(e.data,o.alg)||(s=this._getOrReturnCtx(e,s),ce(s,{validation:"jwt",code:oe.invalid_string,message:o.message}),r.dirty()):o.kind==="cidr"?GR(e.data,o.version)||(s=this._getOrReturnCtx(e,s),ce(s,{validation:"cidr",code:oe.invalid_string,message:o.message}),r.dirty()):o.kind==="base64"?BR.test(e.data)||(s=this._getOrReturnCtx(e,s),ce(s,{validation:"base64",code:oe.invalid_string,message:o.message}),r.dirty()):o.kind==="base64url"?FR.test(e.data)||(s=this._getOrReturnCtx(e,s),ce(s,{validation:"base64url",code:oe.invalid_string,message:o.message}),r.dirty()):Le.assertNever(o);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(s=>e.test(s),{validation:n,code:oe.invalid_string,...he.errToObj(r)})}_addCheck(e){return new wr({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...he.errToObj(e)})}url(e){return this._addCheck({kind:"url",...he.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...he.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...he.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...he.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...he.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...he.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...he.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...he.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...he.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...he.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...he.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...he.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(e==null?void 0:e.offset)??!1,local:(e==null?void 0:e.local)??!1,...he.errToObj(e==null?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...he.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...he.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...he.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n==null?void 0:n.position,...he.errToObj(n==null?void 0:n.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...he.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...he.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...he.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...he.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...he.errToObj(n)})}nonempty(e){return this.min(1,he.errToObj(e))}trim(){return new wr({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new wr({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new wr({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}}wr.create=t=>new wr({checks:[],typeName:be.ZodString,coerce:(t==null?void 0:t.coerce)??!1,...Ee(t)});function KR(t,e){const n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=n>r?n:r,o=Number.parseInt(t.toFixed(s).replace(".","")),c=Number.parseInt(e.toFixed(s).replace(".",""));return o%c/10**s}class Ri extends Re{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==ue.number){const o=this._getOrReturnCtx(e);return ce(o,{code:oe.invalid_type,expected:ue.number,received:o.parsedType}),ge}let r;const s=new sn;for(const o of this._def.checks)o.kind==="int"?Le.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),ce(r,{code:oe.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(r=this._getOrReturnCtx(e,r),ce(r,{code:oe.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(r=this._getOrReturnCtx(e,r),ce(r,{code:oe.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?KR(e.data,o.value)!==0&&(r=this._getOrReturnCtx(e,r),ce(r,{code:oe.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),ce(r,{code:oe.not_finite,message:o.message}),s.dirty()):Le.assertNever(o);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,he.toString(n))}gt(e,n){return this.setLimit("min",e,!1,he.toString(n))}lte(e,n){return this.setLimit("max",e,!0,he.toString(n))}lt(e,n){return this.setLimit("max",e,!1,he.toString(n))}setLimit(e,n,r,s){return new Ri({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:he.toString(s)}]})}_addCheck(e){return new Ri({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:he.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:he.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:he.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:he.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:he.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:he.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:he.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:he.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:he.toString(e)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&Le.isInteger(e.value))}get isFinite(){let e=null,n=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}}Ri.create=t=>new Ri({checks:[],typeName:be.ZodNumber,coerce:(t==null?void 0:t.coerce)||!1,...Ee(t)});class Al extends Re{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==ue.bigint)return this._getInvalidInput(e);let r;const s=new sn;for(const o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(r=this._getOrReturnCtx(e,r),ce(r,{code:oe.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(r=this._getOrReturnCtx(e,r),ce(r,{code:oe.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),ce(r,{code:oe.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):Le.assertNever(o);return{status:s.value,value:e.data}}_getInvalidInput(e){const n=this._getOrReturnCtx(e);return ce(n,{code:oe.invalid_type,expected:ue.bigint,received:n.parsedType}),ge}gte(e,n){return this.setLimit("min",e,!0,he.toString(n))}gt(e,n){return this.setLimit("min",e,!1,he.toString(n))}lte(e,n){return this.setLimit("max",e,!0,he.toString(n))}lt(e,n){return this.setLimit("max",e,!1,he.toString(n))}setLimit(e,n,r,s){return new Al({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:he.toString(s)}]})}_addCheck(e){return new Al({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:he.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:he.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:he.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:he.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:he.toString(n)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}}Al.create=t=>new Al({checks:[],typeName:be.ZodBigInt,coerce:(t==null?void 0:t.coerce)??!1,...Ee(t)});class Hu extends Re{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==ue.boolean){const r=this._getOrReturnCtx(e);return ce(r,{code:oe.invalid_type,expected:ue.boolean,received:r.parsedType}),ge}return Xn(e.data)}}Hu.create=t=>new Hu({typeName:be.ZodBoolean,coerce:(t==null?void 0:t.coerce)||!1,...Ee(t)});class Gu extends Re{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==ue.date){const o=this._getOrReturnCtx(e);return ce(o,{code:oe.invalid_type,expected:ue.date,received:o.parsedType}),ge}if(Number.isNaN(e.data.getTime())){const o=this._getOrReturnCtx(e);return ce(o,{code:oe.invalid_date}),ge}const r=new sn;let s;for(const o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(s=this._getOrReturnCtx(e,s),ce(s,{code:oe.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),r.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(s=this._getOrReturnCtx(e,s),ce(s,{code:oe.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),r.dirty()):Le.assertNever(o);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Gu({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:he.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:he.toString(n)})}get minDate(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}}Gu.create=t=>new Gu({checks:[],coerce:(t==null?void 0:t.coerce)||!1,typeName:be.ZodDate,...Ee(t)});class xw extends Re{_parse(e){if(this._getType(e)!==ue.symbol){const r=this._getOrReturnCtx(e);return ce(r,{code:oe.invalid_type,expected:ue.symbol,received:r.parsedType}),ge}return Xn(e.data)}}xw.create=t=>new xw({typeName:be.ZodSymbol,...Ee(t)});class xm extends Re{_parse(e){if(this._getType(e)!==ue.undefined){const r=this._getOrReturnCtx(e);return ce(r,{code:oe.invalid_type,expected:ue.undefined,received:r.parsedType}),ge}return Xn(e.data)}}xm.create=t=>new xm({typeName:be.ZodUndefined,...Ee(t)});class Ku extends Re{_parse(e){if(this._getType(e)!==ue.null){const r=this._getOrReturnCtx(e);return ce(r,{code:oe.invalid_type,expected:ue.null,received:r.parsedType}),ge}return Xn(e.data)}}Ku.create=t=>new Ku({typeName:be.ZodNull,...Ee(t)});class ww extends Re{constructor(){super(...arguments),this._any=!0}_parse(e){return Xn(e.data)}}ww.create=t=>new ww({typeName:be.ZodAny,...Ee(t)});class wm extends Re{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Xn(e.data)}}wm.create=t=>new wm({typeName:be.ZodUnknown,...Ee(t)});class Gs extends Re{_parse(e){const n=this._getOrReturnCtx(e);return ce(n,{code:oe.invalid_type,expected:ue.never,received:n.parsedType}),ge}}Gs.create=t=>new Gs({typeName:be.ZodNever,...Ee(t)});class Sw extends Re{_parse(e){if(this._getType(e)!==ue.undefined){const r=this._getOrReturnCtx(e);return ce(r,{code:oe.invalid_type,expected:ue.void,received:r.parsedType}),ge}return Xn(e.data)}}Sw.create=t=>new Sw({typeName:be.ZodVoid,...Ee(t)});class _r extends Re{_parse(e){const{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==ue.array)return ce(n,{code:oe.invalid_type,expected:ue.array,received:n.parsedType}),ge;if(s.exactLength!==null){const c=n.data.length>s.exactLength.value,d=n.data.length<s.exactLength.value;(c||d)&&(ce(n,{code:c?oe.too_big:oe.too_small,minimum:d?s.exactLength.value:void 0,maximum:c?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&n.data.length<s.minLength.value&&(ce(n,{code:oe.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&(ce(n,{code:oe.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((c,d)=>s.type._parseAsync(new kr(n,c,n.path,d)))).then(c=>sn.mergeArray(r,c));const o=[...n.data].map((c,d)=>s.type._parseSync(new kr(n,c,n.path,d)));return sn.mergeArray(r,o)}get element(){return this._def.type}min(e,n){return new _r({...this._def,minLength:{value:e,message:he.toString(n)}})}max(e,n){return new _r({...this._def,maxLength:{value:e,message:he.toString(n)}})}length(e,n){return new _r({...this._def,exactLength:{value:e,message:he.toString(n)}})}nonempty(e){return this.min(1,e)}}_r.create=(t,e)=>new _r({type:t,minLength:null,maxLength:null,exactLength:null,typeName:be.ZodArray,...Ee(e)});function Ua(t){if(t instanceof dt){const e={};for(const n in t.shape){const r=t.shape[n];e[n]=Er.create(Ua(r))}return new dt({...t._def,shape:()=>e})}else return t instanceof _r?new _r({...t._def,type:Ua(t.element)}):t instanceof Er?Er.create(Ua(t.unwrap())):t instanceof Mi?Mi.create(Ua(t.unwrap())):t instanceof Di?Di.create(t.items.map(e=>Ua(e))):t}class dt extends Re{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),n=Le.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==ue.object){const p=this._getOrReturnCtx(e);return ce(p,{code:oe.invalid_type,expected:ue.object,received:p.parsedType}),ge}const{status:r,ctx:s}=this._processInputParams(e),{shape:o,keys:c}=this._getCached(),d=[];if(!(this._def.catchall instanceof Gs&&this._def.unknownKeys==="strip"))for(const p in s.data)c.includes(p)||d.push(p);const f=[];for(const p of c){const g=o[p],b=s.data[p];f.push({key:{status:"valid",value:p},value:g._parse(new kr(s,b,s.path,p)),alwaysSet:p in s.data})}if(this._def.catchall instanceof Gs){const p=this._def.unknownKeys;if(p==="passthrough")for(const g of d)f.push({key:{status:"valid",value:g},value:{status:"valid",value:s.data[g]}});else if(p==="strict")d.length>0&&(ce(s,{code:oe.unrecognized_keys,keys:d}),r.dirty());else if(p!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const p=this._def.catchall;for(const g of d){const b=s.data[g];f.push({key:{status:"valid",value:g},value:p._parse(new kr(s,b,s.path,g)),alwaysSet:g in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const p=[];for(const g of f){const b=await g.key,v=await g.value;p.push({key:b,value:v,alwaysSet:g.alwaysSet})}return p}).then(p=>sn.mergeObjectSync(r,p)):sn.mergeObjectSync(r,f)}get shape(){return this._def.shape()}strict(e){return he.errToObj,new dt({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{var o,c;const s=((c=(o=this._def).errorMap)==null?void 0:c.call(o,n,r).message)??r.defaultError;return n.code==="unrecognized_keys"?{message:he.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new dt({...this._def,unknownKeys:"strip"})}passthrough(){return new dt({...this._def,unknownKeys:"passthrough"})}extend(e){return new dt({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new dt({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:be.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new dt({...this._def,catchall:e})}pick(e){const n={};for(const r of Le.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new dt({...this._def,shape:()=>n})}omit(e){const n={};for(const r of Le.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new dt({...this._def,shape:()=>n})}deepPartial(){return Ua(this)}partial(e){const n={};for(const r of Le.objectKeys(this.shape)){const s=this.shape[r];e&&!e[r]?n[r]=s:n[r]=s.optional()}return new dt({...this._def,shape:()=>n})}required(e){const n={};for(const r of Le.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let o=this.shape[r];for(;o instanceof Er;)o=o._def.innerType;n[r]=o}return new dt({...this._def,shape:()=>n})}keyof(){return F1(Le.objectKeys(this.shape))}}dt.create=(t,e)=>new dt({shape:()=>t,unknownKeys:"strip",catchall:Gs.create(),typeName:be.ZodObject,...Ee(e)});dt.strictCreate=(t,e)=>new dt({shape:()=>t,unknownKeys:"strict",catchall:Gs.create(),typeName:be.ZodObject,...Ee(e)});dt.lazycreate=(t,e)=>new dt({shape:t,unknownKeys:"strip",catchall:Gs.create(),typeName:be.ZodObject,...Ee(e)});class jl extends Re{_parse(e){const{ctx:n}=this._processInputParams(e),r=this._def.options;function s(o){for(const d of o)if(d.result.status==="valid")return d.result;for(const d of o)if(d.result.status==="dirty")return n.common.issues.push(...d.ctx.common.issues),d.result;const c=o.map(d=>new rs(d.ctx.common.issues));return ce(n,{code:oe.invalid_union,unionErrors:c}),ge}if(n.common.async)return Promise.all(r.map(async o=>{const c={...n,common:{...n.common,issues:[]},parent:null};return{result:await o._parseAsync({data:n.data,path:n.path,parent:c}),ctx:c}})).then(s);{let o;const c=[];for(const f of r){const p={...n,common:{...n.common,issues:[]},parent:null},g=f._parseSync({data:n.data,path:n.path,parent:p});if(g.status==="valid")return g;g.status==="dirty"&&!o&&(o={result:g,ctx:p}),p.common.issues.length&&c.push(p.common.issues)}if(o)return n.common.issues.push(...o.ctx.common.issues),o.result;const d=c.map(f=>new rs(f));return ce(n,{code:oe.invalid_union,unionErrors:d}),ge}}get options(){return this._def.options}}jl.create=(t,e)=>new jl({options:t,typeName:be.ZodUnion,...Ee(e)});const Qr=t=>t instanceof _m?Qr(t.schema):t instanceof Ii?Qr(t.innerType()):t instanceof Cl?[t.value]:t instanceof Ks?t.options:t instanceof Em?Le.objectValues(t.enum):t instanceof Ju?Qr(t._def.innerType):t instanceof xm?[void 0]:t instanceof Ku?[null]:t instanceof Er?[void 0,...Qr(t.unwrap())]:t instanceof Mi?[null,...Qr(t.unwrap())]:t instanceof P1||t instanceof Xu?Qr(t.unwrap()):t instanceof Qu?Qr(t._def.innerType):[];class Fy extends Re{_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==ue.object)return ce(n,{code:oe.invalid_type,expected:ue.object,received:n.parsedType}),ge;const r=this.discriminator,s=n.data[r],o=this.optionsMap.get(s);return o?n.common.async?o._parseAsync({data:n.data,path:n.path,parent:n}):o._parseSync({data:n.data,path:n.path,parent:n}):(ce(n,{code:oe.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),ge)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){const s=new Map;for(const o of n){const c=Qr(o.shape[e]);if(!c.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const d of c){if(s.has(d))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(d)}`);s.set(d,o)}}return new Fy({typeName:be.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:s,...Ee(r)})}}function Sm(t,e){const n=Ls(t),r=Ls(e);if(t===e)return{valid:!0,data:t};if(n===ue.object&&r===ue.object){const s=Le.objectKeys(e),o=Le.objectKeys(t).filter(d=>s.indexOf(d)!==-1),c={...t,...e};for(const d of o){const f=Sm(t[d],e[d]);if(!f.valid)return{valid:!1};c[d]=f.data}return{valid:!0,data:c}}else if(n===ue.array&&r===ue.array){if(t.length!==e.length)return{valid:!1};const s=[];for(let o=0;o<t.length;o++){const c=t[o],d=e[o],f=Sm(c,d);if(!f.valid)return{valid:!1};s.push(f.data)}return{valid:!0,data:s}}else return n===ue.date&&r===ue.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}class Yu extends Re{_parse(e){const{status:n,ctx:r}=this._processInputParams(e),s=(o,c)=>{if(gw(o)||gw(c))return ge;const d=Sm(o.value,c.value);return d.valid?((bw(o)||bw(c))&&n.dirty(),{status:n.value,value:d.data}):(ce(r,{code:oe.invalid_intersection_types}),ge)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([o,c])=>s(o,c)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}Yu.create=(t,e,n)=>new Yu({left:t,right:e,typeName:be.ZodIntersection,...Ee(n)});class Di extends Re{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==ue.array)return ce(r,{code:oe.invalid_type,expected:ue.array,received:r.parsedType}),ge;if(r.data.length<this._def.items.length)return ce(r,{code:oe.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ge;!this._def.rest&&r.data.length>this._def.items.length&&(ce(r,{code:oe.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const o=[...r.data].map((c,d)=>{const f=this._def.items[d]||this._def.rest;return f?f._parse(new kr(r,c,r.path,d)):null}).filter(c=>!!c);return r.common.async?Promise.all(o).then(c=>sn.mergeArray(n,c)):sn.mergeArray(n,o)}get items(){return this._def.items}rest(e){return new Di({...this._def,rest:e})}}Di.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Di({items:t,typeName:be.ZodTuple,rest:null,...Ee(e)})};class Zu extends Re{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==ue.object)return ce(r,{code:oe.invalid_type,expected:ue.object,received:r.parsedType}),ge;const s=[],o=this._def.keyType,c=this._def.valueType;for(const d in r.data)s.push({key:o._parse(new kr(r,d,r.path,d)),value:c._parse(new kr(r,r.data[d],r.path,d)),alwaysSet:d in r.data});return r.common.async?sn.mergeObjectAsync(n,s):sn.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof Re?new Zu({keyType:e,valueType:n,typeName:be.ZodRecord,...Ee(r)}):new Zu({keyType:wr.create(),valueType:e,typeName:be.ZodRecord,...Ee(n)})}}class _w extends Re{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==ue.map)return ce(r,{code:oe.invalid_type,expected:ue.map,received:r.parsedType}),ge;const s=this._def.keyType,o=this._def.valueType,c=[...r.data.entries()].map(([d,f],p)=>({key:s._parse(new kr(r,d,r.path,[p,"key"])),value:o._parse(new kr(r,f,r.path,[p,"value"]))}));if(r.common.async){const d=new Map;return Promise.resolve().then(async()=>{for(const f of c){const p=await f.key,g=await f.value;if(p.status==="aborted"||g.status==="aborted")return ge;(p.status==="dirty"||g.status==="dirty")&&n.dirty(),d.set(p.value,g.value)}return{status:n.value,value:d}})}else{const d=new Map;for(const f of c){const p=f.key,g=f.value;if(p.status==="aborted"||g.status==="aborted")return ge;(p.status==="dirty"||g.status==="dirty")&&n.dirty(),d.set(p.value,g.value)}return{status:n.value,value:d}}}}_w.create=(t,e,n)=>new _w({valueType:e,keyType:t,typeName:be.ZodMap,...Ee(n)});class kl extends Re{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==ue.set)return ce(r,{code:oe.invalid_type,expected:ue.set,received:r.parsedType}),ge;const s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(ce(r,{code:oe.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(ce(r,{code:oe.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());const o=this._def.valueType;function c(f){const p=new Set;for(const g of f){if(g.status==="aborted")return ge;g.status==="dirty"&&n.dirty(),p.add(g.value)}return{status:n.value,value:p}}const d=[...r.data.values()].map((f,p)=>o._parse(new kr(r,f,r.path,p)));return r.common.async?Promise.all(d).then(f=>c(f)):c(d)}min(e,n){return new kl({...this._def,minSize:{value:e,message:he.toString(n)}})}max(e,n){return new kl({...this._def,maxSize:{value:e,message:he.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}}kl.create=(t,e)=>new kl({valueType:t,minSize:null,maxSize:null,typeName:be.ZodSet,...Ee(e)});class _m extends Re{get schema(){return this._def.getter()}_parse(e){const{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}_m.create=(t,e)=>new _m({getter:t,typeName:be.ZodLazy,...Ee(e)});class Cl extends Re{_parse(e){if(e.data!==this._def.value){const n=this._getOrReturnCtx(e);return ce(n,{received:n.data,code:oe.invalid_literal,expected:this._def.value}),ge}return{status:"valid",value:e.data}}get value(){return this._def.value}}Cl.create=(t,e)=>new Cl({value:t,typeName:be.ZodLiteral,...Ee(e)});function F1(t,e){return new Ks({values:t,typeName:be.ZodEnum,...Ee(e)})}class Ks extends Re{_parse(e){if(typeof e.data!="string"){const n=this._getOrReturnCtx(e),r=this._def.values;return ce(n,{expected:Le.joinValues(r),received:n.parsedType,code:oe.invalid_type}),ge}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const n=this._getOrReturnCtx(e),r=this._def.values;return ce(n,{received:n.data,code:oe.invalid_enum_value,options:r}),ge}return Xn(e.data)}get options(){return this._def.values}get enum(){const e={};for(const n of this._def.values)e[n]=n;return e}get Values(){const e={};for(const n of this._def.values)e[n]=n;return e}get Enum(){const e={};for(const n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return Ks.create(e,{...this._def,...n})}exclude(e,n=this._def){return Ks.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}}Ks.create=F1;class Em extends Re{_parse(e){const n=Le.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==ue.string&&r.parsedType!==ue.number){const s=Le.objectValues(n);return ce(r,{expected:Le.joinValues(s),received:r.parsedType,code:oe.invalid_type}),ge}if(this._cache||(this._cache=new Set(Le.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const s=Le.objectValues(n);return ce(r,{received:r.data,code:oe.invalid_enum_value,options:s}),ge}return Xn(e.data)}get enum(){return this._def.values}}Em.create=(t,e)=>new Em({values:t,typeName:be.ZodNativeEnum,...Ee(e)});class Wu extends Re{unwrap(){return this._def.type}_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==ue.promise&&n.common.async===!1)return ce(n,{code:oe.invalid_type,expected:ue.promise,received:n.parsedType}),ge;const r=n.parsedType===ue.promise?n.data:Promise.resolve(n.data);return Xn(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}}Wu.create=(t,e)=>new Wu({type:t,typeName:be.ZodPromise,...Ee(e)});class Ii extends Re{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===be.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:n,ctx:r}=this._processInputParams(e),s=this._def.effect||null,o={addIssue:c=>{ce(r,c),c.fatal?n.abort():n.dirty()},get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){const c=s.transform(r.data,o);if(r.common.async)return Promise.resolve(c).then(async d=>{if(n.value==="aborted")return ge;const f=await this._def.schema._parseAsync({data:d,path:r.path,parent:r});return f.status==="aborted"?ge:f.status==="dirty"||n.value==="dirty"?pl(f.value):f});{if(n.value==="aborted")return ge;const d=this._def.schema._parseSync({data:c,path:r.path,parent:r});return d.status==="aborted"?ge:d.status==="dirty"||n.value==="dirty"?pl(d.value):d}}if(s.type==="refinement"){const c=d=>{const f=s.refinement(d,o);if(r.common.async)return Promise.resolve(f);if(f instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return d};if(r.common.async===!1){const d=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return d.status==="aborted"?ge:(d.status==="dirty"&&n.dirty(),c(d.value),{status:n.value,value:d.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(d=>d.status==="aborted"?ge:(d.status==="dirty"&&n.dirty(),c(d.value).then(()=>({status:n.value,value:d.value}))))}if(s.type==="transform")if(r.common.async===!1){const c=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Ga(c))return ge;const d=s.transform(c.value,o);if(d instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:d}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(c=>Ga(c)?Promise.resolve(s.transform(c.value,o)).then(d=>({status:n.value,value:d})):ge);Le.assertNever(s)}}Ii.create=(t,e,n)=>new Ii({schema:t,typeName:be.ZodEffects,effect:e,...Ee(n)});Ii.createWithPreprocess=(t,e,n)=>new Ii({schema:e,effect:{type:"preprocess",transform:t},typeName:be.ZodEffects,...Ee(n)});class Er extends Re{_parse(e){return this._getType(e)===ue.undefined?Xn(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Er.create=(t,e)=>new Er({innerType:t,typeName:be.ZodOptional,...Ee(e)});class Mi extends Re{_parse(e){return this._getType(e)===ue.null?Xn(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Mi.create=(t,e)=>new Mi({innerType:t,typeName:be.ZodNullable,...Ee(e)});class Ju extends Re{_parse(e){const{ctx:n}=this._processInputParams(e);let r=n.data;return n.parsedType===ue.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}Ju.create=(t,e)=>new Ju({innerType:t,typeName:be.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Ee(e)});class Qu extends Re{_parse(e){const{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Vu(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new rs(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new rs(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Qu.create=(t,e)=>new Qu({innerType:t,typeName:be.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Ee(e)});class Ew extends Re{_parse(e){if(this._getType(e)!==ue.nan){const r=this._getOrReturnCtx(e);return ce(r,{code:oe.invalid_type,expected:ue.nan,received:r.parsedType}),ge}return{status:"valid",value:e.data}}}Ew.create=t=>new Ew({typeName:be.ZodNaN,...Ee(t)});class P1 extends Re{_parse(e){const{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}}class Py extends Re{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{const o=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?ge:o.status==="dirty"?(n.dirty(),pl(o.value)):this._def.out._parseAsync({data:o.value,path:r.path,parent:r})})();{const s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?ge:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(e,n){return new Py({in:e,out:n,typeName:be.ZodPipeline})}}class Xu extends Re{_parse(e){const n=this._def.innerType._parse(e),r=s=>(Ga(s)&&(s.value=Object.freeze(s.value)),s);return Vu(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}}Xu.create=(t,e)=>new Xu({innerType:t,typeName:be.ZodReadonly,...Ee(e)});var be;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(be||(be={}));const gn=wr.create,Aw=Ri.create,Nl=Hu.create,q1=Ku.create,es=wm.create;Gs.create;const z1=_r.create,Rn=dt.create,kd=jl.create,YR=Fy.create;Yu.create;Di.create;const Ys=Zu.create,hu=Cl.create,Ka=Ks.create;Wu.create;Er.create;Mi.create;const ZR=["get","list","create","update","delete"],WR=Rn({uid:gn(),token:Ys(es()).optional()}),JR=Rn({function:Ka(["get","exists"]).describe("Firestore function to mock"),path:gn().describe('Document path, e.g. "users/alice"'),result:kd([Ys(es()),Nl()]).describe("Document data for get, boolean for exists")}),QR=YR("kind",[Rn({kind:hu("create")}),Rn({kind:hu("set"),merge:Nl()}),Rn({kind:hu("update")}),Rn({kind:hu("delete")})]),XR=Rn({limit:Aw().optional(),offset:Aw().optional(),orderBy:gn().optional()});Rn({description:gn().describe("Human-readable description of what this test verifies"),expectation:Ka(["ALLOW","DENY"]).describe("Expected outcome"),method:Ka(ZR).describe("Firestore method to test"),path:gn().describe('Document path, e.g. "users/alice"'),auth:kd([WR,q1()]).optional().describe("Auth context; null or omitted for unauthenticated"),data:Ys(es()).optional().describe("request.resource.data for write operations"),resource:Ys(es()).optional().describe("Existing document data (resource.data)"),functionMocks:z1(JR).optional().describe("Mock get()/exists() calls in rules"),query:XR.optional().describe("request.query payload (list ops only): limit/offset/orderBy."),requestTime:gn().optional().describe("Override for request.time (ISO-8601). Defaults to wallclock."),writeMode:QR.optional().describe("Optional write-mode override; controls update merge semantics and getAfter() projection.")});function xi(t){if(t.decision==="UNSUPPORTED")return;const e=t.decision==="ALLOW",n=e?t.trace.find(s=>s.verdict==="ALLOW"):t.trace.find(s=>s.verdict==="DENY"||s.verdict==="ERROR")??t.trace[t.trace.length-1];if(!n)return;const r={verdict:e?"allow":"deny"};return n.line!==void 0&&(r.line=n.line),n.conditionText!==void 0&&(r.expression=n.conditionText),n.expressionTrace!==void 0&&(r.expressionTrace=n.expressionTrace),r.line!==void 0||r.expression!==void 0||r.expressionTrace!==void 0?r:void 0}function Te(t){const e=[];for(const n of t.notes)e.push(n);for(const n of t.trace){const r=n.operations.join(","),s=`Rule #${n.ruleIndex} (${r})`;n.verdict==="ALLOW"?e.push(`${s} → ALLOW`):n.verdict==="DENY"?e.push(`${s} → deny`):n.verdict==="UNSUPPORTED"?e.push(`${s} → unsupported: ${n.message??""}`):e.push(`${s} → error: ${n.message??""}`)}return e.push(`Simulated: ${t.decision}`),e}Rn({function:Ka(["get","exists"]).describe("Cross-service Firestore function to mock"),path:gn().describe('Firestore document path in collection/doc form, e.g. "users/alice"'),result:kd([Ys(es()),Nl()]).describe("Document fields for get, boolean for exists")});class Dn extends Error{constructor(n,r,s){super(r);G(this,"code");G(this,"pos");this.name="EvalError",this.code=n,this.pos=s}}function $l(t){if(typeof t!="object"||t===null)return!1;const e=t,n=e.__type,r=Object.keys(e);switch(n){case"serverTimestamp":case"deleteField":return r.length===1;case"increment":return r.length===2&&typeof e.value=="number";case"arrayUnion":case"arrayRemove":return r.length===2&&Array.isArray(e.values);default:return!1}}function Qn(t,e){return new Dn("type-mismatch",e,t.pos)}function In(t,e){switch(t.kind){case"literal":return t.value;case"reference":return e2(t,e);case"sentinel":return t2(t,e);case"unary":return n2(t,e);case"binary":return r2(t,e);case"logical":return i2(t,e);case"ternary":return a2(t,e);case"fieldAccess":return o2(t,e);case"indexAccess":return l2(t,e)}}function e2(t,e){if(!Object.prototype.hasOwnProperty.call(e.reads,t.alias))throw new Dn("unknown-reference",`unknown alias '$${t.alias}' (not in reads). Hint: aliases are case-sensitive; sentinels use '@' not '$'.`,t.pos);return e.reads[t.alias]??null}function t2(t,e){const n=t.args.map(r=>{const s=In(r,e);if($l(s))throw new Dn("sentinel-misuse",`sentinel '@${s.__type}' cannot be a sentinel argument`,r.pos);return s});switch(t.name){case"serverTimestamp":return{__type:"serverTimestamp"};case"deleteField":return{__type:"deleteField"};case"increment":{const r=n[0];if(typeof r!="number")throw Qn(t,`'@increment' expects a numeric argument, got ${Kt(r)}`);return ed(r,t),{__type:"increment",value:r}}case"arrayUnion":return{__type:"arrayUnion",values:n};case"arrayRemove":return{__type:"arrayRemove",values:n}}}function n2(t,e){const n=In(t.operand,e);if(Am(n,t),t.op==="-"){if(typeof n!="number")throw Qn(t,`unary '-' expects a number, got ${Kt(n)}`);const r=-n;return ed(r,t),r}if(typeof n!="boolean")throw Qn(t,`unary '!' expects a boolean, got ${Kt(n)}`);return!n}function r2(t,e){const n=In(t.left,e),r=In(t.right,e);switch(Am(n,t),Am(r,t),t.op){case"+":if(typeof n=="number"&&typeof r=="number"){const s=n+r;return ed(s,t),s}if(typeof n=="string"&&typeof r=="string")return n+r;throw Qn(t,`'+' expects (number, number) or (string, string); got (${Kt(n)}, ${Kt(r)})`);case"-":case"*":case"/":case"%":{if(typeof n!="number"||typeof r!="number")throw Qn(t,`'${t.op}' expects (number, number); got (${Kt(n)}, ${Kt(r)})`);let s;switch(t.op){case"-":s=n-r;break;case"*":s=n*r;break;case"/":s=n/r;break;case"%":s=n%r;break}return ed(s,t),s}case"==":return jw(t,n,r);case"!=":return!jw(t,n,r);case"<":case"<=":case">":case">=":return s2(t,n,r)}}function jw(t,e,n){if(e===null||n===null)return e===n;const r=typeof e;if(r!==typeof n)return!1;if(r==="number"||r==="string"||r==="boolean")return e===n;throw Qn(t,"equality between objects/arrays is not supported (compare specific fields instead)")}function s2(t,e,n){if(!(typeof e=="number"&&typeof n=="number"||typeof e=="string"&&typeof n=="string"))throw Qn(t,`'${t.op}' expects matching number/number or string/string operands; got (${Kt(e)}, ${Kt(n)})`);switch(t.op){case"<":return e<n;case"<=":return e<=n;case">":return e>n;case">=":return e>=n;default:throw new Error("unreachable")}}function i2(t,e){const n=In(t.left,e);if(typeof n!="boolean")throw Qn(t,`'${t.op}' expects boolean operands; left is ${Kt(n)}`);if(t.op==="&&"){if(!n)return!1}else if(n)return!0;const r=In(t.right,e);if(typeof r!="boolean")throw Qn(t,`'${t.op}' expects boolean operands; right is ${Kt(r)}`);return r}function a2(t,e){const n=In(t.cond,e);if(typeof n!="boolean")throw Qn(t,`ternary condition must be boolean, got ${Kt(n)}`);return In(n?t.whenTrue:t.whenFalse,e)}function o2(t,e){const n=In(t.target,e);if(n==null)throw new Dn("null-access",`cannot access field '${t.field}' on null`,t.pos);if(typeof n!="object"||Array.isArray(n)||$l(n))throw Qn(t,`cannot access field '${t.field}' on ${Kt(n)}`);const r=n;return Object.prototype.hasOwnProperty.call(r,t.field)?r[t.field]:null}function l2(t,e){const n=In(t.target,e);if(n==null)throw new Dn("null-access","cannot index null target",t.pos);const r=In(t.index,e);if(Array.isArray(n)){if(typeof r!="number"||!Number.isInteger(r))throw new Dn("invalid-index",`array index must be a non-negative integer, got ${Kt(r)}`,t.pos);if(r<0)throw new Dn("invalid-index",`negative array index ${r} not supported (use length-based indexing in eval)`,t.pos);return r>=n.length?null:n[r]}if(typeof n=="object"&&!$l(n)){if(typeof r!="string")throw new Dn("invalid-index",`object key must be a string, got ${Kt(r)}`,t.pos);const s=n;return Object.prototype.hasOwnProperty.call(s,r)?s[r]:null}throw Qn(t,`cannot index into ${Kt(n)}`)}function Am(t,e){if($l(t))throw new Dn("sentinel-misuse",`sentinel '@${t.__type}' cannot be used as an operator operand`,e.pos)}function ed(t,e){if(!Number.isFinite(t))throw new Dn("division-by-zero",`arithmetic produced a non-finite value (${Number.isNaN(t)?"NaN":"Infinity"})`,e.pos)}function Kt(t){if(t===null)return"null";if(Array.isArray(t))return`array(${t.length})`;if(typeof t=="object"&&t!==null){if($l(t))return`sentinel '@${t.__type}'`;const e=Object.keys(t);if(e.length===0)return"object {}";const n=e.slice(0,3).join(", "),r=e.length>3?", …":"";return`object {${n}${r}}`}return typeof t}const V1="$expr";class td extends Error{constructor(n,r){super(n);G(this,"code","invalid-argument");G(this,"path");this.name="ExpressionWalkError",this.path=r}}function c2(t,e){return jm(t,e,"")}function jm(t,e,n){if(t===null)return null;if(typeof t!="object")return t;if(Array.isArray(t)){const o=new Array(t.length);for(let c=0;c<t.length;c+=1)o[c]=jm(t[c],e,n===""?String(c):`${n}.${c}`);return o}const r=t;if(Object.prototype.hasOwnProperty.call(r,V1))return u2(r,e,n);const s={};for(const o of Object.keys(r))s[o]=jm(r[o],e,n===""?o:`${n}.${o}`);return s}function u2(t,e,n){const r=Object.keys(t);if(r.length!==1)throw new td(`expression wrapper at '${n||"<root>"}' must have only the '$expr' key, got [${r.map(d=>JSON.stringify(d)).join(", ")}]`,n);const s=t[V1];if(typeof s!="string")throw new td(`'$expr' value at '${n||"<root>"}' must be a string, got ${h2(s)}`,n);const o=f2(s,n);return d2(o,e,n)}function d2(t,e,n){try{return In(t,e)}catch(r){if(r instanceof Dn){const s=new Dn(r.code,`at '${n||"<root>"}': ${r.message}`,r.pos);throw s.cause=r,s}throw r}}function f2(t,e){try{return gR(hR(t))}catch(n){throw n instanceof jt?kw(n,jt,e):n instanceof vr?kw(n,vr,e):n}}function kw(t,e,n){const r=new e(`at '${n||"<root>"}': ${t.message}`,t.pos);return r.cause=t,r}function h2(t){return t===null?"null":Array.isArray(t)?"array":typeof t}const H1=new Set(["get","exists","getAfter","debug"]);function nd(t){const e=[],n=r=>{switch(r.type){case"functionCall":e.push(r.name),r.args.forEach(n);break;case"binaryOp":n(r.left),n(r.right);break;case"unaryOp":n(r.operand);break;case"methodCall":n(r.object),r.args.forEach(n);break;case"memberAccess":n(r.object);break;case"bracketAccess":n(r.object),n(r.index);break;case"ternary":n(r.condition),n(r.consequent),n(r.alternate);break;case"inExpr":n(r.element),n(r.collection);break;case"isExpr":n(r.value);break;case"listLiteral":r.elements.forEach(n);break;case"mapLiteral":r.entries.forEach(s=>{n(s.key),n(s.value)});break}};return n(t),e}function p2(t){return t.replace(/^\.\.\//,"_").replace(/^\.\//,"").replace(/[.\/-]/g,"_")}function _t(t,e){switch(t.type){case"functionCall":{const n=e.get(t.name)??t.name,r=t.args.map(s=>_t(s,e));return n===t.name&&r.every((s,o)=>s===t.args[o])?t:{...t,name:n,args:r}}case"binaryOp":{const n=_t(t.left,e),r=_t(t.right,e);return n===t.left&&r===t.right?t:{...t,left:n,right:r}}case"unaryOp":{const n=_t(t.operand,e);return n===t.operand?t:{...t,operand:n}}case"methodCall":{const n=_t(t.object,e),r=t.args.map(s=>_t(s,e));return n===t.object&&r.every((s,o)=>s===t.args[o])?t:{...t,object:n,args:r}}case"memberAccess":{const n=_t(t.object,e);return n===t.object?t:{...t,object:n}}case"bracketAccess":{const n=_t(t.object,e),r=_t(t.index,e);return n===t.object&&r===t.index?t:{...t,object:n,index:r}}case"ternary":{const n=_t(t.condition,e),r=_t(t.consequent,e),s=_t(t.alternate,e);return n===t.condition&&r===t.consequent&&s===t.alternate?t:{...t,condition:n,consequent:r,alternate:s}}case"inExpr":{const n=_t(t.element,e),r=_t(t.collection,e);return n===t.element&&r===t.collection?t:{...t,element:n,collection:r}}case"isExpr":{const n=_t(t.value,e);return n===t.value?t:{...t,value:n}}case"listLiteral":{const n=t.elements.map(r=>_t(r,e));return n.every((r,s)=>r===t.elements[s])?t:{...t,elements:n}}case"mapLiteral":{const n=t.entries.map(r=>{const s=_t(r.key,e),o=_t(r.value,e);return s===r.key&&o===r.value?r:{key:s,value:o}});return n.every((r,s)=>r===t.entries[s])?t:{...t,entries:n}}default:return t}}function m2(t,e){const n=p2(e),r=new Map;for(const s of t)s.exported||r.set(s.name,`${n}__${s.name}`);return r.size===0?t:t.map(s=>{const o=_t(s.body,r),c=s.lets.map(f=>{const p=_t(f.value,r);return p===f.value?f:{...f,value:p}}),d=s.exported?s.name:r.get(s.name)??s.name;return o===s.body&&c===s.lets&&d===s.name?s:{...s,name:d,body:o,lets:c}})}function G1(t,e,n=new Set){if(n.has(t))return[];n.add(t);const r=e.get(t);if(!r)return[];const s=[],o=nd(r.body);for(const c of r.lets)o.push(...nd(c.value));for(const c of o)e.has(c)&&!H1.has(c)&&(s.push(c),s.push(...G1(c,e,n)));return s}function Rp(t,e){const n=zO(t);return n?{success:!0,functions:n}:{success:!1,error:{code:"PARSE_FAILED",message:`Failed to parse module '${e}'`}}}function Cw(t){return t.startsWith("./")||t.startsWith("../")}function y2(t,e,n){if(n!=null&&n.modules&&e in n.modules)return Rp(n.modules[e],e);if(Cw(e)&&(n!=null&&n.basePath)){const s=`${n.basePath}/${e}.rules`,o=(t==null?void 0:t.readRelative(n.basePath,e))??null;return o===null?{success:!1,error:{code:"UNKNOWN_MODULE",message:`Module '${e}' not found at ${s}`}}:Rp(o,e)}if(Cw(e))return{success:!1,error:{code:"UNKNOWN_MODULE",message:`Module '${e}' requires basePath for relative imports`}};const r=(t==null?void 0:t.readStdlib(e))??null;return r===null?{success:!1,error:{code:"UNKNOWN_MODULE",message:`Module '${e}' not found`}}:Rp(r,e)}function g2(t,e,n){var k;const r=$u(e);if(!r.ok){const{line:R,column:C,message:T}=r.error;return{success:!1,error:{code:"PARSE_FAILED",message:`Failed to parse source at line ${R}, col ${C}: ${T}`}}}const s=r.ast;if(s.version!=="2+modules")return{success:!1,error:{code:"NOT_MODULE_SOURCE",message:`Version '${s.version}' is not a module source`}};if(s.imports.length===0)return s.version="2",{success:!0,data:{resolved:rw(s),modules:[]}};const o=new Map,c=new Map,d=new Map,f=[],p=new Map;for(const R of s.imports){const C=y2(t,R.module,n);if(!C.success)return{success:!1,error:C.error};f.includes(R.module)||f.push(R.module);const T=new Set;for(const q of C.functions)q.exported||T.add(q.name);p.set(R.module,T);const U=m2(C.functions,R.module);for(const q of U)if(c.set(q.name,q),q.exported){if(o.has(q.name)&&d.get(q.name)!==R.module)return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Function '${q.name}' exported by both '${d.get(q.name)}' and '${R.module}'`}};o.set(q.name,q),d.set(q.name,R.module)}for(const q of R.functions)if(!o.has(q))return{success:!1,error:{code:"UNKNOWN_FUNCTION",message:((k=p.get(R.module))==null?void 0:k.has(q))?`Function '${q}' in module '${R.module}' is not exported`:`Function '${q}' not found in module '${R.module}'`}}}const g=new Set;for(const R of s.imports)for(const C of R.functions){g.add(C);for(const T of G1(C,c))g.add(T)}const b=[],v=new Set;function x(R){if(v.has(R))return;v.add(R);const C=c.get(R);if(!C)return;const T=nd(C.body);for(const U of C.lets)T.push(...nd(U.value));for(const U of T)c.has(U)&&!H1.has(U)&&x(U);b.push({...C,exported:!1})}for(const R of s.imports)for(const C of R.functions)x(C);const _=new Set(s.service.match.functions.map(R=>R.name));for(const R of b)if(_.has(R.name))return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Imported function '${R.name}' conflicts with a function defined in the source`}};return s.service.match.functions=[...b,...s.service.match.functions],s.version="2",s.imports=[],{success:!0,data:{resolved:rw(s),modules:f}}}const b2={atomic:`// Atomic module — cross-document integrity for BATCH writes, via the
|
|
531
|
-
// get()/getAfter() pair. Firestore evaluates every write in a batch
|
|
532
|
-
// against rules, and getAfter() returns another document's POST-BATCH
|
|
533
|
-
// state — so a rule can require "this write is only valid if a
|
|
534
|
-
// companion write happened in the same atomic batch".
|
|
535
|
-
//
|
|
536
|
-
// All semantics live-verified against a production database: companion
|
|
537
|
-
// visibility, solo-write denial, wrong-delta denial, single-use consumption
|
|
538
|
-
// incl. replay denial, and out-of-batch getAfter() falling back to current
|
|
539
|
-
// state.
|
|
540
|
-
//
|
|
541
|
-
// Explicit-param design: pass BOTH states of the companion doc —
|
|
542
|
-
// \`get(path).data\` (pre-batch) and \`getAfter(path).data\` (post-batch).
|
|
543
|
-
//
|
|
544
|
-
// import { companionChangedBy, consumedFlag } from 'atomic';
|
|
545
|
-
//
|
|
546
|
-
// // Denormalized counter: creating a task REQUIRES the team's
|
|
547
|
-
// // taskCount to have been incremented in the same batch:
|
|
548
|
-
// match /teams/{teamId}/tasks/{taskId} {
|
|
549
|
-
// function teamBefore() {
|
|
550
|
-
// return get(/databases/$(database)/documents/teams/$(teamId)).data;
|
|
551
|
-
// }
|
|
552
|
-
// function teamAfter() {
|
|
553
|
-
// return getAfter(/databases/$(database)/documents/teams/$(teamId)).data;
|
|
554
|
-
// }
|
|
555
|
-
// allow create: if companionChangedBy(teamBefore(), teamAfter(), 'taskCount', 1);
|
|
556
|
-
// }
|
|
557
|
-
//
|
|
558
|
-
// // Single-use invite: the join is valid only when the invite was
|
|
559
|
-
// // consumed (false -> true) IN THIS BATCH — replays deny because
|
|
560
|
-
// // the pre-batch state is already true:
|
|
561
|
-
// allow update: if consumedFlag(inviteBefore(), inviteAfter(), 'used');
|
|
562
|
-
//
|
|
563
|
-
// NOTE (simulator): in-batch companion semantics cannot be expressed
|
|
564
|
-
// in the simulator or the Rules Test API mock surface — the simulator
|
|
565
|
-
// treats cross-doc getAfter() as get(). These function BODIES are
|
|
566
|
-
// simulator-tested with explicit values; the getAfter() WIRING is the
|
|
567
|
-
// live v1 scope's job. Companion writes need their own allow rules too —
|
|
568
|
-
// every write in a batch is evaluated.
|
|
569
|
-
|
|
570
|
-
// The companion doc's field changed by EXACTLY n in this batch.
|
|
571
|
-
// before/after are the SAME doc's get()/getAfter() data.
|
|
572
|
-
export function companionChangedBy(before, after, field, n) {
|
|
573
|
-
return after[field] == before[field] + n;
|
|
574
|
-
}
|
|
575
|
-
|
|
576
|
-
// A single-use flag was consumed IN THIS BATCH: pre-batch false,
|
|
577
|
-
// post-batch true. Replays deny (pre-batch is already true), and a
|
|
578
|
-
// solo write denies (getAfter == get, so false != true).
|
|
579
|
-
export function consumedFlag(before, after, flagField) {
|
|
580
|
-
return before[flagField] == false && after[flagField] == true;
|
|
581
|
-
}
|
|
582
|
-
`,auth:`export function isAuthenticated() {
|
|
583
|
-
return request.auth != null;
|
|
584
|
-
}
|
|
585
|
-
|
|
586
|
-
export function isOwner(userId) {
|
|
587
|
-
return isAuthenticated() && request.auth.uid == userId;
|
|
588
|
-
}
|
|
589
|
-
`,content:`// Content module for author-owned documents — the most common
|
|
590
|
-
// Firebase app shape (posts, notes, docs, comments, tasks).
|
|
591
|
-
//
|
|
592
|
-
// Convention: documents carry an author field (a UID string) and
|
|
593
|
-
// usually a status field ('draft' | 'published' | ...). Field names
|
|
594
|
-
// are parameters, not conventions — pass yours.
|
|
595
|
-
//
|
|
596
|
-
// Usage:
|
|
597
|
-
// import { validAuthorCreate, isAuthor, canReadContent, notDeleted } from 'content';
|
|
598
|
-
// import { onlyFieldsChanged } from 'lifecycle';
|
|
599
|
-
//
|
|
600
|
-
// match /posts/{postId} {
|
|
601
|
-
// // Create: author is the signed-in user.
|
|
602
|
-
// allow create: if validAuthorCreate('author');
|
|
603
|
-
// // Read: published to everyone, drafts to the author only.
|
|
604
|
-
// allow read: if canReadContent('status', 'author') && notDeleted();
|
|
605
|
-
// // Update: author edits content fields; authorship immutable.
|
|
606
|
-
// allow update: if isAuthor('author') && onlyFieldsChanged(['title', 'body', 'status']);
|
|
607
|
-
// allow delete: if isAuthor('author');
|
|
608
|
-
// }
|
|
609
|
-
|
|
610
|
-
// Create guard: signed in, and the incoming doc's author field is the
|
|
611
|
-
// caller. Use on \`create\` (reads request.resource).
|
|
612
|
-
export function validAuthorCreate(authorField) {
|
|
613
|
-
return request.auth != null
|
|
614
|
-
&& request.resource.data[authorField] == request.auth.uid;
|
|
615
|
-
}
|
|
616
|
-
|
|
617
|
-
// The caller is the EXISTING document's author. Use on update/delete
|
|
618
|
-
// (reads resource).
|
|
619
|
-
export function isAuthor(authorField) {
|
|
620
|
-
return request.auth != null
|
|
621
|
-
&& resource.data[authorField] == request.auth.uid;
|
|
622
|
-
}
|
|
623
|
-
|
|
624
|
-
// Read visibility: published content is public; anything else is
|
|
625
|
-
// visible to its author only. Works for get; for list queries the
|
|
626
|
-
// client must filter (rules are not filters — a bare collection query
|
|
627
|
-
// will be denied unless it proves status == 'published').
|
|
628
|
-
export function canReadContent(statusField, authorField) {
|
|
629
|
-
return resource.data[statusField] == 'published'
|
|
630
|
-
|| (request.auth != null && resource.data[authorField] == request.auth.uid);
|
|
631
|
-
}
|
|
632
|
-
|
|
633
|
-
// Soft-delete guard: the document is not marked deleted. Reads the
|
|
634
|
-
// EXISTING doc; a doc without the field passes — bracket access is
|
|
635
|
-
// the null-on-miss idiom (dotted access of a missing key ERRORS).
|
|
636
|
-
export function notDeleted() {
|
|
637
|
-
return resource.data['deleted'] != true;
|
|
638
|
-
}
|
|
639
|
-
`,counters:`// Counters module for denormalized numeric integrity.
|
|
640
|
-
//
|
|
641
|
-
// The recurring shape: a client-maintained count (likes, votes, moves,
|
|
642
|
-
// quantities) that rules must keep honest — it may only change by a
|
|
643
|
-
// known step, or stay within known bounds. Generalizes the
|
|
644
|
-
// state-module's moveIncremented() (hardcoded to moveCount) to any
|
|
645
|
-
// field.
|
|
646
|
-
//
|
|
647
|
-
// Usage:
|
|
648
|
-
// import { incrementedBy, changedBy, boundedNumber } from 'counters';
|
|
649
|
-
//
|
|
650
|
-
// // A like toggle: likeCount moves by exactly ±1:
|
|
651
|
-
// allow update: if changedBy('likeCount', -1, 1);
|
|
652
|
-
//
|
|
653
|
-
// // A move counter: strictly +1 per move:
|
|
654
|
-
// allow update: if incrementedBy('moveCount', 1);
|
|
655
|
-
//
|
|
656
|
-
// // A rating: any write keeps it in [1, 5]:
|
|
657
|
-
// allow write: if boundedNumber('rating', 1, 5);
|
|
658
|
-
|
|
659
|
-
// The field changed by EXACTLY n relative to the existing document.
|
|
660
|
-
// n may be negative (decrement). Update rules only (needs resource).
|
|
661
|
-
export function incrementedBy(field, n) {
|
|
662
|
-
return request.resource.data[field] == resource.data[field] + n;
|
|
663
|
-
}
|
|
664
|
-
|
|
665
|
-
// The field's delta is within [min, max] (inclusive) — and it is NOT
|
|
666
|
-
// required to change (delta 0 passes when min <= 0 <= max).
|
|
667
|
-
export function changedBy(field, min, max) {
|
|
668
|
-
return request.resource.data[field] - resource.data[field] >= min
|
|
669
|
-
&& request.resource.data[field] - resource.data[field] <= max;
|
|
670
|
-
}
|
|
671
|
-
|
|
672
|
-
// The incoming value is a number within [min, max] (inclusive).
|
|
673
|
-
// Works on create and update. Missing field reads null (dynamic
|
|
674
|
-
// access) and fails the type check rather than erroring.
|
|
675
|
-
export function boundedNumber(field, min, max) {
|
|
676
|
-
return (request.resource.data[field] is int || request.resource.data[field] is float)
|
|
677
|
-
&& request.resource.data[field] >= min
|
|
678
|
-
&& request.resource.data[field] <= max;
|
|
679
|
-
}
|
|
680
|
-
`,geometry:`// Geometry module for movement game validation via config document lookup.
|
|
681
|
-
//
|
|
682
|
-
// Caller must pass the config document data as an explicit parameter.
|
|
683
|
-
// The config doc is read via get() and cached per request — define a
|
|
684
|
-
// config() function in your rules and pass its result to these functions.
|
|
685
|
-
//
|
|
686
|
-
// Config doc schema:
|
|
687
|
-
// moves[pieceType][fromCell][toCell] = true
|
|
688
|
-
// jumps[pieceType][fromCell][toCell] = capturedCellName
|
|
689
|
-
//
|
|
690
|
-
// Usage:
|
|
691
|
-
// import { validSimpleMove, validJumpMove } from 'geometry';
|
|
692
|
-
//
|
|
693
|
-
// function config() {
|
|
694
|
-
// return get(/databases/$(database)/documents/gameConfig/checkers).data;
|
|
695
|
-
// }
|
|
696
|
-
//
|
|
697
|
-
// allow update: if validSimpleMove(config())
|
|
698
|
-
// && piecePlaced() && moveIntegrity();
|
|
699
|
-
//
|
|
700
|
-
// allow update: if validJumpMove(config())
|
|
701
|
-
// && captureValid() && captureDecrement() && moveIntegrity();
|
|
702
|
-
|
|
703
|
-
// Validate a simple (non-capture) move via config document lookup.
|
|
704
|
-
// Uses 3-level dynamic nesting: cfg.moves[piece][from][to].
|
|
705
|
-
// piece comes from resource.data (pre-write board) so client can't fake it.
|
|
706
|
-
export function validSimpleMove(cfg) {
|
|
707
|
-
let mf = request.resource.data.moveFrom;
|
|
708
|
-
let mt = request.resource.data.moveTo;
|
|
709
|
-
let piece = resource.data[mf];
|
|
710
|
-
return cfg.moves[piece][mf][mt] == true;
|
|
711
|
-
}
|
|
712
|
-
|
|
713
|
-
// Validate a jump (capture) move via config document lookup.
|
|
714
|
-
// cfg.jumps[piece][from][to] returns the expected captured cell name.
|
|
715
|
-
// Caller must separately verify the captured piece is an opponent piece.
|
|
716
|
-
export function validJumpMove(cfg) {
|
|
717
|
-
let mf = request.resource.data.moveFrom;
|
|
718
|
-
let mt = request.resource.data.moveTo;
|
|
719
|
-
let cap = request.resource.data.captured;
|
|
720
|
-
let piece = resource.data[mf];
|
|
721
|
-
return cfg.jumps[piece][mf][mt] == cap;
|
|
722
|
-
}
|
|
723
|
-
`,joining:`// Joining module — how membership CHANGES, safely. The connective
|
|
724
|
-
// tissue between content/spaces: spaces gates children behind a
|
|
725
|
-
// members field; joining lets users enter and leave that field
|
|
726
|
-
// WITHOUT an admin backend, with no privilege escalation.
|
|
727
|
-
//
|
|
728
|
-
// Convention: a MAP-shaped members field (uid -> role) on the parent
|
|
729
|
-
// doc. Compose with lifecycle's onlyFieldsChanged so a join/leave
|
|
730
|
-
// write can't touch anything else:
|
|
731
|
-
//
|
|
732
|
-
// import { onlyAddedSelf, onlyRemovedSelf } from 'joining';
|
|
733
|
-
// import { onlyFieldsChanged } from 'lifecycle';
|
|
734
|
-
// import { isSpaceMember, hasSpaceRole } from 'spaces';
|
|
735
|
-
//
|
|
736
|
-
// match /teams/{teamId} {
|
|
737
|
-
// allow read: if isSpaceMember(resource.data);
|
|
738
|
-
//
|
|
739
|
-
// // Open self-service join (public team) at a fixed role, and
|
|
740
|
-
// // self-service leave — nothing else about the doc may change:
|
|
741
|
-
// allow update: if onlyFieldsChanged(['members'])
|
|
742
|
-
// && (onlyAddedSelf('members', 'editor') || onlyRemovedSelf('members'));
|
|
743
|
-
// // Admins manage the doc freely:
|
|
744
|
-
// allow update: if hasSpaceRole(resource.data, 'admin');
|
|
745
|
-
// }
|
|
746
|
-
//
|
|
747
|
-
// Every guarantee here is production-verified against the live Rules Test API:
|
|
748
|
-
// the field-level map diff is reliable; the empty no-op diff DENIES (set
|
|
749
|
-
// equality, not hasOnly — hasOnly on an empty set passes); role escalation via
|
|
750
|
-
// CHANGING an existing entry denies; adding or removing anyone else denies.
|
|
751
|
-
|
|
752
|
-
// The write adds EXACTLY the caller to the members map, at EXACTLY
|
|
753
|
-
// \`role\`, changing and removing nobody. Update rules only.
|
|
754
|
-
export function onlyAddedSelf(membersField, role) {
|
|
755
|
-
let diff = request.resource.data[membersField].diff(resource.data[membersField]);
|
|
756
|
-
return request.auth != null
|
|
757
|
-
&& diff.addedKeys() == [request.auth.uid].toSet()
|
|
758
|
-
&& diff.changedKeys().size() == 0
|
|
759
|
-
&& diff.removedKeys().size() == 0
|
|
760
|
-
&& request.resource.data[membersField][request.auth.uid] == role;
|
|
761
|
-
}
|
|
762
|
-
|
|
763
|
-
// The write removes EXACTLY the caller from the members map, adding
|
|
764
|
-
// and changing nobody. Self-service leave. Update rules only.
|
|
765
|
-
export function onlyRemovedSelf(membersField) {
|
|
766
|
-
let diff = request.resource.data[membersField].diff(resource.data[membersField]);
|
|
767
|
-
return request.auth != null
|
|
768
|
-
&& diff.removedKeys() == [request.auth.uid].toSet()
|
|
769
|
-
&& diff.addedKeys().size() == 0
|
|
770
|
-
&& diff.changedKeys().size() == 0;
|
|
771
|
-
}
|
|
772
|
-
`,lifecycle:`// Lifecycle module for field immutability and timestamp enforcement.
|
|
773
|
-
//
|
|
774
|
-
// Common pattern: certain fields must never change after document creation
|
|
775
|
-
// (createdBy, createdAt, authorId).
|
|
776
|
-
//
|
|
777
|
-
// Usage:
|
|
778
|
-
// import { fieldUnchanged, immutableFields, isServerTimestamp } from 'lifecycle';
|
|
779
|
-
//
|
|
780
|
-
// // Single field:
|
|
781
|
-
// allow update: if fieldUnchanged('createdBy');
|
|
782
|
-
//
|
|
783
|
-
// // Multiple fields (replaces chained fieldUnchanged calls):
|
|
784
|
-
// allow update: if immutableFields(['createdBy', 'createdAt', 'authorId']);
|
|
785
|
-
//
|
|
786
|
-
// // The dual: users may edit title/body but NOTHING else:
|
|
787
|
-
// allow update: if onlyFieldsChanged(['title', 'body']);
|
|
788
|
-
//
|
|
789
|
-
// allow create: if isServerTimestamp('createdAt');
|
|
790
|
-
|
|
791
|
-
// Ensure a field's value is identical between existing and incoming document.
|
|
792
|
-
// Use on update rules to enforce immutability.
|
|
793
|
-
export function fieldUnchanged(field) {
|
|
794
|
-
return resource.data[field] == request.resource.data[field];
|
|
795
|
-
}
|
|
796
|
-
|
|
797
|
-
// Ensure multiple fields are unchanged between existing and incoming document.
|
|
798
|
-
// Uses MapDiff — one expression instead of N chained fieldUnchanged() calls.
|
|
799
|
-
export function immutableFields(fields) {
|
|
800
|
-
return request.resource.data.diff(resource.data).unchangedKeys().hasAll(fields);
|
|
801
|
-
}
|
|
802
|
-
|
|
803
|
-
// Ensure a field is set to the server timestamp.
|
|
804
|
-
// Use on create or update rules to enforce server-side time.
|
|
805
|
-
export function isServerTimestamp(field) {
|
|
806
|
-
return request.resource.data[field] == request.time;
|
|
807
|
-
}
|
|
808
|
-
|
|
809
|
-
// The dual of immutableFields: every changed field is in the allowed
|
|
810
|
-
// list (fields NOT listed are implicitly immutable). Top-level keys
|
|
811
|
-
// only — nested-map diffs are unreliable in production; flatten the
|
|
812
|
-
// schema instead of reaching for a nested diff.
|
|
813
|
-
export function onlyFieldsChanged(fields) {
|
|
814
|
-
return request.resource.data.diff(resource.data).affectedKeys().hasOnly(fields);
|
|
815
|
-
}
|
|
816
|
-
|
|
817
|
-
// Exactly n top-level fields changed in this write. n == 1 is the
|
|
818
|
-
// board-integrity / edit-one-field-per-write guard (Pattern 5,
|
|
819
|
-
// generalized beyond games).
|
|
820
|
-
export function nFieldsChanged(n) {
|
|
821
|
-
return request.resource.data.diff(resource.data).affectedKeys().size() == n;
|
|
822
|
-
}
|
|
823
|
-
`,lobby:`// Lobby module for 2-participant coordination.
|
|
824
|
-
//
|
|
825
|
-
// Convention: documents must have these fields:
|
|
826
|
-
// host: string (creator's UID)
|
|
827
|
-
// guest: string ('' when waiting, joiner's UID when joined)
|
|
828
|
-
// status: 'waiting' | 'playing' | 'ready' (or any active state)
|
|
829
|
-
//
|
|
830
|
-
// Usage:
|
|
831
|
-
// import { validCreate, validJoin, canCancel } from 'lobby';
|
|
832
|
-
//
|
|
833
|
-
// allow create: if validCreate();
|
|
834
|
-
// allow update: if validJoin();
|
|
835
|
-
// allow delete: if canCancel();
|
|
836
|
-
|
|
837
|
-
// Is this a waiting lobby with an open seat?
|
|
838
|
-
function isWaiting() {
|
|
839
|
-
return resource.data.status == 'waiting'
|
|
840
|
-
&& resource.data.guest == '';
|
|
841
|
-
}
|
|
842
|
-
|
|
843
|
-
// Create: caller is host, seat empty, status waiting
|
|
844
|
-
export function validCreate() {
|
|
845
|
-
return request.auth != null
|
|
846
|
-
&& request.resource.data.host == request.auth.uid
|
|
847
|
-
&& request.resource.data.guest == ''
|
|
848
|
-
&& request.resource.data.status == 'waiting';
|
|
849
|
-
}
|
|
850
|
-
|
|
851
|
-
// Join: fill empty seat, transition to next status, no self-join
|
|
852
|
-
export function validJoin() {
|
|
853
|
-
return request.auth != null
|
|
854
|
-
&& isWaiting()
|
|
855
|
-
&& request.resource.data.guest == request.auth.uid
|
|
856
|
-
&& request.auth.uid != resource.data.host
|
|
857
|
-
&& request.resource.data.status == 'playing'
|
|
858
|
-
&& request.resource.data.host == resource.data.host;
|
|
859
|
-
}
|
|
860
|
-
|
|
861
|
-
// Cancel: only host, only while waiting
|
|
862
|
-
export function canCancel() {
|
|
863
|
-
return request.auth != null
|
|
864
|
-
&& resource.data.status == 'waiting'
|
|
865
|
-
&& request.auth.uid == resource.data.host;
|
|
866
|
-
}
|
|
867
|
-
`,membership:`// Membership module for role-based and claims-based access control.
|
|
868
|
-
//
|
|
869
|
-
// Two access patterns:
|
|
870
|
-
// 1. Custom claims on auth token (0 get() calls, set server-side)
|
|
871
|
-
// 2. Member maps on documents (0 get() calls on the doc itself)
|
|
872
|
-
//
|
|
873
|
-
// Usage:
|
|
874
|
-
// import { hasClaim, hasClaimRole, isMemberOf, hasRole } from 'membership';
|
|
875
|
-
//
|
|
876
|
-
// // Workspace access via custom claims
|
|
877
|
-
// allow read: if hasClaim('workspace_id');
|
|
878
|
-
// allow write: if hasClaimRole('workspace_role', 'admin');
|
|
879
|
-
//
|
|
880
|
-
// // Project access via member map on document
|
|
881
|
-
// allow read: if isMemberOf(resource.data.members);
|
|
882
|
-
// allow update: if hasRole(resource.data.members, 'admin');
|
|
883
|
-
|
|
884
|
-
// Check if the auth token has a non-null value for a claim key.
|
|
885
|
-
export function hasClaim(claim) {
|
|
886
|
-
return request.auth != null
|
|
887
|
-
&& request.auth.token[claim] != null;
|
|
888
|
-
}
|
|
889
|
-
|
|
890
|
-
// Check if the auth token has a specific value for a claim key.
|
|
891
|
-
export function hasClaimRole(claim, role) {
|
|
892
|
-
return request.auth != null
|
|
893
|
-
&& request.auth.token[claim] == role;
|
|
894
|
-
}
|
|
895
|
-
|
|
896
|
-
// Check if the caller's UID exists as a key in a members map.
|
|
897
|
-
export function isMemberOf(membersMap) {
|
|
898
|
-
return request.auth != null
|
|
899
|
-
&& request.auth.uid in membersMap;
|
|
900
|
-
}
|
|
901
|
-
|
|
902
|
-
// Check if the caller has a specific role in a members map.
|
|
903
|
-
export function hasRole(membersMap, role) {
|
|
904
|
-
return request.auth != null
|
|
905
|
-
&& membersMap[request.auth.uid] == role;
|
|
906
|
-
}
|
|
907
|
-
`,spaces:`// Spaces module — cross-document membership gating for shared spaces
|
|
908
|
-
// (teams, rooms, groups, projects, parties). The second-most-common
|
|
909
|
-
// app shape after author-owned content: a PARENT document defines who
|
|
910
|
-
// may touch its children.
|
|
911
|
-
//
|
|
912
|
-
// Explicit-param design (like geometry): the caller reads the parent
|
|
913
|
-
// doc ONCE via a helper and passes its data in. Define the helper in
|
|
914
|
-
// your rules — get() is cached per request, so every function below
|
|
915
|
-
// can share one read (of the 10-get budget):
|
|
916
|
-
//
|
|
917
|
-
// import { isSpaceMember, hasSpaceRole, validMemberCreate } from 'spaces';
|
|
918
|
-
//
|
|
919
|
-
// match /spaces/{spaceId}/tasks/{taskId} {
|
|
920
|
-
// function space() {
|
|
921
|
-
// return get(/databases/$(database)/documents/spaces/$(spaceId)).data;
|
|
922
|
-
// }
|
|
923
|
-
// allow read: if isSpaceMember(space());
|
|
924
|
-
// allow create: if validMemberCreate(space(), 'author');
|
|
925
|
-
// allow delete: if hasSpaceRole(space(), 'admin');
|
|
926
|
-
// }
|
|
927
|
-
//
|
|
928
|
-
// Members field shapes verified against the production engine:
|
|
929
|
-
// list: members: ['uidA', 'uidB'] → isSpaceMember only
|
|
930
|
-
// map: members: { uidA: 'admin', ... } → isSpaceMember + hasSpaceRole
|
|
931
|
-
// A missing members field, a non-member uid, or a missing parent doc
|
|
932
|
-
// (get() of a missing doc errors) all fail CLOSED.
|
|
933
|
-
|
|
934
|
-
// The caller is in the space's members field. \`in\` covers both
|
|
935
|
-
// shapes: list membership and map keys.
|
|
936
|
-
export function isSpaceMember(spaceData) {
|
|
937
|
-
return request.auth != null && request.auth.uid in spaceData.members;
|
|
938
|
-
}
|
|
939
|
-
|
|
940
|
-
// The caller's role in a MAP-shaped members field equals \`role\`.
|
|
941
|
-
// List-shaped members carry no roles — this denies on them.
|
|
942
|
-
export function hasSpaceRole(spaceData, role) {
|
|
943
|
-
return request.auth != null && spaceData.members[request.auth.uid] == role;
|
|
944
|
-
}
|
|
945
|
-
|
|
946
|
-
// Member-gated authored create: the caller is a member AND the
|
|
947
|
-
// incoming child doc's author field is the caller. The "post a
|
|
948
|
-
// message / add a task" guard.
|
|
949
|
-
export function validMemberCreate(spaceData, authorField) {
|
|
950
|
-
return isSpaceMember(spaceData)
|
|
951
|
-
&& request.resource.data[authorField] == request.auth.uid;
|
|
952
|
-
}
|
|
953
|
-
`,state:`// Game state machine helpers.
|
|
954
|
-
//
|
|
955
|
-
// Convention: documents must have these fields:
|
|
956
|
-
// status: 'waiting' | 'playing' | 'won' | 'draw'
|
|
957
|
-
// moveCount: number
|
|
958
|
-
// host: string (UID)
|
|
959
|
-
// guest: string (UID)
|
|
960
|
-
//
|
|
961
|
-
// Usage:
|
|
962
|
-
// import { isPlaying, moveIncremented, participantsUnchanged } from 'state';
|
|
963
|
-
//
|
|
964
|
-
// allow update: if isPlaying() && moveIncremented() && participantsUnchanged();
|
|
965
|
-
|
|
966
|
-
// Is the game actively in play?
|
|
967
|
-
export function isPlaying() {
|
|
968
|
-
return resource.data.status == 'playing';
|
|
969
|
-
}
|
|
970
|
-
|
|
971
|
-
// Did moveCount increment by exactly 1?
|
|
972
|
-
export function moveIncremented() {
|
|
973
|
-
return request.resource.data.moveCount == resource.data.moveCount + 1;
|
|
974
|
-
}
|
|
975
|
-
|
|
976
|
-
// Are host and guest unchanged? (prevents mid-game identity swap)
|
|
977
|
-
export function participantsUnchanged() {
|
|
978
|
-
return request.resource.data.host == resource.data.host
|
|
979
|
-
&& request.resource.data.guest == resource.data.guest;
|
|
980
|
-
}
|
|
981
|
-
`,timing:`// Timing module for cooldown / rate-limit enforcement.
|
|
982
|
-
//
|
|
983
|
-
// Rules CAN rate-limit (contrary to a common assumption — jrpg
|
|
984
|
-
// FINDINGS F-004): compare request.time against a stored server
|
|
985
|
-
// timestamp. Pair with lifecycle's isServerTimestamp on the SAME
|
|
986
|
-
// write so the stored timestamp cannot be forged by the client:
|
|
987
|
-
//
|
|
988
|
-
// import { cooldownElapsed } from 'timing';
|
|
989
|
-
// import { isServerTimestamp } from 'lifecycle';
|
|
990
|
-
//
|
|
991
|
-
// // At most one move every 2 seconds:
|
|
992
|
-
// allow update: if cooldownElapsed('lastMoveAt', 2)
|
|
993
|
-
// && isServerTimestamp('lastMoveAt');
|
|
994
|
-
|
|
995
|
-
// The stored timestamp is more than \`seconds\` old (strict). Update
|
|
996
|
-
// rules only — needs \`resource\`. The field must be a Timestamp; a
|
|
997
|
-
// missing field errors, which denies (fail-closed).
|
|
998
|
-
export function cooldownElapsed(field, seconds) {
|
|
999
|
-
return request.time > resource.data[field] + duration.value(seconds, 's');
|
|
1000
|
-
}
|
|
1001
|
-
`,transitions:`// Transitions module for state machine enforcement.
|
|
1002
|
-
//
|
|
1003
|
-
// Validates that a field transitions from one known value to another.
|
|
1004
|
-
// Use to enforce valid status flows (e.g., open -> in_progress -> completed).
|
|
1005
|
-
//
|
|
1006
|
-
// Usage:
|
|
1007
|
-
// import { validTransition, statusIs, newStatusIs } from 'transitions';
|
|
1008
|
-
//
|
|
1009
|
-
// // Only allow open -> in_progress
|
|
1010
|
-
// allow update: if validTransition('status', 'open', 'in_progress');
|
|
1011
|
-
//
|
|
1012
|
-
// // Allow update only when currently active
|
|
1013
|
-
// allow update: if statusIs('status', 'active');
|
|
1014
|
-
//
|
|
1015
|
-
// // Compound: multiple valid transitions via OR
|
|
1016
|
-
// allow update: if validTransition('status', 'open', 'in_progress')
|
|
1017
|
-
// || validTransition('status', 'in_progress', 'completed')
|
|
1018
|
-
// || validTransition('status', 'completed', 'archived');
|
|
1019
|
-
|
|
1020
|
-
// Check that a field transitions from one value to another.
|
|
1021
|
-
export function validTransition(field, from, to) {
|
|
1022
|
-
return resource.data[field] == from
|
|
1023
|
-
&& request.resource.data[field] == to;
|
|
1024
|
-
}
|
|
1025
|
-
|
|
1026
|
-
// Check the current (existing) value of a field.
|
|
1027
|
-
export function statusIs(field, value) {
|
|
1028
|
-
return resource.data[field] == value;
|
|
1029
|
-
}
|
|
1030
|
-
|
|
1031
|
-
// Check the incoming (new) value of a field.
|
|
1032
|
-
export function newStatusIs(field, value) {
|
|
1033
|
-
return request.resource.data[field] == value;
|
|
1034
|
-
}
|
|
1035
|
-
`,turns:`// Turn enforcement for 2-participant games/sessions.
|
|
1036
|
-
//
|
|
1037
|
-
// Convention: documents must have these fields:
|
|
1038
|
-
// host: string (UID)
|
|
1039
|
-
// guest: string (UID)
|
|
1040
|
-
// currentTurn: 'host' | 'guest'
|
|
1041
|
-
//
|
|
1042
|
-
// Usage:
|
|
1043
|
-
// import { isMyTurn, turnFlipped } from 'turns';
|
|
1044
|
-
//
|
|
1045
|
-
// allow update: if isMyTurn() && turnFlipped();
|
|
1046
|
-
|
|
1047
|
-
// Is the caller the participant whose turn it is?
|
|
1048
|
-
export function isMyTurn() {
|
|
1049
|
-
return (resource.data.currentTurn == 'host'
|
|
1050
|
-
&& request.auth.uid == resource.data.host)
|
|
1051
|
-
|| (resource.data.currentTurn == 'guest'
|
|
1052
|
-
&& request.auth.uid == resource.data.guest);
|
|
1053
|
-
}
|
|
1054
|
-
|
|
1055
|
-
// Did the turn alternate?
|
|
1056
|
-
export function turnFlipped() {
|
|
1057
|
-
return (resource.data.currentTurn == 'host'
|
|
1058
|
-
&& request.resource.data.currentTurn == 'guest')
|
|
1059
|
-
|| (resource.data.currentTurn == 'guest'
|
|
1060
|
-
&& request.resource.data.currentTurn == 'host');
|
|
1061
|
-
}
|
|
1062
|
-
`,validation:`// Validation module for document field shape and value checks.
|
|
1063
|
-
//
|
|
1064
|
-
// Usage:
|
|
1065
|
-
// import { hasRequired, hasOnly, validString, isOneOf } from 'validation';
|
|
1066
|
-
//
|
|
1067
|
-
// allow create: if hasRequired(['title', 'status'])
|
|
1068
|
-
// && validString('title', 1, 100)
|
|
1069
|
-
// && isOneOf('status', ['draft', 'published']);
|
|
1070
|
-
|
|
1071
|
-
export function hasRequired(fields) {
|
|
1072
|
-
return request.resource.data.keys().hasAll(fields);
|
|
1073
|
-
}
|
|
1074
|
-
|
|
1075
|
-
export function hasOnly(fields) {
|
|
1076
|
-
return request.resource.data.keys().hasOnly(fields);
|
|
1077
|
-
}
|
|
1078
|
-
|
|
1079
|
-
// Incoming field is a string with size in [min, max] (inclusive).
|
|
1080
|
-
// Uses dynamic access, so a MISSING field reads as null (not an
|
|
1081
|
-
// error) and fails the \`is string\` check — safe on optional fields.
|
|
1082
|
-
export function validString(field, min, max) {
|
|
1083
|
-
return request.resource.data[field] is string
|
|
1084
|
-
&& request.resource.data[field].size() >= min
|
|
1085
|
-
&& request.resource.data[field].size() <= max;
|
|
1086
|
-
}
|
|
1087
|
-
|
|
1088
|
-
// Enum check: the incoming field value is one of the allowed values.
|
|
1089
|
-
// (\`in\` on a list — NOT \`.includes()\`, which does not exist in rules.)
|
|
1090
|
-
export function isOneOf(field, values) {
|
|
1091
|
-
return request.resource.data[field] in values;
|
|
1092
|
-
}
|
|
1093
|
-
`};function v2(){const t={};for(const[e,n]of Object.entries(b2))t[e]=n,t[`./stdlib/${e}.rules`]=n;return t}v2();const x2=`RtdbExpr {
|
|
1094
|
-
Expr = Ternary
|
|
1095
|
-
|
|
1096
|
-
Ternary
|
|
1097
|
-
= Logical "?" Ternary ":" Ternary -- ternary
|
|
1098
|
-
| Logical
|
|
1099
|
-
|
|
1100
|
-
Logical
|
|
1101
|
-
= Logical "&&" Comparison -- and
|
|
1102
|
-
| Logical "||" Comparison -- or
|
|
1103
|
-
| Comparison
|
|
1104
|
-
|
|
1105
|
-
Comparison
|
|
1106
|
-
= Comparison "===" Additive -- strictEq
|
|
1107
|
-
| Comparison "!==" Additive -- strictNeq
|
|
1108
|
-
| Comparison ">=" Additive -- gte
|
|
1109
|
-
| Comparison "<=" Additive -- lte
|
|
1110
|
-
| Comparison ">" Additive -- gt
|
|
1111
|
-
| Comparison "<" Additive -- lt
|
|
1112
|
-
| Comparison "==" Additive -- looseEq
|
|
1113
|
-
| Comparison "!=" Additive -- looseNeq
|
|
1114
|
-
| Additive
|
|
1115
|
-
|
|
1116
|
-
Additive
|
|
1117
|
-
= Additive "+" Multiplicative -- add
|
|
1118
|
-
| Additive "-" Multiplicative -- sub
|
|
1119
|
-
| Multiplicative
|
|
1120
|
-
|
|
1121
|
-
Multiplicative
|
|
1122
|
-
= Multiplicative "*" UnaryExpr -- mul
|
|
1123
|
-
| Multiplicative "/" UnaryExpr -- div
|
|
1124
|
-
| Multiplicative "%" UnaryExpr -- mod
|
|
1125
|
-
| UnaryExpr
|
|
1126
|
-
|
|
1127
|
-
UnaryExpr
|
|
1128
|
-
= "!" UnaryExpr -- not
|
|
1129
|
-
| "-" UnaryExpr -- neg
|
|
1130
|
-
| CallExpr
|
|
1131
|
-
|
|
1132
|
-
CallExpr
|
|
1133
|
-
= CallExpr "." ident "(" ListOf<Expr, ","> ")" -- methodCall
|
|
1134
|
-
| CallExpr "." ident -- memberAccess
|
|
1135
|
-
| CallExpr "[" Expr "]" -- indexAccess
|
|
1136
|
-
| Primary
|
|
1137
|
-
|
|
1138
|
-
Primary
|
|
1139
|
-
= "(" Expr ")" -- paren
|
|
1140
|
-
| Array
|
|
1141
|
-
| literal
|
|
1142
|
-
| ident
|
|
1143
|
-
|
|
1144
|
-
Array = "[" ListOf<Expr, ","> "]"
|
|
1145
|
-
|
|
1146
|
-
literal
|
|
1147
|
-
= number
|
|
1148
|
-
| string
|
|
1149
|
-
| regex
|
|
1150
|
-
| bool
|
|
1151
|
-
| null
|
|
1152
|
-
|
|
1153
|
-
number
|
|
1154
|
-
= digit+ "." digit+ -- float
|
|
1155
|
-
| digit+ -- int
|
|
1156
|
-
|
|
1157
|
-
string
|
|
1158
|
-
= "\\"" doubleStringChar* "\\"" -- double
|
|
1159
|
-
| "'" singleStringChar* "'" -- single
|
|
1160
|
-
|
|
1161
|
-
doubleStringChar
|
|
1162
|
-
= "\\\\" any -- escape
|
|
1163
|
-
| ~"\\"" any -- char
|
|
1164
|
-
|
|
1165
|
-
singleStringChar
|
|
1166
|
-
= "\\\\" any -- escape
|
|
1167
|
-
| ~"'" any -- char
|
|
1168
|
-
|
|
1169
|
-
regex = "/" regexBody "/" regexFlags
|
|
1170
|
-
|
|
1171
|
-
regexBody = regexChar+
|
|
1172
|
-
|
|
1173
|
-
regexChar
|
|
1174
|
-
= "\\\\" any -- escape
|
|
1175
|
-
| ~("/" | "\\n") any -- char
|
|
1176
|
-
|
|
1177
|
-
regexFlags = alnum*
|
|
1178
|
-
|
|
1179
|
-
bool
|
|
1180
|
-
= "true" ~identChar -- true
|
|
1181
|
-
| "false" ~identChar -- false
|
|
1182
|
-
|
|
1183
|
-
null = "null" ~identChar
|
|
1184
|
-
|
|
1185
|
-
ident = "$"? identStart identChar*
|
|
1186
|
-
|
|
1187
|
-
identStart = letter | "_"
|
|
1188
|
-
|
|
1189
|
-
identChar = alnum | "_" | "$"
|
|
1190
|
-
}
|
|
1191
|
-
`;let Nw;function K1(){return Nw??(Nw=b1(x2)),Nw}function Cd(t){return K1().match(t.trim())}function Nd(){return K1().createSemantics()}let Dp;function w2(){if(Dp)return Dp;const t=Nd();return t.addOperation("identifiers",{_nonterminal(...e){return e.flatMap(n=>n.identifiers())},_iter(...e){return e.flatMap(n=>n.identifiers())},_terminal(){return[]},CallExpr_methodCall(e,n,r,s,o,c){return[...e.identifiers(),...o.asIteration().children.flatMap(d=>d.identifiers())]},CallExpr_memberAccess(e,n,r){return e.identifiers()},ident(e,n,r){return[this.sourceString]}}),Dp=t,t}function S2(t){const e=Cd(t);if(e.failed())return{raw:t,valid:!1,errors:[{code:"PARSE_ERROR",message:e.message??"Parse failed"}],warnings:[],referencedIdentifiers:[]};const n=w2()(e).identifiers(),r=[...new Set(n)];return{raw:t,valid:!0,errors:[],warnings:[],referencedIdentifiers:r}}function _2(t){return typeof t=="object"&&t!==null&&t.__type==="serverTimestamp"}const E2={name:"date-to-timestamp",convert(t){return t instanceof Date?Nt.fromMillis(t.getTime()):er}},A2={name:"server-timestamp-sentinel",convert(t,e){return _2(t)?e.serverTime instanceof Nt?e.serverTime:Nt.fromMillis(Date.now()):er}};function j2(t){if(t===null||typeof t!="object"||t instanceof Nt)return!1;const e=t;return typeof e.seconds=="number"&&typeof e.nanoseconds=="number"&&typeof e.toMillis=="function"}const k2={name:"user-timestamp-to-rules-timestamp",convert(t){return j2(t)?new Nt(t.seconds,t.nanoseconds):er}};function Ow(t){return typeof t=="object"&&t!==null&&"isEqual"in t&&typeof t.isEqual=="function"}function Tw(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function xr(t,e){if(Object.is(t,e))return!0;if(Ow(t))return t.isEqual(e);if(Ow(e))return e.isEqual(t);if(Array.isArray(t)||Array.isArray(e))return!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length?!1:t.every((s,o)=>xr(s,e[o]));if(!Tw(t)||!Tw(e))return!1;const n=Object.keys(t),r=Object.keys(e);return n.length!==r.length?!1:n.every(s=>s in e&&xr(t[s],e[s]))}function C2(t){return typeof t=="object"&&t!==null&&t.__type==="increment"&&typeof t.value=="number"}function N2(t){return typeof t=="object"&&t!==null&&t.__type==="arrayUnion"&&Array.isArray(t.values)}function O2(t){return typeof t=="object"&&t!==null&&t.__type==="arrayRemove"&&Array.isArray(t.values)}function T2(t){return typeof t=="object"&&t!==null&&t.__type==="deleteField"}function qy(t){if(t.prior===null)return;if(t.fieldPath==="")return t.prior;let e=t.prior;for(const n of t.fieldPath.split(".")){const r=/^([^\[]*)/.exec(n),s=r?r[1]:n;if(s){if(typeof e!="object"||e===null)return;e=e[s]}const o=/\[(\d+)\]/g;let c;for(;(c=o.exec(n))!==null;){if(!Array.isArray(e))return;e=e[Number(c[1])]}}return e}const R2={name:"increment-sentinel",convert(t,e){if(!C2(t))return er;const n=qy(e);return(typeof n=="number"?n:0)+t.value}},D2={name:"array-union-sentinel",convert(t,e){if(!N2(t))return er;const n=qy(e),r=Array.isArray(n)?n.slice():[];for(const s of t.values)r.some(c=>xr(c,s))||r.push(s);return r}},I2={name:"array-remove-sentinel",convert(t,e){if(!O2(t))return er;const n=qy(e);return Array.isArray(n)?n.filter(r=>!t.values.some(s=>xr(r,s))):[]}},M2={name:"delete-field-sentinel",convert(t){return T2(t)?Ar:er}};function L2(t){if(t===null||typeof t!="object"||t instanceof Ha)return!1;const e=t;return typeof e.path=="string"&&typeof e.id=="string"&&e._path!==void 0&&e._firestore!==void 0}const U2={name:"document-reference",convert(t){return L2(t)?new Ha(t.path):er}};function $2(t){return Array.isArray(t)&&t.every(e=>typeof e=="number")}function B2(t){if(t===null||typeof t!="object"||t instanceof no)return null;const e=t;return $2(e._values)&&typeof e.toArray=="function"?e._values:null}const F2={name:"vector-value",convert(t){const e=B2(t);return e===null?er:new no(e)}};function P2(t){if(t===null||typeof t!="object"||t instanceof Tn)return!1;const e=t;return typeof e.toBase64=="function"&&typeof e.toUint8Array=="function"&&typeof e.isEqual=="function"}function q2(t){if(t===null||typeof t!="object"||t instanceof jr)return!1;const e=t;return typeof e.latitude=="number"&&typeof e.longitude=="number"&&typeof e.isEqual=="function"}const z2={name:"fb-bytes-to-rules-bytes",convert(t){return P2(t)?new Tn(t.toUint8Array()):er}},V2={name:"fb-geopoint-to-rules-latlng",convert(t){return q2(t)?new jr(t.latitude,t.longitude):er}},er=Symbol("value-resolver:KEEP"),Ar=Symbol("value-resolver:DELETE_MARKER"),km=[];function ir(t){km.some(e=>e.name===t.name)||km.push(t)}function ar(t,e){const n={};for(const[r,s]of Object.entries(t))n[r]=Cm(s,{...e,fieldPath:r});return n}function Cm(t,e){for(const n of km){const r=n.convert(t,e);if(r!==er)return r}if(Array.isArray(t))return t.map((n,r)=>Cm(n,{...e,fieldPath:`${e.fieldPath}[${r}]`}));if(zi(t)){const n={};for(const[r,s]of Object.entries(t)){const o=e.fieldPath?`${e.fieldPath}.${r}`:r;n[r]=Cm(s,{...e,fieldPath:o})}return n}return t}function zi(t){if(t===null||typeof t!="object")return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function ji(t){const e={},n=[];for(const[r,s]of Object.entries(t)){if(s===Ar){n.push(r);continue}e[r]=rd(s)}return{writes:e,deletedKeys:n}}function rd(t){if(t!==Ar){if(Array.isArray(t))return t.filter(e=>e!==Ar).map(rd);if(zi(t)){const e={};for(const[n,r]of Object.entries(t))r!==Ar&&(e[n]=rd(r));return e}return t}}function H2(){ir(E2),ir(A2),ir(k2),ir(R2),ir(D2),ir(I2),ir(M2),ir(U2),ir(F2),ir(z2),ir(V2)}function Y1(t){return t.split(".")}const G2=new Set(["__proto__","prototype","constructor"]);function Rw(t){if(G2.has(t))throw new Error(`Invalid field-path segment '${t}': the keys __proto__, prototype, and constructor are reserved and cannot appear in a field path.`)}function zy(t){const e={};for(const[n,r]of Object.entries(t))e[n]=Z1(r);return e}function Z1(t){return Array.isArray(t)?t.map(Z1):zi(t)?zy(t):t}function W1(t,e,n){let r=t;for(let o=0;o<e.length-1;o++){const c=e[o];Rw(c);const d=Object.hasOwn(r,c)?r[c]:void 0;zi(d)||(r[c]={}),r=r[c]}const s=e[e.length-1];Rw(s),n===Ar?delete r[s]:r[s]=rd(n)}function Dw(t,e){const n=zy(t);for(const[r,s]of Object.entries(e)){if(s!==Ar&&sd(s))throw new J1;W1(n,Y1(r),s)}return n}class J1 extends Error{constructor(){super("FieldValue.delete() can only appear at the top level of your update data"),this.name="DeleteFieldNestedError"}}function sd(t){return t===Ar?!0:Array.isArray(t)?t.some(sd):zi(t)?Object.values(t).some(sd):!1}function K2(t){for(const e of Object.values(t))if(e!==Ar&&sd(e))throw new J1}function Y2(t,e,n){const r=zy(t),s=[];if(n!==void 0)for(const o of n){const c=Y1(o),d=Z2(e,c);d!==Q1&&s.push({segments:c,value:d})}else X1(e,[],s);for(const{segments:o,value:c}of s)W1(r,o,c);return r}const Q1=Symbol("field-merge:ABSENT");function Z2(t,e){let n=t;for(const r of e){if(!zi(n)||!Object.hasOwn(n,r))return Q1;n=n[r]}return n}function X1(t,e,n){const r=Object.keys(t);if(r.length===0&&e.length>0){n.push({segments:e,value:{}});return}for(const s of r){const o=t[s],c=[...e,s];zi(o)&&o!==Ar?X1(o,c,n):n.push({segments:c,value:o})}}function W2(t,e){const n={};for(const r of e)Object.prototype.hasOwnProperty.call(t,r)&&(n[r]=t[r]);return n}class Ip{constructor(e={},n){G(this,"documents");this.documents=n??new Map;for(const[r,s]of Object.entries(e)){const o=ar({...s},{path:r,method:"seed",prior:null}),{writes:c}=ji(o);this.documents.set(r,c)}}get(e){return this.documents.get(e)??null}exists(e){return this.documents.has(e)}scan(e,n={}){const r=e===""||e.endsWith("/")?e:e+"/",s=n.projection?f=>W2(f,n.projection):f=>f,o=[],c=new Set,d=[];for(const[f,p]of this.documents){if(r!==""&&!f.startsWith(r))continue;if(!n.directOnly){o.push({path:f,data:s(p)});continue}const g=f.slice(r.length),b=g.indexOf("/");if(b===-1)o.push({path:f,data:s(p)}),c.add(g);else if(n.phantoms){const v=g.slice(0,b);v.length>0&&!d.includes(v)&&d.push(v)}}if(n.directOnly&&n.phantoms)for(const f of d)c.has(f)||o.push({path:r+f,data:{},phantom:!0});return o}list(e){return this.scan(e,{directOnly:!0,phantoms:!0})}listRootCollections(){const e=new Set,n=[];for(const r of this.documents.keys()){const s=r.split("/",1)[0];s.length!==0&&(e.has(s)||(e.add(s),n.push(s)))}return n}listSubcollections(e){const n=e.endsWith("/")?e:e+"/",r=new Set,s=[];for(const o of this.documents.keys()){if(!o.startsWith(n))continue;const d=o.slice(n.length).split("/",1)[0];d.length!==0&&(r.has(d)||(r.add(d),s.push(d)))}return s}snapshot(){const e={};for(const[n,r]of this.documents)e[n]={...r};return e}size(){return this.documents.size}create(e,n){if(this.documents.has(e))return{success:!1,error:`Document '${e}' already exists`};let r;try{const s=ar({...n},{path:e,method:"create",prior:null});r=ji(s).writes}catch(s){return{success:!1,error:s.message}}return this.documents.set(e,r),{success:!0}}update(e,n){const r=this.documents.get(e);if(!r)return{success:!1,error:`Document '${e}' does not exist`};let s;try{const o=ar({...n},{path:e,method:"update",prior:r});s=Dw(r,o)}catch(o){return{success:!1,error:o.message}}return this.documents.set(e,s),{success:!0,priorData:{...r}}}setMerge(e,n,r){const s=this.documents.has(e)?{...this.documents.get(e)}:null,o=ar({...n},{path:e,method:"set",prior:s}),c=Y2(s??{},o,r);return this.documents.set(e,c),{success:!0,priorData:s,created:s===null}}set(e,n){const r=this.documents.has(e)?{...this.documents.get(e)}:null,s=ar({...n},{path:e,method:"set",prior:r}),{writes:o}=ji(s);return this.documents.set(e,o),{success:!0,priorData:r,created:r===null}}delete(e){const n=this.documents.get(e);return n?(this.documents.delete(e),{success:!0,priorData:{...n}}):{success:!1,error:`Document '${e}' does not exist`}}applyBatch(e){const n=[];for(let s=0;s<e.length;s++){const o=e[s];switch(o.method){case"create":this.documents.has(o.path)&&n.push({index:s,error:`Document '${o.path}' already exists`});break;case"update":this.documents.has(o.path)||n.push({index:s,error:`Document '${o.path}' does not exist`});break}}if(n.length>0)return{success:!1,errors:n};const r=new Map;for(const s of e)r.has(s.path)||r.set(s.path,this.documents.has(s.path)?{...this.documents.get(s.path)}:null);for(const s of e)switch(s.method){case"create":{const o=ar({...s.data},{path:s.path,method:"create",prior:null}),{writes:c}=ji(o);this.documents.set(s.path,c);break}case"update":{const o=this.documents.get(s.path),c=ar({...s.data},{path:s.path,method:"update",prior:o});this.documents.set(s.path,Dw(o,c));break}case"set":{const o=r.get(s.path)??null,c=ar({...s.data},{path:s.path,method:"set",prior:o}),{writes:d}=ji(c);this.documents.set(s.path,d);break}case"delete":this.documents.delete(s.path);break}return{success:!0,priorStates:r}}restore(e){this.documents.clear();for(const[n,r]of Object.entries(e))this.documents.set(n,{...r})}restorePaths(e){for(const[n,r]of Object.entries(e))r===null?this.documents.delete(n):this.documents.set(n,{...r})}}class J2{constructor(e){G(this,"base");G(this,"overlay",new Map);G(this,"tombstones",new Set);G(this,"baseCache",new Map);G(this,"cleared",!1);this.base=e}inBase(e){return Object.prototype.hasOwnProperty.call(this.base,e)}baseDoc(e){let n=this.baseCache.get(e);return n===void 0&&(n=structuredClone(this.base[e]),this.baseCache.set(e,n)),n}get(e){if(this.overlay.has(e))return this.overlay.get(e);if(!(this.cleared||this.tombstones.has(e)))return this.inBase(e)?this.baseDoc(e):void 0}set(e,n){this.overlay.set(e,n),this.tombstones.delete(e)}has(e){return this.overlay.has(e)?!0:this.cleared||this.tombstones.has(e)?!1:this.inBase(e)}delete(e){const n=this.has(e);return this.overlay.delete(e),!this.cleared&&this.inBase(e)&&this.tombstones.add(e),n}clear(){this.overlay.clear(),this.tombstones.clear(),this.baseCache.clear(),this.cleared=!0}get size(){let e=0;for(const n of this)e++;return e}*keys(){for(const[e]of this)yield e}*[Symbol.iterator](){const e=new Set;if(!this.cleared)for(const n of Object.keys(this.base))this.tombstones.has(n)||(e.add(n),yield[n,this.overlay.has(n)?this.overlay.get(n):this.baseDoc(n)]);for(const[n,r]of this.overlay)e.has(n)||(yield[n,r])}}class Q2{constructor(){G(this,"events",[]);G(this,"nextId",1);G(this,"undoneEvents",[])}append(e,n=!1){const r={...e,id:this.nextId++,timestamp:new Date().toISOString()};return this.events.push(r),n||(this.undoneEvents=[]),r}getEvents(){return[...this.events]}getWriteEvents(){return this.events.filter(e=>e.allowed&&e.method!=="get"&&e.method!=="list")}lastWriteEvent(){const e=this.getWriteEvents();return e.length>0?e[e.length-1]:null}popLastWrite(){for(let e=this.events.length-1;e>=0;e--){const n=this.events[e];if(!n.aborted&&n.allowed&&n.method!=="get"&&n.method!=="list")return this.events.splice(e,1),this.undoneEvents.push(n),n}return null}popLastUndo(){return this.undoneEvents.pop()??null}size(){return this.events.length}clear(){this.events=[],this.undoneEvents=[],this.nextId=1}}function X2(t,e,n=new Map){if(!id(t,n))return{provable:!0,reason:"list rule does not depend on per-document data; every doc is equally readable"};const r=eD(t);if(r.length===0)return{provable:!1,reason:"list rule depends on per-document data through a predicate the query cannot discharge (only top-level `resource.data.field == value` conjunctions are provable here) — prod rejects the whole query rather than filtering"};const s=e.where??[],o=r.filter(c=>!s.some(d=>d.field===c.field&&d.op==="=="&&rD(d.value,c.value)));return o.length>0?{provable:!1,reason:`list rule requires [${o.map(d=>`resource.data.${d.field} == ${JSON.stringify(d.value)}`).join(", ")}] but the query has no matching where(...) equality to guarantee it — prod rejects the query ("rules are not filters")`}:{provable:!0,reason:"every per-document predicate the rule requires is guaranteed by a query where(...) constraint"}}function id(t,e=new Map,n=new Set){const r=s=>{switch(s.type){case"memberAccess":return s.property==="data"&&s.object.type==="identifier"&&s.object.name==="resource"?!0:r(s.object);case"bracketAccess":return r(s.object)||r(s.index);case"functionCall":if(e.has(s.name)&&!n.has(s.name)){n.add(s.name);const o=e.get(s.name);if(id(o.body,e,n)||o.lets.some(c=>id(c.value,e,n)))return!0}return s.args.some(r);case"binaryOp":return r(s.left)||r(s.right);case"unaryOp":return r(s.operand);case"methodCall":return r(s.object)||s.args.some(r);case"ternary":return r(s.condition)||r(s.consequent)||r(s.alternate);case"inExpr":return r(s.element)||r(s.collection);case"isExpr":return r(s.value);case"listLiteral":return s.elements.some(r);case"mapLiteral":return s.entries.some(o=>r(o.key)||r(o.value));default:return!1}};return r(t)}function eD(t){const e=[],n=r=>{if(r.type==="binaryOp"&&r.op==="&&"){n(r.left),n(r.right);return}const s=tD(r);s&&e.push(s)};return n(t),e}function tD(t){if(t.type!=="binaryOp"||t.op!=="==")return null;const e=(n,r)=>{const s=nD(n);return s!==null&&r.type==="literal"?{field:s,op:"==",value:r.value}:null};return e(t.left,t.right)??e(t.right,t.left)}function nD(t){return t.type==="memberAccess"&&t.object.type==="memberAccess"&&t.object.property==="data"&&t.object.object.type==="identifier"&&t.object.object.name==="resource"?t.property:null}function rD(t,e){return t===e}function Iw(t,e,n,r){if(!t)return{kind:"no-rule"};const s=e.split("/").filter(v=>v.length>0),o=t.service.match.functions;let c=null;for(const v of t.service.match.children)if(c=eE(v,s,o),c)break;if(!c)return{kind:"no-rule"};const d=c.block.allows.filter(v=>v.operations.some(x=>x==="list"||x==="read"));if(d.length===0)return{kind:"no-rule"};const f=new Map;for(const v of c.functions)f.set(v.name,v);const p=[];let g=!1,b=!1;for(const v of d){const x=(n==null?void 0:n.uid)!==void 0?aD(v.condition,n.uid):v.condition,_=X2(x,r,f);_.provable?(g=!0,id(x,f)&&(b=!0)):p.push(_.reason)}return g?b?{kind:"provable",syntheticResource:sD(r)}:{kind:"provable"}:{kind:"unprovable",reason:p[0]??"list rule depends on per-document data the query cannot guarantee"}}function eE(t,e,n){const r=[...n,...t.functions];let s=0;for(const c of t.path.segments)if(c.type==="literal"){if(s>=e.length||e[s]!==c.value)return null;s++}else if(c.type==="wildcard"){if(s>=e.length)return null;s++}else s=e.length;const o=e.slice(s);if(o.length===0)return{block:t,functions:r};for(const c of t.children){const d=eE(c,o,r);if(d)return d}return null}function sD(t){const e={};for(const n of t.where??[])n.op==="=="&&(e[n.field]=n.value);return e}function iD(t){return t.type==="memberAccess"&&t.property==="uid"&&t.object.type==="memberAccess"&&t.object.property==="auth"&&t.object.object.type==="identifier"&&t.object.object.name==="request"}function aD(t,e){const n={type:"literal",value:e,raw:JSON.stringify(e)},r=s=>{if(iD(s))return n;switch(s.type){case"literal":case"identifier":return s;case"memberAccess":return{...s,object:r(s.object)};case"methodCall":return{...s,object:r(s.object),args:s.args.map(r)};case"bracketAccess":return{...s,object:r(s.object),index:r(s.index)};case"sliceAccess":return{...s,object:r(s.object),start:r(s.start),end:r(s.end)};case"binaryOp":return{...s,left:r(s.left),right:r(s.right)};case"unaryOp":return{...s,operand:r(s.operand)};case"ternary":return{...s,condition:r(s.condition),consequent:r(s.consequent),alternate:r(s.alternate)};case"inExpr":return{...s,element:r(s.element),collection:r(s.collection)};case"isExpr":return{...s,value:r(s.value)};case"listLiteral":return{...s,elements:s.elements.map(r)};case"mapLiteral":return{...s,entries:s.entries.map(o=>({key:r(o.key),value:r(o.value)}))};case"pathLiteral":return{...s,segments:s.segments.map(o=>typeof o=="string"?o:r(o))};case"functionCall":return{...s,args:s.args.map(r)}}};return r(t)}function Pe(t,e,n){const r={code:t,message:e};return n!=null&&n.request&&(r.request=n.request),n!=null&&n.resource&&(r.resource=n.resource),r}const Mw="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",Lw=20;function Vy(){const t=new Uint8Array(Lw);globalThis.crypto.getRandomValues(t);let e="";for(let n=0;n<Lw;n++)e+=Mw[t[n]%Mw.length];return e}function Mp(t,e=""){const n=[];return r(t,e),n;function r(s,o){if(s==null||typeof s!="object")return;if(Array.isArray(s)){s.forEach((f,p)=>r(f,`${o}[${p}]`));return}const c=s,d=oD(c);if(d){n.push({field:o,kind:d});return}for(const[f,p]of Object.entries(c)){const g=o?`${o}.${f}`:f;r(p,g)}}}function oD(t){const e=t.__type;return e==="serverTimestamp"?"serverTimestamp":e==="increment"?"increment":e==="arrayUnion"?"arrayUnion":e==="arrayRemove"?"arrayRemove":e==="deleteField"?"delete":null}const Nm="Firestore transactions require all reads to be executed before all writes.";class tE extends Error{constructor(){super(Nm);G(this,"simError");this.name="ReadAfterWriteError",this.simError=Pe("failed-precondition",Nm)}}class lD{constructor(e){G(this,"reader");G(this,"reads",[]);G(this,"writes",[]);G(this,"writeStarted",!1);this.reader=e}get(e){this.assertReadsAllowed();const n=this.reader(e);this.reads.push({path:e,data:n});const r=n===null?null:structuredClone(n);return{path:e,exists:r!==null,data:()=>r===null?void 0:r}}getAll(...e){return this.assertReadsAllowed(),e.map(n=>this.get(n))}set(e,n){this.queue({method:"set",path:e,data:n})}create(e,n){this.queue({method:"create",path:e,data:n})}update(e,n){this.queue({method:"update",path:e,data:n})}delete(e){this.queue({method:"delete",path:e})}consume(){return{reads:this.reads,writes:this.writes}}hadWrites(){return this.writeStarted}queue(e){this.writeStarted=!0,this.writes.push(e)}assertReadsAllowed(){if(this.writeStarted)throw new tE}}class cD extends Error{constructor(n,r){super(`Queued ${r} on '${n}' after a delete in the same transaction. This combination is unprobed against production Firestore; refusing to guess. Either drop the delete or split into two transactions.`);G(this,"path");G(this,"secondMethod");this.name="AmbiguousPostDeleteWriteError",this.path=n,this.secondMethod=r}}function uD(t){const e=new Map;for(const n of t){const r=e.get(n.path);if(r===void 0){e.set(n.path,dD(n));continue}if(r.method==="delete")throw new cD(n.path,n.method);e.set(n.path,fD(r,n))}return Array.from(e.values())}function dD(t){if(t.method==="delete")return{method:"delete",path:t.path};if(t.data===void 0)throw new Error(`internal: queued ${t.method} on ${t.path} has no data — Transaction class invariant violated`);return{method:t.method,path:t.path,data:t.data}}function fD(t,e){switch(e.method){case"delete":return{method:"delete",path:e.path};case"set":{const n=Lp(e);return{method:"set",path:e.path,data:n}}case"update":{const n=Lp(e),s={...t.data??{},...n};return{method:t.method,path:e.path,data:s}}case"create":{const n=Lp(e),s={...t.data??{},...n};return{method:"create",path:e.path,data:s}}}}function Lp(t){if(t.data===void 0)throw new Error(`internal: queued ${t.method} on ${t.path} has no data — Transaction class invariant violated`);return t.data}class hD{static serverTimestamp(){return{__type:"serverTimestamp"}}static increment(e){return{__type:"increment",value:e}}static arrayUnion(...e){return{__type:"arrayUnion",values:e}}static arrayRemove(...e){return{__type:"arrayRemove",values:e}}static delete(){return{__type:"deleteField"}}}class Mn{constructor(e,n){G(this,"seconds");G(this,"nanoseconds");this.seconds=e,this.nanoseconds=n}static now(){return Mn.fromMillis(Date.now())}static fromDate(e){return Mn.fromMillis(e.getTime())}static fromMillis(e){const n=Math.floor(e/1e3),r=Math.floor((e-n*1e3)*1e6);return new Mn(n,r)}toDate(){return new Date(this.toMillis())}toMillis(){return this.seconds*1e3+this.nanoseconds/1e6}isEqual(e){return e.seconds===this.seconds&&e.nanoseconds===this.nanoseconds}toString(){return`Timestamp(seconds=${this.seconds}, nanoseconds=${this.nanoseconds})`}toJSON(){return{type:"firestore/timestamp/1.0",seconds:this.seconds,nanoseconds:this.nanoseconds}}valueOf(){const n=this.seconds- -62135596800,r=String(n).padStart(12,"0"),s=String(this.nanoseconds).padStart(9,"0");return`${r}.${s}`}}class tn extends Error{constructor(n){super(n.message);G(this,"code");G(this,"simError");this.name="FirestoreError",this.code=n.code,this.simError=n}}function Om(t){return t instanceof Nt?new Mn(t.seconds,t.nanos):t instanceof Tn||t instanceof jr?t:Array.isArray(t)?t.map(Om):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).map(([e,n])=>[e,Om(n)])):t}function ro(t){return Om(t)}const Ya=Object.freeze({hasPendingWrites:!1,fromCache:!1}),Uw=Object.freeze({hasPendingWrites:!0,fromCache:!1});function nE(t,e){if(t===void 0)return;const n=e.split(".");let r=t;for(const s of n){if(r==null||typeof r!="object")return;r=r[s]}return r}function rE(t){const e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}function $a(t,e,n=Ya){const r={id:rE(t),path:t},s=e!==null,o=s?ro(e):void 0;return{id:r.id,ref:r,metadata:n,exists:()=>s,data:()=>o,get:c=>nE(o,c)}}function sE(t,e,n=Ya){const r={id:rE(t),path:t},s=ro(e);return{id:r.id,ref:r,metadata:n,exists:()=>!0,data:()=>s,get:o=>nE(s,o)}}function Ba(t,e,n,r,s=Ya){const o=e.map(p=>sE(p.path,p.data,s)),c=r?pD(r,e,o,s):o.map((p,g)=>({type:"added",doc:p,oldIndex:-1,newIndex:g}));let d=null,f=null;return{query:t,metadata:s,size:o.length,empty:o.length===0,docs:o,forEach(p){for(const g of o)p(g)},docChanges(p){const g=!!(p!=null&&p.includeMetadataChanges);if(g&&n.excludesMetadataChanges)throw new Error("To include metadata changes with your document changes, you must also pass { includeMetadataChanges: true } to onSnapshot().");return g?(f||(f=c.slice()),f):(d||(d=c.slice()),d)}}}function pD(t,e,n,r=Ya){const s=new Map;t.forEach((d,f)=>s.set(d.path,f));const o=new Map;e.forEach((d,f)=>o.set(d.path,f));const c=[];for(let d=0;d<t.length;d++){const f=t[d];o.has(f.path)||c.push({type:"removed",doc:sE(f.path,f.data,r),oldIndex:d,newIndex:-1})}for(let d=0;d<e.length;d++){const f=e[d],p=s.get(f.path);if(p===void 0)c.push({type:"added",doc:n[d],oldIndex:-1,newIndex:d});else{const g=t[p].data;JSON.stringify(g)!==JSON.stringify(f.data)&&c.push({type:"modified",doc:n[d],oldIndex:p,newIndex:d})}}return c}H2();function mD(t){return new Date(t.toMillis()).toISOString()}class wi extends Error{constructor(n,r,s,o){super(n);G(this,"method");G(this,"path");G(this,"debugMessages");this.method=r,this.path=s,this.debugMessages=o,this.name="SimulatorUnsupportedError"}}function Si(t,e,n){const r=n.filter(o=>o.includes("unsupported:")).map(o=>o.replace(/^.*unsupported:\s*/,"")).join("; "),s=r?` Reason(s): ${r}.`:"";return`Simulator cannot decide ${t} on ${e} — the rule uses a feature the local simulator does not yet implement.${s} Verify this rule against production using TestFirestoreRulesHandler, or file a sim-gap entry in REBUILD_PLAN.md.`}function $w(t,e){return t===null&&e===null?!0:t===null||e===null?!1:JSON.stringify(t)===JSON.stringify(e)}function yD(t,e){const n=`${e}/`;for(const r of t){if(!r.startsWith(n))continue;const s=r.slice(n.length);if(s.length>0&&!s.includes("/"))return!0}return!1}let Up=0;function ml(){return Up=Up+1>>>0,`req-${Up.toString(36)}-${Math.random().toString(36).slice(2,7)}`}function gD(t,e){const n=e==="allow";let r;for(const s of t){const o=/^Rule #(\d+) \(([^)]+)\) → (ALLOW|deny|unsupported)/.exec(s);if(!o)continue;const c={ruleIndex:Number(o[1]),operations:o[2].split(",").map(d=>d.trim())};if(n&&o[3]==="ALLOW")return c;r=c}return r}function bD(t){const e={kind:"request",id:ml(),at:t.at,evalMs:t.evalMs,method:t.method,path:t.path,auth:t.auth?{uid:t.auth.uid,...t.auth.token?{token:t.auth.token}:{}}:null,result:t.result,reasons:t.debugMessages,origin:t.origin};t.resourceData!==void 0&&(e.request={resourceData:t.resourceData}),t.resourceBefore!==void 0&&(e.resourceBefore=t.resourceBefore),t.resourceAfter!==void 0&&(e.resourceAfter=t.resourceAfter);const n=gD(t.debugMessages,t.result);return n&&(e.matchedRule=n),t.result!=="unsupported"&&t.evaluatedRule&&(e.evaluatedRule=t.evaluatedRule),t.groupId!==void 0&&(e.groupId=t.groupId,t.origin==="batch"?e.groupKind="batch":t.origin==="transaction"&&(e.groupKind="transaction")),t.triggeredBy!==void 0&&(e.triggeredBy=t.triggeredBy),t.detail!==void 0&&(e.detail=t.detail),t.provenance!==void 0&&Object.assign(e,t.provenance),e}function Bw(t){if(!(t.limit==null&&t.offset==null&&t.orderBy==null))return{...t.limit!=null?{limit:t.limit}:{},...t.offset!=null?{offset:t.offset}:{},...t.orderBy!=null?{orderBy:t.orderBy}:{}}}function vD(t=""){return{description:t,expectation:"ALLOW",state:"PASSED",decision:"ALLOW",trace:[],notes:["admin lens — rules bypassed (Studio Gap #2)"]}}const xD=`rules_version = '2';
|
|
1192
|
-
service cloud.firestore {
|
|
1193
|
-
match /databases/{database}/documents {
|
|
1194
|
-
match /{document=**} {
|
|
1195
|
-
allow read, write: if true;
|
|
1196
|
-
}
|
|
1197
|
-
}
|
|
1198
|
-
}
|
|
1199
|
-
`;class Fw{constructor(){G(this,"state");G(this,"eventLog");G(this,"simulator");G(this,"rulesSource");G(this,"seedSnapshot");G(this,"denialListeners",new Set);G(this,"requestListeners",new Set);G(this,"writeListeners",new Set);G(this,"deliveryListeners",new Set);G(this,"suppressedListeners",new Set);G(this,"lifecycleListeners",new Set);G(this,"currentTrigger");G(this,"parsedRulesCache",null);G(this,"snapshotErrorListeners",new Set);G(this,"snapshotListeners",new Map);G(this,"nextListenerId",0);G(this,"deliveryQueue",[]);G(this,"deliveryScheduled",!1);this.state=new Ip,this.eventLog=new Q2,this.simulator=new oR,this.rulesSource=xD,this.seedSnapshot={}}onDenial(e){return this.denialListeners.add(e),()=>{this.denialListeners.delete(e)}}emitDenial(e){if(this.denialListeners.size!==0)for(const n of this.denialListeners)try{n(e)}catch{}}onRequest(e){return this.requestListeners.add(e),()=>{this.requestListeners.delete(e)}}onWrite(e){return this.writeListeners.add(e),()=>{this.writeListeners.delete(e)}}onSnapshotDelivery(e){return this.deliveryListeners.add(e),()=>{this.deliveryListeners.delete(e)}}onSnapshotSuppressed(e){return this.suppressedListeners.add(e),()=>{this.suppressedListeners.delete(e)}}onListenerLifecycle(e){return this.lifecycleListeners.add(e),()=>{this.lifecycleListeners.delete(e)}}emitSnapshotDelivery(e){if(this.deliveryListeners.size===0)return;const n={kind:"snapshot_delivery",id:ml().replace(/^req-/,"snd-"),at:Date.now(),listenerId:e.listenerId,target:e.target,auth:e.auth?{uid:e.auth.uid,...e.auth.token?{token:e.auth.token}:{}}:null,addedCount:e.addedCount,modifiedCount:e.modifiedCount,removedCount:e.removedCount,size:e.size,...e.sample?{sample:e.sample}:{},...e.triggeredBy?{triggeredBy:e.triggeredBy}:{}};for(const r of this.deliveryListeners)try{r(n)}catch{}}emitSnapshotSuppressed(e){if(this.suppressedListeners.size===0)return;const n={kind:"snapshot_suppressed",id:ml().replace(/^req-/,"sup-"),at:Date.now(),listenerId:e.listenerId,target:e.target,auth:e.auth?{uid:e.auth.uid,...e.auth.token?{token:e.auth.token}:{}}:null,reason:"no-op",...e.triggeredBy?{triggeredBy:e.triggeredBy}:{}};for(const r of this.suppressedListeners)try{r(n)}catch{}}emitLifecycle(e){if(this.lifecycleListeners.size===0)return;const n={kind:e.phase,id:ml().replace(/^req-/,"lc-"),at:Date.now(),listenerId:e.listenerId,target:e.target,auth:e.auth?{uid:e.auth.uid,...e.auth.token?{token:e.auth.token}:{}}:null};for(const r of this.lifecycleListeners)try{r(n)}catch{}}emitWrite(e){if(this.writeListeners.size===0)return;const n={kind:"write",id:ml().replace(/^req-/,"wr-"),at:Date.now(),method:e.method,path:e.path,auth:e.auth?{uid:e.auth.uid,...e.auth.token?{token:e.auth.token}:{}}:null,...e.data!==void 0?{data:e.data}:{},priorState:e.priorState,nextState:e.nextState,...e.groupId!==void 0?{groupId:e.groupId}:{},...e.groupKind!==void 0?{groupKind:e.groupKind}:{},...e.sentinels&&e.sentinels.length>0?{sentinels:e.sentinels}:{},...e.autoId!==void 0?{autoId:e.autoId}:{},requestTime:{seconds:e.requestTime.seconds,nanoseconds:e.requestTime.nanos},...e.detail!==void 0?{detail:e.detail}:{},...e.provenance??{}};for(const r of this.writeListeners)try{const s=r(n);s&&typeof s.then=="function"&&s.catch(()=>{})}catch{}}emitRequest(e){if(this.requestListeners.size===0)return;const n=bD(e);for(const r of this.requestListeners)try{const s=r(n);s&&typeof s.then=="function"&&s.catch(()=>{})}catch{}}onSnapshotError(e){return this.snapshotErrorListeners.add(e),()=>{this.snapshotErrorListeners.delete(e)}}emitSnapshotError(e,n,r){if(this.snapshotErrorListeners.size!==0)for(const s of this.snapshotErrorListeners)try{s(e,n,r)}catch{}}addSnapshotListener(e,n,r={},s=null,o,c=!1,d=!1,f){const p=String(this.nextListenerId++),g={id:p,target:e,callback:n,auth:s,bypassRules:d,followsCurrentUser:c,...f?{authScope:f}:{},options:r,currentSnapshot:void 0,errored:!1,...o?{errorCallback:o}:{}};return this.snapshotListeners.set(p,g),this.emitLifecycle({phase:"listener_attach",listenerId:p,target:e.kind==="doc"?{kind:"doc",path:e.path}:{kind:"query",collection:e.collection},auth:s}),this.scheduleDelivery(()=>{this.snapshotListeners.has(p)&&this.fireInitialSnapshot(g)}),()=>{const b=this.snapshotListeners.has(p);this.snapshotListeners.delete(p),b&&this.emitLifecycle({phase:"listener_detach",listenerId:p,target:e.kind==="doc"?{kind:"doc",path:e.path}:{kind:"query",collection:e.collection},auth:s})}}fireInitialSnapshot(e){if(e.target.kind==="doc"){const s=this.silentReadDoc(e.target.path,e.auth,e.bypassRules);if(!s.allowed){this.markErrored(e,s.error);return}const o=$a(e.target.path,s.data);e.currentSnapshot=o,e.currentDocData=s.data;try{e.callback(o)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"doc",path:e.target.path},auth:e.auth,addedCount:s.data!==null?1:0,modifiedCount:0,removedCount:0,size:s.data!==null?1:0,sample:{docs:[{path:e.target.path,data:s.data}]}});return}const n=this.silentReadCollection(e.target.collection,e.auth,e.target.constraints,e.bypassRules);if(!n.allowed){this.markErrored(e,n.error);return}const r=Ba({path:e.target.collection},n.docs,{excludesMetadataChanges:!e.options.includeMetadataChanges});e.currentSnapshot=r,e.currentDocs=n.docs;try{e.callback(r)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"query",collection:e.target.collection},auth:e.auth,addedCount:n.docs.length,modifiedCount:0,removedCount:0,size:n.docs.length,sample:{docs:n.docs.map(s=>({path:s.path,data:s.data}))}})}scheduleDelivery(e){this.deliveryQueue.push(e),!this.deliveryScheduled&&(this.deliveryScheduled=!0,queueMicrotask(()=>this.drainDeliveries()))}scheduleTriggeredDelivery(e,n){this.scheduleDelivery(()=>{const r=this.currentTrigger;this.currentTrigger=e;try{n()}finally{this.currentTrigger=r}})}drainDeliveries(){for(this.deliveryScheduled=!1;this.deliveryQueue.length>0;)this.deliveryQueue.shift()()}flushListeners(){this.drainDeliveries()}notifyListenersForPaths(e){if(e.size===0||this.snapshotListeners.size===0)return;const n=this.currentTrigger,r=Array.from(this.snapshotListeners.values());for(const s of r)this.scheduleTriggeredDelivery(n,()=>{this.snapshotListeners.has(s.id)&&(s.errored||(s.target.kind==="doc"?this.notifyDocListener(s,e):this.notifyQueryListener(s,e)))})}notifyDocListener(e,n){if(e.target.kind!=="doc"||!n.has(e.target.path))return;const r=this.silentReadDoc(e.target.path,e.auth,e.bypassRules);if(!r.allowed){this.markErrored(e,r.error);return}const s=e.currentDocData??null;if($w(s,r.data)){this.emitSnapshotSuppressed({listenerId:e.id,target:{kind:"doc",path:e.target.path},auth:e.auth,...this.currentTrigger?{triggeredBy:this.currentTrigger}:{}});return}const o=e.target.path,c=$a(o,r.data,Uw);e.currentSnapshot=c,e.currentDocData=r.data;const d=s!==null,f=r.data!==null,p=!d&&f?1:0,g=d&&!f?1:0,b=d&&f?1:0;try{e.callback(c)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"doc",path:o},auth:e.auth,addedCount:p,modifiedCount:b,removedCount:g,size:f?1:0,sample:{docs:[{path:o,data:r.data}]},...this.currentTrigger?{triggeredBy:this.currentTrigger}:{}}),this.scheduleDocMetadataAck(e,o,r.data)}scheduleDocMetadataAck(e,n,r){e.options.includeMetadataChanges&&this.scheduleTriggeredDelivery(this.currentTrigger,()=>{if(!this.snapshotListeners.has(e.id)||e.errored)return;const s=$a(n,r,Ya);e.currentSnapshot=s;try{e.callback(s)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"doc",path:n},auth:e.auth,addedCount:0,modifiedCount:0,removedCount:0,size:r!==null?1:0,sample:{docs:[{path:n,data:r}]},...this.currentTrigger?{triggeredBy:this.currentTrigger}:{}})})}notifyQueryListener(e,n){if(e.target.kind!=="query"||!yD(n,e.target.collection))return;const r=this.silentReadCollection(e.target.collection,e.auth,e.target.constraints,e.bypassRules);if(!r.allowed){this.markErrored(e,r.error);return}const s=e.target.collection,o=e.currentDocs??[],c=Ba({path:s},r.docs,{excludesMetadataChanges:!e.options.includeMetadataChanges},o,Uw),d=c.docChanges();if(d.length===0){this.emitSnapshotSuppressed({listenerId:e.id,target:{kind:"query",collection:s},auth:e.auth,...this.currentTrigger?{triggeredBy:this.currentTrigger}:{}});return}e.currentSnapshot=c,e.currentDocs=r.docs;let f=0,p=0,g=0;for(const b of d)b.type==="added"?f++:b.type==="modified"?p++:b.type==="removed"&&g++;try{e.callback(c)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"query",collection:s},auth:e.auth,addedCount:f,modifiedCount:p,removedCount:g,size:r.docs.length,sample:{docs:r.docs.map(b=>({path:b.path,data:b.data}))},...this.currentTrigger?{triggeredBy:this.currentTrigger}:{}}),this.scheduleQueryMetadataAck(e,s,r.docs)}scheduleQueryMetadataAck(e,n,r){e.options.includeMetadataChanges&&this.scheduleTriggeredDelivery(this.currentTrigger,()=>{if(!this.snapshotListeners.has(e.id)||e.errored)return;const s=Ba({path:n},r,{excludesMetadataChanges:!1},r,Ya);e.currentSnapshot=s;try{e.callback(s)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"query",collection:n},auth:e.auth,addedCount:0,modifiedCount:0,removedCount:0,size:r.length,sample:{docs:r.map(o=>({path:o.path,data:o.data}))},...this.currentTrigger?{triggeredBy:this.currentTrigger}:{}})})}silentReadDoc(e,n,r=!1){if(r){const x=this.state.get(e);return this.emitRequest({at:Date.now(),evalMs:0,method:"get",path:e,auth:n,result:"allow",debugMessages:["admin lens — rules bypassed"],origin:"listener",resourceBefore:{data:x,exists:x!==null},detail:{admin:!0},...this.currentTrigger?{triggeredBy:this.currentTrigger}:{}}),{allowed:!0,data:x}}const s=Nt.fromMillis(Date.now()),o=this.buildTestCase({method:"get",path:e,auth:n},s),c=Date.now(),d=performance.now(),f=this.simulator.simulate(this.rulesSource,[o],{getDoc:x=>this.state.get(x)}),p=performance.now()-d;if(!f.success)return this.emitRequest({at:c,evalMs:p,method:"get",path:e,auth:n,result:"deny",debugMessages:[`Simulation error: ${f.error.message}`],origin:"listener",...this.currentTrigger?{triggeredBy:this.currentTrigger}:{}}),{allowed:!1,error:Pe("permission-denied",`get ${e} simulator error`,{request:{method:"get",path:e,auth:n}})};const g=f.data.results[0];if(g.state==="UNSUPPORTED")throw this.emitRequest({at:c,evalMs:p,method:"get",path:e,auth:n,result:"unsupported",debugMessages:Te(g),origin:"listener",...this.currentTrigger?{triggeredBy:this.currentTrigger}:{}}),new wi(Si("get",e,Te(g)),"get",e,Te(g));const b=g.state==="PASSED",v=this.state.get(e);return this.emitRequest({at:c,evalMs:p,method:"get",path:e,auth:n,result:b?"allow":"deny",debugMessages:Te(g),evaluatedRule:xi(g),origin:"listener",resourceBefore:{data:v,exists:v!==null},...this.currentTrigger?{triggeredBy:this.currentTrigger}:{}}),b?{allowed:!0,data:v}:{allowed:!1,error:Pe("permission-denied",`get ${e} denied by rules`,{request:{method:"get",path:e,auth:n},resource:{data:v,exists:v!==null}})}}rulesAst(){var e;return((e=this.parsedRulesCache)==null?void 0:e.source)!==this.rulesSource&&(this.parsedRulesCache={source:this.rulesSource,ast:$y(this.rulesSource)}),this.parsedRulesCache.ast}silentReadCollection(e,n,r,s=!1){const o=Nt.fromMillis(Date.now()),c=`${e}/__listPlaceholder__`,d=(r==null?void 0:r.structured)??{},f=Bw(d),p={...s?{admin:!0}:{},...f?{query:f}:{}},g=Object.keys(p).length>0?p:void 0,b=Date.now(),v=performance.now();if(s){const q=this.state.list(e).filter(N=>!N.phantom).map(N=>({path:N.path,data:N.data})),I=r?r(q):q;return this.emitRequest({at:b,evalMs:0,method:"list",path:e,auth:n,result:"allow",debugMessages:["admin lens — rules bypassed"],origin:"listener",...g?{detail:g}:{},...this.currentTrigger?{triggeredBy:this.currentTrigger}:{}}),{allowed:!0,docs:I}}const x=Iw(this.rulesAst(),c,n,d);if(x.kind==="unprovable"){const q=performance.now()-v,I=`list ${e} denied: unprovable query — rules are not filters (${x.reason})`;return this.emitRequest({at:b,evalMs:q,method:"list",path:e,auth:n,result:"deny",debugMessages:[I],origin:"listener",...g?{detail:g}:{},...this.currentTrigger?{triggeredBy:this.currentTrigger}:{}}),{allowed:!1,error:Pe("permission-denied",I,{request:{method:"list",path:e,auth:n}})}}const _=this.buildTestCase({method:"list",path:c,auth:n},o);this.applyListProof(_,x,d);const k=this.simulator.simulate(this.rulesSource,[_],{getDoc:q=>this.state.get(q)}),R=performance.now()-v;if(!k.success)return this.emitRequest({at:b,evalMs:R,method:"list",path:e,auth:n,result:"deny",debugMessages:[`Simulation error: ${k.error.message}`],origin:"listener",...g?{detail:g}:{},...this.currentTrigger?{triggeredBy:this.currentTrigger}:{}}),{allowed:!1,error:Pe("permission-denied",`list ${e} simulator error`,{request:{method:"list",path:e,auth:n}})};const C=k.data.results[0];if(C.state==="UNSUPPORTED")throw this.emitRequest({at:b,evalMs:R,method:"list",path:e,auth:n,result:"unsupported",debugMessages:Te(C),origin:"listener",...g?{detail:g}:{},...this.currentTrigger?{triggeredBy:this.currentTrigger}:{}}),new wi(Si("list",e,Te(C)),"list",e,Te(C));if(C.state!=="PASSED")return this.emitRequest({at:b,evalMs:R,method:"list",path:e,auth:n,result:"deny",debugMessages:Te(C),evaluatedRule:xi(C),origin:"listener",...g?{detail:g}:{},...this.currentTrigger?{triggeredBy:this.currentTrigger}:{}}),{allowed:!1,error:Pe("permission-denied",`list ${e} denied by rules`,{request:{method:"list",path:e,auth:n}})};this.emitRequest({at:b,evalMs:R,method:"list",path:e,auth:n,result:"allow",debugMessages:Te(C),evaluatedRule:xi(C),origin:"listener",...g?{detail:g}:{},...this.currentTrigger?{triggeredBy:this.currentTrigger}:{}});const T=this.state.list(e).filter(q=>!q.phantom).map(q=>({path:q.path,data:q.data}));return{allowed:!0,docs:r?r(T):T}}applyListProof(e,n,r){n.kind==="provable"&&n.syntheticResource&&(e.resource=n.syntheticResource),(r.limit!=null||r.offset!=null||r.orderBy!=null)&&(e.query={...r.limit!=null?{limit:r.limit}:{},...r.offset!=null?{offset:r.offset}:{},...r.orderBy!=null?{orderBy:r.orderBy}:{}})}markErrored(e,n){if(e.errored=!0,this.emitSnapshotError(n,e.target,e.id),!!e.errorCallback)try{e.errorCallback(n)}catch{}}getSnapshotListenerCount(){return this.snapshotListeners.size}dispose(){this.snapshotListeners.clear(),this.denialListeners.clear(),this.snapshotErrorListeners.clear(),this.requestListeners.clear(),this.writeListeners.clear(),this.deliveryListeners.clear(),this.suppressedListeners.clear(),this.lifecycleListeners.clear(),this.deliveryQueue.length=0,this.deliveryScheduled=!1}seed(e){return this.rulesSource=e.rules,this.state=e.baseDocuments?new Ip({},new J2(e.baseDocuments)):new Ip(e.documents??{}),this.seedSnapshot=e.baseDocuments??this.state.snapshot(),this.eventLog.clear(),Pu(e.rules)}deployRules(e){const n=Pu(e);return this.rulesSource=e,this.reEvaluateAllListeners(),n}reEvaluateAllListeners(){if(this.snapshotListeners.size===0)return;const e=Array.from(this.snapshotListeners.values());for(const n of e)this.snapshotListeners.has(n.id)&&(n.target.kind==="doc"?this.reEvaluateDocListener(n):this.reEvaluateQueryListener(n))}reevaluateLiveListeners(e,n){if(this.snapshotListeners.size===0)return;const r=Array.from(this.snapshotListeners.values());for(const s of r)s.followsCurrentUser&&s.authScope===n&&this.snapshotListeners.has(s.id)&&(s.auth=e,s.target.kind==="doc"?this.reEvaluateDocListener(s):this.reEvaluateQueryListener(s))}reEvaluateDocListener(e){if(e.target.kind!=="doc")return;const n=this.silentReadDoc(e.target.path,e.auth,e.bypassRules);if(!n.allowed){if(e.errored)return;this.markErrored(e,n.error);return}if(e.errored){e.errored=!1;const o=$a(e.target.path,n.data);e.currentSnapshot=o,e.currentDocData=n.data;try{e.callback(o)}catch{}return}const r=e.currentDocData??null;if($w(r,n.data))return;const s=$a(e.target.path,n.data);e.currentSnapshot=s,e.currentDocData=n.data;try{e.callback(s)}catch{}}reEvaluateQueryListener(e){if(e.target.kind!=="query")return;const n=this.silentReadCollection(e.target.collection,e.auth,e.target.constraints,e.bypassRules);if(!n.allowed){if(e.errored)return;this.markErrored(e,n.error);return}if(e.errored){e.errored=!1;const c=Ba({path:e.target.collection},n.docs,{excludesMetadataChanges:!e.options.includeMetadataChanges});e.currentSnapshot=c,e.currentDocs=n.docs;try{e.callback(c)}catch{}return}const r=e.currentDocs??[],s=Ba({path:e.target.collection},n.docs,{excludesMetadataChanges:!e.options.includeMetadataChanges},r);if(s.docChanges().length!==0){e.currentSnapshot=s,e.currentDocs=n.docs;try{e.callback(s)}catch{}}}getRules(){return this.rulesSource}getDocument(e){return this.state.get(e)}listDocuments(e){return this.state.list(e)}scanDocuments(e,n){return this.state.scan(e,n)}readQueryCandidates(e,n,r,s,o){const c=s??{},d=Bw(c),f={...o?{admin:!0}:{},...d?{query:d}:{}},p=Object.keys(f).length>0?f:void 0;if(o)return this.emitRequest({at:Date.now(),evalMs:0,method:"list",path:n,auth:r,result:"allow",debugMessages:["admin lens — rules bypassed (Studio Gap #2)"],origin:"user",...p?{detail:p}:{}}),{allowed:!0,docs:e};const g=Nt.fromMillis(Date.now()),b=`${n}/__listPlaceholder__`,v=Date.now(),x=performance.now(),_=Iw(this.rulesAst(),b,r,c);if(_.kind==="unprovable"){const U=performance.now()-x,q=`list ${n} denied: unprovable query — rules are not filters (${_.reason})`;this.emitRequest({at:v,evalMs:U,method:"list",path:n,auth:r,result:"deny",debugMessages:[q],origin:"user",...p?{detail:p}:{}});const I=Pe("permission-denied",q,{request:{method:"list",path:n,auth:r}});return this.emitDenial(I),{allowed:!1,error:I}}const k=this.buildTestCase({method:"list",path:b,auth:r},g);this.applyListProof(k,_,c);const R=this.simulator.simulate(this.rulesSource,[k],{getDoc:U=>this.state.get(U)}),C=performance.now()-x;if(!R.success)return this.emitRequest({at:v,evalMs:C,method:"list",path:n,auth:r,result:"deny",debugMessages:[`Simulation error: ${R.error.message}`],origin:"user",...p?{detail:p}:{}}),{allowed:!1,error:Pe("permission-denied",`list ${n} simulator error`,{request:{method:"list",path:n,auth:r}})};const T=R.data.results[0];if(T.state==="UNSUPPORTED")throw this.emitRequest({at:v,evalMs:C,method:"list",path:n,auth:r,result:"unsupported",debugMessages:Te(T),origin:"user",...p?{detail:p}:{}}),new wi(Si("list",n,Te(T)),"list",n,Te(T));if(T.state!=="PASSED"){const U=Te(T);this.emitRequest({at:v,evalMs:C,method:"list",path:n,auth:r,result:"deny",debugMessages:U,evaluatedRule:xi(T),origin:"user",...p?{detail:p}:{}});const q=Pe("permission-denied",`list ${n} denied by rules`,{request:{method:"list",path:n,auth:r}});return this.emitDenial(q),{allowed:!1,error:q}}return this.emitRequest({at:v,evalMs:C,method:"list",path:n,auth:r,result:"allow",debugMessages:Te(T),evaluatedRule:xi(T),origin:"user",...p?{detail:p}:{}}),{allowed:!0,docs:e}}listRootCollections(){return this.state.listRootCollections()}listSubcollections(e){return this.state.listSubcollections(e)}snapshot(){return this.state.snapshot()}capturePriors(e){const n={};for(const r of e){const s=this.state.get(r);n[r]=s?{...s}:null}return n}adminSetDocument(e,n){this.state.set(e,n??{}),this.notifyListenersForPaths(new Set([e]))}adminDeleteDocument(e){const n=this.state.delete(e);return n.success&&this.notifyListenersForPaths(new Set([e])),{deleted:n.success}}runSimulate(e,n,r){if(n){const s=e.map(o=>vD(o.description));return{success:!0,data:{passed:s.length,failed:0,unsupported:0,results:s}}}return this.simulator.simulate(this.rulesSource,e,{getDoc:s=>this.state.get(s),...r?{batchProjection:r}:{}})}buildBatchProjection(e){const n=new Map;for(const r of e)r.method==="get"||r.method==="list"||n.set(r.path,r.method==="delete"?null:r.data??{});return n}execute(e){const{method:n,path:r,auth:s,data:o,autoId:c,requestTime:d,merge:f,bypassRules:p}=e,g=p?{admin:!0}:void 0;if(n==="get"||n==="list"){const P=Nt.fromMillis(Date.now()),F=this.buildTestCase(e,P),w=Date.now(),E=performance.now(),O=this.runSimulate([F],p),D=performance.now()-E;if(!O.success){const B=this.eventLog.append({type:"single",method:n,path:r,auth:s?{uid:s.uid}:null,allowed:!1,debugMessages:[`Simulation error: ${O.error.message}`]});return this.emitRequest({at:w,evalMs:D,method:n,path:r,auth:s,result:"deny",debugMessages:[`Simulation error: ${O.error.message}`],origin:"user",...g?{detail:g}:{}}),{allowed:!1,debugMessages:[O.error.message],event:B}}const z=O.data.results[0];if(z.state==="UNSUPPORTED")throw this.emitRequest({at:w,evalMs:D,method:n,path:r,auth:s,result:"unsupported",debugMessages:Te(z),origin:"user",...g?{detail:g}:{}}),new wi(Si(n,r,Te(z)),n,r,Te(z));const $=z.state==="PASSED";let K;$&&(K=n==="get"?this.state.get(r):this.state.list(r));const W=this.eventLog.append({type:"single",method:n,path:r,auth:s?{uid:s.uid}:null,allowed:$,debugMessages:Te(z)}),se={allowed:$,data:$?K:void 0,debugMessages:Te(z),event:W};if(!$){const B={method:n,path:r,auth:s},ee=n==="get"?{data:this.state.get(r),exists:this.state.get(r)!==null}:void 0;se.error=Pe("permission-denied",`${n} ${r} denied by rules`,{request:B,...ee?{resource:ee}:{}}),this.emitDenial(se.error)}return this.emitRequest({at:w,evalMs:D,method:n,path:r,auth:s,result:$?"allow":"deny",debugMessages:Te(z),evaluatedRule:xi(z),origin:"user",...n==="get"?{resourceBefore:{data:this.state.get(r),exists:this.state.get(r)!==null}}:{},...g?{detail:g}:{}}),se}const b=this.capturePriors([r]),v=d??Nt.fromMillis(Date.now());let x;try{x=o&&ar({...o},{path:r,method:n,prior:this.state.get(r),serverTime:v}),n==="update"&&x&&K2(x)}catch(P){const F=P.message,w=this.eventLog.append({type:"single",method:n,path:r,auth:s?{uid:s.uid}:null,data:o,allowed:!1,priorDocs:b,debugMessages:[`FieldValue resolve error: ${F}`]});return this.emitRequest({at:Date.now(),evalMs:0,method:n,path:r,auth:s,result:"deny",debugMessages:[`FieldValue resolve error: ${F}`],...x?{resourceData:x}:o?{resourceData:o}:{},resourceBefore:{data:b[r]??null,exists:(b[r]??null)!==null},origin:"user",...g?{detail:g}:{}}),{allowed:!1,debugMessages:[F],event:w,error:Pe("invalid-argument",F)}}const _=this.buildTestCase({...e,data:x},v),k=Date.now(),R=performance.now(),C=this.runSimulate([_],p),T=performance.now()-R;if(!C.success){const P=this.eventLog.append({type:"single",method:n,path:r,auth:s?{uid:s.uid}:null,data:x,allowed:!1,priorDocs:b,debugMessages:[`Simulation error: ${C.error.message}`]});return this.emitRequest({at:k,evalMs:T,method:n,path:r,auth:s,result:"deny",debugMessages:[`Simulation error: ${C.error.message}`],...o?{resourceData:o}:{},resourceBefore:{data:b[r]??null,exists:(b[r]??null)!==null},origin:"user",...g?{detail:g}:{}}),{allowed:!1,debugMessages:[C.error.message],event:P,error:Pe("invalid-argument",C.error.message)}}const U=C.data.results[0];if(U.state==="UNSUPPORTED")throw this.emitRequest({at:k,evalMs:T,method:n,path:r,auth:s,result:"unsupported",debugMessages:Te(U),...o?{resourceData:o}:{},resourceBefore:{data:b[r]??null,exists:(b[r]??null)!==null},origin:"user",...g?{detail:g}:{}}),new wi(Si(n,r,Te(U)),n,r,Te(U));let q=U.state==="PASSED",I=null;q&&(I=this.applyWrite(n,r,x,f),I&&(q=!1));const N=this.eventLog.append({type:"single",method:n,path:r,auth:s?{uid:s.uid}:null,data:x,allowed:q,priorDocs:q?b:void 0,debugMessages:Te(U)}),M={allowed:q,debugMessages:Te(U),event:N};if(!q)if(I)M.error=I;else{const P=b[r]??null,F=n==="set"?P!==null?"update":"create":n;M.error=Pe("permission-denied",`${n} ${r} denied by rules`,{request:{method:F,path:r,auth:s,...o?{resourceData:o}:{}},resource:{data:P,exists:P!==null}}),this.emitDenial(M.error)}const L=b[r]??null,H=q?this.state.get(r):L;if(this.emitRequest({at:k,evalMs:T,method:n,path:r,auth:s,result:q?"allow":"deny",debugMessages:Te(U),evaluatedRule:xi(U),...o?{resourceData:o}:{},resourceBefore:{data:L,exists:L!==null},...n!=="delete"?{resourceAfter:{data:H,exists:H!==null}}:{resourceAfter:{data:null,exists:!1}},origin:"user",...g?{detail:g}:{}}),q){const P=o?Mp(o):void 0,F=c&&n==="create"?r.split("/").pop():void 0;this.emitWrite({method:n,path:r,auth:s,...n!=="delete"&&o?{data:o}:{},priorState:L,nextState:n==="delete"?null:H,...P&&P.length>0?{sentinels:P}:{},...F?{autoId:F}:{},requestTime:v,...g?{detail:g}:{}})}if(q){const P=this.currentTrigger;this.currentTrigger={method:n,path:r};try{this.notifyListenersForPaths(new Set([r]))}finally{this.currentTrigger=P}}return M}createWithAutoId(e,n,r,s){const o=e.endsWith("/")?e.slice(0,-1):e,c=Vy(),d=`${o}/${c}`,f=this.execute({method:"create",path:d,auth:r,data:n,autoId:!0,bypassRules:s});return{path:d,result:f}}batch(e,n,r){var C,T,U,q;const s=r?{admin:!0}:void 0,o=this.capturePriors(e.map(I=>I.path)),c=[],d=Nt.fromMillis(Date.now()),f=`batch-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,p=[],g=[];for(const I of e)try{g.push({...I,data:I.data?ar({...I.data},{path:I.path,method:I.method,prior:this.state.get(I.path),serverTime:d}):I.data})}catch(N){const M=N.message,L=this.eventLog.append({type:"batch",method:"batch",path:"",auth:n?{uid:n.uid}:null,allowed:!1,operations:e.map(P=>({method:P.method,path:P.path,data:P.data,allowed:!1})),debugMessages:[`FieldValue resolve error on '${I.path}': ${M}`]});this.emitRequest({at:Date.now(),evalMs:0,method:I.method,path:I.path,auth:n,result:"deny",debugMessages:[`FieldValue resolve error: ${M}`],...I.data?{resourceData:I.data}:{},resourceBefore:{data:o[I.path]??null,exists:(o[I.path]??null)!==null},origin:"batch",groupId:f,...s?{detail:s}:{}});const H=Pe("invalid-argument",M);return{allowed:!1,results:e.map(P=>({path:P.path,allowed:!1,debugMessages:[M],...P.path===I.path?{error:H}:{}})),event:L,error:H}}const b=g.map(I=>this.buildTestCase({method:I.method,path:I.path,auth:n,data:I.data},d)),v=this.buildBatchProjection(b);let x=!0;for(let I=0;I<g.length;I++){const N=g[I],M=(C=e[I])==null?void 0:C.data,L=b[I],H=Date.now(),P=performance.now(),F=this.runSimulate([L],r,v),w=performance.now()-P;if(!F.success){c.push({path:N.path,allowed:!1,debugMessages:[F.error.message],error:Pe("invalid-argument",F.error.message)}),p.push({at:H,evalMs:w,method:N.method,path:N.path,auth:n,result:"deny",debugMessages:[`Simulation error: ${F.error.message}`],...M?{resourceData:M}:{},resourceBefore:{data:o[N.path]??null,exists:(o[N.path]??null)!==null},origin:"batch",groupId:f,...s?{detail:s}:{}}),x=!1;continue}const E=F.data.results[0];if(E.state==="UNSUPPORTED")throw this.emitRequest({at:H,evalMs:w,method:N.method,path:N.path,auth:n,result:"unsupported",debugMessages:Te(E),...M?{resourceData:M}:{},resourceBefore:{data:o[N.path]??null,exists:(o[N.path]??null)!==null},origin:"batch",groupId:f,...s?{detail:s}:{}}),new wi(Si(N.method,N.path,Te(E)),N.method,N.path,Te(E));const O=E.state==="PASSED",D={path:N.path,allowed:O,debugMessages:Te(E)};if(!O){const z=o[N.path]??null;D.error=Pe("permission-denied",`${N.method} ${N.path} denied by rules`,{request:{method:N.method,path:N.path,auth:n,...M?{resourceData:M}:{}},resource:{data:z,exists:z!==null}}),this.emitDenial(D.error),x=!1}p.push({at:H,evalMs:w,method:N.method,path:N.path,auth:n,result:O?"allow":"deny",debugMessages:Te(E),...M?{resourceData:M}:{},resourceBefore:{data:o[N.path]??null,exists:(o[N.path]??null)!==null},origin:"batch",groupId:f,...s?{detail:s}:{}}),c.push(D)}let _=null;if(x){const I=g.map(M=>({method:M.method,path:M.path,data:M.data})),N=this.state.applyBatch(I);if(!N.success){x=!1;const M=(T=N.errors)==null?void 0:T[0];if(M!==void 0){const L=g[M.index],H=(L==null?void 0:L.method)==="create"?"already-exists":"not-found";_=Pe(H,M.error);const P=c[M.index];P&&(P.allowed=!1,P.error=_)}}}const k=this.eventLog.append({type:"batch",method:"batch",path:"",auth:n?{uid:n.uid}:null,allowed:x,priorDocs:x?o:void 0,operations:g.map((I,N)=>{var M;return{method:I.method,path:I.path,data:I.data,allowed:((M=c[N])==null?void 0:M.allowed)??!1}}),debugMessages:x?["Batch committed"]:["Batch rolled back — one or more operations denied"]});let R;x||(R=_??((U=c.find(I=>I.error))==null?void 0:U.error)??Pe("permission-denied","Batch denied"));for(let I=0;I<p.length;I++){const N=p[I];if(!N)continue;const M=x&&((q=c[I])==null?void 0:q.allowed)===!0;if(M){const L=this.state.get(N.path);N.method!=="delete"?N.resourceAfter={data:L,exists:L!==null}:N.resourceAfter={data:null,exists:!1}}else{const L=o[N.path]??null;N.resourceAfter={data:L,exists:L!==null}}if(this.emitRequest(N),M&&N.method!=="get"&&N.method!=="list"){const L=o[N.path]??null,H=e[I],P=H&&"data"in H&&H.data?Mp(H.data):void 0;this.emitWrite({method:N.method,path:N.path,auth:n,...N.method!=="delete"&&N.resourceData?{data:N.resourceData}:{},priorState:L,nextState:N.method==="delete"?null:this.state.get(N.path),...N.groupId?{groupId:N.groupId,groupKind:"batch"}:{},...P&&P.length>0?{sentinels:P}:{},requestTime:d,...s?{detail:s}:{}})}}if(x){const I=new Set;for(const L of g)I.add(L.path);const N=g[0],M=this.currentTrigger;this.currentTrigger=N?{method:"batch",path:N.path}:{method:"batch",path:""};try{this.notifyListenersForPaths(I)}finally{this.currentTrigger=M}}return{allowed:x,results:c,event:k,...R?{error:R}:{}}}transaction(e,n){const r=n.auth,s=this.state.snapshot(),o=f=>this.state.get(f),c=new lD(o);let d;try{d=e(c)}catch(f){throw this.logAbortedTransaction(c,r,f),f}return d!==null&&typeof(d==null?void 0:d.then)=="function"?d.then(f=>this.commitTransaction(c,r,s,n,f),f=>{throw this.logAbortedTransaction(c,r,f),f}):this.commitTransaction(c,r,s,n,d)}commitTransaction(e,n,r,s,o){var N,M,L,H;const{reads:c,writes:d}=e.consume(),f=s.bypassRules?{admin:!0}:void 0,p=`tx-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,g=[];if(d.length===0){const P=this.eventLog.append({type:"transaction",method:"transaction",path:"",auth:n?{uid:n.uid}:null,allowed:!0,reads:c.map(F=>({path:F.path,data:F.data})),operations:[],snapshot:r,debugMessages:["Transaction committed (read-only — no writes queued)"]});return{allowed:!0,reads:[...c],writes:[],returnValue:o,event:P}}let b;try{b=uD(d)}catch(P){const F=P;throw this.eventLog.append({type:"transaction",method:"transaction",path:"",auth:n?{uid:n.uid}:null,allowed:!1,aborted:!0,reads:c.map(w=>({path:w.path,data:w.data})),error:{name:F.name,message:F.message,code:"failed-precondition"},debugMessages:[`Transaction aborted at merge: ${F.message}`]}),P}const v=Nt.fromMillis(Date.now()),x=[];for(const P of b){if(P.method==="delete"){x.push(P);continue}try{const F=ar({...P.data},{path:P.path,method:P.method,prior:this.state.get(P.path),serverTime:v});x.push({...P,data:F})}catch(F){const w=F.message,E=Pe("invalid-argument",w),O=this.eventLog.append({type:"transaction",method:"transaction",path:"",auth:n?{uid:n.uid}:null,allowed:!1,reads:c.map($=>({path:$.path,data:$.data})),operations:b.map($=>({method:$.method,path:$.path,data:$.data,allowed:!1})),debugMessages:[`FieldValue resolve error on '${P.path}': ${w}`]}),D=P.method==="set"?this.state.get(P.path)!==null?"update":"create":P.method,z=r[P.path]??null;return this.emitRequest({at:Date.now(),evalMs:0,method:D,path:P.path,auth:n,result:"deny",debugMessages:[`FieldValue resolve error: ${w}`],...P.data&&D!=="delete"?{resourceData:P.data}:{},resourceBefore:{data:z,exists:z!==null},origin:"transaction",groupId:p,...f?{detail:f}:{},provenance:s.provenance}),{allowed:!1,reads:[...c],writes:b.map($=>{const K=$.method==="set"?this.state.get($.path)!==null?"update":"create":$.method;return{path:$.path,method:K,allowed:!1,debugMessages:$.path===P.path?[w]:[],...$.path===P.path?{error:E}:{}}}),returnValue:o,event:O,error:E}}}const _=x.map(P=>{const F=this.state.get(P.path)!==null,w=P.method==="set"?F?"update":"create":P.method;return this.buildTestCase({method:w,path:P.path,auth:n,data:P.data},v)}),k=this.buildBatchProjection(_),R=[];let C=!0;for(let P=0;P<x.length;P++){const F=x[P],w=(N=b[P])==null?void 0:N.data,E=this.state.get(F.path)!==null,O=F.method==="set"?E?"update":"create":F.method,D=r[F.path]??null,z=_[P],$=Date.now(),K=performance.now(),W=this.runSimulate([z],s.bypassRules,k),se=performance.now()-K;if(!W.success){R.push({path:F.path,method:O,allowed:!1,debugMessages:[W.error.message],error:Pe("invalid-argument",W.error.message)}),g.push({at:$,evalMs:se,method:O,path:F.path,auth:n,result:"deny",debugMessages:[`Simulation error: ${W.error.message}`],...w&&O!=="delete"?{resourceData:w}:{},resourceBefore:{data:D,exists:D!==null},origin:"transaction",groupId:p,...f?{detail:f}:{},provenance:s.provenance}),C=!1;continue}const B=W.data.results[0];if(B.state==="UNSUPPORTED")throw this.emitRequest({at:$,evalMs:se,method:O,path:F.path,auth:n,result:"unsupported",debugMessages:Te(B),...w&&O!=="delete"?{resourceData:w}:{},resourceBefore:{data:D,exists:D!==null},origin:"transaction",groupId:p,...f?{detail:f}:{},provenance:s.provenance}),new wi(Si(O,F.path,Te(B)),O,F.path,Te(B));const ee=B.state==="PASSED",ae={path:F.path,method:O,allowed:ee,debugMessages:Te(B)};if(g.push({at:$,evalMs:se,method:O,path:F.path,auth:n,result:ee?"allow":"deny",debugMessages:Te(B),...w&&O!=="delete"?{resourceData:w}:{},resourceBefore:{data:D,exists:D!==null},origin:"transaction",groupId:p,...f?{detail:f}:{},provenance:s.provenance}),!ee){const le=r[F.path]??null;ae.error=Pe("permission-denied",`${O} ${F.path} denied by rules`,{request:{method:O,path:F.path,auth:n,...w&&O!=="delete"?{resourceData:w}:{}},resource:{data:le,exists:le!==null}}),this.emitDenial(ae.error),C=!1}R.push(ae)}let T=null;if(C){const P=this.state.applyBatch(x);if(!P.success){C=!1;const F=(M=P.errors)==null?void 0:M[0];if(F!==void 0){const w=x[F.index],E=(w==null?void 0:w.method)==="create"?"already-exists":"not-found";T=Pe(E,F.error);const O=R[F.index];O&&(O.allowed=!1,O.error=T)}}}const U=this.eventLog.append({type:"transaction",method:"transaction",path:"",auth:n?{uid:n.uid}:null,allowed:C,reads:c.map(P=>({path:P.path,data:P.data})),operations:x.map((P,F)=>{var w;return{method:P.method,path:P.path,data:P.data,allowed:((w=R[F])==null?void 0:w.allowed)??!1}}),snapshot:C?r:void 0,debugMessages:C?["Transaction committed"]:["Transaction rolled back — one or more operations denied"]});for(let P=0;P<g.length;P++){const F=g[P],w=C&&((L=R[P])==null?void 0:L.allowed)===!0;if(w){const E=this.state.get(F.path);F.method!=="delete"?F.resourceAfter={data:E,exists:E!==null}:F.resourceAfter={data:null,exists:!1}}else{const E=r[F.path]??null;F.resourceAfter={data:E,exists:E!==null}}if(this.emitRequest(F),w&&F.method!=="get"&&F.method!=="list"){const E=r[F.path]??null,O=b[P],D=O&&O.method!=="delete"&&O.data?Mp(O.data):void 0;this.emitWrite({method:F.method,path:F.path,auth:n,...F.method!=="delete"&&F.resourceData?{data:F.resourceData}:{},priorState:E,nextState:F.method==="delete"?null:this.state.get(F.path),...F.groupId?{groupId:F.groupId,groupKind:"transaction"}:{},...D&&D.length>0?{sentinels:D}:{},requestTime:v,...f?{detail:f}:{},provenance:s.provenance})}}let q;C||(q=T??((H=R.find(P=>P.error))==null?void 0:H.error)??Pe("permission-denied","Transaction denied"));const I={allowed:C,reads:[...c],writes:R,returnValue:o,event:U,...q?{error:q}:{}};if(s.readOnly&&e.hadWrites()&&(I.readOnlyViolation=!0),C){const P=new Set;for(const E of x)P.add(E.path);const F=x[0],w=this.currentTrigger;this.currentTrigger=F?{method:"transaction",path:F.path}:{method:"transaction",path:""};try{this.notifyListenersForPaths(P)}finally{this.currentTrigger=w}}return I}logAbortedTransaction(e,n,r){const s=r,{reads:o}=e.consume();this.eventLog.append({type:"transaction",method:"transaction",path:"",auth:n?{uid:n.uid}:null,allowed:!1,aborted:!0,reads:o.map(c=>({path:c.path,data:c.data})),error:{name:r.name,message:r.message,...s.code!==void 0?{code:String(s.code)}:{}},debugMessages:[`Transaction aborted: ${r.message}`]})}undo(){const e=this.eventLog.popLastWrite();if(!e)return null;if(e.priorDocs)this.state.restorePaths(e.priorDocs);else if(e.snapshot)this.state.restore(e.snapshot);else return null;return e}redo(){const e=this.eventLog.popLastUndo();if(!e)return null;const n=e.type==="batch"&&e.operations?e.operations.map(d=>d.path):e.path?[e.path]:[],r=!!e.snapshot,s=r?void 0:this.capturePriors(n),o=r?this.state.snapshot():void 0;if(e.type==="batch"&&e.operations)for(const d of e.operations)d.allowed&&this.applyWrite(d.method,d.path,d.data);else e.allowed&&this.applyWrite(e.method,e.path,e.data);const c=this.eventLog.append({...e,snapshot:o,priorDocs:s},!0);return{allowed:e.allowed,debugMessages:["Redo: "+(e.allowed?"applied":"skipped (was denied)")],event:c}}getEvents(){return this.eventLog.getEvents()}getEventCount(){return this.eventLog.size()}buildTestCase(e,n){const r=this.state.get(e.path),s=e.method==="set"?r!==null?"update":"create":e.method;let o=e.data;if(e.method==="get"||e.method==="list")o=void 0;else if(e.method==="update"&&r&&e.data){const{writes:c,deletedKeys:d}=ji(e.data),f={...r,...c};for(const p of d)delete f[p];o=f}else e.data&&(o=ji(e.data).writes);return{description:`${e.method} ${e.path}`,expectation:"ALLOW",method:s,path:e.path,auth:e.auth?{uid:e.auth.uid,token:e.auth.token}:null,data:o,resource:r??void 0,...n?{requestTime:mD(n)}:{}}}applyWrite(e,n,r,s){if(s!==void 0&&s!==!1&&(e==="create"||e==="update")){const o=s===!0?void 0:s.mergeFields;return this.state.setMerge(n,r??{},o),null}switch(e){case"create":{const o=this.state.create(n,r??{});return o.success?null:Pe("already-exists",o.error??`Document '${n}' already exists`)}case"update":{const o=this.state.update(n,r??{});return o.success?null:Pe("not-found",o.error??`Document '${n}' does not exist`)}case"set":return this.state.set(n,r??{}),null;case"delete":return this.state.delete(n),null;default:return null}}}class rt extends Error{constructor(n,r,s){const o=typeof n=="object",c=o?n.code:n,d=o?n.message:r,f=o?n.denialContext:s,p=o?n.remediation:void 0,g=p!==void 0?`${d}
|
|
1200
|
-
|
|
1201
|
-
Remediation:
|
|
1202
|
-
${p}`:d;super(g);G(this,"code");G(this,"denialContext");G(this,"remediation");this.name="SandboxError",this.code=c,f!==void 0&&(this.denialContext=f),p!==void 0&&(this.remediation=p)}}function Tm(t){return t.kind==="request"||t.kind==="operation"}function Bl(t){const e=Object.freeze({...t.source}),n=Object.freeze({...t.authLens});return Object.freeze({source:e,authLens:n,...t.planId===void 0?{}:{planId:t.planId}})}function ad(t){const e=Bl(t);return{actor:e.source,authLens:e.authLens,operationContext:e,...e.planId===void 0?{}:{planId:e.planId}}}function Pw(t){var n;const e=(n=t==null?void 0:t.operationContext)==null?void 0:n.source;if(e&&e.kind!=="unattributed")return e;if(t!=null&&t.actor&&t.actor.kind!=="unattributed")return t.actor}function Od(t,e){var s,o,c,d,f,p,g,b;const n=((s=t==null?void 0:t.operationContext)==null?void 0:s.source)??(t==null?void 0:t.actor),r=((o=e==null?void 0:e.operationContext)==null?void 0:o.source)??(e==null?void 0:e.actor);return Bl({source:Pw(t)??Pw(e)??n??r??{kind:"unattributed"},authLens:((c=e==null?void 0:e.operationContext)==null?void 0:c.authLens)??(e==null?void 0:e.authLens)??((d=t==null?void 0:t.operationContext)==null?void 0:d.authLens)??(t==null?void 0:t.authLens)??{mode:"app-session"},...(((f=t==null?void 0:t.operationContext)==null?void 0:f.planId)??(t==null?void 0:t.planId)??((p=e==null?void 0:e.operationContext)==null?void 0:p.planId)??(e==null?void 0:e.planId))===void 0?{}:{planId:((g=t==null?void 0:t.operationContext)==null?void 0:g.planId)??(t==null?void 0:t.planId)??((b=e==null?void 0:e.operationContext)==null?void 0:b.planId)??(e==null?void 0:e.planId)}})}function wD(t){return Od(void 0,t)}function iE(t){var e;return t.rulesDisposition?t.rulesDisposition:t.kind==="operation"&&t.origin==="admin"||((e=t.detail)==null?void 0:e.admin)===!0?{kind:"bypassed",reason:"admin"}:t.result==="unsupported"?{kind:"not-evaluated",reason:"unsupported"}:t.kind==="operation"&&t.result==="error"?{kind:"not-evaluated",reason:"runtime-error"}:t.kind==="operation"&&t.result==="not-applicable"?{kind:"not-evaluated",reason:"not-a-rules-operation"}:t.result==="deny"?{kind:"evaluated",verdict:"deny"}:t.kind==="request"?{kind:"evaluated",verdict:"allow"}:t.rules?{kind:"evaluated",verdict:"allow"}:{kind:"not-evaluated",reason:"no-rules"}}function SD(t){return t===null?null:Object.freeze({uid:t.uid,...t.token===void 0?{}:{token:aE(t.token)}})}function aE(t){const e={};for(const[n,r]of Object.entries(t))e[n]=oE(r);return Object.freeze(e)}function oE(t){return Array.isArray(t)?Object.freeze(t.map(oE)):t&&typeof t=="object"?aE(t):t}function lE(t){return Tm(t)?Object.freeze({id:t.id,at:t.at,eventKind:t.kind,service:t.kind==="request"?t.service??"firestore":t.service,method:t.method,...t.path===void 0?{}:{path:t.path},auth:SD(t.auth),result:t.result,context:wD(t),rules:Object.freeze({...iE(t)})}):null}function qw(t){return t===null?{mode:"anon"}:t.token===void 0?{mode:"as",uid:t.uid}:{mode:"as",uid:t.uid,token:t.token}}class so{constructor(e,n,r){G(this,"sandbox");G(this,"auth");G(this,"operationContext");this.sandbox=e,this.auth=n,this.operationContext=Bl(r??{source:{kind:"unattributed"},authLens:qw(n)})}withAuth(e){return Rm(e),new so(this.sandbox,e,{source:this.operationContext.source,authLens:qw(e),...this.operationContext.planId===void 0?{}:{planId:this.operationContext.planId}})}}function Fl(t,e){return new so(t.sandbox,t.auth,e)}function Rm(t){if(t===null)return;if(t===void 0)throw new rt({code:"invalid-argument",message:"withAuth() requires an explicit AuthState argument.",remediation:["For anonymous (unauthenticated) access: withAuth(null)",'For authenticated access: withAuth({ uid: "someUid" })','For custom claims: withAuth({ uid: "someUid", token: { role: "admin" } })'].join(`
|
|
1203
|
-
`)});if(typeof t!="object")throw new rt("invalid-argument","withAuth() expected null or an object with a `uid` field.");const e=t;if(typeof e.uid!="string"||e.uid.length===0)throw new rt("invalid-argument","withAuth() requires `uid` to be a non-empty string.");if("token"in e&&e.token!==void 0&&(e.token===null||typeof e.token!="object"||Array.isArray(e.token)))throw new rt("invalid-argument","withAuth() requires `token` (when present) to be a plain object.")}function _D(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e.length%4===0?"":"=".repeat(4-e.length%4),r=atob(e+n),s=new Uint8Array(r.length);for(let o=0;o<r.length;o++)s[o]=r.charCodeAt(o);return s}function ED(t){const e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}function Za(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(Za);const e=t;if(e.__type__==="__vector__"&&Array.isArray(e.value))return new no(e.value);if(typeof e.__type=="string")switch(e.__type){case"timestamp":return new Nt(e.seconds,e.nanos);case"bytes":return new Tn(_D(e.base64));case"latlng":return new jr(e.lat,e.lng);case"duration":return new Dt(e.seconds,e.nanos);case"reference":return new Ha(e.path);case"path":return new lr(e.segments)}if(typeof e.type=="string")switch(e.type){case"firestore/timestamp/1.0":{const r=e.seconds,s=e.nanoseconds;return new Nt(r,s)}case"firestore/bytes/1.0":return new Tn(ED(e.bytes));case"firestore/geoPoint/1.0":return new jr(e.latitude,e.longitude)}const n={};for(const[r,s]of Object.entries(e))n[r]=Za(s);return n}class pu extends Error{constructor(e){super(e),this.name="PersistenceSchemaError"}}function AD(t){let e;try{e=JSON.parse(t)}catch(s){throw new pu(`Persisted blob is not valid JSON: ${s.message}`)}if(typeof e!="object"||e===null)throw new pu("Persisted blob is not an object");if(e.version!==1&&e.version!==2)throw new pu(`Persisted blob has version ${String(e.version)}, expected 1 or 2`);if(typeof e.firestore!="object"||e.firestore===null)throw new pu("Persisted blob has no firestore field");const n={};for(const[s,o]of Object.entries(e.firestore))n[s]=Za(o);const r=e.services!==void 0&&typeof e.services=="object"&&e.services!==null?e.services:{};return{firestore:n,services:r}}const jD=3,kD=256,Dm="meta";function CD(t){let e=2166136261;for(let n=0;n<t.length;n++)e^=t.charCodeAt(n),e=e+((e<<1)+(e<<4)+(e<<7)+(e<<8)+(e<<24))>>>0;return(e%kD).toString(16).padStart(2,"0")}function ND(t){return JSON.parse(JSON.stringify(t))}function cE(t){const e=JSON.stringify(t);let n=2166136261;for(let r=0;r<e.length;r++)n^=e.charCodeAt(r),n=Math.imul(n,16777619)>>>0;return n}function uE(t,e,n){const r=new Map;r.set(Dm,{version:jD,savedAt:n,services:e});for(const[s,o]of Object.entries(t)){const c=CD(s);let d=r.get(c);d||(d={docs:{}},r.set(c,d)),d.docs[s]=ND(o)}for(const[s,o]of r)s!==Dm&&(o.checksum=cE(o.docs));return r}const dE="pyric-v3-records";function OD(t){return JSON.stringify({format:dE,records:Object.fromEntries(t)})}function TD(t){let e;try{e=JSON.parse(t)}catch{return new Map}const n=e;return n&&typeof n=="object"&&n.format===dE&&typeof n.records=="object"&&n.records!==null?new Map(Object.entries(n.records)):fE(t)??new Map}function fE(t){let e;try{e=AD(t)}catch{return null}return uE(e.firestore,e.services,0)}function RD(t){const e={};let n={};for(const[r,s]of t){if(r===Dm){const c=s;c&&typeof c.services=="object"&&c.services!==null&&(n=c.services);continue}const o=s;if(!(!o||typeof o.docs!="object"||o.docs===null)){if(typeof o.checksum=="number"&&cE(o.docs)!==o.checksum){console.warn(`[sandbox/persistence] checksum mismatch for bucket '${r}'; skipping corrupt bucket`);continue}for(const[c,d]of Object.entries(o.docs))e[c]=Za(d)}}return{firestore:e,services:n}}const Wa="snapshots";function Im(){const t=new Map,e=n=>{let r=t.get(n);return r||(r=new Map,t.set(n,r)),r};return{async getRecord(n,r){var o;const s=(o=t.get(n))==null?void 0:o.get(r);return s===void 0?null:structuredClone(s)},async listRecords(n){var r;return[...((r=t.get(n))==null?void 0:r.keys())??[]]},async putRecords(n,r){const s=e(n);for(const[o,c]of r)s.set(o,structuredClone(c))},async deleteRecords(n,r){const s=t.get(n);if(s)for(const o of r)s.delete(o)},async clear(n){t.delete(n)}}}function hE(t){return new Promise((e,n)=>{const r=indexedDB.open(t,1);r.onupgradeneeded=()=>{const s=r.result;s.objectStoreNames.contains(Wa)||s.createObjectStore(Wa)},r.onsuccess=()=>e(r.result),r.onerror=()=>n(r.error??new Error(`Failed to open IndexedDB '${t}'`)),r.onblocked=()=>n(new Error(`IndexedDB open blocked for '${t}'`))})}function $p(t,e,n){return hE(t).then(r=>new Promise((s,o)=>{const c=r.transaction(Wa,e),d=c.objectStore(Wa),f=n(d);let p=null;f&&(f.onsuccess=()=>{p=f.result??null},f.onerror=()=>o(f.error)),c.oncomplete=()=>{r.close(),s(p)},c.onerror=()=>{r.close(),o(c.error)},c.onabort=()=>{r.close(),o(c.error??new Error("IndexedDB transaction aborted"))}}))}function zw(t,e){return hE(t).then(n=>new Promise((r,s)=>{const o=n.transaction(Wa,"readwrite");e(o.objectStore(Wa)),o.oncomplete=()=>{n.close(),r()},o.onerror=()=>{n.close(),s(o.error)},o.onabort=()=>{n.close(),s(o.error??new Error("IndexedDB transaction aborted"))}}))}function DD(){if(typeof indexedDB>"u")throw new Error('IndexedDB is not available in this environment. Use { backend: "memory" } or supply an injectedBackend.');return{async getRecord(t,e){return await $p(t,"readonly",r=>r.get(e))??null},async listRecords(t){return(await $p(t,"readonly",n=>n.getAllKeys())??[]).map(n=>String(n))},async putRecords(t,e){await zw(t,n=>{for(const[r,s]of e)n.put(s,r)})},async deleteRecords(t,e){await zw(t,n=>{for(const r of e)n.delete(r)})},async clear(t){await $p(t,"readwrite",e=>e.clear())},async estimate(){var e;if(typeof navigator>"u"||!((e=navigator.storage)!=null&&e.estimate))return null;const t=await navigator.storage.estimate();return{usage:t.usage??0,quota:t.quota??0}}}}const ID=250,Vw="pyric:sandbox:auth-session";function Bp(t){return t==="auth"||t==="auth-session:[DEFAULT]"?Vw:`${Vw}:${encodeURIComponent(t)}`}function pE(t){const e=JSON.stringify(t);let n=2166136261;for(let r=0;r<e.length;r++)n^=e.charCodeAt(r),n=Math.imul(n,16777619)>>>0;return n}function MD(t){if(t&&typeof t=="object"){if(t.name==="QuotaExceededError")return!0;const e=t.message;if(typeof e=="string"&&/quota/i.test(e))return!0}return!1}function LD(t){return t.injectedBackend?t.injectedBackend:(t.backend??"indexedDB")==="memory"||typeof indexedDB>"u"?Im():DD()}async function UD(t,e){const n={...e,flushIntervalMs:e.flushIntervalMs??ID,backend:e.backend??"indexedDB"},r=LD(n),s=new Map,o=await $D(t,r,n.key,s);let c=null,d=!1;const f=new Map,p=async()=>{if(d)return;const L=t.snapshot(),H=uE(L.firestore,L.services,Date.now()),P=new Map,F=new Map;for(const[E,O]of H){const D=pE(O);F.set(E,D),s.get(E)!==D&&P.set(E,O)}const w=[...s.keys()].filter(E=>!H.has(E));P.size>0&&await r.putRecords(n.key,P),w.length>0&&await r.deleteRecords(n.key,w),s.clear();for(const[E,O]of F)s.set(E,O)};let g=Promise.resolve();const b=()=>(c&&(clearTimeout(c),c=null),g=g.then(p,p),g),v=()=>{d||c||(c=setTimeout(()=>{c=null,b().catch(L=>{if(MD(L)){console.warn("[sandbox/persistence] storage quota exceeded; recent changes are kept in memory only. Free storage or reduce sandbox data to persist them.");return}console.warn("[sandbox/persistence] auto-flush failed, will retry:",L),v()})},n.flushIntervalMs))},x=(L,H)=>{if(!H.subscribe||f.has(L))return;const P=H.subscribe(()=>{v()});f.set(L,P)},_=new Map,k=new Map,R=(L,H)=>{if(!n.sessionStorage)return;const{local:P,session:F}=n.sessionStorage,w=Bp(L),E=H.currentUid(),O=H.mode();if(E===null||O==="NONE"){P.removeItem(w),F.removeItem(w);return}const D=JSON.stringify({uid:E});O==="LOCAL"?(F.removeItem(w),P.setItem(w,D)):(P.removeItem(w),F.setItem(w,D))},C=L=>{if(!n.sessionStorage)return null;const H=Bp(L);for(const[P,F]of[["LOCAL",n.sessionStorage.local],["SESSION",n.sessionStorage.session]]){const w=F.getItem(H);if(w)try{const E=JSON.parse(w);if(typeof(E==null?void 0:E.uid)=="string")return{uid:E.uid,mode:P}}catch{F.removeItem(H)}}return null},T=L=>{if(!n.sessionStorage)return;const H=Bp(L);n.sessionStorage.local.removeItem(H),n.sessionStorage.session.removeItem(H)},U=(L,H,P)=>{if(P.session)try{P.session.restore(H.uid,H.mode),k.delete(L)}catch(F){console.warn(`[sandbox/persistence] session restore for uid '${H.uid}' failed — clearing stored session:`,F),T(L),k.delete(L)}},q=(L,H)=>{if(!n.sessionStorage||!H.session||_.has(L))return;const P=H.session;_.set(L,P.subscribe(()=>R(L,P)))},I=(L,H)=>{if(!H.session)return;const P=k.get(L)??C(L);P&&U(L,P,H)};if(t instanceof Zs){for(const[L,H]of t.getServiceRegistry())x(L,H),I(L,H),q(L,H);t.setServiceRegistrationHook((L,H)=>{if(o!==null&&L in o)try{H.restore(o[L])}catch(F){console.warn(`[sandbox/persistence] late-restore for service '${L}' failed:`,F)}const P=C(L);P&&k.set(L,P),I(L,H),x(L,H),q(L,H),v()}),t.setServiceUnregistrationHook(L=>{var H,P;(H=f.get(L))==null||H(),f.delete(L),(P=_.get(L))==null||P(),_.delete(L),k.delete(L),v()})}const N=t.onEvent(L=>{BD(L)&&v()}),M=()=>{b().catch(()=>{})};return typeof window<"u"&&window.addEventListener("beforeunload",M),{options:n,flush:b,async clear(){c&&(clearTimeout(c),c=null),await r.clear(n.key),s.clear()},dispose(){if(!d){d=!0,c&&(clearTimeout(c),c=null),N();for(const L of f.values())L();f.clear();for(const L of _.values())L();_.clear(),t instanceof Zs&&(t.setServiceRegistrationHook(null),t.setServiceUnregistrationHook(null)),typeof window<"u"&&window.removeEventListener("beforeunload",M)}}}}async function $D(t,e,n,r){let s;try{s=await e.listRecords(n)}catch(g){return console.warn("[sandbox/persistence] backend list failed:",g),null}if(s.length===0)return null;const o=[];for(const g of s)try{const b=await e.getRecord(n,g);b!==null&&o.push([g,b])}catch(b){console.warn(`[sandbox/persistence] failed to read persisted record '${g}':`,b)}const c=[],d=[];let f=null;for(const[g,b]of o)if(typeof b=="string"){const v=fE(b);v&&(d.push(g),f=v)}else c.push([g,b]);if(f){try{await e.putRecords(n,f),d.length>0&&await e.deleteRecords(n,d)}catch(g){console.warn("[sandbox/persistence] v2 migration write failed:",g)}for(const[g,b]of f)c.push([g,b])}for(const[g,b]of c)r.set(g,pE(b));const p=RD(c);for(const[g,b]of Object.entries(p.firestore))t.admin.setDocument(g,b);if(t instanceof Zs){const g=t.getServiceRegistry();for(const[b,v]of Object.entries(p.services)){const x=g.get(b);if(x)try{x.restore(v)}catch(_){console.warn(`[sandbox/persistence] service '${b}' restore failed — Firestore state is intact; auth users may need to be re-created:`,_)}}}return p.services}function BD(t){return t.kind==="write"||t.kind==="session_boundary"}function FD(t){return typeof t=="object"&&t!==null&&typeof t.kind=="string"&&typeof t.origin=="string"}let PD=0;function qD(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`tab-${crypto.randomUUID()}`:`tab-${++PD}-${typeof performance<"u"?performance.now().toFixed(3):String(Date.now())}`}function zD(t,e={}){let n,r=!1;if(e.channel)n=e.channel,r=!1;else if(typeof BroadcastChannel<"u")n=new BroadcastChannel("pyric:tabsync"),r=!0;else return()=>{};const s=e.originId??qD();let o=!1,c=!1;const d=t.onEvent(b=>{if(b.kind!=="write"||o)return;const v={kind:"write",origin:s,event:b};n.postMessage(v)}),f=b=>{if(!FD(b.data))return;const v=b.data;if(v.origin!==s){if(v.kind==="write")g(v.event);else if(v.kind==="hello"){const x={kind:"state",origin:s,to:v.origin,snapshot:t.snapshot()};n.postMessage(x)}else if(v.kind==="state"){if(v.to!==s||c)return;if(Object.keys(nn(t).snapshot()).length>0){c=!0;return}o=!0;try{for(const[_,k]of Object.entries(v.snapshot.firestore))t.admin.setDocument(_,k)}finally{o=!1}c=!0}}};n.addEventListener("message",f);const p={kind:"hello",origin:s};return n.postMessage(p),()=>{d(),n.removeEventListener("message",f),r&&n.close()};function g(b){o=!0;try{if(b.method==="delete")t.admin.deleteDocument(b.path);else{const v=b.nextState;v!=null&&t.admin.setDocument(b.path,v)}}finally{o=!1}}}function VD(t,e){var c;const n={...t};n.service=t.service??(e==null?void 0:e.service)??"firestore";const s="detail"in t&&((c=t.detail)==null?void 0:c.admin)===!0&&t.operationContext===void 0&&t.authLens===void 0?{...t,authLens:{mode:"admin"}}:t,o=Tm(n)||t.operationContext!==void 0?Od(e,s):HD(t,e);return n.operationContext=o,n.actor=o.source,n.authLens=o.authLens,o.planId!==void 0&&(n.planId=o.planId),Tm(n)&&(n.rulesDisposition=Object.freeze({...iE(n)})),n}function HD(t,e){var n,r,s,o,c,d,f,p;return Bl({source:t.actor??((n=t.operationContext)==null?void 0:n.source)??(e==null?void 0:e.actor)??((r=e==null?void 0:e.operationContext)==null?void 0:r.source)??{kind:"unattributed"},authLens:t.authLens??((s=t.operationContext)==null?void 0:s.authLens)??(e==null?void 0:e.authLens)??((o=e==null?void 0:e.operationContext)==null?void 0:o.authLens)??{mode:"app-session"},...(t.planId??((c=t.operationContext)==null?void 0:c.planId)??(e==null?void 0:e.planId)??((d=e==null?void 0:e.operationContext)==null?void 0:d.planId))===void 0?{}:{planId:t.planId??((f=t.operationContext)==null?void 0:f.planId)??(e==null?void 0:e.planId)??((p=e==null?void 0:e.operationContext)==null?void 0:p.planId)}})}function GD(t,e){var s,o,c,d;if(!t)return e;if(!e)return t;if(e.operationContext!==void 0)return mE(t,e);if(!(t.operationContext!==void 0||t.actor!==void 0||t.authLens!==void 0||t.planId!==void 0||e.actor!==void 0||e.authLens!==void 0||e.planId!==void 0))return{...t,...e};const r=Bl({source:e.actor??((s=t.operationContext)==null?void 0:s.source)??t.actor??{kind:"unattributed"},authLens:e.authLens??((o=t.operationContext)==null?void 0:o.authLens)??t.authLens??{mode:"app-session"},...(e.planId??((c=t.operationContext)==null?void 0:c.planId)??t.planId)===void 0?{}:{planId:e.planId??((d=t.operationContext)==null?void 0:d.planId)??t.planId}});return{...t,...e,operationContext:r,actor:r.source,authLens:r.authLens,...r.planId===void 0?{}:{planId:r.planId}}}function mE(t,e){if(!t)return e;if(!e)return t;if(!(t.operationContext!==void 0||t.actor!==void 0||t.authLens!==void 0||t.planId!==void 0||e.operationContext!==void 0||e.actor!==void 0||e.authLens!==void 0||e.planId!==void 0))return{...t,...e};const r=Od(t,e);return{...t,...e,operationContext:r,actor:r.source,authLens:r.authLens,...r.planId===void 0?{}:{planId:r.planId}}}let KD=1;function Oi(){const t=(KD++).toString(36),e=Math.random().toString(36).slice(2,7);return`sbe-${t}-${e}`}class Zs{constructor(e){G(this,"_env");G(this,"eventSubs",new Set);G(this,"envUnsubs",[]);G(this,"dispatchedCount",0);G(this,"eventHistory",[]);G(this,"ambientProvenance");G(this,"_currentUser",null);G(this,"currentUserSubs",new Set);G(this,"persistence",null);G(this,"enablePersistencePromise",null);G(this,"serviceRegistry",new Map);G(this,"_onServiceRegistered",null);G(this,"_onServiceUnregistered",null);this._env=e,this.attachToEnv()}static createRoot(){return new Zs(new Fw)}getEnv(){return this._env}withAuth(e){return Rm(e),new so(this,e)}attachToEnv(){this.envUnsubs.push(this._env.onRequest(e=>{this.emitEvent(e)})),this.envUnsubs.push(this._env.onWrite(e=>{this.emitEvent(e)})),this.envUnsubs.push(this._env.onSnapshotDelivery(e=>this.emitEvent(e))),this.envUnsubs.push(this._env.onSnapshotSuppressed(e=>this.emitEvent(e))),this.envUnsubs.push(this._env.onListenerLifecycle(e=>this.emitEvent(e))),this.envUnsubs.push(this._env.onSnapshotError((e,n,r)=>{var o;const s={kind:"listener_errored",id:Oi(),at:Date.now(),listenerId:r,target:n.kind==="doc"?{kind:"doc",path:n.path}:{kind:"query",collection:n.collection},auth:((o=e.request)==null?void 0:o.auth)??null,error:{code:"permission-denied",message:e.message}};this.emitEvent(s)}))}emitEvent(e,n){const r=mE(this.ambientProvenance,n);this.dispatch(VD(e,r))}runWithProvenance(e,n){const r=this.ambientProvenance;this.ambientProvenance=GD(r,e);try{return n()}finally{this.ambientProvenance=r}}dispatch(e){if(this.eventHistory.push(e),this.dispatchedCount++,this.eventSubs.size!==0)for(const n of this.eventSubs)try{const r=n(e);r&&typeof r.then=="function"&&r.catch(()=>{})}catch{}}emitInternal(e,n){this.emitEvent(e,n)}onEvent(e){return this.eventSubs.add(e),()=>{this.eventSubs.delete(e)}}history(){return[...this.eventHistory]}primeEventHistory(e){return this.eventHistory.length>0||e.length===0?0:(this.eventHistory.push(...e),e.length)}get admin(){return{getDocument:e=>this._env.getDocument(e),listDocuments:e=>this._env.listDocuments(e),setDocument:(e,n)=>this._env.adminSetDocument(e,n),deleteDocument:e=>this._env.adminDeleteDocument(e)}}reset(){const e={kind:"session_boundary",id:Oi(),at:Date.now(),phase:"reset",priorOpCount:this.dispatchedCount};this.emitEvent(e),this.eventHistory=[],this._currentUser!==null&&(this._currentUser=null,this.notifyCurrentUserSubs(null));for(const n of this.envUnsubs)n();this.envUnsubs=[],this._env.dispose(),this._env=new Fw,this.attachToEnv()}dispose(){const e={kind:"session_boundary",id:Oi(),at:Date.now(),phase:"dispose",priorOpCount:this.dispatchedCount};this.emitEvent(e);for(const n of this.envUnsubs)n();this.envUnsubs=[],this._env.dispose(),this.persistence&&(this.persistence.dispose(),this.persistence=null),this.serviceRegistry.clear(),this._onServiceRegistered=null,this._onServiceUnregistered=null,this.eventSubs.clear(),this.currentUserSubs.clear()}snapshot(){const e={};for(const[n,r]of this.serviceRegistry)e[n]=r.snapshot();return{firestore:this._env.snapshot(),services:e}}loadSnapshot(e){this.reset();for(const[n,r]of Object.entries(e.firestore))this._env.adminSetDocument(n,r);for(const[n,r]of this.serviceRegistry)if(n in e.services)try{r.restore(e.services[n])}catch(s){console.warn(`[sandbox] loadSnapshot: service '${n}' restore failed — Firestore is intact; that service's state may be incomplete:`,s)}}get currentUser(){return this._currentUser}set currentUser(e){Rm(e),!YD(this._currentUser,e)&&(this._currentUser=e,this.notifyCurrentUserSubs(e))}onCurrentUserChanged(e){return this.currentUserSubs.add(e),()=>{this.currentUserSubs.delete(e)}}notifyCurrentUserSubs(e){if(this._env.reevaluateLiveListeners(e),this.currentUserSubs.size!==0)for(const n of this.currentUserSubs)try{const r=n(e);r&&typeof r.then=="function"&&r.catch(()=>{})}catch{}}async enablePersistence(e){if(this.persistence){if(this.persistence.options.key!==e.key)throw new rt("failed-precondition",`Persistence already enabled with key '${this.persistence.options.key}'; cannot re-enable with key '${e.key}'. Dispose and recreate the sandbox.`);return}if(this.enablePersistencePromise)return this.enablePersistencePromise;this.enablePersistencePromise=(async()=>{const n=await UD(this,e);this.persistence=n})();try{await this.enablePersistencePromise}finally{this.enablePersistencePromise=null}}enableTabSync(e){return zD(this,e)}async flush(){if(!this.persistence)throw new rt("failed-precondition","flush() called before enablePersistence()");await this.persistence.flush()}async clearPersistence(){this.persistence&&await this.persistence.clear()}registerPersistableService(e,n){if(this.serviceRegistry.has(e))throw new rt("failed-precondition",`registerPersistableService: a service named '${e}' is already registered on this sandbox. Each service name must be unique — the auth package registers 'auth' exactly once per sandbox.`);return this.serviceRegistry.set(e,n),this._onServiceRegistered&&this._onServiceRegistered(e,n),()=>{var r;this.serviceRegistry.get(e)===n&&(this.serviceRegistry.delete(e),(r=this._onServiceUnregistered)==null||r.call(this,e))}}setServiceRegistrationHook(e){this._onServiceRegistered=e}setServiceUnregistrationHook(e){this._onServiceUnregistered=e}getServiceRegistry(){return this.serviceRegistry}}function YD(t,e){if(t===e)return!0;if(t===null||e===null||t.uid!==e.uid)return!1;const n=t.token===void 0?void 0:JSON.stringify(t.token),r=e.token===void 0?void 0:JSON.stringify(e.token);return n===r}function nn(t){if(!(t instanceof Zs))throw new rt("invalid-argument","Sandbox handle was not produced by initializeSandbox(); custom Sandbox implementations are not supported.");return t.getEnv()}function Ps(t,e,n){if(!(t instanceof Zs))throw new rt("invalid-argument","Sandbox handle was not produced by initializeSandbox(); custom Sandbox implementations are not supported.");t.emitInternal(e,n)}function Td(t){return{kind:"service_mutation",id:Oi(),at:Date.now(),...t}}function yE(t){const{at:e,...n}=t;return{kind:"operation",id:Oi(),at:e??Date.now(),...n}}function ZD(t){const{at:e,...n}=t;return{kind:"commit",id:Oi(),at:e??Date.now(),...n}}function WD(t){const{at:e,...n}=t;return{kind:"listener",id:Oi(),at:e??Date.now(),...n}}const JD=Symbol.for("pyric.remote.sandbox");function Hy(t){return t!=null&&t[JD]===!0}function gE(t,e=""){const n=vE();return nn(n).seed({rules:e,baseDocuments:t.firestore}),{sandbox:n,rules:e,base:t,events:[],discarded:!1}}function QD(t,e){XD(t);const n=nn(t.sandbox).snapshot(),r=eI(e);return nI(r,n)}function bE(t){t.discarded||(t.discarded=!0,t.sandbox.dispose())}function XD(t){if(t.discarded)throw new Error("Branch has been discarded or promoted; create a new fork.")}function eI(t){return tI(t)?nn(t).snapshot():t.firestore}function tI(t){return typeof t.snapshot=="function"}function nI(t,e){const n=[],r=new Set([...Object.keys(t),...Object.keys(e)]);for(const s of r){const o=t[s],c=e[s];if(o===void 0&&c!==void 0){n.push({kind:"real-divergence",path:s,before:void 0,after:c});continue}if(o!==void 0&&c===void 0){n.push({kind:"real-divergence",path:s,before:o,after:void 0});continue}o===void 0||c===void 0||rI(s,o,c,n)}return n}function rI(t,e,n,r){s(e,n,"");function s(o,c,d){if(o===c)return;const f=o!==null&&typeof o=="object"&&!Array.isArray(o),p=c!==null&&typeof c=="object"&&!Array.isArray(c);if(f&&p){const g=o,b=c,v=new Set([...Object.keys(g),...Object.keys(b)]);for(const x of v){const _=d?`${d}.${x}`:x;s(g[x],b[x],_)}return}if(Array.isArray(o)&&Array.isArray(c)){const g=Math.max(o.length,c.length);for(let b=0;b<g;b++)s(o[b],c[b],`${d}[${b}]`);return}Mm(o,c)||r.push({kind:"real-divergence",path:t,field:d||void 0,before:o,after:c})}}function Mm(t,e){if(t===e)return!0;if(t===null||e===null||typeof t!="object"||typeof e!="object")return!1;const n=Array.isArray(t),r=Array.isArray(e);if(n!==r)return!1;if(n&&r){if(t.length!==e.length)return!1;for(let f=0;f<t.length;f++)if(!Mm(t[f],e[f]))return!1;return!0}const s=t,o=e,c=Object.keys(s),d=Object.keys(o);if(c.length!==d.length)return!1;for(const f of c)if(!Object.prototype.hasOwnProperty.call(o,f)||!Mm(s[f],o[f]))return!1;return!0}function vE(t={}){return Zs.createRoot()}function il(t,e){return`${t.replace(/\/$/,"")}${e}`}function sI(t){const e=t;return{async read(n){const r=await fetch(il(e,`/__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(il(e,`/__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(il(e,`/__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(il(e,`/__pyric/workspace?path=${encodeURIComponent(n)}`),{method:"DELETE"});if(!r.ok)throw new Error(`workspace.remove(${n}) → ${r.status}`)},watch(n){const r=new EventSource(il(e,"/__pyric/workspace/watch")),s=o=>{try{n(JSON.parse(o.data))}catch{}};return r.addEventListener("change",s),()=>{r.removeEventListener("change",s),r.close()}}}}function al(t,e){return`${t.replace(/\/$/,"")}${e}`}function iI(t){const e=t;return{async list(){const n=await fetch(al(e,"/__pyric/projects"));if(!n.ok)throw new Error(`projects.list() → ${n.status}`);return await n.json()},async open(n){const r=await fetch(al(e,`/__pyric/projects/${encodeURIComponent(n)}`));if(!r.ok)throw new Error(`projects.open(${n}) → ${r.status}`);return{meta:await r.json(),workspace:sI(e)}},async create(n){const r=await fetch(al(e,"/__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(al(e,`/__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(al(e,`/__pyric/projects/${encodeURIComponent(n)}`),{method:"DELETE"});if(!r.ok)throw new Error(`projects.remove(${n}) → ${r.status}`)}}}function aI(t,e){return`${t.replace(/\/$/,"")}${e}`}function Fp(t){return/auth/i.test(t)?"auth":"firestore"}function oI(t){const e=t,r={"content-type":"application/json","x-pyric-writer":`studio-${Math.random().toString(36).slice(2)}`},s=new Map,o=f=>aI(e,`/__pyric/state?section=${Fp(f)}`),c=async f=>{const p=Fp(f),g=s.get(p);if(g)return g;const b=await fetch(o(f));let v=new Map;if(b.ok){const x=await b.text();x&&x!=="null"&&(v=TD(x))}else if(b.status!==404)throw new Error(`persistence.read(${f}) → ${b.status}`);return s.set(p,v),v},d=async(f,p)=>{const g=await fetch(o(f),{method:"POST",headers:r,body:OD(p)});if(g.status===423)throw new Error("persistence.write blocked, another tab holds the persist writer lock");if(!g.ok)throw new Error(`persistence.write(${f}) → ${g.status}`)};return{async getRecord(f,p){return(await c(f)).get(p)??null},async listRecords(f){return[...(await c(f)).keys()]},async putRecords(f,p){const g=await c(f);for(const[b,v]of p)g.set(b,v);await d(f,g)},async deleteRecords(f,p){const g=await c(f);for(const b of p)g.delete(b);await d(f,g)},async clear(f){s.set(Fp(f),new Map);const p=await fetch(o(f),{method:"POST",headers:r,body:"null"});if(!p.ok&&p.status!==423)throw new Error(`persistence.clear(${f}) → ${p.status}`)}}}const lI="local";function cI(){const t=new Map,e=new Set,n=r=>{for(const s of e)s(r)};return{async read(r){return t.has(r)?t.get(r):null},async write(r,s){const o=t.has(r)?"update":"create";t.set(r,s),n({path:r,type:o})},async list(r){const s=r?`${r.replace(/\/+$/,"")}/`:"",o=[];for(const c of t.keys())s&&!c.startsWith(s)||o.push({path:c,kind:"file"});return o},async remove(r){t.delete(r)&&n({path:r,type:"delete"})},watch(r){return e.add(r),()=>e.delete(r)}}}function uI(){const t=cI();let e={id:lI,title:"Local Project",createdAt:Date.now(),updatedAt:Date.now()};return{async list(){return[e]},async open(n){if(n!==e.id)throw new Error(`Static Studio runs in single-project mode — no project '${n}'.`);return{meta:e,workspace:t}},async create(){throw new Error("Static Studio runs in single-project mode — creating additional projects is not supported.")},async update(n,r){n===e.id&&(e={...e,...r,updatedAt:Date.now()})},async remove(){}}}class Vi extends Error{constructor(n,r,s){super(r);G(this,"code");G(this,"customData");G(this,"name","FirebaseError");this.code=n,this.customData=s,Object.setPrototypeOf(this,new.target.prototype)}}Object.defineProperty(Vi,"name",{value:"FirebaseError"});let qa;function dI(t){qa=t}function Gy(t){return qa==null?void 0:qa.resolve(t,!1)}function xE(){if(!qa)throw new TypeError("No default sandbox app registry is installed - import and initialize pyric/app before calling a service factory without an app.");return qa.defaultApp()}function fI(){let t=null;const e=new Set;return{get currentUser(){return t},set currentUser(n){if(t!==n){t=n;for(const r of[...e])r(n)}},onCurrentUserChanged(n){return e.add(n),()=>e.delete(n)}}}const wE=new WeakMap;let Lm;function hI(t,e,n=fI()){const r=t.name,s=n===e?void 0:{},o=new Map,c=new Set,d={app:t,sandbox:e,session:n,services:o,cleanups:c,assertAlive(){if(d.deleted)throw new Vi("app/app-deleted",`Firebase: Firebase App named '${r}' already deleted (app/app-deleted).`)},...s?{authScope:s}:{},service(f,p){const g=o.get(f);if(g!==void 0)return g;d.assertAlive();const b=p();return o.set(f,b),b},onDelete(f){return d.deleted?(f(),()=>{}):(c.add(f),()=>c.delete(f))},deleted:!1};return wE.set(t,d),d}function pI(t){Lm=t}dI({resolve(t,e){const n=typeof t=="object"&&t!==null?wE.get(t):void 0;if(n)return n},defaultApp(){if(!Lm)throw new TypeError("No default sandbox app registry is installed - import and initialize pyric/app before calling a service factory without an app.");return Lm()}});const mI="[DEFAULT]",yI=new Map;function gI(t,e){return new Vi(`app/${t}`,`Firebase: ${e} (app/${t}).`)}function bI(t){return gI("no-app",`No Firebase App '${t}' has been created - call initializeApp() first`)}function vI(t=mI){const e=yI.get(t);if(!e)throw bI(t);return e.app}pI(vI);let xI=0,wI=0;function Ae(){return`op-${++xI}`}function io(){return`sub-${++wI}`}const Um=new Map,Ky=new Map,Yy=new Map,Pl=new WeakSet;function SI(){return Object.assign(new Error("Firebase App was deleted"),{code:"app/app-deleted"})}function ql(t,e,n,r){return Pl.has(t)?!1:(Ky.set(e,n),t.postMessage(r),!0)}function _I(t,e,n,r){return Pl.has(t)?!1:(Yy.set(e,{port:t,next:n}),t.postMessage(r),!0)}function zl(t,e){Ky.delete(e),Yy.delete(e),Pl.has(t)||t.postMessage({t:"unsub",subId:e})}function Zy(t){t.onmessage=e=>{const n=e.data;if(n.t==="res"){const r=Um.get(n.id);if(!r)return;if(Um.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),r.reject(s)}}else if(n.t==="snap"){const r=Ky.get(n.subId);if(!r)return;const s=n.value??{};if(s.__error){const o=s.__error,c=new Error(o.message);c.code=o.code,o.denialContext!==void 0&&(c.denialContext=o.denialContext),o.aiEnvelope!==void 0&&(c.aiEnvelope=o.aiEnvelope),r.error?r.error(c):console.error("pyric/firestore: Uncaught Error in snapshot listener:",c);return}r.next(n.value)}else if(n.t==="event"){const r=Yy.get(n.subId);r&&r.next(n.events)}}}let Ja;function Hw(t){Ja=t&&t.mode==="app-session"?void 0:t}function EI(){return Ja}let $m;function AI(t){$m=t}function Wy(t){return $m&&(t.t==="op"||t.t==="sub")?{...t,issuer:$m}:t}function SE(t,e){return Pl.has(t)?Promise.reject(SI()):new Promise((n,r)=>{const s=e;Um.set(s.id,{port:t,resolve:n,reject:r}),t.postMessage(e)})}function Ze(t,e){return SE(t,Wy(e))}function tr(t,e){if(Pl.has(t)&&!e.method.startsWith("rtdb."))return Promise.reject(new Vi("failed-precondition","The client has already been terminated."));const n=Ja?{...e,actAs:Ja}:e;return Ze(t,n)}function jI(t,e){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(t,{type:"classic",name:"pyric-shared-worker"}).port;return r.start(),Zy(r),{__kind:"client-db",port:r}}async function kI(t){return(await Ze(t.port,{t:"op",id:Ae(),method:"getVersion"})).instanceId??""}async function CI(t){return(await Ze(t.port,{t:"op",id:Ae(),method:"exportState"})).bundle}async function NI(t,e){await Ze(t.port,{t:"op",id:Ae(),method:"importState",bundle:e})}async function OI(t,e){await Ze(t.port,{t:"op",id:Ae(),method:"saveBranch",name:e})}async function TI(t){return(await Ze(t.port,{t:"op",id:Ae(),method:"listBranches"})).branches??[]}async function RI(t,e){await Ze(t.port,{t:"op",id:Ae(),method:"switchBranch",name:e})}async function DI(t,e){await Ze(t.port,{t:"op",id:Ae(),method:"deleteBranch",name:e})}async function II(t,e,n){return await Ze(t.port,{t:"tool",id:Ae(),name:e,args:n})}function MI(t,e){return SE(t.port,{...e,t:"op",id:Ae()})}function LI(t,e,n){if(e.target==="events")throw new Error("event-stream subscriptions cannot be relayed over the bridge yet (needs bounded backpressure — slice 2)");const r=io();return ql(t.port,r,{port:t.port,next:n,error:o=>n({__error:{code:o.code??"unknown",message:o instanceof Error?o.message:String(o)}})},{...e,t:"sub",subId:r})||queueMicrotask(()=>n({__error:{code:"app/app-deleted",message:"Firebase App was deleted"}})),()=>{zl(t.port,r)}}function Jy(t){return t.split("/").at(-1)??t}function UI(t,...e){const n=("port"in t,t.port);let r;if(t.__kind==="client-db"){if(e.length===0)throw new TypeError("doc(db, path) requires a path segment.");r=e.join("/")}else{const o=t.descriptor.path;r=e.length>0?`${o}/${e.join("/")}`:o}return{__kind:"doc-ref",descriptor:{__ref:"doc",path:r},port:n,id:Jy(r),path:r}}function $I(t,...e){const n=t.port;if(e.length===0)throw new TypeError("collection() requires a path segment.");let r;return t.__kind==="client-db"?r=e.join("/"):r=`${t.descriptor.path}/${e.join("/")}`,{__kind:"coll-ref",descriptor:{__ref:"collection",path:r},port:n,id:Jy(r),path:r}}function BI(t){return{_descriptor:{kind:"limit",n:t}}}function FI(...t){return{_descriptor:{kind:"startAfter",values:t}}}function PI(t,...e){const n=(t.__kind==="coll-ref",t.descriptor),r=t.__kind==="query"?t.descriptor.constraints:[];return{__kind:"query",descriptor:{__ref:"query",source:n.__ref==="query"?n.source:n,constraints:[...r,...e.map(o=>o._descriptor)]},port:t.port}}function qI(t){return Za(JSON.parse(t.json))}const _E=8*1024*1024;function zI(t,e){const n=new Error(`${e} is ${t} bytes — over the ${_E/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 VI(t){let e="";for(let r=0;r<t.length;r+=32768){const s=t.subarray(r,r+32768);e+=String.fromCharCode.apply(null,s)}return btoa(e)}function HI(t){return qI(t)}function Qy(t,e){const n=t.exists&&t.data?HI(t.data):void 0,r=t.path??t.id,s={__kind:"doc-ref",descriptor:{__ref:"doc",path:r},port:e,id:t.id,path:r};return{id:t.id,path:r,ref:s,exists:()=>t.exists,data:()=>n}}function EE(t,e){const n=t.docs.map(r=>Qy(r,e));return{size:n.length,empty:n.length===0,docs:n}}async function GI(t){const e=await tr(t.port,{t:"op",id:Ae(),method:"getDoc",path:t.descriptor.path});return Qy(e,t.port)}async function KI(t){const e=await tr(t.port,{t:"op",id:Ae(),method:"getDocs",source:(t.__kind==="coll-ref",t.descriptor)});return EE(e,t.port)}async function YI(t){return(await tr(t.port,{t:"op",id:Ae(),method:"listRootCollections"})).ids}async function ZI(t,e){return(await tr(t.port,{t:"op",id:Ae(),method:"listSubcollections",docPath:e})).ids}function WI(t,e,n){const r=io(),s=t.port,o={port:s,service:"firestore",next:f=>{const p=f;"docs"in p?e(EE(p,s)):e(Qy(p,s))},error:n},c=(t.__kind==="doc-ref"||t.__kind==="coll-ref",t.descriptor);return!ql(s,r,o,Wy(Ja?{t:"sub",subId:r,target:c,actAs:Ja}:{t:"sub",subId:r,target:c}))&&n&&queueMicrotask(()=>n(new Error("Firebase App was deleted"))),()=>{zl(s,r)}}async function JI(t,e,n){await tr(t.port,{t:"op",id:Ae(),method:"setDoc",path:t.descriptor.path,data:e,options:n})}async function QI(t){await tr(t.port,{t:"op",id:Ae(),method:"deleteDoc",path:t.descriptor.path})}async function XI(t,e){const n=await tr(t.port,{t:"op",id:Ae(),method:"addDoc",collectionPath:t.descriptor.path,data:e});return{__kind:"doc-ref",descriptor:{__ref:"doc",path:n.path},port:t.port,id:n.id,path:n.path}}async function eM(t,e){return await Ze(t.port,{t:"op",id:Ae(),method:"admin.listDocuments",path:e})}function tM(t){const e=(t??"/").split("/").filter(Boolean).join("/");return e?`/${e}`:"/"}new Array(12).fill(0);async function nM(t){return Ze(t.port,{t:"op",id:Ae(),method:"rtdb.adminSnapshot"})}async function rM(t,e,n){await Ze(t.port,{t:"op",id:Ae(),method:"rtdb.set",path:e,value:n,actAs:{mode:"admin"}})}async function sM(t,e,n){await Ze(t.port,{t:"op",id:Ae(),method:"rtdb.update",path:e,values:n,actAs:{mode:"admin"}})}async function iM(t,e){await Ze(t.port,{t:"op",id:Ae(),method:"rtdb.remove",path:e,actAs:{mode:"admin"}})}function aM(t,e,n,r){const s=io();return!ql(t.port,s,{port:t.port,next:c=>n((c==null?void 0:c.value)??null),error:r},Wy({t:"sub",subId:s,target:{service:"rtdb",path:tM(e)},actAs:{mode:"admin"}}))&&r&&queueMicrotask(()=>r(new Error("FIREBASE FATAL ERROR: Database has been deleted."))),()=>{zl(t.port,s)}}function oM(t,e){const n=io(),r=t.port;return _I(r,n,e,{t:"sub",subId:n,target:"events"}),()=>{zl(r,n)}}async function lM(t){return await Ze(t.port,{t:"op",id:Ae(),method:"getSnapshot"})}const cM=15e3;function uM(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`page-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function Gw(){return typeof location>"u"?"/":`${location.pathname}${location.search}${location.hash}`}function Kw(){return typeof document>"u"?"visible":document.visibilityState==="hidden"?"hidden":"visible"}function dM(t){const{db:e,kind:n}=t,r=t.clientId??uM(),s=t.heartbeatIntervalMs??cM;let o=!1,c=null;const d=()=>{Ze(e.port,{t:"op",id:Ae(),method:"presence.register",clientId:r,kind:n,route:Gw(),visibility:Kw()}).catch(()=>{})},f=()=>{Ze(e.port,{t:"op",id:Ae(),method:"presence.heartbeat",clientId:r}).catch(()=>{})},p=()=>{Ze(e.port,{t:"op",id:Ae(),method:"presence.update",clientId:r,route:Gw(),visibility:Kw()}).catch(()=>{})},g=()=>{Ze(e.port,{t:"op",id:Ae(),method:"presence.disconnect",clientId:r}).catch(()=>{})};d(),typeof document<"u"&&document.addEventListener("visibilitychange",p),typeof window<"u"&&(window.addEventListener("popstate",p),window.addEventListener("hashchange",p),window.addEventListener("pagehide",b),c=setInterval(()=>{o||f()},s));function b(){v()}function v(){o||(o=!0,c!=null&&(clearInterval(c),c=null),typeof document<"u"&&document.removeEventListener("visibilitychange",p),typeof window<"u"&&(window.removeEventListener("popstate",p),window.removeEventListener("hashchange",p),window.removeEventListener("pagehide",b)),g())}return{clientId:r,kind:n,stop:v}}function fM(t,e){const n=io();return ql(t.port,n,{port:t.port,next:r=>{e(r)}},{t:"sub",subId:n,target:"presence"}),()=>{zl(t.port,n)}}const hM=Symbol("pyric.clientUser.port");function pM(t,e){const n={uid:e.uid,email:e.email,emailVerified:e.emailVerified,displayName:e.displayName,photoURL:e.photoURL,phoneNumber:e.phoneNumber,isAnonymous:e.isAnonymous,providerId:e.providerId,providerData:e.providerData,async getIdToken(r){return await Ze(t,{t:"op",id:Ae(),method:"auth.getIdToken",forceRefresh:r})},async getIdTokenResult(r){return await Ze(t,{t:"op",id:Ae(),method:"auth.getIdTokenResult",forceRefresh:r})}};return Object.defineProperty(n,hM,{value:t,enumerable:!1}),n}function mM(t,e){return e?pM(t,e):null}function yM(t,e){let n;if(typeof t=="object"&&"__kind"in t&&t.__kind==="client-db")n=t.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(t,{type:"classic",name:"pyric-shared-worker"}).port,n.start(),Zy(n)}const r={__kind:"client-auth",port:n,currentUser:null},s=io();return ql(n,s,{port:n,next:o=>{r.currentUser=mM(n,o)}},{t:"sub",subId:s,target:"authState"}),r}async function gM(t){return await Ze(t.port,{t:"op",id:Ae(),method:"auth.listUsers"})}async function bM(t,e){return await Ze(t.port,{t:"op",id:Ae(),method:"auth.adminCreateUser",request:e})}async function vM(t,e,n){return await Ze(t.port,{t:"op",id:Ae(),method:"auth.adminUpdateUser",uid:e,request:n})}async function xM(t,e){await Ze(t.port,{t:"op",id:Ae(),method:"auth.adminDeleteUser",uid:e})}async function wM(t){await Ze(t.port,{t:"op",id:Ae(),method:"auth.adminClearUsers"})}async function SM(t){return await Ze(t.port,{t:"op",id:Ae(),method:"auth.getProviderConfig"})}async function _M(t,e,n){await Ze(t.port,{t:"op",id:Ae(),method:"auth.setProviderConfig",providerId:e,enabled:n})}function EM(t){return t.replace(/^\/+|\/+$/g,"")}function AM(t,e){let n;if(typeof t=="object"&&"__kind"in t&&t.__kind==="client-db")n=t.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.");n=new SharedWorker(t,{type:"classic",name:"pyric-shared-worker"}).port,n.start(),Zy(n)}return{__kind:"client-storage",port:n}}function jM(t,e){const n=EM(e??"");let r;if(t.__kind==="client-storage")r=n;else{const s=t.fullPath;r=n?s?`${s}/${n}`:n:s}return{__kind:"storage-ref",port:t.port,fullPath:r,name:Jy(r)}}async function kM(t){const e=await tr(t.port,{t:"op",id:Ae(),method:"storage.listAll",path:t.fullPath}),n=r=>({__kind:"storage-ref",port:t.port,fullPath:r.fullPath,name:r.name});return{items:e.items.map(n),prefixes:e.prefixes.map(n)}}async function CM(t){return await tr(t.port,{t:"op",id:Ae(),method:"storage.getMetadata",path:t.fullPath})}async function NM(t){return await tr(t.port,{t:"op",id:Ae(),method:"storage.getBlob",path:t.fullPath})}async function OM(t,e,n){const r=e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof ArrayBuffer?new Uint8Array(e):e;if(r.byteLength>_E)throw zI(r.byteLength,`uploadBytes payload for '${t.fullPath}'`);const s=(n==null?void 0:n.contentType)??(e instanceof Blob&&e.type?e.type:void 0),o=await tr(t.port,{t:"op",id:Ae(),method:"storage.putBytes",path:t.fullPath,dataB64:VI(r),...s!==void 0?{contentType:s}:{},...n!==void 0?{metadata:n}:{}});return{ref:t,metadata:o}}async function TM(t){await tr(t.port,{t:"op",id:Ae(),method:"storage.deleteObject",path:t.fullPath})}const RM="/__pyric/sdk/worker.js";function DM(t){let e=[],n=!1;const r=new Set;let s=null;function o(){s||(s=oM(t,c=>{!n?(n=!0,e=c):e=[...e,...c];for(const f of c)for(const p of r)p(f)}))}return{history:()=>e,subscribe:c=>(r.add(c),o(),()=>{r.delete(c),r.size===0&&s&&(s(),s=null,n=!1,e=[])})}}function IM(t=RM){if(typeof SharedWorker>"u")return null;AI("studio");let e;try{e=jI(t)}catch{return null}Hw({mode:"admin"});const n=dM({db:e,kind:"studio"}),r=DM(e),s=yM(e);return{db:e,presenceClientId:n.clientId,subscribePresence:o=>fM(e,o),instanceId:()=>kI(e),exportState:()=>CI(e),importState:o=>NI(e,o),saveBranch:o=>OI(e,o),listBranches:()=>TI(e),switchBranch:o=>RI(e,o),deleteBranch:o=>DI(e,o),feed:r,setLens:o=>Hw(o),getLens:()=>EI(),listRootCollections:()=>YI(e),listSubcollections:o=>ZI(e,o),listDocuments:async o=>(await eM(e,o)).map(({path:c,phantom:d})=>({path:c,phantom:d})),readRtdbState:()=>nM(e),setRtdbValue:(o,c)=>rM(e,o,c),updateRtdbValue:(o,c)=>sM(e,o,c),deleteRtdbValue:o=>iM(e,o),subscribeRtdbValue:(o,c,d)=>aM(e,o,c,d),firestoreApi:{collection:$I,doc:UI,getDoc:GI,getDocs:KI,onSnapshot:WI,setDoc:JI,deleteDoc:QI,addDoc:XI,query:PI,limit:BI,startAfter:FI},auth:s,authApi:{listUsers:()=>gM(s),subscribeUsers:(o,c)=>r.subscribe(d=>{d.kind==="service_mutation"&&d.service==="auth"&&c()}),createUser:(o,c)=>bM(s,c),updateUser:(o,c,d)=>vM(s,c,d),deleteUser:(o,c)=>xM(s,c),clearUsers:()=>wM(s),getAuthProviderConfig:()=>SM(s),setAuthProviderConfig:(o,c,d)=>_M(s,c,d),subscribeAuthProviderConfig:(o,c)=>r.subscribe(d=>{d.kind==="service_mutation"&&d.op==="provider_config_update"&&c()})},storage:AM(e),storageApi:{ref:jM,listAll:kM,getMetadata:CM,getBlob:NM,uploadBytes:OM,deleteObject:TM},getSnapshot:()=>lM(e)}}const Yw=5174,Zw="/sandbox",MM=4001,LM="worker-relay";function UM(t){if(t===null||typeof t!="object")return!1;const e=t.type;return e==="hello"||e==="hello-ack"||e==="attach"||e==="attach-ack"||e==="tool-call"||e==="tool-result"||e==="worker-op"||e==="worker-res"||e==="worker-sub"||e==="worker-unsub"||e==="worker-snap"||e==="ping"||e==="pong"}function Bm(t){var e;if(t===null||typeof t!="object")return null;if(typeof Blob<"u"&&t instanceof Blob)return"Blob";if(t instanceof ArrayBuffer)return"ArrayBuffer";if(ArrayBuffer.isView(t))return((e=t.constructor)==null?void 0:e.name)??"TypedArray";if(Array.isArray(t)){for(const n of t){const r=Bm(n);if(r)return r}return null}for(const n of Object.values(t)){const r=Bm(n);if(r)return r}return null}function Ww(t,e){const n=Bm(e);if(!n)return;const r=new Error(`worker ${t} produced a binary payload (${n}) that cannot cross the JSON bridge relay — it would be silently corrupted by JSON.stringify. Use the base64 storage ops instead ('storage.getBytes' / 'storage.putBytes'), which carry bytes as JSON-safe 'dataB64' strings; 'storage.getBlob' is MessagePort-only.`);throw r.code="invalid-argument",r}const $M=()=>{throw new Error("pyric dev: fs is not available in the browser")},Jw=$M,Fm=(...t)=>t.join("/"),BM=t=>t.split("/").slice(0,-1).join("/")||"/",FM=t=>String(t).replace("file://",""),PM=BM(FM(import.meta.url)),qM=Fm(PM,"stdlib"),zM={readRelative(t,e){try{return Jw(Fm(t,`${e}.rules`),"utf-8")}catch{return null}},readStdlib(t){try{return Jw(Fm(qM,`${t}.rules`),"utf-8")}catch{return null}}};function VM(t,e){return g2(zM,t,e)}function HM(t){const{resolveSandbox:e,resolveModulesFn:n}=t;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:o}=r;let c=s;if(c.includes("'2+modules'")||c.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 p=n(c);if(!p.success)return{ok:!1,summary:`Module resolve failed: ${p.error.message}`,data:p};c=p.data.resolved}const f=(await e()).seed({rules:c,documents:o??{}});return{ok:!0,summary:`Seeded sandbox with ${Object.keys(o??{}).length} document(s)`,data:{lint:f,documentCount:Object.keys(o??{}).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:o,auth:c,data:d}=r,p=(await e()).execute({method:s,path:o,auth:c,data:d});return{ok:p.allowed,summary:p.allowed?`${s} on ${o} allowed`:`${s} on ${o} denied`,data:{allowed:p.allowed,debugMessages:p.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:o,auth:c,evaluateRules:d}=r,f=await e();if(d){const p=f.execute({method:o??"get",path:s,auth:c??null});return{ok:p.allowed,summary:p.allowed?`${o??"get"} on ${s} allowed`:`${o??"get"} on ${s} denied`,data:{allowed:p.allowed,document:p.data,debugMessages:p.debugMessages}}}return o==="list"?{ok:!0,summary:`Listed ${s}`,data:{documents:f.listDocuments(s)}}:{ok:!0,summary:`Read ${s}`,data:{document:f.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:o}=r,d=(await e()).batch(s,o);return{ok:d.allowed,summary:d.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:d.allowed,results:d.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:o,data:c}=r,d=await e(),{path:f,result:p}=d.createWithAutoId(s,c,o);return{ok:p.allowed,summary:p.allowed?`Created ${f}`:`Create at ${f} denied by rules (as ${o?o.uid:"unauthenticated"}). To SEED data, use the admin data tool firestore_add_document; to test rules, pass an auth the rules permit.`,data:{path:f,allowed:p.allowed,debugMessages:p.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 e()).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(){var o,c;const s=(await e()).redo();return s?{ok:s.allowed,summary:s.allowed?`Redid ${((o=s.event)==null?void 0:o.method)??"op"} on ${((c=s.event)==null?void 0:c.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 e()).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:o,includeReads:c,reads:d,writes:f}=r;for(let b=0;b<f.length;b+=1){const v=f[b];if(v.method==="delete"&&v.data!==void 0)return{ok:!1,summary:`writes[${b}]: 'delete' must not include 'data'`,data:{code:"INVALID_INPUT"}};if(v.method!=="delete"&&v.data===void 0)return{ok:!1,summary:`writes[${b}]: '${v.method}' requires 'data'`,data:{code:"INVALID_INPUT"}}}const p=await e(),g=c===!0;try{const b=p.transaction(x=>{const _={};for(const[k,R]of Object.entries(d)){const T=x.get(R).data();_[k]=T===void 0?null:T}for(let k=0;k<f.length;k+=1){const R=f[k];if(R.method==="delete"){x.delete(R.path);continue}const C=c2(R.data,{reads:_});if(C===null||typeof C!="object"||Array.isArray(C))throw new td(`writes[${k}].data resolved to a non-object`,`writes.${k}.data`);const T=C;switch(R.method){case"create":x.create(R.path,T);break;case"update":x.update(R.path,T);break;case"set":x.set(R.path,T);break}}},{auth:s,readOnly:o}),v={allowed:b.allowed,writes:b.writes.map(x=>{const _={path:x.path,method:x.method,allowed:x.allowed};return x.error&&(_.error={code:x.error.code,message:x.error.message}),g&&(_.debugMessages=x.debugMessages),_})};return b.error&&(v.error={code:b.error.code,message:b.error.message}),b.readOnlyViolation&&(v.readOnlyViolation=!0),g&&(v.reads=b.reads.map(x=>({path:x.path,data:x.data}))),{ok:b.allowed,summary:b.allowed?`Transaction committed (${f.length} write(s))`:"Transaction rolled back",data:v}}catch(b){if(b instanceof td||b instanceof jt||b instanceof vr||b instanceof Dn)return{ok:!1,summary:`Transaction failed: ${b.message}`,data:{allowed:!1,writes:[],error:{code:"invalid-argument",message:b.message}}};throw b}}}]}function AE(t){return HM({resolveSandbox:t.resolveSandbox,resolveModulesFn:VM})}function Ol(t){return t.replace(/^\/+|\/+$/g,"").split("/")}function jE(t){return Ol(t).length%2===0&&Ol(t).length>0}function Xy(t){return Ol(t).length%2===1}function Rd(t){const e=Ol(t);return e[e.length-1]??""}function kE(t){return Ol(t).slice(0,-1).join("/")}function GM(t,e){const n=e!==void 0,r=n?ro(e):void 0;return{id:t.id,ref:t,exists:n,data:()=>n?r:void 0}}function Ra(t,e){if(t.error)throw new tn(t.error);const n=t.debugMessages.length>0?t.debugMessages.join("; "):"(no debug message)";throw new tn(Pe("permission-denied",`${e}: ${n}`))}class eg{constructor(e,n,r,s=!1){G(this,"env");G(this,"auth");G(this,"bypassRules");G(this,"id");G(this,"path");this.env=e,this.auth=n,this.bypassRules=s,this.path=r,this.id=Rd(r)}get parent(){return new zm(this.env,this.auth,kE(this.path),this.bypassRules)}collection(e){return new zm(this.env,this.auth,`${this.path}/${e}`,this.bypassRules)}async get(e){const n=this.env.execute({method:"get",path:this.path,auth:(e==null?void 0:e.auth)!==void 0?e.auth:this.auth,bypassRules:this.bypassRules});n.allowed||Ra(n,"get denied");const r=n.data===void 0||n.data===null?void 0:n.data;return GM(this,r)}async set(e,n){const r=(n==null?void 0:n.auth)!==void 0?n.auth:this.auth;if((n==null?void 0:n.mergeFields)!==void 0){const o=n.mergeFields.map(p=>String(p)),d=this.env.getDocument(this.path)===null?"create":"update",f=this.env.execute({method:d,path:this.path,data:e,auth:r,merge:{mergeFields:o},bypassRules:this.bypassRules});f.allowed||Ra(f,`set denied (as ${d})`);return}if((n==null?void 0:n.merge)===!0){const c=this.env.getDocument(this.path)===null?"create":"update",d=this.env.execute({method:c,path:this.path,data:e,auth:r,merge:!0,bypassRules:this.bypassRules});d.allowed||Ra(d,`set denied (as ${c})`);return}const s=this.env.execute({method:"set",path:this.path,data:e,auth:r,bypassRules:this.bypassRules});s.allowed||Ra(s,"set denied")}async update(e,n){const r=this.env.execute({method:"update",path:this.path,data:e,auth:(n==null?void 0:n.auth)!==void 0?n.auth:this.auth,bypassRules:this.bypassRules});r.allowed||Ra(r,"update denied")}async delete(e){const n=this.env.execute({method:"delete",path:this.path,auth:(e==null?void 0:e.auth)!==void 0?e.auth:this.auth,bypassRules:this.bypassRules});n.allowed||Ra(n,"delete denied")}}function KM(t){return typeof t.seconds=="number"&&(typeof t.nanos=="number"||typeof t.nanoseconds=="number")}function YM(t){return typeof t.latitude=="number"&&typeof t.longitude=="number"}function ZM(t){return t.data instanceof Uint8Array}function WM(t){return typeof t.path=="string"}function od(t){if(t==null)return 0;const e=typeof t;if(e==="boolean")return 1;if(e==="number"||e==="bigint")return 2;if(e==="string")return 4;if(Array.isArray(t))return 8;if(e==="object"){const n=t;return KM(n)?3:ZM(n)?5:YM(n)?7:WM(n)?6:9}return 9}function Qw(t){const e=typeof t.nanos=="number"?t.nanos:t.nanoseconds??0;return[t.seconds,e]}function JM(t,e){const n=Number.isNaN(t),r=Number.isNaN(e);return n&&r?0:n?-1:r?1:t<e?-1:t>e?1:0}function Xw(t,e){return t<e?-1:t>e?1:0}function Ws(t,e){const n=od(t),r=od(e);if(n!==r)return n<r?-1:1;switch(n){case 0:return 0;case 1:return t===e?0:t?1:-1;case 2:return JM(Number(t),Number(e));case 3:{const[s,o]=Qw(t),[c,d]=Qw(e);return s!==c?s<c?-1:1:o<d?-1:o>d?1:0}case 4:return Xw(t,e);case 5:{const s=t.data,o=e.data,c=Math.min(s.length,o.length);for(let d=0;d<c;d++)if(s[d]!==o[d])return s[d]<o[d]?-1:1;return s.length<o.length?-1:s.length>o.length?1:0}case 6:return Xw(t.path,e.path);case 7:{const s=t,o=e;return s.latitude!==o.latitude?s.latitude<o.latitude?-1:1:s.longitude<o.longitude?-1:s.longitude>o.longitude?1:0}case 8:{const s=t,o=e,c=Math.min(s.length,o.length);for(let d=0;d<c;d++){const f=Ws(s[d],o[d]);if(f!==0)return f}return s.length<o.length?-1:s.length>o.length?1:0}case 9:{const s=t,o=e,c=Object.keys(s).sort(),d=Object.keys(o).sort(),f=Math.min(c.length,d.length);for(let p=0;p<f;p++){if(c[p]!==d[p])return c[p]<d[p]?-1:1;const g=Ws(s[c[p]],o[d[p]]);if(g!==0)return g}return c.length<d.length?-1:c.length>d.length?1:0}default:return 0}}function QM(t,e,n){if(e<=0)return[];const r=[];for(const s of t)r.length<e?eS(r,s,n):n(s,r[r.length-1])<0&&(r.pop(),eS(r,s,n));return r}function eS(t,e,n){let r=0,s=t.length;for(;r<s;){const o=r+s>>1;n(e,t[o])<0?s=o:r=o+1}t.splice(r,0,e)}const Vs="__name__",XM=new Set(["<","<=",">",">=","!=","not-in"]);function Pm(t,e){return e===Vs?{path:t.path}:t.data[e]}function tg(t){return t.kind==="where"?XM.has(t.op)?[t.field]:[]:t.filters.flatMap(tg)}function eL(t){return tg(t).length>0}function Dd(t,e){return od(t)===od(e)}function tL(t,e){return Dd(t,e)&&Ws(t,e)<0}function nL(t,e){return Dd(t,e)&&Ws(t,e)<=0}function rL(t,e){return Dd(t,e)&&Ws(t,e)>0}function sL(t,e){return Dd(t,e)&&Ws(t,e)>=0}function iL(t,e,n){const r=t!==void 0;switch(e){case"==":return r&&xr(t,n);case"!=":return r&&t!==null&&!xr(t,n);case"<":return r&&tL(t,n);case"<=":return r&&nL(t,n);case">":return r&&rL(t,n);case">=":return r&&sL(t,n);case"in":return r&&Array.isArray(n)&&n.some(s=>xr(t,s));case"not-in":return!Array.isArray(n)||n.some(s=>s===null)?!1:r&&t!==null&&!n.some(s=>xr(t,s));case"array-contains":return Array.isArray(t)&&t.some(s=>xr(s,n));case"array-contains-any":return Array.isArray(t)&&Array.isArray(n)&&n.some(s=>t.some(o=>xr(o,s)))}}function aL(t,e){if(e===Vs){const n=t.path.split("/");return n[n.length-1]??t.path}return t.data[e]}function CE(t){if(Array.isArray(t))return t.map(CE);if(t&&typeof t=="object"){const e=t;if(typeof e.id=="string")return e.id;if(typeof e.path=="string"){const n=e.path.split("/");return n[n.length-1]??e.path}}return t}function qm(t,e){if(e.kind==="where"){const n=aL(t,e.field),r=e.field===Vs?CE(e.value):e.value;return iL(n,e.op,r)}return e.kind==="and"?e.filters.every(n=>qm(t,n)):e.filters.some(n=>qm(t,n))}function oL(t,e){return t.filter(n=>e.every(r=>qm(n,r)))}function tS(t,e){const n=t.data();if(n===void 0)throw new tn({code:"not-found",message:`Snapshot-based cursors require an existing document — got an empty snapshot for ${t.id??"<unknown>"}.`});return e.map(r=>r.field===Vs?{path:t.ref.path}:n[r.field])}function nS(t,e,n){for(let r=0;r<e.length;r++){const s=Ws(Pm(t,n[r].field),e[r]);if(s!==0)return n[r].direction==="desc"?-s:s}return 0}function lL(t,e,n,r){return t.filter(s=>{if(n){const o=nS(s,n.values,e);if(n.inclusive?o<0:o<=0)return!1}if(r){const o=nS(s,r.values,e);if(r.inclusive?o>0:o>=0)return!1}return!0})}function NE(t,e){return t.filter(n=>e.every(r=>r.field===Vs||n.data[r.field]!==void 0))}function OE(t){return(e,n)=>{for(const r of t){const s=Ws(Pm(e,r.field),Pm(n,r.field));if(s!==0)return r.direction==="desc"?-s:s}return 0}}function cL(t,e){return e.length===0?t:NE(t,e).sort(OE(e))}class Id{constructor(e,n,r,s=[],o=[],c,d=!1,f,p,g=!1){G(this,"env");G(this,"auth");G(this,"collectionPath");G(this,"clauses");G(this,"orders");G(this,"limitCount");G(this,"limitFromEnd");G(this,"start");G(this,"end");G(this,"bypassRules");this.env=e,this.auth=n,this.collectionPath=r,this.clauses=s,this.orders=o,this.limitCount=c,this.limitFromEnd=d,this.start=f,this.end=p,this.bypassRules=g}where(e,n,r){return this.clone({clauses:[...this.clauses,{kind:"where",field:e,op:n,value:r}]})}applyFilter(e){return this.clone({clauses:[...this.clauses,e]})}orderBy(e,n="asc"){return this.clone({orders:[...this.orders,{field:e,direction:n}]})}limit(e){return this.clone({limitCount:e,limitFromEnd:!1})}limitToLast(e){return this.clone({limitCount:e,limitFromEnd:!0})}startCursor(e,n){return this.clone({start:{values:[...e],inclusive:n,fromSnapshot:!1}})}endCursor(e,n){return this.clone({end:{values:[...e],inclusive:n,fromSnapshot:!1}})}startCursorFromSnapshot(e,n){return this.clone({start:{values:tS(e,this.normalizedOrders()),inclusive:n,fromSnapshot:!0}})}endCursorFromSnapshot(e,n){return this.clone({end:{values:tS(e,this.normalizedOrders()),inclusive:n,fromSnapshot:!0}})}clone(e){return new Id(this.env,this.auth,this.collectionPath,e.clauses??this.clauses,e.orders??this.orders,e.limitCount!==void 0||"limitCount"in e?e.limitCount:this.limitCount,e.limitFromEnd??this.limitFromEnd,"start"in e?e.start:this.start,"end"in e?e.end:this.end,this.bypassRules)}gatherCandidates(){return this.env.scanDocuments(this.collectionPath,{directOnly:!0})}listRulePath(){return this.collectionPath}readCandidates(e){const n=(e==null?void 0:e.auth)!==void 0?e.auth:this.auth,r=this.env.readQueryCandidates(this.gatherCandidates(),this.listRulePath(),n,this.structuredConstraints(),this.bypassRules);if(!r.allowed)throw new tn(r.error);return r.docs}structuredConstraints(){const e=[],n=r=>{if(r.kind==="where"){const s=r.value;(s===null||typeof s=="string"||typeof s=="number"||typeof s=="boolean")&&e.push({field:r.field,op:r.op,value:s});return}r.kind==="and"&&r.filters.forEach(n)};for(const r of this.clauses)n(r);return{where:e,limit:this.limitCount??null,offset:null,orderBy:this.orders.length>0?this.orders[0].field:null}}applyConstraints(e){let n=oL(e,[...this.clauses]);const r=this.normalizedOrders(),s=this.orders.length>0||this.start!==void 0||this.end!==void 0||this.clauses.some(eL);if(s&&this.limitCount!==void 0&&!this.limitFromEnd&&this.start===void 0&&this.end===void 0)return QM(NE(n,r),this.limitCount,OE(r));if(s&&(n=cL(n,r)),this.start||this.end){for(const o of[this.start,this.end])if(o&&!o.fromSnapshot&&o.values.length>this.orders.length)throw new tn({code:"invalid-argument",message:"Too many arguments provided to a cursor (startAt / startAfter / endAt / endBefore). The number of cursor values must be less than or equal to the number of orderBy() clauses."});n=lL(n,r,this.start,this.end)}if(this.limitCount!==void 0)if(this.limitFromEnd){if(this.orders.length===0)throw new tn({code:"invalid-argument",message:"limitToLast() queries require at least one orderBy clause."});n=n.slice(-this.limitCount)}else n=n.slice(0,this.limitCount);return n}normalizedOrders(){const e=[...this.orders],n=new Set(e.map(s=>s.field)),r=this.orders.length>0?this.orders[this.orders.length-1].direction:"asc";for(const s of this.clauses)for(const o of tg(s))o!==Vs&&!n.has(o)&&(n.add(o),e.push({field:o,direction:r}));return n.has(Vs)||e.push({field:Vs,direction:r}),e}snapshotConstraints(){if(this.clauses.length===0&&this.orders.length===0&&this.limitCount===void 0&&this.start===void 0&&this.end===void 0)return;const e=n=>this.applyConstraints(n);return e.structured=this.structuredConstraints(),e}async get(e){const r=this.applyConstraints(this.readCandidates(e)).map(s=>{const o=new eg(this.env,this.auth,s.path,this.bypassRules),c=ro(s.data);return{id:o.id,ref:o,exists:!0,data:()=>c}});return{size:r.length,empty:r.length===0,docs:r,forEach(s){r.forEach(s)}}}async aggregate(e,n){const r=this.applyConstraints(this.readCandidates(n)),s={};for(const o of Object.keys(e))s[o]=dL(e[o],r);return{data:()=>s}}}function uL(t,e){if(!e.includes("."))return t[e];let n=t;for(const r of e.split(".")){if(typeof n!="object"||n===null||Array.isArray(n))return;n=n[r]}return n}function dL(t,e){if(t.kind==="count")return e.length;let n=0,r=0;for(const s of e){const o=uL(s.data,t.field);typeof o=="number"&&Number.isFinite(o)&&(n+=o,r++)}return t.kind==="sum"?n:r===0?null:n/r}class ng extends Id{constructor(n,r,s,o=[],c=[],d,f=!1,p,g,b=!1){super(n,r,"",o,c,d,f,p,g,b);G(this,"collectionId");this.collectionId=s}clone(n){return new ng(this.env,this.auth,this.collectionId,n.clauses??this.clauses,n.orders??this.orders,"limitCount"in n?n.limitCount:this.limitCount,n.limitFromEnd??this.limitFromEnd,"start"in n?n.start:this.start,"end"in n?n.end:this.end,this.bypassRules)}gatherCandidates(){const n=[],r=this.env.snapshot();for(const s of Object.keys(r))fL(s)===this.collectionId&&n.push({path:s,data:r[s]});return n}listRulePath(){return this.collectionId}}function fL(t){const e=t.split("/").filter(n=>n.length>0);return e.length===0||e.length%2!==0?null:e[e.length-2]}class zm extends Id{constructor(n,r,s,o=!1){super(n,r,s,[],[],void 0,!1,void 0,void 0,o);G(this,"id");G(this,"path");this.path=s,this.id=Rd(s)}doc(n){const r=n??Vy();return new eg(this.env,this.auth,`${this.path}/${r}`,this.bypassRules)}async add(n,r){const s=this.doc();return await s.set(n,r),s}}class hL{constructor(e,n,r=!1){G(this,"env");G(this,"auth");G(this,"bypassRules");G(this,"ops",[]);this.env=e,this.auth=n,this.bypassRules=r}set(e,n){const s=this.env.getDocument(e.path)===null?"create":"update";return this.ops.push({method:s,path:e.path,data:n}),this}update(e,n){return this.ops.push({method:"update",path:e.path,data:n}),this}delete(e){return this.ops.push({method:"delete",path:e.path}),this}async commit(e){if(this.ops.length===0)return;const n=this.env.batch(this.ops,(e==null?void 0:e.auth)!==void 0?e.auth:this.auth,this.bypassRules);if(n.allowed)return;if(n.error)throw new tn(n.error);const r=n.results.find(o=>!o.allowed),s=(r==null?void 0:r.debugMessages.join("; "))??"batch denied";throw new tn(Pe("permission-denied",`batch failed: ${s}`))}}function pL(t){return typeof t.where=="function"}class mL{constructor(e){G(this,"simTx");this.simTx=e}async get(e){if(pL(e)){const o=await e.get();return o.size>0&&this.simTx.getAll(...o.docs.map(c=>c.ref.path)),o}const r=this.simTx.get(e.path).data();if(r===void 0)return{id:e.id,ref:e,exists:!1,data:()=>{}};const s=ro(r);return{id:e.id,ref:e,exists:!0,data:()=>s}}set(e,n){return this.simTx.set(e.path,n),this}update(e,n){return this.simTx.update(e.path,n),this}delete(e){return this.simTx.delete(e.path),this}}class yL{constructor(e,n,r=!1,s){G(this,"env");G(this,"auth");G(this,"bypassRules");G(this,"provenance");this.env=e,this.auth=n,this.bypassRules=r,this.provenance=s}collection(e){if(!Xy(e))throw new tn(Pe("invalid-argument",`collection path must have an odd number of segments: ${e}`));return new zm(this.env,this.auth,e,this.bypassRules)}doc(e){if(!jE(e))throw new tn(Pe("invalid-argument",`document path must have an even number of segments: ${e}`));return new eg(this.env,this.auth,e,this.bypassRules)}collectionGroup(e){if(e.length===0||e.includes("/"))throw new tn(Pe("invalid-argument",`collection group id must be a single non-empty segment with no '/': ${e}`));return new ng(this.env,this.auth,e,[],[],void 0,!1,void 0,void 0,this.bypassRules)}batch(){return new hL(this.env,this.auth,this.bypassRules)}async runTransaction(e,n){let r;try{r=await this.env.transaction(s=>{const o=new mL(s);return e(o)},{auth:(n==null?void 0:n.auth)!==void 0?n.auth:this.auth,bypassRules:this.bypassRules,provenance:this.provenance})}catch(s){throw s instanceof tE?new tn(s.simError):s}if(!r.allowed){if(r.error)throw new tn(r.error);const s=r.writes.find(c=>!c.allowed),o=(s==null?void 0:s.debugMessages.join("; "))??"transaction denied at commit";throw new tn(Pe("permission-denied",`transaction failed: ${o}`))}return r.returnValue}}function gL(t,e){return new yL(t,(e==null?void 0:e.auth)??null,(e==null?void 0:e.bypassRules)??!1,e==null?void 0:e.provenance)}const TE=Symbol("pyric/sandbox/context"),RE=Symbol("pyric/sandbox/bypassRules");let Vm=null;function bL(t){Vm=t}function vL(t){const e=t;return typeof e.path=="string"&&e.path.length>0||typeof e.collectionPath=="string"&&e.collectionPath.length>0}function xL(t){const e=t.trim();if(!e)return[];const n=e.indexOf(": ");if(n!==-1){const s=e.slice(n+2).trim().split("; ").map(o=>o.trim()).filter(o=>o.length>0);if(s.length>0)return s}return[e]}function rS(t,e){if(!(t instanceof tn))return t;const n=t.code;if(n!=="permission-denied")return new rt(n,t.message);const r={auth:e.auth,reasons:xL(t.message)},s=t.simError;if(s!=null&&s.request){const o=s.request;r.request={method:o.method,path:o.path,...o.resourceData?{resourceData:o.resourceData}:{}}}return s!=null&&s.resource&&(r.resource={data:s.resource.data,exists:s.resource.exists}),new rt(n,t.message,r)}function ld(t,e,n=!1){return new Proxy(t,{get(r,s,o){if(s===TE)return e;if(s===RE)return n;if(s==="onSnapshot"&&Vm!==null&&!(s in r)&&vL(r))return(...d)=>Vm(o,...d);const c=Reflect.get(r,s,o);return typeof c!="function"?c:function(...d){var p,g;let f;try{const b=()=>c.apply(r,d);f=((g=(p=e.sandbox).runWithProvenance)==null?void 0:g.call(p,ad(e.operationContext),b))??b()}catch(b){throw rS(b,e)}return f instanceof Promise?f.then(b=>b&&typeof b=="object"?ld(b,e,n):b).catch(b=>{throw rS(b,e)}):f&&typeof f=="object"?ld(f,e,n):f}}})}function DE(t,e=!1){if(Hy(t.sandbox))throw new Error("pyric/sandbox/admin-firestore: internal — a remote sandbox context reached the local engine builder; remote dispatch should have handled it. Please report this.");const n=()=>gL(nn(t.sandbox),{auth:t.auth,bypassRules:e,provenance:ad(t.operationContext)});return{collection(r){return n().collection(r)},doc(r){return n().doc(r)},collectionGroup(r){return n().collectionGroup(r)},batch(){return n().batch()},runTransaction(r,s){return n().runTransaction(r)},setRules(r){return nn(t.sandbox).deployRules(r)},seed(r){const s=nn(t.sandbox);return s.seed({rules:s.getRules(),documents:(r==null?void 0:r.documents)??{}})},snapshot(){return nn(t.sandbox).snapshot()}}}function Hm(t){if(t instanceof rt)return t;if(t!==null&&typeof t=="object"){const e=t;if(typeof e.code=="string"&&typeof e.message=="string"){const n=e.denialContext!==null&&typeof e.denialContext=="object"?e.denialContext:void 0;return new rt(e.code,e.message,n)}}return t}function ts(t){return new rt("invalid-argument",t)}async function cr(t,e){try{return await t.sandbox.channel.op({...e,actAs:t.lens})}catch(n){throw Hm(n)}}const wL=new Set(["serverTimestamp","increment","arrayUnion","arrayRemove","deleteField"]);function SL(t){return t!==null&&typeof t=="object"&&typeof t.__type=="string"&&wL.has(t.__type)}function _L(t){switch(t.__type){case"serverTimestamp":return{__sentinel:"serverTimestamp"};case"increment":return{__sentinel:"increment",n:t.value};case"arrayUnion":return{__sentinel:"arrayUnion",values:t.values.map(ss)};case"arrayRemove":return{__sentinel:"arrayRemove",values:t.values.map(ss)};case"deleteField":return{__sentinel:"deleteField"}}}function ss(t){var r;if(t===null||typeof t!="object")return t;if(SL(t))return _L(t);if(t instanceof Mn)return t.toJSON();if(t instanceof Date)return Mn.fromDate(t).toJSON();if(Array.isArray(t))return t.map(ss);const e=Object.getPrototypeOf(t);if(e!==Object.prototype&&e!==null){const s=t.toJSON;if(typeof s=="function")return s.call(t);throw ts(`remote Firestore: cannot serialize a ${((r=e.constructor)==null?void 0:r.name)??"class"} instance for the wire — use plain data, Timestamp, Date, or FieldValue sentinels.`)}const n={};for(const[s,o]of Object.entries(t))n[s]=ss(o);return n}function Li(t){return ss(t)}function Gm(t){return Za(JSON.parse(t.json))}function IE(t){return ro(Gm(t))}function ME(t,e){const n=e.exists&&e.data?IE(e.data):void 0;return{id:t.id,ref:t,exists:e.exists,data:()=>n}}function LE(t,e){const n=e.docs.map(r=>{const s=r.path??r.id,o=cd(t,s),c=r.data?IE(r.data):{};return{id:o.id,ref:o,exists:!0,data:()=>c}});return{size:n.length,empty:n.length===0,docs:n,forEach(r){n.forEach(s=>r(s))}}}const rg=Symbol("pyric/sandbox/admin-firestore/remoteSnapshotRegistrar");function EL(t){if(t===null||typeof t!="object")return;const e=t[rg];return typeof e=="function"?e:void 0}let Km=null;function AL(t){Km=t}function UE(...t){if(Km===null)throw new rt("failed-precondition","remote Firestore: onSnapshot is not wired yet — import pyric-admin/firestore (or pyric/sandbox/admin-firestore) before subscribing.");return Km(this,...t)}function $E(t,e,n,r,s){const o=n.includeMetadataChanges!==!0;let c,d;try{d=t.sandbox.channel.subscribe({target:e,actAs:t.lens},f=>{if(!r)return;const p=f;if(Array.isArray(p.docs)){const g=p.docs.map(x=>({path:x.path??x.id,data:x.data?Gm(x.data):{}})),b=e.__ref==="query"?e.source.__ref==="group"?e.source.collectionId:e.source.path:e.__ref==="group"?e.collectionId:e.path,v=Ba({path:b},g,{excludesMetadataChanges:o},c);c=g,r(v)}else if(typeof p.id=="string"){const g=p.path??p.id,b=p.exists&&p.data?Gm(p.data):null;r($a(g,b))}},f=>{const p=Hm(f);s?s(p):console.error("pyric remote Firestore: uncaught onSnapshot error:",p)})}catch(f){throw Hm(f)}return d}const BE=Symbol("pyric/sandbox/admin-firestore/remoteQueryState");function jL(t){if(!(t===null||typeof t!="object"))return t[BE]}function FE(t){return t.kind==="where"?(PE(t.op),{kind:"where",field:t.field,op:t.op,value:ss(t.value)}):{kind:t.kind,filters:t.filters.map(FE)}}const kL=new Set(["<","<=","==","!=",">=",">","in","not-in","array-contains","array-contains-any"]);function PE(t){if(!kL.has(t))throw ts(`invalid where operator: ${String(t)}`)}function Tu(t){const e=[...t.filters];for(const n of t.orders)e.push({kind:"orderBy",field:n.field,direction:n.direction});return t.start&&e.push({kind:t.start.inclusive?"startAt":"startAfter",values:t.start.values.map(ss)}),t.end&&e.push({kind:t.end.inclusive?"endAt":"endBefore",values:t.end.values.map(ss)}),t.limitCount!==void 0&&e.push(t.limitFromEnd?{kind:"limitToLast",n:t.limitCount}:{kind:"limit",n:t.limitCount}),e.length===0?t.source:{__ref:"query",source:t.source,constraints:e}}function sS(t,e,n){if(e.length===0)throw ts(`${n}(snapshot) on a remote sandbox requires at least one explicit orderBy() clause — the relay protocol has no document-key cursor.`);if(e.some(s=>s.field==="__name__"))throw ts(`${n}(snapshot) on a remote sandbox does not support orderBy('__name__') — the relay protocol has no document-key cursor, and __name__ is not a data field a value cursor can carry. Order by a real document field instead.`);const r=t.data();if(r===void 0)throw new rt("not-found",`Snapshot-based cursors require an existing document — got an empty snapshot for ${t.id??"<unknown>"}.`);return e.map(s=>r[s.field])}function sg(t,e){const n=s=>sg(t,{...e,...s});return{[BE]:e,where(s,o,c){return PE(o),n({filters:[...e.filters,{kind:"where",field:s,op:o,value:ss(c)}]})},applyFilter(s){return n({filters:[...e.filters,FE(s)]})},orderBy(s,o="asc"){return n({orders:[...e.orders,{field:s,direction:o}]})},limit(s){return n({limitCount:s,limitFromEnd:!1})},limitToLast(s){return n({limitCount:s,limitFromEnd:!0})},startCursor(s,o){return n({start:{values:[...s],inclusive:o}})},endCursor(s,o){return n({end:{values:[...s],inclusive:o}})},startCursorFromSnapshot(s,o){return n({start:{values:sS(s,e.orders,o?"startAt":"startAfter"),inclusive:o}})},endCursorFromSnapshot(s,o){return n({end:{values:sS(s,e.orders,o?"endAt":"endBefore"),inclusive:o}})},async get(s){Ru(e);const o=await cr(t,{method:"getDocs",source:Tu(e)});return LE(t,o)},async aggregate(s){Ru(e);const o=await cr(t,{method:"aggregate",source:Tu(e),spec:s});return{data:()=>o.data}},[rg]:(s,o,c)=>(Ru(e),$E(t,Tu(e),s,o,c)),onSnapshot:UE}}function Ru(t){if(t.limitFromEnd&&t.orders.length===0)throw ts("limitToLast() queries require at least one orderBy clause.")}function Ym(t,e){const n=sg(t,{source:{__ref:"collection",path:e},filters:[],orders:[],limitFromEnd:!1});return Object.assign(Object.create(Object.getPrototypeOf(n)),n,{id:Rd(e),path:e,doc(s){const o=s??Vy();return cd(t,`${e}/${o}`)},async add(s,o){const c=await cr(t,{method:"addDoc",collectionPath:e,data:Li(s)});return cd(t,c.path)}})}function cd(t,e){const n={id:Rd(e),path:e,get parent(){return Ym(t,kE(e))},collection(r){const s=`${e}/${r}`;if(!Xy(s))throw ts(`collection path must have an odd number of segments: ${s}`);return Ym(t,s)},async get(r){const s=await cr(t,{method:"getDoc",path:e});return ME(n,s)},async set(r,s){await cr(t,{method:"setDoc",path:e,data:Li(r),...iS(s)?{options:iS(s)}:{}})},async update(r,s){await cr(t,{method:"updateDoc",path:e,data:Li(r)})},async delete(r){await cr(t,{method:"deleteDoc",path:e})},[rg]:(r,s,o)=>$E(t,{__ref:"doc",path:e},r,s,o),onSnapshot:UE};return n}function iS(t){if(!t)return;const e={};return t.merge!==void 0&&(e.merge=t.merge),t.mergeFields!==void 0&&(e.mergeFields=[...t.mergeFields]),e.merge!==void 0||e.mergeFields!==void 0?e:void 0}function CL(t){const e=[];let n=!1;const r={set(o,c){return s(),e.push({method:"set",path:o.path,data:Li(c)}),r},update(o,c){return s(),e.push({method:"update",path:o.path,data:Li(c)}),r},delete(o){return s(),e.push({method:"delete",path:o.path}),r},async commit(o){s(),n=!0,await cr(t,{method:"batchCommit",writes:e})}};function s(){if(n)throw new rt("failed-precondition","WriteBatch has already been committed.")}return r}const aS=5;async function NL(t,e){for(let n=0;n<aS;n++){const r=[],s=[],o=()=>{if(s.length>0)throw new rt("failed-precondition",Nm)},c={get(g){o();const b=jL(g);return b!==void 0?f(b):d(g)},set(g,b){return s.push({method:"set",path:g.path,data:Li(b)}),c},update(g,b){return s.push({method:"update",path:g.path,data:Li(b)}),c},delete(g){return s.push({method:"delete",path:g.path}),c}};async function d(g){const b=await cr(t,{method:"getDoc",path:g.path});return r.push({path:b.path??g.path,data:b.exists&&b.data?b.data:null}),ME(g,b)}async function f(g){Ru(g);const b=await cr(t,{method:"getDocs",source:Tu(g)});for(const v of b.docs)r.push({path:v.path??v.id,data:v.data??null});return LE(t,b)}const p=await e(c);try{return await cr(t,{method:"txnCommit",reads:r,writes:s}),p}catch(g){if(g instanceof rt&&g.code==="aborted")continue;throw g}}throw new rt("aborted",`Transaction failed after ${aS} attempts due to repeated conflicts. Another writer is concurrently updating the same documents.`)}function Pp(t,e){return new rt("unimplemented",`SandboxFirestore.${t} is not available on a remote sandbox — its return value is synchronous and the data lives in the browser worker. ${e}`)}function qE(t,e){const n={sandbox:t,lens:e};return{collection(r){if(!Xy(r))throw ts(`collection path must have an odd number of segments: ${r}`);return Ym(n,r)},doc(r){if(!jE(r))throw ts(`document path must have an even number of segments: ${r}`);return cd(n,r)},collectionGroup(r){if(r.length===0||r.includes("/"))throw ts(`collection group id must be a single non-empty segment with no '/': ${r}`);return sg(n,{source:{__ref:"group",collectionId:r},filters:[],orders:[],limitFromEnd:!1})},batch(){return CL(n)},runTransaction(r,s){return NL(n,r)},setRules(){throw Pp("setRules","Deploy rules asynchronously through the relay instead: `await sandbox.channel.op({ method: 'setFirestoreRules', source })`.")},seed(){throw Pp("seed","The relay has no atomic seed op; write seed docs through this handle (`db.doc(path).set(data)` / `db.batch()`), or drive `sandbox.channel.op({ method: 'admin.setDocument', path, data })` per document.")},snapshot(){throw Pp("snapshot","Read the worker state asynchronously instead: `await sandbox.channel.op({ method: 'admin.readState' })`.")}}}const oS=new WeakMap;function zE(t){const e=oS.get(t);if(e)return e;const n=Hy(t.sandbox)?qE(t.sandbox,OL(t.auth)):ld(DE(t),t);return oS.set(t,n),n}function OL(t){return t==null?{mode:"anon"}:t.token===void 0?{mode:"as",uid:t.uid}:{mode:"as",uid:t.uid,token:t.token}}const lS=new WeakMap;function TL(t){const e=RL(t)?t:t.withAuth(null),n=lS.get(e);if(n)return n;const r=e.operationContext.authLens.mode==="admin"?e:Fl(e,{source:e.operationContext.source,authLens:{mode:"admin"},...e.operationContext.planId===void 0?{}:{planId:e.operationContext.planId}}),s=Hy(r.sandbox)?qE(r.sandbox,{mode:"admin"}):ld(DE(r,!0),r,!0);return lS.set(e,s),s}function RL(t){return t!==null&&typeof t=="object"&&"sandbox"in t&&typeof t.withAuth=="function"}const Pa=Symbol("pyric/firestore/followsCurrentUser"),xl=Symbol("pyric/firestore/authSessionScope");function DL(t){if(t===null||typeof t!="object")return null;const e=t;return typeof e.path=="string"&&e.path.length>0?e.path:typeof e.collectionPath=="string"&&e.collectionPath.length>0?e.collectionPath:null}function IL(t){if(t!==null&&typeof t=="object"){const e=t.snapshotConstraints;if(typeof e=="function")return e.call(t)}}function ML(t){if(t===null||typeof t!="object")return!1;const e=t;return typeof e.path=="string"&&e.path.length>0&&e.parent!==void 0&&e.parent!==null}function VE(t,e,n,r,s){let o={},c,d;if(typeof e=="object"&&e!==null&&typeof e.next!="function"&&typeof e.error!="function"&&typeof e.complete!="function"){if(o=e,typeof n=="function")c=n,d=r;else if(typeof n=="object"&&n!==null){const R=n;c=R.next,d=R.error}}else if(typeof e=="function")c=e,d=n;else if(typeof e=="object"&&e!==null){const R=e;c=R.next,d=R.error}if(!c&&!d)throw new TypeError("onSnapshot: missing handler. Provide a callback, or an observer with a `next` and/or `error` method.");const p=EL(t);if(p){if(o[Pa]===!0)throw new rt("unimplemented","onSnapshot: live (follows-current-user) listeners are not supported on a remote sandbox — remote listeners are frozen to the identity of the context that created the ref.");return p(o,c,d)}const g=LL(t),b=nn(g.sandbox);let v;if(ML(t))v={kind:"doc",path:t.path};else{const R=DL(t);if(R===null)throw new TypeError("onSnapshot: could not determine the collection path for this Query. Pass a CollectionReference or a Query produced by `.where`/`.orderBy`/`.limit` on a CollectionReference obtained from `getFirestore(ctx)`.");const C=IL(t);v={kind:"query",collection:R,constraints:C}}const x=o[Pa]===!0,_=o[xl],k=t[RE]===!0;if(Pa in o){const{[Pa]:R,...C}=o;o=C}if(xl in o){const{[xl]:R,...C}=o;o=C}return b.addSnapshotListener(v,c??(()=>{}),o,g.auth,d,x,k,_)}function LL(t){if(t===null||typeof t!="object")throw new TypeError("onSnapshot: reference must be a DocumentReference or Query.");const e=t[TE];if(!e)throw new TypeError("onSnapshot: reference was not produced by a sandbox context — pass a ref obtained from `getFirestore(ctx)`.");return e}bL(VE);AL(VE);class Sr{constructor(e){G(this,"bytes");this.bytes=e}static fromBase64String(e){const n=atob(e),r=new Uint8Array(n.length);for(let s=0;s<n.length;s+=1)r[s]=n.charCodeAt(s);return new Sr(r)}static fromUint8Array(e){return new Sr(e.slice())}toBase64(){let e="";for(const n of this.bytes)e+=String.fromCharCode(n);return btoa(e)}toUint8Array(){return this.bytes.slice()}toString(){return`Bytes(base64: ${this.toBase64()})`}isEqual(e){return e instanceof Sr&&this.bytes.length===e.bytes.length&&this.bytes.every((n,r)=>n===e.bytes[r])}toJSON(){return{type:"firestore/bytes/1.0",bytes:this.toBase64()}}static fromJSON(e){const n=e;if(n.type!=="firestore/bytes/1.0"||typeof n.bytes!="string")throw new TypeError("Invalid Bytes JSON value.");return Sr.fromBase64String(n.bytes)}}class Cr{constructor(e,n){G(this,"lat");G(this,"lng");if(this.lat=e,this.lng=n,!Number.isFinite(e)||e<-90||e>90)throw new TypeError("Latitude must be a number between -90 and 90.");if(!Number.isFinite(n)||n<-180||n>180)throw new TypeError("Longitude must be a number between -180 and 180.")}get latitude(){return this.lat}get longitude(){return this.lng}isEqual(e){return e instanceof Cr&&this.lat===e.lat&&this.lng===e.lng}toJSON(){return{latitude:this.lat,longitude:this.lng,type:"firestore/geoPoint/1.0"}}static fromJSON(e){const n=e;if(n.type!=="firestore/geoPoint/1.0"||typeof n.latitude!="number"||typeof n.longitude!="number")throw new TypeError("Invalid GeoPoint JSON value.");return new Cr(n.latitude,n.longitude)}}class wl{constructor(e){G(this,"_values");this._values=e}static create(e){if(!e.every(n=>typeof n=="number"))throw new TypeError("Vector values must be numbers.");return new wl(e.slice())}toArray(){return this._values.slice()}isEqual(e){const n=e instanceof wl?e._values:void 0;return n!==void 0&&this._values.length===n.length&&this._values.every((r,s)=>r===n[s])}toJSON(){return{type:"firestore/vectorValue/1.0",vectorValues:this.toArray()}}static fromJSON(e){const n=e;if(n.type!=="firestore/vectorValue/1.0"||!Array.isArray(n.vectorValues)||!n.vectorValues.every(r=>typeof r=="number"))throw new TypeError("Invalid VectorValue JSON value.");return wl.create(n.vectorValues)}}function UL(t=[]){return wl.create(t)}function mq(){return hD.serverTimestamp()}const Hs=Symbol("pyric/firestore/target");function Qs(t){return t.kind==="sandbox"?t.db:t.getDb()}const Md=new WeakMap;function Zm(t,e){return Md.set(t,e),t}const Hi=new WeakMap;function $L(t,e,n){return Md.set(t,e),Hi.set(t,n),t}function Ld(t,e){const n=Gi(e);if(t.kind==="sandbox")return n;const r=Hi.get(n);if(!r)throw new TypeError("pyric/firestore: live ref missing rebuild closure — was it produced by a factory in this package?");return r(Qs(t))}function BL(t,e){const n=Gi(e);if(t.kind==="sandbox")return n;const r=Hi.get(n);if(!r)throw new TypeError("pyric/firestore: live collection ref missing rebuild closure.");return r(Qs(t))}function FL(t,e){const n=Gi(e);if(t.kind==="sandbox")return n;const r=Hi.get(n);if(!r)throw new TypeError("pyric/firestore: live query missing rebuild closure.");return r(Qs(t))}function Qa(t,e,n){return e.kind==="sandbox-live"?$L(t,e,n):Zm(t,e)}function PL(t){const e=Gi(t),n=Hi.get(e);return n||(()=>e)}function Or(t){var n;let e;if(Hs in t?e=t[Hs]:e=Md.get(t),!e)throw new TypeError("pyric/firestore: unrecognized reference — was it produced by a factory in this package?");return e.kind==="sandbox-live"&&((n=e.assertUsable)==null||n.call(e)),e}const HE=new WeakMap,ud=new WeakMap;function ao(t){return HE.get(t)}function Gi(t){return ud.get(t)??t}function ig(t,e,n){const r={id:t.id??"",path:t.path??""};return HE.set(r,n),ud.set(r,t),Md.set(r,e),r}function cS(t){return Array.isArray(t)&&t.every(e=>typeof e=="number")}function qL(t){if(t instanceof no)return Array.from(t.value);if(t===null||typeof t!="object")return null;const e=t;return e.typeName==="vector"&&cS(e.value)||e.__type__==="__vector__"&&cS(e.value)?e.value:null}function Wm(t){if(t instanceof Tn)return Sr.fromUint8Array(t.data);if(t instanceof jr)return new Cr(t.lat,t.lng);const e=qL(t);if(e)return UL(e);if(Array.isArray(t))return t.map(Wm);if(t!==null&&typeof t=="object"){const n=Object.getPrototypeOf(t);if(n===Object.prototype||n===null){const r={};for(const[s,o]of Object.entries(t))r[s]=Wm(o);return r}}return t}function GE(t){if(t!==void 0)return Wm(t)}function Ud(t){if(t===void 0)return Ud(xE());const e=Gy(t);if(e)return e.service("firestore/default",()=>{const{sandbox:n,session:r}=e;let s=!1;e.onDelete(()=>{s=!0});const o=e.authScope;o&&e.onDelete(r.onCurrentUserChanged(d=>{nn(n).reevaluateLiveListeners(d,o)}));const c={kind:"sandbox-live",sandbox:n,getDb:uS(n,()=>r.currentUser),authScope:o,own:d=>e.onDelete(d),assertUsable:()=>{if(s)throw new Vi("failed-precondition","The client has already been terminated.")}};return{[Hs]:c,app:t}});if(KE(t)){const r={kind:"sandbox",db:zE(t),sandbox:t.sandbox};return{[Hs]:r}}if(zL(t)){const n={kind:"sandbox-live",sandbox:t,getDb:uS(t)};return{[Hs]:n}}throw new TypeError("pyric/firestore is a sandbox-only mirror. Package resolution must leave firebase/firestore unchanged for production; activate pyric dev or @pyric/cli/register before importing to select the sandbox.")}function ag(t){const e=Gy(t);if(e){e.assertAlive();const c=e.sandbox;return ag(Fl(c.withAuth(null),{source:{kind:"app"},authLens:{mode:"admin"}}))}const n=KE(t)?t:t.withAuth(null),r=n.sandbox,o={kind:"sandbox",db:TL(n),sandbox:r};return{[Hs]:o}}function KE(t){return t instanceof so}function zL(t){if(t===null||typeof t!="object")return!1;const e=t;return typeof e.withAuth=="function"&&typeof e.onCurrentUserChanged=="function"&&"currentUser"in e&&"admin"in e}function uS(t,e=()=>t.currentUser){return()=>{const n=Fl(t.withAuth(e()),{source:{kind:"app"},authLens:{mode:"app-session"}});return zE(n)}}function dd(t){const e=t,n=e.data.bind(t);return Object.defineProperty(e,"data",{value:()=>GE(n()),configurable:!0,writable:!0}),t}function YE(t,e){return{id:t.id,exists:t.exists,data:()=>{if(!(typeof t.exists=="function"?t.exists():t.exists))return;const r=GE(t.data()),s={id:t.id,exists:!0,data:()=>r};return e.fromFirestore(s)}}}function $d(t,e){if(!t||typeof t!="object")return t;const n=t;if(n.ref&&(Zm(n.ref,e),dS(n.ref,e)),fS(n),Array.isArray(n.docs))for(const r of n.docs)r!=null&&r.ref&&(Zm(r.ref,e),dS(r.ref,e)),r&&fS(r);return t}function dS(t,e){if(typeof t.path!="string"||t.path.length===0||ud.has(t))return;const n=t.path;try{const r=Qs(e).doc(n);ud.set(t,r),e.kind==="sandbox-live"&&Hi.set(r,s=>s.doc(n))}catch{}}function fS(t){const e=t.exists;if(typeof e=="function")return;const n=e===!0;try{Object.defineProperty(t,"exists",{value:()=>n,writable:!0,configurable:!0,enumerable:!0})}catch{}}async function og(t){const e=Or(t),n=ao(t),r=await Ld(e,t).get();return n?YE(r,n):($d(r,e),dd(r))}async function Tl(t){const e=Or(t),n=ao(t),r=await FL(e,t).get();if(n){const o=n,c=r.docs.map(d=>YE(d,o));return{size:c.length,empty:c.length===0,docs:c}}$d(r,e);const s=r.docs;for(const o of s)dd(o);return r}function Yn(t,...e){const n=Or(t),r=Hs in t,s=r?void 0:ao(t),o=Qs(n);if(r){if(e.length===0)throw new TypeError("doc(db, path) requires at least one path segment.");const g=e.join("/"),b=o.doc(g);return Qa(b,n,x=>x.doc(g))}const c=Gi(t),d=e.length===0?c.doc():c.doc(e.join("/")),f=d.path,p=Qa(d,n,g=>g.doc(f));return s?ig(p,n,s):p}function Ti(t,...e){const n=Or(t),r=Hs in t;if(e.length===0)throw new TypeError("collection() requires at least one path segment.");if(r){const f=e.join("/"),p=Qs(n).collection(f);return Qa(p,n,g=>g.collection(f))}const s=Gi(t),o=e.join("/"),c=s.collection(o),d=c.path;return Qa(c,n,f=>f.collection(d))}async function Rl(t,e,n){const r=Or(t),s=ao(t),o=s?s.toFirestore(e):e;return Ld(r,t).set(o,n)}async function Jm(t,e){const n=Or(t);return Ld(n,t).update(e)}async function Dl(t){const e=Or(t);return Ld(e,t).delete()}async function lg(t,e){const n=Or(t),r=ao(t),s=r?r.toFirestore(e):e,o=await BL(n,t).add(s),c=o.path,d=Qa(o,n,f=>f.doc(c));return r?ig(d,n,r):d}function ZE(t){return typeof t=="string"?t:t._internalPath.segments.join(".")}function Il(t,...e){const n=Or(t),r=ao(t),s=PL(t),o=f=>{let p=s(f);for(const g of e)p=g.applySandbox(p);return p},c=o(Qs(n)),d=Qa(c,n,f=>o(f));return r?ig(d,n,r):d}function VL(t,e,n){const r=ZE(t);return{applySandbox:o=>o.where(r,e,n),_sandboxFilter:{kind:"where",field:r,op:e,value:n}}}function hS(t,e){const n=ZE(t);return{applySandbox:r=>r.orderBy(n,e)}}function fd(t){return{applySandbox:e=>e.limit(t)}}function HL(t){if(t.length!==1)return!1;const e=t[0];return e!==null&&typeof e=="object"&&"data"in e&&typeof e.data=="function"}function GL(...t){if(HL(t)){const e=t[0];return{applySandbox:n=>n.startCursorFromSnapshot(e,!1)}}return{applySandbox:e=>e.startCursor(t,!1)}}function KL(t,e,n,r){const s=Or(t),o=ZL(s,t),c=WL(e,n,r,s),d=JL(c,s),f=d.length===3?o.onSnapshot(d[0],d[1],d[2]):d.length===2?o.onSnapshot(d[0],d[1]):o.onSnapshot(d[0]);if(s.kind!=="sandbox-live"||!s.own)return f;let p=!1;const g=()=>{p||(p=!0,f())},b=()=>{var x;p||(g(),(x=YL(d))==null||x(new Vi("aborted","The operation was aborted.")))},v=s.own(b);return()=>{v(),g()}}function YL(t){const e=t.at(-1);if(typeof e=="function"&&t.length>=3)return e;if(e&&typeof e=="object"){const n=e.error;if(typeof n=="function")return n}}function ZL(t,e){const n=Gi(e);if(t.kind==="sandbox")return n;const r=Hi.get(n);if(!r)throw new TypeError("pyric/firestore: live ref missing rebuild closure for onSnapshot.");return r(Qs(t))}function WE(t){if(typeof t!="object"||t===null)return!1;const e=t;return typeof e.next=="function"||typeof e.error=="function"||typeof e.complete=="function"}function WL(t,e,n,r){if(typeof t=="object"&&t!==null&&!WE(t)){const o=e;return typeof o=="function"?[t,pS(o,r),n??Qm]:o&&typeof o=="object"?[t,mS(o,r)]:[t]}return typeof t=="function"?[pS(t,r),e??Qm]:t&&typeof t=="object"?[mS(t,r)]:[t]}function JL(t,e){if(e.kind!=="sandbox-live")return t;const n=t[0];return typeof n=="object"&&n!==null&&!WE(n)?[{...n,[Pa]:!0,...e.authScope?{[xl]:e.authScope}:{}},...t.slice(1)]:[{[Pa]:!0,...e.authScope?{[xl]:e.authScope}:{}},...t]}function JE(t,e){if(!t||typeof t!="object")return t;const n=t;if(typeof n.data=="function"&&dd(t),Array.isArray(n.docs))for(const r of n.docs)dd(r);return t}function Qm(t){console.error("pyric/firestore: Uncaught Error in snapshot listener:",t)}function pS(t,e){return n=>t(JE($d(n,e)))}function mS(t,e){return{...t,next:t.next?n=>t.next(JE($d(n,e))):void 0,error:t.error??Qm}}function QL(t,e={}){const n=e.recentEventLimit??10,r=nn(t),s=r.getRules(),o=s?Pu(s):{warnings:[]},c=o.warnings.map(k=>({rule:k.rule,severity:k.severity,message:k.message})),d={errors:0,warnings:0,info:0};for(const k of o.warnings)k.severity==="error"?d.errors++:k.severity==="warning"?d.warnings++:d.info++;const f=r.snapshot(),p={};for(const k of Object.keys(f)){const R=k.split("/")[0]??"";R&&(p[R]=(p[R]??0)+1)}const g=t.history(),b=g.filter(k=>k.kind==="request"),v=b.filter(k=>k.result==="deny"),x=b.slice(-n).map(k=>({path:String(k.path??""),method:String(k.method??""),result:String(k.result??""),auth:k.auth??null})),_=v.slice(-n).map(k=>({path:String(k.path??""),method:String(k.method??""),auth:k.auth??null,debugMessage:typeof k.debugMessage=="string"?k.debugMessage:void 0}));return{rules:{source:s,sizeBytes:new TextEncoder().encode(s).byteLength,isEmpty:s.trim().length===0,lint:{...d,findings:c}},documents:{totalCount:Object.keys(f).length,byCollection:p},events:{totalCount:g.length,recentDenials:_,recentRequests:x}}}const Ds={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"]}]},XL=["<","<=","==","!=",">=",">","in","not-in","array-contains","array-contains-any"],eU={type:"object",properties:{field:{type:"string"},op:{type:"string",enum:[...XL]},value:{}},required:["field","op","value"]};function QE(t){const{resolveDb:e}=t;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:Ds},required:["path"]},async execute(n){const r=n,s=await e(r.as),o=Yn(s,r.path),c=await og(o),d=typeof c.exists=="function"?c.exists():c.exists;return{ok:!0,summary:d?`Got ${r.path}`:`No document at ${r.path}`,data:{exists:d,data:d?c.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:Ds},required:["collection"]},async execute(n){const r=n,s=await e(r.as),o=Ti(s,r.collection),c=[];r.orderBy&&c.push(hS(r.orderBy)),r.limit&&c.push(fd(r.limit));const d=await Tl(Il(o,...c));return{ok:!0,summary:`${d.size} docs in ${r.collection}`,data:{docs:d.docs.map(f=>({id:f.id,data:f.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:Ds},required:["path","data"]},async execute(n){const r=n,s=await e(r.as);return await Rl(Yn(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:Ds},required:["collection","data"]},async execute(n){const r=n,s=await e(r.as),o=await lg(Ti(s,r.collection),r.data);return{ok:!0,summary:`Created ${o.path}`,data:{path:o.path,id:o.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:Ds},required:["path","data"]},async execute(n){const r=n,s=await e(r.as);return await Jm(Yn(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:Ds},required:["path"]},async execute(n){const r=n,s=await e(r.as);return await Dl(Yn(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:Ds},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 e(r.as);for(const o of r.operations){const c=Yn(s,o.path);o.op==="set"?await Rl(c,o.data??{}):o.op==="update"?await Jm(c,o.data??{}):await Dl(c)}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:eU,minItems:1},orderBy:{type:"string"},limit:{type:"number"},as:Ds},required:["collection","where"]},async execute(n){const r=n,s=await e(r.as),o=Ti(s,r.collection),c=r.where.map(f=>VL(f.field,f.op,f.value));r.orderBy&&c.push(hS(r.orderBy)),r.limit&&c.push(fd(r.limit));const d=await Tl(Il(o,...c));return{ok:!0,summary:`${d.size} matches in ${r.collection}`,data:{docs:d.docs.map(f=>({id:f.id,data:f.data()}))}}}}]}function XE(t){const{resolveSandbox:e}=t;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 e(),o=QL(s,{recentEventLimit:r.recentEventLimit});return{ok:!0,summary:`rules: ${o.rules.isEmpty?"EMPTY (setRules has not been called)":`${o.rules.sizeBytes}B, ${o.rules.lint.errors} errors / ${o.rules.lint.warnings} warnings`} · docs: ${o.documents.totalCount} across ${Object.keys(o.documents.byCollection).length} collections · events: ${o.events.totalCount} total, ${o.events.recentDenials.length} recent denials`,data:o}}}]}function yS(t,e){return{code:t.code,severity:e,message:t.message,path:t.path,origin:"validate"}}let ki=[],Xm=!1,ey=!1,ty=!1,qp;function tU(){if(qp)return qp;const t=Nd();return t.addOperation("lint",{_nonterminal(...e){e.forEach(n=>n.lint())},_iter(...e){e.forEach(n=>n.lint())},_terminal(){},CallExpr_methodCall(e,n,r,s,o,c){e.lint(),o.asIteration().children.forEach(d=>d.lint()),r.sourceString==="child"&&e.sourceString==="data"&&(ty=!0)},ident(e,n,r){const s=this.sourceString;s==="data"&&(Xm=!0),s==="newData"&&(ey=!0)},bool_true(e){ki.push({code:"HARDCODED_TRUE",message:"Rule expression is hardcoded to true"})},bool_false(e){ki.push({code:"HARDCODED_FALSE",message:"Rule expression is hardcoded to false"})},Comparison_looseEq(e,n,r){ki.push({code:"LOOSE_EQUALITY",message:"Use '===' instead of '=='"}),e.lint(),r.lint()},Comparison_looseNeq(e,n,r){ki.push({code:"LOOSE_INEQUALITY",message:"Use '!==' instead of '!='"}),e.lint(),r.lint()}}),qp=t,t}function nU(t,e="read"){const n=Cd(t);return n.failed()?[]:(ki=[],Xm=!1,ey=!1,ty=!1,tU()(n).lint(),e==="write"&&Xm&&!ey&&!ty&&ki.push({code:"DATA_IN_WRITE",message:"Write rule references 'data' but not 'newData'; consider using 'newData' to check incoming data"}),[...ki])}const rU={read:new Set(["auth","data","root","now"]),write:new Set(["auth","data","newData","root","now"]),validate:new Set(["auth","data","newData","root","now"])},sU=new Set(["val","exists","hasChild","hasChildren","isString","isNumber","isBoolean","child","parent","getPriority"]),iU=new Set(["matches","contains","beginsWith","endsWith","replace","toLowerCase","toUpperCase","length"]),aU=new Set([...sU,...iU]);let Sl=[],Du="read",eA=new Set,zp;function oU(){if(zp)return zp;const t=Nd();return t.addOperation("validate",{_nonterminal(...e){e.forEach(n=>n.validate())},_iter(...e){e.forEach(n=>n.validate())},_terminal(){},CallExpr_methodCall(e,n,r,s,o,c){e.validate();const d=r.sourceString;aU.has(d)||Sl.push({code:"UNKNOWN_METHOD",message:`Unknown method '${d}'`}),o.asIteration().children.forEach(f=>f.validate())},CallExpr_memberAccess(e,n,r){e.validate()},CallExpr_indexAccess(e,n,r,s){e.validate(),r.validate()},ident(e,n,r){const s=this.sourceString;if(e.sourceString==="$")return;const c=rU[Du];c&&(!c.has(s)&&!eA.has(s)&&Sl.push({code:"UNKNOWN_IDENTIFIER",message:`Identifier '${s}' is not allowed in '${Du}' context`}),s==="newData"&&Du==="read"&&Sl.push({code:"NEWDATA_IN_READ",message:"'newData' is not available in 'read' context"}))}}),zp=t,t}function lU(t,e,n=[]){const r=Cd(t);return r.failed()?[]:(Sl=[],Du=e,eA=new Set(n.map(s=>s.startsWith("$")?s.slice(1):s)),oU()(r).validate(),[...Sl])}const cU=new Set(["__proto__","prototype","constructor"]);function gS(t,e){return cU.has(e)?null:typeof t=="string"?e==="length"?t.length:null:t===null||typeof t!="object"||!Object.hasOwn(t,e)?null:t[e]??null}class ns{constructor(e,n="/",r){G(this,"_value");G(this,"_path");G(this,"_root");this._value=e??null,this._path=n,this._root=r!==void 0?r:e}val(){return this._value}exists(){return this._value!==null&&this._value!==void 0}hasChild(e){return this.child(e).exists()}hasChildren(e){return Array.isArray(e)?e.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(e){const n=e.split("/").filter(o=>o.length>0);let r=this._value,s=this._path;for(const o of n){if(r==null||typeof r!="object"){r=null,s=`${s}/${o}`.replace(/\/+/g,"/");break}r=Object.hasOwn(r,o)?r[o]??null:null,s=`${s==="/"?"":s}/${o}`}return new ns(r,s,this._root)}parent(){if(this._path==="/")return null;const e=this._path.split("/").filter(s=>s.length>0);e.pop();const n="/"+e.join("/"),r=new ns(this._root,"/");return n==="/"?r:r.child(e.join("/"))}getPriority(){return null}}class uU{constructor(e){G(this,"value");this.value=e}matches(e){return(e instanceof RegExp?e:new RegExp(e)).test(this.value)}contains(e){return this.value.includes(e)}beginsWith(e){return this.value.startsWith(e)}endsWith(e){return this.value.endsWith(e)}replace(e,n){if(e instanceof RegExp){const r=e.flags.includes("g")?e.flags:`${e.flags}g`;return this.value.replace(new RegExp(e.source,r),n)}return e===""?this.value:this.value.split(e).join(n)}toLowerCase(){return this.value.toLowerCase()}toUpperCase(){return this.value.toUpperCase()}get length(){return this.value.length}}let Ms={auth:null,data:new ns(null),newData:new ns(null),root:new ns(null),now:Date.now(),pathVariableBindings:{}},Vp;function dU(){if(Vp)return Vp;const t=Nd();return t.addOperation("eval",{Expr(e){return e.eval()},Ternary_ternary(e,n,r,s,o){return e.eval()?r.eval():o.eval()},Ternary(e){return e.eval()},Logical_and(e,n,r){return e.eval()&&r.eval()},Logical_or(e,n,r){return e.eval()||r.eval()},Logical(e){return e.eval()},Comparison_strictEq(e,n,r){return e.eval()===r.eval()},Comparison_strictNeq(e,n,r){return e.eval()!==r.eval()},Comparison_gte(e,n,r){return e.eval()>=r.eval()},Comparison_lte(e,n,r){return e.eval()<=r.eval()},Comparison_gt(e,n,r){return e.eval()>r.eval()},Comparison_lt(e,n,r){return e.eval()<r.eval()},Comparison_looseEq(e,n,r){return e.eval()==r.eval()},Comparison_looseNeq(e,n,r){return e.eval()!=r.eval()},Comparison(e){return e.eval()},Additive_add(e,n,r){return e.eval()+r.eval()},Additive_sub(e,n,r){return e.eval()-r.eval()},Additive(e){return e.eval()},Multiplicative_mul(e,n,r){return e.eval()*r.eval()},Multiplicative_div(e,n,r){return e.eval()/r.eval()},Multiplicative_mod(e,n,r){return e.eval()%r.eval()},Multiplicative(e){return e.eval()},UnaryExpr_not(e,n){return!n.eval()},UnaryExpr_neg(e,n){return-n.eval()},UnaryExpr(e){return e.eval()},CallExpr_methodCall(e,n,r,s,o,c){const d=e.eval(),f=r.sourceString,p=o.asIteration().children.map(g=>g.eval());if(d instanceof ns)switch(f){case"val":return d.val();case"exists":return d.exists();case"hasChild":return d.hasChild(String(p[0]));case"hasChildren":return d.hasChildren(p.length>0?p[0]:void 0);case"isString":return d.isString();case"isNumber":return d.isNumber();case"isBoolean":return d.isBoolean();case"child":return d.child(String(p[0]));case"parent":return d.parent();case"getPriority":return d.getPriority();default:throw new Error(`Unknown DataSnapshot method: ${f}`)}if(typeof d=="string"){const g=new uU(d);switch(f){case"matches":return g.matches(p[0]);case"contains":return g.contains(String(p[0]));case"beginsWith":return g.beginsWith(String(p[0]));case"endsWith":return g.endsWith(String(p[0]));case"replace":return g.replace(p[0],String(p[1]));case"toLowerCase":return g.toLowerCase();case"toUpperCase":return g.toUpperCase();default:throw new Error(`Unknown string method: ${f}`)}}throw new Error(`Unknown method '${f}' for the given value.`)},CallExpr_memberAccess(e,n,r){const s=e.eval();return s==null?null:gS(s,r.sourceString)},CallExpr_indexAccess(e,n,r,s){const o=e.eval(),c=r.eval();return o==null?null:gS(o,String(c))},CallExpr(e){return e.eval()},Primary_paren(e,n,r){return n.eval()},Primary(e){return e.eval()},Array(e,n,r){return n.asIteration().children.map(s=>s.eval())},literal(e){return e.eval()},number_float(e,n,r){return parseFloat(this.sourceString)},number_int(e){return parseInt(this.sourceString,10)},number(e){return e.eval()},string_double(e,n,r){return JSON.parse(this.sourceString)},string_single(e,n,r){return n.children.map(s=>s.sourceString).join("")},string(e){return e.eval()},regex(e,n,r,s){return new RegExp(n.sourceString,s.sourceString)},bool_true(e){return!0},bool_false(e){return!1},bool(e){return e.eval()},null(e){return null},ident(e,n,r){const s=this.sourceString;if(s in Ms.pathVariableBindings)return Ms.pathVariableBindings[s];switch(s){case"auth":return Ms.auth;case"data":return Ms.data;case"newData":return Ms.newData;case"root":return Ms.root;case"now":return Ms.now;default:return}}}),Vp=t,t}function tA(t,e){const n=Cd(t);if(n.failed())throw new Error(n.message??"RTDB expression failed to parse");return Ms=e,dU()(n).eval()}const fU=Rn({operation:Ka(["read","write","validate"]),path:gn().min(1).startsWith("/"),auth:kd([Rn({uid:gn(),token:Ys(es())}),q1()]),mockData:Ys(es()),newData:es().optional(),updates:z1(Rn({path:gn().min(1).startsWith("/"),value:es()})).optional()});Ka(["INVALID_INPUT","NO_MATCHING_RULE","EVALUATION_ERROR"]);Rn({allowed:Nl(),unsupported:Nl().optional(),matchedPath:gn(),matchedRule:gn(),reason:gn(),pathVariableBindings:Ys(gn())});function hU(t){const e=t.val();return e===null||typeof e!="object"?[]:Object.keys(e)}function pU(t,e,n,r,s,o){let c=null;function d(p,g,b,v,x){if(!b.exists())return null;const _=p.validate;if(_){if(!_.parsed.valid)c||(c={node:p,rule:_,bindings:v,unsupported:!0});else if(!tA(_.raw,s(g,b,v)))return{node:p,rule:_,bindings:v}}for(const k of p.children){const R=k.path.split("/").filter(Boolean);if(R.length===0)continue;const C=R[R.length-1],T=C.startsWith("$");if(x.length>0){if(!T&&x[0]!==C)continue;return d(k,g.child(x[0]),b.child(x[0]),T?{...v,[C]:x[0]}:v,x.slice(1))}if(T)for(const U of hU(b)){const q=d(k,g.child(U),b.child(U),{...v,[C]:U},[]);if(q)return q}else{const U=d(k,g.child(C),b.child(C),v,[]);if(U)return U}}return null}return d(t,e,n,r,o)??c}function nA(t,e,n,r=0){const s=[{node:t,pathVariableBindings:{...n},depth:r}];if(e.length===0)return s;for(const o of t.children){const c=o.path.split("/").filter(Boolean);if(c.length===0)continue;const d=c[c.length-1],f=d.startsWith("$");if(f||e[0]===d){const p=f?{...n,[d]:e[0]}:{...n},g=nA(o,e.slice(1),p,r+1);return s.push(...g),s}}return s}function ny(t,e,n){if(e.length===0)return n??null;const[r,...s]=e,o=t!==null&&typeof t=="object"&&!Array.isArray(t)?{...t}:{},c=Object.hasOwn(o,r)?o[r]:null,d=ny(c,s,n);return d==null?delete o[r]:o[r]=d,o}function mU(t,e,n,r){if(!r||r.length===0)return ny(t,e,n??null);let s=t;for(const o of r){const c=o.path.split("/").filter(Boolean);s=ny(s,c,o.value??null)}return s}class yU{execute(e,n){const r=fU.safeParse(n);if(!r.success)return{success:!1,error:{code:"INVALID_INPUT",message:r.error.message,recoverable:!0}};const{operation:s,path:o,auth:c,mockData:d,newData:f,updates:p}=r.data;try{const g=o.split("/").filter(Boolean),b=e,v=nA(b,g,{}),x=new ns(d,"/"),_=s==="read"?d:mU(d,g,f,p),k=new ns(_,"/"),R=(q,I,N)=>{const M={};for(const[L,H]of Object.entries(N))M[L]=H,M[L.slice(1)]=H;return{auth:c?{uid:c.uid,token:c.token}:null,data:q,newData:I,root:x,now:Date.now(),pathVariableBindings:M}};let C;for(const q of v){const I=q.node[s];if(!I)continue;if(!I.parsed.valid){C||(C=q);continue}const N=g.slice(0,q.depth).join("/"),M=x.child(N),L=k.child(N);if(tA(I.raw,R(M,L,q.pathVariableBindings))){if(s==="write"){const P=pU(b,x,k,{},R,g);if(P)return{success:!0,data:{allowed:!1,unsupported:P.unsupported===!0,matchedPath:P.node.path,matchedRule:P.rule.raw,reason:P.unsupported?`Validation rule at '${P.node.path}' contains an expression the simulator cannot evaluate: ${P.rule.raw} — not evaluated; production may reject this write.`:"Validation rule evaluated to false",pathVariableBindings:P.bindings}}}return{success:!0,data:{allowed:!0,matchedPath:q.node.path,matchedRule:I.raw,reason:"Rule expression evaluated to true",pathVariableBindings:q.pathVariableBindings}}}}if(C){const q=C.node[s];return{success:!0,data:{allowed:!1,unsupported:!0,matchedPath:C.node.path,matchedRule:q.raw,reason:`'${s}' rule at '${C.node.path}' contains an expression the simulator cannot evaluate: ${q.raw} — not evaluated; production may reject or allow this ${s}.`,pathVariableBindings:C.pathVariableBindings}}}const T=v[v.length-1],U=T.node[s];return U?{success:!0,data:{allowed:!1,matchedPath:T.node.path,matchedRule:U.raw,reason:"Rule expression evaluated to false",pathVariableBindings:T.pathVariableBindings}}:{success:!1,error:{code:"NO_MATCHING_RULE",message:`No '${s}' rule found for path '${o}'`,recoverable:!0}}}catch(g){return{success:!1,error:{code:"EVALUATION_ERROR",message:g instanceof Error?g.message:String(g),recoverable:!1}}}}}const gU=new Set([".read",".write",".validate",".indexOn"]);function rA(t,e,n=[]){const r=S2(t),s=r.valid?lU(t,e,n):r.errors,o=r.valid?nU(t,e):[];return{raw:t,parsed:{...r,errors:s,warnings:o}}}function sA(t,e,n){const r={path:e,pathVariables:[...n],children:[]};for(const[o,c]of[[".read","read"],[".write","write"],[".validate","validate"]]){const d=t[o];d!==void 0&&(r[c]=rA(String(d),c,n))}const s=t[".indexOn"];s!==void 0&&(r.indexOn=Array.isArray(s)?s.map(String):[String(s)]);for(const[o,c]of Object.entries(t)){if(gU.has(o)||typeof c!="object"||c===null)continue;const d=e==="/"?`/${o}`:`${e}/${o}`,f=o.startsWith("$")?[...n,o]:[...n];r.children.push(sA(c,d,f))}return r}function iA(t){if(!t||typeof t!="object")throw new Error("Invalid rules JSON: expected an object");const e=t;if(!("rules"in e))throw new Error('Invalid rules JSON: missing top-level "rules" key');if(typeof e.rules!="object"||e.rules===null)throw new Error('Invalid rules JSON: "rules" must be an object');return sA(e.rules,"/",[])}function Hp(t){return t==="true"?!0:t==="false"?!1:t}function aA(t){const e={};t.read&&(e[".read"]=Hp(t.read.raw)),t.write&&(e[".write"]=Hp(t.write.raw)),t.validate&&(e[".validate"]=Hp(t.validate.raw)),t.indexOn&&(e[".indexOn"]=t.indexOn);for(const n of t.children){const r=n.path.split("/").filter(Boolean);e[r[r.length-1]]=aA(n)}return e}function bU(t){if(!t||typeof t!="object"||!("path"in t))throw new Error("Invalid compiled rules: expected a rules node with a 'path' property");return{rules:aA(t)}}function cg(t,e){return new yU().execute(t,e)}const Xr=t=>t,bS=(...t)=>Xr(t.map(e=>`(${e})`).join(" && ")),vU=(...t)=>Xr(t.map(e=>`(${e})`).join(" || ")),oA=t=>t,xU=()=>oA("newData.hasChildren()"),wU=t=>oA(`newData.hasChild("${t}")`);function lA(t,e){const n=t.shape,r=[],s={};for(const[d,f]of Object.entries(n)){const p=f,g=p instanceof Er,b=g?p.unwrap():p;g||r.push(d);const v=cA(b,d),x=e==null?void 0:e[d];if(x&&x.length>0?s[d]={validate:bS(v,...x)}:s[d]={validate:v},b instanceof dt){const _=lA(b);s[d]={validate:_.validate,children:_.children}}}const o=[xU()];for(const d of r)o.push(wU(d));return{validate:bS(...o),children:s}}function cA(t,e){if(t instanceof wr)return Xr("newData.isString()");if(t instanceof Ri)return Xr("newData.isNumber()");if(t instanceof Hu)return Xr("newData.isBoolean()");if(t instanceof Ks){const n=t.options;return Xr(n.map(r=>`newData.val() === "${r}"`).join(" || "))}if(t instanceof Cl){const n=t.value;return Xr(typeof n=="string"?`newData.val() === "${n}"`:`newData.val() === ${n}`)}if(t instanceof jl){const n=t._def.options;return vU(...n.map(r=>cA(r,e)))}if(t instanceof dt)return Xr("newData.hasChildren()");throw new Error(`Unsupported Zod type for RTDB rules: ${t.constructor.name} on field "${e}"`)}function SU(t){let e;if(typeof t=="function"){const s=[];t({path:(o,c)=>s.push([o,c])}),e=s}else e=Object.entries(t);const n=uA(e);n.sort((s,o)=>{const c=s[0]==="/"?0:s[0].split("/").filter(Boolean).length,d=o[0]==="/"?0:o[0].split("/").filter(Boolean).length;return c-d||s[0].localeCompare(o[0])});const r={path:"/",pathVariables:[],children:[]};for(const[s]of n)s!=="/"&&_U(r,s);for(const[s,o]of n){const c=s==="/"?r:ug(r,s);c&&EU(r,c,o,s)}return r}function _U(t,e){const n=e.split("/").filter(Boolean);let r=t;for(let s=0;s<n.length;s++){const o="/"+n.slice(0,s+1).join("/"),c=n.slice(0,s+1).filter(f=>f.startsWith("$"));let d=r.children.find(f=>f.path===o);d||(d={path:o,pathVariables:c,children:[]},r.children.push(d)),r=d}}function EU(t,e,n,r){const s=r.split("/").filter(o=>o.startsWith("$"));if(n.read&&(e.read=Da(n.read,"read",s)),n.write&&(e.write=Da(n.write,"write",s)),n.validate&&(e.validate=Da(n.validate,"validate",s)),n.schema){const o=lA(n.schema,n.fieldConstraints);e.validate||(e.validate=Da(o.validate,"validate",s));for(const[c,d]of Object.entries(o.children)){const f=`${r}/${c}`;let p=e.children.find(g=>g.path===f);if(p||(p={path:f,pathVariables:s,children:[]},e.children.push(p)),p.validate=Da(d.validate,"validate",s),"children"in d&&d.children)for(const[g,b]of Object.entries(d.children)){const v=`${f}/${g}`;let x=p.children.find(_=>_.path===v);x||(x={path:v,pathVariables:s,children:[]},p.children.push(x)),x.validate=Da(b.validate,"validate",s)}}}if(n.indexOn){const o=r.split("/").filter(Boolean),c=o[o.length-1];if(c!=null&&c.startsWith("$")){const d="/"+o.slice(0,-1).join("/"),f=ug(t,d);f&&(f.indexOn=n.indexOn)}}}function uA(t){const e=[];for(const[n,r]of t){const{children:s,...o}=r;if(e.push([n,o]),s){const c=Object.entries(s).map(([d,f])=>[n+d,f]);e.push(...uA(c))}}return e}function Da(t,e,n){return rA(String(t),e,n)}function ug(t,e){if(t.path===e)return t;for(const n of t.children){const r=ug(n,e);if(r)return r}return null}function AU(t){return t==null?null:typeof t=="string"?{uid:t,token:{}}:{uid:t.uid,token:t.token??{}}}function jU(t){return{operation:t.operation,path:t.path,auth:AU(t.auth),mockData:t.mockData??t.data??{},...t.newData!==void 0?{newData:t.newData}:{}}}function Gp(t,e,n,r){return((n==null?void 0:n.parsed[r])??[]).map(s=>({path:t,rule:e,code:s.code,message:s.message}))}function ry(t,e){const n=[...Gp(t.path,".read",t.read,e),...Gp(t.path,".write",t.write,e),...Gp(t.path,".validate",t.validate,e)];for(const r of t.children)n.push(...ry(r,e));return n}class kU{constructor(e){G(this,"definition");this.definition=e}compile(){return SU(this.definition.paths)}toJSON(){return bU(this.compile())}check(){try{const e=this.compile(),n=ry(e,"errors"),r=ry(e,"warnings");return{ok:n.length===0,errors:n,warnings:r}}catch(e){return{ok:!1,errors:[{path:"/",rule:"ruleset",code:"COMPILE_ERROR",message:e instanceof Error?e.message:String(e)}],warnings:[]}}}simulate(e){return cg(this.compile(),jU(e))}}function CU(t){return new kU(t)}function NU(t){const e=t;return typeof e.toJSON=="function"&&typeof e.simulate=="function"&&typeof e.check=="function"}function OU(t){const e=t;return typeof e=="object"&&e!==null&&"rules"in e&&!("paths"in e)&&typeof e.toJSON!="function"}class Kp{constructor(e){G(this,"doc");this.doc=e}lint(){const e=this.doc.check();return[...e.errors.map(n=>yS(n,"error")),...e.warnings.map(n=>yS(n,"warning"))]}runOne(e){const n=this.doc.simulate({operation:e.operation,path:e.path,auth:e.auth??null,...e.data!==void 0?{data:e.data}:{},...e.newData!==void 0?{newData:e.newData}:{}});if(!n.success)return{case:e,...e.description!==void 0?{description:e.description}:{},expectation:e.expectation,decision:"UNSUPPORTED",passed:!1,unsupported:!0,matchedPath:e.path,matchedRule:e.operation,reason:n.error.message};const r=n.data,s=r.unsupported===!0,o=s?"UNSUPPORTED":r.allowed?"ALLOW":"DENY",c=!s&&o===e.expectation;return{case:e,...e.description!==void 0?{description:e.description}:{},expectation:e.expectation,decision:o,passed:c,unsupported:s,matchedPath:r.matchedPath,matchedRule:r.matchedRule,reason:r.reason}}simulate(e){const n=e.map(c=>this.runOne(c));let r=0,s=0,o=0;for(const c of n)c.unsupported?o++:c.passed?r++:s++;return{passed:r,failed:s,unsupported:o,cases:n}}explain(e){const n=this.runOne(e);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 TU(t){return t==null?null:typeof t=="string"?{uid:t,token:{}}:{uid:t.uid,token:t.token??{}}}class RU{constructor(e){G(this,"json");G(this,"compiled");this.json=e,this.compiled=iA(e)}toJSON(){return this.json}compile(){return this.compiled}check(){return{ok:!0,errors:[],warnings:[]}}simulate(e){return cg(this.compiled,{operation:e.operation,path:e.path,auth:TU(e.auth),mockData:e.mockData??e.data??{},...e.newData!==void 0?{newData:e.newData}:{}})}}function DU(t){return NU(t)?new Kp(t):OU(t)?new Kp(new RU(t)):new Kp(CU(t))}const IU=new Set(["__proto__","prototype","constructor"]);function Je(t){if(t===""||t==="/")return[];const e=t.split("/").filter(n=>n.length>0);for(const n of e)if(IU.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 e}function en(t){return t.length===0?"/":"/"+t.join("/")}function Fs(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(n=>Fs(n));const e={};for(const[n,r]of Object.entries(t))e[n]=Fs(r);return e}function vS(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function za(t,e){if(Object.is(t,e))return!0;if(Array.isArray(t)||Array.isArray(e))return!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length?!1:t.every((s,o)=>za(s,e[o]));if(!vS(t)||!vS(e))return!1;const n=Object.keys(t),r=Object.keys(e);return n.length!==r.length?!1:n.every(s=>s in e&&za(t[s],e[s]))}class MU{constructor(){G(this,"root",{})}snapshot(){return Fs(this.root)}restore(e){this.root=Fs(e)}read(e){const n=Je(e);let r=this.root;for(const s of n){if(r===null||typeof r!="object"||Array.isArray(r))return null;const o=r;if(!Object.hasOwn(o,s))return null;r=o[s]}return Fs(r)}write(e,n){const r=Je(e),s=this.read(e);if(r.length===0)return n===null?(this.root={},s):(this.root=Fs(n),s);(this.root===null||typeof this.root!="object"||Array.isArray(this.root))&&(this.root={});let o=this.root;for(let d=0;d<r.length-1;d++){const f=r[d],p=Object.hasOwn(o,f)?o[f]:void 0;if(p==null||typeof p!="object"||Array.isArray(p)){const g={};o[f]=g,o=g}else o=p}const c=r[r.length-1];return n===null?(delete o[c],this.trim(r)):o[c]=Fs(n),s}multiUpdate(e){const r=Object.entries(e).map(([o,c])=>({path:en(Je(o)),value:c}));for(let o=0;o<r.length;o++)for(let c=o+1;c<r.length;c++){const d=r[o].path,f=r[c].path;if(d===f)throw new Error(`multi-path update: duplicate path '${d}'.`);const p=d==="/"?"/":d+"/",g=f==="/"?"/":f+"/";if(d!=="/"&&f.startsWith(p))throw new Error(`multi-path update: '${f}' is a descendant of '${d}'.`);if(f!=="/"&&d.startsWith(g))throw new Error(`multi-path update: '${d}' is a descendant of '${f}'.`)}const s=[];for(const{path:o,value:c}of r){const d=this.write(o,c);s.push({path:o,prior:d})}return s}shallowUpdate(e,n){const r=[],s=Je(e);for(const[o,c]of Object.entries(n)){const d=[...s,...Je(o)],f=en(d),p=this.write(f,c);r.push({path:f,prior:p})}return r}trim(e){if(!(this.root===null||typeof this.root!="object"||Array.isArray(this.root)))for(let n=e.length-1;n>=1;n--){const r=e.slice(0,n),s=e[n-1];let o=this.root;for(let d=0;d<r.length-1;d++){const f=o[r[d]];if(f==null||typeof f!="object"||Array.isArray(f))return;o=f}const c=o[s];if(c!==void 0&&typeof c=="object"&&c!==null&&!Array.isArray(c)&&Object.keys(c).length===0){delete o[s];continue}return}}}const xS="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz";let wS=0;const _i=new Array(12).fill(0);function LU(t=Date.now()){const e=t===wS;wS=t;const n=new Array(8);let r=t;for(let o=7;o>=0;o--)n[o]=xS.charAt(r%64),r=Math.floor(r/64);if(r!==0)throw new Error("RTDB push-id: timestamp overflow.");let s=n.join("");if(e){let o;for(o=11;o>=0&&_i[o]===63;o--)_i[o]=0;if(o<0)for(let c=0;c<12;c++)_i[c]=Math.floor(Math.random()*64);else _i[o]=(_i[o]??0)+1}else for(let o=0;o<12;o++)_i[o]=Math.floor(Math.random()*64);for(let o=0;o<12;o++)s+=xS.charAt(_i[o]);if(s.length!==20)throw new Error(`RTDB push-id: bad length ${s.length}.`);return s}function UU(t){return t===null||typeof t!="object"?!1:t[".sv"]==="timestamp"}function $U(t){if(t===null||typeof t!="object")return!1;const e=t[".sv"];return e!==null&&typeof e=="object"&&typeof e.increment=="number"}function gr(t,e,n){if(UU(t))return e;if($U(t)){const o=t[".sv"].increment;return(typeof n=="number"?n:0)+o}if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map((o,c)=>gr(o,e,Array.isArray(n)?n[c]:void 0));const r=n!==null&&typeof n=="object"&&!Array.isArray(n)?n:void 0,s={};for(const[o,c]of Object.entries(t))s[o]=gr(c,e,r?r[o]:void 0);return s}function Ei(){const t=new Error("PERMISSION_DENIED: Permission denied");return t.code="PERMISSION_DENIED",t}class BU{constructor(){G(this,"compiled",null)}setRules(e){if(e===null){this.compiled=null;return}this.compiled=iA(e)}hasRules(){return this.compiled!==null}check(e,n,r){return this.evaluate(e,n,r).check}evaluate(e,n,r){if(this.compiled===null)return{check:"allow",reasons:["No RTDB rules loaded; default allow."]};const s=r.auth===null?null:{uid:r.auth.uid,token:r.auth.token??{}},o=cg(this.compiled,{operation:e,path:n==="/"?"/":n,auth:s,mockData:r.mockData,newData:r.newData,updates:r.updates});return o.success?o.data.unsupported?{check:"unsupported",reasons:[`${o.data.matchedPath} ${e} UNSUPPORTED: ${o.data.reason}`],matchedPath:o.data.matchedPath,matchedRule:o.data.matchedRule,reason:o.data.reason,pathVariableBindings:o.data.pathVariableBindings}:{check:o.data.allowed?"allow":"deny",reasons:[`${o.data.matchedPath} ${e} ${o.data.allowed?"ALLOW":"DENY"}: ${o.data.reason}`],matchedPath:o.data.matchedPath,matchedRule:o.data.matchedRule,reason:o.data.reason,pathVariableBindings:o.data.pathVariableBindings}:o.error.code==="NO_MATCHING_RULE"?{check:"no-rule",reasons:[o.error.message],errorCode:o.error.code,errorMessage:o.error.message}:{check:"no-rule",reasons:[o.error.message],errorCode:o.error.code,errorMessage:o.error.message}}}function dA(t,e){if(t===e)return 0;if(t===null)return-1;if(e===null)return 1;const n=SS(t),r=SS(e);return n!==r?n-r:typeof t=="number"&&typeof e=="number"?t<e?-1:t>e?1:0:typeof t=="boolean"&&typeof e=="boolean"?t===e?0:t?1:-1:typeof t=="string"&&typeof e=="string"?t<e?-1:t>e?1:0:0}function SS(t){return t===null?0:typeof t=="boolean"?1:typeof t=="number"?2:typeof t=="string"?3:4}const FU=/^-?(0*)\d{1,10}$/,PU=-2147483648,qU=2147483647;function _S(t){if(FU.test(t)){const e=Number(t);if(e>=PU&&e<=qU)return e}return null}function hd(t,e){if(t===e)return 0;const n=_S(t),r=_S(e);return n!==null?r!==null?n-r===0?t.length-e.length:n-r:-1:r!==null?1:t<e?-1:1}function sy(t,e,n){const r=t??{kind:"key"};switch(r.kind){case"key":return e;case"value":return n;case"child":{if(n===null||typeof n!="object"||Array.isArray(n))return null;const s=r.path.split("/").filter(c=>c.length>0);let o=n;for(const c of s){if(o===null||typeof o!="object"||Array.isArray(o))return null;o=o[c]??null}return o}}}function Ia(t,e){if(t===null||typeof t!="object"||Array.isArray(t))return[];let r=Object.entries(t).map(([o,c])=>({key:o,value:c}));const s=(e.orderBy??{kind:"key"}).kind==="key";r.sort((o,c)=>{if(s)return hd(o.key,c.key);const d=sy(e.orderBy,o.key,o.value),f=sy(e.orderBy,c.key,c.value),p=dA(d,f);return p!==0?p:hd(o.key,c.key)});for(const o of e.bounds)r=r.filter(c=>zU(o,c,e.orderBy));if(e.limit){const o=e.limit.n;e.limit.kind==="limitToFirst"?r=r.slice(0,o):r=o>=r.length?r:r.slice(r.length-o)}return r}function zU(t,e,n){const s=(n??{kind:"key"}).kind==="key"?hd(e.key,String(t.value)):dA(sy(n,e.key,e.value),t.value),o=c=>hd(e.key,c);switch(t.kind){case"startAt":return s>0?!0:s<0?!1:t.key===void 0||o(t.key)>=0;case"startAfter":return s>0?!0:s<0||t.key===void 0?!1:o(t.key)>0;case"endAt":return s<0?!0:s>0?!1:t.key===void 0||o(t.key)<=0;case"endBefore":return s<0?!0:s>0||t.key===void 0?!1:o(t.key)<0;case"equalTo":return s!==0?!1:t.key===void 0||o(t.key)===0}}const VU=/[\[\].#$/\u0000-\u001F\u007F]/;function HU(t){return t.length!==0&&!VU.test(t)}function GU(t){return typeof t=="number"&&(Number.isNaN(t)||t===1/0||t===-1/0)}function KU(t){return t===".priority"||t===".value"||t===".sv"}function YU(t,e){iy(t,e,"set")}function iy(t,e,n){if(t===void 0)throw new Error(`${n} failed: value argument contains undefined in property '${e}'`);if(typeof t=="function")throw new Error(`${n} failed: value argument contains a function in property '${e}'`);if(GU(t))throw new Error(`${n} failed: value argument contains ${String(t)} in property '${e}'`);if(!(t===null||typeof t!="object")){if(Array.isArray(t)){for(let r=0;r<t.length;r++){if(!(r in t))continue;const s=t[r];s!==void 0&&iy(s,`${e}/${r}`,n)}return}for(const[r,s]of Object.entries(t)){if(!KU(r)&&!HU(r))throw new Error(`${n} failed: value argument contains an invalid key (${r}) in path ${e}. Keys must be non-empty strings and can't contain ".", "#", "$", "/", "[", or "]"`);iy(s,`${e}/${r}`,n)}}}function Is(t,e){return YU(t,e),ay(t)}function ay(t){if(t==null)return null;if(typeof t!="object")return t;if(Array.isArray(t)){const n={};for(let r=0;r<t.length;r++){if(!(r in t))continue;const s=ay(t[r]);s!==null&&(n[String(r)]=s)}return Object.keys(n).length===0?null:n}const e={};for(const[n,r]of Object.entries(t)){if(n===".sv"){e[n]=r;continue}const s=ay(r);s!==null&&(e[n]=s)}return Object.keys(e).length===0?null:e}function Iu(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(c=>Iu(c));const e=t,n=Object.keys(e);let r=n.length>0,s=0;for(const c of n)if(/^(0|[1-9]\d*)$/.test(c))s=Math.max(s,Number(c));else{r=!1;break}if(r&&s<2*n.length){const c=[];for(let d=0;d<=s;d++){const f=e[String(d)];c[d]=f===void 0?null:Iu(f)}return c}const o={};for(const[c,d]of Object.entries(e))o[c]=Iu(d);return o}function Wr(t){return t==="unsupported"?"unsupported":"deny"}class ZU{constructor(e){G(this,"tree",new MU);G(this,"rules",new BU);G(this,"activeRules",null);G(this,"valueListeners",new Set);G(this,"childListeners",new Set);G(this,"nextId",0);G(this,"writeSubscribers",new Set);G(this,"sandbox");this.sandbox=e}emitRtdbEvent(e,n,r,s={}){if(this.sandbox)try{Ps(this.sandbox,Td({service:"rtdb",op:n,path:r,auth:e,before:s.before,after:s.after,detail:s.detail}),{service:"rtdb"})}catch{}}nextListenerId(){return this.nextId+=1,`rtdb-listener-${this.nextId.toString(36)}`}nextGroupId(e){return this.nextId+=1,`rtdb-${e}-${this.nextId.toString(36)}`}emitOperation(e,n,r,s,o,c={}){if(this.sandbox)try{Ps(this.sandbox,yE({service:"rtdb",method:n,path:yr(r),auth:e,result:s,origin:c.origin??"user",durationMs:c.durationMs,reasons:o==null?void 0:o.reasons,rules:o?{engine:"rtdb",matchedPath:o.matchedPath,matchedRule:o.matchedRule,pathVariableBindings:o.pathVariableBindings,reason:o.reason,errorCode:o.errorCode}:void 0,request:c.request,resourceBefore:c.resourceBefore,resourceAfter:c.resourceAfter,groupId:c.groupId,groupKind:c.groupKind,triggeredBy:c.triggeredBy,detail:c.detail,at:c.at}),{service:"rtdb"})}catch{}}emitCommit(e,n,r,s={}){if(this.sandbox)try{Ps(this.sandbox,ZD({service:"rtdb",method:n,path:yr(r),auth:e,data:s.data,priorState:s.priorState,nextState:s.nextState,groupId:s.groupId,groupKind:s.groupKind,replay:s.replay,detail:s.detail}),{service:"rtdb"})}catch{}}emitListener(e,n,r,s={}){if(this.sandbox)try{Ps(this.sandbox,WD({service:"rtdb",phase:e,listenerId:n.id,target:{kind:s.event??"value",path:yr(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}),{service:"rtdb"})}catch{}}setData(e){this.tree.restore({});for(const[n,r]of Object.entries(e)){const s=Is(gr(r,Date.now()),n==="/"?"":n);this.tree.write(n,s)}this.notifyWrite()}setRules(e){this.rules.setRules(e),this.activeRules=e===null?null:structuredClone(e)}getActiveRules(){return this.activeRules===null?null:structuredClone(this.activeRules)}snapshotState(){return this.tree.snapshot()}adminGet(e){const n=this.tree.read(e);return this.emitOperation(null,"get",e,"not-applicable",void 0,{origin:"admin",resourceBefore:{data:n,exists:n!==null}}),n}adminGetQuery(e,n){const r=Ia(this.tree.read(e),n);return this.emitOperation(null,"get",e,"not-applicable",void 0,{origin:"admin",request:{query:n},resourceBefore:{data:mu(r),exists:r.length>0}}),r}adminSet(e,n){const r=Date.now(),s=this.tree.read(e),o=Is(gr(n,r,s),e==="/"?"":e);this.emitOperation(null,o===null?"remove":"set",e,"not-applicable",void 0,{origin:"admin",request:{data:n,resourceData:n},resourceBefore:{data:s,exists:s!==null},resourceAfter:{data:o,exists:o!==null}});const c=this.snapshotChildListenerParents();this.tree.write(e,o),this.fanOut([e]),this.fanOutChildren(c);const d=this.tree.read(e),f=d===null?"remove":"set";this.emitCommit(null,f,e,{data:n,priorState:s,nextState:d,replay:{requestTime:r},detail:{admin:!0}}),this.notifyWrite()}adminUpdate(e,n){const r=Date.now(),s=this.tree.read(e),o=Object.keys(n).some(g=>g.includes("/")),c=this.snapshotChildListenerParents();if(o){const g={};for(const[v,x]of Object.entries(n)){const _=en([...Je(e),...Je(v)]);g[_]=Is(gr(x,r,this.tree.read(_)),_)}this.emitOperation(null,"update",e,"not-applicable",void 0,{origin:"admin",request:{data:n,resourceData:n},resourceBefore:{data:s,exists:s!==null},detail:{admin:!0,multiPath:!0,paths:Object.keys(g)}}),this.tree.multiUpdate(g),this.fanOut(Object.keys(g)),this.fanOutChildren(c);const b=this.tree.read(e);this.emitCommit(null,"update",e,{data:n,priorState:s,nextState:b,replay:{requestTime:r},detail:{admin:!0,multiPath:!0,paths:Object.keys(g)}}),this.notifyWrite();return}const d={},f=[];for(const[g,b]of Object.entries(n)){const v=en([...Je(e),...Je(g)]);f.push(v),d[g]=Is(gr(b,r,this.tree.read(v)),v)}this.emitOperation(null,"update",e,"not-applicable",void 0,{origin:"admin",request:{data:n,resourceData:n},resourceBefore:{data:s,exists:s!==null},detail:{admin:!0,multiPath:!1,keys:Object.keys(d)}}),this.tree.shallowUpdate(e,d),this.fanOut(f),this.fanOutChildren(c);const p=this.tree.read(e);this.emitCommit(null,"update",e,{data:n,priorState:s,nextState:p,replay:{requestTime:r},detail:{admin:!0,multiPath:!1,keys:Object.keys(d)}}),this.notifyWrite()}adminRemove(e){this.adminSet(e,null)}get(e,n){const r=Date.now(),s=this.tree.read(n),o=this.rules.evaluate("read",n==="/"?"/":n,{auth:e,mockData:this.tree.snapshot()});if(o.check!=="allow")throw this.emitOperation(e,"get",n,Wr(o.check),o,{at:r,durationMs:Date.now()-r,resourceBefore:{data:s,exists:s!==null}}),Ei();return this.emitOperation(e,"get",n,"allow",o,{at:r,durationMs:Date.now()-r,resourceBefore:{data:s,exists:s!==null}}),this.tree.read(n)}set(e,n,r){this.setInternal(e,n,r,"set")}setInternal(e,n,r,s){const o=Date.now(),c=gr(r,o,this.tree.read(n)),d=Is(c,n==="/"?"":n),f=this.tree.read(n),p=Date.now(),g=this.rules.evaluate("write",n==="/"?"/":n,{auth:e,mockData:this.tree.snapshot(),newData:d}),b={data:f,exists:f!==null},v={data:d,exists:d!==null};if(g.check!=="allow")throw this.emitOperation(e,s,n,Wr(g.check),g,{at:p,durationMs:Date.now()-p,request:{data:r,resourceData:r},resourceBefore:b,resourceAfter:v}),Ei();this.emitOperation(e,s,n,"allow",g,{at:p,durationMs:Date.now()-p,request:{data:r,resourceData:r},resourceBefore:b,resourceAfter:v});const x=this.snapshotChildListenerParents();this.tree.write(n,d),this.fanOut([n]),this.fanOutChildren(x);const _=this.tree.read(n),k=_===null?"remove":s;this.emitCommit(e,k,n,{data:r,priorState:f,nextState:_,replay:{requestTime:o}}),this.emitRtdbEvent(e,k,yr(n),{before:f,after:_}),this.notifyWrite()}remove(e,n){this.setInternal(e,n,null,"remove")}update(e,n,r){const s=Date.now();if(Object.keys(r).some(x=>x.includes("/"))){const x=this.nextGroupId("update"),_={};for(const[q,I]of Object.entries(r)){const N=[...Je(n),...Je(q)],M=en(N);_[M]=Is(gr(I,s,this.tree.read(M)),M)}const k=this.tree.snapshot(),R=Object.entries(_).map(([q,I])=>({path:q,value:I}));for(const[q,I]of Object.entries(_)){const N=Date.now(),M=this.tree.read(q),L=this.rules.evaluate("write",q,{auth:e,mockData:k,newData:I,updates:R}),H={at:N,durationMs:Date.now()-N,origin:"batch",request:{data:I,resourceData:I},resourceBefore:{data:M,exists:M!==null},resourceAfter:{data:I,exists:I!==null},groupId:x,groupKind:"batch",detail:{multiPath:!0,rootPath:yr(n)}};if(L.check!=="allow")throw this.emitOperation(e,"update",q,Wr(L.check),L,H),Ei();this.emitOperation(e,"update",q,"allow",L,H)}const C=this.tree.read(n),T=this.snapshotChildListenerParents();this.tree.multiUpdate(_),this.fanOut(Object.keys(_)),this.fanOutChildren(T);const U=this.tree.read(n);this.emitCommit(e,"update",n,{data:r,priorState:C,nextState:U,groupId:x,groupKind:"batch",replay:{requestTime:s},detail:{multiPath:!0,paths:Object.keys(_)}}),this.emitRtdbEvent(e,"update",yr(n),{after:_,detail:{multiPath:!0,paths:Object.keys(_)}}),this.notifyWrite();return}const c={};for(const[x,_]of Object.entries(r)){const k=en([...Je(n),...Je(x)]);c[x]=Is(gr(_,s,this.tree.read(k)),k)}const d=this.tree.snapshot(),f=[],p=this.nextGroupId("update");for(const[x,_]of Object.entries(c)){const k=en([...Je(n),...Je(x)]);f.push(k);const R=Date.now(),C=this.tree.read(k),T=this.rules.evaluate("write",k,{auth:e,mockData:d,newData:_}),U={at:R,durationMs:Date.now()-R,origin:"batch",request:{data:_,resourceData:_},resourceBefore:{data:C,exists:C!==null},resourceAfter:{data:_,exists:_!==null},groupId:p,groupKind:"batch",detail:{multiPath:!1,rootPath:yr(n),key:x}};if(T.check!=="allow")throw this.emitOperation(e,"update",k,Wr(T.check),T,U),Ei();this.emitOperation(e,"update",k,"allow",T,U)}const g=this.tree.read(n),b=this.snapshotChildListenerParents();this.tree.shallowUpdate(n,c),this.fanOut(f),this.fanOutChildren(b);const v=this.tree.read(n);this.emitCommit(e,"update",n,{data:r,priorState:g,nextState:v,groupId:p,groupKind:"batch",replay:{requestTime:s},detail:{multiPath:!1,keys:Object.keys(c)}}),this.emitRtdbEvent(e,"update",yr(n),{after:c,detail:{multiPath:!1,keys:Object.keys(c)}}),this.notifyWrite()}onValue(e,n,r,s){const o=this.nextListenerId(),c=Date.now(),d=this.rules.evaluate("read",n==="/"?"/":n,{auth:e,mockData:this.tree.snapshot()});if(d.check!=="allow")throw this.emitOperation(e,"listen",n,Wr(d.check),d,{at:c,durationMs:Date.now()-c,request:s?{query:s}:void 0,origin:"listener"}),this.emitListener("errored",{id:o,path:n},e,{event:"value",result:"deny",error:{code:"PERMISSION_DENIED",message:"PERMISSION_DENIED: Permission denied",reasons:d.reasons}}),Ei();this.emitOperation(e,"listen",n,"allow",d,{at:c,durationMs:Date.now()-c,request:s?{query:s}:void 0,origin:"listener"});const f={id:o,auth:e,cb:r,path:n,query:s};if(this.valueListeners.add(f),this.emitListener("attach",f,e,{event:"value",result:"allow",detail:s?{query:s}:void 0}),s){const p=Ia(this.tree.read(n),s);f.lastWindow=p;const g={val:mu(p),exists:p.length>0,key:this.keyForPath(n)};try{r(g),this.emitListener("delivery",f,e,{event:"value",size:p.length,sample:g.val,detail:{initial:!0,query:!0}})}catch(b){this.emitListener("errored",f,e,{event:"value",result:"error",error:{message:b instanceof Error?b.message:String(b)},detail:{initial:!0,query:!0}})}}else{const p=this.makeSnap(n);f.lastValue=p.val;try{r(p),this.emitListener("delivery",f,e,{event:"value",size:p.exists?1:0,sample:p.val,detail:{initial:!0}})}catch(g){this.emitListener("errored",f,e,{event:"value",result:"error",error:{message:g instanceof Error?g.message:String(g)},detail:{initial:!0}})}}return()=>{this.valueListeners.delete(f),this.emitListener("detach",f,e,{event:"value"})}}getQuery(e,n,r){const s=Date.now(),o=this.rules.evaluate("read",n==="/"?"/":n,{auth:e,mockData:this.tree.snapshot()});if(o.check!=="allow")throw this.emitOperation(e,"get",n,Wr(o.check),o,{at:s,durationMs:Date.now()-s,request:{query:r}}),Ei();const c=Ia(this.tree.read(n),r);return this.emitOperation(e,"get",n,"allow",o,{at:s,durationMs:Date.now()-s,request:{query:r},resourceBefore:{data:mu(c),exists:c.length>0}}),c}keyForPath(e){const n=Je(e);return n.length===0?null:n[n.length-1]}makeSnap(e){const n=this.tree.read(e),r=n!==null,s=Je(e),o=s.length===0?null:s[s.length-1];return{val:n,exists:r,key:o}}fanOut(e){if(this.valueListeners.size===0)return;const n=e.map(r=>en(Je(r)));for(const r of this.valueListeners){const s=en(Je(r.path));if(!n.some(f=>{if(f===s)return!0;const p=s==="/"?"/":s+"/",g=f==="/"?"/":f+"/";return!!(s==="/"||f.startsWith(p)||s.startsWith(g))}))continue;if(r.query){const f=Ia(this.tree.read(r.path),r.query);if(WU(r.lastWindow??[],f)){this.emitListener("suppressed",r,r.auth,{event:"value",reason:"no-op",detail:{query:!0}});continue}r.lastWindow=f;const p={val:mu(f),exists:f.length>0,key:this.keyForPath(r.path)};this.emitListener("delivery",r,r.auth,{event:"value",size:f.length,sample:p.val,detail:{query:!0}});try{r.cb(p)}catch(g){this.emitListener("errored",r,r.auth,{event:"value",result:"error",error:{message:g instanceof Error?g.message:String(g)},detail:{query:!0}})}continue}const c=this.makeSnap(r.path),d=r.lastValue;if(d!==void 0&&za(d,c.val)){this.emitListener("suppressed",r,r.auth,{event:"value",reason:"no-op"});continue}r.lastValue=c.val,this.emitListener("delivery",r,r.auth,{event:"value",size:c.exists?1:0,sample:c.val});try{r.cb(c)}catch(f){this.emitListener("errored",r,r.auth,{event:"value",result:"error",error:{message:f instanceof Error?f.message:String(f)}})}}}runTransaction(e,n,r,s){const o=(s==null?void 0:s.applyLocally)!==!1,c=Je(n),d=c.length===0?null:c[c.length-1],f=this.tree.read(n),p=f===null?null:Iu(Fs(f)),g=r(p),b=this.nextGroupId("transaction");if(g===void 0)return this.emitOperation(e,"transaction",n,"not-applicable",void 0,{origin:"transaction",groupId:b,groupKind:"transaction",resourceBefore:{data:f,exists:f!==null},detail:{committed:!1,aborted:!0}}),{committed:!1,val:f,key:d};const v=Date.now(),x=Is(gr(g,v,f),n==="/"?"":n);if(o){const R=this.tree.snapshot();this.tree.write(n,x),this.fanOut([n]);const C=Date.now(),T=this.rules.evaluate("write",n==="/"?"/":n,{auth:e,mockData:R,newData:x});if(T.check!=="allow")throw this.emitOperation(e,"transaction",n,Wr(T.check),T,{at:C,durationMs:Date.now()-C,origin:"transaction",request:{data:g,resourceData:g},resourceBefore:{data:f,exists:f!==null},resourceAfter:{data:x,exists:x!==null},groupId:b,groupKind:"transaction"}),this.tree.restore(R),this.fanOut([n]),ES();return this.emitOperation(e,"transaction",n,"allow",T,{at:C,durationMs:Date.now()-C,origin:"transaction",request:{data:g,resourceData:g},resourceBefore:{data:f,exists:f!==null},resourceAfter:{data:x,exists:x!==null},groupId:b,groupKind:"transaction"}),this.emitCommit(e,"transaction",n,{data:g,priorState:f,nextState:x,groupId:b,groupKind:"transaction",replay:{requestTime:v},detail:{committed:!0,applyLocally:!0}}),this.emitRtdbEvent(e,"transaction",yr(n),{before:f,after:x,detail:{committed:!0}}),this.notifyWrite(),{committed:!0,val:x,key:d}}const _=Date.now(),k=this.rules.evaluate("write",n==="/"?"/":n,{auth:e,mockData:this.tree.snapshot(),newData:x});if(k.check!=="allow")throw this.emitOperation(e,"transaction",n,Wr(k.check),k,{at:_,durationMs:Date.now()-_,origin:"transaction",request:{data:g,resourceData:g},resourceBefore:{data:f,exists:f!==null},resourceAfter:{data:x,exists:x!==null},groupId:b,groupKind:"transaction"}),ES();return this.emitOperation(e,"transaction",n,"allow",k,{at:_,durationMs:Date.now()-_,origin:"transaction",request:{data:g,resourceData:g},resourceBefore:{data:f,exists:f!==null},resourceAfter:{data:x,exists:x!==null},groupId:b,groupKind:"transaction"}),this.tree.write(n,x),this.fanOut([n]),this.emitCommit(e,"transaction",n,{data:g,priorState:f,nextState:x,groupId:b,groupKind:"transaction",replay:{requestTime:v},detail:{committed:!0,applyLocally:!1}}),this.emitRtdbEvent(e,"transaction",yr(n),{before:f,after:x,detail:{committed:!0}}),{committed:!0,val:x,key:d}}onChild(e,n,r,s,o){const c=this.nextListenerId(),d=Date.now(),f=this.rules.evaluate("read",r==="/"?"/":r,{auth:e,mockData:this.tree.snapshot()});if(f.check!=="allow")throw this.emitOperation(e,"listen",r,Wr(f.check),f,{at:d,durationMs:Date.now()-d,origin:"listener",detail:{event:n}}),this.emitListener("errored",{id:c,path:r},e,{event:n,result:"deny",error:{code:"PERMISSION_DENIED",message:"PERMISSION_DENIED: Permission denied",reasons:f.reasons}}),Ei();this.emitOperation(e,"listen",r,"allow",f,{at:d,durationMs:Date.now()-d,origin:"listener",detail:{event:n}});const p={id:c,auth:e,event:n,path:r,cb:s,spec:o};if(this.childListeners.add(p),this.emitListener("attach",p,e,{event:n,result:"allow",detail:o?{query:o}:void 0}),o){const g=Ia(this.tree.read(r),o);if(p.lastWindow=g,n==="child_added")for(const{key:b,value:v}of g){this.emitListener("delivery",p,e,{event:n,size:1,sample:{key:b,val:v},detail:{initial:!0,query:!0}});try{s({key:b,val:v})}catch(x){this.emitListener("errored",p,e,{event:n,result:"error",error:{message:x instanceof Error?x.message:String(x)},detail:{initial:!0,query:!0}})}}}else if(n==="child_added")for(const{key:g,val:b}of this.directChildren(r)){this.emitListener("delivery",p,e,{event:n,size:1,sample:{key:g,val:b},detail:{initial:!0}});try{s({key:g,val:b})}catch(v){this.emitListener("errored",p,e,{event:n,result:"error",error:{message:v instanceof Error?v.message:String(v)},detail:{initial:!0}})}}return()=>{this.childListeners.delete(p),this.emitListener("detach",p,e,{event:n})}}off(e,n,r){const s=en(Je(e));if(n===void 0||n==="value")for(const d of[...this.valueListeners])en(Je(d.path))===s&&(r!==void 0&&d.cb!==r||(this.valueListeners.delete(d),this.emitListener("detach",d,d.auth,{event:"value"})));const c=n===void 0?["child_added","child_changed","child_removed","child_moved"]:n==="value"?[]:[n];if(c.length>0)for(const d of[...this.childListeners])c.includes(d.event)&&en(Je(d.path))===s&&(r!==void 0&&d.cb!==r||(this.childListeners.delete(d),this.emitListener("detach",d,d.auth,{event:d.event})))}directChildren(e){const n=this.tree.read(e);if(n===null||typeof n!="object"||Array.isArray(n))return[];const r=[];for(const[s,o]of Object.entries(n))r.push({key:s,val:o});return r}snapshotChildListenerParents(){const e=new Map;if(this.childListeners.size===0)return e;for(const n of this.childListeners){const r=en(Je(n.path));if(e.has(r))continue;const s=new Map;for(const{key:o,val:c}of this.directChildren(r))s.set(o,c);e.set(r,s)}return e}fanOutChildren(e){if(this.childListeners.size===0)return;const n=new Map;for(const r of this.childListeners){if(r.spec){this.fanOutQueryChild(r);continue}const s=en(Je(r.path)),o=n.get(s)??[];o.push(r),n.set(s,o)}for(const[r,s]of n){const o=e.get(r)??new Map,c=new Map;for(const{key:g,val:b}of this.directChildren(r))c.set(g,b);const d=[],f=[],p=[];for(const[g,b]of c)o.has(g)?za(o.get(g),b)||f.push({key:g,val:b}):d.push({key:g,val:b});for(const[g,b]of o)c.has(g)||p.push({key:g,val:b});for(const g of s){let b;switch(g.event){case"child_added":b=d;break;case"child_changed":b=f;break;case"child_removed":b=p;break;case"child_moved":b=[];break}for(const v of b){this.emitListener("delivery",g,g.auth,{event:g.event,size:1,sample:v});try{g.cb(v)}catch(x){this.emitListener("errored",g,g.auth,{event:g.event,result:"error",error:{message:x instanceof Error?x.message:String(x)}})}}}}}fanOutQueryChild(e){const n=e.lastWindow??[],r=Ia(this.tree.read(e.path),e.spec);e.lastWindow=r;const s=new Map(n.map(d=>[d.key,d.value])),o=new Map(r.map(d=>[d.key,d.value]));let c=[];switch(e.event){case"child_added":for(const{key:d,value:f}of r)s.has(d)||c.push({key:d,val:f});break;case"child_changed":for(const{key:d,value:f}of r)s.has(d)&&!za(s.get(d),f)&&c.push({key:d,val:f});break;case"child_removed":for(const{key:d,value:f}of n)o.has(d)||c.push({key:d,val:f});break;case"child_moved":c=[];break}for(const d of c){this.emitListener("delivery",e,e.auth,{event:e.event,size:1,sample:d,detail:{query:!0}});try{e.cb(d)}catch(f){this.emitListener("errored",e,e.auth,{event:e.event,result:"error",error:{message:f instanceof Error?f.message:String(f)},detail:{query:!0}})}}}exportTree(){return this.tree.snapshot()}restoreTree(e){const n=this.snapshotChildListenerParents();this.tree.restore(e??{}),this.fanOut(["/"]),this.fanOutChildren(n)}subscribeWrites(e){return this.writeSubscribers.add(e),()=>{this.writeSubscribers.delete(e)}}notifyWrite(){if(this.writeSubscribers.size!==0)for(const e of this.writeSubscribers)try{e()}catch{}}mintKey(){return LU()}listenerCount(){return this.valueListeners.size}childListenerCount(){return this.childListeners.size}}function yr(t){return en(Je(t))}function ES(){return new Error("permission_denied")}function mu(t){if(t.length===0)return null;const e={};for(const{key:n,value:r}of t)e[n]=r;return e}function WU(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++){const r=t[n],s=e[n];if(r.key!==s.key||!za(r.value,s.value))return!1}return!0}const AS=new WeakMap;function fA(t){let e=AS.get(t);if(e)return e;e=new ZU(t),AS.set(t,e);const n=e;return t.registerPersistableService("rtdb",{snapshot:()=>n.exportTree(),restore:r=>{n.restoreTree(r)},subscribe:r=>n.subscribeWrites(r)}),e}function JU(t){return fA(t).getActiveRules()}function jS(t){return fA(t).snapshotState()}function QU(t,e){return t==="/"?`/${e}`:`${t}/${e}`}function kS(t){return t===null?"null":Array.isArray(t)?"array":typeof t}function XU(t){const e=(t??"/").split("/").filter(Boolean);return e.length===0?"/":`/${e.join("/")}`}function e3(t,e){let n=t;for(const r of e.split("/").filter(Boolean)){if(n===null||typeof n!="object"||Array.isArray(n))return null;n=n[r]}return n??null}function hA(t,e,n,r,s){if(t===null||typeof t!="object"||Array.isArray(t))return{path:e,childCount:0,truncated:!1,children:[],schema:{},valueType:kS(t)};const o=Object.entries(t).sort(([b],[v])=>b.localeCompare(v)),c={},d=[];for(const[b,v]of o)v!==null&&typeof v=="object"&&!Array.isArray(v)?d.push([b,v]):c[b]=kS(v);const f=n>=r&&d.length>0,p=o.length>s,g=n>=r?[]:d.slice(0,s).map(([b,v])=>hA(v,QU(e,b),n+1,r,s));return{path:e,childCount:o.length,truncated:f||p,children:g,schema:c}}function t3(t,e={}){const n=XU(e.path),r=e.maxDepth??10,s=e.maxChildren??100;return hA(e3(t,n),n,0,r,s)}function pA(t){return t.children.reduce((e,n)=>e+1+pA(n),0)}function mA(t){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(e){const n=e,r=await t.resolveSandbox(),s=JU(r);if(!s)return{ok:!1,summary:"No RTDB rules are loaded in the local sandbox.",data:{code:"NO_ACTIVE_RULES"}};const o=jS(r),c=o!==null&&typeof o=="object"&&!Array.isArray(o)?o:{},d={expectation:"ALLOW",operation:n.operation,path:n.path,auth:n.auth?{uid:n.auth.uid,token:n.auth.claims??{}}:null,data:c,...n.newData!==void 0?{newData:n.newData}:{}},f=DU(s).simulate([d]).cases[0];return{ok:!f.unsupported,summary:f.unsupported?`Simulation unsupported: ${f.reason}`:`Simulation: ${f.decision.toLowerCase()}`,data:{decision:f.decision,allowed:f.decision==="ALLOW",unsupported:f.unsupported,matchedPath:f.matchedPath,matchedRule:f.matchedRule,reason:f.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(e){const n=e,r=await t.resolveSandbox(),s=t3(jS(r),n);return{ok:!0,summary:`Crawled ${pA(s)} object paths from ${s.path}`,data:s}}}]}function n3(t){const e=nn(t),n=r=>r&&r!=="admin"?Ud(t.withAuth({uid:r.uid,token:r.claims})):ag(t);return[...AE({resolveSandbox:()=>e}),...QE({resolveDb:n}),...XE({resolveSandbox:()=>t}),...mA({resolveSandbox:()=>t})]}function r3(t){const e=new Map(n3(t).map(n=>[n.name,n]));return async(n,r)=>{const s=e.get(n);if(!s)throw new a3(n);const o={signal:new AbortController().signal},c=await s.execute(r,o);return{ok:c.ok,summary:c.summary,data:c.data}}}const CS=new WeakMap;async function s3(t,e,n){let r=CS.get(t);return r||(r=r3(t),CS.set(t,r)),r(e,n)}const i3=(()=>{const t=async()=>{throw new Error("SANDBOX_TOOL_NAMES: stub resolver should never be invoked")};return[...AE({resolveSandbox:t}),...QE({resolveDb:t}),...XE({resolveSandbox:t}),...mA({resolveSandbox:t})].map(e=>e.name)})();class a3 extends Error{constructor(n){super(`unknown sandbox tool: ${n}`);G(this,"tool");this.tool=n,this.name="UnknownToolError"}}const o3=500,l3=3e4,c3=2e3,u3=.5,d3=3;function f3(t,e={}){const n=h3(e.url),r=e.sandboxId??p3(),s=e.dispatcher??s3,o=e.toolNames??[...i3],c=e.initialReconnectDelayMs??o3,d=e.maxReconnectDelayMs??l3,f=e.noReconnect??!1,p=e.onStateChange??(()=>{}),g=e.standbyPollMs??c3,b=e.fetchImpl??($=>fetch($)),v=e.workerRelay??null;let x=null,_=!1,k=0,R=null,C=null,T=0,U={kind:"connecting"};const q=new Map;function I(){for(const $ of q.values())try{$()}catch{}q.clear()}function N($){U=$;try{p($)}catch{}}function M($){if(x&&x.readyState===WebSocket.OPEN)try{x.send(JSON.stringify($))}catch{}}function L(){if(_)return;N({kind:"connecting"});let $;try{$=new WebSocket(n)}catch(K){z(`failed to open WebSocket: ${K instanceof Error?K.message:String(K)}`);return}x=$,$.onopen=()=>{k=0;const K={type:"hello",protocol:1,tools:o,sandboxId:r,...v?{capabilities:[LM]}:{}};M(K)},$.onmessage=K=>{let W;try{W=JSON.parse(typeof K.data=="string"?K.data:"")}catch{return}if(UM(W)){if(W.type==="hello-ack"){N({kind:"connected",bridgeVersion:W.bridgeVersion});return}if(W.type==="tool-call"){H(W);return}if(W.type==="worker-op"){P(W);return}if(W.type==="worker-sub"){F(W);return}if(W.type==="worker-unsub"){const se=q.get(W.subId);if(se){q.delete(W.subId);try{se()}catch{}}return}if(W.type==="ping"){M({type:"pong",id:W.id});return}}},$.onclose=K=>{const W=K.reason||`closed (code ${K.code})`;if(x=null,I(),K.code===MM){E();return}z(W)},$.onerror=()=>{}}async function H($){let K;try{const W=await s(t,$.name,$.args??{});K={type:"tool-result",id:$.id,ok:!0,result:W}}catch(W){K={type:"tool-result",id:$.id,ok:!1,error:{code:W instanceof Error?W.name:"Error",message:W instanceof Error?W.message:String(W)}}}M(K)}async function P($){if(v)try{const K=await v.op($.op);Ww(`op '${$.op.method}'`,K),M({type:"worker-res",id:$.id,ok:!0,value:K})}catch(K){const W=K.denialContext;M({type:"worker-res",id:$.id,ok:!1,error:{code:K.code??"unknown",message:K instanceof Error?K.message:String(K),...W!==void 0?{denialContext:W}:{}}})}}function F($){if(v&&!q.has($.subId))try{const K=v.subscribe($.sub,W=>{try{Ww(`subscription '${$.subId}'`,W)}catch(se){M({type:"worker-snap",subId:$.subId,value:{__error:{code:se.code??"invalid-argument",message:se instanceof Error?se.message:String(se)}}});return}M({type:"worker-snap",subId:$.subId,value:W})});q.set($.subId,K)}catch(K){const W=K.denialContext;M({type:"worker-snap",subId:$.subId,value:{__error:{code:K.code??"unknown",message:K instanceof Error?K.message:String(K),...W!==void 0?{denialContext:W}:{}}}})}}function w(){try{const $=new URL(n);$.protocol=$.protocol==="wss:"?"https:":"http:";const K=$.origin;return[`${K}/__pyric/health`,`${K}/health`]}catch{return[]}}function E(){if(!_){if(f){N({kind:"disconnected",reason:"replaced by a newer sandbox peer"});return}k=0,T=0,N({kind:"standby"}),O()}}function O(){if(_)return;const $=g*(1+Math.random()*u3);C=setTimeout(()=>{C=null,D()},$)}async function D(){if(_)return;let $=null;for(const K of w())try{const W=await b(K);if(!W.ok)continue;const se=await W.json();if(typeof se.sandboxConnected=="boolean"){$=!se.sandboxConnected;break}}catch{}if(!_){if($===!0){L();return}if($===!1){T=0,O();return}if(T+=1,T>=d3){z("standby health poll unreachable");return}O()}}function z($){if(_)return;if(f){N({kind:"disconnected",reason:$});return}k+=1;const K=Math.min(c*2**(k-1),d);N({kind:"reconnecting",attempt:k,delayMs:K}),R=setTimeout(()=>{R=null,L()},K)}return L(),{disconnect(){if(_=!0,I(),R&&(clearTimeout(R),R=null),C&&(clearTimeout(C),C=null),x){try{x.close()}catch{}x=null}N({kind:"disconnected",reason:"client closed"})},state(){return U}}}function h3(t){if(t)return t;if(typeof window<"u"){const e=window.__PYRIC_BRIDGE_URL__;if(e)return e;const n=window.location.hostname||"localhost";return`${window.location.protocol==="https:"?"wss:":"ws:"}//${n}:${Yw}${Zw}`}return`ws://localhost:${Yw}${Zw}`}function p3(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`sb-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function m3(t,e){try{const n=new URL(t,e.href).pathname;return`${e.protocol==="https:"?"wss:":"ws:"}//${e.host}${n}`}catch{return t}}function y3(t,e){return{url:e,dispatcher:(n,r,s)=>II(t,r,s),workerRelay:{op:n=>MI(t,n),subscribe:(n,r)=>LI(t,n,r)}}}async function g3(t,e={}){const n=e.baseUrl??"",r=e.fetchImpl??(typeof fetch<"u"?fetch:null),s=p=>{var g;return(g=e.onStateChange)==null?void 0:g.call(e,{kind:"disconnected",reason:p})};if(!r)return s("no fetch available"),null;let o;try{const p=await r(`${n}/__pyric/init.json`);if(!p.ok)return s("not served"),null;o=(await p.json()).bridgeUrl??null}catch{return s("not served"),null}if(!o)return s("bridge off"),null;const c=e.locationLike??(typeof window<"u"?window.location:null),d=c?m3(o,c):o,f=f3(null,{...y3(t,d),...e.onStateChange?{onStateChange:e.onStateChange}:{},...e.initialReconnectDelayMs!==void 0?{initialReconnectDelayMs:e.initialReconnectDelayMs}:{},...e.maxReconnectDelayMs!==void 0?{maxReconnectDelayMs:e.maxReconnectDelayMs}:{}});return console.info("[pyric studio] registered as the sandbox bridge peer at",d),f}const b3={};function v3(){return!1}function x3(){let t={kind:"connecting"};const e=new Set;return{get:()=>t,subscribe(n){return e.add(n),()=>e.delete(n)},set(n){t=n;for(const r of e)r()}}}function w3(t,e={}){if(t==="local"){const n=e.baseUrl??"",r=v3(),s=e.persistence==="memory"||r?Im():oI(n),o=e.disableLive?null:IM(e.workerUrl),c=o?x3():null;return o&&c&&g3(o.db,{baseUrl:n,onStateChange:d=>c.set(d)}),{mode:t,projects:r?uI():iI(n),persistence:s,...o?{live:o}:{},...c?{bridge:c}:{}}}throw new Error(`createStudioEnvironment(${t}): only 'local' is wired in v1 (T3). 'browser'/'hosted' land in A3.`)}const yA=A.createContext(null);function S3(t){try{return{status:"ready",env:w3(t),error:null}}catch(e){return{status:"error",env:null,error:e instanceof Error?e:new Error(String(e))}}}function _3({mode:t="local",children:e}){const n=A.useMemo(()=>S3(t),[t]);return h.jsx(yA.Provider,{value:n,children:e})}function dr(){const t=A.useContext(yA);if(!t)throw new Error("useEnvironment must be used within an <EnvironmentProvider>");return t}const E3="pyric-studio:theme",Mu="dark";function A3(){return Mu}function j3(){typeof document>"u"||document.documentElement.setAttribute("data-theme","dark")}const k3=A.createContext(null);function C3({children:t}){const[e,n]=A.useState(A3);A.useEffect(()=>{j3();try{localStorage.setItem(E3,Mu)}catch{}},[e]);const r="dark",s=A.useCallback(d=>n(Mu),[]),o=A.useCallback(()=>n(Mu),[]),c=A.useMemo(()=>({choice:e,resolvedTheme:r,setChoice:s,cycleChoice:o}),[e,r,s,o]);return h.jsx(k3.Provider,{value:c,children:t})}function gA(){const t=typeof import.meta<"u"&&"/__pyric/ui/"||"/";return t.endsWith("/")?t:`${t}/`}function N3(t){const e={};for(const n of t.replace(/^\?/,"").split("&")){if(!n)continue;const r=n.indexOf("="),s=r===-1?n:n.slice(0,r),o=r===-1?"":n.slice(r+1);s&&(e[decodeURIComponent(s)]=decodeURIComponent(o))}return e}function dg(t,e="",n=gA()){let r=t;const s=n.replace(/\/$/,"");n!=="/"&&(t===s||t.startsWith(n))&&(r=t.slice(s.length));const o=r.split("/").filter(Boolean).map(f=>decodeURIComponent(f)),[c="",...d]=o;return{tab:c,rest:d,query:N3(e)}}function O3(t,e=gA()){const n=[t.tab,...t.rest??[]].filter(s=>s!=null&&s!=="").map(s=>encodeURIComponent(s)).join("/"),r=Object.entries(t.query??{}).filter(([,s])=>s!=null&&s!=="").map(([s,o])=>`${encodeURIComponent(s)}=${encodeURIComponent(String(o))}`).join("&");return`${e}${n}${r?`?${r}`:""}`}const oy="pyric:studio:navigated",T3={tab:"",rest:[],query:{}};function bA(){return typeof window<"u"?window.location.pathname+window.location.search:""}function Nr(){return typeof window>"u"?T3:dg(window.location.pathname,window.location.search)}function R3(t){return t.tab==="home"?{...t,tab:""}:t}function Bd(t){return O3(R3(t))}function vA(){typeof window<"u"&&window.dispatchEvent(new Event(oy))}function Jn(t){if(typeof window>"u")return;const e=Bd(t);bA()!==e&&(window.history.pushState(null,"",e),vA())}function pd(t){typeof window>"u"||(window.history.replaceState(null,"",Bd(t)),vA())}function Vl(t){return typeof window>"u"?()=>{}:(window.addEventListener("popstate",t),window.addEventListener(oy,t),()=>{window.removeEventListener("popstate",t),window.removeEventListener(oy,t)})}function D3(t,e){const n=A.useCallback(o=>t.includes(o)?o:e,[t,e]),r=A.useSyncExternalStore(Vl,()=>n(Nr().tab),()=>e);A.useEffect(()=>{const o=typeof window<"u"?window.location.hash:"";if(o.length>1){const d=o.slice(1),f=d.indexOf("?"),p=dg(`/${f===-1?d:d.slice(0,f)}`,f===-1?"":d.slice(f),"/");if(t.includes(p.tab)){pd(p);return}}const c=Nr();c.tab!==""&&!t.includes(c.tab)&&pd({tab:n(c.tab)})},[n]);const s=A.useCallback(o=>{const c=n(o);c!==r&&Jn({tab:c})},[n,r]);return[r,s]}let ly=null;function I3(t){ly=t}function M3(){return ly?(ly(),!0):!1}function L3(t){return(t.metaKey||t.ctrlKey)&&!t.altKey&&!t.shiftKey&&(t.key==="k"||t.key==="K")}const U3=[{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 $3({assuranceEnabled:t=!1}={}){return U3.filter(e=>e.id!=="assurance"||t)}const Ui=$3({assuranceEnabled:!1}),B3=Ui.map(t=>t.id);function F3(t){return Ui.find(e=>e.id===t)??Ui[0]}function P3(t,e){const n=t.toLowerCase(),r=e.toLowerCase();let s=0;for(const o of r)if(o===n[s]&&s++,s===n.length)return!0;return s===n.length}const q3=7;function z3(t,e){const n=t.trim();if(!n)return[];const r=e.filter(b=>b.id!=="settings"),s=[],o=[],c=[],[d="",...f]=n.split(/\s+/),p=f.join(" ");for(const b of r){const v={id:`tab:${b.id}`,label:`Go to ${b.label}`,hint:b.description,target:{tab:b.id}},x=b.label.toLowerCase();if(x.startsWith(n.toLowerCase())?s.push(v):P3(n,b.label)&&o.push(v),p&&(x===d.toLowerCase()||x.startsWith(d.toLowerCase()))){const _=p.split("/").filter(Boolean);b.id==="firestore"||b.id==="storage"?c.push({id:`deep:${b.id}:${p}`,label:`Open /${_.join("/")} in ${b.label}`,hint:b.id==="firestore"?"Firestore path":"Storage object path",target:{tab:b.id,rest:_}}):b.id==="auth"?c.push({id:`deep:auth:${p}`,label:`Open user ${p} in Auth`,hint:"Auth uid",target:{tab:"auth",rest:[p]}}):b.id==="traffic"&&c.push({id:`deep:traffic:${p}`,label:`Open ${p} in the rules inspector`,hint:"Traffic event id",target:{tab:"traffic",query:{inspect:p}}})}}const g=n.match(/^gs:\/\/[^/]+\/(.+)$/);if(g){const b=g[1].split("/").filter(Boolean);c.unshift({id:`deep:storage:${g[1]}`,label:`Open ${g[1]} in Storage`,hint:"Storage object path",target:{tab:"storage",rest:b}})}else if(n.includes("/")&&!n.includes(" ")){const b=n.split("/").filter(Boolean);b.length&&c.push({id:`deep:firestore:${n}`,label:`Open /${b.join("/")} in Firestore`,hint:"Firestore path",target:{tab:"firestore",rest:b}})}return[...s,...c,...o].slice(0,q3)}function cy(t){return`${t.kind}:${t.target.tab}:${(t.target.rest??[]).join("/")}`}const uy={docsPerCollection:50,collectionsScanned:20,users:100,objects:200,storageListCalls:20,subcollections:30,subcollectionRpcCalls:40};async function V3(t,e,{maxObjects:n,maxListCalls:r}){const s=[],o=[t];let c=0;for(;o.length&&s.length<n&&c<r;){c++;const d=await e(o.shift());for(const f of d.items){if(s.length>=n)break;s.push(f.fullPath)}o.push(...d.prefixes)}return s}async function H3(t,e,n,{maxSubcollections:r,maxRpcCalls:s,docsPerCollection:o}){const c=[],d=[],f=[...t];let p=0;for(;f.length&&c.length<r&&p<s;){const g=f.shift();p++;let b=[];try{b=await e(g)}catch{continue}for(const v of b){if(c.length>=r)break;const x=`${g}/${v}`;c.push(x);try{const _=await n(x,o);for(const k of _.slice(0,o))d.push(k),f.push(k)}catch{}}}return{subcollections:c,documents:d}}const G3=5;function md(t,e){const n=t.toLowerCase(),r=e.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 o=0,c=-1,d=-1;for(let p=0;p<r.length&&o<n.length;p++)r[p]===n[o]&&(c===-1&&(c=p),d=p,o++);if(o!==n.length)return 0;const f=d-c+1;return Math.max(1,400-(f-n.length)*10-Math.min(c,50))}const K3={collection:"Firestore collections",document:"Firestore documents",subcollection:"Firestore subcollections",user:"Auth users",object:"Storage objects","rtdb-key":"RTDB keys"},Y3=["collection","document","subcollection","user","object","rtdb-key"];function Z3(t){switch(t.kind){case"collection":return"Firestore collection";case"document":return"Firestore document";case"subcollection":return t.alt?`Subcollection of /${t.alt}`:"Subcollection";case"user":return t.alt?`Auth user · uid ${t.alt}`:"Auth user";case"object":return"Storage object";case"rtdb-key":return"RTDB top-level key"}}function xA(t){return t.endsWith("/")?{base:t.slice(0,-1),trailing:!0}:{base:t,trailing:!1}}function W3(t,e){const{base:n,trailing:r}=xA(t);if(!n)return 0;const s=n.split("/"),o=e.split("/");if(s.length>o.length)return 0;const c=s.length-1;for(let d=0;d<c;d++)if(s[d].toLowerCase()!==o[d].toLowerCase())return 0;return r?s[c].toLowerCase()===o[c].toLowerCase()?850:0:md(s[c],o[c])}function J3(t,e){const{base:n,trailing:r}=xA(t);if(!n||n.includes("/"))return 0;const s=e.split("/").pop()??e;return r?s.toLowerCase()===n.toLowerCase()?850:0:md(n,s)}function NS(t,e,n,r=G3){const s=t.trim();if(!s)return[];const o=[],c=z3(t,e);c.length&&o.push({kind:"navigate",title:"Go to",results:c});for(const d of Y3){const f=d==="document"||d==="subcollection",p=d==="collection"||d==="subcollection",g=new Map;for(const v of n)v.kind===d&&g.set(cy(v),v);const b=[...g.values()].map(v=>({entry:v,score:Math.max(md(s,v.label),v.alt?md(s,v.alt):0,f?W3(s,v.label):0,p?J3(s,v.label):0)})).filter(v=>v.score>0).sort((v,x)=>x.score-v.score||v.entry.label.localeCompare(x.entry.label)).slice(0,r);b.length&&o.push({kind:d,title:K3[d],results:b.map(({entry:v})=>({id:cy(v),label:v.label,hint:Z3(v),target:v.target}))})}return o}function OS(t){return t.flatMap(e=>e.results)}function Q3(t){return{kind:"collection",label:t,target:{tab:"firestore",rest:[t]}}}function TS(t){return{kind:"document",label:t,target:{tab:"firestore",rest:t.split("/").filter(Boolean)}}}function X3(t){const e=t.split("/").filter(Boolean),n=e.slice(0,-1).join("/");return{kind:"subcollection",label:t,alt:n||void 0,target:{tab:"firestore",rest:e}}}function e$(t){return t.email?{kind:"user",label:t.email,alt:t.uid,target:{tab:"auth",rest:[t.uid]}}:{kind:"user",label:t.uid,target:{tab:"auth",rest:[t.uid]}}}function t$(t){return{kind:"object",label:t,target:{tab:"storage",rest:t.split("/").filter(Boolean)}}}function n$(t){return{kind:"rtdb-key",label:t,target:{tab:"rtdb",rest:[t]}}}async function r$(t,e={},n){const r={...uy,...e},s=[],o=g=>{g.length&&(s.push(...g),n==null||n(g))},c=(async()=>{var v;let g=[];try{g=await((v=t.listRootCollections)==null?void 0:v.call(t))??[]}catch{g=[]}g.length&&o(g.map(Q3));const b=[];if(t.listDocumentPaths)for(const x of g.slice(0,r.collectionsScanned))try{const k=(await t.listDocumentPaths(x,r.docsPerCollection)).slice(0,r.docsPerCollection);b.push(...k),o(k.map(TS))}catch{}if(t.listSubcollections&&t.listDocumentPaths)try{const{subcollections:x,documents:_}=await H3(b,t.listSubcollections,t.listDocumentPaths,{maxSubcollections:r.subcollections,maxRpcCalls:r.subcollectionRpcCalls,docsPerCollection:r.docsPerCollection});o(x.map(X3)),o(_.map(TS))}catch{}})(),d=(async()=>{if(t.listUsers)try{const g=await t.listUsers(r.users);o(g.slice(0,r.users).map(e$))}catch{}})(),f=(async()=>{if(t.listStorageObjectPaths)try{const g=await t.listStorageObjectPaths(r.objects);o(g.slice(0,r.objects).map(t$))}catch{}})(),p=(async()=>{if(t.listRtdbTopLevelKeys)try{o((await t.listRtdbTopLevelKeys()).map(n$))}catch{}})();return await Promise.allSettled([c,d,f,p]),s}const wA=Symbol("pyric/auth/target"),s$=Symbol("pyric.user.internal");function Be(t,e){return new Vi(t,`Firebase: ${e} (${t}).`)}const SA={PASSWORD:"password"},Yp={EMAIL_LINK:"emailLink",EMAIL_PASSWORD:"password"};class Fd{constructor(e,n){G(this,"providerId");G(this,"signInMethod");this.providerId=e,this.signInMethod=n}toJSON(){return{providerId:this.providerId,signInMethod:this.signInMethod}}static fromJSON(e){const n=typeof e=="string"?i$(e):e;if(!n)return null;const r=n.providerId,s=n.signInMethod;if(typeof r!="string"||typeof s!="string")return null;if(r===SA.PASSWORD){const o=typeof n.email=="string"?n.email:"",c=typeof n.password=="string"?n.password:"";return new a$(o,c,s)}return new Fd(r,s)}}function i$(t){try{const e=JSON.parse(t);return typeof e=="object"&&e!==null?e:null}catch{return null}}class a$ extends Fd{constructor(n,r,s=Yp.EMAIL_PASSWORD){super(SA.PASSWORD,s);G(this,"email");G(this,"secret");this.email=n,Object.defineProperty(this,"secret",{value:r,enumerable:!1,writable:!1})}get password(){return this.signInMethod===Yp.EMAIL_PASSWORD?this.secret:null}get emailLink(){return this.signInMethod===Yp.EMAIL_LINK?this.secret:null}toJSON(){return{providerId:this.providerId,signInMethod:this.signInMethod,email:this.email,password:this.secret}}}class Pd extends Fd{constructor(n,r,s={}){super(n,r);G(this,"idToken");G(this,"accessToken");G(this,"secret");this.idToken=s.idToken,this.accessToken=s.accessToken,this.secret=s.secret}toJSON(){return{providerId:this.providerId,signInMethod:this.signInMethod,idToken:this.idToken,accessToken:this.accessToken,secret:this.secret}}}function fg(t,e){return e?new Pd(t,t):null}const Us=class Us{constructor(){G(this,"providerId",Us.PROVIDER_ID)}addScope(e){return this}setCustomParameters(e){return this}static credentialFromResult(e){return fg(Us.PROVIDER_ID,e)}static credentialFromError(e){return null}static credential(e,n){return new Pd(Us.PROVIDER_ID,Us.GOOGLE_SIGN_IN_METHOD,{idToken:e??void 0,accessToken:n??void 0})}};G(Us,"PROVIDER_ID","google.com"),G(Us,"GOOGLE_SIGN_IN_METHOD","google.com");let dy=Us;const $s=class $s{constructor(){G(this,"providerId",$s.PROVIDER_ID)}addScope(e){return this}setCustomParameters(e){return this}static credentialFromResult(e){return fg($s.PROVIDER_ID,e)}static credentialFromError(e){return null}static credential(e){return new Pd($s.PROVIDER_ID,$s.FACEBOOK_SIGN_IN_METHOD,{accessToken:e})}};G($s,"PROVIDER_ID","facebook.com"),G($s,"FACEBOOK_SIGN_IN_METHOD","facebook.com");let fy=$s;const Bs=class Bs{constructor(){G(this,"providerId",Bs.PROVIDER_ID)}addScope(e){return this}setCustomParameters(e){return this}static credentialFromResult(e){return fg(Bs.PROVIDER_ID,e)}static credentialFromError(e){return null}static credential(e){return new Pd(Bs.PROVIDER_ID,Bs.GITHUB_SIGN_IN_METHOD,{accessToken:e})}};G(Bs,"PROVIDER_ID","github.com"),G(Bs,"GITHUB_SIGN_IN_METHOD","github.com");let hy=Bs;const _A=[dy.PROVIDER_ID,"apple.com",fy.PROVIDER_ID,hy.PROVIDER_ID,"twitter.com","microsoft.com","yahoo.com"];function hg(t,e=!1){var r;const n=t[wA];if(!n)throw new TypeError("pyric/auth: unrecognized Auth handle — was it produced by getAuth(...)?");return e||(r=n.assertAlive)==null||r.call(n),n}class o${constructor(){G(this,"mockResults",new Map);G(this,"resolver",null);G(this,"redirectResult",null);G(this,"actionCodes",new Map);G(this,"nextCodeSerial",1);G(this,"outbox",[]);G(this,"mailResolver",null)}setMockResult(e,n){this.mockResults.set(e,n)}consumeMockResult(e){const n=this.mockResults.get(e);return n&&this.mockResults.delete(e),n}setResolver(e){this.resolver=e}getResolver(){return this.resolver}setRedirectResult(e){this.redirectResult=e}takeRedirectResult(){const e=this.redirectResult;return this.redirectResult=null,e}mintActionCode(e){const n=`sandbox-oob-${this.nextCodeSerial++}`;return this.actionCodes.set(n,e),n}stageActionCode(e,n){this.actionCodes.set(e,n)}peekActionCode(e){return this.actionCodes.get(e)}consumeActionCode(e){const n=this.actionCodes.get(e);return n&&this.actionCodes.delete(e),n}setMailResolver(e){this.mailResolver=e}deliverMail(e){if(this.outbox.push(e),this.mailResolver)try{this.mailResolver.deliver(e)}catch{}}takeMail(e){const n=e===void 0?this.outbox.length>0?0:-1:this.outbox.findIndex(r=>r.email.toLowerCase()===e.toLowerCase());return n<0?null:this.outbox.splice(n,1)[0]??null}listMail(){return[...this.outbox]}}function l$(t,e,n){let r=5381;const s=JSON.stringify(e)+":"+String(n);for(let c=0;c<s.length;c++)r=(r<<5)+r+s.charCodeAt(c)|0;const o=(r>>>0).toString(16).padStart(8,"0");return`sandbox-id-token-${t}-${o}`}function Ai(t){if(typeof t!="string"||t.length===0)throw Be("auth/invalid-email","Error");const e=t.indexOf("@");if(e<=0||e===t.length-1)throw Be("auth/invalid-email","Error")}function ol(t){if(typeof t!="string"||t.length<6)throw Be("auth/weak-password","Password should be at least 6 characters")}function EA(){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 c$="__pyric_no_password__";class AA{constructor(e,n=e,r=EA(),s){G(this,"usersByEmail");G(this,"usersByUid");G(this,"authStateSubs",[]);G(this,"idTokenSubs",[]);G(this,"userDbSubs");G(this,"beforeStateSubs",[]);G(this,"sharedCounters");G(this,"flow",new o$);G(this,"sandbox");G(this,"session");G(this,"cachedUser",null);G(this,"lastNotifiedUid",null);G(this,"applyingTransition",!1);G(this,"tokenCache",new Map);G(this,"nextTokenSerial",1);G(this,"persistenceMode","LOCAL");G(this,"signInProviderByUid",new Map);G(this,"providerConfig");G(this,"providerConfigSubs");G(this,"providerEnforcementDelegated",!1);G(this,"sessionChangeSubs",new Set);var c;this.sandbox=e,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=((c=this.cachedUser)==null?void 0:c.uid)??null;const o=n.onCurrentUserChanged(d=>{var g;if(this.applyingTransition)return;const f=d===null?null:d.uid,p=((g=this.cachedUser)==null?void 0:g.uid)??null;f!==p&&(this.cachedUser=this.buildUserFromState(d)),this.notifyAuthListeners()});s==null||s(()=>{o(),this.authStateSubs.length=0,this.idTokenSubs.length=0,this.beforeStateSubs.length=0})}getCurrentUser(){return this.cachedUser}subscribe(e,n){const r=e==="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 o=r.indexOf(s);o!==-1&&r.splice(o,1)}}fanOut(e="both"){const n=this.cachedUser;if(e==="both"||e==="auth-state")for(const r of[...this.authStateSubs])this.deliverOne(r,n);if(e==="both"||e==="id-token")for(const r of[...this.idTokenSubs])this.deliverOne(r,n)}notifyAuthListeners(){var n;this.fanOut("id-token");const e=((n=this.cachedUser)==null?void 0:n.uid)??null;this.lastNotifiedUid!==e&&(this.lastNotifiedUid=e,this.fanOut("auth-state"))}deliverOne(e,n){e.hasFired=!0,e.lastValue=n;const r=e.observer;try{typeof r=="function"?r(n):r.next&&r.next(n)}catch{}}makeStored(e){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,...e}}notifyUsersChanged(){for(const e of[...this.userDbSubs])try{e()}catch{}}emitAuthEvent(e,n={}){try{Ps(this.sandbox,Td({service:"auth",op:e,path:n.path,auth:n.auth??this.session.currentUser,before:n.before,after:n.after,detail:n.detail}),{service:"auth"})}catch{}}subscribeUsers(e){return this.userDbSubs.add(e),()=>{this.userDbSubs.delete(e)}}isProviderEnabled(e){return this.providerConfig.get(e)??!0}listProviderConfig(){return[...this.providerConfig.entries()].map(([e,n])=>({providerId:e,enabled:n}))}setProviderConfig(e,n){const r=this.providerConfig.get(e)??!0;r!==n&&(this.providerConfig.set(e,n),this.notifyProviderConfigChanged(),this.emitAuthEvent("provider_config_update",{path:e,auth:null,before:{providerId:e,enabled:r},after:{providerId:e,enabled:n}}))}notifyProviderConfigChanged(){for(const e of[...this.providerConfigSubs])try{e()}catch{}}subscribeProviderConfig(e){return this.providerConfigSubs.add(e),()=>{this.providerConfigSubs.delete(e)}}setProviderEnforcementDelegated(e){this.providerEnforcementDelegated=e}assertProviderEnabled(e){if(!this.providerEnforcementDelegated&&!this.isProviderEnabled(e))throw Be("auth/operation-not-allowed",`${e} sign-in is disabled for this sandbox project. Enable it with sandbox.setAuthProviderConfig(auth, '${e}', true).`)}exportProviderConfig(){return Object.fromEntries(this.providerConfig)}restoreProviderConfig(e){if(this.providerConfig.clear(),e&&typeof e=="object")for(const[n,r]of Object.entries(e))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(e){this.persistenceMode!==e&&(this.persistenceMode=e,this.notifySessionChanged())}notifySessionChanged(){for(const e of[...this.sessionChangeSubs])try{e()}catch{}}subscribeSession(e){return this.sessionChangeSubs.add(e),()=>{this.sessionChangeSubs.delete(e)}}seedUsers(e){for(const n of e){const r=this.usersByUid.get(n.uid);r!=null&&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)}e.length>0&&this.notifyUsersChanged()}exportUsers(){var n;const e=[];for(const r of this.usersByUid.values()){if(r.email===null)continue;const s={uid:r.uid,email:r.email,password:r.password??c$,providerId:((n=r.providerUserInfo[0])==null?void 0:n.providerId)??"password"};r.displayName!==null&&(s.displayName=r.displayName),Object.keys(r.customClaims).length>0&&(s.customClaims=r.customClaims),e.push(s)}return e}restoreSession(e){var o;const n=this.usersByUid.get(e);if(!n)throw Be("auth/user-not-found",`restoreSession: no identity with uid ${e}.`);if(n.disabled)throw Be("auth/user-disabled",`restoreSession: user ${e} is disabled.`);const r=n.isAnonymous?"anonymous":((o=n.providerUserInfo[0])==null?void 0:o.providerId)??"password",s=this.buildUserFromStored(n);return this.setCurrentUser(s,r),s}findByEmail(e){return this.usersByEmail.get(e.toLowerCase())}findByUid(e){return this.usersByUid.get(e)}mintActionCode(e){return this.flow.mintActionCode(e)}stageActionCode(e,n){this.flow.stageActionCode(e,n)}peekActionCode(e){return this.flow.peekActionCode(e)}consumeActionCode(e){return this.flow.consumeActionCode(e)}deliverMail(e){this.flow.deliverMail(e)}takeMail(e){return this.flow.takeMail(e)}listMail(){return this.flow.listMail()}setMailResolver(e){this.flow.setMailResolver(e)}setEmailVerified(e,n){const r=this.requireByEmail(e);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(e,n){ol(n);const r=this.requireByEmail(e);return r.password=n,this.notifyUsersChanged(),this.emitAuthEvent("user_update",{path:r.uid,after:this.toRecord(r),detail:{passwordReset:!0}}),r}changeEmail(e,n){Ai(n);const r=this.requireByEmail(e),s=n.toLowerCase(),o=this.usersByEmail.get(s);if(o&&o.uid!==r.uid)throw Be("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(e){Ai(e);const n=e.toLowerCase(),r=this.usersByEmail.get(n);if(r)return r.providerUserInfo.some(c=>c.providerId==="password")||r.providerUserInfo.push({providerId:"password"}),r.emailVerified=!0,this.notifyUsersChanged(),{stored:r,isNewUser:!1};const s=`email-${n}-${this.usersByEmail.size+1}`,o=this.makeStored({uid:s,email:e,providerUserInfo:[{providerId:"password"}]});return o.emailVerified=!0,this.usersByEmail.set(n,o),this.usersByUid.set(s,o),this.notifyUsersChanged(),this.emitAuthEvent("user_create",{path:s,after:this.toRecord(o),detail:{emailLink:!0}}),{stored:o,isNewUser:!0}}linkProvider(e,n,r){const s=this.usersByUid.get(e);if(!s)throw Be("auth/user-not-found",`linkWithCredential: no identity with uid ${e}.`);if(s.providerUserInfo.some(c=>c.providerId===n))throw Be("auth/provider-already-linked",`User can only be linked to one identity for the given provider (${n}).`);const o=r==null?void 0:r.email;if(o){Ai(o);const c=o.toLowerCase(),d=this.usersByEmail.get(c);if(d&&d.uid!==e)throw Be("auth/email-already-in-use",`An account already exists for ${o}.`);r.password!==void 0&&r.password!==null&&(ol(r.password),s.password=r.password),s.email&&s.email.toLowerCase()!==c&&this.usersByEmail.delete(s.email.toLowerCase()),s.email=o,this.usersByEmail.set(c,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:e,after:this.toRecord(s),detail:{linked:n}}),s}unlinkProvider(e,n){const r=this.usersByUid.get(e);if(!r)throw Be("auth/user-not-found",`unlink: no identity with uid ${e}.`);const s=r.providerUserInfo.findIndex(o=>o.providerId===n);if(s<0)throw Be("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:e,after:this.toRecord(r),detail:{unlinked:n}}),r}requireByEmail(e){const n=this.usersByEmail.get(e.toLowerCase());if(!n)throw Be("auth/user-not-found",`No user found for ${e}.`);return n}createEmailPasswordUser(e,n){Ai(e),ol(n);const r=e.toLowerCase();if(this.usersByEmail.has(r))throw Be("auth/email-already-in-use",`An account already exists for ${e}.`);const s=`email-${r}-${this.usersByEmail.size+1}`,o=this.makeStored({uid:s,email:e,password:n,providerUserInfo:[{providerId:"password"}]});return this.usersByEmail.set(r,o),this.usersByUid.set(s,o),this.notifyUsersChanged(),this.emitAuthEvent("user_create",{path:s,after:this.toRecord(o)}),o}beforeAuthStateChanged(e,n){const r={callback:e,onAbort:n,active:!0};return this.beforeStateSubs.push(r),()=>{r.active=!1}}async runBeforeStateChange(e){if(e===this.cachedUser)return;const n=[];try{for(const r of this.beforeStateSubs)r.active&&(await r.callback(e),r.onAbort&&n.push(r.onAbort))}catch(r){n.reverse();for(const o of n)try{o()}catch{}const s=r instanceof Error?r.message:String(r);throw Be("auth/login-blocked",s)}}transitionCurrentUser(e,n){return!this.beforeStateSubs.some(s=>s.active)||e===this.cachedUser?(this.setCurrentUser(e,n),Promise.resolve()):this.runBeforeStateChange(e).then(()=>{this.setCurrentUser(e,n)})}setCurrentUser(e,n){if(e===null){const c=this.cachedUser;this.cachedUser=null,this.applyingTransition=!0;try{this.session.currentUser=null}finally{this.applyingTransition=!1}c&&(this.tokenCache.delete(c.uid),this.notifyAuthListeners(),this.notifySessionChanged(),this.emitAuthEvent("sign_out",{path:c.uid,auth:{uid:c.uid}}));return}n!==void 0&&this.signInProviderByUid.set(e.uid,n);const r=this.usersByUid.get(e.uid),s=(r==null?void 0:r.customClaims)??{};n!==void 0&&r&&(r.lastLoginAt=new Date().toISOString(),this.notifyUsersChanged()),this.cachedUser=e,this.tokenCache.set(e.uid,this.mintToken(e.uid,s));const o={uid:e.uid,token:s};this.applyingTransition=!0;try{this.session.currentUser=o}finally{this.applyingTransition=!1}this.notifyAuthListeners(),this.notifySessionChanged(),n!==void 0&&this.emitAuthEvent("sign_in",{path:e.uid,auth:o,after:{uid:e.uid,isAnonymous:e.isAnonymous,email:e.email},detail:{providerId:n??"anonymous"}})}setMockResult(e,n){this.flow.setMockResult(e,n)}consumeMockResult(e){return this.flow.consumeMockResult(e)}setResolver(e){this.flow.setResolver(e)}getResolver(){return this.flow.getResolver()}setRedirectResult(e){this.flow.setRedirectResult(e)}takeRedirectResult(){return this.flow.takeRedirectResult()}recordProviderSignIn(e,n){let r=!1,s=this.usersByUid.get(e.uid);s||(s=this.makeStored({uid:e.uid,email:e.email,displayName:e.displayName,isAnonymous:e.isAnonymous}),this.usersByUid.set(e.uid,s),e.email&&this.usersByEmail.set(e.email.toLowerCase(),s),r=!0),s.providerUserInfo.some(o=>o.providerId===n)||(s.providerUserInfo.push({providerId:n}),r=!0),r&&this.notifyUsersChanged()}createSignInCredential(e){const{providerId:n}=e;let r;if("uid"in e){const s=this.usersByUid.get(e.uid);if(!s)throw Be("auth/user-not-found",`createSignInCredential: no identity with uid ${e.uid}. Use the {spec} shape to create one.`);r=s}else{const{spec:s}=e,o=this.usersByEmail.get(s.email.toLowerCase());o?r=o:(r=this.makeStored({uid:s.uid??`${n}:${s.email}`,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(e=>{var n;return{uid:e.uid,email:e.email,displayName:e.displayName,providerId:e.isAnonymous?"anonymous":((n=e.providerUserInfo[0])==null?void 0:n.providerId)??"password",providerUserInfo:[...e.providerUserInfo],isAnonymous:e.isAnonymous,customClaims:e.customClaims}})}toRecord(e){return{uid:e.uid,email:e.email,displayName:e.displayName,phoneNumber:e.phoneNumber,photoUrl:e.photoUrl,customClaims:{...e.customClaims},providerUserInfo:e.providerUserInfo.map(n=>({...n})),isAnonymous:e.isAnonymous,disabled:e.disabled,emailVerified:e.emailVerified,createdAt:e.createdAt,lastLoginAt:e.lastLoginAt}}listUsers(){return[...this.usersByUid.values()].map(e=>this.toRecord(e))}sanitizeLinkedProviders(e,n,r){var c;const s=new Set,o=[];for(const d of e){const f=(c=d==null?void 0:d.providerId)==null?void 0:c.trim();if(!f)throw Be("auth/argument-error",`${r}: providerUserInfo entries need a non-empty providerId.`);f==="password"||f==="anonymous"||s.has(f)||(s.add(f),o.push({providerId:f}))}return n&&o.unshift({providerId:"password"}),o}createUser(e){const n=e.uid??`user-${this.sharedCounters.nextAdminUserId++}`;if(this.usersByUid.has(n))throw Be("auth/uid-already-exists",`createUser: a user with uid ${n} already exists.`);if(e.email!==void 0&&(Ai(e.email),this.usersByEmail.has(e.email.toLowerCase())))throw Be("auth/email-already-in-use",`An account already exists for ${e.email}.`);if(e.password!==void 0&&(ol(e.password),e.email===void 0))throw Be("auth/invalid-email","createUser: a password requires an email.");const r=this.makeStored({uid:n,email:e.email??null,password:e.password??null,displayName:e.displayName??null,phoneNumber:e.phoneNumber??null,photoUrl:e.photoUrl??null,customClaims:e.customClaims??{},disabled:e.disabled??!1,emailVerified:e.emailVerified??!1,providerUserInfo:this.sanitizeLinkedProviders(e.providerUserInfo??[],e.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(e,n){const r=this.usersByUid.get(e);if(!r)throw Be("auth/user-not-found",`No user found for uid ${e}.`);const s=this.toRecord(r);if(n.email!==void 0){Ai(n.email);const c=n.email.toLowerCase(),d=this.usersByEmail.get(c);if(d&&d!==r)throw Be("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(c,r)}n.password!==void 0&&(ol(n.password),r.password=n.password,r.providerUserInfo.some(c=>c.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 o=this.toRecord(r);return this.emitAuthEvent("user_update",{path:e,auth:null,before:s,after:o}),o}deleteUser(e){const n=this.usersByUid.get(e);if(!n)throw Be("auth/user-not-found",`No user found for uid ${e}.`);const r=this.toRecord(n);this.usersByUid.delete(e),n.email&&this.usersByEmail.get(n.email.toLowerCase())===n&&this.usersByEmail.delete(n.email.toLowerCase()),this.tokenCache.delete(e),this.signInProviderByUid.delete(e),this.notifyUsersChanged(),this.emitAuthEvent("user_delete",{path:e,auth:null,before:r})}clearUsers(){if(this.usersByUid.size===0&&this.usersByEmail.size===0)return;const e=this.usersByUid.size;this.usersByUid.clear(),this.usersByEmail.clear(),this.notifyUsersChanged(),this.emitAuthEvent("users_clear",{path:"*",auth:null,detail:{count:e}})}assertSignInAllowed(e){var n;if((n=this.usersByUid.get(e))!=null&&n.disabled)throw Be("auth/user-disabled","The user account has been disabled by an administrator.")}buildUserFromStored(e){return this.makeUser({uid:e.uid,email:e.email,displayName:e.displayName,isAnonymous:e.isAnonymous,claims:e.customClaims,photoURL:e.photoUrl,emailVerified:e.emailVerified,phoneNumber:e.phoneNumber,providers:e.providerUserInfo})}mintAnonymousUser(){const e=`anonymous-${this.sharedCounters.nextAnonymousId++}`,n=this.makeStored({uid:e,isAnonymous:!0});return this.usersByUid.set(e,n),this.notifyUsersChanged(),this.emitAuthEvent("user_create",{path:e,after:this.toRecord(n),detail:{isAnonymous:!0}}),this.makeUser({uid:e,email:null,displayName:null,isAnonymous:!0,claims:{}})}mintDetachedSession(e){var n;switch(e.kind){case"anonymous":return this.assertProviderEnabled("anonymous"),this.establishDetachedSession(this.mintAnonymousUser(),"anonymous");case"password":return this.assertProviderEnabled("password"),this.establishDetachedSession(this.buildUserFromStored(this.validatePassword(e.email,e.password)),"password");case"createPassword":return this.assertProviderEnabled("password"),this.establishDetachedSession(this.buildUserFromStored(this.createEmailPasswordUser(e.email,e.password)),"password");case"uid":{const r=this.usersByUid.get(e.uid);if(!r)throw Be("auth/user-not-found",`mintSession: no identity with uid ${e.uid}.`);if(r.disabled)throw Be("auth/user-disabled",`mintSession: user ${e.uid} is disabled.`);const s=r.isAnonymous?"anonymous":((n=r.providerUserInfo[0])==null?void 0:n.providerId)??"password";return this.establishDetachedSession(this.buildUserFromStored(r),s)}}}establishDetachedSession(e,n){this.signInProviderByUid.set(e.uid,n);const r=this.usersByUid.get(e.uid),s=(r==null?void 0:r.customClaims)??{};r&&(r.lastLoginAt=new Date().toISOString(),this.notifyUsersChanged()),this.tokenCache.set(e.uid,this.mintToken(e.uid,s));const o={uid:e.uid,token:s};return this.emitAuthEvent("sign_in",{path:e.uid,auth:o,after:{uid:e.uid,isAnonymous:e.isAnonymous,email:e.email},detail:{providerId:n,session:"connection"}}),{user:e,state:o}}buildUserFromState(e){if(e===null)return null;const n=this.usersByUid.get(e.uid);return n?this.buildUserFromStored({...n,customClaims:e.token??n.customClaims}):this.makeUser({uid:e.uid,email:null,displayName:null,isAnonymous:e.uid.startsWith("anonymous-"),claims:e.token??{}})}mintToken(e,n){const r=new Date,s=new Date(r.getTime()+100*365*24*60*60*1e3),o=this.nextTokenSerial++,c=l$(e,n,o),d=this.signInProviderByUid.get(e)??null,f={sub:e,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:d}},p={token:c,claims:f,expirationTime:s.toISOString(),issuedAtTime:r.toISOString(),authTime:r.toISOString(),signInProvider:d};return{token:c,result:p}}getIdTokenFor(e,n,r){if(r){const c=this.mintToken(e,n);return this.tokenCache.set(e,c),this.fanOut("id-token"),c.token}const s=this.tokenCache.get(e);if(s)return s.token;const o=this.mintToken(e,n);return this.tokenCache.set(e,o),o.token}getIdTokenResultFor(e,n,r){if(r){const c=this.mintToken(e,n);return this.tokenCache.set(e,c),this.fanOut("id-token"),c.result}const s=this.tokenCache.get(e);if(s)return s.result;const o=this.mintToken(e,n);return this.tokenCache.set(e,o),o.result}makeUser(e){const n=e.photoURL??null,r=e.phoneNumber??null,s=e.emailVerified??!1,o="firebase",c=e.providers??[{providerId:"password"}],d=e.isAnonymous?[]:c.map(p=>({uid:e.uid,displayName:e.displayName,email:e.email,phoneNumber:r,photoURL:n,providerId:p.providerId})),f={uid:e.uid,email:e.email,emailVerified:s,displayName:e.displayName,photoURL:n,phoneNumber:r,isAnonymous:e.isAnonymous,providerId:o,providerData:d,getIdToken:async p=>this.getIdTokenFor(e.uid,this.liveClaims(e.uid,e.claims),p===!0),getIdTokenResult:async p=>this.getIdTokenResultFor(e.uid,this.liveClaims(e.uid,e.claims),p===!0)};return Object.defineProperty(f,s$,{value:{updateProfile:p=>(this.updateProfileFor(f,p),Promise.resolve()),delete:()=>(this.deleteFor(f),Promise.resolve()),updateEmail:p=>(this.updateEmailFor(f,p),Promise.resolve()),updatePassword:p=>(this.updatePasswordFor(f,p),Promise.resolve()),reload:()=>(this.reloadFor(f),Promise.resolve()),target:this.selfTarget()},enumerable:!1}),f}selfTarget(){return{kind:"sandbox",sandbox:this.sandbox,backend:this}}updateProfileFor(e,n){const r=this.usersByUid.get(e.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(e,n),this.cachedUser&&this.cachedUser.uid===e.uid&&this.cachedUser!==e&&this.applyProfileToUser(this.cachedUser,n),this.notifyUsersChanged(),this.emitAuthEvent("user_update",{path:e.uid,auth:{uid:e.uid},before:s,after:r?this.toRecord(r):void 0,detail:{displayName:n.displayName,photoURL:n.photoURL}})}applyProfileToUser(e,n){var o;const r=e;n.displayName!==void 0&&(r.displayName=n.displayName),n.photoURL!==void 0&&(r.photoURL=n.photoURL);const s=(o=e.providerData)==null?void 0:o[0];s&&(n.displayName!==void 0&&(s.displayName=n.displayName),n.photoURL!==void 0&&(s.photoURL=n.photoURL))}updateProfileByUid(e,n){const r=this.usersByUid.get(e);if(!r)throw Be("auth/user-not-found",`updateProfile: no identity with uid ${e}.`);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===e&&this.applyProfileToUser(this.cachedUser,n),this.notifyUsersChanged();const o=this.toRecord(r);return this.emitAuthEvent("user_update",{path:e,auth:{uid:e},before:s,after:o,detail:{displayName:n.displayName,photoURL:n.photoURL}}),o}deleteFor(e){this.usersByUid.has(e.uid)&&this.deleteUser(e.uid),this.cachedUser&&this.cachedUser.uid===e.uid&&this.setCurrentUser(null)}updateEmailFor(e,n){this.updateUser(e.uid,{email:n}),this.applyEmailToUser(e,n),this.cachedUser&&this.cachedUser.uid===e.uid&&this.cachedUser!==e&&this.applyEmailToUser(this.cachedUser,n)}applyEmailToUser(e,n){var s;e.email=n;const r=(s=e.providerData)==null?void 0:s[0];r&&(r.email=n)}updatePasswordFor(e,n){this.updateUser(e.uid,{password:n})}reloadFor(e){const n=this.usersByUid.get(e.uid);if(!n)throw Be("auth/user-token-expired","The user's credential is no longer valid. The user must sign in again.");this.applyStoredToUser(e,n),this.cachedUser&&this.cachedUser.uid===e.uid&&this.cachedUser!==e&&this.applyStoredToUser(this.cachedUser,n)}applyStoredToUser(e,n){const r=e;r.email=n.email,r.displayName=n.displayName,r.photoURL=n.photoUrl,r.emailVerified=n.emailVerified,r.phoneNumber=n.phoneNumber}liveClaims(e,n){var r;return((r=this.usersByUid.get(e))==null?void 0:r.customClaims)??n}validatePassword(e,n){if(Ai(e),typeof n!="string"||n.length===0)throw Be("auth/missing-password","A non-empty password must be provided");const r=this.findByEmail(e);if(!r)throw Be("auth/user-not-found",`No user found for ${e}.`);if(r.disabled)throw Be("auth/user-disabled","The user account has been disabled by an administrator.");if(r.password!==n)throw Be("auth/wrong-password","Invalid password.");return r}}const RS=new WeakSet,yu=new WeakMap;function jA(t,e,n,r="[DEFAULT]"){return u$(t,e),d$(t,e,n,r)}function u$(t,e){RS.has(t)||(RS.add(t),t.registerPersistableService("auth",{snapshot:()=>({users:e.exportUsers(),providers:e.exportProviderConfig()}),restore:n=>{const r=n;e.clearUsers(),Array.isArray(r==null?void 0:r.users)&&r.users.length>0&&e.seedUsers(r.users),e.restoreProviderConfig(r==null?void 0:r.providers)},subscribe:n=>{const r=e.subscribeUsers(n),s=e.subscribeProviderConfig(n);return()=>{r(),s()}}}))}function DS(t){return{snapshot:()=>null,restore:()=>{},session:{currentUid:()=>{var e;return((e=t.session.currentUser)==null?void 0:e.uid)??null},restore:(e,n)=>{t.backend.setPersistenceMode(n),t.backend.restoreSession(e)},mode:()=>t.backend.getPersistenceMode(),subscribe:e=>(t.subscribers.add(e),t.unsubscribeBackend||(t.unsubscribeBackend=t.backend.subscribeSession(()=>{for(const n of t.subscribers)n()})),()=>{var n;t.subscribers.delete(e),t.subscribers.size===0&&((n=t.unsubscribeBackend)==null||n.call(t),t.unsubscribeBackend=void 0)})}}}function d$(t,e,n,r){var p,g;let s=yu.get(t);s||(s=new Map,yu.set(t,s));const o=`auth-session:${r}`,c=s.get(o);if(c){const b=++c.generation;return(p=c.unregisterService)==null||p.call(c),c.unregisterService=void 0,(g=c.unsubscribeBackend)==null||g.call(c),c.unsubscribeBackend=void 0,c.backend=e,c.session=n,c.unregisterService=t.registerPersistableService(o,DS(c)),()=>{var v,x;c.generation===b&&((v=c.unregisterService)==null||v.call(c),c.unregisterService=void 0,(x=c.unsubscribeBackend)==null||x.call(c),c.unsubscribeBackend=void 0,c.subscribers.clear(),s.get(o)===c&&s.delete(o),s.size===0&&yu.delete(t))}}const d={backend:e,session:n,subscribers:new Set,generation:1};s.set(o,d),d.unregisterService=t.registerPersistableService(o,DS(d));const f=d.generation;return()=>{var b,v;d.generation===f&&((b=d.unregisterService)==null||b.call(d),d.unregisterService=void 0,(v=d.unsubscribeBackend)==null||v.call(d),d.unsubscribeBackend=void 0,d.subscribers.clear(),s.get(o)===d&&s.delete(o),s.size===0&&yu.delete(t))}}async function yq(t){const{backend:e}=hg(t);e.assertProviderEnabled("anonymous");const n=e.getCurrentUser();if(n!=null&&n.isAnonymous)return{user:n,providerId:null,operationType:"signIn",_additionalUserInfo:{isNewUser:!1,profile:{},providerId:null}};const r=e.mintAnonymousUser();return await e.transitionCurrentUser(r,"anonymous"),{user:r,providerId:null,operationType:"signIn",_additionalUserInfo:{isNewUser:!0,profile:{},providerId:null}}}async function f$(t){var n;const e=hg(t,!0);try{(n=e.assertAlive)==null||n.call(e)}catch(r){if(r.code==="app/app-deleted")return;throw r}await e.backend.transitionCurrentUser(null)}const IS=new WeakMap,MS=new WeakMap,LS=new WeakMap;function kA(t){let e=MS.get(t);return e||(e=EA(),MS.set(t,e)),e}function h$(t){let e=IS.get(t);return e||(e=new AA(t,t,kA(t)),IS.set(t,e),jA(t,e,t)),e}function p$(t,e){return e.service("auth/backend",()=>{const{sandbox:n,session:r}=e,s=new AA(n,r,kA(n),o=>{e.onDelete(o)});return e.onDelete(jA(n,s,r,t.name)),s})}function CA(t){if(t===void 0)return CA(xE());const e=Gy(t);if(e)return e.service("auth/default",()=>{const n={kind:"sandbox",sandbox:e.sandbox,backend:p$(t,e),own:r=>e.onDelete(r),assertAlive:()=>e.assertAlive()};return US(n,t)});if(m$(t)){let n=LS.get(t);return n||(n=US({kind:"sandbox",sandbox:t,backend:h$(t)}),LS.set(t,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 m$(t){return typeof t=="object"&&t!==null&&typeof t.onCurrentUserChanged=="function"&&typeof t.withAuth=="function"}function US(t,e){const n={[wA]:t,...e?{app:e}:{},signOut(){return f$(n)}};return Object.defineProperty(n,"currentUser",{enumerable:!0,get(){return t.backend.getCurrentUser()}})}function tt(t){return hg(t)}const Kn={setUser(t,e){tt(t).backend.setCurrentUser(e)},setAuthFlowResolver(t,e){tt(t).backend.setResolver(e)},setAuthMailResolver(t,e){tt(t).backend.setMailResolver(e)},takeAuthMail(t,e){return tt(t).backend.takeMail(e)},listAuthMail(t){return tt(t).backend.listMail()},mockActionCode(t,e,n){tt(t).backend.stageActionCode(e,n)},listIdentities(t){return tt(t).backend.listIdentities()},createSignInCredential(t,e){return tt(t).backend.createSignInCredential(e)},mockSignInResult(t,e){const n=e.providerId;if(!n)throw new rt("invalid-argument","sandbox.mockSignInResult: result.providerId is required so the next signInWithPopup / signInWithCredential call can match.");tt(t).backend.setMockResult(n,e)},seedUsers(t,e){tt(t).backend.seedUsers(e)},exportUsers(t){return tt(t).backend.exportUsers()},restoreSession(t,e){return tt(t).backend.restoreSession(e)},mintSession(t,e){return tt(t).backend.mintDetachedSession(e)},listUsers(t){return tt(t).backend.listUsers()},createUser(t,e){return tt(t).backend.createUser(e)},updateUser(t,e,n){return tt(t).backend.updateUser(e,n)},updateProfile(t,e,n){return tt(t).backend.updateProfileByUid(e,n)},deleteUser(t,e){tt(t).backend.deleteUser(e)},clearUsers(t){tt(t).backend.clearUsers()},subscribeUsers(t,e){return tt(t).backend.subscribeUsers(e)},getAuthProviderConfig(t){return tt(t).backend.listProviderConfig()},setAuthProviderConfig(t,e,n){tt(t).backend.setProviderConfig(e,n)},assertAuthProviderEnabled(t,e){tt(t).backend.assertProviderEnabled(e)},delegateProviderEnforcement(t,e){tt(t).backend.setProviderEnforcementDelegated(e)},subscribeAuthProviderConfig(t,e){return tt(t).backend.subscribeProviderConfig(e)}},y$="pyric-storage",g$=1,br="blobs",yn="metadata";function b$(t=y$){return x$(t).then(e=>new v$(e))}class v${constructor(e){G(this,"db");this.db=e}async put(e,n,r){const s=this.db.transaction([br,yn],"readwrite");s.objectStore(br).put(n,e),s.objectStore(yn).put(r,e),await gu(s)}async getBlob(e){const n=this.db.transaction(br,"readonly");return Zp(n.objectStore(br).get(e))}async getMetadata(e){const n=this.db.transaction(yn,"readonly");return Zp(n.objectStore(yn).get(e))}async putMetadata(e,n){const r=this.db.transaction(yn,"readwrite");r.objectStore(yn).put(n,e),await gu(r)}async delete(e){const n=this.db.transaction([br,yn],"readwrite");n.objectStore(br).delete(e),n.objectStore(yn).delete(e),await gu(n)}async listByPrefix(e){const n=this.db.transaction(yn,"readonly"),r=IDBKeyRange.bound(e,e+"",!1,!1);return Zp(n.objectStore(yn).getAll(r))}async reset(){const e=this.db.transaction([br,yn],"readwrite");e.objectStore(br).clear(),e.objectStore(yn).clear(),await gu(e)}close(){this.db.close()}}function x$(t){return new Promise((e,n)=>{const r=indexedDB.open(t,g$);r.addEventListener("upgradeneeded",()=>{const s=r.result;s.objectStoreNames.contains(br)||s.createObjectStore(br),s.objectStoreNames.contains(yn)||s.createObjectStore(yn)}),r.addEventListener("success",()=>e(r.result)),r.addEventListener("error",()=>n(r.error)),r.addEventListener("blocked",()=>n(new Error(`IndexedDB open blocked for db "${t}"`)))})}function Zp(t){return new Promise((e,n)=>{t.addEventListener("success",()=>e(t.result)),t.addEventListener("error",()=>n(t.error))})}function gu(t){return new Promise((e,n)=>{t.addEventListener("complete",()=>e()),t.addEventListener("error",()=>n(t.error)),t.addEventListener("abort",()=>n(t.error??new Error("IndexedDB transaction aborted")))})}function $S(t){switch(t){case"read":return["get","list"];case"write":return["create","update","delete"];default:return[t]}}const w$=new Set(["read","write","get","list","create","update","delete"]),S$=["==","!=","<=",">=","&&","||"];function _$(t){const e=[];let n=0;for(;n<t.length;){const r=t[n];if(r===" "||r===" "||r===`
|
|
1204
|
-
`||r==="\r"){n++;continue}if(r==="/"&&t[n+1]==="/"){for(;n<t.length&&t[n]!==`
|
|
1205
|
-
`;)n++;continue}if(r==="'"||r==='"'){const o=r,c=n;n++;let d="";for(;n<t.length&&t[n]!==o;)d+=t[n],n++;if(n>=t.length)throw new SyntaxError(`Unterminated string literal starting at offset ${c}.`);n++,e.push({kind:"string",value:d,pos:c});continue}if(r>="0"&&r<="9"){const o=n;let c="";for(;n<t.length&&t[n]>="0"&&t[n]<="9";)c+=t[n],n++;e.push({kind:"number",value:Number(c),pos:o});continue}if(NA(r)){const o=n;let c="";for(;n<t.length&&E$(t[n]);)c+=t[n],n++;e.push({kind:"ident",value:c,pos:o});continue}const s=t.slice(n,n+2);if(S$.includes(s)){e.push({kind:"punct",value:s,pos:n}),n+=2;continue}if("{}()[].,;:=*+-/<>!|&$".includes(r)){e.push({kind:"punct",value:r,pos:n}),n++;continue}throw new SyntaxError(`Unexpected character "${r}" at offset ${n}.`)}return e.push({kind:"eof",pos:t.length}),e}function NA(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"}function E$(t){return NA(t)||t>="0"&&t<="9"}class A${constructor(e){G(this,"tokens");G(this,"pos",0);this.tokens=e}parseService(){this.atIdent("rules_version")&&(this.pos++,this.expectPunct("="),this.expect("string"),this.expectPunct(";")),this.expectIdent("service"),this.expectIdent("firebase"),this.expectPunct("."),this.expectIdent("storage"),this.expectPunct("{");const e={segments:[],children:[],allows:[],functions:[]};for(;!this.atPunct("}");)this.atIdent("function")?e.functions.push(this.parseFunction()):this.parseMatchInto(e);return this.expectPunct("}"),e}parseFunction(){this.expectIdent("function");const e=this.expectIdentValue();this.expectPunct("(");const n=[];if(!this.atPunct(")"))for(n.push(this.expectIdentValue());this.atPunct(",");)this.expectPunct(","),n.push(this.expectIdentValue());this.expectPunct(")"),this.expectPunct("{");const r=[];for(;this.atIdent("let");){this.expectIdent("let");const o=this.expectIdentValue();this.expectPunct("=");const c=this.parseExpression();this.expectPunct(";"),r.push({name:o,value:c})}this.expectIdent("return");const s=this.parseExpression();return this.expectPunct(";"),this.expectPunct("}"),{name:e,params:n,lets:r,body:s}}parseMatchInto(e){this.expectIdent("match");const n=this.parsePath();this.expectPunct("{");const r={segments:n,children:[],allows:[],functions:[]};for(;!this.atPunct("}");)if(this.atIdent("match"))this.parseMatchInto(r);else if(this.atIdent("allow"))r.allows.push(this.parseAllow());else if(this.atIdent("function"))r.functions.push(this.parseFunction());else{const s=this.peek();throw new SyntaxError(`Expected 'match', 'allow', or 'function' inside match block at offset ${s.pos}, got "${bu(s)}".`)}this.expectPunct("}"),e.children.push(r)}parsePath(){const e=[];for(;this.atPunct("/");){this.expectPunct("/");const n=this.peek();if(n.kind==="punct"&&n.value==="{"){this.expectPunct("{");const r=this.expectIdentValue();this.atPunct("=")?(this.expectPunct("="),this.expectPunct("*"),this.expectPunct("*"),this.expectPunct("}"),e.push({kind:"wildcard",name:r})):(this.expectPunct("}"),e.push({kind:"param",name:r}))}else if(n.kind==="ident")e.push({kind:"literal",value:n.value}),this.pos++;else throw new SyntaxError(`Expected path segment after '/' at offset ${n.pos}.`)}if(e.length===0)throw new SyntaxError(`Empty match path at offset ${this.peek().pos}.`);return e}parseAllow(){this.expectIdent("allow");const e=[];for(e.push(this.parseVerb());this.atPunct(",");)this.expectPunct(","),e.push(this.parseVerb());this.expectPunct(":");let n=null;return this.atIdent("if")&&(this.expectIdent("if"),n=this.parseExpression()),this.expectPunct(";"),{verbs:e,condition:n}}parseVerb(){const e=this.expect("ident");if(w$.has(e.value))return e.value;throw new SyntaxError(`Unsupported verb "${e.value}" at offset ${e.pos}. Storage rules support read, write, get, list, create, update, and delete.`)}parseExpression(){return this.parseOr()}parseOr(){let e=this.parseAnd();for(;this.atPunct("||");)this.expectPunct("||"),e={kind:"binary",op:"||",left:e,right:this.parseAnd()};return e}parseAnd(){let e=this.parseEq();for(;this.atPunct("&&");)this.expectPunct("&&"),e={kind:"binary",op:"&&",left:e,right:this.parseEq()};return e}parseEq(){let e=this.parseRel();for(;this.atPunct("==")||this.atPunct("!=");)e={kind:"binary",op:this.expect("punct").value,left:e,right:this.parseRel()};return e}parseRel(){let e=this.parseAdd();for(;this.atPunct("<")||this.atPunct(">")||this.atPunct("<=")||this.atPunct(">=");)e={kind:"binary",op:this.expect("punct").value,left:e,right:this.parseAdd()};return e}parseAdd(){let e=this.parseMul();for(;this.atPunct("+")||this.atPunct("-");)e={kind:"binary",op:this.expect("punct").value,left:e,right:this.parseMul()};return e}parseMul(){let e=this.parseUnary();for(;this.atPunct("*")||this.atPunct("/");)e={kind:"binary",op:this.expect("punct").value,left:e,right:this.parseUnary()};return e}parseUnary(){return this.atPunct("!")?(this.expectPunct("!"),{kind:"unary",op:"!",arg:this.parseUnary()}):this.parsePostfix()}parsePostfix(){let e=this.parsePrimary();for(;;)if(this.atPunct(".")){this.expectPunct(".");const n=this.expectIdentValue();e={kind:"member",target:e,name:n}}else if(this.atPunct("[")){this.expectPunct("[");const n=this.parseExpression();this.expectPunct("]"),e={kind:"index",target:e,index:n}}else if(this.atPunct("(")){this.expectPunct("(");const n=[];if(!this.atPunct(")"))for(n.push(this.parseExpression());this.atPunct(",");)this.expectPunct(","),n.push(this.parseExpression());if(this.expectPunct(")"),e.kind==="ident")e={kind:"call",name:e.name,args:n};else if(e.kind==="member")e={kind:"methodcall",target:e.target,method:e.name,args:n};else throw new SyntaxError(`Call expression at offset ${this.peek().pos} must target a function name or a member.`)}else return e}parsePrimary(){const e=this.peek();if(e.kind==="punct"&&e.value==="/")return this.parsePathArg();if(e.kind==="punct"&&e.value==="("){this.expectPunct("(");const n=this.parseExpression();return this.expectPunct(")"),n}if(e.kind==="number")return this.pos++,{kind:"literal",value:e.value};if(e.kind==="string")return this.pos++,{kind:"literal",value:e.value};if(e.kind==="ident")return this.pos++,e.value==="true"?{kind:"literal",value:!0}:e.value==="false"?{kind:"literal",value:!1}:e.value==="null"?{kind:"literal",value:null}:{kind:"ident",name:e.value};throw new SyntaxError(`Unexpected token "${bu(e)}" at offset ${e.pos}.`)}parsePathArg(){const e=[];for(;this.atPunct("/");)if(this.expectPunct("/"),this.atPunct("$")){this.expectPunct("$"),this.expectPunct("(");const n=this.parseExpression();this.expectPunct(")"),e.push({kind:"interp",expr:n})}else if(this.atPunct("(")){this.expectPunct("(");const n=this.expectIdentValue();this.expectPunct(")"),e.push({kind:"literal",value:`(${n})`})}else{const n=this.peek();if(n.kind==="ident")this.pos++,e.push({kind:"literal",value:n.value});else if(n.kind==="number")this.pos++,e.push({kind:"literal",value:String(n.value)});else throw new SyntaxError(`Expected a path segment after '/' at offset ${n.pos}, got "${bu(n)}".`)}if(e.length===0)throw new SyntaxError(`Empty Firestore path literal at offset ${this.peek().pos}.`);return{kind:"path",segments:e}}peek(){return this.tokens[this.pos]}atPunct(e){const n=this.tokens[this.pos];return n.kind==="punct"&&n.value===e}atIdent(e){const n=this.tokens[this.pos];return n.kind==="ident"&&n.value===e}expect(e){const n=this.tokens[this.pos];if(n.kind!==e)throw new SyntaxError(`Expected ${e} at offset ${n.pos}, got "${bu(n)}".`);return this.pos++,n}expectIdent(e){const n=this.expect("ident");if(n.value!==e)throw new SyntaxError(`Expected keyword "${e}" at offset ${n.pos}, got "${n.value}".`)}expectIdentValue(){return this.expect("ident").value}expectPunct(e){const n=this.expect("punct");if(n.value!==e)throw new SyntaxError(`Expected "${e}" at offset ${n.pos}, got "${n.value}".`)}}function bu(t){return t.kind==="eof"?"<eof>":t.kind==="string"?JSON.stringify(t.value):String(t.value)}function OA(t){const e=_$(t),r=new A$(e).parseService();return TA(r,new Map),{_root:r}}function TA(t,e){const n=new Map(e);for(const r of t.functions)n.set(r.name,r);t.visibleFuncs=n;for(const r of t.functions)r.declScope=n;for(const r of t.children)TA(r,n)}function qd(t){return t?{size:t.size,contentType:t.contentType,metadata:t.customMetadata,name:j$(t.fullPath,t.bucket),bucket:t.bucket,timeCreated:t.timeCreated,updated:t.updated,generation:BS(t.generation),metageneration:BS(t.metageneration)}:null}function j$(t,e){if(t===void 0)return;const n=t.startsWith("/")?t.slice(1):t;if(e!==void 0){const s=`b/${e}/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 BS(t){if(t===void 0)return;const e=Number(t);return Number.isFinite(e)?e:void 0}function k$(t){return{size:t.size,contentType:t.contentType,metadata:t.customMetadata}}function RA(t,e,n=new Date,r){const s=n.getTime(),o=C$(e.request.path),c=[],d=new Set($S(e.request.method));function f(g,b,v){const x=N$(g.segments,b,v);if(!x)return!1;const _=x.params,k=x.left;if(k.length===0)for(const R of g.allows){const C=new Set(R.verbs.flatMap($S));if(![...d].some(q=>C.has(q)))continue;let U;try{const q=R.condition?Et(R.condition,{input:e,now:s,params:_,locals:{},funcs:g.visibleFuncs??new Map,depth:0,firestoreLookup:r}):!0;if(or(q)){c.push(`match ${Wp(g.segments)} ${e.request.method}: ${q.message}`);continue}U=yl(q)}catch(q){if(q instanceof nt){c.push(`match ${Wp(g.segments)} ${e.request.method}: ${q.message}`);continue}throw q}if(U)return!0;c.push(`match ${Wp(g.segments)} ${e.request.method}: condition false`)}for(const R of g.children)if(f(R,k,_))return!0;return!1}const p=f(t._root,o,{});return!p&&c.length===0&&c.push(`no rule matches ${e.request.method} /${o.join("/")}`),{allowed:p,reasons:c}}function C$(t){return t.split("/").filter(e=>e.length>0)}function Wp(t){return"/"+t.map(e=>e.kind==="literal"?e.value:e.kind==="param"?`{${e.name}}`:`{${e.name}=**}`).join("/")}function N$(t,e,n){let r=0;const s={...n};for(let o=0;o<t.length;o++){const c=t[o];if(c.kind==="wildcard")return s[c.name]=e.slice(r),{left:[],params:s};if(r>=e.length)return null;if(c.kind==="literal"){if(e[r]!==c.value)return null;r++}else s[c.name]=e[r],r++}return{left:e.slice(r),params:s}}class yd{constructor(e){G(this,"message");this.message=e}}function or(t){return t instanceof yd}function FS(t,e){const n=t[e];return n===void 0?new yd(`Property ${e} is undefined on object.`):n}function yl(t){return or(t)?!1:t!==!1&&t!==null&&t!==void 0&&!(typeof t=="number"&&Number.isNaN(t))}class nt extends Error{}const PS=20;function Et(t,e){switch(t.kind){case"literal":return t.value;case"ident":return t.name in e.locals?e.locals[t.name]:t.name==="request"?R$(e.input,e.now):t.name==="resource"?T$(e.input.resource):t.name in e.params?e.params[t.name]:void 0;case"member":{const n=Et(t.target,e);return or(n)?n:n==null?new yd("Null value error."):FS(n,t.name)}case"index":{const n=Et(t.target,e);if(or(n))return n;if(n==null)return new yd("Null value error.");const r=Et(t.index,e);return or(r)?r:FS(n,String(r))}case"call":return O$(t,e);case"methodcall":return D$(t,e);case"path":throw new nt("a Firestore path literal is only valid as an argument to firestore.get()/exists()");case"unary":{const n=Et(t.arg,e);return or(n)?n:!yl(n)}case"binary":{if(t.op==="&&"){const s=Et(t.left,e);return or(s)?s:yl(s)?Et(t.right,e):s}if(t.op==="||"){const s=Et(t.left,e);if(or(s)){const o=Et(t.right,e);return yl(o)?o:s}return yl(s)?s:Et(t.right,e)}const n=Et(t.left,e);if(or(n))return n;const r=Et(t.right,e);if(or(r))return r;switch(t.op){case"==":return n===r||n==null&&r==null;case"!=":return!(n===r||n==null&&r==null);case"<":return vu(n,r)<0;case">":return vu(n,r)>0;case"<=":return vu(n,r)<=0;case">=":return vu(n,r)>=0;case"+":return xu(n,r,(s,o)=>s+o);case"-":return xu(n,r,(s,o)=>s-o);case"*":return xu(n,r,(s,o)=>s*o);case"/":return xu(n,r,(s,o)=>s/o)}}}}function O$(t,e){const n=e.funcs.get(t.name);if(!n)throw new nt(`undefined function ${t.name}()`);if(n.params.length!==t.args.length)throw new nt(`function ${t.name}() expects ${n.params.length} argument(s), got ${t.args.length}`);const r=e.depth+1;if(r>PS)throw new nt(`function ${t.name}() exceeded max call depth ${PS}`);const s=t.args.map(d=>Et(d,e)),o={};n.params.forEach((d,f)=>{o[d]=s[f]});const c={input:e.input,now:e.now,params:{},locals:o,funcs:n.declScope??new Map,depth:r,firestoreLookup:e.firestoreLookup};for(const d of n.lets)o[d.name]=Et(d.value,c);return Et(n.body,c)}function vu(t,e){return typeof t=="number"&&typeof e=="number"?t-e:typeof t=="string"&&typeof e=="string"?t<e?-1:t>e?1:0:Number.NaN}function xu(t,e,n){if(!(typeof t!="number"||typeof e!="number"))return n(t,e)}function T$(t){return t===null?null:{size:t.size,contentType:t.contentType,metadata:t.metadata,name:t.name,bucket:t.bucket,generation:t.generation,metageneration:t.metageneration,timeCreated:qS(t.timeCreated),updated:qS(t.updated)}}function qS(t){if(t===void 0)return;const e=Date.parse(t);return Number.isNaN(e)?void 0:e}function R$(t,e){return{auth:t.request.auth,resource:t.request.resource??null,method:t.request.method,path:t.request.path,time:e}}function D$(t,e){if(t.target.kind==="ident"&&t.target.name==="timestamp"&&!(t.target.name in e.locals)&&!(t.target.name in e.params))return U$(t,e);if(t.target.kind==="ident"&&t.target.name==="duration"&&!(t.target.name in e.locals)&&!(t.target.name in e.params))return L$(t,e);if(t.target.kind==="ident"&&t.target.name==="firestore"&&!(t.target.name in e.locals)&&!(t.target.name in e.params))return I$(t,e);if(t.method==="matches")return $$(t,e);throw new nt(`unsupported method .${t.method}()`)}function I$(t,e){if(t.method!=="get"&&t.method!=="exists")throw new nt(`unsupported method firestore.${t.method}()`);if(!e.firestoreLookup)throw new nt(`firestore.${t.method}() is unsupported here — no Firestore lookup capability is configured`);if(t.args.length!==1)throw new nt(`firestore.${t.method}() expects a single path argument`);const n=t.args[0];if(n.kind!=="path")throw new nt(`firestore.${t.method}() requires a /databases/.../documents/... path literal`);const r=M$(n,e);if(t.method==="exists")return e.firestoreLookup.exists(r);const s=e.firestoreLookup.get(r);if(s===null)throw new nt(`firestore.get() targeted a nonexistent document: ${r}`);return{data:s}}function M$(t,e){const n=t.segments.map(s=>{if(s.kind==="literal")return s.value;const o=Et(s.expr,e);if(typeof o=="string")return o;if(typeof o=="number")return String(o);throw new nt(`Firestore path interpolation resolved to ${DA(o)} (expected a string)`)});if(n.length<4||n[0]!=="databases"||n[2]!=="documents")throw new nt(`malformed Firestore path — expected /databases/<db>/documents/... , got /${n.join("/")}`);const r=n.slice(3);if(r.length===0||r.length%2!==0)throw new nt(`Firestore path does not point at a document (needs an even segment count): ${r.join("/")}`);return r.join("/")}const zS={w:10080*60*1e3,d:1440*60*1e3,h:3600*1e3,m:60*1e3,s:1e3,ms:1,ns:1e-6};function L$(t,e){if(t.method!=="value")throw new nt(`unsupported duration.${t.method}()`);const n=t.args.map(c=>Et(c,e));if(n.length!==2||typeof n[0]!="number"||typeof n[1]!="string")throw new nt("duration.value() expects (magnitude: number, unit: string)");const[r,s]=n,o=zS[s];if(o===void 0)throw new nt(`duration.value() got unknown unit "${s}" — expected one of ${Object.keys(zS).join(", ")}`);return r*o}function U$(t,e){const n=t.args.map(r=>Et(r,e));if(t.method==="value"){if(n.length!==1||typeof n[0]!="number")throw new nt("timestamp.value() expects (epochMillis: number)");return n[0]}if(t.method==="date"){if(n.length!==3||!n.every(c=>typeof c=="number"))throw new nt("timestamp.date() expects (year, month, day) numbers");const[r,s,o]=n;return Date.UTC(r,s-1,o)}throw new nt(`unsupported timestamp.${t.method}()`)}function $$(t,e){const n=Et(t.target,e);if(or(n))return n;if(typeof n!="string")throw new nt(`matches() requires a string target, got ${DA(n)}`);if(t.args.length!==1)throw new nt("matches() expects a single pattern argument");const r=Et(t.args[0],e);if(typeof r!="string")throw new nt("matches() pattern must be a string");const s=/\\[1-9]/.test(r),o=/\(\?<?[=!]/.test(r);if(s||o)throw new nt(`matches() pattern uses an RE2-unsupported construct (${s?"backreference":"lookaround"}) that production would reject`);let c;try{c=new RegExp(`^(?:${r})$`)}catch(d){throw new nt(`matches() invalid regex pattern: ${d.message}`)}return c.test(n)}function DA(t){return t===null?"null":t===void 0?"undefined":typeof t}const B$="pyric-default",zd=Symbol("pyric/storage/target");function $i(t){var e;return((e=t.currentAuth)==null?void 0:e.call(t))??t.context.auth}class F${constructor(e,n=null){G(this,"backend");G(this,"rules");this.backend=e,this.rules=n}}const VS=new WeakMap,HS=new WeakMap;function P$(t,e,n){const r=VS.get(t);if(r){const c=HS.get(t)??null;if(e.rules!==void 0&&e.rules!==c)throw new Error(`pyric/storage: ${n} received a rules source, but this sandbox's storage service is already open ${c===null?"without rules":"with a different rules source"} — rules are honored only on the FIRST storage call per Sandbox, so these rules would be silently discarded. Configure rules on the first storage call for this sandbox.`);return r}const s=e.rules?OA(e.rules):null,o=b$(e.dbName).then(c=>new F$(c,s));return VS.set(t,o),HS.set(t,e.rules??null),o}function Jp(t){return t instanceof so}const GS=new WeakMap,KS=new WeakMap;function q$(t,e={}){const n=!Jp(t),r=Jp(t)?t.sandbox:t,s=P$(r,e,"getAdminStorageSandbox");if(n){const g=KS.get(r);if(g)return g}const o=Jp(t)?t:r.withAuth(null),c=o.operationContext.authLens.mode==="admin"?o:Fl(o,{source:o.operationContext.source,authLens:{mode:"admin"},...o.operationContext.planId===void 0?{}:{planId:o.operationContext.planId}}),d=GS.get(o);if(d)return d;const f={kind:"sandbox",sandbox:r,context:c,bucket:e.bucket??B$,servicePromise:s,admin:!0},p=Object.freeze({[zd]:f});return GS.set(o,p),n&&KS.set(r,p),p}function oo(t,e){const n=Od(e,ad(t.context.operationContext));return{...e,...ad(n),service:"storage"}}function is(t){const e=t[zd];if(!e)throw new TypeError("pyric/storage: not a FirebaseStorage handle — was it produced by getStorageSandbox?");return e}function Hl(t){return is(t).servicePromise}function z$(t){return`storage/${t}`}class Gl extends Error{constructor(n,r){const s=z$(n);super(`${s}: ${r}`);G(this,"code");this.name="StorageError",this.code=s,Object.setPrototypeOf(this,Gl.prototype)}}function IA(t){return new Gl("object-not-found",`no object at "${t}".`)}function V$(t,e,n){return new Gl("unauthorized",`${t} "${e}" denied by rules${n}.`)}function pg(t){return new Gl("invalid-root-operation",`${t} cannot operate on the root reference.`)}function Ml(t,e){return G$(t)?(is(t.storage),new Ll(t.storage,H$(t.fullPath,e??""))):(is(t),new Ll(t,MA(e??"")))}class Ll{constructor(e,n){G(this,"storage");G(this,"bucket");G(this,"fullPath");this.storage=e;const r=is(e);this.bucket=r.bucket,this.fullPath=n}get name(){if(this.fullPath==="")return"";const e=this.fullPath.lastIndexOf("/");return e===-1?this.fullPath:this.fullPath.slice(e+1)}get parent(){if(this.fullPath==="")return null;const e=this.fullPath.lastIndexOf("/"),n=e===-1?"":this.fullPath.slice(0,e);return new Ll(this.storage,n)}get root(){return this.fullPath===""?this:new Ll(this.storage,"")}toString(){return`gs://${this.bucket}/${this.fullPath}`}}function MA(t){return t===""?"":t.split("/").filter(e=>e.length>0).join("/")}function H$(t,e){const n=MA(e);return t===""?n:n===""?t:`${t}/${n}`}function G$(t){if(t===null||typeof t!="object"||zd in t)return!1;const e=t;return typeof e.fullPath=="string"&&e.storage!==void 0}function Kl(t,e,n,r){const s=(n==null?void 0:n.kind)==="sandbox"?oo(n,r):r;if((n==null?void 0:n.kind)==="sandbox"&&n.admin===!0){wu(n,e,"not-applicable",void 0,"admin",!1,s);return}if(!t.rules){wu(n,e,"allow",void 0,"user",!1,s);return}const o=n?K$(e,n.bucket):e,c=RA(t.rules,o,void 0,Y$(n));if(!c.allowed){wu(n,e,"deny",c.reasons,"user",!0,s);const d=c.reasons.length>0?` — ${c.reasons.join("; ")}`:"";throw V$(e.request.method,e.request.path,d)}wu(n,e,"allow",c.reasons,"user",!0,s)}function K$(t,e){const n=t.request.path.replace(/^\/+/,"");return{...t,request:{...t.request,path:n===""?`b/${e}/o`:`b/${e}/o/${n}`}}}function wu(t,e,n,r,s,o,c){if(t)try{Ps(t.sandbox,yE({service:"storage",method:e.request.method,path:e.request.path,auth:e.request.auth,result:n,origin:s,reasons:r,rulesDisposition:s==="admin"?{kind:"bypassed",reason:"admin"}:o?{kind:"evaluated",verdict:n==="deny"?"deny":"allow"}:{kind:"not-evaluated",reason:"no-rules"},rules:o?{engine:"storage",reason:r&&r.length>0?r.join("; "):void 0}:void 0}),{...c,service:"storage"})}catch{}}function Y$(t){if(!t)return;const e=t.sandbox.admin;return{get:n=>e.getDocument(n),exists:n=>e.getDocument(n)!==null}}function LA(t){return{...t}}async function Z$(t){W$(t,"getMetadata");const e=is(t.storage),n=oo(e),r=await Hl(t.storage),s=await r.backend.getMetadata(t.fullPath);if(Kl(r,{request:{auth:$i(e),method:"get",path:t.fullPath},resource:qd(s)},e,n),!s)throw IA(t.fullPath);return LA(s)}function W$(t,e){if(t.fullPath==="")throw pg(e)}const J$="application/octet-stream";async function Q$(t,e,n,r){n4(t,"uploadBytes");const s=is(t.storage),o=oo(s,r),c=e4(e,n==null?void 0:n.contentType),d=X$({ref:t,blob:c,settable:n}),f=await Hl(t.storage),p=await f.backend.getMetadata(t.fullPath);Kl(f,{request:{auth:$i(s),method:p?"update":"create",path:t.fullPath,resource:k$({size:d.size,contentType:d.contentType,customMetadata:d.customMetadata})},resource:qd(p)},s,o),await f.backend.put(t.fullPath,c,d);try{Ps(s.sandbox,Td({service:"storage",op:"object_put",path:t.fullPath,auth:$i(s),before:p??void 0,after:d,detail:{bucket:t.bucket,size:d.size,contentType:d.contentType,overwrite:p!=null}}),o)}catch{}return{ref:t,metadata:LA(d)}}function X$(t){const{ref:e,blob:n,settable:r}=t,s=(t.now??new Date).toISOString(),o=t4(t.now??new Date),c=e.name;return{fullPath:e.fullPath,name:c,bucket:e.bucket,generation:o,metageneration:"1",timeCreated:s,updated:s,size:n.size,contentType:(r==null?void 0:r.contentType)||n.type||J$,cacheControl:r==null?void 0:r.cacheControl,contentDisposition:r==null?void 0:r.contentDisposition,contentEncoding:r==null?void 0:r.contentEncoding,contentLanguage:r==null?void 0:r.contentLanguage,customMetadata:r==null?void 0:r.customMetadata}}function e4(t,e){return t instanceof Blob?e&&e!==t.type?new Blob([t],{type:e}):t:new Blob([t],{type:e??""})}function t4(t){return String(t.getTime())}function n4(t,e){if(t.fullPath==="")throw pg(e)}async function r4(t,e){return $A(t,"getBlob"),s4(t,e)}async function UA(t,e){$A(t,"deleteObject");const n=is(t.storage),r=oo(n,e),s=await Hl(t.storage),o=await s.backend.getMetadata(t.fullPath);Kl(s,{request:{auth:$i(n),method:"delete",path:t.fullPath},resource:qd(o)},n,r),await s.backend.delete(t.fullPath);try{Ps(n.sandbox,Td({service:"storage",op:"object_delete",path:t.fullPath,auth:$i(n),before:o??void 0,detail:{bucket:t.bucket}}),r)}catch{}}async function s4(t,e){const n=is(t.storage),r=oo(n),s=await Hl(t.storage),o=await s.backend.getMetadata(t.fullPath);Kl(s,{request:{auth:$i(n),method:"get",path:t.fullPath},resource:qd(o)},n,r);const c=await s.backend.getBlob(t.fullPath);if(!c)throw IA(t.fullPath);return typeof e=="number"&&c.size>e?c.slice(0,e):c}function $A(t,e){if(t.fullPath==="")throw pg(e)}async function mg(t){const e=t.storage,n=is(e),r=oo(n),s=await Hl(e);Kl(s,{request:{auth:$i(n),method:"list",path:t.fullPath},resource:null},n,r);const o=t.fullPath===""?"":`${t.fullPath}/`,c=await s.backend.listByPrefix(o),d=[],f=new Set,p=[];for(const g of c){if(!g.fullPath.startsWith(o))continue;const b=g.fullPath.slice(o.length);if(b==="")continue;const v=b.indexOf("/");if(v===-1)d.push(Ml(e,g.fullPath));else{const x=b.slice(0,v),_=`${o}${x}`;f.has(_)||(f.add(_),p.push(Ml(e,_)))}}return p.sort((g,b)=>g.fullPath<b.fullPath?-1:g.fullPath>b.fullPath?1:0),{items:d,prefixes:p}}function i4(t,e,n){const r={name:n,options:structuredClone(e),automaticDataCollectionEnabled:!0};return hI(r,t),r}const a4=Object.freeze({source:Object.freeze({kind:"studio"}),authLens:Object.freeze({mode:"admin"})});function o4(t){return Fl(t.withAuth(null),a4)}const l4="pyric-studio";function BA(t,e){return t.listDocuments(e).map(({path:n,phantom:r})=>({path:n,phantom:r}))}async function c4(t){const e=[],n=[],r=async s=>{try{const o=await t.listDocuments(s);for(const c of o){c.phantom!==!0&&e.push(c.path);for(const d of await t.listSubcollections(c.path))await r(`${c.path}/${d}`)}}catch(o){n.push(`list ${s}: ${o instanceof Error?o.message:String(o)}`)}};for(const s of t.listRootCollections())await r(s);return{docPaths:e,errors:n}}let u4=0;function d4(t){const e=i4(t,{projectId:"pyric-studio"},`pyric-studio-${u4++}`),n=nn(t),r=o4(t);return{sandbox:t,app:e,firestore:Ud(t),adminFirestore:ag(r),auth:CA(t),storage:q$(r),listRootCollections:()=>n.listRootCollections(),listSubcollections:s=>n.listSubcollections(s),listDocuments:s=>BA(n,s)}}function f4(t,e){const[n,r]=A.useState(!1),[s,o]=A.useState(null),c=A.useMemo(()=>vE(),[]),d=A.useMemo(()=>{try{return d4(c)}catch(p){return o(p instanceof Error?p:new Error(String(p))),null}},[c]);return A.useEffect(()=>{let p=!1;if(!t){r(!1);return}return c.enablePersistence({key:l4,injectedBackend:t}).then(()=>{p||r(!0)}).catch(g=>{p||o(g instanceof Error?g:new Error(String(g)))}),()=>{p=!0}},[c,t]),s?{status:"error",handles:null,error:s}:d?t!=null&&n||e==="ready"?{status:"ready",handles:d}:{status:"pending",handles:null}:{status:"error",handles:null,error:new Error("Studio: failed to construct the sandbox data handles.")}}function h4(t){var n;const e=((n=t.rules)==null?void 0:n.engine)??t.service;return e==="rtdb"||e==="storage"?e:"firestore"}function p4(t){switch(h4(t)){case"firestore":return{impersonate:{kind:"live",tool:"worker setLens({mode:'as',uid}) → Firestore replay"},editedRuleset:{kind:"live",tool:"fork + firestore_lint_rules + firestore_simulate_rules"}};case"rtdb":return{impersonate:{kind:"pending",tool:"rtdb_simulate_access",hint:"RTDB re-runs through the local rules simulator as this user once the Studio worker exposes rtdb_simulate_access. This is a simulation, not a live re-issue — RTDB has no live local enforcement path."},editedRuleset:{kind:"pending",tool:"RulesEvaluator.setRules + rtdb_simulate_access",hint:"Editing the RTDB ruleset re-simulates the write once the worker exposes the RTDB simulator. Note: there is no whole-ruleset RTDB linter yet (rtdb_build_expression lints a single expression)."}};case"storage":return{impersonate:{kind:"absent",missingTool:"storage_simulate_rules",hint:"Storage rules are enforced and evaluated allow/deny events open this inspector, but Studio has no Storage replay operation to re-run this request as a user."},editedRuleset:{kind:"absent",missingTool:"storage_simulate_rules + edited-rules deployment seam",hint:"Storage rules are enforced and denial events are inspectable. Testing an edit still needs a Studio Storage replay operation plus a temporary edited-rules deployment seam."}}}}function m4(t){var e;return((e=lE(t))==null?void 0:e.rules.kind)==="evaluated"}function y4(t){return"service"in t&&typeof t.service=="string"?t.service:"firestore"}function g4(t){const e=t.request;if(e){if("resourceData"in e&&e.resourceData!==void 0)return e.resourceData;if("data"in e)return e.data}}function b4(t){const e=[];for(const n of t)m4(n)&&e.push(v4(n));return e.sort((n,r)=>r.at-n.at)}function v4(t){const e={id:t.id,at:t.at,result:t.result==="allow"?"allow":t.result==="unsupported"?"unsupported":"deny",method:t.method,service:y4(t),path:t.path??"(service)",auth:t.auth,reasons:t.reasons??[],origin:t.origin,unsupported:t.result==="unsupported"};"matchedRule"in t&&t.matchedRule&&(e.matchedRule=t.matchedRule),"evaluatedRule"in t&&t.evaluatedRule&&(e.evaluatedRule=t.evaluatedRule),"rules"in t&&t.rules&&(e.rules=t.rules);const n=g4(t);return n!==void 0&&(e.resourceData=n),t.resourceBefore&&(e.resourceBefore={data:t.resourceBefore.data,exists:t.resourceBefore.exists}),e}const YS=/^Rule #(\d+) \(([^)]+)\) → (ALLOW|deny|unsupported)/;function x4(t){var n;const e=((n=t.rules)==null?void 0:n.engine)??t.service;return e==="rtdb"||e==="storage"?e:"firestore"}function w4(t){var n;if(((n=t.rules)==null?void 0:n.reason)==="Validation rule evaluated to false")return"validate";const e=t.method;return e==="get"||e==="list"||e==="listen"?"read":"write"}function S4(t){var s;const e=x4(t),n=t.reasons.filter(o=>YS.test(o)),r=t.reasons.filter(o=>!YS.test(o));if(t.unsupported)return{headline:`The simulator hit an unmodelled rules feature evaluating ${t.method} ${t.path}.`,engine:e,ruleLines:n,otherLines:r,implicitDeny:!1};if(t.result==="allow"){if(e==="firestore"&&t.matchedRule){const c=t.matchedRule,d=`Rule #${c.ruleIndex} (${c.operations.join(", ")})`;return{headline:`${d} allowed ${t.method} on ${t.path}.`,engine:e,ruleNode:d,ruleLines:n,otherLines:r,implicitDeny:!1}}return!t.matchedRule&&!t.rules&&!t.evaluatedRule&&n.length===0?{headline:`This ${t.method} on ${t.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:e,ruleLines:n,otherLines:r,implicitDeny:!1,noEvaluation:!0}:{headline:`Rules allowed ${t.method} on ${t.path}.`,engine:e,...(s=t.rules)!=null&&s.matchedRule?{ruleExpression:t.rules.matchedRule}:{},ruleLines:n,otherLines:r,implicitDeny:!1}}return e==="rtdb"?E4(t,n,r):e==="storage"?A4(t,n,r):_4(t,n,r)}function _4(t,e,n){const r=!t.matchedRule;let s,o;if(r)s=`No rule allowed ${t.method} on ${t.path}: implicit deny (no matching \`allow\`).`;else{const c=t.matchedRule;o=`Rule #${c.ruleIndex} (${c.operations.join(", ")})`,s=`${o} denied ${t.method} on ${t.path}.`}return{headline:s,engine:"firestore",ruleNode:o,ruleLines:e,otherLines:n,implicitDeny:r}}function E4(t,e,n){const r=t.rules,s=w4(t),o=!(r!=null&&r.matchedPath)||(r==null?void 0:r.errorCode)==="NO_MATCHING_RULE",c=r!=null&&r.pathVariableBindings&&Object.keys(r.pathVariableBindings).length>0?r.pathVariableBindings:void 0;let d,f;return o?d=`No \`.${s}\` rule granted ${t.method} on ${t.path}: RTDB implicit deny (no rule matched).`:s==="validate"?(f=`${r.matchedPath} .validate`,d=`The \`.validate\` rule at \`${r.matchedPath}\` rejected the proposed value for ${t.method} ${t.path}.`):(f=`${r.matchedPath} .${s}`,d=`The \`.${s}\` rule at \`${r.matchedPath}\` evaluated false for ${t.method} ${t.path}.`),{headline:d,engine:"rtdb",ruleNode:f,ruleExpression:r==null?void 0:r.matchedRule,phase:s,bindings:c,ruleLines:e,otherLines:n,implicitDeny:o}}function A4(t,e,n){const r=t.reasons.find(d=>/^match\s/.test(d)),o=t.reasons.some(d=>/^no rule matches/.test(d))||!r;return{headline:o?`No \`match\` block allowed ${t.method} on ${t.path}: Storage implicit deny (no rule matched).`:`A \`match\` block condition evaluated false for ${t.method} on ${t.path}.`,engine:"storage",ruleNode:o?void 0:r,ruleLines:e,otherLines:n,implicitDeny:o}}function j4(t){var e;return!!((e=t.auth)!=null&&e.uid)}function k4(t){return t.skipped?"skipped":t.error!==void 0?"error":t.value===!0?"true":t.value===!1?"false":"value"}function C4(t){var s;const e=(s=t.evaluatedRule)==null?void 0:s.expressionTrace;if(!e||e.length===0)return[];const n=e.map(o=>({source:o.source,outcome:k4(o),...o.value!==void 0?{value:o.value}:{},...o.error!==void 0?{error:o.error}:{},...o.letBinding?{letBinding:o.letBinding.name}:{},...o.inlinedFrom?{inlinedFrom:o.inlinedFrom.name}:{},depth:0,children:[]})),r=[];return e.forEach((o,c)=>{o.parent===null||o.parent===void 0||!n[o.parent]?r.push(n[c]):(n[c].depth=n[o.parent].depth+1,n[o.parent].children.push(n[c]))}),r}function N4(t){const e=[{name:"request.auth",present:t.auth!==null,value:t.auth,...t.auth===null?{absentNote:"request.auth was null — the request was unauthenticated."}:{}},{name:"request.method",present:!0,value:t.method},{name:"request.path",present:!0,value:t.path}],n=t.method==="get"||t.method==="list"||t.method==="listen";return e.push({name:"request.resource.data",present:t.resourceData!==void 0,value:t.resourceData??null,...t.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."}:{}}),e.push({name:"resource",present:t.resourceBefore!==void 0,value:t.resourceBefore?{data:t.resourceBefore.data,exists:t.resourceBefore.exists}:null,...t.resourceBefore===void 0?{absentNote:"The rule evaluated no existing document (e.g. a list/query, or the doc did not exist)."}:{}}),e}function O4(t){const e=nn(t.sandbox);return{sandbox:t.sandbox,app:t.app,firestore:t.firestore,adminFirestore:t.adminFirestore,auth:t.auth,storage:t.storage,listRootCollections:()=>e.listRootCollections(),listSubcollections:n=>e.listSubcollections(n),listDocuments:n=>BA(e,n)}}function Xs(){const t=as(),e=dr(),n=e.status==="ready"?e.env.persistence:void 0,r=f4(n,e.status),s=e.status==="ready"?e.env.live:void 0,o=T4(s);return A.useMemo(()=>{switch(t.status){case"ready":return{status:"ready",handles:O4(t.handles)};case"pending":return{status:"pending",handles:null};case"error":return{status:"error",handles:null,error:t.error};case"disabled":{if(s&&r.status==="ready"){const c=s.db;return{status:"ready",firestoreApi:s.firestoreApi,authApi:s.authApi,storageApi:s.storageApi,handles:{...r.handles,firestore:c,adminFirestore:c,auth:s.auth,storage:s.storage,listRootCollections:()=>o,listSubcollections:d=>s.listSubcollections(d),listDocuments:d=>s.listDocuments(d)}}}return r}}},[t,r,s,o])}function T4(t){const[e,n]=A.useState([]);return A.useEffect(()=>{if(!t){n([]);return}let r=!0;const s=()=>{t.listRootCollections().then(c=>{r&&n(c)}).catch(()=>{})};try{t.setLens({mode:"admin"})}catch{}s();const o=t.feed.subscribe(()=>s());return()=>{r=!1,o()}},[t]),e}const gd=500;function Qp(t){return t.length>gd?t.slice(-gd):t}function Yl(){var d;const t=as(),e=dr(),n=e.status==="ready"?(d=e.env.live)==null?void 0:d.feed:void 0,r=t.status==="ready",[s,o]=A.useState([]);A.useEffect(()=>{if(r||!n){o([]);return}return o(Qp(n.history())),n.subscribe(p=>o(g=>Qp([...g,p])))},[r,n]);const c=A.useMemo(()=>r?Qp(t.events):[],[r,t]);return r?c:s}function R4(t){return t.kind==="request"||t.kind==="operation"}function D4(t){const e=lE(t);if(!e)throw new Error("Studio traffic adapter received a non-operation event");return t.kind==="request"?{...t,operationContext:e.context,rulesDisposition:e.rules}:{kind:"operation",service:t.service,id:t.id,at:t.at,durationMs:t.durationMs,method:t.method,path:t.path??"(service)",auth:t.auth,result:t.result,reasons:t.reasons??[],request:t.request,resourceBefore:t.resourceBefore,resourceAfter:t.resourceAfter,origin:t.origin,groupId:t.groupId,groupKind:t.groupKind,triggeredBy:t.triggeredBy,operationContext:e.context,rulesDisposition:e.rules}}function I4(){const t=Yl();return A.useMemo(()=>t.filter(R4).map(D4),[t])}function M4(){const t=Yl();return A.useMemo(()=>b4(t),[t])}function L4(){const t=Xs();return A.useCallback(async e=>{var d,f;if(t.status!=="ready")throw new Error("No sandbox available to seed.");const n=t.handles.adminFirestore,r=((d=t.firestoreApi)==null?void 0:d.doc)??Yn,s=((f=t.firestoreApi)==null?void 0:f.setDoc)??Rl;let o=0;const c=[];for(const p of e)try{await s(r(n,p.path),p.data),o++}catch(g){c.push(`${p.path}: ${g instanceof Error?g.message:String(g)}`)}return{written:o,errors:c}},[t])}function U4(){const t=Xs();return A.useCallback(async e=>{var c;if(t.status!=="ready")throw new Error("No sandbox available to seed auth.");const n=t.handles.auth,r=((c=t.authApi)==null?void 0:c.createUser)??Kn.createUser;let s=0;const o=[];for(const d of e)try{await r(n,d.request),s++}catch(f){const p=d.request.uid??d.request.email??"<auto>";o.push(`${p}: ${f instanceof Error?f.message:String(f)}`)}return{created:s,errors:o}},[t])}function $4(){const t=Xs();return A.useCallback(async()=>{var d,f,p;if(t.status!=="ready")throw new Error("No sandbox to clear.");const e=t.handles.adminFirestore,n=((d=t.firestoreApi)==null?void 0:d.doc)??Yn,r=((f=t.firestoreApi)==null?void 0:f.deleteDoc)??Dl,{docPaths:s,errors:o}=await c4(t.handles);let c=0;for(const g of s)try{await r(n(e,g)),c+=1}catch(b){o.push(`delete ${g}: ${b instanceof Error?b.message:String(b)}`)}try{(((p=t.authApi)==null?void 0:p.clearUsers)??Kn.clearUsers)(t.handles.auth)}catch(g){o.push(`auth: ${g instanceof Error?g.message:String(g)}`)}return{cleared:c,errors:o}},[t])}function B4(){const t=$4(),e=L4(),n=U4(),r=as();return A.useCallback(async()=>{const s=await t();if(r.status==="ready"){const{applySeed:o}=await K_(async()=>{const{applySeed:c}=await import("./seed-3DMedLL3.js");return{applySeed:c}},[]);await o(r.handles)}else try{const o=await fetch("/__pyric/init.json").then(f=>f.ok?f.json():null),c=o==null?void 0:o.seed;c&&await e(Object.entries(c).map(([f,p])=>({path:f,data:p})));const d=o==null?void 0:o.authUsers;Array.isArray(d)&&await n(d.map(f=>({request:f})))}catch(o){s.errors.push(`reseed: ${o instanceof Error?o.message:String(o)}`)}return s},[t,e,n,r])}function F4(){const t=as(),e=dr(),n=e.status==="ready"?e.env.live:void 0,r=t.status==="ready"?t.handles.sandbox:null;return A.useCallback(async()=>r?r.snapshot():n?n.getSnapshot():null,[r,n])}function yg(){const t=dr(),e=t.status==="ready"?t.env.live:void 0,[n,r]=A.useState("");return A.useEffect(()=>{if(!e){r("");return}let s=!1;return e.instanceId().then(o=>{s||r(o)}),()=>{s=!0}},[e]),n}function P4(){const t=dr(),e=t.status==="ready"?t.env.live:void 0;return A.useCallback(async()=>e?e.exportState():null,[e])}function q4(){const t=dr(),e=t.status==="ready"?t.env.live:void 0;return A.useCallback(async n=>e?(await e.importState(n),!0):!1,[e])}function z4(){const t=dr(),e=t.status==="ready"?t.env.live:void 0,[n,r]=A.useState([]),s=A.useCallback(async()=>{r(e?await e.listBranches():[])},[e]);A.useEffect(()=>{s()},[s]);const o=A.useCallback(async f=>{e&&(await e.saveBranch(f),await s())},[e,s]),c=A.useCallback(async f=>{e&&await e.switchBranch(f)},[e]),d=A.useCallback(async f=>{e&&(await e.deleteBranch(f),await s())},[e,s]);return{branches:n,save:o,switchTo:c,remove:d}}function V4(){const t=as(),e=t.status==="ready",[n,r]=A.useState("");return A.useEffect(()=>{if(e)return;let s=!0;return fetch("/__pyric/init.json").then(o=>o.ok?o.json():null).then(o=>{s&&o&&typeof o.rules=="string"&&r(o.rules)}).catch(()=>{}),()=>{s=!1}},[e]),A.useMemo(()=>{if(t.status!=="ready")return n;try{return nn(t.handles.sandbox).getRules()}catch{return""}},[t,n])}function H4(t){let e=!0;return n=>{const r=e;e=!1,t(s=>K4(s,n,r))}}function G4(t){const e=new Map;for(const n of t)e.set(cy(n),n);return[...e.values()]}function K4(t,e,n){return G4(n?e:[...t??[],...e])}const Y4=3e4;function FA(){const t=Xs(),e=dr(),[n,r]=A.useState(null),[s,o]=A.useState(!1),c=A.useRef(!1),d=A.useRef(t);d.current=t;const f=e.status==="ready"?e.env.live:void 0,p=A.useRef(f);p.current=f;const g=A.useRef(null),b=A.useRef(0),v=A.useRef(null),x=A.useRef(0),_=A.useCallback(R=>{var O,D,z,$,K,W,se;const C=d.current;if(C.status!=="ready")return;const T=++b.current;c.current=!0,o(!0);const U=C.handles,q=U.adminFirestore,I=((O=C.firestoreApi)==null?void 0:O.collection)??Ti,N=((D=C.firestoreApi)==null?void 0:D.query)??Il,M=((z=C.firestoreApi)==null?void 0:z.getDocs)??Tl,L=(($=C.firestoreApi)==null?void 0:$.limit)??fd,H=((K=C.storageApi)==null?void 0:K.ref)??Ml,P=((W=C.storageApi)==null?void 0:W.listAll)??mg,F=((se=C.authApi)==null?void 0:se.listUsers)??Kn.listUsers,w={listRootCollections:()=>U.listRootCollections(),listDocumentPaths:async(B,ee)=>(await M(N(I(q,B),L(ee)))).docs.slice(0,ee).map(le=>`${B}/${le.id}`),listSubcollections:B=>Promise.resolve(U.listSubcollections(B)),listUsers:async B=>(await Promise.resolve(F(U.auth))).slice(0,B).map(ae=>({uid:ae.uid,email:ae.email??null})),listStorageObjectPaths:B=>V3(H(U.storage,""),P,{maxObjects:B,maxListCalls:uy.storageListCalls}),listRtdbTopLevelKeys:async()=>{const B=p.current;if(!B)return[];const ee=Date.now()-x.current<Y4;if(v.current!==null&&ee&&!(R!=null&&R.rtdbLikely))return v.current;const ae=await B.readRtdbState(),le=ae===null||typeof ae!="object"||Array.isArray(ae)?[]:Object.keys(ae);return v.current=le,x.current=Date.now(),le}},E=H4(B=>r(B));r$(w,uy,B=>{T===b.current&&E(B)}).catch(()=>{}).finally(()=>{if(T===b.current&&(c.current=!1,o(!1),r(B=>B??[]),g.current)){const B=g.current;g.current=null,_(B)}})},[]),k=A.useCallback(R=>{if(d.current.status==="ready"){if(c.current){g.current={...g.current,...R};return}_(R)}},[_]);return A.useEffect(()=>{t.status==="ready"&&n===null&&!c.current&&_()},[t,n,_]),{entries:n,building:s,ensure:k}}const Z4=150;function W4(t){return t.startsWith("/")||/rtdb/i.test(t)}function PA({autoFocus:t,onNavigated:e,onEscape:n,exposeFocus:r}){const[s,o]=A.useState(""),[c,d]=A.useState(""),[f,p]=A.useState(0),[g,b]=A.useState(!1),v=A.useRef(null),{entries:x,building:_,ensure:k}=FA();A.useEffect(()=>{if(r)return r(()=>{var I;return(I=v.current)==null?void 0:I.focus()}),()=>r(null)},[r]),A.useEffect(()=>{var I;t&&((I=v.current)==null||I.focus())},[t]),A.useEffect(()=>{const I=setTimeout(()=>d(s),Z4);return()=>clearTimeout(I)},[s]);const R=A.useMemo(()=>NS(c,Ui,x??[]),[c,x]),C=A.useMemo(()=>OS(R),[R]);A.useEffect(()=>{p(I=>C.length===0?0:Math.min(I,C.length-1))},[C.length]);const T=I=>{I&&(o(""),d(""),b(!1),Jn(I.target),e==null||e(I.target))},U=()=>{if(s===c){T(C[f]??C[0]);return}const I=OS(NS(s,Ui,x??[]));T(I[0])};let q=0;return h.jsxs("div",{className:"studio-home__command",children:[h.jsx("div",{className:"studio-home__command-row",children:h.jsx("input",{ref:v,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":g&&C.length>0,"aria-autocomplete":"list",onFocus:()=>{k(),b(!0)},onBlur:()=>b(!1),onChange:I=>{const N=I.target.value;o(N),b(!0),W4(N)&&k({rtdbLikely:!0})},onKeyDown:I=>{if(I.key==="ArrowDown")I.preventDefault(),p(N=>Math.min(N+1,Math.max(C.length-1,0)));else if(I.key==="ArrowUp")I.preventDefault(),p(N=>Math.max(N-1,0));else if(I.key==="Enter")U();else if(I.key==="Escape"){if(n){n();return}o(""),d(""),b(!1)}}})}),g&&!R.length&&_&&x===null?h.jsx("div",{className:"studio-home__command-results",role:"status","aria-live":"polite",children:h.jsx("span",{className:"studio-home__command-group-title",children:"Indexing sandbox…"})}):null,g&&R.length?h.jsx("div",{className:"studio-home__command-results",role:"listbox","aria-label":"Suggestions",onMouseDown:I=>I.preventDefault(),children:R.map(I=>{const N=q;return q+=I.results.length,h.jsxs("div",{className:"studio-home__command-group",children:[h.jsx("span",{className:"studio-home__command-group-title","aria-hidden":"true",children:I.title}),h.jsx("ul",{className:"studio-home__command-group-list",children:I.results.map((M,L)=>{const H=N+L;return h.jsx("li",{children:h.jsxs("button",{type:"button",role:"option","aria-selected":H===f,className:"studio-home__command-result","data-active":H===f?"true":void 0,onMouseEnter:()=>p(H),onClick:()=>T(M),children:[h.jsx("span",{className:"studio-home__command-label",children:M.label}),h.jsx("span",{className:"studio-home__command-sub",children:M.hint})]})},M.id)})})]},I.kind)})}):null]})}function J4({onClose:t}){const e=A.useRef(null);return A.useEffect(()=>(e.current=document.activeElement,()=>{const n=e.current;n instanceof HTMLElement&&n.focus()}),[]),A.useEffect(()=>{const n=r=>{r.key==="Escape"&&t()};return window.addEventListener("keydown",n),()=>window.removeEventListener("keydown",n)},[t]),h.jsx("div",{className:"studio__cmdk-backdrop",onMouseDown:t,children:h.jsx("div",{className:"studio__cmdk",role:"dialog","aria-modal":"true","aria-label":"Command",onMouseDown:n=>n.stopPropagation(),children:h.jsx(PA,{autoFocus:!0,onEscape:t,onNavigated:t})})})}const Q4={status:"loading",payload:null},Su={status:"absent",payload:null};let bd=Q4,ZS=!1;const py=new Set;function _u(t){bd=t;for(const e of py)e()}function X4(){if(!ZS){if(ZS=!0,typeof fetch>"u"){bd=Su;return}fetch("/__pyric/init.json").then(async t=>{if(!t.ok||!(t.headers.get("content-type")??"").includes("json"))return _u(Su);const n=await t.json();_u({status:"ready",payload:n})}).catch(()=>_u(Su))}}function e6(t){return py.add(t),X4(),()=>py.delete(t)}function Vd(){return A.useSyncExternalStore(e6,()=>bd,()=>bd)}function t6(t){return t.kind==="absent"?"absent":t.sandboxConnected?"available":"idle"}function n6(t,e){if(t!==200||typeof e!="object"||e===null)return{kind:"absent"};const n=e.sandboxConnected;return typeof n!="boolean"?{kind:"absent"}:{kind:"json",sandboxConnected:n}}async function r6(t){try{const e=await t("/__pyric/health");return e.ok?(e.headers.get("content-type")??"").includes("json")?n6(e.status,await e.json()):{kind:"absent"}:{kind:"absent"}}catch{return{kind:"absent"}}}function s6(t=5e3){const[e,n]=A.useState("checking");return A.useEffect(()=>{if(typeof fetch>"u"){n("absent");return}let r=!0,s=null;const o=async()=>{const p=t6(await r6(fetch));return r&&(n(p),p==="absent"&&s&&(clearInterval(s),s=null)),p},c=()=>typeof document>"u"||document.visibilityState!=="hidden",d=()=>{s||(s=setInterval(()=>{c()&&o()},t))},f=()=>{c()&&o()};return o().then(p=>{r&&p!=="absent"&&d()}),typeof document<"u"&&document.addEventListener("visibilitychange",f),()=>{r=!1,s&&clearInterval(s),typeof document<"u"&&document.removeEventListener("visibilitychange",f)}},[t]),e}const i6="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 a6(t,e){const n=Math.max(0,e-t);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 o6(t){return t==="studio"?"Studio":"App"}function l6(t,e,n=Date.now()){const r=t.clients.length,s=t.clients.map(c=>({clientId:c.clientId,kindLabel:o6(c.kind),route:c.route||"/",visibilityLabel:c.visibility==="hidden"?"Hidden":"Visible",isThisPage:c.clientId===e,freshnessLabel:a6(c.lastSeen,n)}));s.sort((c,d)=>c.isThisPage!==d.isThisPage?c.isThisPage?-1:1:c.kindLabel!==d.kindLabel?c.kindLabel==="Studio"?-1:1:c.route.localeCompare(d.route));const o=s.filter(c=>!c.isThisPage).length;return{count:r,chipLabel:r===1?"1 page connected":`${r} pages connected`,prominent:r>1,clients:s,boundaryCopy:i6,otherCount:o}}function c6(){const t=dr(),e=t.status==="ready"&&t.env.live?t.env.live:null,[n,r]=A.useState(null);return A.useEffect(()=>{if(!e){r(null);return}const s=e.presenceClientId;return e.subscribePresence(o=>{r(l6(o,s))})},[e]),n}function u6(){const t=dr(),e=Vd(),n=s6(),r=c6(),[s,o]=A.useState(!1),c=A.useRef(null),f=e.status==="ready"&&t.status==="ready"&&!t.env.live,p=t.status==="error",g=p?"backend error":f?"worker unreachable":null,b=n==="available";return A.useEffect(()=>{if(!s)return;const v=x=>{var _;x.key==="Escape"&&(o(!1),(_=c.current)==null||_.focus())};return document.addEventListener("keydown",v),()=>document.removeEventListener("keydown",v)},[s]),h.jsxs("div",{className:"studio__status","aria-label":"Studio status",children:[g?h.jsxs("a",{className:"studio-chip studio-chip--warn",href:Bd({tab:"settings"}),title:p?t.error.message:"Served, but the shared sandbox worker is not reachable; data views may be stale. Open Settings diagnostics.",onClick:v=>{v.preventDefault(),Jn({tab:"settings"})},children:[h.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),g]}):null,r&&r.count>0?h.jsxs("span",{className:"studio-presence",children:[h.jsxs("button",{ref:c,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:()=>o(v=>!v),children:[h.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),r.chipLabel]}),s?h.jsxs(h.Fragment,{children:[h.jsx("div",{className:"studio-presence__backdrop",onMouseDown:()=>o(!1)}),h.jsxs("div",{id:"studio-presence-panel",className:"studio-presence__panel",role:"dialog","aria-label":"Connected pages",children:[h.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.`}),h.jsx("ul",{className:"studio-presence__list",children:r.clients.map(v=>h.jsxs("li",{className:"studio-presence__item",children:[h.jsxs("div",{className:"studio-presence__item-head",children:[h.jsx("span",{className:"studio-presence__kind",children:v.kindLabel}),v.isThisPage?h.jsx("span",{className:"studio-presence__this",children:"This page"}):null]}),h.jsx("div",{className:"studio-presence__route",title:v.route,children:v.route}),h.jsxs("div",{className:"studio-presence__meta",children:[v.visibilityLabel," · ",v.freshnessLabel]})]},v.clientId))}),h.jsx("p",{className:"studio-presence__boundary",children:r.boundaryCopy})]})]}):null]}):null,b?h.jsxs("span",{className:"studio-chip studio-chip--live",title:"MCP bridge available — a sandbox peer is connected; external agents can reach this sandbox.",children:[h.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),"MCP bridge"]}):null]})}function d6(t,e){const n=t.triggeredBy,r=e.triggeredBy;return!n&&!r?!0:!n||!r?!1:n.method===r.method&&n.path===r.path}function WS(t,e,n){let r=0;for(const s of n)s.result==="deny"&&r++;return{type:"group",kind:t,key:e,events:n,count:n.length,denies:r}}function f6({events:t,groupBatches:e=!0,groupListenerRuns:n=!0}){return A.useMemo(()=>{const r=[];let s=0;for(;s<t.length;){const o=t[s];if(e&&o.groupId){let c=s+1;for(;c<t.length&&t[c].groupId===o.groupId;)c++;const d=t.slice(s,c),f=o.origin==="transaction"?"transaction":"batch";r.push(WS(f,o.groupId,d)),s=c;continue}if(n&&o.origin==="listener"){let c=s+1;for(;c<t.length&&t[c].origin==="listener"&&!t[c].groupId&&d6(t[c],o);)c++;const d=t.slice(s,c);if(d.length>1){const f=o.triggeredBy?`${o.triggeredBy.method}:${o.triggeredBy.path}`:"unknown";r.push(WS("listener-run",`listener-run:${f}:${s}`,d))}else r.push({type:"single",event:o});s=c;continue}r.push({type:"single",event:o}),s++}return{items:r}},[t,e,n])}const h6={buckets:[],total:0,denies:0,maxCount:0,outOfWindow:0};function p6({events:t,window:e,bucketCount:n=30}){return A.useMemo(()=>m6(t,e,n),[t,e.start,e.end,n])}function m6(t,e,n=30){const r=e.end-e.start;if(n<=0||r<=0)return h6;const s=r/n,o=new Array(n).fill(0),c=new Array(n).fill(0);let d=0,f=0,p=0;for(const v of t){const x=v.at;if(x<e.start||x>=e.end){p++;continue}let _=Math.floor((x-e.start)/s);_>=n&&(_=n-1),o[_]++,d++,v.result==="deny"&&(c[_]++,f++)}let g=0;for(const v of o)v>g&&(g=v);return{buckets:o.map((v,x)=>{const _=c[x];return{index:x,start:e.start+x*s,end:e.start+(x+1)*s,count:v,denies:_,allows:v-_,heightRatio:g===0?0:v/g,denyHeightRatio:g===0?0:_/g}}),total:d,denies:f,maxCount:g,outOfWindow:p}}const y6=new Set(["get","list"]),g6=new Set(["create","update","set"]),b6=new Set(["delete","remove"]),v6=[{key:"reads",label:"Read ops"},{key:"writes",label:"Writes"},{key:"deletes",label:"Deletes"}],x6=[{key:"allows",label:"Allows"},{key:"denies",label:"Denies"},{key:"errors",label:"Errors"}];function Hd(t){return t.origin==="admin"}function w6(t,e=Hd){return t.result==="allow"||e(t)?y6.has(t.method)?"reads":g6.has(t.method)?"writes":b6.has(t.method)?"deletes":null:null}function S6(t,e=Hd){return e(t)?null:t.result==="allow"?"allows":t.result==="deny"?"denies":t.result==="error"?"errors":null}const _6=t=>({points:[],series:t.map(e=>({key:e.key,label:e.label,values:[],total:0})),maxValue:0});function qA(t,e,n,r,s){const o=e.end-e.start;if(n<=0||o<=0)return _6(r);const c=o/n,d=new Map(r.map(v=>[v.key,new Array(n).fill(0)])),f=new Map(r.map(v=>[v.key,0]));for(const v of t){const x=v.at;if(x<e.start||x>=e.end)continue;const _=s(v);if(_==null)continue;let k=Math.floor((x-e.start)/c);k>=n&&(k=n-1);const R=d.get(_);R[k]++,f.set(_,(f.get(_)??0)+1)}let p=0;for(const v of d.values())for(const x of v)x>p&&(p=x);const g=new Array(n);for(let v=0;v<n;v++)g[v]={index:v,start:e.start+v*c,end:e.start+(v+1)*c};const b=r.map(v=>({key:v.key,label:v.label,values:d.get(v.key),total:f.get(v.key)??0}));return{points:g,series:b,maxValue:p}}function E6(t,e,n=24,r=Hd){return qA(t,e,n,v6,s=>w6(s,r))}function A6(t,e,n=24,r=Hd){return qA(t,e,n,x6,s=>S6(s,r))}function j6({events:t,window:e,bucketCount:n=24,isAdmin:r}){return A.useMemo(()=>E6(t,e,n,r),[t,e.start,e.end,n,r])}function k6({events:t,window:e,bucketCount:n=24,isAdmin:r}){return A.useMemo(()=>A6(t,e,n,r),[t,e.start,e.end,n,r])}function Va({children:t,kind:e,className:n,ariaLabel:r}){return h.jsx("span",{"data-pyric-badge":"","data-pyric-badge-kind":e,className:n,"aria-label":r,children:r?h.jsx("span",{"aria-hidden":"true",children:t}):t})}function Ul(t){const e=new Date(t),n=r=>String(r).padStart(2,"0");return`${n(e.getHours())}:${n(e.getMinutes())}:${n(e.getSeconds())}`}function zA({event:t,selected:e,onSelect:n,renderClassification:r,formatTime:s=Ul,className:o}){return h.jsxs("button",{type:"button",onClick:()=>n==null?void 0:n(t),className:o,"data-pyric-traffic-row":"","data-pyric-result":t.result,"data-pyric-origin":t.origin,"data-pyric-method":t.method,"data-pyric-selected":e?"":void 0,children:[h.jsx("span",{"data-pyric-traffic-time":"",children:s(t.at)}),h.jsx("span",{"data-pyric-traffic-service":t.service??"",children:t.service??""}),h.jsx(Va,{kind:t.method,children:t.method}),h.jsx("span",{"data-pyric-traffic-path":"",children:t.path||"/"}),r?r(t):null]})}var gg=G_();function Ma(t,e,n){let r=n.initialDeps??[],s,o=!0;function c(){var d,f,p;let g;n.key&&((d=n.debug)!=null&&d.call(n))&&(g=Date.now());const b=t();if(!(b.length!==r.length||b.some((_,k)=>r[k]!==_)))return s;r=b;let x;if(n.key&&((f=n.debug)!=null&&f.call(n))&&(x=Date.now()),s=e(...b),n.key&&((p=n.debug)!=null&&p.call(n))){const _=Math.round((Date.now()-g)*100)/100,k=Math.round((Date.now()-x)*100)/100,R=k/16,C=(T,U)=>{for(T=String(T);T.length<U;)T=" "+T;return T};console.info(`%c⏱ ${C(k,5)} /${C(_,5)} ms`,`
|
|
1206
|
-
font-size: .6rem;
|
|
1207
|
-
font-weight: bold;
|
|
1208
|
-
color: hsl(${Math.max(0,Math.min(120-120*R,120))}deg 100% 31%);`,n==null?void 0:n.key)}return n!=null&&n.onChange&&!(o&&n.skipInitialOnChange)&&n.onChange(s),o=!1,s}return c.updateDeps=d=>{r=d},c}function JS(t,e){if(t===void 0)throw new Error("Unexpected undefined");return t}const C6=(t,e)=>Math.abs(t-e)<1.01,N6=(t,e,n)=>{let r;return function(...s){t.clearTimeout(r),r=t.setTimeout(()=>e.apply(this,s),n)}},QS=t=>{const{offsetWidth:e,offsetHeight:n}=t;return{width:e,height:n}},O6=t=>t,T6=t=>{const e=Math.max(t.startIndex-t.overscan,0),n=Math.min(t.endIndex+t.overscan,t.count-1),r=[];for(let s=e;s<=n;s++)r.push(s);return r},R6=(t,e)=>{const n=t.scrollElement;if(!n)return;const r=t.targetWindow;if(!r)return;const s=c=>{const{width:d,height:f}=c;e({width:Math.round(d),height:Math.round(f)})};if(s(QS(n)),!r.ResizeObserver)return()=>{};const o=new r.ResizeObserver(c=>{const d=()=>{const f=c[0];if(f!=null&&f.borderBoxSize){const p=f.borderBoxSize[0];if(p){s({width:p.inlineSize,height:p.blockSize});return}}s(QS(n))};t.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(d):d()});return o.observe(n,{box:"border-box"}),()=>{o.unobserve(n)}},XS={passive:!0},e_=typeof window>"u"?!0:"onscrollend"in window,D6=(t,e)=>{const n=t.scrollElement;if(!n)return;const r=t.targetWindow;if(!r)return;let s=0;const o=t.options.useScrollendEvent&&e_?()=>{}:N6(r,()=>{e(s,!1)},t.options.isScrollingResetDelay),c=g=>()=>{const{horizontal:b,isRtl:v}=t.options;s=b?n.scrollLeft*(v&&-1||1):n.scrollTop,o(),e(s,g)},d=c(!0),f=c(!1);n.addEventListener("scroll",d,XS);const p=t.options.useScrollendEvent&&e_;return p&&n.addEventListener("scrollend",f,XS),()=>{n.removeEventListener("scroll",d),p&&n.removeEventListener("scrollend",f)}},I6=(t,e,n)=>{if(e!=null&&e.borderBoxSize){const r=e.borderBoxSize[0];if(r)return Math.round(r[n.options.horizontal?"inlineSize":"blockSize"])}return t[n.options.horizontal?"offsetWidth":"offsetHeight"]},M6=(t,{adjustments:e=0,behavior:n},r)=>{var s,o;const c=t+e;(o=(s=r.scrollElement)==null?void 0:s.scrollTo)==null||o.call(s,{[r.options.horizontal?"left":"top"]:c,behavior:n})};class L6{constructor(e){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(o=>{const c=()=>{const d=o.target,f=this.indexFromElement(d);if(!d.isConnected){this.observer.unobserve(d);return}this.shouldMeasureDuringScroll(f)&&this.resizeItem(f,this.options.measureElement(d,o,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(c):c()})}));return{disconnect:()=>{var s;(s=r())==null||s.disconnect(),n=null},observe:s=>{var o;return(o=r())==null?void 0:o.observe(s,{box:"border-box"})},unobserve:s=>{var o;return(o=r())==null?void 0:o.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:O6,rangeExtractor:T6,onChange:()=>{},measureElement:I6,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=Ma(()=>(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,o)=>{this.scrollAdjustments=0,this.scrollDirection=o?this.getScrollOffset()<s?"forward":"backward":null,this.scrollOffset=s,this.isScrolling=o,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,o=new Map;for(let c=r-1;c>=0;c--){const d=n[c];if(s.has(d.lane))continue;const f=o.get(d.lane);if(f==null||d.end>f.end?o.set(d.lane,d):d.end<f.end&&s.set(d.lane,!0),s.size===this.options.lanes)break}return o.size===this.options.lanes?Array.from(o.values()).sort((c,d)=>c.end===d.end?c.index-d.index:c.end-d.end)[0]:void 0},this.getMeasurementOptions=Ma(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode],(n,r,s,o,c,d,f)=>(this.prevLanes!==void 0&&this.prevLanes!==d&&(this.lanesChangedFlag=!0),this.prevLanes=d,this.pendingMeasuredCacheIndexes=[],{count:n,paddingStart:r,scrollMargin:s,getItemKey:o,enabled:c,lanes:d,laneAssignmentMode:f}),{key:!1}),this.getMeasurements=Ma(()=>[this.getMeasurementOptions(),this.itemSizeCache],({count:n,paddingStart:r,scrollMargin:s,getItemKey:o,enabled:c,lanes:d,laneAssignmentMode:f},p)=>{if(!c)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>n)for(const x of this.laneAssignments.keys())x>=n&&this.laneAssignments.delete(x);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(x=>{this.itemSizeCache.set(x.key,x.size)}));const g=this.lanesSettling?0:this.pendingMeasuredCacheIndexes.length>0?Math.min(...this.pendingMeasuredCacheIndexes):0;this.pendingMeasuredCacheIndexes=[],this.lanesSettling&&this.measurementsCache.length===n&&(this.lanesSettling=!1);const b=this.measurementsCache.slice(0,g),v=new Array(d).fill(void 0);for(let x=0;x<g;x++){const _=b[x];_&&(v[_.lane]=x)}for(let x=g;x<n;x++){const _=o(x),k=this.laneAssignments.get(x);let R,C;const T=f==="estimate"||p.has(_);if(k!==void 0&&this.options.lanes>1){R=k;const N=v[R],M=N!==void 0?b[N]:void 0;C=M?M.end+this.options.gap:r+s}else{const N=this.options.lanes===1?b[x-1]:this.getFurthestMeasurement(b,x);C=N?N.end+this.options.gap:r+s,R=N?N.lane:x%this.options.lanes,this.options.lanes>1&&T&&this.laneAssignments.set(x,R)}const U=p.get(_),q=typeof U=="number"?U:this.options.estimateSize(x),I=C+q;b[x]={index:x,start:C,size:q,end:I,key:_,lane:R},v[R]=x}return this.measurementsCache=b,b},{key:!1,debug:()=>this.options.debug}),this.calculateRange=Ma(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,s,o)=>this.range=n.length>0&&r>0?U6({measurements:n,outerSize:r,scrollOffset:s,lanes:o}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=Ma(()=>{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,o,c)=>o===null||c===null?[]:n({startIndex:o,endIndex:c,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 o=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),c=Math.max(0,s-o),d=Math.min(this.options.count-1,s+o);return n>=c&&n<=d}return!0},this.measureElement=n=>{if(!n){this.elementsCache.forEach((c,d)=>{c.isConnected||(this.observer.unobserve(c),this.elementsCache.delete(d))});return}const r=this.indexFromElement(n),s=this.options.getItemKey(r),o=this.elementsCache.get(s);o!==n&&(o&&this.observer.unobserve(o),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 o=this.measurementsCache[n];if(!o)return;const c=this.itemSizeCache.get(o.key)??o.size,d=r-c;d!==0&&(((s=this.scrollState)==null?void 0:s.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(o,d,this):o.start<this.getScrollOffset()+this.scrollAdjustments)&&this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=d,behavior:void 0}),this.pendingMeasuredCacheIndexes.push(o.index),this.itemSizeCache=new Map(this.itemSizeCache.set(o.key,r)),this.notify(!1))},this.getVirtualItems=Ma(()=>[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const s=[];for(let o=0,c=n.length;o<c;o++){const d=n[o],f=r[d];s.push(f)}return s},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length!==0)return JS(r[VA(0,r.length-1,s=>JS(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 o=this.getSize(),c=this.getScrollOffset();r==="auto"&&(r=n>=c+o?"end":"start"),r==="center"?n+=(s-o)/2:r==="end"&&(n-=o);const d=this.getMaxScrollOffset();return Math.max(Math.min(d,n),0)},this.getOffsetForIndex=(n,r="auto")=>{n=Math.max(0,Math.min(n,this.options.count-1));const s=this.getSize(),o=this.getScrollOffset(),c=this.measurementsCache[n];if(!c)return;if(r==="auto")if(c.end>=o+s-this.options.scrollPaddingEnd)r="end";else if(c.start<=o+this.options.scrollPaddingStart)r="start";else return[o,r];if(r==="end"&&n===this.options.count-1)return[this.getMaxScrollOffset(),r];const d=r==="end"?c.end+this.options.scrollPaddingEnd:c.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(d,r,c.size),r]},this.scrollToOffset=(n,{align:r="start",behavior:s="auto"}={})=>{const o=this.getOffsetForAlignment(n,r),c=this.now();this.scrollState={index:null,align:r,behavior:s,startedAt:c,lastTargetOffset:o,stableFrames:0},this._scrollToOffset(o,{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 o=this.getOffsetForIndex(n,r);if(!o)return;const[c,d]=o,f=this.now();this.scrollState={index:n,align:d,behavior:s,startedAt:f,lastTargetOffset:c,stableFrames:0},this._scrollToOffset(c,{adjustments:void 0,behavior:s}),this.scheduleScrollReconcile()},this.scrollBy=(n,{behavior:r="auto"}={})=>{const s=this.getScrollOffset()+n,o=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:o,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 o=Array(this.options.lanes).fill(null);let c=r.length-1;for(;c>=0&&o.some(d=>d===null);){const d=r[c];o[d.lane]===null&&(o[d.lane]=d.end),c--}s=Math.max(...o.filter(d=>d!==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(e)}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,o=1,c=s!==this.scrollState.lastTargetOffset;if(!c&&C6(s,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=o){this.scrollState=null;return}}else this.scrollState.stableFrames=0,c&&(this.scrollState.lastTargetOffset=s,this.scrollState.behavior="auto",this._scrollToOffset(s,{adjustments:void 0,behavior:"auto"}));this.scheduleScrollReconcile()}}const VA=(t,e,n,r)=>{for(;t<=e;){const s=(t+e)/2|0,o=n(s);if(o<r)t=s+1;else if(o>r)e=s-1;else return s}return t>0?t-1:0};function U6({measurements:t,outerSize:e,scrollOffset:n,lanes:r}){const s=t.length-1,o=f=>t[f].start;if(t.length<=r)return{startIndex:0,endIndex:s};let c=VA(0,s,o,n),d=c;if(r===1)for(;d<s&&t[d].end<n+e;)d++;else if(r>1){const f=Array(r).fill(0);for(;d<s&&f.some(g=>g<n+e);){const g=t[d];f[g.lane]=g.end,d++}const p=Array(r).fill(n+e);for(;c>=0&&p.some(g=>g>=n);){const g=t[c];p[g.lane]=g.start,c--}c=Math.max(0,c-c%r),d=Math.min(s,d+(r-1-d%r))}return{startIndex:c,endIndex:d}}const t_=typeof document<"u"?A.useLayoutEffect:A.useEffect;function $6({useFlushSync:t=!0,...e}){const n=A.useReducer(()=>({}),{})[1],r={...e,onChange:(o,c)=>{var d;t&&c?gg.flushSync(n):n(),(d=e.onChange)==null||d.call(e,o,c)}},[s]=A.useState(()=>new L6(r));return s.setOptions(r),t_(()=>s._didMount(),[]),t_(()=>s._willUpdate()),s}function B6(t){return $6({observeElementRect:R6,observeElementOffset:D6,scrollToFn:M6,...t})}function bg({items:t,estimateSize:e,renderItem:n,overscan:r=5,className:s,height:o="100%",getItemKey:c}){const d=A.useRef(null),f=typeof e=="function"?e:()=>e,p=B6({count:t.length,getScrollElement:()=>d.current,estimateSize:f,overscan:r});return h.jsx("div",{ref:d,className:s,"data-pyric-ui":"virtual-list",style:{height:o,overflowY:"auto",contain:"strict"},children:h.jsx("div",{"data-pyric-virtual-inner":!0,style:{height:`${p.getTotalSize()}px`,width:"100%",position:"relative"},children:p.getVirtualItems().map(g=>{const b=t[g.index],v=c?c(b,g.index):g.key;return h.jsx("div",{"data-pyric-virtual-row":!0,"data-index":g.index,ref:p.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${g.start}px)`},children:n(b,g.index)},v)})})})}const F6={batch:"batch write",transaction:"transaction","listener-run":"listener re-evals"};function P6({group:t,defaultExpanded:e=!1,onSelect:n,selectedId:r,renderClassification:s,formatTime:o,className:c}){const[d,f]=A.useState(e);return h.jsxs("div",{className:c,"data-pyric-traffic-group":"","data-pyric-group-kind":t.kind,"data-pyric-expanded":d?"":void 0,children:[h.jsxs("button",{type:"button",onClick:()=>f(p=>!p),"data-pyric-traffic-group-header":"","data-pyric-group-kind":t.kind,"aria-expanded":d,children:[h.jsx("span",{"data-pyric-group-kind-label":"",children:F6[t.kind]}),h.jsxs("span",{"data-pyric-group-count":"",children:["×",t.count]}),t.denies>0?h.jsxs("span",{"data-pyric-group-denies":"",children:[t.denies," denied"]}):null]}),d?h.jsx("ul",{"data-pyric-traffic-group-members":"",children:t.events.map(p=>h.jsx("li",{"data-pyric-traffic-entry":"","data-pyric-traffic-id":p.id,children:h.jsx(zA,{event:p,selected:p.id===r,onSelect:n,renderClassification:s,formatTime:o})},p.id))}):null]})}function q6(t){return t<0?0:t>1?1:t}function Xp(t,e){const n=e.end-e.start;return n<=0?0:q6((t-e.start)/n)}function z6({events:t,buckets:e,window:n,bucketCount:r=30,brush:s,onBrush:o,renderBucketSummary:c,liveAt:d,header:f,axis:p,emptyState:g,className:b}){const v=A.useId(),[x,_]=A.useState(null),[k,R]=A.useState(null),C=p6({events:t??[],window:n,bucketCount:r}),T=e??C,{buckets:U,total:q}=T,I=x??k,N=I===null?null:U.find(w=>w.index===I)??null,M=N!==null&&(s==null?void 0:s.start)===N.start&&s.end===N.end;if(U.length===0)return h.jsx("div",{className:b,"data-pyric-ui":"traffic-timeline","data-pyric-empty":"",children:g});const L=q===0,H=d===void 0?n.end:d,P=H==null?null:Xp(H,n),F=typeof p=="function"?p(n):p;return h.jsxs("div",{className:b,"data-pyric-ui":"traffic-timeline","data-pyric-empty":L?"":void 0,children:[f!==void 0&&h.jsx("div",{"data-pyric-timeline-header":"",children:f}),h.jsxs("div",{"data-pyric-timeline-chart":"",children:[h.jsx("div",{"data-pyric-timeline-bars":"",role:o?"group":"img","aria-label":"request volume over time",children:U.map(w=>h.jsx(V6,{bucket:w,window:n,onBrush:o,onHover:c?_:void 0,onFocus:c?R:void 0,summaryId:c&&!M&&(N==null?void 0:N.index)===w.index?v:void 0,selected:(s==null?void 0:s.start)===w.start&&s.end===w.end},w.index))}),N&&c&&!M?h.jsx("div",{id:v,role:"tooltip","data-pyric-bucket-summary":"",style:{"--pyric-bucket-summary-x":(N.index+.5)/Math.max(U.length,1)},children:c(N)}):null,s&&h.jsx("div",{"data-pyric-brush":"","aria-hidden":"true",style:{"--pyric-brush-left":Xp(s.start,n),"--pyric-brush-right":1-Xp(s.end,n)}}),P!=null&&h.jsx("div",{"data-pyric-live":"","aria-hidden":"true",style:{"--pyric-live-x":P}})]}),F!=null&&h.jsx("div",{"data-pyric-timeline-axis":"",children:F})]})}function V6({bucket:t,window:e,onBrush:n,onHover:r,onFocus:s,summaryId:o,selected:c}){const d=n!==void 0,f=`${t.count} ${t.count===1?"request":"requests"}`,p=`${t.denies} denied`;return h.jsxs("button",{type:"button","data-pyric-bucket":"","data-pyric-bucket-index":t.index,"data-pyric-bucket-count":t.count,"data-pyric-bucket-denies":t.denies,"data-pyric-has-denies":t.denies>0?"":void 0,"data-pyric-bucket-selected":c?"":void 0,disabled:!d,"aria-label":`${f}, ${p}`,"aria-describedby":o,"aria-pressed":d?c:void 0,onPointerEnter:r?()=>r(t.index):void 0,onPointerLeave:r?()=>r(null):void 0,onFocus:s?()=>s(t.index):void 0,onBlur:s?()=>s(null):void 0,onClick:d?()=>n==null?void 0:n({start:t.start,end:t.end}):void 0,style:{"--pyric-bucket-h":t.heightRatio,"--pyric-bucket-deny-h":t.denyHeightRatio},children:[h.jsx("span",{"data-pyric-bucket-allow":"","aria-hidden":"true"}),h.jsx("span",{"data-pyric-bucket-deny":"","aria-hidden":"true"})]})}const H6=t=>String(t);function G6({series:t,visible:e,onToggle:n,formatValue:r=H6,className:s}){const o=e!==void 0&&n!==void 0;return h.jsx("div",{className:s,"data-pyric-ui":"traffic-metric-cards",role:o?"group":void 0,children:t.map((c,d)=>{const f=e?e.has(c.key):!0,p=h.jsxs(h.Fragment,{children:[h.jsx("span",{"data-pyric-metric-swatch":"","aria-hidden":"true"}),h.jsx("span",{"data-pyric-metric-label":"",children:c.label}),h.jsx("span",{"data-pyric-metric-value":"",children:r(c.total)})]});return o?h.jsxs("label",{"data-pyric-metric-card":"","data-pyric-metric-key":c.key,"data-pyric-series-index":d,"data-pyric-metric-hidden":f?void 0:"",children:[h.jsx("input",{type:"checkbox",checked:f,onChange:()=>n(c.key),"data-pyric-metric-checkbox":""}),p]},c.key):h.jsx("span",{"data-pyric-metric-card":"","data-pyric-metric-key":c.key,"data-pyric-series-index":d,children:p},c.key)})})}const K6=t=>String(t),Y6=t=>new Date(t).toLocaleTimeString();function Z6({points:t,series:e,visible:n,omitZeroSeries:r=!1,formatValue:s=K6,formatTime:o=Y6,emptyState:c,className:d}){const[f,p]=A.useState(null);if(t.length===0)return h.jsx("div",{className:d,"data-pyric-ui":"traffic-line-chart","data-pyric-empty":"",children:c});const g=e.filter(C=>(!n||n.has(C.key))&&(!r||C.total>0));let b=0;for(const C of g)for(const T of C.values)T>b&&(b=T);const v=b===0?1:b,x=t.length,_=C=>x===1?50:C/(x-1)*100,k=C=>100-C/v*100,R=f!=null?t[f]:null;return h.jsx("div",{className:d,"data-pyric-ui":"traffic-line-chart",children:h.jsxs("div",{"data-pyric-chart-svg":"",children:[h.jsx("svg",{viewBox:"0 0 100 100",preserveAspectRatio:"none",role:"img","aria-label":"metrics over time",children:e.map(C=>{const T=e.indexOf(C);if(!((!n||n.has(C.key))&&(!r||C.total>0)))return null;const q=C.values.map((I,N)=>`${N===0?"M":"L"}${_(N)},${k(I)}`).join(" ");return h.jsx("path",{"data-pyric-chart-line":"","data-pyric-series-key":C.key,"data-pyric-series-index":T,d:q,fill:"none",vectorEffect:"non-scaling-stroke"},C.key)})}),h.jsx("div",{"data-pyric-chart-hits":"",children:t.map((C,T)=>h.jsx("button",{type:"button","data-pyric-chart-hit":"","data-pyric-point-index":T,onMouseEnter:()=>p(T),onFocus:()=>p(T),onMouseLeave:()=>p(U=>U===T?null:U),onBlur:()=>p(U=>U===T?null:U),"aria-label":`${o(C.start)} to ${o(C.end)}`},C.index))}),R&&h.jsxs("div",{"data-pyric-chart-tooltip":"",style:{"--pyric-hover-x":_(R.index)},children:[h.jsxs("div",{"data-pyric-tooltip-time":"",children:[o(R.start)," – ",o(R.end)]}),g.map(C=>h.jsxs("div",{"data-pyric-tooltip-row":"","data-pyric-series-key":C.key,"data-pyric-series-index":e.indexOf(C),children:[h.jsx("span",{"data-pyric-tooltip-label":"",children:C.label}),h.jsx("span",{"data-pyric-tooltip-value":"",children:s(C.values[R.index])})]},C.key))]})]})})}const W6={listUsers:Kn.listUsers,subscribeUsers:Kn.subscribeUsers,createUser:Kn.createUser,updateUser:Kn.updateUser,deleteUser:Kn.deleteUser,clearUsers:Kn.clearUsers,getAuthProviderConfig:Kn.getAuthProviderConfig,setAuthProviderConfig:Kn.setAuthProviderConfig,subscribeAuthProviderConfig:Kn.subscribeAuthProviderConfig},HA=A.createContext(W6);function J6(){return A.useContext(HA)}function GA({value:t,children:e}){return A.createElement(HA.Provider,{value:t},e)}function Q6(t,e){return[t.uid,t.email,t.displayName,t.phoneNumber].some(n=>n!=null&&n.toLowerCase().includes(e))}function vg(t){const{listUsers:e,subscribeUsers:n,createUser:r,updateUser:s,deleteUser:o,clearUsers:c}=J6(),[d,f]=A.useState([]),[p,g]=A.useState(!0),[b,v]=A.useState(void 0),[x,_]=A.useState("");A.useEffect(()=>{let I=!1;g(!0),v(void 0);const N=P=>{I||(f(P),g(!1))},M=P=>{I||(f([]),v(P instanceof Error?P:new Error(String(P))),g(!1))},L=()=>{try{const P=e(t);P&&typeof P.then=="function"?P.then(N).catch(M):N(P)}catch(P){M(P)}};let H;try{L(),H=n(t,L)}catch(P){M(P)}return()=>{I=!0,H==null||H()}},[t,e,n]);const k=A.useMemo(()=>{const I=x.trim().toLowerCase();return I?d.filter(N=>Q6(N,I)):d},[d,x]),R=A.useCallback(I=>r(t,I),[t,r]),C=A.useCallback((I,N)=>s(t,I,N),[t,s]),T=A.useCallback(I=>o(t,I),[t,o]),U=A.useCallback(()=>c(t),[t,c]),q=A.useCallback(()=>{const I=e(t);I&&typeof I.then=="function"?I.then(N=>f(N)).catch(()=>{}):f(I)},[t,e]);return{users:k,totalCount:d.length,isLoading:p,error:b,filter:x,setFilter:_,createUser:R,updateUser:C,deleteUser:T,clearUsers:U,refresh:q}}const X6=["iss","aud","sub","iat","exp","nbf","jti","nonce","azp","acr","amr","cnf","auth_time","firebase","at_hash","c_hash"],eB=1e3;function KA(t){const e=t.trim();if(!e)return{ok:!0,claims:void 0};if(e.length>eB)return{ok:!1,message:"Custom claims length must not exceed 1000 characters"};let n;try{n=JSON.parse(e)}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 X6)if(r in n)return{ok:!1,message:`Custom claims must not have forbidden key: ${r}`};return{ok:!0,claims:n}}const tB={email:"",password:"",displayName:"",phoneNumber:"",photoUrl:"",emailVerified:!1,disabled:!1,claimsText:"",providerIds:[]},nB=new Set(["password","anonymous","phone"]),rB=/^[^@]+@[^@]+\.[^@]+$/,n_=6;function sB(t){return t?{email:t.email??"",password:"",displayName:t.displayName??"",phoneNumber:t.phoneNumber??"",photoUrl:t.photoUrl??"",emailVerified:t.emailVerified,disabled:t.disabled,claimsText:Object.keys(t.customClaims).length?JSON.stringify(t.customClaims,null,2):"",providerIds:t.providerUserInfo.map(e=>e.providerId).filter(e=>!nB.has(e))}:{...tB}}function iB(t){const e=sB(t);return{fields:e,initial:{...e}}}function aB(t,e){switch(e.type){case"setField":return{...t,fields:{...t.fields,[e.field]:e.value}};case"reset":return{...t,fields:{...t.initial}}}}function oB(t){const e={},n=t.email.trim(),r=t.password;n&&!rB.test(n)&&(e.email="Invalid email"),r&&r.length<n_&&(e.password=`Password should be at least ${n_} characters`),r&&!n&&(e.password="Email is required for password authentication");const s=KA(t.claimsText);return s.ok||(e.claims=s.message),e}function lB(t){const{fields:e,initial:n}=t;return Object.keys(e).some(r=>r==="providerIds"?!YA(e.providerIds,n.providerIds):e[r]!==n[r])}function YA(t,e){if(t.length!==e.length)return!1;const n=[...e].sort();return[...t].sort().every((r,s)=>r===n[s])}function ZA(t){const e=KA(t.claimsText);return e.ok?e.claims:void 0}function cB(t){const e=t.fields,n={emailVerified:e.emailVerified,disabled:e.disabled};e.email.trim()&&(n.email=e.email.trim()),e.password&&(n.password=e.password),e.displayName.trim()&&(n.displayName=e.displayName.trim()),e.phoneNumber.trim()&&(n.phoneNumber=e.phoneNumber.trim()),e.photoUrl.trim()&&(n.photoUrl=e.photoUrl.trim());const r=ZA(e);return r&&(n.customClaims=r),e.providerIds.length&&(n.providerUserInfo=e.providerIds.map(s=>({providerId:s}))),n}function uB(t){const{fields:e,initial:n}=t,r={};return e.email.trim()!==n.email&&e.email.trim()&&(r.email=e.email.trim()),e.password&&e.password!==n.password&&(r.password=e.password),e.displayName.trim()!==n.displayName&&(r.displayName=e.displayName.trim()||null),e.emailVerified!==n.emailVerified&&(r.emailVerified=e.emailVerified),e.disabled!==n.disabled&&(r.disabled=e.disabled),e.claimsText!==n.claimsText&&(r.customClaims=ZA(e)??{}),YA(e.providerIds,n.providerIds)||(r.providerUserInfo=e.providerIds.map(s=>({providerId:s}))),r}function WA(t={}){const[e,n]=A.useReducer(aB,t.initial,iB),r=A.useMemo(()=>oB(e.fields),[e.fields]),s=A.useMemo(()=>lB(e),[e]),o=A.useCallback((d,f)=>n({type:"setField",field:d,value:f}),[]),c=A.useCallback(()=>n({type:"reset"}),[]);return{fields:e.fields,errors:r,isDirty:s,isValid:Object.keys(r).length===0,setField:o,reset:c,toCreateRequest:()=>cB(e),toUpdateRequest:()=>uB(e),dispatch:n}}const dB={"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 vd(t){return dB[t]??t}function r_(t){return t.email??t.phoneNumber??(t.isAnonymous?"anonymous":t.uid)}function fB(t){return t.isAnonymous&&t.providerUserInfo.length===0?h.jsx("span",{"data-pyric-provider-id":"anonymous",children:vd("anonymous")}):t.providerUserInfo.map(e=>h.jsx("span",{"data-pyric-provider-id":e.providerId,children:vd(e.providerId)},e.providerId))}function s_(t){if(!t)return"—";const e=new Date(t);return Number.isNaN(e.getTime())?"—":e.toLocaleDateString()}function JA({users:t,isLoading:e,error:n,filter:r,onSelect:s,renderIdentifier:o,renderProviders:c,renderSelection:d,renderSelectionHeader:f,renderActions:p,renderActionsHeader:g,formatCreatedAt:b=s_,formatLastLoginAt:v=s_,emptyState:x,noResultsState:_,className:k,virtualizeThreshold:R=100,rowHeight:C=44,virtualizedHeight:T="60vh"}){if(n)return h.jsx("div",{className:k,"data-pyric-ui":"auth-user-list","data-pyric-error":"",role:"alert",children:n.message});if(e&&t.length===0)return h.jsx("div",{className:k,"data-pyric-ui":"auth-user-list","data-pyric-loading":""});if(t.length===0){const I=!!(r!=null&&r.trim());return h.jsx("div",{className:k,"data-pyric-ui":"auth-user-list","data-pyric-empty":"","data-pyric-no-results":I?"":void 0,children:I?_??"No results":x??"No users for this project yet"})}const U=t.length>R,q=I=>h.jsxs("div",{role:"row","data-pyric-user-entry":!0,"data-pyric-user-uid":I.uid,"data-pyric-user-disabled":I.disabled?"":void 0,children:[d?h.jsx("span",{role:"cell","data-pyric-user-cell":"selection",children:d(I)}):null,h.jsx("span",{role:"cell","data-pyric-user-cell":"identifier",children:s?h.jsx("button",{type:"button","data-pyric-user-select":!0,onClick:()=>s(I),children:o?o(I):r_(I)}):(o??r_)(I)}),h.jsx("span",{role:"cell","data-pyric-user-cell":"providers",children:(c??fB)(I)}),h.jsx("span",{role:"cell","data-pyric-user-cell":"created",children:b(I.createdAt)}),h.jsx("span",{role:"cell","data-pyric-user-cell":"signed-in",children:v(I.lastLoginAt)}),h.jsx("span",{role:"cell","data-pyric-user-cell":"uid",children:I.uid}),p?h.jsx("span",{role:"cell","data-pyric-user-cell":"actions",children:p(I)}):null]},I.uid);return h.jsxs("div",{className:k,role:"table","aria-label":"Authentication users","data-pyric-ui":"auth-user-list","data-pyric-virtualized":U?"":void 0,"data-pyric-selection":d?"":void 0,"data-pyric-actions":p?"":void 0,children:[h.jsxs("div",{role:"row","data-pyric-user-header":!0,children:[d?h.jsx("span",{role:"columnheader","data-pyric-user-cell":"selection","aria-label":"Selection",children:f}):null,h.jsx("span",{role:"columnheader","data-pyric-user-cell":"identifier",children:"Identifier"}),h.jsx("span",{role:"columnheader","data-pyric-user-cell":"providers",children:"Provider"}),h.jsx("span",{role:"columnheader","data-pyric-user-cell":"created",children:"Created"}),h.jsx("span",{role:"columnheader","data-pyric-user-cell":"signed-in",children:"Signed In"}),h.jsx("span",{role:"columnheader","data-pyric-user-cell":"uid",children:"User UID"}),p?h.jsx("span",{role:"columnheader","data-pyric-user-cell":"actions","aria-label":"Actions",children:g}):null]}),U?h.jsx(bg,{items:t,estimateSize:C,height:T,getItemKey:I=>I.uid,renderItem:q}):h.jsx("div",{role:"rowgroup","data-pyric-user-rows":!0,children:t.map(q)})]})}function hB({value:t,onChange:e,error:n,hint:r,placeholder:s='{"role":"admin"}',className:o}){return h.jsxs("div",{className:o,"data-pyric-ui":"claims-field",children:[h.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:t,onChange:c=>e(c.target.value)}),n!=null&&h.jsx("p",{role:"alert","data-pyric-claims-error":!0,children:n}),r!=null&&h.jsx("p",{"data-pyric-claims-hint":!0,children:r})]})}function pB({selected:t,onChange:e}){return h.jsx("div",{"data-pyric-provider-checklist":!0,children:_A.map(n=>h.jsxs("label",{"data-pyric-provider-option":n,children:[h.jsx("input",{type:"checkbox",checked:t.includes(n),onChange:r=>e(r.target.checked?[...t,n]:t.filter(s=>s!==n))}),h.jsx("span",{"data-pyric-provider-option-label":!0,children:vd(n)}),h.jsx("span",{"data-pyric-provider-option-id":!0,children:n})]},n))})}function QA({initial:t,onSubmit:e,onCancel:n,submitLabel:r="Save",cancelLabel:s="Cancel",children:o,className:c,renderField:d}){const f=WA({initial:t}),p=t?"edit":"create",g=f.isValid&&(p==="create"||f.isDirty),b=(_,k,R,C,T=null)=>({name:_,label:k,input:C,error:T,kind:R,defaultRender:()=>R==="checkbox"?h.jsxs("label",{"data-pyric-field-label":_,children:[C,h.jsx("span",{"data-pyric-label-text":!0,children:k})]},_):R==="group"?h.jsxs("fieldset",{"data-pyric-field-label":_,children:[h.jsx("legend",{"data-pyric-label-text":!0,children:k}),C]},_):h.jsxs("label",{"data-pyric-field-label":_,children:[h.jsx("span",{"data-pyric-label-text":!0,children:k}),C,T!=null&&h.jsx("p",{role:"alert","data-pyric-field-error":_,children:T})]},_)}),v=[b("email","Email","text",h.jsx("input",{type:"email","data-pyric-field":"email",placeholder:"email@example.com",value:f.fields.email,onChange:_=>f.setField("email",_.target.value)}),f.errors.email??null),b("password","Password","text",h.jsx("input",{type:"password","data-pyric-field":"password",placeholder:p==="edit"?"New password (unchanged if empty)":"Password",value:f.fields.password,onChange:_=>f.setField("password",_.target.value)}),f.errors.password??null),b("display-name","Display name","text",h.jsx("input",{type:"text","data-pyric-field":"display-name",placeholder:"Display name (optional)",value:f.fields.displayName,onChange:_=>f.setField("displayName",_.target.value)})),b("phone-number","Phone number","text",h.jsx("input",{type:"tel","data-pyric-field":"phone-number",placeholder:"+1 555 555 0100",value:f.fields.phoneNumber,onChange:_=>f.setField("phoneNumber",_.target.value)})),b("photo-url","Photo URL","text",h.jsx("input",{type:"url","data-pyric-field":"photo-url",placeholder:"https://example.com/avatar.png",value:f.fields.photoUrl,onChange:_=>f.setField("photoUrl",_.target.value)})),...p==="create"?[b("providers","Sign-in providers","group",h.jsx(pB,{selected:f.fields.providerIds,onChange:_=>f.setField("providerIds",_)}))]:[],b("email-verified","Verified email","checkbox",h.jsx("input",{type:"checkbox","data-pyric-field":"email-verified",checked:f.fields.emailVerified,onChange:_=>f.setField("emailVerified",_.target.checked)})),b("disabled","Disabled (sign-in attempts are rejected)","checkbox",h.jsx("input",{type:"checkbox","data-pyric-field":"disabled",checked:f.fields.disabled,onChange:_=>f.setField("disabled",_.target.checked)}))],x=_=>{_.preventDefault(),g&&e(p==="edit"?{mode:p,uid:t.uid,request:f.toUpdateRequest()}:{mode:p,request:f.toCreateRequest()})};return h.jsxs("form",{className:c,"data-pyric-ui":"auth-user-form","data-pyric-mode":p,"data-pyric-is-dirty":f.isDirty?"":void 0,"data-pyric-is-valid":f.isValid?"":void 0,onSubmit:x,children:[v.map(_=>d?h.jsx(A.Fragment,{children:d(_)},_.name):_.defaultRender()),h.jsx(hB,{value:f.fields.claimsText,onChange:_=>f.setField("claimsText",_),error:f.errors.claims}),o,h.jsxs("footer",{"data-pyric-form-actions":!0,children:[n?h.jsx("button",{type:"button","data-pyric-cancel":!0,onClick:n,children:s}):null,h.jsx("button",{type:"submit","data-pyric-submit":!0,disabled:!g,children:r})]})]})}function mB({open:t,onOpenChange:e,title:n,body:r,destructive:s,confirmLabel:o="Confirm",cancelLabel:c="Cancel",onConfirm:d,className:f}){const p=A.useRef(null),g=A.useRef(null);return A.useEffect(()=>{if(!t)return;const b=v=>{v.key==="Escape"&&(v.stopPropagation(),e(!1))};return window.addEventListener("keydown",b),()=>window.removeEventListener("keydown",b)},[t,e]),A.useEffect(()=>{var b;if(t)return g.current=document.activeElement,(b=p.current)==null||b.focus(),()=>{var x;const v=g.current;(x=v==null?void 0:v.focus)==null||x.call(v)}},[t]),!t||typeof document>"u"?null:gg.createPortal(h.jsxs("div",{role:"presentation","data-pyric-ui":"confirm-portal",onClick:b=>{b.target===b.currentTarget&&e(!1)},children:[h.jsx("div",{"data-pyric-ui":"confirm-overlay","aria-hidden":"true"}),h.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"pyric-confirm-title","aria-describedby":r?"pyric-confirm-body":void 0,className:f,"data-pyric-ui":"confirm-dialog","data-pyric-destructive":s?"":void 0,children:[h.jsx("div",{id:"pyric-confirm-title","data-pyric-confirm-title":!0,children:n}),r?h.jsx("div",{id:"pyric-confirm-body","data-pyric-confirm-body":!0,children:r}):null,h.jsxs("div",{"data-pyric-confirm-actions":!0,children:[h.jsx("button",{type:"button","data-pyric-confirm-cancel":!0,onClick:()=>e(!1),children:c}),h.jsx("button",{ref:p,type:"button","data-pyric-confirm-confirm":!0,"data-pyric-destructive":s?"":void 0,onClick:d,children:o})]})]})]}),document.body)}const XA=A.createContext(null);function lo(){const t=A.useContext(XA);if(!t)throw new Error("useConfirm: missing <ConfirmProvider> ancestor");return t}function xg({children:t,dialogClassName:e}){const[n,r]=A.useState(null),s=A.useRef(!1),o=A.useCallback(p=>new Promise(g=>{s.current=!1,r({options:p,resolve:g})}),[]),c=A.useCallback(()=>{n&&(s.current||(s.current=!0,n.resolve(!0),r(null)))},[n]),d=A.useCallback(p=>{p||n&&(s.current||(s.current=!0,n.resolve(!1),r(null)))},[n]),f=A.useMemo(()=>o,[o]);return h.jsxs(XA.Provider,{value:f,children:[t,n?h.jsx(mB,{open:!0,onOpenChange:d,title:n.options.title,body:n.options.body,destructive:n.options.destructive,confirmLabel:n.options.confirmLabel,cancelLabel:n.options.cancelLabel,onConfirm:c,className:e}):null]})}function yB(t){return t.email??t.phoneNumber??t.displayName??t.uid}function gB({user:t,onDelete:e,title:n="Delete user",body:r,confirmLabel:s="Delete",renderTrigger:o,className:c}){const d=lo(),f=async()=>{await d({title:n,body:r??`This will permanently delete ${yB(t)}.`,destructive:!0,confirmLabel:s})&&e(t.uid)};return o?h.jsx(h.Fragment,{children:o({onClick:f})}):h.jsx("button",{type:"button",className:c,"data-pyric-ui":"delete-user","data-pyric-destructive":!0,onClick:f,children:"Delete user"})}function bB(t){if(t instanceof Error)return t;if(typeof t=="string")return new Error(t);if(t&&typeof t=="object"){const e=t,n=typeof e.message=="string"?e.message:null,r=typeof e.code=="string"?e.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(t))}catch{return new Error(Object.prototype.toString.call(t))}}return new Error(String(t))}const vB={addDoc:lg,collection:Ti,deleteDoc:Dl,doc:Yn,getDoc:og,getDocs:Tl,limit:fd,onSnapshot:KL,query:Il,setDoc:Rl,startAfter:GL},ej=A.createContext(vB);function wg(){return A.useContext(ej)}function xB({value:t,children:e}){return A.createElement(ej.Provider,{value:t},e)}function wB(t){const{onSnapshot:e}=wg(),[n,r]=A.useState(()=>({data:void 0,error:void 0,isLoading:t!=null}));return A.useEffect(()=>{if(!t){r({data:void 0,error:void 0,isLoading:!1});return}return r(o=>({data:o.data,error:void 0,isLoading:!0})),e(t,o=>r({data:o,error:void 0,isLoading:!1}),o=>r({data:void 0,error:bB(o),isLoading:!1}))},[e,t]),n}function Gd(t){return t==null?"null":typeof t=="string"?"string":typeof t=="number"?"number":typeof t=="boolean"?"boolean":typeof t=="object"&&Ki(t)!==null?"vector":Array.isArray(t)?"array":t instanceof Mn?"timestamp":t instanceof Cr?"geopoint":t instanceof Sr?"bytes":typeof t=="object"&&tj(t)?"timestamp":typeof t=="object"&&nj(t)?"geopoint":typeof t=="object"&&SB(t)?"reference":typeof t=="object"?"map":"null"}function tj(t){const e=t;return Object.keys(e).length!==2?!1:typeof e.seconds=="number"&&typeof e.nanoseconds=="number"||typeof e._seconds=="number"&&typeof e._nanoseconds=="number"}function nj(t){const e=t;return Object.keys(e).length===2&&typeof e.latitude=="number"&&typeof e.longitude=="number"}function SB(t){const e=t;if(typeof e.path!="string"||typeof e.id!="string")return!1;const n=typeof e.firestore=="object"&&e.firestore!==null,r=typeof e.env=="object"&&e.env!==null,s=e.type==="document";return n||r||s}function Ki(t){if(t===null||typeof t!="object")return null;const e=t;if(e.typeName==="vector"&&Eu(e.value)||e.__type__==="__vector__"&&Eu(e.value))return Au(e.value);if(Eu(e._values))return Au(e._values);if(typeof e.toArray=="function")try{const n=e.toArray();if(Eu(n))return Au(n)}catch{}return null}function Eu(t){return Array.isArray(t)&&t.every(e=>typeof e=="number")}function Au(t){const e=t.slice();return{values:e,dimension:e.length}}const i_=4;function rj(t){const e=t.values.slice(0,i_).join(", "),n=t.values.length>i_?", …":"";return`vector · ${t.dimension} [${e}${n}]`}function Xa(t){const e=Ki(t);if(e)return rj(e);if(Array.isArray(t))return t.map(Xa);if(t&&typeof t=="object"){const n=Object.getPrototypeOf(t);if(n===Object.prototype||n===null){const r={};for(const[s,o]of Object.entries(t))r[s]=Xa(o);return r}}return t}function sj(){return crypto.randomUUID()}function _B(t){const e=sj(),n={rootId:e,nodes:{[e]:{id:e,parentId:null,key:null,type:"map",value:void 0}},childIds:{[e]:[]}};for(const[r,s]of Object.entries(t))my(n,e,r,s);return n}function my(t,e,n,r){const s=Gd(r),o=sj(),c={id:o,parentId:e,key:n,type:s,value:EB(s)?void 0:r};if(t.nodes[o]=c,t.childIds[o]=[],t.childIds[e].push(o),s==="map"&&r&&typeof r=="object")for(const[d,f]of Object.entries(r))my(t,o,d,f);else if(s==="array"&&Array.isArray(r))for(const d of r)my(t,o,null,d);return o}function EB(t){return t==="map"||t==="array"}function ij(t){const e=t.nodes[t.rootId];if(!e||e.type!=="map")throw new Error("treeToData: tree root must be a map node");return yy(t,t.rootId)}function yy(t,e){const n=t.nodes[e];if(!n)throw new Error(`serializeNode: missing node ${e}`);switch(n.type){case"map":{const r={};for(const s of t.childIds[e]??[]){const o=t.nodes[s];o&&o.key!=null&&(r[o.key]=yy(t,s))}return r}case"array":{const r=[];for(const s of t.childIds[e]??[])r.push(yy(t,s));return r}default:return n.value}}function gy(t){const e={};for(const[r,s]of Object.entries(t.nodes))e[r]={...s};const n={};for(const[r,s]of Object.entries(t.childIds))n[r]=[...s];return{rootId:t.rootId,nodes:e,childIds:n}}function aj(t,e){const n=[e],r=[e];for(;r.length;){const s=r.shift();for(const o of t.childIds[s]??[])n.push(o),r.push(o)}return n}function oj(t,e){switch(t){case"string":return typeof e=="string"?void 0:"Expected a string";case"number":return typeof e!="number"?"Expected a number":Number.isFinite(e)?void 0:"Number must be finite";case"boolean":return typeof e=="boolean"?void 0:"Expected a boolean";case"null":return e==null?void 0:"Expected null";case"timestamp":return e instanceof Mn?void 0:"Expected a Timestamp";case"geopoint":return e instanceof Cr?e.latitude<-90||e.latitude>90?"Latitude must be between -90 and 90":e.longitude<-180||e.longitude>180?"Longitude must be between -180 and 180":void 0:"Expected a GeoPoint";case"reference":if(e===null||typeof e!="object")return"Expected a DocumentReference";const n=e;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 e instanceof Sr?void 0:"Expected a Bytes value";case"vector":return Ki(e)!==null?void 0:"Expected a vector value";case"map":case"array":return}}function lj(t){const e={};let n=0;for(const[r,s]of Object.entries(t.nodes))e[r]={...s,error:void 0};for(const r of Object.values(e)){if(r.type==="map"||r.type==="array")continue;const s=oj(r.type,r.value);s&&(e[r.id].error=s,n++)}for(const[r,s]of Object.entries(e)){if(s.type!=="map")continue;const o=t.childIds[r]??[],c=new Map;for(const d of o){const f=e[d];if(!f)continue;const p=f.key??"";p||(f.error||n++,e[d].error=e[d].error??"Field name is required");const g=c.get(p)??[];g.push(d),c.set(p,g)}for(const[d,f]of c)if(d&&f.length>1)for(const p of f)e[p].error||n++,e[p].error=e[p].error??"Field name must be unique"}return{tree:{rootId:t.rootId,nodes:e,childIds:t.childIds},errorCount:n}}function Sg(t){switch(t){case"string":return"";case"number":return 0;case"boolean":return!1;case"null":return null;case"timestamp":return Mn.now();case"geopoint":return new Cr(0,0);case"reference":return{path:"",id:"",firestore:{}};case"bytes":return Sr.fromUint8Array(new Uint8Array);case"vector":return{__type__:"__vector__",value:[]};case"map":case"array":return}}function by(t){if(t===null||typeof t!="object"||Ki(t)!==null)return t;if(tj(t)){const n=t;return new Mn(n.seconds??n._seconds??0,n.nanoseconds??n._nanoseconds??0)}if(nj(t)){const n=t;return new Cr(n.latitude,n.longitude)}if(Array.isArray(t))return t.map(by);const e=Object.getPrototypeOf(t);if(e===Object.prototype||e===null){const n={};for(const[r,s]of Object.entries(t))n[r]=by(s);return n}return t}function cj(t){const e=_B(by(t)),{tree:n,errorCount:r}=lj(e);return{tree:n,initial:n,errorCount:r}}function AB(t,e){switch(e.type){case"setValue":return La(t,n=>kB(n,e.nodeId,e.value));case"setType":return La(t,n=>CB(n,e.nodeId,e.newType));case"setKey":return La(t,n=>NB(n,e.nodeId,e.key));case"addMapEntry":return La(t,n=>OB(n,e.parentId,e.key,e.childType));case"addArrayEntry":return La(t,n=>TB(n,e.parentId,e.childType));case"remove":return La(t,n=>RB(n,e.nodeId));case"reset":return{tree:t.initial,initial:t.initial,errorCount:jB(t.initial)};case"replaceData":return cj(e.data);case"touch":{const n=t.tree.nodes[e.nodeId];if(!n||n.touched)return t;const r=gy(t.tree);return r.nodes[e.nodeId]={...r.nodes[e.nodeId],touched:!0},{...t,tree:r}}case"touchAll":{const n=gy(t.tree);for(const r of Object.keys(n.nodes))n.nodes[r]={...n.nodes[r],touched:!0};return{...t,tree:n}}}}function La(t,e){const n=e(gy(t.tree)),{tree:r,errorCount:s}=lj(n);return{...t,tree:r,errorCount:s}}function jB(t){let e=0;for(const n of Object.values(t.nodes))n.error&&e++;return e}function kB(t,e,n){const r=t.nodes[e];return!r||r.type==="map"||r.type==="array"||(t.nodes[e]={...r,value:n}),t}function CB(t,e,n){const r=t.nodes[e];if(!r||r.id===t.rootId&&n!=="map"||r.type===n)return t;if(r.type==="map"||r.type==="array"){const o=(t.childIds[e]??[]).slice();for(const c of o)for(const d of aj(t,c))delete t.nodes[d],delete t.childIds[d];t.childIds[e]=[]}const s=n==="map"||n==="array"?void 0:Sg(n);return t.nodes[e]={...r,type:n,value:s},t}function NB(t,e,n){const r=t.nodes[e];if(!r||r.parentId==null)return t;const s=t.nodes[r.parentId];return!s||s.type!=="map"||(t.nodes[e]={...r,key:n}),t}function OB(t,e,n,r){const s=t.nodes[e];if(!s||s.type!=="map")return t;const o=crypto.randomUUID(),c=r==="map"||r==="array"?void 0:Sg(r);return t.nodes[o]={id:o,parentId:e,key:n,type:r,value:c},t.childIds[o]=[],t.childIds[e]=[...t.childIds[e]??[],o],t}function TB(t,e,n){const r=t.nodes[e];if(!r||r.type!=="array"||n==="array")return t;const s=crypto.randomUUID(),o=n==="map"?void 0:Sg(n);return t.nodes[s]={id:s,parentId:e,key:null,type:n,value:o},t.childIds[s]=[],t.childIds[e]=[...t.childIds[e]??[],s],t}function RB(t,e){const n=t.nodes[e];if(!n||n.id===t.rootId)return t;const r=aj(t,e);for(const s of r)delete t.nodes[s],delete t.childIds[s];return n.parentId!=null&&(t.childIds[n.parentId]=(t.childIds[n.parentId]??[]).filter(s=>s!==e)),t}function uj(t={}){const e=t.initial??{},n=A.useRef(null);n.current==null&&(n.current=cj(e));const[r,s]=A.useReducer(AB,n.current),o=A.useCallback((T,U)=>s({type:"setValue",nodeId:T,value:U}),[]),c=A.useCallback((T,U)=>s({type:"setType",nodeId:T,newType:U}),[]),d=A.useCallback((T,U)=>s({type:"setKey",nodeId:T,key:U}),[]),f=A.useCallback((T,U,q)=>s({type:"addMapEntry",parentId:T,key:U,childType:q}),[]),p=A.useCallback((T,U)=>s({type:"addArrayEntry",parentId:T,childType:U}),[]),g=A.useCallback(T=>s({type:"remove",nodeId:T}),[]),b=A.useCallback(()=>s({type:"reset"}),[]),v=A.useCallback(T=>s({type:"replaceData",data:T}),[]),x=A.useCallback(T=>s({type:"touch",nodeId:T}),[]),_=A.useCallback(()=>s({type:"touchAll"}),[]),k=A.useCallback(()=>ij(r.tree),[r.tree]),R=r.tree!==r.initial,C=r.errorCount===0;return A.useMemo(()=>({...r,isDirty:R,isValid:C,dispatch:s,setValue:o,setType:c,setKey:d,addMapEntry:f,addArrayEntry:p,remove:g,reset:b,replaceData:v,touch:x,touchAll:_,toData:k}),[r,R,C,o,c,d,f,p,g,b,v,x,_,k])}function DB({collection:t,query:e,pageSize:n=50,mode:r="paged"}){const[s,o]=A.useState([]),[c,d]=A.useState(!0),[f,p]=A.useState(void 0),[g,b]=A.useState(!1),[v,x]=A.useState(0),[_,k]=A.useState(n),R=A.useRef(0),[C,T]=A.useState(0),{addDoc:U,deleteDoc:q,doc:I,getDoc:N,getDocs:M,limit:L,onSnapshot:H,query:P,setDoc:F,startAfter:w}=wg();A.useEffect(()=>{k(n)},[t,r,n,e]),A.useEffect(()=>{let $=!1;r==="paged"&&o([]),b(!1),d(!0),p(void 0);const K=e??t,W=r==="live"?_:n,se=P(K,L(W)),B=ae=>{$||(o([...ae.docs]),b(ae.docs.length===W),d(!1))},ee=ae=>{$||(p(ae instanceof Error?ae:new Error(String(ae))),d(!1))};if(r==="live"){const ae=++R.current,le=H(se,ye=>{T(ae),B(ye)},ee);return()=>{$=!0,le()}}return M(se).then(ae=>{B(ae)}).catch(ee),()=>{$=!0}},[t,M,L,r,H,n,e,P,_,v]);const E=A.useCallback(()=>{if(!g||c)return;if(r==="live"){d(!0),k(se=>se+n);return}const $=s[s.length-1];if(!$)return;d(!0);const W=P(e??t,w($),L(n));M(W).then(se=>{o(B=>[...B,...se.docs]),b(se.docs.length===n),d(!1)}).catch(se=>{p(se instanceof Error?se:new Error(String(se))),d(!1)})},[t,s,M,g,c,L,r,n,e,P,w]),O=A.useCallback(async($,K,W)=>{if($==null){const B=await U(t,K);return r==="paged"&&x(ee=>ee+1),B}const se=I(t,$);if((W==null?void 0:W.onExisting)==="fail"){const B=await N(se);if(typeof B.exists=="function"?B.exists():!!B.exists){const ae=new Error(`Document "${$}" already exists.`);throw ae.code="already-exists",ae}}return await F(se,K),r==="paged"&&x(B=>B+1),se},[U,t,I,N,r,F]),D=A.useCallback(async $=>{await q($),r==="paged"&&x(K=>K+1)},[q,r]),z=A.useCallback(()=>x($=>$+1),[]);return{documents:s,isLoading:c,error:f,subscriptionGeneration:C,hasMore:g,loadMore:E,createDocument:O,deleteDocument:D,refresh:z}}function IB({firestore:t,documentRef:e,listSubcollections:n}){const[r,s]=A.useState([]),[o,c]=A.useState(!1),[d,f]=A.useState(void 0),p=A.useRef(n);p.current=n;const g=e==null?void 0:e.path;return A.useEffect(()=>{if(!e){s([]),c(!1),f(void 0);return}let b=!1;return c(!0),f(void 0),p.current(t,e).then(v=>{b||(s(v),c(!1))}).catch(v=>{b||(f(v instanceof Error?v:new Error(String(v))),c(!1))}),()=>{b=!0}},[t,g]),{subcollections:r,isLoading:o,error:d}}function a_(t){return typeof t=="object"&&t!==null&&"isEqual"in t&&typeof t.isEqual=="function"}function o_(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function xd(t,e){if(Object.is(t,e))return!0;if(a_(t))return t.isEqual(e);if(a_(e))return e.isEqual(t);if(t instanceof Uint8Array||e instanceof Uint8Array)return!(t instanceof Uint8Array)||!(e instanceof Uint8Array)||t.length!==e.length?!1:t.every((s,o)=>s===e[o]);if(Array.isArray(t)||Array.isArray(e))return!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length?!1:t.every((s,o)=>xd(s,e[o]));if(!o_(t)||!o_(e))return!1;const n=Object.keys(t),r=Object.keys(e);return n.length!==r.length?!1:n.every(s=>s in e&&xd(t[s],e[s]))}function MB({value:t,path:e}){return h.jsx("span",{"data-pyric-field-type":"string","data-pyric-field-path":e,children:t})}function LB({value:t,onChange:e,error:n,path:r}){return h.jsxs("label",{"data-pyric-field-type":"string","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[h.jsx("input",{type:"text",value:t,onChange:s=>e(s.target.value),"aria-invalid":n?"true":void 0}),n?h.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const UB={type:"string",Display:MB,Edit:LB};function $B({value:t,path:e}){return h.jsx("span",{"data-pyric-field-type":"number","data-pyric-field-path":e,children:String(t)})}function BB({value:t,onChange:e,error:n,path:r}){return h.jsxs("label",{"data-pyric-field-type":"number","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[h.jsx("input",{type:"number",value:Number.isFinite(t)?t:"",onChange:s=>{const o=s.target.value,c=o===""?Number.NaN:parseFloat(o);e(c)},"aria-invalid":n?"true":void 0}),n?h.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const FB={type:"number",Display:$B,Edit:BB};function PB({value:t,path:e}){return h.jsx("span",{"data-pyric-field-type":"boolean","data-pyric-field-path":e,"data-value":t?"true":"false",children:t?"true":"false"})}function qB({value:t,onChange:e,path:n}){return h.jsx("span",{"data-pyric-field-type":"boolean","data-pyric-field-path":n,"data-value":t?"true":"false",children:h.jsxs("select",{value:t?"true":"false",onChange:r=>e(r.target.value==="true"),"aria-label":"Boolean value","data-pyric-boolean-select":!0,children:[h.jsx("option",{value:"true",children:"true"}),h.jsx("option",{value:"false",children:"false"})]})})}const zB={type:"boolean",Display:PB,Edit:qB};function VB({path:t}){return h.jsx("span",{"data-pyric-field-type":"null","data-pyric-field-path":t,children:"null"})}function HB({path:t}){return h.jsx("span",{"data-pyric-field-type":"null","data-pyric-field-path":t,children:"null"})}const GB={type:"null",Display:VB,Edit:HB};function dj(t){if(t instanceof Mn)return t.toDate();const e=t,n=e?e.seconds??e._seconds:void 0,r=e?e.nanoseconds??e._nanoseconds??0:0;return typeof n=="number"?new Date(n*1e3+Math.floor(r/1e6)):new Date(NaN)}function KB({value:t,path:e}){const n=dj(t),r=Number.isNaN(n.getTime())?"":n.toISOString();return h.jsx("time",{dateTime:r,"data-pyric-field-type":"timestamp","data-pyric-field-path":e,children:r})}function YB({value:t,onChange:e,error:n,path:r}){const s=dj(t),o=new Date(s.getTime()-s.getTimezoneOffset()*6e4),c=Number.isNaN(o.getTime())?"":o.toISOString().slice(0,16);return h.jsxs("label",{"data-pyric-field-type":"timestamp","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[h.jsx("input",{type:"datetime-local",value:c,onChange:d=>{const f=d.target.value;if(!f)return;const p=new Date(f);e(Mn.fromDate(p))},"aria-invalid":n?"true":void 0}),n?h.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const ZB={type:"timestamp",Display:KB,Edit:YB};function WB({value:t,path:e}){return h.jsxs("span",{"data-pyric-field-type":"geopoint","data-pyric-field-path":e,"data-lat":String(t.latitude),"data-lng":String(t.longitude),children:[t.latitude,", ",t.longitude]})}function JB({value:t,onChange:e,error:n,path:r}){return h.jsxs("span",{"data-pyric-field-type":"geopoint","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[h.jsx("label",{children:h.jsx("input",{type:"number",step:"any",min:-90,max:90,value:t.latitude,onChange:s=>{const o=parseFloat(s.target.value);try{e(new Cr(o,t.longitude))}catch{}},"aria-label":"Latitude"})}),h.jsx("label",{children:h.jsx("input",{type:"number",step:"any",min:-180,max:180,value:t.longitude,onChange:s=>{const o=parseFloat(s.target.value);try{e(new Cr(t.latitude,o))}catch{}},"aria-label":"Longitude"})}),n?h.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const QB={type:"geopoint",Display:WB,Edit:JB},fj=A.createContext({});fj.Provider;function XB(){return A.useContext(fj)}function e5({value:t,path:e}){const{onReferenceClick:n}=XB();return n?h.jsx("button",{type:"button",onClick:()=>n(t),"data-pyric-field-type":"reference","data-pyric-field-path":e,"data-target-path":t.path,"data-pyric-clickable":"",children:t.path}):h.jsx("span",{"data-pyric-field-type":"reference","data-pyric-field-path":e,"data-target-path":t.path,children:t.path})}function t5({value:t,onChange:e,error:n,path:r}){return h.jsxs("label",{"data-pyric-field-type":"reference","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[h.jsx("input",{type:"text",value:t.path,placeholder:"users/alice",onChange:s=>{const o=s.target.value,c=o.split("/").filter(Boolean),d=c[c.length-1]??"",f=t.firestore??{};e({path:o,id:d,firestore:f,type:"document"})},"aria-invalid":n?"true":void 0}),n?h.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const n5={type:"reference",Display:e5,Edit:t5};function r5({value:t,path:e}){const n=t.toBase64();return h.jsx("code",{"data-pyric-field-type":"bytes","data-pyric-field-path":e,"data-byte-length":String(t.toUint8Array().byteLength),children:n})}function s5({value:t,onChange:e,error:n,path:r}){return h.jsxs("label",{"data-pyric-field-type":"bytes","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[h.jsx("textarea",{value:t.toBase64(),onChange:s=>{try{e(Sr.fromBase64String(s.target.value))}catch{}},"aria-invalid":n?"true":void 0}),n?h.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const i5={type:"bytes",Display:r5,Edit:s5};function vy({value:t,path:e,fieldEditors:n}){const r=Gd(t),s=n[r];if(!s)return null;const{Display:o}=s;return h.jsx(o,{value:t,path:e,fieldEditors:n})}function hj({label:t,value:e,path:n,fieldEditors:r,kind:s}){const o=Gd(e),c=o==="map"||o==="array",[d,f]=A.useState(!0),p=s==="key"?{"data-pyric-tree-key":""}:{"data-pyric-tree-index":""},g=s==="key"?{"data-field-name":t}:{"data-field-index":t};return c?h.jsxs("li",{"data-pyric-tree-entry":!0,"data-pyric-tree-nested":!0,...g,children:[h.jsxs("button",{type:"button","data-pyric-tree-toggle":!0,"aria-expanded":d,onClick:()=>f(b=>!b),children:[h.jsx("span",{"data-pyric-tree-chevron":!0,"aria-hidden":"true",children:"›"}),h.jsx("span",{...p,children:t})]}),d?h.jsx(vy,{value:e,path:n,fieldEditors:r}):null]}):h.jsxs("li",{"data-pyric-tree-entry":!0,...g,children:[h.jsx("span",{"data-pyric-tree-chevron":!0,"data-pyric-tree-chevron-empty":!0,"aria-hidden":"true"}),h.jsx("span",{...p,children:t}),h.jsx(vy,{value:e,path:n,fieldEditors:r})]})}function a5({value:t,path:e,fieldEditors:n}){const r=Object.entries(t).sort(([s],[o])=>s.localeCompare(o));return h.jsx("ul",{"data-pyric-field-type":"map","data-pyric-tree":!0,"data-pyric-field-path":e,children:r.map(([s,o])=>h.jsx(hj,{label:s,value:o,path:e?`${e}.${s}`:s,fieldEditors:n??{},kind:"key"},s))})}const o5={type:"map",Display:a5};function l5({value:t,path:e,fieldEditors:n}){return h.jsx("ul",{"data-pyric-field-type":"array","data-pyric-tree":!0,"data-pyric-field-path":e,children:t.map((r,s)=>h.jsx(hj,{label:String(s),value:r,path:e?`${e}[${s}]`:`[${s}]`,fieldEditors:n??{},kind:"index"},s))})}const c5={type:"array",Display:l5},l_=4;function u5(t){return t.length<=l_?`[${t.join(", ")}]`:`[${t.slice(0,l_).join(", ")}, …]`}function d5({value:t,path:e}){const n=Ki(t);return n?h.jsxs("span",{"data-pyric-field-type":"vector","data-pyric-field-path":e,"data-dimension":String(n.dimension),children:[h.jsx("span",{"data-pyric-vector-dims":!0,children:`vector · ${n.dimension}`}),h.jsx("span",{"data-pyric-vector-preview":!0,children:u5(n.values)})]}):h.jsx("span",{"data-pyric-field-type":"vector","data-pyric-field-path":e})}function f5(t){let e;try{e=JSON.parse(t)}catch{return{ok:!1,error:"Invalid JSON"}}return!Array.isArray(e)||!e.every(n=>typeof n=="number")?{ok:!1,error:"Expected a JSON array of numbers"}:{ok:!0,value:{__type__:"__vector__",value:e}}}function h5({value:t,onChange:e,error:n,path:r}){const s=Ki(t),o=s?JSON.stringify(s.values):"[]",[c,d]=A.useState(o),[f,p]=A.useState(void 0),g=x=>{d(x);const _=f5(x);if(!_.ok){p(_.error);return}p(void 0),e(_.value)},b=s?s.dimension:0,v=f??n;return h.jsxs("label",{"data-pyric-field-type":"vector","data-pyric-field-path":r,"data-dimension":String(b),"data-pyric-error":v?"":void 0,children:[h.jsx("span",{"data-pyric-vector-dims":!0,children:`vector · ${b}`}),h.jsx("span",{"data-pyric-vector-note":!0,children:"Replace whole. Paste a JSON number array."}),h.jsx("textarea",{"data-pyric-vector-raw":!0,value:c,onChange:x=>g(x.target.value),"aria-invalid":v?"true":void 0,"aria-label":"Vector value (JSON number array)"}),v?h.jsx("span",{"data-pyric-error-message":!0,children:v}):null]})}const p5={type:"vector",Display:d5,Edit:h5},c_={string:UB,number:FB,boolean:zB,null:GB,timestamp:ZB,geopoint:QB,reference:n5,bytes:i5,map:o5,array:c5,vector:p5};function pj(t){return t?{...c_,...t}:c_}function Kd(t={}){const e=A.useRef(null),n=t.narrowBreakpoint??480,r=t.mediumBreakpoint??768,[s,o]=A.useState("wide");return A.useEffect(()=>{const c=e.current;if(!c||typeof ResizeObserver>"u")return;const d=new ResizeObserver(f=>{const p=f[0];if(!p)return;const g=p.contentRect.width;g<n?o("narrow"):g<r?o("medium"):o("wide")});return d.observe(c),()=>d.disconnect()},[n,r]),{ref:e,size:s}}const mj=A.createContext(null);function ei(){const t=A.useContext(mj);if(!t)throw new Error("DocumentEditor.* components must render inside <DocumentEditor.Root>");return t}function m5({initial:t,fieldEditors:e,onChange:n,children:r,className:s}){const o=uj({initial:t}),c=pj(e),d=A.useRef(n);d.current=n,A.useEffect(()=>{var g;(g=d.current)==null||g.call(d,o)},[o]);const{ref:f,size:p}=Kd();return h.jsx(mj.Provider,{value:{editor:o,fieldEditors:c},children:h.jsx("div",{ref:f,className:s,"data-pyric-ui":"document-editor","data-pyric-is-valid":o.isValid?"":void 0,"data-pyric-is-dirty":o.isDirty?"":void 0,"data-size":p,children:r})})}function y5(){const{editor:t}=ei(),e=t.tree.childIds[t.tree.rootId]??[];return h.jsxs("div",{"data-pyric-editor-fields":!0,children:[e.map(n=>h.jsx(_g,{nodeId:n,path:g5(t,n)},n)),h.jsx(yj,{parentId:t.tree.rootId})]})}function g5(t,e){const n=[];let r=t.tree.nodes[e];for(;r&&r.parentId!=null;){const s=t.tree.nodes[r.parentId];if(!s)break;if(s.type==="array"){const o=(t.tree.childIds[s.id]??[]).indexOf(r.id);n.unshift(`[${o}]`)}else n.unshift(r.key??"");r=s}return n.reduce((s,o)=>o.startsWith("[")?`${s}${o}`:s?`${s}.${o}`:o,"")}function _g({nodeId:t,path:e}){const{editor:n,fieldEditors:r}=ei(),s=n.tree.nodes[t];if(!s)return null;if(s.type==="map")return h.jsx(x5,{node:s,path:e});if(s.type==="array")return h.jsx(w5,{node:s,path:e});const o=r[s.type],c=o==null?void 0:o.Edit;if(!c)return null;const d=s.touched?s.error:void 0;return h.jsxs("div",{"data-pyric-field-entry":!0,"data-field-name":s.key??void 0,"data-pyric-error":d?"":void 0,onBlur:()=>n.touch(s.id),children:[h.jsx(Eg,{node:s,path:e}),h.jsx(c,{value:s.value,path:e,error:d,onChange:f=>n.setValue(s.id,f)})]})}function Eg({node:t,path:e}){const{editor:n}=ei(),r=t.parentId!=null?n.tree.nodes[t.parentId]:null,s=(r==null?void 0:r.type)==="map";return t.id===n.tree.rootId?null:h.jsxs("div",{"data-pyric-field-chrome":!0,"data-pyric-field-path":e,children:[s?h.jsx("input",{type:"text",value:t.key??"",onChange:c=>n.setKey(t.id,c.target.value),"aria-label":"Field name","data-pyric-field-key-input":!0,"aria-invalid":t.touched&&t.error?"true":void 0}):null,h.jsx(v5,{node:t}),h.jsx("button",{type:"button",onClick:()=>n.remove(t.id),"data-pyric-remove":!0,"aria-label":"Remove field",children:"×"})]})}const b5=["string","number","boolean","null","timestamp","geopoint","reference","bytes","vector","map","array"];function v5({node:t}){const{editor:e}=ei(),n=t.parentId!=null?e.tree.nodes[t.parentId]:null,r=b5.filter(s=>!((n==null?void 0:n.type)==="array"&&s==="array"));return h.jsx("select",{value:t.type,onChange:s=>e.setType(t.id,s.target.value),"aria-label":"Field type","data-pyric-field-type-select":!0,children:r.map(s=>h.jsx("option",{value:s,children:s},s))})}function x5({node:t,path:e}){const{editor:n}=ei(),r=n.tree.childIds[t.id]??[];return h.jsxs("div",{"data-pyric-field-entry":!0,"data-pyric-field-type":"map","data-field-name":t.key??void 0,children:[t.id!==n.tree.rootId?h.jsx(Eg,{node:t,path:e}):null,h.jsx("div",{"data-pyric-map-children":!0,children:r.map(s=>{const o=n.tree.nodes[s];if(!o)return null;const c=e?`${e}.${o.key??""}`:o.key??"";return h.jsx(_g,{nodeId:s,path:c},s)})}),h.jsx(yj,{parentId:t.id})]})}function w5({node:t,path:e}){const{editor:n}=ei(),r=n.tree.childIds[t.id]??[];return h.jsxs("div",{"data-pyric-field-entry":!0,"data-pyric-field-type":"array","data-field-name":t.key??void 0,children:[h.jsx(Eg,{node:t,path:e}),h.jsx("ol",{"data-pyric-array-children":!0,children:r.map((s,o)=>{const c=e?`${e}[${o}]`:`[${o}]`;return h.jsx("li",{"data-field-index":String(o),children:h.jsx(_g,{nodeId:s,path:c})},s)})}),h.jsx(S5,{parentId:t.id})]})}function yj({parentId:t}){const{editor:e}=ei();return h.jsx("button",{type:"button","data-pyric-add-map-entry":!0,onClick:()=>e.addMapEntry(t,"","string"),children:"+ Add field"})}function S5({parentId:t}){const{editor:e}=ei();return h.jsx("button",{type:"button","data-pyric-add-array-entry":!0,onClick:()=>e.addArrayEntry(t,"string"),children:"+ Add item"})}const u_={Root:m5,Fields:y5};function _5({collections:t,isLoading:e,error:n,onSelect:r,emptyState:s,className:o}){return n?h.jsx("div",{className:o,"data-pyric-ui":"collection-list","data-pyric-error":"",role:"alert",children:n.message}):e&&t.length===0?h.jsx("div",{className:o,"data-pyric-ui":"collection-list","data-pyric-loading":""}):t.length===0?h.jsx("div",{className:o,"data-pyric-ui":"collection-list","data-pyric-empty":"",children:s}):h.jsx("ul",{className:o,"data-pyric-ui":"collection-list",children:t.map(c=>h.jsx("li",{"data-pyric-collection-entry":!0,"data-pyric-collection-id":c.id,children:h.jsx("button",{type:"button",onClick:()=>r==null?void 0:r(c),"data-pyric-collection-select":!0,children:c.id})},c.path))})}const ll=new Map;function Ag({scope:t,entries:e,equals:n=Object.is,durationMs:r=1200,ready:s=!0}){const o=A.useRef(null),c=A.useRef(new Map),d=A.useRef(new Map),[f,p]=A.useState(ll);return A.useEffect(()=>{const g=o.current;if(!s){if(g&&g.scope!==t){o.current=null;for(const v of d.current.values())clearTimeout(v);d.current.clear(),c.current.clear(),p(ll)}return}if(!g||g.scope!==t){o.current={scope:t,entries:e};for(const v of d.current.values())clearTimeout(v);d.current.clear(),c.current.clear(),p(ll);return}const b=new Map;for(const[v,x]of e){const _=g.entries.has(v),k=g.entries.get(v);if(_&&n(k,x))continue;const R=c.current.get(v)===0?1:0;c.current.set(v,R),b.set(v,{kind:_?"modified":"added",cycle:R})}o.current={scope:t,entries:e},p(v=>{const x=new Map(v);let _=b.size>0;for(const k of v.keys())e.has(k)||(x.delete(k),_=!0);for(const[k,R]of b)x.set(k,R);return _?x.size===0?ll:x:v});for(const[v,x]of b){const _=d.current.get(v);_&&clearTimeout(_);const k=setTimeout(()=>{d.current.delete(v),p(R=>{var T;if(((T=R.get(v))==null?void 0:T.cycle)!==x.cycle)return R;const C=new Map(R);return C.delete(v),C.size===0?ll:C})},r);d.current.set(v,k)}},[r,e,n,s,t]),A.useEffect(()=>()=>{for(const g of d.current.values())clearTimeout(g);d.current.clear()},[]),f}function cl(t){return t.ref}function E5({documents:t,isLoading:e,error:n,hasMore:r,onSelect:s,onLoadMore:o,renderLabel:c,renderRowAction:d,emptyState:f,className:p,updateScope:g="document-list",virtualizeThreshold:b=100,rowHeight:v=36,virtualizedHeight:x="60vh"}){const _=A.useMemo(()=>new Map(t.map(C=>[cl(C).path,C.data()])),[t]),k=Ag({scope:g,entries:_,equals:xd,ready:!e});if(n)return h.jsx("div",{className:p,"data-pyric-ui":"document-list","data-pyric-error":"",role:"alert",children:n.message});if(e&&t.length===0)return h.jsx("div",{className:p,"data-pyric-ui":"document-list","data-pyric-loading":""});if(t.length===0)return h.jsx("div",{className:p,"data-pyric-ui":"document-list","data-pyric-empty":"",children:f});const R=t.length>b;return h.jsxs("div",{className:p,"data-pyric-ui":"document-list","data-pyric-virtualized":R?"":void 0,children:[R?h.jsx(bg,{items:t,estimateSize:v,height:x,getItemKey:C=>cl(C).path,renderItem:C=>{const T=k.get(cl(C).path);return h.jsxs("div",{"data-pyric-document-entry":!0,"data-pyric-document-id":C.id,"data-pyric-update":T==null?void 0:T.kind,"data-pyric-update-cycle":T==null?void 0:T.cycle,children:[h.jsx("button",{type:"button",onClick:()=>s==null?void 0:s(cl(C)),"data-pyric-document-select":!0,"data-pyric-update":T==null?void 0:T.kind,"data-pyric-update-cycle":T==null?void 0:T.cycle,children:c?c(C):C.id}),d?h.jsx("span",{"data-pyric-document-action":!0,children:d(C)}):null]})}}):h.jsx("ul",{"data-pyric-document-list-items":!0,children:t.map(C=>{const T=cl(C),U=k.get(T.path);return h.jsxs("li",{"data-pyric-document-entry":!0,"data-pyric-document-id":C.id,"data-pyric-update":U==null?void 0:U.kind,"data-pyric-update-cycle":U==null?void 0:U.cycle,children:[h.jsx("button",{type:"button",onClick:()=>s==null?void 0:s(T),"data-pyric-document-select":!0,"data-pyric-update":U==null?void 0:U.kind,"data-pyric-update-cycle":U==null?void 0:U.cycle,children:c?c(C):C.id}),d?h.jsx("span",{"data-pyric-document-action":!0,children:d(C)}):null]},T.path)})}),r&&o?h.jsx("button",{type:"button",onClick:o,"data-pyric-load-more":!0,disabled:e,children:"Load more"}):null]})}const A5=/^__.*__$/;function gj(t){if(t.length===0)return"Cannot be empty";if(t.includes("/"))return'Cannot contain "/"';if(t==="."||t==="..")return'Cannot be "." or ".."';if(A5.test(t))return"Cannot match __.*__ (reserved)";if(k5(t)>1500)return"Cannot exceed 1500 bytes"}function j5(t){return gj(t)}function k5(t){return new TextEncoder().encode(t).length}function C5(t){return gj(t)}const d_="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function N5(){let t="";for(let e=0;e<20;e++)t+=d_.charAt(Math.floor(Math.random()*d_.length));return t}const O5={ref:Ml,listAll:mg,getMetadata:Z$,getBlob:r4,uploadBytes:Q$,deleteObject:UA},bj=A.createContext(O5);function Yd(){return A.useContext(bj)}function T5({value:t,children:e}){return A.createElement(bj.Provider,{value:t},e)}function em(t){return t.replace(/^\/+|\/+$/g,"")}function xy(t,e){return t.fullPath<e.fullPath?-1:t.fullPath>e.fullPath?1:0}function tm(t,e){return t.some(n=>n.fullPath===e.fullPath)?t:[...t,e].sort(xy)}function R5(t,e){const{listAll:n,ref:r}=Yd(),s=em(e),[o,c]=A.useState(()=>({status:t==null?"idle":"loading",items:[],prefixes:[],error:void 0})),[d,f]=A.useState(0),p=A.useRef(new Map);A.useEffect(()=>{if(p.current.clear(),t==null){c({status:"idle",items:[],prefixes:[],error:void 0});return}let _=!1;return c({status:"loading",items:[],prefixes:[],error:void 0}),n(r(t,s)).then(k=>{_||c({status:"success",items:[...k.items].sort(xy),prefixes:[...k.prefixes].sort(xy),error:void 0})}).catch(k=>{_||c({status:"error",items:[],prefixes:[],error:k instanceof Error?k:new Error(String(k))})}),()=>{_=!0}},[t,s,d]);const g=A.useCallback(()=>f(_=>_+1),[]),b=A.useCallback(_=>{if(t==null)return;const k=_.endsWith("/"),R=em(_),C=s===""?"":`${s}/`;if(!R.startsWith(C)||R===s)return;const T=R.slice(C.length),U=T.indexOf("/");c(q=>{if(q.status==="idle")return q;if(U===-1)return k?(p.current.set(R,q.prefixes.some(N=>N.fullPath===R)?null:R),{...q,prefixes:tm(q.prefixes,r(t,R))}):(p.current.set(R,q.items.some(N=>N.fullPath===R)?null:R),{...q,items:tm(q.items,r(t,R))});const I=`${C}${T.slice(0,U)}`;return p.current.set(R,q.prefixes.some(N=>N.fullPath===I)?null:I),{...q,prefixes:tm(q.prefixes,r(t,I))}})},[t,s]),v=A.useCallback(_=>{const k=em(_),R=p.current.get(k);if(p.current.delete(k),R===null)return;const C=R??k;c(T=>({...T,items:T.items.filter(U=>U.fullPath!==C),prefixes:T.prefixes.filter(U=>U.fullPath!==C)}))},[]),x=A.useMemo(()=>[...o.prefixes.map(_=>({kind:"folder",name:_.name,fullPath:_.fullPath,ref:_})),...o.items.map(_=>({kind:"object",name:_.name,fullPath:_.fullPath,ref:_}))],[o.prefixes,o.items]);return{status:o.status,items:o.items,prefixes:o.prefixes,entries:x,error:o.error,refresh:g,insertItem:b,removeItem:v}}function ft(t){return t.split("/").filter(Boolean).join("/")}function D5(t={}){const{path:e,onPathChange:n,defaultPath:r=""}=t,s=e!==void 0,[o,c]=A.useState(()=>ft(r)),d=s?ft(e):o,f=A.useCallback(x=>{const _=ft(x);s||c(_),n==null||n(_)},[s,n]),p=A.useMemo(()=>d===""?[]:d.split("/"),[d]),g=A.useCallback(x=>{const _=ft(x);f(_.includes("/")||d===""?_:`${d}/${_}`)},[d,f]),b=A.useCallback(()=>{p.length!==0&&f(p.slice(0,-1).join("/"))},[p,f]),v=A.useCallback(x=>{f(x<0?"":p.slice(0,x+1).join("/"))},[p,f]);return{path:d,segments:p,setPath:f,enter:g,up:b,navigateToIndex:v}}const f_={status:"idle",blob:void 0,url:void 0,error:void 0};function I5(t,e){const{getBlob:n,getMetadata:r,ref:s}=Yd(),o=e==null?null:ft(e),c=t!=null&&o!=null&&o!=="",[d,f]=A.useState(()=>({status:c?"loading":"idle",metadata:void 0,error:void 0})),[p,g]=A.useState(f_),[b,v]=A.useState(0),x=A.useRef(0);A.useEffect(()=>{if(x.current++,g(f_),!c){f({status:"idle",metadata:void 0,error:void 0});return}let C=!1;return f({status:"loading",metadata:void 0,error:void 0}),r(s(t,o)).then(T=>{C||f({status:"success",metadata:T,error:void 0})}).catch(T=>{C||f({status:"error",metadata:void 0,error:T instanceof Error?T:new Error(String(T))})}),()=>{C=!0}},[t,o,b]);const _=p.url;A.useEffect(()=>{if(_!==void 0)return()=>{URL.revokeObjectURL(_)}},[_]);const k=A.useCallback(()=>v(C=>C+1),[]),R=A.useCallback(()=>{if(t==null||o==null||o==="")return;const C=++x.current;g({status:"loading",blob:void 0,url:void 0,error:void 0}),n(s(t,o)).then(T=>{C===x.current&&g({status:"success",blob:T,url:URL.createObjectURL(T),error:void 0})}).catch(T=>{C===x.current&&g({status:"error",blob:void 0,url:void 0,error:T instanceof Error?T:new Error(String(T))})})},[t,o]);return{status:d.status,metadata:d.metadata,error:d.error,refresh:k,blobStatus:p.status,blob:p.blob,blobUrl:p.url,blobError:p.error,loadBlob:R}}function M5(){const[t,e]=A.useState(()=>new Map),n=A.useCallback(p=>t.has(p),[t]),r=A.useCallback(p=>{e(g=>{if(g.has(p.fullPath))return g;const b=new Map(g);return b.set(p.fullPath,p),b})},[]),s=A.useCallback(p=>{e(g=>{if(!g.has(p))return g;const b=new Map(g);return b.delete(p),b})},[]),o=A.useCallback(p=>{e(g=>{const b=new Map(g);return b.has(p.fullPath)?b.delete(p.fullPath):b.set(p.fullPath,p),b})},[]),c=A.useCallback(p=>{e(new Map(p.map(g=>[g.fullPath,g])))},[]),d=A.useCallback(()=>e(new Map),[]);return{selected:A.useMemo(()=>[...t.values()],[t]),size:t.size,isSelected:n,toggle:o,select:r,deselect:s,selectAll:c,clear:d}}function L5(t,e){const n=Ml(t,e);return{storage:t,bucket:n.bucket,fullPath:`${n.fullPath}/`,name:"",parent:n,root:n.root,toString:()=>`${n.toString()}/`}}function U5(t){return{...t,fullPath:`${t.fullPath}/`,name:""}}function $5(t){return{async*start(e){const n=t??{listAll:mg,deleteObject:UA};let r=0;const s=[e],o=[];for(;s.length>0;){const c=s.pop();o.push(c);const d=await n.listAll(c);s.push(...d.prefixes);for(const f of d.items)await n.deleteObject(f),r++,yield{deletedCount:r,done:!1}}for(const c of o)try{await n.deleteObject(U5(c))}catch{}yield{deletedCount:r,done:!0}}}}function B5(t,e={}){const n=Yd(),[r,s]=A.useState(0),[o,c]=A.useState(!1),[d,f]=A.useState(void 0),p=A.useRef(0),g=A.useRef(e);return g.current=e,{deleteEntries:A.useCallback(async v=>{var C,T;const x=++p.current;s(0),f(void 0);const _={deleted:[],failed:[]};if(t==null||v.length===0)return _;c(!0);const k=g.current.impl??$5(n);let R=0;try{for(const U of v){(C=g.current.list)==null||C.removeItem(U.fullPath);try{if(U.kind==="object")await n.deleteObject(n.ref(t,U.fullPath)),R++;else for await(const q of k.start(n.ref(t,U.fullPath))){if(x!==p.current)return _;if(s(R+q.deletedCount),q.done){R+=q.deletedCount;break}}_.deleted.push(U.fullPath),x===p.current&&s(R)}catch(q){const I=q instanceof Error?q:new Error(String(q));_.failed.push({fullPath:U.fullPath,error:I}),(T=g.current.list)==null||T.insertItem(U.kind==="folder"?`${U.fullPath}/`:U.fullPath),x===p.current&&_.failed.length===1&&f(I)}}return _}finally{x===p.current&&c(!1)}},[n,t]),progress:r,isRunning:o,error:d}}const F5=Object.freeze({read:!0,write:!0,delete:!0,upload:!0,reasons:Object.freeze({read:[],write:[]})});function P5(t,e={}){const{paths:n,rules:r,identity:s,writeResource:o}=e,c=t==null?null:t[zd],[d,f]=A.useState(()=>({status:t==null?"idle":"loading",rules:null,source:"none",error:void 0}));A.useEffect(()=>{if(c==null){f({status:"idle",rules:null,source:"none",error:void 0});return}if(r!=null){try{const T=typeof r=="string"?OA(r):r;f({status:"ready",rules:T,source:"option",error:void 0})}catch(T){f({status:"error",rules:null,source:"none",error:T instanceof Error?T:new Error(String(T))})}return}let C=!1;return f({status:"loading",rules:null,source:"none",error:void 0}),c.servicePromise.then(T=>{C||f({status:"ready",rules:T.rules,source:T.rules?"sandbox":"none",error:void 0})}).catch(T=>{C||f({status:"error",rules:null,source:"none",error:T instanceof Error?T:new Error(String(T))})}),()=>{C=!0}},[c,r]);const p=s!==void 0?s:(c==null?void 0:c.context.auth)??null,{rules:g,status:b}=d,v=o==null?void 0:o.size,x=o==null?void 0:o.contentType,_=A.useCallback(C=>{if(g==null)return F5;const T=ft(C),U=(c==null?void 0:c.bucket)??"pyric-default",q=T===""?`b/${U}/o`:`b/${U}/o/${T}`,I=L=>RA(g,{request:{auth:p,method:L,path:q,...L==="write"&&v!==void 0?{resource:{size:v,contentType:x}}:{}},resource:null}),N=I("read"),M=I("write");return{read:N.allowed,write:M.allowed,delete:M.allowed,upload:M.allowed,reasons:{read:N.allowed?[]:N.reasons,write:M.allowed?[]:M.reasons}}},[g,c==null?void 0:c.bucket,p,v,x]),k=typeof n=="string"?n:(n??[]).join(`
|
|
1209
|
-
`),R=A.useMemo(()=>{const C=typeof n=="string"?[n]:n??[],T={};for(const U of C)T[ft(U)]=_(U);return T},[k,_]);return{status:b,source:d.source,advisory:!1,identity:p,verdicts:R,verdictFor:_,error:d.error}}function h_(t,e){return t===""?e:e===""?t:`${t}/${e}`}function q5(t){return t instanceof Blob?t.size:t.byteLength}function z5(t){if(t instanceof Blob){const e=t;return{path:e.webkitRelativePath||e.name,data:e}}return t}function V5(t,e={}){const{ref:n,uploadBytes:r}=Yd(),s=ft(e.path??""),[o,c]=A.useState([]),d=A.useRef(e);d.current=e;const f=A.useCallback(v=>{c(x=>x.map(_=>_.id===v.id?v:_))},[]),p=A.useCallback(async v=>{var k,R,C;if(t==null)throw new Error("useObjectUpload: storage handle is null");const _=(Array.isArray(v)?v:[v]).map(T=>{const U=z5(T);return{task:{id:crypto.randomUUID(),fullPath:h_(s,ft(U.path)),status:"running",bytesTransferred:0,totalBytes:q5(U.data)},entry:U}});c(T=>[...T,..._.map(U=>U.task)]);for(const{task:T}of _)(k=d.current.list)==null||k.insertItem(T.fullPath),(C=(R=d.current).onProgress)==null||C.call(R,T);return Promise.all(_.map(async({task:T,entry:U})=>{var q,I,N,M,L,H,P;try{const F=await r(n(t,T.fullPath),U.data,U.metadata),w={...T,status:"success",bytesTransferred:T.totalBytes,metadata:F.metadata};return f(w),(I=(q=d.current).onProgress)==null||I.call(q,w),(M=(N=d.current).onComplete)==null||M.call(N,w),w}catch(F){const w={...T,status:"error",error:F instanceof Error?F:new Error(String(F))};return(L=d.current.list)==null||L.removeItem(T.fullPath),f(w),(P=(H=d.current).onError)==null||P.call(H,w),w}}))},[t,s,f,n,r]),g=A.useCallback(async v=>{var _,k;if(t==null)throw new Error("useObjectUpload: storage handle is null");const x=h_(s,ft(v));if(x==="")throw new Error("createFolder: folder name is empty");(_=d.current.list)==null||_.insertItem(`${x}/`);try{await r(L5(t,x),new Blob([]),{contentType:"text/plain"})}catch(R){throw(k=d.current.list)==null||k.removeItem(x),R}},[t,s,r]),b=A.useCallback(()=>{c(v=>v.filter(x=>x.status==="running"))},[]);return{tasks:o,isUploading:o.some(v=>v.status==="running"),upload:p,createFolder:g,clearCompleted:b}}function H5({path:t,onNavigate:e,rootLabel:n="/",separator:r="/",className:s}){const o=ft(t),c=o===""?[]:o.split("/");return h.jsx("nav",{className:s,"data-pyric-ui":"path-breadcrumb","aria-label":"Storage path",children:h.jsxs("ol",{"data-pyric-breadcrumb-list":!0,children:[h.jsx("li",{"data-pyric-breadcrumb-item":!0,children:h.jsx("button",{type:"button",onClick:()=>e==null?void 0:e(""),"data-pyric-breadcrumb-link":!0,"data-pyric-breadcrumb-root":!0,"data-pyric-current":c.length===0?"":void 0,"aria-current":c.length===0?"page":void 0,children:n})}),c.map((d,f)=>{const p=f===c.length-1,g=c.slice(0,f+1).join("/");return h.jsxs("li",{"data-pyric-breadcrumb-item":!0,children:[h.jsx("span",{"aria-hidden":!0,"data-pyric-breadcrumb-separator":!0,children:r}),h.jsx("button",{type:"button",onClick:()=>e==null?void 0:e(g),"data-pyric-breadcrumb-link":!0,"data-pyric-current":p?"":void 0,"aria-current":p?"page":void 0,children:d})]},g)})]})})}function G5({entries:t,status:e="success",error:n,onNavigate:r,onSelect:s,selectedPath:o,gate:c,renderEntry:d,renderRowAction:f,emptyState:p,className:g,virtualizeThreshold:b=100,rowHeight:v=36,virtualizedHeight:x="60vh"}){const{ref:_,size:k}=Kd();if(n)return h.jsx("div",{className:g,"data-pyric-ui":"object-browser","data-pyric-error":"",role:"alert",children:n.message});if((e==="loading"||e==="idle")&&t.length===0)return h.jsx("div",{className:g,"data-pyric-ui":"object-browser","data-pyric-loading":e==="loading"?"":void 0,"data-pyric-idle":e==="idle"?"":void 0});if(t.length===0)return h.jsx("div",{className:g,"data-pyric-ui":"object-browser","data-pyric-empty":"",children:p});const R=U=>{if(!c)return{denied:!1};const q=c.verdictFor(U.fullPath);return q.read?{denied:!1}:{denied:!0,reason:q.reasons.read.join("; ")}},C=U=>{const q=U.kind==="object"&&U.fullPath===o;return h.jsxs(h.Fragment,{children:[h.jsx("button",{type:"button",onClick:()=>U.kind==="folder"?r==null?void 0:r(U.fullPath):s==null?void 0:s(U.ref),"data-pyric-entry-select":!0,"data-pyric-selected":q?"":void 0,"aria-selected":q||void 0,children:d?d(U):U.name}),f?h.jsx("span",{"data-pyric-storage-action":!0,children:f(U)}):null]})},T=t.length>b;return h.jsx("div",{ref:_,className:g,"data-pyric-ui":"object-browser","data-size":k,"data-pyric-virtualized":T?"":void 0,children:T?h.jsx(bg,{items:t,estimateSize:v,height:x,getItemKey:U=>`${U.kind}:${U.fullPath}`,renderItem:U=>{const q=R(U);return h.jsx("div",{"data-pyric-storage-entry":!0,"data-pyric-entry-kind":U.kind,"data-pyric-entry-path":U.fullPath,"data-pyric-denied":q.denied?"":void 0,"data-pyric-denied-reason":q.reason,children:C(U)})}}):h.jsx("ul",{"data-pyric-object-browser-items":!0,children:t.map(U=>{const q=R(U);return h.jsx("li",{"data-pyric-storage-entry":!0,"data-pyric-entry-kind":U.kind,"data-pyric-entry-path":U.fullPath,"data-pyric-denied":q.denied?"":void 0,"data-pyric-denied-reason":q.reason,children:C(U)},`${U.kind}:${U.fullPath}`)})})})}async function vj(t,e,n){const r=e===""?t.name:`${e}/${t.name}`;if(t.isFile){const s=await new Promise((o,c)=>t.file(o,c));n.push({file:s,relativePath:r});return}if(t.isDirectory){const s=t.createReader();for(;;){const o=await new Promise((c,d)=>s.readEntries(c,d));if(o.length===0)break;for(const c of o)await vj(c,r,n)}}}async function K5(t){var r;const e=[],n=t.items?Array.from(t.items):[];for(const s of n){if(s.kind!=="file")continue;const o=s.webkitGetAsEntry,c=typeof o=="function"?o.call(s):null;if(c)await vj(c,"",e);else{const d=(r=s.getAsFile)==null?void 0:r.call(s);d&&e.push({file:d,relativePath:d.name})}}if(e.length===0)for(const s of Array.from(t.files??[]))e.push({file:s,relativePath:s.name});return e}function Y5({onFiles:t,children:e,disabled:n,disabledReason:r,className:s}){const[o,c]=A.useState(!1),d=A.useRef(0),f=A.useCallback(v=>{v.preventDefault(),!n&&(d.current+=1,c(!0))},[n]),p=A.useCallback(v=>{v.preventDefault()},[]),g=A.useCallback(v=>{v.preventDefault(),!n&&(d.current=Math.max(0,d.current-1),d.current===0&&c(!1))},[n]),b=A.useCallback(v=>{if(v.preventDefault(),d.current=0,c(!1),n)return;const x=v.dataTransfer;x&&K5(x).then(_=>{_.length>0&&t(_)})},[n,t]);return h.jsx("div",{className:s,"data-pyric-ui":"upload-dropzone","data-dragging":o?"":void 0,"data-disabled":n?"":void 0,"data-disabled-reason":n?r:void 0,"aria-disabled":n||void 0,onDragEnter:f,onDragOver:p,onDragLeave:g,onDrop:b,children:e})}function Z5(t){const e=t.lastIndexOf(".");return e<=0||e===t.length-1?{stem:t,ext:""}:{stem:t.slice(0,e),ext:t.slice(e)}}function W5(t){const e=/^(.*) \((\d+)\)$/.exec(t);if(!e)return{base:t,counter:null};const n=Number(e[2]);return Number.isSafeInteger(n)?{base:e[1],counter:n}:{base:t,counter:null}}function p_(t,e){if(!e.has(t))return t;const{stem:n,ext:r}=Z5(t),{base:s,counter:o}=W5(n);let c=o===null?1:o+1;for(;;){const d=`${s} (${c})${r}`;if(!e.has(d))return d;c+=1}}function J5(t,e){const n=new Set(e),r=new Map;return t.map(s=>{const o=s.indexOf("/");if(o===-1){const f=p_(s,n);return n.add(f),f}const c=s.slice(0,o);let d=r.get(c);return d===void 0&&(d=p_(c,n),n.add(d),r.set(c,d)),`${d}${s.slice(o)}`})}function m_(t){const e=ft(t);if(e==="")return[];const n=e.split("/");return n.map((r,s)=>n.slice(0,s+1).join("/"))}const xj=[];function Q5(t,e){switch(e.type){case"create":{const n=m_(e.path).filter(r=>!t.includes(r));return n.length===0?t:[...t,...n].sort()}case"materialize":{const n=new Set(m_(e.path));if(n.size===0)return t;const r=t.filter(s=>!n.has(s));return r.length===t.length?t:r}case"discard":{const n=ft(e.path);if(n==="")return t;const r=t.filter(s=>s!==n&&!s.startsWith(`${n}/`));return r.length===t.length?t:r}case"clear":return t.length===0?t:xj}}function X5(t,e){const n=ft(e),r=n===""?"":`${n}/`;return t.filter(s=>s.startsWith(r)&&s!==n&&!s.slice(r.length).includes("/")).map(s=>s.slice(r.length))}function y_(t,e){return t.includes(ft(e))}function e8(t){const e=ft(t);return e===""?"Enter a folder name.":e.split("/").some(r=>r==="."||r==="..")?'Folder names may not be "." or "..".':null}const t8=256*1024;function wy(t){return(t.contentType??"").split(";")[0].trim().toLowerCase()}const n8={id:"image",match:t=>wy(t).startsWith("image/"),needsBlob:!0,render:({metadata:t,blobUrl:e})=>e?h.jsx("img",{"data-pyric-preview-image":!0,src:e,alt:t.name}):null};function r8({blob:t,isJson:e}){const[n,r]=A.useState(void 0);return A.useEffect(()=>{let s=!1;return t.text().then(o=>{if(!s){if(e)try{r(JSON.stringify(JSON.parse(o),null,2));return}catch{}r(o)}}),()=>{s=!0}},[t,e]),n===void 0?null:h.jsx("pre",{"data-pyric-preview-text":!0,children:n})}const s8={id:"text",match:t=>{const e=wy(t);return e.startsWith("text/")||e==="application/json"},needsBlob:!0,maxBytes:t8,render:({metadata:t,blob:e})=>e?h.jsx(r8,{blob:e,isJson:wy(t)==="application/json"}):null},i8=[n8,s8];function a8(t,e){for(const n of[...e??[],...i8])if(n.match(t))return n}const o8=[{key:"fullPath",label:"Path",value:t=>t.fullPath},{key:"size",label:"Size",value:t=>`${t.size}`},{key:"contentType",label:"Content type",value:t=>t.contentType},{key:"cacheControl",label:"Cache control",value:t=>t.cacheControl},{key:"timeCreated",label:"Created",value:t=>t.timeCreated},{key:"updated",label:"Updated",value:t=>t.updated}];function l8({metadata:t}){return h.jsxs("dl",{"data-pyric-object-metadata":!0,children:[o8.map(({key:e,label:n,value:r})=>{const s=r(t);return s===void 0?null:h.jsxs("div",{"data-pyric-metadata-field":e,children:[h.jsx("dt",{children:n}),h.jsx("dd",{children:s})]},e)}),Object.entries(t.customMetadata??{}).map(([e,n])=>h.jsxs("div",{"data-pyric-metadata-field":"customMetadata","data-pyric-metadata-key":e,children:[h.jsx("dt",{children:e}),h.jsx("dd",{children:n})]},`custom:${e}`))]})}function c8({storage:t,path:e,previews:n,renderMetadata:r,children:s,className:o}){var C,T;const{ref:c,size:d}=Kd(),f=I5(t,e),{metadata:p,blobStatus:g,loadBlob:b}=f,v=p?a8(p,n):void 0,x=(v==null?void 0:v.maxBytes)!==void 0&&p!==void 0&&p.size>v.maxBytes,_=(v==null?void 0:v.needsBlob)===!0&&!x;if(A.useEffect(()=>{_&&g==="idle"&&b()},[_,g,b]),f.status==="idle")return h.jsx("div",{className:o,"data-pyric-ui":"object-inspector","data-pyric-idle":""});if(f.status==="loading")return h.jsx("div",{className:o,"data-pyric-ui":"object-inspector","data-pyric-loading":""});if(f.status==="error"||p===void 0)return h.jsx("div",{className:o,"data-pyric-ui":"object-inspector","data-pyric-error":"",role:"alert",children:(C=f.error)==null?void 0:C.message});let k,R={};return v===void 0?R={"data-pyric-preview-none":""}:x?R={"data-pyric-preview-too-large":""}:_&&g==="loading"?R={"data-pyric-preview-loading":""}:_&&g==="error"?(R={"data-pyric-preview-error":""},k=(T=f.blobError)==null?void 0:T.message):(!_||g==="success")&&(k=v.render({metadata:p,blob:f.blob,blobUrl:f.blobUrl})),h.jsxs("div",{ref:c,className:o,"data-pyric-ui":"object-inspector","data-size":d,children:[h.jsx("div",{"data-pyric-object-name":!0,children:p.name}),r?r(p):h.jsx(l8,{metadata:p}),h.jsx("div",{"data-pyric-object-preview":!0,"data-pyric-preview":v==null?void 0:v.id,...R,children:k}),s]})}const wj=A.createContext(null);function u8(){const t=A.useContext(wj);if(!t)throw new Error("useToast: missing <ToastProvider> ancestor");return t}function d8({children:t,defaultDuration:e=5e3,className:n,regionLabel:r="Notifications"}){const[s,o]=A.useState([]),c=A.useCallback(p=>{o(g=>g.filter(b=>b.id!==p))},[]),d=A.useCallback(p=>{const g=crypto.randomUUID(),b=p.duration??e;return o(v=>[...v,{id:g,...p}]),b>0&&window.setTimeout(()=>{o(v=>v.filter(x=>x.id!==g))},b),g},[e]),f=A.useMemo(()=>({toast:d,dismiss:c,toasts:s}),[d,c,s]);return h.jsxs(wj.Provider,{value:f,children:[t,h.jsx(f8,{toasts:s,dismiss:c,className:n,regionLabel:r})]})}function f8({toasts:t,dismiss:e,className:n,regionLabel:r}){const[s,o]=A.useState(!1);return A.useEffect(()=>o(!0),[]),!s||typeof document>"u"?null:gg.createPortal(h.jsx("ol",{"aria-label":r,"aria-live":"polite","data-pyric-ui":"toast-region",className:n,children:t.map(c=>h.jsxs("li",{"data-pyric-toast":!0,"data-pyric-toast-kind":c.kind??"info",role:c.kind==="error"?"alert":"status",children:[h.jsx("div",{"data-pyric-toast-title":!0,children:c.title}),c.body?h.jsx("div",{"data-pyric-toast-body":!0,children:c.body}):null,h.jsx("button",{type:"button","data-pyric-toast-dismiss":!0,"aria-label":"Dismiss",onClick:()=>e(c.id),children:"×"})]},c.id))}),document.body)}function h8({storage:t,entries:e,impl:n,list:r,gate:s,title:o,body:c,confirmLabel:d="Delete",onDeleted:f,onFailed:p,renderTrigger:g,className:b}){const v=lo(),{toast:x}=u8(),{deleteEntries:_,isRunning:k,progress:R}=B5(t,{impl:n,list:r}),C=s?e.map(I=>({entry:I,verdict:s.verdictFor(I.fullPath)})).filter(I=>!I.verdict.delete):[],T=C.length===0?void 0:`Delete denied for ${C[0].entry.fullPath}${C.length>1?` (+${C.length-1} more)`:""}: ${C[0].verdict.reasons.write.join("; ")}`,U=k||e.length===0||t==null||C.length>0,q=async()=>{if(U||!await v({title:o??(e.length===1?`Delete ${e[0].fullPath}?`:`Delete ${e.length} items?`),body:c??h.jsx("ul",{"data-pyric-delete-selection-paths":!0,children:e.map(M=>h.jsxs("li",{"data-pyric-entry-kind":M.kind,children:[M.fullPath,M.kind==="folder"?"/":""]},M.fullPath))}),destructive:!0,confirmLabel:d}))return;const N=await _(e);N.failed.length===0?(x({title:`Deleted ${N.deleted.length} ${N.deleted.length===1?"item":"items"}`,kind:"success"}),f==null||f(N)):(x({title:`Delete failed for ${N.failed.length} of ${e.length}`,kind:"error",body:h.jsx("ul",{"data-pyric-delete-selection-failures":!0,children:N.failed.map(M=>h.jsxs("li",{children:[M.fullPath,":"," ",M.error.code??M.error.message]},M.fullPath))})}),p==null||p(N))};return g?h.jsx(h.Fragment,{children:g({onClick:q,isRunning:k,progress:R,disabled:U,deniedReason:T})}):h.jsx("button",{type:"button",onClick:q,className:b,disabled:U,title:T,"data-pyric-ui":"delete-selection","data-pyric-destructive":"","data-pyric-running":k?"":void 0,"data-pyric-denied":T?"":void 0,"data-pyric-denied-reason":T,children:k?`Deleting… (${R})`:d})}function wd(t){const e=t.split("/").filter(Boolean),n=[];let r="";return e.forEach((s,o)=>{r=r?`${r}/${s}`:s,n.push({kind:o%2===0?"collection":"document",id:s,path:r})}),n}function Sj(t){const e=t.indexOf("?");return dg(e===-1?t:t.slice(0,e),e===-1?"":t.slice(e))}function p8(t){const{tab:e,rest:n,query:r}=Sj(t),s=n.join("/");return e==="firestore"?{view:"firestore",path:wd(s)}:e==="auth"?{view:"auth",uid:n[0]??null}:e==="storage"?s?{view:"storage",kind:r.kind==="prefix"?"prefix":"object",path:s}:{view:"storage",kind:"root"}:null}function m8(t){switch(t.view){case"firestore":{const e=t.path[t.path.length-1];return{tab:"firestore",rest:e?e.path.split("/").filter(Boolean):[]}}case"auth":return{tab:"auth",rest:t.uid?[t.uid]:[]};case"storage":return t.kind==="root"?{tab:"storage"}:{tab:"storage",rest:t.path.split("/").filter(Boolean),...t.kind==="prefix"?{query:{kind:"prefix"}}:{}}}}function _j(t){const{tab:e,query:n}=Sj(t),r=p8(t),s=e==="traffic"?n.inspect??null:null;return{target:r,selectedInspectId:s}}let g_=null,Sy=_j("");function y8(){const t=bA();return t!==g_&&(g_=t,Sy=_j(t)),Sy}function g8(){return Sy}function ju(t){Jn(m8(t))}function b8(t){Jn({tab:"traffic",query:{inspect:t}})}function Zd(){const t=A.useSyncExternalStore(Vl,y8,g8),e=A.useCallback(s=>ju(s),[]),n=A.useCallback(s=>{switch(s.kind){case"user":ju({view:"auth",uid:s.uid});break;case"storage":ju({view:"storage",kind:"object",path:s.objectPath});break;case"document":ju({view:"firestore",path:wd(s.path)});break}},[]),r=A.useCallback(s=>b8(s),[]);return A.useMemo(()=>({target:t.target,navigate:e,navigateRef:n,selectedInspectId:t.selectedInspectId,navigateInspect:r}),[t,e,n,r])}const v8={narrowBreakpoint:640,mediumBreakpoint:920};function x8(t){switch(t){case"narrow":return 1;case"medium":return 2;case"wide":return 3}}function w8(t,e){const n=x8(e),r=Math.min(Math.max(t,1),n),s=Math.max(t-r,0),o=e==="narrow"?0:n-r;return{startIndex:s,visibleCount:r,emptySlots:o}}function nm({label:t,error:e,hint:n,children:r}){return h.jsxs("div",{className:"fs-modal__group",children:[h.jsx("span",{className:"fs-modal__label",children:t}),r,e?h.jsx("span",{className:"fs-modal__err",role:"alert",children:e}):n?h.jsx("span",{className:"fs-modal__hint",children:n}):null]})}function Ej({mode:t,parentPath:e,onCreate:n,onClose:r}){const[s,o]=A.useState(""),[c,d]=A.useState(()=>N5()),[f,p]=A.useState(null),[g,b]=A.useState(null),[v,x]=A.useState(!1),_=A.useRef(null),k=t==="collection"&&s?j5(s):void 0,R=c?C5(c):void 0,T=!(t==="collection"&&(!s||k))&&!!c&&!R&&!v;A.useEffect(()=>{const I=N=>{N.key==="Escape"&&!v&&r()};return document.addEventListener("keydown",I),()=>document.removeEventListener("keydown",I)},[v,r]);const U=async()=>{if(!(!T||!f)){if(!f.isValid){f.touchAll();return}x(!0),b(null);try{await n({collectionId:t==="collection"?s:null,docId:c,data:ij(f.tree)}),r()}catch(I){b(I instanceof Error?I:new Error(String(I))),x(!1)}}},q=t==="collection"?"Start a collection":"Add a document";return h.jsx("div",{className:"fs-modal-backdrop",onMouseDown:I=>{I.target===I.currentTarget&&!v&&r()},children:h.jsxs("div",{ref:_,className:"fs-modal",role:"dialog","aria-modal":"true","aria-label":q,"data-pyric-ui":"fs-create-modal","data-fs-create-mode":t,children:[h.jsx("h2",{className:"fs-modal__title",children:q}),h.jsx(nm,{label:"Parent path",children:h.jsx("span",{className:"fs-modal__path",children:e})}),t==="collection"?h.jsx(nm,{label:"Collection ID",error:k,children:h.jsx("input",{autoFocus:!0,type:"text",value:s,placeholder:"e.g. users",onChange:I=>o(I.target.value),"data-pyric-field":"collection-id","aria-invalid":k?"true":void 0})}):null,h.jsx(nm,{label:"Document ID",error:c?R:"Cannot be empty",hint:"Auto-generated — edit to set your own.",children:h.jsx("input",{autoFocus:t==="document",type:"text",value:c,onChange:I=>d(I.target.value),"data-pyric-field":"doc-id","aria-invalid":R||!c?"true":void 0})}),h.jsxs("div",{className:"fs-modal__group",children:[h.jsx("span",{className:"fs-modal__label",children:"Fields"}),h.jsx("div",{className:"fs-modal__fields",children:h.jsx(u_.Root,{initial:{},onChange:p,children:h.jsx(u_.Fields,{})})})]}),g?h.jsx("p",{className:"fs-modal__err",role:"alert",children:g.message}):null,h.jsxs("div",{className:"fs-modal__actions",children:[h.jsx("button",{type:"button",className:"fs-editor__cancel",disabled:v,onClick:r,children:"Cancel"}),h.jsx("button",{type:"button",className:"fs-editor__save",disabled:!T,onClick:()=>void U(),children:v?"Saving…":"Save"})]})]})})}function Aj({items:t,label:e="More actions"}){const[n,r]=A.useState(!1),[s,o]=A.useState(null),c=A.useRef(null),d=()=>{var f;if(!n){const p=(f=c.current)==null?void 0:f.getBoundingClientRect();p&&o({top:p.bottom+4,right:window.innerWidth-p.right})}r(p=>!p)};return A.useEffect(()=>{if(!n)return;const f=p=>{var g;p.key==="Escape"&&(r(!1),(g=c.current)==null||g.focus())};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[n]),h.jsxs("span",{className:"fs-overflow","data-pyric-ui":"fs-overflow-menu",children:[h.jsx("button",{ref:c,type:"button",className:"fs-overflow__trigger","aria-haspopup":"menu","aria-expanded":n,"aria-label":e,onClick:d,children:h.jsx("span",{"aria-hidden":"true",children:"⋮"})}),n?h.jsxs(h.Fragment,{children:[h.jsx("div",{className:"fs-overflow__backdrop",onMouseDown:()=>r(!1)}),h.jsx("div",{className:"fs-overflow__menu",role:"menu",style:s?{top:s.top,right:s.right}:void 0,children:t.map(f=>h.jsx("button",{type:"button",role:"menuitem",className:"fs-overflow__item","data-destructive":f.destructive?"":void 0,disabled:f.disabled,onClick:()=>{r(!1),f.onSelect()},children:f.label},f.label))})]}):null]})}function jj(t){return JSON.stringify(t)}function S8(t,e){const n=new Map,r=(s,o)=>{const c=e(s),d=jj(o);if(c==="map"){const f=s,p=Object.keys(f).sort();n.set(d,[c,p]);for(const g of p)r(f[g],[...o,["field",g]]);return}if(c==="array"){const f=s;n.set(d,[c,f.map((p,g)=>String(g))]),f.forEach((p,g)=>r(p,[...o,["index",g]]));return}n.set(d,[c,s])};for(const[s,o]of Object.entries(t))r(o,[["field",s]]);return n}function kj(t,e){const n=[];let r=t.nodes[e];for(;r&&r.parentId!=null;){const s=t.nodes[r.parentId];if(!s)break;s.type==="array"?n.unshift(["index",(t.childIds[s.id]??[]).indexOf(r.id)]):n.unshift(["field",r.key??""]),r=s}return jj(n)}function _8(t,e){const n=[];let r=t.nodes[e];for(;r&&r.parentId!=null;){const s=t.nodes[r.parentId];if(!s)break;if(s.type==="array"){const o=(t.childIds[s.id]??[]).indexOf(r.id);n.unshift(`[${o}]`)}else n.unshift(r.key??"");r=s}return n.reduce((s,o)=>o.startsWith("[")?`${s}${o}`:s?`${s}.${o}`:o,"")}function E8(t,e){const n=t.nodes[e],r=(n==null?void 0:n.parentId)!=null?t.nodes[n.parentId]:null;if((r==null?void 0:r.type)==="array"){const s=(t.childIds[r.id]??[]).indexOf(e);return{label:String(s),isArrayChild:!0}}return{label:(n==null?void 0:n.key)??"",isArrayChild:!1}}function b_(t,e,n){switch(t.type){case"map":return"{…}";case"array":return"[…]";case"string":return JSON.stringify(t.value);case"null":return"null";case"vector":{const r=e(t.value);return r?n(r):"vector"}default:return String(t.value)}}const A8=42;function j8(t,e,n,r=A8){const s=t.nodes[e],o=t.childIds[e]??[];let c;return s.type==="array"?c=`[${o.slice(0,3).map(f=>b_(t.nodes[f],n.asVectorView,n.vectorPreview)).join(", ")}${o.length>3?", …":""}]`:c=`{${o.slice(0,2).map(f=>`"${t.nodes[f].key}": ${b_(t.nodes[f],n.asVectorView,n.vectorPreview)}`).join(", ")}${o.length>2?", …":""}}`,c.length>r?`${c.slice(0,r-1)}…`:c}function k8(t,e,n){return e.parentId==null?!1:(t.childIds[e.parentId]??[]).some(s=>{var o;return s!==e.id&&((o=t.nodes[s])==null?void 0:o.key)===n})}function C8(t){return t.shiftKey===!0}const Cj=["string","number","boolean","null","timestamp","geopoint","reference","bytes","vector"],N8=[...Cj,"map","array"];function O8({snapshot:t,documentRef:e,onCommit:n,onDeleteDocument:r,onDeleteDocumentFields:s,fieldEditors:o,onReferenceClick:c,onStartCollection:d,firestore:f,listSubcollections:p,onSubcollectionClick:g}){const b=A.useMemo(()=>(t==null?void 0:t.data())??{},[t]),v=A.useMemo(()=>b,[]),x=uj({initial:v}),_=x.replaceData,k=A.useMemo(()=>pj(o),[o]),R=lo(),[C,T]=A.useState(()=>new Set),[U,q]=A.useState(null),I=A.useRef(t),N=A.useRef(new Set),M=A.useRef(!1),[L,H]=A.useState(null),P=A.useMemo(()=>S8(b,Gd),[b]),F=Ag({scope:e.path,entries:P,equals:xd,ready:U===null});A.useEffect(()=>{M.current&&(M.current=!1,H(null),n(x.toData()).catch(se=>{H(se instanceof Error?se:new Error(String(se)))}))},[x.tree]),A.useEffect(()=>{!t||t===I.current||U!==null||(I.current=t,N.current.clear(),_(t.data()??{}))},[U,_,t]);const w=A.useCallback(se=>{T(B=>{const ee=new Set(B);return ee.has(se)?ee.delete(se):ee.add(se),ee})},[]),[E,O]=A.useState(null),D=A.useCallback((se,B)=>{if(B==="map"?x.addMapEntry(se,"","string"):x.addArrayEntry(se,"string"),se!==x.tree.rootId){const ee=kj(x.tree,se);T(ae=>new Set(ae).add(ee))}O(se)},[x]);A.useEffect(()=>{if(!E)return;const se=x.tree.childIds[E]??[],B=se[se.length-1];B&&!U&&(N.current.add(B),q(B),O(null))},[x.tree,E]);const z=A.useCallback(se=>{x.remove(se),N.current.delete(se),M.current=!0,U===se&&q(null)},[x,U]),$=A.useCallback(async(se,B,ee)=>{if(C8(ee)){z(se.id);return}await R({title:`Delete field "${B}"?`,destructive:!0,confirmLabel:"Delete"})&&z(se.id)},[R,z]),K=e.id,W=x.tree.childIds[x.tree.rootId]??[];return h.jsxs("div",{"data-pyric-ui":"fs-doctree",className:"fs-doctree",children:[h.jsxs("div",{className:"fs-doctree__head",children:[h.jsx("span",{className:"fs-doctree__docid",children:K}),h.jsx(Aj,{items:[{label:"Delete document fields",onSelect:()=>{(async()=>await R({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}]})]}),L?h.jsx("p",{className:"fs-doctree__err",children:L.message}):null,h.jsxs("ul",{className:"fs-doctree__rows",children:[d?h.jsx("li",{className:"fs-doctree__action-row",children:h.jsxs("button",{type:"button",className:"fs-doctree__action",onClick:d,children:[h.jsx("span",{"aria-hidden":"true",children:"+"})," Start collection"]})}):null,h.jsx("li",{className:"fs-doctree__action-row",children:h.jsxs("button",{type:"button",className:"fs-doctree__action",onClick:()=>D(x.tree.rootId,"map"),children:[h.jsx("span",{"aria-hidden":"true",children:"+"})," Add field"]})}),W.map(se=>h.jsx(Nj,{nodeId:se,depth:0,editor:x,registry:k,expanded:C,onToggle:w,editingId:U,setEditingId:q,newIdsRef:N,onAdd:D,onDelete:$,onCommitNeeded:()=>{M.current=!0},onReferenceClick:c,updates:F},se))]}),f&&p?h.jsx(Oj,{firestore:f,documentRef:e,listSubcollections:p,onSubcollectionClick:g}):null]})}function Nj({nodeId:t,depth:e,editor:n,registry:r,expanded:s,onToggle:o,editingId:c,setEditingId:d,newIdsRef:f,onAdd:p,onDelete:g,onCommitNeeded:b,onReferenceClick:v,updates:x}){const{tree:_}=n,k=_.nodes[t];if(!k)return null;const{label:R,isArrayChild:C}=E8(_,t),T=k.type==="map"||k.type==="array",U=_8(_,t),q=kj(_,t),I=x.get(q),N=s.has(q),M=c===t,L=f.current.has(t);return M?h.jsx("li",{className:"fs-doctree__row fs-doctree__row--editing","data-pyric-doctree-depth":e,style:{"--fs-depth":e},children:h.jsx(T8,{node:k,isNew:L,isArrayChild:C,tree:_,editor:n,registry:r,path:U,onCommitNeeded:b,onDone:()=>{f.current.delete(t),d(null)},onCancelNew:()=>{n.remove(t),f.current.delete(t),d(null)}})}):h.jsxs("li",{className:"fs-doctree__row","data-pyric-doctree-depth":e,"data-pyric-doctree-nested":T?"":void 0,style:{"--fs-depth":e},children:[h.jsxs("div",{className:"fs-doctree__line","data-pyric-update":I==null?void 0:I.kind,"data-pyric-update-cycle":I==null?void 0:I.cycle,children:[T?h.jsx("button",{type:"button",className:"fs-doctree__caret","aria-expanded":N,onClick:()=>o(q),children:h.jsx("span",{"aria-hidden":"true",children:N?"▼":"▶"})}):h.jsx("span",{className:"fs-doctree__caret fs-doctree__caret--empty","aria-hidden":"true"}),C?h.jsx("span",{className:"fs-doctree__chip",children:R}):h.jsx("span",{className:"fs-doctree__key",children:R}),T?N?null:h.jsx("span",{className:"fs-doctree__preview",children:j8(_,t,{asVectorView:Ki,vectorPreview:rj})}):h.jsx("span",{className:"fs-doctree__value",children:h.jsx(vy,{value:k.value,path:U,fieldEditors:r})}),h.jsxs("span",{className:"fs-doctree__hover",children:[h.jsxs("span",{className:"fs-doctree__typenote",children:["(",k.type,")"]}),T?h.jsx("button",{type:"button",className:"fs-doctree__icon",title:"Add field","aria-label":`Add field to ${R||"document"}`,onClick:()=>p(t,k.type==="array"?"array":"map"),children:"+"}):h.jsx("button",{type:"button",className:"fs-doctree__icon",title:"Edit","aria-label":`Edit ${R}`,onClick:()=>d(t),children:"✎"}),h.jsx("button",{type:"button",className:"fs-doctree__icon fs-doctree__icon--danger",title:"Delete (shift-click to skip confirmation)","aria-label":`Delete ${R||"field"} (shift-click to skip confirmation)`,onClick:H=>void g(k,R,{shiftKey:H.shiftKey}),children:"🗑"})]})]}),T&&N?h.jsxs("ul",{className:"fs-doctree__children",children:[(_.childIds[t]??[]).map(H=>h.jsx(Nj,{nodeId:H,depth:e+1,editor:n,registry:r,expanded:s,onToggle:o,editingId:c,setEditingId:d,newIdsRef:f,onAdd:p,onDelete:g,onCommitNeeded:b,onReferenceClick:v,updates:x},H)),h.jsx("li",{className:"fs-doctree__action-row fs-doctree__action-row--nested",children:h.jsxs("button",{type:"button",className:"fs-doctree__action",onClick:()=>p(t,k.type==="array"?"array":"map"),children:[h.jsx("span",{"aria-hidden":"true",children:"+"})," ",k.type==="array"?"Add item":"Add field"]})})]}):null]})}function T8({node:t,isNew:e,isArrayChild:n,tree:r,editor:s,registry:o,path:c,onCommitNeeded:d,onDone:f,onCancelNew:p}){const[g,b]=A.useState(t.key??""),[v,x]=A.useState(t.type),[_,k]=A.useState(t.value),[R,C]=A.useState(!1),T=n?void 0:g===""?"Field name is required":k8(r,t,g)?"Field name must be unique":void 0,U=v==="map"||v==="array"?void 0:oj(v,_),q=!T&&!U,I=()=>{if(!q){C(!0);return}n||s.setKey(t.id,g),v!==t.type&&s.setType(t.id,v),v!=="map"&&v!=="array"&&s.setValue(t.id,_),d(),f()},N=()=>{e?p():f()},M=o[v],L=M==null?void 0:M.Edit,H=v!=="map"&&v!=="array"&&L?h.jsx(L,{value:_,path:c,error:R?U:void 0,onChange:w=>k(w)}):v==="map"||v==="array"?h.jsxs("span",{className:"fs-doctree__editnote",children:["Saves as an empty ",v," — add its children afterward."]}):null,P=h.jsxs("span",{className:"fs-doctree__editactions",children:[h.jsx("button",{type:"button",className:"fs-doctree__editsave",onClick:I,"aria-label":"Save field",children:"✓"}),h.jsx("button",{type:"button",className:"fs-doctree__editcancel",onClick:N,"aria-label":"Cancel edit",children:"✕"})]}),F=h.jsx("select",{className:"fs-doctree__edittype",value:v,onChange:w=>{const E=w.target.value;x(E),E!=="map"&&E!=="array"&&E!==v&&k(R8(E))},"aria-label":"Field type",children:(e?N8:Cj).map(w=>h.jsx("option",{value:w,children:w},w))});return h.jsxs("div",{className:"fs-doctree__editrow",onKeyDown:w=>{w.key==="Enter"&&!w.target.matches("textarea")?(w.preventDefault(),I()):w.key==="Escape"&&(w.preventDefault(),N())},children:[n?null:h.jsxs("div",{className:"fs-doctree__editline",children:[h.jsx("input",{type:"text",className:"fs-doctree__editkey",value:g,placeholder:"Field name",autoFocus:e,onChange:w=>b(w.target.value),onBlur:()=>C(!0),"aria-label":"Field name","aria-invalid":R&&T?"true":void 0}),F]}),h.jsxs("div",{className:"fs-doctree__editline",children:[n?F:null,H,P]}),R&&T?h.jsx("span",{className:"fs-doctree__editerr",children:T}):null]})}function R8(t){switch(t){case"string":return"";case"number":return 0;case"boolean":return!1;default:return null}}function Oj({firestore:t,documentRef:e,listSubcollections:n,onSubcollectionClick:r}){const{subcollections:s,isLoading:o}=IB({firestore:t,documentRef:e,listSubcollections:n});return!o&&s.length===0?null:h.jsxs("section",{"data-pyric-ui":"fs-doctree-subcollections","data-pyric-loading":o?"":void 0,children:[h.jsx("div",{className:"fs-doctree__subhead",children:"Subcollections"}),h.jsx("ul",{className:"fs-doctree__sublist",children:s.map(c=>h.jsx("li",{children:r?h.jsxs("button",{type:"button",className:"fs-doctree__subrow",onClick:()=>r(c),"aria-label":`Open subcollection ${c.id}`,children:[h.jsx("span",{children:c.id}),h.jsx("span",{className:"fs-doctree__subtype",children:"subcollection"}),h.jsx("span",{"aria-hidden":"true",children:"›"})]}):h.jsxs("div",{className:"fs-doctree__subrow",children:[h.jsx("span",{children:c.id}),h.jsx("span",{className:"fs-doctree__subtype",children:"subcollection"})]})},c.path))})]})}function D8(t){return t.split("/").filter(Boolean).length%2===0}function Tj(t,e){async function*n(s,o,c=!1){const d=await e.listSubcollections(s.path);for(const f of d)yield*r(t.collection(s,f),o);c||(await t.deleteDoc(s),o.n++,yield{deletedCount:o.n,done:!1})}async function*r(s,o){const c=await e.listDocuments(s.path);for(const d of c){const f=d.path.split("/").pop();f&&(yield*n(t.doc(s,f),o,d.phantom===!0))}}return{async*start(s){const o={n:0};D8(s.path)?yield*n(s,o):yield*r(s,o),yield{deletedCount:o.n,done:!0}}}}async function Rj(t,e){for await(const n of t.start(e))if(n.done)return}async function Dj({confirm:t,ref:e,api:n,recursiveImpl:r}){let s=!1;return await t({title:`Delete document "${e.id}"?`,body:h.jsxs("label",{className:"fs-delete-recursive",children:[h.jsx("input",{type:"checkbox",onChange:c=>{s=c.currentTarget.checked}}),h.jsx("span",{children:"Also delete subcollections recursively. Leave this off to keep nested data."})]}),destructive:!0,confirmLabel:"Delete document"})?(s?await Rj(r,e):await n.deleteDoc(e),!0):!1}function I8(t){const e=t.exists;return typeof e=="function"?e.call(t):e}async function M8(t,e,n,r){const s=t.doc(e,n),o=await t.getDoc(s);if(typeof o.exists=="function"?o.exists():!!o.exists)throw new Error(`Document "${n}" already exists here — choose a different ID.`);await t.setDoc(s,r)}function L8(t){return{id:t.id,ref:t,data:()=>{},__pyricPhantom:!0}}function v_(t){return t.__pyricPhantom===!0}function U8(t,e,n){const r=n.split("/");if(r.length===1)return t.collection(e,n);const s=r[r.length-1],o=r.slice(0,-1).join("/");return t.collection(t.doc(e,o),s)}function $8({handles:t}){var q;const{target:e,navigate:n}=Zd(),r=t.adminFirestore,s=wg(),o=A.useMemo(()=>(e==null?void 0:e.view)==="firestore"?e.path:[],[e]),c=A.useCallback(I=>{const N=typeof I=="function"?I(o):I;n({view:"firestore",path:N})},[n,o]),d=(I,N)=>c(M=>[...M.slice(0,I+1),N]),[f,p]=A.useState(null),g=A.useCallback(async({collectionId:I,docId:N,data:M})=>{if(!f||!I)return;const L=f.parentDocPath,H=L?s.collection(s.doc(r,L),I):s.collection(r,I);await M8(s,H,N,M);const P=L?`${L}/${I}`:I;n({view:"firestore",path:wd(`${P}/${N}`)})},[s,r,f,n]),b=[h.jsx(P8,{api:s,firestore:r,collectionIds:t.listRootCollections(),onSelect:I=>c([{kind:"collection",id:I,path:I}]),onStartCollection:()=>p({parentDocPath:null})},"__root__"),...o.map((I,N)=>{var M;return I.kind==="collection"?h.jsx(q8,{api:s,firestore:r,handles:t,collectionPath:I.path,selectedId:((M=o[N+1])==null?void 0:M.id)??null,onSelect:L=>d(N,{kind:"document",id:L.id,path:L.path}),onCollectionDeleted:()=>c(L=>L.slice(0,N))},I.path):h.jsx(z8,{api:s,firestore:r,handles:t,docPath:I.path,onOpenSubcollection:L=>d(N,{kind:"collection",id:L.id,path:L.path}),onReferenceClick:L=>n({view:"firestore",path:wd(L.path)}),onStartCollection:()=>p({parentDocPath:I.path}),onDeleted:()=>c(L=>L.slice(0,N))},I.path)})],{ref:v,size:x}=Kd(v8),{startIndex:_,visibleCount:k,emptySlots:R}=w8(b.length,x),C=b.slice(_,_+k),T=o.length===0?"Select a collection":((q=o[o.length-1])==null?void 0:q.kind)==="collection"?"Select a document":null,U=[...C,...Array.from({length:R},(I,N)=>h.jsx(F8,{hint:N===0?T:null},`__empty_${N}__`))];return A.useEffect(()=>{if(x==="wide")return;const I=v.current;if(!I)return;const N=document.activeElement;if(N&&N!==document.body&&I.contains(N))return;const M=I.querySelector(".fs-columns > .fs-col:last-child");M&&(M.tabIndex=-1,M.focus({preventScroll:!0}))},[o.length,x]),h.jsx(xg,{children:h.jsxs("div",{ref:v,"data-pyric-ui":"fs-browser","data-fs-depth":o.length,"data-size":x,children:[h.jsx(B8,{path:o,onHome:()=>c([]),onJump:I=>c(N=>N.slice(0,I+1))}),h.jsx("div",{className:"fs-columns",children:U}),f?h.jsx(Ej,{mode:"collection",parentPath:f.parentDocPath?`/${f.parentDocPath}`:"/",onCreate:g,onClose:()=>p(null)}):null]})})}function B8({path:t,onHome:e,onJump:n}){return h.jsxs("nav",{"data-pyric-ui":"fs-breadcrumb","aria-label":"Firestore path",children:[h.jsx("button",{type:"button",className:"fs-crumb",onClick:e,children:"home"}),t.map((r,s)=>h.jsxs(A.Fragment,{children:[h.jsx("span",{className:"fs-crumb-sep","aria-hidden":!0,children:"›"}),s===t.length-1?h.jsx("span",{className:"fs-crumb fs-crumb--current",children:r.id}):h.jsx("button",{type:"button",className:"fs-crumb",onClick:()=>n(s),children:r.id})]},r.path))]})}function F8({hint:t}){return h.jsx("section",{"data-pyric-ui":"fs-empty-col",className:"fs-pane fs-col fs-col--empty","aria-hidden":t?void 0:!0,children:t?h.jsx("p",{className:"fs-empty",children:t}):null})}function P8({api:t,firestore:e,collectionIds:n,onSelect:r,onStartCollection:s}){const o=A.useMemo(()=>n.map(c=>t.collection(e,c)),[t,e,n]);return h.jsxs("section",{"data-pyric-ui":"fs-collections",className:"fs-pane fs-col",children:[h.jsxs("div",{className:"fs-phead",children:[h.jsx("span",{className:"fs-phead-title",children:"Collections"}),h.jsx("button",{type:"button",className:"fs-add",onClick:s,children:"+ New"})]}),h.jsx(_5,{collections:o,onSelect:c=>r(c.id),emptyState:h.jsx("p",{className:"fs-empty",children:"No collections yet. App or agent writes show up here."})})]})}function q8({api:t,firestore:e,handles:n,collectionPath:r,selectedId:s,onSelect:o,onCollectionDeleted:c}){const d=A.useMemo(()=>U8(t,e,r),[t,e,r]),{documents:f,isLoading:p,error:g,subscriptionGeneration:b,hasMore:v,loadMore:x,createDocument:_}=DB({collection:d,mode:"live"}),[k,R]=A.useState([]);A.useEffect(()=>{let F=!1;return Promise.resolve(n.listDocuments(r)).then(w=>{F||R(w.filter(E=>E.phantom).map(E=>E.path.split("/").pop()??""))}).catch(()=>{F||R([])}),()=>{F=!0}},[n,r,f]);const C=A.useMemo(()=>{const F=new Set(f.map(w=>w.id));return[...f,...k.filter(w=>w.length>0&&!F.has(w)).map(w=>L8(t.doc(e,`${r}/${w}`)))]},[f,k,t,e,r]),T=r.split("/").pop()??r,[U,q]=A.useState(null),[I,N]=A.useState(!1),M=lo(),L=A.useMemo(()=>Tj(t,n),[t,n]),H=A.useCallback(async F=>{q(null);try{await Dj({confirm:M,ref:F,api:t,recursiveImpl:L})}catch(w){q(w instanceof Error?w:new Error(String(w)))}},[t,M,L]),P=A.useCallback(async()=>{if(await M({title:`Delete collection "${T}"?`,body:"This deletes every document in it (and their subcollections).",destructive:!0,confirmLabel:"Delete collection"})){q(null);try{await Rj(L,d),c()}catch(w){q(w instanceof Error?w:new Error(String(w)))}}},[M,L,d,T,c]);return h.jsxs("section",{"data-pyric-ui":"fs-documents",className:"fs-pane fs-col",children:[h.jsxs("div",{className:"fs-phead",children:[h.jsx("span",{className:"fs-phead-title",children:T}),h.jsx("span",{className:"fs-phead-actions",children:h.jsx("button",{type:"button",className:"fs-add",onClick:()=>N(!0),children:"+ New"})}),h.jsx(Aj,{items:[{label:"Delete collection",onSelect:()=>void P(),destructive:!0}]})]}),I?h.jsx(Ej,{mode:"document",parentPath:`/${r}`,onCreate:async({docId:F,data:w})=>{const E=await _(F,w,{onExisting:"fail"});o(E)},onClose:()=>N(!1)}):null,h.jsx(E5,{documents:C,isLoading:p,error:g,updateScope:`${r}:${b}`,hasMore:v,onLoadMore:x,onSelect:o,renderLabel:F=>{const w=F.ref;return h.jsx("span",{"data-pyric-selected":s===w.id?"":void 0,style:{display:"contents"},children:v_(F)?h.jsxs(h.Fragment,{children:[h.jsx("span",{className:"fs-doc-phantom",children:F.id}),h.jsx("span",{className:"fs-sub fs-doc-phantom-hint",children:"missing"})]}):F.id})},renderRowAction:F=>{if(v_(F))return null;const w=F.ref;return h.jsx("button",{type:"button",className:"fs-doc-del",title:"Delete document","aria-label":`Delete ${w.id}`,onClick:E=>{E.stopPropagation(),H(w)},children:"×"})},emptyState:h.jsx("p",{className:"fs-empty",children:"No documents."})}),U?h.jsx("p",{className:"fs-empty fs-doc-del-err",children:U.message}):null]})}function z8({api:t,firestore:e,handles:n,docPath:r,onOpenSubcollection:s,onReferenceClick:o,onStartCollection:c,onDeleted:d}){const f=A.useMemo(()=>t.doc(e,r),[t,e,r]),{data:p,error:g,isLoading:b}=wB(f),v=A.useCallback(async(q,I)=>(await n.listSubcollections(I.path)).map(M=>t.collection(I,M)),[n,t]),x=lo(),_=A.useMemo(()=>Tj(t,n),[t,n]),[k,R]=A.useState(null),C=A.useCallback(async()=>{R(null);try{await Dj({confirm:x,ref:f,api:t,recursiveImpl:_})&&d()}catch(q){R(q instanceof Error?q:new Error(String(q)))}},[t,x,_,f,d]),T=A.useCallback(async()=>{await t.setDoc(f,{})},[t,f]),U=p!=null&&I8(p);return h.jsxs("section",{"data-pyric-ui":"fs-document",className:"fs-pane fs-col doc",children:[U?null:h.jsxs("div",{className:"fs-phead",children:[h.jsx("span",{className:"fs-phead-title",children:f.id}),h.jsx("span",{className:"fs-phead-actions",children:h.jsx("button",{type:"button",className:"fs-add",onClick:c,children:"+ Collection"})})]}),p&&U?h.jsx(O8,{snapshot:p,documentRef:f,firestore:e,listSubcollections:v,onReferenceClick:o,onSubcollectionClick:s,onStartCollection:c,onDeleteDocument:()=>void C(),onDeleteDocumentFields:T,onCommit:async q=>{await t.setDoc(f,q)}},r):g?h.jsx("p",{className:"fs-empty fs-doc-del-err",children:g.message}):b?h.jsx("p",{className:"fs-empty",children:"Loading document…"}):h.jsxs(h.Fragment,{children:[h.jsx("p",{className:"fs-empty",children:"This document does not exist."}),h.jsx(Oj,{firestore:e,documentRef:f,listSubcollections:v,onSubcollectionClick:s})]}),k?h.jsx("p",{className:"fs-empty fs-doc-del-err",children:k.message}):null]})}const V8="block w-full text-sm text-soft-white";function H8({auth:t,focusUid:e}){const{users:n,totalCount:r,isLoading:s,error:o,filter:c,setFilter:d,updateUser:f}=vg(t),[p,g]=A.useState(null);A.useEffect(()=>{e&&(g(e),d(e))},[e,d]);const b=n.find(v=>v.uid===p)??null;return h.jsxs("div",{className:"grid grid-cols-[1fr_320px] gap-4",children:[h.jsxs("section",{className:"min-w-0",children:[h.jsx("input",{value:c,onChange:v=>d(v.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"}),h.jsx(JA,{users:n,isLoading:s,error:o,filter:c,onSelect:v=>g(v.uid),className:V8,emptyState:h.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:h.jsx("p",{className:"py-6 text-sm text-slate-gray",children:"No users match the filter."})}),h.jsxs("p",{className:"mt-2 text-xs text-slate-gray",children:[r," user(s) total"]})]}),h.jsx("section",{className:"min-w-0 border-l border-border pl-4",children:b?h.jsx(G8,{user:b,onSave:v=>f(b.uid,v)},b.uid):h.jsx("p",{className:"py-6 text-sm text-slate-gray",children:"Select a user to view and edit."})})]})}function G8({user:t,onSave:e}){const n=WA({initial:t}),[r,s]=A.useState(null),[o,c]=A.useState(!1),d=()=>{s(null),c(!1);try{e(n.toUpdateRequest()),c(!0)}catch(f){s(f instanceof Error?f:new Error(String(f)))}};return h.jsxs("div",{"data-pyric-ui":"auth-editor",children:[h.jsx("h3",{className:"mb-3 truncate font-mono text-xs text-slate-gray",title:t.uid,children:t.uid}),h.jsxs("label",{className:"mb-3 block text-xs text-slate-gray",children:["Display name",h.jsx("input",{value:n.fields.displayName,onChange:f=>n.setField("displayName",f.target.value),className:"mt-1 w-full rounded border border-border bg-content-bg px-2 py-1 text-sm text-soft-white"})]}),h.jsxs("label",{className:"mb-3 block text-xs text-slate-gray",children:["Custom claims (JSON)",h.jsx("textarea",{value:n.fields.claimsText,onChange:f=>n.setField("claimsText",f.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?h.jsx("span",{className:"text-danger",children:n.errors.claims}):null]}),h.jsxs("label",{className:"mb-3 flex items-center gap-2 text-xs text-slate-gray",children:[h.jsx("input",{type:"checkbox",checked:n.fields.disabled,onChange:f=>n.setField("disabled",f.target.checked)}),"Disabled"]}),r?h.jsx("p",{className:"mb-2 text-xs text-danger",children:r.message}):null,o?h.jsx("p",{className:"mb-2 text-xs text-primary",children:"Saved."}):null,h.jsxs("div",{className:"flex gap-2",children:[h.jsx("button",{type:"button",onClick:d,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"}),h.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 x_(t){const e=ft(t),n=e.lastIndexOf("/");return n===-1?"":e.slice(0,n)}function w_(t,e){return t===""?e:e===""?t:`${t}/${e}`}function S_(t){const e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}const K8=[{key:"size",label:"size",value:t=>`${t.size} bytes`},{key:"contentType",label:"content type",value:t=>t.contentType},{key:"timeCreated",label:"created",value:t=>t.timeCreated},{key:"updated",label:"updated",value:t=>t.updated},{key:"md5Hash",label:"md5",value:t=>t.md5Hash},{key:"cacheControl",label:"cache control",value:t=>t.cacheControl},{key:"fullPath",label:"path",value:t=>`gs://${t.bucket}/${t.fullPath}`}];function Y8(t){const e=Object.entries(t.customMetadata??{});return h.jsxs("dl",{"data-pyric-object-metadata":!0,children:[h.jsx("div",{"data-storage-meta-group":!0,children:"Metadata"}),K8.map(({key:n,label:r,value:s})=>{const o=s(t);return o===void 0?null:h.jsxs("div",{"data-pyric-metadata-field":n,children:[h.jsx("dt",{children:r}),h.jsx("dd",{children:o})]},n)}),e.length>0?h.jsx("div",{"data-storage-meta-group":!0,children:"Custom metadata"}):null,e.map(([n,r])=>h.jsxs("div",{"data-pyric-metadata-field":"customMetadata","data-pyric-metadata-key":n,children:[h.jsx("dt",{children:n}),h.jsx("dd",{children:r})]},`custom:${n}`))]})}function Z8(){return h.jsx("svg",{"aria-hidden":!0,viewBox:"0 0 16 16",width:"13",height:"13",fill:"none",stroke:"currentColor",strokeWidth:"1.25",strokeLinejoin:"round",children:h.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 W8(){return h.jsxs("svg",{"aria-hidden":!0,viewBox:"0 0 16 16",width:"13",height:"13",fill:"none",stroke:"currentColor",strokeWidth:"1.25",strokeLinejoin:"round",children:[h.jsx("path",{d:"M4.25 1.75h5l3 3v9.5h-8z"}),h.jsx("path",{d:"M9.25 1.75v3h3"})]})}function J8(t){const e=t.kind==="folder";return h.jsxs(h.Fragment,{children:[h.jsxs("span",{className:"storage__cell-name",children:[h.jsx("span",{className:"storage__ic","aria-hidden":!0,children:e?h.jsx(Z8,{}):h.jsx(W8,{})}),h.jsx("span",{className:"storage__nm",children:t.name}),e?h.jsx("span",{"aria-hidden":!0,className:"storage__chev",children:"›"}):null]}),h.jsx("span",{className:"storage__cell-type",children:e?"folder":"file"}),h.jsx("span",{className:"storage__cell-size"}),h.jsx("span",{className:"storage__cell-updated"})]})}function Q8({storage:t,focusTarget:e}){var F;const n=Zd(),r=e.kind==="object"?ft(e.path):null,s=e.kind==="prefix"?ft(e.path):r?x_(r):"",o=A.useCallback(w=>{const E=ft(w);n.navigate(E?{view:"storage",kind:"prefix",path:E}:{view:"storage",kind:"root"})},[n.navigate]),c=D5({path:s,onPathChange:o}),d=w=>{n.navigate({view:"storage",kind:"object",path:ft(w)})},f=R5(t,c.path),p=M5(),g=P5(t),[b,v]=A.useReducer(Q5,xj),x=V5(t,{path:c.path,list:f,onComplete:w=>v({type:"materialize",path:x_(w.fullPath)})});A.useEffect(()=>{if(f.status==="success")for(const w of f.entries)w.kind==="folder"&&y_(b,w.fullPath)&&v({type:"materialize",path:w.fullPath})},[f.status,f.entries,b]);const[_,k]=A.useState(!1),[R,C]=A.useState(""),[T,U]=A.useState(null),q=A.useRef(null),I=A.useMemo(()=>{const w=X5(b,c.path).filter(D=>!f.entries.some(z=>z.kind==="folder"&&z.name===D));if(w.length===0)return f.entries;const E=w.map(D=>{const z=w_(c.path,D);return{kind:"folder",name:D,fullPath:z,ref:{fullPath:z,name:D}}});return[...[...f.entries.filter(D=>D.kind==="folder"),...E].sort((D,z)=>D.name<z.name?-1:D.name>z.name?1:0),...f.entries.filter(D=>D.kind==="object")]},[f.entries,b,c.path]),N=I.length>0&&I.every(w=>p.isSelected(w.fullPath)),M=w=>{const E=new Set(I.map(D=>D.name)),O=J5(w.map(D=>D.relativePath),E);x.upload(w.map((D,z)=>({path:O[z],data:D.file})))},L=w=>{w.preventDefault();const E=e8(R);if(E){U(E);return}const O=w_(c.path,ft(R));v({type:"create",path:O}),c.setPath(O),C(""),U(null),k(!1)};A.useEffect(()=>p.clear(),[c.path,p.clear]);const H=x.tasks.filter(w=>w.status==="error"),P=g.verdictFor(c.path);return h.jsx(d8,{children:h.jsx(xg,{children:h.jsxs("div",{className:"storage",children:[h.jsxs("div",{className:"storage__sub",children:[h.jsx(H5,{path:c.path,rootLabel:"files",onNavigate:c.setPath}),h.jsx("div",{className:"storage__actions",children:p.size>0?h.jsxs(h.Fragment,{children:[h.jsxs("span",{className:"studio-selection-count",children:[p.size," selected"]}),h.jsx(h8,{storage:t,entries:p.selected,list:f,gate:g,className:"studio-selection-delete",onDeleted:w=>{for(const E of p.selected)E.kind==="folder"&&w.deleted.includes(E.fullPath)&&v({type:"discard",path:E.fullPath});r&&p.selected.some(E=>E.kind==="object"?E.fullPath===r:r.startsWith(`${E.fullPath}/`))&&c.setPath(c.path),p.clear(),f.refresh()},onFailed:w=>{const E=new Set(w.failed.map(O=>O.fullPath));p.selectAll(p.selected.filter(O=>E.has(O.fullPath))),f.refresh()}}),h.jsx("button",{type:"button",className:"storage__action",onClick:p.clear,children:"Clear selection"})]}):h.jsxs(h.Fragment,{children:[h.jsx("button",{type:"button",className:"storage__action","aria-expanded":_,onClick:()=>{k(w=>!w),U(null)},children:"New folder"}),h.jsx("button",{type:"button",className:"storage__action storage__action--upload",onClick:()=>{var w;return(w=q.current)==null?void 0:w.click()},children:"Upload files"}),h.jsx("input",{ref:q,type:"file",multiple:!0,hidden:!0,onChange:w=>{const E=Array.from(w.currentTarget.files??[]);E.length>0&&M(E.map(O=>({file:O,relativePath:O.name}))),w.currentTarget.value=""}})]})})]}),_?h.jsxs("form",{className:"storage__newfolder",onSubmit:L,children:[h.jsx("input",{autoFocus:!0,className:"storage__newfolder-input",placeholder:"folder or nested/path/of/folders","aria-label":"New folder name",value:R,onChange:w=>{C(w.currentTarget.value),U(null)},onKeyDown:w=>{w.key==="Escape"&&k(!1)}}),h.jsx("button",{type:"submit",className:"storage__newfolder-btn",children:"Create"}),T?h.jsx("span",{className:"storage__newfolder-err",role:"alert",children:T}):h.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,H.length>0?h.jsxs("p",{className:"storage__upload-err",role:"alert",children:[H.length===1?`Upload failed: ${S_(H[0].fullPath)} — ${((F=H[0].error)==null?void 0:F.message)??"error"}`:`${H.length} uploads failed: ${H.map(w=>S_(w.fullPath)).join(", ")}`,h.jsx("button",{type:"button",className:"storage__upload-err-dismiss",onClick:x.clearCompleted,children:"Dismiss"})]}):null,h.jsxs("div",{className:"storage__body","data-storage-level":r?"inspector":"browser",children:[h.jsxs(Y5,{className:"storage__browser",onFiles:M,disabled:!P.upload,disabledReason:P.reasons.write.join("; "),children:[h.jsxs("div",{className:"storage__lhead",children:[h.jsx("label",{className:"storage__select-all",title:"Select all in this folder",children:h.jsx("input",{type:"checkbox","aria-label":"Select all in this folder",checked:N,onChange:w=>w.currentTarget.checked?p.selectAll(I):p.clear()})}),h.jsx("span",{children:"name"}),h.jsx("span",{children:"type"}),h.jsx("span",{children:"size"}),h.jsx("span",{children:"updated"})]}),h.jsx(G5,{entries:I,status:f.status,error:f.error,gate:g,selectedPath:r??void 0,renderEntry:J8,renderRowAction:w=>h.jsx("label",{className:"storage__select-row",title:`Select ${w.name}`,children:h.jsx("input",{type:"checkbox","aria-label":`Select ${w.name}`,checked:p.isSelected(w.fullPath),onChange:()=>p.toggle(w)})}),onNavigate:c.enter,onSelect:w=>d(w.fullPath),emptyState:h.jsx("p",{className:"storage__empty",children:y_(b,c.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."})}),h.jsxs("div",{className:"storage__dropcue","aria-hidden":!0,children:["Drop to upload to /",c.path||""]})]}),h.jsx("div",{className:"storage__inspector",children:r?h.jsxs(h.Fragment,{children:[h.jsx("button",{type:"button",className:"storage__back",onClick:()=>c.setPath(c.path),"aria-label":"Back to files",children:"‹ Files"}),h.jsx(c8,{storage:t,path:r,renderMetadata:Y8})]}):h.jsx("p",{className:"storage__inspector-hint",children:"Select an object to inspect its preview and metadata."})})]})]})})})}function X8({view:t}){const e=t==="firestore"?"Firestore":t==="auth"?"Auth":"Storage";return h.jsxs("div",{"data-pyric-ui":"data-pending",className:"flex flex-col items-center justify-center gap-2 py-16 text-center",children:[h.jsx("span",{className:"rounded-full border border-border px-3 py-1 text-xs uppercase tracking-wide text-slate-gray",children:"Local backend pending"}),h.jsxs("p",{className:"max-w-md text-sm leading-relaxed text-slate-gray",children:["The ",e," viewer mounts here. It goes live once the local sandbox backend is reachable (the served `pyric dev --ui` workspace)."]})]})}function Ij({view:t}){const{target:e}=Zd(),n=Xs(),r=n.status==="ready"?n.handles.auth:null;return h.jsx("div",{"data-pyric-ui":"data-feature",children:n.status!=="ready"||!r?h.jsx(X8,{view:t}):n.authApi?h.jsx(GA,{value:n.authApi,children:h.jsx(__,{view:t,handles:n.handles,auth:r,target:e,firestoreApi:n.firestoreApi,storageApi:n.storageApi})}):h.jsx(__,{view:t,handles:n.handles,auth:r,target:e,firestoreApi:n.firestoreApi,storageApi:n.storageApi})})}function __({view:t,handles:e,auth:n,target:r,firestoreApi:s,storageApi:o}){const{users:c}=vg(n),d=A.useMemo(()=>new Set(c.map(f=>f.uid)),[c]);switch(t){case"firestore":{const f=h.jsx($8,{handles:e,knownUids:d});return s?h.jsx(xB,{value:s,children:f}):f}case"auth":return h.jsx(H8,{auth:n,focusUid:(r==null?void 0:r.view)==="auth"?r.uid:null});case"storage":{const f=h.jsx(Q8,{storage:e.storage,focusTarget:(r==null?void 0:r.view)==="storage"?r:{kind:"root"}});return o?h.jsx(T5,{value:o,children:f}):f}}}function eF(){return h.jsx(Ij,{view:"firestore"})}function tF(){return h.jsx(Ij,{view:"storage"})}function nF(t,e){const n=new Set(e.map(r=>r.uid));return new Set([...t].filter(r=>n.has(r)))}async function rF(t,e){const n=[];for(const r of t)try{await e(r.uid)}catch{n.push(r.uid)}return n}function sF(t){const[e,n]=A.useState(()=>new Set);A.useEffect(()=>{n(s=>{const o=nF(s,t);return o.size===s.size&&[...o].every(c=>s.has(c))?s:o})},[t]);const r=A.useMemo(()=>t.filter(s=>e.has(s.uid)),[e,t]);return{selectedUsers:r,allVisibleSelected:t.length>0&&r.length===t.length,isSelected:s=>e.has(s),toggle(s){n(o=>{const c=new Set(o);return c.has(s)?c.delete(s):c.add(s),c})},selectAll(s){n(s?new Set(t.map(o=>o.uid)):new Set)},replace(s){n(new Set(s))},clear(){n(new Set)}}}function iF({users:t,filter:e,onDelete:n,onComplete:r}){const s=lo(),[o,c]=A.useState(!1),[d,f]=A.useState(null),p=async()=>{const g=e.trim().length>0;if(!await s({title:`Delete ${t.length} ${t.length===1?"user":"users"}?`,body:g?`Only the ${t.length} users shown by the current filter will be deleted.`:`This will permanently delete the ${t.length} selected users.`,destructive:!0,confirmLabel:"Delete users"}))return;c(!0),f(null);const v=await rF(t,n);c(!1),f(v.length>0?`Could not delete ${v.length} selected user(s).`:null),r(v)};return h.jsxs(h.Fragment,{children:[h.jsx("button",{type:"button",className:"studio-selection-delete",disabled:o,onClick:()=>void p(),children:o?"Deleting…":"Delete"}),d?h.jsx("span",{className:"auth-sub__error",children:d}):null]})}function Mj(t){if(!t)return"never";const e=new Date(t).getTime();if(Number.isNaN(e))return"never";const n=Math.max(0,Math.round((Date.now()-e)/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 Lj(t){if(!t)return"unknown";const e=new Date(t);return Number.isNaN(e.getTime())?"unknown":e.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}function aF(t){const e=t.isAnonymous&&!t.email,n=t.email??t.phoneNumber??(e?"anonymous":t.uid);return h.jsxs("span",{className:e?"auth-ident auth-ident--anon":"auth-ident",children:[h.jsx("span",{className:"auth-ident__primary",title:n,children:n}),h.jsx("span",{className:"auth-ident__uid",title:t.uid,children:t.uid})]})}function oF({auth:t}={}){const e=as(),n=Xs(),r=t??(n.status==="ready"?n.handles.auth:null),s=n.status==="ready"?n.authApi:void 0;if(!r)return h.jsx("div",{className:"auth-surface","data-pyric-ui":"auth-surface",children:h.jsx(fF,{status:e.status})});const o=h.jsx(xg,{children:h.jsx(lF,{auth:r})});return s?h.jsx(GA,{value:s,children:o}):o}function lF({auth:t}){var C;const{users:e,totalCount:n,isLoading:r,error:s,filter:o,setFilter:c,createUser:d,updateUser:f,deleteUser:p}=vg(t),g=Zd(),b=((C=g.target)==null?void 0:C.view)==="auth"?g.target.uid:null,v=T=>g.navigate({view:"auth",uid:T}),x=A.useMemo(()=>e.find(T=>T.uid===b)??null,[e,b]),[_,k]=A.useState(!1),R=sF(e);return h.jsxs("div",{className:"auth-surface","data-pyric-ui":"auth-surface",children:[h.jsxs("div",{className:"auth-sub",children:[h.jsxs("span",{className:"auth-sub__h",children:["users ",h.jsxs("span",{className:"auth-sub__n",children:["· ",n]})]}),h.jsx("input",{className:"auth-sub__filter",value:o,onChange:T=>c(T.target.value),placeholder:"filter users…","aria-label":"Filter users"}),h.jsx("div",{className:"auth-sub__right",children:R.selectedUsers.length>0?h.jsxs(h.Fragment,{children:[h.jsxs("span",{className:"studio-selection-count",children:[R.selectedUsers.length," selected"]}),h.jsx(iF,{users:R.selectedUsers,filter:o,onDelete:T=>Promise.resolve(p(T)),onComplete:T=>{R.replace(T),b&&!T.includes(b)&&v(null)}}),h.jsx("button",{type:"button",className:"auth-sub__clear",onClick:R.clear,children:"Clear selection"})]}):h.jsx("button",{type:"button",className:"auth-sub__add",onClick:()=>{k(!0),v(null)},children:"Add user"})})]}),h.jsxs("div",{className:"auth-body","data-auth-level":x||_?"detail":"list",children:[h.jsx("div",{className:"auth-list",children:h.jsx(JA,{users:e,isLoading:r,error:s,filter:o,onSelect:T=>{k(!1),v(T.uid)},renderIdentifier:aF,formatCreatedAt:Lj,formatLastLoginAt:Mj,renderSelectionHeader:h.jsx("label",{className:"auth-select",title:"Select all shown users",children:h.jsx("input",{type:"checkbox","aria-label":"Select all shown users",checked:R.allVisibleSelected,onChange:T=>R.selectAll(T.currentTarget.checked)})}),renderSelection:T=>h.jsx("label",{className:"auth-select",title:`Select ${T.uid}`,children:h.jsx("input",{type:"checkbox","aria-label":`Select ${T.uid}`,checked:R.isSelected(T.uid),onChange:()=>R.toggle(T.uid)})}),emptyState:h.jsx("p",{className:"auth-zero",children:"No users yet. Sign-ins from the app, agent-seeded users, and “Add user” all land here."}),noResultsState:h.jsxs("p",{className:"auth-zero",children:["No users match “",o,"”."]})})}),h.jsx("div",{className:"auth-detail",children:_?h.jsx(cF,{onCancel:()=>k(!1),onCreate:async T=>{const U=await Promise.resolve(d(T));k(!1),v(U.uid)}}):x?h.jsxs(h.Fragment,{children:[h.jsx("button",{type:"button",className:"auth-back",onClick:()=>v(null),"aria-label":"Back to users",children:"‹ Users"}),h.jsx(dF,{user:x,onSave:T=>{T.mode==="edit"&&f(T.uid,T.request)},onProvidersChange:async T=>{await Promise.resolve(f(x.uid,{providerUserInfo:T}))},onDelete:()=>{p(x.uid),v(null)}},x.uid)]}):h.jsx("div",{className:"auth-detail__empty",children:h.jsx("p",{className:"auth-zero",children:"Select a user to view and edit."})})})]})]})}function cF({onCreate:t,onCancel:e}){const[n,r]=A.useState(null),s=o=>{o.mode==="create"&&(r(null),t(o.request).catch(c=>{r(c instanceof Error?c:new Error(String(c)))}))};return h.jsxs("div",{className:"auth-editor","data-pyric-ui":"auth-create-user",children:[h.jsxs("div",{className:"auth-editor__head",children:[h.jsx("div",{className:"auth-editor__who",children:"New user"}),h.jsx("div",{className:"auth-editor__meta",children:"Created without signing in — admin semantics, like the emulator’s add-user flow."})]}),h.jsx(QA,{onSubmit:s,onCancel:e,submitLabel:"Create user",children:n?h.jsx("p",{className:"auth-save auth-save--error",role:"alert",children:n.message}):null})]})}const E_=[..._A];function uF({user:t,onChange:e}){const[n,r]=A.useState(null),[s,o]=A.useState(""),c=t.providerUserInfo.map(x=>x.providerId),d=c.includes("password"),f=c.filter(x=>x!=="password"),p=f.filter(x=>!E_.includes(x)),g=x=>{r(null),e(x.map(_=>({providerId:_}))).catch(_=>{r(_ instanceof Error?_:new Error(String(_)))})},b=(x,_)=>{g(_?[...f,x]:f.filter(k=>k!==x))},v=()=>{const x=s.trim();x&&(o(""),!f.includes(x)&&g([...f,x]))};return h.jsxs("section",{className:"auth-providers-editor","aria-label":"Sign-in providers",children:[h.jsx("div",{className:"auth-group",children:"Sign-in providers"}),h.jsx("div",{className:"auth-providers-editor__list",children:[...E_,...p].map(x=>h.jsxs("label",{className:"auth-provider-row","data-pyric-provider-id":x,children:[h.jsx("input",{type:"checkbox",checked:f.includes(x),onChange:_=>b(x,_.target.checked)}),h.jsx("span",{className:"auth-provider-row__label",children:vd(x)}),h.jsx("span",{className:"auth-provider-row__id",children:x})]},x))}),d||t.isAnonymous?h.jsx("p",{className:"auth-providers-editor__derived",children:d?"Password is linked by the password credential above.":"Anonymous — the provider lives on the token, not the record."}):null,h.jsx("div",{className:"auth-provider-custom",children:h.jsxs("label",{className:"auth-provider-custom__field",children:[h.jsx("span",{className:"auth-provider-custom__label",children:"Custom provider ID"}),h.jsxs("span",{className:"auth-provider-custom__row",children:[h.jsx("input",{type:"text",value:s,placeholder:"oidc.my-provider",onChange:x=>o(x.target.value),onKeyDown:x=>{x.key==="Enter"&&(x.preventDefault(),v())}}),h.jsx("button",{type:"button",onClick:v,disabled:!s.trim(),children:"Link"})]})]})}),n?h.jsx("p",{className:"auth-save auth-save--error",role:"alert",children:n.message}):null]})}function dF({user:t,onSave:e,onProvidersChange:n,onDelete:r}){const[s,o]=A.useState(null),[c,d]=A.useState(!1),f=b=>{o(null),d(!1);try{e(b),d(!0)}catch(v){o(v instanceof Error?v:new Error(String(v)))}},p=Lj(t.createdAt),g=Mj(t.lastLoginAt);return h.jsxs("div",{className:"auth-editor","data-pyric-user-disabled":t.disabled?"":void 0,children:[h.jsxs("div",{className:"auth-editor__head",children:[h.jsxs("div",{className:"auth-editor__who",children:[t.email??(t.isAnonymous?"anonymous":t.uid),t.disabled?h.jsx("span",{className:"auth-tag-off",children:"disabled"}):null]}),h.jsxs("div",{className:"auth-editor__uid",children:["uid · ",t.uid]}),h.jsxs("div",{className:"auth-editor__meta",children:["created ",p," · signed in ",g]})]}),h.jsx(uF,{user:t,onChange:n}),h.jsxs(QA,{initial:t,onSubmit:f,submitLabel:"Save",children:[s?h.jsx("p",{className:"auth-save auth-save--error",role:"alert",children:s.message}):null,c?h.jsx("p",{className:"auth-save auth-save--ok",children:"Saved."}):null]},t.uid),h.jsx("div",{className:"auth-editor__foot",children:h.jsx(gB,{user:t,onDelete:r,className:"auth-del"})})]})}function fF({status:t}){const e=t==="pending"?"Seeding the sandbox…":t==="error"?"The dev-seed failed. Check the console.":"No sandbox Auth handle. Run with the dev-seed (DEV) or a live env.";return h.jsx("div",{className:"auth-detail__empty","data-pyric-ui":"auth-surface-empty",children:h.jsx("p",{className:"auth-zero",children:e})})}function hF(t){return t.operationContext.source.kind==="studio"}function pF(t,e){return e?t.filter(n=>!hF(n)):[...t]}const mF=["all","allow","deny","bypassed"];function Wd(t){return t.rulesDisposition.kind==="bypassed"?"bypassed":t.rulesDisposition.kind==="evaluated"?t.rulesDisposition.verdict:null}function yF(t,e){return e==="all"?[...t]:t.filter(n=>Wd(n)===e)}function rm(t){return t.rulesDisposition.kind==="evaluated"}function A_(t){const e=t.path;if(t.service==="storage"&&t.method==="list"&&(e===""||e==="/"))return{tab:"storage"};if(!e||e==="(service)")return null;const n=e.split("/").filter(Boolean);switch(t.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,...t.method==="list"?{query:{kind:"prefix"}}:{}}:null;case"auth":return e!=="*"?{tab:"auth",rest:[e]}:null;default:return null}}const _y="inspect";function Uj(t){const e=t[_y];return e||null}function $j(t,e){const{[_y]:n,...r}=t;return e?{...r,[_y]:e}:r}function gF(t,e){return $j(t,Uj(t)===e?null:e)}function bF(t){const e=Pu(t),n=e.warnings.map(r=>({rule:r.rule,severity:r.severity,message:r.message,...r.fix?{fix:r.fix}:{}}));return e.parseError?{parseable:!1,parseError:e.parseError.message,findings:n}:{parseable:!0,findings:n}}async function vF(t,e,n,r){const s=bF(n);if(!s.parseable)return{result:{outcome:"error",code:"lint-parse-error",message:s.parseError??"The edited ruleset did not parse."},diff:[],lint:s};const o=gE(t,n);try{const c=await Bj(o.sandbox,e),d=c.outcome==="allow"?QD(o,r):[];return{result:c,diff:d,lint:s}}finally{bE(o)}}async function Bj(t,e){var s;const n=Ud(t.withAuth(e.auth)),r=xF(e.resourceData);try{switch(e.method){case"get":await og(Yn(n,e.path));break;case"list":case"listen":await Tl(Il(Ti(n,e.path)));break;case"create":case"set":await Rl(Yn(n,e.path),r);break;case"update":await Jm(Yn(n,e.path),r);break;case"delete":await Dl(Yn(n,e.path));break;default:await lg(Ti(n,wF(e.path)),r)}return{outcome:"allow"}}catch(o){if(o instanceof rt&&o.code==="permission-denied"){const d=(s=o.denialContext)==null?void 0:s.reasons;return{outcome:"deny",code:o.code,message:o.message,...d?{reasons:d}:{}}}return{outcome:"error",code:o instanceof rt?o.code:"unknown",message:o instanceof Error?o.message:String(o)}}}function xF(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:{}}function wF(t){const e=t.lastIndexOf("/");return e<0?t:t.slice(0,e)}const SF=A.lazy(()=>K_(()=>import("./RulesCodeEditor-CXdSLKhO.js"),[]));function Fj(t){return h.jsx(A.Suspense,{fallback:h.jsx(_F,{value:t.value,minHeightRem:t.minHeightRem}),children:h.jsx(SF,{...t})})}function _F({value:t,minHeightRem:e=14}){return h.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:`${e}rem`},children:t||"Loading editor…"})}function Pj({denial:t,editedRules:e,rulesSource:n,onEditedRulesChange:r,onRerunAsUser:s,onRerunAgainstRules:o}){const c=S4(t);return h.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:[h.jsxs("section",{children:[h.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[t.result==="allow"?h.jsx(Va,{kind:"allow",className:"rounded bg-primary/15 px-2 py-0.5 text-xs font-semibold uppercase text-primary",children:"allowed"}):h.jsx(Va,{kind:"deny",className:"rounded bg-danger/15 px-2 py-0.5 text-xs font-semibold uppercase text-danger",children:t.unsupported?"unsupported":"denied"}),h.jsxs("span",{className:"font-mono text-sm text-soft-white",children:[t.service!=="firestore"?`${t.service} · `:"",t.method," ",t.path]})]}),h.jsx("p",{className:"text-sm leading-relaxed text-soft-white",children:c.headline})]}),c.noEvaluation?h.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."}):h.jsxs(h.Fragment,{children:[h.jsx(EF,{denial:t,exp:c,rulesSource:n}),h.jsx(jF,{denial:t})]}),h.jsx(CF,{denial:t}),c.noEvaluation?null:h.jsx(RF,{denial:t,editedRules:e,onEditedRulesChange:r,onRerunAsUser:s,onRerunAgainstRules:o})]})}function EF({denial:t,exp:e,rulesSource:n}){return e.engine==="rtdb"?h.jsx(OF,{denial:t,exp:e}):e.engine==="storage"?h.jsx(TF,{exp:e}):h.jsx(AF,{denial:t,exp:e,rulesSource:n})}function AF({denial:t,exp:e,rulesSource:n}){var c;const r=(c=t.evaluatedRule)==null?void 0:c.line,s=t.result==="allow",o=!!n&&n.trim().length>0;return h.jsx(qs,{label:e.implicitDeny||!e.ruleNode?"matched rule":`matched rule — ${e.ruleNode}${r?` · line ${r}`:""}`,children:o?h.jsx(Fj,{value:n,readOnly:!0,markLine:r,markKind:s?"allow":"deny",minHeightRem:12,ariaLabel:`Deployed firestore.rules — the ${s?"allowing":"denying"} rule is marked`}):h.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(`
|
|
1210
|
-
`)||"(no trace)"})})}function jF({denial:t}){const e=C4(t);return e.length===0?null:h.jsx(qs,{label:"show the work — how the condition evaluated",children:h.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:e.map((n,r)=>h.jsx(qj,{step:n},r))})})}const kF={true:"✓",false:"✗",skipped:"⊘",error:"!",value:"·"};function qj({step:t}){const e=t.outcome==="true"?"text-diff-add":t.outcome==="false"||t.outcome==="error"?"text-danger":"text-slate-gray",n=t.outcome==="skipped"?"not evaluated (short-circuit)":t.outcome==="error"?t.error:`→ ${zj(t.value)}`;return h.jsxs(h.Fragment,{children:[h.jsxs("div",{className:"flex items-baseline gap-2 font-mono text-xs",style:{paddingLeft:`${t.depth*.9}rem`},children:[h.jsx("span",{"aria-hidden":!0,className:`w-3 shrink-0 text-center font-bold ${e}`,children:kF[t.outcome]}),h.jsxs("span",{className:t.outcome==="skipped"?"text-slate-gray line-through":"text-soft-white",children:[t.letBinding?`let ${t.letBinding} = `:"",t.source]}),h.jsx("span",{className:"text-slate-gray",children:n}),t.inlinedFrom?h.jsxs("span",{className:"text-[0.6rem] uppercase tracking-wide text-slate-gray",children:[t.inlinedFrom,"()"]}):null]}),t.children.map((r,s)=>h.jsx(qj,{step:r},s))]})}function zj(t){if(t===void 0)return"undefined";try{return JSON.stringify(Xa(t))}catch{return String(t)}}function CF({denial:t}){const e=N4(t);return h.jsx(qs,{label:"what the rule saw (request / resource)",children:h.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:e.map(n=>h.jsx(NF,{variable:n},n.name))})})}function NF({variable:t}){return h.jsxs("div",{className:"flex flex-col gap-0.5",children:[h.jsx("span",{className:"font-mono text-[0.7rem] text-primary",children:t.name}),t.present?h.jsx(Vj,{value:t.value}):h.jsxs("span",{className:"font-mono text-xs italic text-slate-gray",children:["absent",t.absentNote?` — ${t.absentNote}`:""]})]})}function Vj({value:t,depth:e=0}){const[n,r]=A.useState(e<2),s=Xa(t);if(s===null||typeof s!="object")return h.jsx("span",{className:"font-mono text-xs text-soft-white",children:zj(s)});const o=Array.isArray(s)?s.map((c,d)=>[String(d),c]):Object.entries(s);return o.length===0?h.jsx("span",{className:"font-mono text-xs text-slate-gray",children:Array.isArray(s)?"[]":"{}"}):h.jsxs("div",{className:"flex flex-col",children:[h.jsxs("button",{type:"button",onClick:()=>r(c=>!c),"aria-expanded":n,className:"flex w-fit items-center gap-1 font-mono text-xs text-slate-gray hover:text-soft-white",children:[h.jsx("span",{"aria-hidden":!0,children:n?"▾":"▸"}),h.jsx("span",{children:Array.isArray(s)?`[${o.length}]`:`{${o.length}}`})]}),n?h.jsx("div",{className:"flex flex-col gap-0.5 border-l border-border pl-3",children:o.map(([c,d])=>h.jsxs("div",{className:"flex flex-wrap items-baseline gap-2",children:[h.jsxs("span",{className:"font-mono text-xs text-slate-gray",children:[c,":"]}),h.jsx(Vj,{value:d,depth:e+1})]},c))}):null]})}function OF({denial:t,exp:e}){var n,r;return h.jsxs(h.Fragment,{children:[h.jsx(qs,{label:e.implicitDeny?"rule node":`rule node — ${e.ruleNode}`,children:h.jsxs("code",{className:"font-mono text-xs text-soft-white",children:[e.phase?`.${e.phase}`:"(no matching rule)",(n=t.rules)!=null&&n.matchedPath?` at ${t.rules.matchedPath}`:""]})}),e.ruleExpression?h.jsx(qs,{label:"rule expression",children:h.jsx("pre",{className:"overflow-auto rounded-md border border-border bg-content-bg p-3 font-mono text-xs text-slate-gray",children:e.ruleExpression})}):null,e.bindings?h.jsx(qs,{label:"$variable bindings",children:h.jsx("code",{className:"font-mono text-xs text-soft-white",children:Object.entries(e.bindings).map(([s,o])=>`${s.startsWith("$")?s:`$${s}`} → ${o}`).join(", ")})}):null,(r=t.rules)!=null&&r.reason?h.jsx(qs,{label:"simulator reason",children:h.jsx("code",{className:"font-mono text-xs text-slate-gray",children:t.rules.reason})}):null]})}function TF({exp:t}){return h.jsxs(qs,{label:t.implicitDeny?"matched rule":"matched rule (match block)",children:[t.ruleNode?h.jsx("code",{className:"mb-2 block font-mono text-xs text-soft-white",children:t.ruleNode}):null,h.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(`
|
|
1211
|
-
`)||"(no trace)"})]})}function qs({label:t,children:e}){return h.jsxs("div",{className:"flex flex-col gap-1",children:[h.jsx("span",{className:"text-[0.65rem] font-semibold uppercase tracking-wider text-slate-gray",children:t}),e]})}function RF({denial:t,editedRules:e,onEditedRulesChange:n,onRerunAsUser:r,onRerunAgainstRules:s}){var _,k,R;const[o,c]=A.useState(null),[d,f]=A.useState(null),p=p4(t),g=p.impersonate.kind==="live"&&!!r&&!!((_=t.auth)!=null&&_.uid),b=p.editedRuleset.kind==="live"&&!!s;async function v(){if(r){c("pending");try{c(await r(t))}catch(C){c({outcome:"error",code:"unknown",message:String(C)})}}}async function x(){if(s){f("pending");try{f(await s(t,e??""))}catch(C){f({result:{outcome:"error",code:"unknown",message:String(C)},diff:[],lint:{parseable:!0,findings:[]}})}}}return h.jsxs("section",{"data-pyric-ui":"rerun-panel",className:"mt-1 flex flex-col gap-4 border-t border-border pt-4",children:[j4(t)?h.jsxs("div",{className:"flex flex-col gap-2",children:[h.jsxs("div",{className:"flex items-center justify-between gap-3",children:[h.jsx("span",{className:"text-sm font-medium text-soft-white",children:"Re-run as the attempting user"}),h.jsx("button",{type:"button",disabled:!g||o==="pending",onClick:v,className:"rounded-md border border-primary/40 px-3 py-1 text-xs font-medium text-primary transition-colors hover:bg-primary/10 disabled:cursor-not-allowed disabled:border-border disabled:text-slate-gray",children:o==="pending"?"Running…":p.impersonate.kind==="live"?`Impersonate ${((k=t.auth)==null?void 0:k.uid)??""}`:"Impersonation not available"})]}),h.jsx(j_,{support:p.impersonate,haveCallback:!!r}),o&&o!=="pending"?h.jsx(k_,{result:o}):null]}):null,h.jsxs("div",{className:"flex flex-col gap-2",children:[h.jsxs("div",{className:"flex items-center justify-between gap-3",children:[h.jsx("span",{className:"text-sm font-medium text-soft-white",children:"Re-run against an edited ruleset"}),h.jsx("button",{type:"button",disabled:!b||d==="pending",onClick:x,className:"rounded-md border border-primary/40 px-3 py-1 text-xs font-medium text-primary transition-colors hover:bg-primary/10 disabled:cursor-not-allowed disabled:border-border disabled:text-slate-gray",children:d==="pending"?"Linting + forking…":"Lint, then test on a branch"})]}),n&&p.editedRuleset.kind==="live"?h.jsx(Fj,{value:e??"",onChange:n,markLine:(R=t.evaluatedRule)==null?void 0:R.line,markKind:t.result==="allow"?"allow":"deny",minHeightRem:14,ariaLabel:"Edited firestore.rules to test the op against"}):null,h.jsx(j_,{support:p.editedRuleset,haveCallback:!!s}),d&&d!=="pending"?h.jsxs(h.Fragment,{children:[d.lint.findings.length>0||!d.lint.parseable?h.jsx(DF,{lint:d.lint}):null,h.jsx(k_,{result:d.result}),d.diff.length>0?h.jsx(MF,{diff:d.diff}):null]}):null]})]})}function j_({support:t,haveCallback:e}){if(t.kind==="pending"||t.kind==="absent"){const n=t.kind==="pending"?t.tool:t.missingTool;return h.jsxs("p",{"data-pyric-ui":"rerun-hint-gated",className:"rounded-md border border-border bg-content-bg px-3 py-2 text-xs text-slate-gray",children:[t.hint," ",h.jsx("code",{className:"font-mono text-[0.7rem] text-warning",children:n})]})}return e?null:h.jsx("p",{className:"rounded-md border border-border bg-content-bg px-3 py-2 text-xs text-slate-gray",children:"Wired to the live sandbox once the local backend is reachable. The denial, rule, and context above are already live."})}function DF({lint:t}){return h.jsxs("div",{"data-pyric-ui":"rerun-lint",className:"flex flex-col gap-1 rounded-md border border-border bg-content-bg p-3",children:[h.jsx("span",{className:"text-[0.65rem] font-semibold uppercase tracking-wider text-slate-gray",children:"lint (firestore_lint_rules)"}),t.parseable?t.findings.map((e,n)=>h.jsxs("p",{className:"font-mono text-xs",children:[h.jsx("span",{className:e.severity==="error"?"text-danger":"text-warning",children:e.rule}),h.jsxs("span",{className:"text-slate-gray",children:[" — ",e.message]})]},`${e.rule}-${n}`)):h.jsx("p",{className:"font-mono text-xs text-danger",children:t.parseError})]})}function k_({result:t}){return t.outcome==="allow"?h.jsxs("p",{className:"flex items-center gap-2 text-xs",children:[h.jsx(Va,{kind:"allow",className:"rounded bg-primary/15 px-2 py-0.5 font-semibold uppercase text-primary",children:"allow"}),h.jsx("span",{className:"text-slate-gray",children:"The re-run is permitted under these rules."})]}):t.outcome==="deny"?h.jsxs("p",{className:"flex items-center gap-2 text-xs",children:[h.jsx(Va,{kind:"deny",className:"rounded bg-danger/15 px-2 py-0.5 font-semibold uppercase text-danger",children:"deny"}),h.jsxs("span",{className:"text-slate-gray",children:["Denied under these rules: ",t.message]})]}):h.jsxs("p",{className:"flex items-center gap-2 text-xs",children:[h.jsx(Va,{kind:"error",className:"rounded bg-warning/15 px-2 py-0.5 font-semibold uppercase text-warning",children:t.code}),h.jsx("span",{className:"text-slate-gray",children:t.message})]})}function IF(t){return t.kind==="autoid-alias"?{path:t.originalPath,before:t.originalPath,after:t.replayedPath}:{path:t.path,..."field"in t&&t.field?{field:t.field}:{},before:t.before,after:t.after}}function MF({diff:t}){return h.jsxs("div",{"data-pyric-ui":"rules-debug-diff",className:"flex flex-col gap-1 rounded-md border border-border bg-content-bg p-3",children:[h.jsx("span",{className:"text-[0.65rem] font-semibold uppercase tracking-wider text-slate-gray",children:"what the re-run changed (branch vs live)"}),t.map((e,n)=>{const r=IF(e),s=r.field?`.${r.field}`:"",o=r.before===void 0&&r.after!==void 0,c=r.before!==void 0&&r.after===void 0;return h.jsxs("div",{className:"font-mono text-xs",children:[h.jsxs("span",{className:o?"text-diff-add":c?"text-diff-remove":"text-warning",children:[o?"+ ":c?"- ":"~ ",r.path,s]}),o?null:h.jsx("span",{className:"ml-2 text-slate-gray",children:JSON.stringify(Xa(r.before))}),c?null:h.jsxs("span",{className:"ml-2 text-soft-white",children:["→ ",JSON.stringify(Xa(r.after))]})]},`${r.path}-${n}`)})]})}function C_({eventId:t,onClose:e}){const n=M4(),r=F4(),s=V4(),o=n.find(b=>b.id===t),[c,d]=A.useState(""),f=c||s;if(!o)return h.jsxs("div",{"data-pyric-ui":"traffic-inspect-missing",className:"traffic__inspector",children:[h.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."}),h.jsx("button",{type:"button",className:"traffic__inspector-close",onClick:e,children:"Back to the log"})]});const p=async b=>{const v=await r();if(!v)return{outcome:"error",code:"no-backend",message:"No sandbox snapshot to re-run against."};const x=gE(v,s);try{return await Bj(x.sandbox,b)}finally{bE(x)}},g=async(b,v)=>{const x=await r();return x?vF(x,b,v,x):{result:{outcome:"error",code:"no-backend",message:"No sandbox snapshot to re-run against."},diff:[],lint:{parseable:!0,findings:[]}}};return h.jsxs("div",{"data-pyric-ui":"traffic-rules-inspector",className:"traffic__inspector",children:[h.jsxs("div",{className:"traffic__inspector-bar",children:[h.jsx("span",{className:"traffic__inspector-title",children:"rules inspector"}),h.jsx("button",{type:"button",className:"traffic__inspector-close",onClick:e,"aria-label":"Close rules inspector (Esc)",children:"close (esc)"})]}),h.jsx(Pj,{denial:o,editedRules:f,rulesSource:s,onEditedRulesChange:d,onRerunAsUser:p,onRerunAgainstRules:g})]})}const LF=new Intl.NumberFormat,UF={reads:"read operations",writes:"writes",deletes:"deletes"},$F={allows:"allowed requests",denies:"denied requests"};function N_(t){return t.length<=1?t[0]??"":t.length===2?`${t[0]} and ${t[1]}`:`${t.slice(0,-1).join(", ")}, and ${t.at(-1)}`}function O_(t){return t&&`${t[0].toUpperCase()}${t.slice(1)}`}function Hj(t,e){const n=t.reduce((p,g)=>p+g.total,0);if(n===0)return{total:n,headline:e.emptyHeadline,finding:e.emptyFinding};const r=Math.max(...t.map(p=>p.total)),s=t.filter(p=>p.total===r),o=`${LF.format(n)} observed ${n===1?e.singular:e.plural}`,c=p=>e.labels[p.key]??p.label.toLowerCase();if(s.length>1){const p=s.map(c);return{total:n,headline:o,finding:s.length===t.length?`${e.evenSplitPrefix} ${N_(p)}.`:`${O_(N_(p))} tied for the largest share of ${e.subject} in this window.`}}const d=s[0],f=Math.round(d.total/n*100);return{total:n,headline:o,finding:`${O_(c(d))} accounted for ${f}% of ${e.subject} in this window.`}}function BF(t){return Hj(t,{labels:UF,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 FF(t){return Hj(t,{labels:$F,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 PF=new Intl.NumberFormat,qF=new Intl.DateTimeFormat(void 0,{hour:"numeric",minute:"2-digit"});function T_(t){return PF.format(t)}function ul(t){return qF.format(t)}function zF(t){return Wd(t)==="bypassed"}function VF(t){return t.every(e=>e.total===0)}function Gj({eyebrow:t,story:e,series:n,points:r,window:s,emptyLabel:o,evidenceTitle:c,source:d,methodology:f}){const[p,g]=A.useState(()=>new Set(n.map(v=>v.key))),b=A.useCallback(v=>{g(x=>{const _=new Set(x);return _.has(v)?_.delete(v):_.add(v),_})},[]);return h.jsxs("section",{className:"traffic__metric-panel traffic__metric-panel--journal","data-pyric-ui":"traffic-metric-panel",children:[h.jsxs("header",{className:"traffic__metric-story",children:[h.jsx("p",{className:"traffic__metric-eyebrow",children:t}),h.jsx("h3",{className:"traffic__metric-headline",children:e.headline}),h.jsx("p",{className:"traffic__metric-finding",children:e.finding})]}),h.jsx(G6,{series:n,visible:p,onToggle:b,formatValue:T_,className:`traffic__metric-cards traffic__metric-cards--journal traffic__metric-cards--${n.length}`}),VF(n)?h.jsx("p",{className:"traffic__empty",children:o}):h.jsxs("div",{className:"traffic__metric-evidence",children:[h.jsxs("div",{className:"traffic__metric-evidence-header",children:[h.jsx("h4",{children:c}),h.jsxs("span",{children:[ul(s.start),"–",ul(s.end)]})]}),h.jsx(Z6,{points:r,series:n,visible:p,omitZeroSeries:!0,formatValue:T_,formatTime:ul,className:"traffic__chart traffic__chart--journal"}),h.jsxs("div",{className:"traffic__metric-axis","aria-hidden":"true",children:[h.jsx("span",{children:ul(s.start)}),h.jsx("span",{children:ul(s.end)})]})]}),h.jsxs("footer",{className:"traffic__metric-footer",children:[h.jsx("p",{className:"traffic__metric-source",children:d}),h.jsxs("details",{className:"traffic__metric-methodology",children:[h.jsx("summary",{children:"How this is counted"}),h.jsx("div",{children:f})]})]})]})}function HF({events:t,window:e}){const n=A.useMemo(()=>t.filter(o=>(o.service??"firestore")==="firestore"),[t]),r=j6({events:n,window:e,isAdmin:zF}),s=A.useMemo(()=>BF(r.series),[r.series]);return h.jsx("div",{className:"traffic__metrics","data-pyric-ui":"traffic-billable-view",children:h.jsx(Gj,{eyebrow:"Billable activity",story:s,series:r.series,points:r.points,window:e,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:h.jsxs(h.Fragment,{children:[h.jsxs("p",{children:["Counts successful Firestore sandbox ",h.jsx("code",{children:"get"}),"/",h.jsx("code",{children:"list"}),","," ",h.jsx("code",{children:"create"}),"/",h.jsx("code",{children:"update"}),"/",h.jsx("code",{children:"set"}),", and"," ",h.jsx("code",{children:"delete"}),"/",h.jsx("code",{children:"remove"})," operations in the displayed window. Rules-bypassed admin operations are included because they still execute."]}),h.jsxs("p",{children:[h.jsx("strong",{children:"Read ops are a proxy, not billed document reads."})," Each"," ",h.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 GF({events:t,window:e}){const n=A.useMemo(()=>t.filter(c=>c.rulesDisposition.kind==="evaluated"),[t]),r=k6({events:n,window:e}),s=A.useMemo(()=>r.series.filter(c=>c.key==="allows"||c.key==="denies"),[r.series]),o=A.useMemo(()=>FF(s),[s]);return h.jsx("div",{className:"traffic__metrics","data-pyric-ui":"traffic-rules-view",children:h.jsx(Gj,{eyebrow:"Rules decisions",story:o,series:s,points:r.points,window:e,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:h.jsxs(h.Fragment,{children:[h.jsxs("p",{children:["Counts only operations whose canonical Rules disposition is"," ",h.jsx("code",{children:"evaluated"}),", grouped by its ",h.jsx("code",{children:"allow"})," or ",h.jsx("code",{children:"deny"})," ","verdict."]}),h.jsxs("p",{children:[h.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 KF=[{id:"timeline",label:"Timeline"},{id:"billable",label:"Billable metrics"},{id:"rules",label:"Rules"}];function YF(t){return t==="billable"?"billable":t==="rules"||t==="subscriptions"?"rules":"timeline"}function ZF(t,e){return t===0?"No requests occurred in this interval.":t===1?e===1?"The request in this interval was denied.":"One request occurred in this interval; it was not denied.":e===0?`${t} requests occurred in this interval; none were denied.`:e===t?`All ${t} requests in this interval were denied.`:`${t} requests occurred in this interval; ${e} ${e===1?"was":"were"} denied.`}function WF(t,e){const n=t.filter(s=>s.at>=e.start&&s.at<e.end),r=n.reduce((s,o)=>s+(o.result==="deny"?1:0),0);return{window:e,events:n,total:n.length,denies:r,finding:ZF(n.length,r)}}function JF(t,e){return(t==null?void 0:t.start)===e.start&&t.end===e.end?null:e}function QF(){const{tab:t,query:e}=Nr();return t!=="traffic"?"timeline":YF(e.view)}function XF(){const t=A.useSyncExternalStore(Vl,QF,()=>"timeline"),e=A.useCallback(n=>{const r={...Nr().query,view:n==="timeline"?void 0:n};r.view===void 0&&delete r.view,Jn({tab:"traffic",query:r})},[]);return[t,e]}function eP(){const t=A.useSyncExternalStore(Vl,()=>Nr().query.hide==="studio",()=>!1),e=A.useCallback(()=>{const n={...Nr().query};n.hide==="studio"?delete n.hide:n.hide="studio",Jn({tab:"traffic",query:n})},[]);return[t,e]}function tP(t,e){const n=Math.max(0,Math.round((e-t)/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 R_(t){return`${Ul(t.start)}–${Ul(t.end)}`}function nP({event:t}){const e=Wd(t);return e?h.jsx("span",{className:"traffic__verdict","data-verdict":e,children:e}):null}function rP(){return A.useSyncExternalStore(Vl,()=>Uj(Nr().query),()=>null)}const sm=100;function sP(){const t=I4(),[e,n]=XF(),[r,s]=eP(),o=A.useMemo(()=>pF(t,r),[t,r]),c=t.length-o.length,[d,f]=A.useState("all"),[p,g]=A.useState(null),b=rP(),[v,x]=A.useState(sm),_=E=>{Jn({tab:"traffic",query:gF(Nr().query,E)})},k=()=>{Jn({tab:"traffic",query:$j(Nr().query,null)})};A.useEffect(()=>{if(!b)return;const E=O=>{O.key==="Escape"&&k()};return globalThis.addEventListener("keydown",E),()=>globalThis.removeEventListener("keydown",E)},[b]);const R=A.useMemo(()=>{const E=Date.now();if(o.length===0)return{start:E-15*6e4,end:E};let O=1/0;for(const D of o)D.at<O&&(O=D.at);return{start:Math.min(O,E-6e4),end:E+1e3}},[o]),C=R.end,T=A.useMemo(()=>p?WF(o,p):null,[o,p]),U=(T==null?void 0:T.events)??o,q=A.useMemo(()=>yF(U,d).sort((E,O)=>O.at-E.at),[U,d]),{items:I}=f6({events:q}),N=I.slice(0,v),M=I.length-N.length,L=o.length>=gd,H=o.filter(E=>E.result==="deny").length,P=E=>h.jsx(nP,{event:E}),F=E=>{if(rm(E)){_(E.id);return}const O=A_(E);O&&Jn(O)},w=b!=null&&N.some(E=>E.type!=="group"&&E.event.id===b);return h.jsxs("section",{"data-pyric-ui":"traffic-surface",className:"traffic",children:[h.jsxs("div",{className:"traffic__tabs",role:"tablist","aria-label":"Traffic views",children:[KF.map(E=>h.jsx("button",{type:"button",role:"tab",className:"traffic__tab","aria-selected":e===E.id,onClick:()=>n(E.id),children:E.label},E.id)),h.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&&c>0?` (${c} hidden)`:""]})]}),e==="billable"?h.jsx(HF,{events:o,window:R}):e==="rules"?h.jsx(GF,{events:o,window:R}):h.jsxs(h.Fragment,{children:[h.jsx(z6,{events:o,window:R,brush:p??void 0,onBrush:E=>{g(O=>JF(O,E)),b&&k()},liveAt:R.end,bucketCount:36,className:"traffic__timeline",header:h.jsxs("div",{className:"traffic__tl-header",children:[h.jsxs("span",{className:"traffic__tl-count",children:[o.length," requests",L?` (showing latest ${gd})`:""]}),H>0?h.jsxs("button",{type:"button",className:"traffic__tl-deny","aria-pressed":d==="deny",onClick:()=>f(E=>E==="deny"?"all":"deny"),title:"Filter the stream to denied requests",children:[H," denied"]}):null,h.jsx("span",{className:"traffic__tl-live",children:"live"})]}),axis:E=>h.jsxs("div",{className:"traffic__tl-axis",children:[h.jsx("span",{children:tP(E.start,C)}),h.jsx("span",{children:"now"})]}),renderBucketSummary:E=>h.jsxs("div",{className:"traffic__bucket-summary",children:[h.jsx("span",{children:R_(E)}),h.jsxs("strong",{children:[E.count," ",E.count===1?"request":"requests"]}),h.jsxs("span",{children:[E.denies," denied"]})]}),emptyState:h.jsx("p",{className:"traffic__empty",children:"No requests in this window yet."})}),T?h.jsxs("section",{className:"traffic__time-focus","aria-label":"Selected traffic interval","aria-live":"polite",children:[h.jsxs("div",{className:"traffic__time-focus-story",children:[h.jsx("p",{className:"traffic__time-focus-eyebrow",children:"Selected interval"}),h.jsx("h3",{children:R_(T.window)}),h.jsx("p",{children:T.finding})]}),h.jsx("button",{type:"button",onClick:()=>g(null),children:"Show all traffic"})]}):null,h.jsxs("div",{className:"traffic__filters",role:"group","aria-label":"Traffic filters",children:[h.jsx("span",{className:"traffic__filters-label","aria-hidden":"true",children:"verdict"}),mF.map(E=>h.jsx("button",{type:"button",className:"traffic__filter","aria-pressed":d===E,onClick:()=>f(E),children:E},E))]}),b&&!w?h.jsx(C_,{eventId:b,onClose:k},b):null,I.length===0?h.jsx("p",{className:"traffic__empty",children:T?d==="all"?"No requests occurred in the selected interval.":`No ${d} traffic occurred in the selected interval.`:d==="all"?"No requests yet. Reads, writes, and listeners against the sandbox stream in live.":`No ${d} traffic in this session.`}):h.jsxs("div",{className:"traffic__log","data-pyric-ui":"traffic-log","data-pyric-grouped":"","data-pyric-time-focused":T?"":void 0,children:[h.jsx("ul",{"data-pyric-traffic-log-items":"",children:N.map(E=>E.type==="group"?h.jsx("li",{"data-pyric-traffic-group-entry":"",children:h.jsx(P6,{group:E,onSelect:O=>{const D=O;if(rm(D)){_(D.id);return}const z=A_(D);z&&Jn(z)},renderClassification:O=>P(O),formatTime:Ul})},E.key):h.jsxs("li",{"data-pyric-traffic-entry":"","data-pyric-traffic-id":E.event.id,"data-verdict":Wd(E.event)??void 0,children:[h.jsx(zA,{event:E.event,selected:E.event.id===b,onSelect:O=>F(O),renderClassification:O=>P(O),formatTime:Ul}),E.event.id===b&&rm(E.event)?h.jsx(C_,{eventId:b,onClose:k},b):null]},E.event.id))}),M>0?h.jsxs("button",{type:"button",className:"traffic__show-more",onClick:()=>x(E=>E+sm),children:["Show ",Math.min(M,sm)," more (",M," hidden)"]}):null]})]})]})}const D_=["amber","teal","coral","slate","olive","plum","rust","indigo","mint","sand","ash","jade"],I_=["fox","owl","lynx","crane","otter","wren","ibex","hare","newt","moth","seal","vole"];function jg(t){if(!t)return"";let e=0;for(let n=0;n<t.length;n++)e=Math.imul(e,31)+t.charCodeAt(n)>>>0;return`${D_[e%D_.length]}-${I_[(e>>>4)%I_.length]}`}function iP(t){var r;const e=((r=t.operationContext)==null?void 0:r.source)??t.actor;if((e==null?void 0:e.kind)==="agent")return{provenance:"agent",identity:`agent:${e.name}`};if((e==null?void 0:e.kind)==="studio")return{provenance:"studio",identity:"studio"};if((e==null?void 0:e.kind)==="app-builder")return{provenance:"app-builder",identity:"builder"};const n="auth"in t&&t.auth&&typeof t.auth=="object"?t.auth.uid:void 0;return!e||e.kind==="unattributed"?{provenance:"unattributed",identity:n??"unattributed"}:{provenance:"app",identity:n??"app"}}function aP(t){return t?{tab:"firestore",rest:t.split("/").filter(Boolean)}:null}function oP(t){var s;const{provenance:e,identity:n}=iP(t),r={id:t.id,at:t.at,provenance:e,identity:n};switch(t.kind){case"write":return{...r,denied:!1,summary:`${t.method} /${t.path}`,target:aP(t.path)};case"request":return t.result!=="deny"?null:{...r,denied:!0,summary:`denied ${t.method} /${t.path}`,target:{tab:"traffic",query:{inspect:t.id}}};case"operation":return t.result==="deny"?{...r,denied:!0,summary:`denied ${t.service} ${t.method}${t.path?` ${t.path}`:""}`,target:{tab:"traffic",query:{inspect:t.id}}}:null;case"service_mutation":{const o=t.path?` ${t.path}`:"",c=t.service==="auth"&&t.path&&t.path!=="*"?{tab:"auth",rest:[t.path]}:t.service==="storage"&&t.path?{tab:"storage",rest:t.path.split("/").filter(Boolean)}:t.service==="rtdb"?{tab:"rtdb"}:null;return{...r,denied:!1,summary:`${t.service} ${t.op}${o}`,target:c}}case"commit":return t.service!=="rtdb"||((s=t.detail)==null?void 0:s.admin)!==!0?null:{...r,denied:!1,summary:`rtdb ${t.method}${t.path?` ${t.path}`:""}`,target:{tab:"rtdb"}};case"session_boundary":return{...r,provenance:"system",identity:"sandbox",denied:!1,summary:`session ${t.phase}`,target:null};default:return null}}function lP(t,e=20){const n=[];for(let r=t.length-1;r>=0&&n.length<e;r--){const s=oP(t[r]);s&&n.push(s)}return n}const cP=20;function uP(t){Jn(t)}function eo({target:t,className:e,children:n,title:r}){return h.jsx("a",{className:e,href:Bd(t),title:r,onClick:s=>{s.metaKey||s.ctrlKey||s.shiftKey||s.altKey||(s.preventDefault(),uP(t))},children:n})}function dP(){const t=as(),e=Vd(),n=yg();if(e.status==="loading"||t.status==="pending")return h.jsxs("div",{className:"studio-home__status","aria-label":"Sandbox status",children:[h.jsx("span",{className:"studio-chip studio-home__skeleton-chip","aria-hidden":"true"}),h.jsx("span",{className:"studio-chip studio-home__skeleton-chip","aria-hidden":"true"})]});const s=[];if(t.status==="ready"&&e.status!=="ready"&&s.push(h.jsxs("span",{className:"studio-chip",title:"In-page seeded sandbox — no server. Data resets on reload.",children:[h.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),"dev seed · in-page"]},"seed")),e.status==="ready"){const o=e.payload;s.push(h.jsxs(eo,{className:"studio-chip",target:{tab:"settings"},title:"Persistence mode — manage in Settings.",children:[h.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),o.persist?"persisted to disk":"ephemeral"]},"persist")),o.rulesHash&&s.push(h.jsxs("span",{className:"studio-chip",title:"Hash of the rules this serve deployed to the sandbox.",children:[h.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),"rules ",o.rulesHash.slice(0,8)]},"rules"))}return n&&s.push(h.jsxs(eo,{className:"studio-chip",target:{tab:"settings"},title:`Sandbox instance ${n} — maintenance lives in Settings.`,children:[h.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),jg(n)]},"instance")),h.jsx("div",{className:"studio-home__status","aria-label":"Sandbox status",children:s})}function fP(t){return new Date(t).toLocaleTimeString(void 0,{hour12:!1})}function hP(){const t=Yl(),e=A.useMemo(()=>lP(t,cP),[t]);return h.jsxs("section",{className:"studio-panel studio-home__feed","aria-label":"Live activity",children:[h.jsxs("header",{className:"studio-home__feed-head",children:[h.jsx("h2",{className:"studio-panel__title studio-home__feed-title",children:"Activity"}),h.jsx(eo,{className:"studio-home__feed-all",target:{tab:"traffic"},children:"view all in Traffic →"})]}),e.length===0?h.jsx("p",{className:"studio-home__feed-empty",children:"No activity yet — writes, denials, and seeds show up here live."}):h.jsx("div",{className:"studio-home__feed-scroll",children:h.jsx("ol",{className:"studio-home__feed-list",children:e.map(n=>{const r=h.jsxs(h.Fragment,{children:[h.jsxs("span",{className:"studio-home__feed-ident","data-provenance":n.provenance,children:[h.jsx("span",{className:"studio-home__feed-dot","aria-hidden":"true"}),n.identity]}),h.jsx("span",{className:"studio-home__feed-summary","data-denied":n.denied?"true":void 0,children:n.summary}),h.jsx("time",{className:"studio-home__feed-time",dateTime:new Date(n.at).toISOString(),children:fP(n.at)})]});return h.jsx("li",{children:n.target?h.jsx(eo,{className:"studio-home__feed-row",target:n.target,children:r}):h.jsx("span",{className:"studio-home__feed-row",children:r})},n.id)})})})]})}const pP=["firestore","auth","rtdb","storage","traffic"];function mP(){const t=Xs(),e=Yl(),n=A.useMemo(()=>{const r={};if(t.status==="ready"){const s=t.handles.listRootCollections().length;r.firestore=`${s} collection${s===1?"":"s"}`}return e.length&&(r.traffic=`${e.length} events`),r},[t,e]);return h.jsx("div",{className:"studio-home__tiles",children:pP.map(r=>{const s=Ui.find(o=>o.id===r);return s?h.jsxs(eo,{className:"studio-card studio-home__tile",target:{tab:r},children:[h.jsxs("span",{className:"studio-home__tile-top",children:[h.jsx("span",{className:"studio-home__tile-label",children:s.label}),n[r]?h.jsx("span",{className:"studio-badge",children:n[r]}):null]}),h.jsx("span",{className:"studio-home__tile-desc",children:s.description})]},r):null})})}function yP(){const t=Vd(),e=t.status==="ready",n=e&&!!t.payload.bridgeUrl,r=typeof window<"u"?window.location.origin:"",s=e?t.payload.rulesHash:null;return h.jsxs(h.Fragment,{children:[h.jsxs("section",{className:"studio-card studio-home__onboard","aria-label":"Connect your agent",children:[h.jsx("span",{className:"studio-home__tile-label",children:"Connect your agent"}),h.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."}),h.jsx("code",{className:"studio-home__snippet",children:n?`${r}/__pyric/mcp`:"pyric dev --bridge # then <url>/__pyric/mcp"})]}),h.jsxs("section",{className:"studio-card studio-home__onboard","aria-label":"Seed data",children:[h.jsx("span",{className:"studio-home__tile-label",children:"Seed data"}),h.jsx("span",{className:"studio-home__tile-desc",children:"Start from a fixture, or create documents by hand in the Firestore browser."}),h.jsx("code",{className:"studio-home__snippet",children:"pyric dev --seed seed.json"}),h.jsx(eo,{className:"studio-home__onboard-link",target:{tab:"firestore"},children:"open Firestore →"})]}),h.jsxs("section",{className:"studio-card studio-home__onboard","aria-label":"Bring your rules",children:[h.jsx("span",{className:"studio-home__tile-label",children:"Bring your rules"}),s?h.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."]}):h.jsxs(h.Fragment,{children:[h.jsx("span",{className:"studio-home__tile-desc",children:"Serve your repo's rules file and every denial becomes a debuggable event."}),h.jsx("code",{className:"studio-home__snippet",children:"pyric dev --rules firestore.rules"})]})]})]})}function gP(){const t=Xs(),e=Yl(),n=as(),r=t.status==="pending"||n.status==="pending",s=!r&&e.length===0&&(t.status!=="ready"||t.handles.listRootCollections().length===0);return h.jsxs("section",{className:"studio-surface studio-home","aria-label":"Home",children:[h.jsxs("div",{className:"studio-home__hero",children:[h.jsx("img",{className:"studio-home__hero-logo",src:"/__pyric/ui/pyric-logo.svg",alt:"","aria-hidden":"true"}),h.jsx("h1",{className:"studio-home__hero-title",children:"Firebase that runs in the browser"})]}),h.jsx(PA,{exposeFocus:I3}),h.jsx(dP,{}),h.jsx("div",{className:"studio-home__body",children:r?h.jsxs("section",{className:"studio-panel studio-home__feed studio-home__skeleton","aria-hidden":"true",children:[h.jsx("div",{className:"studio-home__skeleton-row"}),h.jsx("div",{className:"studio-home__skeleton-row"}),h.jsx("div",{className:"studio-home__skeleton-row"})]}):s?h.jsx(yP,{}):h.jsxs(h.Fragment,{children:[h.jsx(hP,{}),h.jsx(mP,{})]})})]})}function Pt(t){const e=t.split("/").filter(Boolean);return e.length===0?"/":`/${e.join("/")}`}function Bi(t){return Pt(t).split("/").filter(Boolean)}function Ey(t,e){return Pt([...Bi(t),...e.split("/").filter(Boolean)].join("/"))}function Kj(t,e){const n=Bi(t),r=Bi(e);if(r.length<n.length)return null;for(let o=0;o<n.length;o++)if(r[o]!==n[o])return null;const s=r.slice(n.length);return s.length===0?"/":`/${s.join("/")}`}function Yj(t){if(t==null)return null;if(typeof t!="object")return t;const e=t;let n=!1;const r={};for(const[s,o]of Object.entries(e)){const c=Yj(o);if(c===null){n=!0;continue}c!==o&&(n=!0),r[s]=c}return Object.keys(r).length===0?null:n?r:t}function bP(t){if(typeof t=="string")return JSON.stringify(t);if(t==null)return"null";if(typeof t=="object")try{return JSON.stringify(t)??"null"}catch{return"null"}return String(t)}function kg(t){return t===null||typeof t!="object"?!1:Object.keys(t).length>0}function Zj(t){return t===null||typeof t!="object"?[]:Object.entries(t).sort(([e],[n])=>e.localeCompare(n,void 0,{numeric:!0}))}function Wj(t,e){let n=t??null;for(const r of Bi(e)){if(n===null||typeof n!="object")return null;n=n[r]??null}return n}function vP(t){return t==null?"null":Array.isArray(t)?"array":typeof t}function Ay(t,e){if(Object.is(t,e))return!0;if(Array.isArray(t)||Array.isArray(e))return!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length?!1:t.every((c,d)=>Ay(c,e[d]));if(t===null||e===null||typeof t!="object"||typeof e!="object")return!1;const n=t,r=e,s=Object.keys(n),o=Object.keys(r);return s.length!==o.length?!1:s.every(c=>c in r&&Ay(n[c],r[c]))}function xP(t,e){const n=new Map,r=(s,o)=>{if(!kg(s)){n.set(o,["leaf",s??null]);return}const c=Zj(s);n.set(o,["parent",c.map(([d])=>d)]);for(const[d,f]of c)r(f,Ey(o,d))};return r(t,Pt(e)),n}function wP(t){let e=t.trim();if(e.length===0)return"/";const n=/^[a-z][a-z0-9+.-]*:\/\/[^/?#]+/i.exec(e);return n&&(e=e.slice(n[0].length)),e=e.replace(/[?#].*$/,""),Pt(e)}function SP(t){const e=Bi(t);return e.map((n,r)=>({label:n,path:`/${e.slice(0,r+1).join("/")}`}))}const _P=["string","number","boolean","json"];function M_(t){switch(typeof t){case"string":return"string";case"number":return"number";case"boolean":return"boolean";default:return"json"}}function EP(t,e){return e==="json"?JSON.stringify(t??null):t==null?"":String(t)}function AP(t){if(t.trim().length===0)return"Enter a key.";const e=t.match(/[.$#[\]/]/);return e?`Keys can't contain "${e[0]}".`:null}function jP(t,e){switch(t){case"string":return{ok:!0,value:e};case"number":{const n=e.trim();if(n.length===0)return{ok:!1,error:"Enter a number."};const r=Number(n);return Number.isNaN(r)?{ok:!1,error:`"${e}" is not a number.`}:{ok:!0,value:r}}case"boolean":{const n=e.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=e.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 Jj(t){return{path:Pt(t),status:"loading",value:null,error:null,expanded:{},pages:{}}}function Qj(t,e){const n=Kj(t.path,e);return n===null?null:Wj(t.value,n)}function kP(t,e){const n=Pt(e);return n===t.path||t.expanded[n]===!0}function CP(t,e,n){const r=Zj(Qj(t,e)),s=Math.min(r.length,t.pages[Pt(e)]??n);return{entries:r.slice(0,s),total:r.length,hiddenCount:r.length-s}}function L_(t,e){const n={};let r=!1;for(const[s,o]of Object.entries(t)){const c=Kj(e.path,s);c!==null&&kg(Wj(e.value,c))?n[s]=o:r=!0}return r?n:t}function Xj(t,e){switch(e.type){case"navigate":{const n=Pt(e.path);return n===t.path?t:Jj(n)}case"value":{if(Pt(e.path)!==t.path)return t;const n={...t,status:"live",value:Yj(e.value),error:null};return n.expanded=L_(t.expanded,n),n.pages=L_(t.pages,n),n}case"error":return Pt(e.path)!==t.path?t:{...t,status:"error",error:e.message};case"expand":{const n=Pt(e.path);return n===t.path||t.expanded[n]?t:{...t,expanded:{...t.expanded,[n]:!0}}}case"collapse":{const n=Pt(e.path);if(!t.expanded[n])return t;const r={...t.expanded};return delete r[n],{...t,expanded:r}}case"toggle":{const n=Pt(e.path);return Xj(t,{type:t.expanded[n]?"collapse":"expand",path:n})}case"show-more":{const n=Pt(e.path),r=t.pages[n]??e.pageSize;return{...t,pages:{...t.pages,[n]:r+e.pageSize}}}}}const NP=50;function OP(t,e,n={}){const r=n.pageSize??NP,s=Pt(e),[o,c]=A.useReducer(Xj,s,Jj),d=A.useMemo(()=>xP(o.value,o.path),[o.path,o.value]),f=Ag({scope:o.path,entries:d,equals:Ay,ready:o.status==="live"});o.path!==s&&c({type:"navigate",path:s}),A.useEffect(()=>{let k=!1;const R=t.subscribeValue(s,C=>{k||c({type:"value",path:s,value:C})},C=>{k||c({type:"error",path:s,message:C instanceof Error?C.message:String(C)})});return()=>{k=!0,R()}},[t,s]);const p=A.useCallback(k=>Qj(o,k),[o]),g=A.useCallback(k=>kP(o,k),[o]),b=A.useCallback(k=>CP(o,k,r),[o,r]),v=A.useCallback(k=>c({type:"toggle",path:k}),[]),x=A.useCallback(k=>c({type:"show-more",path:k,pageSize:r}),[r]),_=A.useCallback(k=>f.get(Pt(k)),[f]);return A.useMemo(()=>({state:o,pageSize:r,valueAt:p,isExpanded:g,childrenAt:b,toggle:v,showMore:x,updateAt:_}),[o,r,p,g,b,v,x,_])}function TP({path:t,onNavigate:e,rootLabel:n="/",inputPrefix:r,className:s}){const o=Pt(t),[c,d]=A.useState(!1),f=A.useRef(null);A.useEffect(()=>{var v;c&&((v=f.current)==null||v.select())},[c]);const p=v=>{var x;v.preventDefault(),e(wP(((x=f.current)==null?void 0:x.value)??"")),d(!1)},g=()=>d(!1),b=SP(o);return h.jsx("nav",{className:s,"data-pyric-ui":"rtdb-path-bar","data-rtdb-editing":c?"":void 0,"aria-label":"Database path",children:c?h.jsxs("form",{"data-rtdb-path-form":!0,onSubmit:p,children:[r?h.jsx("span",{"data-rtdb-path-prefix":!0,children:r}):null,h.jsx("input",{ref:f,"data-rtdb-path-input":!0,"aria-label":"Database path",autoFocus:!0,defaultValue:o,onBlur:g,onKeyDown:v=>{v.key==="Escape"&&g()},spellCheck:!1})]}):h.jsxs(h.Fragment,{children:[h.jsxs("ol",{"data-rtdb-crumb-list":!0,children:[h.jsx("li",{"data-rtdb-crumb-item":!0,children:h.jsx("button",{type:"button","data-rtdb-crumb":!0,"data-rtdb-crumb-root":!0,"data-pyric-current":b.length===0?"":void 0,"aria-current":b.length===0?"page":void 0,onClick:()=>e("/"),children:n})}),b.map((v,x)=>{const _=x===b.length-1;return h.jsxs("li",{"data-rtdb-crumb-item":!0,children:[h.jsx("span",{"aria-hidden":!0,"data-rtdb-crumb-separator":!0,children:"/"}),h.jsx("button",{type:"button","data-rtdb-crumb":!0,"data-pyric-current":_?"":void 0,"aria-current":_?"page":void 0,onClick:()=>e(v.path),children:v.label})]},v.path)})]}),h.jsx("button",{type:"button","data-rtdb-path-edit":!0,"aria-label":"Edit path",title:"Edit path",onClick:()=>d(!0),children:h.jsx("svg",{"aria-hidden":!0,viewBox:"0 0 16 16",width:"12",height:"12",fill:"currentColor",children:h.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 RP({tree:t,api:e,onNavigate:n,rootLabel:r="/",className:s}){const{state:o}=t,c=Bi(o.path),d=c.length===0?r:c[c.length-1];return h.jsx("div",{className:s,"data-pyric-ui":"rtdb-tree",children:o.status==="loading"?h.jsx("p",{"data-rtdb-loading":!0,children:"Loading…"}):o.status==="error"?h.jsx("p",{role:"alert","data-rtdb-error":!0,children:o.error}):h.jsx(ek,{tree:t,api:e,onNavigate:n,path:o.path,label:d,isViewRoot:!0})})}function ek({tree:t,api:e,onNavigate:n,path:r,label:s,isViewRoot:o}){const c=t.valueAt(r),d=kg(c),f=t.isExpanded(r),p=t.updateAt(r),[g,b]=A.useState(!1),[v,x]=A.useState(!1),[_,k]=A.useState(!1),[R,C]=A.useState(null),T=async(I,N)=>{try{await I(),C(null),N()}catch(M){C(M instanceof Error?M.message:String(M))}},U=()=>{b(!0),k(!1),d&&!f&&t.toggle(r)},q=d&&f?t.childrenAt(r):null;return h.jsxs("div",{"data-rtdb-node":!0,"data-rtdb-kind":d?"parent":"leaf","data-rtdb-view-root":o?"":void 0,"data-rtdb-expanded":d&&f?"":void 0,children:[h.jsxs("div",{"data-rtdb-row":!0,"data-pyric-update":p==null?void 0:p.kind,"data-pyric-update-cycle":p==null?void 0:p.cycle,children:[d&&!o?h.jsx("button",{type:"button","data-rtdb-caret":!0,"aria-expanded":f,"aria-label":f?"Collapse":"Expand",onClick:()=>t.toggle(r),children:h.jsx("svg",{"aria-hidden":!0,viewBox:"0 0 8 8",width:"8",height:"8",fill:"currentColor",children:h.jsx("path",{d:"M1 0l6 4-6 4z"})})}):h.jsx("span",{"aria-hidden":!0,"data-rtdb-caret-spacer":!0}),h.jsx("button",{type:"button","data-rtdb-key":!0,"aria-label":"Key name",onClick:()=>n==null?void 0:n(r),children:s}),d?null:h.jsxs(h.Fragment,{children:[h.jsx("span",{"aria-hidden":!0,"data-rtdb-sep":!0,children:":"}),h.jsx("button",{type:"button","data-rtdb-value":!0,"data-rtdb-type":vP(c),title:"Edit value",onClick:()=>{x(!0),k(!1)},children:bP(c)})]}),h.jsx("span",{"data-rtdb-actions":!0,children:_?h.jsxs("span",{"data-rtdb-confirm":!0,children:[h.jsxs("span",{"data-rtdb-confirm-label":!0,children:["Delete",d?" subtree":"","?"]}),h.jsx("button",{type:"button","data-rtdb-confirm-yes":!0,onClick:()=>void T(()=>e.remove(r),()=>k(!1)),children:"Delete"}),h.jsx("button",{type:"button","data-rtdb-confirm-no":!0,onClick:()=>k(!1),children:"Cancel"})]}):h.jsxs(h.Fragment,{children:[h.jsx("button",{type:"button","data-rtdb-action-add":!0,"aria-label":`Add child to ${U_(r)}`,title:"Add child",onClick:U,children:"+"}),h.jsx("button",{type:"button","data-rtdb-action-delete":!0,"aria-label":`Delete ${U_(r)}`,title:"Delete",onClick:()=>k(!0),children:"×"})]})})]}),R?h.jsx("p",{role:"alert","data-rtdb-error":!0,children:R}):null,v?h.jsx($_,{initialType:M_(c),initialText:EP(c,M_(c)),submitLabel:"Save",onCancel:()=>x(!1),onSubmit:I=>T(()=>e.set(r,I),()=>x(!1))}):null,g?h.jsx($_,{withKey:!0,initialType:"string",initialText:"",submitLabel:"Add",onCancel:()=>b(!1),onSubmit:(I,N)=>T(()=>e.set(Ey(r,N),I),()=>b(!1))}):null,q?h.jsxs("ul",{"data-rtdb-children":!0,children:[q.entries.map(([I])=>h.jsx("li",{children:h.jsx(ek,{tree:t,api:e,onNavigate:n,path:Ey(r,I),label:I})},I)),q.hiddenCount>0?h.jsx("li",{"data-rtdb-show-more-item":!0,children:h.jsxs("button",{type:"button","data-rtdb-show-more":!0,onClick:()=>t.showMore(r),children:["Show more (",q.hiddenCount," hidden)"]})}):null]}):null]})}function U_(t){const e=Bi(t);return e.length===0?"root":e[e.length-1]}function $_({withKey:t,initialType:e,initialText:n,submitLabel:r,onSubmit:s,onCancel:o}){const c=A.useRef(null),d=A.useRef(null),[f,p]=A.useState(e),[g,b]=A.useState(null),v=_=>{var C,T;_.preventDefault();const k=((C=c.current)==null?void 0:C.value)??"";if(t){const U=AP(k);if(U){b(U);return}}const R=jP(f,((T=d.current)==null?void 0:T.value)??"");if(!R.ok){b(R.error);return}b(null),s(R.value,t?k.trim():void 0)},x=_=>{_.key==="Escape"&&o()};return h.jsxs("form",{"data-rtdb-editor":!0,onSubmit:v,children:[t?h.jsx("input",{ref:c,"data-rtdb-editor-key":!0,"aria-label":"Child key",placeholder:"key",autoFocus:!0,onKeyDown:x,spellCheck:!1}):null,h.jsx("select",{"data-rtdb-editor-type":!0,"aria-label":"Value type",value:f,onChange:_=>p(_.currentTarget.value),onKeyDown:x,children:_P.map(_=>h.jsx("option",{value:_,children:_},_))}),f==="boolean"?h.jsxs("select",{ref:d,"data-rtdb-editor-value":!0,"aria-label":"Value",defaultValue:n.trim().toLowerCase()==="true"?"true":"false",onKeyDown:x,children:[h.jsx("option",{value:"true",children:"true"}),h.jsx("option",{value:"false",children:"false"})]}):h.jsx("input",{ref:d,"data-rtdb-editor-value":!0,"aria-label":"Value",placeholder:f==="json"?'{ "key": "value" }':"value",autoFocus:!t,defaultValue:n,onKeyDown:x,spellCheck:!1}),h.jsx("button",{type:"submit","data-rtdb-editor-save":!0,children:r}),h.jsx("button",{type:"button","data-rtdb-editor-cancel":!0,onClick:o,children:"Cancel"}),g?h.jsx("span",{role:"alert","data-rtdb-editor-error":!0,children:g}):null]})}function DP(){const t=dr(),e=t.status==="ready"?t.env.live:void 0;return h.jsxs("section",{className:"studio-surface grid gap-4","aria-labelledby":"rtdb-title",children:[h.jsxs("div",{className:"studio-surface__intro",children:[h.jsx("p",{className:"studio-surface__eyebrow",children:"RTDB"}),h.jsx("h1",{id:"rtdb-title",className:"studio-surface__title",children:"RTDB"}),h.jsx("p",{className:"studio-surface__copy",children:"Browse and edit RTDB data in the shared sandbox."})]}),e?h.jsx(MP,{live:e}):h.jsx(IP,{})]})}function IP(){return h.jsxs("div",{className:"rounded-md border border-dashed border-line bg-panel p-8 text-center",children:[h.jsx("span",{className:"rounded-full border border-line px-3 py-1 text-xs uppercase tracking-wide text-muted",children:"Shared worker pending"}),h.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 MP({live:t}){const[e,n]=A.useState("/"),r=jg(yg()),s=r?`${r}-sandbox`:"sandbox",o=A.useMemo(()=>({set:(d,f)=>t.setRtdbValue(d,f),remove:d=>t.deleteRtdbValue(d),subscribeValue:(d,f,p)=>t.subscribeRtdbValue(d,f,p)}),[t]),c=OP(o,e);return h.jsxs("div",{className:"rtdb",children:[h.jsx(TP,{className:"rtdb__pathbar",path:e,onNavigate:n,rootLabel:s,inputPrefix:s}),h.jsx(RP,{className:"rtdb__tree",tree:c,api:o,onNavigate:n,rootLabel:s})]})}function LP(t){if(t===null)return null;const e={collections:0,users:0,objects:0,rtdbKeys:0};for(const n of t)n.kind==="collection"?e.collections++:n.kind==="user"?e.users++:n.kind==="object"?e.objects++:n.kind==="rtdb-key"&&e.rtdbKeys++;return e}function ku(t,e,n=`${e}s`){return`${t} ${t===1?e:n}`}function UP(t){if(t===null)return"measuring…";const e=[];return t.collections&&e.push(ku(t.collections,"collection")),t.users&&e.push(ku(t.users,"user")),t.objects&&e.push(ku(t.objects,"file")),t.rtdbKeys&&e.push(ku(t.rtdbKeys,"RTDB key")),e.length?e.join(" · "):"empty — no data yet"}function Jd(){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 $P(){return h.jsxs("svg",{...Jd(),children:[h.jsx("path",{d:"M12 4v10"}),h.jsx("path",{d:"M8 10l4 4 4-4"}),h.jsx("path",{d:"M4 19h16"})]})}function BP(){return h.jsxs("svg",{...Jd(),children:[h.jsx("path",{d:"M12 14V4"}),h.jsx("path",{d:"M8 8l4-4 4 4"}),h.jsx("path",{d:"M4 19h16"})]})}function FP(){return h.jsxs("svg",{...Jd(),children:[h.jsx("circle",{cx:"7",cy:"6",r:"2.4"}),h.jsx("circle",{cx:"7",cy:"18",r:"2.4"}),h.jsx("circle",{cx:"17",cy:"8",r:"2.4"}),h.jsx("path",{d:"M7 8.4v7.2"}),h.jsx("path",{d:"M17 10.4c0 3-4 3.6-7 4.4"})]})}function PP(){return h.jsxs("svg",{...Jd(),children:[h.jsx("path",{d:"M4 5v5h5"}),h.jsx("path",{d:"M4.6 10a8 8 0 1 0 1.7-5.3"})]})}function Cu({glyph:t,name:e,caption:n,disabled:r,danger:s,onClick:o}){return h.jsxs("button",{type:"button",className:"studio-sandbox__action","data-danger":s?"true":void 0,disabled:r,onClick:o,children:[h.jsxs("span",{className:"studio-sandbox__action-top",children:[t,h.jsx("span",{className:"studio-sandbox__action-name",children:e})]}),h.jsx("span",{className:"studio-sandbox__action-caption",children:n})]})}function qP(){const t=B4(),e=P4(),n=q4(),r=z4(),s=Vd(),o=A.useRef(null),c=jg(yg()),[d,f]=A.useState(!1),[p,g]=A.useState(!1),[b,v]=A.useState(!1),[x,_]=A.useState(!1),[k,R]=A.useState(""),C=FA(),{ensure:T}=C;A.useEffect(()=>T(),[T]);const U=LP(C.entries),q=UP(U),I=s.status==="ready"?s.payload.persist?"persisted to disk":"ephemeral":"in-page · resets on reload",N=async()=>{const w=await e();if(!w||typeof document>"u")return;const E=URL.createObjectURL(new Blob([w],{type:"application/json"})),O=document.createElement("a");O.href=E,O.download=`pyric-sandbox-${c||"export"}.json`,O.click(),URL.revokeObjectURL(E)},M=async w=>{var O;const E=(O=w.target.files)==null?void 0:O[0];if(w.target.value="",!!E&&!(typeof window<"u"&&!window.confirm("Import replaces all data in this sandbox. This cannot be undone. Continue?"))){g(!0);try{await n(await E.text())}finally{g(!1)}}},L=async()=>{v(!1),f(!0);try{await t()}finally{f(!1)}},H=async()=>{const w=k.trim();w&&(await r.save(w),R(""),_(!1))},P=async w=>{typeof window<"u"&&!window.confirm(`Switch to branch "${w}"? This replaces the current sandbox state.`)||await r.switchTo(w)},F=async w=>{typeof window<"u"&&!window.confirm(`Delete branch "${w}"?`)||await r.remove(w)};return h.jsxs("section",{className:"studio-surface studio-settings","aria-labelledby":"settings-title",children:[h.jsxs("div",{className:"studio-surface__intro",children:[h.jsx("p",{className:"studio-surface__eyebrow",children:"Settings"}),h.jsx("h1",{id:"settings-title",className:"studio-surface__title",children:"Configuration and maintenance."}),h.jsx("p",{className:"studio-surface__copy",children:"Global controls live here so service surfaces can stay focused on their primary work."})]}),h.jsx("div",{className:"studio-settings__grid",children:h.jsxs("section",{className:"studio-panel studio-settings__panel","aria-labelledby":"settings-sandbox-title",children:[h.jsx("h2",{id:"settings-sandbox-title",className:"studio-panel__title",children:"Sandbox"}),h.jsxs("div",{className:"studio-sandbox__live","aria-label":"Sandbox contents",children:[h.jsx("span",{className:"studio-sandbox__instance mono",children:c||"local"}),h.jsx("span",{className:"studio-sandbox__inventory",children:q}),h.jsx("span",{className:"studio-sandbox__persist",children:I})]}),h.jsxs("div",{className:"studio-sandbox__actions",children:[h.jsx(Cu,{glyph:h.jsx($P,{}),name:"Export",caption:"Downloads all of this as one file.",onClick:()=>void N()}),h.jsx(Cu,{glyph:h.jsx(BP,{}),name:p?"Importing…":"Import",caption:"A chosen file replaces everything here.",disabled:p,onClick:()=>{var w;return(w=o.current)==null?void 0:w.click()}}),h.jsx(Cu,{glyph:h.jsx(FP,{}),name:"Save branch",caption:"Keeps a copy you can return to.",onClick:()=>_(w=>!w)}),h.jsx(Cu,{glyph:h.jsx(PP,{}),name:d?"Resetting…":"Reset session",caption:"Everything returns to the seeded start.",disabled:d,danger:!0,onClick:()=>v(!0)})]}),h.jsx("input",{ref:o,type:"file",accept:"application/json,.json",className:"studio-settings__file",onChange:M}),x?h.jsxs("form",{className:"studio-sandbox__name-row",onSubmit:w=>{w.preventDefault(),H()},children:[h.jsx("input",{className:"studio-sandbox__name-input",type:"text",value:k,placeholder:"branch name","aria-label":"Branch name",autoFocus:!0,onChange:w=>R(w.target.value),onKeyDown:w=>{w.key==="Escape"&&(_(!1),R(""))}}),h.jsx("button",{type:"submit",className:"studio-button",disabled:!k.trim(),children:"Save"}),h.jsx("button",{type:"button",className:"studio-button",onClick:()=>{_(!1),R("")},children:"Cancel"})]}):null,b?h.jsxs("div",{className:"studio-sandbox__confirm",role:"alert",children:[h.jsx("span",{className:"studio-sandbox__confirm-copy",children:U&&q!=="empty — no data yet"?`This erases ${q}.`:"This erases everything in this sandbox."}),h.jsxs("span",{className:"studio-sandbox__confirm-actions",children:[h.jsx("button",{type:"button",className:"studio-button studio-button--danger",onClick:()=>void L(),children:"Erase and reseed"}),h.jsx("button",{type:"button",className:"studio-button",onClick:()=>v(!1),children:"Keep"})]})]}):null,r.branches.length>0?h.jsx("div",{className:"studio-settings__branches",children:r.branches.map(w=>h.jsxs("div",{className:"studio-settings__branch",children:[h.jsx("span",{className:"mono",children:w}),h.jsxs("span",{className:"studio-settings__branch-actions",children:[h.jsx("button",{type:"button",className:"studio-button",onClick:()=>void P(w),children:"Switch"}),h.jsx("button",{type:"button",className:"studio-button",onClick:()=>void F(w),children:"Delete"})]})]},w))}):h.jsx("p",{className:"studio-sandbox__branches-empty",children:"No branches yet — Save branch keeps this exact state to come back to."})]})})]})}function Nu(t){return t===null?"absent":t===void 0?"unknown":typeof t=="string"?t:typeof t=="number"||typeof t=="boolean"?String(t):JSON.stringify(t)}function zP(t){const e=t.stateDiff;if(!e)return"No state evidence";if(!e.changed)return t.mutation.output!==void 0?"Read result captured":"No state change";if(e.before&&e.after&&typeof e.before=="object"&&typeof e.after=="object"&&!Array.isArray(e.before)&&!Array.isArray(e.after)){const n=e.before,r=e.after,o=[...new Set([...Object.keys(n),...Object.keys(r)])].filter(c=>JSON.stringify(n[c])!==JSON.stringify(r[c]));if(o.length>0&&o.length<=3)return o.map(c=>`${c}: ${Nu(n[c])} -> ${Nu(r[c])}`).join(", ")}return`${Nu(e.before)} -> ${Nu(e.after)}`}function VP(t){return t.results.map(e=>({id:e.probeId,service:e.control.operation.service,operation:`${e.mutation.operation.method} ${e.mutation.operation.path}`,actor:e.actorEvidence.uid??(e.actorEvidence.acquisition==="anonymous-request"?"anonymous":e.actorEvidence.actorId),expected:e.invariant.expected,observed:e.mutation.decision,classification:e.classification,impact:zP(e),supported:e.qualification.supported}))}function HP(t){const e=t.mutation.events.find(c=>c.result==="allow"||c.result==="deny"||c.result==="unsupported");if(!e)return null;const n=e.result,r={id:e.id??`${t.probeId}-decision`,at:e.at??0,result:n,method:e.method??e.op??t.mutation.operation.method,service:e.service??t.mutation.operation.service,path:e.path??t.mutation.operation.path,auth:e.auth??null,reasons:e.reasons??[],origin:e.origin??"user",unsupported:n==="unsupported"};e.matchedRule&&(r.matchedRule=e.matchedRule),e.evaluatedRule&&(r.evaluatedRule=e.evaluatedRule),e.rules&&(r.rules=e.rules),e.resourceBefore&&(r.resourceBefore=e.resourceBefore);const s=e.request,o=(s==null?void 0:s.resourceData)??(s==null?void 0:s.data);return o!==void 0&&(r.resourceData=o),r}const GP="pyric:assurance-campaign",KP="pyric-assurance-v1",jy=new Set;let B_=!1,F_;function P_(t){for(const e of jy)e(t)}function q_(t){return!!t&&typeof t=="object"&&t.schema==="pyric.assurance.visualization.v1"&&typeof t.campaignId=="string"}function YP(){if(!(B_||typeof document>"u")){B_=!0,globalThis.addEventListener(GP,t=>{const e=t.detail;q_(e)&&P_(e)});try{F_=new BroadcastChannel(KP),F_.onmessage=t=>{q_(t.data)&&P_(t.data)}}catch{}}}function ZP(t){return YP(),jy.add(t),()=>jy.delete(t)}function im(t){return{campaignId:"collaboration-local-v1",probeId:t.id,targetHash:"fnv1a32-7f4c911a",actorEvidence:{actorId:"member-b",acquisition:"password",reachability:"reachable",uid:"mallory"},invariant:{id:`${t.id}-invariant`,service:t.service,statement:t.statement,expected:"DENY",source:"declared",confidence:"authoritative"},mutationSpec:{dimension:t.service==="firestore"?"payload":"path",description:t.description,operation:t.mutation},control:{operation:t.control,decision:"ALLOW",events:[]},mutation:{operation:t.mutation,decision:"ALLOW",events:t.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:t.before},matchedRule:{ruleIndex:0,operations:["update"]}}]:[]},stateDiff:{changed:!0,before:t.before,after:t.after},qualification:{engine:"pyric-local-sandboxes",supported:!0,requirements:[{id:`${t.service}.local-supported-subset`,supported:!0,reason:"This probe stays within the supported local evaluator subset."}]},classification:"local-counterexample"}}const WP=[im({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"}}),im({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"}),im({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"}}})],gq=WP.map(t=>({...t,campaignId:"collaboration-local-v1-fixed",targetHash:"fnv1a32-a9f18f23",mutation:{...t.mutation,decision:"DENY",events:[]},stateDiff:void 0,classification:"no-counterexample"}));const ky="pyric:assurance:campaigns",tk="pyric:assurance:campaign:";function JP(t){return!!t&&typeof t=="object"&&t.schema==="pyric.assurance.visualization.v1"&&typeof t.campaignId=="string"}function QP(){if(typeof sessionStorage>"u")return[];try{const t=JSON.parse(sessionStorage.getItem(ky)??"[]");if(!Array.isArray(t))return[];const e=t.map(n=>sessionStorage.getItem(`${tk}${String(n)}`)).filter(n=>!!n).map(n=>JSON.parse(n)).filter(JP);return e.length,e}catch{return[]}}function XP(t){if(!(typeof sessionStorage>"u"))try{const e=JSON.parse(sessionStorage.getItem(ky)??"[]"),n=Array.isArray(e)?e.map(String):[];n.includes(t.campaignId)||n.push(t.campaignId),sessionStorage.setItem(ky,JSON.stringify(n)),sessionStorage.setItem(`${tk}${t.campaignId}`,JSON.stringify(t))}catch{}}function eq(t,e){const n=t.findIndex(s=>s.campaignId===e.campaignId);if(n===-1)return[...t,e];const r=[...t];return r[n]=e,r}function tq(){const[t,e]=A.useState(QP);return A.useEffect(()=>{const r=ZP(s=>{XP(s),e(o=>eq(o,s))});return()=>{r()}},[]),t}function nq(t,e){return t!==e?"assurance-verdict--mismatch":e==="ALLOW"?"assurance-verdict--allow":"assurance-verdict--deny"}function rq(t){return t.replaceAll("-"," ")}function z_({value:t}){return h.jsx("pre",{className:"assurance-evidence__json",children:JSON.stringify(t,null,2)})}function sq(){return h.jsxs("section",{className:"assurance-empty","aria-labelledby":"assurance-empty-title",children:[h.jsx("p",{className:"assurance-surface__eyebrow",children:"Local authorization assurance"}),h.jsx("h1",{id:"assurance-empty-title",children:"No campaign in this Studio session"}),h.jsx("p",{children:"Campaigns appear here as the local assurance tools map actors, run controls, and test explicit security invariants."}),h.jsx("span",{className:"assurance-local-state",children:"Pyric sandboxes only | network off"})]})}function V_({attachment:t}){return t?h.jsxs("div",{className:"assurance-attachment","aria-label":"Attached sandbox inventory",children:[h.jsxs("span",{children:[h.jsx("strong",{children:t.source.origin}),"read-only clone"]}),h.jsxs("span",{children:[h.jsx("strong",{children:t.inventory.firestoreDocuments}),"Firestore docs"]}),h.jsxs("span",{children:[h.jsx("strong",{children:t.inventory.authUsers}),"Auth users"]}),h.jsxs("span",{children:[h.jsx("strong",{children:t.inventory.rtdbPresent?"present":"empty"}),"RTDB"]})]}):null}function iq({campaigns:t}){var U,q,I,N,M;const e=tq(),n=t??e,r=Nr().query,[s,o]=A.useState(r.campaign??((U=n.find(L=>L.report))==null?void 0:U.campaignId)??((q=n[0])==null?void 0:q.campaignId)??""),c=n.find(L=>L.campaignId===s)??n[0],d=A.useMemo(()=>c!=null&&c.report?VP(c.report):[],[c]),[f,p]=A.useState(r.probe??((I=d[0])==null?void 0:I.id)??"");if(A.useEffect(()=>{!s&&n[0]&&o(n[0].campaignId)},[s,n]),A.useEffect(()=>{var L;d.some(H=>H.id===f)||p(((L=d[0])==null?void 0:L.id)??"")},[d,f]),!c)return h.jsx(sq,{});const g=(N=c.context)==null?void 0:N.attachment,b=c.report;if(!b)return h.jsxs("section",{className:"assurance-empty","aria-labelledby":"assurance-mapped-title",children:[h.jsx("p",{className:"assurance-surface__eyebrow",children:c.campaignId}),h.jsx("h1",{id:"assurance-mapped-title",children:"Campaign mapped, awaiting its first run"}),h.jsxs("p",{children:[c.observations.length," known-good operation(s) and"," ",c.probes.length," probe(s) are available."]}),h.jsx(V_,{attachment:g}),g!=null&&g.coverageGaps.length?h.jsx("ul",{className:"assurance-coverage-gaps","aria-label":"Attachment coverage gaps",children:g.coverageGaps.map(L=>h.jsxs("li",{children:[h.jsx("code",{children:L.service}),L.reason]},L.code))}):null,h.jsx("span",{className:"assurance-local-state",children:"Pyric sandboxes only | network off"})]});const v=d.find(L=>L.id===f)??d[0],x=b.results.find(L=>L.probeId===(v==null?void 0:v.id)),_=x?HP(x):null,k=(M=c.verifications)==null?void 0:M.at(-1),R=k!==void 0&&k.summary.controlsPassed===k.summary.probes&&k.summary.noCounterexamples===k.summary.probes&&k.summary.localCounterexamples===0&&k.summary.engineGaps===0&&k.summary.invalidProbes===0;function C(L){var F,w;o(L);const H=n.find(E=>E.campaignId===L),P=((w=(F=H==null?void 0:H.report)==null?void 0:F.results[0])==null?void 0:w.probeId)??"";p(P),pd({tab:"assurance",query:{campaign:L,probe:P||void 0}})}function T(L){p(L.id),pd({tab:"assurance",query:{campaign:c.campaignId,probe:L.id}})}return h.jsxs("section",{className:"assurance-surface","aria-labelledby":"assurance-title",children:[h.jsxs("header",{className:"assurance-surface__header",children:[h.jsxs("div",{children:[h.jsx("p",{className:"assurance-surface__eyebrow",children:"Local authorization assurance"}),h.jsx("h1",{id:"assurance-title",children:c.campaignId})]}),h.jsxs("div",{className:"assurance-surface__controls",children:[n.length>1?h.jsxs("label",{children:[h.jsx("span",{children:"Campaign"}),h.jsx("select",{value:c.campaignId,onChange:L=>C(L.target.value),children:n.map(L=>h.jsx("option",{value:L.campaignId,children:L.campaignId},L.campaignId))})]}):null,h.jsx("span",{className:"assurance-local-state",children:"Pyric sandboxes only | network off"})]})]}),h.jsx(V_,{attachment:g}),h.jsxs("div",{className:"assurance-summary","aria-label":"Campaign summary",children:[h.jsxs("div",{children:[h.jsx("span",{children:"Controls"}),h.jsxs("strong",{children:[b.summary.controlsPassed,"/",b.summary.probes]})]}),h.jsxs("div",{children:[h.jsx("span",{children:"Counterexamples"}),h.jsx("strong",{children:b.summary.localCounterexamples})]}),h.jsxs("div",{children:[h.jsx("span",{children:"Candidate signals"}),h.jsx("strong",{children:b.summary.candidateSignals})]}),h.jsxs("div",{children:[h.jsx("span",{children:"Engine gaps"}),h.jsx("strong",{children:b.summary.engineGaps})]}),h.jsxs("div",{children:[h.jsx("span",{children:"Coverage gaps"}),h.jsx("strong",{children:(g==null?void 0:g.coverageGaps.length)??0})]})]}),k?h.jsxs("div",{className:`assurance-verification-band assurance-verification-band--${R?"passed":"failed"}`,role:"status",children:[h.jsx("strong",{children:R?"Candidate rules verified":"Candidate rules need review"}),h.jsxs("span",{children:[k.summary.controlsPassed,"/",k.summary.probes," ","controls preserved"," | ",k.summary.noCounterexamples,"/",k.summary.probes," negative cases denied"]}),h.jsx("code",{children:k.campaignId})]}):null,g!=null&&g.coverageGaps.length?h.jsxs("div",{className:"assurance-coverage-band",children:[h.jsxs("strong",{children:[g.coverageGaps.length," attachment gap(s)"]}),h.jsx("span",{children:g.coverageGaps.map(L=>`${L.service}: ${L.reason}`).join(" ")})]}):null,h.jsxs("div",{className:"assurance-workspace",children:[h.jsxs("section",{className:"assurance-matrix","aria-labelledby":"assurance-matrix-title",children:[h.jsxs("div",{className:"assurance-section-heading",children:[h.jsx("h2",{id:"assurance-matrix-title",children:"Expected and observed access"}),h.jsx("span",{children:b.targetHash})]}),h.jsxs("div",{className:"assurance-table",role:"table",children:[h.jsxs("div",{className:"assurance-table__header",role:"row",children:[h.jsx("span",{role:"columnheader",children:"Operation"}),h.jsx("span",{role:"columnheader",children:"Actor"}),h.jsx("span",{role:"columnheader",children:"Expected"}),h.jsx("span",{role:"columnheader",children:"Observed"}),h.jsx("span",{role:"columnheader",children:"Impact"})]}),d.map(L=>h.jsxs("button",{type:"button",className:"assurance-table__row","aria-pressed":L.id===(v==null?void 0:v.id),onClick:()=>T(L),role:"row",children:[h.jsxs("span",{role:"cell",children:[h.jsx("small",{children:L.service}),L.operation]}),h.jsx("span",{role:"cell",children:L.actor}),h.jsx("span",{role:"cell",className:`assurance-verdict ${L.expected==="ALLOW"?"assurance-verdict--allow":"assurance-verdict--deny"}`,children:L.expected}),h.jsx("span",{role:"cell",className:`assurance-verdict ${nq(L.expected,L.observed)}`,children:L.observed}),h.jsx("span",{role:"cell",children:L.impact})]},L.id))]})]}),x?h.jsxs("aside",{className:"assurance-inspector","aria-labelledby":"assurance-inspector-title",children:[h.jsxs("div",{className:"assurance-section-heading",children:[h.jsxs("div",{children:[h.jsx("span",{className:`assurance-classification assurance-classification--${x.classification}`,children:rq(x.classification)}),h.jsx("h2",{id:"assurance-inspector-title",children:x.probeId})]}),h.jsx("span",{children:x.actorEvidence.reachability})]}),h.jsxs("dl",{className:"assurance-facts",children:[h.jsxs("div",{children:[h.jsx("dt",{children:"Invariant"}),h.jsx("dd",{children:x.invariant.statement})]}),h.jsxs("div",{children:[h.jsx("dt",{children:"Mutation"}),h.jsx("dd",{children:x.mutationSpec.description})]}),h.jsxs("div",{children:[h.jsx("dt",{children:"Actor"}),h.jsxs("dd",{children:[x.actorEvidence.uid??x.actorEvidence.actorId," ","via ",x.actorEvidence.acquisition]})]}),h.jsxs("div",{children:[h.jsx("dt",{children:"Fidelity"}),h.jsx("dd",{children:x.qualification.supported?"Supported for this probe":"Engine gap"})]})]}),x.qualification.requirements.some(L=>!L.supported)?h.jsx("ul",{className:"assurance-gaps",children:x.qualification.requirements.filter(L=>!L.supported).map(L=>h.jsxs("li",{children:[h.jsx("code",{children:L.id}),L.reason]},L.id))}):null,x.stateDiff?h.jsxs("section",{className:"assurance-evidence","aria-labelledby":"assurance-state-title",children:[h.jsx("h3",{id:"assurance-state-title",children:"State evidence"}),h.jsxs("div",{className:"assurance-evidence__diff",children:[h.jsxs("div",{children:[h.jsx("span",{children:"Before"}),h.jsx(z_,{value:x.stateDiff.before})]}),h.jsxs("div",{children:[h.jsx("span",{children:"After"}),h.jsx(z_,{value:x.stateDiff.after})]})]})]}):null,_?h.jsxs("section",{className:"assurance-rule-decision","aria-labelledby":"assurance-rule-title",children:[h.jsx("h3",{id:"assurance-rule-title",children:"Rule decision"}),h.jsx(Pj,{denial:_})]}):h.jsx("p",{className:"assurance-no-decision",children:"This service recorded operation and state evidence but no canonical rule-decision event."})]}):null]})]})}function nk(){const t="/__pyric/ui/";return`${t.endsWith("/")?t:`${t}/`}docs`}function aq(){const[t,e]=A.useState(!1);return A.useEffect(()=>{let n=!0;return fetch(`${nk()}/index.json`,{method:"HEAD"}).then(r=>{const s=r.headers.get("content-type")??"";n&&r.ok&&s.includes("json")&&e(!0)}).catch(()=>{}),()=>{n=!1}},[]),t}function oq({id:t}){const e=F3(t),n=as(),r=[`route #${e.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"),h.jsxs("section",{className:"studio__placeholder","aria-labelledby":`route-${e.id}`,children:[h.jsx("p",{className:"studio__placeholder-eyebrow",children:"Surface"}),h.jsx("h2",{id:`route-${e.id}`,className:"studio__placeholder-title",children:e.label}),h.jsx("p",{className:"studio__placeholder-blurb",children:e.description}),h.jsx("div",{className:"studio__placeholder-meta",children:r.map(s=>h.jsx("span",{children:s},s))})]})}function lq({id:t}){switch(t){case"home":return h.jsx(gP,{});case"firestore":return h.jsx(eF,{});case"auth":return h.jsx(oF,{});case"storage":return h.jsx(tF,{});case"rtdb":return h.jsx(DP,{});case"traffic":return h.jsx(sP,{});case"assurance":return h.jsx(iq,{});case"settings":return h.jsx(qP,{});default:return h.jsx(oq,{id:t})}}function cq(){const[t,e]=D3(B3,"home"),n=d=>e(d),[r,s]=A.useState(!1),o=aq(),c=t==="home";return A.useEffect(()=>{const d=f=>{if(L3(f)){if(r){f.preventDefault(),s(!1);return}if(c){M3()&&f.preventDefault();return}f.preventDefault(),s(!0)}};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[c,r]),A.useEffect(()=>{c&&s(!1)},[c]),A.useEffect(()=>{var d;(d=document.querySelector('.studio__nav [aria-current="page"]'))==null||d.scrollIntoView({block:"nearest",inline:"center"})},[t]),h.jsxs("div",{className:"studio","data-surface":t,children:[h.jsx("header",{className:"studio__bar",children:h.jsxs("div",{className:"studio__bar-inner",children:[h.jsx("span",{className:"studio__brand","aria-label":"Pyric Studio",children:"Pyric"}),h.jsxs("nav",{className:"studio__nav","aria-label":"Studio tabs",children:[Ui.map(d=>h.jsx("button",{type:"button",className:"studio__nav-tab","aria-current":d.id===t?"page":void 0,onClick:()=>n(d.id),children:d.label},d.id)),o?h.jsx("a",{className:"studio__nav-tab",href:nk(),children:"Docs"}):null]}),h.jsx(u6,{})]})}),h.jsx("main",{className:"studio__content","data-surface":t,children:h.jsx("div",{className:"studio__surface-slot","data-active":"true",children:h.jsx(lq,{id:t})})}),r?h.jsx(J4,{onClose:()=>s(!1)}):null]})}function uq(){return h.jsx(C3,{children:h.jsx(PN,{children:h.jsx(_3,{mode:"local",children:h.jsx(cq,{})})})})}const rk=document.getElementById("root");if(!rk)throw new Error("Pyric Studio: #root element not found");$N.createRoot(rk).render(h.jsx(A.StrictMode,{children:h.jsx(uq,{})}));export{Cr as G,Mn as T,mq as a,Kn as b,yq as c,Yn as d,f$ as e,A as f,h as j,Ml as r,Rl as s,Q$ as u};
|