@pyric/cli 0.1.0-alpha.11 → 0.1.0-alpha.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/serve.js +4 -4
- 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 +2 -2
- package/dist/conformance/.generated/can-i-use.js.map +1 -1
- package/dist/serve/bundler.d.ts +13 -8
- package/dist/serve/bundler.d.ts.map +1 -1
- package/dist/serve/bundler.js +31 -36
- package/dist/serve/bundler.js.map +1 -1
- package/dist/serve/docs-ui/docs/_rhythm/index.html +1 -1
- package/dist/serve/docs-ui/docs/agent/set-up-your-agent/index.html +1 -1
- package/dist/serve/docs-ui/docs/agent/watch-and-review/index.html +1 -1
- package/dist/serve/docs-ui/docs/agent/work-with-an-agent/index.html +1 -1
- package/dist/serve/docs-ui/docs/ai-compat/index.html +1 -1
- package/dist/serve/docs-ui/docs/api-reference/index.html +2 -2
- package/dist/serve/docs-ui/docs/api-reference.md +1 -1
- package/dist/serve/docs-ui/docs/app-compat/index.html +1 -1
- package/dist/serve/docs-ui/docs/auth-compat/index.html +1 -1
- package/dist/serve/docs-ui/docs/build/ai-logic/index.html +44 -22
- package/dist/serve/docs-ui/docs/build/ai-logic.md +69 -21
- package/dist/serve/docs-ui/docs/build/authentication/index.html +1 -1
- package/dist/serve/docs-ui/docs/build/cloud-firestore/index.html +1 -1
- package/dist/serve/docs-ui/docs/build/cloud-messaging/index.html +1 -1
- package/dist/serve/docs-ui/docs/build/cloud-storage/index.html +1 -1
- package/dist/serve/docs-ui/docs/build/realtime-database/index.html +1 -1
- package/dist/serve/docs-ui/docs/conformance-scores/index.html +1 -1
- package/dist/serve/docs-ui/docs/create-pyric-reference-api/index.html +1 -1
- package/dist/serve/docs-ui/docs/database-compat/index.html +1 -1
- package/dist/serve/docs-ui/docs/firestore-compat/index.html +1 -1
- package/dist/serve/docs-ui/docs/functions-rtdb-compat/index.html +1 -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/how-the-swap-works.md +2 -0
- package/dist/serve/docs-ui/docs/get-started/start-building/index.html +3 -2
- package/dist/serve/docs-ui/docs/get-started/start-building.md +3 -1
- package/dist/serve/docs-ui/docs/index.json +349 -29
- package/dist/serve/docs-ui/docs/messaging-compat/index.html +1 -1
- package/dist/serve/docs-ui/docs/observe/resolve-runtime-status/index.html +28 -0
- package/dist/serve/docs-ui/docs/observe/resolve-runtime-status.md +47 -0
- package/dist/serve/docs-ui/docs/observe/see-whats-happening/index.html +1 -1
- package/dist/serve/docs-ui/docs/observe/shape-your-data/index.html +1 -1
- package/dist/serve/docs-ui/docs/overview/index.html +1 -1
- package/dist/serve/docs-ui/docs/pyric-admin-app-reference-api/index.html +1 -1
- package/dist/serve/docs-ui/docs/pyric-admin-auth-reference-api/index.html +1 -1
- package/dist/serve/docs-ui/docs/pyric-admin-database-reference-api/index.html +1 -1
- package/dist/serve/docs-ui/docs/pyric-admin-firestore-reference-api/index.html +1 -1
- package/dist/serve/docs-ui/docs/pyric-admin-messaging-reference-api/index.html +916 -0
- package/dist/serve/docs-ui/docs/pyric-admin-messaging-reference-api.md +706 -0
- package/dist/serve/docs-ui/docs/pyric-admin-storage-reference-api/index.html +1 -1
- package/dist/serve/docs-ui/docs/pyric-ai-reference-api/index.html +1 -1
- package/dist/serve/docs-ui/docs/pyric-ai-scripting-reference-api/index.html +1 -1
- package/dist/serve/docs-ui/docs/pyric-app-reference-api/index.html +1 -1
- package/dist/serve/docs-ui/docs/pyric-auth-reference-api/index.html +1 -1
- package/dist/serve/docs-ui/docs/pyric-cli-assurance-browser-reference-api/index.html +1 -1
- package/dist/serve/docs-ui/docs/pyric-cli-assurance-reference-api/index.html +1 -1
- package/dist/serve/docs-ui/docs/pyric-cli-bridge-client-reference-api/index.html +1 -1
- package/dist/serve/docs-ui/docs/pyric-cli-bridge-reference-api/index.html +1 -1
- package/dist/serve/docs-ui/docs/pyric-cli-conformance-browser-reference-api/index.html +1 -1
- package/dist/serve/docs-ui/docs/pyric-cli-conformance-docs-reference-api/index.html +1 -1
- package/dist/serve/docs-ui/docs/pyric-cli-conformance-reference-api/index.html +1 -1
- package/dist/serve/docs-ui/docs/pyric-cli-credentials-node-reference-api/index.html +1 -1
- package/dist/serve/docs-ui/docs/pyric-cli-discover-reference-api/index.html +1 -1
- package/dist/serve/docs-ui/docs/pyric-cli-register-reference-api/index.html +1 -1
- package/dist/serve/docs-ui/docs/pyric-cli-remote-reference-api/index.html +1 -1
- package/dist/serve/docs-ui/docs/pyric-cli-serve-worker-reference-api/index.html +168 -76
- package/dist/serve/docs-ui/docs/pyric-cli-serve-worker-reference-api.md +156 -73
- package/dist/serve/docs-ui/docs/pyric-cli-verify-reference-api/index.html +1 -1
- package/dist/serve/docs-ui/docs/pyric-cli-vite-reference-api/index.html +11 -8
- package/dist/serve/docs-ui/docs/pyric-cli-vite-reference-api.md +17 -4
- package/dist/serve/docs-ui/docs/pyric-database-reference-api/index.html +1 -1
- package/dist/serve/docs-ui/docs/pyric-firestore-reference-api/index.html +1 -1
- package/dist/serve/docs-ui/docs/pyric-messaging-reference-api/index.html +1 -1
- package/dist/serve/docs-ui/docs/pyric-messaging-sw-reference-api/index.html +1 -1
- package/dist/serve/docs-ui/docs/pyric-rules-reference-api/index.html +1 -1
- package/dist/serve/docs-ui/docs/pyric-sandbox-database-reference-api/index.html +1 -1
- package/dist/serve/docs-ui/docs/pyric-sandbox-firestore-reference-api/index.html +1 -1
- package/dist/serve/docs-ui/docs/pyric-sandbox-reference-api/index.html +37 -14
- package/dist/serve/docs-ui/docs/pyric-sandbox-reference-api.md +28 -8
- package/dist/serve/docs-ui/docs/pyric-storage-reference-api/index.html +1 -1
- package/dist/serve/docs-ui/docs/pyric-ui-agents-reference-api/index.html +1 -1
- package/dist/serve/docs-ui/docs/pyric-ui-auth-hooks-reference-api/index.html +1 -1
- package/dist/serve/docs-ui/docs/pyric-ui-auth-reference-api/index.html +1 -1
- package/dist/serve/docs-ui/docs/pyric-ui-events-hooks-reference-api/index.html +1 -1
- package/dist/serve/docs-ui/docs/pyric-ui-events-reference-api/index.html +1 -1
- package/dist/serve/docs-ui/docs/pyric-ui-firestore-hooks-reference-api/index.html +1 -1
- package/dist/serve/docs-ui/docs/pyric-ui-firestore-reference-api/index.html +1 -1
- package/dist/serve/docs-ui/docs/pyric-ui-primitives-reference-api/index.html +1 -1
- package/dist/serve/docs-ui/docs/pyric-ui-rtdb-reference-api/index.html +1 -1
- package/dist/serve/docs-ui/docs/pyric-ui-rules-hooks-reference-api/index.html +1 -1
- package/dist/serve/docs-ui/docs/pyric-ui-rules-reference-api/index.html +1 -1
- package/dist/serve/docs-ui/docs/pyric-ui-storage-hooks-reference-api/index.html +1 -1
- package/dist/serve/docs-ui/docs/pyric-ui-storage-reference-api/index.html +1 -1
- package/dist/serve/docs-ui/docs/pyric-ui-traffic-hooks-reference-api/index.html +1 -1
- package/dist/serve/docs-ui/docs/pyric-ui-traffic-reference-api/index.html +1 -1
- package/dist/serve/docs-ui/docs/rules-compat/index.html +1 -1
- package/dist/serve/docs-ui/docs/secure/audit-your-rules/index.html +1 -1
- package/dist/serve/docs-ui/docs/secure/firestore-rules-limits/index.html +1 -1
- package/dist/serve/docs-ui/docs/secure/read-a-denial/index.html +1 -1
- package/dist/serve/docs-ui/docs/secure/rtdb-rules-in-typescript/index.html +1 -1
- package/dist/serve/docs-ui/docs/secure/rules-standard-library/index.html +1 -1
- package/dist/serve/docs-ui/docs/secure/secure-it-with-rules/index.html +1 -1
- package/dist/serve/docs-ui/docs/secure/simulate-and-lint/index.html +1 -1
- package/dist/serve/docs-ui/docs/secure/write-a-rules-test-suite/index.html +1 -1
- package/dist/serve/docs-ui/docs/ship/ship-to-production/index.html +1 -1
- package/dist/serve/docs-ui/docs/ship/test-in-node/index.html +1 -1
- package/dist/serve/docs-ui/docs/storage-compat/index.html +1 -1
- package/dist/serve/docs-ui/docs/trust/how-we-know-it-matches-firebase/index.html +1 -1
- package/dist/serve/docs-ui/docs/trust/versioning-and-compatibility/index.html +1 -1
- package/dist/serve/docs-ui/docs/tutorial/index.html +429 -0
- package/dist/serve/docs-ui/docs/tutorial.md +701 -0
- package/dist/serve/docs-ui/llms.txt +3 -1
- package/dist/serve/entries/init.d.ts.map +1 -1
- package/dist/serve/entries/init.js +3 -0
- package/dist/serve/entries/init.js.map +1 -1
- package/dist/serve/entries/runtime.d.ts.map +1 -1
- package/dist/serve/entries/runtime.js +20 -5
- package/dist/serve/entries/runtime.js.map +1 -1
- package/dist/serve/entries/worker-runtime.d.ts +2 -2
- package/dist/serve/entries/worker-runtime.d.ts.map +1 -1
- package/dist/serve/entries/worker-runtime.js +45 -10
- package/dist/serve/entries/worker-runtime.js.map +1 -1
- package/dist/serve/runtime/chip-config.d.ts +19 -0
- package/dist/serve/runtime/chip-config.d.ts.map +1 -0
- package/dist/serve/runtime/chip-config.js +19 -0
- package/dist/serve/runtime/chip-config.js.map +1 -0
- package/dist/serve/runtime/chip-install.d.ts +10 -0
- package/dist/serve/runtime/chip-install.d.ts.map +1 -0
- package/dist/serve/runtime/chip-install.js +15 -0
- package/dist/serve/runtime/chip-install.js.map +1 -0
- package/dist/serve/runtime/chip.d.ts +17 -0
- package/dist/serve/runtime/chip.d.ts.map +1 -0
- package/dist/serve/runtime/chip.js +257 -0
- package/dist/serve/runtime/chip.js.map +1 -0
- package/dist/serve/runtime/manifest.d.ts +22 -0
- package/dist/serve/runtime/manifest.d.ts.map +1 -0
- package/dist/serve/runtime/manifest.js +20 -0
- package/dist/serve/runtime/manifest.js.map +1 -0
- package/dist/serve/runtime/status.d.ts +49 -0
- package/dist/serve/runtime/status.d.ts.map +1 -0
- package/dist/serve/runtime/status.js +164 -0
- package/dist/serve/runtime/status.js.map +1 -0
- package/dist/serve/runtime/worker-connection.d.ts +4 -0
- package/dist/serve/runtime/worker-connection.d.ts.map +1 -0
- package/dist/serve/runtime/worker-connection.js +11 -0
- package/dist/serve/runtime/worker-connection.js.map +1 -0
- package/dist/serve/runtime/worker-generation.d.ts +14 -0
- package/dist/serve/runtime/worker-generation.d.ts.map +1 -0
- package/dist/serve/runtime/worker-generation.js +56 -0
- package/dist/serve/runtime/worker-generation.js.map +1 -0
- package/dist/serve/runtime/worker-replacement.d.ts +18 -0
- package/dist/serve/runtime/worker-replacement.d.ts.map +1 -0
- package/dist/serve/runtime/worker-replacement.js +29 -0
- package/dist/serve/runtime/worker-replacement.js.map +1 -0
- package/dist/serve/standalone-assets.d.ts +2 -2
- package/dist/serve/standalone-assets.d.ts.map +1 -1
- package/dist/serve/standalone-assets.js +1 -1
- package/dist/serve/standalone-assets.js.map +1 -1
- package/dist/serve/studio-ui/assets/{RulesCodeEditor-CxVYcZXw.js → RulesCodeEditor-BDlH-5lp.js} +1 -1
- package/dist/serve/studio-ui/assets/{index-cpSfgQ7H.js → index-Bf9SSE8L.js} +5 -5
- package/dist/serve/studio-ui/assets/{seed-DeuFKi4J.js → seed-D_UjxfOU.js} +1 -1
- package/dist/serve/studio-ui/index.html +1 -1
- package/dist/serve/vite-ai-config.d.ts +25 -0
- package/dist/serve/vite-ai-config.d.ts.map +1 -0
- package/dist/serve/vite-ai-config.js +45 -0
- package/dist/serve/vite-ai-config.js.map +1 -0
- package/dist/serve/vite-plugin.d.ts +17 -36
- package/dist/serve/vite-plugin.d.ts.map +1 -1
- package/dist/serve/vite-plugin.js +38 -57
- package/dist/serve/vite-plugin.js.map +1 -1
- package/dist/serve/vite-rules-source.d.ts +8 -0
- package/dist/serve/vite-rules-source.d.ts.map +1 -0
- package/dist/serve/vite-rules-source.js +23 -0
- package/dist/serve/vite-rules-source.js.map +1 -0
- package/dist/serve/vite-worker-runtime.d.ts +20 -0
- package/dist/serve/vite-worker-runtime.d.ts.map +1 -0
- package/dist/serve/vite-worker-runtime.js +25 -0
- package/dist/serve/vite-worker-runtime.js.map +1 -0
- package/dist/serve/worker/client/connection.d.ts +7 -2
- package/dist/serve/worker/client/connection.d.ts.map +1 -1
- package/dist/serve/worker/client/connection.js +13 -16
- package/dist/serve/worker/client/connection.js.map +1 -1
- package/dist/serve/worker/client/core.d.ts +7 -0
- package/dist/serve/worker/client/core.d.ts.map +1 -1
- package/dist/serve/worker/client/core.js +28 -0
- package/dist/serve/worker/client/core.js.map +1 -1
- package/dist/serve/worker/client/runtime-control.d.ts +8 -0
- package/dist/serve/worker/client/runtime-control.d.ts.map +1 -0
- package/dist/serve/worker/client/runtime-control.js +11 -0
- package/dist/serve/worker/client/runtime-control.js.map +1 -0
- package/dist/serve/worker/entry.js +44 -2
- package/dist/serve/worker/entry.js.map +1 -1
- package/dist/serve/worker/host/core.js +1 -1
- package/dist/serve/worker/host/core.js.map +1 -1
- package/dist/serve/worker/host/firestore-writes.d.ts.map +1 -1
- package/dist/serve/worker/host/firestore-writes.js +3 -2
- package/dist/serve/worker/host/firestore-writes.js.map +1 -1
- package/dist/serve/worker/host/studio.js +1 -1
- package/dist/serve/worker/host/studio.js.map +1 -1
- package/dist/serve/worker/host-context.d.ts +1 -1
- package/dist/serve/worker/host-context.d.ts.map +1 -1
- package/dist/serve/worker/index.d.ts +2 -1
- package/dist/serve/worker/index.d.ts.map +1 -1
- package/dist/serve/worker/index.js +2 -1
- package/dist/serve/worker/index.js.map +1 -1
- package/dist/serve/worker/protocol.d.ts +15 -1
- package/dist/serve/worker/protocol.d.ts.map +1 -1
- package/dist/serve/worker/protocol.js +2 -2
- package/dist/serve/worker/protocol.js.map +1 -1
- package/dist/serve/worker/retirement.d.ts +21 -0
- package/dist/serve/worker/retirement.d.ts.map +1 -0
- package/dist/serve/worker/retirement.js +97 -0
- package/dist/serve/worker/retirement.js.map +1 -0
- package/dist/serve/worker/serve-init.d.ts.map +1 -1
- package/dist/serve/worker/serve-init.js +5 -6
- package/dist/serve/worker/serve-init.js.map +1 -1
- package/dist/vite.d.ts +1 -0
- package/dist/vite.d.ts.map +1 -1
- package/dist/vite.js.map +1 -1
- package/package.json +6 -4
- package/src/assurance/.generated/conformance-verdicts.ts +1090 -0
- package/src/assurance/attachment.ts +211 -0
- package/src/assurance/browser.ts +80 -0
- package/src/assurance/campaign.ts +496 -0
- package/src/assurance/capabilities.ts +446 -0
- package/src/assurance/cases.ts +43 -0
- package/src/assurance/index.ts +75 -0
- package/src/assurance/runner.ts +885 -0
- package/src/assurance/tool-names.ts +15 -0
- package/src/assurance/tools.ts +830 -0
- package/src/assurance/types.ts +352 -0
- package/src/assurance/validation.ts +434 -0
- package/src/bridge/client/bridge.ts +550 -0
- package/src/bridge/client/dispatch.ts +137 -0
- package/src/bridge/client.ts +45 -0
- package/src/bridge/protocol.ts +351 -0
- package/src/bridge/server/audit.ts +53 -0
- package/src/bridge/server/bridge.ts +597 -0
- package/src/bridge/server/headless.ts +160 -0
- package/src/bridge/server/json-schema-to-zod.ts +108 -0
- package/src/bridge/server/local-bridge.ts +66 -0
- package/src/bridge/server/logger.ts +50 -0
- package/src/bridge/server/mcp-contract.ts +93 -0
- package/src/bridge/server/mcp.ts +129 -0
- package/src/bridge/server/peer.ts +232 -0
- package/src/bridge/server/standalone.ts +347 -0
- package/src/bridge/server/tool-metadata.ts +99 -0
- package/src/bridge/server.ts +28 -0
- package/src/cli/can-i-use.ts +50 -0
- package/src/cli/cli.test.ts +493 -0
- package/src/cli/database-rules.ts +329 -0
- package/src/cli/dev-runner.ts +282 -0
- package/src/cli/firebase-json.ts +100 -0
- package/src/cli/firestore-indexes.ts +70 -0
- package/src/cli/index.ts +425 -0
- package/src/cli/init.ts +260 -0
- package/src/cli/mcp-proxy.ts +196 -0
- package/src/cli/parse-args.ts +80 -0
- package/src/cli/rules.ts +259 -0
- package/src/cli/scope.ts +67 -0
- package/src/cli/serve.ts +996 -0
- package/src/cli/service-commands.ts +73 -0
- package/src/cli/snapshot.ts +164 -0
- package/src/cli/storage-rules.ts +172 -0
- package/src/cli/verify.ts +416 -0
- package/src/conformance/.generated/can-i-use-browser.ts +113 -0
- package/src/conformance/.generated/can-i-use.ts +117 -0
- package/src/conformance/.generated/conformance-docs.ts +14 -0
- package/src/conformance/browser.ts +24 -0
- package/src/conformance/can-i-use-tool.ts +51 -0
- package/src/conformance/can-i-use.ts +18 -0
- package/src/conformance/docs.ts +8 -0
- package/src/conformance/index.ts +20 -0
- package/src/conformance/tools.ts +16 -0
- package/src/credentials/core/memoize-ttl.ts +142 -0
- package/src/credentials/core/types.ts +10 -0
- package/src/credentials/node/from-adc.ts +96 -0
- package/src/credentials/node/from-service-account.ts +133 -0
- package/src/credentials/node/index.ts +6 -0
- package/src/discover/concurrency.ts +127 -0
- package/src/discover/crawler-adapter.ts +142 -0
- package/src/discover/crawler.ts +1127 -0
- package/src/discover/credential-free.ts +27 -0
- package/src/discover/findCollectionGroup.ts +131 -0
- package/src/discover/firestore-source.ts +59 -0
- package/src/discover/index.ts +5 -0
- package/src/discover/merge.ts +523 -0
- package/src/discover/session.ts +402 -0
- package/src/discover/tools.ts +201 -0
- package/src/discover/types.ts +187 -0
- package/src/discover/wire.ts +324 -0
- package/src/functions-rtdb/child.ts +382 -0
- package/src/functions-rtdb/delivery.ts +7 -0
- package/src/functions-rtdb/discovery.ts +136 -0
- package/src/functions-rtdb/event.ts +64 -0
- package/src/functions-rtdb/execution.ts +111 -0
- package/src/functions-rtdb/in-memory-delivery.ts +40 -0
- package/src/functions-rtdb/project.ts +74 -0
- package/src/functions-rtdb/projection.ts +104 -0
- package/src/functions-rtdb/reference-pattern.ts +20 -0
- package/src/functions-rtdb/remote-delivery.ts +23 -0
- package/src/pkg-version.ts +49 -0
- package/src/register/esm-exports.ts +63 -0
- package/src/register/hooks.ts +30 -0
- package/src/register/index.ts +150 -0
- package/src/register/mapping.ts +33 -0
- package/src/remote/index.ts +1050 -0
- package/src/rtdb/crawl-snapshot.ts +118 -0
- package/src/rtdb/inspection.ts +137 -0
- package/src/rtdb/load-rules-document.ts +56 -0
- package/src/rtdb/rules-generation-tool.ts +38 -0
- package/src/rtdb/rules-json.ts +29 -0
- package/src/serve/activity-guard.ts +29 -0
- package/src/serve/activity-route.ts +164 -0
- package/src/serve/activity-warning.ts +26 -0
- package/src/serve/bridge-mount.ts +200 -0
- package/src/serve/bundler.ts +519 -0
- package/src/serve/capture-store.ts +65 -0
- package/src/serve/discovery.ts +199 -0
- package/src/serve/entries/ai.ts +292 -0
- package/src/serve/entries/app-backend.ts +4 -0
- package/src/serve/entries/app-client.ts +26 -0
- package/src/serve/entries/app-session-store.ts +47 -0
- package/src/serve/entries/app.ts +11 -0
- package/src/serve/entries/auth-helper-core.ts +181 -0
- package/src/serve/entries/auth-helper-dom.ts +134 -0
- package/src/serve/entries/auth-helper-runtime.ts +20 -0
- package/src/serve/entries/auth.ts +255 -0
- package/src/serve/entries/bridge-url.ts +31 -0
- package/src/serve/entries/database.ts +129 -0
- package/src/serve/entries/firestore.ts +232 -0
- package/src/serve/entries/init.ts +49 -0
- package/src/serve/entries/keepalive.ts +46 -0
- package/src/serve/entries/messaging-sw.ts +75 -0
- package/src/serve/entries/messaging.ts +96 -0
- package/src/serve/entries/runtime.ts +556 -0
- package/src/serve/entries/session-store.ts +97 -0
- package/src/serve/entries/storage.ts +92 -0
- package/src/serve/entries/tab-sync-wiring.ts +274 -0
- package/src/serve/entries/worker-runtime.ts +135 -0
- package/src/serve/init-payload.ts +42 -0
- package/src/serve/namespace.ts +675 -0
- package/src/serve/open-browser.ts +68 -0
- package/src/serve/rules.ts +272 -0
- package/src/serve/runtime/chip-config.ts +30 -0
- package/src/serve/runtime/chip-install.ts +27 -0
- package/src/serve/runtime/chip.ts +282 -0
- package/src/serve/runtime/manifest.ts +37 -0
- package/src/serve/runtime/status.ts +216 -0
- package/src/serve/runtime/worker-connection.ts +14 -0
- package/src/serve/runtime/worker-generation.ts +75 -0
- package/src/serve/runtime/worker-replacement.ts +42 -0
- package/src/serve/sandbox-marker.ts +31 -0
- package/src/serve/server.ts +428 -0
- package/src/serve/standalone-assets.ts +180 -0
- package/src/serve/state-store.ts +166 -0
- package/src/serve/studio/disk-project-store.ts +185 -0
- package/src/serve/studio/disk-workspace.ts +162 -0
- package/src/serve/studio/index.ts +20 -0
- package/src/serve/studio/routes.ts +237 -0
- package/src/serve/studio/store-types.ts +48 -0
- package/src/serve/studio/studio-storage.test.ts +289 -0
- package/src/serve/vite-ai-config.ts +77 -0
- package/src/serve/vite-plugin.ts +1075 -0
- package/src/serve/vite-rules-source.ts +28 -0
- package/src/serve/vite-worker-runtime.ts +51 -0
- package/src/serve/worker/activity-bootstrap.ts +24 -0
- package/src/serve/worker/client/admin-firestore.ts +38 -0
- package/src/serve/worker/client/ai.ts +124 -0
- package/src/serve/worker/client/auth.ts +489 -0
- package/src/serve/worker/client/connection.ts +227 -0
- package/src/serve/worker/client/core.ts +384 -0
- package/src/serve/worker/client/disconnect.ts +45 -0
- package/src/serve/worker/client/firestore-reads.ts +181 -0
- package/src/serve/worker/client/firestore-refs.ts +226 -0
- package/src/serve/worker/client/firestore-writes.ts +232 -0
- package/src/serve/worker/client/handles.ts +91 -0
- package/src/serve/worker/client/messaging.ts +119 -0
- package/src/serve/worker/client/presence.ts +174 -0
- package/src/serve/worker/client/rtdb.ts +311 -0
- package/src/serve/worker/client/rules.ts +63 -0
- package/src/serve/worker/client/runtime-control.ts +22 -0
- package/src/serve/worker/client/service-worker-connection.ts +59 -0
- package/src/serve/worker/client/snapshots.ts +86 -0
- package/src/serve/worker/client/storage.ts +195 -0
- package/src/serve/worker/client/studio.ts +88 -0
- package/src/serve/worker/client.ts +57 -0
- package/src/serve/worker/durable-persistence.ts +137 -0
- package/src/serve/worker/entry.ts +223 -0
- package/src/serve/worker/host/admin-firestore.ts +88 -0
- package/src/serve/worker/host/connection.ts +179 -0
- package/src/serve/worker/host/core.ts +387 -0
- package/src/serve/worker/host/dispatch.ts +316 -0
- package/src/serve/worker/host/firestore-reads.ts +117 -0
- package/src/serve/worker/host/firestore-writes.ts +456 -0
- package/src/serve/worker/host/presence.ts +312 -0
- package/src/serve/worker/host/rtdb.ts +136 -0
- package/src/serve/worker/host/rules.ts +128 -0
- package/src/serve/worker/host/storage.ts +312 -0
- package/src/serve/worker/host/studio.ts +75 -0
- package/src/serve/worker/host/subscriptions.ts +238 -0
- package/src/serve/worker/host-ai.ts +165 -0
- package/src/serve/worker/host-auth.ts +469 -0
- package/src/serve/worker/host-context.ts +273 -0
- package/src/serve/worker/host-events.ts +94 -0
- package/src/serve/worker/host-messaging.ts +240 -0
- package/src/serve/worker/host.ts +47 -0
- package/src/serve/worker/index.ts +196 -0
- package/src/serve/worker/presence-timing.ts +15 -0
- package/src/serve/worker/protocol.ts +1124 -0
- package/src/serve/worker/retirement.ts +125 -0
- package/src/serve/worker/serve-init.ts +605 -0
- package/src/serve/worker/service-worker-channel.ts +33 -0
- package/src/serve/worker/service-worker-relay.ts +86 -0
- package/src/serve/writer-lock.ts +53 -0
- package/src/verify/cases.ts +233 -0
- package/src/verify/fixture.ts +258 -0
- package/src/verify/index.ts +519 -0
- package/src/verify/tools.ts +108 -0
- package/src/version/compat-target.ts +17 -0
- package/src/vite.ts +18 -0
- package/dist/serve/docs-ui/docs/pyric-firestore-values-reference-api/index.html +0 -31
- package/dist/serve/docs-ui/docs/pyric-firestore-values-reference-api.md +0 -29
|
@@ -1209,10 +1209,10 @@ ${e.join(`
|
|
|
1209
1209
|
|
|
1210
1210
|
Remediation:
|
|
1211
1211
|
${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 Bm(t){return t.kind==="request"||t.kind==="operation"}function Zl(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 ql(t){const e=Zl(t);return{actor:e.source,authLens:e.authLens,operationContext:e,...e.planId===void 0?{}:{planId:e.planId}}}function sS(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 Ld(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 Zl({source:sS(t)??sS(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 eI(t){return Ld(void 0,t)}function OE(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 tI(t){return t===null?null:Object.freeze({uid:t.uid,...t.token===void 0?{}:{token:RE(t.token)}})}function RE(t){const e={};for(const[n,r]of Object.entries(t))e[n]=TE(r);return Object.freeze(e)}function TE(t){return Array.isArray(t)?Object.freeze(t.map(TE)):t&&typeof t=="object"?RE(t):t}function DE(t){return Bm(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:tI(t.auth),result:t.result,context:eI(t),rules:Object.freeze({...OE(t)})}):null}function iS(t){return t===null?{mode:"anon"}:t.token===void 0?{mode:"as",uid:t.uid}:{mode:"as",uid:t.uid,token:t.token}}class ho{constructor(e,n,r){G(this,"sandbox");G(this,"auth");G(this,"operationContext");this.sandbox=e,this.auth=n,this.operationContext=Zl(r??{source:{kind:"unattributed"},authLens:iS(n)})}withAuth(e){return qm(e),new ho(this.sandbox,e,{source:this.operationContext.source,authLens:iS(e),...this.operationContext.planId===void 0?{}:{planId:this.operationContext.planId}})}}function Wl(t,e){return new ho(t.sandbox,t.auth,e)}function qm(t){if(t===null)return;if(t===void 0)throw new nt({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(`
|
|
1212
|
-
`)});if(typeof t!="object")throw new nt("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 nt("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 nt("invalid-argument","withAuth() requires `token` (when present) to be a plain object.")}function nI(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 rI(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 Ud(t){return Fm(t,!0)}function Fm(t,e){if(t===null||typeof t!="object")return t;if(Array.isArray(t)){const o=t.map(c=>Fm(c,!1));return e&&no(o,Wx(t)),o}const n=t,r=o=>(e&&no(o,Wx(t)),o);if(n.__type__==="__vector__"&&Array.isArray(n.value))return r(new uo(n.value));if(typeof n.__type=="string")switch(n.__type){case"timestamp":return r(new Rt(n.seconds,n.nanos));case"bytes":return r(new In(nI(n.base64)));case"latlng":return r(new Cr(n.lat,n.lng));case"duration":return r(new Mt(n.seconds,n.nanos));case"reference":return r(new Xa(n.path));case"path":return r(new dr(n.segments))}if(typeof n.type=="string")switch(n.type){case"firestore/timestamp/1.0":{const o=n.seconds,c=n.nanoseconds;return r(new Rt(o,c))}case"firestore/bytes/1.0":return r(new In(rI(n.bytes)));case"firestore/geoPoint/1.0":return r(new Cr(n.latitude,n.longitude))}const s={};for(const[o,c]of Object.entries(n))s[o]=Fm(c,!1);return r(s)}class Eu extends Error{constructor(e){super(e),this.name="PersistenceSchemaError"}}function sI(t){let e;try{e=JSON.parse(t)}catch(s){throw new Eu(`Persisted blob is not valid JSON: ${s.message}`)}if(typeof e!="object"||e===null)throw new Eu("Persisted blob is not an object");if(e.version!==1&&e.version!==2)throw new Eu(`Persisted blob has version ${String(e.version)}, expected 1 or 2`);if(typeof e.firestore!="object"||e.firestore===null)throw new Eu("Persisted blob has no firestore field");const n={};for(const[s,o]of Object.entries(e.firestore))n[s]=Ud(o);const r=e.services!==void 0&&typeof e.services=="object"&&e.services!==null?e.services:{};return{firestore:n,services:r}}const iI=3,aI=256,zm="meta";function oI(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%aI).toString(16).padStart(2,"0")}function lI(t){return JSON.parse(JSON.stringify(t))}function IE(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 ME(t,e,n){const r=new Map;r.set(zm,{version:iI,savedAt:n,services:e});for(const[s,o]of Object.entries(t)){const c=oI(s);let d=r.get(c);d||(d={docs:{}},r.set(c,d)),d.docs[s]=lI(o)}for(const[s,o]of r)s!==zm&&(o.checksum=IE(o.docs));return r}const LE="pyric-v3-records";function cI(t){return JSON.stringify({format:LE,records:Object.fromEntries(t)})}function uI(t){let e;try{e=JSON.parse(t)}catch{return new Map}const n=e;return n&&typeof n=="object"&&n.format===LE&&typeof n.records=="object"&&n.records!==null?new Map(Object.entries(n.records)):UE(t)??new Map}function UE(t){let e;try{e=sI(t)}catch{return null}return ME(e.firestore,e.services,0)}function dI(t){const e={};let n={};for(const[r,s]of t){if(r===zm){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"&&IE(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]=Ud(d)}}return{firestore:e,services:n}}const so="snapshots";function Pm(){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 $E(t){return new Promise((e,n)=>{const r=indexedDB.open(t,1);r.onupgradeneeded=()=>{const s=r.result;s.objectStoreNames.contains(so)||s.createObjectStore(so)},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 Hp(t,e,n){return $E(t).then(r=>new Promise((s,o)=>{const c=r.transaction(so,e),d=c.objectStore(so),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 aS(t,e){return $E(t).then(n=>new Promise((r,s)=>{const o=n.transaction(so,"readwrite");e(o.objectStore(so)),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 fI(){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 Hp(t,"readonly",r=>r.get(e))??null},async listRecords(t){return(await Hp(t,"readonly",n=>n.getAllKeys())??[]).map(n=>String(n))},async putRecords(t,e){await aS(t,n=>{for(const[r,s]of e)n.put(s,r)})},async deleteRecords(t,e){await aS(t,n=>{for(const r of e)n.delete(r)})},async clear(t){await Hp(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 hI=250,oS="pyric:sandbox:auth-session";function Gp(t){return t==="auth"||t==="auth-session:[DEFAULT]"?oS:`${oS}:${encodeURIComponent(t)}`}function BE(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 pI(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 mI(t){return t.injectedBackend?t.injectedBackend:(t.backend??"indexedDB")==="memory"||typeof indexedDB>"u"?Pm():fI()}async function yI(t,e){const n={...e,flushIntervalMs:e.flushIntervalMs??hI,backend:e.backend??"indexedDB"},r=mI(n),s=new Map,o=await gI(t,r,n.key,s);let c=null,d=!1;const f=new Map,p=async()=>{if(d)return;const U=t.snapshot(),H=ME(U.firestore,U.services,Date.now()),z=new Map,q=new Map;for(const[E,O]of H){const T=BE(O);q.set(E,T),s.get(E)!==T&&z.set(E,O)}const x=[...s.keys()].filter(E=>!H.has(E));z.size>0&&await r.putRecords(n.key,z),x.length>0&&await r.deleteRecords(n.key,x),s.clear();for(const[E,O]of q)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(U=>{if(pI(U)){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:",U),v()})},n.flushIntervalMs))},w=(U,H)=>{if(!H.subscribe||f.has(U))return;const z=H.subscribe(()=>{v()});f.set(U,z)},_=new Map,k=new Map,I=(U,H)=>{if(!n.sessionStorage)return;const{local:z,session:q}=n.sessionStorage,x=Gp(U),E=H.currentUid(),O=H.mode();if(E===null||O==="NONE"){z.removeItem(x),q.removeItem(x);return}const T=JSON.stringify({uid:E});O==="LOCAL"?(q.removeItem(x),z.setItem(x,T)):(z.removeItem(x),q.setItem(x,T))},N=U=>{if(!n.sessionStorage)return null;const H=Gp(U);for(const[z,q]of[["LOCAL",n.sessionStorage.local],["SESSION",n.sessionStorage.session]]){const x=q.getItem(H);if(x)try{const E=JSON.parse(x);if(typeof(E==null?void 0:E.uid)=="string")return{uid:E.uid,mode:z}}catch{q.removeItem(H)}}return null},R=U=>{if(!n.sessionStorage)return;const H=Gp(U);n.sessionStorage.local.removeItem(H),n.sessionStorage.session.removeItem(H)},M=(U,H,z)=>{if(z.session)try{z.session.restore(H.uid,H.mode),k.delete(U)}catch(q){console.warn(`[sandbox/persistence] session restore for uid '${H.uid}' failed — clearing stored session:`,q),R(U),k.delete(U)}},F=(U,H)=>{if(!n.sessionStorage||!H.session||_.has(U))return;const z=H.session;_.set(U,z.subscribe(()=>I(U,z)))},D=(U,H)=>{if(!H.session)return;const z=k.get(U)??N(U);z&&M(U,z,H)};if(t instanceof Js){for(const[U,H]of t.getServiceRegistry())w(U,H),D(U,H),F(U,H);t.setServiceRegistrationHook((U,H)=>{if(o!==null&&U in o)try{H.restore(o[U])}catch(q){console.warn(`[sandbox/persistence] late-restore for service '${U}' failed:`,q)}const z=N(U);z&&k.set(U,z),D(U,H),w(U,H),F(U,H),v()}),t.setServiceUnregistrationHook(U=>{var H,z;(H=f.get(U))==null||H(),f.delete(U),(z=_.get(U))==null||z(),_.delete(U),k.delete(U),v()})}const C=t.onEvent(U=>{bI(U)&&v()}),L=()=>{b().catch(()=>{})};return typeof window<"u"&&window.addEventListener("beforeunload",L),{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),C();for(const U of f.values())U();f.clear();for(const U of _.values())U();_.clear(),t instanceof Js&&(t.setServiceRegistrationHook(null),t.setServiceUnregistrationHook(null)),typeof window<"u"&&window.removeEventListener("beforeunload",L)}}}}async function gI(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=UE(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,BE(b));const p=dI(c);for(const[g,b]of Object.entries(p.firestore))t.admin.setDocument(g,b);if(t instanceof Js){const g=t.getServiceRegistry();for(const[b,v]of Object.entries(p.services)){const w=g.get(b);if(w)try{w.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 bI(t){return t.kind==="write"||t.kind==="session_boundary"}function vI(t){return typeof t=="object"&&t!==null&&typeof t.kind=="string"&&typeof t.origin=="string"}let wI=0;function xI(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`tab-${crypto.randomUUID()}`:`tab-${++wI}-${typeof performance<"u"?performance.now().toFixed(3):String(Date.now())}`}function SI(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??xI();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(!vI(b.data))return;const v=b.data;if(v.origin!==s){if(v.kind==="write")g(v.event);else if(v.kind==="hello"){const w={kind:"state",origin:s,to:v.origin,snapshot:t.snapshot()};n.postMessage(w)}else if(v.kind==="state"){if(v.to!==s||c)return;if(Object.keys(Wt(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 _I(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=Bm(n)||t.operationContext!==void 0?Ld(e,s):EI(t,e);return n.operationContext=o,n.actor=o.source,n.authLens=o.authLens,o.planId!==void 0&&(n.planId=o.planId),(e==null?void 0:e.activity)!==void 0&&(n.activity={...n.activity,...e.activity}),Bm(n)&&(n.rulesDisposition=Object.freeze({...OE(n)})),n}function EI(t,e){var n,r,s,o,c,d,f,p;return Zl({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 AI(t,e){var s,o,c,d;if(!t)return e;if(!e)return t;if(e.operationContext!==void 0)return qE(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=Zl({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 qE(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=Ld(t,e);return{...t,...e,operationContext:r,actor:r.source,authLens:r.authLens,...r.planId===void 0?{}:{planId:r.planId}}}let jI=1;function Li(){const t=(jI++).toString(36),e=Math.random().toString(36).slice(2,7);return`sbe-${t}-${e}`}class Js{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 Js(new rS)}getEnv(){return this._env}withAuth(e){return qm(e),new ho(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:Li(),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=qE(this.ambientProvenance,n);this.dispatch(_I(e,r))}runWithProvenance(e,n){const r=this.ambientProvenance;this.ambientProvenance=AI(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:Li(),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 rS,this.attachToEnv()}async resetAll(){this.reset();const e=[],n=[];for(const[r,s]of this.serviceRegistry)s.reset&&n.push(Promise.resolve().then(()=>s.reset()).catch(o=>{e.push(`${r}: ${o instanceof Error?o.message:String(o)}`)}));return await Promise.all(n),{errors:e}}dispose(){const e={kind:"session_boundary",id:Li(),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){qm(e),!kI(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 nt("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 yI(this,e);this.persistence=n})();try{await this.enablePersistencePromise}finally{this.enablePersistencePromise=null}}enableTabSync(e){return SI(this,e)}async flush(){if(!this.persistence)throw new nt("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 nt("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 kI(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 Wt(t){if(!(t instanceof Js))throw new nt("invalid-argument","Sandbox handle was not produced by initializeSandbox(); custom Sandbox implementations are not supported.");return t.getEnv()}function Vs(t,e,n){if(!(t instanceof Js))throw new nt("invalid-argument","Sandbox handle was not produced by initializeSandbox(); custom Sandbox implementations are not supported.");t.emitInternal(e,n)}function $d(t){return{kind:"service_mutation",id:Li(),at:Date.now(),...t}}function FE(t){const{at:e,...n}=t;return{kind:"operation",id:Li(),at:e??Date.now(),...n}}function CI(t){const{at:e,...n}=t;return{kind:"commit",id:Li(),at:e??Date.now(),...n}}function NI(t){const{at:e,...n}=t;return{kind:"listener",id:Li(),at:e??Date.now(),...n}}const OI=Symbol.for("pyric.remote.sandbox");function rg(t){return t!=null&&t[OI]===!0}function zE(t,e=""){const n=VE();return Wt(n).seed({rules:e,baseDocuments:t.firestore}),{sandbox:n,rules:e,base:t,events:[],discarded:!1}}function RI(t,e){TI(t);const n=Wt(t.sandbox).snapshot(),r=DI(e);return MI(r,n)}function PE(t){t.discarded||(t.discarded=!0,t.sandbox.dispose())}function TI(t){if(t.discarded)throw new Error("Branch has been discarded or promoted; create a new fork.")}function DI(t){return II(t)?Wt(t).snapshot():t.firestore}function II(t){return typeof t.snapshot=="function"}function MI(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||LI(s,o,c,n)}return n}function LI(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 w of v){const _=d?`${d}.${w}`:w;s(g[w],b[w],_)}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}Vm(o,c)||r.push({kind:"real-divergence",path:t,field:d||void 0,before:o,after:c})}}function Vm(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(!Vm(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)||!Vm(s[f],o[f]))return!1;return!0}function VE(t={}){return Js.createRoot()}function hl(t,e){return`${t.replace(/\/$/,"")}${e}`}function UI(t){const e=t;return{async read(n){const r=await fetch(hl(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(hl(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(hl(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(hl(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(hl(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 pl(t,e){return`${t.replace(/\/$/,"")}${e}`}function $I(t){const e=t;return{async list(){const n=await fetch(pl(e,"/__pyric/projects"));if(!n.ok)throw new Error(`projects.list() → ${n.status}`);return await n.json()},async open(n){const r=await fetch(pl(e,`/__pyric/projects/${encodeURIComponent(n)}`));if(!r.ok)throw new Error(`projects.open(${n}) → ${r.status}`);return{meta:await r.json(),workspace:UI(e)}},async create(n){const r=await fetch(pl(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(pl(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(pl(e,`/__pyric/projects/${encodeURIComponent(n)}`),{method:"DELETE"});if(!r.ok)throw new Error(`projects.remove(${n}) → ${r.status}`)}}}function BI(t,e){return`${t.replace(/\/$/,"")}${e}`}function Kp(t){return/auth/i.test(t)?"auth":"firestore"}function qI(t){const e=t,r={"content-type":"application/json","x-pyric-writer":`studio-${Math.random().toString(36).slice(2)}`},s=new Map,o=f=>BI(e,`/__pyric/state?section=${Kp(f)}`),c=async f=>{const p=Kp(f),g=s.get(p);if(g)return g;const b=await fetch(o(f));let v=new Map;if(b.ok){const w=await b.text();w&&w!=="null"&&(v=uI(w))}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:cI(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(Kp(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 FI="local";function zI(){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 PI(){const t=zI();let e={id:FI,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 Wi 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(Wi,"name",{value:"FirebaseError"});let Wa;function VI(t){Wa=t}function sg(t){return Wa==null?void 0:Wa.resolve(t,!1)}function HE(){if(!Wa)throw new TypeError("No default sandbox app registry is installed - import and initialize pyric/app before calling a service factory without an app.");return Wa.defaultApp()}function HI(){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 GE=new WeakMap;let Hm;function GI(t,e,n=HI()){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 Wi("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 GE.set(t,d),d}function KI(t){Hm=t}VI({resolve(t,e){const n=typeof t=="object"&&t!==null?GE.get(t):void 0;if(n)return n},defaultApp(){if(!Hm)throw new TypeError("No default sandbox app registry is installed - import and initialize pyric/app before calling a service factory without an app.");return Hm()}});const YI="[DEFAULT]",ZI=new Map;function WI(t,e){return new Wi(`app/${t}`,`Firebase: ${e} (app/${t}).`)}function QI(t){return WI("no-app",`No Firebase App '${t}' has been created - call initializeApp() first`)}function JI(t=YI){const e=ZI.get(t);if(!e)throw QI(t);return e.app}KI(JI);let XI=0,eM=0;function Ae(){return`op-${++XI}`}function po(){return`sub-${++eM}`}const Gm=new Map,ig=new Map,ag=new Map,Ql=new WeakSet;function tM(){return Object.assign(new Error("Firebase App was deleted"),{code:"app/app-deleted"})}function Jl(t,e,n,r){return Ql.has(t)?!1:(ig.set(e,n),t.postMessage(r),!0)}function nM(t,e,n,r){return Ql.has(t)?!1:(ag.set(e,{port:t,next:n}),t.postMessage(r),!0)}function Xl(t,e){ig.delete(e),ag.delete(e),Ql.has(t)||t.postMessage({t:"unsub",subId:e})}function lS(t,e){if(e.denialContext===void 0||typeof fetch!="function")return;const n={kind:t,code:e.code,message:e.message,denialContext:e.denialContext,...typeof e.remediation=="string"?{remediation:e.remediation}:{}};try{fetch("/__pyric/denials",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(n)}).catch(()=>{})}catch{}}function og(t){t.onmessage=e=>{const n=e.data;if(n.t==="res"){const r=Gm.get(n.id);if(!r)return;if(Gm.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),lS("read",s),r.reject(s)}}else if(n.t==="snap"){const r=ig.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),lS("listener",c),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=ag.get(n.subId);r&&r.next(n.events)}}}let io;function cS(t){io=t&&t.mode==="app-session"?void 0:t}function rM(){return io}let Km;function sM(t){Km=t}function lg(t){return Km&&(t.t==="op"||t.t==="sub")?{...t,issuer:Km}:t}function KE(t,e){return Ql.has(t)?Promise.reject(tM()):new Promise((n,r)=>{const s=e;Gm.set(s.id,{port:t,resolve:n,reject:r}),t.postMessage(e)})}function Ye(t,e){return KE(t,lg(e))}function nr(t,e){if(Ql.has(t)&&!e.method.startsWith("rtdb."))return Promise.reject(new Wi("failed-precondition","The client has already been terminated."));const n=io?{...e,actAs:io}:e;return Ye(t,n)}function iM(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(),og(r),{__kind:"client-db",port:r}}async function aM(t){return(await Ye(t.port,{t:"op",id:Ae(),method:"getVersion"})).instanceId??""}async function oM(t){return(await Ye(t.port,{t:"op",id:Ae(),method:"exportState"})).bundle}async function lM(t,e){await Ye(t.port,{t:"op",id:Ae(),method:"importState",bundle:e})}async function cM(t,e){await Ye(t.port,{t:"op",id:Ae(),method:"saveBranch",name:e})}async function uM(t){return(await Ye(t.port,{t:"op",id:Ae(),method:"listBranches"})).branches??[]}async function dM(t,e){await Ye(t.port,{t:"op",id:Ae(),method:"switchBranch",name:e})}async function fM(t,e){await Ye(t.port,{t:"op",id:Ae(),method:"deleteBranch",name:e})}async function hM(t,e,n){return await Ye(t.port,{t:"tool",id:Ae(),name:e,args:n})}function pM(t,e){return KE(t.port,{...e,issuer:void 0,relaySource:"remote",t:"op",id:Ae()})}function mM(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=po();return Jl(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,issuer:void 0,relaySource:"remote",t:"sub",subId:r})||queueMicrotask(()=>n({__error:{code:"app/app-deleted",message:"Firebase App was deleted"}})),()=>{Xl(t.port,r)}}function cg(t){return t.split("/").at(-1)??t}function yM(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:cg(r),path:r}}function gM(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:cg(r),path:r}}function bM(t){return{_descriptor:{kind:"limit",n:t}}}function vM(...t){return{_descriptor:{kind:"startAfter",values:t}}}function wM(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 xM(t){return Ud(JSON.parse(t.json))}const YE=8*1024*1024;function SM(t,e){const n=new Error(`${e} is ${t} bytes — over the ${YE/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 _M(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 EM(t){return xM(t)}function ug(t,e){const n=t.exists&&t.data?EM(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 ZE(t,e){const n=t.docs.map(r=>ug(r,e));return{size:n.length,empty:n.length===0,docs:n}}async function AM(t){const e=await nr(t.port,{t:"op",id:Ae(),method:"getDoc",path:t.descriptor.path});return ug(e,t.port)}async function jM(t){const e=await nr(t.port,{t:"op",id:Ae(),method:"getDocs",source:(t.__kind==="coll-ref",t.descriptor)});return ZE(e,t.port)}async function kM(t){return(await nr(t.port,{t:"op",id:Ae(),method:"listRootCollections"})).ids}async function CM(t,e){return(await nr(t.port,{t:"op",id:Ae(),method:"listSubcollections",docPath:e})).ids}function NM(t,e,n){const r=po(),s=t.port,o={port:s,service:"firestore",next:f=>{const p=f;"docs"in p?e(ZE(p,s)):e(ug(p,s))},error:n},c=(t.__kind==="doc-ref"||t.__kind==="coll-ref",t.descriptor);return!Jl(s,r,o,lg(io?{t:"sub",subId:r,target:c,actAs:io}:{t:"sub",subId:r,target:c}))&&n&&queueMicrotask(()=>n(new Error("Firebase App was deleted"))),()=>{Xl(s,r)}}async function OM(t,e,n){await nr(t.port,{t:"op",id:Ae(),method:"setDoc",path:t.descriptor.path,data:e,options:n})}async function RM(t){await nr(t.port,{t:"op",id:Ae(),method:"deleteDoc",path:t.descriptor.path})}async function TM(t,e){const n=await nr(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 DM(t,e){return await Ye(t.port,{t:"op",id:Ae(),method:"admin.listDocuments",path:e})}function IM(t){const e=(t??"/").split("/").filter(Boolean).join("/");return e?`/${e}`:"/"}new Array(12).fill(0);async function MM(t){return Ye(t.port,{t:"op",id:Ae(),method:"rtdb.adminSnapshot"})}async function LM(t,e,n){await Ye(t.port,{t:"op",id:Ae(),method:"rtdb.set",path:e,value:n,actAs:{mode:"admin"}})}async function UM(t,e,n){await Ye(t.port,{t:"op",id:Ae(),method:"rtdb.update",path:e,values:n,actAs:{mode:"admin"}})}async function $M(t,e){await Ye(t.port,{t:"op",id:Ae(),method:"rtdb.remove",path:e,actAs:{mode:"admin"}})}function BM(t,e,n,r){const s=po();return!Jl(t.port,s,{port:t.port,next:c=>n((c==null?void 0:c.value)??null),error:r},lg({t:"sub",subId:s,target:{service:"rtdb",path:IM(e)},actAs:{mode:"admin"}}))&&r&&queueMicrotask(()=>r(new Error("FIREBASE FATAL ERROR: Database has been deleted."))),()=>{Xl(t.port,s)}}function qM(t,e){const n=po(),r=t.port;return nM(r,n,e,{t:"sub",subId:n,target:"events"}),()=>{Xl(r,n)}}async function FM(t){return await Ye(t.port,{t:"op",id:Ae(),method:"getSnapshot"})}async function zM(t){return await Ye(t.port,{t:"op",id:Ae(),method:"resetAll"})??{errors:[]}}const PM=15e3;function VM(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`page-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function uS(){return typeof location>"u"?"/":`${location.pathname}${location.search}${location.hash}`}function dS(){return typeof document>"u"?"visible":document.visibilityState==="hidden"?"hidden":"visible"}function HM(t){const{db:e,kind:n}=t,r=t.clientId??VM(),s=t.heartbeatIntervalMs??PM;let o=!1,c=null;const d=()=>{Ye(e.port,{t:"op",id:Ae(),method:"presence.register",clientId:r,kind:n,route:uS(),visibility:dS()}).catch(()=>{})},f=()=>{Ye(e.port,{t:"op",id:Ae(),method:"presence.heartbeat",clientId:r}).catch(()=>{})},p=()=>{Ye(e.port,{t:"op",id:Ae(),method:"presence.update",clientId:r,route:uS(),visibility:dS()}).catch(()=>{})},g=()=>{Ye(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 GM(t,e){const n=po();return Jl(t.port,n,{port:t.port,next:r=>{e(r)}},{t:"sub",subId:n,target:"presence"}),()=>{Xl(t.port,n)}}const KM=Symbol("pyric.clientUser.port");function YM(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 Ye(t,{t:"op",id:Ae(),method:"auth.getIdToken",forceRefresh:r})},async getIdTokenResult(r){return await Ye(t,{t:"op",id:Ae(),method:"auth.getIdTokenResult",forceRefresh:r})}};return Object.defineProperty(n,KM,{value:t,enumerable:!1}),n}function ZM(t,e){return e?YM(t,e):null}function WM(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(),og(n)}const r={__kind:"client-auth",port:n,currentUser:null},s=po();return Jl(n,s,{port:n,next:o=>{r.currentUser=ZM(n,o)}},{t:"sub",subId:s,target:"authState"}),r}async function QM(t){return await Ye(t.port,{t:"op",id:Ae(),method:"auth.listUsers"})}async function JM(t,e){return await Ye(t.port,{t:"op",id:Ae(),method:"auth.adminCreateUser",request:e})}async function XM(t,e,n){return await Ye(t.port,{t:"op",id:Ae(),method:"auth.adminUpdateUser",uid:e,request:n})}async function eL(t,e){await Ye(t.port,{t:"op",id:Ae(),method:"auth.adminDeleteUser",uid:e})}async function tL(t){await Ye(t.port,{t:"op",id:Ae(),method:"auth.adminClearUsers"})}async function nL(t){return await Ye(t.port,{t:"op",id:Ae(),method:"auth.getProviderConfig"})}async function rL(t,e,n){await Ye(t.port,{t:"op",id:Ae(),method:"auth.setProviderConfig",providerId:e,enabled:n})}function sL(t){return t.replace(/^\/+|\/+$/g,"")}function iL(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(),og(n)}return{__kind:"client-storage",port:n}}function aL(t,e){const n=sL(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:cg(r)}}async function oL(t){const e=await nr(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 lL(t){return await nr(t.port,{t:"op",id:Ae(),method:"storage.getMetadata",path:t.fullPath})}async function cL(t){return await nr(t.port,{t:"op",id:Ae(),method:"storage.getBlob",path:t.fullPath})}async function uL(t,e,n){const r=e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof ArrayBuffer?new Uint8Array(e):e;if(r.byteLength>YE)throw SM(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 nr(t.port,{t:"op",id:Ae(),method:"storage.putBytes",path:t.fullPath,dataB64:_M(r),...s!==void 0?{contentType:s}:{},...n!==void 0?{metadata:n}:{}});return{ref:t,metadata:o}}async function dL(t){await nr(t.port,{t:"op",id:Ae(),method:"storage.deleteObject",path:t.fullPath})}const fL="/__pyric/sdk/worker.js";function hL(t){let e=[],n=!1;const r=new Set;let s=null;function o(){s||(s=qM(t,c=>{const d=!n;n=!0;const f=d?[]:[...e];for(const p of c)m1(p)&&(f.length=0),f.push(p);e=f;for(const p of c)for(const g of r)g(p)}))}return{history:()=>e,subscribe:c=>(r.add(c),o(),()=>{r.delete(c),r.size===0&&s&&(s(),s=null,n=!1,e=[])})}}function pL(t=fL){if(typeof SharedWorker>"u")return null;sM("studio");let e;try{e=iM(t)}catch{return null}cS({mode:"admin"});const n=HM({db:e,kind:"studio"}),r=hL(e),s=WM(e);return{db:e,presenceClientId:n.clientId,subscribePresence:o=>GM(e,o),instanceId:()=>aM(e),exportState:()=>oM(e),importState:o=>lM(e,o),saveBranch:o=>cM(e,o),listBranches:()=>uM(e),switchBranch:o=>dM(e,o),deleteBranch:o=>fM(e,o),feed:r,setLens:o=>cS(o),getLens:()=>rM(),listRootCollections:()=>kM(e),listSubcollections:o=>CM(e,o),listDocuments:async o=>(await DM(e,o)).map(({path:c,phantom:d})=>({path:c,phantom:d})),readRtdbState:()=>MM(e),setRtdbValue:(o,c)=>LM(e,o,c),updateRtdbValue:(o,c)=>UM(e,o,c),deleteRtdbValue:o=>$M(e,o),subscribeRtdbValue:(o,c,d)=>BM(e,o,c,d),firestoreApi:{collection:gM,doc:yM,getDoc:AM,getDocs:jM,onSnapshot:NM,setDoc:OM,deleteDoc:RM,addDoc:TM,query:wM,limit:bM,startAfter:vM},auth:s,authApi:{listUsers:()=>QM(s),subscribeUsers:(o,c)=>r.subscribe(d=>{d.kind==="service_mutation"&&d.service==="auth"&&c()}),createUser:(o,c)=>JM(s,c),updateUser:(o,c,d)=>XM(s,c,d),deleteUser:(o,c)=>eL(s,c),clearUsers:()=>tL(s),getAuthProviderConfig:()=>nL(s),setAuthProviderConfig:(o,c,d)=>rL(s,c,d),subscribeAuthProviderConfig:(o,c)=>r.subscribe(d=>{d.kind==="service_mutation"&&d.op==="provider_config_update"&&c()})},storage:iL(e),storageApi:{ref:aL,listAll:oL,getMetadata:lL,getBlob:cL,uploadBytes:uL,deleteObject:dL},getSnapshot:()=>FM(e),resetAll:()=>zM(e)}}const fS=5174,hS="/sandbox",mL=4001,yL="worker-relay";function gL(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 Ym(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=Ym(n);if(r)return r}return null}for(const n of Object.values(t)){const r=Ym(n);if(r)return r}return null}function pS(t,e){const n=Ym(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 bL=()=>{throw new Error("pyric dev: fs is not available in the browser")},mS=bL,Zm=(...t)=>t.join("/"),vL=t=>t.split("/").slice(0,-1).join("/")||"/",wL=t=>String(t).replace("file://",""),xL=vL(wL(import.meta.url)),SL=Zm(xL,"stdlib"),_L={readRelative(t,e){try{return mS(Zm(t,`${e}.rules`),"utf-8")}catch{return null}},readStdlib(t){try{return mS(Zm(SL,`${t}.rules`),"utf-8")}catch{return null}}};function EL(t,e){return z2(_L,t,e)}function AL(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(w=>{const _={};for(const[k,I]of Object.entries(d)){const R=w.get(I).data();_[k]=R===void 0?null:R}for(let k=0;k<f.length;k+=1){const I=f[k];if(I.method==="delete"){w.delete(I.path);continue}const N=I2(I.data,{reads:_});if(N===null||typeof N!="object"||Array.isArray(N))throw new ld(`writes[${k}].data resolved to a non-object`,`writes.${k}.data`);const R=N;switch(I.method){case"create":w.create(I.path,R);break;case"update":w.update(I.path,R);break;case"set":w.set(I.path,R);break}}},{auth:s,readOnly:o}),v={allowed:b.allowed,writes:b.writes.map(w=>{const _={path:w.path,method:w.method,allowed:w.allowed};return w.error&&(_.error={code:w.error.code,message:w.error.message}),g&&(_.debugMessages=w.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(w=>({path:w.path,data:w.data}))),{ok:b.allowed,summary:b.allowed?`Transaction committed (${f.length} write(s))`:"Transaction rolled back",data:v}}catch(b){if(b instanceof ld||b instanceof Ct||b instanceof xr||b instanceof Ln)return{ok:!1,summary:`Transaction failed: ${b.message}`,data:{allowed:!1,writes:[],error:{code:"invalid-argument",message:b.message}}};throw b}}}]}function WE(t){return AL({resolveSandbox:t.resolveSandbox,resolveModulesFn:EL})}function Fl(t){return t.replace(/^\/+|\/+$/g,"").split("/")}function QE(t){return Fl(t).length%2===0&&Fl(t).length>0}function dg(t){return Fl(t).length%2===1}function Bd(t){const e=Fl(t);return e[e.length-1]??""}function JE(t){return Fl(t).slice(0,-1).join("/")}function jL(t,e){const n=e!==void 0,r=n?fo(e):void 0;return{id:t.id,ref:t,exists:n,data:()=>n?r:void 0}}function $a(t,e){if(t.error)throw new sn(t.error);const n=t.debugMessages.length>0?t.debugMessages.join("; "):"(no debug message)";throw new sn(Pe("permission-denied",`${e}: ${n}`))}class fg{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=Bd(r),no(this,Bl("reference",r))}get parent(){return new Jm(this.env,this.auth,JE(this.path),this.bypassRules)}collection(e){return new Jm(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||$a(n,"get denied");const r=n.data===void 0||n.data===null?void 0:n.data;return jL(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||$a(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||$a(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||$a(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||$a(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||$a(n,"delete denied")}}const yS=new WeakMap;let kL=1;function gS(t){let e=yS.get(t);return e===void 0&&(e=kL++,yS.set(t,e)),e}function bS(t){if(t===null||typeof t=="boolean")return t;if(typeof t=="string")return LD(t);if(typeof t>"u")return{type:"undefined"};if(typeof t=="bigint")return Bl("bigint",t.toString());if(typeof t=="number"){const n=Number.isNaN(t)?"NaN":t===1/0?"Infinity":t===-1/0?"-Infinity":Object.is(t,-0)?"-0":String(t);return Bl("number",n)}if(typeof t!="object"&&typeof t!="function")return{type:typeof t,value:String(t)};const e=$D(t);if(e!==void 0)return e;try{if(Array.isArray(t))return{type:"array",id:gS(t)}}catch{}return{type:"opaque-object",id:gS(t)}}function CL(t){return typeof t.seconds=="number"&&(typeof t.nanos=="number"||typeof t.nanoseconds=="number")}function NL(t){return typeof t.latitude=="number"&&typeof t.longitude=="number"}function OL(t){return t.data instanceof Uint8Array}function RL(t){return typeof t.path=="string"}function hd(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 CL(n)?3:OL(n)?5:NL(n)?7:RL(n)?6:9}return 9}function vS(t){const e=typeof t.nanos=="number"?t.nanos:t.nanoseconds??0;return[t.seconds,e]}function TL(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 wS(t,e){return t<e?-1:t>e?1:0}function Xs(t,e){const n=hd(t),r=hd(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 TL(Number(t),Number(e));case 3:{const[s,o]=vS(t),[c,d]=vS(e);return s!==c?s<c?-1:1:o<d?-1:o>d?1:0}case 4:return wS(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 wS(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=Xs(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=Xs(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 DL(t,e,n){if(e<=0)return[];const r=[];for(const s of t)r.length<e?xS(r,s,n):n(s,r[r.length-1])<0&&(r.pop(),xS(r,s,n));return r}function xS(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 Ks="__name__",IL=new Set(["<","<=",">",">=","!=","not-in"]);function Wm(t,e){return e===Ks?{path:t.path}:t.data[e]}function hg(t){return t.kind==="where"?IL.has(t.op)?[t.field]:[]:t.filters.flatMap(hg)}function ML(t){return hg(t).length>0}function qd(t,e){return hd(t)===hd(e)}function LL(t,e){return qd(t,e)&&Xs(t,e)<0}function UL(t,e){return qd(t,e)&&Xs(t,e)<=0}function $L(t,e){return qd(t,e)&&Xs(t,e)>0}function BL(t,e){return qd(t,e)&&Xs(t,e)>=0}function qL(t,e,n){const r=t!==void 0;switch(e){case"==":return r&&Sr(t,n);case"!=":return r&&t!==null&&!Sr(t,n);case"<":return r&&LL(t,n);case"<=":return r&&UL(t,n);case">":return r&&$L(t,n);case">=":return r&&BL(t,n);case"in":return r&&Array.isArray(n)&&n.some(s=>Sr(t,s));case"not-in":return!Array.isArray(n)||n.some(s=>s===null)?!1:r&&t!==null&&!n.some(s=>Sr(t,s));case"array-contains":return Array.isArray(t)&&t.some(s=>Sr(s,n));case"array-contains-any":return Array.isArray(t)&&Array.isArray(n)&&n.some(s=>t.some(o=>Sr(o,s)))}}function FL(t,e){if(e===Ks){const n=t.path.split("/");return n[n.length-1]??t.path}return t.data[e]}function XE(t){if(Array.isArray(t))return t.map(XE);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=FL(t,e.field),r=e.field===Ks?XE(e.value):e.value;return qL(n,e.op,r)}return e.kind==="and"?e.filters.every(n=>Qm(t,n)):e.filters.some(n=>Qm(t,n))}function zL(t,e){return t.filter(n=>e.every(r=>Qm(n,r)))}function SS(t,e){const n=t.data();if(n===void 0)throw new sn({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===Ks?{path:t.ref.path}:n[r.field])}function _S(t,e,n){for(let r=0;r<e.length;r++){const s=Xs(Wm(t,n[r].field),e[r]);if(s!==0)return n[r].direction==="desc"?-s:s}return 0}function PL(t,e,n,r){return t.filter(s=>{if(n){const o=_S(s,n.values,e);if(n.inclusive?o<0:o<=0)return!1}if(r){const o=_S(s,r.values,e);if(r.inclusive?o>0:o>=0)return!1}return!0})}function eA(t,e){return t.filter(n=>e.every(r=>r.field===Ks||n.data[r.field]!==void 0))}function tA(t){return(e,n)=>{for(const r of t){const s=Xs(Wm(e,r.field),Wm(n,r.field));if(s!==0)return r.direction==="desc"?-s:s}return 0}}function VL(t,e){return e.length===0?t:eA(t,e).sort(tA(e))}class Fd{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:SS(e,this.normalizedOrders()),inclusive:n,fromSnapshot:!0}})}endCursorFromSnapshot(e,n){return this.clone({end:{values:SS(e,this.normalizedOrders()),inclusive:n,fromSnapshot:!0}})}clone(e){return new Fd(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,this.activityQuery());if(!r.allowed)throw new sn(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}}activityQuery(){const e=r=>r.kind==="where"?{kind:"where",field:r.field,op:r.op,value:bS(r.value)}:{kind:r.kind,filters:r.filters.map(e)},n=r=>r===void 0?null:{values:r.values.map(s=>bS(s)),inclusive:r.inclusive,fromSnapshot:r.fromSnapshot};return{scope:this.activityScope(),filters:this.clauses.map(e),orderBy:this.orders.map(r=>({...r})),limit:this.limitCount??null,limitFromEnd:this.limitFromEnd,start:n(this.start),end:n(this.end)}}activityScope(){return{kind:"collection"}}applyConstraints(e){let n=zL(e,[...this.clauses]);const r=this.normalizedOrders(),s=this.orders.length>0||this.start!==void 0||this.end!==void 0||this.clauses.some(ML);if(s&&this.limitCount!==void 0&&!this.limitFromEnd&&this.start===void 0&&this.end===void 0)return DL(eA(n,r),this.limitCount,tA(r));if(s&&(n=VL(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 sn({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=PL(n,r,this.start,this.end)}if(this.limitCount!==void 0)if(this.limitFromEnd){if(this.orders.length===0)throw new sn({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 hg(s))o!==Ks&&!n.has(o)&&(n.add(o),e.push({field:o,direction:r}));return n.has(Ks)||e.push({field:Ks,direction:r}),e}snapshotConstraints(){const e=n=>this.applyConstraints(n);return e.structured=this.structuredConstraints(),e.activityQuery=this.activityQuery(),e}async get(e){const r=this.applyConstraints(this.readCandidates(e)).map(s=>{const o=new fg(this.env,this.auth,s.path,this.bypassRules),c=fo(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]=GL(e[o],r);return{data:()=>s}}}function HL(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 GL(t,e){if(t.kind==="count")return e.length;let n=0,r=0;for(const s of e){const o=HL(s.data,t.field);typeof o=="number"&&Number.isFinite(o)&&(n+=o,r++)}return t.kind==="sum"?n:r===0?null:n/r}class pg extends Fd{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 pg(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))KL(s)===this.collectionId&&n.push({path:s,data:r[s]});return n}listRulePath(){return this.collectionId}activityScope(){return{kind:"collection-group"}}}function KL(t){const e=t.split("/").filter(n=>n.length>0);return e.length===0||e.length%2!==0?null:e[e.length-2]}class Jm extends Fd{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=Bd(s)}doc(n){const r=n??tg();return new fg(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 YL{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 sn(n.error);const r=n.results.find(o=>!o.allowed),s=(r==null?void 0:r.debugMessages.join("; "))??"batch denied";throw new sn(Pe("permission-denied",`batch failed: ${s}`))}}function ZL(t){return typeof t.where=="function"}class WL{constructor(e){G(this,"simTx");this.simTx=e}async get(e){if(ZL(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=fo(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 QL{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(!dg(e))throw new sn(Pe("invalid-argument",`collection path must have an odd number of segments: ${e}`));return new Jm(this.env,this.auth,e,this.bypassRules)}doc(e){if(!QE(e))throw new sn(Pe("invalid-argument",`document path must have an even number of segments: ${e}`));return new fg(this.env,this.auth,e,this.bypassRules)}collectionGroup(e){if(e.length===0||e.includes("/"))throw new sn(Pe("invalid-argument",`collection group id must be a single non-empty segment with no '/': ${e}`));return new pg(this.env,this.auth,e,[],[],void 0,!1,void 0,void 0,this.bypassRules)}batch(){return new YL(this.env,this.auth,this.bypassRules)}async runTransaction(e,n){let r;try{r=await this.env.transaction(s=>{const o=new WL(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 SE?new sn(s.simError):s}if(!r.allowed){if(r.error)throw new sn(r.error);const s=r.writes.find(c=>!c.allowed),o=(s==null?void 0:s.debugMessages.join("; "))??"transaction denied at commit";throw new sn(Pe("permission-denied",`transaction failed: ${o}`))}return r.returnValue}}function JL(t,e){return new QL(t,(e==null?void 0:e.auth)??null,(e==null?void 0:e.bypassRules)??!1,e==null?void 0:e.provenance)}const nA=Symbol("pyric/sandbox/context"),rA=Symbol("pyric/sandbox/bypassRules");let Xm=null;function XL(t){Xm=t}function eU(t){const e=t;return typeof e.path=="string"&&e.path.length>0||typeof e.collectionPath=="string"&&e.collectionPath.length>0}function tU(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 ES(t,e){if(!(t instanceof sn))return t;const n=t.code;if(n!=="permission-denied")return new nt(n,t.message);const r={auth:e.auth,reasons:tU(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}),s!=null&&s.query&&(r.query=s.query),(s==null?void 0:s.remediation)!==void 0?new nt({code:n,message:t.message,denialContext:r,remediation:s.remediation}):new nt(n,t.message,r)}function pd(t,e,n=!1){return new Proxy(t,{get(r,s,o){if(s===nA)return e;if(s===rA)return n;if(s==="onSnapshot"&&Xm!==null&&!(s in r)&&eU(r))return(...d)=>Xm(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,ql(e.operationContext),b))??b()}catch(b){throw ES(b,e)}return f instanceof Promise?f.then(b=>b&&typeof b=="object"?pd(b,e,n):b).catch(b=>{throw ES(b,e)}):f&&typeof f=="object"?pd(f,e,n):f}}})}function sA(t,e=!1){if(rg(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=()=>JL(Wt(t.sandbox),{auth:t.auth,bypassRules:e,provenance:ql(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 Wt(t.sandbox).deployRules(r)},seed(r){const s=Wt(t.sandbox);return s.seed({rules:s.getRules(),documents:(r==null?void 0:r.documents)??{}})},snapshot(){return Wt(t.sandbox).snapshot()}}}function ey(t){if(t instanceof nt)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 nt(e.code,e.message,n)}}return t}function ss(t){return new nt("invalid-argument",t)}async function fr(t,e){try{return await t.sandbox.channel.op({...e,actAs:t.lens})}catch(n){throw ey(n)}}const nU=new Set(["serverTimestamp","increment","arrayUnion","arrayRemove","deleteField"]);function rU(t){return t!==null&&typeof t=="object"&&typeof t.__type=="string"&&nU.has(t.__type)}function sU(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(os)};case"arrayRemove":return{__sentinel:"arrayRemove",values:t.values.map(os)};case"deleteField":return{__sentinel:"deleteField"}}}function os(t){var r;if(t===null||typeof t!="object")return t;if(rU(t))return sU(t);if(t instanceof $n)return t.toJSON();if(t instanceof Date)return $n.fromDate(t).toJSON();if(Array.isArray(t))return t.map(os);const e=Object.getPrototypeOf(t);if(e!==Object.prototype&&e!==null){const s=t.toJSON;if(typeof s=="function")return s.call(t);throw ss(`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]=os(o);return n}function zi(t){return os(t)}function ty(t){return Ud(JSON.parse(t.json))}function iA(t){return fo(ty(t))}function aA(t,e){const n=e.exists&&e.data?iA(e.data):void 0;return{id:t.id,ref:t,exists:e.exists,data:()=>n}}function oA(t,e){const n=e.docs.map(r=>{const s=r.path??r.id,o=md(t,s),c=r.data?iA(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 mg=Symbol("pyric/sandbox/admin-firestore/remoteSnapshotRegistrar");function iU(t){if(t===null||typeof t!="object")return;const e=t[mg];return typeof e=="function"?e:void 0}let ny=null;function aU(t){ny=t}function lA(...t){if(ny===null)throw new nt("failed-precondition","remote Firestore: onSnapshot is not wired yet — import pyric-admin/firestore (or pyric/sandbox/admin-firestore) before subscribing.");return ny(this,...t)}function cA(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(w=>({path:w.path??w.id,data:w.data?ty(w.data):{}})),b=e.__ref==="query"?e.source.__ref==="group"?e.source.collectionId:e.source.path:e.__ref==="group"?e.collectionId:e.path,v=Ha({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?ty(p.data):null;r(Va(g,b))}},f=>{const p=ey(f);s?s(p):console.error("pyric remote Firestore: uncaught onSnapshot error:",p)})}catch(f){throw ey(f)}return d}const uA=Symbol("pyric/sandbox/admin-firestore/remoteQueryState");function oU(t){if(!(t===null||typeof t!="object"))return t[uA]}function dA(t){return t.kind==="where"?(fA(t.op),{kind:"where",field:t.field,op:t.op,value:os(t.value)}):{kind:t.kind,filters:t.filters.map(dA)}}const lU=new Set(["<","<=","==","!=",">=",">","in","not-in","array-contains","array-contains-any"]);function fA(t){if(!lU.has(t))throw ss(`invalid where operator: ${String(t)}`)}function Bu(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(os)}),t.end&&e.push({kind:t.end.inclusive?"endAt":"endBefore",values:t.end.values.map(os)}),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 AS(t,e,n){if(e.length===0)throw ss(`${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 ss(`${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 nt("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 yg(t,e){const n=s=>yg(t,{...e,...s});return{[uA]:e,where(s,o,c){return fA(o),n({filters:[...e.filters,{kind:"where",field:s,op:o,value:os(c)}]})},applyFilter(s){return n({filters:[...e.filters,dA(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:AS(s,e.orders,o?"startAt":"startAfter"),inclusive:o}})},endCursorFromSnapshot(s,o){return n({end:{values:AS(s,e.orders,o?"endAt":"endBefore"),inclusive:o}})},async get(s){qu(e);const o=await fr(t,{method:"getDocs",source:Bu(e)});return oA(t,o)},async aggregate(s){qu(e);const o=await fr(t,{method:"aggregate",source:Bu(e),spec:s});return{data:()=>o.data}},[mg]:(s,o,c)=>(qu(e),cA(t,Bu(e),s,o,c)),onSnapshot:lA}}function qu(t){if(t.limitFromEnd&&t.orders.length===0)throw ss("limitToLast() queries require at least one orderBy clause.")}function ry(t,e){const n=yg(t,{source:{__ref:"collection",path:e},filters:[],orders:[],limitFromEnd:!1});return Object.assign(Object.create(Object.getPrototypeOf(n)),n,{id:Bd(e),path:e,doc(s){const o=s??tg();return md(t,`${e}/${o}`)},async add(s,o){const c=await fr(t,{method:"addDoc",collectionPath:e,data:zi(s)});return md(t,c.path)}})}function md(t,e){const n={id:Bd(e),path:e,get parent(){return ry(t,JE(e))},collection(r){const s=`${e}/${r}`;if(!dg(s))throw ss(`collection path must have an odd number of segments: ${s}`);return ry(t,s)},async get(r){const s=await fr(t,{method:"getDoc",path:e});return aA(n,s)},async set(r,s){await fr(t,{method:"setDoc",path:e,data:zi(r),...jS(s)?{options:jS(s)}:{}})},async update(r,s){await fr(t,{method:"updateDoc",path:e,data:zi(r)})},async delete(r){await fr(t,{method:"deleteDoc",path:e})},[mg]:(r,s,o)=>cA(t,{__ref:"doc",path:e},r,s,o),onSnapshot:lA};return n}function jS(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 cU(t){const e=[];let n=!1;const r={set(o,c){return s(),e.push({method:"set",path:o.path,data:zi(c)}),r},update(o,c){return s(),e.push({method:"update",path:o.path,data:zi(c)}),r},delete(o){return s(),e.push({method:"delete",path:o.path}),r},async commit(o){s(),n=!0,await fr(t,{method:"batchCommit",writes:e})}};function s(){if(n)throw new nt("failed-precondition","WriteBatch has already been committed.")}return r}const kS=5;async function uU(t,e){for(let n=0;n<kS;n++){const r=[],s=[],o=()=>{if(s.length>0)throw new nt("failed-precondition",Lm)},c={get(g){o();const b=oU(g);return b!==void 0?f(b):d(g)},set(g,b){return s.push({method:"set",path:g.path,data:zi(b)}),c},update(g,b){return s.push({method:"update",path:g.path,data:zi(b)}),c},delete(g){return s.push({method:"delete",path:g.path}),c}};async function d(g){const b=await fr(t,{method:"getDoc",path:g.path});return r.push({path:b.path??g.path,data:b.exists&&b.data?b.data:null}),aA(g,b)}async function f(g){qu(g);const b=await fr(t,{method:"getDocs",source:Bu(g)});for(const v of b.docs)r.push({path:v.path??v.id,data:v.data??null});return oA(t,b)}const p=await e(c);try{return await fr(t,{method:"txnCommit",reads:r,writes:s}),p}catch(g){if(g instanceof nt&&g.code==="aborted")continue;throw g}}throw new nt("aborted",`Transaction failed after ${kS} attempts due to repeated conflicts. Another writer is concurrently updating the same documents.`)}function Yp(t,e){return new nt("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 hA(t,e){const n={sandbox:t,lens:e};return{collection(r){if(!dg(r))throw ss(`collection path must have an odd number of segments: ${r}`);return ry(n,r)},doc(r){if(!QE(r))throw ss(`document path must have an even number of segments: ${r}`);return md(n,r)},collectionGroup(r){if(r.length===0||r.includes("/"))throw ss(`collection group id must be a single non-empty segment with no '/': ${r}`);return yg(n,{source:{__ref:"group",collectionId:r},filters:[],orders:[],limitFromEnd:!1})},batch(){return cU(n)},runTransaction(r,s){return uU(n,r)},setRules(){throw Yp("setRules","Deploy rules asynchronously through the relay instead: `await sandbox.channel.op({ method: 'setFirestoreRules', source })`.")},seed(){throw Yp("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 Yp("snapshot","Read the worker state asynchronously instead: `await sandbox.channel.op({ method: 'admin.readState' })`.")}}}const CS=new WeakMap;function pA(t){const e=CS.get(t);if(e)return e;const n=rg(t.sandbox)?hA(t.sandbox,dU(t.auth)):pd(sA(t),t);return CS.set(t,n),n}function dU(t){return t==null?{mode:"anon"}:t.token===void 0?{mode:"as",uid:t.uid}:{mode:"as",uid:t.uid,token:t.token}}const NS=new WeakMap;function fU(t){const e=hU(t)?t:t.withAuth(null),n=NS.get(e);if(n)return n;const r=e.operationContext.authLens.mode==="admin"?e:Wl(e,{source:e.operationContext.source,authLens:{mode:"admin"},...e.operationContext.planId===void 0?{}:{planId:e.operationContext.planId}}),s=rg(r.sandbox)?hA(r.sandbox,{mode:"admin"}):pd(sA(r,!0),r,!0);return NS.set(e,s),s}function hU(t){return t!==null&&typeof t=="object"&&"sandbox"in t&&typeof t.withAuth=="function"}const Ya=Symbol("pyric/firestore/followsCurrentUser"),kl=Symbol("pyric/firestore/authSessionScope");function pU(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 mU(t){if(t!==null&&typeof t=="object"){const e=t.snapshotConstraints;if(typeof e=="function")return e.call(t)}}function yU(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 mA(t,e,n,r,s){var N,R;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 M=n;c=M.next,d=M.error}}else if(typeof e=="function")c=e,d=n;else if(typeof e=="object"&&e!==null){const M=e;c=M.next,d=M.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=iU(t);if(p){if(o[Ya]===!0)throw new nt("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=gU(t),b=Wt(g.sandbox);let v;if(yU(t))v={kind:"doc",path:t.path};else{const M=pU(t);if(M===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 F=mU(t);v={kind:"query",collection:M,constraints:F}}const w=o[Ya]===!0,_=o[kl],k=t[rA]===!0;if(Ya in o){const{[Ya]:M,...F}=o;o=F}if(kl in o){const{[kl]:M,...F}=o;o=F}const I=()=>b.addSnapshotListener(v,c??(()=>{}),o,g.auth,d,w,k,_);return((R=(N=g.sandbox).runWithProvenance)==null?void 0:R.call(N,ql(g.operationContext),I))??I()}function gU(t){if(t===null||typeof t!="object")throw new TypeError("onSnapshot: reference must be a DocumentReference or Query.");const e=t[nA];if(!e)throw new TypeError("onSnapshot: reference was not produced by a sandbox context — pass a ref obtained from `getFirestore(ctx)`.");return e}XL(mA);aU(mA);class Er{constructor(e){G(this,"bytes");this.bytes=e,no(this,UD(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 Er(r)}static fromUint8Array(e){return new Er(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 Er&&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 Er.fromBase64String(n.bytes)}}class Or{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.");no(this,Bl("geo-point",String(e),"\0",String(n)))}get latitude(){return this.lat}get longitude(){return this.lng}isEqual(e){return e instanceof Or&&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 Or(n.latitude,n.longitude)}}class Cl{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 Cl(e.slice())}toArray(){return this._values.slice()}isEqual(e){const n=e instanceof Cl?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 Cl.create(n.vectorValues)}}function bU(t=[]){return Cl.create(t)}function Yz(){return BD.serverTimestamp()}const Ys=Symbol("pyric/firestore/target");function ni(t){return t.kind==="sandbox"?t.db:t.getDb()}const zd=new WeakMap;function sy(t,e){return zd.set(t,e),t}const Qi=new WeakMap;function vU(t,e,n){return zd.set(t,e),Qi.set(t,n),t}function Pd(t,e){const n=Ji(e);if(t.kind==="sandbox")return n;const r=Qi.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(ni(t))}function wU(t,e){const n=Ji(e);if(t.kind==="sandbox")return n;const r=Qi.get(n);if(!r)throw new TypeError("pyric/firestore: live collection ref missing rebuild closure.");return r(ni(t))}function xU(t,e){const n=Ji(e);if(t.kind==="sandbox")return n;const r=Qi.get(n);if(!r)throw new TypeError("pyric/firestore: live query missing rebuild closure.");return r(ni(t))}function ao(t,e,n){return e.kind==="sandbox-live"?vU(t,e,n):sy(t,e)}function SU(t){const e=Ji(t),n=Qi.get(e);return n||(()=>e)}function Tr(t){var n;let e;if(Ys in t?e=t[Ys]:e=zd.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 yA=new WeakMap,yd=new WeakMap;function mo(t){return yA.get(t)}function Ji(t){return yd.get(t)??t}function gg(t,e,n){const r={id:t.id??"",path:t.path??""};return yA.set(r,n),yd.set(r,t),zd.set(r,e),r}function OS(t){return Array.isArray(t)&&t.every(e=>typeof e=="number")}function _U(t){if(t instanceof uo)return Array.from(t.value);if(t===null||typeof t!="object")return null;const e=t;return e.typeName==="vector"&&OS(e.value)||e.__type__==="__vector__"&&OS(e.value)?e.value:null}function iy(t){if(t instanceof In)return Er.fromUint8Array(t.data);if(t instanceof Cr)return new Or(t.lat,t.lng);const e=_U(t);if(e)return bU(e);if(Array.isArray(t))return t.map(iy);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]=iy(o);return r}}return t}function gA(t){if(t!==void 0)return iy(t)}function Vd(t){if(t===void 0)return Vd(HE());const e=sg(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=>{Wt(n).reevaluateLiveListeners(d,o)}));const c={kind:"sandbox-live",sandbox:n,getDb:RS(n,()=>r.currentUser),authScope:o,own:d=>e.onDelete(d),assertUsable:()=>{if(s)throw new Wi("failed-precondition","The client has already been terminated.")}};return{[Ys]:c,app:t}});if(bA(t)){const r={kind:"sandbox",db:pA(t),sandbox:t.sandbox};return{[Ys]:r}}if(EU(t)){const n={kind:"sandbox-live",sandbox:t,getDb:RS(t)};return{[Ys]: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 bg(t){const e=sg(t);if(e){e.assertAlive();const c=e.sandbox;return bg(Wl(c.withAuth(null),{source:{kind:"app"},authLens:{mode:"admin"}}))}const n=bA(t)?t:t.withAuth(null),r=n.sandbox,o={kind:"sandbox",db:fU(n),sandbox:r};return{[Ys]:o}}function bA(t){return t instanceof ho}function EU(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 RS(t,e=()=>t.currentUser){return()=>{const n=Wl(t.withAuth(e()),{source:{kind:"app"},authLens:{mode:"app-session"}});return pA(n)}}function gd(t){const e=t,n=e.data.bind(t);return Object.defineProperty(e,"data",{value:()=>gA(n()),configurable:!0,writable:!0}),t}function vA(t,e){return{id:t.id,exists:t.exists,data:()=>{if(!(typeof t.exists=="function"?t.exists():t.exists))return;const r=gA(t.data()),s={id:t.id,exists:!0,data:()=>r};return e.fromFirestore(s)}}}function Hd(t,e){if(!t||typeof t!="object")return t;const n=t;if(n.ref&&(sy(n.ref,e),TS(n.ref,e)),DS(n),Array.isArray(n.docs))for(const r of n.docs)r!=null&&r.ref&&(sy(r.ref,e),TS(r.ref,e)),r&&DS(r);return t}function TS(t,e){if(typeof t.path!="string"||t.path.length===0||yd.has(t))return;const n=t.path;try{const r=ni(e).doc(n);yd.set(t,r),e.kind==="sandbox-live"&&Qi.set(r,s=>s.doc(n))}catch{}}function DS(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 vg(t){const e=Tr(t),n=mo(t),r=await Pd(e,t).get();return n?vA(r,n):(Hd(r,e),gd(r))}async function zl(t){const e=Tr(t),n=mo(t),r=await xU(e,t).get();if(n){const o=n,c=r.docs.map(d=>vA(d,o));return{size:c.length,empty:c.length===0,docs:c}}Hd(r,e);const s=r.docs;for(const o of s)gd(o);return r}function ur(t,...e){const n=Tr(t),r=Ys in t,s=r?void 0:mo(t),o=ni(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 ao(b,n,w=>w.doc(g))}const c=Ji(t),d=e.length===0?c.doc():c.doc(e.join("/")),f=d.path,p=ao(d,n,g=>g.doc(f));return s?gg(p,n,s):p}function Ui(t,...e){const n=Tr(t),r=Ys in t;if(e.length===0)throw new TypeError("collection() requires at least one path segment.");if(r){const f=e.join("/"),p=ni(n).collection(f);return ao(p,n,g=>g.collection(f))}const s=Ji(t),o=e.join("/"),c=s.collection(o),d=c.path;return ao(c,n,f=>f.collection(d))}async function Pl(t,e,n){const r=Tr(t),s=mo(t),o=s?s.toFirestore(e):e;return Pd(r,t).set(o,n)}async function ay(t,e){const n=Tr(t);return Pd(n,t).update(e)}async function bd(t){const e=Tr(t);return Pd(e,t).delete()}async function wg(t,e){const n=Tr(t),r=mo(t),s=r?r.toFirestore(e):e,o=await wU(n,t).add(s),c=o.path,d=ao(o,n,f=>f.doc(c));return r?gg(d,n,r):d}function wA(t){return typeof t=="string"?t:t._internalPath.segments.join(".")}function Vl(t,...e){const n=Tr(t),r=mo(t),s=SU(t),o=f=>{let p=s(f);for(const g of e)p=g.applySandbox(p);return p},c=o(ni(n)),d=ao(c,n,f=>o(f));return r?gg(d,n,r):d}function AU(t,e,n){const r=wA(t);return{applySandbox:o=>o.where(r,e,n),_sandboxFilter:{kind:"where",field:r,op:e,value:n}}}function IS(t,e){const n=wA(t);return{applySandbox:r=>r.orderBy(n,e)}}function vd(t){return{applySandbox:e=>e.limit(t)}}function jU(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 kU(...t){if(jU(t)){const e=t[0];return{applySandbox:n=>n.startCursorFromSnapshot(e,!1)}}return{applySandbox:e=>e.startCursor(t,!1)}}function CU(t,e,n,r){const s=Tr(t),o=OU(s,t),c=RU(e,n,r,s),d=TU(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 w;p||(g(),(w=NU(d))==null||w(new Wi("aborted","The operation was aborted.")))},v=s.own(b);return()=>{v(),g()}}function NU(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 OU(t,e){const n=Ji(e);if(t.kind==="sandbox")return n;const r=Qi.get(n);if(!r)throw new TypeError("pyric/firestore: live ref missing rebuild closure for onSnapshot.");return r(ni(t))}function xA(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 RU(t,e,n,r){if(typeof t=="object"&&t!==null&&!xA(t)){const o=e;return typeof o=="function"?[t,MS(o,r),n??oy]:o&&typeof o=="object"?[t,LS(o,r)]:[t]}return typeof t=="function"?[MS(t,r),e??oy]:t&&typeof t=="object"?[LS(t,r)]:[t]}function TU(t,e){if(e.kind!=="sandbox-live")return t;const n=t[0];return typeof n=="object"&&n!==null&&!xA(n)?[{...n,[Ya]:!0,...e.authScope?{[kl]:e.authScope}:{}},...t.slice(1)]:[{[Ya]:!0,...e.authScope?{[kl]:e.authScope}:{}},...t]}function SA(t,e){if(!t||typeof t!="object")return t;const n=t;if(typeof n.data=="function"&&gd(t),Array.isArray(n.docs))for(const r of n.docs)gd(r);return t}function oy(t){console.error("pyric/firestore: Uncaught Error in snapshot listener:",t)}function MS(t,e){return n=>t(SA(Hd(n,e)))}function LS(t,e){return{...t,next:t.next?n=>t.next(SA(Hd(n,e))):void 0,error:t.error??oy}}function Zz(t,e){return Wt(t).deployRules(e)}function DU(t,e={}){const n=e.recentEventLimit??10,r=Wt(t),s=r.getRules(),o=s?Yu(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 I=k.split("/")[0]??"";I&&(p[I]=(p[I]??0)+1)}const g=t.history(),b=g.filter(k=>k.kind==="request"),v=b.filter(k=>k.result==="deny"),w=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:w}}}const Ls={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"]}]},IU=["<","<=","==","!=",">=",">","in","not-in","array-contains","array-contains-any"],MU={type:"object",properties:{field:{type:"string"},op:{type:"string",enum:[...IU]},value:{}},required:["field","op","value"]};function _A(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:Ls},required:["path"]},async execute(n){const r=n,s=await e(r.as),o=ur(s,r.path),c=await vg(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:Ls},required:["collection"]},async execute(n){const r=n,s=await e(r.as),o=Ui(s,r.collection),c=[];r.orderBy&&c.push(IS(r.orderBy)),r.limit&&c.push(vd(r.limit));const d=await zl(Vl(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:Ls},required:["path","data"]},async execute(n){const r=n,s=await e(r.as);return await Pl(ur(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:Ls},required:["collection","data"]},async execute(n){const r=n,s=await e(r.as),o=await wg(Ui(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:Ls},required:["path","data"]},async execute(n){const r=n,s=await e(r.as);return await ay(ur(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:Ls},required:["path"]},async execute(n){const r=n,s=await e(r.as);return await bd(ur(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:Ls},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=ur(s,o.path);o.op==="set"?await Pl(c,o.data??{}):o.op==="update"?await ay(c,o.data??{}):await bd(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:MU,minItems:1},orderBy:{type:"string"},limit:{type:"number"},as:Ls},required:["collection","where"]},async execute(n){const r=n,s=await e(r.as),o=Ui(s,r.collection),c=r.where.map(f=>AU(f.field,f.op,f.value));r.orderBy&&c.push(IS(r.orderBy)),r.limit&&c.push(vd(r.limit));const d=await zl(Vl(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 EA(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=DU(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 US(t,e){return{code:t.code,severity:e,message:t.message,path:t.path,origin:"validate"}}let Di=[],ly=!1,cy=!1,uy=!1,Zp;function LU(){if(Zp)return Zp;const t=Md();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"&&(uy=!0)},ident(e,n,r){const s=this.sourceString;s==="data"&&(ly=!0),s==="newData"&&(cy=!0)},bool_true(e){Di.push({code:"HARDCODED_TRUE",message:"Rule expression is hardcoded to true"})},bool_false(e){Di.push({code:"HARDCODED_FALSE",message:"Rule expression is hardcoded to false"})},Comparison_looseEq(e,n,r){Di.push({code:"LOOSE_EQUALITY",message:"Use '===' instead of '=='"}),e.lint(),r.lint()},Comparison_looseNeq(e,n,r){Di.push({code:"LOOSE_INEQUALITY",message:"Use '!==' instead of '!='"}),e.lint(),r.lint()}}),Zp=t,t}function UU(t,e="read"){const n=Id(t);return n.failed()?[]:(Di=[],ly=!1,cy=!1,uy=!1,LU()(n).lint(),e==="write"&&ly&&!cy&&!uy&&Di.push({code:"DATA_IN_WRITE",message:"Write rule references 'data' but not 'newData'; consider using 'newData' to check incoming data"}),[...Di])}const $U={read:new Set(["auth","data","root","now"]),write:new Set(["auth","data","newData","root","now"]),validate:new Set(["auth","data","newData","root","now"])},BU=new Set(["val","exists","hasChild","hasChildren","isString","isNumber","isBoolean","child","parent","getPriority"]),qU=new Set(["matches","contains","beginsWith","endsWith","replace","toLowerCase","toUpperCase","length"]),FU=new Set([...BU,...qU]);let Nl=[],Fu="read",AA=new Set,Wp;function zU(){if(Wp)return Wp;const t=Md();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;FU.has(d)||Nl.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=$U[Fu];c&&(!c.has(s)&&!AA.has(s)&&Nl.push({code:"UNKNOWN_IDENTIFIER",message:`Identifier '${s}' is not allowed in '${Fu}' context`}),s==="newData"&&Fu==="read"&&Nl.push({code:"NEWDATA_IN_READ",message:"'newData' is not available in 'read' context"}))}}),Wp=t,t}function PU(t,e,n=[]){const r=Id(t);return r.failed()?[]:(Nl=[],Fu=e,AA=new Set(n.map(s=>s.startsWith("$")?s.slice(1):s)),zU()(r).validate(),[...Nl])}const VU=new Set(["__proto__","prototype","constructor"]);function $S(t,e){return VU.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 is{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 is(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 is(this._root,"/");return n==="/"?r:r.child(e.join("/"))}getPriority(){return null}}class HU{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 $s={auth:null,data:new is(null),newData:new is(null),root:new is(null),now:Date.now(),pathVariableBindings:{}},Qp;function GU(){if(Qp)return Qp;const t=Md();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 is)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 HU(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:$S(s,r.sourceString)},CallExpr_indexAccess(e,n,r,s){const o=e.eval(),c=r.eval();return o==null?null:$S(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 $s.pathVariableBindings)return $s.pathVariableBindings[s];switch(s){case"auth":return $s.auth;case"data":return $s.data;case"newData":return $s.newData;case"root":return $s.root;case"now":return $s.now;default:return}}}),Qp=t,t}function jA(t,e){const n=Id(t);if(n.failed())throw new Error(n.message??"RTDB expression failed to parse");return $s=e,GU()(n).eval()}const KU=Mn({operation:to(["read","write","validate"]),path:vn().min(1).startsWith("/"),auth:Dd([Mn({uid:vn(),token:Qs(rs())}),uE()]),mockData:Qs(rs()),newData:rs().optional(),updates:dE(Mn({path:vn().min(1).startsWith("/"),value:rs()})).optional()});to(["INVALID_INPUT","NO_MATCHING_RULE","EVALUATION_ERROR"]);Mn({allowed:$l(),unsupported:$l().optional(),matchedPath:vn(),matchedRule:vn(),reason:vn(),pathVariableBindings:Qs(vn())});function YU(t){const e=t.val();return e===null||typeof e!="object"?[]:Object.keys(e)}function ZU(t,e,n,r,s,o){let c=null;function d(p,g,b,v,w){if(!b.exists())return null;const _=p.validate;if(_){if(!_.parsed.valid)c||(c={node:p,rule:_,bindings:v,unsupported:!0});else if(!jA(_.raw,s(g,b,v)))return{node:p,rule:_,bindings:v}}for(const k of p.children){const I=k.path.split("/").filter(Boolean);if(I.length===0)continue;const N=I[I.length-1],R=N.startsWith("$");if(w.length>0){if(!R&&w[0]!==N)continue;return d(k,g.child(w[0]),b.child(w[0]),R?{...v,[N]:w[0]}:v,w.slice(1))}if(R)for(const M of YU(b)){const F=d(k,g.child(M),b.child(M),{...v,[N]:M},[]);if(F)return F}else{const M=d(k,g.child(N),b.child(N),v,[]);if(M)return M}}return null}return d(t,e,n,r,o)??c}function kA(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=kA(o,e.slice(1),p,r+1);return s.push(...g),s}}return s}function dy(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=dy(c,s,n);return d==null?delete o[r]:o[r]=d,o}function WU(t,e,n,r){if(!r||r.length===0)return dy(t,e,n??null);let s=t;for(const o of r){const c=o.path.split("/").filter(Boolean);s=dy(s,c,o.value??null)}return s}class QU{execute(e,n){const r=KU.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=kA(b,g,{}),w=new is(d,"/"),_=s==="read"?d:WU(d,g,f,p),k=new is(_,"/"),I=(F,D,C)=>{const L={};for(const[U,H]of Object.entries(C))L[U]=H,L[U.slice(1)]=H;return{auth:c?{uid:c.uid,token:c.token}:null,data:F,newData:D,root:w,now:Date.now(),pathVariableBindings:L}};let N;for(const F of v){const D=F.node[s];if(!D)continue;if(!D.parsed.valid){N||(N=F);continue}const C=g.slice(0,F.depth).join("/"),L=w.child(C),U=k.child(C);if(jA(D.raw,I(L,U,F.pathVariableBindings))){if(s==="write"){const z=ZU(b,w,k,{},I,g);if(z)return{success:!0,data:{allowed:!1,unsupported:z.unsupported===!0,matchedPath:z.node.path,matchedRule:z.rule.raw,reason:z.unsupported?`Validation rule at '${z.node.path}' contains an expression the simulator cannot evaluate: ${z.rule.raw} — not evaluated; production may reject this write.`:"Validation rule evaluated to false",pathVariableBindings:z.bindings}}}return{success:!0,data:{allowed:!0,matchedPath:F.node.path,matchedRule:D.raw,reason:"Rule expression evaluated to true",pathVariableBindings:F.pathVariableBindings}}}}if(N){const F=N.node[s];return{success:!0,data:{allowed:!1,unsupported:!0,matchedPath:N.node.path,matchedRule:F.raw,reason:`'${s}' rule at '${N.node.path}' contains an expression the simulator cannot evaluate: ${F.raw} — not evaluated; production may reject or allow this ${s}.`,pathVariableBindings:N.pathVariableBindings}}}const R=v[v.length-1],M=R.node[s];return M?{success:!0,data:{allowed:!1,matchedPath:R.node.path,matchedRule:M.raw,reason:"Rule expression evaluated to false",pathVariableBindings:R.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 JU=new Set([".read",".write",".validate",".indexOn"]);function CA(t,e,n=[]){const r=K2(t),s=r.valid?PU(t,e,n):r.errors,o=r.valid?UU(t,e):[];return{raw:t,parsed:{...r,errors:s,warnings:o}}}function NA(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]=CA(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(JU.has(o)||typeof c!="object"||c===null)continue;const d=e==="/"?`/${o}`:`${e}/${o}`,f=o.startsWith("$")?[...n,o]:[...n];r.children.push(NA(c,d,f))}return r}function OA(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 NA(e.rules,"/",[])}function Jp(t){return t==="true"?!0:t==="false"?!1:t}function RA(t){const e={};t.read&&(e[".read"]=Jp(t.read.raw)),t.write&&(e[".write"]=Jp(t.write.raw)),t.validate&&(e[".validate"]=Jp(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]]=RA(n)}return e}function XU(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:RA(t)}}function xg(t,e){return new QU().execute(t,e)}const ts=t=>t,BS=(...t)=>ts(t.map(e=>`(${e})`).join(" && ")),e$=(...t)=>ts(t.map(e=>`(${e})`).join(" || ")),TA=t=>t,t$=()=>TA("newData.hasChildren()"),n$=t=>TA(`newData.hasChild("${t}")`);function DA(t,e){const n=t.shape,r=[],s={};for(const[d,f]of Object.entries(n)){const p=f,g=p instanceof jr,b=g?p.unwrap():p;g||r.push(d);const v=IA(b,d),w=e==null?void 0:e[d];if(w&&w.length>0?s[d]={validate:BS(v,...w)}:s[d]={validate:v},b instanceof mt){const _=DA(b);s[d]={validate:_.validate,children:_.children}}}const o=[t$()];for(const d of r)o.push(n$(d));return{validate:BS(...o),children:s}}function IA(t,e){if(t instanceof _r)return ts("newData.isString()");if(t instanceof $i)return ts("newData.isNumber()");if(t instanceof Ju)return ts("newData.isBoolean()");if(t instanceof Ws){const n=t.options;return ts(n.map(r=>`newData.val() === "${r}"`).join(" || "))}if(t instanceof Ul){const n=t.value;return ts(typeof n=="string"?`newData.val() === "${n}"`:`newData.val() === ${n}`)}if(t instanceof Ml){const n=t._def.options;return e$(...n.map(r=>IA(r,e)))}if(t instanceof mt)return ts("newData.hasChildren()");throw new Error(`Unsupported Zod type for RTDB rules: ${t.constructor.name} on field "${e}"`)}function r$(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=MA(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!=="/"&&s$(r,s);for(const[s,o]of n){const c=s==="/"?r:Sg(r,s);c&&i$(r,c,o,s)}return r}function s$(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 i$(t,e,n,r){const s=r.split("/").filter(o=>o.startsWith("$"));if(n.read&&(e.read=Ba(n.read,"read",s)),n.write&&(e.write=Ba(n.write,"write",s)),n.validate&&(e.validate=Ba(n.validate,"validate",s)),n.schema){const o=DA(n.schema,n.fieldConstraints);e.validate||(e.validate=Ba(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=Ba(d.validate,"validate",s),"children"in d&&d.children)for(const[g,b]of Object.entries(d.children)){const v=`${f}/${g}`;let w=p.children.find(_=>_.path===v);w||(w={path:v,pathVariables:s,children:[]},p.children.push(w)),w.validate=Ba(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=Sg(t,d);f&&(f.indexOn=n.indexOn)}}}function MA(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(...MA(c))}}return e}function Ba(t,e,n){return CA(String(t),e,n)}function Sg(t,e){if(t.path===e)return t;for(const n of t.children){const r=Sg(n,e);if(r)return r}return null}function a$(t){return t==null?null:typeof t=="string"?{uid:t,token:{}}:{uid:t.uid,token:t.token??{}}}function o$(t){return{operation:t.operation,path:t.path,auth:a$(t.auth),mockData:t.mockData??t.data??{},...t.newData!==void 0?{newData:t.newData}:{}}}function Xp(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 fy(t,e){const n=[...Xp(t.path,".read",t.read,e),...Xp(t.path,".write",t.write,e),...Xp(t.path,".validate",t.validate,e)];for(const r of t.children)n.push(...fy(r,e));return n}class l${constructor(e){G(this,"definition");this.definition=e}compile(){return r$(this.definition.paths)}toJSON(){return XU(this.compile())}check(){try{const e=this.compile(),n=fy(e,"errors"),r=fy(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 xg(this.compile(),o$(e))}}function c$(t){return new l$(t)}function u$(t){const e=t;return typeof e.toJSON=="function"&&typeof e.simulate=="function"&&typeof e.check=="function"}function d$(t){const e=t;return typeof e=="object"&&e!==null&&"rules"in e&&!("paths"in e)&&typeof e.toJSON!="function"}class em{constructor(e){G(this,"doc");this.doc=e}lint(){const e=this.doc.check();return[...e.errors.map(n=>US(n,"error")),...e.warnings.map(n=>US(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 f$(t){return t==null?null:typeof t=="string"?{uid:t,token:{}}:{uid:t.uid,token:t.token??{}}}class h${constructor(e){G(this,"json");G(this,"compiled");this.json=e,this.compiled=OA(e)}toJSON(){return this.json}compile(){return this.compiled}check(){return{ok:!0,errors:[],warnings:[]}}simulate(e){return xg(this.compiled,{operation:e.operation,path:e.path,auth:f$(e.auth),mockData:e.mockData??e.data??{},...e.newData!==void 0?{newData:e.newData}:{}})}}function p$(t){return u$(t)?new em(t):d$(t)?new em(new h$(t)):new em(c$(t))}const m$=new Set(["__proto__","prototype","constructor"]);function et(t){if(t===""||t==="/")return[];const e=t.split("/").filter(n=>n.length>0);for(const n of e)if(m$.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 rn(t){return t.length===0?"/":"/"+t.join("/")}function Ps(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(n=>Ps(n));const e={};for(const[n,r]of Object.entries(t))e[n]=Ps(r);return e}function qS(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Qa(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)=>Qa(s,e[o]));if(!qS(t)||!qS(e))return!1;const n=Object.keys(t),r=Object.keys(e);return n.length!==r.length?!1:n.every(s=>s in e&&Qa(t[s],e[s]))}class y${constructor(){G(this,"root",{})}snapshot(){return Ps(this.root)}restore(e){this.root=Ps(e)}read(e){const n=et(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 Ps(r)}write(e,n){const r=et(e),s=this.read(e);if(r.length===0)return n===null?(this.root={},s):(this.root=Ps(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]=Ps(n),s}multiUpdate(e){const r=Object.entries(e).map(([o,c])=>({path:rn(et(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=et(e);for(const[o,c]of Object.entries(n)){const d=[...s,...et(o)],f=rn(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 FS="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz";let zS=0;const Ai=new Array(12).fill(0);function g$(t=Date.now()){const e=t===zS;zS=t;const n=new Array(8);let r=t;for(let o=7;o>=0;o--)n[o]=FS.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&&Ai[o]===63;o--)Ai[o]=0;if(o<0)for(let c=0;c<12;c++)Ai[c]=Math.floor(Math.random()*64);else Ai[o]=(Ai[o]??0)+1}else for(let o=0;o<12;o++)Ai[o]=Math.floor(Math.random()*64);for(let o=0;o<12;o++)s+=FS.charAt(Ai[o]);if(s.length!==20)throw new Error(`RTDB push-id: bad length ${s.length}.`);return s}function b$(t){return t===null||typeof t!="object"?!1:t[".sv"]==="timestamp"}function v$(t){if(t===null||typeof t!="object")return!1;const e=t[".sv"];return e!==null&&typeof e=="object"&&typeof e.increment=="number"}function vr(t,e,n){if(b$(t))return e;if(v$(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)=>vr(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]=vr(c,e,r?r[o]:void 0);return s}function ji(){const t=new Error("PERMISSION_DENIED: Permission denied");return t.code="PERMISSION_DENIED",t}class w${constructor(){G(this,"compiled",null)}setRules(e){if(e===null){this.compiled=null;return}this.compiled=OA(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=xg(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 LA(t,e){if(t===e)return 0;if(t===null)return-1;if(e===null)return 1;const n=PS(t),r=PS(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 PS(t){return t===null?0:typeof t=="boolean"?1:typeof t=="number"?2:typeof t=="string"?3:4}const x$=/^-?(0*)\d{1,10}$/,S$=-2147483648,_$=2147483647;function VS(t){if(x$.test(t)){const e=Number(t);if(e>=S$&&e<=_$)return e}return null}function wd(t,e){if(t===e)return 0;const n=VS(t),r=VS(e);return n!==null?r!==null?n-r===0?t.length-e.length:n-r:-1:r!==null?1:t<e?-1:1}function hy(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 qa(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 wd(o.key,c.key);const d=hy(e.orderBy,o.key,o.value),f=hy(e.orderBy,c.key,c.value),p=LA(d,f);return p!==0?p:wd(o.key,c.key)});for(const o of e.bounds)r=r.filter(c=>E$(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 E$(t,e,n){const s=(n??{kind:"key"}).kind==="key"?wd(e.key,String(t.value)):LA(hy(n,e.key,e.value),t.value),o=c=>wd(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 A$=/[\[\].#$/\u0000-\u001F\u007F]/;function j$(t){return t.length!==0&&!A$.test(t)}function k$(t){return typeof t=="number"&&(Number.isNaN(t)||t===1/0||t===-1/0)}function C$(t){return t===".priority"||t===".value"||t===".sv"}function N$(t,e){py(t,e,"set")}function py(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(k$(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&&py(s,`${e}/${r}`,n)}return}for(const[r,s]of Object.entries(t)){if(!C$(r)&&!j$(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 "]"`);py(s,`${e}/${r}`,n)}}}function Us(t,e){return N$(t,e),my(t)}function my(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=my(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=my(r);s!==null&&(e[n]=s)}return Object.keys(e).length===0?null:e}function zu(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(c=>zu(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:zu(f)}return c}const o={};for(const[c,d]of Object.entries(e))o[c]=zu(d);return o}function Jr(t){return t==="unsupported"?"unsupported":"deny"}class O${constructor(e){G(this,"tree",new y$);G(this,"rules",new w$);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{Vs(this.sandbox,$d({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{Vs(this.sandbox,FE({service:"rtdb",method:n,path:br(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{Vs(this.sandbox,CI({service:"rtdb",method:n,path:br(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{Vs(this.sandbox,NI({service:"rtdb",phase:e,listenerId:n.id,target:{kind:s.event??"value",path:br(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=Us(vr(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=qa(this.tree.read(e),n);return this.emitOperation(null,"get",e,"not-applicable",void 0,{origin:"admin",request:{query:n},resourceBefore:{data:Au(r),exists:r.length>0}}),r}adminSet(e,n){const r=Date.now(),s=this.tree.read(e),o=Us(vr(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,w]of Object.entries(n)){const _=rn([...et(e),...et(v)]);g[_]=Us(vr(w,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=rn([...et(e),...et(g)]);f.push(v),d[g]=Us(vr(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,Jr(o.check),o,{at:r,durationMs:Date.now()-r,resourceBefore:{data:s,exists:s!==null}}),ji();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=vr(r,o,this.tree.read(n)),d=Us(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,Jr(g.check),g,{at:p,durationMs:Date.now()-p,request:{data:r,resourceData:r},resourceBefore:b,resourceAfter:v}),ji();this.emitOperation(e,s,n,"allow",g,{at:p,durationMs:Date.now()-p,request:{data:r,resourceData:r},resourceBefore:b,resourceAfter:v});const w=this.snapshotChildListenerParents();this.tree.write(n,d),this.fanOut([n]),this.fanOutChildren(w);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,br(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(w=>w.includes("/"))){const w=this.nextGroupId("update"),_={};for(const[F,D]of Object.entries(r)){const C=[...et(n),...et(F)],L=rn(C);_[L]=Us(vr(D,s,this.tree.read(L)),L)}const k=this.tree.snapshot(),I=Object.entries(_).map(([F,D])=>({path:F,value:D}));for(const[F,D]of Object.entries(_)){const C=Date.now(),L=this.tree.read(F),U=this.rules.evaluate("write",F,{auth:e,mockData:k,newData:D,updates:I}),H={at:C,durationMs:Date.now()-C,origin:"batch",request:{data:D,resourceData:D},resourceBefore:{data:L,exists:L!==null},resourceAfter:{data:D,exists:D!==null},groupId:w,groupKind:"batch",detail:{multiPath:!0,rootPath:br(n)}};if(U.check!=="allow")throw this.emitOperation(e,"update",F,Jr(U.check),U,H),ji();this.emitOperation(e,"update",F,"allow",U,H)}const N=this.tree.read(n),R=this.snapshotChildListenerParents();this.tree.multiUpdate(_),this.fanOut(Object.keys(_)),this.fanOutChildren(R);const M=this.tree.read(n);this.emitCommit(e,"update",n,{data:r,priorState:N,nextState:M,groupId:w,groupKind:"batch",replay:{requestTime:s},detail:{multiPath:!0,paths:Object.keys(_)}}),this.emitRtdbEvent(e,"update",br(n),{after:_,detail:{multiPath:!0,paths:Object.keys(_)}}),this.notifyWrite();return}const c={};for(const[w,_]of Object.entries(r)){const k=rn([...et(n),...et(w)]);c[w]=Us(vr(_,s,this.tree.read(k)),k)}const d=this.tree.snapshot(),f=[],p=this.nextGroupId("update");for(const[w,_]of Object.entries(c)){const k=rn([...et(n),...et(w)]);f.push(k);const I=Date.now(),N=this.tree.read(k),R=this.rules.evaluate("write",k,{auth:e,mockData:d,newData:_}),M={at:I,durationMs:Date.now()-I,origin:"batch",request:{data:_,resourceData:_},resourceBefore:{data:N,exists:N!==null},resourceAfter:{data:_,exists:_!==null},groupId:p,groupKind:"batch",detail:{multiPath:!1,rootPath:br(n),key:w}};if(R.check!=="allow")throw this.emitOperation(e,"update",k,Jr(R.check),R,M),ji();this.emitOperation(e,"update",k,"allow",R,M)}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",br(n),{after:c,detail:{multiPath:!1,keys:Object.keys(c)}}),this.notifyWrite()}onValue(e,n,r,s){const o=Date.now(),c=this.rules.evaluate("read",n==="/"?"/":n,{auth:e,mockData:this.tree.snapshot()});if(c.check!=="allow")throw this.emitOperation(e,"listen",n,Jr(c.check),c,{at:o,durationMs:Date.now()-o,request:s?{query:s}:void 0,origin:"listener"}),this.emitListener("errored",{id:this.nextListenerId(),path:n},e,{event:"value",result:"deny",error:{code:"PERMISSION_DENIED",message:"PERMISSION_DENIED: Permission denied",reasons:c.reasons}}),ji();return this.attachValueListener(e,n,r,s,{origin:"listener",result:"allow",evaluation:c,at:o})}adminOnValue(e,n,r){return this.attachValueListener(null,e,n,r,{origin:"admin",result:"not-applicable",evaluation:void 0,at:Date.now()})}attachValueListener(e,n,r,s,o){const{at:c}=o,d=this.nextListenerId();this.emitOperation(e,"listen",n,o.result,o.evaluation,{at:c,durationMs:Date.now()-c,request:s?{query:s}:void 0,origin:o.origin});const f={id:d,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=qa(this.tree.read(n),s);f.lastWindow=p;const g={val:Au(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,Jr(o.check),o,{at:s,durationMs:Date.now()-s,request:{query:r}}),ji();const c=qa(this.tree.read(n),r);return this.emitOperation(e,"get",n,"allow",o,{at:s,durationMs:Date.now()-s,request:{query:r},resourceBefore:{data:Au(c),exists:c.length>0}}),c}keyForPath(e){const n=et(e);return n.length===0?null:n[n.length-1]}makeSnap(e){const n=this.tree.read(e),r=n!==null,s=et(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=>rn(et(r)));for(const r of this.valueListeners){const s=rn(et(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=qa(this.tree.read(r.path),r.query);if(R$(r.lastWindow??[],f)){this.emitListener("suppressed",r,r.auth,{event:"value",reason:"no-op",detail:{query:!0}});continue}r.lastWindow=f;const p={val:Au(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&&Qa(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=et(n),d=c.length===0?null:c[c.length-1],f=this.tree.read(n),p=f===null?null:zu(Ps(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(),w=Us(vr(g,v,f),n==="/"?"":n);if(o){const I=this.tree.snapshot();this.tree.write(n,w),this.fanOut([n]);const N=Date.now(),R=this.rules.evaluate("write",n==="/"?"/":n,{auth:e,mockData:I,newData:w});if(R.check!=="allow")throw this.emitOperation(e,"transaction",n,Jr(R.check),R,{at:N,durationMs:Date.now()-N,origin:"transaction",request:{data:g,resourceData:g},resourceBefore:{data:f,exists:f!==null},resourceAfter:{data:w,exists:w!==null},groupId:b,groupKind:"transaction"}),this.tree.restore(I),this.fanOut([n]),HS();return this.emitOperation(e,"transaction",n,"allow",R,{at:N,durationMs:Date.now()-N,origin:"transaction",request:{data:g,resourceData:g},resourceBefore:{data:f,exists:f!==null},resourceAfter:{data:w,exists:w!==null},groupId:b,groupKind:"transaction"}),this.emitCommit(e,"transaction",n,{data:g,priorState:f,nextState:w,groupId:b,groupKind:"transaction",replay:{requestTime:v},detail:{committed:!0,applyLocally:!0}}),this.emitRtdbEvent(e,"transaction",br(n),{before:f,after:w,detail:{committed:!0}}),this.notifyWrite(),{committed:!0,val:w,key:d}}const _=Date.now(),k=this.rules.evaluate("write",n==="/"?"/":n,{auth:e,mockData:this.tree.snapshot(),newData:w});if(k.check!=="allow")throw this.emitOperation(e,"transaction",n,Jr(k.check),k,{at:_,durationMs:Date.now()-_,origin:"transaction",request:{data:g,resourceData:g},resourceBefore:{data:f,exists:f!==null},resourceAfter:{data:w,exists:w!==null},groupId:b,groupKind:"transaction"}),HS();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:w,exists:w!==null},groupId:b,groupKind:"transaction"}),this.tree.write(n,w),this.fanOut([n]),this.emitCommit(e,"transaction",n,{data:g,priorState:f,nextState:w,groupId:b,groupKind:"transaction",replay:{requestTime:v},detail:{committed:!0,applyLocally:!1}}),this.emitRtdbEvent(e,"transaction",br(n),{before:f,after:w,detail:{committed:!0}}),{committed:!0,val:w,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,Jr(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}}),ji();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=qa(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(w){this.emitListener("errored",p,e,{event:n,result:"error",error:{message:w instanceof Error?w.message:String(w)},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=rn(et(e));if(n===void 0||n==="value")for(const d of[...this.valueListeners])rn(et(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)&&rn(et(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=rn(et(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=rn(et(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)?Qa(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(w){this.emitListener("errored",g,g.auth,{event:g.event,result:"error",error:{message:w instanceof Error?w.message:String(w)}})}}}}}fanOutQueryChild(e){const n=e.lastWindow??[],r=qa(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)&&!Qa(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 g$()}listenerCount(){return this.valueListeners.size}childListenerCount(){return this.childListeners.size}}function br(t){return rn(et(t))}function HS(){return new Error("permission_denied")}function Au(t){if(t.length===0)return null;const e={};for(const{key:n,value:r}of t)e[n]=r;return e}function R$(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||!Qa(r.value,s.value))return!1}return!0}const GS=new WeakMap;function UA(t){let e=GS.get(t);if(e)return e;e=new O$(t),GS.set(t,e);const n=e;return t.registerPersistableService("rtdb",{snapshot:()=>n.exportTree(),restore:r=>{n.restoreTree(r)},subscribe:r=>n.subscribeWrites(r),reset:()=>{n.restoreTree(null)}}),e}function T$(t){return UA(t).getActiveRules()}function KS(t){return UA(t).snapshotState()}function D$(t,e){return t==="/"?`/${e}`:`${t}/${e}`}function YS(t){return t===null?"null":Array.isArray(t)?"array":typeof t}function I$(t){const e=(t??"/").split("/").filter(Boolean);return e.length===0?"/":`/${e.join("/")}`}function M$(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 $A(t,e,n,r,s){if(t===null||typeof t!="object"||Array.isArray(t))return{path:e,childCount:0,truncated:!1,children:[],schema:{},valueType:YS(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]=YS(v);const f=n>=r&&d.length>0,p=o.length>s,g=n>=r?[]:d.slice(0,s).map(([b,v])=>$A(v,D$(e,b),n+1,r,s));return{path:e,childCount:o.length,truncated:f||p,children:g,schema:c}}function L$(t,e={}){const n=I$(e.path),r=e.maxDepth??10,s=e.maxChildren??100;return $A(M$(t,n),n,0,r,s)}function BA(t){return t.children.reduce((e,n)=>e+1+BA(n),0)}function qA(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=T$(r);if(!s)return{ok:!1,summary:"No RTDB rules are loaded in the local sandbox.",data:{code:"NO_ACTIVE_RULES"}};const o=KS(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=p$(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=L$(KS(r),n);return{ok:!0,summary:`Crawled ${BA(s)} object paths from ${s.path}`,data:s}}}]}function U$(t){const e=Wt(t),n=r=>r&&r!=="admin"?Vd(t.withAuth({uid:r.uid,token:r.claims})):bg(t);return[...WE({resolveSandbox:()=>e}),..._A({resolveDb:n}),...EA({resolveSandbox:()=>t}),...qA({resolveSandbox:()=>t})]}function $$(t){const e=new Map(U$(t).map(n=>[n.name,n]));return async(n,r)=>{const s=e.get(n);if(!s)throw new F$(n);const o={signal:new AbortController().signal},c=await s.execute(r,o);return{ok:c.ok,summary:c.summary,data:c.data}}}const ZS=new WeakMap;async function B$(t,e,n){let r=ZS.get(t);return r||(r=$$(t),ZS.set(t,r)),r(e,n)}const q$=(()=>{const t=async()=>{throw new Error("SANDBOX_TOOL_NAMES: stub resolver should never be invoked")};return[...WE({resolveSandbox:t}),..._A({resolveDb:t}),...EA({resolveSandbox:t}),...qA({resolveSandbox:t})].map(e=>e.name)})();class F$ extends Error{constructor(n){super(`unknown sandbox tool: ${n}`);G(this,"tool");this.tool=n,this.name="UnknownToolError"}}const z$=500,P$=3e4,V$=2e3,H$=.5,G$=3;function K$(t,e={}){const n=Y$(e.url),r=e.sandboxId??Z$(),s=e.dispatcher??B$,o=e.toolNames??[...q$],c=e.initialReconnectDelayMs??z$,d=e.maxReconnectDelayMs??P$,f=e.noReconnect??!1,p=e.onStateChange??(()=>{}),g=e.standbyPollMs??V$,b=e.fetchImpl??($=>fetch($)),v=e.workerRelay??null;let w=null,_=!1,k=0,I=null,N=null,R=0,M={kind:"connecting"};const F=new Map;function D(){for(const $ of F.values())try{$()}catch{}F.clear()}function C($){M=$;try{p($)}catch{}}function L($){if(w&&w.readyState===WebSocket.OPEN)try{w.send(JSON.stringify($))}catch{}}function U(){if(_)return;C({kind:"connecting"});let $;try{$=new WebSocket(n)}catch(K){P(`failed to open WebSocket: ${K instanceof Error?K.message:String(K)}`);return}w=$,$.onopen=()=>{k=0;const K={type:"hello",protocol:1,tools:o,sandboxId:r,...v?{capabilities:[yL]}:{}};L(K)},$.onmessage=K=>{let W;try{W=JSON.parse(typeof K.data=="string"?K.data:"")}catch{return}if(gL(W)){if(W.type==="hello-ack"){C({kind:"connected",bridgeVersion:W.bridgeVersion});return}if(W.type==="tool-call"){H(W);return}if(W.type==="worker-op"){z(W);return}if(W.type==="worker-sub"){q(W);return}if(W.type==="worker-unsub"){const se=F.get(W.subId);if(se){F.delete(W.subId);try{se()}catch{}}return}if(W.type==="ping"){L({type:"pong",id:W.id});return}}},$.onclose=K=>{const W=K.reason||`closed (code ${K.code})`;if(w=null,D(),K.code===mL){E();return}P(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)}}}L(K)}async function z($){if(v)try{const K=await v.op($.op);pS(`op '${$.op.method}'`,K),L({type:"worker-res",id:$.id,ok:!0,value:K})}catch(K){const W=K.denialContext;L({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 q($){if(v&&!F.has($.subId))try{const K=v.subscribe($.sub,W=>{try{pS(`subscription '${$.subId}'`,W)}catch(se){L({type:"worker-snap",subId:$.subId,value:{__error:{code:se.code??"invalid-argument",message:se instanceof Error?se.message:String(se)}}});return}L({type:"worker-snap",subId:$.subId,value:W})});F.set($.subId,K)}catch(K){const W=K.denialContext;L({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 x(){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){C({kind:"disconnected",reason:"replaced by a newer sandbox peer"});return}k=0,R=0,C({kind:"standby"}),O()}}function O(){if(_)return;const $=g*(1+Math.random()*H$);N=setTimeout(()=>{N=null,T()},$)}async function T(){if(_)return;let $=null;for(const K of x())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){U();return}if($===!1){R=0,O();return}if(R+=1,R>=G$){P("standby health poll unreachable");return}O()}}function P($){if(_)return;if(f){C({kind:"disconnected",reason:$});return}k+=1;const K=Math.min(c*2**(k-1),d);C({kind:"reconnecting",attempt:k,delayMs:K}),I=setTimeout(()=>{I=null,U()},K)}return U(),{disconnect(){if(_=!0,D(),I&&(clearTimeout(I),I=null),N&&(clearTimeout(N),N=null),w){try{w.close()}catch{}w=null}C({kind:"disconnected",reason:"client closed"})},state(){return M}}}function Y$(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}:${fS}${hS}`}return`ws://localhost:${fS}${hS}`}function Z$(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`sb-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function W$(t,e){try{const n=new URL(t,e.href).pathname;return`${e.protocol==="https:"?"wss:":"ws:"}//${e.host}${n}`}catch{return t}}function Q$(t,e){return{url:e,dispatcher:(n,r,s)=>hM(t,r,s),workerRelay:{op:n=>pM(t,n),subscribe:(n,r)=>mM(t,n,r)}}}async function J$(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?W$(o,c):o,f=K$(null,{...Q$(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 X$={};function e3(){return!1}function t3(){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 n3(t,e={}){if(t==="local"){const n=e.baseUrl??"",r=e3(),s=e.persistence==="memory"||r?Pm():qI(n),o=e.disableLive?null:pL(e.workerUrl),c=o?t3():null;return o&&c&&J$(o.db,{baseUrl:n,onStateChange:d=>c.set(d)}),{mode:t,projects:r?PI():$I(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 FA=A.createContext(null);function r3(t){try{return{status:"ready",env:n3(t),error:null}}catch(e){return{status:"error",env:null,error:e instanceof Error?e:new Error(String(e))}}}function s3({mode:t="local",children:e}){const n=A.useMemo(()=>r3(t),[t]);return h.jsx(FA.Provider,{value:n,children:e})}function rr(){const t=A.useContext(FA);if(!t)throw new Error("useEnvironment must be used within an <EnvironmentProvider>");return t}const i3="pyric-studio:theme",Pu="dark";function a3(){return Pu}function o3(){typeof document>"u"||document.documentElement.setAttribute("data-theme","dark")}const l3=A.createContext(null);function c3({children:t}){const[e,n]=A.useState(a3);A.useEffect(()=>{o3();try{localStorage.setItem(i3,Pu)}catch{}},[e]);const r="dark",s=A.useCallback(d=>n(Pu),[]),o=A.useCallback(()=>n(Pu),[]),c=A.useMemo(()=>({choice:e,resolvedTheme:r,setChoice:s,cycleChoice:o}),[e,r,s,o]);return h.jsx(l3.Provider,{value:c,children:t})}function zA(){const t=typeof import.meta<"u"&&"/__pyric/ui/"||"/";return t.endsWith("/")?t:`${t}/`}function u3(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 _g(t,e="",n=zA()){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:u3(e)}}function d3(t,e=zA()){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 yy="pyric:studio:navigated",f3={tab:"",rest:[],query:{}};function PA(){return typeof window<"u"?window.location.pathname+window.location.search:""}function Rr(){return typeof window>"u"?f3:_g(window.location.pathname,window.location.search)}function h3(t){return t.tab==="home"?{...t,tab:""}:t}function Gd(t){return d3(h3(t))}function VA(){typeof window<"u"&&window.dispatchEvent(new Event(yy))}function Jn(t){if(typeof window>"u")return;const e=Gd(t);PA()!==e&&(window.history.pushState(null,"",e),VA())}function xd(t){typeof window>"u"||(window.history.replaceState(null,"",Gd(t)),VA())}function ec(t){return typeof window>"u"?()=>{}:(window.addEventListener("popstate",t),window.addEventListener(yy,t),()=>{window.removeEventListener("popstate",t),window.removeEventListener(yy,t)})}function p3(t,e){const n=A.useCallback(o=>t.includes(o)?o:e,[t,e]),r=A.useSyncExternalStore(ec,()=>n(Rr().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=_g(`/${f===-1?d:d.slice(0,f)}`,f===-1?"":d.slice(f),"/");if(t.includes(p.tab)){xd(p);return}}const c=Rr();c.tab!==""&&!t.includes(c.tab)&&xd({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 gy=null;function m3(t){gy=t}function y3(){return gy?(gy(),!0):!1}function g3(t){return(t.metaKey||t.ctrlKey)&&!t.altKey&&!t.shiftKey&&(t.key==="k"||t.key==="K")}const b3=[{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 v3({assuranceEnabled:t=!1}={}){return b3.filter(e=>e.id!=="assurance"||t)}const Pi=v3({assuranceEnabled:!1}),w3=Pi.map(t=>t.id);function x3(t){return Pi.find(e=>e.id===t)??Pi[0]}function S3(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 _3=7;function E3(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}},w=b.label.toLowerCase();if(w.startsWith(n.toLowerCase())?s.push(v):S3(n,b.label)&&o.push(v),p&&(w===d.toLowerCase()||w.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,_3)}function by(t){return`${t.kind}:${t.target.tab}:${(t.target.rest??[]).join("/")}`}const vy={docsPerCollection:50,collectionsScanned:20,users:100,objects:200,storageListCalls:20,subcollections:30,subcollectionRpcCalls:40};async function A3(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 j3(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 w=`${g}/${v}`;c.push(w);try{const _=await n(w,o);for(const k of _.slice(0,o))d.push(k),f.push(k)}catch{}}}return{subcollections:c,documents:d}}const k3=5;function Sd(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 C3={collection:"Firestore collections",document:"Firestore documents",subcollection:"Firestore subcollections",user:"Auth users",object:"Storage objects","rtdb-key":"RTDB keys"},N3=["collection","document","subcollection","user","object","rtdb-key"];function O3(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 HA(t){return t.endsWith("/")?{base:t.slice(0,-1),trailing:!0}:{base:t,trailing:!1}}function R3(t,e){const{base:n,trailing:r}=HA(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:Sd(s[c],o[c])}function T3(t,e){const{base:n,trailing:r}=HA(t);if(!n||n.includes("/"))return 0;const s=e.split("/").pop()??e;return r?s.toLowerCase()===n.toLowerCase()?850:0:Sd(n,s)}function WS(t,e,n,r=k3){const s=t.trim();if(!s)return[];const o=[],c=E3(t,e);c.length&&o.push({kind:"navigate",title:"Go to",results:c});for(const d of N3){const f=d==="document"||d==="subcollection",p=d==="collection"||d==="subcollection",g=new Map;for(const v of n)v.kind===d&&g.set(by(v),v);const b=[...g.values()].map(v=>({entry:v,score:Math.max(Sd(s,v.label),v.alt?Sd(s,v.alt):0,f?R3(s,v.label):0,p?T3(s,v.label):0)})).filter(v=>v.score>0).sort((v,w)=>w.score-v.score||v.entry.label.localeCompare(w.entry.label)).slice(0,r);b.length&&o.push({kind:d,title:C3[d],results:b.map(({entry:v})=>({id:by(v),label:v.label,hint:O3(v),target:v.target}))})}return o}function QS(t){return t.flatMap(e=>e.results)}function D3(t){return{kind:"collection",label:t,target:{tab:"firestore",rest:[t]}}}function JS(t){return{kind:"document",label:t,target:{tab:"firestore",rest:t.split("/").filter(Boolean)}}}function I3(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 M3(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 L3(t){return{kind:"object",label:t,target:{tab:"storage",rest:t.split("/").filter(Boolean)}}}function U3(t){return{kind:"rtdb-key",label:t,target:{tab:"rtdb",rest:[t]}}}async function $3(t,e={},n){const r={...vy,...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(D3));const b=[];if(t.listDocumentPaths)for(const w of g.slice(0,r.collectionsScanned))try{const k=(await t.listDocumentPaths(w,r.docsPerCollection)).slice(0,r.docsPerCollection);b.push(...k),o(k.map(JS))}catch{}if(t.listSubcollections&&t.listDocumentPaths)try{const{subcollections:w,documents:_}=await j3(b,t.listSubcollections,t.listDocumentPaths,{maxSubcollections:r.subcollections,maxRpcCalls:r.subcollectionRpcCalls,docsPerCollection:r.docsPerCollection});o(w.map(I3)),o(_.map(JS))}catch{}})(),d=(async()=>{if(t.listUsers)try{const g=await t.listUsers(r.users);o(g.slice(0,r.users).map(M3))}catch{}})(),f=(async()=>{if(t.listStorageObjectPaths)try{const g=await t.listStorageObjectPaths(r.objects);o(g.slice(0,r.objects).map(L3))}catch{}})(),p=(async()=>{if(t.listRtdbTopLevelKeys)try{o((await t.listRtdbTopLevelKeys()).map(U3))}catch{}})();return await Promise.allSettled([c,d,f,p]),s}const GA=Symbol("pyric/auth/target"),B3=Symbol("pyric.user.internal");function Fe(t,e){return new Wi(t,`Firebase: ${e} (${t}).`)}const KA={PASSWORD:"password"},tm={EMAIL_LINK:"emailLink",EMAIL_PASSWORD:"password"};class Kd{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"?q3(e):e;if(!n)return null;const r=n.providerId,s=n.signInMethod;if(typeof r!="string"||typeof s!="string")return null;if(r===KA.PASSWORD){const o=typeof n.email=="string"?n.email:"",c=typeof n.password=="string"?n.password:"";return new F3(o,c,s)}return new Kd(r,s)}}function q3(t){try{const e=JSON.parse(t);return typeof e=="object"&&e!==null?e:null}catch{return null}}class F3 extends Kd{constructor(n,r,s=tm.EMAIL_PASSWORD){super(KA.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===tm.EMAIL_PASSWORD?this.secret:null}get emailLink(){return this.signInMethod===tm.EMAIL_LINK?this.secret:null}toJSON(){return{providerId:this.providerId,signInMethod:this.signInMethod,email:this.email,password:this.secret}}}class Yd extends Kd{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 Eg(t,e){return e?new Yd(t,t):null}const qs=class qs{constructor(){G(this,"providerId",qs.PROVIDER_ID)}addScope(e){return this}setCustomParameters(e){return this}static credentialFromResult(e){return Eg(qs.PROVIDER_ID,e)}static credentialFromError(e){return null}static credential(e,n){return new Yd(qs.PROVIDER_ID,qs.GOOGLE_SIGN_IN_METHOD,{idToken:e??void 0,accessToken:n??void 0})}};G(qs,"PROVIDER_ID","google.com"),G(qs,"GOOGLE_SIGN_IN_METHOD","google.com");let wy=qs;const Fs=class Fs{constructor(){G(this,"providerId",Fs.PROVIDER_ID)}addScope(e){return this}setCustomParameters(e){return this}static credentialFromResult(e){return Eg(Fs.PROVIDER_ID,e)}static credentialFromError(e){return null}static credential(e){return new Yd(Fs.PROVIDER_ID,Fs.FACEBOOK_SIGN_IN_METHOD,{accessToken:e})}};G(Fs,"PROVIDER_ID","facebook.com"),G(Fs,"FACEBOOK_SIGN_IN_METHOD","facebook.com");let xy=Fs;const zs=class zs{constructor(){G(this,"providerId",zs.PROVIDER_ID)}addScope(e){return this}setCustomParameters(e){return this}static credentialFromResult(e){return Eg(zs.PROVIDER_ID,e)}static credentialFromError(e){return null}static credential(e){return new Yd(zs.PROVIDER_ID,zs.GITHUB_SIGN_IN_METHOD,{accessToken:e})}};G(zs,"PROVIDER_ID","github.com"),G(zs,"GITHUB_SIGN_IN_METHOD","github.com");let Sy=zs;const YA=[wy.PROVIDER_ID,"apple.com",xy.PROVIDER_ID,Sy.PROVIDER_ID,"twitter.com","microsoft.com","yahoo.com"];function Ag(t,e=!1){var r;const n=t[GA];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 z3{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 P3(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 ki(t){if(typeof t!="string"||t.length===0)throw Fe("auth/invalid-email","Error");const e=t.indexOf("@");if(e<=0||e===t.length-1)throw Fe("auth/invalid-email","Error")}function ml(t){if(typeof t!="string"||t.length<6)throw Fe("auth/weak-password","Password should be at least 6 characters")}function ZA(){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 V3="__pyric_no_password__";class WA{constructor(e,n=e,r=ZA(),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 z3);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{Vs(this.sandbox,$d({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 Fe("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??V3,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 Fe("auth/user-not-found",`restoreSession: no identity with uid ${e}.`);if(n.disabled)throw Fe("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){ml(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){ki(n);const r=this.requireByEmail(e),s=n.toLowerCase(),o=this.usersByEmail.get(s);if(o&&o.uid!==r.uid)throw Fe("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){ki(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 Fe("auth/user-not-found",`linkWithCredential: no identity with uid ${e}.`);if(s.providerUserInfo.some(c=>c.providerId===n))throw Fe("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){ki(o);const c=o.toLowerCase(),d=this.usersByEmail.get(c);if(d&&d.uid!==e)throw Fe("auth/email-already-in-use",`An account already exists for ${o}.`);r.password!==void 0&&r.password!==null&&(ml(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 Fe("auth/user-not-found",`unlink: no identity with uid ${e}.`);const s=r.providerUserInfo.findIndex(o=>o.providerId===n);if(s<0)throw Fe("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 Fe("auth/user-not-found",`No user found for ${e}.`);return n}createEmailPasswordUser(e,n){ki(e),ml(n);const r=e.toLowerCase();if(this.usersByEmail.has(r))throw Fe("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 Fe("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 Fe("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 Fe("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 Fe("auth/uid-already-exists",`createUser: a user with uid ${n} already exists.`);if(e.email!==void 0&&(ki(e.email),this.usersByEmail.has(e.email.toLowerCase())))throw Fe("auth/email-already-in-use",`An account already exists for ${e.email}.`);if(e.password!==void 0&&(ml(e.password),e.email===void 0))throw Fe("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 Fe("auth/user-not-found",`No user found for uid ${e}.`);const s=this.toRecord(r);if(n.email!==void 0){ki(n.email);const c=n.email.toLowerCase(),d=this.usersByEmail.get(c);if(d&&d!==r)throw Fe("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&&(ml(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 Fe("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 Fe("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 Fe("auth/user-not-found",`mintSession: no identity with uid ${e.uid}.`);if(r.disabled)throw Fe("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=P3(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,B3,{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 Fe("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 Fe("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(ki(e),typeof n!="string"||n.length===0)throw Fe("auth/missing-password","A non-empty password must be provided");const r=this.findByEmail(e);if(!r)throw Fe("auth/user-not-found",`No user found for ${e}.`);if(r.disabled)throw Fe("auth/user-disabled","The user account has been disabled by an administrator.");if(r.password!==n)throw Fe("auth/wrong-password","Invalid password.");return r}}const XS=new WeakSet,ju=new WeakMap;function QA(t,e,n,r="[DEFAULT]"){return H3(t,e),G3(t,e,n,r)}function H3(t,e){XS.has(t)||(XS.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)},reset:()=>{e.clearUsers(),e.restoreProviderConfig(void 0)},subscribe:n=>{const r=e.subscribeUsers(n),s=e.subscribeProviderConfig(n);return()=>{r(),s()}}}))}function e_(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 G3(t,e,n,r){var p,g;let s=ju.get(t);s||(s=new Map,ju.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,e_(c)),()=>{var v,w;c.generation===b&&((v=c.unregisterService)==null||v.call(c),c.unregisterService=void 0,(w=c.unsubscribeBackend)==null||w.call(c),c.unsubscribeBackend=void 0,c.subscribers.clear(),s.get(o)===c&&s.delete(o),s.size===0&&ju.delete(t))}}const d={backend:e,session:n,subscribers:new Set,generation:1};s.set(o,d),d.unregisterService=t.registerPersistableService(o,e_(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&&ju.delete(t))}}async function Wz(t){const{backend:e}=Ag(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 K3(t){var n;const e=Ag(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 t_=new WeakMap,n_=new WeakMap,r_=new WeakMap;function JA(t){let e=n_.get(t);return e||(e=ZA(),n_.set(t,e)),e}function Y3(t){let e=t_.get(t);return e||(e=new WA(t,t,JA(t)),t_.set(t,e),QA(t,e,t)),e}function Z3(t,e){return e.service("auth/backend",()=>{const{sandbox:n,session:r}=e,s=new WA(n,r,JA(n),o=>{e.onDelete(o)});return e.onDelete(QA(n,s,r,t.name)),s})}function XA(t){if(t===void 0)return XA(HE());const e=sg(t);if(e)return e.service("auth/default",()=>{const n={kind:"sandbox",sandbox:e.sandbox,backend:Z3(t,e),own:r=>e.onDelete(r),assertAlive:()=>e.assertAlive()};return s_(n,t)});if(W3(t)){let n=r_.get(t);return n||(n=s_({kind:"sandbox",sandbox:t,backend:Y3(t)}),r_.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 W3(t){return typeof t=="object"&&t!==null&&typeof t.onCurrentUserChanged=="function"&&typeof t.withAuth=="function"}function s_(t,e){const n={[GA]:t,...e?{app:e}:{},signOut(){return K3(n)}};return Object.defineProperty(n,"currentUser",{enumerable:!0,get(){return t.backend.getCurrentUser()}})}function it(t){return Ag(t)}const lr={setUser(t,e){it(t).backend.setCurrentUser(e)},setAuthFlowResolver(t,e){it(t).backend.setResolver(e)},setAuthMailResolver(t,e){it(t).backend.setMailResolver(e)},takeAuthMail(t,e){return it(t).backend.takeMail(e)},listAuthMail(t){return it(t).backend.listMail()},mockActionCode(t,e,n){it(t).backend.stageActionCode(e,n)},listIdentities(t){return it(t).backend.listIdentities()},createSignInCredential(t,e){return it(t).backend.createSignInCredential(e)},mockSignInResult(t,e){const n=e.providerId;if(!n)throw new nt("invalid-argument","sandbox.mockSignInResult: result.providerId is required so the next signInWithPopup / signInWithCredential call can match.");it(t).backend.setMockResult(n,e)},seedUsers(t,e){it(t).backend.seedUsers(e)},exportUsers(t){return it(t).backend.exportUsers()},restoreSession(t,e){return it(t).backend.restoreSession(e)},mintSession(t,e){return it(t).backend.mintDetachedSession(e)},listUsers(t){return it(t).backend.listUsers()},createUser(t,e){return it(t).backend.createUser(e)},updateUser(t,e,n){return it(t).backend.updateUser(e,n)},updateProfile(t,e,n){return it(t).backend.updateProfileByUid(e,n)},deleteUser(t,e){it(t).backend.deleteUser(e)},clearUsers(t){it(t).backend.clearUsers()},subscribeUsers(t,e){return it(t).backend.subscribeUsers(e)},getAuthProviderConfig(t){return it(t).backend.listProviderConfig()},setAuthProviderConfig(t,e,n){it(t).backend.setProviderConfig(e,n)},assertAuthProviderEnabled(t,e){it(t).backend.assertProviderEnabled(e)},delegateProviderEnforcement(t,e){it(t).backend.setProviderEnforcementDelegated(e)},subscribeAuthProviderConfig(t,e){return it(t).backend.subscribeProviderConfig(e)}},_y="pyric-storage";function Q3(t){return t?`${_y}:${t}`:_y}const J3=1,wr="blobs",bn="metadata";function X3(t=_y){return t6(t).then(e=>new e6(e))}class e6{constructor(e){G(this,"db");this.db=e}async put(e,n,r){const s=this.db.transaction([wr,bn],"readwrite");s.objectStore(wr).put(n,e),s.objectStore(bn).put(r,e),await ku(s)}async getBlob(e){const n=this.db.transaction(wr,"readonly");return nm(n.objectStore(wr).get(e))}async getMetadata(e){const n=this.db.transaction(bn,"readonly");return nm(n.objectStore(bn).get(e))}async putMetadata(e,n){const r=this.db.transaction(bn,"readwrite");r.objectStore(bn).put(n,e),await ku(r)}async delete(e){const n=this.db.transaction([wr,bn],"readwrite");n.objectStore(wr).delete(e),n.objectStore(bn).delete(e),await ku(n)}async listByPrefix(e){const n=this.db.transaction(bn,"readonly"),r=IDBKeyRange.bound(e,e+"",!1,!1);return nm(n.objectStore(bn).getAll(r))}async reset(){const e=this.db.transaction([wr,bn],"readwrite");e.objectStore(wr).clear(),e.objectStore(bn).clear(),await ku(e)}close(){this.db.close()}}function t6(t){return new Promise((e,n)=>{const r=indexedDB.open(t,J3);r.addEventListener("upgradeneeded",()=>{const s=r.result;s.objectStoreNames.contains(wr)||s.createObjectStore(wr),s.objectStoreNames.contains(bn)||s.createObjectStore(bn)}),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 nm(t){return new Promise((e,n)=>{t.addEventListener("success",()=>e(t.result)),t.addEventListener("error",()=>n(t.error))})}function ku(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 i_(t){switch(t){case"read":return["get","list"];case"write":return["create","update","delete"];default:return[t]}}const n6=new Set(["&&","||","==","!=","<",">","<=",">=","+","-","*","/","%"]);function ej(t){return{segments:t.path.segments.map(r6),children:t.children.map(ej),allows:t.allows.map(e=>({verbs:e.operations,condition:at(e.condition)})),functions:t.functions.map(Ey)}}function r6(t){switch(t.type){case"literal":return{kind:"literal",value:t.value};case"wildcard":return{kind:"param",name:t.name};case"recursive":return{kind:"wildcard",name:t.name}}}function Ey(t){return{name:t.name,params:t.parameters,lets:t.lets.map(e=>({name:e.name,value:at(e.value)})),body:at(t.body)}}function at(t){switch(t.type){case"literal":return typeof t.value=="number"&&t.raw.includes(".")?{kind:"literal",value:new Ke(t.value)}:{kind:"literal",value:t.value};case"identifier":return{kind:"ident",name:t.name};case"memberAccess":return{kind:"member",target:at(t.object),name:t.property};case"methodCall":return{kind:"methodcall",target:at(t.object),method:t.method,args:t.args.map(at)};case"bracketAccess":return{kind:"index",target:at(t.object),index:at(t.index)};case"sliceAccess":return{kind:"slice",target:at(t.object),start:at(t.start),end:at(t.end)};case"binaryOp":if(!n6.has(t.op))throw new SyntaxError(`Unsupported binary operator '${t.op}' in storage rules.`);return{kind:"binary",op:t.op,left:at(t.left),right:at(t.right)};case"unaryOp":if(t.op!=="!"&&t.op!=="-")throw new SyntaxError(`Unsupported unary operator '${t.op}' in storage rules.`);return{kind:"unary",op:t.op,arg:at(t.operand)};case"ternary":return{kind:"ternary",cond:at(t.condition),then:at(t.consequent),else:at(t.alternate)};case"inExpr":return{kind:"in",element:at(t.element),collection:at(t.collection)};case"isExpr":return{kind:"is",value:at(t.value),typeName:t.typeName};case"listLiteral":return{kind:"list",elements:t.elements.map(at)};case"mapLiteral":return{kind:"map",entries:t.entries.map(e=>({key:at(e.key),value:at(e.value)}))};case"pathLiteral":return{kind:"path",segments:t.segments.map(e=>typeof e=="string"?{kind:"literal",value:e}:{kind:"interp",expr:at(e)})};case"functionCall":return{kind:"call",name:t.name,args:t.args.map(at)};default:{const e=t;throw new SyntaxError(`Unsupported expression construct: ${JSON.stringify(e)}`)}}}function tj(t){const e=Tl(t);if(!e.ok)throw new SyntaxError(`Storage rules parse error at line ${e.error.line}, column ${e.error.column}: expected ${e.error.expected}.`);const n=e.ast;if(n.service.name!=="firebase.storage")throw new SyntaxError(`Expected 'service firebase.storage', got 'service ${n.service.name}'.`);const r={segments:[],children:[ej(n.service.match)],allows:[],functions:[...(n.imports??[]).flatMap(s=>s.functions.map(o=>({name:o,params:[],lets:[],body:{kind:"literal",value:null},unresolvedImport:s.module}))),...(n.functions??[]).map(Ey),...(n.service.functions??[]).map(Ey)]};return nj(r,new Map),{_root:r}}function nj(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)nj(r,n)}function Zd(t){return t?{size:t.size,contentType:t.contentType,metadata:t.customMetadata,name:s6(t.fullPath,t.bucket),bucket:t.bucket,timeCreated:t.timeCreated,updated:t.updated,generation:a_(t.generation),metageneration:a_(t.metageneration)}:null}function s6(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 a_(t){if(t===void 0)return;const e=Number(t);return Number.isFinite(e)?e:void 0}function i6(t){return{size:t.size,contentType:t.contentType,metadata:t.customMetadata}}function rj(t,e,n=new Date,r){const s=n.getTime(),o=a6(e.request.path),c=[],d=new Set(i_(e.request.method));function f(g,b,v){const w=o6(g.segments,b,v);if(!w)return!1;const _=w.params,k=w.left;if(k.length===0)for(const I of g.allows){const N=new Set(I.verbs.flatMap(i_));if(![...d].some(F=>N.has(F)))continue;let M;try{const F=I.condition?Ie(I.condition,{input:e,now:s,params:_,locals:{},funcs:g.visibleFuncs??new Map,depth:0,firestoreLookup:r}):!0;if(ut(F)){c.push(`match ${rm(g.segments)} ${e.request.method}: ${F.message}`);continue}M=Ga(F)}catch(F){if(F instanceof $e){c.push(`match ${rm(g.segments)} ${e.request.method}: ${F.message}`);continue}throw F}if(M)return!0;c.push(`match ${rm(g.segments)} ${e.request.method}: condition false`)}for(const I of g.children)if(f(I,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 a6(t){return t.split("/").filter(e=>e.length>0)}function rm(t){return"/"+t.map(e=>e.kind==="literal"?e.value:e.kind==="param"?`{${e.name}}`:`{${e.name}=**}`).join("/")}function o6(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 Dn{constructor(e){G(this,"message");this.message=e}}function ut(t){return t instanceof Dn}function o_(t,e){const n=t[e];return n===void 0?new Dn(`Property ${e} is undefined on object.`):n}function Ga(t){return ut(t)?!1:t!==!1&&t!==null&&t!==void 0&&!(typeof t=="number"&&Number.isNaN(t))}class $e extends Error{}const l_=20;function Ie(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"?d6(e.input,e.now):t.name==="resource"?u6(e.input.resource):t.name in e.params?e.params[t.name]:void 0;case"member":{const n=Ie(t.target,e);return ut(n)?n:n==null?new Dn("Null value error."):o_(n,t.name)}case"index":{const n=Ie(t.target,e);if(ut(n))return n;if(n==null)return new Dn("Null value error.");const r=Ie(t.index,e);return ut(r)?r:o_(n,String(r))}case"call":return l6(t,e);case"methodcall":return f6(t,e);case"path":throw new $e("a Firestore path literal is only valid as an argument to firestore.get()/exists()");case"unary":{const n=Ie(t.arg,e);return ut(n)?n:t.op==="-"?n instanceof Ke?new Ke(-n.value):typeof n!="number"?new Dn(`Unary '-' applied to ${ns(n)}.`):-n:!Ga(n)}case"ternary":{const n=Ie(t.cond,e);return ut(n)?n:Ga(n)?Ie(t.then,e):Ie(t.else,e)}case"in":{const n=Ie(t.element,e);if(ut(n))return n;const r=Ie(t.collection,e);return ut(r)?r:Array.isArray(r)?r.some(s=>Ol(s,n)):r!==null&&typeof r=="object"?typeof n=="string"&&Object.prototype.hasOwnProperty.call(r,n):new Dn(`'in' applied to ${ns(r)} (expected a list or map).`)}case"is":{const n=Ie(t.value,e);return ut(n)?n:c6(n,t.typeName)}case"list":{const n=[];for(const r of t.elements){const s=Ie(r,e);if(ut(s))return s;n.push(s)}return n}case"map":{const n={};for(const r of t.entries){const s=Ie(r.key,e);if(ut(s))return s;if(typeof s!="string")return new Dn(`Map literal key is ${ns(s)} (expected a string).`);const o=Ie(r.value,e);if(ut(o))return o;n[s]=o}return n}case"slice":{const n=Ie(t.target,e);if(ut(n))return n;const r=Ie(t.start,e);if(ut(r))return r;const s=Ie(t.end,e);return ut(s)?s:typeof r!="number"||typeof s!="number"||!Number.isInteger(r)||!Number.isInteger(s)?new Dn("Slice bounds must be integers."):Array.isArray(n)||typeof n=="string"?r<0||s<r||s>n.length?new Dn(`Slice bounds [${r}:${s}] out of range for ${ns(n)} of size ${n.length}.`):n.slice(r,s):new Dn(`Slice applied to ${ns(n)} (expected a list or string).`)}case"binary":{if(t.op==="&&"){const s=Ie(t.left,e);return ut(s)?s:Ga(s)?Ie(t.right,e):s}if(t.op==="||"){const s=Ie(t.left,e);if(ut(s)){const o=Ie(t.right,e);return Ga(o)?o:s}return Ga(s)?s:Ie(t.right,e)}const n=Ie(t.left,e);if(ut(n))return n;const r=Ie(t.right,e);if(ut(r))return r;switch(t.op){case"==":return Ol(n,r);case"!=":return!Ol(n,r);case"<":return Cu(n,r)<0;case">":return Cu(n,r)>0;case"<=":return Cu(n,r)<=0;case">=":return Cu(n,r)>=0;case"+":return Ci(n,r,(s,o)=>s+o);case"-":return Ci(n,r,(s,o)=>s-o);case"*":return Ci(n,r,(s,o)=>s*o);case"/":return Za(n)||Za(r)?Ci(n,r,(s,o)=>s/o):ei(r)===0?new Dn("Division by zero."):Ci(n,r,(s,o)=>Math.trunc(s/o));case"%":return Za(n)||Za(r)?Ci(n,r,(s,o)=>s%o):ei(r)===0?new Dn("Modulo by zero."):Ci(n,r,(s,o)=>s%o)}}}}function l6(t,e){const n=e.funcs.get(t.name);if(!n)throw new $e(`undefined function ${t.name}()`);if(n.unresolvedImport!==void 0)throw new $e(`function ${t.name}() is imported from '${n.unresolvedImport}', but import module resolution is not implemented`);if(n.params.length!==t.args.length)throw new $e(`function ${t.name}() expects ${n.params.length} argument(s), got ${t.args.length}`);const r=e.depth+1;if(r>l_)throw new $e(`function ${t.name}() exceeded max call depth ${l_}`);const s=t.args.map(d=>Ie(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]=Ie(d.value,c);return Ie(n.body,c)}function c6(t,e){switch(e){case"string":return typeof t=="string";case"bool":return typeof t=="boolean";case"int":return typeof t=="number"&&Number.isInteger(t);case"float":return t instanceof Ke||typeof t=="number"&&!Number.isInteger(t);case"number":return t instanceof Ke||typeof t=="number";case"list":return Array.isArray(t);case"map":return t!==null&&typeof t=="object"&&!Array.isArray(t);default:return new Dn(`'is ${e}' is not supported by the storage evaluator.`)}}function ei(t){if(typeof t=="number")return t;if(t instanceof Ke)return t.value}function Za(t){return t instanceof Ke}function Cu(t,e){const n=ei(t),r=ei(e);return n!==void 0&&r!==void 0?n-r:typeof t=="string"&&typeof e=="string"?t<e?-1:t>e?1:0:Number.NaN}function Ci(t,e,n){const r=ei(t),s=ei(e);if(r===void 0||s===void 0)return;const o=n(r,s);return Za(t)||Za(e)?new Ke(o):o}function u6(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:c_(t.timeCreated),updated:c_(t.updated)}}function c_(t){if(t===void 0)return;const e=Date.parse(t);return Number.isNaN(e)?void 0:e}function d6(t,e){return{auth:t.request.auth,resource:t.request.resource??null,method:t.request.method,path:t.request.path,time:e}}function f6(t,e){if(t.target.kind==="ident"&&t.target.name==="timestamp"&&!(t.target.name in e.locals)&&!(t.target.name in e.params))return y6(t,e);if(t.target.kind==="ident"&&t.target.name==="duration"&&!(t.target.name in e.locals)&&!(t.target.name in e.params))return m6(t,e);if(t.target.kind==="ident"&&t.target.name==="firestore"&&!(t.target.name in e.locals)&&!(t.target.name in e.params))return h6(t,e);if(t.method==="matches")return g6(t,e);if(t.method==="split")return b6(t,e);if(t.method==="size")return v6(t,e);throw new $e(`unsupported method .${t.method}()`)}function h6(t,e){if(t.method!=="get"&&t.method!=="exists")throw new $e(`unsupported method firestore.${t.method}()`);if(!e.firestoreLookup)throw new $e(`firestore.${t.method}() is unsupported here — no Firestore lookup capability is configured`);if(t.args.length!==1)throw new $e(`firestore.${t.method}() expects a single path argument`);const n=t.args[0];if(n.kind!=="path")throw new $e(`firestore.${t.method}() requires a /databases/.../documents/... path literal`);const r=p6(n,e);if(t.method==="exists")return e.firestoreLookup.exists(r);const s=e.firestoreLookup.get(r);if(s===null)throw new $e(`firestore.get() targeted a nonexistent document: ${r}`);return{data:s}}function p6(t,e){const n=t.segments.map(s=>{if(s.kind==="literal")return s.value;const o=Ie(s.expr,e);if(typeof o=="string")return o;if(typeof o=="number")return String(o);throw new $e(`Firestore path interpolation resolved to ${ns(o)} (expected a string)`)});if(n.length<4||n[0]!=="databases"||n[2]!=="documents")throw new $e(`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 $e(`Firestore path does not point at a document (needs an even segment count): ${r.join("/")}`);return r.join("/")}const u_={w:10080*60*1e3,d:1440*60*1e3,h:3600*1e3,m:60*1e3,s:1e3,ms:1,ns:1e-6};function m6(t,e){if(t.method!=="value")throw new $e(`unsupported duration.${t.method}()`);const n=t.args.map(c=>Ie(c,e));if(n.length!==2||typeof n[0]!="number"||typeof n[1]!="string")throw new $e("duration.value() expects (magnitude: number, unit: string)");const[r,s]=n,o=u_[s];if(o===void 0)throw new $e(`duration.value() got unknown unit "${s}" — expected one of ${Object.keys(u_).join(", ")}`);return r*o}function y6(t,e){const n=t.args.map(r=>Ie(r,e));if(t.method==="value"){if(n.length!==1||typeof n[0]!="number")throw new $e("timestamp.value() expects (epochMillis: number)");return n[0]}if(t.method==="date"){if(n.length!==3||!n.every(c=>typeof c=="number"))throw new $e("timestamp.date() expects (year, month, day) numbers");const[r,s,o]=n;return Date.UTC(r,s-1,o)}throw new $e(`unsupported timestamp.${t.method}()`)}function g6(t,e){const n=Ie(t.target,e);if(ut(n))return n;if(typeof n!="string")throw new $e(`matches() requires a string target, got ${ns(n)}`);if(t.args.length!==1)throw new $e("matches() expects a single pattern argument");const r=Ie(t.args[0],e);if(typeof r!="string")throw new $e("matches() pattern must be a string");const s=/\\[1-9]/.test(r),o=/\(\?<?[=!]/.test(r);if(s||o)throw new $e(`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 $e(`matches() invalid regex pattern: ${d.message}`)}return c.test(n)}function b6(t,e){const n=Ie(t.target,e);if(ut(n))return n;if(typeof n!="string")throw new $e(`split() requires a string target, got ${ns(n)}`);if(t.args.length!==1)throw new $e("split() expects a single pattern argument");const r=Ie(t.args[0],e);if(typeof r!="string")throw new $e("split() pattern must be a string");const s=/\\[1-9]/.test(r),o=/\(\?<?[=!]/.test(r);if(s||o)throw new $e(`split() pattern uses an RE2-unsupported construct (${s?"backreference":"lookaround"}) that production would reject`);let c;try{c=new RegExp(r)}catch(d){throw new $e(`split() invalid regex pattern: ${d.message}`)}return n.split(c)}function v6(t,e){const n=Ie(t.target,e);if(ut(n))return n;if(t.args.length!==0)throw new $e("size() expects no arguments");if(typeof n=="string"||Array.isArray(n))return n.length;if(n!==null&&typeof n=="object")return Object.keys(n).length;throw new $e(`size() requires a string, list, or map target, got ${ns(n)}`)}function Ol(t,e){if(t===e)return!0;if(t==null||e==null)return t==null&&e==null;const n=ei(t),r=ei(e);if(n!==void 0&&r!==void 0)return n===r;if(Array.isArray(t)&&Array.isArray(e))return t.length===e.length&&t.every((s,o)=>Ol(s,e[o]));if(typeof t=="object"&&typeof e=="object"&&!Array.isArray(t)&&!Array.isArray(e)){const s=Object.keys(t),o=Object.keys(e);return s.length===o.length&&s.every(c=>Object.prototype.hasOwnProperty.call(e,c)&&Ol(t[c],e[c]))}return!1}function ns(t){return t===null?"null":t===void 0?"undefined":t instanceof Ke?"float":typeof t}const w6="pyric-default",Wd=Symbol("pyric/storage/target");function Vi(t){var e;return((e=t.currentAuth)==null?void 0:e.call(t))??t.context.auth}class x6{constructor(e,n=null){G(this,"backend");G(this,"rules");this.backend=e,this.rules=n}}const d_=new WeakMap,f_=new WeakMap;function S6(t,e,n){const r=d_.get(t);if(r){const c=f_.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?tj(e.rules):null,o=X3(e.dbName??Q3(e.projectId)).then(c=>new x6(c,s));return d_.set(t,o),f_.set(t,e.rules??null),t.registerPersistableService("storage",{snapshot:()=>null,restore:()=>{},reset:async()=>{await(await o).backend.reset()}}),o}function sm(t){return t instanceof ho}const h_=new WeakMap,p_=new WeakMap;function _6(t,e={}){const n=!sm(t),r=sm(t)?t.sandbox:t,s=S6(r,e,"getAdminStorageSandbox");if(n){const g=p_.get(r);if(g)return g}const o=sm(t)?t:r.withAuth(null),c=o.operationContext.authLens.mode==="admin"?o:Wl(o,{source:o.operationContext.source,authLens:{mode:"admin"},...o.operationContext.planId===void 0?{}:{planId:o.operationContext.planId}}),d=h_.get(o);if(d)return d;const f={kind:"sandbox",sandbox:r,context:c,bucket:e.bucket??w6,servicePromise:s,admin:!0},p=Object.freeze({[Wd]:f});return h_.set(o,p),n&&p_.set(r,p),p}function yo(t,e){const n=Ld(e,ql(t.context.operationContext));return{...e,...ql(n),service:"storage"}}function ls(t){const e=t[Wd];if(!e)throw new TypeError("pyric/storage: not a FirebaseStorage handle — was it produced by getStorageSandbox?");return e}function tc(t){return ls(t).servicePromise}function E6(t){return`storage/${t}`}class nc extends Error{constructor(n,r){const s=E6(n);super(`${s}: ${r}`);G(this,"code");this.name="StorageError",this.code=s,Object.setPrototypeOf(this,nc.prototype)}}function sj(t){return new nc("object-not-found",`no object at "${t}".`)}function A6(t,e,n){return new nc("unauthorized",`${t} "${e}" denied by rules${n}.`)}function jg(t){return new nc("invalid-root-operation",`${t} cannot operate on the root reference.`)}function Hl(t,e){return k6(t)?(ls(t.storage),new Gl(t.storage,j6(t.fullPath,e??""))):(ls(t),new Gl(t,ij(e??"")))}class Gl{constructor(e,n){G(this,"storage");G(this,"bucket");G(this,"fullPath");this.storage=e;const r=ls(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 Gl(this.storage,n)}get root(){return this.fullPath===""?this:new Gl(this.storage,"")}toString(){return`gs://${this.bucket}/${this.fullPath}`}}function ij(t){return t===""?"":t.split("/").filter(e=>e.length>0).join("/")}function j6(t,e){const n=ij(e);return t===""?n:n===""?t:`${t}/${n}`}function k6(t){if(t===null||typeof t!="object"||Wd in t)return!1;const e=t;return typeof e.fullPath=="string"&&e.storage!==void 0}function rc(t,e,n,r){const s=(n==null?void 0:n.kind)==="sandbox"?yo(n,r):r;if((n==null?void 0:n.kind)==="sandbox"&&n.admin===!0){Nu(n,e,"not-applicable",void 0,"admin",!1,s);return}if(!t.rules){Nu(n,e,"allow",void 0,"user",!1,s);return}const o=n?C6(e,n.bucket):e,c=rj(t.rules,o,void 0,N6(n));if(!c.allowed){Nu(n,e,"deny",c.reasons,"user",!0,s);const d=c.reasons.length>0?` — ${c.reasons.join("; ")}`:"";throw A6(e.request.method,e.request.path,d)}Nu(n,e,"allow",c.reasons,"user",!0,s)}function C6(t,e){const n=t.request.path.replace(/^\/+/,"");return{...t,request:{...t.request,path:n===""?`b/${e}/o`:`b/${e}/o/${n}`}}}function Nu(t,e,n,r,s,o,c){if(t)try{Vs(t.sandbox,FE({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 N6(t){if(!t)return;const e=t.sandbox.admin;return{get:n=>e.getDocument(n),exists:n=>e.getDocument(n)!==null}}function aj(t){return{...t}}async function O6(t){R6(t,"getMetadata");const e=ls(t.storage),n=yo(e),r=await tc(t.storage),s=await r.backend.getMetadata(t.fullPath);if(rc(r,{request:{auth:Vi(e),method:"get",path:t.fullPath},resource:Zd(s)},e,n),!s)throw sj(t.fullPath);return aj(s)}function R6(t,e){if(t.fullPath==="")throw jg(e)}const T6="application/octet-stream";async function D6(t,e,n,r){U6(t,"uploadBytes");const s=ls(t.storage),o=yo(s,r),c=M6(e,n==null?void 0:n.contentType),d=I6({ref:t,blob:c,settable:n}),f=await tc(t.storage),p=await f.backend.getMetadata(t.fullPath);rc(f,{request:{auth:Vi(s),method:p?"update":"create",path:t.fullPath,resource:i6({size:d.size,contentType:d.contentType,customMetadata:d.customMetadata})},resource:Zd(p)},s,o),await f.backend.put(t.fullPath,c,d);try{Vs(s.sandbox,$d({service:"storage",op:"object_put",path:t.fullPath,auth:Vi(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:aj(d)}}function I6(t){const{ref:e,blob:n,settable:r}=t,s=(t.now??new Date).toISOString(),o=L6(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||T6,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 M6(t,e){return t instanceof Blob?e&&e!==t.type?new Blob([t],{type:e}):t:new Blob([t],{type:e??""})}function L6(t){return String(t.getTime())}function U6(t,e){if(t.fullPath==="")throw jg(e)}async function $6(t,e){return lj(t,"getBlob"),B6(t,e)}async function oj(t,e){lj(t,"deleteObject");const n=ls(t.storage),r=yo(n,e),s=await tc(t.storage),o=await s.backend.getMetadata(t.fullPath);rc(s,{request:{auth:Vi(n),method:"delete",path:t.fullPath},resource:Zd(o)},n,r),await s.backend.delete(t.fullPath);try{Vs(n.sandbox,$d({service:"storage",op:"object_delete",path:t.fullPath,auth:Vi(n),before:o??void 0,detail:{bucket:t.bucket}}),r)}catch{}}async function B6(t,e){const n=ls(t.storage),r=yo(n),s=await tc(t.storage),o=await s.backend.getMetadata(t.fullPath);rc(s,{request:{auth:Vi(n),method:"get",path:t.fullPath},resource:Zd(o)},n,r);const c=await s.backend.getBlob(t.fullPath);if(!c)throw sj(t.fullPath);return typeof e=="number"&&c.size>e?c.slice(0,e):c}function lj(t,e){if(t.fullPath==="")throw jg(e)}async function kg(t){const e=t.storage,n=ls(e),r=yo(n),s=await tc(e);rc(s,{request:{auth:Vi(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(Hl(e,g.fullPath));else{const w=b.slice(0,v),_=`${o}${w}`;f.has(_)||(f.add(_),p.push(Hl(e,_)))}}return p.sort((g,b)=>g.fullPath<b.fullPath?-1:g.fullPath>b.fullPath?1:0),{items:d,prefixes:p}}function q6(t,e,n){const r={name:n,options:structuredClone(e),automaticDataCollectionEnabled:!0};return GI(r,t),r}const F6=Object.freeze({source:Object.freeze({kind:"studio"}),authLens:Object.freeze({mode:"admin"})});function z6(t){return Wl(t.withAuth(null),F6)}const P6="pyric-studio";function cj(t,e){return t.listDocuments(e).map(({path:n,phantom:r})=>({path:n,phantom:r}))}let V6=0;function H6(t){const e=q6(t,{projectId:"pyric-studio"},`pyric-studio-${V6++}`),n=Wt(t),r=z6(t);return{sandbox:t,app:e,firestore:Vd(t),adminFirestore:bg(r),auth:XA(t),storage:_6(r),listRootCollections:()=>n.listRootCollections(),listSubcollections:s=>n.listSubcollections(s),listDocuments:s=>cj(n,s)}}function G6(t,e){const[n,r]=A.useState(!1),[s,o]=A.useState(null),c=A.useMemo(()=>VE(),[]),d=A.useMemo(()=>{try{return H6(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:P6,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 K6(t){var n;const e=((n=t.rules)==null?void 0:n.engine)??t.service;return e==="rtdb"||e==="storage"?e:"firestore"}function Y6(t){switch(K6(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 Z6(t){var e;return((e=DE(t))==null?void 0:e.rules.kind)==="evaluated"}function W6(t){return"service"in t&&typeof t.service=="string"?t.service:"firestore"}function Q6(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 J6(t){const e=[];for(const n of t)Z6(n)&&e.push(X6(n));return e.sort((n,r)=>r.at-n.at)}function X6(t){const e={id:t.id,at:t.at,result:t.result==="allow"?"allow":t.result==="unsupported"?"unsupported":"deny",method:t.method,service:W6(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=Q6(t);return n!==void 0&&(e.resourceData=n),t.resourceBefore&&(e.resourceBefore={data:t.resourceBefore.data,exists:t.resourceBefore.exists}),e}const m_=/^Rule #(\d+) \(([^)]+)\) → (ALLOW|deny|unsupported)/;function e4(t){var n;const e=((n=t.rules)==null?void 0:n.engine)??t.service;return e==="rtdb"||e==="storage"?e:"firestore"}function t4(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 n4(t){var s;const e=e4(t),n=t.reasons.filter(o=>m_.test(o)),r=t.reasons.filter(o=>!m_.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"?s4(t,n,r):e==="storage"?i4(t,n,r):r4(t,n,r)}function r4(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 s4(t,e,n){const r=t.rules,s=t4(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 i4(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 a4(t){var e;return!!((e=t.auth)!=null&&e.uid)}function o4(t){return t.skipped?"skipped":t.error!==void 0?"error":t.value===!0?"true":t.value===!1?"false":"value"}function l4(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:o4(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 c4(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 u4(t){const e=Wt(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=>cj(e,n)}}function ri(){const t=cs(),e=rr(),n=e.status==="ready"?e.env.persistence:void 0,r=G6(n,e.status),s=e.status==="ready"?e.env.live:void 0,o=d4(s);return A.useMemo(()=>{switch(t.status){case"ready":return{status:"ready",handles:u4(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 d4(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 _d=500;function im(t){return t.length>_d?t.slice(-_d):t}function sc(){var d;const t=cs(),e=rr(),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(im(n.history())),n.subscribe(p=>o(g=>im(dO(g,p))))},[r,n]);const c=A.useMemo(()=>r?im(t.events):[],[r,t]);return r?c:s}function f4(t){return t.kind==="request"||t.kind==="operation"}function h4(t){const e=DE(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 p4(){const t=sc();return A.useMemo(()=>t.filter(f4).map(h4),[t])}function m4(){const t=sc();return A.useMemo(()=>J6(t),[t])}function y4(){const t=ri();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)??ur,s=((f=t.firestoreApi)==null?void 0:f.setDoc)??Pl;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 g4(){const t=ri();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)??lr.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 b4(){const t=ri(),e=rr(),n=e.status==="ready"?e.env.live:void 0;return A.useCallback(async()=>{if(t.status!=="ready")throw new Error("No sandbox to clear.");const r=[];try{const s=n?await n.resetAll():await t.handles.sandbox.resetAll();r.push(...(s==null?void 0:s.errors)??[])}catch(s){r.push(`reset: ${s instanceof Error?s.message:String(s)}`)}return{errors:r}},[t,n])}function v4(){const t=b4(),e=y4(),n=g4(),r=cs();return A.useCallback(async()=>{const s=await t();if(r.status==="ready"){const{applySeed:o,deploySeedRules:c}=await p1(async()=>{const{applySeed:d,deploySeedRules:f}=await import("./seed-DeuFKi4J.js");return{applySeed:d,deploySeedRules:f}},[]);c(r.handles.sandbox),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 w4(){const t=cs(),e=rr(),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 Cg(){const t=rr(),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 x4(){const t=rr(),e=t.status==="ready"?t.env.live:void 0;return A.useCallback(async()=>e?e.exportState():null,[e])}function S4(){const t=rr(),e=t.status==="ready"?t.env.live:void 0;return A.useCallback(async n=>e?(await e.importState(n),!0):!1,[e])}function _4(){const t=rr(),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 E4(){const t=cs(),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 Wt(t.handles.sandbox).getRules()}catch{return""}},[t,n])}function A4(t){let e=!0;return n=>{const r=e;e=!1,t(s=>k4(s,n,r))}}function j4(t){const e=new Map;for(const n of t)e.set(by(n),n);return[...e.values()]}function k4(t,e,n){return j4(n?e:[...t??[],...e])}const C4=3e4;function uj(){const t=ri(),e=rr(),[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),w=A.useRef(0),_=A.useCallback(I=>{var O,T,P,$,K,W,se;const N=d.current;if(N.status!=="ready")return;const R=++b.current;c.current=!0,o(!0);const M=N.handles,F=M.adminFirestore,D=((O=N.firestoreApi)==null?void 0:O.collection)??Ui,C=((T=N.firestoreApi)==null?void 0:T.query)??Vl,L=((P=N.firestoreApi)==null?void 0:P.getDocs)??zl,U=(($=N.firestoreApi)==null?void 0:$.limit)??vd,H=((K=N.storageApi)==null?void 0:K.ref)??Hl,z=((W=N.storageApi)==null?void 0:W.listAll)??kg,q=((se=N.authApi)==null?void 0:se.listUsers)??lr.listUsers,x={listRootCollections:()=>M.listRootCollections(),listDocumentPaths:async(B,ee)=>(await L(C(D(F,B),U(ee)))).docs.slice(0,ee).map(le=>`${B}/${le.id}`),listSubcollections:B=>Promise.resolve(M.listSubcollections(B)),listUsers:async B=>(await Promise.resolve(q(M.auth))).slice(0,B).map(ae=>({uid:ae.uid,email:ae.email??null})),listStorageObjectPaths:B=>A3(H(M.storage,""),z,{maxObjects:B,maxListCalls:vy.storageListCalls}),listRtdbTopLevelKeys:async()=>{const B=p.current;if(!B)return[];const ee=Date.now()-w.current<C4;if(v.current!==null&&ee&&!(I!=null&&I.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,w.current=Date.now(),le}},E=A4(B=>r(B));$3(x,vy,B=>{R===b.current&&E(B)}).catch(()=>{}).finally(()=>{if(R===b.current&&(c.current=!1,o(!1),r(B=>B??[]),g.current)){const B=g.current;g.current=null,_(B)}})},[]),k=A.useCallback(I=>{if(d.current.status==="ready"){if(c.current){g.current={...g.current,...I};return}_(I)}},[_]);return A.useEffect(()=>{t.status==="ready"&&n===null&&!c.current&&_()},[t,n,_]),{entries:n,building:s,ensure:k}}const N4=150;function O4(t){return t.startsWith("/")||/rtdb/i.test(t)}function dj({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:w,building:_,ensure:k}=uj();A.useEffect(()=>{if(r)return r(()=>{var D;return(D=v.current)==null?void 0:D.focus()}),()=>r(null)},[r]),A.useEffect(()=>{var D;t&&((D=v.current)==null||D.focus())},[t]),A.useEffect(()=>{const D=setTimeout(()=>d(s),N4);return()=>clearTimeout(D)},[s]);const I=A.useMemo(()=>WS(c,Pi,w??[]),[c,w]),N=A.useMemo(()=>QS(I),[I]);A.useEffect(()=>{p(D=>N.length===0?0:Math.min(D,N.length-1))},[N.length]);const R=D=>{D&&(o(""),d(""),b(!1),Jn(D.target),e==null||e(D.target))},M=()=>{if(s===c){R(N[f]??N[0]);return}const D=QS(WS(s,Pi,w??[]));R(D[0])};let F=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&&N.length>0,"aria-autocomplete":"list",onFocus:()=>{k(),b(!0)},onBlur:()=>b(!1),onChange:D=>{const C=D.target.value;o(C),b(!0),O4(C)&&k({rtdbLikely:!0})},onKeyDown:D=>{if(D.key==="ArrowDown")D.preventDefault(),p(C=>Math.min(C+1,Math.max(N.length-1,0)));else if(D.key==="ArrowUp")D.preventDefault(),p(C=>Math.max(C-1,0));else if(D.key==="Enter")M();else if(D.key==="Escape"){if(n){n();return}o(""),d(""),b(!1)}}})}),g&&!I.length&&_&&w===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&&I.length?h.jsx("div",{className:"studio-home__command-results",role:"listbox","aria-label":"Suggestions",onMouseDown:D=>D.preventDefault(),children:I.map(D=>{const C=F;return F+=D.results.length,h.jsxs("div",{className:"studio-home__command-group",children:[h.jsx("span",{className:"studio-home__command-group-title","aria-hidden":"true",children:D.title}),h.jsx("ul",{className:"studio-home__command-group-list",children:D.results.map((L,U)=>{const H=C+U;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:()=>R(L),children:[h.jsx("span",{className:"studio-home__command-label",children:L.label}),h.jsx("span",{className:"studio-home__command-sub",children:L.hint})]})},L.id)})})]},D.kind)})}):null]})}function R4({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(dj,{autoFocus:!0,onEscape:t,onNavigated:t})})})}const T4={status:"loading",payload:null},Ou={status:"absent",payload:null};let Ed=T4,y_=!1;const Ay=new Set;function Ru(t){Ed=t;for(const e of Ay)e()}function D4(){if(!y_){if(y_=!0,typeof fetch>"u"){Ed=Ou;return}fetch("/__pyric/init.json").then(async t=>{if(!t.ok||!(t.headers.get("content-type")??"").includes("json"))return Ru(Ou);const n=await t.json();Ru({status:"ready",payload:n})}).catch(()=>Ru(Ou))}}function I4(t){return Ay.add(t),D4(),()=>Ay.delete(t)}function Qd(){return A.useSyncExternalStore(I4,()=>Ed,()=>Ed)}function M4(t){return t.kind==="absent"?"absent":t.sandboxConnected?"available":"idle"}function L4(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 U4(t){try{const e=await t("/__pyric/health");return e.ok?(e.headers.get("content-type")??"").includes("json")?L4(e.status,await e.json()):{kind:"absent"}:{kind:"absent"}}catch{return{kind:"absent"}}}function $4(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=M4(await U4(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 B4="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 q4(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 F4(t){return t==="studio"?"Studio":"App"}function z4(t,e,n=Date.now()){const r=t.clients.length,s=t.clients.map(c=>({clientId:c.clientId,kindLabel:F4(c.kind),route:c.route||"/",visibilityLabel:c.visibility==="hidden"?"Hidden":"Visible",isThisPage:c.clientId===e,freshnessLabel:q4(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:B4,otherCount:o}}function P4(){const t=rr(),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(z4(o,s))})},[e]),n}function V4(){const t=rr(),e=Qd(),n=$4(),r=P4(),[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=w=>{var _;w.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:Gd({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 H4(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 g_(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 G4({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(g_(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&&H4(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(g_("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 K4={buckets:[],total:0,denies:0,maxCount:0,outOfWindow:0};function Y4({events:t,window:e,bucketCount:n=30}){return A.useMemo(()=>Z4(t,e,n),[t,e.start,e.end,n])}function Z4(t,e,n=30){const r=e.end-e.start;if(n<=0||r<=0)return K4;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 w=v.at;if(w<e.start||w>=e.end){p++;continue}let _=Math.floor((w-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,w)=>{const _=c[w];return{index:w,start:e.start+w*s,end:e.start+(w+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 W4=new Set(["get","list"]),Q4=new Set(["create","update","set"]),J4=new Set(["delete","remove"]),X4=[{key:"reads",label:"Read ops"},{key:"writes",label:"Writes"},{key:"deletes",label:"Deletes"}],eB=[{key:"allows",label:"Allows"},{key:"denies",label:"Denies"},{key:"errors",label:"Errors"}];function Jd(t){return t.origin==="admin"}function tB(t,e=Jd){return t.result==="allow"||e(t)?W4.has(t.method)?"reads":Q4.has(t.method)?"writes":J4.has(t.method)?"deletes":null:null}function nB(t,e=Jd){return e(t)?null:t.result==="allow"?"allows":t.result==="deny"?"denies":t.result==="error"?"errors":null}const rB=t=>({points:[],series:t.map(e=>({key:e.key,label:e.label,values:[],total:0})),maxValue:0});function fj(t,e,n,r,s){const o=e.end-e.start;if(n<=0||o<=0)return rB(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 w=v.at;if(w<e.start||w>=e.end)continue;const _=s(v);if(_==null)continue;let k=Math.floor((w-e.start)/c);k>=n&&(k=n-1);const I=d.get(_);I[k]++,f.set(_,(f.get(_)??0)+1)}let p=0;for(const v of d.values())for(const w of v)w>p&&(p=w);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 sB(t,e,n=24,r=Jd){return fj(t,e,n,X4,s=>tB(s,r))}function iB(t,e,n=24,r=Jd){return fj(t,e,n,eB,s=>nB(s,r))}function aB({events:t,window:e,bucketCount:n=24,isAdmin:r}){return A.useMemo(()=>sB(t,e,n,r),[t,e.start,e.end,n,r])}function oB({events:t,window:e,bucketCount:n=24,isAdmin:r}){return A.useMemo(()=>iB(t,e,n,r),[t,e.start,e.end,n,r])}function Ja({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 Kl(t){const e=new Date(t),n=r=>String(r).padStart(2,"0");return`${n(e.getHours())}:${n(e.getMinutes())}:${n(e.getSeconds())}`}function hj({event:t,selected:e,onSelect:n,renderClassification:r,formatTime:s=Kl,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(Ja,{kind:t.method,children:t.method}),h.jsx("span",{"data-pyric-traffic-path":"",children:t.path||"/"}),r?r(t):null]})}var Ng=h1();function Fa(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 w;if(n.key&&((f=n.debug)!=null&&f.call(n))&&(w=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()-w)*100)/100,I=k/16,N=(R,M)=>{for(R=String(R);R.length<M;)R=" "+R;return R};console.info(`%c⏱ ${N(k,5)} /${N(_,5)} ms`,`
|
|
1212
|
+
`)});if(typeof t!="object")throw new nt("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 nt("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 nt("invalid-argument","withAuth() requires `token` (when present) to be a plain object.")}function nI(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 rI(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 Ud(t){return Fm(t,!0)}function Fm(t,e){if(t===null||typeof t!="object")return t;if(Array.isArray(t)){const o=t.map(c=>Fm(c,!1));return e&&no(o,Wx(t)),o}const n=t,r=o=>(e&&no(o,Wx(t)),o);if(n.__type__==="__vector__"&&Array.isArray(n.value))return r(new uo(n.value));if(typeof n.__type=="string")switch(n.__type){case"timestamp":return r(new Rt(n.seconds,n.nanos));case"bytes":return r(new In(nI(n.base64)));case"latlng":return r(new Cr(n.lat,n.lng));case"duration":return r(new Mt(n.seconds,n.nanos));case"reference":return r(new Xa(n.path));case"path":return r(new dr(n.segments))}if(typeof n.type=="string")switch(n.type){case"firestore/timestamp/1.0":{const o=n.seconds,c=n.nanoseconds;return r(new Rt(o,c))}case"firestore/bytes/1.0":return r(new In(rI(n.bytes)));case"firestore/geoPoint/1.0":return r(new Cr(n.latitude,n.longitude))}const s={};for(const[o,c]of Object.entries(n))s[o]=Fm(c,!1);return r(s)}class Eu extends Error{constructor(e){super(e),this.name="PersistenceSchemaError"}}function sI(t){let e;try{e=JSON.parse(t)}catch(s){throw new Eu(`Persisted blob is not valid JSON: ${s.message}`)}if(typeof e!="object"||e===null)throw new Eu("Persisted blob is not an object");if(e.version!==1&&e.version!==2)throw new Eu(`Persisted blob has version ${String(e.version)}, expected 1 or 2`);if(typeof e.firestore!="object"||e.firestore===null)throw new Eu("Persisted blob has no firestore field");const n={};for(const[s,o]of Object.entries(e.firestore))n[s]=Ud(o);const r=e.services!==void 0&&typeof e.services=="object"&&e.services!==null?e.services:{};return{firestore:n,services:r}}const iI=3,aI=256,zm="meta";function oI(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%aI).toString(16).padStart(2,"0")}function lI(t){return JSON.parse(JSON.stringify(t))}function IE(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 ME(t,e,n){const r=new Map;r.set(zm,{version:iI,savedAt:n,services:e});for(const[s,o]of Object.entries(t)){const c=oI(s);let d=r.get(c);d||(d={docs:{}},r.set(c,d)),d.docs[s]=lI(o)}for(const[s,o]of r)s!==zm&&(o.checksum=IE(o.docs));return r}const LE="pyric-v3-records";function cI(t){return JSON.stringify({format:LE,records:Object.fromEntries(t)})}function uI(t){let e;try{e=JSON.parse(t)}catch{return new Map}const n=e;return n&&typeof n=="object"&&n.format===LE&&typeof n.records=="object"&&n.records!==null?new Map(Object.entries(n.records)):UE(t)??new Map}function UE(t){let e;try{e=sI(t)}catch{return null}return ME(e.firestore,e.services,0)}function dI(t){const e={};let n={};for(const[r,s]of t){if(r===zm){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"&&IE(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]=Ud(d)}}return{firestore:e,services:n}}const so="snapshots";function Pm(){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 $E(t){return new Promise((e,n)=>{const r=indexedDB.open(t,1);r.onupgradeneeded=()=>{const s=r.result;s.objectStoreNames.contains(so)||s.createObjectStore(so)},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 Hp(t,e,n){return $E(t).then(r=>new Promise((s,o)=>{const c=r.transaction(so,e),d=c.objectStore(so),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 aS(t,e){return $E(t).then(n=>new Promise((r,s)=>{const o=n.transaction(so,"readwrite");e(o.objectStore(so)),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 fI(){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 Hp(t,"readonly",r=>r.get(e))??null},async listRecords(t){return(await Hp(t,"readonly",n=>n.getAllKeys())??[]).map(n=>String(n))},async putRecords(t,e){await aS(t,n=>{for(const[r,s]of e)n.put(s,r)})},async deleteRecords(t,e){await aS(t,n=>{for(const r of e)n.delete(r)})},async clear(t){await Hp(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 hI=250,oS="pyric:sandbox:auth-session";function Gp(t){return t==="auth"||t==="auth-session:[DEFAULT]"?oS:`${oS}:${encodeURIComponent(t)}`}function BE(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 pI(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 mI(t){return t.injectedBackend?t.injectedBackend:(t.backend??"indexedDB")==="memory"||typeof indexedDB>"u"?Pm():fI()}async function yI(t,e){const n={...e,flushIntervalMs:e.flushIntervalMs??hI,backend:e.backend??"indexedDB"},r=mI(n),s=new Map,o=await gI(t,r,n.key,s);let c=null,d=!1;const f=new Map,p=async()=>{if(d)return;const U=t.snapshot(),H=ME(U.firestore,U.services,Date.now()),z=new Map,q=new Map;for(const[E,O]of H){const T=BE(O);q.set(E,T),s.get(E)!==T&&z.set(E,O)}const x=[...s.keys()].filter(E=>!H.has(E));z.size>0&&await r.putRecords(n.key,z),x.length>0&&await r.deleteRecords(n.key,x),s.clear();for(const[E,O]of q)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(U=>{if(pI(U)){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:",U),v()})},n.flushIntervalMs))},w=(U,H)=>{if(!H.subscribe||f.has(U))return;const z=H.subscribe(()=>{v()});f.set(U,z)},_=new Map,k=new Map,I=(U,H)=>{if(!n.sessionStorage)return;const{local:z,session:q}=n.sessionStorage,x=Gp(U),E=H.currentUid(),O=H.mode();if(E===null||O==="NONE"){z.removeItem(x),q.removeItem(x);return}const T=JSON.stringify({uid:E});O==="LOCAL"?(q.removeItem(x),z.setItem(x,T)):(z.removeItem(x),q.setItem(x,T))},N=U=>{if(!n.sessionStorage)return null;const H=Gp(U);for(const[z,q]of[["LOCAL",n.sessionStorage.local],["SESSION",n.sessionStorage.session]]){const x=q.getItem(H);if(x)try{const E=JSON.parse(x);if(typeof(E==null?void 0:E.uid)=="string")return{uid:E.uid,mode:z}}catch{q.removeItem(H)}}return null},R=U=>{if(!n.sessionStorage)return;const H=Gp(U);n.sessionStorage.local.removeItem(H),n.sessionStorage.session.removeItem(H)},M=(U,H,z)=>{if(z.session)try{z.session.restore(H.uid,H.mode),k.delete(U)}catch(q){console.warn(`[sandbox/persistence] session restore for uid '${H.uid}' failed — clearing stored session:`,q),R(U),k.delete(U)}},F=(U,H)=>{if(!n.sessionStorage||!H.session||_.has(U))return;const z=H.session;_.set(U,z.subscribe(()=>I(U,z)))},D=(U,H)=>{if(!H.session)return;const z=k.get(U)??N(U);z&&M(U,z,H)};if(t instanceof Js){for(const[U,H]of t.getServiceRegistry())w(U,H),D(U,H),F(U,H);t.setServiceRegistrationHook((U,H)=>{if(o!==null&&U in o)try{H.restore(o[U])}catch(q){console.warn(`[sandbox/persistence] late-restore for service '${U}' failed:`,q)}const z=N(U);z&&k.set(U,z),D(U,H),w(U,H),F(U,H),v()}),t.setServiceUnregistrationHook(U=>{var H,z;(H=f.get(U))==null||H(),f.delete(U),(z=_.get(U))==null||z(),_.delete(U),k.delete(U),v()})}const C=t.onEvent(U=>{bI(U)&&v()}),L=()=>{b().catch(()=>{})};return typeof window<"u"&&window.addEventListener("beforeunload",L),{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),C();for(const U of f.values())U();f.clear();for(const U of _.values())U();_.clear(),t instanceof Js&&(t.setServiceRegistrationHook(null),t.setServiceUnregistrationHook(null)),typeof window<"u"&&window.removeEventListener("beforeunload",L)}}}}async function gI(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=UE(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,BE(b));const p=dI(c);for(const[g,b]of Object.entries(p.firestore))t.admin.setDocument(g,b);if(t instanceof Js){const g=t.getServiceRegistry();for(const[b,v]of Object.entries(p.services)){const w=g.get(b);if(w)try{w.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 bI(t){return t.kind==="write"||t.kind==="session_boundary"}function vI(t){return typeof t=="object"&&t!==null&&typeof t.kind=="string"&&typeof t.origin=="string"}let wI=0;function xI(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`tab-${crypto.randomUUID()}`:`tab-${++wI}-${typeof performance<"u"?performance.now().toFixed(3):String(Date.now())}`}function SI(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??xI();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(!vI(b.data))return;const v=b.data;if(v.origin!==s){if(v.kind==="write")g(v.event);else if(v.kind==="hello"){const w={kind:"state",origin:s,to:v.origin,snapshot:t.snapshot()};n.postMessage(w)}else if(v.kind==="state"){if(v.to!==s||c)return;if(Object.keys(Wt(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 _I(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=Bm(n)||t.operationContext!==void 0?Ld(e,s):EI(t,e);return n.operationContext=o,n.actor=o.source,n.authLens=o.authLens,o.planId!==void 0&&(n.planId=o.planId),(e==null?void 0:e.activity)!==void 0&&(n.activity={...n.activity,...e.activity}),Bm(n)&&(n.rulesDisposition=Object.freeze({...OE(n)})),n}function EI(t,e){var n,r,s,o,c,d,f,p;return Zl({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 AI(t,e){var s,o,c,d;if(!t)return e;if(!e)return t;if(e.operationContext!==void 0)return qE(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=Zl({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 qE(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=Ld(t,e);return{...t,...e,operationContext:r,actor:r.source,authLens:r.authLens,...r.planId===void 0?{}:{planId:r.planId}}}let jI=1;function Li(){const t=(jI++).toString(36),e=Math.random().toString(36).slice(2,7);return`sbe-${t}-${e}`}class Js{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 Js(new rS)}getEnv(){return this._env}withAuth(e){return qm(e),new ho(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:Li(),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=qE(this.ambientProvenance,n);this.dispatch(_I(e,r))}runWithProvenance(e,n){const r=this.ambientProvenance;this.ambientProvenance=AI(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:Li(),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 rS,this.attachToEnv()}async resetAll(){this.reset();const e=[],n=[];for(const[r,s]of this.serviceRegistry)s.reset&&n.push(Promise.resolve().then(()=>s.reset()).catch(o=>{e.push(`${r}: ${o instanceof Error?o.message:String(o)}`)}));return await Promise.all(n),{errors:e}}dispose(){const e={kind:"session_boundary",id:Li(),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){qm(e),!kI(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 nt("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 yI(this,e);this.persistence=n})();try{await this.enablePersistencePromise}finally{this.enablePersistencePromise=null}}enableTabSync(e){return SI(this,e)}async flush(){if(!this.persistence)throw new nt("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 nt("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 kI(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 Wt(t){if(!(t instanceof Js))throw new nt("invalid-argument","Sandbox handle was not produced by initializeSandbox(); custom Sandbox implementations are not supported.");return t.getEnv()}function Vs(t,e,n){if(!(t instanceof Js))throw new nt("invalid-argument","Sandbox handle was not produced by initializeSandbox(); custom Sandbox implementations are not supported.");t.emitInternal(e,n)}function $d(t){return{kind:"service_mutation",id:Li(),at:Date.now(),...t}}function FE(t){const{at:e,...n}=t;return{kind:"operation",id:Li(),at:e??Date.now(),...n}}function CI(t){const{at:e,...n}=t;return{kind:"commit",id:Li(),at:e??Date.now(),...n}}function NI(t){const{at:e,...n}=t;return{kind:"listener",id:Li(),at:e??Date.now(),...n}}const OI=Symbol.for("pyric.remote.sandbox");function rg(t){return t!=null&&t[OI]===!0}function zE(t,e=""){const n=VE();return Wt(n).seed({rules:e,baseDocuments:t.firestore}),{sandbox:n,rules:e,base:t,events:[],discarded:!1}}function RI(t,e){TI(t);const n=Wt(t.sandbox).snapshot(),r=DI(e);return MI(r,n)}function PE(t){t.discarded||(t.discarded=!0,t.sandbox.dispose())}function TI(t){if(t.discarded)throw new Error("Branch has been discarded or promoted; create a new fork.")}function DI(t){return II(t)?Wt(t).snapshot():t.firestore}function II(t){return typeof t.snapshot=="function"}function MI(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||LI(s,o,c,n)}return n}function LI(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 w of v){const _=d?`${d}.${w}`:w;s(g[w],b[w],_)}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}Vm(o,c)||r.push({kind:"real-divergence",path:t,field:d||void 0,before:o,after:c})}}function Vm(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(!Vm(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)||!Vm(s[f],o[f]))return!1;return!0}function VE(t={}){return Js.createRoot()}function hl(t,e){return`${t.replace(/\/$/,"")}${e}`}function UI(t){const e=t;return{async read(n){const r=await fetch(hl(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(hl(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(hl(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(hl(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(hl(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 pl(t,e){return`${t.replace(/\/$/,"")}${e}`}function $I(t){const e=t;return{async list(){const n=await fetch(pl(e,"/__pyric/projects"));if(!n.ok)throw new Error(`projects.list() → ${n.status}`);return await n.json()},async open(n){const r=await fetch(pl(e,`/__pyric/projects/${encodeURIComponent(n)}`));if(!r.ok)throw new Error(`projects.open(${n}) → ${r.status}`);return{meta:await r.json(),workspace:UI(e)}},async create(n){const r=await fetch(pl(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(pl(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(pl(e,`/__pyric/projects/${encodeURIComponent(n)}`),{method:"DELETE"});if(!r.ok)throw new Error(`projects.remove(${n}) → ${r.status}`)}}}function BI(t,e){return`${t.replace(/\/$/,"")}${e}`}function Kp(t){return/auth/i.test(t)?"auth":"firestore"}function qI(t){const e=t,r={"content-type":"application/json","x-pyric-writer":`studio-${Math.random().toString(36).slice(2)}`},s=new Map,o=f=>BI(e,`/__pyric/state?section=${Kp(f)}`),c=async f=>{const p=Kp(f),g=s.get(p);if(g)return g;const b=await fetch(o(f));let v=new Map;if(b.ok){const w=await b.text();w&&w!=="null"&&(v=uI(w))}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:cI(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(Kp(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 FI="local";function zI(){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 PI(){const t=zI();let e={id:FI,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 Wi 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(Wi,"name",{value:"FirebaseError"});let Wa;function VI(t){Wa=t}function sg(t){return Wa==null?void 0:Wa.resolve(t,!1)}function HE(){if(!Wa)throw new TypeError("No default sandbox app registry is installed - import and initialize pyric/app before calling a service factory without an app.");return Wa.defaultApp()}function HI(){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 GE=new WeakMap;let Hm;function GI(t,e,n=HI()){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 Wi("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 GE.set(t,d),d}function KI(t){Hm=t}VI({resolve(t,e){const n=typeof t=="object"&&t!==null?GE.get(t):void 0;if(n)return n},defaultApp(){if(!Hm)throw new TypeError("No default sandbox app registry is installed - import and initialize pyric/app before calling a service factory without an app.");return Hm()}});const YI="[DEFAULT]",ZI=new Map;function WI(t,e){return new Wi(`app/${t}`,`Firebase: ${e} (app/${t}).`)}function QI(t){return WI("no-app",`No Firebase App '${t}' has been created - call initializeApp() first`)}function JI(t=YI){const e=ZI.get(t);if(!e)throw QI(t);return e.app}KI(JI);let XI=0,eM=0;function Ae(){return`op-${++XI}`}function po(){return`sub-${++eM}`}const Gm=new Map,ig=new Map,ag=new Map,Ql=new WeakSet,tM=new Set;function nM(){return Object.assign(new Error("Firebase App was deleted"),{code:"app/app-deleted"})}function Jl(t,e,n,r){return Ql.has(t)?!1:(ig.set(e,n),t.postMessage(r),!0)}function rM(t,e,n,r){return Ql.has(t)?!1:(ag.set(e,{port:t,next:n}),t.postMessage(r),!0)}function Xl(t,e){ig.delete(e),ag.delete(e),Ql.has(t)||t.postMessage({t:"unsub",subId:e})}function lS(t,e){if(e.denialContext===void 0||typeof fetch!="function")return;const n={kind:t,code:e.code,message:e.message,denialContext:e.denialContext,...typeof e.remediation=="string"?{remediation:e.remediation}:{}};try{fetch("/__pyric/denials",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(n)}).catch(()=>{})}catch{}}function og(t){t.onmessage=e=>{const n=e.data;if(n.t==="res"){const r=Gm.get(n.id);if(!r)return;if(Gm.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),lS("read",s),r.reject(s)}}else if(n.t==="snap"){const r=ig.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),lS("listener",c),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=ag.get(n.subId);r&&r.next(n.events)}else if(n.t==="runtime-reload")for(const r of tM)r(n)}}let io;function cS(t){io=t&&t.mode==="app-session"?void 0:t}function sM(){return io}let Km;function iM(t){Km=t}function lg(t){return Km&&(t.t==="op"||t.t==="sub")?{...t,issuer:Km}:t}function KE(t,e){return Ql.has(t)?Promise.reject(nM()):new Promise((n,r)=>{const s=e;Gm.set(s.id,{port:t,resolve:n,reject:r}),t.postMessage(e)})}function Ye(t,e){return KE(t,lg(e))}function nr(t,e){if(Ql.has(t)&&!e.method.startsWith("rtdb."))return Promise.reject(new Wi("failed-precondition","The client has already been terminated."));const n=io?{...e,actAs:io}:e;return Ye(t,n)}function aM(t,e,n={}){if(typeof SharedWorker>"u")throw new Error("SharedWorker is not available. Open this page over http:// (not file://) and use a supported browser (Chrome 4+, Firefox 29+, Safari 16.4+).");const r=new SharedWorker(t,{type:"classic",name:"pyric-shared-worker"});n.onError&&r.addEventListener("error",o=>{var d;const c=o.message||`failed to load ${String(t)}`;(d=n.onError)==null||d.call(n,new Error(`Pyric SharedWorker error: ${c}`))});const s=r.port;return og(s),s.start(),{__kind:"client-db",port:s}}async function oM(t){return(await Ye(t.port,{t:"op",id:Ae(),method:"getVersion"})).instanceId??""}async function lM(t){return(await Ye(t.port,{t:"op",id:Ae(),method:"exportState"})).bundle}async function cM(t,e){await Ye(t.port,{t:"op",id:Ae(),method:"importState",bundle:e})}async function uM(t,e){await Ye(t.port,{t:"op",id:Ae(),method:"saveBranch",name:e})}async function dM(t){return(await Ye(t.port,{t:"op",id:Ae(),method:"listBranches"})).branches??[]}async function fM(t,e){await Ye(t.port,{t:"op",id:Ae(),method:"switchBranch",name:e})}async function hM(t,e){await Ye(t.port,{t:"op",id:Ae(),method:"deleteBranch",name:e})}async function pM(t,e,n){return await Ye(t.port,{t:"tool",id:Ae(),name:e,args:n})}function mM(t,e){return KE(t.port,{...e,issuer:void 0,relaySource:"remote",t:"op",id:Ae()})}function yM(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=po();return Jl(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,issuer:void 0,relaySource:"remote",t:"sub",subId:r})||queueMicrotask(()=>n({__error:{code:"app/app-deleted",message:"Firebase App was deleted"}})),()=>{Xl(t.port,r)}}function cg(t){return t.split("/").at(-1)??t}function gM(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:cg(r),path:r}}function bM(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:cg(r),path:r}}function vM(t){return{_descriptor:{kind:"limit",n:t}}}function wM(...t){return{_descriptor:{kind:"startAfter",values:t}}}function xM(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 SM(t){return Ud(JSON.parse(t.json))}const YE=8*1024*1024;function _M(t,e){const n=new Error(`${e} is ${t} bytes — over the ${YE/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 EM(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 AM(t){return SM(t)}function ug(t,e){const n=t.exists&&t.data?AM(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 ZE(t,e){const n=t.docs.map(r=>ug(r,e));return{size:n.length,empty:n.length===0,docs:n}}async function jM(t){const e=await nr(t.port,{t:"op",id:Ae(),method:"getDoc",path:t.descriptor.path});return ug(e,t.port)}async function kM(t){const e=await nr(t.port,{t:"op",id:Ae(),method:"getDocs",source:(t.__kind==="coll-ref",t.descriptor)});return ZE(e,t.port)}async function CM(t){return(await nr(t.port,{t:"op",id:Ae(),method:"listRootCollections"})).ids}async function NM(t,e){return(await nr(t.port,{t:"op",id:Ae(),method:"listSubcollections",docPath:e})).ids}function OM(t,e,n){const r=po(),s=t.port,o={port:s,service:"firestore",next:f=>{const p=f;"docs"in p?e(ZE(p,s)):e(ug(p,s))},error:n},c=(t.__kind==="doc-ref"||t.__kind==="coll-ref",t.descriptor);return!Jl(s,r,o,lg(io?{t:"sub",subId:r,target:c,actAs:io}:{t:"sub",subId:r,target:c}))&&n&&queueMicrotask(()=>n(new Error("Firebase App was deleted"))),()=>{Xl(s,r)}}async function RM(t,e,n){await nr(t.port,{t:"op",id:Ae(),method:"setDoc",path:t.descriptor.path,data:e,options:n})}async function TM(t){await nr(t.port,{t:"op",id:Ae(),method:"deleteDoc",path:t.descriptor.path})}async function DM(t,e){const n=await nr(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 IM(t,e){return await Ye(t.port,{t:"op",id:Ae(),method:"admin.listDocuments",path:e})}function MM(t){const e=(t??"/").split("/").filter(Boolean).join("/");return e?`/${e}`:"/"}new Array(12).fill(0);async function LM(t){return Ye(t.port,{t:"op",id:Ae(),method:"rtdb.adminSnapshot"})}async function UM(t,e,n){await Ye(t.port,{t:"op",id:Ae(),method:"rtdb.set",path:e,value:n,actAs:{mode:"admin"}})}async function $M(t,e,n){await Ye(t.port,{t:"op",id:Ae(),method:"rtdb.update",path:e,values:n,actAs:{mode:"admin"}})}async function BM(t,e){await Ye(t.port,{t:"op",id:Ae(),method:"rtdb.remove",path:e,actAs:{mode:"admin"}})}function qM(t,e,n,r){const s=po();return!Jl(t.port,s,{port:t.port,next:c=>n((c==null?void 0:c.value)??null),error:r},lg({t:"sub",subId:s,target:{service:"rtdb",path:MM(e)},actAs:{mode:"admin"}}))&&r&&queueMicrotask(()=>r(new Error("FIREBASE FATAL ERROR: Database has been deleted."))),()=>{Xl(t.port,s)}}function FM(t,e){const n=po(),r=t.port;return rM(r,n,e,{t:"sub",subId:n,target:"events"}),()=>{Xl(r,n)}}async function zM(t){return await Ye(t.port,{t:"op",id:Ae(),method:"getSnapshot"})}async function PM(t){return await Ye(t.port,{t:"op",id:Ae(),method:"resetAll"})??{errors:[]}}const VM=15e3;function HM(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`page-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function uS(){return typeof location>"u"?"/":`${location.pathname}${location.search}${location.hash}`}function dS(){return typeof document>"u"?"visible":document.visibilityState==="hidden"?"hidden":"visible"}function GM(t){const{db:e,kind:n}=t,r=t.clientId??HM(),s=t.heartbeatIntervalMs??VM;let o=!1,c=null;const d=()=>{Ye(e.port,{t:"op",id:Ae(),method:"presence.register",clientId:r,kind:n,route:uS(),visibility:dS()}).catch(()=>{})},f=()=>{Ye(e.port,{t:"op",id:Ae(),method:"presence.heartbeat",clientId:r}).catch(()=>{})},p=()=>{Ye(e.port,{t:"op",id:Ae(),method:"presence.update",clientId:r,route:uS(),visibility:dS()}).catch(()=>{})},g=()=>{Ye(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 KM(t,e){const n=po();return Jl(t.port,n,{port:t.port,next:r=>{e(r)}},{t:"sub",subId:n,target:"presence"}),()=>{Xl(t.port,n)}}const YM=Symbol("pyric.clientUser.port");function ZM(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 Ye(t,{t:"op",id:Ae(),method:"auth.getIdToken",forceRefresh:r})},async getIdTokenResult(r){return await Ye(t,{t:"op",id:Ae(),method:"auth.getIdTokenResult",forceRefresh:r})}};return Object.defineProperty(n,YM,{value:t,enumerable:!1}),n}function WM(t,e){return e?ZM(t,e):null}function QM(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(),og(n)}const r={__kind:"client-auth",port:n,currentUser:null},s=po();return Jl(n,s,{port:n,next:o=>{r.currentUser=WM(n,o)}},{t:"sub",subId:s,target:"authState"}),r}async function JM(t){return await Ye(t.port,{t:"op",id:Ae(),method:"auth.listUsers"})}async function XM(t,e){return await Ye(t.port,{t:"op",id:Ae(),method:"auth.adminCreateUser",request:e})}async function eL(t,e,n){return await Ye(t.port,{t:"op",id:Ae(),method:"auth.adminUpdateUser",uid:e,request:n})}async function tL(t,e){await Ye(t.port,{t:"op",id:Ae(),method:"auth.adminDeleteUser",uid:e})}async function nL(t){await Ye(t.port,{t:"op",id:Ae(),method:"auth.adminClearUsers"})}async function rL(t){return await Ye(t.port,{t:"op",id:Ae(),method:"auth.getProviderConfig"})}async function sL(t,e,n){await Ye(t.port,{t:"op",id:Ae(),method:"auth.setProviderConfig",providerId:e,enabled:n})}function iL(t){return t.replace(/^\/+|\/+$/g,"")}function aL(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(),og(n)}return{__kind:"client-storage",port:n}}function oL(t,e){const n=iL(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:cg(r)}}async function lL(t){const e=await nr(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 cL(t){return await nr(t.port,{t:"op",id:Ae(),method:"storage.getMetadata",path:t.fullPath})}async function uL(t){return await nr(t.port,{t:"op",id:Ae(),method:"storage.getBlob",path:t.fullPath})}async function dL(t,e,n){const r=e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof ArrayBuffer?new Uint8Array(e):e;if(r.byteLength>YE)throw _M(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 nr(t.port,{t:"op",id:Ae(),method:"storage.putBytes",path:t.fullPath,dataB64:EM(r),...s!==void 0?{contentType:s}:{},...n!==void 0?{metadata:n}:{}});return{ref:t,metadata:o}}async function fL(t){await nr(t.port,{t:"op",id:Ae(),method:"storage.deleteObject",path:t.fullPath})}const hL="/__pyric/sdk/worker.js";function pL(t){let e=[],n=!1;const r=new Set;let s=null;function o(){s||(s=FM(t,c=>{const d=!n;n=!0;const f=d?[]:[...e];for(const p of c)m1(p)&&(f.length=0),f.push(p);e=f;for(const p of c)for(const g of r)g(p)}))}return{history:()=>e,subscribe:c=>(r.add(c),o(),()=>{r.delete(c),r.size===0&&s&&(s(),s=null,n=!1,e=[])})}}function mL(t=hL){if(typeof SharedWorker>"u")return null;iM("studio");let e;try{e=aM(t)}catch{return null}cS({mode:"admin"});const n=GM({db:e,kind:"studio"}),r=pL(e),s=QM(e);return{db:e,presenceClientId:n.clientId,subscribePresence:o=>KM(e,o),instanceId:()=>oM(e),exportState:()=>lM(e),importState:o=>cM(e,o),saveBranch:o=>uM(e,o),listBranches:()=>dM(e),switchBranch:o=>fM(e,o),deleteBranch:o=>hM(e,o),feed:r,setLens:o=>cS(o),getLens:()=>sM(),listRootCollections:()=>CM(e),listSubcollections:o=>NM(e,o),listDocuments:async o=>(await IM(e,o)).map(({path:c,phantom:d})=>({path:c,phantom:d})),readRtdbState:()=>LM(e),setRtdbValue:(o,c)=>UM(e,o,c),updateRtdbValue:(o,c)=>$M(e,o,c),deleteRtdbValue:o=>BM(e,o),subscribeRtdbValue:(o,c,d)=>qM(e,o,c,d),firestoreApi:{collection:bM,doc:gM,getDoc:jM,getDocs:kM,onSnapshot:OM,setDoc:RM,deleteDoc:TM,addDoc:DM,query:xM,limit:vM,startAfter:wM},auth:s,authApi:{listUsers:()=>JM(s),subscribeUsers:(o,c)=>r.subscribe(d=>{d.kind==="service_mutation"&&d.service==="auth"&&c()}),createUser:(o,c)=>XM(s,c),updateUser:(o,c,d)=>eL(s,c,d),deleteUser:(o,c)=>tL(s,c),clearUsers:()=>nL(s),getAuthProviderConfig:()=>rL(s),setAuthProviderConfig:(o,c,d)=>sL(s,c,d),subscribeAuthProviderConfig:(o,c)=>r.subscribe(d=>{d.kind==="service_mutation"&&d.op==="provider_config_update"&&c()})},storage:aL(e),storageApi:{ref:oL,listAll:lL,getMetadata:cL,getBlob:uL,uploadBytes:dL,deleteObject:fL},getSnapshot:()=>zM(e),resetAll:()=>PM(e)}}const fS=5174,hS="/sandbox",yL=4001,gL="worker-relay";function bL(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 Ym(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=Ym(n);if(r)return r}return null}for(const n of Object.values(t)){const r=Ym(n);if(r)return r}return null}function pS(t,e){const n=Ym(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 vL=()=>{throw new Error("pyric dev: fs is not available in the browser")},mS=vL,Zm=(...t)=>t.join("/"),wL=t=>t.split("/").slice(0,-1).join("/")||"/",xL=t=>String(t).replace("file://",""),SL=wL(xL(import.meta.url)),_L=Zm(SL,"stdlib"),EL={readRelative(t,e){try{return mS(Zm(t,`${e}.rules`),"utf-8")}catch{return null}},readStdlib(t){try{return mS(Zm(_L,`${t}.rules`),"utf-8")}catch{return null}}};function AL(t,e){return z2(EL,t,e)}function jL(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(w=>{const _={};for(const[k,I]of Object.entries(d)){const R=w.get(I).data();_[k]=R===void 0?null:R}for(let k=0;k<f.length;k+=1){const I=f[k];if(I.method==="delete"){w.delete(I.path);continue}const N=I2(I.data,{reads:_});if(N===null||typeof N!="object"||Array.isArray(N))throw new ld(`writes[${k}].data resolved to a non-object`,`writes.${k}.data`);const R=N;switch(I.method){case"create":w.create(I.path,R);break;case"update":w.update(I.path,R);break;case"set":w.set(I.path,R);break}}},{auth:s,readOnly:o}),v={allowed:b.allowed,writes:b.writes.map(w=>{const _={path:w.path,method:w.method,allowed:w.allowed};return w.error&&(_.error={code:w.error.code,message:w.error.message}),g&&(_.debugMessages=w.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(w=>({path:w.path,data:w.data}))),{ok:b.allowed,summary:b.allowed?`Transaction committed (${f.length} write(s))`:"Transaction rolled back",data:v}}catch(b){if(b instanceof ld||b instanceof Ct||b instanceof xr||b instanceof Ln)return{ok:!1,summary:`Transaction failed: ${b.message}`,data:{allowed:!1,writes:[],error:{code:"invalid-argument",message:b.message}}};throw b}}}]}function WE(t){return jL({resolveSandbox:t.resolveSandbox,resolveModulesFn:AL})}function Fl(t){return t.replace(/^\/+|\/+$/g,"").split("/")}function QE(t){return Fl(t).length%2===0&&Fl(t).length>0}function dg(t){return Fl(t).length%2===1}function Bd(t){const e=Fl(t);return e[e.length-1]??""}function JE(t){return Fl(t).slice(0,-1).join("/")}function kL(t,e){const n=e!==void 0,r=n?fo(e):void 0;return{id:t.id,ref:t,exists:n,data:()=>n?r:void 0}}function $a(t,e){if(t.error)throw new sn(t.error);const n=t.debugMessages.length>0?t.debugMessages.join("; "):"(no debug message)";throw new sn(Pe("permission-denied",`${e}: ${n}`))}class fg{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=Bd(r),no(this,Bl("reference",r))}get parent(){return new Jm(this.env,this.auth,JE(this.path),this.bypassRules)}collection(e){return new Jm(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||$a(n,"get denied");const r=n.data===void 0||n.data===null?void 0:n.data;return kL(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||$a(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||$a(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||$a(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||$a(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||$a(n,"delete denied")}}const yS=new WeakMap;let CL=1;function gS(t){let e=yS.get(t);return e===void 0&&(e=CL++,yS.set(t,e)),e}function bS(t){if(t===null||typeof t=="boolean")return t;if(typeof t=="string")return LD(t);if(typeof t>"u")return{type:"undefined"};if(typeof t=="bigint")return Bl("bigint",t.toString());if(typeof t=="number"){const n=Number.isNaN(t)?"NaN":t===1/0?"Infinity":t===-1/0?"-Infinity":Object.is(t,-0)?"-0":String(t);return Bl("number",n)}if(typeof t!="object"&&typeof t!="function")return{type:typeof t,value:String(t)};const e=$D(t);if(e!==void 0)return e;try{if(Array.isArray(t))return{type:"array",id:gS(t)}}catch{}return{type:"opaque-object",id:gS(t)}}function NL(t){return typeof t.seconds=="number"&&(typeof t.nanos=="number"||typeof t.nanoseconds=="number")}function OL(t){return typeof t.latitude=="number"&&typeof t.longitude=="number"}function RL(t){return t.data instanceof Uint8Array}function TL(t){return typeof t.path=="string"}function hd(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 NL(n)?3:RL(n)?5:OL(n)?7:TL(n)?6:9}return 9}function vS(t){const e=typeof t.nanos=="number"?t.nanos:t.nanoseconds??0;return[t.seconds,e]}function DL(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 wS(t,e){return t<e?-1:t>e?1:0}function Xs(t,e){const n=hd(t),r=hd(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 DL(Number(t),Number(e));case 3:{const[s,o]=vS(t),[c,d]=vS(e);return s!==c?s<c?-1:1:o<d?-1:o>d?1:0}case 4:return wS(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 wS(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=Xs(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=Xs(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 IL(t,e,n){if(e<=0)return[];const r=[];for(const s of t)r.length<e?xS(r,s,n):n(s,r[r.length-1])<0&&(r.pop(),xS(r,s,n));return r}function xS(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 Ks="__name__",ML=new Set(["<","<=",">",">=","!=","not-in"]);function Wm(t,e){return e===Ks?{path:t.path}:t.data[e]}function hg(t){return t.kind==="where"?ML.has(t.op)?[t.field]:[]:t.filters.flatMap(hg)}function LL(t){return hg(t).length>0}function qd(t,e){return hd(t)===hd(e)}function UL(t,e){return qd(t,e)&&Xs(t,e)<0}function $L(t,e){return qd(t,e)&&Xs(t,e)<=0}function BL(t,e){return qd(t,e)&&Xs(t,e)>0}function qL(t,e){return qd(t,e)&&Xs(t,e)>=0}function FL(t,e,n){const r=t!==void 0;switch(e){case"==":return r&&Sr(t,n);case"!=":return r&&t!==null&&!Sr(t,n);case"<":return r&&UL(t,n);case"<=":return r&&$L(t,n);case">":return r&&BL(t,n);case">=":return r&&qL(t,n);case"in":return r&&Array.isArray(n)&&n.some(s=>Sr(t,s));case"not-in":return!Array.isArray(n)||n.some(s=>s===null)?!1:r&&t!==null&&!n.some(s=>Sr(t,s));case"array-contains":return Array.isArray(t)&&t.some(s=>Sr(s,n));case"array-contains-any":return Array.isArray(t)&&Array.isArray(n)&&n.some(s=>t.some(o=>Sr(o,s)))}}function zL(t,e){if(e===Ks){const n=t.path.split("/");return n[n.length-1]??t.path}return t.data[e]}function XE(t){if(Array.isArray(t))return t.map(XE);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=zL(t,e.field),r=e.field===Ks?XE(e.value):e.value;return FL(n,e.op,r)}return e.kind==="and"?e.filters.every(n=>Qm(t,n)):e.filters.some(n=>Qm(t,n))}function PL(t,e){return t.filter(n=>e.every(r=>Qm(n,r)))}function SS(t,e){const n=t.data();if(n===void 0)throw new sn({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===Ks?{path:t.ref.path}:n[r.field])}function _S(t,e,n){for(let r=0;r<e.length;r++){const s=Xs(Wm(t,n[r].field),e[r]);if(s!==0)return n[r].direction==="desc"?-s:s}return 0}function VL(t,e,n,r){return t.filter(s=>{if(n){const o=_S(s,n.values,e);if(n.inclusive?o<0:o<=0)return!1}if(r){const o=_S(s,r.values,e);if(r.inclusive?o>0:o>=0)return!1}return!0})}function eA(t,e){return t.filter(n=>e.every(r=>r.field===Ks||n.data[r.field]!==void 0))}function tA(t){return(e,n)=>{for(const r of t){const s=Xs(Wm(e,r.field),Wm(n,r.field));if(s!==0)return r.direction==="desc"?-s:s}return 0}}function HL(t,e){return e.length===0?t:eA(t,e).sort(tA(e))}class Fd{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:SS(e,this.normalizedOrders()),inclusive:n,fromSnapshot:!0}})}endCursorFromSnapshot(e,n){return this.clone({end:{values:SS(e,this.normalizedOrders()),inclusive:n,fromSnapshot:!0}})}clone(e){return new Fd(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,this.activityQuery());if(!r.allowed)throw new sn(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}}activityQuery(){const e=r=>r.kind==="where"?{kind:"where",field:r.field,op:r.op,value:bS(r.value)}:{kind:r.kind,filters:r.filters.map(e)},n=r=>r===void 0?null:{values:r.values.map(s=>bS(s)),inclusive:r.inclusive,fromSnapshot:r.fromSnapshot};return{scope:this.activityScope(),filters:this.clauses.map(e),orderBy:this.orders.map(r=>({...r})),limit:this.limitCount??null,limitFromEnd:this.limitFromEnd,start:n(this.start),end:n(this.end)}}activityScope(){return{kind:"collection"}}applyConstraints(e){let n=PL(e,[...this.clauses]);const r=this.normalizedOrders(),s=this.orders.length>0||this.start!==void 0||this.end!==void 0||this.clauses.some(LL);if(s&&this.limitCount!==void 0&&!this.limitFromEnd&&this.start===void 0&&this.end===void 0)return IL(eA(n,r),this.limitCount,tA(r));if(s&&(n=HL(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 sn({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=VL(n,r,this.start,this.end)}if(this.limitCount!==void 0)if(this.limitFromEnd){if(this.orders.length===0)throw new sn({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 hg(s))o!==Ks&&!n.has(o)&&(n.add(o),e.push({field:o,direction:r}));return n.has(Ks)||e.push({field:Ks,direction:r}),e}snapshotConstraints(){const e=n=>this.applyConstraints(n);return e.structured=this.structuredConstraints(),e.activityQuery=this.activityQuery(),e}async get(e){const r=this.applyConstraints(this.readCandidates(e)).map(s=>{const o=new fg(this.env,this.auth,s.path,this.bypassRules),c=fo(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]=KL(e[o],r);return{data:()=>s}}}function GL(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 KL(t,e){if(t.kind==="count")return e.length;let n=0,r=0;for(const s of e){const o=GL(s.data,t.field);typeof o=="number"&&Number.isFinite(o)&&(n+=o,r++)}return t.kind==="sum"?n:r===0?null:n/r}class pg extends Fd{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 pg(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))YL(s)===this.collectionId&&n.push({path:s,data:r[s]});return n}listRulePath(){return this.collectionId}activityScope(){return{kind:"collection-group"}}}function YL(t){const e=t.split("/").filter(n=>n.length>0);return e.length===0||e.length%2!==0?null:e[e.length-2]}class Jm extends Fd{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=Bd(s)}doc(n){const r=n??tg();return new fg(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 ZL{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 sn(n.error);const r=n.results.find(o=>!o.allowed),s=(r==null?void 0:r.debugMessages.join("; "))??"batch denied";throw new sn(Pe("permission-denied",`batch failed: ${s}`))}}function WL(t){return typeof t.where=="function"}class QL{constructor(e){G(this,"simTx");this.simTx=e}async get(e){if(WL(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=fo(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 JL{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(!dg(e))throw new sn(Pe("invalid-argument",`collection path must have an odd number of segments: ${e}`));return new Jm(this.env,this.auth,e,this.bypassRules)}doc(e){if(!QE(e))throw new sn(Pe("invalid-argument",`document path must have an even number of segments: ${e}`));return new fg(this.env,this.auth,e,this.bypassRules)}collectionGroup(e){if(e.length===0||e.includes("/"))throw new sn(Pe("invalid-argument",`collection group id must be a single non-empty segment with no '/': ${e}`));return new pg(this.env,this.auth,e,[],[],void 0,!1,void 0,void 0,this.bypassRules)}batch(){return new ZL(this.env,this.auth,this.bypassRules)}async runTransaction(e,n){let r;try{r=await this.env.transaction(s=>{const o=new QL(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 SE?new sn(s.simError):s}if(!r.allowed){if(r.error)throw new sn(r.error);const s=r.writes.find(c=>!c.allowed),o=(s==null?void 0:s.debugMessages.join("; "))??"transaction denied at commit";throw new sn(Pe("permission-denied",`transaction failed: ${o}`))}return r.returnValue}}function XL(t,e){return new JL(t,(e==null?void 0:e.auth)??null,(e==null?void 0:e.bypassRules)??!1,e==null?void 0:e.provenance)}const nA=Symbol("pyric/sandbox/context"),rA=Symbol("pyric/sandbox/bypassRules");let Xm=null;function eU(t){Xm=t}function tU(t){const e=t;return typeof e.path=="string"&&e.path.length>0||typeof e.collectionPath=="string"&&e.collectionPath.length>0}function nU(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 ES(t,e){if(!(t instanceof sn))return t;const n=t.code;if(n!=="permission-denied")return new nt(n,t.message);const r={auth:e.auth,reasons:nU(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}),s!=null&&s.query&&(r.query=s.query),(s==null?void 0:s.remediation)!==void 0?new nt({code:n,message:t.message,denialContext:r,remediation:s.remediation}):new nt(n,t.message,r)}function pd(t,e,n=!1){return new Proxy(t,{get(r,s,o){if(s===nA)return e;if(s===rA)return n;if(s==="onSnapshot"&&Xm!==null&&!(s in r)&&tU(r))return(...d)=>Xm(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,ql(e.operationContext),b))??b()}catch(b){throw ES(b,e)}return f instanceof Promise?f.then(b=>b&&typeof b=="object"?pd(b,e,n):b).catch(b=>{throw ES(b,e)}):f&&typeof f=="object"?pd(f,e,n):f}}})}function sA(t,e=!1){if(rg(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=()=>XL(Wt(t.sandbox),{auth:t.auth,bypassRules:e,provenance:ql(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 Wt(t.sandbox).deployRules(r)},seed(r){const s=Wt(t.sandbox);return s.seed({rules:s.getRules(),documents:(r==null?void 0:r.documents)??{}})},snapshot(){return Wt(t.sandbox).snapshot()}}}function ey(t){if(t instanceof nt)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 nt(e.code,e.message,n)}}return t}function ss(t){return new nt("invalid-argument",t)}async function fr(t,e){try{return await t.sandbox.channel.op({...e,actAs:t.lens})}catch(n){throw ey(n)}}const rU=new Set(["serverTimestamp","increment","arrayUnion","arrayRemove","deleteField"]);function sU(t){return t!==null&&typeof t=="object"&&typeof t.__type=="string"&&rU.has(t.__type)}function iU(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(os)};case"arrayRemove":return{__sentinel:"arrayRemove",values:t.values.map(os)};case"deleteField":return{__sentinel:"deleteField"}}}function os(t){var r;if(t===null||typeof t!="object")return t;if(sU(t))return iU(t);if(t instanceof $n)return t.toJSON();if(t instanceof Date)return $n.fromDate(t).toJSON();if(Array.isArray(t))return t.map(os);const e=Object.getPrototypeOf(t);if(e!==Object.prototype&&e!==null){const s=t.toJSON;if(typeof s=="function")return s.call(t);throw ss(`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]=os(o);return n}function zi(t){return os(t)}function ty(t){return Ud(JSON.parse(t.json))}function iA(t){return fo(ty(t))}function aA(t,e){const n=e.exists&&e.data?iA(e.data):void 0;return{id:t.id,ref:t,exists:e.exists,data:()=>n}}function oA(t,e){const n=e.docs.map(r=>{const s=r.path??r.id,o=md(t,s),c=r.data?iA(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 mg=Symbol("pyric/sandbox/admin-firestore/remoteSnapshotRegistrar");function aU(t){if(t===null||typeof t!="object")return;const e=t[mg];return typeof e=="function"?e:void 0}let ny=null;function oU(t){ny=t}function lA(...t){if(ny===null)throw new nt("failed-precondition","remote Firestore: onSnapshot is not wired yet — import pyric-admin/firestore (or pyric/sandbox/admin-firestore) before subscribing.");return ny(this,...t)}function cA(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(w=>({path:w.path??w.id,data:w.data?ty(w.data):{}})),b=e.__ref==="query"?e.source.__ref==="group"?e.source.collectionId:e.source.path:e.__ref==="group"?e.collectionId:e.path,v=Ha({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?ty(p.data):null;r(Va(g,b))}},f=>{const p=ey(f);s?s(p):console.error("pyric remote Firestore: uncaught onSnapshot error:",p)})}catch(f){throw ey(f)}return d}const uA=Symbol("pyric/sandbox/admin-firestore/remoteQueryState");function lU(t){if(!(t===null||typeof t!="object"))return t[uA]}function dA(t){return t.kind==="where"?(fA(t.op),{kind:"where",field:t.field,op:t.op,value:os(t.value)}):{kind:t.kind,filters:t.filters.map(dA)}}const cU=new Set(["<","<=","==","!=",">=",">","in","not-in","array-contains","array-contains-any"]);function fA(t){if(!cU.has(t))throw ss(`invalid where operator: ${String(t)}`)}function Bu(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(os)}),t.end&&e.push({kind:t.end.inclusive?"endAt":"endBefore",values:t.end.values.map(os)}),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 AS(t,e,n){if(e.length===0)throw ss(`${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 ss(`${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 nt("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 yg(t,e){const n=s=>yg(t,{...e,...s});return{[uA]:e,where(s,o,c){return fA(o),n({filters:[...e.filters,{kind:"where",field:s,op:o,value:os(c)}]})},applyFilter(s){return n({filters:[...e.filters,dA(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:AS(s,e.orders,o?"startAt":"startAfter"),inclusive:o}})},endCursorFromSnapshot(s,o){return n({end:{values:AS(s,e.orders,o?"endAt":"endBefore"),inclusive:o}})},async get(s){qu(e);const o=await fr(t,{method:"getDocs",source:Bu(e)});return oA(t,o)},async aggregate(s){qu(e);const o=await fr(t,{method:"aggregate",source:Bu(e),spec:s});return{data:()=>o.data}},[mg]:(s,o,c)=>(qu(e),cA(t,Bu(e),s,o,c)),onSnapshot:lA}}function qu(t){if(t.limitFromEnd&&t.orders.length===0)throw ss("limitToLast() queries require at least one orderBy clause.")}function ry(t,e){const n=yg(t,{source:{__ref:"collection",path:e},filters:[],orders:[],limitFromEnd:!1});return Object.assign(Object.create(Object.getPrototypeOf(n)),n,{id:Bd(e),path:e,doc(s){const o=s??tg();return md(t,`${e}/${o}`)},async add(s,o){const c=await fr(t,{method:"addDoc",collectionPath:e,data:zi(s)});return md(t,c.path)}})}function md(t,e){const n={id:Bd(e),path:e,get parent(){return ry(t,JE(e))},collection(r){const s=`${e}/${r}`;if(!dg(s))throw ss(`collection path must have an odd number of segments: ${s}`);return ry(t,s)},async get(r){const s=await fr(t,{method:"getDoc",path:e});return aA(n,s)},async set(r,s){await fr(t,{method:"setDoc",path:e,data:zi(r),...jS(s)?{options:jS(s)}:{}})},async update(r,s){await fr(t,{method:"updateDoc",path:e,data:zi(r)})},async delete(r){await fr(t,{method:"deleteDoc",path:e})},[mg]:(r,s,o)=>cA(t,{__ref:"doc",path:e},r,s,o),onSnapshot:lA};return n}function jS(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 uU(t){const e=[];let n=!1;const r={set(o,c){return s(),e.push({method:"set",path:o.path,data:zi(c)}),r},update(o,c){return s(),e.push({method:"update",path:o.path,data:zi(c)}),r},delete(o){return s(),e.push({method:"delete",path:o.path}),r},async commit(o){s(),n=!0,await fr(t,{method:"batchCommit",writes:e})}};function s(){if(n)throw new nt("failed-precondition","WriteBatch has already been committed.")}return r}const kS=5;async function dU(t,e){for(let n=0;n<kS;n++){const r=[],s=[],o=()=>{if(s.length>0)throw new nt("failed-precondition",Lm)},c={get(g){o();const b=lU(g);return b!==void 0?f(b):d(g)},set(g,b){return s.push({method:"set",path:g.path,data:zi(b)}),c},update(g,b){return s.push({method:"update",path:g.path,data:zi(b)}),c},delete(g){return s.push({method:"delete",path:g.path}),c}};async function d(g){const b=await fr(t,{method:"getDoc",path:g.path});return r.push({path:b.path??g.path,data:b.exists&&b.data?b.data:null}),aA(g,b)}async function f(g){qu(g);const b=await fr(t,{method:"getDocs",source:Bu(g)});for(const v of b.docs)r.push({path:v.path??v.id,data:v.data??null});return oA(t,b)}const p=await e(c);try{return await fr(t,{method:"txnCommit",reads:r,writes:s}),p}catch(g){if(g instanceof nt&&g.code==="aborted")continue;throw g}}throw new nt("aborted",`Transaction failed after ${kS} attempts due to repeated conflicts. Another writer is concurrently updating the same documents.`)}function Yp(t,e){return new nt("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 hA(t,e){const n={sandbox:t,lens:e};return{collection(r){if(!dg(r))throw ss(`collection path must have an odd number of segments: ${r}`);return ry(n,r)},doc(r){if(!QE(r))throw ss(`document path must have an even number of segments: ${r}`);return md(n,r)},collectionGroup(r){if(r.length===0||r.includes("/"))throw ss(`collection group id must be a single non-empty segment with no '/': ${r}`);return yg(n,{source:{__ref:"group",collectionId:r},filters:[],orders:[],limitFromEnd:!1})},batch(){return uU(n)},runTransaction(r,s){return dU(n,r)},setRules(){throw Yp("setRules","Deploy rules asynchronously through the relay instead: `await sandbox.channel.op({ method: 'setFirestoreRules', source })`.")},seed(){throw Yp("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 Yp("snapshot","Read the worker state asynchronously instead: `await sandbox.channel.op({ method: 'admin.readState' })`.")}}}const CS=new WeakMap;function pA(t){const e=CS.get(t);if(e)return e;const n=rg(t.sandbox)?hA(t.sandbox,fU(t.auth)):pd(sA(t),t);return CS.set(t,n),n}function fU(t){return t==null?{mode:"anon"}:t.token===void 0?{mode:"as",uid:t.uid}:{mode:"as",uid:t.uid,token:t.token}}const NS=new WeakMap;function hU(t){const e=pU(t)?t:t.withAuth(null),n=NS.get(e);if(n)return n;const r=e.operationContext.authLens.mode==="admin"?e:Wl(e,{source:e.operationContext.source,authLens:{mode:"admin"},...e.operationContext.planId===void 0?{}:{planId:e.operationContext.planId}}),s=rg(r.sandbox)?hA(r.sandbox,{mode:"admin"}):pd(sA(r,!0),r,!0);return NS.set(e,s),s}function pU(t){return t!==null&&typeof t=="object"&&"sandbox"in t&&typeof t.withAuth=="function"}const Ya=Symbol("pyric/firestore/followsCurrentUser"),kl=Symbol("pyric/firestore/authSessionScope");function mU(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 yU(t){if(t!==null&&typeof t=="object"){const e=t.snapshotConstraints;if(typeof e=="function")return e.call(t)}}function gU(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 mA(t,e,n,r,s){var N,R;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 M=n;c=M.next,d=M.error}}else if(typeof e=="function")c=e,d=n;else if(typeof e=="object"&&e!==null){const M=e;c=M.next,d=M.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=aU(t);if(p){if(o[Ya]===!0)throw new nt("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=bU(t),b=Wt(g.sandbox);let v;if(gU(t))v={kind:"doc",path:t.path};else{const M=mU(t);if(M===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 F=yU(t);v={kind:"query",collection:M,constraints:F}}const w=o[Ya]===!0,_=o[kl],k=t[rA]===!0;if(Ya in o){const{[Ya]:M,...F}=o;o=F}if(kl in o){const{[kl]:M,...F}=o;o=F}const I=()=>b.addSnapshotListener(v,c??(()=>{}),o,g.auth,d,w,k,_);return((R=(N=g.sandbox).runWithProvenance)==null?void 0:R.call(N,ql(g.operationContext),I))??I()}function bU(t){if(t===null||typeof t!="object")throw new TypeError("onSnapshot: reference must be a DocumentReference or Query.");const e=t[nA];if(!e)throw new TypeError("onSnapshot: reference was not produced by a sandbox context — pass a ref obtained from `getFirestore(ctx)`.");return e}eU(mA);oU(mA);class Er{constructor(e){G(this,"bytes");this.bytes=e,no(this,UD(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 Er(r)}static fromUint8Array(e){return new Er(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 Er&&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 Er.fromBase64String(n.bytes)}}class Or{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.");no(this,Bl("geo-point",String(e),"\0",String(n)))}get latitude(){return this.lat}get longitude(){return this.lng}isEqual(e){return e instanceof Or&&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 Or(n.latitude,n.longitude)}}class Cl{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 Cl(e.slice())}toArray(){return this._values.slice()}isEqual(e){const n=e instanceof Cl?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 Cl.create(n.vectorValues)}}function vU(t=[]){return Cl.create(t)}function Zz(){return BD.serverTimestamp()}const Ys=Symbol("pyric/firestore/target");function ni(t){return t.kind==="sandbox"?t.db:t.getDb()}const zd=new WeakMap;function sy(t,e){return zd.set(t,e),t}const Qi=new WeakMap;function wU(t,e,n){return zd.set(t,e),Qi.set(t,n),t}function Pd(t,e){const n=Ji(e);if(t.kind==="sandbox")return n;const r=Qi.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(ni(t))}function xU(t,e){const n=Ji(e);if(t.kind==="sandbox")return n;const r=Qi.get(n);if(!r)throw new TypeError("pyric/firestore: live collection ref missing rebuild closure.");return r(ni(t))}function SU(t,e){const n=Ji(e);if(t.kind==="sandbox")return n;const r=Qi.get(n);if(!r)throw new TypeError("pyric/firestore: live query missing rebuild closure.");return r(ni(t))}function ao(t,e,n){return e.kind==="sandbox-live"?wU(t,e,n):sy(t,e)}function _U(t){const e=Ji(t),n=Qi.get(e);return n||(()=>e)}function Tr(t){var n;let e;if(Ys in t?e=t[Ys]:e=zd.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 yA=new WeakMap,yd=new WeakMap;function mo(t){return yA.get(t)}function Ji(t){return yd.get(t)??t}function gg(t,e,n){const r={id:t.id??"",path:t.path??""};return yA.set(r,n),yd.set(r,t),zd.set(r,e),r}function OS(t){return Array.isArray(t)&&t.every(e=>typeof e=="number")}function EU(t){if(t instanceof uo)return Array.from(t.value);if(t===null||typeof t!="object")return null;const e=t;return e.typeName==="vector"&&OS(e.value)||e.__type__==="__vector__"&&OS(e.value)?e.value:null}function iy(t){if(t instanceof In)return Er.fromUint8Array(t.data);if(t instanceof Cr)return new Or(t.lat,t.lng);const e=EU(t);if(e)return vU(e);if(Array.isArray(t))return t.map(iy);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]=iy(o);return r}}return t}function gA(t){if(t!==void 0)return iy(t)}function Vd(t){if(t===void 0)return Vd(HE());const e=sg(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=>{Wt(n).reevaluateLiveListeners(d,o)}));const c={kind:"sandbox-live",sandbox:n,getDb:RS(n,()=>r.currentUser),authScope:o,own:d=>e.onDelete(d),assertUsable:()=>{if(s)throw new Wi("failed-precondition","The client has already been terminated.")}};return{[Ys]:c,app:t}});if(bA(t)){const r={kind:"sandbox",db:pA(t),sandbox:t.sandbox};return{[Ys]:r}}if(AU(t)){const n={kind:"sandbox-live",sandbox:t,getDb:RS(t)};return{[Ys]: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 bg(t){const e=sg(t);if(e){e.assertAlive();const c=e.sandbox;return bg(Wl(c.withAuth(null),{source:{kind:"app"},authLens:{mode:"admin"}}))}const n=bA(t)?t:t.withAuth(null),r=n.sandbox,o={kind:"sandbox",db:hU(n),sandbox:r};return{[Ys]:o}}function bA(t){return t instanceof ho}function AU(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 RS(t,e=()=>t.currentUser){return()=>{const n=Wl(t.withAuth(e()),{source:{kind:"app"},authLens:{mode:"app-session"}});return pA(n)}}function gd(t){const e=t,n=e.data.bind(t);return Object.defineProperty(e,"data",{value:()=>gA(n()),configurable:!0,writable:!0}),t}function vA(t,e){return{id:t.id,exists:t.exists,data:()=>{if(!(typeof t.exists=="function"?t.exists():t.exists))return;const r=gA(t.data()),s={id:t.id,exists:!0,data:()=>r};return e.fromFirestore(s)}}}function Hd(t,e){if(!t||typeof t!="object")return t;const n=t;if(n.ref&&(sy(n.ref,e),TS(n.ref,e)),DS(n),Array.isArray(n.docs))for(const r of n.docs)r!=null&&r.ref&&(sy(r.ref,e),TS(r.ref,e)),r&&DS(r);return t}function TS(t,e){if(typeof t.path!="string"||t.path.length===0||yd.has(t))return;const n=t.path;try{const r=ni(e).doc(n);yd.set(t,r),e.kind==="sandbox-live"&&Qi.set(r,s=>s.doc(n))}catch{}}function DS(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 vg(t){const e=Tr(t),n=mo(t),r=await Pd(e,t).get();return n?vA(r,n):(Hd(r,e),gd(r))}async function zl(t){const e=Tr(t),n=mo(t),r=await SU(e,t).get();if(n){const o=n,c=r.docs.map(d=>vA(d,o));return{size:c.length,empty:c.length===0,docs:c}}Hd(r,e);const s=r.docs;for(const o of s)gd(o);return r}function ur(t,...e){const n=Tr(t),r=Ys in t,s=r?void 0:mo(t),o=ni(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 ao(b,n,w=>w.doc(g))}const c=Ji(t),d=e.length===0?c.doc():c.doc(e.join("/")),f=d.path,p=ao(d,n,g=>g.doc(f));return s?gg(p,n,s):p}function Ui(t,...e){const n=Tr(t),r=Ys in t;if(e.length===0)throw new TypeError("collection() requires at least one path segment.");if(r){const f=e.join("/"),p=ni(n).collection(f);return ao(p,n,g=>g.collection(f))}const s=Ji(t),o=e.join("/"),c=s.collection(o),d=c.path;return ao(c,n,f=>f.collection(d))}async function Pl(t,e,n){const r=Tr(t),s=mo(t),o=s?s.toFirestore(e):e;return Pd(r,t).set(o,n)}async function ay(t,e){const n=Tr(t);return Pd(n,t).update(e)}async function bd(t){const e=Tr(t);return Pd(e,t).delete()}async function wg(t,e){const n=Tr(t),r=mo(t),s=r?r.toFirestore(e):e,o=await xU(n,t).add(s),c=o.path,d=ao(o,n,f=>f.doc(c));return r?gg(d,n,r):d}function wA(t){return typeof t=="string"?t:t._internalPath.segments.join(".")}function Vl(t,...e){const n=Tr(t),r=mo(t),s=_U(t),o=f=>{let p=s(f);for(const g of e)p=g.applySandbox(p);return p},c=o(ni(n)),d=ao(c,n,f=>o(f));return r?gg(d,n,r):d}function jU(t,e,n){const r=wA(t);return{applySandbox:o=>o.where(r,e,n),_sandboxFilter:{kind:"where",field:r,op:e,value:n}}}function IS(t,e){const n=wA(t);return{applySandbox:r=>r.orderBy(n,e)}}function vd(t){return{applySandbox:e=>e.limit(t)}}function kU(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 CU(...t){if(kU(t)){const e=t[0];return{applySandbox:n=>n.startCursorFromSnapshot(e,!1)}}return{applySandbox:e=>e.startCursor(t,!1)}}function NU(t,e,n,r){const s=Tr(t),o=RU(s,t),c=TU(e,n,r,s),d=DU(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 w;p||(g(),(w=OU(d))==null||w(new Wi("aborted","The operation was aborted.")))},v=s.own(b);return()=>{v(),g()}}function OU(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 RU(t,e){const n=Ji(e);if(t.kind==="sandbox")return n;const r=Qi.get(n);if(!r)throw new TypeError("pyric/firestore: live ref missing rebuild closure for onSnapshot.");return r(ni(t))}function xA(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 TU(t,e,n,r){if(typeof t=="object"&&t!==null&&!xA(t)){const o=e;return typeof o=="function"?[t,MS(o,r),n??oy]:o&&typeof o=="object"?[t,LS(o,r)]:[t]}return typeof t=="function"?[MS(t,r),e??oy]:t&&typeof t=="object"?[LS(t,r)]:[t]}function DU(t,e){if(e.kind!=="sandbox-live")return t;const n=t[0];return typeof n=="object"&&n!==null&&!xA(n)?[{...n,[Ya]:!0,...e.authScope?{[kl]:e.authScope}:{}},...t.slice(1)]:[{[Ya]:!0,...e.authScope?{[kl]:e.authScope}:{}},...t]}function SA(t,e){if(!t||typeof t!="object")return t;const n=t;if(typeof n.data=="function"&&gd(t),Array.isArray(n.docs))for(const r of n.docs)gd(r);return t}function oy(t){console.error("pyric/firestore: Uncaught Error in snapshot listener:",t)}function MS(t,e){return n=>t(SA(Hd(n,e)))}function LS(t,e){return{...t,next:t.next?n=>t.next(SA(Hd(n,e))):void 0,error:t.error??oy}}function Wz(t,e){return Wt(t).deployRules(e)}function IU(t,e={}){const n=e.recentEventLimit??10,r=Wt(t),s=r.getRules(),o=s?Yu(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 I=k.split("/")[0]??"";I&&(p[I]=(p[I]??0)+1)}const g=t.history(),b=g.filter(k=>k.kind==="request"),v=b.filter(k=>k.result==="deny"),w=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:w}}}const Ls={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"]}]},MU=["<","<=","==","!=",">=",">","in","not-in","array-contains","array-contains-any"],LU={type:"object",properties:{field:{type:"string"},op:{type:"string",enum:[...MU]},value:{}},required:["field","op","value"]};function _A(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:Ls},required:["path"]},async execute(n){const r=n,s=await e(r.as),o=ur(s,r.path),c=await vg(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:Ls},required:["collection"]},async execute(n){const r=n,s=await e(r.as),o=Ui(s,r.collection),c=[];r.orderBy&&c.push(IS(r.orderBy)),r.limit&&c.push(vd(r.limit));const d=await zl(Vl(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:Ls},required:["path","data"]},async execute(n){const r=n,s=await e(r.as);return await Pl(ur(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:Ls},required:["collection","data"]},async execute(n){const r=n,s=await e(r.as),o=await wg(Ui(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:Ls},required:["path","data"]},async execute(n){const r=n,s=await e(r.as);return await ay(ur(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:Ls},required:["path"]},async execute(n){const r=n,s=await e(r.as);return await bd(ur(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:Ls},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=ur(s,o.path);o.op==="set"?await Pl(c,o.data??{}):o.op==="update"?await ay(c,o.data??{}):await bd(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:LU,minItems:1},orderBy:{type:"string"},limit:{type:"number"},as:Ls},required:["collection","where"]},async execute(n){const r=n,s=await e(r.as),o=Ui(s,r.collection),c=r.where.map(f=>jU(f.field,f.op,f.value));r.orderBy&&c.push(IS(r.orderBy)),r.limit&&c.push(vd(r.limit));const d=await zl(Vl(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 EA(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=IU(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 US(t,e){return{code:t.code,severity:e,message:t.message,path:t.path,origin:"validate"}}let Di=[],ly=!1,cy=!1,uy=!1,Zp;function UU(){if(Zp)return Zp;const t=Md();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"&&(uy=!0)},ident(e,n,r){const s=this.sourceString;s==="data"&&(ly=!0),s==="newData"&&(cy=!0)},bool_true(e){Di.push({code:"HARDCODED_TRUE",message:"Rule expression is hardcoded to true"})},bool_false(e){Di.push({code:"HARDCODED_FALSE",message:"Rule expression is hardcoded to false"})},Comparison_looseEq(e,n,r){Di.push({code:"LOOSE_EQUALITY",message:"Use '===' instead of '=='"}),e.lint(),r.lint()},Comparison_looseNeq(e,n,r){Di.push({code:"LOOSE_INEQUALITY",message:"Use '!==' instead of '!='"}),e.lint(),r.lint()}}),Zp=t,t}function $U(t,e="read"){const n=Id(t);return n.failed()?[]:(Di=[],ly=!1,cy=!1,uy=!1,UU()(n).lint(),e==="write"&&ly&&!cy&&!uy&&Di.push({code:"DATA_IN_WRITE",message:"Write rule references 'data' but not 'newData'; consider using 'newData' to check incoming data"}),[...Di])}const BU={read:new Set(["auth","data","root","now"]),write:new Set(["auth","data","newData","root","now"]),validate:new Set(["auth","data","newData","root","now"])},qU=new Set(["val","exists","hasChild","hasChildren","isString","isNumber","isBoolean","child","parent","getPriority"]),FU=new Set(["matches","contains","beginsWith","endsWith","replace","toLowerCase","toUpperCase","length"]),zU=new Set([...qU,...FU]);let Nl=[],Fu="read",AA=new Set,Wp;function PU(){if(Wp)return Wp;const t=Md();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;zU.has(d)||Nl.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=BU[Fu];c&&(!c.has(s)&&!AA.has(s)&&Nl.push({code:"UNKNOWN_IDENTIFIER",message:`Identifier '${s}' is not allowed in '${Fu}' context`}),s==="newData"&&Fu==="read"&&Nl.push({code:"NEWDATA_IN_READ",message:"'newData' is not available in 'read' context"}))}}),Wp=t,t}function VU(t,e,n=[]){const r=Id(t);return r.failed()?[]:(Nl=[],Fu=e,AA=new Set(n.map(s=>s.startsWith("$")?s.slice(1):s)),PU()(r).validate(),[...Nl])}const HU=new Set(["__proto__","prototype","constructor"]);function $S(t,e){return HU.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 is{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 is(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 is(this._root,"/");return n==="/"?r:r.child(e.join("/"))}getPriority(){return null}}class GU{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 $s={auth:null,data:new is(null),newData:new is(null),root:new is(null),now:Date.now(),pathVariableBindings:{}},Qp;function KU(){if(Qp)return Qp;const t=Md();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 is)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 GU(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:$S(s,r.sourceString)},CallExpr_indexAccess(e,n,r,s){const o=e.eval(),c=r.eval();return o==null?null:$S(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 $s.pathVariableBindings)return $s.pathVariableBindings[s];switch(s){case"auth":return $s.auth;case"data":return $s.data;case"newData":return $s.newData;case"root":return $s.root;case"now":return $s.now;default:return}}}),Qp=t,t}function jA(t,e){const n=Id(t);if(n.failed())throw new Error(n.message??"RTDB expression failed to parse");return $s=e,KU()(n).eval()}const YU=Mn({operation:to(["read","write","validate"]),path:vn().min(1).startsWith("/"),auth:Dd([Mn({uid:vn(),token:Qs(rs())}),uE()]),mockData:Qs(rs()),newData:rs().optional(),updates:dE(Mn({path:vn().min(1).startsWith("/"),value:rs()})).optional()});to(["INVALID_INPUT","NO_MATCHING_RULE","EVALUATION_ERROR"]);Mn({allowed:$l(),unsupported:$l().optional(),matchedPath:vn(),matchedRule:vn(),reason:vn(),pathVariableBindings:Qs(vn())});function ZU(t){const e=t.val();return e===null||typeof e!="object"?[]:Object.keys(e)}function WU(t,e,n,r,s,o){let c=null;function d(p,g,b,v,w){if(!b.exists())return null;const _=p.validate;if(_){if(!_.parsed.valid)c||(c={node:p,rule:_,bindings:v,unsupported:!0});else if(!jA(_.raw,s(g,b,v)))return{node:p,rule:_,bindings:v}}for(const k of p.children){const I=k.path.split("/").filter(Boolean);if(I.length===0)continue;const N=I[I.length-1],R=N.startsWith("$");if(w.length>0){if(!R&&w[0]!==N)continue;return d(k,g.child(w[0]),b.child(w[0]),R?{...v,[N]:w[0]}:v,w.slice(1))}if(R)for(const M of ZU(b)){const F=d(k,g.child(M),b.child(M),{...v,[N]:M},[]);if(F)return F}else{const M=d(k,g.child(N),b.child(N),v,[]);if(M)return M}}return null}return d(t,e,n,r,o)??c}function kA(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=kA(o,e.slice(1),p,r+1);return s.push(...g),s}}return s}function dy(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=dy(c,s,n);return d==null?delete o[r]:o[r]=d,o}function QU(t,e,n,r){if(!r||r.length===0)return dy(t,e,n??null);let s=t;for(const o of r){const c=o.path.split("/").filter(Boolean);s=dy(s,c,o.value??null)}return s}class JU{execute(e,n){const r=YU.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=kA(b,g,{}),w=new is(d,"/"),_=s==="read"?d:QU(d,g,f,p),k=new is(_,"/"),I=(F,D,C)=>{const L={};for(const[U,H]of Object.entries(C))L[U]=H,L[U.slice(1)]=H;return{auth:c?{uid:c.uid,token:c.token}:null,data:F,newData:D,root:w,now:Date.now(),pathVariableBindings:L}};let N;for(const F of v){const D=F.node[s];if(!D)continue;if(!D.parsed.valid){N||(N=F);continue}const C=g.slice(0,F.depth).join("/"),L=w.child(C),U=k.child(C);if(jA(D.raw,I(L,U,F.pathVariableBindings))){if(s==="write"){const z=WU(b,w,k,{},I,g);if(z)return{success:!0,data:{allowed:!1,unsupported:z.unsupported===!0,matchedPath:z.node.path,matchedRule:z.rule.raw,reason:z.unsupported?`Validation rule at '${z.node.path}' contains an expression the simulator cannot evaluate: ${z.rule.raw} — not evaluated; production may reject this write.`:"Validation rule evaluated to false",pathVariableBindings:z.bindings}}}return{success:!0,data:{allowed:!0,matchedPath:F.node.path,matchedRule:D.raw,reason:"Rule expression evaluated to true",pathVariableBindings:F.pathVariableBindings}}}}if(N){const F=N.node[s];return{success:!0,data:{allowed:!1,unsupported:!0,matchedPath:N.node.path,matchedRule:F.raw,reason:`'${s}' rule at '${N.node.path}' contains an expression the simulator cannot evaluate: ${F.raw} — not evaluated; production may reject or allow this ${s}.`,pathVariableBindings:N.pathVariableBindings}}}const R=v[v.length-1],M=R.node[s];return M?{success:!0,data:{allowed:!1,matchedPath:R.node.path,matchedRule:M.raw,reason:"Rule expression evaluated to false",pathVariableBindings:R.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 XU=new Set([".read",".write",".validate",".indexOn"]);function CA(t,e,n=[]){const r=K2(t),s=r.valid?VU(t,e,n):r.errors,o=r.valid?$U(t,e):[];return{raw:t,parsed:{...r,errors:s,warnings:o}}}function NA(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]=CA(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(XU.has(o)||typeof c!="object"||c===null)continue;const d=e==="/"?`/${o}`:`${e}/${o}`,f=o.startsWith("$")?[...n,o]:[...n];r.children.push(NA(c,d,f))}return r}function OA(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 NA(e.rules,"/",[])}function Jp(t){return t==="true"?!0:t==="false"?!1:t}function RA(t){const e={};t.read&&(e[".read"]=Jp(t.read.raw)),t.write&&(e[".write"]=Jp(t.write.raw)),t.validate&&(e[".validate"]=Jp(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]]=RA(n)}return e}function e$(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:RA(t)}}function xg(t,e){return new JU().execute(t,e)}const ts=t=>t,BS=(...t)=>ts(t.map(e=>`(${e})`).join(" && ")),t$=(...t)=>ts(t.map(e=>`(${e})`).join(" || ")),TA=t=>t,n$=()=>TA("newData.hasChildren()"),r$=t=>TA(`newData.hasChild("${t}")`);function DA(t,e){const n=t.shape,r=[],s={};for(const[d,f]of Object.entries(n)){const p=f,g=p instanceof jr,b=g?p.unwrap():p;g||r.push(d);const v=IA(b,d),w=e==null?void 0:e[d];if(w&&w.length>0?s[d]={validate:BS(v,...w)}:s[d]={validate:v},b instanceof mt){const _=DA(b);s[d]={validate:_.validate,children:_.children}}}const o=[n$()];for(const d of r)o.push(r$(d));return{validate:BS(...o),children:s}}function IA(t,e){if(t instanceof _r)return ts("newData.isString()");if(t instanceof $i)return ts("newData.isNumber()");if(t instanceof Ju)return ts("newData.isBoolean()");if(t instanceof Ws){const n=t.options;return ts(n.map(r=>`newData.val() === "${r}"`).join(" || "))}if(t instanceof Ul){const n=t.value;return ts(typeof n=="string"?`newData.val() === "${n}"`:`newData.val() === ${n}`)}if(t instanceof Ml){const n=t._def.options;return t$(...n.map(r=>IA(r,e)))}if(t instanceof mt)return ts("newData.hasChildren()");throw new Error(`Unsupported Zod type for RTDB rules: ${t.constructor.name} on field "${e}"`)}function s$(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=MA(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!=="/"&&i$(r,s);for(const[s,o]of n){const c=s==="/"?r:Sg(r,s);c&&a$(r,c,o,s)}return r}function i$(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 a$(t,e,n,r){const s=r.split("/").filter(o=>o.startsWith("$"));if(n.read&&(e.read=Ba(n.read,"read",s)),n.write&&(e.write=Ba(n.write,"write",s)),n.validate&&(e.validate=Ba(n.validate,"validate",s)),n.schema){const o=DA(n.schema,n.fieldConstraints);e.validate||(e.validate=Ba(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=Ba(d.validate,"validate",s),"children"in d&&d.children)for(const[g,b]of Object.entries(d.children)){const v=`${f}/${g}`;let w=p.children.find(_=>_.path===v);w||(w={path:v,pathVariables:s,children:[]},p.children.push(w)),w.validate=Ba(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=Sg(t,d);f&&(f.indexOn=n.indexOn)}}}function MA(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(...MA(c))}}return e}function Ba(t,e,n){return CA(String(t),e,n)}function Sg(t,e){if(t.path===e)return t;for(const n of t.children){const r=Sg(n,e);if(r)return r}return null}function o$(t){return t==null?null:typeof t=="string"?{uid:t,token:{}}:{uid:t.uid,token:t.token??{}}}function l$(t){return{operation:t.operation,path:t.path,auth:o$(t.auth),mockData:t.mockData??t.data??{},...t.newData!==void 0?{newData:t.newData}:{}}}function Xp(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 fy(t,e){const n=[...Xp(t.path,".read",t.read,e),...Xp(t.path,".write",t.write,e),...Xp(t.path,".validate",t.validate,e)];for(const r of t.children)n.push(...fy(r,e));return n}class c${constructor(e){G(this,"definition");this.definition=e}compile(){return s$(this.definition.paths)}toJSON(){return e$(this.compile())}check(){try{const e=this.compile(),n=fy(e,"errors"),r=fy(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 xg(this.compile(),l$(e))}}function u$(t){return new c$(t)}function d$(t){const e=t;return typeof e.toJSON=="function"&&typeof e.simulate=="function"&&typeof e.check=="function"}function f$(t){const e=t;return typeof e=="object"&&e!==null&&"rules"in e&&!("paths"in e)&&typeof e.toJSON!="function"}class em{constructor(e){G(this,"doc");this.doc=e}lint(){const e=this.doc.check();return[...e.errors.map(n=>US(n,"error")),...e.warnings.map(n=>US(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 h$(t){return t==null?null:typeof t=="string"?{uid:t,token:{}}:{uid:t.uid,token:t.token??{}}}class p${constructor(e){G(this,"json");G(this,"compiled");this.json=e,this.compiled=OA(e)}toJSON(){return this.json}compile(){return this.compiled}check(){return{ok:!0,errors:[],warnings:[]}}simulate(e){return xg(this.compiled,{operation:e.operation,path:e.path,auth:h$(e.auth),mockData:e.mockData??e.data??{},...e.newData!==void 0?{newData:e.newData}:{}})}}function m$(t){return d$(t)?new em(t):f$(t)?new em(new p$(t)):new em(u$(t))}const y$=new Set(["__proto__","prototype","constructor"]);function et(t){if(t===""||t==="/")return[];const e=t.split("/").filter(n=>n.length>0);for(const n of e)if(y$.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 rn(t){return t.length===0?"/":"/"+t.join("/")}function Ps(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(n=>Ps(n));const e={};for(const[n,r]of Object.entries(t))e[n]=Ps(r);return e}function qS(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Qa(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)=>Qa(s,e[o]));if(!qS(t)||!qS(e))return!1;const n=Object.keys(t),r=Object.keys(e);return n.length!==r.length?!1:n.every(s=>s in e&&Qa(t[s],e[s]))}class g${constructor(){G(this,"root",{})}snapshot(){return Ps(this.root)}restore(e){this.root=Ps(e)}read(e){const n=et(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 Ps(r)}write(e,n){const r=et(e),s=this.read(e);if(r.length===0)return n===null?(this.root={},s):(this.root=Ps(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]=Ps(n),s}multiUpdate(e){const r=Object.entries(e).map(([o,c])=>({path:rn(et(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=et(e);for(const[o,c]of Object.entries(n)){const d=[...s,...et(o)],f=rn(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 FS="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz";let zS=0;const Ai=new Array(12).fill(0);function b$(t=Date.now()){const e=t===zS;zS=t;const n=new Array(8);let r=t;for(let o=7;o>=0;o--)n[o]=FS.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&&Ai[o]===63;o--)Ai[o]=0;if(o<0)for(let c=0;c<12;c++)Ai[c]=Math.floor(Math.random()*64);else Ai[o]=(Ai[o]??0)+1}else for(let o=0;o<12;o++)Ai[o]=Math.floor(Math.random()*64);for(let o=0;o<12;o++)s+=FS.charAt(Ai[o]);if(s.length!==20)throw new Error(`RTDB push-id: bad length ${s.length}.`);return s}function v$(t){return t===null||typeof t!="object"?!1:t[".sv"]==="timestamp"}function w$(t){if(t===null||typeof t!="object")return!1;const e=t[".sv"];return e!==null&&typeof e=="object"&&typeof e.increment=="number"}function vr(t,e,n){if(v$(t))return e;if(w$(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)=>vr(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]=vr(c,e,r?r[o]:void 0);return s}function ji(){const t=new Error("PERMISSION_DENIED: Permission denied");return t.code="PERMISSION_DENIED",t}class x${constructor(){G(this,"compiled",null)}setRules(e){if(e===null){this.compiled=null;return}this.compiled=OA(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=xg(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 LA(t,e){if(t===e)return 0;if(t===null)return-1;if(e===null)return 1;const n=PS(t),r=PS(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 PS(t){return t===null?0:typeof t=="boolean"?1:typeof t=="number"?2:typeof t=="string"?3:4}const S$=/^-?(0*)\d{1,10}$/,_$=-2147483648,E$=2147483647;function VS(t){if(S$.test(t)){const e=Number(t);if(e>=_$&&e<=E$)return e}return null}function wd(t,e){if(t===e)return 0;const n=VS(t),r=VS(e);return n!==null?r!==null?n-r===0?t.length-e.length:n-r:-1:r!==null?1:t<e?-1:1}function hy(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 qa(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 wd(o.key,c.key);const d=hy(e.orderBy,o.key,o.value),f=hy(e.orderBy,c.key,c.value),p=LA(d,f);return p!==0?p:wd(o.key,c.key)});for(const o of e.bounds)r=r.filter(c=>A$(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 A$(t,e,n){const s=(n??{kind:"key"}).kind==="key"?wd(e.key,String(t.value)):LA(hy(n,e.key,e.value),t.value),o=c=>wd(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 j$=/[\[\].#$/\u0000-\u001F\u007F]/;function k$(t){return t.length!==0&&!j$.test(t)}function C$(t){return typeof t=="number"&&(Number.isNaN(t)||t===1/0||t===-1/0)}function N$(t){return t===".priority"||t===".value"||t===".sv"}function O$(t,e){py(t,e,"set")}function py(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(C$(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&&py(s,`${e}/${r}`,n)}return}for(const[r,s]of Object.entries(t)){if(!N$(r)&&!k$(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 "]"`);py(s,`${e}/${r}`,n)}}}function Us(t,e){return O$(t,e),my(t)}function my(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=my(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=my(r);s!==null&&(e[n]=s)}return Object.keys(e).length===0?null:e}function zu(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(c=>zu(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:zu(f)}return c}const o={};for(const[c,d]of Object.entries(e))o[c]=zu(d);return o}function Jr(t){return t==="unsupported"?"unsupported":"deny"}class R${constructor(e){G(this,"tree",new g$);G(this,"rules",new x$);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{Vs(this.sandbox,$d({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{Vs(this.sandbox,FE({service:"rtdb",method:n,path:br(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{Vs(this.sandbox,CI({service:"rtdb",method:n,path:br(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{Vs(this.sandbox,NI({service:"rtdb",phase:e,listenerId:n.id,target:{kind:s.event??"value",path:br(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=Us(vr(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=qa(this.tree.read(e),n);return this.emitOperation(null,"get",e,"not-applicable",void 0,{origin:"admin",request:{query:n},resourceBefore:{data:Au(r),exists:r.length>0}}),r}adminSet(e,n){const r=Date.now(),s=this.tree.read(e),o=Us(vr(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,w]of Object.entries(n)){const _=rn([...et(e),...et(v)]);g[_]=Us(vr(w,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=rn([...et(e),...et(g)]);f.push(v),d[g]=Us(vr(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,Jr(o.check),o,{at:r,durationMs:Date.now()-r,resourceBefore:{data:s,exists:s!==null}}),ji();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=vr(r,o,this.tree.read(n)),d=Us(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,Jr(g.check),g,{at:p,durationMs:Date.now()-p,request:{data:r,resourceData:r},resourceBefore:b,resourceAfter:v}),ji();this.emitOperation(e,s,n,"allow",g,{at:p,durationMs:Date.now()-p,request:{data:r,resourceData:r},resourceBefore:b,resourceAfter:v});const w=this.snapshotChildListenerParents();this.tree.write(n,d),this.fanOut([n]),this.fanOutChildren(w);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,br(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(w=>w.includes("/"))){const w=this.nextGroupId("update"),_={};for(const[F,D]of Object.entries(r)){const C=[...et(n),...et(F)],L=rn(C);_[L]=Us(vr(D,s,this.tree.read(L)),L)}const k=this.tree.snapshot(),I=Object.entries(_).map(([F,D])=>({path:F,value:D}));for(const[F,D]of Object.entries(_)){const C=Date.now(),L=this.tree.read(F),U=this.rules.evaluate("write",F,{auth:e,mockData:k,newData:D,updates:I}),H={at:C,durationMs:Date.now()-C,origin:"batch",request:{data:D,resourceData:D},resourceBefore:{data:L,exists:L!==null},resourceAfter:{data:D,exists:D!==null},groupId:w,groupKind:"batch",detail:{multiPath:!0,rootPath:br(n)}};if(U.check!=="allow")throw this.emitOperation(e,"update",F,Jr(U.check),U,H),ji();this.emitOperation(e,"update",F,"allow",U,H)}const N=this.tree.read(n),R=this.snapshotChildListenerParents();this.tree.multiUpdate(_),this.fanOut(Object.keys(_)),this.fanOutChildren(R);const M=this.tree.read(n);this.emitCommit(e,"update",n,{data:r,priorState:N,nextState:M,groupId:w,groupKind:"batch",replay:{requestTime:s},detail:{multiPath:!0,paths:Object.keys(_)}}),this.emitRtdbEvent(e,"update",br(n),{after:_,detail:{multiPath:!0,paths:Object.keys(_)}}),this.notifyWrite();return}const c={};for(const[w,_]of Object.entries(r)){const k=rn([...et(n),...et(w)]);c[w]=Us(vr(_,s,this.tree.read(k)),k)}const d=this.tree.snapshot(),f=[],p=this.nextGroupId("update");for(const[w,_]of Object.entries(c)){const k=rn([...et(n),...et(w)]);f.push(k);const I=Date.now(),N=this.tree.read(k),R=this.rules.evaluate("write",k,{auth:e,mockData:d,newData:_}),M={at:I,durationMs:Date.now()-I,origin:"batch",request:{data:_,resourceData:_},resourceBefore:{data:N,exists:N!==null},resourceAfter:{data:_,exists:_!==null},groupId:p,groupKind:"batch",detail:{multiPath:!1,rootPath:br(n),key:w}};if(R.check!=="allow")throw this.emitOperation(e,"update",k,Jr(R.check),R,M),ji();this.emitOperation(e,"update",k,"allow",R,M)}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",br(n),{after:c,detail:{multiPath:!1,keys:Object.keys(c)}}),this.notifyWrite()}onValue(e,n,r,s){const o=Date.now(),c=this.rules.evaluate("read",n==="/"?"/":n,{auth:e,mockData:this.tree.snapshot()});if(c.check!=="allow")throw this.emitOperation(e,"listen",n,Jr(c.check),c,{at:o,durationMs:Date.now()-o,request:s?{query:s}:void 0,origin:"listener"}),this.emitListener("errored",{id:this.nextListenerId(),path:n},e,{event:"value",result:"deny",error:{code:"PERMISSION_DENIED",message:"PERMISSION_DENIED: Permission denied",reasons:c.reasons}}),ji();return this.attachValueListener(e,n,r,s,{origin:"listener",result:"allow",evaluation:c,at:o})}adminOnValue(e,n,r){return this.attachValueListener(null,e,n,r,{origin:"admin",result:"not-applicable",evaluation:void 0,at:Date.now()})}attachValueListener(e,n,r,s,o){const{at:c}=o,d=this.nextListenerId();this.emitOperation(e,"listen",n,o.result,o.evaluation,{at:c,durationMs:Date.now()-c,request:s?{query:s}:void 0,origin:o.origin});const f={id:d,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=qa(this.tree.read(n),s);f.lastWindow=p;const g={val:Au(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,Jr(o.check),o,{at:s,durationMs:Date.now()-s,request:{query:r}}),ji();const c=qa(this.tree.read(n),r);return this.emitOperation(e,"get",n,"allow",o,{at:s,durationMs:Date.now()-s,request:{query:r},resourceBefore:{data:Au(c),exists:c.length>0}}),c}keyForPath(e){const n=et(e);return n.length===0?null:n[n.length-1]}makeSnap(e){const n=this.tree.read(e),r=n!==null,s=et(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=>rn(et(r)));for(const r of this.valueListeners){const s=rn(et(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=qa(this.tree.read(r.path),r.query);if(T$(r.lastWindow??[],f)){this.emitListener("suppressed",r,r.auth,{event:"value",reason:"no-op",detail:{query:!0}});continue}r.lastWindow=f;const p={val:Au(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&&Qa(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=et(n),d=c.length===0?null:c[c.length-1],f=this.tree.read(n),p=f===null?null:zu(Ps(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(),w=Us(vr(g,v,f),n==="/"?"":n);if(o){const I=this.tree.snapshot();this.tree.write(n,w),this.fanOut([n]);const N=Date.now(),R=this.rules.evaluate("write",n==="/"?"/":n,{auth:e,mockData:I,newData:w});if(R.check!=="allow")throw this.emitOperation(e,"transaction",n,Jr(R.check),R,{at:N,durationMs:Date.now()-N,origin:"transaction",request:{data:g,resourceData:g},resourceBefore:{data:f,exists:f!==null},resourceAfter:{data:w,exists:w!==null},groupId:b,groupKind:"transaction"}),this.tree.restore(I),this.fanOut([n]),HS();return this.emitOperation(e,"transaction",n,"allow",R,{at:N,durationMs:Date.now()-N,origin:"transaction",request:{data:g,resourceData:g},resourceBefore:{data:f,exists:f!==null},resourceAfter:{data:w,exists:w!==null},groupId:b,groupKind:"transaction"}),this.emitCommit(e,"transaction",n,{data:g,priorState:f,nextState:w,groupId:b,groupKind:"transaction",replay:{requestTime:v},detail:{committed:!0,applyLocally:!0}}),this.emitRtdbEvent(e,"transaction",br(n),{before:f,after:w,detail:{committed:!0}}),this.notifyWrite(),{committed:!0,val:w,key:d}}const _=Date.now(),k=this.rules.evaluate("write",n==="/"?"/":n,{auth:e,mockData:this.tree.snapshot(),newData:w});if(k.check!=="allow")throw this.emitOperation(e,"transaction",n,Jr(k.check),k,{at:_,durationMs:Date.now()-_,origin:"transaction",request:{data:g,resourceData:g},resourceBefore:{data:f,exists:f!==null},resourceAfter:{data:w,exists:w!==null},groupId:b,groupKind:"transaction"}),HS();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:w,exists:w!==null},groupId:b,groupKind:"transaction"}),this.tree.write(n,w),this.fanOut([n]),this.emitCommit(e,"transaction",n,{data:g,priorState:f,nextState:w,groupId:b,groupKind:"transaction",replay:{requestTime:v},detail:{committed:!0,applyLocally:!1}}),this.emitRtdbEvent(e,"transaction",br(n),{before:f,after:w,detail:{committed:!0}}),{committed:!0,val:w,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,Jr(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}}),ji();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=qa(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(w){this.emitListener("errored",p,e,{event:n,result:"error",error:{message:w instanceof Error?w.message:String(w)},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=rn(et(e));if(n===void 0||n==="value")for(const d of[...this.valueListeners])rn(et(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)&&rn(et(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=rn(et(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=rn(et(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)?Qa(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(w){this.emitListener("errored",g,g.auth,{event:g.event,result:"error",error:{message:w instanceof Error?w.message:String(w)}})}}}}}fanOutQueryChild(e){const n=e.lastWindow??[],r=qa(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)&&!Qa(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 b$()}listenerCount(){return this.valueListeners.size}childListenerCount(){return this.childListeners.size}}function br(t){return rn(et(t))}function HS(){return new Error("permission_denied")}function Au(t){if(t.length===0)return null;const e={};for(const{key:n,value:r}of t)e[n]=r;return e}function T$(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||!Qa(r.value,s.value))return!1}return!0}const GS=new WeakMap;function UA(t){let e=GS.get(t);if(e)return e;e=new R$(t),GS.set(t,e);const n=e;return t.registerPersistableService("rtdb",{snapshot:()=>n.exportTree(),restore:r=>{n.restoreTree(r)},subscribe:r=>n.subscribeWrites(r),reset:()=>{n.restoreTree(null)}}),e}function D$(t){return UA(t).getActiveRules()}function KS(t){return UA(t).snapshotState()}function I$(t,e){return t==="/"?`/${e}`:`${t}/${e}`}function YS(t){return t===null?"null":Array.isArray(t)?"array":typeof t}function M$(t){const e=(t??"/").split("/").filter(Boolean);return e.length===0?"/":`/${e.join("/")}`}function L$(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 $A(t,e,n,r,s){if(t===null||typeof t!="object"||Array.isArray(t))return{path:e,childCount:0,truncated:!1,children:[],schema:{},valueType:YS(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]=YS(v);const f=n>=r&&d.length>0,p=o.length>s,g=n>=r?[]:d.slice(0,s).map(([b,v])=>$A(v,I$(e,b),n+1,r,s));return{path:e,childCount:o.length,truncated:f||p,children:g,schema:c}}function U$(t,e={}){const n=M$(e.path),r=e.maxDepth??10,s=e.maxChildren??100;return $A(L$(t,n),n,0,r,s)}function BA(t){return t.children.reduce((e,n)=>e+1+BA(n),0)}function qA(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=D$(r);if(!s)return{ok:!1,summary:"No RTDB rules are loaded in the local sandbox.",data:{code:"NO_ACTIVE_RULES"}};const o=KS(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=m$(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=U$(KS(r),n);return{ok:!0,summary:`Crawled ${BA(s)} object paths from ${s.path}`,data:s}}}]}function $$(t){const e=Wt(t),n=r=>r&&r!=="admin"?Vd(t.withAuth({uid:r.uid,token:r.claims})):bg(t);return[...WE({resolveSandbox:()=>e}),..._A({resolveDb:n}),...EA({resolveSandbox:()=>t}),...qA({resolveSandbox:()=>t})]}function B$(t){const e=new Map($$(t).map(n=>[n.name,n]));return async(n,r)=>{const s=e.get(n);if(!s)throw new z$(n);const o={signal:new AbortController().signal},c=await s.execute(r,o);return{ok:c.ok,summary:c.summary,data:c.data}}}const ZS=new WeakMap;async function q$(t,e,n){let r=ZS.get(t);return r||(r=B$(t),ZS.set(t,r)),r(e,n)}const F$=(()=>{const t=async()=>{throw new Error("SANDBOX_TOOL_NAMES: stub resolver should never be invoked")};return[...WE({resolveSandbox:t}),..._A({resolveDb:t}),...EA({resolveSandbox:t}),...qA({resolveSandbox:t})].map(e=>e.name)})();class z$ extends Error{constructor(n){super(`unknown sandbox tool: ${n}`);G(this,"tool");this.tool=n,this.name="UnknownToolError"}}const P$=500,V$=3e4,H$=2e3,G$=.5,K$=3;function Y$(t,e={}){const n=Z$(e.url),r=e.sandboxId??W$(),s=e.dispatcher??q$,o=e.toolNames??[...F$],c=e.initialReconnectDelayMs??P$,d=e.maxReconnectDelayMs??V$,f=e.noReconnect??!1,p=e.onStateChange??(()=>{}),g=e.standbyPollMs??H$,b=e.fetchImpl??($=>fetch($)),v=e.workerRelay??null;let w=null,_=!1,k=0,I=null,N=null,R=0,M={kind:"connecting"};const F=new Map;function D(){for(const $ of F.values())try{$()}catch{}F.clear()}function C($){M=$;try{p($)}catch{}}function L($){if(w&&w.readyState===WebSocket.OPEN)try{w.send(JSON.stringify($))}catch{}}function U(){if(_)return;C({kind:"connecting"});let $;try{$=new WebSocket(n)}catch(K){P(`failed to open WebSocket: ${K instanceof Error?K.message:String(K)}`);return}w=$,$.onopen=()=>{k=0;const K={type:"hello",protocol:1,tools:o,sandboxId:r,...v?{capabilities:[gL]}:{}};L(K)},$.onmessage=K=>{let W;try{W=JSON.parse(typeof K.data=="string"?K.data:"")}catch{return}if(bL(W)){if(W.type==="hello-ack"){C({kind:"connected",bridgeVersion:W.bridgeVersion});return}if(W.type==="tool-call"){H(W);return}if(W.type==="worker-op"){z(W);return}if(W.type==="worker-sub"){q(W);return}if(W.type==="worker-unsub"){const se=F.get(W.subId);if(se){F.delete(W.subId);try{se()}catch{}}return}if(W.type==="ping"){L({type:"pong",id:W.id});return}}},$.onclose=K=>{const W=K.reason||`closed (code ${K.code})`;if(w=null,D(),K.code===yL){E();return}P(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)}}}L(K)}async function z($){if(v)try{const K=await v.op($.op);pS(`op '${$.op.method}'`,K),L({type:"worker-res",id:$.id,ok:!0,value:K})}catch(K){const W=K.denialContext;L({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 q($){if(v&&!F.has($.subId))try{const K=v.subscribe($.sub,W=>{try{pS(`subscription '${$.subId}'`,W)}catch(se){L({type:"worker-snap",subId:$.subId,value:{__error:{code:se.code??"invalid-argument",message:se instanceof Error?se.message:String(se)}}});return}L({type:"worker-snap",subId:$.subId,value:W})});F.set($.subId,K)}catch(K){const W=K.denialContext;L({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 x(){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){C({kind:"disconnected",reason:"replaced by a newer sandbox peer"});return}k=0,R=0,C({kind:"standby"}),O()}}function O(){if(_)return;const $=g*(1+Math.random()*G$);N=setTimeout(()=>{N=null,T()},$)}async function T(){if(_)return;let $=null;for(const K of x())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){U();return}if($===!1){R=0,O();return}if(R+=1,R>=K$){P("standby health poll unreachable");return}O()}}function P($){if(_)return;if(f){C({kind:"disconnected",reason:$});return}k+=1;const K=Math.min(c*2**(k-1),d);C({kind:"reconnecting",attempt:k,delayMs:K}),I=setTimeout(()=>{I=null,U()},K)}return U(),{disconnect(){if(_=!0,D(),I&&(clearTimeout(I),I=null),N&&(clearTimeout(N),N=null),w){try{w.close()}catch{}w=null}C({kind:"disconnected",reason:"client closed"})},state(){return M}}}function Z$(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}:${fS}${hS}`}return`ws://localhost:${fS}${hS}`}function W$(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`sb-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function Q$(t,e){try{const n=new URL(t,e.href).pathname;return`${e.protocol==="https:"?"wss:":"ws:"}//${e.host}${n}`}catch{return t}}function J$(t,e){return{url:e,dispatcher:(n,r,s)=>pM(t,r,s),workerRelay:{op:n=>mM(t,n),subscribe:(n,r)=>yM(t,n,r)}}}async function X$(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?Q$(o,c):o,f=Y$(null,{...J$(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 e3={};function t3(){return!1}function n3(){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 r3(t,e={}){if(t==="local"){const n=e.baseUrl??"",r=t3(),s=e.persistence==="memory"||r?Pm():qI(n),o=e.disableLive?null:mL(e.workerUrl),c=o?n3():null;return o&&c&&X$(o.db,{baseUrl:n,onStateChange:d=>c.set(d)}),{mode:t,projects:r?PI():$I(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 FA=A.createContext(null);function s3(t){try{return{status:"ready",env:r3(t),error:null}}catch(e){return{status:"error",env:null,error:e instanceof Error?e:new Error(String(e))}}}function i3({mode:t="local",children:e}){const n=A.useMemo(()=>s3(t),[t]);return h.jsx(FA.Provider,{value:n,children:e})}function rr(){const t=A.useContext(FA);if(!t)throw new Error("useEnvironment must be used within an <EnvironmentProvider>");return t}const a3="pyric-studio:theme",Pu="dark";function o3(){return Pu}function l3(){typeof document>"u"||document.documentElement.setAttribute("data-theme","dark")}const c3=A.createContext(null);function u3({children:t}){const[e,n]=A.useState(o3);A.useEffect(()=>{l3();try{localStorage.setItem(a3,Pu)}catch{}},[e]);const r="dark",s=A.useCallback(d=>n(Pu),[]),o=A.useCallback(()=>n(Pu),[]),c=A.useMemo(()=>({choice:e,resolvedTheme:r,setChoice:s,cycleChoice:o}),[e,r,s,o]);return h.jsx(c3.Provider,{value:c,children:t})}function zA(){const t=typeof import.meta<"u"&&"/__pyric/ui/"||"/";return t.endsWith("/")?t:`${t}/`}function d3(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 _g(t,e="",n=zA()){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:d3(e)}}function f3(t,e=zA()){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 yy="pyric:studio:navigated",h3={tab:"",rest:[],query:{}};function PA(){return typeof window<"u"?window.location.pathname+window.location.search:""}function Rr(){return typeof window>"u"?h3:_g(window.location.pathname,window.location.search)}function p3(t){return t.tab==="home"?{...t,tab:""}:t}function Gd(t){return f3(p3(t))}function VA(){typeof window<"u"&&window.dispatchEvent(new Event(yy))}function Jn(t){if(typeof window>"u")return;const e=Gd(t);PA()!==e&&(window.history.pushState(null,"",e),VA())}function xd(t){typeof window>"u"||(window.history.replaceState(null,"",Gd(t)),VA())}function ec(t){return typeof window>"u"?()=>{}:(window.addEventListener("popstate",t),window.addEventListener(yy,t),()=>{window.removeEventListener("popstate",t),window.removeEventListener(yy,t)})}function m3(t,e){const n=A.useCallback(o=>t.includes(o)?o:e,[t,e]),r=A.useSyncExternalStore(ec,()=>n(Rr().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=_g(`/${f===-1?d:d.slice(0,f)}`,f===-1?"":d.slice(f),"/");if(t.includes(p.tab)){xd(p);return}}const c=Rr();c.tab!==""&&!t.includes(c.tab)&&xd({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 gy=null;function y3(t){gy=t}function g3(){return gy?(gy(),!0):!1}function b3(t){return(t.metaKey||t.ctrlKey)&&!t.altKey&&!t.shiftKey&&(t.key==="k"||t.key==="K")}const v3=[{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 w3({assuranceEnabled:t=!1}={}){return v3.filter(e=>e.id!=="assurance"||t)}const Pi=w3({assuranceEnabled:!1}),x3=Pi.map(t=>t.id);function S3(t){return Pi.find(e=>e.id===t)??Pi[0]}function _3(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 E3=7;function A3(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}},w=b.label.toLowerCase();if(w.startsWith(n.toLowerCase())?s.push(v):_3(n,b.label)&&o.push(v),p&&(w===d.toLowerCase()||w.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,E3)}function by(t){return`${t.kind}:${t.target.tab}:${(t.target.rest??[]).join("/")}`}const vy={docsPerCollection:50,collectionsScanned:20,users:100,objects:200,storageListCalls:20,subcollections:30,subcollectionRpcCalls:40};async function j3(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 k3(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 w=`${g}/${v}`;c.push(w);try{const _=await n(w,o);for(const k of _.slice(0,o))d.push(k),f.push(k)}catch{}}}return{subcollections:c,documents:d}}const C3=5;function Sd(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 N3={collection:"Firestore collections",document:"Firestore documents",subcollection:"Firestore subcollections",user:"Auth users",object:"Storage objects","rtdb-key":"RTDB keys"},O3=["collection","document","subcollection","user","object","rtdb-key"];function R3(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 HA(t){return t.endsWith("/")?{base:t.slice(0,-1),trailing:!0}:{base:t,trailing:!1}}function T3(t,e){const{base:n,trailing:r}=HA(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:Sd(s[c],o[c])}function D3(t,e){const{base:n,trailing:r}=HA(t);if(!n||n.includes("/"))return 0;const s=e.split("/").pop()??e;return r?s.toLowerCase()===n.toLowerCase()?850:0:Sd(n,s)}function WS(t,e,n,r=C3){const s=t.trim();if(!s)return[];const o=[],c=A3(t,e);c.length&&o.push({kind:"navigate",title:"Go to",results:c});for(const d of O3){const f=d==="document"||d==="subcollection",p=d==="collection"||d==="subcollection",g=new Map;for(const v of n)v.kind===d&&g.set(by(v),v);const b=[...g.values()].map(v=>({entry:v,score:Math.max(Sd(s,v.label),v.alt?Sd(s,v.alt):0,f?T3(s,v.label):0,p?D3(s,v.label):0)})).filter(v=>v.score>0).sort((v,w)=>w.score-v.score||v.entry.label.localeCompare(w.entry.label)).slice(0,r);b.length&&o.push({kind:d,title:N3[d],results:b.map(({entry:v})=>({id:by(v),label:v.label,hint:R3(v),target:v.target}))})}return o}function QS(t){return t.flatMap(e=>e.results)}function I3(t){return{kind:"collection",label:t,target:{tab:"firestore",rest:[t]}}}function JS(t){return{kind:"document",label:t,target:{tab:"firestore",rest:t.split("/").filter(Boolean)}}}function M3(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 L3(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 U3(t){return{kind:"object",label:t,target:{tab:"storage",rest:t.split("/").filter(Boolean)}}}function $3(t){return{kind:"rtdb-key",label:t,target:{tab:"rtdb",rest:[t]}}}async function B3(t,e={},n){const r={...vy,...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(I3));const b=[];if(t.listDocumentPaths)for(const w of g.slice(0,r.collectionsScanned))try{const k=(await t.listDocumentPaths(w,r.docsPerCollection)).slice(0,r.docsPerCollection);b.push(...k),o(k.map(JS))}catch{}if(t.listSubcollections&&t.listDocumentPaths)try{const{subcollections:w,documents:_}=await k3(b,t.listSubcollections,t.listDocumentPaths,{maxSubcollections:r.subcollections,maxRpcCalls:r.subcollectionRpcCalls,docsPerCollection:r.docsPerCollection});o(w.map(M3)),o(_.map(JS))}catch{}})(),d=(async()=>{if(t.listUsers)try{const g=await t.listUsers(r.users);o(g.slice(0,r.users).map(L3))}catch{}})(),f=(async()=>{if(t.listStorageObjectPaths)try{const g=await t.listStorageObjectPaths(r.objects);o(g.slice(0,r.objects).map(U3))}catch{}})(),p=(async()=>{if(t.listRtdbTopLevelKeys)try{o((await t.listRtdbTopLevelKeys()).map($3))}catch{}})();return await Promise.allSettled([c,d,f,p]),s}const GA=Symbol("pyric/auth/target"),q3=Symbol("pyric.user.internal");function Fe(t,e){return new Wi(t,`Firebase: ${e} (${t}).`)}const KA={PASSWORD:"password"},tm={EMAIL_LINK:"emailLink",EMAIL_PASSWORD:"password"};class Kd{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"?F3(e):e;if(!n)return null;const r=n.providerId,s=n.signInMethod;if(typeof r!="string"||typeof s!="string")return null;if(r===KA.PASSWORD){const o=typeof n.email=="string"?n.email:"",c=typeof n.password=="string"?n.password:"";return new z3(o,c,s)}return new Kd(r,s)}}function F3(t){try{const e=JSON.parse(t);return typeof e=="object"&&e!==null?e:null}catch{return null}}class z3 extends Kd{constructor(n,r,s=tm.EMAIL_PASSWORD){super(KA.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===tm.EMAIL_PASSWORD?this.secret:null}get emailLink(){return this.signInMethod===tm.EMAIL_LINK?this.secret:null}toJSON(){return{providerId:this.providerId,signInMethod:this.signInMethod,email:this.email,password:this.secret}}}class Yd extends Kd{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 Eg(t,e){return e?new Yd(t,t):null}const qs=class qs{constructor(){G(this,"providerId",qs.PROVIDER_ID)}addScope(e){return this}setCustomParameters(e){return this}static credentialFromResult(e){return Eg(qs.PROVIDER_ID,e)}static credentialFromError(e){return null}static credential(e,n){return new Yd(qs.PROVIDER_ID,qs.GOOGLE_SIGN_IN_METHOD,{idToken:e??void 0,accessToken:n??void 0})}};G(qs,"PROVIDER_ID","google.com"),G(qs,"GOOGLE_SIGN_IN_METHOD","google.com");let wy=qs;const Fs=class Fs{constructor(){G(this,"providerId",Fs.PROVIDER_ID)}addScope(e){return this}setCustomParameters(e){return this}static credentialFromResult(e){return Eg(Fs.PROVIDER_ID,e)}static credentialFromError(e){return null}static credential(e){return new Yd(Fs.PROVIDER_ID,Fs.FACEBOOK_SIGN_IN_METHOD,{accessToken:e})}};G(Fs,"PROVIDER_ID","facebook.com"),G(Fs,"FACEBOOK_SIGN_IN_METHOD","facebook.com");let xy=Fs;const zs=class zs{constructor(){G(this,"providerId",zs.PROVIDER_ID)}addScope(e){return this}setCustomParameters(e){return this}static credentialFromResult(e){return Eg(zs.PROVIDER_ID,e)}static credentialFromError(e){return null}static credential(e){return new Yd(zs.PROVIDER_ID,zs.GITHUB_SIGN_IN_METHOD,{accessToken:e})}};G(zs,"PROVIDER_ID","github.com"),G(zs,"GITHUB_SIGN_IN_METHOD","github.com");let Sy=zs;const YA=[wy.PROVIDER_ID,"apple.com",xy.PROVIDER_ID,Sy.PROVIDER_ID,"twitter.com","microsoft.com","yahoo.com"];function Ag(t,e=!1){var r;const n=t[GA];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 P3{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 V3(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 ki(t){if(typeof t!="string"||t.length===0)throw Fe("auth/invalid-email","Error");const e=t.indexOf("@");if(e<=0||e===t.length-1)throw Fe("auth/invalid-email","Error")}function ml(t){if(typeof t!="string"||t.length<6)throw Fe("auth/weak-password","Password should be at least 6 characters")}function ZA(){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 H3="__pyric_no_password__";class WA{constructor(e,n=e,r=ZA(),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 P3);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{Vs(this.sandbox,$d({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 Fe("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??H3,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 Fe("auth/user-not-found",`restoreSession: no identity with uid ${e}.`);if(n.disabled)throw Fe("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){ml(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){ki(n);const r=this.requireByEmail(e),s=n.toLowerCase(),o=this.usersByEmail.get(s);if(o&&o.uid!==r.uid)throw Fe("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){ki(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 Fe("auth/user-not-found",`linkWithCredential: no identity with uid ${e}.`);if(s.providerUserInfo.some(c=>c.providerId===n))throw Fe("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){ki(o);const c=o.toLowerCase(),d=this.usersByEmail.get(c);if(d&&d.uid!==e)throw Fe("auth/email-already-in-use",`An account already exists for ${o}.`);r.password!==void 0&&r.password!==null&&(ml(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 Fe("auth/user-not-found",`unlink: no identity with uid ${e}.`);const s=r.providerUserInfo.findIndex(o=>o.providerId===n);if(s<0)throw Fe("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 Fe("auth/user-not-found",`No user found for ${e}.`);return n}createEmailPasswordUser(e,n){ki(e),ml(n);const r=e.toLowerCase();if(this.usersByEmail.has(r))throw Fe("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 Fe("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 Fe("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 Fe("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 Fe("auth/uid-already-exists",`createUser: a user with uid ${n} already exists.`);if(e.email!==void 0&&(ki(e.email),this.usersByEmail.has(e.email.toLowerCase())))throw Fe("auth/email-already-in-use",`An account already exists for ${e.email}.`);if(e.password!==void 0&&(ml(e.password),e.email===void 0))throw Fe("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 Fe("auth/user-not-found",`No user found for uid ${e}.`);const s=this.toRecord(r);if(n.email!==void 0){ki(n.email);const c=n.email.toLowerCase(),d=this.usersByEmail.get(c);if(d&&d!==r)throw Fe("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&&(ml(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 Fe("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 Fe("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 Fe("auth/user-not-found",`mintSession: no identity with uid ${e.uid}.`);if(r.disabled)throw Fe("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=V3(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,q3,{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 Fe("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 Fe("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(ki(e),typeof n!="string"||n.length===0)throw Fe("auth/missing-password","A non-empty password must be provided");const r=this.findByEmail(e);if(!r)throw Fe("auth/user-not-found",`No user found for ${e}.`);if(r.disabled)throw Fe("auth/user-disabled","The user account has been disabled by an administrator.");if(r.password!==n)throw Fe("auth/wrong-password","Invalid password.");return r}}const XS=new WeakSet,ju=new WeakMap;function QA(t,e,n,r="[DEFAULT]"){return G3(t,e),K3(t,e,n,r)}function G3(t,e){XS.has(t)||(XS.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)},reset:()=>{e.clearUsers(),e.restoreProviderConfig(void 0)},subscribe:n=>{const r=e.subscribeUsers(n),s=e.subscribeProviderConfig(n);return()=>{r(),s()}}}))}function e_(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 K3(t,e,n,r){var p,g;let s=ju.get(t);s||(s=new Map,ju.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,e_(c)),()=>{var v,w;c.generation===b&&((v=c.unregisterService)==null||v.call(c),c.unregisterService=void 0,(w=c.unsubscribeBackend)==null||w.call(c),c.unsubscribeBackend=void 0,c.subscribers.clear(),s.get(o)===c&&s.delete(o),s.size===0&&ju.delete(t))}}const d={backend:e,session:n,subscribers:new Set,generation:1};s.set(o,d),d.unregisterService=t.registerPersistableService(o,e_(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&&ju.delete(t))}}async function Qz(t){const{backend:e}=Ag(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 Y3(t){var n;const e=Ag(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 t_=new WeakMap,n_=new WeakMap,r_=new WeakMap;function JA(t){let e=n_.get(t);return e||(e=ZA(),n_.set(t,e)),e}function Z3(t){let e=t_.get(t);return e||(e=new WA(t,t,JA(t)),t_.set(t,e),QA(t,e,t)),e}function W3(t,e){return e.service("auth/backend",()=>{const{sandbox:n,session:r}=e,s=new WA(n,r,JA(n),o=>{e.onDelete(o)});return e.onDelete(QA(n,s,r,t.name)),s})}function XA(t){if(t===void 0)return XA(HE());const e=sg(t);if(e)return e.service("auth/default",()=>{const n={kind:"sandbox",sandbox:e.sandbox,backend:W3(t,e),own:r=>e.onDelete(r),assertAlive:()=>e.assertAlive()};return s_(n,t)});if(Q3(t)){let n=r_.get(t);return n||(n=s_({kind:"sandbox",sandbox:t,backend:Z3(t)}),r_.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 Q3(t){return typeof t=="object"&&t!==null&&typeof t.onCurrentUserChanged=="function"&&typeof t.withAuth=="function"}function s_(t,e){const n={[GA]:t,...e?{app:e}:{},signOut(){return Y3(n)}};return Object.defineProperty(n,"currentUser",{enumerable:!0,get(){return t.backend.getCurrentUser()}})}function it(t){return Ag(t)}const lr={setUser(t,e){it(t).backend.setCurrentUser(e)},setAuthFlowResolver(t,e){it(t).backend.setResolver(e)},setAuthMailResolver(t,e){it(t).backend.setMailResolver(e)},takeAuthMail(t,e){return it(t).backend.takeMail(e)},listAuthMail(t){return it(t).backend.listMail()},mockActionCode(t,e,n){it(t).backend.stageActionCode(e,n)},listIdentities(t){return it(t).backend.listIdentities()},createSignInCredential(t,e){return it(t).backend.createSignInCredential(e)},mockSignInResult(t,e){const n=e.providerId;if(!n)throw new nt("invalid-argument","sandbox.mockSignInResult: result.providerId is required so the next signInWithPopup / signInWithCredential call can match.");it(t).backend.setMockResult(n,e)},seedUsers(t,e){it(t).backend.seedUsers(e)},exportUsers(t){return it(t).backend.exportUsers()},restoreSession(t,e){return it(t).backend.restoreSession(e)},mintSession(t,e){return it(t).backend.mintDetachedSession(e)},listUsers(t){return it(t).backend.listUsers()},createUser(t,e){return it(t).backend.createUser(e)},updateUser(t,e,n){return it(t).backend.updateUser(e,n)},updateProfile(t,e,n){return it(t).backend.updateProfileByUid(e,n)},deleteUser(t,e){it(t).backend.deleteUser(e)},clearUsers(t){it(t).backend.clearUsers()},subscribeUsers(t,e){return it(t).backend.subscribeUsers(e)},getAuthProviderConfig(t){return it(t).backend.listProviderConfig()},setAuthProviderConfig(t,e,n){it(t).backend.setProviderConfig(e,n)},assertAuthProviderEnabled(t,e){it(t).backend.assertProviderEnabled(e)},delegateProviderEnforcement(t,e){it(t).backend.setProviderEnforcementDelegated(e)},subscribeAuthProviderConfig(t,e){return it(t).backend.subscribeProviderConfig(e)}},_y="pyric-storage";function J3(t){return t?`${_y}:${t}`:_y}const X3=1,wr="blobs",bn="metadata";function e6(t=_y){return n6(t).then(e=>new t6(e))}class t6{constructor(e){G(this,"db");this.db=e}async put(e,n,r){const s=this.db.transaction([wr,bn],"readwrite");s.objectStore(wr).put(n,e),s.objectStore(bn).put(r,e),await ku(s)}async getBlob(e){const n=this.db.transaction(wr,"readonly");return nm(n.objectStore(wr).get(e))}async getMetadata(e){const n=this.db.transaction(bn,"readonly");return nm(n.objectStore(bn).get(e))}async putMetadata(e,n){const r=this.db.transaction(bn,"readwrite");r.objectStore(bn).put(n,e),await ku(r)}async delete(e){const n=this.db.transaction([wr,bn],"readwrite");n.objectStore(wr).delete(e),n.objectStore(bn).delete(e),await ku(n)}async listByPrefix(e){const n=this.db.transaction(bn,"readonly"),r=IDBKeyRange.bound(e,e+"",!1,!1);return nm(n.objectStore(bn).getAll(r))}async reset(){const e=this.db.transaction([wr,bn],"readwrite");e.objectStore(wr).clear(),e.objectStore(bn).clear(),await ku(e)}close(){this.db.close()}}function n6(t){return new Promise((e,n)=>{const r=indexedDB.open(t,X3);r.addEventListener("upgradeneeded",()=>{const s=r.result;s.objectStoreNames.contains(wr)||s.createObjectStore(wr),s.objectStoreNames.contains(bn)||s.createObjectStore(bn)}),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 nm(t){return new Promise((e,n)=>{t.addEventListener("success",()=>e(t.result)),t.addEventListener("error",()=>n(t.error))})}function ku(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 i_(t){switch(t){case"read":return["get","list"];case"write":return["create","update","delete"];default:return[t]}}const r6=new Set(["&&","||","==","!=","<",">","<=",">=","+","-","*","/","%"]);function ej(t){return{segments:t.path.segments.map(s6),children:t.children.map(ej),allows:t.allows.map(e=>({verbs:e.operations,condition:at(e.condition)})),functions:t.functions.map(Ey)}}function s6(t){switch(t.type){case"literal":return{kind:"literal",value:t.value};case"wildcard":return{kind:"param",name:t.name};case"recursive":return{kind:"wildcard",name:t.name}}}function Ey(t){return{name:t.name,params:t.parameters,lets:t.lets.map(e=>({name:e.name,value:at(e.value)})),body:at(t.body)}}function at(t){switch(t.type){case"literal":return typeof t.value=="number"&&t.raw.includes(".")?{kind:"literal",value:new Ke(t.value)}:{kind:"literal",value:t.value};case"identifier":return{kind:"ident",name:t.name};case"memberAccess":return{kind:"member",target:at(t.object),name:t.property};case"methodCall":return{kind:"methodcall",target:at(t.object),method:t.method,args:t.args.map(at)};case"bracketAccess":return{kind:"index",target:at(t.object),index:at(t.index)};case"sliceAccess":return{kind:"slice",target:at(t.object),start:at(t.start),end:at(t.end)};case"binaryOp":if(!r6.has(t.op))throw new SyntaxError(`Unsupported binary operator '${t.op}' in storage rules.`);return{kind:"binary",op:t.op,left:at(t.left),right:at(t.right)};case"unaryOp":if(t.op!=="!"&&t.op!=="-")throw new SyntaxError(`Unsupported unary operator '${t.op}' in storage rules.`);return{kind:"unary",op:t.op,arg:at(t.operand)};case"ternary":return{kind:"ternary",cond:at(t.condition),then:at(t.consequent),else:at(t.alternate)};case"inExpr":return{kind:"in",element:at(t.element),collection:at(t.collection)};case"isExpr":return{kind:"is",value:at(t.value),typeName:t.typeName};case"listLiteral":return{kind:"list",elements:t.elements.map(at)};case"mapLiteral":return{kind:"map",entries:t.entries.map(e=>({key:at(e.key),value:at(e.value)}))};case"pathLiteral":return{kind:"path",segments:t.segments.map(e=>typeof e=="string"?{kind:"literal",value:e}:{kind:"interp",expr:at(e)})};case"functionCall":return{kind:"call",name:t.name,args:t.args.map(at)};default:{const e=t;throw new SyntaxError(`Unsupported expression construct: ${JSON.stringify(e)}`)}}}function tj(t){const e=Tl(t);if(!e.ok)throw new SyntaxError(`Storage rules parse error at line ${e.error.line}, column ${e.error.column}: expected ${e.error.expected}.`);const n=e.ast;if(n.service.name!=="firebase.storage")throw new SyntaxError(`Expected 'service firebase.storage', got 'service ${n.service.name}'.`);const r={segments:[],children:[ej(n.service.match)],allows:[],functions:[...(n.imports??[]).flatMap(s=>s.functions.map(o=>({name:o,params:[],lets:[],body:{kind:"literal",value:null},unresolvedImport:s.module}))),...(n.functions??[]).map(Ey),...(n.service.functions??[]).map(Ey)]};return nj(r,new Map),{_root:r}}function nj(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)nj(r,n)}function Zd(t){return t?{size:t.size,contentType:t.contentType,metadata:t.customMetadata,name:i6(t.fullPath,t.bucket),bucket:t.bucket,timeCreated:t.timeCreated,updated:t.updated,generation:a_(t.generation),metageneration:a_(t.metageneration)}:null}function i6(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 a_(t){if(t===void 0)return;const e=Number(t);return Number.isFinite(e)?e:void 0}function a6(t){return{size:t.size,contentType:t.contentType,metadata:t.customMetadata}}function rj(t,e,n=new Date,r){const s=n.getTime(),o=o6(e.request.path),c=[],d=new Set(i_(e.request.method));function f(g,b,v){const w=l6(g.segments,b,v);if(!w)return!1;const _=w.params,k=w.left;if(k.length===0)for(const I of g.allows){const N=new Set(I.verbs.flatMap(i_));if(![...d].some(F=>N.has(F)))continue;let M;try{const F=I.condition?Ie(I.condition,{input:e,now:s,params:_,locals:{},funcs:g.visibleFuncs??new Map,depth:0,firestoreLookup:r}):!0;if(ut(F)){c.push(`match ${rm(g.segments)} ${e.request.method}: ${F.message}`);continue}M=Ga(F)}catch(F){if(F instanceof $e){c.push(`match ${rm(g.segments)} ${e.request.method}: ${F.message}`);continue}throw F}if(M)return!0;c.push(`match ${rm(g.segments)} ${e.request.method}: condition false`)}for(const I of g.children)if(f(I,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 o6(t){return t.split("/").filter(e=>e.length>0)}function rm(t){return"/"+t.map(e=>e.kind==="literal"?e.value:e.kind==="param"?`{${e.name}}`:`{${e.name}=**}`).join("/")}function l6(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 Dn{constructor(e){G(this,"message");this.message=e}}function ut(t){return t instanceof Dn}function o_(t,e){const n=t[e];return n===void 0?new Dn(`Property ${e} is undefined on object.`):n}function Ga(t){return ut(t)?!1:t!==!1&&t!==null&&t!==void 0&&!(typeof t=="number"&&Number.isNaN(t))}class $e extends Error{}const l_=20;function Ie(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"?f6(e.input,e.now):t.name==="resource"?d6(e.input.resource):t.name in e.params?e.params[t.name]:void 0;case"member":{const n=Ie(t.target,e);return ut(n)?n:n==null?new Dn("Null value error."):o_(n,t.name)}case"index":{const n=Ie(t.target,e);if(ut(n))return n;if(n==null)return new Dn("Null value error.");const r=Ie(t.index,e);return ut(r)?r:o_(n,String(r))}case"call":return c6(t,e);case"methodcall":return h6(t,e);case"path":throw new $e("a Firestore path literal is only valid as an argument to firestore.get()/exists()");case"unary":{const n=Ie(t.arg,e);return ut(n)?n:t.op==="-"?n instanceof Ke?new Ke(-n.value):typeof n!="number"?new Dn(`Unary '-' applied to ${ns(n)}.`):-n:!Ga(n)}case"ternary":{const n=Ie(t.cond,e);return ut(n)?n:Ga(n)?Ie(t.then,e):Ie(t.else,e)}case"in":{const n=Ie(t.element,e);if(ut(n))return n;const r=Ie(t.collection,e);return ut(r)?r:Array.isArray(r)?r.some(s=>Ol(s,n)):r!==null&&typeof r=="object"?typeof n=="string"&&Object.prototype.hasOwnProperty.call(r,n):new Dn(`'in' applied to ${ns(r)} (expected a list or map).`)}case"is":{const n=Ie(t.value,e);return ut(n)?n:u6(n,t.typeName)}case"list":{const n=[];for(const r of t.elements){const s=Ie(r,e);if(ut(s))return s;n.push(s)}return n}case"map":{const n={};for(const r of t.entries){const s=Ie(r.key,e);if(ut(s))return s;if(typeof s!="string")return new Dn(`Map literal key is ${ns(s)} (expected a string).`);const o=Ie(r.value,e);if(ut(o))return o;n[s]=o}return n}case"slice":{const n=Ie(t.target,e);if(ut(n))return n;const r=Ie(t.start,e);if(ut(r))return r;const s=Ie(t.end,e);return ut(s)?s:typeof r!="number"||typeof s!="number"||!Number.isInteger(r)||!Number.isInteger(s)?new Dn("Slice bounds must be integers."):Array.isArray(n)||typeof n=="string"?r<0||s<r||s>n.length?new Dn(`Slice bounds [${r}:${s}] out of range for ${ns(n)} of size ${n.length}.`):n.slice(r,s):new Dn(`Slice applied to ${ns(n)} (expected a list or string).`)}case"binary":{if(t.op==="&&"){const s=Ie(t.left,e);return ut(s)?s:Ga(s)?Ie(t.right,e):s}if(t.op==="||"){const s=Ie(t.left,e);if(ut(s)){const o=Ie(t.right,e);return Ga(o)?o:s}return Ga(s)?s:Ie(t.right,e)}const n=Ie(t.left,e);if(ut(n))return n;const r=Ie(t.right,e);if(ut(r))return r;switch(t.op){case"==":return Ol(n,r);case"!=":return!Ol(n,r);case"<":return Cu(n,r)<0;case">":return Cu(n,r)>0;case"<=":return Cu(n,r)<=0;case">=":return Cu(n,r)>=0;case"+":return Ci(n,r,(s,o)=>s+o);case"-":return Ci(n,r,(s,o)=>s-o);case"*":return Ci(n,r,(s,o)=>s*o);case"/":return Za(n)||Za(r)?Ci(n,r,(s,o)=>s/o):ei(r)===0?new Dn("Division by zero."):Ci(n,r,(s,o)=>Math.trunc(s/o));case"%":return Za(n)||Za(r)?Ci(n,r,(s,o)=>s%o):ei(r)===0?new Dn("Modulo by zero."):Ci(n,r,(s,o)=>s%o)}}}}function c6(t,e){const n=e.funcs.get(t.name);if(!n)throw new $e(`undefined function ${t.name}()`);if(n.unresolvedImport!==void 0)throw new $e(`function ${t.name}() is imported from '${n.unresolvedImport}', but import module resolution is not implemented`);if(n.params.length!==t.args.length)throw new $e(`function ${t.name}() expects ${n.params.length} argument(s), got ${t.args.length}`);const r=e.depth+1;if(r>l_)throw new $e(`function ${t.name}() exceeded max call depth ${l_}`);const s=t.args.map(d=>Ie(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]=Ie(d.value,c);return Ie(n.body,c)}function u6(t,e){switch(e){case"string":return typeof t=="string";case"bool":return typeof t=="boolean";case"int":return typeof t=="number"&&Number.isInteger(t);case"float":return t instanceof Ke||typeof t=="number"&&!Number.isInteger(t);case"number":return t instanceof Ke||typeof t=="number";case"list":return Array.isArray(t);case"map":return t!==null&&typeof t=="object"&&!Array.isArray(t);default:return new Dn(`'is ${e}' is not supported by the storage evaluator.`)}}function ei(t){if(typeof t=="number")return t;if(t instanceof Ke)return t.value}function Za(t){return t instanceof Ke}function Cu(t,e){const n=ei(t),r=ei(e);return n!==void 0&&r!==void 0?n-r:typeof t=="string"&&typeof e=="string"?t<e?-1:t>e?1:0:Number.NaN}function Ci(t,e,n){const r=ei(t),s=ei(e);if(r===void 0||s===void 0)return;const o=n(r,s);return Za(t)||Za(e)?new Ke(o):o}function d6(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:c_(t.timeCreated),updated:c_(t.updated)}}function c_(t){if(t===void 0)return;const e=Date.parse(t);return Number.isNaN(e)?void 0:e}function f6(t,e){return{auth:t.request.auth,resource:t.request.resource??null,method:t.request.method,path:t.request.path,time:e}}function h6(t,e){if(t.target.kind==="ident"&&t.target.name==="timestamp"&&!(t.target.name in e.locals)&&!(t.target.name in e.params))return g6(t,e);if(t.target.kind==="ident"&&t.target.name==="duration"&&!(t.target.name in e.locals)&&!(t.target.name in e.params))return y6(t,e);if(t.target.kind==="ident"&&t.target.name==="firestore"&&!(t.target.name in e.locals)&&!(t.target.name in e.params))return p6(t,e);if(t.method==="matches")return b6(t,e);if(t.method==="split")return v6(t,e);if(t.method==="size")return w6(t,e);throw new $e(`unsupported method .${t.method}()`)}function p6(t,e){if(t.method!=="get"&&t.method!=="exists")throw new $e(`unsupported method firestore.${t.method}()`);if(!e.firestoreLookup)throw new $e(`firestore.${t.method}() is unsupported here — no Firestore lookup capability is configured`);if(t.args.length!==1)throw new $e(`firestore.${t.method}() expects a single path argument`);const n=t.args[0];if(n.kind!=="path")throw new $e(`firestore.${t.method}() requires a /databases/.../documents/... path literal`);const r=m6(n,e);if(t.method==="exists")return e.firestoreLookup.exists(r);const s=e.firestoreLookup.get(r);if(s===null)throw new $e(`firestore.get() targeted a nonexistent document: ${r}`);return{data:s}}function m6(t,e){const n=t.segments.map(s=>{if(s.kind==="literal")return s.value;const o=Ie(s.expr,e);if(typeof o=="string")return o;if(typeof o=="number")return String(o);throw new $e(`Firestore path interpolation resolved to ${ns(o)} (expected a string)`)});if(n.length<4||n[0]!=="databases"||n[2]!=="documents")throw new $e(`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 $e(`Firestore path does not point at a document (needs an even segment count): ${r.join("/")}`);return r.join("/")}const u_={w:10080*60*1e3,d:1440*60*1e3,h:3600*1e3,m:60*1e3,s:1e3,ms:1,ns:1e-6};function y6(t,e){if(t.method!=="value")throw new $e(`unsupported duration.${t.method}()`);const n=t.args.map(c=>Ie(c,e));if(n.length!==2||typeof n[0]!="number"||typeof n[1]!="string")throw new $e("duration.value() expects (magnitude: number, unit: string)");const[r,s]=n,o=u_[s];if(o===void 0)throw new $e(`duration.value() got unknown unit "${s}" — expected one of ${Object.keys(u_).join(", ")}`);return r*o}function g6(t,e){const n=t.args.map(r=>Ie(r,e));if(t.method==="value"){if(n.length!==1||typeof n[0]!="number")throw new $e("timestamp.value() expects (epochMillis: number)");return n[0]}if(t.method==="date"){if(n.length!==3||!n.every(c=>typeof c=="number"))throw new $e("timestamp.date() expects (year, month, day) numbers");const[r,s,o]=n;return Date.UTC(r,s-1,o)}throw new $e(`unsupported timestamp.${t.method}()`)}function b6(t,e){const n=Ie(t.target,e);if(ut(n))return n;if(typeof n!="string")throw new $e(`matches() requires a string target, got ${ns(n)}`);if(t.args.length!==1)throw new $e("matches() expects a single pattern argument");const r=Ie(t.args[0],e);if(typeof r!="string")throw new $e("matches() pattern must be a string");const s=/\\[1-9]/.test(r),o=/\(\?<?[=!]/.test(r);if(s||o)throw new $e(`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 $e(`matches() invalid regex pattern: ${d.message}`)}return c.test(n)}function v6(t,e){const n=Ie(t.target,e);if(ut(n))return n;if(typeof n!="string")throw new $e(`split() requires a string target, got ${ns(n)}`);if(t.args.length!==1)throw new $e("split() expects a single pattern argument");const r=Ie(t.args[0],e);if(typeof r!="string")throw new $e("split() pattern must be a string");const s=/\\[1-9]/.test(r),o=/\(\?<?[=!]/.test(r);if(s||o)throw new $e(`split() pattern uses an RE2-unsupported construct (${s?"backreference":"lookaround"}) that production would reject`);let c;try{c=new RegExp(r)}catch(d){throw new $e(`split() invalid regex pattern: ${d.message}`)}return n.split(c)}function w6(t,e){const n=Ie(t.target,e);if(ut(n))return n;if(t.args.length!==0)throw new $e("size() expects no arguments");if(typeof n=="string"||Array.isArray(n))return n.length;if(n!==null&&typeof n=="object")return Object.keys(n).length;throw new $e(`size() requires a string, list, or map target, got ${ns(n)}`)}function Ol(t,e){if(t===e)return!0;if(t==null||e==null)return t==null&&e==null;const n=ei(t),r=ei(e);if(n!==void 0&&r!==void 0)return n===r;if(Array.isArray(t)&&Array.isArray(e))return t.length===e.length&&t.every((s,o)=>Ol(s,e[o]));if(typeof t=="object"&&typeof e=="object"&&!Array.isArray(t)&&!Array.isArray(e)){const s=Object.keys(t),o=Object.keys(e);return s.length===o.length&&s.every(c=>Object.prototype.hasOwnProperty.call(e,c)&&Ol(t[c],e[c]))}return!1}function ns(t){return t===null?"null":t===void 0?"undefined":t instanceof Ke?"float":typeof t}const x6="pyric-default",Wd=Symbol("pyric/storage/target");function Vi(t){var e;return((e=t.currentAuth)==null?void 0:e.call(t))??t.context.auth}class S6{constructor(e,n=null){G(this,"backend");G(this,"rules");this.backend=e,this.rules=n}}const d_=new WeakMap,f_=new WeakMap;function _6(t,e,n){const r=d_.get(t);if(r){const c=f_.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?tj(e.rules):null,o=e6(e.dbName??J3(e.projectId)).then(c=>new S6(c,s));return d_.set(t,o),f_.set(t,e.rules??null),t.registerPersistableService("storage",{snapshot:()=>null,restore:()=>{},reset:async()=>{await(await o).backend.reset()}}),o}function sm(t){return t instanceof ho}const h_=new WeakMap,p_=new WeakMap;function E6(t,e={}){const n=!sm(t),r=sm(t)?t.sandbox:t,s=_6(r,e,"getAdminStorageSandbox");if(n){const g=p_.get(r);if(g)return g}const o=sm(t)?t:r.withAuth(null),c=o.operationContext.authLens.mode==="admin"?o:Wl(o,{source:o.operationContext.source,authLens:{mode:"admin"},...o.operationContext.planId===void 0?{}:{planId:o.operationContext.planId}}),d=h_.get(o);if(d)return d;const f={kind:"sandbox",sandbox:r,context:c,bucket:e.bucket??x6,servicePromise:s,admin:!0},p=Object.freeze({[Wd]:f});return h_.set(o,p),n&&p_.set(r,p),p}function yo(t,e){const n=Ld(e,ql(t.context.operationContext));return{...e,...ql(n),service:"storage"}}function ls(t){const e=t[Wd];if(!e)throw new TypeError("pyric/storage: not a FirebaseStorage handle — was it produced by getStorageSandbox?");return e}function tc(t){return ls(t).servicePromise}function A6(t){return`storage/${t}`}class nc extends Error{constructor(n,r){const s=A6(n);super(`${s}: ${r}`);G(this,"code");this.name="StorageError",this.code=s,Object.setPrototypeOf(this,nc.prototype)}}function sj(t){return new nc("object-not-found",`no object at "${t}".`)}function j6(t,e,n){return new nc("unauthorized",`${t} "${e}" denied by rules${n}.`)}function jg(t){return new nc("invalid-root-operation",`${t} cannot operate on the root reference.`)}function Hl(t,e){return C6(t)?(ls(t.storage),new Gl(t.storage,k6(t.fullPath,e??""))):(ls(t),new Gl(t,ij(e??"")))}class Gl{constructor(e,n){G(this,"storage");G(this,"bucket");G(this,"fullPath");this.storage=e;const r=ls(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 Gl(this.storage,n)}get root(){return this.fullPath===""?this:new Gl(this.storage,"")}toString(){return`gs://${this.bucket}/${this.fullPath}`}}function ij(t){return t===""?"":t.split("/").filter(e=>e.length>0).join("/")}function k6(t,e){const n=ij(e);return t===""?n:n===""?t:`${t}/${n}`}function C6(t){if(t===null||typeof t!="object"||Wd in t)return!1;const e=t;return typeof e.fullPath=="string"&&e.storage!==void 0}function rc(t,e,n,r){const s=(n==null?void 0:n.kind)==="sandbox"?yo(n,r):r;if((n==null?void 0:n.kind)==="sandbox"&&n.admin===!0){Nu(n,e,"not-applicable",void 0,"admin",!1,s);return}if(!t.rules){Nu(n,e,"allow",void 0,"user",!1,s);return}const o=n?N6(e,n.bucket):e,c=rj(t.rules,o,void 0,O6(n));if(!c.allowed){Nu(n,e,"deny",c.reasons,"user",!0,s);const d=c.reasons.length>0?` — ${c.reasons.join("; ")}`:"";throw j6(e.request.method,e.request.path,d)}Nu(n,e,"allow",c.reasons,"user",!0,s)}function N6(t,e){const n=t.request.path.replace(/^\/+/,"");return{...t,request:{...t.request,path:n===""?`b/${e}/o`:`b/${e}/o/${n}`}}}function Nu(t,e,n,r,s,o,c){if(t)try{Vs(t.sandbox,FE({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 O6(t){if(!t)return;const e=t.sandbox.admin;return{get:n=>e.getDocument(n),exists:n=>e.getDocument(n)!==null}}function aj(t){return{...t}}async function R6(t){T6(t,"getMetadata");const e=ls(t.storage),n=yo(e),r=await tc(t.storage),s=await r.backend.getMetadata(t.fullPath);if(rc(r,{request:{auth:Vi(e),method:"get",path:t.fullPath},resource:Zd(s)},e,n),!s)throw sj(t.fullPath);return aj(s)}function T6(t,e){if(t.fullPath==="")throw jg(e)}const D6="application/octet-stream";async function I6(t,e,n,r){$6(t,"uploadBytes");const s=ls(t.storage),o=yo(s,r),c=L6(e,n==null?void 0:n.contentType),d=M6({ref:t,blob:c,settable:n}),f=await tc(t.storage),p=await f.backend.getMetadata(t.fullPath);rc(f,{request:{auth:Vi(s),method:p?"update":"create",path:t.fullPath,resource:a6({size:d.size,contentType:d.contentType,customMetadata:d.customMetadata})},resource:Zd(p)},s,o),await f.backend.put(t.fullPath,c,d);try{Vs(s.sandbox,$d({service:"storage",op:"object_put",path:t.fullPath,auth:Vi(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:aj(d)}}function M6(t){const{ref:e,blob:n,settable:r}=t,s=(t.now??new Date).toISOString(),o=U6(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||D6,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 L6(t,e){return t instanceof Blob?e&&e!==t.type?new Blob([t],{type:e}):t:new Blob([t],{type:e??""})}function U6(t){return String(t.getTime())}function $6(t,e){if(t.fullPath==="")throw jg(e)}async function B6(t,e){return lj(t,"getBlob"),q6(t,e)}async function oj(t,e){lj(t,"deleteObject");const n=ls(t.storage),r=yo(n,e),s=await tc(t.storage),o=await s.backend.getMetadata(t.fullPath);rc(s,{request:{auth:Vi(n),method:"delete",path:t.fullPath},resource:Zd(o)},n,r),await s.backend.delete(t.fullPath);try{Vs(n.sandbox,$d({service:"storage",op:"object_delete",path:t.fullPath,auth:Vi(n),before:o??void 0,detail:{bucket:t.bucket}}),r)}catch{}}async function q6(t,e){const n=ls(t.storage),r=yo(n),s=await tc(t.storage),o=await s.backend.getMetadata(t.fullPath);rc(s,{request:{auth:Vi(n),method:"get",path:t.fullPath},resource:Zd(o)},n,r);const c=await s.backend.getBlob(t.fullPath);if(!c)throw sj(t.fullPath);return typeof e=="number"&&c.size>e?c.slice(0,e):c}function lj(t,e){if(t.fullPath==="")throw jg(e)}async function kg(t){const e=t.storage,n=ls(e),r=yo(n),s=await tc(e);rc(s,{request:{auth:Vi(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(Hl(e,g.fullPath));else{const w=b.slice(0,v),_=`${o}${w}`;f.has(_)||(f.add(_),p.push(Hl(e,_)))}}return p.sort((g,b)=>g.fullPath<b.fullPath?-1:g.fullPath>b.fullPath?1:0),{items:d,prefixes:p}}function F6(t,e,n){const r={name:n,options:structuredClone(e),automaticDataCollectionEnabled:!0};return GI(r,t),r}const z6=Object.freeze({source:Object.freeze({kind:"studio"}),authLens:Object.freeze({mode:"admin"})});function P6(t){return Wl(t.withAuth(null),z6)}const V6="pyric-studio";function cj(t,e){return t.listDocuments(e).map(({path:n,phantom:r})=>({path:n,phantom:r}))}let H6=0;function G6(t){const e=F6(t,{projectId:"pyric-studio"},`pyric-studio-${H6++}`),n=Wt(t),r=P6(t);return{sandbox:t,app:e,firestore:Vd(t),adminFirestore:bg(r),auth:XA(t),storage:E6(r),listRootCollections:()=>n.listRootCollections(),listSubcollections:s=>n.listSubcollections(s),listDocuments:s=>cj(n,s)}}function K6(t,e){const[n,r]=A.useState(!1),[s,o]=A.useState(null),c=A.useMemo(()=>VE(),[]),d=A.useMemo(()=>{try{return G6(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:V6,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 Y6(t){var n;const e=((n=t.rules)==null?void 0:n.engine)??t.service;return e==="rtdb"||e==="storage"?e:"firestore"}function Z6(t){switch(Y6(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 W6(t){var e;return((e=DE(t))==null?void 0:e.rules.kind)==="evaluated"}function Q6(t){return"service"in t&&typeof t.service=="string"?t.service:"firestore"}function J6(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 X6(t){const e=[];for(const n of t)W6(n)&&e.push(e4(n));return e.sort((n,r)=>r.at-n.at)}function e4(t){const e={id:t.id,at:t.at,result:t.result==="allow"?"allow":t.result==="unsupported"?"unsupported":"deny",method:t.method,service:Q6(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=J6(t);return n!==void 0&&(e.resourceData=n),t.resourceBefore&&(e.resourceBefore={data:t.resourceBefore.data,exists:t.resourceBefore.exists}),e}const m_=/^Rule #(\d+) \(([^)]+)\) → (ALLOW|deny|unsupported)/;function t4(t){var n;const e=((n=t.rules)==null?void 0:n.engine)??t.service;return e==="rtdb"||e==="storage"?e:"firestore"}function n4(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 r4(t){var s;const e=t4(t),n=t.reasons.filter(o=>m_.test(o)),r=t.reasons.filter(o=>!m_.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"?i4(t,n,r):e==="storage"?a4(t,n,r):s4(t,n,r)}function s4(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 i4(t,e,n){const r=t.rules,s=n4(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 o4(t){var e;return!!((e=t.auth)!=null&&e.uid)}function l4(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:l4(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 u4(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 d4(t){const e=Wt(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=>cj(e,n)}}function ri(){const t=cs(),e=rr(),n=e.status==="ready"?e.env.persistence:void 0,r=K6(n,e.status),s=e.status==="ready"?e.env.live:void 0,o=f4(s);return A.useMemo(()=>{switch(t.status){case"ready":return{status:"ready",handles:d4(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 f4(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 _d=500;function im(t){return t.length>_d?t.slice(-_d):t}function sc(){var d;const t=cs(),e=rr(),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(im(n.history())),n.subscribe(p=>o(g=>im(dO(g,p))))},[r,n]);const c=A.useMemo(()=>r?im(t.events):[],[r,t]);return r?c:s}function h4(t){return t.kind==="request"||t.kind==="operation"}function p4(t){const e=DE(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 m4(){const t=sc();return A.useMemo(()=>t.filter(h4).map(p4),[t])}function y4(){const t=sc();return A.useMemo(()=>X6(t),[t])}function g4(){const t=ri();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)??ur,s=((f=t.firestoreApi)==null?void 0:f.setDoc)??Pl;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 b4(){const t=ri();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)??lr.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 v4(){const t=ri(),e=rr(),n=e.status==="ready"?e.env.live:void 0;return A.useCallback(async()=>{if(t.status!=="ready")throw new Error("No sandbox to clear.");const r=[];try{const s=n?await n.resetAll():await t.handles.sandbox.resetAll();r.push(...(s==null?void 0:s.errors)??[])}catch(s){r.push(`reset: ${s instanceof Error?s.message:String(s)}`)}return{errors:r}},[t,n])}function w4(){const t=v4(),e=g4(),n=b4(),r=cs();return A.useCallback(async()=>{const s=await t();if(r.status==="ready"){const{applySeed:o,deploySeedRules:c}=await p1(async()=>{const{applySeed:d,deploySeedRules:f}=await import("./seed-D_UjxfOU.js");return{applySeed:d,deploySeedRules:f}},[]);c(r.handles.sandbox),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 x4(){const t=cs(),e=rr(),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 Cg(){const t=rr(),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 S4(){const t=rr(),e=t.status==="ready"?t.env.live:void 0;return A.useCallback(async()=>e?e.exportState():null,[e])}function _4(){const t=rr(),e=t.status==="ready"?t.env.live:void 0;return A.useCallback(async n=>e?(await e.importState(n),!0):!1,[e])}function E4(){const t=rr(),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 A4(){const t=cs(),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 Wt(t.handles.sandbox).getRules()}catch{return""}},[t,n])}function j4(t){let e=!0;return n=>{const r=e;e=!1,t(s=>C4(s,n,r))}}function k4(t){const e=new Map;for(const n of t)e.set(by(n),n);return[...e.values()]}function C4(t,e,n){return k4(n?e:[...t??[],...e])}const N4=3e4;function uj(){const t=ri(),e=rr(),[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),w=A.useRef(0),_=A.useCallback(I=>{var O,T,P,$,K,W,se;const N=d.current;if(N.status!=="ready")return;const R=++b.current;c.current=!0,o(!0);const M=N.handles,F=M.adminFirestore,D=((O=N.firestoreApi)==null?void 0:O.collection)??Ui,C=((T=N.firestoreApi)==null?void 0:T.query)??Vl,L=((P=N.firestoreApi)==null?void 0:P.getDocs)??zl,U=(($=N.firestoreApi)==null?void 0:$.limit)??vd,H=((K=N.storageApi)==null?void 0:K.ref)??Hl,z=((W=N.storageApi)==null?void 0:W.listAll)??kg,q=((se=N.authApi)==null?void 0:se.listUsers)??lr.listUsers,x={listRootCollections:()=>M.listRootCollections(),listDocumentPaths:async(B,ee)=>(await L(C(D(F,B),U(ee)))).docs.slice(0,ee).map(le=>`${B}/${le.id}`),listSubcollections:B=>Promise.resolve(M.listSubcollections(B)),listUsers:async B=>(await Promise.resolve(q(M.auth))).slice(0,B).map(ae=>({uid:ae.uid,email:ae.email??null})),listStorageObjectPaths:B=>j3(H(M.storage,""),z,{maxObjects:B,maxListCalls:vy.storageListCalls}),listRtdbTopLevelKeys:async()=>{const B=p.current;if(!B)return[];const ee=Date.now()-w.current<N4;if(v.current!==null&&ee&&!(I!=null&&I.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,w.current=Date.now(),le}},E=j4(B=>r(B));B3(x,vy,B=>{R===b.current&&E(B)}).catch(()=>{}).finally(()=>{if(R===b.current&&(c.current=!1,o(!1),r(B=>B??[]),g.current)){const B=g.current;g.current=null,_(B)}})},[]),k=A.useCallback(I=>{if(d.current.status==="ready"){if(c.current){g.current={...g.current,...I};return}_(I)}},[_]);return A.useEffect(()=>{t.status==="ready"&&n===null&&!c.current&&_()},[t,n,_]),{entries:n,building:s,ensure:k}}const O4=150;function R4(t){return t.startsWith("/")||/rtdb/i.test(t)}function dj({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:w,building:_,ensure:k}=uj();A.useEffect(()=>{if(r)return r(()=>{var D;return(D=v.current)==null?void 0:D.focus()}),()=>r(null)},[r]),A.useEffect(()=>{var D;t&&((D=v.current)==null||D.focus())},[t]),A.useEffect(()=>{const D=setTimeout(()=>d(s),O4);return()=>clearTimeout(D)},[s]);const I=A.useMemo(()=>WS(c,Pi,w??[]),[c,w]),N=A.useMemo(()=>QS(I),[I]);A.useEffect(()=>{p(D=>N.length===0?0:Math.min(D,N.length-1))},[N.length]);const R=D=>{D&&(o(""),d(""),b(!1),Jn(D.target),e==null||e(D.target))},M=()=>{if(s===c){R(N[f]??N[0]);return}const D=QS(WS(s,Pi,w??[]));R(D[0])};let F=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&&N.length>0,"aria-autocomplete":"list",onFocus:()=>{k(),b(!0)},onBlur:()=>b(!1),onChange:D=>{const C=D.target.value;o(C),b(!0),R4(C)&&k({rtdbLikely:!0})},onKeyDown:D=>{if(D.key==="ArrowDown")D.preventDefault(),p(C=>Math.min(C+1,Math.max(N.length-1,0)));else if(D.key==="ArrowUp")D.preventDefault(),p(C=>Math.max(C-1,0));else if(D.key==="Enter")M();else if(D.key==="Escape"){if(n){n();return}o(""),d(""),b(!1)}}})}),g&&!I.length&&_&&w===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&&I.length?h.jsx("div",{className:"studio-home__command-results",role:"listbox","aria-label":"Suggestions",onMouseDown:D=>D.preventDefault(),children:I.map(D=>{const C=F;return F+=D.results.length,h.jsxs("div",{className:"studio-home__command-group",children:[h.jsx("span",{className:"studio-home__command-group-title","aria-hidden":"true",children:D.title}),h.jsx("ul",{className:"studio-home__command-group-list",children:D.results.map((L,U)=>{const H=C+U;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:()=>R(L),children:[h.jsx("span",{className:"studio-home__command-label",children:L.label}),h.jsx("span",{className:"studio-home__command-sub",children:L.hint})]})},L.id)})})]},D.kind)})}):null]})}function T4({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(dj,{autoFocus:!0,onEscape:t,onNavigated:t})})})}const D4={status:"loading",payload:null},Ou={status:"absent",payload:null};let Ed=D4,y_=!1;const Ay=new Set;function Ru(t){Ed=t;for(const e of Ay)e()}function I4(){if(!y_){if(y_=!0,typeof fetch>"u"){Ed=Ou;return}fetch("/__pyric/init.json").then(async t=>{if(!t.ok||!(t.headers.get("content-type")??"").includes("json"))return Ru(Ou);const n=await t.json();Ru({status:"ready",payload:n})}).catch(()=>Ru(Ou))}}function M4(t){return Ay.add(t),I4(),()=>Ay.delete(t)}function Qd(){return A.useSyncExternalStore(M4,()=>Ed,()=>Ed)}function L4(t){return t.kind==="absent"?"absent":t.sandboxConnected?"available":"idle"}function U4(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 $4(t){try{const e=await t("/__pyric/health");return e.ok?(e.headers.get("content-type")??"").includes("json")?U4(e.status,await e.json()):{kind:"absent"}:{kind:"absent"}}catch{return{kind:"absent"}}}function B4(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=L4(await $4(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 q4="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 F4(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 z4(t){return t==="studio"?"Studio":"App"}function P4(t,e,n=Date.now()){const r=t.clients.length,s=t.clients.map(c=>({clientId:c.clientId,kindLabel:z4(c.kind),route:c.route||"/",visibilityLabel:c.visibility==="hidden"?"Hidden":"Visible",isThisPage:c.clientId===e,freshnessLabel:F4(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:q4,otherCount:o}}function V4(){const t=rr(),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(P4(o,s))})},[e]),n}function H4(){const t=rr(),e=Qd(),n=B4(),r=V4(),[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=w=>{var _;w.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:Gd({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 G4(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 g_(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 K4({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(g_(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&&G4(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(g_("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 Y4={buckets:[],total:0,denies:0,maxCount:0,outOfWindow:0};function Z4({events:t,window:e,bucketCount:n=30}){return A.useMemo(()=>W4(t,e,n),[t,e.start,e.end,n])}function W4(t,e,n=30){const r=e.end-e.start;if(n<=0||r<=0)return Y4;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 w=v.at;if(w<e.start||w>=e.end){p++;continue}let _=Math.floor((w-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,w)=>{const _=c[w];return{index:w,start:e.start+w*s,end:e.start+(w+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 Q4=new Set(["get","list"]),J4=new Set(["create","update","set"]),X4=new Set(["delete","remove"]),eB=[{key:"reads",label:"Read ops"},{key:"writes",label:"Writes"},{key:"deletes",label:"Deletes"}],tB=[{key:"allows",label:"Allows"},{key:"denies",label:"Denies"},{key:"errors",label:"Errors"}];function Jd(t){return t.origin==="admin"}function nB(t,e=Jd){return t.result==="allow"||e(t)?Q4.has(t.method)?"reads":J4.has(t.method)?"writes":X4.has(t.method)?"deletes":null:null}function rB(t,e=Jd){return e(t)?null:t.result==="allow"?"allows":t.result==="deny"?"denies":t.result==="error"?"errors":null}const sB=t=>({points:[],series:t.map(e=>({key:e.key,label:e.label,values:[],total:0})),maxValue:0});function fj(t,e,n,r,s){const o=e.end-e.start;if(n<=0||o<=0)return sB(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 w=v.at;if(w<e.start||w>=e.end)continue;const _=s(v);if(_==null)continue;let k=Math.floor((w-e.start)/c);k>=n&&(k=n-1);const I=d.get(_);I[k]++,f.set(_,(f.get(_)??0)+1)}let p=0;for(const v of d.values())for(const w of v)w>p&&(p=w);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 iB(t,e,n=24,r=Jd){return fj(t,e,n,eB,s=>nB(s,r))}function aB(t,e,n=24,r=Jd){return fj(t,e,n,tB,s=>rB(s,r))}function oB({events:t,window:e,bucketCount:n=24,isAdmin:r}){return A.useMemo(()=>iB(t,e,n,r),[t,e.start,e.end,n,r])}function lB({events:t,window:e,bucketCount:n=24,isAdmin:r}){return A.useMemo(()=>aB(t,e,n,r),[t,e.start,e.end,n,r])}function Ja({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 Kl(t){const e=new Date(t),n=r=>String(r).padStart(2,"0");return`${n(e.getHours())}:${n(e.getMinutes())}:${n(e.getSeconds())}`}function hj({event:t,selected:e,onSelect:n,renderClassification:r,formatTime:s=Kl,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(Ja,{kind:t.method,children:t.method}),h.jsx("span",{"data-pyric-traffic-path":"",children:t.path||"/"}),r?r(t):null]})}var Ng=h1();function Fa(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 w;if(n.key&&((f=n.debug)!=null&&f.call(n))&&(w=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()-w)*100)/100,I=k/16,N=(R,M)=>{for(R=String(R);R.length<M;)R=" "+R;return R};console.info(`%c⏱ ${N(k,5)} /${N(_,5)} ms`,`
|
|
1213
1213
|
font-size: .6rem;
|
|
1214
1214
|
font-weight: bold;
|
|
1215
|
-
color: hsl(${Math.max(0,Math.min(120-120*I,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 b_(t,e){if(t===void 0)throw new Error("Unexpected undefined");return t}const lB=(t,e)=>Math.abs(t-e)<1.01,cB=(t,e,n)=>{let r;return function(...s){t.clearTimeout(r),r=t.setTimeout(()=>e.apply(this,s),n)}},v_=t=>{const{offsetWidth:e,offsetHeight:n}=t;return{width:e,height:n}},uB=t=>t,dB=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},fB=(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(v_(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(v_(n))};t.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(d):d()});return o.observe(n,{box:"border-box"}),()=>{o.unobserve(n)}},w_={passive:!0},x_=typeof window>"u"?!0:"onscrollend"in window,hB=(t,e)=>{const n=t.scrollElement;if(!n)return;const r=t.targetWindow;if(!r)return;let s=0;const o=t.options.useScrollendEvent&&x_?()=>{}:cB(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,w_);const p=t.options.useScrollendEvent&&x_;return p&&n.addEventListener("scrollend",f,w_),()=>{n.removeEventListener("scroll",d),p&&n.removeEventListener("scrollend",f)}},pB=(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"]},mB=(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 yB{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:uB,rangeExtractor:dB,onChange:()=>{},measureElement:pB,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=Fa(()=>(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=Fa(()=>[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=Fa(()=>[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 w of this.laneAssignments.keys())w>=n&&this.laneAssignments.delete(w);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(w=>{this.itemSizeCache.set(w.key,w.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 w=0;w<g;w++){const _=b[w];_&&(v[_.lane]=w)}for(let w=g;w<n;w++){const _=o(w),k=this.laneAssignments.get(w);let I,N;const R=f==="estimate"||p.has(_);if(k!==void 0&&this.options.lanes>1){I=k;const C=v[I],L=C!==void 0?b[C]:void 0;N=L?L.end+this.options.gap:r+s}else{const C=this.options.lanes===1?b[w-1]:this.getFurthestMeasurement(b,w);N=C?C.end+this.options.gap:r+s,I=C?C.lane:w%this.options.lanes,this.options.lanes>1&&R&&this.laneAssignments.set(w,I)}const M=p.get(_),F=typeof M=="number"?M:this.options.estimateSize(w),D=N+F;b[w]={index:w,start:N,size:F,end:D,key:_,lane:I},v[I]=w}return this.measurementsCache=b,b},{key:!1,debug:()=>this.options.debug}),this.calculateRange=Fa(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,s,o)=>this.range=n.length>0&&r>0?gB({measurements:n,outerSize:r,scrollOffset:s,lanes:o}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=Fa(()=>{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=Fa(()=>[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 b_(r[pj(0,r.length-1,s=>b_(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&&lB(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 pj=(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 gB({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=pj(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 S_=typeof document<"u"?A.useLayoutEffect:A.useEffect;function bB({useFlushSync:t=!0,...e}){const n=A.useReducer(()=>({}),{})[1],r={...e,onChange:(o,c)=>{var d;t&&c?Ng.flushSync(n):n(),(d=e.onChange)==null||d.call(e,o,c)}},[s]=A.useState(()=>new yB(r));return s.setOptions(r),S_(()=>s._didMount(),[]),S_(()=>s._willUpdate()),s}function vB(t){return bB({observeElementRect:fB,observeElementOffset:hB,scrollToFn:mB,...t})}function Og({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=vB({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 wB={batch:"batch write",transaction:"transaction","listener-run":"listener re-evals"};function xB({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:wB[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(hj,{event:p,selected:p.id===r,onSelect:n,renderClassification:s,formatTime:o})},p.id))}):null]})}function SB(t){return t<0?0:t>1?1:t}function am(t,e){const n=e.end-e.start;return n<=0?0:SB((t-e.start)/n)}function _B({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(),[w,_]=A.useState(null),[k,I]=A.useState(null),N=Y4({events:t??[],window:n,bucketCount:r}),R=e??N,{buckets:M,total:F}=R,D=w??k,C=D===null?null:M.find(x=>x.index===D)??null,L=C!==null&&(s==null?void 0:s.start)===C.start&&s.end===C.end;if(M.length===0)return h.jsx("div",{className:b,"data-pyric-ui":"traffic-timeline","data-pyric-empty":"",children:g});const U=F===0,H=d===void 0?n.end:d,z=H==null?null:am(H,n),q=typeof p=="function"?p(n):p;return h.jsxs("div",{className:b,"data-pyric-ui":"traffic-timeline","data-pyric-empty":U?"":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:M.map(x=>h.jsx(EB,{bucket:x,window:n,onBrush:o,onHover:c?_:void 0,onFocus:c?I:void 0,summaryId:c&&!L&&(C==null?void 0:C.index)===x.index?v:void 0,selected:(s==null?void 0:s.start)===x.start&&s.end===x.end},x.index))}),C&&c&&!L?h.jsx("div",{id:v,role:"tooltip","data-pyric-bucket-summary":"",style:{"--pyric-bucket-summary-x":(C.index+.5)/Math.max(M.length,1)},children:c(C)}):null,s&&h.jsx("div",{"data-pyric-brush":"","aria-hidden":"true",style:{"--pyric-brush-left":am(s.start,n),"--pyric-brush-right":1-am(s.end,n)}}),z!=null&&h.jsx("div",{"data-pyric-live":"","aria-hidden":"true",style:{"--pyric-live-x":z}})]}),q!=null&&h.jsx("div",{"data-pyric-timeline-axis":"",children:q})]})}function EB({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 AB=t=>String(t);function jB({series:t,visible:e,onToggle:n,formatValue:r=AB,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 kB=t=>String(t),CB=t=>new Date(t).toLocaleTimeString();function NB({points:t,series:e,visible:n,omitZeroSeries:r=!1,formatValue:s=kB,formatTime:o=CB,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(N=>(!n||n.has(N.key))&&(!r||N.total>0));let b=0;for(const N of g)for(const R of N.values)R>b&&(b=R);const v=b===0?1:b,w=t.length,_=N=>w===1?50:N/(w-1)*100,k=N=>100-N/v*100,I=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(N=>{const R=e.indexOf(N);if(!((!n||n.has(N.key))&&(!r||N.total>0)))return null;const F=N.values.map((D,C)=>`${C===0?"M":"L"}${_(C)},${k(D)}`).join(" ");return h.jsx("path",{"data-pyric-chart-line":"","data-pyric-series-key":N.key,"data-pyric-series-index":R,d:F,fill:"none",vectorEffect:"non-scaling-stroke"},N.key)})}),h.jsx("div",{"data-pyric-chart-hits":"",children:t.map((N,R)=>h.jsx("button",{type:"button","data-pyric-chart-hit":"","data-pyric-point-index":R,onMouseEnter:()=>p(R),onFocus:()=>p(R),onMouseLeave:()=>p(M=>M===R?null:M),onBlur:()=>p(M=>M===R?null:M),"aria-label":`${o(N.start)} to ${o(N.end)}`},N.index))}),I&&h.jsxs("div",{"data-pyric-chart-tooltip":"",style:{"--pyric-hover-x":_(I.index)},children:[h.jsxs("div",{"data-pyric-tooltip-time":"",children:[o(I.start)," – ",o(I.end)]}),g.map(N=>h.jsxs("div",{"data-pyric-tooltip-row":"","data-pyric-series-key":N.key,"data-pyric-series-index":e.indexOf(N),children:[h.jsx("span",{"data-pyric-tooltip-label":"",children:N.label}),h.jsx("span",{"data-pyric-tooltip-value":"",children:s(N.values[I.index])})]},N.key))]})]})})}const OB={listUsers:lr.listUsers,subscribeUsers:lr.subscribeUsers,createUser:lr.createUser,updateUser:lr.updateUser,deleteUser:lr.deleteUser,clearUsers:lr.clearUsers,getAuthProviderConfig:lr.getAuthProviderConfig,setAuthProviderConfig:lr.setAuthProviderConfig,subscribeAuthProviderConfig:lr.subscribeAuthProviderConfig},mj=A.createContext(OB);function RB(){return A.useContext(mj)}function yj({value:t,children:e}){return A.createElement(mj.Provider,{value:t},e)}function TB(t,e){return[t.uid,t.email,t.displayName,t.phoneNumber].some(n=>n!=null&&n.toLowerCase().includes(e))}function Rg(t){const{listUsers:e,subscribeUsers:n,createUser:r,updateUser:s,deleteUser:o,clearUsers:c}=RB(),[d,f]=A.useState([]),[p,g]=A.useState(!0),[b,v]=A.useState(void 0),[w,_]=A.useState("");A.useEffect(()=>{let D=!1;g(!0),v(void 0);const C=z=>{D||(f(z),g(!1))},L=z=>{D||(f([]),v(z instanceof Error?z:new Error(String(z))),g(!1))},U=()=>{try{const z=e(t);z&&typeof z.then=="function"?z.then(C).catch(L):C(z)}catch(z){L(z)}};let H;try{U(),H=n(t,U)}catch(z){L(z)}return()=>{D=!0,H==null||H()}},[t,e,n]);const k=A.useMemo(()=>{const D=w.trim().toLowerCase();return D?d.filter(C=>TB(C,D)):d},[d,w]),I=A.useCallback(D=>r(t,D),[t,r]),N=A.useCallback((D,C)=>s(t,D,C),[t,s]),R=A.useCallback(D=>o(t,D),[t,o]),M=A.useCallback(()=>c(t),[t,c]),F=A.useCallback(()=>{const D=e(t);D&&typeof D.then=="function"?D.then(C=>f(C)).catch(()=>{}):f(D)},[t,e]);return{users:k,totalCount:d.length,isLoading:p,error:b,filter:w,setFilter:_,createUser:I,updateUser:N,deleteUser:R,clearUsers:M,refresh:F}}const DB=["iss","aud","sub","iat","exp","nbf","jti","nonce","azp","acr","amr","cnf","auth_time","firebase","at_hash","c_hash"],IB=1e3;function gj(t){const e=t.trim();if(!e)return{ok:!0,claims:void 0};if(e.length>IB)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 DB)if(r in n)return{ok:!1,message:`Custom claims must not have forbidden key: ${r}`};return{ok:!0,claims:n}}const MB={email:"",password:"",displayName:"",phoneNumber:"",photoUrl:"",emailVerified:!1,disabled:!1,claimsText:"",providerIds:[]},LB=new Set(["password","anonymous","phone"]),UB=/^[^@]+@[^@]+\.[^@]+$/,__=6;function $B(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=>!LB.has(e))}:{...MB}}function BB(t){const e=$B(t);return{fields:e,initial:{...e}}}function qB(t,e){switch(e.type){case"setField":return{...t,fields:{...t.fields,[e.field]:e.value}};case"reset":return{...t,fields:{...t.initial}}}}function FB(t){const e={},n=t.email.trim(),r=t.password;n&&!UB.test(n)&&(e.email="Invalid email"),r&&r.length<__&&(e.password=`Password should be at least ${__} characters`),r&&!n&&(e.password="Email is required for password authentication");const s=gj(t.claimsText);return s.ok||(e.claims=s.message),e}function zB(t){const{fields:e,initial:n}=t;return Object.keys(e).some(r=>r==="providerIds"?!bj(e.providerIds,n.providerIds):e[r]!==n[r])}function bj(t,e){if(t.length!==e.length)return!1;const n=[...e].sort();return[...t].sort().every((r,s)=>r===n[s])}function vj(t){const e=gj(t.claimsText);return e.ok?e.claims:void 0}function PB(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=vj(e);return r&&(n.customClaims=r),e.providerIds.length&&(n.providerUserInfo=e.providerIds.map(s=>({providerId:s}))),n}function VB(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=vj(e)??{}),bj(e.providerIds,n.providerIds)||(r.providerUserInfo=e.providerIds.map(s=>({providerId:s}))),r}function wj(t={}){const[e,n]=A.useReducer(qB,t.initial,BB),r=A.useMemo(()=>FB(e.fields),[e.fields]),s=A.useMemo(()=>zB(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:()=>PB(e),toUpdateRequest:()=>VB(e),dispatch:n}}const HB={"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 Ad(t){return HB[t]??t}function E_(t){return t.email??t.phoneNumber??(t.isAnonymous?"anonymous":t.uid)}function GB(t){return t.isAnonymous&&t.providerUserInfo.length===0?h.jsx("span",{"data-pyric-provider-id":"anonymous",children:Ad("anonymous")}):t.providerUserInfo.map(e=>h.jsx("span",{"data-pyric-provider-id":e.providerId,children:Ad(e.providerId)},e.providerId))}function A_(t){if(!t)return"—";const e=new Date(t);return Number.isNaN(e.getTime())?"—":e.toLocaleDateString()}function xj({users:t,isLoading:e,error:n,filter:r,onSelect:s,renderIdentifier:o,renderProviders:c,renderSelection:d,renderSelectionHeader:f,renderActions:p,renderActionsHeader:g,formatCreatedAt:b=A_,formatLastLoginAt:v=A_,emptyState:w,noResultsState:_,className:k,virtualizeThreshold:I=100,rowHeight:N=44,virtualizedHeight:R="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 D=!!(r!=null&&r.trim());return h.jsx("div",{className:k,"data-pyric-ui":"auth-user-list","data-pyric-empty":"","data-pyric-no-results":D?"":void 0,children:D?_??"No results":w??"No users for this project yet"})}const M=t.length>I,F=D=>h.jsxs("div",{role:"row","data-pyric-user-entry":!0,"data-pyric-user-uid":D.uid,"data-pyric-user-disabled":D.disabled?"":void 0,children:[d?h.jsx("span",{role:"cell","data-pyric-user-cell":"selection",children:d(D)}):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(D),children:o?o(D):E_(D)}):(o??E_)(D)}),h.jsx("span",{role:"cell","data-pyric-user-cell":"providers",children:(c??GB)(D)}),h.jsx("span",{role:"cell","data-pyric-user-cell":"created",children:b(D.createdAt)}),h.jsx("span",{role:"cell","data-pyric-user-cell":"signed-in",children:v(D.lastLoginAt)}),h.jsx("span",{role:"cell","data-pyric-user-cell":"uid",children:D.uid}),p?h.jsx("span",{role:"cell","data-pyric-user-cell":"actions",children:p(D)}):null]},D.uid);return h.jsxs("div",{className:k,role:"table","aria-label":"Authentication users","data-pyric-ui":"auth-user-list","data-pyric-virtualized":M?"":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]}),M?h.jsx(Og,{items:t,estimateSize:N,height:R,getItemKey:D=>D.uid,renderItem:F}):h.jsx("div",{role:"rowgroup","data-pyric-user-rows":!0,children:t.map(F)})]})}function KB({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 YB({selected:t,onChange:e}){return h.jsx("div",{"data-pyric-provider-checklist":!0,children:YA.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:Ad(n)}),h.jsx("span",{"data-pyric-provider-option-id":!0,children:n})]},n))})}function Sj({initial:t,onSubmit:e,onCancel:n,submitLabel:r="Save",cancelLabel:s="Cancel",children:o,className:c,renderField:d}){const f=wj({initial:t}),p=t?"edit":"create",g=f.isValid&&(p==="create"||f.isDirty),b=(_,k,I,N,R=null)=>({name:_,label:k,input:N,error:R,kind:I,defaultRender:()=>I==="checkbox"?h.jsxs("label",{"data-pyric-field-label":_,children:[N,h.jsx("span",{"data-pyric-label-text":!0,children:k})]},_):I==="group"?h.jsxs("fieldset",{"data-pyric-field-label":_,children:[h.jsx("legend",{"data-pyric-label-text":!0,children:k}),N]},_):h.jsxs("label",{"data-pyric-field-label":_,children:[h.jsx("span",{"data-pyric-label-text":!0,children:k}),N,R!=null&&h.jsx("p",{role:"alert","data-pyric-field-error":_,children:R})]},_)}),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(YB,{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)}))],w=_=>{_.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:w,children:[v.map(_=>d?h.jsx(A.Fragment,{children:d(_)},_.name):_.defaultRender()),h.jsx(KB,{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 ZB({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 w;const v=g.current;(w=v==null?void 0:v.focus)==null||w.call(v)}},[t]),!t||typeof document>"u"?null:Ng.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 _j=A.createContext(null);function go(){const t=A.useContext(_j);if(!t)throw new Error("useConfirm: missing <ConfirmProvider> ancestor");return t}function Tg({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(_j.Provider,{value:f,children:[t,n?h.jsx(ZB,{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 WB(t){return t.email??t.phoneNumber??t.displayName??t.uid}function QB({user:t,onDelete:e,title:n="Delete user",body:r,confirmLabel:s="Delete",renderTrigger:o,className:c}){const d=go(),f=async()=>{await d({title:n,body:r??`This will permanently delete ${WB(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 JB(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 XB={addDoc:wg,collection:Ui,deleteDoc:bd,doc:ur,getDoc:vg,getDocs:zl,limit:vd,onSnapshot:CU,query:Vl,setDoc:Pl,startAfter:kU},Ej=A.createContext(XB);function Dg(){return A.useContext(Ej)}function e5({value:t,children:e}){return A.createElement(Ej.Provider,{value:t},e)}function t5(t){const{onSnapshot:e}=Dg(),[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:JB(o),isLoading:!1}))},[e,t]),n}function Xd(t){return t==null?"null":typeof t=="string"?"string":typeof t=="number"?"number":typeof t=="boolean"?"boolean":typeof t=="object"&&Xi(t)!==null?"vector":Array.isArray(t)?"array":t instanceof $n?"timestamp":t instanceof Or?"geopoint":t instanceof Er?"bytes":typeof t=="object"&&Aj(t)?"timestamp":typeof t=="object"&&jj(t)?"geopoint":typeof t=="object"&&n5(t)?"reference":typeof t=="object"?"map":"null"}function Aj(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 jj(t){const e=t;return Object.keys(e).length===2&&typeof e.latitude=="number"&&typeof e.longitude=="number"}function n5(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 Xi(t){if(t===null||typeof t!="object")return null;const e=t;if(e.typeName==="vector"&&Tu(e.value)||e.__type__==="__vector__"&&Tu(e.value))return Du(e.value);if(Tu(e._values))return Du(e._values);if(typeof e.toArray=="function")try{const n=e.toArray();if(Tu(n))return Du(n)}catch{}return null}function Tu(t){return Array.isArray(t)&&t.every(e=>typeof e=="number")}function Du(t){const e=t.slice();return{values:e,dimension:e.length}}const j_=4;function kj(t){const e=t.values.slice(0,j_).join(", "),n=t.values.length>j_?", …":"";return`vector · ${t.dimension} [${e}${n}]`}function oo(t){const e=Xi(t);if(e)return kj(e);if(Array.isArray(t))return t.map(oo);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]=oo(o);return r}}return t}function Cj(){return crypto.randomUUID()}function r5(t){const e=Cj(),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))jy(n,e,r,s);return n}function jy(t,e,n,r){const s=Xd(r),o=Cj(),c={id:o,parentId:e,key:n,type:s,value:s5(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))jy(t,o,d,f);else if(s==="array"&&Array.isArray(r))for(const d of r)jy(t,o,null,d);return o}function s5(t){return t==="map"||t==="array"}function Nj(t){const e=t.nodes[t.rootId];if(!e||e.type!=="map")throw new Error("treeToData: tree root must be a map node");return ky(t,t.rootId)}function ky(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]=ky(t,s))}return r}case"array":{const r=[];for(const s of t.childIds[e]??[])r.push(ky(t,s));return r}default:return n.value}}function Cy(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 Oj(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 Rj(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 $n?void 0:"Expected a Timestamp";case"geopoint":return e instanceof Or?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 Er?void 0:"Expected a Bytes value";case"vector":return Xi(e)!==null?void 0:"Expected a vector value";case"map":case"array":return}}function Tj(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=Rj(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 Ig(t){switch(t){case"string":return"";case"number":return 0;case"boolean":return!1;case"null":return null;case"timestamp":return $n.now();case"geopoint":return new Or(0,0);case"reference":return{path:"",id:"",firestore:{}};case"bytes":return Er.fromUint8Array(new Uint8Array);case"vector":return{__type__:"__vector__",value:[]};case"map":case"array":return}}function Ny(t){if(t===null||typeof t!="object"||Xi(t)!==null)return t;if(Aj(t)){const n=t;return new $n(n.seconds??n._seconds??0,n.nanoseconds??n._nanoseconds??0)}if(jj(t)){const n=t;return new Or(n.latitude,n.longitude)}if(Array.isArray(t))return t.map(Ny);const e=Object.getPrototypeOf(t);if(e===Object.prototype||e===null){const n={};for(const[r,s]of Object.entries(t))n[r]=Ny(s);return n}return t}function Dj(t){const e=r5(Ny(t)),{tree:n,errorCount:r}=Tj(e);return{tree:n,initial:n,errorCount:r}}function i5(t,e){switch(e.type){case"setValue":return za(t,n=>o5(n,e.nodeId,e.value));case"setType":return za(t,n=>l5(n,e.nodeId,e.newType));case"setKey":return za(t,n=>c5(n,e.nodeId,e.key));case"addMapEntry":return za(t,n=>u5(n,e.parentId,e.key,e.childType));case"addArrayEntry":return za(t,n=>d5(n,e.parentId,e.childType));case"remove":return za(t,n=>f5(n,e.nodeId));case"reset":return{tree:t.initial,initial:t.initial,errorCount:a5(t.initial)};case"replaceData":return Dj(e.data);case"touch":{const n=t.tree.nodes[e.nodeId];if(!n||n.touched)return t;const r=Cy(t.tree);return r.nodes[e.nodeId]={...r.nodes[e.nodeId],touched:!0},{...t,tree:r}}case"touchAll":{const n=Cy(t.tree);for(const r of Object.keys(n.nodes))n.nodes[r]={...n.nodes[r],touched:!0};return{...t,tree:n}}}}function za(t,e){const n=e(Cy(t.tree)),{tree:r,errorCount:s}=Tj(n);return{...t,tree:r,errorCount:s}}function a5(t){let e=0;for(const n of Object.values(t.nodes))n.error&&e++;return e}function o5(t,e,n){const r=t.nodes[e];return!r||r.type==="map"||r.type==="array"||(t.nodes[e]={...r,value:n}),t}function l5(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 Oj(t,c))delete t.nodes[d],delete t.childIds[d];t.childIds[e]=[]}const s=n==="map"||n==="array"?void 0:Ig(n);return t.nodes[e]={...r,type:n,value:s},t}function c5(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 u5(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:Ig(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 d5(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:Ig(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 f5(t,e){const n=t.nodes[e];if(!n||n.id===t.rootId)return t;const r=Oj(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 Ij(t={}){const e=t.initial??{},n=A.useRef(null);n.current==null&&(n.current=Dj(e));const[r,s]=A.useReducer(i5,n.current),o=A.useCallback((R,M)=>s({type:"setValue",nodeId:R,value:M}),[]),c=A.useCallback((R,M)=>s({type:"setType",nodeId:R,newType:M}),[]),d=A.useCallback((R,M)=>s({type:"setKey",nodeId:R,key:M}),[]),f=A.useCallback((R,M,F)=>s({type:"addMapEntry",parentId:R,key:M,childType:F}),[]),p=A.useCallback((R,M)=>s({type:"addArrayEntry",parentId:R,childType:M}),[]),g=A.useCallback(R=>s({type:"remove",nodeId:R}),[]),b=A.useCallback(()=>s({type:"reset"}),[]),v=A.useCallback(R=>s({type:"replaceData",data:R}),[]),w=A.useCallback(R=>s({type:"touch",nodeId:R}),[]),_=A.useCallback(()=>s({type:"touchAll"}),[]),k=A.useCallback(()=>Nj(r.tree),[r.tree]),I=r.tree!==r.initial,N=r.errorCount===0;return A.useMemo(()=>({...r,isDirty:I,isValid:N,dispatch:s,setValue:o,setType:c,setKey:d,addMapEntry:f,addArrayEntry:p,remove:g,reset:b,replaceData:v,touch:w,touchAll:_,toData:k}),[r,I,N,o,c,d,f,p,g,b,v,w,_,k])}function h5({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,w]=A.useState(0),[_,k]=A.useState(n),I=A.useRef(0),[N,R]=A.useState(0),{addDoc:M,deleteDoc:F,doc:D,getDoc:C,getDocs:L,limit:U,onSnapshot:H,query:z,setDoc:q,startAfter:x}=Dg();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=z(K,U(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=++I.current,le=H(se,ye=>{R(ae),B(ye)},ee);return()=>{$=!0,le()}}return L(se).then(ae=>{B(ae)}).catch(ee),()=>{$=!0}},[t,L,U,r,H,n,e,z,_,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=z(e??t,x($),U(n));L(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,L,g,c,U,r,n,e,z,x]),O=A.useCallback(async($,K,W)=>{if($==null){const B=await M(t,K);return r==="paged"&&w(ee=>ee+1),B}const se=D(t,$);if((W==null?void 0:W.onExisting)==="fail"){const B=await C(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 q(se,K),r==="paged"&&w(B=>B+1),se},[M,t,D,C,r,q]),T=A.useCallback(async $=>{await F($),r==="paged"&&w(K=>K+1)},[F,r]),P=A.useCallback(()=>w($=>$+1),[]);return{documents:s,isLoading:c,error:f,subscriptionGeneration:N,hasMore:g,loadMore:E,createDocument:O,deleteDocument:T,refresh:P}}function p5({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 k_(t){return typeof t=="object"&&t!==null&&"isEqual"in t&&typeof t.isEqual=="function"}function C_(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function jd(t,e){if(Object.is(t,e))return!0;if(k_(t))return t.isEqual(e);if(k_(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)=>jd(s,e[o]));if(!C_(t)||!C_(e))return!1;const n=Object.keys(t),r=Object.keys(e);return n.length!==r.length?!1:n.every(s=>s in e&&jd(t[s],e[s]))}function m5({value:t,path:e}){return h.jsx("span",{"data-pyric-field-type":"string","data-pyric-field-path":e,children:t})}function y5({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 g5={type:"string",Display:m5,Edit:y5};function b5({value:t,path:e}){return h.jsx("span",{"data-pyric-field-type":"number","data-pyric-field-path":e,children:String(t)})}function v5({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 w5={type:"number",Display:b5,Edit:v5};function x5({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 S5({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 _5={type:"boolean",Display:x5,Edit:S5};function E5({path:t}){return h.jsx("span",{"data-pyric-field-type":"null","data-pyric-field-path":t,children:"null"})}function A5({path:t}){return h.jsx("span",{"data-pyric-field-type":"null","data-pyric-field-path":t,children:"null"})}const j5={type:"null",Display:E5,Edit:A5};function Mj(t){if(t instanceof $n)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 k5({value:t,path:e}){const n=Mj(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 C5({value:t,onChange:e,error:n,path:r}){const s=Mj(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($n.fromDate(p))},"aria-invalid":n?"true":void 0}),n?h.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const N5={type:"timestamp",Display:k5,Edit:C5};function O5({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 R5({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 Or(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 Or(t.latitude,o))}catch{}},"aria-label":"Longitude"})}),n?h.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const T5={type:"geopoint",Display:O5,Edit:R5},Lj=A.createContext({});Lj.Provider;function D5(){return A.useContext(Lj)}function I5({value:t,path:e}){const{onReferenceClick:n}=D5();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 M5({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 L5={type:"reference",Display:I5,Edit:M5};function U5({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 $5({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(Er.fromBase64String(s.target.value))}catch{}},"aria-invalid":n?"true":void 0}),n?h.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const B5={type:"bytes",Display:U5,Edit:$5};function Oy({value:t,path:e,fieldEditors:n}){const r=Xd(t),s=n[r];if(!s)return null;const{Display:o}=s;return h.jsx(o,{value:t,path:e,fieldEditors:n})}function Uj({label:t,value:e,path:n,fieldEditors:r,kind:s}){const o=Xd(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(Oy,{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(Oy,{value:e,path:n,fieldEditors:r})]})}function q5({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(Uj,{label:s,value:o,path:e?`${e}.${s}`:s,fieldEditors:n??{},kind:"key"},s))})}const F5={type:"map",Display:q5};function z5({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(Uj,{label:String(s),value:r,path:e?`${e}[${s}]`:`[${s}]`,fieldEditors:n??{},kind:"index"},s))})}const P5={type:"array",Display:z5},N_=4;function V5(t){return t.length<=N_?`[${t.join(", ")}]`:`[${t.slice(0,N_).join(", ")}, …]`}function H5({value:t,path:e}){const n=Xi(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:V5(n.values)})]}):h.jsx("span",{"data-pyric-field-type":"vector","data-pyric-field-path":e})}function G5(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 K5({value:t,onChange:e,error:n,path:r}){const s=Xi(t),o=s?JSON.stringify(s.values):"[]",[c,d]=A.useState(o),[f,p]=A.useState(void 0),g=w=>{d(w);const _=G5(w);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:w=>g(w.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 Y5={type:"vector",Display:H5,Edit:K5},O_={string:g5,number:w5,boolean:_5,null:j5,timestamp:N5,geopoint:T5,reference:L5,bytes:B5,map:F5,array:P5,vector:Y5};function $j(t){return t?{...O_,...t}:O_}function ef(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 Bj=A.createContext(null);function si(){const t=A.useContext(Bj);if(!t)throw new Error("DocumentEditor.* components must render inside <DocumentEditor.Root>");return t}function Z5({initial:t,fieldEditors:e,onChange:n,children:r,className:s}){const o=Ij({initial:t}),c=$j(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}=ef();return h.jsx(Bj.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 W5(){const{editor:t}=si(),e=t.tree.childIds[t.tree.rootId]??[];return h.jsxs("div",{"data-pyric-editor-fields":!0,children:[e.map(n=>h.jsx(Mg,{nodeId:n,path:Q5(t,n)},n)),h.jsx(qj,{parentId:t.tree.rootId})]})}function Q5(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 Mg({nodeId:t,path:e}){const{editor:n,fieldEditors:r}=si(),s=n.tree.nodes[t];if(!s)return null;if(s.type==="map")return h.jsx(e8,{node:s,path:e});if(s.type==="array")return h.jsx(t8,{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(Lg,{node:s,path:e}),h.jsx(c,{value:s.value,path:e,error:d,onChange:f=>n.setValue(s.id,f)})]})}function Lg({node:t,path:e}){const{editor:n}=si(),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(X5,{node:t}),h.jsx("button",{type:"button",onClick:()=>n.remove(t.id),"data-pyric-remove":!0,"aria-label":"Remove field",children:"×"})]})}const J5=["string","number","boolean","null","timestamp","geopoint","reference","bytes","vector","map","array"];function X5({node:t}){const{editor:e}=si(),n=t.parentId!=null?e.tree.nodes[t.parentId]:null,r=J5.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 e8({node:t,path:e}){const{editor:n}=si(),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(Lg,{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(Mg,{nodeId:s,path:c},s)})}),h.jsx(qj,{parentId:t.id})]})}function t8({node:t,path:e}){const{editor:n}=si(),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(Lg,{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(Mg,{nodeId:s,path:c})},s)})}),h.jsx(n8,{parentId:t.id})]})}function qj({parentId:t}){const{editor:e}=si();return h.jsx("button",{type:"button","data-pyric-add-map-entry":!0,onClick:()=>e.addMapEntry(t,"","string"),children:"+ Add field"})}function n8({parentId:t}){const{editor:e}=si();return h.jsx("button",{type:"button","data-pyric-add-array-entry":!0,onClick:()=>e.addArrayEntry(t,"string"),children:"+ Add item"})}const R_={Root:Z5,Fields:W5};function r8({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 yl=new Map;function Ug({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(yl);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(yl)}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(yl);return}const b=new Map;for(const[v,w]of e){const _=g.entries.has(v),k=g.entries.get(v);if(_&&n(k,w))continue;const I=c.current.get(v)===0?1:0;c.current.set(v,I),b.set(v,{kind:_?"modified":"added",cycle:I})}o.current={scope:t,entries:e},p(v=>{const w=new Map(v);let _=b.size>0;for(const k of v.keys())e.has(k)||(w.delete(k),_=!0);for(const[k,I]of b)w.set(k,I);return _?w.size===0?yl:w:v});for(const[v,w]of b){const _=d.current.get(v);_&&clearTimeout(_);const k=setTimeout(()=>{d.current.delete(v),p(I=>{var R;if(((R=I.get(v))==null?void 0:R.cycle)!==w.cycle)return I;const N=new Map(I);return N.delete(v),N.size===0?yl:N})},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 gl(t){return t.ref}function s8({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:w="60vh"}){const _=A.useMemo(()=>new Map(t.map(N=>[gl(N).path,N.data()])),[t]),k=Ug({scope:g,entries:_,equals:jd,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 I=t.length>b;return h.jsxs("div",{className:p,"data-pyric-ui":"document-list","data-pyric-virtualized":I?"":void 0,children:[I?h.jsx(Og,{items:t,estimateSize:v,height:w,getItemKey:N=>gl(N).path,renderItem:N=>{const R=k.get(gl(N).path);return h.jsxs("div",{"data-pyric-document-entry":!0,"data-pyric-document-id":N.id,"data-pyric-update":R==null?void 0:R.kind,"data-pyric-update-cycle":R==null?void 0:R.cycle,children:[h.jsx("button",{type:"button",onClick:()=>s==null?void 0:s(gl(N)),"data-pyric-document-select":!0,"data-pyric-update":R==null?void 0:R.kind,"data-pyric-update-cycle":R==null?void 0:R.cycle,children:c?c(N):N.id}),d?h.jsx("span",{"data-pyric-document-action":!0,children:d(N)}):null]})}}):h.jsx("ul",{"data-pyric-document-list-items":!0,children:t.map(N=>{const R=gl(N),M=k.get(R.path);return h.jsxs("li",{"data-pyric-document-entry":!0,"data-pyric-document-id":N.id,"data-pyric-update":M==null?void 0:M.kind,"data-pyric-update-cycle":M==null?void 0:M.cycle,children:[h.jsx("button",{type:"button",onClick:()=>s==null?void 0:s(R),"data-pyric-document-select":!0,"data-pyric-update":M==null?void 0:M.kind,"data-pyric-update-cycle":M==null?void 0:M.cycle,children:c?c(N):N.id}),d?h.jsx("span",{"data-pyric-document-action":!0,children:d(N)}):null]},R.path)})}),r&&o?h.jsx("button",{type:"button",onClick:o,"data-pyric-load-more":!0,disabled:e,children:"Load more"}):null]})}const i8=/^__.*__$/;function Fj(t){if(t.length===0)return"Cannot be empty";if(t.includes("/"))return'Cannot contain "/"';if(t==="."||t==="..")return'Cannot be "." or ".."';if(i8.test(t))return"Cannot match __.*__ (reserved)";if(o8(t)>1500)return"Cannot exceed 1500 bytes"}function a8(t){return Fj(t)}function o8(t){return new TextEncoder().encode(t).length}function l8(t){return Fj(t)}const T_="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function c8(){let t="";for(let e=0;e<20;e++)t+=T_.charAt(Math.floor(Math.random()*T_.length));return t}const u8={ref:Hl,listAll:kg,getMetadata:O6,getBlob:$6,uploadBytes:D6,deleteObject:oj},zj=A.createContext(u8);function tf(){return A.useContext(zj)}function d8({value:t,children:e}){return A.createElement(zj.Provider,{value:t},e)}function om(t){return t.replace(/^\/+|\/+$/g,"")}function Ry(t,e){return t.fullPath<e.fullPath?-1:t.fullPath>e.fullPath?1:0}function lm(t,e){return t.some(n=>n.fullPath===e.fullPath)?t:[...t,e].sort(Ry)}function f8(t,e){const{listAll:n,ref:r}=tf(),s=om(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(Ry),prefixes:[...k.prefixes].sort(Ry),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("/"),I=om(_),N=s===""?"":`${s}/`;if(!I.startsWith(N)||I===s)return;const R=I.slice(N.length),M=R.indexOf("/");c(F=>{if(F.status==="idle")return F;if(M===-1)return k?(p.current.set(I,F.prefixes.some(C=>C.fullPath===I)?null:I),{...F,prefixes:lm(F.prefixes,r(t,I))}):(p.current.set(I,F.items.some(C=>C.fullPath===I)?null:I),{...F,items:lm(F.items,r(t,I))});const D=`${N}${R.slice(0,M)}`;return p.current.set(I,F.prefixes.some(C=>C.fullPath===D)?null:D),{...F,prefixes:lm(F.prefixes,r(t,D))}})},[t,s]),v=A.useCallback(_=>{const k=om(_),I=p.current.get(k);if(p.current.delete(k),I===null)return;const N=I??k;c(R=>({...R,items:R.items.filter(M=>M.fullPath!==N),prefixes:R.prefixes.filter(M=>M.fullPath!==N)}))},[]),w=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:w,error:o.error,refresh:g,insertItem:b,removeItem:v}}function yt(t){return t.split("/").filter(Boolean).join("/")}function h8(t={}){const{path:e,onPathChange:n,defaultPath:r=""}=t,s=e!==void 0,[o,c]=A.useState(()=>yt(r)),d=s?yt(e):o,f=A.useCallback(w=>{const _=yt(w);s||c(_),n==null||n(_)},[s,n]),p=A.useMemo(()=>d===""?[]:d.split("/"),[d]),g=A.useCallback(w=>{const _=yt(w);f(_.includes("/")||d===""?_:`${d}/${_}`)},[d,f]),b=A.useCallback(()=>{p.length!==0&&f(p.slice(0,-1).join("/"))},[p,f]),v=A.useCallback(w=>{f(w<0?"":p.slice(0,w+1).join("/"))},[p,f]);return{path:d,segments:p,setPath:f,enter:g,up:b,navigateToIndex:v}}const D_={status:"idle",blob:void 0,url:void 0,error:void 0};function p8(t,e){const{getBlob:n,getMetadata:r,ref:s}=tf(),o=e==null?null:yt(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(D_),[b,v]=A.useState(0),w=A.useRef(0);A.useEffect(()=>{if(w.current++,g(D_),!c){f({status:"idle",metadata:void 0,error:void 0});return}let N=!1;return f({status:"loading",metadata:void 0,error:void 0}),r(s(t,o)).then(R=>{N||f({status:"success",metadata:R,error:void 0})}).catch(R=>{N||f({status:"error",metadata:void 0,error:R instanceof Error?R:new Error(String(R))})}),()=>{N=!0}},[t,o,b]);const _=p.url;A.useEffect(()=>{if(_!==void 0)return()=>{URL.revokeObjectURL(_)}},[_]);const k=A.useCallback(()=>v(N=>N+1),[]),I=A.useCallback(()=>{if(t==null||o==null||o==="")return;const N=++w.current;g({status:"loading",blob:void 0,url:void 0,error:void 0}),n(s(t,o)).then(R=>{N===w.current&&g({status:"success",blob:R,url:URL.createObjectURL(R),error:void 0})}).catch(R=>{N===w.current&&g({status:"error",blob:void 0,url:void 0,error:R instanceof Error?R:new Error(String(R))})})},[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:I}}function m8(){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 y8(t,e){const n=Hl(t,e);return{storage:t,bucket:n.bucket,fullPath:`${n.fullPath}/`,name:"",parent:n,root:n.root,toString:()=>`${n.toString()}/`}}function g8(t){return{...t,fullPath:`${t.fullPath}/`,name:""}}function b8(t){return{async*start(e){const n=t??{listAll:kg,deleteObject:oj};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(g8(c))}catch{}yield{deletedCount:r,done:!0}}}}function v8(t,e={}){const n=tf(),[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 N,R;const w=++p.current;s(0),f(void 0);const _={deleted:[],failed:[]};if(t==null||v.length===0)return _;c(!0);const k=g.current.impl??b8(n);let I=0;try{for(const M of v){(N=g.current.list)==null||N.removeItem(M.fullPath);try{if(M.kind==="object")await n.deleteObject(n.ref(t,M.fullPath)),I++;else for await(const F of k.start(n.ref(t,M.fullPath))){if(w!==p.current)return _;if(s(I+F.deletedCount),F.done){I+=F.deletedCount;break}}_.deleted.push(M.fullPath),w===p.current&&s(I)}catch(F){const D=F instanceof Error?F:new Error(String(F));_.failed.push({fullPath:M.fullPath,error:D}),(R=g.current.list)==null||R.insertItem(M.kind==="folder"?`${M.fullPath}/`:M.fullPath),w===p.current&&_.failed.length===1&&f(D)}}return _}finally{w===p.current&&c(!1)}},[n,t]),progress:r,isRunning:o,error:d}}const w8=Object.freeze({read:!0,write:!0,delete:!0,upload:!0,reasons:Object.freeze({read:[],write:[]})});function x8(t,e={}){const{paths:n,rules:r,identity:s,writeResource:o}=e,c=t==null?null:t[Wd],[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 R=typeof r=="string"?tj(r):r;f({status:"ready",rules:R,source:"option",error:void 0})}catch(R){f({status:"error",rules:null,source:"none",error:R instanceof Error?R:new Error(String(R))})}return}let N=!1;return f({status:"loading",rules:null,source:"none",error:void 0}),c.servicePromise.then(R=>{N||f({status:"ready",rules:R.rules,source:R.rules?"sandbox":"none",error:void 0})}).catch(R=>{N||f({status:"error",rules:null,source:"none",error:R instanceof Error?R:new Error(String(R))})}),()=>{N=!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,w=o==null?void 0:o.contentType,_=A.useCallback(N=>{if(g==null)return w8;const R=yt(N),M=(c==null?void 0:c.bucket)??"pyric-default",F=R===""?`b/${M}/o`:`b/${M}/o/${R}`,D=U=>rj(g,{request:{auth:p,method:U,path:F,...U==="write"&&v!==void 0?{resource:{size:v,contentType:w}}:{}},resource:null}),C=D("read"),L=D("write");return{read:C.allowed,write:L.allowed,delete:L.allowed,upload:L.allowed,reasons:{read:C.allowed?[]:C.reasons,write:L.allowed?[]:L.reasons}}},[g,c==null?void 0:c.bucket,p,v,w]),k=typeof n=="string"?n:(n??[]).join(`
|
|
1216
|
-
`),I=A.useMemo(()=>{const N=typeof n=="string"?[n]:n??[],R={};for(const M of N)R[yt(M)]=_(M);return R},[k,_]);return{status:b,source:d.source,advisory:!1,identity:p,verdicts:I,verdictFor:_,error:d.error}}function I_(t,e){return t===""?e:e===""?t:`${t}/${e}`}function S8(t){return t instanceof Blob?t.size:t.byteLength}function _8(t){if(t instanceof Blob){const e=t;return{path:e.webkitRelativePath||e.name,data:e}}return t}function E8(t,e={}){const{ref:n,uploadBytes:r}=tf(),s=yt(e.path??""),[o,c]=A.useState([]),d=A.useRef(e);d.current=e;const f=A.useCallback(v=>{c(w=>w.map(_=>_.id===v.id?v:_))},[]),p=A.useCallback(async v=>{var k,I,N;if(t==null)throw new Error("useObjectUpload: storage handle is null");const _=(Array.isArray(v)?v:[v]).map(R=>{const M=_8(R);return{task:{id:crypto.randomUUID(),fullPath:I_(s,yt(M.path)),status:"running",bytesTransferred:0,totalBytes:S8(M.data)},entry:M}});c(R=>[...R,..._.map(M=>M.task)]);for(const{task:R}of _)(k=d.current.list)==null||k.insertItem(R.fullPath),(N=(I=d.current).onProgress)==null||N.call(I,R);return Promise.all(_.map(async({task:R,entry:M})=>{var F,D,C,L,U,H,z;try{const q=await r(n(t,R.fullPath),M.data,M.metadata),x={...R,status:"success",bytesTransferred:R.totalBytes,metadata:q.metadata};return f(x),(D=(F=d.current).onProgress)==null||D.call(F,x),(L=(C=d.current).onComplete)==null||L.call(C,x),x}catch(q){const x={...R,status:"error",error:q instanceof Error?q:new Error(String(q))};return(U=d.current.list)==null||U.removeItem(R.fullPath),f(x),(z=(H=d.current).onError)==null||z.call(H,x),x}}))},[t,s,f,n,r]),g=A.useCallback(async v=>{var _,k;if(t==null)throw new Error("useObjectUpload: storage handle is null");const w=I_(s,yt(v));if(w==="")throw new Error("createFolder: folder name is empty");(_=d.current.list)==null||_.insertItem(`${w}/`);try{await r(y8(t,w),new Blob([]),{contentType:"text/plain"})}catch(I){throw(k=d.current.list)==null||k.removeItem(w),I}},[t,s,r]),b=A.useCallback(()=>{c(v=>v.filter(w=>w.status==="running"))},[]);return{tasks:o,isUploading:o.some(v=>v.status==="running"),upload:p,createFolder:g,clearCompleted:b}}function A8({path:t,onNavigate:e,rootLabel:n="/",separator:r="/",className:s}){const o=yt(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 j8({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:w="60vh"}){const{ref:_,size:k}=ef();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 I=M=>{if(!c)return{denied:!1};const F=c.verdictFor(M.fullPath);return F.read?{denied:!1}:{denied:!0,reason:F.reasons.read.join("; ")}},N=M=>{const F=M.kind==="object"&&M.fullPath===o;return h.jsxs(h.Fragment,{children:[h.jsx("button",{type:"button",onClick:()=>M.kind==="folder"?r==null?void 0:r(M.fullPath):s==null?void 0:s(M.ref),"data-pyric-entry-select":!0,"data-pyric-selected":F?"":void 0,"aria-selected":F||void 0,children:d?d(M):M.name}),f?h.jsx("span",{"data-pyric-storage-action":!0,children:f(M)}):null]})},R=t.length>b;return h.jsx("div",{ref:_,className:g,"data-pyric-ui":"object-browser","data-size":k,"data-pyric-virtualized":R?"":void 0,children:R?h.jsx(Og,{items:t,estimateSize:v,height:w,getItemKey:M=>`${M.kind}:${M.fullPath}`,renderItem:M=>{const F=I(M);return h.jsx("div",{"data-pyric-storage-entry":!0,"data-pyric-entry-kind":M.kind,"data-pyric-entry-path":M.fullPath,"data-pyric-denied":F.denied?"":void 0,"data-pyric-denied-reason":F.reason,children:N(M)})}}):h.jsx("ul",{"data-pyric-object-browser-items":!0,children:t.map(M=>{const F=I(M);return h.jsx("li",{"data-pyric-storage-entry":!0,"data-pyric-entry-kind":M.kind,"data-pyric-entry-path":M.fullPath,"data-pyric-denied":F.denied?"":void 0,"data-pyric-denied-reason":F.reason,children:N(M)},`${M.kind}:${M.fullPath}`)})})})}async function Pj(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 Pj(c,r,n)}}}async function k8(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 Pj(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 C8({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 w=v.dataTransfer;w&&k8(w).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 N8(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 O8(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 M_(t,e){if(!e.has(t))return t;const{stem:n,ext:r}=N8(t),{base:s,counter:o}=O8(n);let c=o===null?1:o+1;for(;;){const d=`${s} (${c})${r}`;if(!e.has(d))return d;c+=1}}function R8(t,e){const n=new Set(e),r=new Map;return t.map(s=>{const o=s.indexOf("/");if(o===-1){const f=M_(s,n);return n.add(f),f}const c=s.slice(0,o);let d=r.get(c);return d===void 0&&(d=M_(c,n),n.add(d),r.set(c,d)),`${d}${s.slice(o)}`})}function L_(t){const e=yt(t);if(e==="")return[];const n=e.split("/");return n.map((r,s)=>n.slice(0,s+1).join("/"))}const Vj=[];function T8(t,e){switch(e.type){case"create":{const n=L_(e.path).filter(r=>!t.includes(r));return n.length===0?t:[...t,...n].sort()}case"materialize":{const n=new Set(L_(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=yt(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:Vj}}function D8(t,e){const n=yt(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 U_(t,e){return t.includes(yt(e))}function I8(t){const e=yt(t);return e===""?"Enter a folder name.":e.split("/").some(r=>r==="."||r==="..")?'Folder names may not be "." or "..".':null}const M8=256*1024;function Ty(t){return(t.contentType??"").split(";")[0].trim().toLowerCase()}const L8={id:"image",match:t=>Ty(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 U8({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 $8={id:"text",match:t=>{const e=Ty(t);return e.startsWith("text/")||e==="application/json"},needsBlob:!0,maxBytes:M8,render:({metadata:t,blob:e})=>e?h.jsx(U8,{blob:e,isJson:Ty(t)==="application/json"}):null},B8=[L8,$8];function q8(t,e){for(const n of[...e??[],...B8])if(n.match(t))return n}const F8=[{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 z8({metadata:t}){return h.jsxs("dl",{"data-pyric-object-metadata":!0,children:[F8.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 P8({storage:t,path:e,previews:n,renderMetadata:r,children:s,className:o}){var N,R;const{ref:c,size:d}=ef(),f=p8(t,e),{metadata:p,blobStatus:g,loadBlob:b}=f,v=p?q8(p,n):void 0,w=(v==null?void 0:v.maxBytes)!==void 0&&p!==void 0&&p.size>v.maxBytes,_=(v==null?void 0:v.needsBlob)===!0&&!w;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:(N=f.error)==null?void 0:N.message});let k,I={};return v===void 0?I={"data-pyric-preview-none":""}:w?I={"data-pyric-preview-too-large":""}:_&&g==="loading"?I={"data-pyric-preview-loading":""}:_&&g==="error"?(I={"data-pyric-preview-error":""},k=(R=f.blobError)==null?void 0:R.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(z8,{metadata:p}),h.jsx("div",{"data-pyric-object-preview":!0,"data-pyric-preview":v==null?void 0:v.id,...I,children:k}),s]})}const Hj=A.createContext(null);function V8(){const t=A.useContext(Hj);if(!t)throw new Error("useToast: missing <ToastProvider> ancestor");return t}function H8({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(w=>w.id!==g))},b),g},[e]),f=A.useMemo(()=>({toast:d,dismiss:c,toasts:s}),[d,c,s]);return h.jsxs(Hj.Provider,{value:f,children:[t,h.jsx(G8,{toasts:s,dismiss:c,className:n,regionLabel:r})]})}function G8({toasts:t,dismiss:e,className:n,regionLabel:r}){const[s,o]=A.useState(!1);return A.useEffect(()=>o(!0),[]),!s||typeof document>"u"?null:Ng.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 K8({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=go(),{toast:w}=V8(),{deleteEntries:_,isRunning:k,progress:I}=v8(t,{impl:n,list:r}),N=s?e.map(D=>({entry:D,verdict:s.verdictFor(D.fullPath)})).filter(D=>!D.verdict.delete):[],R=N.length===0?void 0:`Delete denied for ${N[0].entry.fullPath}${N.length>1?` (+${N.length-1} more)`:""}: ${N[0].verdict.reasons.write.join("; ")}`,M=k||e.length===0||t==null||N.length>0,F=async()=>{if(M||!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(L=>h.jsxs("li",{"data-pyric-entry-kind":L.kind,children:[L.fullPath,L.kind==="folder"?"/":""]},L.fullPath))}),destructive:!0,confirmLabel:d}))return;const C=await _(e);C.failed.length===0?(w({title:`Deleted ${C.deleted.length} ${C.deleted.length===1?"item":"items"}`,kind:"success"}),f==null||f(C)):(w({title:`Delete failed for ${C.failed.length} of ${e.length}`,kind:"error",body:h.jsx("ul",{"data-pyric-delete-selection-failures":!0,children:C.failed.map(L=>h.jsxs("li",{children:[L.fullPath,":"," ",L.error.code??L.error.message]},L.fullPath))})}),p==null||p(C))};return g?h.jsx(h.Fragment,{children:g({onClick:F,isRunning:k,progress:I,disabled:M,deniedReason:R})}):h.jsx("button",{type:"button",onClick:F,className:b,disabled:M,title:R,"data-pyric-ui":"delete-selection","data-pyric-destructive":"","data-pyric-running":k?"":void 0,"data-pyric-denied":R?"":void 0,"data-pyric-denied-reason":R,children:k?`Deleting… (${I})`:d})}function kd(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 Gj(t){const e=t.indexOf("?");return _g(e===-1?t:t.slice(0,e),e===-1?"":t.slice(e))}function Y8(t){const{tab:e,rest:n,query:r}=Gj(t),s=n.join("/");return e==="firestore"?{view:"firestore",path:kd(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 Z8(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 Kj(t){const{tab:e,query:n}=Gj(t),r=Y8(t),s=e==="traffic"?n.inspect??null:null;return{target:r,selectedInspectId:s}}let $_=null,Dy=Kj("");function W8(){const t=PA();return t!==$_&&($_=t,Dy=Kj(t)),Dy}function Q8(){return Dy}function Iu(t){Jn(Z8(t))}function J8(t){Jn({tab:"traffic",query:{inspect:t}})}function nf(){const t=A.useSyncExternalStore(ec,W8,Q8),e=A.useCallback(s=>Iu(s),[]),n=A.useCallback(s=>{switch(s.kind){case"user":Iu({view:"auth",uid:s.uid});break;case"storage":Iu({view:"storage",kind:"object",path:s.objectPath});break;case"document":Iu({view:"firestore",path:kd(s.path)});break}},[]),r=A.useCallback(s=>J8(s),[]);return A.useMemo(()=>({target:t.target,navigate:e,navigateRef:n,selectedInspectId:t.selectedInspectId,navigateInspect:r}),[t,e,n,r])}const X8={narrowBreakpoint:640,mediumBreakpoint:920};function eq(t){switch(t){case"narrow":return 1;case"medium":return 2;case"wide":return 3}}function tq(t,e){const n=eq(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 cm({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 Yj({mode:t,parentPath:e,onCreate:n,onClose:r}){const[s,o]=A.useState(""),[c,d]=A.useState(()=>c8()),[f,p]=A.useState(null),[g,b]=A.useState(null),[v,w]=A.useState(!1),_=A.useRef(null),k=t==="collection"&&s?a8(s):void 0,I=c?l8(c):void 0,R=!(t==="collection"&&(!s||k))&&!!c&&!I&&!v;A.useEffect(()=>{const D=C=>{C.key==="Escape"&&!v&&r()};return document.addEventListener("keydown",D),()=>document.removeEventListener("keydown",D)},[v,r]);const M=async()=>{if(!(!R||!f)){if(!f.isValid){f.touchAll();return}w(!0),b(null);try{await n({collectionId:t==="collection"?s:null,docId:c,data:Nj(f.tree)}),r()}catch(D){b(D instanceof Error?D:new Error(String(D))),w(!1)}}},F=t==="collection"?"Start a collection":"Add a document";return h.jsx("div",{className:"fs-modal-backdrop",onMouseDown:D=>{D.target===D.currentTarget&&!v&&r()},children:h.jsxs("div",{ref:_,className:"fs-modal",role:"dialog","aria-modal":"true","aria-label":F,"data-pyric-ui":"fs-create-modal","data-fs-create-mode":t,children:[h.jsx("h2",{className:"fs-modal__title",children:F}),h.jsx(cm,{label:"Parent path",children:h.jsx("span",{className:"fs-modal__path",children:e})}),t==="collection"?h.jsx(cm,{label:"Collection ID",error:k,children:h.jsx("input",{autoFocus:!0,type:"text",value:s,placeholder:"e.g. users",onChange:D=>o(D.target.value),"data-pyric-field":"collection-id","aria-invalid":k?"true":void 0})}):null,h.jsx(cm,{label:"Document ID",error:c?I:"Cannot be empty",hint:"Auto-generated — edit to set your own.",children:h.jsx("input",{autoFocus:t==="document",type:"text",value:c,onChange:D=>d(D.target.value),"data-pyric-field":"doc-id","aria-invalid":I||!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(R_.Root,{initial:{},onChange:p,children:h.jsx(R_.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:!R,onClick:()=>void M(),children:v?"Saving…":"Save"})]})]})})}function Zj({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 Wj(t){return JSON.stringify(t)}function nq(t,e){const n=new Map,r=(s,o)=>{const c=e(s),d=Wj(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 Qj(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 Wj(n)}function rq(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 sq(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 iq=42;function aq(t,e,n,r=iq){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 oq(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 lq(t){return t.shiftKey===!0}const Jj=["string","number","boolean","null","timestamp","geopoint","reference","bytes","vector"],cq=[...Jj,"map","array"];function uq({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,[]),w=Ij({initial:v}),_=w.replaceData,k=A.useMemo(()=>$j(o),[o]),I=go(),[N,R]=A.useState(()=>new Set),[M,F]=A.useState(null),D=A.useRef(t),C=A.useRef(new Set),L=A.useRef(!1),[U,H]=A.useState(null),z=A.useMemo(()=>nq(b,Xd),[b]),q=Ug({scope:e.path,entries:z,equals:jd,ready:M===null});A.useEffect(()=>{L.current&&(L.current=!1,H(null),n(w.toData()).catch(se=>{H(se instanceof Error?se:new Error(String(se)))}))},[w.tree]),A.useEffect(()=>{!t||t===D.current||M!==null||(D.current=t,C.current.clear(),_(t.data()??{}))},[M,_,t]);const x=A.useCallback(se=>{R(B=>{const ee=new Set(B);return ee.has(se)?ee.delete(se):ee.add(se),ee})},[]),[E,O]=A.useState(null),T=A.useCallback((se,B)=>{if(B==="map"?w.addMapEntry(se,"","string"):w.addArrayEntry(se,"string"),se!==w.tree.rootId){const ee=Qj(w.tree,se);R(ae=>new Set(ae).add(ee))}O(se)},[w]);A.useEffect(()=>{if(!E)return;const se=w.tree.childIds[E]??[],B=se[se.length-1];B&&!M&&(C.current.add(B),F(B),O(null))},[w.tree,E]);const P=A.useCallback(se=>{w.remove(se),C.current.delete(se),L.current=!0,M===se&&F(null)},[w,M]),$=A.useCallback(async(se,B,ee)=>{if(lq(ee)){P(se.id);return}await I({title:`Delete field "${B}"?`,destructive:!0,confirmLabel:"Delete"})&&P(se.id)},[I,P]),K=e.id,W=w.tree.childIds[w.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(Zj,{items:[{label:"Delete document fields",onSelect:()=>{(async()=>await I({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}]})]}),U?h.jsx("p",{className:"fs-doctree__err",children:U.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:()=>T(w.tree.rootId,"map"),children:[h.jsx("span",{"aria-hidden":"true",children:"+"})," Add field"]})}),W.map(se=>h.jsx(Xj,{nodeId:se,depth:0,editor:w,registry:k,expanded:N,onToggle:x,editingId:M,setEditingId:F,newIdsRef:C,onAdd:T,onDelete:$,onCommitNeeded:()=>{L.current=!0},onReferenceClick:c,updates:q},se))]}),f&&p?h.jsx(ek,{firestore:f,documentRef:e,listSubcollections:p,onSubcollectionClick:g}):null]})}function Xj({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:w}){const{tree:_}=n,k=_.nodes[t];if(!k)return null;const{label:I,isArrayChild:N}=sq(_,t),R=k.type==="map"||k.type==="array",M=rq(_,t),F=Qj(_,t),D=w.get(F),C=s.has(F),L=c===t,U=f.current.has(t);return L?h.jsx("li",{className:"fs-doctree__row fs-doctree__row--editing","data-pyric-doctree-depth":e,style:{"--fs-depth":e},children:h.jsx(dq,{node:k,isNew:U,isArrayChild:N,tree:_,editor:n,registry:r,path:M,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":R?"":void 0,style:{"--fs-depth":e},children:[h.jsxs("div",{className:"fs-doctree__line","data-pyric-update":D==null?void 0:D.kind,"data-pyric-update-cycle":D==null?void 0:D.cycle,children:[R?h.jsx("button",{type:"button",className:"fs-doctree__caret","aria-expanded":C,onClick:()=>o(F),children:h.jsx("span",{"aria-hidden":"true",children:C?"▼":"▶"})}):h.jsx("span",{className:"fs-doctree__caret fs-doctree__caret--empty","aria-hidden":"true"}),N?h.jsx("span",{className:"fs-doctree__chip",children:I}):h.jsx("span",{className:"fs-doctree__key",children:I}),R?C?null:h.jsx("span",{className:"fs-doctree__preview",children:aq(_,t,{asVectorView:Xi,vectorPreview:kj})}):h.jsx("span",{className:"fs-doctree__value",children:h.jsx(Oy,{value:k.value,path:M,fieldEditors:r})}),h.jsxs("span",{className:"fs-doctree__hover",children:[h.jsxs("span",{className:"fs-doctree__typenote",children:["(",k.type,")"]}),R?h.jsx("button",{type:"button",className:"fs-doctree__icon",title:"Add field","aria-label":`Add field to ${I||"document"}`,onClick:()=>p(t,k.type==="array"?"array":"map"),children:"+"}):h.jsx("button",{type:"button",className:"fs-doctree__icon",title:"Edit","aria-label":`Edit ${I}`,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 ${I||"field"} (shift-click to skip confirmation)`,onClick:H=>void g(k,I,{shiftKey:H.shiftKey}),children:"🗑"})]})]}),R&&C?h.jsxs("ul",{className:"fs-doctree__children",children:[(_.childIds[t]??[]).map(H=>h.jsx(Xj,{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:w},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 dq({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,w]=A.useState(t.type),[_,k]=A.useState(t.value),[I,N]=A.useState(!1),R=n?void 0:g===""?"Field name is required":oq(r,t,g)?"Field name must be unique":void 0,M=v==="map"||v==="array"?void 0:Rj(v,_),F=!R&&!M,D=()=>{if(!F){N(!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()},C=()=>{e?p():f()},L=o[v],U=L==null?void 0:L.Edit,H=v!=="map"&&v!=="array"&&U?h.jsx(U,{value:_,path:c,error:I?M:void 0,onChange:x=>k(x)}):v==="map"||v==="array"?h.jsxs("span",{className:"fs-doctree__editnote",children:["Saves as an empty ",v," — add its children afterward."]}):null,z=h.jsxs("span",{className:"fs-doctree__editactions",children:[h.jsx("button",{type:"button",className:"fs-doctree__editsave",onClick:D,"aria-label":"Save field",children:"✓"}),h.jsx("button",{type:"button",className:"fs-doctree__editcancel",onClick:C,"aria-label":"Cancel edit",children:"✕"})]}),q=h.jsx("select",{className:"fs-doctree__edittype",value:v,onChange:x=>{const E=x.target.value;w(E),E!=="map"&&E!=="array"&&E!==v&&k(fq(E))},"aria-label":"Field type",children:(e?cq:Jj).map(x=>h.jsx("option",{value:x,children:x},x))});return h.jsxs("div",{className:"fs-doctree__editrow",onKeyDown:x=>{x.key==="Enter"&&!x.target.matches("textarea")?(x.preventDefault(),D()):x.key==="Escape"&&(x.preventDefault(),C())},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:x=>b(x.target.value),onBlur:()=>N(!0),"aria-label":"Field name","aria-invalid":I&&R?"true":void 0}),q]}),h.jsxs("div",{className:"fs-doctree__editline",children:[n?q:null,H,z]}),I&&R?h.jsx("span",{className:"fs-doctree__editerr",children:R}):null]})}function fq(t){switch(t){case"string":return"";case"number":return 0;case"boolean":return!1;default:return null}}function ek({firestore:t,documentRef:e,listSubcollections:n,onSubcollectionClick:r}){const{subcollections:s,isLoading:o}=p5({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 hq(t){return t.split("/").filter(Boolean).length%2===0}function tk(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};hq(s.path)?yield*n(s,o):yield*r(s,o),yield{deletedCount:o.n,done:!0}}}}async function nk(t,e){for await(const n of t.start(e))if(n.done)return}async function rk({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 nk(r,e):await n.deleteDoc(e),!0):!1}function pq(t){const e=t.exists;return typeof e=="function"?e.call(t):e}async function mq(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 yq(t){return{id:t.id,ref:t,data:()=>{},__pyricPhantom:!0}}function q_(t){return t.__pyricPhantom===!0}function gq(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 bq({handles:t}){var F;const{target:e,navigate:n}=nf(),r=t.adminFirestore,s=Dg(),o=A.useMemo(()=>(e==null?void 0:e.view)==="firestore"?e.path:[],[e]),c=A.useCallback(D=>{const C=typeof D=="function"?D(o):D;n({view:"firestore",path:C})},[n,o]),d=(D,C)=>c(L=>[...L.slice(0,D+1),C]),[f,p]=A.useState(null),g=A.useCallback(async({collectionId:D,docId:C,data:L})=>{if(!f||!D)return;const U=f.parentDocPath,H=U?s.collection(s.doc(r,U),D):s.collection(r,D);await mq(s,H,C,L);const z=U?`${U}/${D}`:D;n({view:"firestore",path:kd(`${z}/${C}`)})},[s,r,f,n]),b=[h.jsx(xq,{api:s,firestore:r,collectionIds:t.listRootCollections(),onSelect:D=>c([{kind:"collection",id:D,path:D}]),onStartCollection:()=>p({parentDocPath:null})},"__root__"),...o.map((D,C)=>{var L;return D.kind==="collection"?h.jsx(Sq,{api:s,firestore:r,handles:t,collectionPath:D.path,selectedId:((L=o[C+1])==null?void 0:L.id)??null,onSelect:U=>d(C,{kind:"document",id:U.id,path:U.path}),onCollectionDeleted:()=>c(U=>U.slice(0,C))},D.path):h.jsx(_q,{api:s,firestore:r,handles:t,docPath:D.path,onOpenSubcollection:U=>d(C,{kind:"collection",id:U.id,path:U.path}),onReferenceClick:U=>n({view:"firestore",path:kd(U.path)}),onStartCollection:()=>p({parentDocPath:D.path}),onDeleted:()=>c(U=>U.slice(0,C))},D.path)})],{ref:v,size:w}=ef(X8),{startIndex:_,visibleCount:k,emptySlots:I}=tq(b.length,w),N=b.slice(_,_+k),R=o.length===0?"Select a collection":((F=o[o.length-1])==null?void 0:F.kind)==="collection"?"Select a document":null,M=[...N,...Array.from({length:I},(D,C)=>h.jsx(wq,{hint:C===0?R:null},`__empty_${C}__`))];return A.useEffect(()=>{if(w==="wide")return;const D=v.current;if(!D)return;const C=document.activeElement;if(C&&C!==document.body&&D.contains(C))return;const L=D.querySelector(".fs-columns > .fs-col:last-child");L&&(L.tabIndex=-1,L.focus({preventScroll:!0}))},[o.length,w]),h.jsx(Tg,{children:h.jsxs("div",{ref:v,"data-pyric-ui":"fs-browser","data-fs-depth":o.length,"data-size":w,children:[h.jsx(vq,{path:o,onHome:()=>c([]),onJump:D=>c(C=>C.slice(0,D+1))}),h.jsx("div",{className:"fs-columns",children:M}),f?h.jsx(Yj,{mode:"collection",parentPath:f.parentDocPath?`/${f.parentDocPath}`:"/",onCreate:g,onClose:()=>p(null)}):null]})})}function vq({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 wq({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 xq({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(r8,{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 Sq({api:t,firestore:e,handles:n,collectionPath:r,selectedId:s,onSelect:o,onCollectionDeleted:c}){const d=A.useMemo(()=>gq(t,e,r),[t,e,r]),{documents:f,isLoading:p,error:g,subscriptionGeneration:b,hasMore:v,loadMore:w,createDocument:_}=h5({collection:d,mode:"live"}),[k,I]=A.useState([]);A.useEffect(()=>{let q=!1;return Promise.resolve(n.listDocuments(r)).then(x=>{q||I(x.filter(E=>E.phantom).map(E=>E.path.split("/").pop()??""))}).catch(()=>{q||I([])}),()=>{q=!0}},[n,r,f]);const N=A.useMemo(()=>{const q=new Set(f.map(x=>x.id));return[...f,...k.filter(x=>x.length>0&&!q.has(x)).map(x=>yq(t.doc(e,`${r}/${x}`)))]},[f,k,t,e,r]),R=r.split("/").pop()??r,[M,F]=A.useState(null),[D,C]=A.useState(!1),L=go(),U=A.useMemo(()=>tk(t,n),[t,n]),H=A.useCallback(async q=>{F(null);try{await rk({confirm:L,ref:q,api:t,recursiveImpl:U})}catch(x){F(x instanceof Error?x:new Error(String(x)))}},[t,L,U]),z=A.useCallback(async()=>{if(await L({title:`Delete collection "${R}"?`,body:"This deletes every document in it (and their subcollections).",destructive:!0,confirmLabel:"Delete collection"})){F(null);try{await nk(U,d),c()}catch(x){F(x instanceof Error?x:new Error(String(x)))}}},[L,U,d,R,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:R}),h.jsx("span",{className:"fs-phead-actions",children:h.jsx("button",{type:"button",className:"fs-add",onClick:()=>C(!0),children:"+ New"})}),h.jsx(Zj,{items:[{label:"Delete collection",onSelect:()=>void z(),destructive:!0}]})]}),D?h.jsx(Yj,{mode:"document",parentPath:`/${r}`,onCreate:async({docId:q,data:x})=>{const E=await _(q,x,{onExisting:"fail"});o(E)},onClose:()=>C(!1)}):null,h.jsx(s8,{documents:N,isLoading:p,error:g,updateScope:`${r}:${b}`,hasMore:v,onLoadMore:w,onSelect:o,renderLabel:q=>{const x=q.ref;return h.jsx("span",{"data-pyric-selected":s===x.id?"":void 0,style:{display:"contents"},children:q_(q)?h.jsxs(h.Fragment,{children:[h.jsx("span",{className:"fs-doc-phantom",children:q.id}),h.jsx("span",{className:"fs-sub fs-doc-phantom-hint",children:"missing"})]}):q.id})},renderRowAction:q=>{if(q_(q))return null;const x=q.ref;return h.jsx("button",{type:"button",className:"fs-doc-del",title:"Delete document","aria-label":`Delete ${x.id}`,onClick:E=>{E.stopPropagation(),H(x)},children:"×"})},emptyState:h.jsx("p",{className:"fs-empty",children:"No documents."})}),M?h.jsx("p",{className:"fs-empty fs-doc-del-err",children:M.message}):null]})}function _q({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}=t5(f),v=A.useCallback(async(F,D)=>(await n.listSubcollections(D.path)).map(L=>t.collection(D,L)),[n,t]),w=go(),_=A.useMemo(()=>tk(t,n),[t,n]),[k,I]=A.useState(null),N=A.useCallback(async()=>{I(null);try{await rk({confirm:w,ref:f,api:t,recursiveImpl:_})&&d()}catch(F){I(F instanceof Error?F:new Error(String(F)))}},[t,w,_,f,d]),R=A.useCallback(async()=>{await t.setDoc(f,{})},[t,f]),M=p!=null&&pq(p);return h.jsxs("section",{"data-pyric-ui":"fs-document",className:"fs-pane fs-col doc",children:[M?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&&M?h.jsx(uq,{snapshot:p,documentRef:f,firestore:e,listSubcollections:v,onReferenceClick:o,onSubcollectionClick:s,onStartCollection:c,onDeleteDocument:()=>void N(),onDeleteDocumentFields:R,onCommit:async F=>{await t.setDoc(f,F)}},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(ek,{firestore:e,documentRef:f,listSubcollections:v,onSubcollectionClick:s})]}),k?h.jsx("p",{className:"fs-empty fs-doc-del-err",children:k.message}):null]})}const Eq="block w-full text-sm text-soft-white";function Aq({auth:t,focusUid:e}){const{users:n,totalCount:r,isLoading:s,error:o,filter:c,setFilter:d,updateUser:f}=Rg(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(xj,{users:n,isLoading:s,error:o,filter:c,onSelect:v=>g(v.uid),className:Eq,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(jq,{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 jq({user:t,onSave:e}){const n=wj({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 F_(t){const e=yt(t),n=e.lastIndexOf("/");return n===-1?"":e.slice(0,n)}function z_(t,e){return t===""?e:e===""?t:`${t}/${e}`}function P_(t){const e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}const kq=[{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 Cq(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"}),kq.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 Nq(){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 Oq(){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 Rq(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(Nq,{}):h.jsx(Oq,{})}),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 Tq({storage:t,focusTarget:e}){var q;const n=nf(),r=e.kind==="object"?yt(e.path):null,s=e.kind==="prefix"?yt(e.path):r?F_(r):"",o=A.useCallback(x=>{const E=yt(x);n.navigate(E?{view:"storage",kind:"prefix",path:E}:{view:"storage",kind:"root"})},[n.navigate]),c=h8({path:s,onPathChange:o}),d=x=>{n.navigate({view:"storage",kind:"object",path:yt(x)})},f=f8(t,c.path),p=m8(),g=x8(t),[b,v]=A.useReducer(T8,Vj),w=E8(t,{path:c.path,list:f,onComplete:x=>v({type:"materialize",path:F_(x.fullPath)})});A.useEffect(()=>{if(f.status==="success")for(const x of f.entries)x.kind==="folder"&&U_(b,x.fullPath)&&v({type:"materialize",path:x.fullPath})},[f.status,f.entries,b]);const[_,k]=A.useState(!1),[I,N]=A.useState(""),[R,M]=A.useState(null),F=A.useRef(null),D=A.useMemo(()=>{const x=D8(b,c.path).filter(T=>!f.entries.some(P=>P.kind==="folder"&&P.name===T));if(x.length===0)return f.entries;const E=x.map(T=>{const P=z_(c.path,T);return{kind:"folder",name:T,fullPath:P,ref:{fullPath:P,name:T}}});return[...[...f.entries.filter(T=>T.kind==="folder"),...E].sort((T,P)=>T.name<P.name?-1:T.name>P.name?1:0),...f.entries.filter(T=>T.kind==="object")]},[f.entries,b,c.path]),C=D.length>0&&D.every(x=>p.isSelected(x.fullPath)),L=x=>{const E=new Set(D.map(T=>T.name)),O=R8(x.map(T=>T.relativePath),E);w.upload(x.map((T,P)=>({path:O[P],data:T.file})))},U=x=>{x.preventDefault();const E=I8(I);if(E){M(E);return}const O=z_(c.path,yt(I));v({type:"create",path:O}),c.setPath(O),N(""),M(null),k(!1)};A.useEffect(()=>p.clear(),[c.path,p.clear]);const H=w.tasks.filter(x=>x.status==="error"),z=g.verdictFor(c.path);return h.jsx(H8,{children:h.jsx(Tg,{children:h.jsxs("div",{className:"storage",children:[h.jsxs("div",{className:"storage__sub",children:[h.jsx(A8,{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(K8,{storage:t,entries:p.selected,list:f,gate:g,className:"studio-selection-delete",onDeleted:x=>{for(const E of p.selected)E.kind==="folder"&&x.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:x=>{const E=new Set(x.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(x=>!x),M(null)},children:"New folder"}),h.jsx("button",{type:"button",className:"storage__action storage__action--upload",onClick:()=>{var x;return(x=F.current)==null?void 0:x.click()},children:"Upload files"}),h.jsx("input",{ref:F,type:"file",multiple:!0,hidden:!0,onChange:x=>{const E=Array.from(x.currentTarget.files??[]);E.length>0&&L(E.map(O=>({file:O,relativePath:O.name}))),x.currentTarget.value=""}})]})})]}),_?h.jsxs("form",{className:"storage__newfolder",onSubmit:U,children:[h.jsx("input",{autoFocus:!0,className:"storage__newfolder-input",placeholder:"folder or nested/path/of/folders","aria-label":"New folder name",value:I,onChange:x=>{N(x.currentTarget.value),M(null)},onKeyDown:x=>{x.key==="Escape"&&k(!1)}}),h.jsx("button",{type:"submit",className:"storage__newfolder-btn",children:"Create"}),R?h.jsx("span",{className:"storage__newfolder-err",role:"alert",children:R}):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: ${P_(H[0].fullPath)} — ${((q=H[0].error)==null?void 0:q.message)??"error"}`:`${H.length} uploads failed: ${H.map(x=>P_(x.fullPath)).join(", ")}`,h.jsx("button",{type:"button",className:"storage__upload-err-dismiss",onClick:w.clearCompleted,children:"Dismiss"})]}):null,h.jsxs("div",{className:"storage__body","data-storage-level":r?"inspector":"browser",children:[h.jsxs(C8,{className:"storage__browser",onFiles:L,disabled:!z.upload,disabledReason:z.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:C,onChange:x=>x.currentTarget.checked?p.selectAll(D):p.clear()})}),h.jsx("span",{children:"name"}),h.jsx("span",{children:"type"}),h.jsx("span",{children:"size"}),h.jsx("span",{children:"updated"})]}),h.jsx(j8,{entries:D,status:f.status,error:f.error,gate:g,selectedPath:r??void 0,renderEntry:Rq,renderRowAction:x=>h.jsx("label",{className:"storage__select-row",title:`Select ${x.name}`,children:h.jsx("input",{type:"checkbox","aria-label":`Select ${x.name}`,checked:p.isSelected(x.fullPath),onChange:()=>p.toggle(x)})}),onNavigate:c.enter,onSelect:x=>d(x.fullPath),emptyState:h.jsx("p",{className:"storage__empty",children:U_(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(P8,{storage:t,path:r,renderMetadata:Cq})]}):h.jsx("p",{className:"storage__inspector-hint",children:"Select an object to inspect its preview and metadata."})})]})]})})})}function Dq({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 sk({view:t}){const{target:e}=nf(),n=ri(),r=n.status==="ready"?n.handles.auth:null;return h.jsx("div",{"data-pyric-ui":"data-feature",children:n.status!=="ready"||!r?h.jsx(Dq,{view:t}):n.authApi?h.jsx(yj,{value:n.authApi,children:h.jsx(V_,{view:t,handles:n.handles,auth:r,target:e,firestoreApi:n.firestoreApi,storageApi:n.storageApi})}):h.jsx(V_,{view:t,handles:n.handles,auth:r,target:e,firestoreApi:n.firestoreApi,storageApi:n.storageApi})})}function V_({view:t,handles:e,auth:n,target:r,firestoreApi:s,storageApi:o}){const{users:c}=Rg(n),d=A.useMemo(()=>new Set(c.map(f=>f.uid)),[c]);switch(t){case"firestore":{const f=h.jsx(bq,{handles:e,knownUids:d});return s?h.jsx(e5,{value:s,children:f}):f}case"auth":return h.jsx(Aq,{auth:n,focusUid:(r==null?void 0:r.view)==="auth"?r.uid:null});case"storage":{const f=h.jsx(Tq,{storage:e.storage,focusTarget:(r==null?void 0:r.view)==="storage"?r:{kind:"root"}});return o?h.jsx(d8,{value:o,children:f}):f}}}function Iq(){return h.jsx(sk,{view:"firestore"})}function Mq(){return h.jsx(sk,{view:"storage"})}function Lq(t,e){const n=new Set(e.map(r=>r.uid));return new Set([...t].filter(r=>n.has(r)))}async function Uq(t,e){const n=[];for(const r of t)try{await e(r.uid)}catch{n.push(r.uid)}return n}function $q(t){const[e,n]=A.useState(()=>new Set);A.useEffect(()=>{n(s=>{const o=Lq(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 Bq({users:t,filter:e,onDelete:n,onComplete:r}){const s=go(),[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 Uq(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 ik(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 ak(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 qq(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 Fq({auth:t}={}){const e=cs(),n=ri(),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(Gq,{status:e.status})});const o=h.jsx(Tg,{children:h.jsx(zq,{auth:r})});return s?h.jsx(yj,{value:s,children:o}):o}function zq({auth:t}){var N;const{users:e,totalCount:n,isLoading:r,error:s,filter:o,setFilter:c,createUser:d,updateUser:f,deleteUser:p}=Rg(t),g=nf(),b=((N=g.target)==null?void 0:N.view)==="auth"?g.target.uid:null,v=R=>g.navigate({view:"auth",uid:R}),w=A.useMemo(()=>e.find(R=>R.uid===b)??null,[e,b]),[_,k]=A.useState(!1),I=$q(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:R=>c(R.target.value),placeholder:"filter users…","aria-label":"Filter users"}),h.jsx("div",{className:"auth-sub__right",children:I.selectedUsers.length>0?h.jsxs(h.Fragment,{children:[h.jsxs("span",{className:"studio-selection-count",children:[I.selectedUsers.length," selected"]}),h.jsx(Bq,{users:I.selectedUsers,filter:o,onDelete:R=>Promise.resolve(p(R)),onComplete:R=>{I.replace(R),b&&!R.includes(b)&&v(null)}}),h.jsx("button",{type:"button",className:"auth-sub__clear",onClick:I.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":w||_?"detail":"list",children:[h.jsx("div",{className:"auth-list",children:h.jsx(xj,{users:e,isLoading:r,error:s,filter:o,onSelect:R=>{k(!1),v(R.uid)},renderIdentifier:qq,formatCreatedAt:ak,formatLastLoginAt:ik,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:I.allVisibleSelected,onChange:R=>I.selectAll(R.currentTarget.checked)})}),renderSelection:R=>h.jsx("label",{className:"auth-select",title:`Select ${R.uid}`,children:h.jsx("input",{type:"checkbox","aria-label":`Select ${R.uid}`,checked:I.isSelected(R.uid),onChange:()=>I.toggle(R.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(Pq,{onCancel:()=>k(!1),onCreate:async R=>{const M=await Promise.resolve(d(R));k(!1),v(M.uid)}}):w?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(Hq,{user:w,onSave:R=>{R.mode==="edit"&&f(R.uid,R.request)},onProvidersChange:async R=>{await Promise.resolve(f(w.uid,{providerUserInfo:R}))},onDelete:()=>{p(w.uid),v(null)}},w.uid)]}):h.jsx("div",{className:"auth-detail__empty",children:h.jsx("p",{className:"auth-zero",children:"Select a user to view and edit."})})})]})]})}function Pq({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(Sj,{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 H_=[...YA];function Vq({user:t,onChange:e}){const[n,r]=A.useState(null),[s,o]=A.useState(""),c=t.providerUserInfo.map(w=>w.providerId),d=c.includes("password"),f=c.filter(w=>w!=="password"),p=f.filter(w=>!H_.includes(w)),g=w=>{r(null),e(w.map(_=>({providerId:_}))).catch(_=>{r(_ instanceof Error?_:new Error(String(_)))})},b=(w,_)=>{g(_?[...f,w]:f.filter(k=>k!==w))},v=()=>{const w=s.trim();w&&(o(""),!f.includes(w)&&g([...f,w]))};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:[...H_,...p].map(w=>h.jsxs("label",{className:"auth-provider-row","data-pyric-provider-id":w,children:[h.jsx("input",{type:"checkbox",checked:f.includes(w),onChange:_=>b(w,_.target.checked)}),h.jsx("span",{className:"auth-provider-row__label",children:Ad(w)}),h.jsx("span",{className:"auth-provider-row__id",children:w})]},w))}),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:w=>o(w.target.value),onKeyDown:w=>{w.key==="Enter"&&(w.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 Hq({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=ak(t.createdAt),g=ik(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(Vq,{user:t,onChange:n}),h.jsxs(Sj,{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(QB,{user:t,onDelete:r,className:"auth-del"})})]})}function Gq({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 Kq(t){return t.operationContext.source.kind==="studio"}function Yq(t,e){return e?t.filter(n=>!Kq(n)):[...t]}const Zq=["all","allow","deny","bypassed"];function rf(t){return t.rulesDisposition.kind==="bypassed"?"bypassed":t.rulesDisposition.kind==="evaluated"?t.rulesDisposition.verdict:null}function Wq(t,e){return e==="all"?[...t]:t.filter(n=>rf(n)===e)}function um(t){return t.rulesDisposition.kind==="evaluated"}function G_(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 Iy="inspect";function ok(t){const e=t[Iy];return e||null}function lk(t,e){const{[Iy]:n,...r}=t;return e?{...r,[Iy]:e}:r}function Qq(t,e){return lk(t,ok(t)===e?null:e)}function Jq(t){const e=Yu(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 Xq(t,e,n,r){const s=Jq(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=zE(t,n);try{const c=await ck(o.sandbox,e),d=c.outcome==="allow"?RI(o,r):[];return{result:c,diff:d,lint:s}}finally{PE(o)}}async function ck(t,e){var s;const n=Vd(t.withAuth(e.auth)),r=eF(e.resourceData);try{switch(e.method){case"get":await vg(ur(n,e.path));break;case"list":case"listen":await zl(Vl(Ui(n,e.path)));break;case"create":case"set":await Pl(ur(n,e.path),r);break;case"update":await ay(ur(n,e.path),r);break;case"delete":await bd(ur(n,e.path));break;default:await wg(Ui(n,tF(e.path)),r)}return{outcome:"allow"}}catch(o){if(o instanceof nt&&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 nt?o.code:"unknown",message:o instanceof Error?o.message:String(o)}}}function eF(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:{}}function tF(t){const e=t.lastIndexOf("/");return e<0?t:t.slice(0,e)}const nF=A.lazy(()=>p1(()=>import("./RulesCodeEditor-CxVYcZXw.js"),[]));function uk(t){return h.jsx(A.Suspense,{fallback:h.jsx(rF,{value:t.value,minHeightRem:t.minHeightRem}),children:h.jsx(nF,{...t})})}function rF({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 dk({denial:t,editedRules:e,rulesSource:n,onEditedRulesChange:r,onRerunAsUser:s,onRerunAgainstRules:o}){const c=n4(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(Ja,{kind:"allow",className:"rounded bg-primary/15 px-2 py-0.5 text-xs font-semibold uppercase text-primary",children:"allowed"}):h.jsx(Ja,{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(sF,{denial:t,exp:c,rulesSource:n}),h.jsx(aF,{denial:t})]}),h.jsx(lF,{denial:t}),c.noEvaluation?null:h.jsx(fF,{denial:t,editedRules:e,onEditedRulesChange:r,onRerunAsUser:s,onRerunAgainstRules:o})]})}function sF({denial:t,exp:e,rulesSource:n}){return e.engine==="rtdb"?h.jsx(uF,{denial:t,exp:e}):e.engine==="storage"?h.jsx(dF,{exp:e}):h.jsx(iF,{denial:t,exp:e,rulesSource:n})}function iF({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(Hs,{label:e.implicitDeny||!e.ruleNode?"matched rule":`matched rule — ${e.ruleNode}${r?` · line ${r}`:""}`,children:o?h.jsx(uk,{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(`
|
|
1217
|
-
`)||"(no trace)"})})}function
|
|
1218
|
-
`)||"(no trace)"})]})}function Hs({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 fF({denial:t,editedRules:e,onEditedRulesChange:n,onRerunAsUser:r,onRerunAgainstRules:s}){var _,k,I;const[o,c]=A.useState(null),[d,f]=A.useState(null),p=Y6(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(N){c({outcome:"error",code:"unknown",message:String(N)})}}}async function w(){if(s){f("pending");try{f(await s(t,e??""))}catch(N){f({result:{outcome:"error",code:"unknown",message:String(N)},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:[a4(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(K_,{support:p.impersonate,haveCallback:!!r}),o&&o!=="pending"?h.jsx(Y_,{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:w,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(uk,{value:e??"",onChange:n,markLine:(I=t.evaluatedRule)==null?void 0:I.line,markKind:t.result==="allow"?"allow":"deny",minHeightRem:14,ariaLabel:"Edited firestore.rules to test the op against"}):null,h.jsx(K_,{support:p.editedRuleset,haveCallback:!!s}),d&&d!=="pending"?h.jsxs(h.Fragment,{children:[d.lint.findings.length>0||!d.lint.parseable?h.jsx(hF,{lint:d.lint}):null,h.jsx(Y_,{result:d.result}),d.diff.length>0?h.jsx(mF,{diff:d.diff}):null]}):null]})]})}function K_({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 hF({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 Y_({result:t}){return t.outcome==="allow"?h.jsxs("p",{className:"flex items-center gap-2 text-xs",children:[h.jsx(Ja,{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(Ja,{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(Ja,{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 pF(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=pF(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(oo(r.before))}),c?null:h.jsxs("span",{className:"ml-2 text-soft-white",children:["→ ",JSON.stringify(oo(r.after))]})]},`${r.path}-${n}`)})]})}function Z_({eventId:t,onClose:e}){const n=m4(),r=w4(),s=E4(),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 w=zE(v,s);try{return await ck(w.sandbox,b)}finally{PE(w)}},g=async(b,v)=>{const w=await r();return w?Xq(w,b,v,w):{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(dk,{denial:o,editedRules:f,rulesSource:s,onEditedRulesChange:d,onRerunAsUser:p,onRerunAgainstRules:g})]})}const yF=new Intl.NumberFormat,gF={reads:"read operations",writes:"writes",deletes:"deletes"},bF={allows:"allowed requests",denies:"denied requests"};function W_(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 Q_(t){return t&&`${t[0].toUpperCase()}${t.slice(1)}`}function mk(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=`${yF.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} ${W_(p)}.`:`${Q_(W_(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:`${Q_(c(d))} accounted for ${f}% of ${e.subject} in this window.`}}function vF(t){return mk(t,{labels:gF,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 wF(t){return mk(t,{labels:bF,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 xF=new Intl.NumberFormat,SF=new Intl.DateTimeFormat(void 0,{hour:"numeric",minute:"2-digit"});function J_(t){return xF.format(t)}function bl(t){return SF.format(t)}function _F(t){return rf(t)==="bypassed"}function EF(t){return t.every(e=>e.total===0)}function yk({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(w=>{const _=new Set(w);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(jB,{series:n,visible:p,onToggle:b,formatValue:J_,className:`traffic__metric-cards traffic__metric-cards--journal traffic__metric-cards--${n.length}`}),EF(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:[bl(s.start),"–",bl(s.end)]})]}),h.jsx(NB,{points:r,series:n,visible:p,omitZeroSeries:!0,formatValue:J_,formatTime:bl,className:"traffic__chart traffic__chart--journal"}),h.jsxs("div",{className:"traffic__metric-axis","aria-hidden":"true",children:[h.jsx("span",{children:bl(s.start)}),h.jsx("span",{children:bl(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 AF({events:t,window:e}){const n=A.useMemo(()=>t.filter(o=>(o.service??"firestore")==="firestore"),[t]),r=aB({events:n,window:e,isAdmin:_F}),s=A.useMemo(()=>vF(r.series),[r.series]);return h.jsx("div",{className:"traffic__metrics","data-pyric-ui":"traffic-billable-view",children:h.jsx(yk,{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 jF({events:t,window:e}){const n=A.useMemo(()=>t.filter(c=>c.rulesDisposition.kind==="evaluated"),[t]),r=oB({events:n,window:e}),s=A.useMemo(()=>r.series.filter(c=>c.key==="allows"||c.key==="denies"),[r.series]),o=A.useMemo(()=>wF(s),[s]);return h.jsx("div",{className:"traffic__metrics","data-pyric-ui":"traffic-rules-view",children:h.jsx(yk,{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 CF(t){return t==="billable"?"billable":t==="rules"||t==="subscriptions"?"rules":"timeline"}function NF(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 OF(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:NF(n.length,r)}}function RF(t,e){return(t==null?void 0:t.start)===e.start&&t.end===e.end?null:e}function TF(){const{tab:t,query:e}=Rr();return t!=="traffic"?"timeline":CF(e.view)}function DF(){const t=A.useSyncExternalStore(ec,TF,()=>"timeline"),e=A.useCallback(n=>{const r={...Rr().query,view:n==="timeline"?void 0:n};r.view===void 0&&delete r.view,Jn({tab:"traffic",query:r})},[]);return[t,e]}function IF(){const t=A.useSyncExternalStore(ec,()=>Rr().query.hide==="studio",()=>!1),e=A.useCallback(()=>{const n={...Rr().query};n.hide==="studio"?delete n.hide:n.hide="studio",Jn({tab:"traffic",query:n})},[]);return[t,e]}function MF(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 X_(t){return`${Kl(t.start)}–${Kl(t.end)}`}function LF({event:t}){const e=rf(t);return e?h.jsx("span",{className:"traffic__verdict","data-verdict":e,children:e}):null}function UF(){return A.useSyncExternalStore(ec,()=>ok(Rr().query),()=>null)}const dm=100;function $F(){const t=p4(),[e,n]=DF(),[r,s]=IF(),o=A.useMemo(()=>Yq(t,r),[t,r]),c=t.length-o.length,[d,f]=A.useState("all"),[p,g]=A.useState(null),b=UF(),[v,w]=A.useState(dm),_=E=>{Jn({tab:"traffic",query:Qq(Rr().query,E)})},k=()=>{Jn({tab:"traffic",query:lk(Rr().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 I=A.useMemo(()=>{const E=Date.now();if(o.length===0)return{start:E-15*6e4,end:E};let O=1/0;for(const T of o)T.at<O&&(O=T.at);return{start:Math.min(O,E-6e4),end:E+1e3}},[o]),N=I.end,R=A.useMemo(()=>p?OF(o,p):null,[o,p]),M=(R==null?void 0:R.events)??o,F=A.useMemo(()=>Wq(M,d).sort((E,O)=>O.at-E.at),[M,d]),{items:D}=G4({events:F}),C=D.slice(0,v),L=D.length-C.length,U=o.length>=_d,H=o.filter(E=>E.result==="deny").length,z=E=>h.jsx(LF,{event:E}),q=E=>{if(um(E)){_(E.id);return}const O=G_(E);O&&Jn(O)},x=b!=null&&C.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(AF,{events:o,window:I}):e==="rules"?h.jsx(jF,{events:o,window:I}):h.jsxs(h.Fragment,{children:[h.jsx(_B,{events:o,window:I,brush:p??void 0,onBrush:E=>{g(O=>RF(O,E)),b&&k()},liveAt:I.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",U?` (showing latest ${_d})`:""]}),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:MF(E.start,N)}),h.jsx("span",{children:"now"})]}),renderBucketSummary:E=>h.jsxs("div",{className:"traffic__bucket-summary",children:[h.jsx("span",{children:X_(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."})}),R?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:X_(R.window)}),h.jsx("p",{children:R.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"}),Zq.map(E=>h.jsx("button",{type:"button",className:"traffic__filter","aria-pressed":d===E,onClick:()=>f(E),children:E},E))]}),b&&!x?h.jsx(Z_,{eventId:b,onClose:k},b):null,D.length===0?h.jsx("p",{className:"traffic__empty",children:R?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":R?"":void 0,children:[h.jsx("ul",{"data-pyric-traffic-log-items":"",children:C.map(E=>E.type==="group"?h.jsx("li",{"data-pyric-traffic-group-entry":"",children:h.jsx(xB,{group:E,onSelect:O=>{const T=O;if(um(T)){_(T.id);return}const P=G_(T);P&&Jn(P)},renderClassification:O=>z(O),formatTime:Kl})},E.key):h.jsxs("li",{"data-pyric-traffic-entry":"","data-pyric-traffic-id":E.event.id,"data-verdict":rf(E.event)??void 0,children:[h.jsx(hj,{event:E.event,selected:E.event.id===b,onSelect:O=>q(O),renderClassification:O=>z(O),formatTime:Kl}),E.event.id===b&&um(E.event)?h.jsx(Z_,{eventId:b,onClose:k},b):null]},E.event.id))}),L>0?h.jsxs("button",{type:"button",className:"traffic__show-more",onClick:()=>w(E=>E+dm),children:["Show ",Math.min(L,dm)," more (",L," hidden)"]}):null]})]})]})}const e1=["amber","teal","coral","slate","olive","plum","rust","indigo","mint","sand","ash","jade"],t1=["fox","owl","lynx","crane","otter","wren","ibex","hare","newt","moth","seal","vole"];function $g(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`${e1[e%e1.length]}-${t1[(e>>>4)%t1.length]}`}function BF(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 qF(t){return t?{tab:"firestore",rest:t.split("/").filter(Boolean)}:null}function FF(t){var s;const{provenance:e,identity:n}=BF(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:qF(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 zF(t,e=20){const n=[];for(let r=t.length-1;r>=0&&n.length<e;r--){const s=FF(t[r]);s&&n.push(s)}return n}const PF=20;function VF(t){Jn(t)}function lo({target:t,className:e,children:n,title:r}){return h.jsx("a",{className:e,href:Gd(t),title:r,onClick:s=>{s.metaKey||s.ctrlKey||s.shiftKey||s.altKey||(s.preventDefault(),VF(t))},children:n})}function HF(){const t=cs(),e=Qd(),n=Cg();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(lo,{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(lo,{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"}),$g(n)]},"instance")),h.jsx("div",{className:"studio-home__status","aria-label":"Sandbox status",children:s})}function GF(t){return new Date(t).toLocaleTimeString(void 0,{hour12:!1})}function KF(){const t=sc(),e=A.useMemo(()=>zF(t,PF),[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(lo,{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:GF(n.at)})]});return h.jsx("li",{children:n.target?h.jsx(lo,{className:"studio-home__feed-row",target:n.target,children:r}):h.jsx("span",{className:"studio-home__feed-row",children:r})},n.id)})})})]})}const YF=["firestore","auth","rtdb","storage","traffic"];function ZF(){const t=ri(),e=sc(),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:YF.map(r=>{const s=Pi.find(o=>o.id===r);return s?h.jsxs(lo,{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 WF(){const t=Qd(),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(lo,{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 QF(){const t=ri(),e=sc(),n=cs(),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(dj,{exposeFocus:m3}),h.jsx(HF,{}),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(WF,{}):h.jsxs(h.Fragment,{children:[h.jsx(KF,{}),h.jsx(ZF,{})]})})]})}function Pt(t){const e=t.split("/").filter(Boolean);return e.length===0?"/":`/${e.join("/")}`}function Hi(t){return Pt(t).split("/").filter(Boolean)}function My(t,e){return Pt([...Hi(t),...e.split("/").filter(Boolean)].join("/"))}function gk(t,e){const n=Hi(t),r=Hi(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 bk(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=bk(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 JF(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 Bg(t){return t===null||typeof t!="object"?!1:Object.keys(t).length>0}function vk(t){return t===null||typeof t!="object"?[]:Object.entries(t).sort(([e],[n])=>e.localeCompare(n,void 0,{numeric:!0}))}function wk(t,e){let n=t??null;for(const r of Hi(e)){if(n===null||typeof n!="object")return null;n=n[r]??null}return n}function XF(t){return t==null?"null":Array.isArray(t)?"array":typeof t}function Ly(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)=>Ly(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&&Ly(n[c],r[c]))}function ez(t,e){const n=new Map,r=(s,o)=>{if(!Bg(s)){n.set(o,["leaf",s??null]);return}const c=vk(s);n.set(o,["parent",c.map(([d])=>d)]);for(const[d,f]of c)r(f,My(o,d))};return r(t,Pt(e)),n}function tz(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 nz(t){const e=Hi(t);return e.map((n,r)=>({label:n,path:`/${e.slice(0,r+1).join("/")}`}))}const rz=["string","number","boolean","json"];function n1(t){switch(typeof t){case"string":return"string";case"number":return"number";case"boolean":return"boolean";default:return"json"}}function sz(t,e){return e==="json"?JSON.stringify(t??null):t==null?"":String(t)}function iz(t){if(t.trim().length===0)return"Enter a key.";const e=t.match(/[.$#[\]/]/);return e?`Keys can't contain "${e[0]}".`:null}function az(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 xk(t){return{path:Pt(t),status:"loading",value:null,error:null,expanded:{},pages:{}}}function Sk(t,e){const n=gk(t.path,e);return n===null?null:wk(t.value,n)}function oz(t,e){const n=Pt(e);return n===t.path||t.expanded[n]===!0}function lz(t,e,n){const r=vk(Sk(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 r1(t,e){const n={};let r=!1;for(const[s,o]of Object.entries(t)){const c=gk(e.path,s);c!==null&&Bg(wk(e.value,c))?n[s]=o:r=!0}return r?n:t}function _k(t,e){switch(e.type){case"navigate":{const n=Pt(e.path);return n===t.path?t:xk(n)}case"value":{if(Pt(e.path)!==t.path)return t;const n={...t,status:"live",value:bk(e.value),error:null};return n.expanded=r1(t.expanded,n),n.pages=r1(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 _k(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 cz=50;function uz(t,e,n={}){const r=n.pageSize??cz,s=Pt(e),[o,c]=A.useReducer(_k,s,xk),d=A.useMemo(()=>ez(o.value,o.path),[o.path,o.value]),f=Ug({scope:o.path,entries:d,equals:Ly,ready:o.status==="live"});o.path!==s&&c({type:"navigate",path:s}),A.useEffect(()=>{let k=!1;const I=t.subscribeValue(s,N=>{k||c({type:"value",path:s,value:N})},N=>{k||c({type:"error",path:s,message:N instanceof Error?N.message:String(N)})});return()=>{k=!0,I()}},[t,s]);const p=A.useCallback(k=>Sk(o,k),[o]),g=A.useCallback(k=>oz(o,k),[o]),b=A.useCallback(k=>lz(o,k,r),[o,r]),v=A.useCallback(k=>c({type:"toggle",path:k}),[]),w=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:w,updateAt:_}),[o,r,p,g,b,v,w,_])}function dz({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 w;v.preventDefault(),e(tz(((w=f.current)==null?void 0:w.value)??"")),d(!1)},g=()=>d(!1),b=nz(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,w)=>{const _=w===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 fz({tree:t,api:e,onNavigate:n,rootLabel:r="/",className:s}){const{state:o}=t,c=Hi(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=Bg(c),f=t.isExpanded(r),p=t.updateAt(r),[g,b]=A.useState(!1),[v,w]=A.useState(!1),[_,k]=A.useState(!1),[I,N]=A.useState(null),R=async(D,C)=>{try{await D(),N(null),C()}catch(L){N(L instanceof Error?L.message:String(L))}},M=()=>{b(!0),k(!1),d&&!f&&t.toggle(r)},F=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":XF(c),title:"Edit value",onClick:()=>{w(!0),k(!1)},children:JF(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 R(()=>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 ${s1(r)}`,title:"Add child",onClick:M,children:"+"}),h.jsx("button",{type:"button","data-rtdb-action-delete":!0,"aria-label":`Delete ${s1(r)}`,title:"Delete",onClick:()=>k(!0),children:"×"})]})})]}),I?h.jsx("p",{role:"alert","data-rtdb-error":!0,children:I}):null,v?h.jsx(i1,{initialType:n1(c),initialText:sz(c,n1(c)),submitLabel:"Save",onCancel:()=>w(!1),onSubmit:D=>R(()=>e.set(r,D),()=>w(!1))}):null,g?h.jsx(i1,{withKey:!0,initialType:"string",initialText:"",submitLabel:"Add",onCancel:()=>b(!1),onSubmit:(D,C)=>R(()=>e.set(My(r,C),D),()=>b(!1))}):null,F?h.jsxs("ul",{"data-rtdb-children":!0,children:[F.entries.map(([D])=>h.jsx("li",{children:h.jsx(Ek,{tree:t,api:e,onNavigate:n,path:My(r,D),label:D})},D)),F.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 (",F.hiddenCount," hidden)"]})}):null]}):null]})}function s1(t){const e=Hi(t);return e.length===0?"root":e[e.length-1]}function i1({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 N,R;_.preventDefault();const k=((N=c.current)==null?void 0:N.value)??"";if(t){const M=iz(k);if(M){b(M);return}}const I=az(f,((R=d.current)==null?void 0:R.value)??"");if(!I.ok){b(I.error);return}b(null),s(I.value,t?k.trim():void 0)},w=_=>{_.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:w,spellCheck:!1}):null,h.jsx("select",{"data-rtdb-editor-type":!0,"aria-label":"Value type",value:f,onChange:_=>p(_.currentTarget.value),onKeyDown:w,children:rz.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:w,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:w,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 hz(){const t=rr(),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(mz,{live:e}):h.jsx(pz,{})]})}function pz(){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 mz({live:t}){const[e,n]=A.useState("/"),r=$g(Cg()),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=uz(o,e);return h.jsxs("div",{className:"rtdb",children:[h.jsx(dz,{className:"rtdb__pathbar",path:e,onNavigate:n,rootLabel:s,inputPrefix:s}),h.jsx(fz,{className:"rtdb__tree",tree:c,api:o,onNavigate:n,rootLabel:s})]})}function yz(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 Mu(t,e,n=`${e}s`){return`${t} ${t===1?e:n}`}function gz(t){if(t===null)return"measuring…";const e=[];return t.collections&&e.push(Mu(t.collections,"collection")),t.users&&e.push(Mu(t.users,"user")),t.objects&&e.push(Mu(t.objects,"file")),t.rtdbKeys&&e.push(Mu(t.rtdbKeys,"RTDB key")),e.length?e.join(" · "):"empty — no data yet"}function sf(){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 bz(){return h.jsxs("svg",{...sf(),children:[h.jsx("path",{d:"M12 4v10"}),h.jsx("path",{d:"M8 10l4 4 4-4"}),h.jsx("path",{d:"M4 19h16"})]})}function vz(){return h.jsxs("svg",{...sf(),children:[h.jsx("path",{d:"M12 14V4"}),h.jsx("path",{d:"M8 8l4-4 4 4"}),h.jsx("path",{d:"M4 19h16"})]})}function wz(){return h.jsxs("svg",{...sf(),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 xz(){return h.jsxs("svg",{...sf(),children:[h.jsx("path",{d:"M4 5v5h5"}),h.jsx("path",{d:"M4.6 10a8 8 0 1 0 1.7-5.3"})]})}function Lu({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 Sz(){const t=v4(),e=x4(),n=S4(),r=_4(),s=Qd(),o=A.useRef(null),c=$g(Cg()),[d,f]=A.useState(!1),[p,g]=A.useState(!1),[b,v]=A.useState(!1),[w,_]=A.useState(!1),[k,I]=A.useState(""),N=uj(),{ensure:R}=N;A.useEffect(()=>R(),[R]);const M=yz(N.entries),F=gz(M),D=s.status==="ready"?s.payload.persist?"persisted to disk":"ephemeral":"in-page · resets on reload",C=async()=>{const x=await e();if(!x||typeof document>"u")return;const E=URL.createObjectURL(new Blob([x],{type:"application/json"})),O=document.createElement("a");O.href=E,O.download=`pyric-sandbox-${c||"export"}.json`,O.click(),URL.revokeObjectURL(E)},L=async x=>{var O;const E=(O=x.target.files)==null?void 0:O[0];if(x.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)}}},U=async()=>{v(!1),f(!0);try{await t()}finally{f(!1)}},H=async()=>{const x=k.trim();x&&(await r.save(x),I(""),_(!1))},z=async x=>{typeof window<"u"&&!window.confirm(`Switch to branch "${x}"? This replaces the current sandbox state.`)||await r.switchTo(x)},q=async x=>{typeof window<"u"&&!window.confirm(`Delete branch "${x}"?`)||await r.remove(x)};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:F}),h.jsx("span",{className:"studio-sandbox__persist",children:D})]}),h.jsxs("div",{className:"studio-sandbox__actions",children:[h.jsx(Lu,{glyph:h.jsx(bz,{}),name:"Export",caption:"Downloads all of this as one file.",onClick:()=>void C()}),h.jsx(Lu,{glyph:h.jsx(vz,{}),name:p?"Importing…":"Import",caption:"A chosen file replaces everything here.",disabled:p,onClick:()=>{var x;return(x=o.current)==null?void 0:x.click()}}),h.jsx(Lu,{glyph:h.jsx(wz,{}),name:"Save branch",caption:"Keeps a copy you can return to.",onClick:()=>_(x=>!x)}),h.jsx(Lu,{glyph:h.jsx(xz,{}),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:L}),w?h.jsxs("form",{className:"studio-sandbox__name-row",onSubmit:x=>{x.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:x=>I(x.target.value),onKeyDown:x=>{x.key==="Escape"&&(_(!1),I(""))}}),h.jsx("button",{type:"submit",className:"studio-button",disabled:!k.trim(),children:"Save"}),h.jsx("button",{type:"button",className:"studio-button",onClick:()=>{_(!1),I("")},children:"Cancel"})]}):null,b?h.jsxs("div",{className:"studio-sandbox__confirm",role:"alert",children:[h.jsx("span",{className:"studio-sandbox__confirm-copy",children:M&&F!=="empty — no data yet"?`This erases ${F}.`:"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 U(),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(x=>h.jsxs("div",{className:"studio-settings__branch",children:[h.jsx("span",{className:"mono",children:x}),h.jsxs("span",{className:"studio-settings__branch-actions",children:[h.jsx("button",{type:"button",className:"studio-button",onClick:()=>void z(x),children:"Switch"}),h.jsx("button",{type:"button",className:"studio-button",onClick:()=>void q(x),children:"Delete"})]})]},x))}):h.jsx("p",{className:"studio-sandbox__branches-empty",children:"No branches yet — Save branch keeps this exact state to come back to."})]})})]})}function Uu(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 _z(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}: ${Uu(n[c])} -> ${Uu(r[c])}`).join(", ")}return`${Uu(e.before)} -> ${Uu(e.after)}`}function Ez(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:_z(e),supported:e.qualification.supported}))}function Az(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 jz="pyric:assurance-campaign",kz="pyric-assurance-v1",Uy=new Set;let a1=!1,o1;function l1(t){for(const e of Uy)e(t)}function c1(t){return!!t&&typeof t=="object"&&t.schema==="pyric.assurance.visualization.v1"&&typeof t.campaignId=="string"}function Cz(){if(!(a1||typeof document>"u")){a1=!0,globalThis.addEventListener(jz,t=>{const e=t.detail;c1(e)&&l1(e)});try{o1=new BroadcastChannel(kz),o1.onmessage=t=>{c1(t.data)&&l1(t.data)}}catch{}}}function Nz(t){return Cz(),Uy.add(t),()=>Uy.delete(t)}function fm(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 Oz=[fm({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"}}),fm({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"}),fm({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"}}})],Qz=Oz.map(t=>({...t,campaignId:"collaboration-local-v1-fixed",targetHash:"fnv1a32-a9f18f23",mutation:{...t.mutation,decision:"DENY",events:[]},stateDiff:void 0,classification:"no-counterexample"}));const $y="pyric:assurance:campaigns",Ak="pyric:assurance:campaign:";function Rz(t){return!!t&&typeof t=="object"&&t.schema==="pyric.assurance.visualization.v1"&&typeof t.campaignId=="string"}function Tz(){if(typeof sessionStorage>"u")return[];try{const t=JSON.parse(sessionStorage.getItem($y)??"[]");if(!Array.isArray(t))return[];const e=t.map(n=>sessionStorage.getItem(`${Ak}${String(n)}`)).filter(n=>!!n).map(n=>JSON.parse(n)).filter(Rz);return e.length,e}catch{return[]}}function Dz(t){if(!(typeof sessionStorage>"u"))try{const e=JSON.parse(sessionStorage.getItem($y)??"[]"),n=Array.isArray(e)?e.map(String):[];n.includes(t.campaignId)||n.push(t.campaignId),sessionStorage.setItem($y,JSON.stringify(n)),sessionStorage.setItem(`${Ak}${t.campaignId}`,JSON.stringify(t))}catch{}}function Iz(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 Mz(){const[t,e]=A.useState(Tz);return A.useEffect(()=>{const r=Nz(s=>{Dz(s),e(o=>Iz(o,s))});return()=>{r()}},[]),t}function Lz(t,e){return t!==e?"assurance-verdict--mismatch":e==="ALLOW"?"assurance-verdict--allow":"assurance-verdict--deny"}function Uz(t){return t.replaceAll("-"," ")}function u1({value:t}){return h.jsx("pre",{className:"assurance-evidence__json",children:JSON.stringify(t,null,2)})}function $z(){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 d1({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 Bz({campaigns:t}){var M,F,D,C,L;const e=Mz(),n=t??e,r=Rr().query,[s,o]=A.useState(r.campaign??((M=n.find(U=>U.report))==null?void 0:M.campaignId)??((F=n[0])==null?void 0:F.campaignId)??""),c=n.find(U=>U.campaignId===s)??n[0],d=A.useMemo(()=>c!=null&&c.report?Ez(c.report):[],[c]),[f,p]=A.useState(r.probe??((D=d[0])==null?void 0:D.id)??"");if(A.useEffect(()=>{!s&&n[0]&&o(n[0].campaignId)},[s,n]),A.useEffect(()=>{var U;d.some(H=>H.id===f)||p(((U=d[0])==null?void 0:U.id)??"")},[d,f]),!c)return h.jsx($z,{});const g=(C=c.context)==null?void 0:C.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(d1,{attachment:g}),g!=null&&g.coverageGaps.length?h.jsx("ul",{className:"assurance-coverage-gaps","aria-label":"Attachment coverage gaps",children:g.coverageGaps.map(U=>h.jsxs("li",{children:[h.jsx("code",{children:U.service}),U.reason]},U.code))}):null,h.jsx("span",{className:"assurance-local-state",children:"Pyric sandboxes only | network off"})]});const v=d.find(U=>U.id===f)??d[0],w=b.results.find(U=>U.probeId===(v==null?void 0:v.id)),_=w?Az(w):null,k=(L=c.verifications)==null?void 0:L.at(-1),I=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 N(U){var q,x;o(U);const H=n.find(E=>E.campaignId===U),z=((x=(q=H==null?void 0:H.report)==null?void 0:q.results[0])==null?void 0:x.probeId)??"";p(z),xd({tab:"assurance",query:{campaign:U,probe:z||void 0}})}function R(U){p(U.id),xd({tab:"assurance",query:{campaign:c.campaignId,probe:U.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:U=>N(U.target.value),children:n.map(U=>h.jsx("option",{value:U.campaignId,children:U.campaignId},U.campaignId))})]}):null,h.jsx("span",{className:"assurance-local-state",children:"Pyric sandboxes only | network off"})]})]}),h.jsx(d1,{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--${I?"passed":"failed"}`,role:"status",children:[h.jsx("strong",{children:I?"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(U=>`${U.service}: ${U.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(U=>h.jsxs("button",{type:"button",className:"assurance-table__row","aria-pressed":U.id===(v==null?void 0:v.id),onClick:()=>R(U),role:"row",children:[h.jsxs("span",{role:"cell",children:[h.jsx("small",{children:U.service}),U.operation]}),h.jsx("span",{role:"cell",children:U.actor}),h.jsx("span",{role:"cell",className:`assurance-verdict ${U.expected==="ALLOW"?"assurance-verdict--allow":"assurance-verdict--deny"}`,children:U.expected}),h.jsx("span",{role:"cell",className:`assurance-verdict ${Lz(U.expected,U.observed)}`,children:U.observed}),h.jsx("span",{role:"cell",children:U.impact})]},U.id))]})]}),w?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--${w.classification}`,children:Uz(w.classification)}),h.jsx("h2",{id:"assurance-inspector-title",children:w.probeId})]}),h.jsx("span",{children:w.actorEvidence.reachability})]}),h.jsxs("dl",{className:"assurance-facts",children:[h.jsxs("div",{children:[h.jsx("dt",{children:"Invariant"}),h.jsx("dd",{children:w.invariant.statement})]}),h.jsxs("div",{children:[h.jsx("dt",{children:"Mutation"}),h.jsx("dd",{children:w.mutationSpec.description})]}),h.jsxs("div",{children:[h.jsx("dt",{children:"Actor"}),h.jsxs("dd",{children:[w.actorEvidence.uid??w.actorEvidence.actorId," ","via ",w.actorEvidence.acquisition]})]}),h.jsxs("div",{children:[h.jsx("dt",{children:"Fidelity"}),h.jsx("dd",{children:w.qualification.supported?"Supported for this probe":"Engine gap"})]})]}),w.qualification.requirements.some(U=>!U.supported)?h.jsx("ul",{className:"assurance-gaps",children:w.qualification.requirements.filter(U=>!U.supported).map(U=>h.jsxs("li",{children:[h.jsx("code",{children:U.id}),U.reason]},U.id))}):null,w.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(u1,{value:w.stateDiff.before})]}),h.jsxs("div",{children:[h.jsx("span",{children:"After"}),h.jsx(u1,{value:w.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(dk,{denial:_})]}):h.jsx("p",{className:"assurance-no-decision",children:"This service recorded operation and state evidence but no canonical rule-decision event."})]}):null]})]})}function jk(){const t="/__pyric/ui/";return`${t.endsWith("/")?t:`${t}/`}docs`}function qz(){const[t,e]=A.useState(!1);return A.useEffect(()=>{let n=!0;return fetch(`${jk()}/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 Fz({id:t}){const e=x3(t),n=cs(),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 zz({id:t}){switch(t){case"home":return h.jsx(QF,{});case"firestore":return h.jsx(Iq,{});case"auth":return h.jsx(Fq,{});case"storage":return h.jsx(Mq,{});case"rtdb":return h.jsx(hz,{});case"traffic":return h.jsx($F,{});case"assurance":return h.jsx(Bz,{});case"settings":return h.jsx(Sz,{});default:return h.jsx(Fz,{id:t})}}function Pz(){const[t,e]=p3(w3,"home"),n=d=>e(d),[r,s]=A.useState(!1),o=qz(),c=t==="home";return A.useEffect(()=>{const d=f=>{if(g3(f)){if(r){f.preventDefault(),s(!1);return}if(c){y3()&&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:[Pi.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:jk(),children:"Docs"}):null]}),h.jsx(V4,{})]})}),h.jsx("main",{className:"studio__content","data-surface":t,children:h.jsx("div",{className:"studio__surface-slot","data-active":"true",children:h.jsx(zz,{id:t})})}),r?h.jsx(R4,{onClose:()=>s(!1)}):null]})}function Vz(){return h.jsx(c3,{children:h.jsx(fO,{children:h.jsx(s3,{mode:"local",children:h.jsx(Pz,{})})})})}const kk=document.getElementById("root");if(!kk)throw new Error("Pyric Studio: #root element not found");lO.createRoot(kk).render(h.jsx(A.StrictMode,{children:h.jsx(Vz,{})}));export{Or as G,$n as T,Pl as a,Yz as b,lr as c,ur as d,Wz as e,K3 as f,A as g,h as j,Hl as r,Zz as s,D6 as u};
|
|
1215
|
+
color: hsl(${Math.max(0,Math.min(120-120*I,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 b_(t,e){if(t===void 0)throw new Error("Unexpected undefined");return t}const cB=(t,e)=>Math.abs(t-e)<1.01,uB=(t,e,n)=>{let r;return function(...s){t.clearTimeout(r),r=t.setTimeout(()=>e.apply(this,s),n)}},v_=t=>{const{offsetWidth:e,offsetHeight:n}=t;return{width:e,height:n}},dB=t=>t,fB=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},hB=(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(v_(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(v_(n))};t.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(d):d()});return o.observe(n,{box:"border-box"}),()=>{o.unobserve(n)}},w_={passive:!0},x_=typeof window>"u"?!0:"onscrollend"in window,pB=(t,e)=>{const n=t.scrollElement;if(!n)return;const r=t.targetWindow;if(!r)return;let s=0;const o=t.options.useScrollendEvent&&x_?()=>{}:uB(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,w_);const p=t.options.useScrollendEvent&&x_;return p&&n.addEventListener("scrollend",f,w_),()=>{n.removeEventListener("scroll",d),p&&n.removeEventListener("scrollend",f)}},mB=(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"]},yB=(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 gB{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:dB,rangeExtractor:fB,onChange:()=>{},measureElement:mB,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=Fa(()=>(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=Fa(()=>[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=Fa(()=>[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 w of this.laneAssignments.keys())w>=n&&this.laneAssignments.delete(w);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(w=>{this.itemSizeCache.set(w.key,w.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 w=0;w<g;w++){const _=b[w];_&&(v[_.lane]=w)}for(let w=g;w<n;w++){const _=o(w),k=this.laneAssignments.get(w);let I,N;const R=f==="estimate"||p.has(_);if(k!==void 0&&this.options.lanes>1){I=k;const C=v[I],L=C!==void 0?b[C]:void 0;N=L?L.end+this.options.gap:r+s}else{const C=this.options.lanes===1?b[w-1]:this.getFurthestMeasurement(b,w);N=C?C.end+this.options.gap:r+s,I=C?C.lane:w%this.options.lanes,this.options.lanes>1&&R&&this.laneAssignments.set(w,I)}const M=p.get(_),F=typeof M=="number"?M:this.options.estimateSize(w),D=N+F;b[w]={index:w,start:N,size:F,end:D,key:_,lane:I},v[I]=w}return this.measurementsCache=b,b},{key:!1,debug:()=>this.options.debug}),this.calculateRange=Fa(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,s,o)=>this.range=n.length>0&&r>0?bB({measurements:n,outerSize:r,scrollOffset:s,lanes:o}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=Fa(()=>{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=Fa(()=>[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 b_(r[pj(0,r.length-1,s=>b_(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&&cB(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 pj=(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 bB({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=pj(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 S_=typeof document<"u"?A.useLayoutEffect:A.useEffect;function vB({useFlushSync:t=!0,...e}){const n=A.useReducer(()=>({}),{})[1],r={...e,onChange:(o,c)=>{var d;t&&c?Ng.flushSync(n):n(),(d=e.onChange)==null||d.call(e,o,c)}},[s]=A.useState(()=>new gB(r));return s.setOptions(r),S_(()=>s._didMount(),[]),S_(()=>s._willUpdate()),s}function wB(t){return vB({observeElementRect:hB,observeElementOffset:pB,scrollToFn:yB,...t})}function Og({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=wB({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 xB={batch:"batch write",transaction:"transaction","listener-run":"listener re-evals"};function SB({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:xB[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(hj,{event:p,selected:p.id===r,onSelect:n,renderClassification:s,formatTime:o})},p.id))}):null]})}function _B(t){return t<0?0:t>1?1:t}function am(t,e){const n=e.end-e.start;return n<=0?0:_B((t-e.start)/n)}function EB({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(),[w,_]=A.useState(null),[k,I]=A.useState(null),N=Z4({events:t??[],window:n,bucketCount:r}),R=e??N,{buckets:M,total:F}=R,D=w??k,C=D===null?null:M.find(x=>x.index===D)??null,L=C!==null&&(s==null?void 0:s.start)===C.start&&s.end===C.end;if(M.length===0)return h.jsx("div",{className:b,"data-pyric-ui":"traffic-timeline","data-pyric-empty":"",children:g});const U=F===0,H=d===void 0?n.end:d,z=H==null?null:am(H,n),q=typeof p=="function"?p(n):p;return h.jsxs("div",{className:b,"data-pyric-ui":"traffic-timeline","data-pyric-empty":U?"":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:M.map(x=>h.jsx(AB,{bucket:x,window:n,onBrush:o,onHover:c?_:void 0,onFocus:c?I:void 0,summaryId:c&&!L&&(C==null?void 0:C.index)===x.index?v:void 0,selected:(s==null?void 0:s.start)===x.start&&s.end===x.end},x.index))}),C&&c&&!L?h.jsx("div",{id:v,role:"tooltip","data-pyric-bucket-summary":"",style:{"--pyric-bucket-summary-x":(C.index+.5)/Math.max(M.length,1)},children:c(C)}):null,s&&h.jsx("div",{"data-pyric-brush":"","aria-hidden":"true",style:{"--pyric-brush-left":am(s.start,n),"--pyric-brush-right":1-am(s.end,n)}}),z!=null&&h.jsx("div",{"data-pyric-live":"","aria-hidden":"true",style:{"--pyric-live-x":z}})]}),q!=null&&h.jsx("div",{"data-pyric-timeline-axis":"",children:q})]})}function AB({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 jB=t=>String(t);function kB({series:t,visible:e,onToggle:n,formatValue:r=jB,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 CB=t=>String(t),NB=t=>new Date(t).toLocaleTimeString();function OB({points:t,series:e,visible:n,omitZeroSeries:r=!1,formatValue:s=CB,formatTime:o=NB,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(N=>(!n||n.has(N.key))&&(!r||N.total>0));let b=0;for(const N of g)for(const R of N.values)R>b&&(b=R);const v=b===0?1:b,w=t.length,_=N=>w===1?50:N/(w-1)*100,k=N=>100-N/v*100,I=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(N=>{const R=e.indexOf(N);if(!((!n||n.has(N.key))&&(!r||N.total>0)))return null;const F=N.values.map((D,C)=>`${C===0?"M":"L"}${_(C)},${k(D)}`).join(" ");return h.jsx("path",{"data-pyric-chart-line":"","data-pyric-series-key":N.key,"data-pyric-series-index":R,d:F,fill:"none",vectorEffect:"non-scaling-stroke"},N.key)})}),h.jsx("div",{"data-pyric-chart-hits":"",children:t.map((N,R)=>h.jsx("button",{type:"button","data-pyric-chart-hit":"","data-pyric-point-index":R,onMouseEnter:()=>p(R),onFocus:()=>p(R),onMouseLeave:()=>p(M=>M===R?null:M),onBlur:()=>p(M=>M===R?null:M),"aria-label":`${o(N.start)} to ${o(N.end)}`},N.index))}),I&&h.jsxs("div",{"data-pyric-chart-tooltip":"",style:{"--pyric-hover-x":_(I.index)},children:[h.jsxs("div",{"data-pyric-tooltip-time":"",children:[o(I.start)," – ",o(I.end)]}),g.map(N=>h.jsxs("div",{"data-pyric-tooltip-row":"","data-pyric-series-key":N.key,"data-pyric-series-index":e.indexOf(N),children:[h.jsx("span",{"data-pyric-tooltip-label":"",children:N.label}),h.jsx("span",{"data-pyric-tooltip-value":"",children:s(N.values[I.index])})]},N.key))]})]})})}const RB={listUsers:lr.listUsers,subscribeUsers:lr.subscribeUsers,createUser:lr.createUser,updateUser:lr.updateUser,deleteUser:lr.deleteUser,clearUsers:lr.clearUsers,getAuthProviderConfig:lr.getAuthProviderConfig,setAuthProviderConfig:lr.setAuthProviderConfig,subscribeAuthProviderConfig:lr.subscribeAuthProviderConfig},mj=A.createContext(RB);function TB(){return A.useContext(mj)}function yj({value:t,children:e}){return A.createElement(mj.Provider,{value:t},e)}function DB(t,e){return[t.uid,t.email,t.displayName,t.phoneNumber].some(n=>n!=null&&n.toLowerCase().includes(e))}function Rg(t){const{listUsers:e,subscribeUsers:n,createUser:r,updateUser:s,deleteUser:o,clearUsers:c}=TB(),[d,f]=A.useState([]),[p,g]=A.useState(!0),[b,v]=A.useState(void 0),[w,_]=A.useState("");A.useEffect(()=>{let D=!1;g(!0),v(void 0);const C=z=>{D||(f(z),g(!1))},L=z=>{D||(f([]),v(z instanceof Error?z:new Error(String(z))),g(!1))},U=()=>{try{const z=e(t);z&&typeof z.then=="function"?z.then(C).catch(L):C(z)}catch(z){L(z)}};let H;try{U(),H=n(t,U)}catch(z){L(z)}return()=>{D=!0,H==null||H()}},[t,e,n]);const k=A.useMemo(()=>{const D=w.trim().toLowerCase();return D?d.filter(C=>DB(C,D)):d},[d,w]),I=A.useCallback(D=>r(t,D),[t,r]),N=A.useCallback((D,C)=>s(t,D,C),[t,s]),R=A.useCallback(D=>o(t,D),[t,o]),M=A.useCallback(()=>c(t),[t,c]),F=A.useCallback(()=>{const D=e(t);D&&typeof D.then=="function"?D.then(C=>f(C)).catch(()=>{}):f(D)},[t,e]);return{users:k,totalCount:d.length,isLoading:p,error:b,filter:w,setFilter:_,createUser:I,updateUser:N,deleteUser:R,clearUsers:M,refresh:F}}const IB=["iss","aud","sub","iat","exp","nbf","jti","nonce","azp","acr","amr","cnf","auth_time","firebase","at_hash","c_hash"],MB=1e3;function gj(t){const e=t.trim();if(!e)return{ok:!0,claims:void 0};if(e.length>MB)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 IB)if(r in n)return{ok:!1,message:`Custom claims must not have forbidden key: ${r}`};return{ok:!0,claims:n}}const LB={email:"",password:"",displayName:"",phoneNumber:"",photoUrl:"",emailVerified:!1,disabled:!1,claimsText:"",providerIds:[]},UB=new Set(["password","anonymous","phone"]),$B=/^[^@]+@[^@]+\.[^@]+$/,__=6;function BB(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=>!UB.has(e))}:{...LB}}function qB(t){const e=BB(t);return{fields:e,initial:{...e}}}function FB(t,e){switch(e.type){case"setField":return{...t,fields:{...t.fields,[e.field]:e.value}};case"reset":return{...t,fields:{...t.initial}}}}function zB(t){const e={},n=t.email.trim(),r=t.password;n&&!$B.test(n)&&(e.email="Invalid email"),r&&r.length<__&&(e.password=`Password should be at least ${__} characters`),r&&!n&&(e.password="Email is required for password authentication");const s=gj(t.claimsText);return s.ok||(e.claims=s.message),e}function PB(t){const{fields:e,initial:n}=t;return Object.keys(e).some(r=>r==="providerIds"?!bj(e.providerIds,n.providerIds):e[r]!==n[r])}function bj(t,e){if(t.length!==e.length)return!1;const n=[...e].sort();return[...t].sort().every((r,s)=>r===n[s])}function vj(t){const e=gj(t.claimsText);return e.ok?e.claims:void 0}function VB(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=vj(e);return r&&(n.customClaims=r),e.providerIds.length&&(n.providerUserInfo=e.providerIds.map(s=>({providerId:s}))),n}function HB(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=vj(e)??{}),bj(e.providerIds,n.providerIds)||(r.providerUserInfo=e.providerIds.map(s=>({providerId:s}))),r}function wj(t={}){const[e,n]=A.useReducer(FB,t.initial,qB),r=A.useMemo(()=>zB(e.fields),[e.fields]),s=A.useMemo(()=>PB(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:()=>VB(e),toUpdateRequest:()=>HB(e),dispatch:n}}const GB={"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 Ad(t){return GB[t]??t}function E_(t){return t.email??t.phoneNumber??(t.isAnonymous?"anonymous":t.uid)}function KB(t){return t.isAnonymous&&t.providerUserInfo.length===0?h.jsx("span",{"data-pyric-provider-id":"anonymous",children:Ad("anonymous")}):t.providerUserInfo.map(e=>h.jsx("span",{"data-pyric-provider-id":e.providerId,children:Ad(e.providerId)},e.providerId))}function A_(t){if(!t)return"—";const e=new Date(t);return Number.isNaN(e.getTime())?"—":e.toLocaleDateString()}function xj({users:t,isLoading:e,error:n,filter:r,onSelect:s,renderIdentifier:o,renderProviders:c,renderSelection:d,renderSelectionHeader:f,renderActions:p,renderActionsHeader:g,formatCreatedAt:b=A_,formatLastLoginAt:v=A_,emptyState:w,noResultsState:_,className:k,virtualizeThreshold:I=100,rowHeight:N=44,virtualizedHeight:R="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 D=!!(r!=null&&r.trim());return h.jsx("div",{className:k,"data-pyric-ui":"auth-user-list","data-pyric-empty":"","data-pyric-no-results":D?"":void 0,children:D?_??"No results":w??"No users for this project yet"})}const M=t.length>I,F=D=>h.jsxs("div",{role:"row","data-pyric-user-entry":!0,"data-pyric-user-uid":D.uid,"data-pyric-user-disabled":D.disabled?"":void 0,children:[d?h.jsx("span",{role:"cell","data-pyric-user-cell":"selection",children:d(D)}):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(D),children:o?o(D):E_(D)}):(o??E_)(D)}),h.jsx("span",{role:"cell","data-pyric-user-cell":"providers",children:(c??KB)(D)}),h.jsx("span",{role:"cell","data-pyric-user-cell":"created",children:b(D.createdAt)}),h.jsx("span",{role:"cell","data-pyric-user-cell":"signed-in",children:v(D.lastLoginAt)}),h.jsx("span",{role:"cell","data-pyric-user-cell":"uid",children:D.uid}),p?h.jsx("span",{role:"cell","data-pyric-user-cell":"actions",children:p(D)}):null]},D.uid);return h.jsxs("div",{className:k,role:"table","aria-label":"Authentication users","data-pyric-ui":"auth-user-list","data-pyric-virtualized":M?"":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]}),M?h.jsx(Og,{items:t,estimateSize:N,height:R,getItemKey:D=>D.uid,renderItem:F}):h.jsx("div",{role:"rowgroup","data-pyric-user-rows":!0,children:t.map(F)})]})}function YB({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 ZB({selected:t,onChange:e}){return h.jsx("div",{"data-pyric-provider-checklist":!0,children:YA.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:Ad(n)}),h.jsx("span",{"data-pyric-provider-option-id":!0,children:n})]},n))})}function Sj({initial:t,onSubmit:e,onCancel:n,submitLabel:r="Save",cancelLabel:s="Cancel",children:o,className:c,renderField:d}){const f=wj({initial:t}),p=t?"edit":"create",g=f.isValid&&(p==="create"||f.isDirty),b=(_,k,I,N,R=null)=>({name:_,label:k,input:N,error:R,kind:I,defaultRender:()=>I==="checkbox"?h.jsxs("label",{"data-pyric-field-label":_,children:[N,h.jsx("span",{"data-pyric-label-text":!0,children:k})]},_):I==="group"?h.jsxs("fieldset",{"data-pyric-field-label":_,children:[h.jsx("legend",{"data-pyric-label-text":!0,children:k}),N]},_):h.jsxs("label",{"data-pyric-field-label":_,children:[h.jsx("span",{"data-pyric-label-text":!0,children:k}),N,R!=null&&h.jsx("p",{role:"alert","data-pyric-field-error":_,children:R})]},_)}),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(ZB,{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)}))],w=_=>{_.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:w,children:[v.map(_=>d?h.jsx(A.Fragment,{children:d(_)},_.name):_.defaultRender()),h.jsx(YB,{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 WB({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 w;const v=g.current;(w=v==null?void 0:v.focus)==null||w.call(v)}},[t]),!t||typeof document>"u"?null:Ng.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 _j=A.createContext(null);function go(){const t=A.useContext(_j);if(!t)throw new Error("useConfirm: missing <ConfirmProvider> ancestor");return t}function Tg({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(_j.Provider,{value:f,children:[t,n?h.jsx(WB,{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 QB(t){return t.email??t.phoneNumber??t.displayName??t.uid}function JB({user:t,onDelete:e,title:n="Delete user",body:r,confirmLabel:s="Delete",renderTrigger:o,className:c}){const d=go(),f=async()=>{await d({title:n,body:r??`This will permanently delete ${QB(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 XB(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 e5={addDoc:wg,collection:Ui,deleteDoc:bd,doc:ur,getDoc:vg,getDocs:zl,limit:vd,onSnapshot:NU,query:Vl,setDoc:Pl,startAfter:CU},Ej=A.createContext(e5);function Dg(){return A.useContext(Ej)}function t5({value:t,children:e}){return A.createElement(Ej.Provider,{value:t},e)}function n5(t){const{onSnapshot:e}=Dg(),[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:XB(o),isLoading:!1}))},[e,t]),n}function Xd(t){return t==null?"null":typeof t=="string"?"string":typeof t=="number"?"number":typeof t=="boolean"?"boolean":typeof t=="object"&&Xi(t)!==null?"vector":Array.isArray(t)?"array":t instanceof $n?"timestamp":t instanceof Or?"geopoint":t instanceof Er?"bytes":typeof t=="object"&&Aj(t)?"timestamp":typeof t=="object"&&jj(t)?"geopoint":typeof t=="object"&&r5(t)?"reference":typeof t=="object"?"map":"null"}function Aj(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 jj(t){const e=t;return Object.keys(e).length===2&&typeof e.latitude=="number"&&typeof e.longitude=="number"}function r5(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 Xi(t){if(t===null||typeof t!="object")return null;const e=t;if(e.typeName==="vector"&&Tu(e.value)||e.__type__==="__vector__"&&Tu(e.value))return Du(e.value);if(Tu(e._values))return Du(e._values);if(typeof e.toArray=="function")try{const n=e.toArray();if(Tu(n))return Du(n)}catch{}return null}function Tu(t){return Array.isArray(t)&&t.every(e=>typeof e=="number")}function Du(t){const e=t.slice();return{values:e,dimension:e.length}}const j_=4;function kj(t){const e=t.values.slice(0,j_).join(", "),n=t.values.length>j_?", …":"";return`vector · ${t.dimension} [${e}${n}]`}function oo(t){const e=Xi(t);if(e)return kj(e);if(Array.isArray(t))return t.map(oo);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]=oo(o);return r}}return t}function Cj(){return crypto.randomUUID()}function s5(t){const e=Cj(),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))jy(n,e,r,s);return n}function jy(t,e,n,r){const s=Xd(r),o=Cj(),c={id:o,parentId:e,key:n,type:s,value:i5(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))jy(t,o,d,f);else if(s==="array"&&Array.isArray(r))for(const d of r)jy(t,o,null,d);return o}function i5(t){return t==="map"||t==="array"}function Nj(t){const e=t.nodes[t.rootId];if(!e||e.type!=="map")throw new Error("treeToData: tree root must be a map node");return ky(t,t.rootId)}function ky(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]=ky(t,s))}return r}case"array":{const r=[];for(const s of t.childIds[e]??[])r.push(ky(t,s));return r}default:return n.value}}function Cy(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 Oj(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 Rj(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 $n?void 0:"Expected a Timestamp";case"geopoint":return e instanceof Or?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 Er?void 0:"Expected a Bytes value";case"vector":return Xi(e)!==null?void 0:"Expected a vector value";case"map":case"array":return}}function Tj(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=Rj(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 Ig(t){switch(t){case"string":return"";case"number":return 0;case"boolean":return!1;case"null":return null;case"timestamp":return $n.now();case"geopoint":return new Or(0,0);case"reference":return{path:"",id:"",firestore:{}};case"bytes":return Er.fromUint8Array(new Uint8Array);case"vector":return{__type__:"__vector__",value:[]};case"map":case"array":return}}function Ny(t){if(t===null||typeof t!="object"||Xi(t)!==null)return t;if(Aj(t)){const n=t;return new $n(n.seconds??n._seconds??0,n.nanoseconds??n._nanoseconds??0)}if(jj(t)){const n=t;return new Or(n.latitude,n.longitude)}if(Array.isArray(t))return t.map(Ny);const e=Object.getPrototypeOf(t);if(e===Object.prototype||e===null){const n={};for(const[r,s]of Object.entries(t))n[r]=Ny(s);return n}return t}function Dj(t){const e=s5(Ny(t)),{tree:n,errorCount:r}=Tj(e);return{tree:n,initial:n,errorCount:r}}function a5(t,e){switch(e.type){case"setValue":return za(t,n=>l5(n,e.nodeId,e.value));case"setType":return za(t,n=>c5(n,e.nodeId,e.newType));case"setKey":return za(t,n=>u5(n,e.nodeId,e.key));case"addMapEntry":return za(t,n=>d5(n,e.parentId,e.key,e.childType));case"addArrayEntry":return za(t,n=>f5(n,e.parentId,e.childType));case"remove":return za(t,n=>h5(n,e.nodeId));case"reset":return{tree:t.initial,initial:t.initial,errorCount:o5(t.initial)};case"replaceData":return Dj(e.data);case"touch":{const n=t.tree.nodes[e.nodeId];if(!n||n.touched)return t;const r=Cy(t.tree);return r.nodes[e.nodeId]={...r.nodes[e.nodeId],touched:!0},{...t,tree:r}}case"touchAll":{const n=Cy(t.tree);for(const r of Object.keys(n.nodes))n.nodes[r]={...n.nodes[r],touched:!0};return{...t,tree:n}}}}function za(t,e){const n=e(Cy(t.tree)),{tree:r,errorCount:s}=Tj(n);return{...t,tree:r,errorCount:s}}function o5(t){let e=0;for(const n of Object.values(t.nodes))n.error&&e++;return e}function l5(t,e,n){const r=t.nodes[e];return!r||r.type==="map"||r.type==="array"||(t.nodes[e]={...r,value:n}),t}function c5(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 Oj(t,c))delete t.nodes[d],delete t.childIds[d];t.childIds[e]=[]}const s=n==="map"||n==="array"?void 0:Ig(n);return t.nodes[e]={...r,type:n,value:s},t}function u5(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 d5(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:Ig(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 f5(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:Ig(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 h5(t,e){const n=t.nodes[e];if(!n||n.id===t.rootId)return t;const r=Oj(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 Ij(t={}){const e=t.initial??{},n=A.useRef(null);n.current==null&&(n.current=Dj(e));const[r,s]=A.useReducer(a5,n.current),o=A.useCallback((R,M)=>s({type:"setValue",nodeId:R,value:M}),[]),c=A.useCallback((R,M)=>s({type:"setType",nodeId:R,newType:M}),[]),d=A.useCallback((R,M)=>s({type:"setKey",nodeId:R,key:M}),[]),f=A.useCallback((R,M,F)=>s({type:"addMapEntry",parentId:R,key:M,childType:F}),[]),p=A.useCallback((R,M)=>s({type:"addArrayEntry",parentId:R,childType:M}),[]),g=A.useCallback(R=>s({type:"remove",nodeId:R}),[]),b=A.useCallback(()=>s({type:"reset"}),[]),v=A.useCallback(R=>s({type:"replaceData",data:R}),[]),w=A.useCallback(R=>s({type:"touch",nodeId:R}),[]),_=A.useCallback(()=>s({type:"touchAll"}),[]),k=A.useCallback(()=>Nj(r.tree),[r.tree]),I=r.tree!==r.initial,N=r.errorCount===0;return A.useMemo(()=>({...r,isDirty:I,isValid:N,dispatch:s,setValue:o,setType:c,setKey:d,addMapEntry:f,addArrayEntry:p,remove:g,reset:b,replaceData:v,touch:w,touchAll:_,toData:k}),[r,I,N,o,c,d,f,p,g,b,v,w,_,k])}function p5({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,w]=A.useState(0),[_,k]=A.useState(n),I=A.useRef(0),[N,R]=A.useState(0),{addDoc:M,deleteDoc:F,doc:D,getDoc:C,getDocs:L,limit:U,onSnapshot:H,query:z,setDoc:q,startAfter:x}=Dg();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=z(K,U(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=++I.current,le=H(se,ye=>{R(ae),B(ye)},ee);return()=>{$=!0,le()}}return L(se).then(ae=>{B(ae)}).catch(ee),()=>{$=!0}},[t,L,U,r,H,n,e,z,_,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=z(e??t,x($),U(n));L(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,L,g,c,U,r,n,e,z,x]),O=A.useCallback(async($,K,W)=>{if($==null){const B=await M(t,K);return r==="paged"&&w(ee=>ee+1),B}const se=D(t,$);if((W==null?void 0:W.onExisting)==="fail"){const B=await C(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 q(se,K),r==="paged"&&w(B=>B+1),se},[M,t,D,C,r,q]),T=A.useCallback(async $=>{await F($),r==="paged"&&w(K=>K+1)},[F,r]),P=A.useCallback(()=>w($=>$+1),[]);return{documents:s,isLoading:c,error:f,subscriptionGeneration:N,hasMore:g,loadMore:E,createDocument:O,deleteDocument:T,refresh:P}}function m5({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 k_(t){return typeof t=="object"&&t!==null&&"isEqual"in t&&typeof t.isEqual=="function"}function C_(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function jd(t,e){if(Object.is(t,e))return!0;if(k_(t))return t.isEqual(e);if(k_(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)=>jd(s,e[o]));if(!C_(t)||!C_(e))return!1;const n=Object.keys(t),r=Object.keys(e);return n.length!==r.length?!1:n.every(s=>s in e&&jd(t[s],e[s]))}function y5({value:t,path:e}){return h.jsx("span",{"data-pyric-field-type":"string","data-pyric-field-path":e,children:t})}function g5({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 b5={type:"string",Display:y5,Edit:g5};function v5({value:t,path:e}){return h.jsx("span",{"data-pyric-field-type":"number","data-pyric-field-path":e,children:String(t)})}function w5({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 x5={type:"number",Display:v5,Edit:w5};function S5({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 _5({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 E5={type:"boolean",Display:S5,Edit:_5};function A5({path:t}){return h.jsx("span",{"data-pyric-field-type":"null","data-pyric-field-path":t,children:"null"})}function j5({path:t}){return h.jsx("span",{"data-pyric-field-type":"null","data-pyric-field-path":t,children:"null"})}const k5={type:"null",Display:A5,Edit:j5};function Mj(t){if(t instanceof $n)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 C5({value:t,path:e}){const n=Mj(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 N5({value:t,onChange:e,error:n,path:r}){const s=Mj(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($n.fromDate(p))},"aria-invalid":n?"true":void 0}),n?h.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const O5={type:"timestamp",Display:C5,Edit:N5};function R5({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 T5({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 Or(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 Or(t.latitude,o))}catch{}},"aria-label":"Longitude"})}),n?h.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const D5={type:"geopoint",Display:R5,Edit:T5},Lj=A.createContext({});Lj.Provider;function I5(){return A.useContext(Lj)}function M5({value:t,path:e}){const{onReferenceClick:n}=I5();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 L5({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 U5={type:"reference",Display:M5,Edit:L5};function $5({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 B5({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(Er.fromBase64String(s.target.value))}catch{}},"aria-invalid":n?"true":void 0}),n?h.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const q5={type:"bytes",Display:$5,Edit:B5};function Oy({value:t,path:e,fieldEditors:n}){const r=Xd(t),s=n[r];if(!s)return null;const{Display:o}=s;return h.jsx(o,{value:t,path:e,fieldEditors:n})}function Uj({label:t,value:e,path:n,fieldEditors:r,kind:s}){const o=Xd(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(Oy,{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(Oy,{value:e,path:n,fieldEditors:r})]})}function F5({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(Uj,{label:s,value:o,path:e?`${e}.${s}`:s,fieldEditors:n??{},kind:"key"},s))})}const z5={type:"map",Display:F5};function P5({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(Uj,{label:String(s),value:r,path:e?`${e}[${s}]`:`[${s}]`,fieldEditors:n??{},kind:"index"},s))})}const V5={type:"array",Display:P5},N_=4;function H5(t){return t.length<=N_?`[${t.join(", ")}]`:`[${t.slice(0,N_).join(", ")}, …]`}function G5({value:t,path:e}){const n=Xi(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:H5(n.values)})]}):h.jsx("span",{"data-pyric-field-type":"vector","data-pyric-field-path":e})}function K5(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 Y5({value:t,onChange:e,error:n,path:r}){const s=Xi(t),o=s?JSON.stringify(s.values):"[]",[c,d]=A.useState(o),[f,p]=A.useState(void 0),g=w=>{d(w);const _=K5(w);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:w=>g(w.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 Z5={type:"vector",Display:G5,Edit:Y5},O_={string:b5,number:x5,boolean:E5,null:k5,timestamp:O5,geopoint:D5,reference:U5,bytes:q5,map:z5,array:V5,vector:Z5};function $j(t){return t?{...O_,...t}:O_}function ef(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 Bj=A.createContext(null);function si(){const t=A.useContext(Bj);if(!t)throw new Error("DocumentEditor.* components must render inside <DocumentEditor.Root>");return t}function W5({initial:t,fieldEditors:e,onChange:n,children:r,className:s}){const o=Ij({initial:t}),c=$j(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}=ef();return h.jsx(Bj.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 Q5(){const{editor:t}=si(),e=t.tree.childIds[t.tree.rootId]??[];return h.jsxs("div",{"data-pyric-editor-fields":!0,children:[e.map(n=>h.jsx(Mg,{nodeId:n,path:J5(t,n)},n)),h.jsx(qj,{parentId:t.tree.rootId})]})}function J5(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 Mg({nodeId:t,path:e}){const{editor:n,fieldEditors:r}=si(),s=n.tree.nodes[t];if(!s)return null;if(s.type==="map")return h.jsx(t8,{node:s,path:e});if(s.type==="array")return h.jsx(n8,{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(Lg,{node:s,path:e}),h.jsx(c,{value:s.value,path:e,error:d,onChange:f=>n.setValue(s.id,f)})]})}function Lg({node:t,path:e}){const{editor:n}=si(),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(e8,{node:t}),h.jsx("button",{type:"button",onClick:()=>n.remove(t.id),"data-pyric-remove":!0,"aria-label":"Remove field",children:"×"})]})}const X5=["string","number","boolean","null","timestamp","geopoint","reference","bytes","vector","map","array"];function e8({node:t}){const{editor:e}=si(),n=t.parentId!=null?e.tree.nodes[t.parentId]:null,r=X5.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 t8({node:t,path:e}){const{editor:n}=si(),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(Lg,{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(Mg,{nodeId:s,path:c},s)})}),h.jsx(qj,{parentId:t.id})]})}function n8({node:t,path:e}){const{editor:n}=si(),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(Lg,{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(Mg,{nodeId:s,path:c})},s)})}),h.jsx(r8,{parentId:t.id})]})}function qj({parentId:t}){const{editor:e}=si();return h.jsx("button",{type:"button","data-pyric-add-map-entry":!0,onClick:()=>e.addMapEntry(t,"","string"),children:"+ Add field"})}function r8({parentId:t}){const{editor:e}=si();return h.jsx("button",{type:"button","data-pyric-add-array-entry":!0,onClick:()=>e.addArrayEntry(t,"string"),children:"+ Add item"})}const R_={Root:W5,Fields:Q5};function s8({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 yl=new Map;function Ug({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(yl);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(yl)}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(yl);return}const b=new Map;for(const[v,w]of e){const _=g.entries.has(v),k=g.entries.get(v);if(_&&n(k,w))continue;const I=c.current.get(v)===0?1:0;c.current.set(v,I),b.set(v,{kind:_?"modified":"added",cycle:I})}o.current={scope:t,entries:e},p(v=>{const w=new Map(v);let _=b.size>0;for(const k of v.keys())e.has(k)||(w.delete(k),_=!0);for(const[k,I]of b)w.set(k,I);return _?w.size===0?yl:w:v});for(const[v,w]of b){const _=d.current.get(v);_&&clearTimeout(_);const k=setTimeout(()=>{d.current.delete(v),p(I=>{var R;if(((R=I.get(v))==null?void 0:R.cycle)!==w.cycle)return I;const N=new Map(I);return N.delete(v),N.size===0?yl:N})},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 gl(t){return t.ref}function i8({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:w="60vh"}){const _=A.useMemo(()=>new Map(t.map(N=>[gl(N).path,N.data()])),[t]),k=Ug({scope:g,entries:_,equals:jd,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 I=t.length>b;return h.jsxs("div",{className:p,"data-pyric-ui":"document-list","data-pyric-virtualized":I?"":void 0,children:[I?h.jsx(Og,{items:t,estimateSize:v,height:w,getItemKey:N=>gl(N).path,renderItem:N=>{const R=k.get(gl(N).path);return h.jsxs("div",{"data-pyric-document-entry":!0,"data-pyric-document-id":N.id,"data-pyric-update":R==null?void 0:R.kind,"data-pyric-update-cycle":R==null?void 0:R.cycle,children:[h.jsx("button",{type:"button",onClick:()=>s==null?void 0:s(gl(N)),"data-pyric-document-select":!0,"data-pyric-update":R==null?void 0:R.kind,"data-pyric-update-cycle":R==null?void 0:R.cycle,children:c?c(N):N.id}),d?h.jsx("span",{"data-pyric-document-action":!0,children:d(N)}):null]})}}):h.jsx("ul",{"data-pyric-document-list-items":!0,children:t.map(N=>{const R=gl(N),M=k.get(R.path);return h.jsxs("li",{"data-pyric-document-entry":!0,"data-pyric-document-id":N.id,"data-pyric-update":M==null?void 0:M.kind,"data-pyric-update-cycle":M==null?void 0:M.cycle,children:[h.jsx("button",{type:"button",onClick:()=>s==null?void 0:s(R),"data-pyric-document-select":!0,"data-pyric-update":M==null?void 0:M.kind,"data-pyric-update-cycle":M==null?void 0:M.cycle,children:c?c(N):N.id}),d?h.jsx("span",{"data-pyric-document-action":!0,children:d(N)}):null]},R.path)})}),r&&o?h.jsx("button",{type:"button",onClick:o,"data-pyric-load-more":!0,disabled:e,children:"Load more"}):null]})}const a8=/^__.*__$/;function Fj(t){if(t.length===0)return"Cannot be empty";if(t.includes("/"))return'Cannot contain "/"';if(t==="."||t==="..")return'Cannot be "." or ".."';if(a8.test(t))return"Cannot match __.*__ (reserved)";if(l8(t)>1500)return"Cannot exceed 1500 bytes"}function o8(t){return Fj(t)}function l8(t){return new TextEncoder().encode(t).length}function c8(t){return Fj(t)}const T_="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function u8(){let t="";for(let e=0;e<20;e++)t+=T_.charAt(Math.floor(Math.random()*T_.length));return t}const d8={ref:Hl,listAll:kg,getMetadata:R6,getBlob:B6,uploadBytes:I6,deleteObject:oj},zj=A.createContext(d8);function tf(){return A.useContext(zj)}function f8({value:t,children:e}){return A.createElement(zj.Provider,{value:t},e)}function om(t){return t.replace(/^\/+|\/+$/g,"")}function Ry(t,e){return t.fullPath<e.fullPath?-1:t.fullPath>e.fullPath?1:0}function lm(t,e){return t.some(n=>n.fullPath===e.fullPath)?t:[...t,e].sort(Ry)}function h8(t,e){const{listAll:n,ref:r}=tf(),s=om(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(Ry),prefixes:[...k.prefixes].sort(Ry),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("/"),I=om(_),N=s===""?"":`${s}/`;if(!I.startsWith(N)||I===s)return;const R=I.slice(N.length),M=R.indexOf("/");c(F=>{if(F.status==="idle")return F;if(M===-1)return k?(p.current.set(I,F.prefixes.some(C=>C.fullPath===I)?null:I),{...F,prefixes:lm(F.prefixes,r(t,I))}):(p.current.set(I,F.items.some(C=>C.fullPath===I)?null:I),{...F,items:lm(F.items,r(t,I))});const D=`${N}${R.slice(0,M)}`;return p.current.set(I,F.prefixes.some(C=>C.fullPath===D)?null:D),{...F,prefixes:lm(F.prefixes,r(t,D))}})},[t,s]),v=A.useCallback(_=>{const k=om(_),I=p.current.get(k);if(p.current.delete(k),I===null)return;const N=I??k;c(R=>({...R,items:R.items.filter(M=>M.fullPath!==N),prefixes:R.prefixes.filter(M=>M.fullPath!==N)}))},[]),w=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:w,error:o.error,refresh:g,insertItem:b,removeItem:v}}function yt(t){return t.split("/").filter(Boolean).join("/")}function p8(t={}){const{path:e,onPathChange:n,defaultPath:r=""}=t,s=e!==void 0,[o,c]=A.useState(()=>yt(r)),d=s?yt(e):o,f=A.useCallback(w=>{const _=yt(w);s||c(_),n==null||n(_)},[s,n]),p=A.useMemo(()=>d===""?[]:d.split("/"),[d]),g=A.useCallback(w=>{const _=yt(w);f(_.includes("/")||d===""?_:`${d}/${_}`)},[d,f]),b=A.useCallback(()=>{p.length!==0&&f(p.slice(0,-1).join("/"))},[p,f]),v=A.useCallback(w=>{f(w<0?"":p.slice(0,w+1).join("/"))},[p,f]);return{path:d,segments:p,setPath:f,enter:g,up:b,navigateToIndex:v}}const D_={status:"idle",blob:void 0,url:void 0,error:void 0};function m8(t,e){const{getBlob:n,getMetadata:r,ref:s}=tf(),o=e==null?null:yt(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(D_),[b,v]=A.useState(0),w=A.useRef(0);A.useEffect(()=>{if(w.current++,g(D_),!c){f({status:"idle",metadata:void 0,error:void 0});return}let N=!1;return f({status:"loading",metadata:void 0,error:void 0}),r(s(t,o)).then(R=>{N||f({status:"success",metadata:R,error:void 0})}).catch(R=>{N||f({status:"error",metadata:void 0,error:R instanceof Error?R:new Error(String(R))})}),()=>{N=!0}},[t,o,b]);const _=p.url;A.useEffect(()=>{if(_!==void 0)return()=>{URL.revokeObjectURL(_)}},[_]);const k=A.useCallback(()=>v(N=>N+1),[]),I=A.useCallback(()=>{if(t==null||o==null||o==="")return;const N=++w.current;g({status:"loading",blob:void 0,url:void 0,error:void 0}),n(s(t,o)).then(R=>{N===w.current&&g({status:"success",blob:R,url:URL.createObjectURL(R),error:void 0})}).catch(R=>{N===w.current&&g({status:"error",blob:void 0,url:void 0,error:R instanceof Error?R:new Error(String(R))})})},[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:I}}function y8(){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 g8(t,e){const n=Hl(t,e);return{storage:t,bucket:n.bucket,fullPath:`${n.fullPath}/`,name:"",parent:n,root:n.root,toString:()=>`${n.toString()}/`}}function b8(t){return{...t,fullPath:`${t.fullPath}/`,name:""}}function v8(t){return{async*start(e){const n=t??{listAll:kg,deleteObject:oj};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(b8(c))}catch{}yield{deletedCount:r,done:!0}}}}function w8(t,e={}){const n=tf(),[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 N,R;const w=++p.current;s(0),f(void 0);const _={deleted:[],failed:[]};if(t==null||v.length===0)return _;c(!0);const k=g.current.impl??v8(n);let I=0;try{for(const M of v){(N=g.current.list)==null||N.removeItem(M.fullPath);try{if(M.kind==="object")await n.deleteObject(n.ref(t,M.fullPath)),I++;else for await(const F of k.start(n.ref(t,M.fullPath))){if(w!==p.current)return _;if(s(I+F.deletedCount),F.done){I+=F.deletedCount;break}}_.deleted.push(M.fullPath),w===p.current&&s(I)}catch(F){const D=F instanceof Error?F:new Error(String(F));_.failed.push({fullPath:M.fullPath,error:D}),(R=g.current.list)==null||R.insertItem(M.kind==="folder"?`${M.fullPath}/`:M.fullPath),w===p.current&&_.failed.length===1&&f(D)}}return _}finally{w===p.current&&c(!1)}},[n,t]),progress:r,isRunning:o,error:d}}const x8=Object.freeze({read:!0,write:!0,delete:!0,upload:!0,reasons:Object.freeze({read:[],write:[]})});function S8(t,e={}){const{paths:n,rules:r,identity:s,writeResource:o}=e,c=t==null?null:t[Wd],[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 R=typeof r=="string"?tj(r):r;f({status:"ready",rules:R,source:"option",error:void 0})}catch(R){f({status:"error",rules:null,source:"none",error:R instanceof Error?R:new Error(String(R))})}return}let N=!1;return f({status:"loading",rules:null,source:"none",error:void 0}),c.servicePromise.then(R=>{N||f({status:"ready",rules:R.rules,source:R.rules?"sandbox":"none",error:void 0})}).catch(R=>{N||f({status:"error",rules:null,source:"none",error:R instanceof Error?R:new Error(String(R))})}),()=>{N=!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,w=o==null?void 0:o.contentType,_=A.useCallback(N=>{if(g==null)return x8;const R=yt(N),M=(c==null?void 0:c.bucket)??"pyric-default",F=R===""?`b/${M}/o`:`b/${M}/o/${R}`,D=U=>rj(g,{request:{auth:p,method:U,path:F,...U==="write"&&v!==void 0?{resource:{size:v,contentType:w}}:{}},resource:null}),C=D("read"),L=D("write");return{read:C.allowed,write:L.allowed,delete:L.allowed,upload:L.allowed,reasons:{read:C.allowed?[]:C.reasons,write:L.allowed?[]:L.reasons}}},[g,c==null?void 0:c.bucket,p,v,w]),k=typeof n=="string"?n:(n??[]).join(`
|
|
1216
|
+
`),I=A.useMemo(()=>{const N=typeof n=="string"?[n]:n??[],R={};for(const M of N)R[yt(M)]=_(M);return R},[k,_]);return{status:b,source:d.source,advisory:!1,identity:p,verdicts:I,verdictFor:_,error:d.error}}function I_(t,e){return t===""?e:e===""?t:`${t}/${e}`}function _8(t){return t instanceof Blob?t.size:t.byteLength}function E8(t){if(t instanceof Blob){const e=t;return{path:e.webkitRelativePath||e.name,data:e}}return t}function A8(t,e={}){const{ref:n,uploadBytes:r}=tf(),s=yt(e.path??""),[o,c]=A.useState([]),d=A.useRef(e);d.current=e;const f=A.useCallback(v=>{c(w=>w.map(_=>_.id===v.id?v:_))},[]),p=A.useCallback(async v=>{var k,I,N;if(t==null)throw new Error("useObjectUpload: storage handle is null");const _=(Array.isArray(v)?v:[v]).map(R=>{const M=E8(R);return{task:{id:crypto.randomUUID(),fullPath:I_(s,yt(M.path)),status:"running",bytesTransferred:0,totalBytes:_8(M.data)},entry:M}});c(R=>[...R,..._.map(M=>M.task)]);for(const{task:R}of _)(k=d.current.list)==null||k.insertItem(R.fullPath),(N=(I=d.current).onProgress)==null||N.call(I,R);return Promise.all(_.map(async({task:R,entry:M})=>{var F,D,C,L,U,H,z;try{const q=await r(n(t,R.fullPath),M.data,M.metadata),x={...R,status:"success",bytesTransferred:R.totalBytes,metadata:q.metadata};return f(x),(D=(F=d.current).onProgress)==null||D.call(F,x),(L=(C=d.current).onComplete)==null||L.call(C,x),x}catch(q){const x={...R,status:"error",error:q instanceof Error?q:new Error(String(q))};return(U=d.current.list)==null||U.removeItem(R.fullPath),f(x),(z=(H=d.current).onError)==null||z.call(H,x),x}}))},[t,s,f,n,r]),g=A.useCallback(async v=>{var _,k;if(t==null)throw new Error("useObjectUpload: storage handle is null");const w=I_(s,yt(v));if(w==="")throw new Error("createFolder: folder name is empty");(_=d.current.list)==null||_.insertItem(`${w}/`);try{await r(g8(t,w),new Blob([]),{contentType:"text/plain"})}catch(I){throw(k=d.current.list)==null||k.removeItem(w),I}},[t,s,r]),b=A.useCallback(()=>{c(v=>v.filter(w=>w.status==="running"))},[]);return{tasks:o,isUploading:o.some(v=>v.status==="running"),upload:p,createFolder:g,clearCompleted:b}}function j8({path:t,onNavigate:e,rootLabel:n="/",separator:r="/",className:s}){const o=yt(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 k8({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:w="60vh"}){const{ref:_,size:k}=ef();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 I=M=>{if(!c)return{denied:!1};const F=c.verdictFor(M.fullPath);return F.read?{denied:!1}:{denied:!0,reason:F.reasons.read.join("; ")}},N=M=>{const F=M.kind==="object"&&M.fullPath===o;return h.jsxs(h.Fragment,{children:[h.jsx("button",{type:"button",onClick:()=>M.kind==="folder"?r==null?void 0:r(M.fullPath):s==null?void 0:s(M.ref),"data-pyric-entry-select":!0,"data-pyric-selected":F?"":void 0,"aria-selected":F||void 0,children:d?d(M):M.name}),f?h.jsx("span",{"data-pyric-storage-action":!0,children:f(M)}):null]})},R=t.length>b;return h.jsx("div",{ref:_,className:g,"data-pyric-ui":"object-browser","data-size":k,"data-pyric-virtualized":R?"":void 0,children:R?h.jsx(Og,{items:t,estimateSize:v,height:w,getItemKey:M=>`${M.kind}:${M.fullPath}`,renderItem:M=>{const F=I(M);return h.jsx("div",{"data-pyric-storage-entry":!0,"data-pyric-entry-kind":M.kind,"data-pyric-entry-path":M.fullPath,"data-pyric-denied":F.denied?"":void 0,"data-pyric-denied-reason":F.reason,children:N(M)})}}):h.jsx("ul",{"data-pyric-object-browser-items":!0,children:t.map(M=>{const F=I(M);return h.jsx("li",{"data-pyric-storage-entry":!0,"data-pyric-entry-kind":M.kind,"data-pyric-entry-path":M.fullPath,"data-pyric-denied":F.denied?"":void 0,"data-pyric-denied-reason":F.reason,children:N(M)},`${M.kind}:${M.fullPath}`)})})})}async function Pj(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 Pj(c,r,n)}}}async function C8(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 Pj(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 N8({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 w=v.dataTransfer;w&&C8(w).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 O8(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 R8(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 M_(t,e){if(!e.has(t))return t;const{stem:n,ext:r}=O8(t),{base:s,counter:o}=R8(n);let c=o===null?1:o+1;for(;;){const d=`${s} (${c})${r}`;if(!e.has(d))return d;c+=1}}function T8(t,e){const n=new Set(e),r=new Map;return t.map(s=>{const o=s.indexOf("/");if(o===-1){const f=M_(s,n);return n.add(f),f}const c=s.slice(0,o);let d=r.get(c);return d===void 0&&(d=M_(c,n),n.add(d),r.set(c,d)),`${d}${s.slice(o)}`})}function L_(t){const e=yt(t);if(e==="")return[];const n=e.split("/");return n.map((r,s)=>n.slice(0,s+1).join("/"))}const Vj=[];function D8(t,e){switch(e.type){case"create":{const n=L_(e.path).filter(r=>!t.includes(r));return n.length===0?t:[...t,...n].sort()}case"materialize":{const n=new Set(L_(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=yt(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:Vj}}function I8(t,e){const n=yt(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 U_(t,e){return t.includes(yt(e))}function M8(t){const e=yt(t);return e===""?"Enter a folder name.":e.split("/").some(r=>r==="."||r==="..")?'Folder names may not be "." or "..".':null}const L8=256*1024;function Ty(t){return(t.contentType??"").split(";")[0].trim().toLowerCase()}const U8={id:"image",match:t=>Ty(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 $8({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 B8={id:"text",match:t=>{const e=Ty(t);return e.startsWith("text/")||e==="application/json"},needsBlob:!0,maxBytes:L8,render:({metadata:t,blob:e})=>e?h.jsx($8,{blob:e,isJson:Ty(t)==="application/json"}):null},q8=[U8,B8];function F8(t,e){for(const n of[...e??[],...q8])if(n.match(t))return n}const z8=[{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 P8({metadata:t}){return h.jsxs("dl",{"data-pyric-object-metadata":!0,children:[z8.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 V8({storage:t,path:e,previews:n,renderMetadata:r,children:s,className:o}){var N,R;const{ref:c,size:d}=ef(),f=m8(t,e),{metadata:p,blobStatus:g,loadBlob:b}=f,v=p?F8(p,n):void 0,w=(v==null?void 0:v.maxBytes)!==void 0&&p!==void 0&&p.size>v.maxBytes,_=(v==null?void 0:v.needsBlob)===!0&&!w;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:(N=f.error)==null?void 0:N.message});let k,I={};return v===void 0?I={"data-pyric-preview-none":""}:w?I={"data-pyric-preview-too-large":""}:_&&g==="loading"?I={"data-pyric-preview-loading":""}:_&&g==="error"?(I={"data-pyric-preview-error":""},k=(R=f.blobError)==null?void 0:R.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(P8,{metadata:p}),h.jsx("div",{"data-pyric-object-preview":!0,"data-pyric-preview":v==null?void 0:v.id,...I,children:k}),s]})}const Hj=A.createContext(null);function H8(){const t=A.useContext(Hj);if(!t)throw new Error("useToast: missing <ToastProvider> ancestor");return t}function G8({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(w=>w.id!==g))},b),g},[e]),f=A.useMemo(()=>({toast:d,dismiss:c,toasts:s}),[d,c,s]);return h.jsxs(Hj.Provider,{value:f,children:[t,h.jsx(K8,{toasts:s,dismiss:c,className:n,regionLabel:r})]})}function K8({toasts:t,dismiss:e,className:n,regionLabel:r}){const[s,o]=A.useState(!1);return A.useEffect(()=>o(!0),[]),!s||typeof document>"u"?null:Ng.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 Y8({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=go(),{toast:w}=H8(),{deleteEntries:_,isRunning:k,progress:I}=w8(t,{impl:n,list:r}),N=s?e.map(D=>({entry:D,verdict:s.verdictFor(D.fullPath)})).filter(D=>!D.verdict.delete):[],R=N.length===0?void 0:`Delete denied for ${N[0].entry.fullPath}${N.length>1?` (+${N.length-1} more)`:""}: ${N[0].verdict.reasons.write.join("; ")}`,M=k||e.length===0||t==null||N.length>0,F=async()=>{if(M||!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(L=>h.jsxs("li",{"data-pyric-entry-kind":L.kind,children:[L.fullPath,L.kind==="folder"?"/":""]},L.fullPath))}),destructive:!0,confirmLabel:d}))return;const C=await _(e);C.failed.length===0?(w({title:`Deleted ${C.deleted.length} ${C.deleted.length===1?"item":"items"}`,kind:"success"}),f==null||f(C)):(w({title:`Delete failed for ${C.failed.length} of ${e.length}`,kind:"error",body:h.jsx("ul",{"data-pyric-delete-selection-failures":!0,children:C.failed.map(L=>h.jsxs("li",{children:[L.fullPath,":"," ",L.error.code??L.error.message]},L.fullPath))})}),p==null||p(C))};return g?h.jsx(h.Fragment,{children:g({onClick:F,isRunning:k,progress:I,disabled:M,deniedReason:R})}):h.jsx("button",{type:"button",onClick:F,className:b,disabled:M,title:R,"data-pyric-ui":"delete-selection","data-pyric-destructive":"","data-pyric-running":k?"":void 0,"data-pyric-denied":R?"":void 0,"data-pyric-denied-reason":R,children:k?`Deleting… (${I})`:d})}function kd(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 Gj(t){const e=t.indexOf("?");return _g(e===-1?t:t.slice(0,e),e===-1?"":t.slice(e))}function Z8(t){const{tab:e,rest:n,query:r}=Gj(t),s=n.join("/");return e==="firestore"?{view:"firestore",path:kd(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 W8(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 Kj(t){const{tab:e,query:n}=Gj(t),r=Z8(t),s=e==="traffic"?n.inspect??null:null;return{target:r,selectedInspectId:s}}let $_=null,Dy=Kj("");function Q8(){const t=PA();return t!==$_&&($_=t,Dy=Kj(t)),Dy}function J8(){return Dy}function Iu(t){Jn(W8(t))}function X8(t){Jn({tab:"traffic",query:{inspect:t}})}function nf(){const t=A.useSyncExternalStore(ec,Q8,J8),e=A.useCallback(s=>Iu(s),[]),n=A.useCallback(s=>{switch(s.kind){case"user":Iu({view:"auth",uid:s.uid});break;case"storage":Iu({view:"storage",kind:"object",path:s.objectPath});break;case"document":Iu({view:"firestore",path:kd(s.path)});break}},[]),r=A.useCallback(s=>X8(s),[]);return A.useMemo(()=>({target:t.target,navigate:e,navigateRef:n,selectedInspectId:t.selectedInspectId,navigateInspect:r}),[t,e,n,r])}const eq={narrowBreakpoint:640,mediumBreakpoint:920};function tq(t){switch(t){case"narrow":return 1;case"medium":return 2;case"wide":return 3}}function nq(t,e){const n=tq(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 cm({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 Yj({mode:t,parentPath:e,onCreate:n,onClose:r}){const[s,o]=A.useState(""),[c,d]=A.useState(()=>u8()),[f,p]=A.useState(null),[g,b]=A.useState(null),[v,w]=A.useState(!1),_=A.useRef(null),k=t==="collection"&&s?o8(s):void 0,I=c?c8(c):void 0,R=!(t==="collection"&&(!s||k))&&!!c&&!I&&!v;A.useEffect(()=>{const D=C=>{C.key==="Escape"&&!v&&r()};return document.addEventListener("keydown",D),()=>document.removeEventListener("keydown",D)},[v,r]);const M=async()=>{if(!(!R||!f)){if(!f.isValid){f.touchAll();return}w(!0),b(null);try{await n({collectionId:t==="collection"?s:null,docId:c,data:Nj(f.tree)}),r()}catch(D){b(D instanceof Error?D:new Error(String(D))),w(!1)}}},F=t==="collection"?"Start a collection":"Add a document";return h.jsx("div",{className:"fs-modal-backdrop",onMouseDown:D=>{D.target===D.currentTarget&&!v&&r()},children:h.jsxs("div",{ref:_,className:"fs-modal",role:"dialog","aria-modal":"true","aria-label":F,"data-pyric-ui":"fs-create-modal","data-fs-create-mode":t,children:[h.jsx("h2",{className:"fs-modal__title",children:F}),h.jsx(cm,{label:"Parent path",children:h.jsx("span",{className:"fs-modal__path",children:e})}),t==="collection"?h.jsx(cm,{label:"Collection ID",error:k,children:h.jsx("input",{autoFocus:!0,type:"text",value:s,placeholder:"e.g. users",onChange:D=>o(D.target.value),"data-pyric-field":"collection-id","aria-invalid":k?"true":void 0})}):null,h.jsx(cm,{label:"Document ID",error:c?I:"Cannot be empty",hint:"Auto-generated — edit to set your own.",children:h.jsx("input",{autoFocus:t==="document",type:"text",value:c,onChange:D=>d(D.target.value),"data-pyric-field":"doc-id","aria-invalid":I||!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(R_.Root,{initial:{},onChange:p,children:h.jsx(R_.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:!R,onClick:()=>void M(),children:v?"Saving…":"Save"})]})]})})}function Zj({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 Wj(t){return JSON.stringify(t)}function rq(t,e){const n=new Map,r=(s,o)=>{const c=e(s),d=Wj(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 Qj(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 Wj(n)}function sq(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 iq(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 aq=42;function oq(t,e,n,r=aq){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 lq(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 cq(t){return t.shiftKey===!0}const Jj=["string","number","boolean","null","timestamp","geopoint","reference","bytes","vector"],uq=[...Jj,"map","array"];function dq({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,[]),w=Ij({initial:v}),_=w.replaceData,k=A.useMemo(()=>$j(o),[o]),I=go(),[N,R]=A.useState(()=>new Set),[M,F]=A.useState(null),D=A.useRef(t),C=A.useRef(new Set),L=A.useRef(!1),[U,H]=A.useState(null),z=A.useMemo(()=>rq(b,Xd),[b]),q=Ug({scope:e.path,entries:z,equals:jd,ready:M===null});A.useEffect(()=>{L.current&&(L.current=!1,H(null),n(w.toData()).catch(se=>{H(se instanceof Error?se:new Error(String(se)))}))},[w.tree]),A.useEffect(()=>{!t||t===D.current||M!==null||(D.current=t,C.current.clear(),_(t.data()??{}))},[M,_,t]);const x=A.useCallback(se=>{R(B=>{const ee=new Set(B);return ee.has(se)?ee.delete(se):ee.add(se),ee})},[]),[E,O]=A.useState(null),T=A.useCallback((se,B)=>{if(B==="map"?w.addMapEntry(se,"","string"):w.addArrayEntry(se,"string"),se!==w.tree.rootId){const ee=Qj(w.tree,se);R(ae=>new Set(ae).add(ee))}O(se)},[w]);A.useEffect(()=>{if(!E)return;const se=w.tree.childIds[E]??[],B=se[se.length-1];B&&!M&&(C.current.add(B),F(B),O(null))},[w.tree,E]);const P=A.useCallback(se=>{w.remove(se),C.current.delete(se),L.current=!0,M===se&&F(null)},[w,M]),$=A.useCallback(async(se,B,ee)=>{if(cq(ee)){P(se.id);return}await I({title:`Delete field "${B}"?`,destructive:!0,confirmLabel:"Delete"})&&P(se.id)},[I,P]),K=e.id,W=w.tree.childIds[w.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(Zj,{items:[{label:"Delete document fields",onSelect:()=>{(async()=>await I({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}]})]}),U?h.jsx("p",{className:"fs-doctree__err",children:U.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:()=>T(w.tree.rootId,"map"),children:[h.jsx("span",{"aria-hidden":"true",children:"+"})," Add field"]})}),W.map(se=>h.jsx(Xj,{nodeId:se,depth:0,editor:w,registry:k,expanded:N,onToggle:x,editingId:M,setEditingId:F,newIdsRef:C,onAdd:T,onDelete:$,onCommitNeeded:()=>{L.current=!0},onReferenceClick:c,updates:q},se))]}),f&&p?h.jsx(ek,{firestore:f,documentRef:e,listSubcollections:p,onSubcollectionClick:g}):null]})}function Xj({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:w}){const{tree:_}=n,k=_.nodes[t];if(!k)return null;const{label:I,isArrayChild:N}=iq(_,t),R=k.type==="map"||k.type==="array",M=sq(_,t),F=Qj(_,t),D=w.get(F),C=s.has(F),L=c===t,U=f.current.has(t);return L?h.jsx("li",{className:"fs-doctree__row fs-doctree__row--editing","data-pyric-doctree-depth":e,style:{"--fs-depth":e},children:h.jsx(fq,{node:k,isNew:U,isArrayChild:N,tree:_,editor:n,registry:r,path:M,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":R?"":void 0,style:{"--fs-depth":e},children:[h.jsxs("div",{className:"fs-doctree__line","data-pyric-update":D==null?void 0:D.kind,"data-pyric-update-cycle":D==null?void 0:D.cycle,children:[R?h.jsx("button",{type:"button",className:"fs-doctree__caret","aria-expanded":C,onClick:()=>o(F),children:h.jsx("span",{"aria-hidden":"true",children:C?"▼":"▶"})}):h.jsx("span",{className:"fs-doctree__caret fs-doctree__caret--empty","aria-hidden":"true"}),N?h.jsx("span",{className:"fs-doctree__chip",children:I}):h.jsx("span",{className:"fs-doctree__key",children:I}),R?C?null:h.jsx("span",{className:"fs-doctree__preview",children:oq(_,t,{asVectorView:Xi,vectorPreview:kj})}):h.jsx("span",{className:"fs-doctree__value",children:h.jsx(Oy,{value:k.value,path:M,fieldEditors:r})}),h.jsxs("span",{className:"fs-doctree__hover",children:[h.jsxs("span",{className:"fs-doctree__typenote",children:["(",k.type,")"]}),R?h.jsx("button",{type:"button",className:"fs-doctree__icon",title:"Add field","aria-label":`Add field to ${I||"document"}`,onClick:()=>p(t,k.type==="array"?"array":"map"),children:"+"}):h.jsx("button",{type:"button",className:"fs-doctree__icon",title:"Edit","aria-label":`Edit ${I}`,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 ${I||"field"} (shift-click to skip confirmation)`,onClick:H=>void g(k,I,{shiftKey:H.shiftKey}),children:"🗑"})]})]}),R&&C?h.jsxs("ul",{className:"fs-doctree__children",children:[(_.childIds[t]??[]).map(H=>h.jsx(Xj,{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:w},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 fq({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,w]=A.useState(t.type),[_,k]=A.useState(t.value),[I,N]=A.useState(!1),R=n?void 0:g===""?"Field name is required":lq(r,t,g)?"Field name must be unique":void 0,M=v==="map"||v==="array"?void 0:Rj(v,_),F=!R&&!M,D=()=>{if(!F){N(!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()},C=()=>{e?p():f()},L=o[v],U=L==null?void 0:L.Edit,H=v!=="map"&&v!=="array"&&U?h.jsx(U,{value:_,path:c,error:I?M:void 0,onChange:x=>k(x)}):v==="map"||v==="array"?h.jsxs("span",{className:"fs-doctree__editnote",children:["Saves as an empty ",v," — add its children afterward."]}):null,z=h.jsxs("span",{className:"fs-doctree__editactions",children:[h.jsx("button",{type:"button",className:"fs-doctree__editsave",onClick:D,"aria-label":"Save field",children:"✓"}),h.jsx("button",{type:"button",className:"fs-doctree__editcancel",onClick:C,"aria-label":"Cancel edit",children:"✕"})]}),q=h.jsx("select",{className:"fs-doctree__edittype",value:v,onChange:x=>{const E=x.target.value;w(E),E!=="map"&&E!=="array"&&E!==v&&k(hq(E))},"aria-label":"Field type",children:(e?uq:Jj).map(x=>h.jsx("option",{value:x,children:x},x))});return h.jsxs("div",{className:"fs-doctree__editrow",onKeyDown:x=>{x.key==="Enter"&&!x.target.matches("textarea")?(x.preventDefault(),D()):x.key==="Escape"&&(x.preventDefault(),C())},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:x=>b(x.target.value),onBlur:()=>N(!0),"aria-label":"Field name","aria-invalid":I&&R?"true":void 0}),q]}),h.jsxs("div",{className:"fs-doctree__editline",children:[n?q:null,H,z]}),I&&R?h.jsx("span",{className:"fs-doctree__editerr",children:R}):null]})}function hq(t){switch(t){case"string":return"";case"number":return 0;case"boolean":return!1;default:return null}}function ek({firestore:t,documentRef:e,listSubcollections:n,onSubcollectionClick:r}){const{subcollections:s,isLoading:o}=m5({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 pq(t){return t.split("/").filter(Boolean).length%2===0}function tk(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};pq(s.path)?yield*n(s,o):yield*r(s,o),yield{deletedCount:o.n,done:!0}}}}async function nk(t,e){for await(const n of t.start(e))if(n.done)return}async function rk({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 nk(r,e):await n.deleteDoc(e),!0):!1}function mq(t){const e=t.exists;return typeof e=="function"?e.call(t):e}async function yq(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 gq(t){return{id:t.id,ref:t,data:()=>{},__pyricPhantom:!0}}function q_(t){return t.__pyricPhantom===!0}function bq(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 vq({handles:t}){var F;const{target:e,navigate:n}=nf(),r=t.adminFirestore,s=Dg(),o=A.useMemo(()=>(e==null?void 0:e.view)==="firestore"?e.path:[],[e]),c=A.useCallback(D=>{const C=typeof D=="function"?D(o):D;n({view:"firestore",path:C})},[n,o]),d=(D,C)=>c(L=>[...L.slice(0,D+1),C]),[f,p]=A.useState(null),g=A.useCallback(async({collectionId:D,docId:C,data:L})=>{if(!f||!D)return;const U=f.parentDocPath,H=U?s.collection(s.doc(r,U),D):s.collection(r,D);await yq(s,H,C,L);const z=U?`${U}/${D}`:D;n({view:"firestore",path:kd(`${z}/${C}`)})},[s,r,f,n]),b=[h.jsx(Sq,{api:s,firestore:r,collectionIds:t.listRootCollections(),onSelect:D=>c([{kind:"collection",id:D,path:D}]),onStartCollection:()=>p({parentDocPath:null})},"__root__"),...o.map((D,C)=>{var L;return D.kind==="collection"?h.jsx(_q,{api:s,firestore:r,handles:t,collectionPath:D.path,selectedId:((L=o[C+1])==null?void 0:L.id)??null,onSelect:U=>d(C,{kind:"document",id:U.id,path:U.path}),onCollectionDeleted:()=>c(U=>U.slice(0,C))},D.path):h.jsx(Eq,{api:s,firestore:r,handles:t,docPath:D.path,onOpenSubcollection:U=>d(C,{kind:"collection",id:U.id,path:U.path}),onReferenceClick:U=>n({view:"firestore",path:kd(U.path)}),onStartCollection:()=>p({parentDocPath:D.path}),onDeleted:()=>c(U=>U.slice(0,C))},D.path)})],{ref:v,size:w}=ef(eq),{startIndex:_,visibleCount:k,emptySlots:I}=nq(b.length,w),N=b.slice(_,_+k),R=o.length===0?"Select a collection":((F=o[o.length-1])==null?void 0:F.kind)==="collection"?"Select a document":null,M=[...N,...Array.from({length:I},(D,C)=>h.jsx(xq,{hint:C===0?R:null},`__empty_${C}__`))];return A.useEffect(()=>{if(w==="wide")return;const D=v.current;if(!D)return;const C=document.activeElement;if(C&&C!==document.body&&D.contains(C))return;const L=D.querySelector(".fs-columns > .fs-col:last-child");L&&(L.tabIndex=-1,L.focus({preventScroll:!0}))},[o.length,w]),h.jsx(Tg,{children:h.jsxs("div",{ref:v,"data-pyric-ui":"fs-browser","data-fs-depth":o.length,"data-size":w,children:[h.jsx(wq,{path:o,onHome:()=>c([]),onJump:D=>c(C=>C.slice(0,D+1))}),h.jsx("div",{className:"fs-columns",children:M}),f?h.jsx(Yj,{mode:"collection",parentPath:f.parentDocPath?`/${f.parentDocPath}`:"/",onCreate:g,onClose:()=>p(null)}):null]})})}function wq({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 xq({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 Sq({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(s8,{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 _q({api:t,firestore:e,handles:n,collectionPath:r,selectedId:s,onSelect:o,onCollectionDeleted:c}){const d=A.useMemo(()=>bq(t,e,r),[t,e,r]),{documents:f,isLoading:p,error:g,subscriptionGeneration:b,hasMore:v,loadMore:w,createDocument:_}=p5({collection:d,mode:"live"}),[k,I]=A.useState([]);A.useEffect(()=>{let q=!1;return Promise.resolve(n.listDocuments(r)).then(x=>{q||I(x.filter(E=>E.phantom).map(E=>E.path.split("/").pop()??""))}).catch(()=>{q||I([])}),()=>{q=!0}},[n,r,f]);const N=A.useMemo(()=>{const q=new Set(f.map(x=>x.id));return[...f,...k.filter(x=>x.length>0&&!q.has(x)).map(x=>gq(t.doc(e,`${r}/${x}`)))]},[f,k,t,e,r]),R=r.split("/").pop()??r,[M,F]=A.useState(null),[D,C]=A.useState(!1),L=go(),U=A.useMemo(()=>tk(t,n),[t,n]),H=A.useCallback(async q=>{F(null);try{await rk({confirm:L,ref:q,api:t,recursiveImpl:U})}catch(x){F(x instanceof Error?x:new Error(String(x)))}},[t,L,U]),z=A.useCallback(async()=>{if(await L({title:`Delete collection "${R}"?`,body:"This deletes every document in it (and their subcollections).",destructive:!0,confirmLabel:"Delete collection"})){F(null);try{await nk(U,d),c()}catch(x){F(x instanceof Error?x:new Error(String(x)))}}},[L,U,d,R,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:R}),h.jsx("span",{className:"fs-phead-actions",children:h.jsx("button",{type:"button",className:"fs-add",onClick:()=>C(!0),children:"+ New"})}),h.jsx(Zj,{items:[{label:"Delete collection",onSelect:()=>void z(),destructive:!0}]})]}),D?h.jsx(Yj,{mode:"document",parentPath:`/${r}`,onCreate:async({docId:q,data:x})=>{const E=await _(q,x,{onExisting:"fail"});o(E)},onClose:()=>C(!1)}):null,h.jsx(i8,{documents:N,isLoading:p,error:g,updateScope:`${r}:${b}`,hasMore:v,onLoadMore:w,onSelect:o,renderLabel:q=>{const x=q.ref;return h.jsx("span",{"data-pyric-selected":s===x.id?"":void 0,style:{display:"contents"},children:q_(q)?h.jsxs(h.Fragment,{children:[h.jsx("span",{className:"fs-doc-phantom",children:q.id}),h.jsx("span",{className:"fs-sub fs-doc-phantom-hint",children:"missing"})]}):q.id})},renderRowAction:q=>{if(q_(q))return null;const x=q.ref;return h.jsx("button",{type:"button",className:"fs-doc-del",title:"Delete document","aria-label":`Delete ${x.id}`,onClick:E=>{E.stopPropagation(),H(x)},children:"×"})},emptyState:h.jsx("p",{className:"fs-empty",children:"No documents."})}),M?h.jsx("p",{className:"fs-empty fs-doc-del-err",children:M.message}):null]})}function Eq({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}=n5(f),v=A.useCallback(async(F,D)=>(await n.listSubcollections(D.path)).map(L=>t.collection(D,L)),[n,t]),w=go(),_=A.useMemo(()=>tk(t,n),[t,n]),[k,I]=A.useState(null),N=A.useCallback(async()=>{I(null);try{await rk({confirm:w,ref:f,api:t,recursiveImpl:_})&&d()}catch(F){I(F instanceof Error?F:new Error(String(F)))}},[t,w,_,f,d]),R=A.useCallback(async()=>{await t.setDoc(f,{})},[t,f]),M=p!=null&&mq(p);return h.jsxs("section",{"data-pyric-ui":"fs-document",className:"fs-pane fs-col doc",children:[M?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&&M?h.jsx(dq,{snapshot:p,documentRef:f,firestore:e,listSubcollections:v,onReferenceClick:o,onSubcollectionClick:s,onStartCollection:c,onDeleteDocument:()=>void N(),onDeleteDocumentFields:R,onCommit:async F=>{await t.setDoc(f,F)}},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(ek,{firestore:e,documentRef:f,listSubcollections:v,onSubcollectionClick:s})]}),k?h.jsx("p",{className:"fs-empty fs-doc-del-err",children:k.message}):null]})}const Aq="block w-full text-sm text-soft-white";function jq({auth:t,focusUid:e}){const{users:n,totalCount:r,isLoading:s,error:o,filter:c,setFilter:d,updateUser:f}=Rg(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(xj,{users:n,isLoading:s,error:o,filter:c,onSelect:v=>g(v.uid),className:Aq,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(kq,{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 kq({user:t,onSave:e}){const n=wj({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 F_(t){const e=yt(t),n=e.lastIndexOf("/");return n===-1?"":e.slice(0,n)}function z_(t,e){return t===""?e:e===""?t:`${t}/${e}`}function P_(t){const e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}const Cq=[{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 Nq(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"}),Cq.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 Oq(){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 Rq(){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 Tq(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(Oq,{}):h.jsx(Rq,{})}),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 Dq({storage:t,focusTarget:e}){var q;const n=nf(),r=e.kind==="object"?yt(e.path):null,s=e.kind==="prefix"?yt(e.path):r?F_(r):"",o=A.useCallback(x=>{const E=yt(x);n.navigate(E?{view:"storage",kind:"prefix",path:E}:{view:"storage",kind:"root"})},[n.navigate]),c=p8({path:s,onPathChange:o}),d=x=>{n.navigate({view:"storage",kind:"object",path:yt(x)})},f=h8(t,c.path),p=y8(),g=S8(t),[b,v]=A.useReducer(D8,Vj),w=A8(t,{path:c.path,list:f,onComplete:x=>v({type:"materialize",path:F_(x.fullPath)})});A.useEffect(()=>{if(f.status==="success")for(const x of f.entries)x.kind==="folder"&&U_(b,x.fullPath)&&v({type:"materialize",path:x.fullPath})},[f.status,f.entries,b]);const[_,k]=A.useState(!1),[I,N]=A.useState(""),[R,M]=A.useState(null),F=A.useRef(null),D=A.useMemo(()=>{const x=I8(b,c.path).filter(T=>!f.entries.some(P=>P.kind==="folder"&&P.name===T));if(x.length===0)return f.entries;const E=x.map(T=>{const P=z_(c.path,T);return{kind:"folder",name:T,fullPath:P,ref:{fullPath:P,name:T}}});return[...[...f.entries.filter(T=>T.kind==="folder"),...E].sort((T,P)=>T.name<P.name?-1:T.name>P.name?1:0),...f.entries.filter(T=>T.kind==="object")]},[f.entries,b,c.path]),C=D.length>0&&D.every(x=>p.isSelected(x.fullPath)),L=x=>{const E=new Set(D.map(T=>T.name)),O=T8(x.map(T=>T.relativePath),E);w.upload(x.map((T,P)=>({path:O[P],data:T.file})))},U=x=>{x.preventDefault();const E=M8(I);if(E){M(E);return}const O=z_(c.path,yt(I));v({type:"create",path:O}),c.setPath(O),N(""),M(null),k(!1)};A.useEffect(()=>p.clear(),[c.path,p.clear]);const H=w.tasks.filter(x=>x.status==="error"),z=g.verdictFor(c.path);return h.jsx(G8,{children:h.jsx(Tg,{children:h.jsxs("div",{className:"storage",children:[h.jsxs("div",{className:"storage__sub",children:[h.jsx(j8,{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(Y8,{storage:t,entries:p.selected,list:f,gate:g,className:"studio-selection-delete",onDeleted:x=>{for(const E of p.selected)E.kind==="folder"&&x.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:x=>{const E=new Set(x.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(x=>!x),M(null)},children:"New folder"}),h.jsx("button",{type:"button",className:"storage__action storage__action--upload",onClick:()=>{var x;return(x=F.current)==null?void 0:x.click()},children:"Upload files"}),h.jsx("input",{ref:F,type:"file",multiple:!0,hidden:!0,onChange:x=>{const E=Array.from(x.currentTarget.files??[]);E.length>0&&L(E.map(O=>({file:O,relativePath:O.name}))),x.currentTarget.value=""}})]})})]}),_?h.jsxs("form",{className:"storage__newfolder",onSubmit:U,children:[h.jsx("input",{autoFocus:!0,className:"storage__newfolder-input",placeholder:"folder or nested/path/of/folders","aria-label":"New folder name",value:I,onChange:x=>{N(x.currentTarget.value),M(null)},onKeyDown:x=>{x.key==="Escape"&&k(!1)}}),h.jsx("button",{type:"submit",className:"storage__newfolder-btn",children:"Create"}),R?h.jsx("span",{className:"storage__newfolder-err",role:"alert",children:R}):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: ${P_(H[0].fullPath)} — ${((q=H[0].error)==null?void 0:q.message)??"error"}`:`${H.length} uploads failed: ${H.map(x=>P_(x.fullPath)).join(", ")}`,h.jsx("button",{type:"button",className:"storage__upload-err-dismiss",onClick:w.clearCompleted,children:"Dismiss"})]}):null,h.jsxs("div",{className:"storage__body","data-storage-level":r?"inspector":"browser",children:[h.jsxs(N8,{className:"storage__browser",onFiles:L,disabled:!z.upload,disabledReason:z.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:C,onChange:x=>x.currentTarget.checked?p.selectAll(D):p.clear()})}),h.jsx("span",{children:"name"}),h.jsx("span",{children:"type"}),h.jsx("span",{children:"size"}),h.jsx("span",{children:"updated"})]}),h.jsx(k8,{entries:D,status:f.status,error:f.error,gate:g,selectedPath:r??void 0,renderEntry:Tq,renderRowAction:x=>h.jsx("label",{className:"storage__select-row",title:`Select ${x.name}`,children:h.jsx("input",{type:"checkbox","aria-label":`Select ${x.name}`,checked:p.isSelected(x.fullPath),onChange:()=>p.toggle(x)})}),onNavigate:c.enter,onSelect:x=>d(x.fullPath),emptyState:h.jsx("p",{className:"storage__empty",children:U_(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(V8,{storage:t,path:r,renderMetadata:Nq})]}):h.jsx("p",{className:"storage__inspector-hint",children:"Select an object to inspect its preview and metadata."})})]})]})})})}function Iq({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 sk({view:t}){const{target:e}=nf(),n=ri(),r=n.status==="ready"?n.handles.auth:null;return h.jsx("div",{"data-pyric-ui":"data-feature",children:n.status!=="ready"||!r?h.jsx(Iq,{view:t}):n.authApi?h.jsx(yj,{value:n.authApi,children:h.jsx(V_,{view:t,handles:n.handles,auth:r,target:e,firestoreApi:n.firestoreApi,storageApi:n.storageApi})}):h.jsx(V_,{view:t,handles:n.handles,auth:r,target:e,firestoreApi:n.firestoreApi,storageApi:n.storageApi})})}function V_({view:t,handles:e,auth:n,target:r,firestoreApi:s,storageApi:o}){const{users:c}=Rg(n),d=A.useMemo(()=>new Set(c.map(f=>f.uid)),[c]);switch(t){case"firestore":{const f=h.jsx(vq,{handles:e,knownUids:d});return s?h.jsx(t5,{value:s,children:f}):f}case"auth":return h.jsx(jq,{auth:n,focusUid:(r==null?void 0:r.view)==="auth"?r.uid:null});case"storage":{const f=h.jsx(Dq,{storage:e.storage,focusTarget:(r==null?void 0:r.view)==="storage"?r:{kind:"root"}});return o?h.jsx(f8,{value:o,children:f}):f}}}function Mq(){return h.jsx(sk,{view:"firestore"})}function Lq(){return h.jsx(sk,{view:"storage"})}function Uq(t,e){const n=new Set(e.map(r=>r.uid));return new Set([...t].filter(r=>n.has(r)))}async function $q(t,e){const n=[];for(const r of t)try{await e(r.uid)}catch{n.push(r.uid)}return n}function Bq(t){const[e,n]=A.useState(()=>new Set);A.useEffect(()=>{n(s=>{const o=Uq(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 qq({users:t,filter:e,onDelete:n,onComplete:r}){const s=go(),[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 $q(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 ik(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 ak(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 Fq(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 zq({auth:t}={}){const e=cs(),n=ri(),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(Kq,{status:e.status})});const o=h.jsx(Tg,{children:h.jsx(Pq,{auth:r})});return s?h.jsx(yj,{value:s,children:o}):o}function Pq({auth:t}){var N;const{users:e,totalCount:n,isLoading:r,error:s,filter:o,setFilter:c,createUser:d,updateUser:f,deleteUser:p}=Rg(t),g=nf(),b=((N=g.target)==null?void 0:N.view)==="auth"?g.target.uid:null,v=R=>g.navigate({view:"auth",uid:R}),w=A.useMemo(()=>e.find(R=>R.uid===b)??null,[e,b]),[_,k]=A.useState(!1),I=Bq(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:R=>c(R.target.value),placeholder:"filter users…","aria-label":"Filter users"}),h.jsx("div",{className:"auth-sub__right",children:I.selectedUsers.length>0?h.jsxs(h.Fragment,{children:[h.jsxs("span",{className:"studio-selection-count",children:[I.selectedUsers.length," selected"]}),h.jsx(qq,{users:I.selectedUsers,filter:o,onDelete:R=>Promise.resolve(p(R)),onComplete:R=>{I.replace(R),b&&!R.includes(b)&&v(null)}}),h.jsx("button",{type:"button",className:"auth-sub__clear",onClick:I.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":w||_?"detail":"list",children:[h.jsx("div",{className:"auth-list",children:h.jsx(xj,{users:e,isLoading:r,error:s,filter:o,onSelect:R=>{k(!1),v(R.uid)},renderIdentifier:Fq,formatCreatedAt:ak,formatLastLoginAt:ik,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:I.allVisibleSelected,onChange:R=>I.selectAll(R.currentTarget.checked)})}),renderSelection:R=>h.jsx("label",{className:"auth-select",title:`Select ${R.uid}`,children:h.jsx("input",{type:"checkbox","aria-label":`Select ${R.uid}`,checked:I.isSelected(R.uid),onChange:()=>I.toggle(R.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(Vq,{onCancel:()=>k(!1),onCreate:async R=>{const M=await Promise.resolve(d(R));k(!1),v(M.uid)}}):w?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(Gq,{user:w,onSave:R=>{R.mode==="edit"&&f(R.uid,R.request)},onProvidersChange:async R=>{await Promise.resolve(f(w.uid,{providerUserInfo:R}))},onDelete:()=>{p(w.uid),v(null)}},w.uid)]}):h.jsx("div",{className:"auth-detail__empty",children:h.jsx("p",{className:"auth-zero",children:"Select a user to view and edit."})})})]})]})}function Vq({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(Sj,{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 H_=[...YA];function Hq({user:t,onChange:e}){const[n,r]=A.useState(null),[s,o]=A.useState(""),c=t.providerUserInfo.map(w=>w.providerId),d=c.includes("password"),f=c.filter(w=>w!=="password"),p=f.filter(w=>!H_.includes(w)),g=w=>{r(null),e(w.map(_=>({providerId:_}))).catch(_=>{r(_ instanceof Error?_:new Error(String(_)))})},b=(w,_)=>{g(_?[...f,w]:f.filter(k=>k!==w))},v=()=>{const w=s.trim();w&&(o(""),!f.includes(w)&&g([...f,w]))};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:[...H_,...p].map(w=>h.jsxs("label",{className:"auth-provider-row","data-pyric-provider-id":w,children:[h.jsx("input",{type:"checkbox",checked:f.includes(w),onChange:_=>b(w,_.target.checked)}),h.jsx("span",{className:"auth-provider-row__label",children:Ad(w)}),h.jsx("span",{className:"auth-provider-row__id",children:w})]},w))}),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:w=>o(w.target.value),onKeyDown:w=>{w.key==="Enter"&&(w.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 Gq({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=ak(t.createdAt),g=ik(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(Hq,{user:t,onChange:n}),h.jsxs(Sj,{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(JB,{user:t,onDelete:r,className:"auth-del"})})]})}function Kq({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 Yq(t){return t.operationContext.source.kind==="studio"}function Zq(t,e){return e?t.filter(n=>!Yq(n)):[...t]}const Wq=["all","allow","deny","bypassed"];function rf(t){return t.rulesDisposition.kind==="bypassed"?"bypassed":t.rulesDisposition.kind==="evaluated"?t.rulesDisposition.verdict:null}function Qq(t,e){return e==="all"?[...t]:t.filter(n=>rf(n)===e)}function um(t){return t.rulesDisposition.kind==="evaluated"}function G_(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 Iy="inspect";function ok(t){const e=t[Iy];return e||null}function lk(t,e){const{[Iy]:n,...r}=t;return e?{...r,[Iy]:e}:r}function Jq(t,e){return lk(t,ok(t)===e?null:e)}function Xq(t){const e=Yu(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 eF(t,e,n,r){const s=Xq(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=zE(t,n);try{const c=await ck(o.sandbox,e),d=c.outcome==="allow"?RI(o,r):[];return{result:c,diff:d,lint:s}}finally{PE(o)}}async function ck(t,e){var s;const n=Vd(t.withAuth(e.auth)),r=tF(e.resourceData);try{switch(e.method){case"get":await vg(ur(n,e.path));break;case"list":case"listen":await zl(Vl(Ui(n,e.path)));break;case"create":case"set":await Pl(ur(n,e.path),r);break;case"update":await ay(ur(n,e.path),r);break;case"delete":await bd(ur(n,e.path));break;default:await wg(Ui(n,nF(e.path)),r)}return{outcome:"allow"}}catch(o){if(o instanceof nt&&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 nt?o.code:"unknown",message:o instanceof Error?o.message:String(o)}}}function tF(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:{}}function nF(t){const e=t.lastIndexOf("/");return e<0?t:t.slice(0,e)}const rF=A.lazy(()=>p1(()=>import("./RulesCodeEditor-BDlH-5lp.js"),[]));function uk(t){return h.jsx(A.Suspense,{fallback:h.jsx(sF,{value:t.value,minHeightRem:t.minHeightRem}),children:h.jsx(rF,{...t})})}function sF({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 dk({denial:t,editedRules:e,rulesSource:n,onEditedRulesChange:r,onRerunAsUser:s,onRerunAgainstRules:o}){const c=r4(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(Ja,{kind:"allow",className:"rounded bg-primary/15 px-2 py-0.5 text-xs font-semibold uppercase text-primary",children:"allowed"}):h.jsx(Ja,{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(iF,{denial:t,exp:c,rulesSource:n}),h.jsx(oF,{denial:t})]}),h.jsx(cF,{denial:t}),c.noEvaluation?null:h.jsx(hF,{denial:t,editedRules:e,onEditedRulesChange:r,onRerunAsUser:s,onRerunAgainstRules:o})]})}function iF({denial:t,exp:e,rulesSource:n}){return e.engine==="rtdb"?h.jsx(dF,{denial:t,exp:e}):e.engine==="storage"?h.jsx(fF,{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(Hs,{label:e.implicitDeny||!e.ruleNode?"matched rule":`matched rule — ${e.ruleNode}${r?` · line ${r}`:""}`,children:o?h.jsx(uk,{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(`
|
|
1217
|
+
`)||"(no trace)"})})}function oF({denial:t}){const e=c4(t);return e.length===0?null:h.jsx(Hs,{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(fk,{step:n},r))})})}const lF={true:"✓",false:"✗",skipped:"⊘",error:"!",value:"·"};function fk({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:`→ ${hk(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:lF[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(fk,{step:r},s))]})}function hk(t){if(t===void 0)return"undefined";try{return JSON.stringify(oo(t))}catch{return String(t)}}function cF({denial:t}){const e=u4(t);return h.jsx(Hs,{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(uF,{variable:n},n.name))})})}function uF({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(pk,{value:t.value}):h.jsxs("span",{className:"font-mono text-xs italic text-slate-gray",children:["absent",t.absentNote?` — ${t.absentNote}`:""]})]})}function pk({value:t,depth:e=0}){const[n,r]=A.useState(e<2),s=oo(t);if(s===null||typeof s!="object")return h.jsx("span",{className:"font-mono text-xs text-soft-white",children:hk(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(pk,{value:d,depth:e+1})]},c))}):null]})}function dF({denial:t,exp:e}){var n,r;return h.jsxs(h.Fragment,{children:[h.jsx(Hs,{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(Hs,{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(Hs,{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(Hs,{label:"simulator reason",children:h.jsx("code",{className:"font-mono text-xs text-slate-gray",children:t.rules.reason})}):null]})}function fF({exp:t}){return h.jsxs(Hs,{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(`
|
|
1218
|
+
`)||"(no trace)"})]})}function Hs({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 hF({denial:t,editedRules:e,onEditedRulesChange:n,onRerunAsUser:r,onRerunAgainstRules:s}){var _,k,I;const[o,c]=A.useState(null),[d,f]=A.useState(null),p=Z6(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(N){c({outcome:"error",code:"unknown",message:String(N)})}}}async function w(){if(s){f("pending");try{f(await s(t,e??""))}catch(N){f({result:{outcome:"error",code:"unknown",message:String(N)},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:[o4(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(K_,{support:p.impersonate,haveCallback:!!r}),o&&o!=="pending"?h.jsx(Y_,{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:w,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(uk,{value:e??"",onChange:n,markLine:(I=t.evaluatedRule)==null?void 0:I.line,markKind:t.result==="allow"?"allow":"deny",minHeightRem:14,ariaLabel:"Edited firestore.rules to test the op against"}):null,h.jsx(K_,{support:p.editedRuleset,haveCallback:!!s}),d&&d!=="pending"?h.jsxs(h.Fragment,{children:[d.lint.findings.length>0||!d.lint.parseable?h.jsx(pF,{lint:d.lint}):null,h.jsx(Y_,{result:d.result}),d.diff.length>0?h.jsx(yF,{diff:d.diff}):null]}):null]})]})}function K_({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 pF({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 Y_({result:t}){return t.outcome==="allow"?h.jsxs("p",{className:"flex items-center gap-2 text-xs",children:[h.jsx(Ja,{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(Ja,{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(Ja,{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 mF(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 yF({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=mF(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(oo(r.before))}),c?null:h.jsxs("span",{className:"ml-2 text-soft-white",children:["→ ",JSON.stringify(oo(r.after))]})]},`${r.path}-${n}`)})]})}function Z_({eventId:t,onClose:e}){const n=y4(),r=x4(),s=A4(),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 w=zE(v,s);try{return await ck(w.sandbox,b)}finally{PE(w)}},g=async(b,v)=>{const w=await r();return w?eF(w,b,v,w):{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(dk,{denial:o,editedRules:f,rulesSource:s,onEditedRulesChange:d,onRerunAsUser:p,onRerunAgainstRules:g})]})}const gF=new Intl.NumberFormat,bF={reads:"read operations",writes:"writes",deletes:"deletes"},vF={allows:"allowed requests",denies:"denied requests"};function W_(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 Q_(t){return t&&`${t[0].toUpperCase()}${t.slice(1)}`}function mk(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=`${gF.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} ${W_(p)}.`:`${Q_(W_(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:`${Q_(c(d))} accounted for ${f}% of ${e.subject} in this window.`}}function wF(t){return mk(t,{labels:bF,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 xF(t){return mk(t,{labels:vF,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 SF=new Intl.NumberFormat,_F=new Intl.DateTimeFormat(void 0,{hour:"numeric",minute:"2-digit"});function J_(t){return SF.format(t)}function bl(t){return _F.format(t)}function EF(t){return rf(t)==="bypassed"}function AF(t){return t.every(e=>e.total===0)}function yk({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(w=>{const _=new Set(w);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(kB,{series:n,visible:p,onToggle:b,formatValue:J_,className:`traffic__metric-cards traffic__metric-cards--journal traffic__metric-cards--${n.length}`}),AF(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:[bl(s.start),"–",bl(s.end)]})]}),h.jsx(OB,{points:r,series:n,visible:p,omitZeroSeries:!0,formatValue:J_,formatTime:bl,className:"traffic__chart traffic__chart--journal"}),h.jsxs("div",{className:"traffic__metric-axis","aria-hidden":"true",children:[h.jsx("span",{children:bl(s.start)}),h.jsx("span",{children:bl(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 jF({events:t,window:e}){const n=A.useMemo(()=>t.filter(o=>(o.service??"firestore")==="firestore"),[t]),r=oB({events:n,window:e,isAdmin:EF}),s=A.useMemo(()=>wF(r.series),[r.series]);return h.jsx("div",{className:"traffic__metrics","data-pyric-ui":"traffic-billable-view",children:h.jsx(yk,{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 kF({events:t,window:e}){const n=A.useMemo(()=>t.filter(c=>c.rulesDisposition.kind==="evaluated"),[t]),r=lB({events:n,window:e}),s=A.useMemo(()=>r.series.filter(c=>c.key==="allows"||c.key==="denies"),[r.series]),o=A.useMemo(()=>xF(s),[s]);return h.jsx("div",{className:"traffic__metrics","data-pyric-ui":"traffic-rules-view",children:h.jsx(yk,{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 CF=[{id:"timeline",label:"Timeline"},{id:"billable",label:"Billable metrics"},{id:"rules",label:"Rules"}];function NF(t){return t==="billable"?"billable":t==="rules"||t==="subscriptions"?"rules":"timeline"}function OF(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 RF(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:OF(n.length,r)}}function TF(t,e){return(t==null?void 0:t.start)===e.start&&t.end===e.end?null:e}function DF(){const{tab:t,query:e}=Rr();return t!=="traffic"?"timeline":NF(e.view)}function IF(){const t=A.useSyncExternalStore(ec,DF,()=>"timeline"),e=A.useCallback(n=>{const r={...Rr().query,view:n==="timeline"?void 0:n};r.view===void 0&&delete r.view,Jn({tab:"traffic",query:r})},[]);return[t,e]}function MF(){const t=A.useSyncExternalStore(ec,()=>Rr().query.hide==="studio",()=>!1),e=A.useCallback(()=>{const n={...Rr().query};n.hide==="studio"?delete n.hide:n.hide="studio",Jn({tab:"traffic",query:n})},[]);return[t,e]}function LF(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 X_(t){return`${Kl(t.start)}–${Kl(t.end)}`}function UF({event:t}){const e=rf(t);return e?h.jsx("span",{className:"traffic__verdict","data-verdict":e,children:e}):null}function $F(){return A.useSyncExternalStore(ec,()=>ok(Rr().query),()=>null)}const dm=100;function BF(){const t=m4(),[e,n]=IF(),[r,s]=MF(),o=A.useMemo(()=>Zq(t,r),[t,r]),c=t.length-o.length,[d,f]=A.useState("all"),[p,g]=A.useState(null),b=$F(),[v,w]=A.useState(dm),_=E=>{Jn({tab:"traffic",query:Jq(Rr().query,E)})},k=()=>{Jn({tab:"traffic",query:lk(Rr().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 I=A.useMemo(()=>{const E=Date.now();if(o.length===0)return{start:E-15*6e4,end:E};let O=1/0;for(const T of o)T.at<O&&(O=T.at);return{start:Math.min(O,E-6e4),end:E+1e3}},[o]),N=I.end,R=A.useMemo(()=>p?RF(o,p):null,[o,p]),M=(R==null?void 0:R.events)??o,F=A.useMemo(()=>Qq(M,d).sort((E,O)=>O.at-E.at),[M,d]),{items:D}=K4({events:F}),C=D.slice(0,v),L=D.length-C.length,U=o.length>=_d,H=o.filter(E=>E.result==="deny").length,z=E=>h.jsx(UF,{event:E}),q=E=>{if(um(E)){_(E.id);return}const O=G_(E);O&&Jn(O)},x=b!=null&&C.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:[CF.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(jF,{events:o,window:I}):e==="rules"?h.jsx(kF,{events:o,window:I}):h.jsxs(h.Fragment,{children:[h.jsx(EB,{events:o,window:I,brush:p??void 0,onBrush:E=>{g(O=>TF(O,E)),b&&k()},liveAt:I.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",U?` (showing latest ${_d})`:""]}),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:LF(E.start,N)}),h.jsx("span",{children:"now"})]}),renderBucketSummary:E=>h.jsxs("div",{className:"traffic__bucket-summary",children:[h.jsx("span",{children:X_(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."})}),R?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:X_(R.window)}),h.jsx("p",{children:R.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"}),Wq.map(E=>h.jsx("button",{type:"button",className:"traffic__filter","aria-pressed":d===E,onClick:()=>f(E),children:E},E))]}),b&&!x?h.jsx(Z_,{eventId:b,onClose:k},b):null,D.length===0?h.jsx("p",{className:"traffic__empty",children:R?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":R?"":void 0,children:[h.jsx("ul",{"data-pyric-traffic-log-items":"",children:C.map(E=>E.type==="group"?h.jsx("li",{"data-pyric-traffic-group-entry":"",children:h.jsx(SB,{group:E,onSelect:O=>{const T=O;if(um(T)){_(T.id);return}const P=G_(T);P&&Jn(P)},renderClassification:O=>z(O),formatTime:Kl})},E.key):h.jsxs("li",{"data-pyric-traffic-entry":"","data-pyric-traffic-id":E.event.id,"data-verdict":rf(E.event)??void 0,children:[h.jsx(hj,{event:E.event,selected:E.event.id===b,onSelect:O=>q(O),renderClassification:O=>z(O),formatTime:Kl}),E.event.id===b&&um(E.event)?h.jsx(Z_,{eventId:b,onClose:k},b):null]},E.event.id))}),L>0?h.jsxs("button",{type:"button",className:"traffic__show-more",onClick:()=>w(E=>E+dm),children:["Show ",Math.min(L,dm)," more (",L," hidden)"]}):null]})]})]})}const e1=["amber","teal","coral","slate","olive","plum","rust","indigo","mint","sand","ash","jade"],t1=["fox","owl","lynx","crane","otter","wren","ibex","hare","newt","moth","seal","vole"];function $g(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`${e1[e%e1.length]}-${t1[(e>>>4)%t1.length]}`}function qF(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 FF(t){return t?{tab:"firestore",rest:t.split("/").filter(Boolean)}:null}function zF(t){var s;const{provenance:e,identity:n}=qF(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:FF(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 PF(t,e=20){const n=[];for(let r=t.length-1;r>=0&&n.length<e;r--){const s=zF(t[r]);s&&n.push(s)}return n}const VF=20;function HF(t){Jn(t)}function lo({target:t,className:e,children:n,title:r}){return h.jsx("a",{className:e,href:Gd(t),title:r,onClick:s=>{s.metaKey||s.ctrlKey||s.shiftKey||s.altKey||(s.preventDefault(),HF(t))},children:n})}function GF(){const t=cs(),e=Qd(),n=Cg();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(lo,{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(lo,{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"}),$g(n)]},"instance")),h.jsx("div",{className:"studio-home__status","aria-label":"Sandbox status",children:s})}function KF(t){return new Date(t).toLocaleTimeString(void 0,{hour12:!1})}function YF(){const t=sc(),e=A.useMemo(()=>PF(t,VF),[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(lo,{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:KF(n.at)})]});return h.jsx("li",{children:n.target?h.jsx(lo,{className:"studio-home__feed-row",target:n.target,children:r}):h.jsx("span",{className:"studio-home__feed-row",children:r})},n.id)})})})]})}const ZF=["firestore","auth","rtdb","storage","traffic"];function WF(){const t=ri(),e=sc(),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:ZF.map(r=>{const s=Pi.find(o=>o.id===r);return s?h.jsxs(lo,{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 QF(){const t=Qd(),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(lo,{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 JF(){const t=ri(),e=sc(),n=cs(),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(dj,{exposeFocus:y3}),h.jsx(GF,{}),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(QF,{}):h.jsxs(h.Fragment,{children:[h.jsx(YF,{}),h.jsx(WF,{})]})})]})}function Pt(t){const e=t.split("/").filter(Boolean);return e.length===0?"/":`/${e.join("/")}`}function Hi(t){return Pt(t).split("/").filter(Boolean)}function My(t,e){return Pt([...Hi(t),...e.split("/").filter(Boolean)].join("/"))}function gk(t,e){const n=Hi(t),r=Hi(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 bk(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=bk(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 XF(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 Bg(t){return t===null||typeof t!="object"?!1:Object.keys(t).length>0}function vk(t){return t===null||typeof t!="object"?[]:Object.entries(t).sort(([e],[n])=>e.localeCompare(n,void 0,{numeric:!0}))}function wk(t,e){let n=t??null;for(const r of Hi(e)){if(n===null||typeof n!="object")return null;n=n[r]??null}return n}function ez(t){return t==null?"null":Array.isArray(t)?"array":typeof t}function Ly(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)=>Ly(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&&Ly(n[c],r[c]))}function tz(t,e){const n=new Map,r=(s,o)=>{if(!Bg(s)){n.set(o,["leaf",s??null]);return}const c=vk(s);n.set(o,["parent",c.map(([d])=>d)]);for(const[d,f]of c)r(f,My(o,d))};return r(t,Pt(e)),n}function nz(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 rz(t){const e=Hi(t);return e.map((n,r)=>({label:n,path:`/${e.slice(0,r+1).join("/")}`}))}const sz=["string","number","boolean","json"];function n1(t){switch(typeof t){case"string":return"string";case"number":return"number";case"boolean":return"boolean";default:return"json"}}function iz(t,e){return e==="json"?JSON.stringify(t??null):t==null?"":String(t)}function az(t){if(t.trim().length===0)return"Enter a key.";const e=t.match(/[.$#[\]/]/);return e?`Keys can't contain "${e[0]}".`:null}function oz(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 xk(t){return{path:Pt(t),status:"loading",value:null,error:null,expanded:{},pages:{}}}function Sk(t,e){const n=gk(t.path,e);return n===null?null:wk(t.value,n)}function lz(t,e){const n=Pt(e);return n===t.path||t.expanded[n]===!0}function cz(t,e,n){const r=vk(Sk(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 r1(t,e){const n={};let r=!1;for(const[s,o]of Object.entries(t)){const c=gk(e.path,s);c!==null&&Bg(wk(e.value,c))?n[s]=o:r=!0}return r?n:t}function _k(t,e){switch(e.type){case"navigate":{const n=Pt(e.path);return n===t.path?t:xk(n)}case"value":{if(Pt(e.path)!==t.path)return t;const n={...t,status:"live",value:bk(e.value),error:null};return n.expanded=r1(t.expanded,n),n.pages=r1(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 _k(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 uz=50;function dz(t,e,n={}){const r=n.pageSize??uz,s=Pt(e),[o,c]=A.useReducer(_k,s,xk),d=A.useMemo(()=>tz(o.value,o.path),[o.path,o.value]),f=Ug({scope:o.path,entries:d,equals:Ly,ready:o.status==="live"});o.path!==s&&c({type:"navigate",path:s}),A.useEffect(()=>{let k=!1;const I=t.subscribeValue(s,N=>{k||c({type:"value",path:s,value:N})},N=>{k||c({type:"error",path:s,message:N instanceof Error?N.message:String(N)})});return()=>{k=!0,I()}},[t,s]);const p=A.useCallback(k=>Sk(o,k),[o]),g=A.useCallback(k=>lz(o,k),[o]),b=A.useCallback(k=>cz(o,k,r),[o,r]),v=A.useCallback(k=>c({type:"toggle",path:k}),[]),w=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:w,updateAt:_}),[o,r,p,g,b,v,w,_])}function fz({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 w;v.preventDefault(),e(nz(((w=f.current)==null?void 0:w.value)??"")),d(!1)},g=()=>d(!1),b=rz(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,w)=>{const _=w===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 hz({tree:t,api:e,onNavigate:n,rootLabel:r="/",className:s}){const{state:o}=t,c=Hi(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=Bg(c),f=t.isExpanded(r),p=t.updateAt(r),[g,b]=A.useState(!1),[v,w]=A.useState(!1),[_,k]=A.useState(!1),[I,N]=A.useState(null),R=async(D,C)=>{try{await D(),N(null),C()}catch(L){N(L instanceof Error?L.message:String(L))}},M=()=>{b(!0),k(!1),d&&!f&&t.toggle(r)},F=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":ez(c),title:"Edit value",onClick:()=>{w(!0),k(!1)},children:XF(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 R(()=>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 ${s1(r)}`,title:"Add child",onClick:M,children:"+"}),h.jsx("button",{type:"button","data-rtdb-action-delete":!0,"aria-label":`Delete ${s1(r)}`,title:"Delete",onClick:()=>k(!0),children:"×"})]})})]}),I?h.jsx("p",{role:"alert","data-rtdb-error":!0,children:I}):null,v?h.jsx(i1,{initialType:n1(c),initialText:iz(c,n1(c)),submitLabel:"Save",onCancel:()=>w(!1),onSubmit:D=>R(()=>e.set(r,D),()=>w(!1))}):null,g?h.jsx(i1,{withKey:!0,initialType:"string",initialText:"",submitLabel:"Add",onCancel:()=>b(!1),onSubmit:(D,C)=>R(()=>e.set(My(r,C),D),()=>b(!1))}):null,F?h.jsxs("ul",{"data-rtdb-children":!0,children:[F.entries.map(([D])=>h.jsx("li",{children:h.jsx(Ek,{tree:t,api:e,onNavigate:n,path:My(r,D),label:D})},D)),F.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 (",F.hiddenCount," hidden)"]})}):null]}):null]})}function s1(t){const e=Hi(t);return e.length===0?"root":e[e.length-1]}function i1({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 N,R;_.preventDefault();const k=((N=c.current)==null?void 0:N.value)??"";if(t){const M=az(k);if(M){b(M);return}}const I=oz(f,((R=d.current)==null?void 0:R.value)??"");if(!I.ok){b(I.error);return}b(null),s(I.value,t?k.trim():void 0)},w=_=>{_.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:w,spellCheck:!1}):null,h.jsx("select",{"data-rtdb-editor-type":!0,"aria-label":"Value type",value:f,onChange:_=>p(_.currentTarget.value),onKeyDown:w,children:sz.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:w,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:w,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 pz(){const t=rr(),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(yz,{live:e}):h.jsx(mz,{})]})}function mz(){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 yz({live:t}){const[e,n]=A.useState("/"),r=$g(Cg()),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=dz(o,e);return h.jsxs("div",{className:"rtdb",children:[h.jsx(fz,{className:"rtdb__pathbar",path:e,onNavigate:n,rootLabel:s,inputPrefix:s}),h.jsx(hz,{className:"rtdb__tree",tree:c,api:o,onNavigate:n,rootLabel:s})]})}function gz(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 Mu(t,e,n=`${e}s`){return`${t} ${t===1?e:n}`}function bz(t){if(t===null)return"measuring…";const e=[];return t.collections&&e.push(Mu(t.collections,"collection")),t.users&&e.push(Mu(t.users,"user")),t.objects&&e.push(Mu(t.objects,"file")),t.rtdbKeys&&e.push(Mu(t.rtdbKeys,"RTDB key")),e.length?e.join(" · "):"empty — no data yet"}function sf(){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 vz(){return h.jsxs("svg",{...sf(),children:[h.jsx("path",{d:"M12 4v10"}),h.jsx("path",{d:"M8 10l4 4 4-4"}),h.jsx("path",{d:"M4 19h16"})]})}function wz(){return h.jsxs("svg",{...sf(),children:[h.jsx("path",{d:"M12 14V4"}),h.jsx("path",{d:"M8 8l4-4 4 4"}),h.jsx("path",{d:"M4 19h16"})]})}function xz(){return h.jsxs("svg",{...sf(),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 Sz(){return h.jsxs("svg",{...sf(),children:[h.jsx("path",{d:"M4 5v5h5"}),h.jsx("path",{d:"M4.6 10a8 8 0 1 0 1.7-5.3"})]})}function Lu({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 _z(){const t=w4(),e=S4(),n=_4(),r=E4(),s=Qd(),o=A.useRef(null),c=$g(Cg()),[d,f]=A.useState(!1),[p,g]=A.useState(!1),[b,v]=A.useState(!1),[w,_]=A.useState(!1),[k,I]=A.useState(""),N=uj(),{ensure:R}=N;A.useEffect(()=>R(),[R]);const M=gz(N.entries),F=bz(M),D=s.status==="ready"?s.payload.persist?"persisted to disk":"ephemeral":"in-page · resets on reload",C=async()=>{const x=await e();if(!x||typeof document>"u")return;const E=URL.createObjectURL(new Blob([x],{type:"application/json"})),O=document.createElement("a");O.href=E,O.download=`pyric-sandbox-${c||"export"}.json`,O.click(),URL.revokeObjectURL(E)},L=async x=>{var O;const E=(O=x.target.files)==null?void 0:O[0];if(x.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)}}},U=async()=>{v(!1),f(!0);try{await t()}finally{f(!1)}},H=async()=>{const x=k.trim();x&&(await r.save(x),I(""),_(!1))},z=async x=>{typeof window<"u"&&!window.confirm(`Switch to branch "${x}"? This replaces the current sandbox state.`)||await r.switchTo(x)},q=async x=>{typeof window<"u"&&!window.confirm(`Delete branch "${x}"?`)||await r.remove(x)};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:F}),h.jsx("span",{className:"studio-sandbox__persist",children:D})]}),h.jsxs("div",{className:"studio-sandbox__actions",children:[h.jsx(Lu,{glyph:h.jsx(vz,{}),name:"Export",caption:"Downloads all of this as one file.",onClick:()=>void C()}),h.jsx(Lu,{glyph:h.jsx(wz,{}),name:p?"Importing…":"Import",caption:"A chosen file replaces everything here.",disabled:p,onClick:()=>{var x;return(x=o.current)==null?void 0:x.click()}}),h.jsx(Lu,{glyph:h.jsx(xz,{}),name:"Save branch",caption:"Keeps a copy you can return to.",onClick:()=>_(x=>!x)}),h.jsx(Lu,{glyph:h.jsx(Sz,{}),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:L}),w?h.jsxs("form",{className:"studio-sandbox__name-row",onSubmit:x=>{x.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:x=>I(x.target.value),onKeyDown:x=>{x.key==="Escape"&&(_(!1),I(""))}}),h.jsx("button",{type:"submit",className:"studio-button",disabled:!k.trim(),children:"Save"}),h.jsx("button",{type:"button",className:"studio-button",onClick:()=>{_(!1),I("")},children:"Cancel"})]}):null,b?h.jsxs("div",{className:"studio-sandbox__confirm",role:"alert",children:[h.jsx("span",{className:"studio-sandbox__confirm-copy",children:M&&F!=="empty — no data yet"?`This erases ${F}.`:"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 U(),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(x=>h.jsxs("div",{className:"studio-settings__branch",children:[h.jsx("span",{className:"mono",children:x}),h.jsxs("span",{className:"studio-settings__branch-actions",children:[h.jsx("button",{type:"button",className:"studio-button",onClick:()=>void z(x),children:"Switch"}),h.jsx("button",{type:"button",className:"studio-button",onClick:()=>void q(x),children:"Delete"})]})]},x))}):h.jsx("p",{className:"studio-sandbox__branches-empty",children:"No branches yet — Save branch keeps this exact state to come back to."})]})})]})}function Uu(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 Ez(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}: ${Uu(n[c])} -> ${Uu(r[c])}`).join(", ")}return`${Uu(e.before)} -> ${Uu(e.after)}`}function Az(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:Ez(e),supported:e.qualification.supported}))}function jz(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 kz="pyric:assurance-campaign",Cz="pyric-assurance-v1",Uy=new Set;let a1=!1,o1;function l1(t){for(const e of Uy)e(t)}function c1(t){return!!t&&typeof t=="object"&&t.schema==="pyric.assurance.visualization.v1"&&typeof t.campaignId=="string"}function Nz(){if(!(a1||typeof document>"u")){a1=!0,globalThis.addEventListener(kz,t=>{const e=t.detail;c1(e)&&l1(e)});try{o1=new BroadcastChannel(Cz),o1.onmessage=t=>{c1(t.data)&&l1(t.data)}}catch{}}}function Oz(t){return Nz(),Uy.add(t),()=>Uy.delete(t)}function fm(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 Rz=[fm({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"}}),fm({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"}),fm({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"}}})],Jz=Rz.map(t=>({...t,campaignId:"collaboration-local-v1-fixed",targetHash:"fnv1a32-a9f18f23",mutation:{...t.mutation,decision:"DENY",events:[]},stateDiff:void 0,classification:"no-counterexample"}));const $y="pyric:assurance:campaigns",Ak="pyric:assurance:campaign:";function Tz(t){return!!t&&typeof t=="object"&&t.schema==="pyric.assurance.visualization.v1"&&typeof t.campaignId=="string"}function Dz(){if(typeof sessionStorage>"u")return[];try{const t=JSON.parse(sessionStorage.getItem($y)??"[]");if(!Array.isArray(t))return[];const e=t.map(n=>sessionStorage.getItem(`${Ak}${String(n)}`)).filter(n=>!!n).map(n=>JSON.parse(n)).filter(Tz);return e.length,e}catch{return[]}}function Iz(t){if(!(typeof sessionStorage>"u"))try{const e=JSON.parse(sessionStorage.getItem($y)??"[]"),n=Array.isArray(e)?e.map(String):[];n.includes(t.campaignId)||n.push(t.campaignId),sessionStorage.setItem($y,JSON.stringify(n)),sessionStorage.setItem(`${Ak}${t.campaignId}`,JSON.stringify(t))}catch{}}function Mz(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 Lz(){const[t,e]=A.useState(Dz);return A.useEffect(()=>{const r=Oz(s=>{Iz(s),e(o=>Mz(o,s))});return()=>{r()}},[]),t}function Uz(t,e){return t!==e?"assurance-verdict--mismatch":e==="ALLOW"?"assurance-verdict--allow":"assurance-verdict--deny"}function $z(t){return t.replaceAll("-"," ")}function u1({value:t}){return h.jsx("pre",{className:"assurance-evidence__json",children:JSON.stringify(t,null,2)})}function Bz(){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 d1({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 qz({campaigns:t}){var M,F,D,C,L;const e=Lz(),n=t??e,r=Rr().query,[s,o]=A.useState(r.campaign??((M=n.find(U=>U.report))==null?void 0:M.campaignId)??((F=n[0])==null?void 0:F.campaignId)??""),c=n.find(U=>U.campaignId===s)??n[0],d=A.useMemo(()=>c!=null&&c.report?Az(c.report):[],[c]),[f,p]=A.useState(r.probe??((D=d[0])==null?void 0:D.id)??"");if(A.useEffect(()=>{!s&&n[0]&&o(n[0].campaignId)},[s,n]),A.useEffect(()=>{var U;d.some(H=>H.id===f)||p(((U=d[0])==null?void 0:U.id)??"")},[d,f]),!c)return h.jsx(Bz,{});const g=(C=c.context)==null?void 0:C.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(d1,{attachment:g}),g!=null&&g.coverageGaps.length?h.jsx("ul",{className:"assurance-coverage-gaps","aria-label":"Attachment coverage gaps",children:g.coverageGaps.map(U=>h.jsxs("li",{children:[h.jsx("code",{children:U.service}),U.reason]},U.code))}):null,h.jsx("span",{className:"assurance-local-state",children:"Pyric sandboxes only | network off"})]});const v=d.find(U=>U.id===f)??d[0],w=b.results.find(U=>U.probeId===(v==null?void 0:v.id)),_=w?jz(w):null,k=(L=c.verifications)==null?void 0:L.at(-1),I=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 N(U){var q,x;o(U);const H=n.find(E=>E.campaignId===U),z=((x=(q=H==null?void 0:H.report)==null?void 0:q.results[0])==null?void 0:x.probeId)??"";p(z),xd({tab:"assurance",query:{campaign:U,probe:z||void 0}})}function R(U){p(U.id),xd({tab:"assurance",query:{campaign:c.campaignId,probe:U.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:U=>N(U.target.value),children:n.map(U=>h.jsx("option",{value:U.campaignId,children:U.campaignId},U.campaignId))})]}):null,h.jsx("span",{className:"assurance-local-state",children:"Pyric sandboxes only | network off"})]})]}),h.jsx(d1,{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--${I?"passed":"failed"}`,role:"status",children:[h.jsx("strong",{children:I?"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(U=>`${U.service}: ${U.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(U=>h.jsxs("button",{type:"button",className:"assurance-table__row","aria-pressed":U.id===(v==null?void 0:v.id),onClick:()=>R(U),role:"row",children:[h.jsxs("span",{role:"cell",children:[h.jsx("small",{children:U.service}),U.operation]}),h.jsx("span",{role:"cell",children:U.actor}),h.jsx("span",{role:"cell",className:`assurance-verdict ${U.expected==="ALLOW"?"assurance-verdict--allow":"assurance-verdict--deny"}`,children:U.expected}),h.jsx("span",{role:"cell",className:`assurance-verdict ${Uz(U.expected,U.observed)}`,children:U.observed}),h.jsx("span",{role:"cell",children:U.impact})]},U.id))]})]}),w?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--${w.classification}`,children:$z(w.classification)}),h.jsx("h2",{id:"assurance-inspector-title",children:w.probeId})]}),h.jsx("span",{children:w.actorEvidence.reachability})]}),h.jsxs("dl",{className:"assurance-facts",children:[h.jsxs("div",{children:[h.jsx("dt",{children:"Invariant"}),h.jsx("dd",{children:w.invariant.statement})]}),h.jsxs("div",{children:[h.jsx("dt",{children:"Mutation"}),h.jsx("dd",{children:w.mutationSpec.description})]}),h.jsxs("div",{children:[h.jsx("dt",{children:"Actor"}),h.jsxs("dd",{children:[w.actorEvidence.uid??w.actorEvidence.actorId," ","via ",w.actorEvidence.acquisition]})]}),h.jsxs("div",{children:[h.jsx("dt",{children:"Fidelity"}),h.jsx("dd",{children:w.qualification.supported?"Supported for this probe":"Engine gap"})]})]}),w.qualification.requirements.some(U=>!U.supported)?h.jsx("ul",{className:"assurance-gaps",children:w.qualification.requirements.filter(U=>!U.supported).map(U=>h.jsxs("li",{children:[h.jsx("code",{children:U.id}),U.reason]},U.id))}):null,w.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(u1,{value:w.stateDiff.before})]}),h.jsxs("div",{children:[h.jsx("span",{children:"After"}),h.jsx(u1,{value:w.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(dk,{denial:_})]}):h.jsx("p",{className:"assurance-no-decision",children:"This service recorded operation and state evidence but no canonical rule-decision event."})]}):null]})]})}function jk(){const t="/__pyric/ui/";return`${t.endsWith("/")?t:`${t}/`}docs`}function Fz(){const[t,e]=A.useState(!1);return A.useEffect(()=>{let n=!0;return fetch(`${jk()}/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 zz({id:t}){const e=S3(t),n=cs(),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 Pz({id:t}){switch(t){case"home":return h.jsx(JF,{});case"firestore":return h.jsx(Mq,{});case"auth":return h.jsx(zq,{});case"storage":return h.jsx(Lq,{});case"rtdb":return h.jsx(pz,{});case"traffic":return h.jsx(BF,{});case"assurance":return h.jsx(qz,{});case"settings":return h.jsx(_z,{});default:return h.jsx(zz,{id:t})}}function Vz(){const[t,e]=m3(x3,"home"),n=d=>e(d),[r,s]=A.useState(!1),o=Fz(),c=t==="home";return A.useEffect(()=>{const d=f=>{if(b3(f)){if(r){f.preventDefault(),s(!1);return}if(c){g3()&&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:[Pi.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:jk(),children:"Docs"}):null]}),h.jsx(H4,{})]})}),h.jsx("main",{className:"studio__content","data-surface":t,children:h.jsx("div",{className:"studio__surface-slot","data-active":"true",children:h.jsx(Pz,{id:t})})}),r?h.jsx(T4,{onClose:()=>s(!1)}):null]})}function Hz(){return h.jsx(u3,{children:h.jsx(fO,{children:h.jsx(i3,{mode:"local",children:h.jsx(Vz,{})})})})}const kk=document.getElementById("root");if(!kk)throw new Error("Pyric Studio: #root element not found");lO.createRoot(kk).render(h.jsx(A.StrictMode,{children:h.jsx(Hz,{})}));export{Or as G,$n as T,Pl as a,Zz as b,lr as c,ur as d,Qz as e,Y3 as f,A as g,h as j,Hl as r,Wz as s,I6 as u};
|