@pyric/cli 0.1.0-alpha.19 → 0.1.0-alpha.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -9
- package/dist/cli/index.d.ts +2 -2
- package/dist/cli/index.d.ts.map +1 -1
- package/dist/cli/index.js +48 -42
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/mcp-proxy.js +3 -3
- package/dist/cli/mcp-proxy.js.map +1 -1
- package/dist/cli/parse-args.d.ts +1 -1
- package/dist/cli/parse-args.d.ts.map +1 -1
- package/dist/cli/parse-args.js +51 -15
- package/dist/cli/parse-args.js.map +1 -1
- package/dist/cli/pyric-config.d.ts +24 -0
- package/dist/cli/pyric-config.d.ts.map +1 -0
- package/dist/cli/pyric-config.js +28 -0
- package/dist/cli/pyric-config.js.map +1 -0
- package/dist/cli/{dev-runner.d.ts → sandbox-runner.d.ts} +33 -36
- package/dist/cli/sandbox-runner.d.ts.map +1 -0
- package/dist/cli/{dev-runner.js → sandbox-runner.js} +90 -55
- package/dist/cli/sandbox-runner.js.map +1 -0
- package/dist/cli/serve.d.ts +6 -4
- package/dist/cli/serve.d.ts.map +1 -1
- package/dist/cli/serve.js +99 -40
- package/dist/cli/serve.js.map +1 -1
- package/dist/cli/snapshot.js +5 -5
- package/dist/cli/snapshot.js.map +1 -1
- package/dist/cli/verify.js +1 -1
- package/dist/cli/verify.js.map +1 -1
- package/dist/functions-rtdb/development-runtime.js +1 -1
- package/dist/functions-rtdb/development-runtime.js.map +1 -1
- package/dist/functions-rtdb/project.js +8 -8
- package/dist/functions-rtdb/project.js.map +1 -1
- package/dist/next/guard.js +1 -1
- package/dist/next/guard.js.map +1 -1
- package/dist/remote/index.d.ts +1 -1
- package/dist/remote/index.js +9 -9
- package/dist/remote/index.js.map +1 -1
- package/dist/serve/bundler.js +10 -10
- package/dist/serve/bundler.js.map +1 -1
- package/dist/serve/entries/ai.d.ts.map +1 -1
- package/dist/serve/entries/ai.js +27 -1
- package/dist/serve/entries/ai.js.map +1 -1
- package/dist/serve/entries/auth-helper-dom.js +1 -1
- package/dist/serve/entries/auth-helper-dom.js.map +1 -1
- package/dist/serve/entries/auth-helper-runtime.js +1 -1
- package/dist/serve/entries/auth-helper-runtime.js.map +1 -1
- package/dist/serve/entries/firestore.js +3 -3
- package/dist/serve/entries/firestore.js.map +1 -1
- package/dist/serve/entries/keepalive.js +1 -1
- package/dist/serve/entries/keepalive.js.map +1 -1
- package/dist/serve/entries/runtime.js +21 -14
- package/dist/serve/entries/runtime.js.map +1 -1
- package/dist/serve/entries/storage.js +1 -1
- package/dist/serve/entries/storage.js.map +1 -1
- package/dist/serve/entries/worker-runtime.js +1 -1
- package/dist/serve/entries/worker-runtime.js.map +1 -1
- package/dist/serve/init-payload.d.ts +4 -0
- package/dist/serve/init-payload.d.ts.map +1 -1
- package/dist/serve/namespace.d.ts +6 -0
- package/dist/serve/namespace.d.ts.map +1 -1
- package/dist/serve/namespace.js +36 -5
- package/dist/serve/namespace.js.map +1 -1
- package/dist/serve/rules.d.ts.map +1 -1
- package/dist/serve/rules.js +44 -21
- package/dist/serve/rules.js.map +1 -1
- package/dist/serve/runtime/chip.d.ts.map +1 -1
- package/dist/serve/runtime/chip.js +32 -1
- package/dist/serve/runtime/chip.js.map +1 -1
- package/dist/serve/runtime/manifest.d.ts +1 -1
- package/dist/serve/runtime/manifest.d.ts.map +1 -1
- package/dist/serve/runtime/manifest.js +1 -1
- package/dist/serve/runtime/manifest.js.map +1 -1
- package/dist/serve/runtime/status.d.ts.map +1 -1
- package/dist/serve/runtime/status.js +23 -0
- package/dist/serve/runtime/status.js.map +1 -1
- package/dist/serve/sandbox-session.d.ts +1 -0
- package/dist/serve/sandbox-session.d.ts.map +1 -1
- package/dist/serve/sandbox-session.js +10 -4
- package/dist/serve/sandbox-session.js.map +1 -1
- package/dist/serve/server.d.ts +7 -0
- package/dist/serve/server.d.ts.map +1 -1
- package/dist/serve/server.js +15 -1
- package/dist/serve/server.js.map +1 -1
- package/dist/serve/site-ui/404.html +1 -1
- package/dist/serve/site-ui/_astro/{RulesCodeEditor.Bl-XMkhD.js → RulesCodeEditor.XtDmHOlN.js} +1 -1
- package/dist/serve/site-ui/_astro/_slug_.Da5VLhW1.css +1 -0
- package/dist/serve/site-ui/_astro/_studio_.BnfYCKoI.css +1 -0
- package/dist/serve/site-ui/_astro/app.B52xr-DK.js +1 -0
- package/dist/serve/site-ui/_astro/app.DWBraPUw.js +12 -0
- package/dist/serve/site-ui/_astro/app.pMSnN6Qw.css +1 -0
- package/dist/serve/site-ui/_astro/{chess-showcase.Dh5D8kqe.js → chess-showcase.B72XYeoh.js} +1 -1
- package/dist/serve/site-ui/_astro/{example-runtime.CuyAjjiG.js → example-runtime.C25_lx6Z.js} +1 -1
- package/dist/serve/site-ui/_astro/index.Tb-31efc.css +1 -0
- package/dist/serve/site-ui/_astro/index.UkCBr-_0.css +1 -0
- package/dist/serve/site-ui/_astro/{sandbox-controls.BP4M5f1M.js → sandbox-controls.DEpnKg-O.js} +11 -11
- package/dist/serve/site-ui/_astro/{seed.CSUkloMi.js → seed.Co0yUJY5.js} +1 -1
- package/dist/serve/site-ui/_astro/{writes.C57paAj2.js → writes.rpjrFzmu.js} +7 -4
- package/dist/serve/site-ui/auth/index.html +5 -3
- package/dist/serve/site-ui/david-east.jpg +0 -0
- package/dist/serve/site-ui/docs/_rhythm/index.html +6 -3
- package/dist/serve/site-ui/docs/_rhythm.md +1 -1
- package/dist/serve/site-ui/docs/agent/set-up-your-agent/index.html +18 -15
- package/dist/serve/site-ui/docs/agent/set-up-your-agent.md +16 -16
- package/dist/serve/site-ui/docs/agent/watch-and-review/index.html +6 -5
- package/dist/serve/site-ui/docs/agent/watch-and-review.md +1 -5
- package/dist/serve/site-ui/docs/agent/work-with-an-agent/index.html +8 -5
- package/dist/serve/site-ui/docs/agent/work-with-an-agent.md +4 -4
- package/dist/serve/site-ui/docs/ai-compat/index.html +5 -2
- package/dist/serve/site-ui/docs/api-reference/index.html +6 -2
- package/dist/serve/site-ui/docs/api-reference.md +1 -0
- package/dist/serve/site-ui/docs/app-compat/index.html +5 -2
- package/dist/serve/site-ui/docs/auth-compat/index.html +5 -2
- package/dist/serve/site-ui/docs/build/ai-logic/index.html +5 -2
- package/dist/serve/site-ui/docs/build/authentication/index.html +7 -4
- package/dist/serve/site-ui/docs/build/authentication.md +2 -2
- package/dist/serve/site-ui/docs/build/cloud-firestore/index.html +5 -2
- package/dist/serve/site-ui/docs/build/cloud-messaging/index.html +5 -2
- package/dist/serve/site-ui/docs/build/cloud-storage/index.html +6 -3
- package/dist/serve/site-ui/docs/build/cloud-storage.md +1 -1
- package/dist/serve/site-ui/docs/build/realtime-database/index.html +9 -6
- package/dist/serve/site-ui/docs/build/realtime-database.md +4 -4
- package/dist/serve/site-ui/docs/conformance-scores/index.html +5 -2
- package/dist/serve/site-ui/docs/create-pyric-reference-api/index.html +6 -3
- package/dist/serve/site-ui/docs/create-pyric-reference-api.md +1 -1
- package/dist/serve/site-ui/docs/database-compat/index.html +5 -2
- package/dist/serve/site-ui/docs/examples/chess/index.html +5 -2
- package/dist/serve/site-ui/docs/examples/index.html +5 -2
- package/dist/serve/site-ui/docs/firestore-compat/index.html +5 -2
- package/dist/serve/site-ui/docs/functions-rtdb-compat/index.html +5 -2
- package/dist/serve/site-ui/docs/get-started/how-the-swap-works/index.html +9 -6
- package/dist/serve/site-ui/docs/get-started/how-the-swap-works.md +5 -5
- package/dist/serve/site-ui/docs/get-started/nextjs/index.html +9 -6
- package/dist/serve/site-ui/docs/get-started/nextjs.md +4 -4
- package/dist/serve/site-ui/docs/get-started/start-building/index.html +14 -9
- package/dist/serve/site-ui/docs/get-started/start-building.md +16 -10
- package/dist/serve/site-ui/docs/get-started/vite/index.html +6 -3
- package/dist/serve/site-ui/docs/get-started/vite.md +1 -1
- package/dist/serve/site-ui/docs/index.json +180 -150
- package/dist/serve/site-ui/docs/messaging-compat/index.html +5 -2
- package/dist/serve/site-ui/docs/observe/resolve-runtime-status/index.html +5 -2
- package/dist/serve/site-ui/docs/observe/see-whats-happening/index.html +6 -4
- package/dist/serve/site-ui/docs/observe/see-whats-happening.md +2 -4
- package/dist/serve/site-ui/docs/observe/shape-your-data/index.html +9 -6
- package/dist/serve/site-ui/docs/observe/shape-your-data.md +4 -4
- package/dist/serve/site-ui/docs/overview/index.html +16 -10
- package/dist/serve/site-ui/docs/overview.md +19 -11
- package/dist/serve/site-ui/docs/pyric-admin-app-reference-api/index.html +5 -2
- package/dist/serve/site-ui/docs/pyric-admin-auth-reference-api/index.html +5 -2
- package/dist/serve/site-ui/docs/pyric-admin-database-reference-api/index.html +5 -2
- package/dist/serve/site-ui/docs/pyric-admin-firestore-reference-api/index.html +8 -5
- package/dist/serve/site-ui/docs/pyric-admin-firestore-reference-api.md +3 -3
- package/dist/serve/site-ui/docs/pyric-admin-messaging-reference-api/index.html +5 -2
- package/dist/serve/site-ui/docs/pyric-admin-reference-api/index.html +501 -0
- package/dist/serve/site-ui/docs/pyric-admin-reference-api.md +587 -0
- package/dist/serve/site-ui/docs/pyric-admin-storage-reference-api/index.html +5 -2
- package/dist/serve/site-ui/docs/pyric-ai-reference-api/index.html +5 -2
- package/dist/serve/site-ui/docs/pyric-ai-scripting-reference-api/index.html +5 -2
- package/dist/serve/site-ui/docs/pyric-app-reference-api/index.html +5 -2
- package/dist/serve/site-ui/docs/pyric-auth-reference-api/index.html +5 -2
- package/dist/serve/site-ui/docs/pyric-cli-assurance-browser-reference-api/index.html +5 -2
- package/dist/serve/site-ui/docs/pyric-cli-assurance-reference-api/index.html +5 -2
- package/dist/serve/site-ui/docs/pyric-cli-bridge-client-reference-api/index.html +5 -2
- package/dist/serve/site-ui/docs/pyric-cli-bridge-reference-api/index.html +5 -2
- package/dist/serve/site-ui/docs/pyric-cli-conformance-browser-reference-api/index.html +5 -2
- package/dist/serve/site-ui/docs/pyric-cli-conformance-docs-reference-api/index.html +5 -2
- package/dist/serve/site-ui/docs/pyric-cli-conformance-reference-api/index.html +5 -2
- package/dist/serve/site-ui/docs/pyric-cli-credentials-node-reference-api/index.html +5 -2
- package/dist/serve/site-ui/docs/pyric-cli-discover-reference-api/index.html +5 -2
- package/dist/serve/site-ui/docs/pyric-cli-next-reference-api/index.html +5 -2
- package/dist/serve/site-ui/docs/pyric-cli-register-app-bridge-reference-api/index.html +5 -2
- package/dist/serve/site-ui/docs/pyric-cli-register-reference-api/index.html +5 -2
- package/dist/serve/site-ui/docs/pyric-cli-remote-reference-api/index.html +6 -3
- package/dist/serve/site-ui/docs/pyric-cli-remote-reference-api.md +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-serve-worker-reference-api/index.html +5 -2
- package/dist/serve/site-ui/docs/pyric-cli-verify-reference-api/index.html +5 -2
- package/dist/serve/site-ui/docs/pyric-cli-vite-reference-api/index.html +5 -2
- package/dist/serve/site-ui/docs/pyric-database-reference-api/index.html +166 -95
- package/dist/serve/site-ui/docs/pyric-database-reference-api.md +107 -1
- package/dist/serve/site-ui/docs/pyric-firestore-reference-api/index.html +5 -2
- package/dist/serve/site-ui/docs/pyric-messaging-reference-api/index.html +10 -4
- package/dist/serve/site-ui/docs/pyric-messaging-reference-api.md +5 -2
- package/dist/serve/site-ui/docs/pyric-messaging-sw-reference-api/index.html +10 -4
- package/dist/serve/site-ui/docs/pyric-messaging-sw-reference-api.md +5 -2
- package/dist/serve/site-ui/docs/pyric-rules-reference-api/index.html +5 -2
- package/dist/serve/site-ui/docs/pyric-sandbox-database-reference-api/index.html +5 -2
- package/dist/serve/site-ui/docs/pyric-sandbox-firestore-reference-api/index.html +6 -3
- package/dist/serve/site-ui/docs/pyric-sandbox-firestore-reference-api.md +2 -2
- package/dist/serve/site-ui/docs/pyric-sandbox-reference-api/index.html +5 -2
- package/dist/serve/site-ui/docs/pyric-storage-reference-api/index.html +5 -2
- package/dist/serve/site-ui/docs/pyric-ui-agents-reference-api/index.html +5 -2
- package/dist/serve/site-ui/docs/pyric-ui-auth-hooks-reference-api/index.html +5 -2
- package/dist/serve/site-ui/docs/pyric-ui-auth-reference-api/index.html +5 -2
- package/dist/serve/site-ui/docs/pyric-ui-events-hooks-reference-api/index.html +5 -2
- package/dist/serve/site-ui/docs/pyric-ui-events-reference-api/index.html +5 -2
- package/dist/serve/site-ui/docs/pyric-ui-firestore-hooks-reference-api/index.html +5 -2
- package/dist/serve/site-ui/docs/pyric-ui-firestore-reference-api/index.html +5 -2
- package/dist/serve/site-ui/docs/pyric-ui-primitives-reference-api/index.html +5 -2
- package/dist/serve/site-ui/docs/pyric-ui-rtdb-reference-api/index.html +5 -2
- package/dist/serve/site-ui/docs/pyric-ui-rules-hooks-reference-api/index.html +5 -2
- package/dist/serve/site-ui/docs/pyric-ui-rules-reference-api/index.html +5 -2
- package/dist/serve/site-ui/docs/pyric-ui-storage-hooks-reference-api/index.html +5 -2
- package/dist/serve/site-ui/docs/pyric-ui-storage-reference-api/index.html +5 -2
- package/dist/serve/site-ui/docs/pyric-ui-traffic-hooks-reference-api/index.html +5 -2
- package/dist/serve/site-ui/docs/pyric-ui-traffic-reference-api/index.html +5 -2
- package/dist/serve/site-ui/docs/reference/cli/index.html +153 -0
- package/dist/serve/site-ui/docs/reference/cli.md +114 -0
- package/dist/serve/site-ui/docs/rules-compat/index.html +5 -2
- package/dist/serve/site-ui/docs/secure/audit-your-rules/index.html +5 -2
- package/dist/serve/site-ui/docs/secure/firestore-rules-limits/index.html +5 -2
- package/dist/serve/site-ui/docs/secure/read-a-denial/index.html +6 -3
- package/dist/serve/site-ui/docs/secure/read-a-denial.md +1 -1
- package/dist/serve/site-ui/docs/secure/rtdb-rules-in-typescript/index.html +5 -2
- package/dist/serve/site-ui/docs/secure/rules-standard-library/index.html +5 -2
- package/dist/serve/site-ui/docs/secure/secure-it-with-rules/index.html +5 -2
- package/dist/serve/site-ui/docs/secure/simulate-and-lint/index.html +5 -2
- package/dist/serve/site-ui/docs/secure/write-a-rules-test-suite/index.html +5 -2
- package/dist/serve/site-ui/docs/ship/ship-to-production/index.html +7 -4
- package/dist/serve/site-ui/docs/ship/ship-to-production.md +2 -2
- package/dist/serve/site-ui/docs/ship/test-in-node/index.html +9 -6
- package/dist/serve/site-ui/docs/ship/test-in-node.md +4 -4
- package/dist/serve/site-ui/docs/storage-compat/index.html +5 -2
- package/dist/serve/site-ui/docs/trust/how-we-know-it-matches-firebase/index.html +5 -2
- package/dist/serve/site-ui/docs/trust/rules-standard-library/index.html +5 -2
- package/dist/serve/site-ui/docs/trust/versioning-and-compatibility/index.html +5 -2
- package/dist/serve/site-ui/docs/tutorial/index.html +10 -7
- package/dist/serve/site-ui/docs/tutorial.md +4 -4
- package/dist/serve/site-ui/examples/chess/index.html +4 -2
- package/dist/serve/site-ui/firestore/index.html +5 -3
- package/dist/serve/site-ui/hero-charcoal.jpg +0 -0
- package/dist/serve/site-ui/index.html +9 -7
- package/dist/serve/site-ui/llms.txt +4 -3
- package/dist/serve/site-ui/pyric-campfire-full.png +0 -0
- package/dist/serve/site-ui/pyric-campfire.png +0 -0
- package/dist/serve/site-ui/rtdb/index.html +5 -3
- package/dist/serve/site-ui/settings/index.html +5 -3
- package/dist/serve/site-ui/storage/index.html +5 -3
- package/dist/serve/site-ui/studio/index.html +13 -0
- package/dist/serve/site-ui/studio-routes.json +1 -1
- package/dist/serve/site-ui/traffic/index.html +5 -3
- package/dist/serve/studio/routes.d.ts +9 -0
- package/dist/serve/studio/routes.d.ts.map +1 -1
- package/dist/serve/studio/routes.js +47 -7
- package/dist/serve/studio/routes.js.map +1 -1
- package/dist/serve/vite-ai-config.d.ts.map +1 -1
- package/dist/serve/vite-ai-config.js +38 -8
- package/dist/serve/vite-ai-config.js.map +1 -1
- package/dist/serve/vite-module-swap.d.ts.map +1 -1
- package/dist/serve/vite-module-swap.js +0 -28
- package/dist/serve/vite-module-swap.js.map +1 -1
- package/dist/serve/vite-sandbox-generation.d.ts +1 -1
- package/dist/serve/vite-sandbox-generation.d.ts.map +1 -1
- package/dist/serve/vite-sandbox-generation.js +1 -1
- package/dist/serve/vite-sandbox-generation.js.map +1 -1
- package/dist/serve/worker/client/disconnect.js +1 -1
- package/dist/serve/worker/client/disconnect.js.map +1 -1
- package/dist/serve/worker/client/presence.d.ts.map +1 -1
- package/dist/serve/worker/client/presence.js +18 -5
- package/dist/serve/worker/client/presence.js.map +1 -1
- package/dist/serve/worker/host-ai.d.ts.map +1 -1
- package/dist/serve/worker/host-ai.js +15 -0
- package/dist/serve/worker/host-ai.js.map +1 -1
- package/dist/serve/worker/protocol.d.ts +4 -0
- package/dist/serve/worker/protocol.d.ts.map +1 -1
- package/dist/serve/worker/protocol.js.map +1 -1
- package/dist/serve/worker/serve-init.d.ts.map +1 -1
- package/dist/serve/worker/serve-init.js +7 -1
- package/dist/serve/worker/serve-init.js.map +1 -1
- package/package.json +5 -5
- package/src/cli/cli.test.ts +2 -2
- package/src/cli/index.ts +48 -42
- package/src/cli/mcp-proxy.ts +4 -4
- package/src/cli/parse-args.ts +61 -15
- package/src/cli/pyric-config.ts +45 -0
- package/src/cli/{dev-runner.ts → sandbox-runner.ts} +117 -72
- package/src/cli/serve.ts +115 -47
- package/src/cli/snapshot.ts +5 -5
- package/src/cli/verify.ts +1 -1
- package/src/functions-rtdb/development-runtime.ts +1 -1
- package/src/functions-rtdb/project.ts +8 -8
- package/src/next/guard.ts +1 -1
- package/src/remote/index.ts +9 -9
- package/src/serve/bundler.ts +10 -10
- package/src/serve/entries/ai.ts +27 -1
- package/src/serve/entries/auth-helper-dom.ts +1 -1
- package/src/serve/entries/auth-helper-runtime.ts +1 -1
- package/src/serve/entries/firestore.ts +3 -3
- package/src/serve/entries/keepalive.ts +1 -1
- package/src/serve/entries/runtime.ts +19 -14
- package/src/serve/entries/storage.ts +1 -1
- package/src/serve/entries/worker-runtime.ts +1 -1
- package/src/serve/init-payload.ts +4 -0
- package/src/serve/namespace.ts +44 -5
- package/src/serve/rules.ts +47 -22
- package/src/serve/runtime/chip.ts +38 -1
- package/src/serve/runtime/manifest.ts +1 -1
- package/src/serve/runtime/status.ts +24 -0
- package/src/serve/sandbox-session.ts +10 -4
- package/src/serve/server.ts +18 -1
- package/src/serve/studio/routes.ts +63 -7
- package/src/serve/vite-ai-config.ts +37 -7
- package/src/serve/vite-module-swap.ts +0 -28
- package/src/serve/vite-sandbox-generation.ts +1 -1
- package/src/serve/worker/client/disconnect.ts +1 -1
- package/src/serve/worker/client/presence.ts +25 -5
- package/src/serve/worker/host-ai.ts +15 -0
- package/src/serve/worker/protocol.ts +2 -1
- package/src/serve/worker/serve-init.ts +5 -1
- package/README.md.orig +0 -145
- package/dist/cli/dev-runner.d.ts.map +0 -1
- package/dist/cli/dev-runner.js.map +0 -1
- package/dist/serve/site-ui/_astro/_slug_.CXh9yTP1.css +0 -1
- package/dist/serve/site-ui/_astro/_slug_.CupVK4TM.css +0 -1
- package/dist/serve/site-ui/_astro/_studio_.CfxiQWkk.css +0 -1
- package/dist/serve/site-ui/_astro/app.BsFsMjn0.css +0 -1
- package/dist/serve/site-ui/_astro/app.Ce3MTLQm.js +0 -1
- package/dist/serve/site-ui/_astro/app.taqzyjD0.js +0 -11
- package/dist/serve/site-ui/docs/trust/storage-rules-stdlib-research/index.html +0 -582
- package/dist/serve/site-ui/docs/trust/storage-rules-stdlib-research.md +0 -448
package/dist/serve/site-ui/_astro/{sandbox-controls.BP4M5f1M.js → sandbox-controls.DEpnKg-O.js}
RENAMED
|
@@ -34,8 +34,8 @@ NOTE: as of Ohm v16, there is no default action for iteration nodes — see `,"
|
|
|
34
34
|
var semantics = `+n+`(grammar);
|
|
35
35
|
return semantics;
|
|
36
36
|
});
|
|
37
|
-
`),n}addOperationOrAttribute(e,r,n){const s=e+"s",i=Gs(r,e),{name:a}=i,{formals:o}=i;this.assertNewName(a,e);const c=Ic(e,a,l),u={_default:c};Object.keys(n).forEach(p=>{u[p]=n[p]});const f=e==="operation"?new dr(a,o,u,c):new jn(a,u,c);f.checkActionDict(this.grammar),this[s][a]=f;function l(...p){const y=this._semantics[s][a];if(arguments.length!==y.formals.length)throw new Error("Invalid number of arguments passed to "+a+" "+e+" (expected "+y.formals.length+", got "+arguments.length+")");const v=Object.create(null);for(const[C,k]of Object.entries(p)){const x=y.formals[C];v[x]=k}const
|
|
38
|
-
`));throw a.problems=s,a}}_topDownActionArity(e){return Ks.includes(e)?0:this.rules[e].body.getArity()}_inheritsFrom(e){let r=this.superGrammar;for(;r;){if(r.equals(e,!0))return!0;r=r.superGrammar}return!1}toRecipe(e=void 0){const r={};this.source&&(r.source=this.source.contents);let n=null;this.defaultStartRule&&(n=this.defaultStartRule);const s={};Object.keys(this.rules).forEach(o=>{const c=this.rules[o],{body:u}=c,f=!this.superGrammar||!this.superGrammar.rules[o];let l;f?l="define":l=u instanceof an?"extend":"override";const p={};if(c.source&&this.source){const
|
|
37
|
+
`),n}addOperationOrAttribute(e,r,n){const s=e+"s",i=Gs(r,e),{name:a}=i,{formals:o}=i;this.assertNewName(a,e);const c=Ic(e,a,l),u={_default:c};Object.keys(n).forEach(p=>{u[p]=n[p]});const f=e==="operation"?new dr(a,o,u,c):new jn(a,u,c);f.checkActionDict(this.grammar),this[s][a]=f;function l(...p){const y=this._semantics[s][a];if(arguments.length!==y.formals.length)throw new Error("Invalid number of arguments passed to "+a+" "+e+" (expected "+y.formals.length+", got "+arguments.length+")");const v=Object.create(null);for(const[C,k]of Object.entries(p)){const x=y.formals[C];v[x]=k}const b=this.args;this.args=v;const R=y.execute(this._semantics,this);return this.args=b,R}e==="operation"?(this.Wrapper.prototype[a]=l,this.Wrapper.prototype[a].toString=function(){return"["+a+" operation]"}):(Object.defineProperty(this.Wrapper.prototype,a,{get:l,configurable:!0}),Object.defineProperty(this.attributeKeys,a,{value:Vs(a)}))}extendOperationOrAttribute(e,r,n){const s=e+"s";if(Gs(r,"attribute"),!(this.super&&r in this.super[s]))throw new Error("Cannot extend "+e+" '"+r+"': did not inherit an "+e+" with that name");if(Fn(this[s],r))throw new Error("Cannot extend "+e+" '"+r+"' again");const i=this[s][r].formals,a=this[s][r].actionDict,o=Object.create(a);Object.keys(n).forEach(c=>{o[c]=n[c]}),this[s][r]=e==="operation"?new dr(r,i,o):new jn(r,o),this[s][r].checkActionDict(this.grammar)}assertNewName(e,r){if(Fn(Ws.prototype,e))throw new Error("Cannot add "+r+" '"+e+"': that's a reserved name");if(e in this.operations)throw new Error("Cannot add "+r+" '"+e+"': an operation with that name already exists");if(e in this.attributes)throw new Error("Cannot add "+r+" '"+e+"': an attribute with that name already exists")}wrap(e,r,n){const s=n||r;return e instanceof this.Wrapper?e:new this.Wrapper(e,r,s)}}function Gs(t,e){if(!Pe.prototypeGrammar)return wt(t.indexOf("(")===-1),{name:t,formals:[]};const r=Pe.prototypeGrammar.match(t,e==="operation"?"OperationSignature":"AttributeSignature");if(r.failed())throw new Error(r.message);return Pe.prototypeGrammarSemantics(r).parse()}function Ic(t,e,r){return function(...n){const i=(this._semantics.operations[e]||this._semantics.attributes[e]).formals.map(a=>this.args[a]);if(!this.isIteration()&&n.length===1)return r.apply(n[0],i);throw nc(this.ctorName,e,t,sr)}}Pe.createSemantics=function(t,e){const r=new Pe(t,e!==void 0?e:Pe.BuiltInSemantics._getSemantics()),n=function(i){if(!(i instanceof Sa))throw new TypeError("Semantics expected a MatchResult, but got "+fs(i));if(i.failed())throw new TypeError("cannot apply Semantics to "+i.toString());const a=i._cst;if(a.grammar!==t)throw new Error("Cannot use a MatchResult from grammar '"+a.grammar.name+"' with a semantics for '"+t.name+"'");const o=new cn(i.input);return r.wrap(a,o.interval(i._cstOffset,i.input.length))};return n.addOperation=function(s,i){return r.addOperationOrAttribute("operation",s,i),n},n.extendOperation=function(s,i){return r.extendOperationOrAttribute("operation",s,i),n},n.addAttribute=function(s,i){return r.addOperationOrAttribute("attribute",s,i),n},n.extendAttribute=function(s,i){return r.extendOperationOrAttribute("attribute",s,i),n},n._getActionDict=function(s){const i=r.operations[s]||r.attributes[s];if(!i)throw new Error('"'+s+'" is not a valid operation or attribute name in this semantics for "'+t.name+'"');return i.actionDict},n._remove=function(s){let i;return s in r.operations?(i=r.operations[s],delete r.operations[s]):s in r.attributes&&(i=r.attributes[s],delete r.attributes[s]),delete r.Wrapper.prototype[s],i},n.getOperationNames=function(){return Object.keys(r.operations)},n.getAttributeNames=function(){return Object.keys(r.attributes)},n.getGrammar=function(){return r.grammar},n.toRecipe=function(s){return r.toRecipe(s)},n.toString=r.toString.bind(r),n._getSemantics=function(){return r},n};class dr{constructor(e,r,n,s){this.name=e,this.formals=r,this.actionDict=n,this.builtInDefault=s}checkActionDict(e){e._checkTopDownActionDict(this.typeName,this.name,this.actionDict)}execute(e,r){try{const{ctorName:n}=r._node;let s=this.actionDict[n];return s?(sr.push([this,n]),s.apply(r,r._children())):r.isNonterminal()&&(s=this.actionDict._nonterminal,s)?(sr.push([this,"_nonterminal",n]),s.apply(r,r._children())):(sr.push([this,"default action",n]),this.actionDict._default.apply(r,r._children()))}finally{sr.pop()}}}dr.prototype.typeName="operation";class jn extends dr{constructor(e,r,n){super(e,[],r,n)}execute(e,r){const n=r._node,s=e.attributeKeys[this.name];return Fn(n,s)||(n[s]=dr.prototype.execute.call(this,e,r)),n[s]}}jn.prototype.typeName="attribute";const Ks=["_iter","_terminal","_nonterminal","_default"];function Zs(t){return Object.keys(t.rules).sort().map(e=>t.rules[e])}const xc=t=>t.replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029");let xa,ka;class Me{constructor(e,r,n,s){if(this.name=e,this.superGrammar=r,this.rules=n,s){if(!(s in n))throw new Error("Invalid start rule: '"+s+"' is not a rule in grammar '"+e+"'");this.defaultStartRule=s}this._matchStateInitializer=void 0,this.supportsIncrementalParsing=!0}matcher(){return new Ac(this)}isBuiltIn(){return this===Me.ProtoBuiltInRules||this===Me.BuiltInRules}equals(e){if(this===e)return!0;if(e==null||this.name!==e.name||this.defaultStartRule!==e.defaultStartRule||!(this.superGrammar===e.superGrammar||this.superGrammar.equals(e.superGrammar)))return!1;const r=Zs(this),n=Zs(e);return r.length===n.length&&r.every((s,i)=>s.description===n[i].description&&s.formals.join(",")===n[i].formals.join(",")&&s.body.toString()===n[i].body.toString())}match(e,r){const n=this.matcher();return n.replaceInputRange(0,0,e),n.match(r)}trace(e,r){const n=this.matcher();return n.replaceInputRange(0,0,e),n.trace(r)}createSemantics(){return Pe.createSemantics(this)}extendSemantics(e){return Pe.createSemantics(this,e._getSemantics())}_checkTopDownActionDict(e,r,n){const s=[];for(const i in n){const a=n[i];if(!Ks.includes(i)&&!(i in this.rules)){s.push(`'${i}' is not a valid semantic action for '${this.name}'`);continue}if(typeof a!="function"){s.push(`'${i}' must be a function in an action dictionary for '${this.name}'`);continue}const c=a.length,u=this._topDownActionArity(i);if(c!==u){let f;i==="_iter"||i==="_nonterminal"?f=`it should use a rest parameter, e.g. \`${i}(...children) {}\`. NOTE: this is new in Ohm v16 — see https://ohmjs.org/d/ati for details.`:f=`expected ${u}, got ${c}`,s.push(`Semantic action '${i}' has the wrong arity: ${f}`)}}if(s.length>0){const i=s.map(o=>"- "+o),a=new Error([`Found errors in the action dictionary of the '${r}' ${e}:`,...i].join(`
|
|
38
|
+
`));throw a.problems=s,a}}_topDownActionArity(e){return Ks.includes(e)?0:this.rules[e].body.getArity()}_inheritsFrom(e){let r=this.superGrammar;for(;r;){if(r.equals(e,!0))return!0;r=r.superGrammar}return!1}toRecipe(e=void 0){const r={};this.source&&(r.source=this.source.contents);let n=null;this.defaultStartRule&&(n=this.defaultStartRule);const s={};Object.keys(this.rules).forEach(o=>{const c=this.rules[o],{body:u}=c,f=!this.superGrammar||!this.superGrammar.rules[o];let l;f?l="define":l=u instanceof an?"extend":"override";const p={};if(c.source&&this.source){const b=c.source.relativeTo(this.source);p.sourceInterval=[b.startIdx,b.endIdx]}const y=f?c.description:null,v=u.outputRecipe(c.formals,this.source);s[o]=[l,p,y,c.formals,v]});let i="null";e?i=e:this.superGrammar&&!this.superGrammar.isBuiltIn()&&(i=this.superGrammar.toRecipe());const a=[...["grammar",r,this.name].map(JSON.stringify),i,...[n,s].map(JSON.stringify)];return xc(`[${a.join(",")}]`)}toOperationActionDictionaryTemplate(){return this._toOperationOrAttributeActionDictionaryTemplate()}toAttributeActionDictionaryTemplate(){return this._toOperationOrAttributeActionDictionaryTemplate()}_toOperationOrAttributeActionDictionaryTemplate(){const e=new Dt;e.append("{");let r=!0;for(const n in this.rules){const{body:s}=this.rules[n];r?r=!1:e.append(","),e.append(`
|
|
39
39
|
`),e.append(" "),this.addSemanticActionTemplate(n,s,e)}return e.append(`
|
|
40
40
|
}`),e.contents()}addSemanticActionTemplate(e,r,n){n.append(e),n.append(": function(");const s=this._topDownActionArity(e);n.append(sn("_",s).join(", ")),n.append(`) {
|
|
41
41
|
`),n.append(" }")}parseApplication(e){let r;if(e.indexOf("<")===-1)r=new X(e);else{const s=xa.match(e,"Base_application");r=ka(s,{})}if(!(r.ruleName in this.rules))throw ga(r.ruleName,this.name);const{formals:n}=this.rules[r.ruleName];if(n.length!==r.args.length){const{source:s}=this.rules[r.ruleName];throw ya(r.ruleName,n.length,r.args.length,s)}return r}_setUpMatchState(e){this._matchStateInitializer&&this._matchStateInitializer(e)}}Me.ProtoBuiltInRules=new Me("ProtoBuiltInRules",void 0,{any:{body:Ce,formals:[],description:"any character",primitive:!0},end:{body:Re,formals:[],description:"end of input",primitive:!0},caseInsensitive:{body:new vs(new Le(0)),formals:["str"],primitive:!0},lower:{body:new xe("Ll"),formals:[],description:"a lowercase letter",primitive:!0},upper:{body:new xe("Lu"),formals:[],description:"an uppercase letter",primitive:!0},unicodeLtmo:{body:new xe("Ltmo"),formals:[],description:"a Unicode character in Lt, Lm, or Lo",primitive:!0},spaces:{body:new Ft(new X("space")),formals:[]},space:{body:new Ne("\0"," "),formals:[],description:"a space"}});Me.initApplicationParser=function(t,e){xa=t,ka=e};class Js{constructor(e){this.name=e}sourceInterval(e,r){return this.source.subInterval(e,r-e)}ensureSuperGrammar(){return this.superGrammar||this.withSuperGrammar(this.name==="BuiltInRules"?Me.ProtoBuiltInRules:Me.BuiltInRules),this.superGrammar}ensureSuperGrammarRuleForOverriding(e,r){const n=this.ensureSuperGrammar().rules[e];if(!n)throw Wo(e,this.superGrammar.name,r);return n}installOverriddenOrExtendedRule(e,r,n,s){const i=Rn(r);if(i.length>0)throw Us(e,i,s);const a=this.ensureSuperGrammar().rules[e],o=a.formals,c=o?o.length:0;if(r.length!==c)throw ya(e,c,r.length,s);return this.install(e,r,n,a.description,s)}install(e,r,n,s,i,a=!1){return this.rules[e]={body:n.introduceParams(r),formals:r,description:s,source:i,primitive:a},this}withSuperGrammar(e){if(this.superGrammar)throw new Error("the super grammar of a GrammarDecl cannot be set more than once");return this.superGrammar=e,this.rules=Object.create(e.rules),e.isBuiltIn()||(this.defaultStartRule=e.defaultStartRule),this}withDefaultStartRule(e){return this.defaultStartRule=e,this}withSource(e){return this.source=new cn(e).interval(0,e.length),this}build(){const e=new Me(this.name,this.ensureSuperGrammar(),this.rules,this.defaultStartRule);e._matchStateInitializer=e.superGrammar._matchStateInitializer,e.supportsIncrementalParsing=e.superGrammar.supportsIncrementalParsing;const r=[];let n=!1;return Object.keys(e.rules).forEach(s=>{const{body:i}=e.rules[s];try{i.assertChoicesHaveUniformArity(s)}catch(a){r.push(a)}try{i.assertAllApplicationsAreValid(s,e)}catch(a){r.push(a),n=!0}}),n||Object.keys(e.rules).forEach(s=>{const{body:i}=e.rules[s];try{i.assertIteratedExprsAreNotNullable(e,[])}catch(a){r.push(a)}}),r.length>0&&sc(r),this.source&&(e.source=this.source),e}define(e,r,n,s,i,a){if(this.ensureSuperGrammar(),this.superGrammar.rules[e])throw $s(e,this.name,this.superGrammar.name,i);if(this.rules[e])throw $s(e,this.name,this.name,i);const o=Rn(r);if(o.length>0)throw Us(e,o,i);return this.install(e,r,n,s,i,a)}override(e,r,n,s,i){return this.ensureSuperGrammarRuleForOverriding(e,i),this.installOverriddenOrExtendedRule(e,r,n,i),this}extend(e,r,n,s,i){if(!this.ensureSuperGrammar().rules[e])throw Go(e,this.superGrammar.name,i);const o=new an(this.superGrammar,e,n);return o.source=n.source,this.installOverriddenOrExtendedRule(e,r,o,i),this}}class Tr{constructor(e){this.currentDecl=null,this.currentRuleName=null,this.options=e||{}}newGrammar(e){return new Js(e)}grammar(e,r,n,s,i){const a=new Js(r);return n&&a.withSuperGrammar(n instanceof Me?n:this.fromRecipe(n)),s&&a.withDefaultStartRule(s),e&&e.source&&a.withSource(e.source),this.currentDecl=a,Object.keys(i).forEach(o=>{this.currentRuleName=o;const c=i[o],u=c[0],f=c[1],l=c[2],p=c[3],y=this.fromRecipe(c[4]);let v;a.source&&f&&f.sourceInterval&&(v=a.source.subInterval(f.sourceInterval[0],f.sourceInterval[1]-f.sourceInterval[0])),a[u](o,p,y,l,v)}),this.currentRuleName=this.currentDecl=null,a.build()}terminal(e){return new ke(e)}range(e,r){return new Ne(e,r)}param(e){return new Le(e)}alt(...e){let r=[];for(let n of e)n instanceof V||(n=this.fromRecipe(n)),n instanceof ge?r=r.concat(n.terms):r.push(n);return r.length===1?r[0]:new ge(r)}seq(...e){let r=[];for(let n of e)n instanceof V||(n=this.fromRecipe(n)),n instanceof Se?r=r.concat(n.factors):r.push(n);return r.length===1?r[0]:new Se(r)}star(e){return e instanceof V||(e=this.fromRecipe(e)),new Ft(e)}plus(e){return e instanceof V||(e=this.fromRecipe(e)),new Yt(e)}opt(e){return e instanceof V||(e=this.fromRecipe(e)),new ht(e)}not(e){return e instanceof V||(e=this.fromRecipe(e)),new Ie(e)}lookahead(e){return e instanceof V||(e=this.fromRecipe(e)),this.options.eliminateLookaheads?new Ie(new Ie(e)):new qe(e)}lex(e){return e instanceof V||(e=this.fromRecipe(e)),new $e(e)}app(e,r){return r&&r.length>0&&(r=r.map(function(n){return n instanceof V?n:this.fromRecipe(n)},this)),new X(e,r)}splice(e,r){return new on(this.currentDecl.superGrammar,this.currentRuleName,e.map(n=>this.fromRecipe(n)),r.map(n=>this.fromRecipe(n)))}fromRecipe(e){const r=e[0]==="grammar"?e.slice(1):e.slice(2),n=this[e[0]](...r),s=e[1];return s&&s.sourceInterval&&this.currentDecl&&n.withSource(this.currentDecl.sourceInterval(...s.sourceInterval)),n}}function bs(t){return typeof t=="function"?t.call(new Tr):(typeof t=="string"&&(t=JSON.parse(t)),new Tr().fromRecipe(t))}const ws=bs(["grammar",{source:`BuiltInRules {
|
|
@@ -208,7 +208,7 @@ NOTE: as of Ohm v16, there is no default action for iteration nodes — see `,"
|
|
|
208
208
|
`],["lookahead",{sourceInterval:[1333,1337]},["terminal",{sourceInterval:[1334,1337]},"}"]]]]],name:["define",{sourceInterval:[1342,1382]},"a name",[],["seq",{sourceInterval:[1363,1382]},["app",{sourceInterval:[1363,1372]},"nameFirst",[]],["star",{sourceInterval:[1373,1382]},["app",{sourceInterval:[1373,1381]},"nameRest",[]]]]],nameFirst:["define",{sourceInterval:[1386,1418]},null,[],["alt",{sourceInterval:[1402,1418]},["terminal",{sourceInterval:[1402,1405]},"_"],["app",{sourceInterval:[1412,1418]},"letter",[]]]],nameRest:["define",{sourceInterval:[1422,1452]},null,[],["alt",{sourceInterval:[1437,1452]},["terminal",{sourceInterval:[1437,1440]},"_"],["app",{sourceInterval:[1447,1452]},"alnum",[]]]],ident:["define",{sourceInterval:[1456,1489]},"an identifier",[],["app",{sourceInterval:[1485,1489]},"name",[]]],terminal:["define",{sourceInterval:[1493,1531]},null,[],["seq",{sourceInterval:[1508,1531]},["terminal",{sourceInterval:[1508,1512]},'"'],["star",{sourceInterval:[1513,1526]},["app",{sourceInterval:[1513,1525]},"terminalChar",[]]],["terminal",{sourceInterval:[1527,1531]},'"']]],oneCharTerminal:["define",{sourceInterval:[1535,1579]},null,[],["seq",{sourceInterval:[1557,1579]},["terminal",{sourceInterval:[1557,1561]},'"'],["app",{sourceInterval:[1562,1574]},"terminalChar",[]],["terminal",{sourceInterval:[1575,1579]},'"']]],terminalChar:["define",{sourceInterval:[1583,1660]},null,[],["alt",{sourceInterval:[1602,1660]},["app",{sourceInterval:[1602,1612]},"escapeChar",[]],["seq",{sourceInterval:[1621,1660]},["not",{sourceInterval:[1621,1626]},["terminal",{sourceInterval:[1622,1626]},"\\"]],["not",{sourceInterval:[1627,1632]},["terminal",{sourceInterval:[1628,1632]},'"']],["not",{sourceInterval:[1633,1638]},["terminal",{sourceInterval:[1634,1638]},`
|
|
209
209
|
`]],["range",{sourceInterval:[1639,1660]},"\0",""]]]],escapeChar_backslash:["define",{sourceInterval:[1703,1758]},null,[],["terminal",{sourceInterval:[1703,1709]},"\\\\"]],escapeChar_doubleQuote:["define",{sourceInterval:[1765,1822]},null,[],["terminal",{sourceInterval:[1765,1771]},'\\"']],escapeChar_singleQuote:["define",{sourceInterval:[1829,1886]},null,[],["terminal",{sourceInterval:[1829,1835]},"\\'"]],escapeChar_backspace:["define",{sourceInterval:[1893,1948]},null,[],["terminal",{sourceInterval:[1893,1898]},"\\b"]],escapeChar_lineFeed:["define",{sourceInterval:[1955,2009]},null,[],["terminal",{sourceInterval:[1955,1960]},"\\n"]],escapeChar_carriageReturn:["define",{sourceInterval:[2016,2076]},null,[],["terminal",{sourceInterval:[2016,2021]},"\\r"]],escapeChar_tab:["define",{sourceInterval:[2083,2132]},null,[],["terminal",{sourceInterval:[2083,2088]},"\\t"]],escapeChar_unicodeCodePoint:["define",{sourceInterval:[2139,2243]},null,[],["seq",{sourceInterval:[2139,2221]},["terminal",{sourceInterval:[2139,2145]},"\\u{"],["app",{sourceInterval:[2146,2154]},"hexDigit",[]],["opt",{sourceInterval:[2155,2164]},["app",{sourceInterval:[2155,2163]},"hexDigit",[]]],["opt",{sourceInterval:[2165,2174]},["app",{sourceInterval:[2165,2173]},"hexDigit",[]]],["opt",{sourceInterval:[2188,2197]},["app",{sourceInterval:[2188,2196]},"hexDigit",[]]],["opt",{sourceInterval:[2198,2207]},["app",{sourceInterval:[2198,2206]},"hexDigit",[]]],["opt",{sourceInterval:[2208,2217]},["app",{sourceInterval:[2208,2216]},"hexDigit",[]]],["terminal",{sourceInterval:[2218,2221]},"}"]]],escapeChar_unicodeEscape:["define",{sourceInterval:[2250,2309]},null,[],["seq",{sourceInterval:[2250,2291]},["terminal",{sourceInterval:[2250,2255]},"\\u"],["app",{sourceInterval:[2256,2264]},"hexDigit",[]],["app",{sourceInterval:[2265,2273]},"hexDigit",[]],["app",{sourceInterval:[2274,2282]},"hexDigit",[]],["app",{sourceInterval:[2283,2291]},"hexDigit",[]]]],escapeChar_hexEscape:["define",{sourceInterval:[2316,2371]},null,[],["seq",{sourceInterval:[2316,2339]},["terminal",{sourceInterval:[2316,2321]},"\\x"],["app",{sourceInterval:[2322,2330]},"hexDigit",[]],["app",{sourceInterval:[2331,2339]},"hexDigit",[]]]],escapeChar:["define",{sourceInterval:[1664,2371]},"an escape sequence",[],["alt",{sourceInterval:[1703,2371]},["app",{sourceInterval:[1703,1709]},"escapeChar_backslash",[]],["app",{sourceInterval:[1765,1771]},"escapeChar_doubleQuote",[]],["app",{sourceInterval:[1829,1835]},"escapeChar_singleQuote",[]],["app",{sourceInterval:[1893,1898]},"escapeChar_backspace",[]],["app",{sourceInterval:[1955,1960]},"escapeChar_lineFeed",[]],["app",{sourceInterval:[2016,2021]},"escapeChar_carriageReturn",[]],["app",{sourceInterval:[2083,2088]},"escapeChar_tab",[]],["app",{sourceInterval:[2139,2221]},"escapeChar_unicodeCodePoint",[]],["app",{sourceInterval:[2250,2291]},"escapeChar_unicodeEscape",[]],["app",{sourceInterval:[2316,2339]},"escapeChar_hexEscape",[]]]],space:["extend",{sourceInterval:[2375,2394]},null,[],["app",{sourceInterval:[2387,2394]},"comment",[]]],comment_singleLine:["define",{sourceInterval:[2412,2458]},null,[],["seq",{sourceInterval:[2412,2443]},["terminal",{sourceInterval:[2412,2416]},"//"],["star",{sourceInterval:[2417,2429]},["seq",{sourceInterval:[2418,2427]},["not",{sourceInterval:[2418,2423]},["terminal",{sourceInterval:[2419,2423]},`
|
|
210
210
|
`]],["app",{sourceInterval:[2424,2427]},"any",[]]]],["lookahead",{sourceInterval:[2430,2443]},["alt",{sourceInterval:[2432,2442]},["terminal",{sourceInterval:[2432,2436]},`
|
|
211
|
-
`],["app",{sourceInterval:[2439,2442]},"end",[]]]]]],comment_multiLine:["define",{sourceInterval:[2465,2501]},null,[],["seq",{sourceInterval:[2465,2487]},["terminal",{sourceInterval:[2465,2469]},"/*"],["star",{sourceInterval:[2470,2482]},["seq",{sourceInterval:[2471,2480]},["not",{sourceInterval:[2471,2476]},["terminal",{sourceInterval:[2472,2476]},"*/"]],["app",{sourceInterval:[2477,2480]},"any",[]]]],["terminal",{sourceInterval:[2483,2487]},"*/"]]],comment:["define",{sourceInterval:[2398,2501]},null,[],["alt",{sourceInterval:[2412,2501]},["app",{sourceInterval:[2412,2443]},"comment_singleLine",[]],["app",{sourceInterval:[2465,2487]},"comment_multiLine",[]]]],tokens:["define",{sourceInterval:[2505,2520]},null,[],["star",{sourceInterval:[2514,2520]},["app",{sourceInterval:[2514,2519]},"token",[]]]],token:["define",{sourceInterval:[2524,2600]},null,[],["alt",{sourceInterval:[2532,2600]},["app",{sourceInterval:[2532,2540]},"caseName",[]],["app",{sourceInterval:[2543,2550]},"comment",[]],["app",{sourceInterval:[2553,2558]},"ident",[]],["app",{sourceInterval:[2561,2569]},"operator",[]],["app",{sourceInterval:[2572,2583]},"punctuation",[]],["app",{sourceInterval:[2586,2594]},"terminal",[]],["app",{sourceInterval:[2597,2600]},"any",[]]]],operator:["define",{sourceInterval:[2604,2669]},null,[],["alt",{sourceInterval:[2615,2669]},["terminal",{sourceInterval:[2615,2619]},"<:"],["terminal",{sourceInterval:[2622,2625]},"="],["terminal",{sourceInterval:[2628,2632]},":="],["terminal",{sourceInterval:[2635,2639]},"+="],["terminal",{sourceInterval:[2642,2645]},"*"],["terminal",{sourceInterval:[2648,2651]},"+"],["terminal",{sourceInterval:[2654,2657]},"?"],["terminal",{sourceInterval:[2660,2663]},"~"],["terminal",{sourceInterval:[2666,2669]},"&"]]],punctuation:["define",{sourceInterval:[2673,2709]},null,[],["alt",{sourceInterval:[2687,2709]},["terminal",{sourceInterval:[2687,2690]},"<"],["terminal",{sourceInterval:[2693,2696]},">"],["terminal",{sourceInterval:[2699,2702]},","],["terminal",{sourceInterval:[2705,2709]},"--"]]]}]),vn=Object.create(V.prototype);function Ys(t,e){for(const r in t)if(r===e)return!0;return!1}function Ea(t,e,r,n){const s=new Tr(n);let i,a,o,c=!1;return(r||Ss).createSemantics().addOperation("visit",{Grammars(l){return l.children.map(p=>p.visit())},Grammar(l,p,y,v,
|
|
211
|
+
`],["app",{sourceInterval:[2439,2442]},"end",[]]]]]],comment_multiLine:["define",{sourceInterval:[2465,2501]},null,[],["seq",{sourceInterval:[2465,2487]},["terminal",{sourceInterval:[2465,2469]},"/*"],["star",{sourceInterval:[2470,2482]},["seq",{sourceInterval:[2471,2480]},["not",{sourceInterval:[2471,2476]},["terminal",{sourceInterval:[2472,2476]},"*/"]],["app",{sourceInterval:[2477,2480]},"any",[]]]],["terminal",{sourceInterval:[2483,2487]},"*/"]]],comment:["define",{sourceInterval:[2398,2501]},null,[],["alt",{sourceInterval:[2412,2501]},["app",{sourceInterval:[2412,2443]},"comment_singleLine",[]],["app",{sourceInterval:[2465,2487]},"comment_multiLine",[]]]],tokens:["define",{sourceInterval:[2505,2520]},null,[],["star",{sourceInterval:[2514,2520]},["app",{sourceInterval:[2514,2519]},"token",[]]]],token:["define",{sourceInterval:[2524,2600]},null,[],["alt",{sourceInterval:[2532,2600]},["app",{sourceInterval:[2532,2540]},"caseName",[]],["app",{sourceInterval:[2543,2550]},"comment",[]],["app",{sourceInterval:[2553,2558]},"ident",[]],["app",{sourceInterval:[2561,2569]},"operator",[]],["app",{sourceInterval:[2572,2583]},"punctuation",[]],["app",{sourceInterval:[2586,2594]},"terminal",[]],["app",{sourceInterval:[2597,2600]},"any",[]]]],operator:["define",{sourceInterval:[2604,2669]},null,[],["alt",{sourceInterval:[2615,2669]},["terminal",{sourceInterval:[2615,2619]},"<:"],["terminal",{sourceInterval:[2622,2625]},"="],["terminal",{sourceInterval:[2628,2632]},":="],["terminal",{sourceInterval:[2635,2639]},"+="],["terminal",{sourceInterval:[2642,2645]},"*"],["terminal",{sourceInterval:[2648,2651]},"+"],["terminal",{sourceInterval:[2654,2657]},"?"],["terminal",{sourceInterval:[2660,2663]},"~"],["terminal",{sourceInterval:[2666,2669]},"&"]]],punctuation:["define",{sourceInterval:[2673,2709]},null,[],["alt",{sourceInterval:[2687,2709]},["terminal",{sourceInterval:[2687,2690]},"<"],["terminal",{sourceInterval:[2693,2696]},">"],["terminal",{sourceInterval:[2699,2702]},","],["terminal",{sourceInterval:[2705,2709]},"--"]]]}]),vn=Object.create(V.prototype);function Ys(t,e){for(const r in t)if(r===e)return!0;return!1}function Ea(t,e,r,n){const s=new Tr(n);let i,a,o,c=!1;return(r||Ss).createSemantics().addOperation("visit",{Grammars(l){return l.children.map(p=>p.visit())},Grammar(l,p,y,v,b){const R=l.visit();i=s.newGrammar(R),p.child(0)&&p.child(0).visit(),v.children.map(k=>k.visit());const C=i.build();if(C.source=this.source.trimmed(),Ys(e,R))throw Vo(C);return e[R]=C,C},SuperGrammar(l,p){const y=p.visit();if(y==="null")i.withSuperGrammar(null);else{if(!e||!Ys(e,y))throw zo(y,e,p.source);i.withSuperGrammar(e[y])}},Rule_define(l,p,y,v,b){a=l.visit(),o=p.children.map(x=>x.visit())[0]||[],!i.defaultStartRule&&i.ensureSuperGrammar()!==Me.ProtoBuiltInRules&&i.withDefaultStartRule(a);const R=b.visit(),C=y.children.map(x=>x.visit())[0],k=this.source.trimmed();return i.define(a,o,R,C,k)},Rule_override(l,p,y,v){a=l.visit(),o=p.children.map(C=>C.visit())[0]||[];const b=this.source.trimmed();i.ensureSuperGrammarRuleForOverriding(a,b),c=!0;const R=v.visit();return c=!1,i.override(a,o,R,null,b)},Rule_extend(l,p,y,v){a=l.visit(),o=p.children.map(C=>C.visit())[0]||[];const b=v.visit(),R=this.source.trimmed();return i.extend(a,o,b,null,R)},RuleBody(l,p){return s.alt(...p.visit()).withSource(this.source)},OverrideRuleBody(l,p){const y=p.visit(),v=y.indexOf(vn);if(v>=0){const b=y.slice(0,v),R=y.slice(v+1);return R.forEach(C=>{if(C===vn)throw ec(C)}),new on(i.superGrammar,a,b,R).withSource(this.source)}else return s.alt(...y).withSource(this.source)},Formals(l,p,y){return p.visit()},Params(l,p,y){return p.visit()},Alt(l){return s.alt(...l.visit()).withSource(this.source)},TopLevelTerm_inline(l,p){const y=a+"_"+p.visit(),v=l.visit(),b=this.source.trimmed(),R=!(i.superGrammar&&i.superGrammar.rules[y]);c&&!R?i.override(y,o,v,null,b):i.define(y,o,v,null,b);const C=o.map(k=>s.app(k));return s.app(y,C).withSource(v.source)},OverrideTopLevelTerm_superSplice(l){return vn},Seq(l){return s.seq(...l.children.map(p=>p.visit())).withSource(this.source)},Iter_star(l,p){return s.star(l.visit()).withSource(this.source)},Iter_plus(l,p){return s.plus(l.visit()).withSource(this.source)},Iter_opt(l,p){return s.opt(l.visit()).withSource(this.source)},Pred_not(l,p){return s.not(p.visit()).withSource(this.source)},Pred_lookahead(l,p){return s.lookahead(p.visit()).withSource(this.source)},Lex_lex(l,p){return s.lex(p.visit()).withSource(this.source)},Base_application(l,p){const y=p.children.map(v=>v.visit())[0]||[];return s.app(l.visit(),y).withSource(this.source)},Base_range(l,p,y){return s.range(l.visit(),y.visit()).withSource(this.source)},Base_terminal(l){return s.terminal(l.visit()).withSource(this.source)},Base_paren(l,p,y){return p.visit()},ruleDescr(l,p,y){return p.visit()},ruleDescrText(l){return this.sourceString.trim()},caseName(l,p,y,v,b){return y.visit()},name(l,p){return this.sourceString},nameFirst(l){},nameRest(l){},terminal(l,p,y){return p.children.map(v=>v.visit()).join("")},oneCharTerminal(l,p,y){return p.visit()},escapeChar(l){try{return fa(this.sourceString)}catch(p){throw p instanceof RangeError&&p.message.startsWith("Invalid code point ")?tc(l):p}},NonemptyListOf(l,p,y){return[l.visit()].concat(y.children.map(v=>v.visit()))},EmptyListOf(){return[]},_terminal(){return this.sourceString}})(t).visit()}const kc=bs(["grammar",{source:`OperationsAndAttributes {
|
|
212
212
|
|
|
213
213
|
AttributeSignature =
|
|
214
214
|
name
|
|
@@ -474,10 +474,10 @@ service cloud.firestore {
|
|
|
474
474
|
${t}
|
|
475
475
|
}
|
|
476
476
|
}`,n=_s(r);if(n===null)return null;const i=n.service.match.functions;for(const a of i)Ar(a,-3),e!==void 0&&zc(a,e);return i}const Na={"||":2,"&&":3,"==":5,"!=":5,">":6,"<":6,">=":6,"<=":6,"+":7,"-":7,"*":8,"/":8,"%":8};function Hc(t){switch(t.type){case"ternary":return 1;case"binaryOp":return Na[t.op]??0;case"inExpr":return 4;case"isExpr":return 4;case"unaryOp":return 9;default:return 100}}function Wc(t){switch(t.type){case"literal":return typeof t.value=="string"&&t.raw.startsWith('"')&&t.raw.endsWith('"')?`'${t.raw.slice(1,-1)}'`:t.raw;case"identifier":return t.name;case"memberAccess":return`${Ve(t.object,10)}.${t.property}`;case"methodCall":return`${Ve(t.object,10)}.${t.method}(${t.args.map(e=>ye(e)).join(", ")})`;case"bracketAccess":return`${Ve(t.object,10)}[${ye(t.index)}]`;case"sliceAccess":return`${Ve(t.object,10)}[${ye(t.start)}:${ye(t.end)}]`;case"binaryOp":{const e=Na[t.op]??0,r=Ve(t.left,e),n=Ve(t.right,e+1);return`${r} ${t.op} ${n}`}case"unaryOp":return`${t.op}${Ve(t.operand,9)}`;case"ternary":return`${Ve(t.condition,2)} ? ${ye(t.consequent)} : ${ye(t.alternate)}`;case"inExpr":return`${Ve(t.element,5)} in ${Ve(t.collection,5)}`;case"isExpr":return`${Ve(t.value,5)} is ${t.typeName}`;case"listLiteral":return t.elements.length===0?"[]":`[${t.elements.map(e=>ye(e)).join(", ")}]`;case"mapLiteral":return t.entries.length===0?"{}":`{${t.entries.map(e=>`${ye(e.key)}: ${ye(e.value)}`).join(", ")}}`;case"pathLiteral":return"/"+t.segments.map(e=>typeof e=="string"?e:`$(${ye(e)})`).join("/");case"functionCall":return`${t.name}(${t.args.map(e=>ye(e)).join(", ")})`}}function Ve(t,e){const r=Wc(t);return Hc(t)<e?`(${r})`:r}function ye(t){return Ve(t,0)}function Gc(t){return"/"+t.segments.map(e=>{switch(e.type){case"literal":return e.value;case"wildcard":return`{${e.name}}`;case"recursive":return`{${e.name}=**}`}}).join("/")}function Cr(t){return" ".repeat(t)}function Ht(t,e,r,n){if(t!==void 0){let i="firestore.rules";t.file!==void 0&&(i=t.file);const o={generatedLine:e,authoredLine:t.line,authoredCol:t.col,authoredFile:i};n!==void 0&&(o.expression=n),r.push(o)}}function qn(t,e,r,n){const s=Cr(e),i=Cr(e+2),a=t.parameters.join(", ");let o="";t.exported===!0&&(o="export ");const u=r.length+1;r.push(`${s}${o}function ${t.name}(${a}) {`),Ht(t.loc,u,n);for(const l of t.lets){const p=r.length+1;r.push(`${i}let ${l.name} = ${ye(l.value)};`),Ht(l.loc,p,n)}const f=r.length+1;r.push(`${i}return ${ye(t.body)};`),Ht(t.body.loc,f,n),r.push(`${s}}`)}function Kc(t,e,r,n){const s=Cr(e),i=t.operations.join(", "),a=ye(t.condition),o=r.length+1;r.push(`${s}allow ${i}: if ${a};`),Ht(t.loc,o,n,a)}function La(t,e,r,n){const s=Cr(e),i=e+2,a=r.length+1;r.push(`${s}match ${Gc(t.path)} {`),Ht(t.loc,a,n);for(const o of t.functions)qn(o,i,r,n);for(const o of t.allows)Kc(o,i,r,n);for(const o of t.children)La(o,i,r,n);r.push(`${s}}`)}function Pn(t){const e=[],r=[];for(const o of t.imports)e.push(`import { ${o.functions.join(", ")} } from '${o.module}';`);if(e.push(`rules_version = '${t.version}';`),t.functions!==void 0)for(const o of t.functions)qn(o,0,e,r);const s=e.length+1;if(e.push(`service ${t.service.name} {`),Ht(t.service.loc,s,r),t.service.functions!==void 0)for(const o of t.service.functions)qn(o,2,e,r);const a=t.service.match;return La(a,2,e,r),e.push("}"),e.push(""),{resolved:e.join(`
|
|
477
|
-
`),sourceMap:r}}function ri(t){return Pn(t).resolved}const Ir=new Set(["get","exists","getAfter","debug"]);function Rr(t,e){return t.type!=="binaryOp"||t.op!==e?0:1+Rr(t.right,e)}function $n(t){let e={op:"",depth:0};function r(s){if(s.type==="binaryOp"){const i=Rr(s,"&&"),a=Rr(s,"||");i>e.depth&&(e={op:"&&",depth:i}),a>e.depth&&(e={op:"||",depth:a}),r(s.left),r(s.right)}else n(s)}function n(s){switch(s.type){case"unaryOp":r(s.operand);break;case"methodCall":r(s.object),s.args.forEach(r);break;case"memberAccess":r(s.object);break;case"bracketAccess":r(s.object),r(s.index);break;case"ternary":r(s.condition),r(s.consequent),r(s.alternate);break;case"inExpr":r(s.element),r(s.collection);break;case"isExpr":r(s.value);break;case"listLiteral":s.elements.forEach(r);break;case"mapLiteral":s.entries.forEach(i=>{r(i.key),r(i.value)});break;case"functionCall":s.args.forEach(r);break}}return r(t),e}function ie(t){let e=1;switch(t.type){case"binaryOp":e+=ie(t.left)+ie(t.right);break;case"unaryOp":e+=ie(t.operand);break;case"methodCall":e+=ie(t.object);for(const r of t.args)e+=ie(r);break;case"memberAccess":e+=ie(t.object);break;case"bracketAccess":e+=ie(t.object)+ie(t.index);break;case"ternary":e+=ie(t.condition)+ie(t.consequent)+ie(t.alternate);break;case"inExpr":e+=ie(t.element)+ie(t.collection);break;case"isExpr":e+=ie(t.value);break;case"listLiteral":for(const r of t.elements)e+=ie(r);break;case"mapLiteral":for(const r of t.entries)e+=ie(r.key)+ie(r.value);break;case"functionCall":for(const r of t.args)e+=ie(r);break;case"pathLiteral":for(const r of t.segments)typeof r!="string"&&(e+=ie(r));break}return e}function se(t){switch(t.type){case"literal":return`L:${t.raw}`;case"identifier":return`I:${t.name}`;case"memberAccess":return`M:${se(t.object)}.${t.property}`;case"methodCall":return`MC:${se(t.object)}.${t.method}(${t.args.map(se).join(",")})`;case"bracketAccess":return`B:${se(t.object)}[${se(t.index)}]`;case"binaryOp":return`BO:${se(t.left)}${t.op}${se(t.right)}`;case"unaryOp":return`UO:${t.op}${se(t.operand)}`;case"ternary":return`T:${se(t.condition)}?${se(t.consequent)}:${se(t.alternate)}`;case"inExpr":return`IN:${se(t.element)}in${se(t.collection)}`;case"isExpr":return`IS:${se(t.value)}is${t.typeName}`;case"listLiteral":return`LL:[${t.elements.map(se).join(",")}]`;case"mapLiteral":return`ML:{${t.entries.map(e=>se(e.key)+":"+se(e.value)).join(",")}}`;case"functionCall":return`FC:${t.name}(${t.args.map(se).join(",")})`;case"pathLiteral":return`PL:${t.raw}`;case"sliceAccess":return`SL:${se(t.object)}[${se(t.start)}:${se(t.end)}]`;default:{const e=t;throw new Error(`expressionFingerprint: unhandled type ${e.type}`)}}}function Ma(t){return t.type==="binaryOp"&&t.op==="&&"?Ma(t.left):t}function Da(t){const e=new Map,r=new Set(t.map(s=>s.name));function n(s){const i=[],a=o=>{switch(o.type){case"functionCall":r.has(o.name)&&!Ir.has(o.name)&&i.push(o.name),o.args.forEach(a);break;case"binaryOp":a(o.left),a(o.right);break;case"unaryOp":a(o.operand);break;case"methodCall":a(o.object),o.args.forEach(a);break;case"memberAccess":a(o.object);break;case"bracketAccess":a(o.object),a(o.index);break;case"ternary":a(o.condition),a(o.consequent),a(o.alternate);break;case"inExpr":a(o.element),a(o.collection);break;case"isExpr":a(o.value);break;case"listLiteral":o.elements.forEach(a);break;case"mapLiteral":o.entries.forEach(c=>{a(c.key),a(c.value)});break}};return a(s),[...new Set(i)]}for(const s of t){const i=[];i.push(...n(s.body));for(const a of s.lets)i.push(...n(a.value));e.set(s.name,[...new Set(i)])}return e}function As(t,e,r=new Set){if(r.has(t))return 0;r.add(t);const n=e.get(t)||[];if(n.length===0)return 1;let s=0;for(const i of n)s=Math.max(s,As(i,e,new Set(r)));return 1+s}function Fa(t,e,r=new Set){let n=0;const s=i=>{switch(i.type){case"functionCall":if(i.name==="get"||i.name==="exists")n++;else if(e.has(i.name)&&!r.has(i.name)){r.add(i.name);const a=e.get(i.name);s(a.body);for(const o of a.lets)s(o.value)}i.args.forEach(s);break;case"binaryOp":s(i.left),s(i.right);break;case"unaryOp":s(i.operand);break;case"methodCall":s(i.object),i.args.forEach(s);break;case"memberAccess":s(i.object);break;case"bracketAccess":s(i.object),s(i.index);break;case"ternary":s(i.condition),s(i.consequent),s(i.alternate);break;case"inExpr":s(i.element),s(i.collection);break;case"isExpr":s(i.value);break;case"listLiteral":i.elements.forEach(s);break;case"mapLiteral":i.entries.forEach(a=>{s(a.key),s(a.value)});break}};return s(t),n}function Zc(t,e){const r=new Map,n=s=>{switch(s.type){case"functionCall":e.has(s.name)&&r.set(s.name,(r.get(s.name)??0)+1),s.args.forEach(n);break;case"binaryOp":n(s.left),n(s.right);break;case"unaryOp":n(s.operand);break;case"methodCall":n(s.object),s.args.forEach(n);break;case"memberAccess":n(s.object);break;case"bracketAccess":n(s.object),n(s.index);break;case"ternary":n(s.condition),n(s.consequent),n(s.alternate);break;case"inExpr":n(s.element),n(s.collection);break;case"isExpr":n(s.value);break;case"listLiteral":s.elements.forEach(n);break;case"mapLiteral":s.entries.forEach(i=>{n(i.key),n(i.value)});break}};return n(t),r}function ja(t,e,r=new Set){if(r.has(t))return!1;r.add(t);const n=e.get(t);if(!n)return!1;const s=i=>{switch(i.type){case"functionCall":return i.name==="get"||i.name==="exists"?!0:e.has(i.name)?ja(i.name,e,r):i.args.some(s);case"binaryOp":return s(i.left)||s(i.right);case"unaryOp":return s(i.operand);case"methodCall":return s(i.object)||i.args.some(s);case"memberAccess":return s(i.object);case"bracketAccess":return s(i.object)||s(i.index);case"ternary":return s(i.condition)||s(i.consequent)||s(i.alternate);case"inExpr":return s(i.element)||s(i.collection);case"isExpr":return s(i.value);case"listLiteral":return i.elements.some(s);case"mapLiteral":return i.entries.some(a=>s(a.key)||s(a.value));default:return!1}};return s(n.body)||n.lets.some(i=>s(i.value))}function Un(t,e,r=new Set){const n=s=>{switch(s.type){case"memberAccess":return s.property==="time"&&s.object.type==="identifier"&&s.object.name==="request"?!0:n(s.object);case"bracketAccess":return s.object.type==="identifier"&&s.object.name==="request"&&s.index.type==="literal"&&s.index.value==="time"?!0:n(s.object)||n(s.index);case"functionCall":if(e.has(s.name)&&!r.has(s.name)){r.add(s.name);const i=e.get(s.name);if(Un(i.body,e,r)||i.lets.some(a=>Un(a.value,e,r)))return!0}return s.args.some(n);case"binaryOp":return n(s.left)||n(s.right);case"unaryOp":return n(s.operand);case"methodCall":return n(s.object)||s.args.some(n);case"ternary":return n(s.condition)||n(s.consequent)||n(s.alternate);case"inExpr":return n(s.element)||n(s.collection);case"isExpr":return n(s.value);case"listLiteral":return s.elements.some(n);case"mapLiteral":return s.entries.some(i=>n(i.key)||n(i.value));default:return!1}};return n(t)}function qa(t){const e=[...t.functions];for(const r of t.children)e.push(...qa(r));return e}function Pa(t){const e=[];for(const r of t.allows)e.push({rule:r,path:t.path.raw,matchFunctions:t.functions});for(const r of t.children){const n=Pa(r);for(const s of n)s.matchFunctions=[...t.functions,...s.matchFunctions];e.push(...n)}return e}const Bn={where:"No equivalent in rules — restructure logic instead of filtering a list",filter:"No equivalent in rules — restructure logic instead of filtering a list",find:"No equivalent in rules",findIndex:"No equivalent in rules",map:"No equivalent in rules — lists are not transformable",reduce:"No equivalent in rules",forEach:"No equivalent in rules",every:'Use `list.hasAll([...])` for "all elements present"',some:'Use `list.hasAny([...])` for "any element present"',includes:"Use `x in list` instead of `list.includes(x)`",indexOf:"No equivalent in rules",push:"Lists are immutable in rules",pop:"Lists are immutable in rules",shift:"Lists are immutable in rules",unshift:"Lists are immutable in rules",splice:"Lists are immutable in rules",slice:"No equivalent in rules",sort:"Lists are immutable in rules",reverse:"Lists are immutable in rules",flat:"No equivalent in rules",flatMap:"No equivalent in rules",toLowerCase:"Use `.lower()` instead of `.toLowerCase()`",toUpperCase:"Use `.upper()` instead of `.toUpperCase()`",charAt:'No equivalent in rules — use `.split("")` and index',charCodeAt:"No equivalent in rules",substring:"No `.substring()` — use `.split()` and reassembly",substr:"No `.substr()` — use `.split()` and reassembly",padStart:"No equivalent in rules",padEnd:"No equivalent in rules",trimStart:"Use `.trim()` (trims both ends)",trimEnd:"Use `.trim()` (trims both ends)",toString:"Use the `string(x)` cast instead of `.toString()`"},it={Object:"No `Object` in rules — use `data.keys()` / `data.values()` directly",Array:"No `Array` in rules — test list type with `x is list`",JSON:"No `JSON` in rules — rules cannot parse or serialize JSON",Math:"No `Math` in rules — inline arithmetic or ternaries",Date:"No `Date` in rules — use `request.time` (a Timestamp)",String:"Use lowercase `string(x)` for casting",Number:"Use lowercase `int(x)` or `float(x)` for casting",Boolean:"Use direct comparison or validation instead of boolean casting",bool:"No `bool()` cast in rules — boolean casting is not supported in production Firestore rules.",parseInt:"Use `int(x)` instead",parseFloat:"Use `float(x)` instead",isNaN:"No equivalent in rules",isFinite:"No equivalent in rules",Promise:"Rules are synchronous — no Promise support",undefined:"`undefined` does not exist in rules — use `null`"},Jc=new Set(["abs","ceil","floor","round","sqrt","pow","isNaN"]),Yc=[{receiver:"request",property:"data",suggestion:"Use `request.resource.data` (the incoming write payload)"},{receiver:"request",property:"uid",suggestion:"Use `request.auth.uid`"},{receiver:"request",property:"token",suggestion:"Use `request.auth.token`"},{receiver:"request",property:"user",suggestion:"Use `request.auth` (or `request.auth.uid` for the user id)"},{receiver:"resource",property:"path",suggestion:"`resource.path` is not available — bind path captures in the match pattern"},{receiver:"resource",property:"exists",suggestion:"Use `resource != null` (or `exists()` for cross-document checks)"},{receiver:"resource",property:"id",suggestion:"`resource.id` is not available — capture the document id with `/{docId}` in the match path"}],Qc=new Set(["size","keys","values","lower","upper","trim","hasAll","hasAny","hasOnly","toSet","toUtf8"]),Xc=[{pattern:/===/,message:"Strict equality `===` is not supported in Firestore rules — use `==`."},{pattern:/!==/,message:"Strict inequality `!==` is not supported in Firestore rules — use `!=`."},{pattern:/\?\./,message:"Optional chaining `?.` is not supported — use `'field' in obj && obj.field`."},{pattern:/\?\?/,message:"Nullish coalescing `??` is not supported — use a ternary `cond ? a : b`."},{pattern:/=>/,message:"Arrow functions `=>` are not supported — define functions with `function name() { return ...; }`."},{pattern:/`[^`]*`/,message:"Backtick strings are not supported — use single or double quoted strings with `+` for concatenation."}];function eu(t){const e=[],r=t.replace(/\/\/[^\n]*/g,"").replace(/\/\*[\s\S]*?\*\//g,"");for(const n of Xc)n.pattern.test(r)&&e.push({rule:"INVALID_OPERATOR",severity:"error",message:n.message});return e}function $a(t,e){const r=t.path.raw;for(const n of t.functions){const s={matchPath:r,functionName:n.name};ue(n.body,s,e);for(const i of n.lets)ue(i.value,s,e)}for(let n=0;n<t.allows.length;n++)ue(t.allows[n].condition,{matchPath:r,ruleIndex:n},e);for(const n of t.children)$a(n,e)}function ue(t,e,r){switch(r(t,e),t.type){case"binaryOp":ue(t.left,e,r),ue(t.right,e,r);break;case"unaryOp":ue(t.operand,e,r);break;case"methodCall":ue(t.object,e,r),t.args.forEach(n=>ue(n,e,r));break;case"memberAccess":ue(t.object,e,r);break;case"bracketAccess":ue(t.object,e,r),ue(t.index,e,r);break;case"ternary":ue(t.condition,e,r),ue(t.consequent,e,r),ue(t.alternate,e,r);break;case"inExpr":ue(t.element,e,r),ue(t.collection,e,r);break;case"isExpr":ue(t.value,e,r);break;case"listLiteral":t.elements.forEach(n=>ue(n,e,r));break;case"mapLiteral":t.entries.forEach(n=>{ue(n.key,e,r),ue(n.value,e,r)});break;case"functionCall":t.args.forEach(n=>ue(n,e,r));break}}function tu(t,e){return e?!1:t.type==="functionCall"&&t.name==="debug"}function ru(t){return t.type==="methodCall"&&!!Bn[t.method]}function nu(t){return t.type!=="methodCall"||t.object.type!=="identifier"||t.object.name!=="math"?!1:!Jc.has(t.method)}function su(t){return t.type!=="methodCall"||t.method!=="hasAll"&&t.method!=="hasAny"&&t.method!=="hasOnly"?!1:t.object.type==="mapLiteral"||t.object.type==="memberAccess"&&t.object.property==="data"}function iu(t){return t.type!=="methodCall"||t.object.type!=="identifier"?!1:!!it[t.object.name]}function au(t){return t.type==="functionCall"&&!!it[t.name]}function ou(t){return t.type==="identifier"&&!!it[t.name]}function cu(t){if(t.type!=="memberAccess"||t.object.type!=="identifier")return;const e=t.object.name,r=t.property;return Yc.find(n=>n.receiver===e&&n.property===r)}function uu(t){return t.type==="memberAccess"&&t.property==="length"&&t.object.type==="methodCall"}function lu(t){return t.type!=="memberAccess"||!Qc.has(t.property)?!1:t.object.type==="identifier"&&(t.object.name==="request"||t.object.name==="resource")||t.object.type==="memberAccess"||t.object.type==="methodCall"||t.object.type==="bracketAccess"}function du(t,e={}){const r=[],n=new Set;function s(i,a,o,c){const u=`${i}|${a}|${o.matchPath||""}|${o.functionName||""}|${o.ruleIndex??""}`;n.has(u)||(n.add(u),r.push(c))}return $a(t.service.match,(i,a)=>{if(tu(i,e.allowDebug)&&s("HALLUCINATED_GLOBAL","debug",a,{rule:"HALLUCINATED_GLOBAL",severity:"error",message:"`debug()` helper is only permitted in local testing environments; remove it before deployment.",location:a,fix:"Remove debug() wrapper around the expression."}),ru(i)&&i.type==="methodCall"&&s("HALLUCINATED_METHOD",i.method,a,{rule:"HALLUCINATED_METHOD",severity:"error",message:`\`.${i.method}()\` does not exist in Firestore rules. ${Bn[i.method]}`,location:a,fix:Bn[i.method]}),nu(i)&&i.type==="methodCall"&&s("HALLUCINATED_METHOD",`math.${i.method}`,a,{rule:"HALLUCINATED_METHOD",severity:"error",message:`\`math.${i.method}()\` does not exist in production Firestore security rules.`,location:a,fix:"Use supported math namespace functions: abs, ceil, floor, round, sqrt, pow, isNaN."}),su(i)&&i.type==="methodCall"&&s("HALLUCINATED_METHOD",`map.${i.method}`,a,{rule:"HALLUCINATED_METHOD",severity:"error",message:`\`.${i.method}()\` cannot be called directly on a map in Firestore rules — call it on \`.keys()\` instead.`,location:a,fix:`Insert \`.keys()\`: e.g. \`data.keys().${i.method}(...)\`.`}),iu(i)&&i.type==="methodCall"&&i.object.type==="identifier"){const c=i.object.name;s("HALLUCINATED_GLOBAL",`${c}.${i.method}`,a,{rule:"HALLUCINATED_GLOBAL",severity:"error",message:`\`${c}.${i.method}()\` does not exist in Firestore rules. ${it[c]}`,location:a,fix:it[c]})}au(i)&&i.type==="functionCall"&&s("HALLUCINATED_GLOBAL",i.name,a,{rule:"HALLUCINATED_GLOBAL",severity:"error",message:`\`${i.name}()\` does not exist in Firestore rules. ${it[i.name]}`,location:a,fix:it[i.name]}),ou(i)&&i.type==="identifier"&&s("HALLUCINATED_GLOBAL",`ref:${i.name}`,a,{rule:"HALLUCINATED_GLOBAL",severity:"error",message:`\`${i.name}\` is not a Firestore rules identifier. ${it[i.name]}`,location:a,fix:it[i.name]});const o=cu(i);if(o&&i.type==="memberAccess"&&i.object.type==="identifier"){const c=i.object.name,u=i.property;s("WRONG_CONTEXT_PATH",`${c}.${u}`,a,{rule:"WRONG_CONTEXT_PATH",severity:"error",message:`\`${c}.${u}\` is not a valid Firestore rules path. ${o.suggestion}`,location:a,fix:o.suggestion})}if(uu(i)&&s("LENGTH_PROPERTY","",a,{rule:"LENGTH_PROPERTY",severity:"error",message:"`.length` is not a valid property in Firestore rules — use `.size()` (a method, with parentheses).",location:a,fix:"Replace `.length` with `.size()`."}),i.type==="pathLiteral")for(const c of i.segments){if(typeof c!="string")continue;const u=c.match(/^\{([A-Za-z_][A-Za-z0-9_]*)\}$/);if(!u)continue;const f=u[1];s("INVALID_PATH_INTERPOLATION",`${i.raw}|${f}`,a,{rule:"INVALID_PATH_INTERPOLATION",severity:"error",message:`\`{${f}}\` is not valid inside a path literal — Firestore rejects this at deploy. The \`{var}\` syntax is for match statement wildcards (e.g. \`match /users/{userId}\`); path interpolation in get()/exists()/getAfter()/existsAfter() requires \`$(var)\`. Replace \`{${f}}\` with \`$(${f})\` in path \`${i.raw}\`.`,location:a,fix:`Replace \`{${f}}\` with \`$(${f})\` inside the path argument.`})}lu(i)&&i.type==="memberAccess"&&s("METHOD_MISSING_PARENS",i.property,a,{rule:"METHOD_MISSING_PARENS",severity:"warning",message:`\`.${i.property}\` looks like a built-in method called without parentheses. Use \`.${i.property}()\` if you meant to invoke it (otherwise this is a field access).`,location:a,fix:`Add parentheses: \`.${i.property}()\`.`})}),r}const pe={SOURCE_SIZE:256*1024,CHAIN_DEPTH_ERROR:95,CHAIN_DEPTH_WARN:85,CHAIN_DEPTH_LIMIT:98,LET_LIMIT:11,RUNTIME_BUDGET:{low:{calls:2,warn:100},mid:{calls:4,warn:60},high:{warn:40}},CALL_DEPTH_WARN:6,CALL_DEPTH_ERROR:10,GET_COUNT_WARN:5,GET_COUNT_ERROR:10};function hu(t,e){t.length>pe.SOURCE_SIZE&&e.push({rule:"SOURCE_SIZE",severity:"error",message:`Rules source is ${(t.length/1024).toFixed(0)} KB, exceeding the 256 KB limit.`,fix:"Reduce string literals, remove comments, or split into smaller match blocks."})}function fu(t,e){for(const r of t)r.lets.length>pe.LET_LIMIT&&e.push({rule:"LET_LIMIT",severity:"error",message:`Function '${r.name}' has ${r.lets.length} let bindings. Limit is ${pe.LET_LIMIT}.`,location:{functionName:r.name},fix:"Inline some let expressions into the return statement, or split the function."})}function pu(t,e){for(const r of t){const n=$n(r.body);for(const s of r.lets){const i=$n(s.value);i.depth>n.depth&&(n.depth=i.depth,n.op=i.op)}n.depth>=pe.CHAIN_DEPTH_LIMIT?e.push({rule:"CHAIN_DEPTH",severity:"error",message:`Function '${r.name}' has a ${n.op} chain of depth ${n.depth}. Limit is ${pe.CHAIN_DEPTH_LIMIT}.`,location:{functionName:r.name},fix:"Split into nested groups: 'a && b && c && d' → '(a && b) && (c && d)' to halve chain depth."}):n.depth>=pe.CHAIN_DEPTH_ERROR?e.push({rule:"CHAIN_DEPTH",severity:"error",message:`Function '${r.name}' has a ${n.op} chain of depth ${n.depth}. Limit is ${pe.CHAIN_DEPTH_LIMIT}. Approaching failure.`,location:{functionName:r.name},fix:"Split the chain into nested groups to reduce depth."}):n.depth>=pe.CHAIN_DEPTH_WARN&&e.push({rule:"CHAIN_DEPTH",severity:"warning",message:`Function '${r.name}' has a ${n.op} chain of depth ${n.depth}. Limit is ${pe.CHAIN_DEPTH_LIMIT}.`,location:{functionName:r.name}})}}function mu(t,e){const r=new Map;for(let n=0;n<t.length;n++){const s=t[n];if(!s.rule.operations.some(o=>o==="update"||o==="write"))continue;const i=se(Ma(s.rule.condition)),a=s.path;r.has(a)||r.set(a,[]),r.get(a).push({index:n,gate:i,ops:s.rule.operations})}for(const[n,s]of r){const i=new Map;for(const a of s)i.has(a.gate)||i.set(a.gate,[]),i.get(a.gate).push(a.index);for(const[a,o]of i)o.length>=2&&e.push({rule:"SHARED_GATE",severity:"warning",message:`${o.length} allow rules in '${n}' share the same gate expression. This may cause cross-rule budget exhaustion. Rules: ${o.join(", ")}.`,location:{matchPath:n},fix:"Assign unique moveType or discriminator values so each rule has a unique first expression."})}}function gu(t,e){let r=ie(t);const n=new Set;function s(i){if(i.type==="functionCall"&&e.has(i.name)&&!n.has(i.name)){n.add(i.name);const a=e.get(i.name);r+=ie(a.body);for(const o of a.lets)r+=ie(o.value);s(a.body);for(const o of a.lets)s(o.value)}switch(i.type){case"binaryOp":s(i.left),s(i.right);break;case"unaryOp":s(i.operand);break;case"methodCall":s(i.object),i.args.forEach(s);break;case"memberAccess":s(i.object);break;case"bracketAccess":s(i.object),s(i.index);break;case"ternary":s(i.condition),s(i.consequent),s(i.alternate);break;case"inExpr":s(i.element),s(i.collection);break;case"isExpr":s(i.value);break;case"listLiteral":i.elements.forEach(s);break;case"mapLiteral":i.entries.forEach(a=>{s(a.key),s(a.value)});break;case"functionCall":i.args.forEach(s);break}}return s(t),{totalExprs:r,callCount:n.size}}function yu(t,e,r){const n=new Map;for(const s of e)n.set(s.name,s);for(let s=0;s<t.length;s++){const{totalExprs:i,callCount:a}=gu(t[s].rule.condition,n),o=Rr(t[s].rule.condition,"||"),c=o>5?.3:o>2?.5:1,u=Math.round(i*c),f=a<=pe.RUNTIME_BUDGET.low.calls?pe.RUNTIME_BUDGET.low:a<=pe.RUNTIME_BUDGET.mid.calls?pe.RUNTIME_BUDGET.mid:pe.RUNTIME_BUDGET.high;u>=f.warn&&r.push({rule:"EXPRESSION_BUDGET",severity:"warning",message:`Rule #${s} has ~${i} expression nodes across ${a} function calls. Runtime budget is non-deterministic; actual evaluation depends on short-circuit behavior.`,location:{ruleIndex:s},fix:"If this rule fails at runtime (403), reduce function calls or expression count."})}}function vu(t,e,r){const n=Da(e),s=new Map;for(const i of e)s.set(i.name,i);for(let i=0;i<t.length;i++){let a=0;const o=c=>{if(c.type==="functionCall"&&s.has(c.name)){const u=As(c.name,n);u>a&&(a=u)}switch(c.type){case"binaryOp":o(c.left),o(c.right);break;case"unaryOp":o(c.operand);break;case"methodCall":o(c.object),c.args.forEach(o);break;case"memberAccess":o(c.object);break;case"bracketAccess":o(c.object),o(c.index);break;case"ternary":o(c.condition),o(c.consequent),o(c.alternate);break;case"inExpr":o(c.element),o(c.collection);break;case"functionCall":c.args.forEach(o);break}};o(t[i].rule.condition),a>=pe.CALL_DEPTH_ERROR?r.push({rule:"CALL_DEPTH",severity:"error",message:`Rule #${i} has a function call chain of depth ${a}. May exceed call budget.`,location:{ruleIndex:i},fix:"Inline intermediate functions to reduce call depth."}):a>=pe.CALL_DEPTH_WARN&&r.push({rule:"CALL_DEPTH",severity:"warning",message:`Rule #${i} has a function call chain of depth ${a}.`,location:{ruleIndex:i}})}}function bu(t,e,r){const n=new Map;for(const s of e)n.set(s.name,s);for(let s=0;s<t.length;s++){const i=Fa(t[s].rule.condition,n);i>=pe.GET_COUNT_ERROR?r.push({rule:"GET_COUNT",severity:"error",message:`Rule #${s} may invoke ${i} get()/exists() calls. Limit is ${pe.GET_COUNT_ERROR}.`,location:{ruleIndex:s},fix:"Cache get() results via a config() wrapper function. Same-path calls are cached by Firestore."}):i>=pe.GET_COUNT_WARN&&r.push({rule:"GET_COUNT",severity:"warning",message:`Rule #${s} invokes ${i} get()/exists() calls. Limit is ${pe.GET_COUNT_ERROR}.`,location:{ruleIndex:s}})}}function wu(t,e,r){const n=new Map;for(const i of e)n.set(i.name,i);const s=new Set(e.map(i=>i.name));for(let i=0;i<t.length;i++){const a=Zc(t[i].rule.condition,s);for(const[o,c]of a)c>=2&&ja(o,n)&&r.push({rule:"GET_DUPLICATION",severity:"warning",message:`Function '${o}' (contains get/exists) is called ${c} times in rule #${i}. Cache the result with a let binding in a wrapper function to reduce get() calls from ${c} to 1.`,location:{ruleIndex:i},fix:`Create a wrapper: function verifyAll(ret) { let c = ${o}(); return verify1(ret, c) && verify2(ret, c) && ...; }`})}}function Su(t,e,r,n){const s=new Map;for(const o of e)s.set(o.name,o);const i=new Set;for(let o=0;o<t.length;o++)Un(t[o].rule.condition,s)&&i.add(o);if(i.size===0)return;function a(o,c){const u=o.split("/").filter(Boolean),f=c.split("/").filter(Boolean);if(u.length!==f.length)return!1;for(let l=0;l<u.length;l++){const p=u[l];if(!(p.startsWith("{")&&p.endsWith("}"))&&p!==f[l])return!1}return!0}for(const o of r)if(!o.requestTime)for(const c of i)a(t[c].path,o.path)&&n.push({rule:"REQUEST_TIME_NOT_PINNED",severity:"warning",message:`Test case "${o.description}" targets rule #${c} (path '${t[c].path}') which reads request.time, but does not set requestTime. Result is non-deterministic across runs.`,location:{ruleIndex:c,matchPath:t[c].path,testCaseDescription:o.description},fix:"Set requestTime on this TestCase to an ISO-8601 timestamp so the rule evaluates deterministically."})}function or(t){if(t.type==="literal"&&typeof t.value=="boolean")return t.value;if(t.type==="binaryOp"){const e=or(t.left),r=or(t.right);if(t.op==="&&")return e===!1||r===!1?!1:e===!0&&r===!0?!0:null;if(t.op==="||")return e===!0||r===!0?!0:e===!1&&r===!1?!1:null}if(t.type==="unaryOp"&&t.op==="!"){const e=or(t.operand);return e===null?null:!e}return null}const _u=new Set(["write","create","update","delete"]);function Au(t,e){for(let r=0;r<t.length;r++){const n=t[r];if(or(n.rule.condition)!==!0||!n.rule.operations.some(a=>_u.has(a)))continue;const i=n.rule.operations.join(", ");e.push({rule:"PERMISSIVE_RULE",severity:"warning",message:`allow ${i} at ${n.path} resolves to a constant true predicate — this disables write security for the matched paths. If you reached for \`if true\` to escape a denial you don't understand, narrow the predicate to the specific request shape instead (auth identity, affected fields via diff, status transitions).`,location:{ruleIndex:r,matchPath:n.path},fix:"Replace the always-true predicate with a request-shape check (e.g. request.auth != null && request.resource.data.ownerId == request.auth.uid)."})}}function Ua(t,e){if(t.path.segments.some(n=>n.type==="recursive"))for(let n=0;n<t.allows.length;n++)or(t.allows[n].condition)===!0&&e.push({rule:"RECURSIVE_WILDCARD_OPEN",severity:"error",message:`Recursive wildcard match (${t.path.raw}) with an always-true predicate exposes every document under this prefix. This is the Firebase open-rules anti-pattern — never ship it.`,location:{ruleIndex:n,matchPath:t.path.raw},fix:"Either narrow the match path to specific collections, or replace `if true` with a real predicate (auth identity, ownership, role)."});for(const n of t.children)Ua(n,e)}function Iu(t){return t.type==="literal"?t.value??"":t.type==="wildcard"?"{*}":t.type==="recursive"?"{**}":""}function xu(t){return t.map(Iu).join("/")}function zn(t,e){const r=xu(t.path.segments),n=e?`${e}/${r}`:r,s=[{block:t,normalizedPath:n}];for(const i of t.children)s.push(...zn(i,n));return s}function ne(t){switch(t.type){case"literal":return t.raw;case"identifier":return t.name;case"memberAccess":return`${ne(t.object)}.${t.property}`;case"methodCall":return`${ne(t.object)}.${t.method}(${t.args.map(ne).join(",")})`;case"bracketAccess":return`${ne(t.object)}[${ne(t.index)}]`;case"sliceAccess":return`${ne(t.object)}[${ne(t.start)}:${ne(t.end)}]`;case"binaryOp":return`(${ne(t.left)}${t.op}${ne(t.right)})`;case"unaryOp":return`(${t.op}${ne(t.operand)})`;case"ternary":return`(${ne(t.condition)}?${ne(t.consequent)}:${ne(t.alternate)})`;case"inExpr":return`(${ne(t.element)} in ${ne(t.collection)})`;case"isExpr":return`(${ne(t.value)} is ${t.typeName})`;case"listLiteral":return`[${t.elements.map(ne).join(",")}]`;case"mapLiteral":return`{${t.entries.map(e=>`${ne(e.key)}:${ne(e.value)}`).join(",")}}`;case"pathLiteral":return t.raw;case"functionCall":return`${t.name}(${t.args.map(ne).join(",")})`}}function Nr(t){return t.type==="binaryOp"&&t.op==="&&"?[...Nr(t.left),...Nr(t.right)]:[t]}function ku(t,e,r){const n=zn(t,""),s=zn(e,""),i=new Map;for(const{block:a,normalizedPath:o}of n)i.has(o)||i.set(o,a);for(const{block:a,normalizedPath:o}of s){const c=i.get(o);if(!c){a.allows.length>0&&r.push({rule:"RULES_WEAKENED",severity:"warning",message:`Match block removed: ${o}`,location:{matchPath:o}});continue}for(const u of a.allows){const f=[...u.operations].sort().join(","),l=c.allows.find(w=>[...w.operations].sort().join(",")===f),p=u.operations.join(", ");if(!l){r.push({rule:"RULES_WEAKENED",severity:"warning",message:`Allow rule removed: ${o} allow ${p}`,location:{matchPath:o}});continue}const y=Nr(u.condition).map(ne),v=new Set(Nr(l.condition).map(ne));for(const w of y)v.has(w)||r.push({rule:"RULES_WEAKENED",severity:"warning",message:`Predicate removed from ${o} allow ${p}: ${w}`,location:{matchPath:o}})}}}function Vn(t,e={}){const r=[];r.push(...eu(t)),hu(t,r);const n=Or(t);if(!n.ok)return{warnings:r,metrics:{sourceSize:t.length,functionCount:0,allowRuleCount:0,maxChainDepth:0,maxChainOp:"",maxLetBindings:0,maxLetBindingsFunction:"",maxCallDepth:0,maxEstimatedExpressions:0,getCallCount:0},parseError:n.error};const s=n.ast,i=qa(s.service.match),a=Pa(s.service.match);if(pu(i,r),fu(i,r),mu(a,r),yu(a,i,r),vu(a,i,r),bu(a,i,r),wu(a,i,r),r.push(...du(s,{allowDebug:e.allowDebug||!!(e.testCases&&e.testCases.length>0)})),Au(a,r),Ua(s.service.match,r),e.testCases&&e.testCases.length>0&&Su(a,i,e.testCases,r),e.previousSource){const v=Or(e.previousSource);v.ok&&ku(s.service.match,v.ast.service.match,r)}let o={depth:0,op:""},c={count:0,fn:""};for(const v of i){const w=$n(v.body);w.depth>o.depth&&(o={depth:w.depth,op:w.op}),v.lets.length>c.count&&(c={count:v.lets.length,fn:v.name})}const u=Da(i);let f=0;for(const v of i){const w=As(v.name,u);w>f&&(f=w)}const l=new Map;for(const v of i)l.set(v.name,v);let p=0,y=0;for(const v of a){const w=Fa(v.rule.condition,l);w>y&&(y=w)}return{warnings:r,metrics:{sourceSize:t.length,functionCount:i.length,allowRuleCount:a.length,maxChainDepth:o.depth,maxChainOp:o.op,maxLetBindings:c.count,maxLetBindingsFunction:c.fn,maxCallDepth:f,maxEstimatedExpressions:p,getCallCount:y}}}const Is={atomic:["cloud.firestore"],auth:["cloud.firestore","firebase.storage"],content:["cloud.firestore"],counters:["cloud.firestore"],geometry:["cloud.firestore"],joining:["cloud.firestore"],lifecycle:["cloud.firestore"],lobby:["cloud.firestore"],membership:["cloud.firestore","firebase.storage"],spaces:["cloud.firestore"],state:["cloud.firestore"],"storage/metadata":["firebase.storage"],"storage/objects":["firebase.storage"],"storage/time":["firebase.storage"],"storage/uploads":["firebase.storage"],timing:["cloud.firestore"],transitions:["cloud.firestore"],turns:["cloud.firestore"],validation:["cloud.firestore"]};Object.freeze(Object.keys(Is).sort());const Eu={atomic:[],auth:["storage-rules#125","firestore-rules#189"],content:[],counters:[],geometry:[],joining:[],lifecycle:[],lobby:[],membership:["storage-rules#125","firestore-rules#189"],spaces:[],state:[],"storage/metadata":["storage-rules#132"],"storage/objects":["storage-rules#132"],"storage/time":["storage-rules#132"],"storage/uploads":["storage-rules#132"],timing:[],transitions:[],turns:[],validation:[]},Ba=["exists","existsAfter","get","getAfter"],Tu=["addedKeys","affectedKeys","bind","changedKeys","concat","date","day","dayOfWeek","dayOfYear","diff","difference","distance","get","hasAll","hasAny","hasOnly","hours","intersection","join","keys","latitude","longitude","lower","matches","minutes","month","nanos","removeAll","removedKeys","replace","seconds","size","split","time","toBase64","toHexString","toMillis","toSet","toUtf8","trim","unchangedKeys","union","upper","values","year"],Ou={addedKeys:["mapdiff"],affectedKeys:["mapdiff"],bind:["path"],changedKeys:["mapdiff"],concat:["list"],date:["timestamp"],day:["timestamp"],dayOfWeek:["timestamp"],dayOfYear:["timestamp"],diff:["map"],difference:["set"],distance:["latlng"],get:["map"],hasAll:["list","set"],hasAny:["list","set"],hasOnly:["list","set"],hours:["timestamp"],intersection:["set"],join:["list"],keys:["map"],latitude:["latlng"],longitude:["latlng"],lower:["string"],matches:["string"],minutes:["timestamp"],month:["timestamp"],nanos:["duration","timestamp"],removeAll:["list"],removedKeys:["mapdiff"],replace:["string"],seconds:["duration","timestamp"],size:["bytes","list","map","set","string"],split:["string"],time:["timestamp"],toBase64:["bytes"],toHexString:["bytes"],toMillis:["timestamp"],toSet:["list"],toUtf8:["string"],trim:["string"],unchangedKeys:["mapdiff"],union:["set"],upper:["string"],values:["map"],year:["timestamp"]},za={cast:["float","int","path","string"],duration:["abs","time","value"],hashing:["crc32","crc32c","md5","sha256"],latlng:["value"],math:["abs","ceil","floor","isNaN","pow","round","sqrt"],timestamp:["date","value"]},Cu=["request","request.auth","request.auth.token","request.auth.uid","request.method","request.path","request.resource","request.resource.contentType","request.resource.metadata","request.resource.size","request.time","resource","resource.bucket","resource.contentType","resource.generation","resource.metadata","resource.metageneration","resource.name","resource.size","resource.timeCreated","resource.updated"],Ru=["get","hasAll","keys","matches","size","split"],Nu={get:["map"],hasAll:["set"],keys:["map"],matches:["string"],size:["list","map","string"],split:["string"]},Va={duration:["value"],firestore:["exists","get"],timestamp:["date","value"]},Lu=new Set(Cu),Mu=["request.auth.token","request.resource.metadata","resource.metadata"];function Du(t,e){if(e.length===1)return!0;if(t==="firebase.storage"){const r=e.join(".");return Lu.has(r)||Mu.some(n=>r.startsWith(`${n}.`))}return e[0]==="request"?e[1]==="auth"||e[1]==="query"?!0:["time","method","path"].includes(e[1])?e.length===2:e[1]==="resource"&&(e.length===2||e[2]==="data"):e[0]==="resource"&&(e.length===1||e[1]==="data")}function Lr(t,e){return e[0]==="request"&&e[1]==="auth"&&e[2]==="token"?!0:t==="firebase.storage"?e[0]==="resource"&&e[1]==="metadata"||e[0]==="request"&&e[1]==="resource"&&e[2]==="metadata":e[0]==="resource"&&e[1]==="data"||e[0]==="request"&&e[1]==="resource"&&e[2]==="data"||e[0]==="request"&&e[1]==="query"}function Fu(t,e){if(!e||e==="unknown-ambient")return null;const r=e.join(".");return r==="request.resource"||r==="resource"?"resource":r==="request.auth"||r==="request.auth.token"||t==="cloud.firestore"&&(r==="request.resource.data"||r==="resource.data"||r==="request.query")||r==="request.resource.metadata"||r==="resource.metadata"?"map":r==="request.auth.uid"||r==="request.method"||r==="request.resource.contentType"||r==="resource.contentType"||t==="firebase.storage"&&(r.startsWith("request.resource.metadata.")||r.startsWith("resource.metadata."))?"string":r==="request.path"?"path":r==="request.time"||r==="resource.timeCreated"||r==="resource.updated"?"timestamp":["request.resource.size","resource.size","resource.generation","resource.metageneration"].includes(r)?"number":null}function ni(t){if(t.type!=="methodCall")return null;if(t.object.type==="identifier"){if(t.object.name==="firestore"){if(t.method==="get")return"document";if(t.method==="exists")return"boolean"}if(t.object.name==="duration")return"duration";if(t.object.name==="timestamp")return"timestamp";if(t.object.name==="latlng")return"latlng";if(t.object.name==="hashing")return"bytes";if(t.object.name==="math")return"number";if(t.object.name==="cast"){if(t.method==="string")return"string";if(t.method==="path")return"path";if(t.method==="int"||t.method==="float")return"number"}}return["lower","upper","trim","replace","join","toBase64","toHexString"].includes(t.method)?"string":["matches","hasAny","hasAll","hasOnly"].includes(t.method)?"boolean":["concat","removeAll","split","values"].includes(t.method)?"list":["keys","toSet","addedKeys","removedKeys","changedKeys","affectedKeys","unchangedKeys","difference","union","intersection"].includes(t.method)?"set":t.method==="diff"?"mapdiff":t.method==="get"?null:t.method==="toUtf8"?"bytes":t.method==="date"?"timestamp":["size","year","month","day","hours","minutes","seconds","nanos","dayOfWeek","dayOfYear","toMillis","latitude","longitude","distance"].includes(t.method)?"number":null}const ju=new Set(Ba),qu=Object.fromEntries(Object.entries(za).map(([t,e])=>[t,new Set(e)])),Pu=Object.fromEntries(Object.entries(Va).map(([t,e])=>[t,new Set(e)]));function rt(t,e){return t.some(r=>we(r,e)!==null)?"unknown-ambient":null}function Ha(t,e,r){const n=r.declarations?.get(t),s=new Map(n?.aliases),i=new Map(n?.receiverTypes);return t.parameters.forEach((a,o)=>{s.set(a,e[o]?.provenance??null),i.set(a,e[o]?.receiverType??null)}),{aliases:s,receiverTypes:i,functions:n?.functions??r.functions,service:r.service,stack:new Set([...r.stack,t.name]),declarations:r.declarations}}function Wt(t,e){return{expression:t,provenance:we(t,e),receiverType:le(t,e)}}function we(t,e){if(t.type==="identifier")return t.name==="request"||t.name==="resource"?[t.name]:e.aliases.get(t.name)??null;if(t.type==="memberAccess"){const r=we(t.object,e);return r==="unknown-ambient"?r:r?[...r,t.property]:null}if(t.type==="bracketAccess"){const r=we(t.object,e);return!r||r==="unknown-ambient"?r:t.index.type==="literal"&&typeof t.index.value=="string"?[...r,t.index.value]:[...r,"*"]}if(t.type==="ternary"){const r=we(t.consequent,e),n=we(t.alternate,e);return!r&&!n?null:Array.isArray(r)&&Array.isArray(n)&&r.join(".")===n.join(".")?r:"unknown-ambient"}if(t.type==="functionCall"){const r=e.functions.get(t.name),n=t.args.map(i=>Wt(i,e));if(!r&&ju.has(t.name))return null;if(!r||e.stack.has(r.name))return n.some(({provenance:i})=>i!==null)?"unknown-ambient":null;const s=Ha(r,n,e);for(const i of r.lets){const a=Wt(i.value,s);s.aliases.set(i.name,a.provenance),s.receiverTypes.set(i.name,a.receiverType)}return we(r.body,s)}if(t.type==="methodCall"&&t.object.type==="identifier"&&t.object.name==="firestore"&&(t.method==="get"||t.method==="exists"))return null;switch(t.type){case"literal":return null;case"methodCall":return rt([t.object,...t.args],e);case"sliceAccess":return rt([t.object,t.start,t.end],e);case"binaryOp":return rt([t.left,t.right],e);case"unaryOp":return rt([t.operand],e);case"inExpr":return rt([t.element,t.collection],e);case"isExpr":return rt([t.value],e);case"listLiteral":return rt(t.elements,e);case"mapLiteral":return rt(t.entries.flatMap(({key:r,value:n})=>[r,n]),e);case"pathLiteral":return rt(t.segments.filter(r=>typeof r!="string"),e);default:return null}}function le(t,e){const r=Fu(e.service,we(t,e));if(r)return r;switch(t.type){case"identifier":{const n=e.receiverTypes.get(t.name);return n||((e.service==="cloud.firestore"?qu:Pu)[t.name]||t.name==="firestore"?"namespace":null)}case"literal":return t.value===null?"null":typeof t.value=="string"?"string":typeof t.value=="number"?"number":typeof t.value=="boolean"?"boolean":null;case"listLiteral":return"list";case"mapLiteral":return"map";case"pathLiteral":return"path";case"memberAccess":{const n=le(t.object,e);if(n==="mixed")return"mixed";if(t.property==="data"&&n==="document")return"map";if(t.object.type==="mapLiteral"){const s=t.object.entries.find(({key:i})=>i.type==="literal"&&i.value===t.property);return s?le(s.value,e):null}return null}case"bracketAccess":{const n=le(t.object,e);if(n==="mixed")return"mixed";if(t.object.type==="listLiteral"&&t.index.type==="literal"&&typeof t.index.value=="number"&&Number.isInteger(t.index.value)){const i=t.object.elements[t.index.value];return i?le(i,e):null}if(t.object.type==="mapLiteral"&&t.index.type==="literal"){const i=t.index.value,a=t.object.entries.find(({key:o})=>o.type==="literal"&&o.value===i);return a?le(a.value,e):null}if(n==="string")return"string";const s=we(t.object,e);return e.service==="firebase.storage"&&Array.isArray(s)&&(s.join(".")==="request.resource.metadata"||s.join(".")==="resource.metadata")?"string":null}case"sliceAccess":{const n=le(t.object,e);return n==="mixed"?"mixed":n==="list"||n==="string"?n:null}case"methodCall":{const n=ni(t);if(t.object.type==="identifier"&&n)return n;if(t.method==="get"){const s=we(t.object,e);if(e.service==="firebase.storage"&&Array.isArray(s)&&(s.join(".")==="request.resource.metadata"||s.join(".")==="resource.metadata"))return"string";const i=t.args[1];if(t.object.type==="mapLiteral"&&t.args[0]?.type==="literal"){const a=t.args[0].value,o=t.object.entries.find(({key:c})=>c.type==="literal"&&c.value===a);return o?le(o.value,e):i?le(i,e):null}return i&&le(i,e)?"mixed":null}return ni(t)}case"binaryOp":{const n=le(t.left,e),s=le(t.right,e);return t.op==="+"&&(n==="string"||s==="string")?"string":["==","!=","<","<=",">",">=","&&","||"].includes(t.op)?"boolean":["+","-","*","/","%"].includes(t.op)&&n==="number"&&s==="number"?"number":null}case"unaryOp":return t.op==="!"?"boolean":t.op==="-"&&le(t.operand,e)==="number"?"number":null;case"inExpr":case"isExpr":return"boolean";case"ternary":{const n=le(t.consequent,e),s=le(t.alternate,e);return!n&&!s?null:n===s?n:"mixed"}case"functionCall":{const n=e.functions.get(t.name);if(!n&&e.service==="cloud.firestore"){if(t.name==="get"||t.name==="getAfter")return"document";if(t.name==="exists")return"boolean"}if(!n||e.stack.has(n.name))return null;const s=Ha(n,t.args.map(i=>Wt(i,e)),e);for(const i of n.lets){const a=Wt(i.value,s);s.aliases.set(i.name,a.provenance),s.receiverTypes.set(i.name,a.receiverType)}return le(n.body,s)}default:return null}}function $u(t){return t.match(/^\.\/stdlib\/(.+?)(?:\.rules)?$/)?.[1]??t}function Uu(t,e,r){const n=$u(e),s=Is[n];return s?s.includes(t)?null:`Function '${r}' from module '${e}' is not compatible with service '${t}'`:null}function Bu(t){throw new Error(`Unhandled Rules expression: ${JSON.stringify(t)}`)}const zu=new Set(Ba),Vu=new Set(Tu),Hu=Object.fromEntries(Object.entries(za).map(([t,e])=>[t,new Set(e)])),Wu=new Set(Ru),Gu=Object.fromEntries(Object.entries(Va).map(([t,e])=>[t,new Set(e)]));function Mr(t,e){return t==="unknown-ambient"?"binding '<derived ambient value>'":t&&!Du(e,t)?`binding '${t.join(".")}'`:null}function Ku(t,e,r,n,s){if(e!=="get"&&e!=="keys"&&e!=="values")return null;const i=we(t,s);if(i==="unknown-ambient")return"binding '<derived ambient value>'";if(!i)return null;if(e==="get"){const a=r[0];if(a?.type==="literal"&&typeof a.value=="string")return Mr([...i,a.value],n);if(!Lr(n,i))return`binding '${i.join(".")}.get(...)'`}return(e==="keys"||e==="values")&&!Lr(n,i)?`binding '${i.join(".")}.${e}()'`:null}function Zu(t,e,r,n){const s=we(t,n),i=le(t,n);if(!i){if(s==="unknown-ambient")return"binding '<derived ambient receiver>'";let c=t;for(;c.type==="memberAccess"||c.type==="bracketAccess"||c.type==="methodCall"&&c.method==="get";)c=c.object;const u=le(c,n);return u==="map"||u==="list"||u==="document"?`method '.${e}()' has an unresolved projected receiver`:null}const o=(r==="cloud.firestore"?Ou:Nu)[e];return o?.includes(i)?null:`method '.${e}()' requires ${o?.join("|")??"an accepted"} receiver, got ${i}`}function Ju(t,e,r,n){const s=we(e,n);return s==="unknown-ambient"?"binding '<derived ambient value>'":s?t.type==="literal"&&typeof t.value=="string"?Mr([...s,t.value],r):Lr(r,s)?null:`binding '<value> in ${s.join(".")}'`:null}function si(t,e,r){const n=s=>{switch(s.type){case"memberAccess":{const i=Mr(we(s,r),e);return i||n(s.object)}case"functionCall":{const i=r.functions.get(s.name);if(!i&&e==="firebase.storage")return`function '${s.name}()'`;if(!i&&!zu.has(s.name))return`function '${s.name}()'`;for(const a of s.args){const o=n(a);if(o)return o}if(i&&!r.stack.has(i.name)){const a=new Map,o=new Map;i.parameters.forEach((u,f)=>{const l=s.args[f];a.set(u,l?we(l,r):null),o.set(u,l?le(l,r):null)});const c=Wa(i,e,{aliases:a,receiverTypes:o,functions:r.functions,service:e,stack:new Set([...r.stack,i.name])});if(c)return c}return null}case"methodCall":{if(s.object.type==="identifier"&&!r.aliases.has(s.object.name)){const u=(e==="cloud.firestore"?Hu:Gu)[s.object.name];if(u){if(!u.has(s.method))return`method '${s.object.name}.${s.method}()'`;for(const f of s.args){const l=n(f);if(l)return l}return null}return s.object.name==="firestore"?`method 'firestore.${s.method}()'`:`namespace '${s.object.name}'`}if(!(e==="cloud.firestore"?Vu:Wu).has(s.method))return`method '.${s.method}()'`;const a=Zu(s.object,s.method,e,r);if(a)return a;const o=Ku(s.object,s.method,s.args,e,r);return o||(n(s.object)??s.args.map(n).find(Boolean)??null)}case"binaryOp":return n(s.left)??n(s.right);case"unaryOp":return n(s.operand);case"bracketAccess":{const i=we(s.object,r);if(i==="unknown-ambient")return"binding '<derived ambient value>[...]'";const a=s.index.type==="literal"&&typeof s.index.value=="string";if(i&&!a)return Lr(e,i)?n(s.object)??n(s.index):`binding '${i.join(".")}[...]'`;const o=Mr(we(s,r),e);return o||(n(s.object)??n(s.index))}case"sliceAccess":return n(s.object)??n(s.start)??n(s.end);case"ternary":return n(s.condition)??n(s.consequent)??n(s.alternate);case"inExpr":return Ju(s.element,s.collection,e,r)??n(s.element)??n(s.collection);case"isExpr":return n(s.value);case"listLiteral":return s.elements.map(n).find(Boolean)??null;case"mapLiteral":for(const i of s.entries){const a=n(i.key)??n(i.value);if(a)return a}return null;case"pathLiteral":for(const i of s.segments)if(typeof i!="string"){const a=n(i);if(a)return a}return null;case"literal":return null;case"identifier":return s.name==="request"||s.name==="resource"||r.aliases.has(s.name)?null:`identifier '${s.name}'`;default:return Bu(s)}};return n(t)}function Wa(t,e,r){const n=new Map(r.aliases),s=new Map(r.receiverTypes),i={...r,aliases:n,receiverTypes:s};for(const a of t.lets){const o=si(a.value,e,i);if(o)return o;n.set(a.name,we(a.value,i)),s.set(a.name,le(a.value,i))}return si(t.body,e,i)}function Yu(t,e,r=new Map([[t.name,t]]),n=[]){const s={aliases:new Map,receiverTypes:new Map,functions:r,service:e,stack:new Set([t.name])};return Wa(t,e,{aliases:new Map(t.parameters.map((i,a)=>[i,a<n.length?n[a]?.provenance??null:null])),receiverTypes:new Map(t.parameters.map((i,a)=>[i,n[a]?le(n[a].expression,s)??n[a].receiverType??null:null])),functions:r,service:e,stack:new Set([t.name])})}function Qu(t){throw new Error(`Unhandled Rules expression: ${JSON.stringify(t)}`)}function Xu(t){return t.replace(/^\.\.\//,"_").replace(/^\.\//,"").replace(/[.\/-]/g,"_")}function re(t,e){switch(t.type){case"functionCall":{const r=e.get(t.name)??t.name,n=t.args.map(s=>re(s,e));return r===t.name&&n.every((s,i)=>s===t.args[i])?t:{...t,name:r,args:n}}case"binaryOp":{const r=re(t.left,e),n=re(t.right,e);return r===t.left&&n===t.right?t:{...t,left:r,right:n}}case"unaryOp":{const r=re(t.operand,e);return r===t.operand?t:{...t,operand:r}}case"methodCall":{const r=re(t.object,e),n=t.args.map(s=>re(s,e));return r===t.object&&n.every((s,i)=>s===t.args[i])?t:{...t,object:r,args:n}}case"memberAccess":{const r=re(t.object,e);return r===t.object?t:{...t,object:r}}case"bracketAccess":{const r=re(t.object,e),n=re(t.index,e);return r===t.object&&n===t.index?t:{...t,object:r,index:n}}case"sliceAccess":{const r=re(t.object,e),n=re(t.start,e),s=re(t.end,e);return r===t.object&&n===t.start&&s===t.end?t:{...t,object:r,start:n,end:s}}case"ternary":{const r=re(t.condition,e),n=re(t.consequent,e),s=re(t.alternate,e);return r===t.condition&&n===t.consequent&&s===t.alternate?t:{...t,condition:r,consequent:n,alternate:s}}case"inExpr":{const r=re(t.element,e),n=re(t.collection,e);return r===t.element&&n===t.collection?t:{...t,element:r,collection:n}}case"isExpr":{const r=re(t.value,e);return r===t.value?t:{...t,value:r}}case"listLiteral":{const r=t.elements.map(n=>re(n,e));return r.every((n,s)=>n===t.elements[s])?t:{...t,elements:r}}case"mapLiteral":{const r=t.entries.map(n=>{const s=re(n.key,e),i=re(n.value,e);return s===n.key&&i===n.value?n:{key:s,value:i}});return r.every((n,s)=>n===t.entries[s])?t:{...t,entries:r}}case"pathLiteral":{const r=t.segments.map(n=>typeof n=="string"?n:re(n,e));return r.every((n,s)=>n===t.segments[s])?t:{...t,segments:r}}case"literal":case"identifier":return t;default:return Qu(t)}}function el(t,e){const r=Xu(e),n=new Map;for(const s of t)s.exported||n.set(s.name,`${r}__${s.name}`);return n.size===0?t:t.map(s=>{const i=re(s.body,n),a=s.lets.map(c=>{const u=re(c.value,n);return u===c.value?c:{...c,value:u}}),o=s.exported?s.name:n.get(s.name)??s.name;return i===s.body&&a===s.lets&&o===s.name?s:{...s,name:o,body:i,lets:a}})}function tl(t){throw new Error(`Unhandled Rules expression: ${JSON.stringify(t)}`)}function xs(t){const e=[],r=n=>{switch(n.type){case"functionCall":e.push(n),n.args.forEach(r);break;case"binaryOp":r(n.left),r(n.right);break;case"unaryOp":r(n.operand);break;case"methodCall":r(n.object),n.args.forEach(r);break;case"memberAccess":r(n.object);break;case"bracketAccess":r(n.object),r(n.index);break;case"sliceAccess":r(n.object),r(n.start),r(n.end);break;case"ternary":r(n.condition),r(n.consequent),r(n.alternate);break;case"inExpr":r(n.element),r(n.collection);break;case"isExpr":r(n.value);break;case"listLiteral":n.elements.forEach(r);break;case"mapLiteral":n.entries.forEach(({key:s,value:i})=>{r(s),r(i)});break;case"pathLiteral":n.segments.forEach(s=>{typeof s!="string"&&r(s)});break;case"literal":case"identifier":break;default:tl(n)}};return r(t),e}function rl(t){return{expression:t.expression,provenance:t.provenance,receiverType:!t.receiverType||t.receiverType==="mixed"?"unknown":t.receiverType}}function nl(t,e){const r=[],n=new Map,s=t.service.name==="firebase.storage"?"firebase.storage":"cloud.firestore",i=(l,p=new Set)=>({aliases:new Map(l.aliases),receiverTypes:new Map(l.receiverTypes),functions:l.functions,service:s,stack:p,declarations:n}),a=(l,p,y)=>{if(y.has(l.name))return;const v=n.get(l);if(!v)return;const w=new Map(v.aliases),R=new Map(v.receiverTypes);l.parameters.forEach((k,x)=>{w.set(k,p[x]?.provenance??null),R.set(k,p[x]?.receiverType??null)});const C=i({aliases:w,receiverTypes:R,functions:v.functions},new Set([...y,l.name]));for(const k of l.lets){o(k.value,C);const x=Wt(k.value,C);C.aliases.set(k.name,x.provenance),C.receiverTypes.set(k.name,x.receiverType)}o(l.body,C)},o=(l,p)=>{for(const y of xs(l)){const v=y.args.map(R=>Wt(R,p));y.name===e&&r.push({arguments:v.map(rl)});const w=p.functions.get(y.name);w&&a(w,v,p.stack)}},c=new Map((t.functions??[]).map(l=>[l.name,l])),u=new Map(c);for(const l of t.service.functions??[])u.set(l.name,l);for(const l of t.functions??[])n.set(l,{aliases:new Map,receiverTypes:new Map,functions:c});for(const l of t.service.functions??[])n.set(l,{aliases:new Map,receiverTypes:new Map,functions:u});const f=(l,p)=>{const y=new Map(p.receiverTypes);for(const C of l.path.segments)C.type==="wildcard"&&y.set(C.name,"string"),C.type==="recursive"&&y.set(C.name,"path");const v=new Map(p.functions),w={aliases:p.aliases,receiverTypes:y,functions:v};for(const C of l.functions)v.set(C.name,C),n.set(C,w);const R=i(w);for(const{condition:C}of l.allows)o(C,R);l.children.forEach(C=>f(C,w))};return f(t.service.match,{aliases:new Map,receiverTypes:new Map,functions:u}),r}function _t(t){return xs(t).map(({name:e})=>e)}function sl(t,e){return[...t.values()].flatMap(n=>[...n.lets.map(({value:s})=>s),n.body]).flatMap(xs).filter(({name:n})=>n===e).map(({args:n})=>n)}function il(t,e,r){const n=Vc(t,e);return n===null?{success:!1,error:{code:"PARSE_FAILED",message:`Failed to parse module '${e}'`}}:{success:!0,functions:n,bundled:r}}function ii(t){return t.startsWith("./")||t.startsWith("../")}function Hn(t){return/^\.\/stdlib\/([A-Za-z0-9_-]+(?:\/[A-Za-z0-9_-]+)*)\.rules$/.exec(t)?.[1]??null}function al(t,e,r,n=new Set){if(r?.modules&&Object.prototype.hasOwnProperty.call(r.modules,e))return il(r.modules[e],e,n.has(e));if(ii(e)&&r?.basePath){const i=`${r.basePath}/${e}${e.endsWith(".rules")?"":".rules"}`;if(!Hn(e))return{success:!1,error:{code:"UNKNOWN_MODULE",message:`Module '${e}' not found at ${i}`}}}return Hn(e)?{success:!1,error:{code:"UNKNOWN_MODULE",message:`Module '${e}' not found`}}:ii(e)?{success:!1,error:{code:"UNKNOWN_MODULE",message:`Module '${e}' requires basePath for relative imports`}}:{success:!1,error:{code:"UNKNOWN_MODULE",message:`Module '${e}' not found`}}}function ol(t,e,r,n=new Set){const s=Or(e);if(!s.ok){const{line:M,column:z,message:ee}=s.error;return{success:!1,error:{code:"PARSE_FAILED",message:`Failed to parse source at line ${M}, col ${z}: ${ee}`}}}const i=s.ast,a=i.version==="2+modules",o=i.service.name==="firebase.storage";let c=o?"storage.rules":"firestore.rules";if(a&&(c=o?"storage.modules.rules":"firestore.modules.rules"),r!==void 0&&r.sourceFile!==void 0&&r.sourceFile!==""&&(c=r.sourceFile),cl(i,c),a===!1)return{success:!1,error:{code:"NOT_MODULE_SOURCE",message:`Version '${i.version}' is not a module source`}};if(i.service.name==="cloud.firestore"===!1&&i.service.name==="firebase.storage"===!1)return{success:!1,error:{code:"UNSUPPORTED_SERVICE",message:`Module resolution does not support service '${i.service.name}'`}};if(i.imports.length===0){i.version="2";const M=Pn(i),z=JSON.stringify(M.sourceMap);return{success:!0,data:{resolved:`${M.resolved}// @pyric-source-map: ${z}
|
|
478
|
-
`,modules:[],bundledModules:[],evidenceIds:[],sourceMap:M.sourceMap}}}const p=i.imports.find(M=>M.functions.length===0);if(p)return{success:!1,error:{code:"UNKNOWN_FUNCTION",message:`Import from '${p.module}' must request at least one function`}};const y=new Map,v=new Map,
|
|
477
|
+
`),sourceMap:r}}function ri(t){return Pn(t).resolved}const Ir=new Set(["get","exists","getAfter","debug"]);function Rr(t,e){return t.type!=="binaryOp"||t.op!==e?0:1+Rr(t.right,e)}function $n(t){let e={op:"",depth:0};function r(s){if(s.type==="binaryOp"){const i=Rr(s,"&&"),a=Rr(s,"||");i>e.depth&&(e={op:"&&",depth:i}),a>e.depth&&(e={op:"||",depth:a}),r(s.left),r(s.right)}else n(s)}function n(s){switch(s.type){case"unaryOp":r(s.operand);break;case"methodCall":r(s.object),s.args.forEach(r);break;case"memberAccess":r(s.object);break;case"bracketAccess":r(s.object),r(s.index);break;case"ternary":r(s.condition),r(s.consequent),r(s.alternate);break;case"inExpr":r(s.element),r(s.collection);break;case"isExpr":r(s.value);break;case"listLiteral":s.elements.forEach(r);break;case"mapLiteral":s.entries.forEach(i=>{r(i.key),r(i.value)});break;case"functionCall":s.args.forEach(r);break}}return r(t),e}function ie(t){let e=1;switch(t.type){case"binaryOp":e+=ie(t.left)+ie(t.right);break;case"unaryOp":e+=ie(t.operand);break;case"methodCall":e+=ie(t.object);for(const r of t.args)e+=ie(r);break;case"memberAccess":e+=ie(t.object);break;case"bracketAccess":e+=ie(t.object)+ie(t.index);break;case"ternary":e+=ie(t.condition)+ie(t.consequent)+ie(t.alternate);break;case"inExpr":e+=ie(t.element)+ie(t.collection);break;case"isExpr":e+=ie(t.value);break;case"listLiteral":for(const r of t.elements)e+=ie(r);break;case"mapLiteral":for(const r of t.entries)e+=ie(r.key)+ie(r.value);break;case"functionCall":for(const r of t.args)e+=ie(r);break;case"pathLiteral":for(const r of t.segments)typeof r!="string"&&(e+=ie(r));break}return e}function se(t){switch(t.type){case"literal":return`L:${t.raw}`;case"identifier":return`I:${t.name}`;case"memberAccess":return`M:${se(t.object)}.${t.property}`;case"methodCall":return`MC:${se(t.object)}.${t.method}(${t.args.map(se).join(",")})`;case"bracketAccess":return`B:${se(t.object)}[${se(t.index)}]`;case"binaryOp":return`BO:${se(t.left)}${t.op}${se(t.right)}`;case"unaryOp":return`UO:${t.op}${se(t.operand)}`;case"ternary":return`T:${se(t.condition)}?${se(t.consequent)}:${se(t.alternate)}`;case"inExpr":return`IN:${se(t.element)}in${se(t.collection)}`;case"isExpr":return`IS:${se(t.value)}is${t.typeName}`;case"listLiteral":return`LL:[${t.elements.map(se).join(",")}]`;case"mapLiteral":return`ML:{${t.entries.map(e=>se(e.key)+":"+se(e.value)).join(",")}}`;case"functionCall":return`FC:${t.name}(${t.args.map(se).join(",")})`;case"pathLiteral":return`PL:${t.raw}`;case"sliceAccess":return`SL:${se(t.object)}[${se(t.start)}:${se(t.end)}]`;default:{const e=t;throw new Error(`expressionFingerprint: unhandled type ${e.type}`)}}}function Ma(t){return t.type==="binaryOp"&&t.op==="&&"?Ma(t.left):t}function Da(t){const e=new Map,r=new Set(t.map(s=>s.name));function n(s){const i=[],a=o=>{switch(o.type){case"functionCall":r.has(o.name)&&!Ir.has(o.name)&&i.push(o.name),o.args.forEach(a);break;case"binaryOp":a(o.left),a(o.right);break;case"unaryOp":a(o.operand);break;case"methodCall":a(o.object),o.args.forEach(a);break;case"memberAccess":a(o.object);break;case"bracketAccess":a(o.object),a(o.index);break;case"ternary":a(o.condition),a(o.consequent),a(o.alternate);break;case"inExpr":a(o.element),a(o.collection);break;case"isExpr":a(o.value);break;case"listLiteral":o.elements.forEach(a);break;case"mapLiteral":o.entries.forEach(c=>{a(c.key),a(c.value)});break}};return a(s),[...new Set(i)]}for(const s of t){const i=[];i.push(...n(s.body));for(const a of s.lets)i.push(...n(a.value));e.set(s.name,[...new Set(i)])}return e}function As(t,e,r=new Set){if(r.has(t))return 0;r.add(t);const n=e.get(t)||[];if(n.length===0)return 1;let s=0;for(const i of n)s=Math.max(s,As(i,e,new Set(r)));return 1+s}function Fa(t,e,r=new Set){let n=0;const s=i=>{switch(i.type){case"functionCall":if(i.name==="get"||i.name==="exists")n++;else if(e.has(i.name)&&!r.has(i.name)){r.add(i.name);const a=e.get(i.name);s(a.body);for(const o of a.lets)s(o.value)}i.args.forEach(s);break;case"binaryOp":s(i.left),s(i.right);break;case"unaryOp":s(i.operand);break;case"methodCall":s(i.object),i.args.forEach(s);break;case"memberAccess":s(i.object);break;case"bracketAccess":s(i.object),s(i.index);break;case"ternary":s(i.condition),s(i.consequent),s(i.alternate);break;case"inExpr":s(i.element),s(i.collection);break;case"isExpr":s(i.value);break;case"listLiteral":i.elements.forEach(s);break;case"mapLiteral":i.entries.forEach(a=>{s(a.key),s(a.value)});break}};return s(t),n}function Zc(t,e){const r=new Map,n=s=>{switch(s.type){case"functionCall":e.has(s.name)&&r.set(s.name,(r.get(s.name)??0)+1),s.args.forEach(n);break;case"binaryOp":n(s.left),n(s.right);break;case"unaryOp":n(s.operand);break;case"methodCall":n(s.object),s.args.forEach(n);break;case"memberAccess":n(s.object);break;case"bracketAccess":n(s.object),n(s.index);break;case"ternary":n(s.condition),n(s.consequent),n(s.alternate);break;case"inExpr":n(s.element),n(s.collection);break;case"isExpr":n(s.value);break;case"listLiteral":s.elements.forEach(n);break;case"mapLiteral":s.entries.forEach(i=>{n(i.key),n(i.value)});break}};return n(t),r}function ja(t,e,r=new Set){if(r.has(t))return!1;r.add(t);const n=e.get(t);if(!n)return!1;const s=i=>{switch(i.type){case"functionCall":return i.name==="get"||i.name==="exists"?!0:e.has(i.name)?ja(i.name,e,r):i.args.some(s);case"binaryOp":return s(i.left)||s(i.right);case"unaryOp":return s(i.operand);case"methodCall":return s(i.object)||i.args.some(s);case"memberAccess":return s(i.object);case"bracketAccess":return s(i.object)||s(i.index);case"ternary":return s(i.condition)||s(i.consequent)||s(i.alternate);case"inExpr":return s(i.element)||s(i.collection);case"isExpr":return s(i.value);case"listLiteral":return i.elements.some(s);case"mapLiteral":return i.entries.some(a=>s(a.key)||s(a.value));default:return!1}};return s(n.body)||n.lets.some(i=>s(i.value))}function Un(t,e,r=new Set){const n=s=>{switch(s.type){case"memberAccess":return s.property==="time"&&s.object.type==="identifier"&&s.object.name==="request"?!0:n(s.object);case"bracketAccess":return s.object.type==="identifier"&&s.object.name==="request"&&s.index.type==="literal"&&s.index.value==="time"?!0:n(s.object)||n(s.index);case"functionCall":if(e.has(s.name)&&!r.has(s.name)){r.add(s.name);const i=e.get(s.name);if(Un(i.body,e,r)||i.lets.some(a=>Un(a.value,e,r)))return!0}return s.args.some(n);case"binaryOp":return n(s.left)||n(s.right);case"unaryOp":return n(s.operand);case"methodCall":return n(s.object)||s.args.some(n);case"ternary":return n(s.condition)||n(s.consequent)||n(s.alternate);case"inExpr":return n(s.element)||n(s.collection);case"isExpr":return n(s.value);case"listLiteral":return s.elements.some(n);case"mapLiteral":return s.entries.some(i=>n(i.key)||n(i.value));default:return!1}};return n(t)}function qa(t){const e=[...t.functions];for(const r of t.children)e.push(...qa(r));return e}function Pa(t){const e=[];for(const r of t.allows)e.push({rule:r,path:t.path.raw,matchFunctions:t.functions});for(const r of t.children){const n=Pa(r);for(const s of n)s.matchFunctions=[...t.functions,...s.matchFunctions];e.push(...n)}return e}const Bn={where:"No equivalent in rules — restructure logic instead of filtering a list",filter:"No equivalent in rules — restructure logic instead of filtering a list",find:"No equivalent in rules",findIndex:"No equivalent in rules",map:"No equivalent in rules — lists are not transformable",reduce:"No equivalent in rules",forEach:"No equivalent in rules",every:'Use `list.hasAll([...])` for "all elements present"',some:'Use `list.hasAny([...])` for "any element present"',includes:"Use `x in list` instead of `list.includes(x)`",indexOf:"No equivalent in rules",push:"Lists are immutable in rules",pop:"Lists are immutable in rules",shift:"Lists are immutable in rules",unshift:"Lists are immutable in rules",splice:"Lists are immutable in rules",slice:"No equivalent in rules",sort:"Lists are immutable in rules",reverse:"Lists are immutable in rules",flat:"No equivalent in rules",flatMap:"No equivalent in rules",toLowerCase:"Use `.lower()` instead of `.toLowerCase()`",toUpperCase:"Use `.upper()` instead of `.toUpperCase()`",charAt:'No equivalent in rules — use `.split("")` and index',charCodeAt:"No equivalent in rules",substring:"No `.substring()` — use `.split()` and reassembly",substr:"No `.substr()` — use `.split()` and reassembly",padStart:"No equivalent in rules",padEnd:"No equivalent in rules",trimStart:"Use `.trim()` (trims both ends)",trimEnd:"Use `.trim()` (trims both ends)",toString:"Use the `string(x)` cast instead of `.toString()`"},it={Object:"No `Object` in rules — use `data.keys()` / `data.values()` directly",Array:"No `Array` in rules — test list type with `x is list`",JSON:"No `JSON` in rules — rules cannot parse or serialize JSON",Math:"No `Math` in rules — inline arithmetic or ternaries",Date:"No `Date` in rules — use `request.time` (a Timestamp)",String:"Use lowercase `string(x)` for casting",Number:"Use lowercase `int(x)` or `float(x)` for casting",Boolean:"Use direct comparison or validation instead of boolean casting",bool:"No `bool()` cast in rules — boolean casting is not supported in production Firestore rules.",parseInt:"Use `int(x)` instead",parseFloat:"Use `float(x)` instead",isNaN:"No equivalent in rules",isFinite:"No equivalent in rules",Promise:"Rules are synchronous — no Promise support",undefined:"`undefined` does not exist in rules — use `null`"},Jc=new Set(["abs","ceil","floor","round","sqrt","pow","isNaN"]),Yc=[{receiver:"request",property:"data",suggestion:"Use `request.resource.data` (the incoming write payload)"},{receiver:"request",property:"uid",suggestion:"Use `request.auth.uid`"},{receiver:"request",property:"token",suggestion:"Use `request.auth.token`"},{receiver:"request",property:"user",suggestion:"Use `request.auth` (or `request.auth.uid` for the user id)"},{receiver:"resource",property:"path",suggestion:"`resource.path` is not available — bind path captures in the match pattern"},{receiver:"resource",property:"exists",suggestion:"Use `resource != null` (or `exists()` for cross-document checks)"},{receiver:"resource",property:"id",suggestion:"`resource.id` is not available — capture the document id with `/{docId}` in the match path"}],Qc=new Set(["size","keys","values","lower","upper","trim","hasAll","hasAny","hasOnly","toSet","toUtf8"]),Xc=[{pattern:/===/,message:"Strict equality `===` is not supported in Firestore rules — use `==`."},{pattern:/!==/,message:"Strict inequality `!==` is not supported in Firestore rules — use `!=`."},{pattern:/\?\./,message:"Optional chaining `?.` is not supported — use `'field' in obj && obj.field`."},{pattern:/\?\?/,message:"Nullish coalescing `??` is not supported — use a ternary `cond ? a : b`."},{pattern:/=>/,message:"Arrow functions `=>` are not supported — define functions with `function name() { return ...; }`."},{pattern:/`[^`]*`/,message:"Backtick strings are not supported — use single or double quoted strings with `+` for concatenation."}];function eu(t){const e=[],r=t.replace(/\/\/[^\n]*/g,"").replace(/\/\*[\s\S]*?\*\//g,"");for(const n of Xc)n.pattern.test(r)&&e.push({rule:"INVALID_OPERATOR",severity:"error",message:n.message});return e}function $a(t,e){const r=t.path.raw;for(const n of t.functions){const s={matchPath:r,functionName:n.name};ue(n.body,s,e);for(const i of n.lets)ue(i.value,s,e)}for(let n=0;n<t.allows.length;n++)ue(t.allows[n].condition,{matchPath:r,ruleIndex:n},e);for(const n of t.children)$a(n,e)}function ue(t,e,r){switch(r(t,e),t.type){case"binaryOp":ue(t.left,e,r),ue(t.right,e,r);break;case"unaryOp":ue(t.operand,e,r);break;case"methodCall":ue(t.object,e,r),t.args.forEach(n=>ue(n,e,r));break;case"memberAccess":ue(t.object,e,r);break;case"bracketAccess":ue(t.object,e,r),ue(t.index,e,r);break;case"ternary":ue(t.condition,e,r),ue(t.consequent,e,r),ue(t.alternate,e,r);break;case"inExpr":ue(t.element,e,r),ue(t.collection,e,r);break;case"isExpr":ue(t.value,e,r);break;case"listLiteral":t.elements.forEach(n=>ue(n,e,r));break;case"mapLiteral":t.entries.forEach(n=>{ue(n.key,e,r),ue(n.value,e,r)});break;case"functionCall":t.args.forEach(n=>ue(n,e,r));break}}function tu(t,e){return e?!1:t.type==="functionCall"&&t.name==="debug"}function ru(t){return t.type==="methodCall"&&!!Bn[t.method]}function nu(t){return t.type!=="methodCall"||t.object.type!=="identifier"||t.object.name!=="math"?!1:!Jc.has(t.method)}function su(t){return t.type!=="methodCall"||t.method!=="hasAll"&&t.method!=="hasAny"&&t.method!=="hasOnly"?!1:t.object.type==="mapLiteral"||t.object.type==="memberAccess"&&t.object.property==="data"}function iu(t){return t.type!=="methodCall"||t.object.type!=="identifier"?!1:!!it[t.object.name]}function au(t){return t.type==="functionCall"&&!!it[t.name]}function ou(t){return t.type==="identifier"&&!!it[t.name]}function cu(t){if(t.type!=="memberAccess"||t.object.type!=="identifier")return;const e=t.object.name,r=t.property;return Yc.find(n=>n.receiver===e&&n.property===r)}function uu(t){return t.type==="memberAccess"&&t.property==="length"&&t.object.type==="methodCall"}function lu(t){return t.type!=="memberAccess"||!Qc.has(t.property)?!1:t.object.type==="identifier"&&(t.object.name==="request"||t.object.name==="resource")||t.object.type==="memberAccess"||t.object.type==="methodCall"||t.object.type==="bracketAccess"}function du(t,e={}){const r=[],n=new Set;function s(i,a,o,c){const u=`${i}|${a}|${o.matchPath||""}|${o.functionName||""}|${o.ruleIndex??""}`;n.has(u)||(n.add(u),r.push(c))}return $a(t.service.match,(i,a)=>{if(tu(i,e.allowDebug)&&s("HALLUCINATED_GLOBAL","debug",a,{rule:"HALLUCINATED_GLOBAL",severity:"error",message:"`debug()` helper is only permitted in local testing environments; remove it before deployment.",location:a,fix:"Remove debug() wrapper around the expression."}),ru(i)&&i.type==="methodCall"&&s("HALLUCINATED_METHOD",i.method,a,{rule:"HALLUCINATED_METHOD",severity:"error",message:`\`.${i.method}()\` does not exist in Firestore rules. ${Bn[i.method]}`,location:a,fix:Bn[i.method]}),nu(i)&&i.type==="methodCall"&&s("HALLUCINATED_METHOD",`math.${i.method}`,a,{rule:"HALLUCINATED_METHOD",severity:"error",message:`\`math.${i.method}()\` does not exist in production Firestore security rules.`,location:a,fix:"Use supported math namespace functions: abs, ceil, floor, round, sqrt, pow, isNaN."}),su(i)&&i.type==="methodCall"&&s("HALLUCINATED_METHOD",`map.${i.method}`,a,{rule:"HALLUCINATED_METHOD",severity:"error",message:`\`.${i.method}()\` cannot be called directly on a map in Firestore rules — call it on \`.keys()\` instead.`,location:a,fix:`Insert \`.keys()\`: e.g. \`data.keys().${i.method}(...)\`.`}),iu(i)&&i.type==="methodCall"&&i.object.type==="identifier"){const c=i.object.name;s("HALLUCINATED_GLOBAL",`${c}.${i.method}`,a,{rule:"HALLUCINATED_GLOBAL",severity:"error",message:`\`${c}.${i.method}()\` does not exist in Firestore rules. ${it[c]}`,location:a,fix:it[c]})}au(i)&&i.type==="functionCall"&&s("HALLUCINATED_GLOBAL",i.name,a,{rule:"HALLUCINATED_GLOBAL",severity:"error",message:`\`${i.name}()\` does not exist in Firestore rules. ${it[i.name]}`,location:a,fix:it[i.name]}),ou(i)&&i.type==="identifier"&&s("HALLUCINATED_GLOBAL",`ref:${i.name}`,a,{rule:"HALLUCINATED_GLOBAL",severity:"error",message:`\`${i.name}\` is not a Firestore rules identifier. ${it[i.name]}`,location:a,fix:it[i.name]});const o=cu(i);if(o&&i.type==="memberAccess"&&i.object.type==="identifier"){const c=i.object.name,u=i.property;s("WRONG_CONTEXT_PATH",`${c}.${u}`,a,{rule:"WRONG_CONTEXT_PATH",severity:"error",message:`\`${c}.${u}\` is not a valid Firestore rules path. ${o.suggestion}`,location:a,fix:o.suggestion})}if(uu(i)&&s("LENGTH_PROPERTY","",a,{rule:"LENGTH_PROPERTY",severity:"error",message:"`.length` is not a valid property in Firestore rules — use `.size()` (a method, with parentheses).",location:a,fix:"Replace `.length` with `.size()`."}),i.type==="pathLiteral")for(const c of i.segments){if(typeof c!="string")continue;const u=c.match(/^\{([A-Za-z_][A-Za-z0-9_]*)\}$/);if(!u)continue;const f=u[1];s("INVALID_PATH_INTERPOLATION",`${i.raw}|${f}`,a,{rule:"INVALID_PATH_INTERPOLATION",severity:"error",message:`\`{${f}}\` is not valid inside a path literal — Firestore rejects this at deploy. The \`{var}\` syntax is for match statement wildcards (e.g. \`match /users/{userId}\`); path interpolation in get()/exists()/getAfter()/existsAfter() requires \`$(var)\`. Replace \`{${f}}\` with \`$(${f})\` in path \`${i.raw}\`.`,location:a,fix:`Replace \`{${f}}\` with \`$(${f})\` inside the path argument.`})}lu(i)&&i.type==="memberAccess"&&s("METHOD_MISSING_PARENS",i.property,a,{rule:"METHOD_MISSING_PARENS",severity:"warning",message:`\`.${i.property}\` looks like a built-in method called without parentheses. Use \`.${i.property}()\` if you meant to invoke it (otherwise this is a field access).`,location:a,fix:`Add parentheses: \`.${i.property}()\`.`})}),r}const pe={SOURCE_SIZE:256*1024,CHAIN_DEPTH_ERROR:95,CHAIN_DEPTH_WARN:85,CHAIN_DEPTH_LIMIT:98,LET_LIMIT:11,RUNTIME_BUDGET:{low:{calls:2,warn:100},mid:{calls:4,warn:60},high:{warn:40}},CALL_DEPTH_WARN:6,CALL_DEPTH_ERROR:10,GET_COUNT_WARN:5,GET_COUNT_ERROR:10};function hu(t,e){t.length>pe.SOURCE_SIZE&&e.push({rule:"SOURCE_SIZE",severity:"error",message:`Rules source is ${(t.length/1024).toFixed(0)} KB, exceeding the 256 KB limit.`,fix:"Reduce string literals, remove comments, or split into smaller match blocks."})}function fu(t,e){for(const r of t)r.lets.length>pe.LET_LIMIT&&e.push({rule:"LET_LIMIT",severity:"error",message:`Function '${r.name}' has ${r.lets.length} let bindings. Limit is ${pe.LET_LIMIT}.`,location:{functionName:r.name},fix:"Inline some let expressions into the return statement, or split the function."})}function pu(t,e){for(const r of t){const n=$n(r.body);for(const s of r.lets){const i=$n(s.value);i.depth>n.depth&&(n.depth=i.depth,n.op=i.op)}n.depth>=pe.CHAIN_DEPTH_LIMIT?e.push({rule:"CHAIN_DEPTH",severity:"error",message:`Function '${r.name}' has a ${n.op} chain of depth ${n.depth}. Limit is ${pe.CHAIN_DEPTH_LIMIT}.`,location:{functionName:r.name},fix:"Split into nested groups: 'a && b && c && d' → '(a && b) && (c && d)' to halve chain depth."}):n.depth>=pe.CHAIN_DEPTH_ERROR?e.push({rule:"CHAIN_DEPTH",severity:"error",message:`Function '${r.name}' has a ${n.op} chain of depth ${n.depth}. Limit is ${pe.CHAIN_DEPTH_LIMIT}. Approaching failure.`,location:{functionName:r.name},fix:"Split the chain into nested groups to reduce depth."}):n.depth>=pe.CHAIN_DEPTH_WARN&&e.push({rule:"CHAIN_DEPTH",severity:"warning",message:`Function '${r.name}' has a ${n.op} chain of depth ${n.depth}. Limit is ${pe.CHAIN_DEPTH_LIMIT}.`,location:{functionName:r.name}})}}function mu(t,e){const r=new Map;for(let n=0;n<t.length;n++){const s=t[n];if(!s.rule.operations.some(o=>o==="update"||o==="write"))continue;const i=se(Ma(s.rule.condition)),a=s.path;r.has(a)||r.set(a,[]),r.get(a).push({index:n,gate:i,ops:s.rule.operations})}for(const[n,s]of r){const i=new Map;for(const a of s)i.has(a.gate)||i.set(a.gate,[]),i.get(a.gate).push(a.index);for(const[a,o]of i)o.length>=2&&e.push({rule:"SHARED_GATE",severity:"warning",message:`${o.length} allow rules in '${n}' share the same gate expression. This may cause cross-rule budget exhaustion. Rules: ${o.join(", ")}.`,location:{matchPath:n},fix:"Assign unique moveType or discriminator values so each rule has a unique first expression."})}}function gu(t,e){let r=ie(t);const n=new Set;function s(i){if(i.type==="functionCall"&&e.has(i.name)&&!n.has(i.name)){n.add(i.name);const a=e.get(i.name);r+=ie(a.body);for(const o of a.lets)r+=ie(o.value);s(a.body);for(const o of a.lets)s(o.value)}switch(i.type){case"binaryOp":s(i.left),s(i.right);break;case"unaryOp":s(i.operand);break;case"methodCall":s(i.object),i.args.forEach(s);break;case"memberAccess":s(i.object);break;case"bracketAccess":s(i.object),s(i.index);break;case"ternary":s(i.condition),s(i.consequent),s(i.alternate);break;case"inExpr":s(i.element),s(i.collection);break;case"isExpr":s(i.value);break;case"listLiteral":i.elements.forEach(s);break;case"mapLiteral":i.entries.forEach(a=>{s(a.key),s(a.value)});break;case"functionCall":i.args.forEach(s);break}}return s(t),{totalExprs:r,callCount:n.size}}function yu(t,e,r){const n=new Map;for(const s of e)n.set(s.name,s);for(let s=0;s<t.length;s++){const{totalExprs:i,callCount:a}=gu(t[s].rule.condition,n),o=Rr(t[s].rule.condition,"||"),c=o>5?.3:o>2?.5:1,u=Math.round(i*c),f=a<=pe.RUNTIME_BUDGET.low.calls?pe.RUNTIME_BUDGET.low:a<=pe.RUNTIME_BUDGET.mid.calls?pe.RUNTIME_BUDGET.mid:pe.RUNTIME_BUDGET.high;u>=f.warn&&r.push({rule:"EXPRESSION_BUDGET",severity:"warning",message:`Rule #${s} has ~${i} expression nodes across ${a} function calls. Runtime budget is non-deterministic; actual evaluation depends on short-circuit behavior.`,location:{ruleIndex:s},fix:"If this rule fails at runtime (403), reduce function calls or expression count."})}}function vu(t,e,r){const n=Da(e),s=new Map;for(const i of e)s.set(i.name,i);for(let i=0;i<t.length;i++){let a=0;const o=c=>{if(c.type==="functionCall"&&s.has(c.name)){const u=As(c.name,n);u>a&&(a=u)}switch(c.type){case"binaryOp":o(c.left),o(c.right);break;case"unaryOp":o(c.operand);break;case"methodCall":o(c.object),c.args.forEach(o);break;case"memberAccess":o(c.object);break;case"bracketAccess":o(c.object),o(c.index);break;case"ternary":o(c.condition),o(c.consequent),o(c.alternate);break;case"inExpr":o(c.element),o(c.collection);break;case"functionCall":c.args.forEach(o);break}};o(t[i].rule.condition),a>=pe.CALL_DEPTH_ERROR?r.push({rule:"CALL_DEPTH",severity:"error",message:`Rule #${i} has a function call chain of depth ${a}. May exceed call budget.`,location:{ruleIndex:i},fix:"Inline intermediate functions to reduce call depth."}):a>=pe.CALL_DEPTH_WARN&&r.push({rule:"CALL_DEPTH",severity:"warning",message:`Rule #${i} has a function call chain of depth ${a}.`,location:{ruleIndex:i}})}}function bu(t,e,r){const n=new Map;for(const s of e)n.set(s.name,s);for(let s=0;s<t.length;s++){const i=Fa(t[s].rule.condition,n);i>=pe.GET_COUNT_ERROR?r.push({rule:"GET_COUNT",severity:"error",message:`Rule #${s} may invoke ${i} get()/exists() calls. Limit is ${pe.GET_COUNT_ERROR}.`,location:{ruleIndex:s},fix:"Cache get() results via a config() wrapper function. Same-path calls are cached by Firestore."}):i>=pe.GET_COUNT_WARN&&r.push({rule:"GET_COUNT",severity:"warning",message:`Rule #${s} invokes ${i} get()/exists() calls. Limit is ${pe.GET_COUNT_ERROR}.`,location:{ruleIndex:s}})}}function wu(t,e,r){const n=new Map;for(const i of e)n.set(i.name,i);const s=new Set(e.map(i=>i.name));for(let i=0;i<t.length;i++){const a=Zc(t[i].rule.condition,s);for(const[o,c]of a)c>=2&&ja(o,n)&&r.push({rule:"GET_DUPLICATION",severity:"warning",message:`Function '${o}' (contains get/exists) is called ${c} times in rule #${i}. Cache the result with a let binding in a wrapper function to reduce get() calls from ${c} to 1.`,location:{ruleIndex:i},fix:`Create a wrapper: function verifyAll(ret) { let c = ${o}(); return verify1(ret, c) && verify2(ret, c) && ...; }`})}}function Su(t,e,r,n){const s=new Map;for(const o of e)s.set(o.name,o);const i=new Set;for(let o=0;o<t.length;o++)Un(t[o].rule.condition,s)&&i.add(o);if(i.size===0)return;function a(o,c){const u=o.split("/").filter(Boolean),f=c.split("/").filter(Boolean);if(u.length!==f.length)return!1;for(let l=0;l<u.length;l++){const p=u[l];if(!(p.startsWith("{")&&p.endsWith("}"))&&p!==f[l])return!1}return!0}for(const o of r)if(!o.requestTime)for(const c of i)a(t[c].path,o.path)&&n.push({rule:"REQUEST_TIME_NOT_PINNED",severity:"warning",message:`Test case "${o.description}" targets rule #${c} (path '${t[c].path}') which reads request.time, but does not set requestTime. Result is non-deterministic across runs.`,location:{ruleIndex:c,matchPath:t[c].path,testCaseDescription:o.description},fix:"Set requestTime on this TestCase to an ISO-8601 timestamp so the rule evaluates deterministically."})}function or(t){if(t.type==="literal"&&typeof t.value=="boolean")return t.value;if(t.type==="binaryOp"){const e=or(t.left),r=or(t.right);if(t.op==="&&")return e===!1||r===!1?!1:e===!0&&r===!0?!0:null;if(t.op==="||")return e===!0||r===!0?!0:e===!1&&r===!1?!1:null}if(t.type==="unaryOp"&&t.op==="!"){const e=or(t.operand);return e===null?null:!e}return null}const _u=new Set(["write","create","update","delete"]);function Au(t,e){for(let r=0;r<t.length;r++){const n=t[r];if(or(n.rule.condition)!==!0||!n.rule.operations.some(a=>_u.has(a)))continue;const i=n.rule.operations.join(", ");e.push({rule:"PERMISSIVE_RULE",severity:"warning",message:`allow ${i} at ${n.path} resolves to a constant true predicate — this disables write security for the matched paths. If you reached for \`if true\` to escape a denial you don't understand, narrow the predicate to the specific request shape instead (auth identity, affected fields via diff, status transitions).`,location:{ruleIndex:r,matchPath:n.path},fix:"Replace the always-true predicate with a request-shape check (e.g. request.auth != null && request.resource.data.ownerId == request.auth.uid)."})}}function Ua(t,e){if(t.path.segments.some(n=>n.type==="recursive"))for(let n=0;n<t.allows.length;n++)or(t.allows[n].condition)===!0&&e.push({rule:"RECURSIVE_WILDCARD_OPEN",severity:"error",message:`Recursive wildcard match (${t.path.raw}) with an always-true predicate exposes every document under this prefix. This is the Firebase open-rules anti-pattern — never ship it.`,location:{ruleIndex:n,matchPath:t.path.raw},fix:"Either narrow the match path to specific collections, or replace `if true` with a real predicate (auth identity, ownership, role)."});for(const n of t.children)Ua(n,e)}function Iu(t){return t.type==="literal"?t.value??"":t.type==="wildcard"?"{*}":t.type==="recursive"?"{**}":""}function xu(t){return t.map(Iu).join("/")}function zn(t,e){const r=xu(t.path.segments),n=e?`${e}/${r}`:r,s=[{block:t,normalizedPath:n}];for(const i of t.children)s.push(...zn(i,n));return s}function ne(t){switch(t.type){case"literal":return t.raw;case"identifier":return t.name;case"memberAccess":return`${ne(t.object)}.${t.property}`;case"methodCall":return`${ne(t.object)}.${t.method}(${t.args.map(ne).join(",")})`;case"bracketAccess":return`${ne(t.object)}[${ne(t.index)}]`;case"sliceAccess":return`${ne(t.object)}[${ne(t.start)}:${ne(t.end)}]`;case"binaryOp":return`(${ne(t.left)}${t.op}${ne(t.right)})`;case"unaryOp":return`(${t.op}${ne(t.operand)})`;case"ternary":return`(${ne(t.condition)}?${ne(t.consequent)}:${ne(t.alternate)})`;case"inExpr":return`(${ne(t.element)} in ${ne(t.collection)})`;case"isExpr":return`(${ne(t.value)} is ${t.typeName})`;case"listLiteral":return`[${t.elements.map(ne).join(",")}]`;case"mapLiteral":return`{${t.entries.map(e=>`${ne(e.key)}:${ne(e.value)}`).join(",")}}`;case"pathLiteral":return t.raw;case"functionCall":return`${t.name}(${t.args.map(ne).join(",")})`}}function Nr(t){return t.type==="binaryOp"&&t.op==="&&"?[...Nr(t.left),...Nr(t.right)]:[t]}function ku(t,e,r){const n=zn(t,""),s=zn(e,""),i=new Map;for(const{block:a,normalizedPath:o}of n)i.has(o)||i.set(o,a);for(const{block:a,normalizedPath:o}of s){const c=i.get(o);if(!c){a.allows.length>0&&r.push({rule:"RULES_WEAKENED",severity:"warning",message:`Match block removed: ${o}`,location:{matchPath:o}});continue}for(const u of a.allows){const f=[...u.operations].sort().join(","),l=c.allows.find(b=>[...b.operations].sort().join(",")===f),p=u.operations.join(", ");if(!l){r.push({rule:"RULES_WEAKENED",severity:"warning",message:`Allow rule removed: ${o} allow ${p}`,location:{matchPath:o}});continue}const y=Nr(u.condition).map(ne),v=new Set(Nr(l.condition).map(ne));for(const b of y)v.has(b)||r.push({rule:"RULES_WEAKENED",severity:"warning",message:`Predicate removed from ${o} allow ${p}: ${b}`,location:{matchPath:o}})}}}function Vn(t,e={}){const r=[];r.push(...eu(t)),hu(t,r);const n=Or(t);if(!n.ok)return{warnings:r,metrics:{sourceSize:t.length,functionCount:0,allowRuleCount:0,maxChainDepth:0,maxChainOp:"",maxLetBindings:0,maxLetBindingsFunction:"",maxCallDepth:0,maxEstimatedExpressions:0,getCallCount:0},parseError:n.error};const s=n.ast,i=qa(s.service.match),a=Pa(s.service.match);if(pu(i,r),fu(i,r),mu(a,r),yu(a,i,r),vu(a,i,r),bu(a,i,r),wu(a,i,r),r.push(...du(s,{allowDebug:e.allowDebug||!!(e.testCases&&e.testCases.length>0)})),Au(a,r),Ua(s.service.match,r),e.testCases&&e.testCases.length>0&&Su(a,i,e.testCases,r),e.previousSource){const v=Or(e.previousSource);v.ok&&ku(s.service.match,v.ast.service.match,r)}let o={depth:0,op:""},c={count:0,fn:""};for(const v of i){const b=$n(v.body);b.depth>o.depth&&(o={depth:b.depth,op:b.op}),v.lets.length>c.count&&(c={count:v.lets.length,fn:v.name})}const u=Da(i);let f=0;for(const v of i){const b=As(v.name,u);b>f&&(f=b)}const l=new Map;for(const v of i)l.set(v.name,v);let p=0,y=0;for(const v of a){const b=Fa(v.rule.condition,l);b>y&&(y=b)}return{warnings:r,metrics:{sourceSize:t.length,functionCount:i.length,allowRuleCount:a.length,maxChainDepth:o.depth,maxChainOp:o.op,maxLetBindings:c.count,maxLetBindingsFunction:c.fn,maxCallDepth:f,maxEstimatedExpressions:p,getCallCount:y}}}const Is={atomic:["cloud.firestore"],auth:["cloud.firestore","firebase.storage"],content:["cloud.firestore"],counters:["cloud.firestore"],geometry:["cloud.firestore"],joining:["cloud.firestore"],lifecycle:["cloud.firestore"],lobby:["cloud.firestore"],membership:["cloud.firestore","firebase.storage"],spaces:["cloud.firestore"],state:["cloud.firestore"],"storage/metadata":["firebase.storage"],"storage/objects":["firebase.storage"],"storage/time":["firebase.storage"],"storage/uploads":["firebase.storage"],timing:["cloud.firestore"],transitions:["cloud.firestore"],turns:["cloud.firestore"],validation:["cloud.firestore"]};Object.freeze(Object.keys(Is).sort());const Eu={atomic:[],auth:["storage-rules#125","firestore-rules#189"],content:[],counters:[],geometry:[],joining:[],lifecycle:[],lobby:[],membership:["storage-rules#125","firestore-rules#189"],spaces:[],state:[],"storage/metadata":["storage-rules#132"],"storage/objects":["storage-rules#132"],"storage/time":["storage-rules#132"],"storage/uploads":["storage-rules#132"],timing:[],transitions:[],turns:[],validation:[]},Ba=["exists","existsAfter","get","getAfter"],Tu=["addedKeys","affectedKeys","bind","changedKeys","concat","date","day","dayOfWeek","dayOfYear","diff","difference","distance","get","hasAll","hasAny","hasOnly","hours","intersection","join","keys","latitude","longitude","lower","matches","minutes","month","nanos","removeAll","removedKeys","replace","seconds","size","split","time","toBase64","toHexString","toMillis","toSet","toUtf8","trim","unchangedKeys","union","upper","values","year"],Ou={addedKeys:["mapdiff"],affectedKeys:["mapdiff"],bind:["path"],changedKeys:["mapdiff"],concat:["list"],date:["timestamp"],day:["timestamp"],dayOfWeek:["timestamp"],dayOfYear:["timestamp"],diff:["map"],difference:["set"],distance:["latlng"],get:["map"],hasAll:["list","set"],hasAny:["list","set"],hasOnly:["list","set"],hours:["timestamp"],intersection:["set"],join:["list"],keys:["map"],latitude:["latlng"],longitude:["latlng"],lower:["string"],matches:["string"],minutes:["timestamp"],month:["timestamp"],nanos:["duration","timestamp"],removeAll:["list"],removedKeys:["mapdiff"],replace:["string"],seconds:["duration","timestamp"],size:["bytes","list","map","set","string"],split:["string"],time:["timestamp"],toBase64:["bytes"],toHexString:["bytes"],toMillis:["timestamp"],toSet:["list"],toUtf8:["string"],trim:["string"],unchangedKeys:["mapdiff"],union:["set"],upper:["string"],values:["map"],year:["timestamp"]},za={cast:["float","int","path","string"],duration:["abs","time","value"],hashing:["crc32","crc32c","md5","sha256"],latlng:["value"],math:["abs","ceil","floor","isNaN","pow","round","sqrt"],timestamp:["date","value"]},Cu=["request","request.auth","request.auth.token","request.auth.uid","request.method","request.path","request.resource","request.resource.contentType","request.resource.metadata","request.resource.size","request.time","resource","resource.bucket","resource.contentType","resource.generation","resource.metadata","resource.metageneration","resource.name","resource.size","resource.timeCreated","resource.updated"],Ru=["get","hasAll","keys","matches","size","split"],Nu={get:["map"],hasAll:["set"],keys:["map"],matches:["string"],size:["list","map","string"],split:["string"]},Va={duration:["value"],firestore:["exists","get"],timestamp:["date","value"]},Lu=new Set(Cu),Mu=["request.auth.token","request.resource.metadata","resource.metadata"];function Du(t,e){if(e.length===1)return!0;if(t==="firebase.storage"){const r=e.join(".");return Lu.has(r)||Mu.some(n=>r.startsWith(`${n}.`))}return e[0]==="request"?e[1]==="auth"||e[1]==="query"?!0:["time","method","path"].includes(e[1])?e.length===2:e[1]==="resource"&&(e.length===2||e[2]==="data"):e[0]==="resource"&&(e.length===1||e[1]==="data")}function Lr(t,e){return e[0]==="request"&&e[1]==="auth"&&e[2]==="token"?!0:t==="firebase.storage"?e[0]==="resource"&&e[1]==="metadata"||e[0]==="request"&&e[1]==="resource"&&e[2]==="metadata":e[0]==="resource"&&e[1]==="data"||e[0]==="request"&&e[1]==="resource"&&e[2]==="data"||e[0]==="request"&&e[1]==="query"}function Fu(t,e){if(!e||e==="unknown-ambient")return null;const r=e.join(".");return r==="request.resource"||r==="resource"?"resource":r==="request.auth"||r==="request.auth.token"||t==="cloud.firestore"&&(r==="request.resource.data"||r==="resource.data"||r==="request.query")||r==="request.resource.metadata"||r==="resource.metadata"?"map":r==="request.auth.uid"||r==="request.method"||r==="request.resource.contentType"||r==="resource.contentType"||t==="firebase.storage"&&(r.startsWith("request.resource.metadata.")||r.startsWith("resource.metadata."))?"string":r==="request.path"?"path":r==="request.time"||r==="resource.timeCreated"||r==="resource.updated"?"timestamp":["request.resource.size","resource.size","resource.generation","resource.metageneration"].includes(r)?"number":null}function ni(t){if(t.type!=="methodCall")return null;if(t.object.type==="identifier"){if(t.object.name==="firestore"){if(t.method==="get")return"document";if(t.method==="exists")return"boolean"}if(t.object.name==="duration")return"duration";if(t.object.name==="timestamp")return"timestamp";if(t.object.name==="latlng")return"latlng";if(t.object.name==="hashing")return"bytes";if(t.object.name==="math")return"number";if(t.object.name==="cast"){if(t.method==="string")return"string";if(t.method==="path")return"path";if(t.method==="int"||t.method==="float")return"number"}}return["lower","upper","trim","replace","join","toBase64","toHexString"].includes(t.method)?"string":["matches","hasAny","hasAll","hasOnly"].includes(t.method)?"boolean":["concat","removeAll","split","values"].includes(t.method)?"list":["keys","toSet","addedKeys","removedKeys","changedKeys","affectedKeys","unchangedKeys","difference","union","intersection"].includes(t.method)?"set":t.method==="diff"?"mapdiff":t.method==="get"?null:t.method==="toUtf8"?"bytes":t.method==="date"?"timestamp":["size","year","month","day","hours","minutes","seconds","nanos","dayOfWeek","dayOfYear","toMillis","latitude","longitude","distance"].includes(t.method)?"number":null}const ju=new Set(Ba),qu=Object.fromEntries(Object.entries(za).map(([t,e])=>[t,new Set(e)])),Pu=Object.fromEntries(Object.entries(Va).map(([t,e])=>[t,new Set(e)]));function rt(t,e){return t.some(r=>we(r,e)!==null)?"unknown-ambient":null}function Ha(t,e,r){const n=r.declarations?.get(t),s=new Map(n?.aliases),i=new Map(n?.receiverTypes);return t.parameters.forEach((a,o)=>{s.set(a,e[o]?.provenance??null),i.set(a,e[o]?.receiverType??null)}),{aliases:s,receiverTypes:i,functions:n?.functions??r.functions,service:r.service,stack:new Set([...r.stack,t.name]),declarations:r.declarations}}function Wt(t,e){return{expression:t,provenance:we(t,e),receiverType:le(t,e)}}function we(t,e){if(t.type==="identifier")return t.name==="request"||t.name==="resource"?[t.name]:e.aliases.get(t.name)??null;if(t.type==="memberAccess"){const r=we(t.object,e);return r==="unknown-ambient"?r:r?[...r,t.property]:null}if(t.type==="bracketAccess"){const r=we(t.object,e);return!r||r==="unknown-ambient"?r:t.index.type==="literal"&&typeof t.index.value=="string"?[...r,t.index.value]:[...r,"*"]}if(t.type==="ternary"){const r=we(t.consequent,e),n=we(t.alternate,e);return!r&&!n?null:Array.isArray(r)&&Array.isArray(n)&&r.join(".")===n.join(".")?r:"unknown-ambient"}if(t.type==="functionCall"){const r=e.functions.get(t.name),n=t.args.map(i=>Wt(i,e));if(!r&&ju.has(t.name))return null;if(!r||e.stack.has(r.name))return n.some(({provenance:i})=>i!==null)?"unknown-ambient":null;const s=Ha(r,n,e);for(const i of r.lets){const a=Wt(i.value,s);s.aliases.set(i.name,a.provenance),s.receiverTypes.set(i.name,a.receiverType)}return we(r.body,s)}if(t.type==="methodCall"&&t.object.type==="identifier"&&t.object.name==="firestore"&&(t.method==="get"||t.method==="exists"))return null;switch(t.type){case"literal":return null;case"methodCall":return rt([t.object,...t.args],e);case"sliceAccess":return rt([t.object,t.start,t.end],e);case"binaryOp":return rt([t.left,t.right],e);case"unaryOp":return rt([t.operand],e);case"inExpr":return rt([t.element,t.collection],e);case"isExpr":return rt([t.value],e);case"listLiteral":return rt(t.elements,e);case"mapLiteral":return rt(t.entries.flatMap(({key:r,value:n})=>[r,n]),e);case"pathLiteral":return rt(t.segments.filter(r=>typeof r!="string"),e);default:return null}}function le(t,e){const r=Fu(e.service,we(t,e));if(r)return r;switch(t.type){case"identifier":{const n=e.receiverTypes.get(t.name);return n||((e.service==="cloud.firestore"?qu:Pu)[t.name]||t.name==="firestore"?"namespace":null)}case"literal":return t.value===null?"null":typeof t.value=="string"?"string":typeof t.value=="number"?"number":typeof t.value=="boolean"?"boolean":null;case"listLiteral":return"list";case"mapLiteral":return"map";case"pathLiteral":return"path";case"memberAccess":{const n=le(t.object,e);if(n==="mixed")return"mixed";if(t.property==="data"&&n==="document")return"map";if(t.object.type==="mapLiteral"){const s=t.object.entries.find(({key:i})=>i.type==="literal"&&i.value===t.property);return s?le(s.value,e):null}return null}case"bracketAccess":{const n=le(t.object,e);if(n==="mixed")return"mixed";if(t.object.type==="listLiteral"&&t.index.type==="literal"&&typeof t.index.value=="number"&&Number.isInteger(t.index.value)){const i=t.object.elements[t.index.value];return i?le(i,e):null}if(t.object.type==="mapLiteral"&&t.index.type==="literal"){const i=t.index.value,a=t.object.entries.find(({key:o})=>o.type==="literal"&&o.value===i);return a?le(a.value,e):null}if(n==="string")return"string";const s=we(t.object,e);return e.service==="firebase.storage"&&Array.isArray(s)&&(s.join(".")==="request.resource.metadata"||s.join(".")==="resource.metadata")?"string":null}case"sliceAccess":{const n=le(t.object,e);return n==="mixed"?"mixed":n==="list"||n==="string"?n:null}case"methodCall":{const n=ni(t);if(t.object.type==="identifier"&&n)return n;if(t.method==="get"){const s=we(t.object,e);if(e.service==="firebase.storage"&&Array.isArray(s)&&(s.join(".")==="request.resource.metadata"||s.join(".")==="resource.metadata"))return"string";const i=t.args[1];if(t.object.type==="mapLiteral"&&t.args[0]?.type==="literal"){const a=t.args[0].value,o=t.object.entries.find(({key:c})=>c.type==="literal"&&c.value===a);return o?le(o.value,e):i?le(i,e):null}return i&&le(i,e)?"mixed":null}return ni(t)}case"binaryOp":{const n=le(t.left,e),s=le(t.right,e);return t.op==="+"&&(n==="string"||s==="string")?"string":["==","!=","<","<=",">",">=","&&","||"].includes(t.op)?"boolean":["+","-","*","/","%"].includes(t.op)&&n==="number"&&s==="number"?"number":null}case"unaryOp":return t.op==="!"?"boolean":t.op==="-"&&le(t.operand,e)==="number"?"number":null;case"inExpr":case"isExpr":return"boolean";case"ternary":{const n=le(t.consequent,e),s=le(t.alternate,e);return!n&&!s?null:n===s?n:"mixed"}case"functionCall":{const n=e.functions.get(t.name);if(!n&&e.service==="cloud.firestore"){if(t.name==="get"||t.name==="getAfter")return"document";if(t.name==="exists")return"boolean"}if(!n||e.stack.has(n.name))return null;const s=Ha(n,t.args.map(i=>Wt(i,e)),e);for(const i of n.lets){const a=Wt(i.value,s);s.aliases.set(i.name,a.provenance),s.receiverTypes.set(i.name,a.receiverType)}return le(n.body,s)}default:return null}}function $u(t){return t.match(/^\.\/stdlib\/(.+?)(?:\.rules)?$/)?.[1]??t}function Uu(t,e,r){const n=$u(e),s=Is[n];return s?s.includes(t)?null:`Function '${r}' from module '${e}' is not compatible with service '${t}'`:null}function Bu(t){throw new Error(`Unhandled Rules expression: ${JSON.stringify(t)}`)}const zu=new Set(Ba),Vu=new Set(Tu),Hu=Object.fromEntries(Object.entries(za).map(([t,e])=>[t,new Set(e)])),Wu=new Set(Ru),Gu=Object.fromEntries(Object.entries(Va).map(([t,e])=>[t,new Set(e)]));function Mr(t,e){return t==="unknown-ambient"?"binding '<derived ambient value>'":t&&!Du(e,t)?`binding '${t.join(".")}'`:null}function Ku(t,e,r,n,s){if(e!=="get"&&e!=="keys"&&e!=="values")return null;const i=we(t,s);if(i==="unknown-ambient")return"binding '<derived ambient value>'";if(!i)return null;if(e==="get"){const a=r[0];if(a?.type==="literal"&&typeof a.value=="string")return Mr([...i,a.value],n);if(!Lr(n,i))return`binding '${i.join(".")}.get(...)'`}return(e==="keys"||e==="values")&&!Lr(n,i)?`binding '${i.join(".")}.${e}()'`:null}function Zu(t,e,r,n){const s=we(t,n),i=le(t,n);if(!i){if(s==="unknown-ambient")return"binding '<derived ambient receiver>'";let c=t;for(;c.type==="memberAccess"||c.type==="bracketAccess"||c.type==="methodCall"&&c.method==="get";)c=c.object;const u=le(c,n);return u==="map"||u==="list"||u==="document"?`method '.${e}()' has an unresolved projected receiver`:null}const o=(r==="cloud.firestore"?Ou:Nu)[e];return o?.includes(i)?null:`method '.${e}()' requires ${o?.join("|")??"an accepted"} receiver, got ${i}`}function Ju(t,e,r,n){const s=we(e,n);return s==="unknown-ambient"?"binding '<derived ambient value>'":s?t.type==="literal"&&typeof t.value=="string"?Mr([...s,t.value],r):Lr(r,s)?null:`binding '<value> in ${s.join(".")}'`:null}function si(t,e,r){const n=s=>{switch(s.type){case"memberAccess":{const i=Mr(we(s,r),e);return i||n(s.object)}case"functionCall":{const i=r.functions.get(s.name);if(!i&&e==="firebase.storage")return`function '${s.name}()'`;if(!i&&!zu.has(s.name))return`function '${s.name}()'`;for(const a of s.args){const o=n(a);if(o)return o}if(i&&!r.stack.has(i.name)){const a=new Map,o=new Map;i.parameters.forEach((u,f)=>{const l=s.args[f];a.set(u,l?we(l,r):null),o.set(u,l?le(l,r):null)});const c=Wa(i,e,{aliases:a,receiverTypes:o,functions:r.functions,service:e,stack:new Set([...r.stack,i.name])});if(c)return c}return null}case"methodCall":{if(s.object.type==="identifier"&&!r.aliases.has(s.object.name)){const u=(e==="cloud.firestore"?Hu:Gu)[s.object.name];if(u){if(!u.has(s.method))return`method '${s.object.name}.${s.method}()'`;for(const f of s.args){const l=n(f);if(l)return l}return null}return s.object.name==="firestore"?`method 'firestore.${s.method}()'`:`namespace '${s.object.name}'`}if(!(e==="cloud.firestore"?Vu:Wu).has(s.method))return`method '.${s.method}()'`;const a=Zu(s.object,s.method,e,r);if(a)return a;const o=Ku(s.object,s.method,s.args,e,r);return o||(n(s.object)??s.args.map(n).find(Boolean)??null)}case"binaryOp":return n(s.left)??n(s.right);case"unaryOp":return n(s.operand);case"bracketAccess":{const i=we(s.object,r);if(i==="unknown-ambient")return"binding '<derived ambient value>[...]'";const a=s.index.type==="literal"&&typeof s.index.value=="string";if(i&&!a)return Lr(e,i)?n(s.object)??n(s.index):`binding '${i.join(".")}[...]'`;const o=Mr(we(s,r),e);return o||(n(s.object)??n(s.index))}case"sliceAccess":return n(s.object)??n(s.start)??n(s.end);case"ternary":return n(s.condition)??n(s.consequent)??n(s.alternate);case"inExpr":return Ju(s.element,s.collection,e,r)??n(s.element)??n(s.collection);case"isExpr":return n(s.value);case"listLiteral":return s.elements.map(n).find(Boolean)??null;case"mapLiteral":for(const i of s.entries){const a=n(i.key)??n(i.value);if(a)return a}return null;case"pathLiteral":for(const i of s.segments)if(typeof i!="string"){const a=n(i);if(a)return a}return null;case"literal":return null;case"identifier":return s.name==="request"||s.name==="resource"||r.aliases.has(s.name)?null:`identifier '${s.name}'`;default:return Bu(s)}};return n(t)}function Wa(t,e,r){const n=new Map(r.aliases),s=new Map(r.receiverTypes),i={...r,aliases:n,receiverTypes:s};for(const a of t.lets){const o=si(a.value,e,i);if(o)return o;n.set(a.name,we(a.value,i)),s.set(a.name,le(a.value,i))}return si(t.body,e,i)}function Yu(t,e,r=new Map([[t.name,t]]),n=[]){const s={aliases:new Map,receiverTypes:new Map,functions:r,service:e,stack:new Set([t.name])};return Wa(t,e,{aliases:new Map(t.parameters.map((i,a)=>[i,a<n.length?n[a]?.provenance??null:null])),receiverTypes:new Map(t.parameters.map((i,a)=>[i,n[a]?le(n[a].expression,s)??n[a].receiverType??null:null])),functions:r,service:e,stack:new Set([t.name])})}function Qu(t){throw new Error(`Unhandled Rules expression: ${JSON.stringify(t)}`)}function Xu(t){return t.replace(/^\.\.\//,"_").replace(/^\.\//,"").replace(/[.\/-]/g,"_")}function re(t,e){switch(t.type){case"functionCall":{const r=e.get(t.name)??t.name,n=t.args.map(s=>re(s,e));return r===t.name&&n.every((s,i)=>s===t.args[i])?t:{...t,name:r,args:n}}case"binaryOp":{const r=re(t.left,e),n=re(t.right,e);return r===t.left&&n===t.right?t:{...t,left:r,right:n}}case"unaryOp":{const r=re(t.operand,e);return r===t.operand?t:{...t,operand:r}}case"methodCall":{const r=re(t.object,e),n=t.args.map(s=>re(s,e));return r===t.object&&n.every((s,i)=>s===t.args[i])?t:{...t,object:r,args:n}}case"memberAccess":{const r=re(t.object,e);return r===t.object?t:{...t,object:r}}case"bracketAccess":{const r=re(t.object,e),n=re(t.index,e);return r===t.object&&n===t.index?t:{...t,object:r,index:n}}case"sliceAccess":{const r=re(t.object,e),n=re(t.start,e),s=re(t.end,e);return r===t.object&&n===t.start&&s===t.end?t:{...t,object:r,start:n,end:s}}case"ternary":{const r=re(t.condition,e),n=re(t.consequent,e),s=re(t.alternate,e);return r===t.condition&&n===t.consequent&&s===t.alternate?t:{...t,condition:r,consequent:n,alternate:s}}case"inExpr":{const r=re(t.element,e),n=re(t.collection,e);return r===t.element&&n===t.collection?t:{...t,element:r,collection:n}}case"isExpr":{const r=re(t.value,e);return r===t.value?t:{...t,value:r}}case"listLiteral":{const r=t.elements.map(n=>re(n,e));return r.every((n,s)=>n===t.elements[s])?t:{...t,elements:r}}case"mapLiteral":{const r=t.entries.map(n=>{const s=re(n.key,e),i=re(n.value,e);return s===n.key&&i===n.value?n:{key:s,value:i}});return r.every((n,s)=>n===t.entries[s])?t:{...t,entries:r}}case"pathLiteral":{const r=t.segments.map(n=>typeof n=="string"?n:re(n,e));return r.every((n,s)=>n===t.segments[s])?t:{...t,segments:r}}case"literal":case"identifier":return t;default:return Qu(t)}}function el(t,e){const r=Xu(e),n=new Map;for(const s of t)s.exported||n.set(s.name,`${r}__${s.name}`);return n.size===0?t:t.map(s=>{const i=re(s.body,n),a=s.lets.map(c=>{const u=re(c.value,n);return u===c.value?c:{...c,value:u}}),o=s.exported?s.name:n.get(s.name)??s.name;return i===s.body&&a===s.lets&&o===s.name?s:{...s,name:o,body:i,lets:a}})}function tl(t){throw new Error(`Unhandled Rules expression: ${JSON.stringify(t)}`)}function xs(t){const e=[],r=n=>{switch(n.type){case"functionCall":e.push(n),n.args.forEach(r);break;case"binaryOp":r(n.left),r(n.right);break;case"unaryOp":r(n.operand);break;case"methodCall":r(n.object),n.args.forEach(r);break;case"memberAccess":r(n.object);break;case"bracketAccess":r(n.object),r(n.index);break;case"sliceAccess":r(n.object),r(n.start),r(n.end);break;case"ternary":r(n.condition),r(n.consequent),r(n.alternate);break;case"inExpr":r(n.element),r(n.collection);break;case"isExpr":r(n.value);break;case"listLiteral":n.elements.forEach(r);break;case"mapLiteral":n.entries.forEach(({key:s,value:i})=>{r(s),r(i)});break;case"pathLiteral":n.segments.forEach(s=>{typeof s!="string"&&r(s)});break;case"literal":case"identifier":break;default:tl(n)}};return r(t),e}function rl(t){return{expression:t.expression,provenance:t.provenance,receiverType:!t.receiverType||t.receiverType==="mixed"?"unknown":t.receiverType}}function nl(t,e){const r=[],n=new Map,s=t.service.name==="firebase.storage"?"firebase.storage":"cloud.firestore",i=(l,p=new Set)=>({aliases:new Map(l.aliases),receiverTypes:new Map(l.receiverTypes),functions:l.functions,service:s,stack:p,declarations:n}),a=(l,p,y)=>{if(y.has(l.name))return;const v=n.get(l);if(!v)return;const b=new Map(v.aliases),R=new Map(v.receiverTypes);l.parameters.forEach((k,x)=>{b.set(k,p[x]?.provenance??null),R.set(k,p[x]?.receiverType??null)});const C=i({aliases:b,receiverTypes:R,functions:v.functions},new Set([...y,l.name]));for(const k of l.lets){o(k.value,C);const x=Wt(k.value,C);C.aliases.set(k.name,x.provenance),C.receiverTypes.set(k.name,x.receiverType)}o(l.body,C)},o=(l,p)=>{for(const y of xs(l)){const v=y.args.map(R=>Wt(R,p));y.name===e&&r.push({arguments:v.map(rl)});const b=p.functions.get(y.name);b&&a(b,v,p.stack)}},c=new Map((t.functions??[]).map(l=>[l.name,l])),u=new Map(c);for(const l of t.service.functions??[])u.set(l.name,l);for(const l of t.functions??[])n.set(l,{aliases:new Map,receiverTypes:new Map,functions:c});for(const l of t.service.functions??[])n.set(l,{aliases:new Map,receiverTypes:new Map,functions:u});const f=(l,p)=>{const y=new Map(p.receiverTypes);for(const C of l.path.segments)C.type==="wildcard"&&y.set(C.name,"string"),C.type==="recursive"&&y.set(C.name,"path");const v=new Map(p.functions),b={aliases:p.aliases,receiverTypes:y,functions:v};for(const C of l.functions)v.set(C.name,C),n.set(C,b);const R=i(b);for(const{condition:C}of l.allows)o(C,R);l.children.forEach(C=>f(C,b))};return f(t.service.match,{aliases:new Map,receiverTypes:new Map,functions:u}),r}function _t(t){return xs(t).map(({name:e})=>e)}function sl(t,e){return[...t.values()].flatMap(n=>[...n.lets.map(({value:s})=>s),n.body]).flatMap(xs).filter(({name:n})=>n===e).map(({args:n})=>n)}function il(t,e,r){const n=Vc(t,e);return n===null?{success:!1,error:{code:"PARSE_FAILED",message:`Failed to parse module '${e}'`}}:{success:!0,functions:n,bundled:r}}function ii(t){return t.startsWith("./")||t.startsWith("../")}function Hn(t){return/^\.\/stdlib\/([A-Za-z0-9_-]+(?:\/[A-Za-z0-9_-]+)*)\.rules$/.exec(t)?.[1]??null}function al(t,e,r,n=new Set){if(r?.modules&&Object.prototype.hasOwnProperty.call(r.modules,e))return il(r.modules[e],e,n.has(e));if(ii(e)&&r?.basePath){const i=`${r.basePath}/${e}${e.endsWith(".rules")?"":".rules"}`;if(!Hn(e))return{success:!1,error:{code:"UNKNOWN_MODULE",message:`Module '${e}' not found at ${i}`}}}return Hn(e)?{success:!1,error:{code:"UNKNOWN_MODULE",message:`Module '${e}' not found`}}:ii(e)?{success:!1,error:{code:"UNKNOWN_MODULE",message:`Module '${e}' requires basePath for relative imports`}}:{success:!1,error:{code:"UNKNOWN_MODULE",message:`Module '${e}' not found`}}}function ol(t,e,r,n=new Set){const s=Or(e);if(!s.ok){const{line:M,column:z,message:ee}=s.error;return{success:!1,error:{code:"PARSE_FAILED",message:`Failed to parse source at line ${M}, col ${z}: ${ee}`}}}const i=s.ast,a=i.version==="2+modules",o=i.service.name==="firebase.storage";let c=o?"storage.rules":"firestore.rules";if(a&&(c=o?"storage.modules.rules":"firestore.modules.rules"),r!==void 0&&r.sourceFile!==void 0&&r.sourceFile!==""&&(c=r.sourceFile),cl(i,c),a===!1)return{success:!1,error:{code:"NOT_MODULE_SOURCE",message:`Version '${i.version}' is not a module source`}};if(i.service.name==="cloud.firestore"===!1&&i.service.name==="firebase.storage"===!1)return{success:!1,error:{code:"UNSUPPORTED_SERVICE",message:`Module resolution does not support service '${i.service.name}'`}};if(i.imports.length===0){i.version="2";const M=Pn(i),z=JSON.stringify(M.sourceMap);return{success:!0,data:{resolved:`${M.resolved}// @pyric-source-map: ${z}
|
|
478
|
+
`,modules:[],bundledModules:[],evidenceIds:[],sourceMap:M.sourceMap}}}const p=i.imports.find(M=>M.functions.length===0);if(p)return{success:!1,error:{code:"UNKNOWN_FUNCTION",message:`Import from '${p.module}' must request at least one function`}};const y=new Map,v=new Map,b=new Map,R=new Map,C=[],k=[],x=new Map;for(const M of i.imports){const z=al(t,M.module,r,n);if(!z.success)return{success:!1,error:z.error};C.includes(M.module)||C.push(M.module),z.bundled&&!k.includes(M.module)&&k.push(M.module);const ee=new Set,Te=z.functions.find(Z=>ee.has(Z.name)?!0:(ee.add(Z.name),!1));if(Te)return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Module '${M.module}' defines duplicate function '${Te.name}'`}};const Q=z.functions.find(Z=>Ir.has(Z.name));if(Q)return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Function '${Q.name}' from module '${M.module}' conflicts with a Rules builtin`}};const Be=new Set;for(const Z of z.functions)Z.exported||Be.add(Z.name);x.set(M.module,Be);const pn=el(z.functions,M.module),Fs=new Set;for(const Z of pn){if(Fs.has(Z.name))return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Module '${M.module}' defines conflicting function name '${Z.name}'`}};Fs.add(Z.name)}const jo=new Set(pn.filter(Z=>Z.exported).map(Z=>Z.name));for(const Z of pn){const St=R.get(Z.name);if(St&&St!==M.module)return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Function '${Z.name}' from module '${M.module}' conflicts with module '${St}'`}};if(R.set(Z.name,M.module),v.set(Z.name,Z),Z.exported){if(y.has(Z.name)&&b.get(Z.name)!==M.module)return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Function '${Z.name}' exported by both '${b.get(Z.name)}' and '${M.module}'`}};y.set(Z.name,Z),b.set(Z.name,M.module)}}for(const Z of M.functions){if(!jo.has(Z))return{success:!1,error:{code:"UNKNOWN_FUNCTION",message:x.get(M.module)?.has(Z)?`Function '${Z}' in module '${M.module}' is not exported`:`Function '${Z}' not found in module '${M.module}'`}};if(i.service.name==="cloud.firestore"||i.service.name==="firebase.storage"){const St=z.bundled?Uu(i.service.name,M.module,Z):null;if(St)return{success:!1,error:{code:"INCOMPATIBLE_FUNCTION",message:St}}}}}const L=new Set(i.imports.flatMap(M=>M.functions)),$=[],S=new Set,T=[],_={cycle:null};function w(M){if(_.cycle)return;const z=T.indexOf(M);if(z>=0){_.cycle=[...T.slice(z),M];return}if(S.has(M))return;const ee=v.get(M);if(!ee)return;T.push(M);const Te=_t(ee.body);for(const Q of ee.lets)Te.push(..._t(Q.value));for(const Q of Te)v.has(Q)&&!Ir.has(Q)&&w(Q);T.pop(),!_.cycle&&(S.add(M),$.push({...ee,exported:!1}))}for(const M of i.imports)for(const z of M.functions)w(z);if(_.cycle)return{success:!1,error:{code:"CIRCULAR_DEPENDENCY",message:`Recursive module function dependency: ${_.cycle.join(" -> ")}`}};for(const M of $){const z=R.get(M.name),Te=[...M.lets.flatMap(({value:Q})=>_t(Q)),..._t(M.body)].find(Q=>{const Be=R.get(Q);return Be&&Be!==z&&!L.has(Q)});if(Te)return{success:!1,error:{code:"UNKNOWN_FUNCTION",message:`Function '${M.name}' in module '${z}' cannot call '${Te}' from another module`}}}const A=new Set($.map(M=>M.name)),I=new Map((i.functions??[]).map(M=>[M.name,M])),h=new Set((i.service.functions??[]).map(M=>M.name)),d=(M,z)=>M.flatMap(_t).find(ee=>y.has(ee)&&!A.has(ee)&&!z.has(ee))??null,g=M=>M.flatMap(z=>[...z.lets.map(({value:ee})=>ee),z.body]),m=new Set(I.keys());let F=d(g(i.functions??[]),m);const E=new Set([...m,...h]);F??=d(g(i.service.functions??[]),E);const O=(M,z)=>{const ee=new Set([...z,...M.functions.map(Q=>Q.name)]),Te=[...g(M.functions),...M.allows.map(({condition:Q})=>Q)];return d(Te,ee)??M.children.map(Q=>O(Q,ee)).find(Boolean)??null};if(F??=O(i.service.match,E),F)return{success:!1,error:{code:"UNKNOWN_FUNCTION",message:`Source calls function '${F}' from module '${b.get(F)}' without importing it`}};const D=(M,z)=>{if(z.has(M.name))return!1;const ee=new Set([...z,M.name]);return[...M.lets.flatMap(({value:Q})=>_t(Q)),..._t(M.body)].some(Q=>{const Be=I.get(Q);return Be?D(Be,ee):A.has(Q)||h.has(Q)})},Y=[...I.values()].find(M=>D(M,new Set));if(Y)return{success:!1,error:{code:"INCOMPATIBLE_FUNCTION",message:`Global function '${Y.name}' cannot call a service-scoped function`}};if(i.service.name==="firebase.storage"||i.service.name==="cloud.firestore"){const M=new Map($.map(z=>[z.name,z]));for(const z of $){const ee=[...nl(i,z.name),...sl(M,z.name).map(Q=>({arguments:Q.map(Be=>({expression:Be,provenance:null,receiverType:"unknown"}))}))],Te=ee.length>0?ee:[{arguments:[]}];for(const{arguments:Q}of Te){const Be=Yu(z,i.service.name,v,Q);if(Be)return{success:!1,error:{code:"INCOMPATIBLE_FUNCTION",message:`Function '${z.name}' requires unsupported ${Be} for service '${i.service.name}'`}}}}}const Ee=new Set([...(i.functions??[]).map(M=>M.name),...(i.service.functions??[]).map(M=>M.name)]),ze=M=>{M.functions.forEach(z=>Ee.add(z.name)),M.children.forEach(ze)};ze(i.service.match);const Pt=[...Ee].find(M=>Ir.has(M));if(Pt)return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Source function '${Pt}' conflicts with a Rules builtin`}};for(const M of $)if(Ee.has(M.name))return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Imported function '${M.name}' conflicts with a function defined in the source`}};i.service.functions=[...$,...i.service.functions??[]],i.version="2",i.imports=[];const $t=new Set,Ut=i.service.name==="firebase.storage"?"storage-rules#":"firestore-rules#";for(const M of k){const z=Hn(M)??M,ee=Eu[z]??[];for(const Te of ee)Te.startsWith(Ut)&&$t.add(Te)}const fn=Pn(i),Fo=JSON.stringify(fn.sourceMap);return{success:!0,data:{resolved:`${fn.resolved}// @pyric-source-map: ${Fo}
|
|
479
479
|
`,modules:C,bundledModules:k,evidenceIds:[...$t].sort(),sourceMap:fn.sourceMap}}}function cl(t,e){if(t.functions!==void 0)for(const a of t.functions)a.loc!==void 0&&(a.loc.file=e);if(t.service.functions!==void 0)for(const a of t.service.functions)a.loc!==void 0&&(a.loc.file=e);const s=[t.service.match];let i=s.length;for(;i>0;){const a=s.pop();a.loc!==void 0&&(a.loc.file=e);for(const c of a.allows)c.loc!==void 0&&(c.loc.file=e);for(const c of a.functions)c.loc!==void 0&&(c.loc.file=e);for(const c of a.children)s.push(c);i=s.length}}function Ga(t,e,r,n,s){if(e===void 0)return;let a=e,o=1;r!==void 0&&(o=r);let u="firestore.rules";n!==void 0&&n!==""&&(u=n);let l;s!==void 0&&(l=s);const y="// @pyric-source-map: ",v=t.indexOf(y);if(v!==-1){const x=v+y.length,L=t.indexOf(`
|
|
480
|
-
`,x);let $="";L!==-1?$=t.slice(x,L).trim():$=t.slice(x).trim();try{const T=JSON.parse($);if(Array.isArray(T)){for(const b of T)if(b.generatedLine===a){a=b.authoredLine,o=b.authoredCol,u=b.authoredFile,b.expression!==void 0&&(l=b.expression);break}}}catch{}}const R=`${u}:${a}:${o}`,C={line:a,col:o,file:u,citation:R};return l!==void 0&&(C.expression=l),C}const oe=Symbol.for("pyric.RulesValue.NO_OP");class te{field(e){return null}callMethod(e,r){return oe}binaryOp(e,r){return oe}}function me(t,e){if(Object.is(t,e))return!0;if(t instanceof te)return t.equals(e);if(e instanceof te)return e.equals(t);if(t instanceof de||e instanceof de)return t instanceof de&&t.equals(e);if(Array.isArray(t)||Array.isArray(e))return!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length?!1:t.every((s,i)=>me(s,e[i]));if(!ai(t)||!ai(e))return!1;const r=Object.keys(t),n=Object.keys(e);return r.length!==n.length?!1:r.every(s=>s in e&&me(t[s],e[s]))}function ai(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}class de{items;constructor(e){this.items=[];for(const r of e)this.items.some(n=>me(n,r))||this.items.push(r)}hasOnly(e){const r=e instanceof de?e.toArray():e;return this.items.every(n=>r.some(s=>me(n,s)))}equals(e){return!(e instanceof de)||e.items.length!==this.items.length?!1:this.items.every(r=>e.items.some(n=>me(r,n)))}hasAll(e){const r=e instanceof de?e.toArray():e;for(const n of r)if(!this.items.some(s=>me(s,n)))return!1;return!0}hasAny(e){const r=e instanceof de?e.toArray():e;for(const n of r)if(this.items.some(s=>me(s,n)))return!0;return!1}size(){return this.items.length}toArray(){return[...this.items]}difference(e){const r=e.toArray(),n=[];for(const s of this.items)r.some(i=>me(s,i))||n.push(s);return new de(n)}union(e){const r=e.toArray();return new de([...this.items,...r])}intersection(e){const r=e.toArray(),n=[];for(const s of this.items)r.some(i=>me(s,i))&&n.push(s);return new de(n)}}class cr{before;after;constructor(e,r){this.before=e,this.after=r}addedKeys(){const e=[];for(const r of Object.keys(this.after))r in this.before||e.push(r);return new de(e)}removedKeys(){const e=[];for(const r of Object.keys(this.before))r in this.after||e.push(r);return new de(e)}changedKeys(){const e=[];for(const r of Object.keys(this.after))r in this.before&&!me(this.before[r],this.after[r])&&e.push(r);return new de(e)}affectedKeys(){const e=[],r=new Set([...Object.keys(this.before),...Object.keys(this.after)]);for(const n of r)(!(n in this.before)||!(n in this.after)||!me(this.before[n],this.after[n]))&&e.push(n);return new de(e)}unchangedKeys(){const e=[];for(const r of Object.keys(this.before))r in this.after&&me(this.before[r],this.after[r])&&e.push(r);return new de(e)}}const ul=/^\{([A-Za-z_][A-Za-z0-9_]*)\}$/;class Qe extends te{typeName="path";segments;bindings;constructor(e,r={}){super(),this.segments=e,this.bindings=r}static fromString(e){const r=e.startsWith("/")?e.slice(1):e;return r.length===0?new Qe([]):new Qe(r.split("/"))}bind(e){const r=[],n={...this.bindings};for(const s of this.segments){const i=s.match(ul);if(!i){r.push(s);continue}const a=i[1];if(a in e){const o=e[a];if(o==null)throw new TypeError(`Path.bind(): binding '${a}' must not be null`);const c=String(o);r.push(c),n[a]=c}else r.push(s)}return new Qe(r,n)}valueOf(){return NaN}toString(){return"/"+this.segments.join("/")}toJSON(){return{__type:"path",segments:[...this.segments]}}equals(e){if(!(e instanceof Qe)||this.segments.length!==e.segments.length)return!1;for(let r=0;r<this.segments.length;r++)if(this.segments[r]!==e.segments[r])return!1;return!0}field(e){if(/^\d+$/.test(e)){const r=Number(e);return r<0||r>=this.segments.length?null:this.segments[r]}return e in this.bindings?this.bindings[e]:null}callMethod(e,r){switch(e){case"bind":{const n=r[0];if(n==null||typeof n!="object"||Array.isArray(n)||n instanceof te)throw new TypeError(`Path.bind() requires a Map argument, got ${n===null?"null":typeof n}`);return this.bind(n)}default:return oe}}}class ae extends te{typeName="float";value;constructor(e){super(),this.value=e}valueOf(){return this.value}toString(){return Number.isInteger(this.value)?`${this.value}.0`:String(this.value)}toJSON(){return{__type:"float",value:this.value}}equals(e){return e instanceof ae?this.value===e.value:typeof e=="number"?this.value===e:!1}binaryOp(e,r){const n=r instanceof ae?r.value:typeof r=="number"?r:void 0;if(n===void 0)return oe;const s=this.value;switch(e){case"+":return new ae(s+n);case"-":return new ae(s-n);case"*":return new ae(s*n);case"/":return new ae(s/n);case"%":return new ae(s%n);case"<":return s<n;case"<=":return s<=n;case">":return s>n;case">=":return s>=n;default:return oe}}}class G extends Error{expr;constructor(e,r){super(e),this.expr=r,this.name="EvalError"}}class gt extends G{constructor(e,r){super(e,r),this.name="UnsupportedError"}}class ll{entries=[];parents=[];frames=[];capture(e,r){const n=this.entries.length,s=this.parents.length>0?this.parents[this.parents.length-1]:null,i={source:ye(e),kind:e.type,parent:s};this.stampFrame(i),this.entries.push(i),this.parents.push(n);try{const a=r();return this.entries[n].value=a,a}catch(a){throw this.entries[n].error=a instanceof Error?a.message:String(a),a}finally{this.parents.pop()}}skip(e){const r=this.parents.length>0?this.parents[this.parents.length-1]:null,n={source:ye(e),kind:e.type,parent:r,skipped:!0};this.stampFrame(n),this.entries.push(n)}enterFrame(e){this.frames.push(e)}exitFrame(){this.frames.pop()}markEntryAsLetBinding(e,r){e<0||e>=this.entries.length||(this.entries[e].letBinding={name:r})}stampFrame(e){this.frames.length!==0&&(e.inlinedFrom={name:this.frames[this.frames.length-1]})}}function dl(t,e,r,n){const i=p=>p*Math.PI/180,a=i(t),o=i(r),c=i(r-t),u=i(n-e),f=Math.sin(c/2)**2+Math.cos(a)*Math.cos(o)*Math.sin(u/2)**2;return 6371e3*(2*Math.atan2(Math.sqrt(f),Math.sqrt(1-f)))}class lt extends te{typeName="latlng";lat;lng;constructor(e,r){super(),this.lat=e,this.lng=r}valueOf(){return NaN}toString(){return`${this.lat},${this.lng}`}toJSON(){return{__type:"latlng",lat:this.lat,lng:this.lng}}equals(e){return e instanceof lt&&this.lat===e.lat&&this.lng===e.lng}callMethod(e,r){switch(e){case"latitude":return this.lat;case"longitude":return this.lng;case"distance":{const n=r[0];if(!(n instanceof lt))throw new TypeError(`latlng.distance() requires a LatLng argument, got ${typeof n}`);return dl(this.lat,this.lng,n.lat,n.lng)}default:return oe}}}const zt=1e9,oi={w:10080*60,d:1440*60,h:3600,m:60,s:1};function hl(t,e){let r=t+Math.trunc(e/zt),n=e%zt;return r>0&&n<0?(r-=1,n+=zt):r<0&&n>0&&(r+=1,n-=zt),{seconds:r,nanos:n}}class ve extends te{typeName="duration";seconds;nanos;constructor(e,r){super();const n=hl(e,r);this.seconds=n.seconds,this.nanos=n.nanos}static fromValue(e,r){if(r in oi)return new ve(e*oi[r],0);if(r==="ms"){const n=Math.trunc(e/1e3),s=e-n*1e3;return new ve(n,s*1e6)}if(r==="ns"){const n=Math.trunc(e/zt),s=e-n*zt;return new ve(n,s)}throw new Error(`Unknown duration unit '${r}' (expected one of: w, d, h, m, s, ms, ns)`)}static fromTime(e,r,n,s){return new ve(e*3600+r*60+n,s)}static abs(e){return new ve(Math.abs(e.seconds),Math.abs(e.nanos))}valueOf(){return this.seconds*1e3+Math.round(this.nanos/1e6)}toString(){const e=this.seconds<0||this.nanos<0,r=Math.abs(this.seconds),n=Math.abs(this.nanos);return`${e?"-":""}${r}.${n.toString().padStart(9,"0")}s`}toJSON(){return{__type:"duration",seconds:this.seconds,nanos:this.nanos}}equals(e){return e instanceof ve&&this.seconds===e.seconds&&this.nanos===e.nanos}callMethod(e,r){switch(e){case"seconds":return this.seconds;case"nanos":return this.nanos;default:return oe}}binaryOp(e,r){if(!(r instanceof ve))return oe;switch(e){case"+":return new ve(this.seconds+r.seconds,this.nanos+r.nanos);case"-":return new ve(this.seconds-r.seconds,this.nanos-r.nanos);case"<":return this.compareTo(r)<0;case"<=":return this.compareTo(r)<=0;case">":return this.compareTo(r)>0;case">=":return this.compareTo(r)>=0;default:return oe}}compareTo(e){return this.seconds!==e.seconds?this.seconds-e.seconds:this.nanos-e.nanos}}const ci=1e9,fl=864e5,bn=86400;function pl(t,e){const r=Math.floor(e/ci);return{seconds:t+r,nanos:e-r*ci}}let _e=class nt extends te{typeName="timestamp";seconds;nanos;constructor(e,r){super();const n=pl(e,r);this.seconds=n.seconds,this.nanos=n.nanos}static fromMillis(e){const r=Math.floor(e/1e3),n=e-r*1e3;return new nt(r,n*1e6)}static fromYMD(e,r,n){return nt.fromMillis(Date.UTC(e,r-1,n))}static fromIsoString(e){return nt.fromMillis(Date.parse(e))}toMillis(){return this.seconds*1e3+Math.floor(this.nanos/1e6)}toDate(){return new Date(this.toMillis())}valueOf(){return this.toMillis()}toString(){const e=new Date(this.toMillis()).toISOString(),r=this.nanos.toString().padStart(9,"0");return e.replace(/\.\d{3}Z$/,`.${r}Z`)}toJSON(){return{__type:"timestamp",seconds:this.seconds,nanos:this.nanos}}equals(e){return e instanceof nt&&this.seconds===e.seconds&&this.nanos===e.nanos}callMethod(e,r){switch(e){case"seconds":return this.seconds;case"nanos":return this.nanos;case"toMillis":return this.toMillis();case"year":return this.asDate().getUTCFullYear();case"month":return this.asDate().getUTCMonth()+1;case"day":return this.asDate().getUTCDate();case"hours":return this.asDate().getUTCHours();case"minutes":return this.asDate().getUTCMinutes();case"dayOfWeek":{const n=this.asDate().getUTCDay();return n===0?7:n}case"dayOfYear":{const n=this.asDate(),s=Date.UTC(n.getUTCFullYear(),0,1);return Math.floor((this.toMillis()-s)/fl)+1}case"date":return nt.fromYMD(this.asDate().getUTCFullYear(),this.asDate().getUTCMonth()+1,this.asDate().getUTCDate());case"time":{const n=(this.seconds%bn+bn)%bn,s=Math.floor(n/3600),i=Math.floor(n%3600/60),a=n%60;return ve.fromTime(s,i,a,this.nanos)}default:return oe}}asDate(){return new Date(this.toMillis())}binaryOp(e,r){if(r instanceof nt)switch(e){case"-":return new ve(this.seconds-r.seconds,this.nanos-r.nanos);case"<":return this.compareTo(r)<0;case"<=":return this.compareTo(r)<=0;case">":return this.compareTo(r)>0;case">=":return this.compareTo(r)>=0;default:return oe}if(r instanceof ve)switch(e){case"+":return new nt(this.seconds+r.seconds,this.nanos+r.nanos);case"-":return new nt(this.seconds-r.seconds,this.nanos-r.nanos);default:return oe}return oe}compareTo(e){return this.seconds!==e.seconds?this.seconds-e.seconds:this.nanos-e.nanos}};const ui="0123456789ABCDEF";function ml(t){let e="";for(let r=0;r<t.length;r++){const n=t[r];e+=ui[n>>>4]+ui[n&15]}return e}function gl(t){let e="";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_")}function yl(t,e){const r=Math.min(t.length,e.length);for(let n=0;n<r;n++)if(t[n]!==e[n])return t[n]<e[n]?-1:1;return t.length===e.length?0:t.length<e.length?-1:1}class Ae extends te{typeName="bytes";data;constructor(e){super(),this.data=e}static fromUtf8(e){return new Ae(new TextEncoder().encode(e))}static fromHex(e){if(e.length%2!==0)throw new Error(`Invalid hex string length: ${e.length}`);const r=new Uint8Array(e.length/2);for(let n=0;n<r.length;n++)r[n]=parseInt(e.substr(n*2,2),16);return new Ae(r)}size(){return this.data.length}toBase64(){return gl(this.data)}toHexString(){return ml(this.data)}valueOf(){return this.data.length}toString(){return this.toBase64()}toJSON(){return{__type:"bytes",base64:this.toBase64()}}equals(e){if(!(e instanceof Ae)||this.data.length!==e.data.length)return!1;for(let r=0;r<this.data.length;r++)if(this.data[r]!==e.data[r])return!1;return!0}callMethod(e,r){switch(e){case"size":return this.size();case"toBase64":return this.toBase64();case"toHexString":return this.toHexString()}return oe}binaryOp(e,r){if(!(r instanceof Ae))return oe;const n=yl(this.data,r.data);switch(e){case"<":return n<0;case"<=":return n<=0;case">":return n>0;case">=":return n>=0}return oe}}function ur(t){return t.replace(/\$\(database\)/g,"(default)").replace(/^\/databases\/\(default\)\/documents\//,"")}function Wn(t,e){const r=t.split("/").filter(Boolean);return{data:e,id:r.at(-1)??"",__name__:new Qe(["databases","(default)","documents",...r])}}function li(t,e){const r=ur(t);let n=e.mockDocuments.get(r);if(!n&&e.getDoc){const s=e.getDoc(r);s&&(e.mockDocuments.set(r,s),n=s)}if(n)return e.identitylessFunctionMocks?.has(r)?{data:n}:Wn(r,n);throw new G(`get() of non-existent document '${r}' (guard with exists() first)`)}function di(t,e){const r=ur(t);if(e.mockDocuments.has(r))return!0;if(e.getDoc){const n=e.getDoc(r);if(n)return e.mockDocuments.set(r,n),!0}return!1}var wn={exports:{}};const vl={},bl=Object.freeze(Object.defineProperty({__proto__:null,default:vl},Symbol.toStringTag,{value:"Module"})),Dr=qo(bl);/**
|
|
480
|
+
`,x);let $="";L!==-1?$=t.slice(x,L).trim():$=t.slice(x).trim();try{const T=JSON.parse($);if(Array.isArray(T)){for(const w of T)if(w.generatedLine===a){a=w.authoredLine,o=w.authoredCol,u=w.authoredFile,w.expression!==void 0&&(l=w.expression);break}}}catch{}}const R=`${u}:${a}:${o}`,C={line:a,col:o,file:u,citation:R};return l!==void 0&&(C.expression=l),C}const oe=Symbol.for("pyric.RulesValue.NO_OP");class te{field(e){return null}callMethod(e,r){return oe}binaryOp(e,r){return oe}}function me(t,e){if(Object.is(t,e))return!0;if(t instanceof te)return t.equals(e);if(e instanceof te)return e.equals(t);if(t instanceof de||e instanceof de)return t instanceof de&&t.equals(e);if(Array.isArray(t)||Array.isArray(e))return!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length?!1:t.every((s,i)=>me(s,e[i]));if(!ai(t)||!ai(e))return!1;const r=Object.keys(t),n=Object.keys(e);return r.length!==n.length?!1:r.every(s=>s in e&&me(t[s],e[s]))}function ai(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}class de{items;constructor(e){this.items=[];for(const r of e)this.items.some(n=>me(n,r))||this.items.push(r)}hasOnly(e){const r=e instanceof de?e.toArray():e;return this.items.every(n=>r.some(s=>me(n,s)))}equals(e){return!(e instanceof de)||e.items.length!==this.items.length?!1:this.items.every(r=>e.items.some(n=>me(r,n)))}hasAll(e){const r=e instanceof de?e.toArray():e;for(const n of r)if(!this.items.some(s=>me(s,n)))return!1;return!0}hasAny(e){const r=e instanceof de?e.toArray():e;for(const n of r)if(this.items.some(s=>me(s,n)))return!0;return!1}size(){return this.items.length}toArray(){return[...this.items]}difference(e){const r=e.toArray(),n=[];for(const s of this.items)r.some(i=>me(s,i))||n.push(s);return new de(n)}union(e){const r=e.toArray();return new de([...this.items,...r])}intersection(e){const r=e.toArray(),n=[];for(const s of this.items)r.some(i=>me(s,i))&&n.push(s);return new de(n)}}class cr{before;after;constructor(e,r){this.before=e,this.after=r}addedKeys(){const e=[];for(const r of Object.keys(this.after))r in this.before||e.push(r);return new de(e)}removedKeys(){const e=[];for(const r of Object.keys(this.before))r in this.after||e.push(r);return new de(e)}changedKeys(){const e=[];for(const r of Object.keys(this.after))r in this.before&&!me(this.before[r],this.after[r])&&e.push(r);return new de(e)}affectedKeys(){const e=[],r=new Set([...Object.keys(this.before),...Object.keys(this.after)]);for(const n of r)(!(n in this.before)||!(n in this.after)||!me(this.before[n],this.after[n]))&&e.push(n);return new de(e)}unchangedKeys(){const e=[];for(const r of Object.keys(this.before))r in this.after&&me(this.before[r],this.after[r])&&e.push(r);return new de(e)}}const ul=/^\{([A-Za-z_][A-Za-z0-9_]*)\}$/;class Qe extends te{typeName="path";segments;bindings;constructor(e,r={}){super(),this.segments=e,this.bindings=r}static fromString(e){const r=e.startsWith("/")?e.slice(1):e;return r.length===0?new Qe([]):new Qe(r.split("/"))}bind(e){const r=[],n={...this.bindings};for(const s of this.segments){const i=s.match(ul);if(!i){r.push(s);continue}const a=i[1];if(a in e){const o=e[a];if(o==null)throw new TypeError(`Path.bind(): binding '${a}' must not be null`);const c=String(o);r.push(c),n[a]=c}else r.push(s)}return new Qe(r,n)}valueOf(){return NaN}toString(){return"/"+this.segments.join("/")}toJSON(){return{__type:"path",segments:[...this.segments]}}equals(e){if(!(e instanceof Qe)||this.segments.length!==e.segments.length)return!1;for(let r=0;r<this.segments.length;r++)if(this.segments[r]!==e.segments[r])return!1;return!0}field(e){if(/^\d+$/.test(e)){const r=Number(e);return r<0||r>=this.segments.length?null:this.segments[r]}return e in this.bindings?this.bindings[e]:null}callMethod(e,r){switch(e){case"bind":{const n=r[0];if(n==null||typeof n!="object"||Array.isArray(n)||n instanceof te)throw new TypeError(`Path.bind() requires a Map argument, got ${n===null?"null":typeof n}`);return this.bind(n)}default:return oe}}}class ae extends te{typeName="float";value;constructor(e){super(),this.value=e}valueOf(){return this.value}toString(){return Number.isInteger(this.value)?`${this.value}.0`:String(this.value)}toJSON(){return{__type:"float",value:this.value}}equals(e){return e instanceof ae?this.value===e.value:typeof e=="number"?this.value===e:!1}binaryOp(e,r){const n=r instanceof ae?r.value:typeof r=="number"?r:void 0;if(n===void 0)return oe;const s=this.value;switch(e){case"+":return new ae(s+n);case"-":return new ae(s-n);case"*":return new ae(s*n);case"/":return new ae(s/n);case"%":return new ae(s%n);case"<":return s<n;case"<=":return s<=n;case">":return s>n;case">=":return s>=n;default:return oe}}}class G extends Error{expr;constructor(e,r){super(e),this.expr=r,this.name="EvalError"}}class gt extends G{constructor(e,r){super(e,r),this.name="UnsupportedError"}}class ll{entries=[];parents=[];frames=[];capture(e,r){const n=this.entries.length,s=this.parents.length>0?this.parents[this.parents.length-1]:null,i={source:ye(e),kind:e.type,parent:s};this.stampFrame(i),this.entries.push(i),this.parents.push(n);try{const a=r();return this.entries[n].value=a,a}catch(a){throw this.entries[n].error=a instanceof Error?a.message:String(a),a}finally{this.parents.pop()}}skip(e){const r=this.parents.length>0?this.parents[this.parents.length-1]:null,n={source:ye(e),kind:e.type,parent:r,skipped:!0};this.stampFrame(n),this.entries.push(n)}enterFrame(e){this.frames.push(e)}exitFrame(){this.frames.pop()}markEntryAsLetBinding(e,r){e<0||e>=this.entries.length||(this.entries[e].letBinding={name:r})}stampFrame(e){this.frames.length!==0&&(e.inlinedFrom={name:this.frames[this.frames.length-1]})}}function dl(t,e,r,n){const i=p=>p*Math.PI/180,a=i(t),o=i(r),c=i(r-t),u=i(n-e),f=Math.sin(c/2)**2+Math.cos(a)*Math.cos(o)*Math.sin(u/2)**2;return 6371e3*(2*Math.atan2(Math.sqrt(f),Math.sqrt(1-f)))}class lt extends te{typeName="latlng";lat;lng;constructor(e,r){super(),this.lat=e,this.lng=r}valueOf(){return NaN}toString(){return`${this.lat},${this.lng}`}toJSON(){return{__type:"latlng",lat:this.lat,lng:this.lng}}equals(e){return e instanceof lt&&this.lat===e.lat&&this.lng===e.lng}callMethod(e,r){switch(e){case"latitude":return this.lat;case"longitude":return this.lng;case"distance":{const n=r[0];if(!(n instanceof lt))throw new TypeError(`latlng.distance() requires a LatLng argument, got ${typeof n}`);return dl(this.lat,this.lng,n.lat,n.lng)}default:return oe}}}const zt=1e9,oi={w:10080*60,d:1440*60,h:3600,m:60,s:1};function hl(t,e){let r=t+Math.trunc(e/zt),n=e%zt;return r>0&&n<0?(r-=1,n+=zt):r<0&&n>0&&(r+=1,n-=zt),{seconds:r,nanos:n}}class ve extends te{typeName="duration";seconds;nanos;constructor(e,r){super();const n=hl(e,r);this.seconds=n.seconds,this.nanos=n.nanos}static fromValue(e,r){if(r in oi)return new ve(e*oi[r],0);if(r==="ms"){const n=Math.trunc(e/1e3),s=e-n*1e3;return new ve(n,s*1e6)}if(r==="ns"){const n=Math.trunc(e/zt),s=e-n*zt;return new ve(n,s)}throw new Error(`Unknown duration unit '${r}' (expected one of: w, d, h, m, s, ms, ns)`)}static fromTime(e,r,n,s){return new ve(e*3600+r*60+n,s)}static abs(e){return new ve(Math.abs(e.seconds),Math.abs(e.nanos))}valueOf(){return this.seconds*1e3+Math.round(this.nanos/1e6)}toString(){const e=this.seconds<0||this.nanos<0,r=Math.abs(this.seconds),n=Math.abs(this.nanos);return`${e?"-":""}${r}.${n.toString().padStart(9,"0")}s`}toJSON(){return{__type:"duration",seconds:this.seconds,nanos:this.nanos}}equals(e){return e instanceof ve&&this.seconds===e.seconds&&this.nanos===e.nanos}callMethod(e,r){switch(e){case"seconds":return this.seconds;case"nanos":return this.nanos;default:return oe}}binaryOp(e,r){if(!(r instanceof ve))return oe;switch(e){case"+":return new ve(this.seconds+r.seconds,this.nanos+r.nanos);case"-":return new ve(this.seconds-r.seconds,this.nanos-r.nanos);case"<":return this.compareTo(r)<0;case"<=":return this.compareTo(r)<=0;case">":return this.compareTo(r)>0;case">=":return this.compareTo(r)>=0;default:return oe}}compareTo(e){return this.seconds!==e.seconds?this.seconds-e.seconds:this.nanos-e.nanos}}const ci=1e9,fl=864e5,bn=86400;function pl(t,e){const r=Math.floor(e/ci);return{seconds:t+r,nanos:e-r*ci}}let _e=class nt extends te{typeName="timestamp";seconds;nanos;constructor(e,r){super();const n=pl(e,r);this.seconds=n.seconds,this.nanos=n.nanos}static fromMillis(e){const r=Math.floor(e/1e3),n=e-r*1e3;return new nt(r,n*1e6)}static fromYMD(e,r,n){return nt.fromMillis(Date.UTC(e,r-1,n))}static fromIsoString(e){return nt.fromMillis(Date.parse(e))}toMillis(){return this.seconds*1e3+Math.floor(this.nanos/1e6)}toDate(){return new Date(this.toMillis())}valueOf(){return this.toMillis()}toString(){const e=new Date(this.toMillis()).toISOString(),r=this.nanos.toString().padStart(9,"0");return e.replace(/\.\d{3}Z$/,`.${r}Z`)}toJSON(){return{__type:"timestamp",seconds:this.seconds,nanos:this.nanos}}equals(e){return e instanceof nt&&this.seconds===e.seconds&&this.nanos===e.nanos}callMethod(e,r){switch(e){case"seconds":return this.seconds;case"nanos":return this.nanos;case"toMillis":return this.toMillis();case"year":return this.asDate().getUTCFullYear();case"month":return this.asDate().getUTCMonth()+1;case"day":return this.asDate().getUTCDate();case"hours":return this.asDate().getUTCHours();case"minutes":return this.asDate().getUTCMinutes();case"dayOfWeek":{const n=this.asDate().getUTCDay();return n===0?7:n}case"dayOfYear":{const n=this.asDate(),s=Date.UTC(n.getUTCFullYear(),0,1);return Math.floor((this.toMillis()-s)/fl)+1}case"date":return nt.fromYMD(this.asDate().getUTCFullYear(),this.asDate().getUTCMonth()+1,this.asDate().getUTCDate());case"time":{const n=(this.seconds%bn+bn)%bn,s=Math.floor(n/3600),i=Math.floor(n%3600/60),a=n%60;return ve.fromTime(s,i,a,this.nanos)}default:return oe}}asDate(){return new Date(this.toMillis())}binaryOp(e,r){if(r instanceof nt)switch(e){case"-":return new ve(this.seconds-r.seconds,this.nanos-r.nanos);case"<":return this.compareTo(r)<0;case"<=":return this.compareTo(r)<=0;case">":return this.compareTo(r)>0;case">=":return this.compareTo(r)>=0;default:return oe}if(r instanceof ve)switch(e){case"+":return new nt(this.seconds+r.seconds,this.nanos+r.nanos);case"-":return new nt(this.seconds-r.seconds,this.nanos-r.nanos);default:return oe}return oe}compareTo(e){return this.seconds!==e.seconds?this.seconds-e.seconds:this.nanos-e.nanos}};const ui="0123456789ABCDEF";function ml(t){let e="";for(let r=0;r<t.length;r++){const n=t[r];e+=ui[n>>>4]+ui[n&15]}return e}function gl(t){let e="";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_")}function yl(t,e){const r=Math.min(t.length,e.length);for(let n=0;n<r;n++)if(t[n]!==e[n])return t[n]<e[n]?-1:1;return t.length===e.length?0:t.length<e.length?-1:1}class Ae extends te{typeName="bytes";data;constructor(e){super(),this.data=e}static fromUtf8(e){return new Ae(new TextEncoder().encode(e))}static fromHex(e){if(e.length%2!==0)throw new Error(`Invalid hex string length: ${e.length}`);const r=new Uint8Array(e.length/2);for(let n=0;n<r.length;n++)r[n]=parseInt(e.substr(n*2,2),16);return new Ae(r)}size(){return this.data.length}toBase64(){return gl(this.data)}toHexString(){return ml(this.data)}valueOf(){return this.data.length}toString(){return this.toBase64()}toJSON(){return{__type:"bytes",base64:this.toBase64()}}equals(e){if(!(e instanceof Ae)||this.data.length!==e.data.length)return!1;for(let r=0;r<this.data.length;r++)if(this.data[r]!==e.data[r])return!1;return!0}callMethod(e,r){switch(e){case"size":return this.size();case"toBase64":return this.toBase64();case"toHexString":return this.toHexString()}return oe}binaryOp(e,r){if(!(r instanceof Ae))return oe;const n=yl(this.data,r.data);switch(e){case"<":return n<0;case"<=":return n<=0;case">":return n>0;case">=":return n>=0}return oe}}function ur(t){return t.replace(/\$\(database\)/g,"(default)").replace(/^\/databases\/\(default\)\/documents\//,"")}function Wn(t,e){const r=t.split("/").filter(Boolean);return{data:e,id:r.at(-1)??"",__name__:new Qe(["databases","(default)","documents",...r])}}function li(t,e){const r=ur(t);let n=e.mockDocuments.get(r);if(!n&&e.getDoc){const s=e.getDoc(r);s&&(e.mockDocuments.set(r,s),n=s)}if(n)return e.identitylessFunctionMocks?.has(r)?{data:n}:Wn(r,n);throw new G(`get() of non-existent document '${r}' (guard with exists() first)`)}function di(t,e){const r=ur(t);if(e.mockDocuments.has(r))return!0;if(e.getDoc){const n=e.getDoc(r);if(n)return e.mockDocuments.set(r,n),!0}return!1}var wn={exports:{}};const vl={},bl=Object.freeze(Object.defineProperty({__proto__:null,default:vl},Symbol.toStringTag,{value:"Module"})),Dr=qo(bl);/**
|
|
481
481
|
* [js-md5]{@link https://github.com/emn178/js-md5}
|
|
482
482
|
*
|
|
483
483
|
* @namespace md5
|
|
@@ -485,14 +485,14 @@ ${t}
|
|
|
485
485
|
* @author Chen, Yi-Cyuan [emn178@gmail.com]
|
|
486
486
|
* @copyright Chen, Yi-Cyuan 2014-2023
|
|
487
487
|
* @license MIT
|
|
488
|
-
*/var hi;function wl(){return hi||(hi=1,(function(t){(function(){var e="input is invalid type",r="finalize already called",n=typeof window=="object",s=n?window:{};s.JS_MD5_NO_WINDOW&&(n=!1);var i=!n&&typeof self=="object",a=!s.JS_MD5_NO_NODE_JS&&typeof process=="object"&&process.versions&&process.versions.node;a?s=oa:i&&(s=self);var o=!s.JS_MD5_NO_COMMON_JS&&!0&&t.exports,c=!s.JS_MD5_NO_ARRAY_BUFFER&&typeof ArrayBuffer<"u",u="0123456789abcdef".split(""),f=[128,32768,8388608,-2147483648],l=[0,8,16,24],p=["hex","array","digest","buffer","arrayBuffer","base64"],y="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),v=[],w;if(c){var R=new ArrayBuffer(68);w=new Uint8Array(R),v=new Uint32Array(R)}var C=Array.isArray;(s.JS_MD5_NO_NODE_JS||!C)&&(C=function(h){return Object.prototype.toString.call(h)==="[object Array]"});var k=ArrayBuffer.isView;c&&(s.JS_MD5_NO_ARRAY_BUFFER_IS_VIEW||!k)&&(k=function(h){return typeof h=="object"&&h.buffer&&h.buffer.constructor===ArrayBuffer});var x=function(h){var d=typeof h;if(d==="string")return[h,!0];if(d!=="object"||h===null)throw new Error(e);if(c&&h.constructor===ArrayBuffer)return[new Uint8Array(h),!1];if(!C(h)&&!k(h))throw new Error(e);return[h,!1]},L=function(h){return function(d){return new b(!0).update(d)[h]()}},$=function(){var h=L("hex");a&&(h=S(h)),h.create=function(){return new b},h.update=function(m){return h.create().update(m)};for(var d=0;d<p.length;++d){var g=p[d];h[g]=L(g)}return h},S=function(h){var d=Dr,g=Dr.Buffer,m;g.from&&!s.JS_MD5_NO_BUFFER_FROM?m=g.from:m=function(E){return new g(E)};var F=function(E){if(typeof E=="string")return d.createHash("md5").update(E,"utf8").digest("hex");if(E==null)throw new Error(e);return E.constructor===ArrayBuffer&&(E=new Uint8Array(E)),C(E)||k(E)||E.constructor===g?d.createHash("md5").update(m(E)).digest("hex"):h(E)};return F},T=function(h){return function(d,g){return new A(d,!0).update(g)[h]()}},_=function(){var h=T("hex");h.create=function(m){return new A(m)},h.update=function(m,F){return h.create(m).update(F)};for(var d=0;d<p.length;++d){var g=p[d];h[g]=T(g)}return h};function b(h){if(h)v[0]=v[16]=v[1]=v[2]=v[3]=v[4]=v[5]=v[6]=v[7]=v[8]=v[9]=v[10]=v[11]=v[12]=v[13]=v[14]=v[15]=0,this.blocks=v,this.buffer8=w;else if(c){var d=new ArrayBuffer(68);this.buffer8=new Uint8Array(d),this.blocks=new Uint32Array(d)}else this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];this.h0=this.h1=this.h2=this.h3=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0}b.prototype.update=function(h){if(this.finalized)throw new Error(r);var d=x(h);h=d[0];for(var g=d[1],m,F=0,E,O=h.length,D=this.blocks,Y=this.buffer8;F<O;){if(this.hashed&&(this.hashed=!1,D[0]=D[16],D[16]=D[1]=D[2]=D[3]=D[4]=D[5]=D[6]=D[7]=D[8]=D[9]=D[10]=D[11]=D[12]=D[13]=D[14]=D[15]=0),g)if(c)for(E=this.start;F<O&&E<64;++F)m=h.charCodeAt(F),m<128?Y[E++]=m:m<2048?(Y[E++]=192|m>>>6,Y[E++]=128|m&63):m<55296||m>=57344?(Y[E++]=224|m>>>12,Y[E++]=128|m>>>6&63,Y[E++]=128|m&63):(m=65536+((m&1023)<<10|h.charCodeAt(++F)&1023),Y[E++]=240|m>>>18,Y[E++]=128|m>>>12&63,Y[E++]=128|m>>>6&63,Y[E++]=128|m&63);else for(E=this.start;F<O&&E<64;++F)m=h.charCodeAt(F),m<128?D[E>>>2]|=m<<l[E++&3]:m<2048?(D[E>>>2]|=(192|m>>>6)<<l[E++&3],D[E>>>2]|=(128|m&63)<<l[E++&3]):m<55296||m>=57344?(D[E>>>2]|=(224|m>>>12)<<l[E++&3],D[E>>>2]|=(128|m>>>6&63)<<l[E++&3],D[E>>>2]|=(128|m&63)<<l[E++&3]):(m=65536+((m&1023)<<10|h.charCodeAt(++F)&1023),D[E>>>2]|=(240|m>>>18)<<l[E++&3],D[E>>>2]|=(128|m>>>12&63)<<l[E++&3],D[E>>>2]|=(128|m>>>6&63)<<l[E++&3],D[E>>>2]|=(128|m&63)<<l[E++&3]);else if(c)for(E=this.start;F<O&&E<64;++F)Y[E++]=h[F];else for(E=this.start;F<O&&E<64;++F)D[E>>>2]|=h[F]<<l[E++&3];this.lastByteIndex=E,this.bytes+=E-this.start,E>=64?(this.start=E-64,this.hash(),this.hashed=!0):this.start=E}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this},b.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var h=this.blocks,d=this.lastByteIndex;h[d>>>2]|=f[d&3],d>=56&&(this.hashed||this.hash(),h[0]=h[16],h[16]=h[1]=h[2]=h[3]=h[4]=h[5]=h[6]=h[7]=h[8]=h[9]=h[10]=h[11]=h[12]=h[13]=h[14]=h[15]=0),h[14]=this.bytes<<3,h[15]=this.hBytes<<3|this.bytes>>>29,this.hash()}},b.prototype.hash=function(){var h,d,g,m,F,E,O=this.blocks;this.first?(h=O[0]-680876937,h=(h<<7|h>>>25)-271733879<<0,m=(-1732584194^h&2004318071)+O[1]-117830708,m=(m<<12|m>>>20)+h<<0,g=(-271733879^m&(h^-271733879))+O[2]-1126478375,g=(g<<17|g>>>15)+m<<0,d=(h^g&(m^h))+O[3]-1316259209,d=(d<<22|d>>>10)+g<<0):(h=this.h0,d=this.h1,g=this.h2,m=this.h3,h+=(m^d&(g^m))+O[0]-680876936,h=(h<<7|h>>>25)+d<<0,m+=(g^h&(d^g))+O[1]-389564586,m=(m<<12|m>>>20)+h<<0,g+=(d^m&(h^d))+O[2]+606105819,g=(g<<17|g>>>15)+m<<0,d+=(h^g&(m^h))+O[3]-1044525330,d=(d<<22|d>>>10)+g<<0),h+=(m^d&(g^m))+O[4]-176418897,h=(h<<7|h>>>25)+d<<0,m+=(g^h&(d^g))+O[5]+1200080426,m=(m<<12|m>>>20)+h<<0,g+=(d^m&(h^d))+O[6]-1473231341,g=(g<<17|g>>>15)+m<<0,d+=(h^g&(m^h))+O[7]-45705983,d=(d<<22|d>>>10)+g<<0,h+=(m^d&(g^m))+O[8]+1770035416,h=(h<<7|h>>>25)+d<<0,m+=(g^h&(d^g))+O[9]-1958414417,m=(m<<12|m>>>20)+h<<0,g+=(d^m&(h^d))+O[10]-42063,g=(g<<17|g>>>15)+m<<0,d+=(h^g&(m^h))+O[11]-1990404162,d=(d<<22|d>>>10)+g<<0,h+=(m^d&(g^m))+O[12]+1804603682,h=(h<<7|h>>>25)+d<<0,m+=(g^h&(d^g))+O[13]-40341101,m=(m<<12|m>>>20)+h<<0,g+=(d^m&(h^d))+O[14]-1502002290,g=(g<<17|g>>>15)+m<<0,d+=(h^g&(m^h))+O[15]+1236535329,d=(d<<22|d>>>10)+g<<0,h+=(g^m&(d^g))+O[1]-165796510,h=(h<<5|h>>>27)+d<<0,m+=(d^g&(h^d))+O[6]-1069501632,m=(m<<9|m>>>23)+h<<0,g+=(h^d&(m^h))+O[11]+643717713,g=(g<<14|g>>>18)+m<<0,d+=(m^h&(g^m))+O[0]-373897302,d=(d<<20|d>>>12)+g<<0,h+=(g^m&(d^g))+O[5]-701558691,h=(h<<5|h>>>27)+d<<0,m+=(d^g&(h^d))+O[10]+38016083,m=(m<<9|m>>>23)+h<<0,g+=(h^d&(m^h))+O[15]-660478335,g=(g<<14|g>>>18)+m<<0,d+=(m^h&(g^m))+O[4]-405537848,d=(d<<20|d>>>12)+g<<0,h+=(g^m&(d^g))+O[9]+568446438,h=(h<<5|h>>>27)+d<<0,m+=(d^g&(h^d))+O[14]-1019803690,m=(m<<9|m>>>23)+h<<0,g+=(h^d&(m^h))+O[3]-187363961,g=(g<<14|g>>>18)+m<<0,d+=(m^h&(g^m))+O[8]+1163531501,d=(d<<20|d>>>12)+g<<0,h+=(g^m&(d^g))+O[13]-1444681467,h=(h<<5|h>>>27)+d<<0,m+=(d^g&(h^d))+O[2]-51403784,m=(m<<9|m>>>23)+h<<0,g+=(h^d&(m^h))+O[7]+1735328473,g=(g<<14|g>>>18)+m<<0,d+=(m^h&(g^m))+O[12]-1926607734,d=(d<<20|d>>>12)+g<<0,F=d^g,h+=(F^m)+O[5]-378558,h=(h<<4|h>>>28)+d<<0,m+=(F^h)+O[8]-2022574463,m=(m<<11|m>>>21)+h<<0,E=m^h,g+=(E^d)+O[11]+1839030562,g=(g<<16|g>>>16)+m<<0,d+=(E^g)+O[14]-35309556,d=(d<<23|d>>>9)+g<<0,F=d^g,h+=(F^m)+O[1]-1530992060,h=(h<<4|h>>>28)+d<<0,m+=(F^h)+O[4]+1272893353,m=(m<<11|m>>>21)+h<<0,E=m^h,g+=(E^d)+O[7]-155497632,g=(g<<16|g>>>16)+m<<0,d+=(E^g)+O[10]-1094730640,d=(d<<23|d>>>9)+g<<0,F=d^g,h+=(F^m)+O[13]+681279174,h=(h<<4|h>>>28)+d<<0,m+=(F^h)+O[0]-358537222,m=(m<<11|m>>>21)+h<<0,E=m^h,g+=(E^d)+O[3]-722521979,g=(g<<16|g>>>16)+m<<0,d+=(E^g)+O[6]+76029189,d=(d<<23|d>>>9)+g<<0,F=d^g,h+=(F^m)+O[9]-640364487,h=(h<<4|h>>>28)+d<<0,m+=(F^h)+O[12]-421815835,m=(m<<11|m>>>21)+h<<0,E=m^h,g+=(E^d)+O[15]+530742520,g=(g<<16|g>>>16)+m<<0,d+=(E^g)+O[2]-995338651,d=(d<<23|d>>>9)+g<<0,h+=(g^(d|~m))+O[0]-198630844,h=(h<<6|h>>>26)+d<<0,m+=(d^(h|~g))+O[7]+1126891415,m=(m<<10|m>>>22)+h<<0,g+=(h^(m|~d))+O[14]-1416354905,g=(g<<15|g>>>17)+m<<0,d+=(m^(g|~h))+O[5]-57434055,d=(d<<21|d>>>11)+g<<0,h+=(g^(d|~m))+O[12]+1700485571,h=(h<<6|h>>>26)+d<<0,m+=(d^(h|~g))+O[3]-1894986606,m=(m<<10|m>>>22)+h<<0,g+=(h^(m|~d))+O[10]-1051523,g=(g<<15|g>>>17)+m<<0,d+=(m^(g|~h))+O[1]-2054922799,d=(d<<21|d>>>11)+g<<0,h+=(g^(d|~m))+O[8]+1873313359,h=(h<<6|h>>>26)+d<<0,m+=(d^(h|~g))+O[15]-30611744,m=(m<<10|m>>>22)+h<<0,g+=(h^(m|~d))+O[6]-1560198380,g=(g<<15|g>>>17)+m<<0,d+=(m^(g|~h))+O[13]+1309151649,d=(d<<21|d>>>11)+g<<0,h+=(g^(d|~m))+O[4]-145523070,h=(h<<6|h>>>26)+d<<0,m+=(d^(h|~g))+O[11]-1120210379,m=(m<<10|m>>>22)+h<<0,g+=(h^(m|~d))+O[2]+718787259,g=(g<<15|g>>>17)+m<<0,d+=(m^(g|~h))+O[9]-343485551,d=(d<<21|d>>>11)+g<<0,this.first?(this.h0=h+1732584193<<0,this.h1=d-271733879<<0,this.h2=g-1732584194<<0,this.h3=m+271733878<<0,this.first=!1):(this.h0=this.h0+h<<0,this.h1=this.h1+d<<0,this.h2=this.h2+g<<0,this.h3=this.h3+m<<0)},b.prototype.hex=function(){this.finalize();var h=this.h0,d=this.h1,g=this.h2,m=this.h3;return u[h>>>4&15]+u[h&15]+u[h>>>12&15]+u[h>>>8&15]+u[h>>>20&15]+u[h>>>16&15]+u[h>>>28&15]+u[h>>>24&15]+u[d>>>4&15]+u[d&15]+u[d>>>12&15]+u[d>>>8&15]+u[d>>>20&15]+u[d>>>16&15]+u[d>>>28&15]+u[d>>>24&15]+u[g>>>4&15]+u[g&15]+u[g>>>12&15]+u[g>>>8&15]+u[g>>>20&15]+u[g>>>16&15]+u[g>>>28&15]+u[g>>>24&15]+u[m>>>4&15]+u[m&15]+u[m>>>12&15]+u[m>>>8&15]+u[m>>>20&15]+u[m>>>16&15]+u[m>>>28&15]+u[m>>>24&15]},b.prototype.toString=b.prototype.hex,b.prototype.digest=function(){this.finalize();var h=this.h0,d=this.h1,g=this.h2,m=this.h3;return[h&255,h>>>8&255,h>>>16&255,h>>>24&255,d&255,d>>>8&255,d>>>16&255,d>>>24&255,g&255,g>>>8&255,g>>>16&255,g>>>24&255,m&255,m>>>8&255,m>>>16&255,m>>>24&255]},b.prototype.array=b.prototype.digest,b.prototype.arrayBuffer=function(){this.finalize();var h=new ArrayBuffer(16),d=new Uint32Array(h);return d[0]=this.h0,d[1]=this.h1,d[2]=this.h2,d[3]=this.h3,h},b.prototype.buffer=b.prototype.arrayBuffer,b.prototype.base64=function(){for(var h,d,g,m="",F=this.array(),E=0;E<15;)h=F[E++],d=F[E++],g=F[E++],m+=y[h>>>2]+y[(h<<4|d>>>4)&63]+y[(d<<2|g>>>6)&63]+y[g&63];return h=F[E],m+=y[h>>>2]+y[h<<4&63]+"==",m};function A(h,d){var g,m=x(h);if(h=m[0],m[1]){var F=[],E=h.length,O=0,D;for(g=0;g<E;++g)D=h.charCodeAt(g),D<128?F[O++]=D:D<2048?(F[O++]=192|D>>>6,F[O++]=128|D&63):D<55296||D>=57344?(F[O++]=224|D>>>12,F[O++]=128|D>>>6&63,F[O++]=128|D&63):(D=65536+((D&1023)<<10|h.charCodeAt(++g)&1023),F[O++]=240|D>>>18,F[O++]=128|D>>>12&63,F[O++]=128|D>>>6&63,F[O++]=128|D&63);h=F}h.length>64&&(h=new b(!0).update(h).array());var Y=[],Ee=[];for(g=0;g<64;++g){var ze=h[g]||0;Y[g]=92^ze,Ee[g]=54^ze}b.call(this,d),this.update(Ee),this.oKeyPad=Y,this.inner=!0,this.sharedMemory=d}A.prototype=new b,A.prototype.finalize=function(){if(b.prototype.finalize.call(this),this.inner){this.inner=!1;var h=this.array();b.call(this,this.sharedMemory),this.update(this.oKeyPad),this.update(h),b.prototype.finalize.call(this)}};var I=$();I.md5=I,I.md5.hmac=_(),o?t.exports=I:s.md5=I})()})(wn)),wn.exports}var Sl=wl(),Sn={exports:{}};/**
|
|
488
|
+
*/var hi;function wl(){return hi||(hi=1,(function(t){(function(){var e="input is invalid type",r="finalize already called",n=typeof window=="object",s=n?window:{};s.JS_MD5_NO_WINDOW&&(n=!1);var i=!n&&typeof self=="object",a=!s.JS_MD5_NO_NODE_JS&&typeof process=="object"&&process.versions&&process.versions.node;a?s=oa:i&&(s=self);var o=!s.JS_MD5_NO_COMMON_JS&&!0&&t.exports,c=!s.JS_MD5_NO_ARRAY_BUFFER&&typeof ArrayBuffer<"u",u="0123456789abcdef".split(""),f=[128,32768,8388608,-2147483648],l=[0,8,16,24],p=["hex","array","digest","buffer","arrayBuffer","base64"],y="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),v=[],b;if(c){var R=new ArrayBuffer(68);b=new Uint8Array(R),v=new Uint32Array(R)}var C=Array.isArray;(s.JS_MD5_NO_NODE_JS||!C)&&(C=function(h){return Object.prototype.toString.call(h)==="[object Array]"});var k=ArrayBuffer.isView;c&&(s.JS_MD5_NO_ARRAY_BUFFER_IS_VIEW||!k)&&(k=function(h){return typeof h=="object"&&h.buffer&&h.buffer.constructor===ArrayBuffer});var x=function(h){var d=typeof h;if(d==="string")return[h,!0];if(d!=="object"||h===null)throw new Error(e);if(c&&h.constructor===ArrayBuffer)return[new Uint8Array(h),!1];if(!C(h)&&!k(h))throw new Error(e);return[h,!1]},L=function(h){return function(d){return new w(!0).update(d)[h]()}},$=function(){var h=L("hex");a&&(h=S(h)),h.create=function(){return new w},h.update=function(m){return h.create().update(m)};for(var d=0;d<p.length;++d){var g=p[d];h[g]=L(g)}return h},S=function(h){var d=Dr,g=Dr.Buffer,m;g.from&&!s.JS_MD5_NO_BUFFER_FROM?m=g.from:m=function(E){return new g(E)};var F=function(E){if(typeof E=="string")return d.createHash("md5").update(E,"utf8").digest("hex");if(E==null)throw new Error(e);return E.constructor===ArrayBuffer&&(E=new Uint8Array(E)),C(E)||k(E)||E.constructor===g?d.createHash("md5").update(m(E)).digest("hex"):h(E)};return F},T=function(h){return function(d,g){return new A(d,!0).update(g)[h]()}},_=function(){var h=T("hex");h.create=function(m){return new A(m)},h.update=function(m,F){return h.create(m).update(F)};for(var d=0;d<p.length;++d){var g=p[d];h[g]=T(g)}return h};function w(h){if(h)v[0]=v[16]=v[1]=v[2]=v[3]=v[4]=v[5]=v[6]=v[7]=v[8]=v[9]=v[10]=v[11]=v[12]=v[13]=v[14]=v[15]=0,this.blocks=v,this.buffer8=b;else if(c){var d=new ArrayBuffer(68);this.buffer8=new Uint8Array(d),this.blocks=new Uint32Array(d)}else this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];this.h0=this.h1=this.h2=this.h3=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0}w.prototype.update=function(h){if(this.finalized)throw new Error(r);var d=x(h);h=d[0];for(var g=d[1],m,F=0,E,O=h.length,D=this.blocks,Y=this.buffer8;F<O;){if(this.hashed&&(this.hashed=!1,D[0]=D[16],D[16]=D[1]=D[2]=D[3]=D[4]=D[5]=D[6]=D[7]=D[8]=D[9]=D[10]=D[11]=D[12]=D[13]=D[14]=D[15]=0),g)if(c)for(E=this.start;F<O&&E<64;++F)m=h.charCodeAt(F),m<128?Y[E++]=m:m<2048?(Y[E++]=192|m>>>6,Y[E++]=128|m&63):m<55296||m>=57344?(Y[E++]=224|m>>>12,Y[E++]=128|m>>>6&63,Y[E++]=128|m&63):(m=65536+((m&1023)<<10|h.charCodeAt(++F)&1023),Y[E++]=240|m>>>18,Y[E++]=128|m>>>12&63,Y[E++]=128|m>>>6&63,Y[E++]=128|m&63);else for(E=this.start;F<O&&E<64;++F)m=h.charCodeAt(F),m<128?D[E>>>2]|=m<<l[E++&3]:m<2048?(D[E>>>2]|=(192|m>>>6)<<l[E++&3],D[E>>>2]|=(128|m&63)<<l[E++&3]):m<55296||m>=57344?(D[E>>>2]|=(224|m>>>12)<<l[E++&3],D[E>>>2]|=(128|m>>>6&63)<<l[E++&3],D[E>>>2]|=(128|m&63)<<l[E++&3]):(m=65536+((m&1023)<<10|h.charCodeAt(++F)&1023),D[E>>>2]|=(240|m>>>18)<<l[E++&3],D[E>>>2]|=(128|m>>>12&63)<<l[E++&3],D[E>>>2]|=(128|m>>>6&63)<<l[E++&3],D[E>>>2]|=(128|m&63)<<l[E++&3]);else if(c)for(E=this.start;F<O&&E<64;++F)Y[E++]=h[F];else for(E=this.start;F<O&&E<64;++F)D[E>>>2]|=h[F]<<l[E++&3];this.lastByteIndex=E,this.bytes+=E-this.start,E>=64?(this.start=E-64,this.hash(),this.hashed=!0):this.start=E}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this},w.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var h=this.blocks,d=this.lastByteIndex;h[d>>>2]|=f[d&3],d>=56&&(this.hashed||this.hash(),h[0]=h[16],h[16]=h[1]=h[2]=h[3]=h[4]=h[5]=h[6]=h[7]=h[8]=h[9]=h[10]=h[11]=h[12]=h[13]=h[14]=h[15]=0),h[14]=this.bytes<<3,h[15]=this.hBytes<<3|this.bytes>>>29,this.hash()}},w.prototype.hash=function(){var h,d,g,m,F,E,O=this.blocks;this.first?(h=O[0]-680876937,h=(h<<7|h>>>25)-271733879<<0,m=(-1732584194^h&2004318071)+O[1]-117830708,m=(m<<12|m>>>20)+h<<0,g=(-271733879^m&(h^-271733879))+O[2]-1126478375,g=(g<<17|g>>>15)+m<<0,d=(h^g&(m^h))+O[3]-1316259209,d=(d<<22|d>>>10)+g<<0):(h=this.h0,d=this.h1,g=this.h2,m=this.h3,h+=(m^d&(g^m))+O[0]-680876936,h=(h<<7|h>>>25)+d<<0,m+=(g^h&(d^g))+O[1]-389564586,m=(m<<12|m>>>20)+h<<0,g+=(d^m&(h^d))+O[2]+606105819,g=(g<<17|g>>>15)+m<<0,d+=(h^g&(m^h))+O[3]-1044525330,d=(d<<22|d>>>10)+g<<0),h+=(m^d&(g^m))+O[4]-176418897,h=(h<<7|h>>>25)+d<<0,m+=(g^h&(d^g))+O[5]+1200080426,m=(m<<12|m>>>20)+h<<0,g+=(d^m&(h^d))+O[6]-1473231341,g=(g<<17|g>>>15)+m<<0,d+=(h^g&(m^h))+O[7]-45705983,d=(d<<22|d>>>10)+g<<0,h+=(m^d&(g^m))+O[8]+1770035416,h=(h<<7|h>>>25)+d<<0,m+=(g^h&(d^g))+O[9]-1958414417,m=(m<<12|m>>>20)+h<<0,g+=(d^m&(h^d))+O[10]-42063,g=(g<<17|g>>>15)+m<<0,d+=(h^g&(m^h))+O[11]-1990404162,d=(d<<22|d>>>10)+g<<0,h+=(m^d&(g^m))+O[12]+1804603682,h=(h<<7|h>>>25)+d<<0,m+=(g^h&(d^g))+O[13]-40341101,m=(m<<12|m>>>20)+h<<0,g+=(d^m&(h^d))+O[14]-1502002290,g=(g<<17|g>>>15)+m<<0,d+=(h^g&(m^h))+O[15]+1236535329,d=(d<<22|d>>>10)+g<<0,h+=(g^m&(d^g))+O[1]-165796510,h=(h<<5|h>>>27)+d<<0,m+=(d^g&(h^d))+O[6]-1069501632,m=(m<<9|m>>>23)+h<<0,g+=(h^d&(m^h))+O[11]+643717713,g=(g<<14|g>>>18)+m<<0,d+=(m^h&(g^m))+O[0]-373897302,d=(d<<20|d>>>12)+g<<0,h+=(g^m&(d^g))+O[5]-701558691,h=(h<<5|h>>>27)+d<<0,m+=(d^g&(h^d))+O[10]+38016083,m=(m<<9|m>>>23)+h<<0,g+=(h^d&(m^h))+O[15]-660478335,g=(g<<14|g>>>18)+m<<0,d+=(m^h&(g^m))+O[4]-405537848,d=(d<<20|d>>>12)+g<<0,h+=(g^m&(d^g))+O[9]+568446438,h=(h<<5|h>>>27)+d<<0,m+=(d^g&(h^d))+O[14]-1019803690,m=(m<<9|m>>>23)+h<<0,g+=(h^d&(m^h))+O[3]-187363961,g=(g<<14|g>>>18)+m<<0,d+=(m^h&(g^m))+O[8]+1163531501,d=(d<<20|d>>>12)+g<<0,h+=(g^m&(d^g))+O[13]-1444681467,h=(h<<5|h>>>27)+d<<0,m+=(d^g&(h^d))+O[2]-51403784,m=(m<<9|m>>>23)+h<<0,g+=(h^d&(m^h))+O[7]+1735328473,g=(g<<14|g>>>18)+m<<0,d+=(m^h&(g^m))+O[12]-1926607734,d=(d<<20|d>>>12)+g<<0,F=d^g,h+=(F^m)+O[5]-378558,h=(h<<4|h>>>28)+d<<0,m+=(F^h)+O[8]-2022574463,m=(m<<11|m>>>21)+h<<0,E=m^h,g+=(E^d)+O[11]+1839030562,g=(g<<16|g>>>16)+m<<0,d+=(E^g)+O[14]-35309556,d=(d<<23|d>>>9)+g<<0,F=d^g,h+=(F^m)+O[1]-1530992060,h=(h<<4|h>>>28)+d<<0,m+=(F^h)+O[4]+1272893353,m=(m<<11|m>>>21)+h<<0,E=m^h,g+=(E^d)+O[7]-155497632,g=(g<<16|g>>>16)+m<<0,d+=(E^g)+O[10]-1094730640,d=(d<<23|d>>>9)+g<<0,F=d^g,h+=(F^m)+O[13]+681279174,h=(h<<4|h>>>28)+d<<0,m+=(F^h)+O[0]-358537222,m=(m<<11|m>>>21)+h<<0,E=m^h,g+=(E^d)+O[3]-722521979,g=(g<<16|g>>>16)+m<<0,d+=(E^g)+O[6]+76029189,d=(d<<23|d>>>9)+g<<0,F=d^g,h+=(F^m)+O[9]-640364487,h=(h<<4|h>>>28)+d<<0,m+=(F^h)+O[12]-421815835,m=(m<<11|m>>>21)+h<<0,E=m^h,g+=(E^d)+O[15]+530742520,g=(g<<16|g>>>16)+m<<0,d+=(E^g)+O[2]-995338651,d=(d<<23|d>>>9)+g<<0,h+=(g^(d|~m))+O[0]-198630844,h=(h<<6|h>>>26)+d<<0,m+=(d^(h|~g))+O[7]+1126891415,m=(m<<10|m>>>22)+h<<0,g+=(h^(m|~d))+O[14]-1416354905,g=(g<<15|g>>>17)+m<<0,d+=(m^(g|~h))+O[5]-57434055,d=(d<<21|d>>>11)+g<<0,h+=(g^(d|~m))+O[12]+1700485571,h=(h<<6|h>>>26)+d<<0,m+=(d^(h|~g))+O[3]-1894986606,m=(m<<10|m>>>22)+h<<0,g+=(h^(m|~d))+O[10]-1051523,g=(g<<15|g>>>17)+m<<0,d+=(m^(g|~h))+O[1]-2054922799,d=(d<<21|d>>>11)+g<<0,h+=(g^(d|~m))+O[8]+1873313359,h=(h<<6|h>>>26)+d<<0,m+=(d^(h|~g))+O[15]-30611744,m=(m<<10|m>>>22)+h<<0,g+=(h^(m|~d))+O[6]-1560198380,g=(g<<15|g>>>17)+m<<0,d+=(m^(g|~h))+O[13]+1309151649,d=(d<<21|d>>>11)+g<<0,h+=(g^(d|~m))+O[4]-145523070,h=(h<<6|h>>>26)+d<<0,m+=(d^(h|~g))+O[11]-1120210379,m=(m<<10|m>>>22)+h<<0,g+=(h^(m|~d))+O[2]+718787259,g=(g<<15|g>>>17)+m<<0,d+=(m^(g|~h))+O[9]-343485551,d=(d<<21|d>>>11)+g<<0,this.first?(this.h0=h+1732584193<<0,this.h1=d-271733879<<0,this.h2=g-1732584194<<0,this.h3=m+271733878<<0,this.first=!1):(this.h0=this.h0+h<<0,this.h1=this.h1+d<<0,this.h2=this.h2+g<<0,this.h3=this.h3+m<<0)},w.prototype.hex=function(){this.finalize();var h=this.h0,d=this.h1,g=this.h2,m=this.h3;return u[h>>>4&15]+u[h&15]+u[h>>>12&15]+u[h>>>8&15]+u[h>>>20&15]+u[h>>>16&15]+u[h>>>28&15]+u[h>>>24&15]+u[d>>>4&15]+u[d&15]+u[d>>>12&15]+u[d>>>8&15]+u[d>>>20&15]+u[d>>>16&15]+u[d>>>28&15]+u[d>>>24&15]+u[g>>>4&15]+u[g&15]+u[g>>>12&15]+u[g>>>8&15]+u[g>>>20&15]+u[g>>>16&15]+u[g>>>28&15]+u[g>>>24&15]+u[m>>>4&15]+u[m&15]+u[m>>>12&15]+u[m>>>8&15]+u[m>>>20&15]+u[m>>>16&15]+u[m>>>28&15]+u[m>>>24&15]},w.prototype.toString=w.prototype.hex,w.prototype.digest=function(){this.finalize();var h=this.h0,d=this.h1,g=this.h2,m=this.h3;return[h&255,h>>>8&255,h>>>16&255,h>>>24&255,d&255,d>>>8&255,d>>>16&255,d>>>24&255,g&255,g>>>8&255,g>>>16&255,g>>>24&255,m&255,m>>>8&255,m>>>16&255,m>>>24&255]},w.prototype.array=w.prototype.digest,w.prototype.arrayBuffer=function(){this.finalize();var h=new ArrayBuffer(16),d=new Uint32Array(h);return d[0]=this.h0,d[1]=this.h1,d[2]=this.h2,d[3]=this.h3,h},w.prototype.buffer=w.prototype.arrayBuffer,w.prototype.base64=function(){for(var h,d,g,m="",F=this.array(),E=0;E<15;)h=F[E++],d=F[E++],g=F[E++],m+=y[h>>>2]+y[(h<<4|d>>>4)&63]+y[(d<<2|g>>>6)&63]+y[g&63];return h=F[E],m+=y[h>>>2]+y[h<<4&63]+"==",m};function A(h,d){var g,m=x(h);if(h=m[0],m[1]){var F=[],E=h.length,O=0,D;for(g=0;g<E;++g)D=h.charCodeAt(g),D<128?F[O++]=D:D<2048?(F[O++]=192|D>>>6,F[O++]=128|D&63):D<55296||D>=57344?(F[O++]=224|D>>>12,F[O++]=128|D>>>6&63,F[O++]=128|D&63):(D=65536+((D&1023)<<10|h.charCodeAt(++g)&1023),F[O++]=240|D>>>18,F[O++]=128|D>>>12&63,F[O++]=128|D>>>6&63,F[O++]=128|D&63);h=F}h.length>64&&(h=new w(!0).update(h).array());var Y=[],Ee=[];for(g=0;g<64;++g){var ze=h[g]||0;Y[g]=92^ze,Ee[g]=54^ze}w.call(this,d),this.update(Ee),this.oKeyPad=Y,this.inner=!0,this.sharedMemory=d}A.prototype=new w,A.prototype.finalize=function(){if(w.prototype.finalize.call(this),this.inner){this.inner=!1;var h=this.array();w.call(this,this.sharedMemory),this.update(this.oKeyPad),this.update(h),w.prototype.finalize.call(this)}};var I=$();I.md5=I,I.md5.hmac=_(),o?t.exports=I:s.md5=I})()})(wn)),wn.exports}var Sl=wl(),Sn={exports:{}};/**
|
|
489
489
|
* [js-sha256]{@link https://github.com/emn178/js-sha256}
|
|
490
490
|
*
|
|
491
491
|
* @version 0.11.1
|
|
492
492
|
* @author Chen, Yi-Cyuan [emn178@gmail.com]
|
|
493
493
|
* @copyright Chen, Yi-Cyuan 2014-2025
|
|
494
494
|
* @license MIT
|
|
495
|
-
*/var fi;function _l(){return fi||(fi=1,(function(t){(function(){var e="input is invalid type",r=typeof window=="object",n=r?window:{};n.JS_SHA256_NO_WINDOW&&(r=!1);var s=!r&&typeof self=="object",i=!n.JS_SHA256_NO_NODE_JS&&typeof process=="object"&&process.versions&&process.versions.node&&process.type!="renderer";i?n=oa:s&&(n=self);var a=!n.JS_SHA256_NO_COMMON_JS&&!0&&t.exports,o=!n.JS_SHA256_NO_ARRAY_BUFFER&&typeof ArrayBuffer<"u",c="0123456789abcdef".split(""),u=[-2147483648,8388608,32768,128],f=[24,16,8,0],l=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],p=["hex","array","digest","arrayBuffer"],y=[];(n.JS_SHA256_NO_NODE_JS||!Array.isArray)&&(Array.isArray=function(S){return Object.prototype.toString.call(S)==="[object Array]"}),o&&(n.JS_SHA256_NO_ARRAY_BUFFER_IS_VIEW||!ArrayBuffer.isView)&&(ArrayBuffer.isView=function(S){return typeof S=="object"&&S.buffer&&S.buffer.constructor===ArrayBuffer});var v=function(S,T){return function(_){return new x(T,!0).update(_)[S]()}},w=function(S){var T=v("hex",S);i&&(T=R(T,S)),T.create=function(){return new x(S)},T.update=function(A){return T.create().update(A)};for(var _=0;_<p.length;++_){var b=p[_];T[b]=v(b,S)}return T},R=function(S,T){var _=Dr,b=Dr.Buffer,A=T?"sha224":"sha256",I;b.from&&!n.JS_SHA256_NO_BUFFER_FROM?I=b.from:I=function(d){return new b(d)};var h=function(d){if(typeof d=="string")return _.createHash(A).update(d,"utf8").digest("hex");if(d==null)throw new Error(e);return d.constructor===ArrayBuffer&&(d=new Uint8Array(d)),Array.isArray(d)||ArrayBuffer.isView(d)||d.constructor===b?_.createHash(A).update(I(d)).digest("hex"):S(d)};return h},C=function(S,T){return function(_,b){return new L(_,T,!0).update(b)[S]()}},k=function(S){var T=C("hex",S);T.create=function(A){return new L(A,S)},T.update=function(A,I){return T.create(A).update(I)};for(var _=0;_<p.length;++_){var b=p[_];T[b]=C(b,S)}return T};function x(S,T){T?(y[0]=y[16]=y[1]=y[2]=y[3]=y[4]=y[5]=y[6]=y[7]=y[8]=y[9]=y[10]=y[11]=y[12]=y[13]=y[14]=y[15]=0,this.blocks=y):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],S?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=S}x.prototype.update=function(S){if(!this.finalized){var T,_=typeof S;if(_!=="string"){if(_==="object"){if(S===null)throw new Error(e);if(o&&S.constructor===ArrayBuffer)S=new Uint8Array(S);else if(!Array.isArray(S)&&(!o||!ArrayBuffer.isView(S)))throw new Error(e)}else throw new Error(e);T=!0}for(var b,A=0,I,h=S.length,d=this.blocks;A<h;){if(this.hashed&&(this.hashed=!1,d[0]=this.block,this.block=d[16]=d[1]=d[2]=d[3]=d[4]=d[5]=d[6]=d[7]=d[8]=d[9]=d[10]=d[11]=d[12]=d[13]=d[14]=d[15]=0),T)for(I=this.start;A<h&&I<64;++A)d[I>>>2]|=S[A]<<f[I++&3];else for(I=this.start;A<h&&I<64;++A)b=S.charCodeAt(A),b<128?d[I>>>2]|=b<<f[I++&3]:b<2048?(d[I>>>2]|=(192|b>>>6)<<f[I++&3],d[I>>>2]|=(128|b&63)<<f[I++&3]):b<55296||b>=57344?(d[I>>>2]|=(224|b>>>12)<<f[I++&3],d[I>>>2]|=(128|b>>>6&63)<<f[I++&3],d[I>>>2]|=(128|b&63)<<f[I++&3]):(b=65536+((b&1023)<<10|S.charCodeAt(++A)&1023),d[I>>>2]|=(240|b>>>18)<<f[I++&3],d[I>>>2]|=(128|b>>>12&63)<<f[I++&3],d[I>>>2]|=(128|b>>>6&63)<<f[I++&3],d[I>>>2]|=(128|b&63)<<f[I++&3]);this.lastByteIndex=I,this.bytes+=I-this.start,I>=64?(this.block=d[16],this.start=I-64,this.hash(),this.hashed=!0):this.start=I}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}},x.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var S=this.blocks,T=this.lastByteIndex;S[16]=this.block,S[T>>>2]|=u[T&3],this.block=S[16],T>=56&&(this.hashed||this.hash(),S[0]=this.block,S[16]=S[1]=S[2]=S[3]=S[4]=S[5]=S[6]=S[7]=S[8]=S[9]=S[10]=S[11]=S[12]=S[13]=S[14]=S[15]=0),S[14]=this.hBytes<<3|this.bytes>>>29,S[15]=this.bytes<<3,this.hash()}},x.prototype.hash=function(){var S=this.h0,T=this.h1,_=this.h2,b=this.h3,A=this.h4,I=this.h5,h=this.h6,d=this.h7,g=this.blocks,m,F,E,O,D,Y,Ee,ze,Pt,$t,Ut;for(m=16;m<64;++m)D=g[m-15],F=(D>>>7|D<<25)^(D>>>18|D<<14)^D>>>3,D=g[m-2],E=(D>>>17|D<<15)^(D>>>19|D<<13)^D>>>10,g[m]=g[m-16]+F+g[m-7]+E<<0;for(Ut=T&_,m=0;m<64;m+=4)this.first?(this.is224?(ze=300032,D=g[0]-1413257819,d=D-150054599<<0,b=D+24177077<<0):(ze=704751109,D=g[0]-210244248,d=D-1521486534<<0,b=D+143694565<<0),this.first=!1):(F=(S>>>2|S<<30)^(S>>>13|S<<19)^(S>>>22|S<<10),E=(A>>>6|A<<26)^(A>>>11|A<<21)^(A>>>25|A<<7),ze=S&T,O=ze^S&_^Ut,Ee=A&I^~A&h,D=d+E+Ee+l[m]+g[m],Y=F+O,d=b+D<<0,b=D+Y<<0),F=(b>>>2|b<<30)^(b>>>13|b<<19)^(b>>>22|b<<10),E=(d>>>6|d<<26)^(d>>>11|d<<21)^(d>>>25|d<<7),Pt=b&S,O=Pt^b&T^ze,Ee=d&A^~d&I,D=h+E+Ee+l[m+1]+g[m+1],Y=F+O,h=_+D<<0,_=D+Y<<0,F=(_>>>2|_<<30)^(_>>>13|_<<19)^(_>>>22|_<<10),E=(h>>>6|h<<26)^(h>>>11|h<<21)^(h>>>25|h<<7),$t=_&b,O=$t^_&S^Pt,Ee=h&d^~h&A,D=I+E+Ee+l[m+2]+g[m+2],Y=F+O,I=T+D<<0,T=D+Y<<0,F=(T>>>2|T<<30)^(T>>>13|T<<19)^(T>>>22|T<<10),E=(I>>>6|I<<26)^(I>>>11|I<<21)^(I>>>25|I<<7),Ut=T&_,O=Ut^T&b^$t,Ee=I&h^~I&d,D=A+E+Ee+l[m+3]+g[m+3],Y=F+O,A=S+D<<0,S=D+Y<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+S<<0,this.h1=this.h1+T<<0,this.h2=this.h2+_<<0,this.h3=this.h3+b<<0,this.h4=this.h4+A<<0,this.h5=this.h5+I<<0,this.h6=this.h6+h<<0,this.h7=this.h7+d<<0},x.prototype.hex=function(){this.finalize();var S=this.h0,T=this.h1,_=this.h2,b=this.h3,A=this.h4,I=this.h5,h=this.h6,d=this.h7,g=c[S>>>28&15]+c[S>>>24&15]+c[S>>>20&15]+c[S>>>16&15]+c[S>>>12&15]+c[S>>>8&15]+c[S>>>4&15]+c[S&15]+c[T>>>28&15]+c[T>>>24&15]+c[T>>>20&15]+c[T>>>16&15]+c[T>>>12&15]+c[T>>>8&15]+c[T>>>4&15]+c[T&15]+c[_>>>28&15]+c[_>>>24&15]+c[_>>>20&15]+c[_>>>16&15]+c[_>>>12&15]+c[_>>>8&15]+c[_>>>4&15]+c[_&15]+c[b>>>28&15]+c[b>>>24&15]+c[b>>>20&15]+c[b>>>16&15]+c[b>>>12&15]+c[b>>>8&15]+c[b>>>4&15]+c[b&15]+c[A>>>28&15]+c[A>>>24&15]+c[A>>>20&15]+c[A>>>16&15]+c[A>>>12&15]+c[A>>>8&15]+c[A>>>4&15]+c[A&15]+c[I>>>28&15]+c[I>>>24&15]+c[I>>>20&15]+c[I>>>16&15]+c[I>>>12&15]+c[I>>>8&15]+c[I>>>4&15]+c[I&15]+c[h>>>28&15]+c[h>>>24&15]+c[h>>>20&15]+c[h>>>16&15]+c[h>>>12&15]+c[h>>>8&15]+c[h>>>4&15]+c[h&15];return this.is224||(g+=c[d>>>28&15]+c[d>>>24&15]+c[d>>>20&15]+c[d>>>16&15]+c[d>>>12&15]+c[d>>>8&15]+c[d>>>4&15]+c[d&15]),g},x.prototype.toString=x.prototype.hex,x.prototype.digest=function(){this.finalize();var S=this.h0,T=this.h1,_=this.h2,b=this.h3,A=this.h4,I=this.h5,h=this.h6,d=this.h7,g=[S>>>24&255,S>>>16&255,S>>>8&255,S&255,T>>>24&255,T>>>16&255,T>>>8&255,T&255,_>>>24&255,_>>>16&255,_>>>8&255,_&255,b>>>24&255,b>>>16&255,b>>>8&255,b&255,A>>>24&255,A>>>16&255,A>>>8&255,A&255,I>>>24&255,I>>>16&255,I>>>8&255,I&255,h>>>24&255,h>>>16&255,h>>>8&255,h&255];return this.is224||g.push(d>>>24&255,d>>>16&255,d>>>8&255,d&255),g},x.prototype.array=x.prototype.digest,x.prototype.arrayBuffer=function(){this.finalize();var S=new ArrayBuffer(this.is224?28:32),T=new DataView(S);return T.setUint32(0,this.h0),T.setUint32(4,this.h1),T.setUint32(8,this.h2),T.setUint32(12,this.h3),T.setUint32(16,this.h4),T.setUint32(20,this.h5),T.setUint32(24,this.h6),this.is224||T.setUint32(28,this.h7),S};function L(S,T,_){var b,A=typeof S;if(A==="string"){var I=[],h=S.length,d=0,g;for(b=0;b<h;++b)g=S.charCodeAt(b),g<128?I[d++]=g:g<2048?(I[d++]=192|g>>>6,I[d++]=128|g&63):g<55296||g>=57344?(I[d++]=224|g>>>12,I[d++]=128|g>>>6&63,I[d++]=128|g&63):(g=65536+((g&1023)<<10|S.charCodeAt(++b)&1023),I[d++]=240|g>>>18,I[d++]=128|g>>>12&63,I[d++]=128|g>>>6&63,I[d++]=128|g&63);S=I}else if(A==="object"){if(S===null)throw new Error(e);if(o&&S.constructor===ArrayBuffer)S=new Uint8Array(S);else if(!Array.isArray(S)&&(!o||!ArrayBuffer.isView(S)))throw new Error(e)}else throw new Error(e);S.length>64&&(S=new x(T,!0).update(S).array());var m=[],F=[];for(b=0;b<64;++b){var E=S[b]||0;m[b]=92^E,F[b]=54^E}x.call(this,T,_),this.update(F),this.oKeyPad=m,this.inner=!0,this.sharedMemory=_}L.prototype=new x,L.prototype.finalize=function(){if(x.prototype.finalize.call(this),this.inner){this.inner=!1;var S=this.array();x.call(this,this.is224,this.sharedMemory),this.update(this.oKeyPad),this.update(S),x.prototype.finalize.call(this)}};var $=w();$.sha256=$,$.sha224=w(!0),$.sha256.hmac=k(),$.sha224.hmac=k(!0),a?t.exports=$:(n.sha256=$.sha256,n.sha224=$.sha224)})()})(Sn)),Sn.exports}var Al=_l();function Il(t){if(t instanceof Ae)return t;if(typeof t=="string")return Ae.fromUtf8(t);throw new G(`hashing.* requires Bytes or String, got ${typeof t}`)}function xl(t,e){const r=Il(e[0]);switch(t){case"md5":return new Ae(new Uint8Array(Sl.md5.arrayBuffer(r.data)));case"sha256":return new Ae(new Uint8Array(Al.sha256.arrayBuffer(r.data)));case"crc32":{const n=El(r.data);return new Ae(pi(n))}case"crc32c":{const n=Ol(r.data);return new Ae(pi(n))}}throw new gt(`Unknown hashing method '${t}'`)}function pi(t){return new Uint8Array([t&255,t>>>8&255,t>>>16&255,t>>>24&255])}const kl=(()=>{const t=new Uint32Array(256);for(let e=0;e<256;e++){let r=e;for(let n=0;n<8;n++)r=r&1?3988292384^r>>>1:r>>>1;t[e]=r>>>0}return t})();function El(t){let e=4294967295;for(let r=0;r<t.length;r++)e=kl[(e^t[r])&255]^e>>>8;return(e^4294967295)>>>0}const Tl=(()=>{const t=new Uint32Array(256);for(let e=0;e<256;e++){let r=e;for(let n=0;n<8;n++)r=r&1?2197175160^r>>>1:r>>>1;t[e]=r>>>0}return t})();function Ol(t){let e=4294967295;for(let r=0;r<t.length;r++)e=Tl[(e^t[r])&255]^e>>>8;return(e^4294967295)>>>0}function Cl(t){if(typeof t=="number")return Math.trunc(t);if(t instanceof ae)return Math.trunc(t.value);if(typeof t=="boolean")return t?1:0;if(typeof t=="string"){if(/^[+-]?\d+$/.test(t.trim()))return parseInt(t.trim(),10);throw new G(`int() cannot convert string '${t}' to an integer`)}throw new G(`int() cannot convert ${typeof t} to an integer`)}function Rl(t){if(t instanceof ae)return t;if(typeof t=="number")return new ae(t);if(typeof t=="string"){const e=t.trim();if(/^[+-]?(\d+\.?\d*|\.\d+)$/.test(e))return new ae(parseFloat(e));throw new G(`float() cannot convert string '${t}' to a float`)}throw new G(`float() cannot convert ${typeof t} to a float`)}function Nl(t,e,r,n){switch(t){case"get":{const a=String(W(e[0],r,n));return li(a,r)}case"exists":{const a=String(W(e[0],r,n));return di(a,r)}case"getAfter":{const a=W(e[0],r,n),o=String(a);if(o===r.afterStatePath.toString()){if(r.afterState===null)throw new G(`getAfter() of non-existent document '${o}' (guard with existsAfter() first)`);return Wn(ur(o),r.afterState)}const c=ur(o);if(r.batchProjection?.has(c)){const u=r.batchProjection.get(c);if(u===null)throw new G(`getAfter() of non-existent document '${o}' (guard with existsAfter() first)`);return Wn(c,u)}return li(o,r)}case"existsAfter":{const a=W(e[0],r,n),o=String(a);if(o===r.afterStatePath.toString())return r.existsAfter;const c=ur(o);return r.batchProjection?.has(c)?r.batchProjection.get(c)!==null:di(o,r)}case"debug":return W(e[0],r,n);case"string":return String(W(e[0],r,n));case"int":return Cl(W(e[0],r,n));case"float":return Rl(W(e[0],r,n));case"path":{const a=W(e[0],r,n);if(typeof a=="string")return Qe.fromString(a);throw new G(`path() requires a string argument, got ${typeof a}`)}}const s=r.functions.get(t);if(!s)throw new G(`Unknown function: ${t}`);const i={...n};for(let a=0;a<s.parameters.length;a++)i[s.parameters[a]]=W(e[a],r,n);r.trace?.enterFrame(t);try{for(const a of s.lets){const o=r.trace?r.trace.entries.length:-1;i[a.name]=W(a.value,r,i),o>=0&&r.trace?.markEntryAsLetBinding(o,a.name)}return W(s.body,r,i)}finally{r.trace?.exitFrame()}}function Ll(t,e,r,n,s){if(t.type==="identifier"){const o=t.name;if(mi(o)&&!(o in s)&&!(o in n.pathVariables)){const c=r.map(u=>W(u,n,s));return Dl(o,e,c)}if(!mi(o)&&!(o in s)&&!(o in n.pathVariables)&&!Bl(o))throw new gt(`Unknown namespace or method '${o}.${e}()'`)}const i=W(t,n,s),a=r.map(o=>W(o,n,s));if(i instanceof te){const o=i.callMethod(e,a);if(o===oe)throw new gt(`Unknown method '${e}' on ${i.typeName}`);return o}if(e==="diff"&&typeof i=="object"&&i!==null&&!Array.isArray(i)){const o=a[0];if(typeof o=="object"&&o!==null)return new cr(o,i);throw new G("diff() requires a map argument")}if(typeof i=="function")return i(...a);if(i instanceof de)switch(e){case"hasOnly":return i.hasOnly(a[0]);case"hasAll":return i.hasAll(a[0]);case"hasAny":return i.hasAny(a[0]);case"size":return i.size();case"difference":case"union":case"intersection":{const o=a[0];if(!(o instanceof de))throw new G(`Unsupported operation: set.${e} requires a Set argument`);return i[e](o)}}if(i instanceof cr)switch(e){case"addedKeys":return i.addedKeys();case"removedKeys":return i.removedKeys();case"changedKeys":return i.changedKeys();case"affectedKeys":return i.affectedKeys();case"unchangedKeys":return i.unchangedKeys()}if(typeof i=="object"&&i!==null&&!Array.isArray(i)){const o=i;switch(e){case"keys":return Object.keys(o);case"values":return Object.values(o);case"size":return Object.keys(o).length;case"diff":{const c=a[0];return new cr(c,o)}case"get":{const c=a[0],u=a[1];if(Array.isArray(c)){let l=o;for(const p of c){if(l==null||typeof l!="object"||Array.isArray(l)||l instanceof te)return u;const y=String(p);if(!Object.hasOwn(l,y))return u;l=l[y]}return l}const f=String(c);return Object.hasOwn(o,f)?o[f]:u}}}if(Array.isArray(i))switch(e){case"size":return i.length;case"hasAll":return a[0].every(o=>i.some(c=>me(c,o)));case"hasAny":return a[0].some(o=>i.some(c=>me(c,o)));case"hasOnly":{const o=a[0];return i.every(c=>o.some(u=>me(u,c)))}case"join":return i.join(String(a[0]??","));case"concat":{const o=a[0];if(!Array.isArray(o))throw new G(`List.concat requires a list argument, got ${typeof o}`);return[...i,...o]}case"removeAll":{const o=a[0];if(!Array.isArray(o))throw new G(`List.removeAll requires a list argument, got ${typeof o}`);return i.filter(c=>!o.some(u=>me(c,u)))}case"toSet":return new de(i);case"difference":case"union":case"intersection":throw new G(`Function not found on List receiver: ${e}`)}if(typeof i=="string")switch(e){case"size":return i.length;case"lower":return i.toLowerCase();case"upper":return i.toUpperCase();case"trim":return i.trim();case"split":return i.split(_n(String(a[0]),"g"));case"matches":return _n(`^(?:${String(a[0])})$`).test(i);case"replace":return i.replace(_n(String(a[0]),"g"),String(a[1]));case"toUtf8":return Ae.fromUtf8(i)}throw new G(`Unknown method '${e}' on ${typeof i}`)}function _n(t,e=""){try{return new RegExp(t,e)}catch(r){throw new G(`Invalid regex '${t}': ${r.message}`)}}const Ml=new Set(["math","timestamp","duration","latlng","hashing"]);function mi(t){return Ml.has(t)}function Dl(t,e,r){const n=t==="hashing"?r:r.map(Fl);switch(t){case"math":return ql(e,n);case"timestamp":return Pl(e,n);case"duration":return $l(e,n);case"latlng":return jl(e,n);case"hashing":return xl(e,r)}throw new gt(`Unknown namespace '${t}'`)}function Fl(t){return t instanceof ae?t.value:t}function jl(t,e){switch(t){case"value":{const[r,n]=e;return new lt(r,n)}}throw new gt(`Unknown latlng method '${t}'`)}function ql(t,e){switch(t){case"abs":return Math.abs(e[0]);case"ceil":return Math.ceil(e[0]);case"floor":return Math.floor(e[0]);case"round":return Math.round(e[0]);case"sqrt":return Math.sqrt(e[0]);case"pow":return Math.pow(e[0],e[1]);case"isNaN":return Number.isNaN(e[0])}throw new G(`Unknown math method '${t}'`)}function Pl(t,e){switch(t){case"date":{const[r,n,s]=e;return _e.fromYMD(r,n,s)}case"value":return _e.fromMillis(e[0])}throw new gt(`Unknown timestamp method '${t}'`)}function $l(t,e){switch(t){case"value":try{return ve.fromValue(e[0],e[1])}catch(r){throw new G(r.message)}case"time":{const[r,n,s,i]=e;return ve.fromTime(r,n,s,i)}case"abs":{const r=e[0];if(!(r instanceof ve))throw new G(`duration.abs() requires a Duration argument, got ${typeof r}`);return ve.abs(r)}}throw new gt(`Unknown duration method '${t}'`)}function W(t,e,r={}){return e.trace?e.trace.capture(t,()=>gi(t,e,r)):gi(t,e,r)}function gi(t,e,r){switch(t.type){case"literal":return typeof t.value=="number"&&t.raw.includes(".")?new ae(t.value):t.value;case"identifier":return Ul(t.name,e,r);case"binaryOp":return zl(t.op,t.left,t.right,e,r);case"unaryOp":{if(t.op==="!")return!W(t.operand,e,r);if(t.op==="-"){const n=W(t.operand,e,r);return n instanceof ae?new ae(-n.value):-n}throw new G(`Unknown unary op: ${t.op}`,t)}case"ternary":{const n=ir(W(t.condition,e,r),t.condition);return W(n?t.consequent:t.alternate,e,r)}case"memberAccess":{const n=W(t.object,e,r);if(n==null)throw new G(`Property '${t.property}' accessed on ${n===null?"null":"undefined"} value`,t);if(n instanceof te)return n.field(t.property);if(n instanceof cr)switch(t.property){case"addedKeys":return()=>n.addedKeys();case"removedKeys":return()=>n.removedKeys();case"changedKeys":return()=>n.changedKeys();case"affectedKeys":return()=>n.affectedKeys();case"unchangedKeys":return()=>n.unchangedKeys()}if(n instanceof de)switch(t.property){case"size":return()=>n.size()}if(Object.hasOwn(n,t.property))return n[t.property];throw new G(`No field '${t.property}' on map (use 'in' or .get() to read a possibly-absent field)`,t)}case"bracketAccess":{const n=W(t.object,e,r),s=W(t.index,e,r);if(n==null)throw new G(`Index access on ${n===null?"null":"undefined"} value`,t);if(n instanceof te)return n.field(String(s));const i=String(s);return Object.hasOwn(n,i)?n[i]:null}case"sliceAccess":{const n=W(t.object,e,r),s=W(t.start,e,r),i=W(t.end,e,r);if(n==null)return null;if(typeof s!="number"||!Number.isInteger(s))throw new G(`Slice start must be an integer, got ${typeof s}`);if(typeof i!="number"||!Number.isInteger(i))throw new G(`Slice end must be an integer, got ${typeof i}`);if(s<0||i<0)throw new G(`Slice indices must be non-negative, got [${s}:${i}]`);if(typeof n=="string"||Array.isArray(n)){if(i>n.length)throw new G(`Slice end ${i} exceeds length ${n.length}`);return n.slice(s,i)}throw new G(`Slice not supported on ${typeof n}`)}case"inExpr":{const n=W(t.element,e,r),s=W(t.collection,e,r);return s==null?!1:Array.isArray(s)?s.some(i=>me(i,n)):typeof s=="object"?Object.hasOwn(s,String(n)):!1}case"isExpr":{const n=W(t.value,e,r);switch(t.typeName){case"string":return typeof n=="string";case"int":return n instanceof te?!1:typeof n=="number";case"float":return n instanceof ae;case"number":return n instanceof ae?!0:n instanceof te?!1:typeof n=="number";case"bool":return typeof n=="boolean";case"null":return n===null;case"list":return Array.isArray(n);case"map":return n instanceof te||n instanceof cr||n instanceof de?!1:typeof n=="object"&&n!==null&&!Array.isArray(n);default:return n instanceof te?n.typeName===t.typeName:!1}}case"listLiteral":return t.elements.map(n=>W(n,e,r));case"mapLiteral":{const n={};for(const s of t.entries){const i=String(W(s.key,e,r));n[i]=W(s.value,e,r)}return n}case"functionCall":return Nl(t.name,t.args,e,r);case"methodCall":return Ll(t.object,t.method,t.args,e,r);case"pathLiteral":{const n=[];for(const s of t.segments)typeof s=="string"?n.push(s):n.push(String(W(s,e,r)));return new Qe(n)}default:throw new G(`Unknown expression type: ${t.type}`,t)}}function Ul(t,e,r){if(t in r)return r[t];if(t in e.pathVariables)return e.pathVariables[t];switch(t){case"request":return e.request;case"resource":if(e.resource===null)throw new G("Null value error.");return e.resource;case"true":return!0;case"false":return!1;case"null":return null}throw new G(`Undefined variable '${t}'`)}function Bl(t){return t==="request"||t==="resource"||t==="true"||t==="false"||t==="null"}function zl(t,e,r,n,s){if(t==="&&"){let o,c;try{o=ir(W(e,n,s),e)}catch(l){c=l}if(c===void 0&&o===!1)return n.trace?.skip(r),!1;let u,f;try{u=ir(W(r,n,s),r)}catch(l){f=l}if(f===void 0&&u===!1)return!1;if(c!==void 0)throw c;if(f!==void 0)throw f;return u}if(t==="||"){let o,c;try{o=ir(W(e,n,s),e)}catch(l){c=l}if(c===void 0&&o===!0)return n.trace?.skip(r),!0;let u,f;try{u=ir(W(r,n,s),r)}catch(l){f=l}if(f===void 0&&u===!0)return!0;if(c!==void 0)throw c;if(f!==void 0)throw f;return u}const i=W(e,n,s),a=W(r,n,s);if(t!=="=="&&t!=="!="){if(i instanceof te){const o=i.binaryOp(t,a);if(o!==oe)return o}if(typeof i=="number"&&a instanceof ae){const o=new ae(i).binaryOp(t,a);if(o!==oe)return o}if(a instanceof te&&(t==="+"||t==="*")){const o=a.binaryOp(t,i);if(o!==oe)return o}if((t!=="+"||typeof i!="string"&&typeof a!="string")&&(i instanceof te||a instanceof te)){const o=i instanceof te?i.typeName:typeof i,c=a instanceof te?a.typeName:typeof a;throw new G(`Operator '${t}' is not defined between ${o} and ${c}`)}}if((t==="<"||t===">"||t==="<="||t===">=")&&!(typeof i=="number"&&typeof a=="number"||typeof i=="string"&&typeof a=="string"))throw new G(`Operator '${t}' is not defined between ${typeof i} and ${typeof a}`);switch(t){case"==":return i===a||me(i,a);case"!=":return!(i===a||me(i,a));case"<":return i<a;case">":return i>a;case"<=":return i<=a;case">=":return i>=a;case"+":{if(Array.isArray(i)&&Array.isArray(a))return[...i,...a];if(typeof i=="string"&&typeof a=="string"||typeof i=="number"&&typeof a=="number")return i+a;if(typeof i=="string"&&a instanceof te)return i+String(a);throw new G(`Operator '+' is not defined between ${Array.isArray(i)?"list":typeof i} and ${Array.isArray(a)?"list":typeof a}`)}case"-":return i-a;case"*":return i*a;case"/":if(a===0)throw new G("Division by zero");return Math.trunc(i/a);case"%":if(a===0)throw new G("Modulo by zero");return i%a;default:throw new G(`Unknown binary op: ${t}`)}}function ir(t,e){if(typeof t=="boolean")return t;throw new G(`Expected a boolean control-flow operand, got ${t===null?"null":typeof t}`,e)}const Vl=new Set(["__proto__","prototype","constructor"]);function Fr(t){if(Vl.has(t))throw new Error(`Invalid field-path segment '${t}': the keys __proto__, prototype, and constructor are reserved and cannot appear in a field path.`)}function Ka(t,e){const r={...t};for(const[n,s]of Object.entries(e)){Fr(n);const i=Object.hasOwn(r,n)?r[n]:void 0;s!==null&&typeof s=="object"&&!Array.isArray(s)&&i!==null&&typeof i=="object"&&!Array.isArray(i)?r[n]=Ka(i,s):r[n]=s}return r}function Hl(t,e,r){let n=t;for(let i=0;i<e.length-1;i++){const a=e[i];Fr(a);const o=Object.hasOwn(n,a)?n[a]:void 0;(o===null||typeof o!="object"||Array.isArray(o))&&(n[a]={}),n=n[a]}const s=e[e.length-1];Fr(s),n[s]=r}function Wl(t,e){const r={...t};for(const[n,s]of Object.entries(e))n.includes(".")?Hl(r,n.split("."),s):(Fr(n),r[n]=s);return r}function Gl(t,e,r){switch(t.kind){case"create":return r;case"set":return t.merge?Ka(e??{},r):r;case"update":return Wl(e??{},r);case"delete":return null}}function Za(t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function Kl(t){return typeof t=="object"&&t!==null&&t.__type==="serverTimestamp"}function Ja(t,e){const r={};for(const[n,s]of Object.entries(t))Kl(s)?r[n]=e:Za(s)?r[n]=Ja(s,e):r[n]=s;return r}function It(t){return typeof t=="number"&&!Number.isInteger(t)?new ae(t):Array.isArray(t)?t.map(It):Za(t)?t.__type==="float"&&typeof t.value=="number"?new ae(t.value):Object.fromEntries(Object.entries(t).map(([e,r])=>[e,It(r)])):t}function yi(t){if(t.method==="list")return{limit:t.query?.limit??null,offset:t.query?.offset??null,orderBy:t.query?.orderBy??null}}function xr(t){return`/${t.path.segments.map(r=>r.type==="literal"?r.value:r.type==="wildcard"?`{${r.name}}`:`{${r.name}=**}`).join("/")}`}function jr(t,e,r,n){const s=[...r,...t.functions],i=t.path.segments,a={},o=[];let c=0,u;for(const p of i)if(p.type==="literal"){if(c>=e.length){u="request-shorter";break}if(e[c]!==p.value){u="literal-mismatch";break}c++}else if(p.type==="wildcard"){if(c>=e.length){u="request-shorter";break}a[p.name]=e[c],c===e.length-1&&o.push(p.name),c++}else a[p.name]=e.slice(c).join("/"),c<e.length&&o.push(p.name),c=e.length;if(u!==void 0)return n?.push({...t.loc?{line:t.loc.line}:{},blockPath:xr(t),matchedSegments:c,totalSegments:i.length,bindings:a,matched:!1,reason:u}),[];const f=e.slice(c);if(f.length===0)return n?.push({...t.loc?{line:t.loc.line}:{},blockPath:xr(t),matchedSegments:c,totalSegments:i.length,bindings:a,matched:!0}),[{block:t,pathVariables:a,candidateVariables:o,functions:s}];const l=[];for(const p of t.children)for(const y of jr(p,f,s,n))y.pathVariables={...a,...y.pathVariables},y.candidateVariables=[...o,...y.candidateVariables],l.push(y);return n?.push({...t.loc?{line:t.loc.line}:{},blockPath:xr(t),matchedSegments:c,totalSegments:i.length,bindings:a,...l.length>0?{matched:!0}:{matched:!1,reason:"no-matching-child"}}),l}class Zl{attempts=[];push(e){this.attempts.push(e)}}function Jl(t){switch(t){case"get":return["get","read"];case"list":return["list","read"];case"create":return["create","write"];case"update":return["update","write"];case"delete":return["delete","write"];default:return[t]}}function Yl(t,e,r,n){const s=Jl(e),i=[],a=[],o=[];for(let p=0;p<t.allows.length;p++){const y=t.allows[p];y.operations.some(w=>s.includes(w))&&o.push({rule:y,index:p})}if(o.length===0)return a.push(`No allow rules found for operation '${e}'`),{decision:"DENY",trace:i,notes:a};let u=!1;const f=r.trace;for(const{rule:p,index:y}of o){const v=Ql(p,y,n),w=new ll;r.trace=w;try{const R=W(p.condition,r);if(v.expressionTrace=w.entries,!!R)return v.verdict="ALLOW",i.push(v),r.trace=f,{decision:"ALLOW",trace:i,notes:a};v.verdict="DENY",i.push(v)}catch(R){v.expressionTrace=w.entries,R instanceof gt?(u=!0,v.verdict="UNSUPPORTED",v.message=R.message):(v.verdict="ERROR",R instanceof Error?v.message=R.message:v.message=String(R)),i.push(v)}}r.trace=f;let l="DENY";return u&&(l="UNSUPPORTED"),{decision:l,trace:i,notes:a}}function Ql(t,e,r){const n=ye(t.condition),s={ruleIndex:e,operations:[...t.operations],verdict:"DENY",conditionText:n};if(t.loc!==void 0){const a=t.loc;if(s.line=a.line,s.col=a.col,s.column=a.col,a.file!==void 0?(s.file=a.file,s.citation=`${a.file}:${a.line}:${a.col}`):(s.file="firestore.rules",s.citation=`firestore.rules:${a.line}:${a.col}`),r!==void 0){const u=Ga(r,a.line,a.col,a.file,n);u!==void 0&&(s.line=u.line,s.col=u.col,s.column=u.col,s.file=u.file,s.citation=u.citation,u.expression!==void 0&&(s.conditionText=u.expression))}}return s}function Xl(t,e,r,n,s){const i=new Map;for(const k of e)i.set(k.name,k);const a=new Map,o=new Set;if(t.functionMocks)for(const k of t.functionMocks)k.function==="get"&&typeof k.result=="object"&&k.result!==null?(a.set(k.path,It(k.result)),o.add(k.path)):k.function==="exists"&&k.result===!0&&(a.set(k.path,{}),o.add(k.path));const c=t.requestTime?_e.fromIsoString(t.requestTime):_e.fromMillis(Date.now()),f=["databases","(default)","documents",...(t.path.startsWith("/")?t.path.slice(1):t.path).split("/").filter(Boolean)],l=new Qe(f,r),p=It(t.data??{}),y=t.resource===void 0||t.resource===null?null:It(t.resource);let v,w;if(t.writeMode)v=Gl(t.writeMode,y,p),w=v!==null;else switch(t.method){case"create":case"update":v=p,w=!0;break;case"delete":v=null,w=!1;break;case"get":case"list":default:v=y,w=y!==null;break}const R=v!==null?It(Ja(v,c)):null,C=R??{};return{request:{auth:t.auth?{uid:t.auth.uid,token:t.auth.token??{}}:null,resource:{data:C},method:t.method,path:l,...yi(t)?{query:yi(t)}:{},time:c},resource:t.method==="create"||y===null?null:{data:It(y)},mockDocuments:a,identitylessFunctionMocks:o,getDoc:n,pathVariables:r,functions:i,database:"(default)",afterStatePath:l,afterState:R,existsAfter:w,...s?{batchProjection:s}:{}}}class ed{simulate(e,r,n){if(!e||e.trim().length===0)return{success:!1,error:{code:"PARSE_FAILED",message:"Empty rules source — call setRules(sandbox, rules) from pyric/sandbox/firestore before operating, or initialize without rules to use the open-by-default ruleset. See pyric/sandbox docs.",recoverable:!0}};const s=_s(e);if(!s)return{success:!1,error:{code:"PARSE_FAILED",message:"Failed to parse rules source",recoverable:!0}};const i=[];let a=0,o=0,c=0;const u={database:"(default)"};for(const f of s.service.match.path.segments)f.type==="wildcard"&&(u[f.name]="(default)");for(const f of r){const l=f.path.split("/").filter(Boolean),p=[...s.functions??[],...s.service.functions??[],...s.service.match.functions];let y=[];const v=new Zl;for(const d of s.service.match.children)y.push(...jr(d,l,p,v));let w=!1;const R=y.length===0,C=f.method==="list";if(R&&C){const d=[...l,"__hypothetical_doc__"];for(const m of s.service.match.children)y.push(...jr(m,d,p,v));y.length>0&&(w=!0)}const k={requestPath:f.path,attempts:v.attempts};if(y.length===0){const d=f.expectation==="DENY"?"PASSED":"FAILED";d==="PASSED"?a++:o++,i.push({description:f.description,expectation:f.expectation,state:d,decision:"DENY",trace:[],notes:[`No match block found for path '${f.path}'`],pathResolution:k});continue}let L="DENY";const $=[],S=[];let T=!1,_;for(const d of y){const g={...u,...d.pathVariables},m=Xl(f,d.functions,g,n?.getDoc,n?.batchProjection),F=xr(d.block),E=Yl(d.block,f.method,m,e);for(const Y of E.trace)Y.matchPath=F;if($.push(...E.trace),S.push(...E.notes),E.decision==="ALLOW"){L="ALLOW",_=F;break}E.decision==="UNSUPPORTED"&&(T=!0)}L!=="ALLOW"&&T&&(L="UNSUPPORTED"),L==="ALLOW"&&_!==void 0&&S.push(`Allowed by match block '${_}'`),w===!0&&S.push(`list on collection path '${f.path}' evaluated against the document-level match block (document wildcard hypothetical, resource undefined) — emulator-faithful`);let h;L==="UNSUPPORTED"?(h="UNSUPPORTED",c++):L===f.expectation?(h="PASSED",a++):(h="FAILED",o++),i.push({description:f.description,expectation:f.expectation,state:h,decision:L,trace:$,notes:S,pathResolution:k})}return{success:!0,data:{passed:a,failed:o,unsupported:c,results:i}}}}function td(t,e,r=new Map,n){if(qr(t,r))return{provable:!0,reason:"list rule does not depend on per-document data; every doc is equally readable"};const s=nd(t,r,n);if(!s.ok||s.required.length===0){const u="list rule depends on per-document data through a predicate the query cannot discharge (a rule is provable only when its entire doc-dependence reduces to top-level `resource.data.field == value` conjunctions, including through inlined helpers — disjunctions, ranges, `in`, membership/type checks, and nested paths are not provable)";return{provable:!1,reason:`${u} — prod rejects the whole query rather than filtering`,residual:{missing:[],mismatched:[],outOfScope:u}}}const i=s.required,a=e.where??[],o=[],c=[];for(const u of i){if(a.some(p=>p.field===u.field&&p.op==="=="&&od(p.value,u.value)))continue;const l=a.find(p=>p.field===u.field&&p.op==="==");l?c.push({field:u.field,expectedValue:u.value,actualValue:l.value}):o.push({field:u.field,expectedValue:u.value,fromAuthUid:u.fromAuthUid})}return o.length===0&&c.length===0?{provable:!0,reason:"every per-document predicate the rule requires is guaranteed by a query where(...) constraint"}:{provable:!1,reason:rd(o,c),residual:{missing:o,mismatched:c}}}function rd(t,e){const r=[];if(t.length>0){const n=t.map(s=>`resource.data.${s.field} == ${s.fromAuthUid?"request.auth.uid":JSON.stringify(s.expectedValue)}`).join(", ");r.push(`the query has no matching where(...) equality for [${n}]`)}if(e.length>0){const n=e.map(s=>`resource.data.${s.field} == ${JSON.stringify(s.expectedValue)} but the query pins ${JSON.stringify(s.actualValue)}`).join(", ");r.push(`the query where(...) value does not match [${n}]`)}return`${r.join("; ")} — prod rejects the query ("rules are not filters")`}function qr(t,e=new Map,r=new Set){const n=s=>{switch(s.type){case"literal":return!0;case"identifier":return s.name!=="resource";case"memberAccess":return n(s.object);case"bracketAccess":return n(s.object)&&n(s.index);case"sliceAccess":return n(s.object)&&n(s.start)&&n(s.end);case"binaryOp":return n(s.left)&&n(s.right);case"unaryOp":return n(s.operand);case"ternary":return n(s.condition)&&n(s.consequent)&&n(s.alternate);case"inExpr":return n(s.element)&&n(s.collection);case"isExpr":return n(s.value);case"listLiteral":return s.elements.every(n);case"mapLiteral":return s.entries.every(i=>n(i.key)&&n(i.value));case"pathLiteral":return s.segments.every(i=>typeof i=="string"||n(i));case"methodCall":return n(s.object)&&s.args.every(n);case"functionCall":{if(!s.args.every(n))return!1;const i=e.get(s.name);if(!i)return!0;if(r.has(s.name))return!1;const a=new Set(r).add(s.name);return qr(i.body,e,a)&&i.lets.every(o=>qr(o.value,e,a))}default:return!1}};return n(t)}function nd(t,e,r){const n=[],s=(i,a)=>{if(i.type==="binaryOp"&&i.op==="&&")return s(i.left,a)&&s(i.right,a);if(i.type==="functionCall"&&e.has(i.name)&&!a.has(i.name)){const c=e.get(i.name),u=new Map;c.parameters.forEach((p,y)=>{const v=i.args[y];v&&u.set(p,v)});for(const p of c.lets)u.set(p.name,vi(p.value,u));const f=vi(c.body,u),l=new Set(a).add(i.name);return s(f,l)}const o=sd(i,r);return o?(n.push(o),!0):qr(i,e)};return s(t,new Set)?{ok:!0,required:n}:{ok:!1}}function sd(t,e){if(t.type!=="binaryOp"||t.op!=="==")return null;const r=(n,s)=>{const i=ad(n);return i===null?null:s.type==="literal"?{field:i,value:s.value,fromAuthUid:!1}:e!==void 0&&id(s)?{field:i,value:e,fromAuthUid:!0}:null};return r(t.left,t.right)??r(t.right,t.left)}function id(t){return t.type==="memberAccess"&&t.property==="uid"&&t.object.type==="memberAccess"&&t.object.property==="auth"&&t.object.object.type==="identifier"&&t.object.object.name==="request"}function vi(t,e){const r=n=>{switch(n.type){case"identifier":return e.get(n.name)??n;case"literal":return n;case"memberAccess":return{...n,object:r(n.object)};case"methodCall":return{...n,object:r(n.object),args:n.args.map(r)};case"bracketAccess":return{...n,object:r(n.object),index:r(n.index)};case"sliceAccess":return{...n,object:r(n.object),start:r(n.start),end:r(n.end)};case"binaryOp":return{...n,left:r(n.left),right:r(n.right)};case"unaryOp":return{...n,operand:r(n.operand)};case"ternary":return{...n,condition:r(n.condition),consequent:r(n.consequent),alternate:r(n.alternate)};case"inExpr":return{...n,element:r(n.element),collection:r(n.collection)};case"isExpr":return{...n,value:r(n.value)};case"listLiteral":return{...n,elements:n.elements.map(r)};case"mapLiteral":return{...n,entries:n.entries.map(s=>({key:r(s.key),value:r(s.value)}))};case"pathLiteral":return{...n,segments:n.segments.map(s=>typeof s=="string"?s:r(s))};case"functionCall":return{...n,args:n.args.map(r)}}};return r(t)}function ad(t){return t.type==="memberAccess"&&t.object.type==="memberAccess"&&t.object.property==="data"&&t.object.object.type==="identifier"&&t.object.object.name==="resource"?t.property:null}function od(t,e){return t===e}class Ot extends te{typeName="reference";path;constructor(e){super(),this.path=cd(e)}static fromResourceName(e){return new Ot(Ya(e))}get id(){const e=this.path.lastIndexOf("/");return e===-1?this.path:this.path.slice(e+1)}get parent(){const e=this.path.lastIndexOf("/");return e===-1?"":this.path.slice(0,e)}valueOf(){return NaN}toString(){return this.path}toJSON(){return{__type:"reference",path:this.path}}equals(e){return e instanceof Ot?this.path===e.path:!1}field(e){switch(e){case"path":return this.path;case"id":return this.id;case"parent":return this.parent;default:return null}}callMethod(e,r){return oe}}function cd(t){let e=Ya(t);return e.startsWith("/")&&(e=e.slice(1)),e.endsWith("/")&&(e=e.slice(0,-1)),e}function Ya(t){const e="/documents/",r=t.indexOf(e);return r===-1?t:t.slice(r+e.length)}class Qt extends te{typeName="vector";value;constructor(e){if(super(),!Array.isArray(e))throw new TypeError("Vector: value must be a number[]");for(let r=0;r<e.length;r++)if(typeof e[r]!="number")throw new TypeError(`Vector: element at index ${r} is not a number (got ${typeof e[r]})`);this.value=Object.freeze(e.slice())}get dimension(){return this.value.length}valueOf(){return NaN}toString(){return`[${this.value.join(", ")}]`}toJSON(){return{__type__:"__vector__",value:this.value.slice()}}equals(e){if(!(e instanceof Qt)||e.value.length!==this.value.length)return!1;for(let r=0;r<this.value.length;r++)if(e.value[r]!==this.value[r])return!1;return!0}callMethod(e,r){return oe}}var J;(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function r(s){throw new Error}t.assertNever=r,t.arrayToEnum=s=>{const i={};for(const a of s)i[a]=a;return i},t.getValidEnumValues=s=>{const i=t.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),a={};for(const o of i)a[o]=s[o];return t.objectValues(a)},t.objectValues=s=>t.objectKeys(s).map(function(i){return s[i]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const i=[];for(const a in s)Object.prototype.hasOwnProperty.call(s,a)&&i.push(a);return i},t.find=(s,i)=>{for(const a of s)if(i(a))return a},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,i=" | "){return s.map(a=>typeof a=="string"?`'${a}'`:a).join(i)}t.joinValues=n,t.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(J||(J={}));var bi;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(bi||(bi={}));const q=J.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ft=t=>{switch(typeof t){case"undefined":return q.undefined;case"string":return q.string;case"number":return Number.isNaN(t)?q.nan:q.number;case"boolean":return q.boolean;case"function":return q.function;case"bigint":return q.bigint;case"symbol":return q.symbol;case"object":return Array.isArray(t)?q.array:t===null?q.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?q.promise:typeof Map<"u"&&t instanceof Map?q.map:typeof Set<"u"&&t instanceof Set?q.set:typeof Date<"u"&&t instanceof Date?q.date:q.object;default:return q.unknown}},N=J.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class dt extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){const r=e||function(i){return i.message},n={_errors:[]},s=i=>{for(const a of i.issues)if(a.code==="invalid_union")a.unionErrors.map(s);else if(a.code==="invalid_return_type")s(a.returnTypeError);else if(a.code==="invalid_arguments")s(a.argumentsError);else if(a.path.length===0)n._errors.push(r(a));else{let o=n,c=0;for(;c<a.path.length;){const u=a.path[c];c===a.path.length-1?(o[u]=o[u]||{_errors:[]},o[u]._errors.push(r(a))):o[u]=o[u]||{_errors:[]},o=o[u],c++}}};return s(this),n}static assert(e){if(!(e instanceof dt))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,J.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){const r={},n=[];for(const s of this.issues)if(s.path.length>0){const i=s.path[0];r[i]=r[i]||[],r[i].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}}dt.create=t=>new dt(t);const Gn=(t,e)=>{let r;switch(t.code){case N.invalid_type:t.received===q.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case N.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,J.jsonStringifyReplacer)}`;break;case N.unrecognized_keys:r=`Unrecognized key(s) in object: ${J.joinValues(t.keys,", ")}`;break;case N.invalid_union:r="Invalid input";break;case N.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${J.joinValues(t.options)}`;break;case N.invalid_enum_value:r=`Invalid enum value. Expected ${J.joinValues(t.options)}, received '${t.received}'`;break;case N.invalid_arguments:r="Invalid function arguments";break;case N.invalid_return_type:r="Invalid function return type";break;case N.invalid_date:r="Invalid date";break;case N.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:J.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case N.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case N.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case N.custom:r="Invalid input";break;case N.invalid_intersection_types:r="Intersection results could not be merged";break;case N.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case N.not_finite:r="Number must be finite";break;default:r=e.defaultError,J.assertNever(t)}return{message:r}};let ud=Gn;function ld(){return ud}const dd=t=>{const{data:e,path:r,errorMaps:n,issueData:s}=t,i=[...r,...s.path||[]],a={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let o="";const c=n.filter(u=>!!u).slice().reverse();for(const u of c)o=u(a,{data:e,defaultError:o}).message;return{...s,path:i,message:o}};function j(t,e){const r=ld(),n=dd({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Gn?void 0:Gn].filter(s=>!!s)});t.common.issues.push(n)}class De{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){const n=[];for(const s of r){if(s.status==="aborted")return U;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){const n=[];for(const s of r){const i=await s.key,a=await s.value;n.push({key:i,value:a})}return De.mergeObjectSync(e,n)}static mergeObjectSync(e,r){const n={};for(const s of r){const{key:i,value:a}=s;if(i.status==="aborted"||a.status==="aborted")return U;i.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof a.value<"u"||s.alwaysSet)&&(n[i.value]=a.value)}return{status:e.value,value:n}}}const U=Object.freeze({status:"aborted"}),ar=t=>({status:"dirty",value:t}),He=t=>({status:"valid",value:t}),wi=t=>t.status==="aborted",Si=t=>t.status==="dirty",Gt=t=>t.status==="valid",Pr=t=>typeof Promise<"u"&&t instanceof Promise;var P;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(P||(P={}));class tt{constructor(e,r,n,s){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const _i=(t,e)=>{if(Gt(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const r=new dt(t.common.issues);return this._error=r,this._error}}};function H(t){if(!t)return{};const{errorMap:e,invalid_type_error:r,required_error:n,description:s}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(a,o)=>{const{message:c}=t;return a.code==="invalid_enum_value"?{message:c??o.defaultError}:typeof o.data>"u"?{message:c??n??o.defaultError}:a.code!=="invalid_type"?{message:o.defaultError}:{message:c??r??o.defaultError}},description:s}}class K{get description(){return this._def.description}_getType(e){return ft(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:ft(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new De,ctx:{common:e.parent.common,data:e.data,parsedType:ft(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const r=this._parse(e);if(Pr(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){const r=this._parse(e);return Promise.resolve(r)}parse(e,r){const n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){const n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ft(e)},s=this._parseSync({data:e,path:n.path,parent:n});return _i(n,s)}"~validate"(e){const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ft(e)};if(!this["~standard"].async)try{const n=this._parseSync({data:e,path:[],parent:r});return Gt(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>Gt(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){const n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){const n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ft(e)},s=this._parse({data:e,path:n.path,parent:n}),i=await(Pr(s)?s:Promise.resolve(s));return _i(n,i)}refine(e,r){const n=s=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(s):r;return this._refinement((s,i)=>{const a=e(s),o=()=>i.addIssue({code:N.custom,...n(s)});return typeof Promise<"u"&&a instanceof Promise?a.then(c=>c?!0:(o(),!1)):a?!0:(o(),!1)})}refinement(e,r){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof r=="function"?r(n,s):r),!1))}_refinement(e){return new Nt({schema:this,typeName:B.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return ut.create(this,this._def)}nullable(){return Lt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Xe.create(this)}promise(){return Wr.create(this,this._def)}or(e){return Br.create([this,e],this._def)}and(e){return zr.create(this,e,this._def)}transform(e){return new Nt({...H(this._def),schema:this,typeName:B.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const r=typeof e=="function"?e:()=>e;return new Gr({...H(this._def),innerType:this,defaultValue:r,typeName:B.ZodDefault})}brand(){return new to({typeName:B.ZodBranded,type:this,...H(this._def)})}catch(e){const r=typeof e=="function"?e:()=>e;return new Kr({...H(this._def),innerType:this,catchValue:r,typeName:B.ZodCatch})}describe(e){const r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Es.create(this,e)}readonly(){return Zr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const hd=/^c[^\s-]{8,}$/i,fd=/^[0-9a-z]+$/,pd=/^[0-9A-HJKMNP-TV-Z]{26}$/i,md=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,gd=/^[a-z0-9_-]{21}$/i,yd=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,vd=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,bd=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,wd="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let An;const Sd=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,_d=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Ad=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Id=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,xd=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,kd=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Qa="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Ed=new RegExp(`^${Qa}$`);function Xa(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);const r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function Td(t){return new RegExp(`^${Xa(t)}$`)}function Od(t){let e=`${Qa}T${Xa(t)}`;const r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function Cd(t,e){return!!((e==="v4"||!e)&&Sd.test(t)||(e==="v6"||!e)&&Ad.test(t))}function Rd(t,e){if(!yd.test(t))return!1;try{const[r]=t.split(".");if(!r)return!1;const n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function Nd(t,e){return!!((e==="v4"||!e)&&_d.test(t)||(e==="v6"||!e)&&Id.test(t))}class at extends K{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==q.string){const i=this._getOrReturnCtx(e);return j(i,{code:N.invalid_type,expected:q.string,received:i.parsedType}),U}const n=new De;let s;for(const i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),j(s,{code:N.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),j(s,{code:N.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="length"){const a=e.data.length>i.value,o=e.data.length<i.value;(a||o)&&(s=this._getOrReturnCtx(e,s),a?j(s,{code:N.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):o&&j(s,{code:N.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),n.dirty())}else if(i.kind==="email")bd.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"email",code:N.invalid_string,message:i.message}),n.dirty());else if(i.kind==="emoji")An||(An=new RegExp(wd,"u")),An.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"emoji",code:N.invalid_string,message:i.message}),n.dirty());else if(i.kind==="uuid")md.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"uuid",code:N.invalid_string,message:i.message}),n.dirty());else if(i.kind==="nanoid")gd.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"nanoid",code:N.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid")hd.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"cuid",code:N.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid2")fd.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"cuid2",code:N.invalid_string,message:i.message}),n.dirty());else if(i.kind==="ulid")pd.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"ulid",code:N.invalid_string,message:i.message}),n.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),j(s,{validation:"url",code:N.invalid_string,message:i.message}),n.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"regex",code:N.invalid_string,message:i.message}),n.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),j(s,{code:N.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),n.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),j(s,{code:N.invalid_string,validation:{startsWith:i.value},message:i.message}),n.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),j(s,{code:N.invalid_string,validation:{endsWith:i.value},message:i.message}),n.dirty()):i.kind==="datetime"?Od(i).test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{code:N.invalid_string,validation:"datetime",message:i.message}),n.dirty()):i.kind==="date"?Ed.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{code:N.invalid_string,validation:"date",message:i.message}),n.dirty()):i.kind==="time"?Td(i).test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{code:N.invalid_string,validation:"time",message:i.message}),n.dirty()):i.kind==="duration"?vd.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"duration",code:N.invalid_string,message:i.message}),n.dirty()):i.kind==="ip"?Cd(e.data,i.version)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"ip",code:N.invalid_string,message:i.message}),n.dirty()):i.kind==="jwt"?Rd(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"jwt",code:N.invalid_string,message:i.message}),n.dirty()):i.kind==="cidr"?Nd(e.data,i.version)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"cidr",code:N.invalid_string,message:i.message}),n.dirty()):i.kind==="base64"?xd.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"base64",code:N.invalid_string,message:i.message}),n.dirty()):i.kind==="base64url"?kd.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"base64url",code:N.invalid_string,message:i.message}),n.dirty()):J.assertNever(i);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(s=>e.test(s),{validation:r,code:N.invalid_string,...P.errToObj(n)})}_addCheck(e){return new at({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...P.errToObj(e)})}url(e){return this._addCheck({kind:"url",...P.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...P.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...P.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...P.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...P.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...P.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...P.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...P.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...P.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...P.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...P.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...P.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...P.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...P.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...P.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...P.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...P.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...P.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...P.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...P.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...P.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...P.errToObj(r)})}nonempty(e){return this.min(1,P.errToObj(e))}trim(){return new at({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new at({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new at({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}}at.create=t=>new at({checks:[],typeName:B.ZodString,coerce:t?.coerce??!1,...H(t)});function Ld(t,e){const r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=r>n?r:n,i=Number.parseInt(t.toFixed(s).replace(".","")),a=Number.parseInt(e.toFixed(s).replace(".",""));return i%a/10**s}class Kt extends K{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==q.number){const i=this._getOrReturnCtx(e);return j(i,{code:N.invalid_type,expected:q.number,received:i.parsedType}),U}let n;const s=new De;for(const i of this._def.checks)i.kind==="int"?J.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),j(n,{code:N.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),j(n,{code:N.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),j(n,{code:N.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?Ld(e.data,i.value)!==0&&(n=this._getOrReturnCtx(e,n),j(n,{code:N.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),j(n,{code:N.not_finite,message:i.message}),s.dirty()):J.assertNever(i);return{status:s.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,P.toString(r))}gt(e,r){return this.setLimit("min",e,!1,P.toString(r))}lte(e,r){return this.setLimit("max",e,!0,P.toString(r))}lt(e,r){return this.setLimit("max",e,!1,P.toString(r))}setLimit(e,r,n,s){return new Kt({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:P.toString(s)}]})}_addCheck(e){return new Kt({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:P.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:P.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:P.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:P.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:P.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:P.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:P.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:P.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:P.toString(e)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&J.isInteger(e.value))}get isFinite(){let e=null,r=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}}Kt.create=t=>new Kt({checks:[],typeName:B.ZodNumber,coerce:t?.coerce||!1,...H(t)});class hr extends K{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==q.bigint)return this._getInvalidInput(e);let n;const s=new De;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),j(n,{code:N.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),j(n,{code:N.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),j(n,{code:N.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):J.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){const r=this._getOrReturnCtx(e);return j(r,{code:N.invalid_type,expected:q.bigint,received:r.parsedType}),U}gte(e,r){return this.setLimit("min",e,!0,P.toString(r))}gt(e,r){return this.setLimit("min",e,!1,P.toString(r))}lte(e,r){return this.setLimit("max",e,!0,P.toString(r))}lt(e,r){return this.setLimit("max",e,!1,P.toString(r))}setLimit(e,r,n,s){return new hr({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:P.toString(s)}]})}_addCheck(e){return new hr({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:P.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:P.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:P.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:P.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:P.toString(r)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}}hr.create=t=>new hr({checks:[],typeName:B.ZodBigInt,coerce:t?.coerce??!1,...H(t)});class Kn extends K{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==q.boolean){const n=this._getOrReturnCtx(e);return j(n,{code:N.invalid_type,expected:q.boolean,received:n.parsedType}),U}return He(e.data)}}Kn.create=t=>new Kn({typeName:B.ZodBoolean,coerce:t?.coerce||!1,...H(t)});class $r extends K{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==q.date){const i=this._getOrReturnCtx(e);return j(i,{code:N.invalid_type,expected:q.date,received:i.parsedType}),U}if(Number.isNaN(e.data.getTime())){const i=this._getOrReturnCtx(e);return j(i,{code:N.invalid_date}),U}const n=new De;let s;for(const i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),j(s,{code:N.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),n.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),j(s,{code:N.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()):J.assertNever(i);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new $r({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:P.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:P.toString(r)})}get minDate(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}}$r.create=t=>new $r({checks:[],coerce:t?.coerce||!1,typeName:B.ZodDate,...H(t)});class Ai extends K{_parse(e){if(this._getType(e)!==q.symbol){const n=this._getOrReturnCtx(e);return j(n,{code:N.invalid_type,expected:q.symbol,received:n.parsedType}),U}return He(e.data)}}Ai.create=t=>new Ai({typeName:B.ZodSymbol,...H(t)});class Zn extends K{_parse(e){if(this._getType(e)!==q.undefined){const n=this._getOrReturnCtx(e);return j(n,{code:N.invalid_type,expected:q.undefined,received:n.parsedType}),U}return He(e.data)}}Zn.create=t=>new Zn({typeName:B.ZodUndefined,...H(t)});class Ur extends K{_parse(e){if(this._getType(e)!==q.null){const n=this._getOrReturnCtx(e);return j(n,{code:N.invalid_type,expected:q.null,received:n.parsedType}),U}return He(e.data)}}Ur.create=t=>new Ur({typeName:B.ZodNull,...H(t)});class Ii extends K{constructor(){super(...arguments),this._any=!0}_parse(e){return He(e.data)}}Ii.create=t=>new Ii({typeName:B.ZodAny,...H(t)});class Jn extends K{constructor(){super(...arguments),this._unknown=!0}_parse(e){return He(e.data)}}Jn.create=t=>new Jn({typeName:B.ZodUnknown,...H(t)});class yt extends K{_parse(e){const r=this._getOrReturnCtx(e);return j(r,{code:N.invalid_type,expected:q.never,received:r.parsedType}),U}}yt.create=t=>new yt({typeName:B.ZodNever,...H(t)});class xi extends K{_parse(e){if(this._getType(e)!==q.undefined){const n=this._getOrReturnCtx(e);return j(n,{code:N.invalid_type,expected:q.void,received:n.parsedType}),U}return He(e.data)}}xi.create=t=>new xi({typeName:B.ZodVoid,...H(t)});class Xe extends K{_parse(e){const{ctx:r,status:n}=this._processInputParams(e),s=this._def;if(r.parsedType!==q.array)return j(r,{code:N.invalid_type,expected:q.array,received:r.parsedType}),U;if(s.exactLength!==null){const a=r.data.length>s.exactLength.value,o=r.data.length<s.exactLength.value;(a||o)&&(j(r,{code:a?N.too_big:N.too_small,minimum:o?s.exactLength.value:void 0,maximum:a?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&r.data.length<s.minLength.value&&(j(r,{code:N.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&r.data.length>s.maxLength.value&&(j(r,{code:N.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((a,o)=>s.type._parseAsync(new tt(r,a,r.path,o)))).then(a=>De.mergeArray(n,a));const i=[...r.data].map((a,o)=>s.type._parseSync(new tt(r,a,r.path,o)));return De.mergeArray(n,i)}get element(){return this._def.type}min(e,r){return new Xe({...this._def,minLength:{value:e,message:P.toString(r)}})}max(e,r){return new Xe({...this._def,maxLength:{value:e,message:P.toString(r)}})}length(e,r){return new Xe({...this._def,exactLength:{value:e,message:P.toString(r)}})}nonempty(e){return this.min(1,e)}}Xe.create=(t,e)=>new Xe({type:t,minLength:null,maxLength:null,exactLength:null,typeName:B.ZodArray,...H(e)});function Bt(t){if(t instanceof fe){const e={};for(const r in t.shape){const n=t.shape[r];e[r]=ut.create(Bt(n))}return new fe({...t._def,shape:()=>e})}else return t instanceof Xe?new Xe({...t._def,type:Bt(t.element)}):t instanceof ut?ut.create(Bt(t.unwrap())):t instanceof Lt?Lt.create(Bt(t.unwrap())):t instanceof Ct?Ct.create(t.items.map(e=>Bt(e))):t}class fe extends K{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),r=J.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==q.object){const u=this._getOrReturnCtx(e);return j(u,{code:N.invalid_type,expected:q.object,received:u.parsedType}),U}const{status:n,ctx:s}=this._processInputParams(e),{shape:i,keys:a}=this._getCached(),o=[];if(!(this._def.catchall instanceof yt&&this._def.unknownKeys==="strip"))for(const u in s.data)a.includes(u)||o.push(u);const c=[];for(const u of a){const f=i[u],l=s.data[u];c.push({key:{status:"valid",value:u},value:f._parse(new tt(s,l,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof yt){const u=this._def.unknownKeys;if(u==="passthrough")for(const f of o)c.push({key:{status:"valid",value:f},value:{status:"valid",value:s.data[f]}});else if(u==="strict")o.length>0&&(j(s,{code:N.unrecognized_keys,keys:o}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const u=this._def.catchall;for(const f of o){const l=s.data[f];c.push({key:{status:"valid",value:f},value:u._parse(new tt(s,l,s.path,f)),alwaysSet:f in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const u=[];for(const f of c){const l=await f.key,p=await f.value;u.push({key:l,value:p,alwaysSet:f.alwaysSet})}return u}).then(u=>De.mergeObjectSync(n,u)):De.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return P.errToObj,new fe({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{const s=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:P.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new fe({...this._def,unknownKeys:"strip"})}passthrough(){return new fe({...this._def,unknownKeys:"passthrough"})}extend(e){return new fe({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new fe({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:B.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new fe({...this._def,catchall:e})}pick(e){const r={};for(const n of J.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new fe({...this._def,shape:()=>r})}omit(e){const r={};for(const n of J.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new fe({...this._def,shape:()=>r})}deepPartial(){return Bt(this)}partial(e){const r={};for(const n of J.objectKeys(this.shape)){const s=this.shape[n];e&&!e[n]?r[n]=s:r[n]=s.optional()}return new fe({...this._def,shape:()=>r})}required(e){const r={};for(const n of J.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let i=this.shape[n];for(;i instanceof ut;)i=i._def.innerType;r[n]=i}return new fe({...this._def,shape:()=>r})}keyof(){return eo(J.objectKeys(this.shape))}}fe.create=(t,e)=>new fe({shape:()=>t,unknownKeys:"strip",catchall:yt.create(),typeName:B.ZodObject,...H(e)});fe.strictCreate=(t,e)=>new fe({shape:()=>t,unknownKeys:"strict",catchall:yt.create(),typeName:B.ZodObject,...H(e)});fe.lazycreate=(t,e)=>new fe({shape:t,unknownKeys:"strip",catchall:yt.create(),typeName:B.ZodObject,...H(e)});class Br extends K{_parse(e){const{ctx:r}=this._processInputParams(e),n=this._def.options;function s(i){for(const o of i)if(o.result.status==="valid")return o.result;for(const o of i)if(o.result.status==="dirty")return r.common.issues.push(...o.ctx.common.issues),o.result;const a=i.map(o=>new dt(o.ctx.common.issues));return j(r,{code:N.invalid_union,unionErrors:a}),U}if(r.common.async)return Promise.all(n.map(async i=>{const a={...r,common:{...r.common,issues:[]},parent:null};return{result:await i._parseAsync({data:r.data,path:r.path,parent:a}),ctx:a}})).then(s);{let i;const a=[];for(const c of n){const u={...r,common:{...r.common,issues:[]},parent:null},f=c._parseSync({data:r.data,path:r.path,parent:u});if(f.status==="valid")return f;f.status==="dirty"&&!i&&(i={result:f,ctx:u}),u.common.issues.length&&a.push(u.common.issues)}if(i)return r.common.issues.push(...i.ctx.common.issues),i.result;const o=a.map(c=>new dt(c));return j(r,{code:N.invalid_union,unionErrors:o}),U}}get options(){return this._def.options}}Br.create=(t,e)=>new Br({options:t,typeName:B.ZodUnion,...H(e)});const st=t=>t instanceof Qn?st(t.schema):t instanceof Nt?st(t.innerType()):t instanceof Hr?[t.value]:t instanceof Rt?t.options:t instanceof Xn?J.objectValues(t.enum):t instanceof Gr?st(t._def.innerType):t instanceof Zn?[void 0]:t instanceof Ur?[null]:t instanceof ut?[void 0,...st(t.unwrap())]:t instanceof Lt?[null,...st(t.unwrap())]:t instanceof to||t instanceof Zr?st(t.unwrap()):t instanceof Kr?st(t._def.innerType):[];class ks extends K{_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==q.object)return j(r,{code:N.invalid_type,expected:q.object,received:r.parsedType}),U;const n=this.discriminator,s=r.data[n],i=this.optionsMap.get(s);return i?r.common.async?i._parseAsync({data:r.data,path:r.path,parent:r}):i._parseSync({data:r.data,path:r.path,parent:r}):(j(r,{code:N.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),U)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){const s=new Map;for(const i of r){const a=st(i.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const o of a){if(s.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);s.set(o,i)}}return new ks({typeName:B.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:s,...H(n)})}}function Yn(t,e){const r=ft(t),n=ft(e);if(t===e)return{valid:!0,data:t};if(r===q.object&&n===q.object){const s=J.objectKeys(e),i=J.objectKeys(t).filter(o=>s.indexOf(o)!==-1),a={...t,...e};for(const o of i){const c=Yn(t[o],e[o]);if(!c.valid)return{valid:!1};a[o]=c.data}return{valid:!0,data:a}}else if(r===q.array&&n===q.array){if(t.length!==e.length)return{valid:!1};const s=[];for(let i=0;i<t.length;i++){const a=t[i],o=e[i],c=Yn(a,o);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return r===q.date&&n===q.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}class zr extends K{_parse(e){const{status:r,ctx:n}=this._processInputParams(e),s=(i,a)=>{if(wi(i)||wi(a))return U;const o=Yn(i.value,a.value);return o.valid?((Si(i)||Si(a))&&r.dirty(),{status:r.value,value:o.data}):(j(n,{code:N.invalid_intersection_types}),U)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([i,a])=>s(i,a)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}zr.create=(t,e,r)=>new zr({left:t,right:e,typeName:B.ZodIntersection,...H(r)});class Ct extends K{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==q.array)return j(n,{code:N.invalid_type,expected:q.array,received:n.parsedType}),U;if(n.data.length<this._def.items.length)return j(n,{code:N.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),U;!this._def.rest&&n.data.length>this._def.items.length&&(j(n,{code:N.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const i=[...n.data].map((a,o)=>{const c=this._def.items[o]||this._def.rest;return c?c._parse(new tt(n,a,n.path,o)):null}).filter(a=>!!a);return n.common.async?Promise.all(i).then(a=>De.mergeArray(r,a)):De.mergeArray(r,i)}get items(){return this._def.items}rest(e){return new Ct({...this._def,rest:e})}}Ct.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ct({items:t,typeName:B.ZodTuple,rest:null,...H(e)})};class Vr extends K{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==q.object)return j(n,{code:N.invalid_type,expected:q.object,received:n.parsedType}),U;const s=[],i=this._def.keyType,a=this._def.valueType;for(const o in n.data)s.push({key:i._parse(new tt(n,o,n.path,o)),value:a._parse(new tt(n,n.data[o],n.path,o)),alwaysSet:o in n.data});return n.common.async?De.mergeObjectAsync(r,s):De.mergeObjectSync(r,s)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof K?new Vr({keyType:e,valueType:r,typeName:B.ZodRecord,...H(n)}):new Vr({keyType:at.create(),valueType:e,typeName:B.ZodRecord,...H(r)})}}class ki extends K{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==q.map)return j(n,{code:N.invalid_type,expected:q.map,received:n.parsedType}),U;const s=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([o,c],u)=>({key:s._parse(new tt(n,o,n.path,[u,"key"])),value:i._parse(new tt(n,c,n.path,[u,"value"]))}));if(n.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const c of a){const u=await c.key,f=await c.value;if(u.status==="aborted"||f.status==="aborted")return U;(u.status==="dirty"||f.status==="dirty")&&r.dirty(),o.set(u.value,f.value)}return{status:r.value,value:o}})}else{const o=new Map;for(const c of a){const u=c.key,f=c.value;if(u.status==="aborted"||f.status==="aborted")return U;(u.status==="dirty"||f.status==="dirty")&&r.dirty(),o.set(u.value,f.value)}return{status:r.value,value:o}}}}ki.create=(t,e,r)=>new ki({valueType:e,keyType:t,typeName:B.ZodMap,...H(r)});class fr extends K{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==q.set)return j(n,{code:N.invalid_type,expected:q.set,received:n.parsedType}),U;const s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(j(n,{code:N.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),r.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(j(n,{code:N.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),r.dirty());const i=this._def.valueType;function a(c){const u=new Set;for(const f of c){if(f.status==="aborted")return U;f.status==="dirty"&&r.dirty(),u.add(f.value)}return{status:r.value,value:u}}const o=[...n.data.values()].map((c,u)=>i._parse(new tt(n,c,n.path,u)));return n.common.async?Promise.all(o).then(c=>a(c)):a(o)}min(e,r){return new fr({...this._def,minSize:{value:e,message:P.toString(r)}})}max(e,r){return new fr({...this._def,maxSize:{value:e,message:P.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}}fr.create=(t,e)=>new fr({valueType:t,minSize:null,maxSize:null,typeName:B.ZodSet,...H(e)});class Qn extends K{get schema(){return this._def.getter()}_parse(e){const{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}}Qn.create=(t,e)=>new Qn({getter:t,typeName:B.ZodLazy,...H(e)});class Hr extends K{_parse(e){if(e.data!==this._def.value){const r=this._getOrReturnCtx(e);return j(r,{received:r.data,code:N.invalid_literal,expected:this._def.value}),U}return{status:"valid",value:e.data}}get value(){return this._def.value}}Hr.create=(t,e)=>new Hr({value:t,typeName:B.ZodLiteral,...H(e)});function eo(t,e){return new Rt({values:t,typeName:B.ZodEnum,...H(e)})}class Rt extends K{_parse(e){if(typeof e.data!="string"){const r=this._getOrReturnCtx(e),n=this._def.values;return j(r,{expected:J.joinValues(n),received:r.parsedType,code:N.invalid_type}),U}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const r=this._getOrReturnCtx(e),n=this._def.values;return j(r,{received:r.data,code:N.invalid_enum_value,options:n}),U}return He(e.data)}get options(){return this._def.values}get enum(){const e={};for(const r of this._def.values)e[r]=r;return e}get Values(){const e={};for(const r of this._def.values)e[r]=r;return e}get Enum(){const e={};for(const r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return Rt.create(e,{...this._def,...r})}exclude(e,r=this._def){return Rt.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}}Rt.create=eo;class Xn extends K{_parse(e){const r=J.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==q.string&&n.parsedType!==q.number){const s=J.objectValues(r);return j(n,{expected:J.joinValues(s),received:n.parsedType,code:N.invalid_type}),U}if(this._cache||(this._cache=new Set(J.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const s=J.objectValues(r);return j(n,{received:n.data,code:N.invalid_enum_value,options:s}),U}return He(e.data)}get enum(){return this._def.values}}Xn.create=(t,e)=>new Xn({values:t,typeName:B.ZodNativeEnum,...H(e)});class Wr extends K{unwrap(){return this._def.type}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==q.promise&&r.common.async===!1)return j(r,{code:N.invalid_type,expected:q.promise,received:r.parsedType}),U;const n=r.parsedType===q.promise?r.data:Promise.resolve(r.data);return He(n.then(s=>this._def.type.parseAsync(s,{path:r.path,errorMap:r.common.contextualErrorMap})))}}Wr.create=(t,e)=>new Wr({type:t,typeName:B.ZodPromise,...H(e)});class Nt extends K{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===B.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:r,ctx:n}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:a=>{j(n,a),a.fatal?r.abort():r.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){const a=s.transform(n.data,i);if(n.common.async)return Promise.resolve(a).then(async o=>{if(r.value==="aborted")return U;const c=await this._def.schema._parseAsync({data:o,path:n.path,parent:n});return c.status==="aborted"?U:c.status==="dirty"||r.value==="dirty"?ar(c.value):c});{if(r.value==="aborted")return U;const o=this._def.schema._parseSync({data:a,path:n.path,parent:n});return o.status==="aborted"?U:o.status==="dirty"||r.value==="dirty"?ar(o.value):o}}if(s.type==="refinement"){const a=o=>{const c=s.refinement(o,i);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(n.common.async===!1){const o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?U:(o.status==="dirty"&&r.dirty(),a(o.value),{status:r.value,value:o.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>o.status==="aborted"?U:(o.status==="dirty"&&r.dirty(),a(o.value).then(()=>({status:r.value,value:o.value}))))}if(s.type==="transform")if(n.common.async===!1){const a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Gt(a))return U;const o=s.transform(a.value,i);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:o}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>Gt(a)?Promise.resolve(s.transform(a.value,i)).then(o=>({status:r.value,value:o})):U);J.assertNever(s)}}Nt.create=(t,e,r)=>new Nt({schema:t,typeName:B.ZodEffects,effect:e,...H(r)});Nt.createWithPreprocess=(t,e,r)=>new Nt({schema:e,effect:{type:"preprocess",transform:t},typeName:B.ZodEffects,...H(r)});class ut extends K{_parse(e){return this._getType(e)===q.undefined?He(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ut.create=(t,e)=>new ut({innerType:t,typeName:B.ZodOptional,...H(e)});class Lt extends K{_parse(e){return this._getType(e)===q.null?He(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Lt.create=(t,e)=>new Lt({innerType:t,typeName:B.ZodNullable,...H(e)});class Gr extends K{_parse(e){const{ctx:r}=this._processInputParams(e);let n=r.data;return r.parsedType===q.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}}Gr.create=(t,e)=>new Gr({innerType:t,typeName:B.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...H(e)});class Kr extends K{_parse(e){const{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Pr(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new dt(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new dt(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}Kr.create=(t,e)=>new Kr({innerType:t,typeName:B.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...H(e)});class Ei extends K{_parse(e){if(this._getType(e)!==q.nan){const n=this._getOrReturnCtx(e);return j(n,{code:N.invalid_type,expected:q.nan,received:n.parsedType}),U}return{status:"valid",value:e.data}}}Ei.create=t=>new Ei({typeName:B.ZodNaN,...H(t)});class to extends K{_parse(e){const{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}}class Es extends K{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?U:i.status==="dirty"?(r.dirty(),ar(i.value)):this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();{const s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?U:s.status==="dirty"?(r.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,r){return new Es({in:e,out:r,typeName:B.ZodPipeline})}}class Zr extends K{_parse(e){const r=this._def.innerType._parse(e),n=s=>(Gt(s)&&(s.value=Object.freeze(s.value)),s);return Pr(r)?r.then(s=>n(s)):n(r)}unwrap(){return this._def.innerType}}Zr.create=(t,e)=>new Zr({innerType:t,typeName:B.ZodReadonly,...H(e)});var B;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(B||(B={}));const Et=at.create,Ti=Kt.create,Ts=Kn.create,Md=Ur.create,pr=Jn.create;yt.create;const Dd=Xe.create,ot=fe.create,Os=Br.create,Fd=ks.create;zr.create;Ct.create;const mr=Vr.create,Sr=Hr.create,Jr=Rt.create;Wr.create;ut.create;Lt.create;const jd=["get","list","create","update","delete"],qd=ot({uid:Et(),token:mr(pr()).optional()}),Pd=ot({function:Jr(["get","exists"]).describe("Firestore function to mock"),path:Et().describe('Document path, e.g. "users/alice"'),result:Os([mr(pr()),Ts()]).describe("Document data for get, boolean for exists")}),$d=Fd("kind",[ot({kind:Sr("create")}),ot({kind:Sr("set"),merge:Ts()}),ot({kind:Sr("update")}),ot({kind:Sr("delete")})]),Ud=ot({limit:Ti().optional(),offset:Ti().optional(),orderBy:Et().optional()});ot({description:Et().describe("Human-readable description of what this test verifies"),expectation:Jr(["ALLOW","DENY"]).describe("Expected outcome"),method:Jr(jd).describe("Firestore method to test"),path:Et().describe('Document path, e.g. "users/alice"'),auth:Os([qd,Md()]).optional().describe("Auth context; null or omitted for unauthenticated"),data:mr(pr()).optional().describe("request.resource.data for write operations"),resource:mr(pr()).optional().describe("Existing document data (resource.data)"),functionMocks:Dd(Pd).optional().describe("Mock get()/exists() calls in rules"),query:Ud.optional().describe("request.query payload (list ops only): limit/offset/orderBy."),requestTime:Et().optional().describe("Override for request.time (ISO-8601). Defaults to wallclock."),writeMode:$d.optional().describe("Optional write-mode override; controls update merge semantics and getAfter() projection.")});function Mt(t){if(t.decision==="UNSUPPORTED")return;const r=t.decision==="ALLOW";let n="deny",s;if(r)n="allow",s=t.trace.find(C=>C.verdict==="ALLOW");else if(n="deny",s=t.trace.find(k=>k.verdict==="DENY"?!0:k.verdict==="ERROR"),s===void 0){const k=t.trace.length;k>0&&(s=t.trace[k-1])}if(s===void 0)return;const a={verdict:n};s.line!==void 0&&(a.line=s.line),s.col!==void 0&&(a.col=s.col,a.column=s.col),s.column!==void 0&&(a.col=s.column,a.column=s.column),s.file!==void 0&&(a.file=s.file),s.citation!==void 0&&(a.citation=s.citation),s.conditionText!==void 0&&(a.expression=s.conditionText),s.expressionTrace!==void 0&&(a.expressionTrace=s.expressionTrace);const v=a.line!==void 0,w=a.expression!==void 0,R=a.expressionTrace!==void 0;if(v||w||R)return a}function be(t){const e=[];for(const r of t.notes)e.push(r);for(const r of t.trace){const n=r.operations.join(","),s=`Rule #${r.ruleIndex} (${n})`;r.verdict==="ALLOW"?e.push(`${s} → ALLOW`):r.verdict==="DENY"?e.push(`${s} → deny`):r.verdict==="UNSUPPORTED"?e.push(`${s} → unsupported: ${r.message??""}`):e.push(`${s} → error: ${r.message??""}`)}return e.push(`Simulated: ${t.decision}`),e}ot({function:Jr(["get","exists"]).describe("Cross-service Firestore function to mock"),path:Et().describe('Firestore document path in collection/doc form, e.g. "users/alice"'),result:Os([mr(pr()),Ts()]).describe("Document fields for get, boolean for exists")});const Bd={atomic:`// @pyric-services cloud.firestore
|
|
495
|
+
*/var fi;function _l(){return fi||(fi=1,(function(t){(function(){var e="input is invalid type",r=typeof window=="object",n=r?window:{};n.JS_SHA256_NO_WINDOW&&(r=!1);var s=!r&&typeof self=="object",i=!n.JS_SHA256_NO_NODE_JS&&typeof process=="object"&&process.versions&&process.versions.node&&process.type!="renderer";i?n=oa:s&&(n=self);var a=!n.JS_SHA256_NO_COMMON_JS&&!0&&t.exports,o=!n.JS_SHA256_NO_ARRAY_BUFFER&&typeof ArrayBuffer<"u",c="0123456789abcdef".split(""),u=[-2147483648,8388608,32768,128],f=[24,16,8,0],l=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],p=["hex","array","digest","arrayBuffer"],y=[];(n.JS_SHA256_NO_NODE_JS||!Array.isArray)&&(Array.isArray=function(S){return Object.prototype.toString.call(S)==="[object Array]"}),o&&(n.JS_SHA256_NO_ARRAY_BUFFER_IS_VIEW||!ArrayBuffer.isView)&&(ArrayBuffer.isView=function(S){return typeof S=="object"&&S.buffer&&S.buffer.constructor===ArrayBuffer});var v=function(S,T){return function(_){return new x(T,!0).update(_)[S]()}},b=function(S){var T=v("hex",S);i&&(T=R(T,S)),T.create=function(){return new x(S)},T.update=function(A){return T.create().update(A)};for(var _=0;_<p.length;++_){var w=p[_];T[w]=v(w,S)}return T},R=function(S,T){var _=Dr,w=Dr.Buffer,A=T?"sha224":"sha256",I;w.from&&!n.JS_SHA256_NO_BUFFER_FROM?I=w.from:I=function(d){return new w(d)};var h=function(d){if(typeof d=="string")return _.createHash(A).update(d,"utf8").digest("hex");if(d==null)throw new Error(e);return d.constructor===ArrayBuffer&&(d=new Uint8Array(d)),Array.isArray(d)||ArrayBuffer.isView(d)||d.constructor===w?_.createHash(A).update(I(d)).digest("hex"):S(d)};return h},C=function(S,T){return function(_,w){return new L(_,T,!0).update(w)[S]()}},k=function(S){var T=C("hex",S);T.create=function(A){return new L(A,S)},T.update=function(A,I){return T.create(A).update(I)};for(var _=0;_<p.length;++_){var w=p[_];T[w]=C(w,S)}return T};function x(S,T){T?(y[0]=y[16]=y[1]=y[2]=y[3]=y[4]=y[5]=y[6]=y[7]=y[8]=y[9]=y[10]=y[11]=y[12]=y[13]=y[14]=y[15]=0,this.blocks=y):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],S?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=S}x.prototype.update=function(S){if(!this.finalized){var T,_=typeof S;if(_!=="string"){if(_==="object"){if(S===null)throw new Error(e);if(o&&S.constructor===ArrayBuffer)S=new Uint8Array(S);else if(!Array.isArray(S)&&(!o||!ArrayBuffer.isView(S)))throw new Error(e)}else throw new Error(e);T=!0}for(var w,A=0,I,h=S.length,d=this.blocks;A<h;){if(this.hashed&&(this.hashed=!1,d[0]=this.block,this.block=d[16]=d[1]=d[2]=d[3]=d[4]=d[5]=d[6]=d[7]=d[8]=d[9]=d[10]=d[11]=d[12]=d[13]=d[14]=d[15]=0),T)for(I=this.start;A<h&&I<64;++A)d[I>>>2]|=S[A]<<f[I++&3];else for(I=this.start;A<h&&I<64;++A)w=S.charCodeAt(A),w<128?d[I>>>2]|=w<<f[I++&3]:w<2048?(d[I>>>2]|=(192|w>>>6)<<f[I++&3],d[I>>>2]|=(128|w&63)<<f[I++&3]):w<55296||w>=57344?(d[I>>>2]|=(224|w>>>12)<<f[I++&3],d[I>>>2]|=(128|w>>>6&63)<<f[I++&3],d[I>>>2]|=(128|w&63)<<f[I++&3]):(w=65536+((w&1023)<<10|S.charCodeAt(++A)&1023),d[I>>>2]|=(240|w>>>18)<<f[I++&3],d[I>>>2]|=(128|w>>>12&63)<<f[I++&3],d[I>>>2]|=(128|w>>>6&63)<<f[I++&3],d[I>>>2]|=(128|w&63)<<f[I++&3]);this.lastByteIndex=I,this.bytes+=I-this.start,I>=64?(this.block=d[16],this.start=I-64,this.hash(),this.hashed=!0):this.start=I}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}},x.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var S=this.blocks,T=this.lastByteIndex;S[16]=this.block,S[T>>>2]|=u[T&3],this.block=S[16],T>=56&&(this.hashed||this.hash(),S[0]=this.block,S[16]=S[1]=S[2]=S[3]=S[4]=S[5]=S[6]=S[7]=S[8]=S[9]=S[10]=S[11]=S[12]=S[13]=S[14]=S[15]=0),S[14]=this.hBytes<<3|this.bytes>>>29,S[15]=this.bytes<<3,this.hash()}},x.prototype.hash=function(){var S=this.h0,T=this.h1,_=this.h2,w=this.h3,A=this.h4,I=this.h5,h=this.h6,d=this.h7,g=this.blocks,m,F,E,O,D,Y,Ee,ze,Pt,$t,Ut;for(m=16;m<64;++m)D=g[m-15],F=(D>>>7|D<<25)^(D>>>18|D<<14)^D>>>3,D=g[m-2],E=(D>>>17|D<<15)^(D>>>19|D<<13)^D>>>10,g[m]=g[m-16]+F+g[m-7]+E<<0;for(Ut=T&_,m=0;m<64;m+=4)this.first?(this.is224?(ze=300032,D=g[0]-1413257819,d=D-150054599<<0,w=D+24177077<<0):(ze=704751109,D=g[0]-210244248,d=D-1521486534<<0,w=D+143694565<<0),this.first=!1):(F=(S>>>2|S<<30)^(S>>>13|S<<19)^(S>>>22|S<<10),E=(A>>>6|A<<26)^(A>>>11|A<<21)^(A>>>25|A<<7),ze=S&T,O=ze^S&_^Ut,Ee=A&I^~A&h,D=d+E+Ee+l[m]+g[m],Y=F+O,d=w+D<<0,w=D+Y<<0),F=(w>>>2|w<<30)^(w>>>13|w<<19)^(w>>>22|w<<10),E=(d>>>6|d<<26)^(d>>>11|d<<21)^(d>>>25|d<<7),Pt=w&S,O=Pt^w&T^ze,Ee=d&A^~d&I,D=h+E+Ee+l[m+1]+g[m+1],Y=F+O,h=_+D<<0,_=D+Y<<0,F=(_>>>2|_<<30)^(_>>>13|_<<19)^(_>>>22|_<<10),E=(h>>>6|h<<26)^(h>>>11|h<<21)^(h>>>25|h<<7),$t=_&w,O=$t^_&S^Pt,Ee=h&d^~h&A,D=I+E+Ee+l[m+2]+g[m+2],Y=F+O,I=T+D<<0,T=D+Y<<0,F=(T>>>2|T<<30)^(T>>>13|T<<19)^(T>>>22|T<<10),E=(I>>>6|I<<26)^(I>>>11|I<<21)^(I>>>25|I<<7),Ut=T&_,O=Ut^T&w^$t,Ee=I&h^~I&d,D=A+E+Ee+l[m+3]+g[m+3],Y=F+O,A=S+D<<0,S=D+Y<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+S<<0,this.h1=this.h1+T<<0,this.h2=this.h2+_<<0,this.h3=this.h3+w<<0,this.h4=this.h4+A<<0,this.h5=this.h5+I<<0,this.h6=this.h6+h<<0,this.h7=this.h7+d<<0},x.prototype.hex=function(){this.finalize();var S=this.h0,T=this.h1,_=this.h2,w=this.h3,A=this.h4,I=this.h5,h=this.h6,d=this.h7,g=c[S>>>28&15]+c[S>>>24&15]+c[S>>>20&15]+c[S>>>16&15]+c[S>>>12&15]+c[S>>>8&15]+c[S>>>4&15]+c[S&15]+c[T>>>28&15]+c[T>>>24&15]+c[T>>>20&15]+c[T>>>16&15]+c[T>>>12&15]+c[T>>>8&15]+c[T>>>4&15]+c[T&15]+c[_>>>28&15]+c[_>>>24&15]+c[_>>>20&15]+c[_>>>16&15]+c[_>>>12&15]+c[_>>>8&15]+c[_>>>4&15]+c[_&15]+c[w>>>28&15]+c[w>>>24&15]+c[w>>>20&15]+c[w>>>16&15]+c[w>>>12&15]+c[w>>>8&15]+c[w>>>4&15]+c[w&15]+c[A>>>28&15]+c[A>>>24&15]+c[A>>>20&15]+c[A>>>16&15]+c[A>>>12&15]+c[A>>>8&15]+c[A>>>4&15]+c[A&15]+c[I>>>28&15]+c[I>>>24&15]+c[I>>>20&15]+c[I>>>16&15]+c[I>>>12&15]+c[I>>>8&15]+c[I>>>4&15]+c[I&15]+c[h>>>28&15]+c[h>>>24&15]+c[h>>>20&15]+c[h>>>16&15]+c[h>>>12&15]+c[h>>>8&15]+c[h>>>4&15]+c[h&15];return this.is224||(g+=c[d>>>28&15]+c[d>>>24&15]+c[d>>>20&15]+c[d>>>16&15]+c[d>>>12&15]+c[d>>>8&15]+c[d>>>4&15]+c[d&15]),g},x.prototype.toString=x.prototype.hex,x.prototype.digest=function(){this.finalize();var S=this.h0,T=this.h1,_=this.h2,w=this.h3,A=this.h4,I=this.h5,h=this.h6,d=this.h7,g=[S>>>24&255,S>>>16&255,S>>>8&255,S&255,T>>>24&255,T>>>16&255,T>>>8&255,T&255,_>>>24&255,_>>>16&255,_>>>8&255,_&255,w>>>24&255,w>>>16&255,w>>>8&255,w&255,A>>>24&255,A>>>16&255,A>>>8&255,A&255,I>>>24&255,I>>>16&255,I>>>8&255,I&255,h>>>24&255,h>>>16&255,h>>>8&255,h&255];return this.is224||g.push(d>>>24&255,d>>>16&255,d>>>8&255,d&255),g},x.prototype.array=x.prototype.digest,x.prototype.arrayBuffer=function(){this.finalize();var S=new ArrayBuffer(this.is224?28:32),T=new DataView(S);return T.setUint32(0,this.h0),T.setUint32(4,this.h1),T.setUint32(8,this.h2),T.setUint32(12,this.h3),T.setUint32(16,this.h4),T.setUint32(20,this.h5),T.setUint32(24,this.h6),this.is224||T.setUint32(28,this.h7),S};function L(S,T,_){var w,A=typeof S;if(A==="string"){var I=[],h=S.length,d=0,g;for(w=0;w<h;++w)g=S.charCodeAt(w),g<128?I[d++]=g:g<2048?(I[d++]=192|g>>>6,I[d++]=128|g&63):g<55296||g>=57344?(I[d++]=224|g>>>12,I[d++]=128|g>>>6&63,I[d++]=128|g&63):(g=65536+((g&1023)<<10|S.charCodeAt(++w)&1023),I[d++]=240|g>>>18,I[d++]=128|g>>>12&63,I[d++]=128|g>>>6&63,I[d++]=128|g&63);S=I}else if(A==="object"){if(S===null)throw new Error(e);if(o&&S.constructor===ArrayBuffer)S=new Uint8Array(S);else if(!Array.isArray(S)&&(!o||!ArrayBuffer.isView(S)))throw new Error(e)}else throw new Error(e);S.length>64&&(S=new x(T,!0).update(S).array());var m=[],F=[];for(w=0;w<64;++w){var E=S[w]||0;m[w]=92^E,F[w]=54^E}x.call(this,T,_),this.update(F),this.oKeyPad=m,this.inner=!0,this.sharedMemory=_}L.prototype=new x,L.prototype.finalize=function(){if(x.prototype.finalize.call(this),this.inner){this.inner=!1;var S=this.array();x.call(this,this.is224,this.sharedMemory),this.update(this.oKeyPad),this.update(S),x.prototype.finalize.call(this)}};var $=b();$.sha256=$,$.sha224=b(!0),$.sha256.hmac=k(),$.sha224.hmac=k(!0),a?t.exports=$:(n.sha256=$.sha256,n.sha224=$.sha224)})()})(Sn)),Sn.exports}var Al=_l();function Il(t){if(t instanceof Ae)return t;if(typeof t=="string")return Ae.fromUtf8(t);throw new G(`hashing.* requires Bytes or String, got ${typeof t}`)}function xl(t,e){const r=Il(e[0]);switch(t){case"md5":return new Ae(new Uint8Array(Sl.md5.arrayBuffer(r.data)));case"sha256":return new Ae(new Uint8Array(Al.sha256.arrayBuffer(r.data)));case"crc32":{const n=El(r.data);return new Ae(pi(n))}case"crc32c":{const n=Ol(r.data);return new Ae(pi(n))}}throw new gt(`Unknown hashing method '${t}'`)}function pi(t){return new Uint8Array([t&255,t>>>8&255,t>>>16&255,t>>>24&255])}const kl=(()=>{const t=new Uint32Array(256);for(let e=0;e<256;e++){let r=e;for(let n=0;n<8;n++)r=r&1?3988292384^r>>>1:r>>>1;t[e]=r>>>0}return t})();function El(t){let e=4294967295;for(let r=0;r<t.length;r++)e=kl[(e^t[r])&255]^e>>>8;return(e^4294967295)>>>0}const Tl=(()=>{const t=new Uint32Array(256);for(let e=0;e<256;e++){let r=e;for(let n=0;n<8;n++)r=r&1?2197175160^r>>>1:r>>>1;t[e]=r>>>0}return t})();function Ol(t){let e=4294967295;for(let r=0;r<t.length;r++)e=Tl[(e^t[r])&255]^e>>>8;return(e^4294967295)>>>0}function Cl(t){if(typeof t=="number")return Math.trunc(t);if(t instanceof ae)return Math.trunc(t.value);if(typeof t=="boolean")return t?1:0;if(typeof t=="string"){if(/^[+-]?\d+$/.test(t.trim()))return parseInt(t.trim(),10);throw new G(`int() cannot convert string '${t}' to an integer`)}throw new G(`int() cannot convert ${typeof t} to an integer`)}function Rl(t){if(t instanceof ae)return t;if(typeof t=="number")return new ae(t);if(typeof t=="string"){const e=t.trim();if(/^[+-]?(\d+\.?\d*|\.\d+)$/.test(e))return new ae(parseFloat(e));throw new G(`float() cannot convert string '${t}' to a float`)}throw new G(`float() cannot convert ${typeof t} to a float`)}function Nl(t,e,r,n){switch(t){case"get":{const a=String(W(e[0],r,n));return li(a,r)}case"exists":{const a=String(W(e[0],r,n));return di(a,r)}case"getAfter":{const a=W(e[0],r,n),o=String(a);if(o===r.afterStatePath.toString()){if(r.afterState===null)throw new G(`getAfter() of non-existent document '${o}' (guard with existsAfter() first)`);return Wn(ur(o),r.afterState)}const c=ur(o);if(r.batchProjection?.has(c)){const u=r.batchProjection.get(c);if(u===null)throw new G(`getAfter() of non-existent document '${o}' (guard with existsAfter() first)`);return Wn(c,u)}return li(o,r)}case"existsAfter":{const a=W(e[0],r,n),o=String(a);if(o===r.afterStatePath.toString())return r.existsAfter;const c=ur(o);return r.batchProjection?.has(c)?r.batchProjection.get(c)!==null:di(o,r)}case"debug":return W(e[0],r,n);case"string":return String(W(e[0],r,n));case"int":return Cl(W(e[0],r,n));case"float":return Rl(W(e[0],r,n));case"path":{const a=W(e[0],r,n);if(typeof a=="string")return Qe.fromString(a);throw new G(`path() requires a string argument, got ${typeof a}`)}}const s=r.functions.get(t);if(!s)throw new G(`Unknown function: ${t}`);const i={...n};for(let a=0;a<s.parameters.length;a++)i[s.parameters[a]]=W(e[a],r,n);r.trace?.enterFrame(t);try{for(const a of s.lets){const o=r.trace?r.trace.entries.length:-1;i[a.name]=W(a.value,r,i),o>=0&&r.trace?.markEntryAsLetBinding(o,a.name)}return W(s.body,r,i)}finally{r.trace?.exitFrame()}}function Ll(t,e,r,n,s){if(t.type==="identifier"){const o=t.name;if(mi(o)&&!(o in s)&&!(o in n.pathVariables)){const c=r.map(u=>W(u,n,s));return Dl(o,e,c)}if(!mi(o)&&!(o in s)&&!(o in n.pathVariables)&&!Bl(o))throw new gt(`Unknown namespace or method '${o}.${e}()'`)}const i=W(t,n,s),a=r.map(o=>W(o,n,s));if(i instanceof te){const o=i.callMethod(e,a);if(o===oe)throw new gt(`Unknown method '${e}' on ${i.typeName}`);return o}if(e==="diff"&&typeof i=="object"&&i!==null&&!Array.isArray(i)){const o=a[0];if(typeof o=="object"&&o!==null)return new cr(o,i);throw new G("diff() requires a map argument")}if(typeof i=="function")return i(...a);if(i instanceof de)switch(e){case"hasOnly":return i.hasOnly(a[0]);case"hasAll":return i.hasAll(a[0]);case"hasAny":return i.hasAny(a[0]);case"size":return i.size();case"difference":case"union":case"intersection":{const o=a[0];if(!(o instanceof de))throw new G(`Unsupported operation: set.${e} requires a Set argument`);return i[e](o)}}if(i instanceof cr)switch(e){case"addedKeys":return i.addedKeys();case"removedKeys":return i.removedKeys();case"changedKeys":return i.changedKeys();case"affectedKeys":return i.affectedKeys();case"unchangedKeys":return i.unchangedKeys()}if(typeof i=="object"&&i!==null&&!Array.isArray(i)){const o=i;switch(e){case"keys":return Object.keys(o);case"values":return Object.values(o);case"size":return Object.keys(o).length;case"diff":{const c=a[0];return new cr(c,o)}case"get":{const c=a[0],u=a[1];if(Array.isArray(c)){let l=o;for(const p of c){if(l==null||typeof l!="object"||Array.isArray(l)||l instanceof te)return u;const y=String(p);if(!Object.hasOwn(l,y))return u;l=l[y]}return l}const f=String(c);return Object.hasOwn(o,f)?o[f]:u}}}if(Array.isArray(i))switch(e){case"size":return i.length;case"hasAll":return a[0].every(o=>i.some(c=>me(c,o)));case"hasAny":return a[0].some(o=>i.some(c=>me(c,o)));case"hasOnly":{const o=a[0];return i.every(c=>o.some(u=>me(u,c)))}case"join":return i.join(String(a[0]??","));case"concat":{const o=a[0];if(!Array.isArray(o))throw new G(`List.concat requires a list argument, got ${typeof o}`);return[...i,...o]}case"removeAll":{const o=a[0];if(!Array.isArray(o))throw new G(`List.removeAll requires a list argument, got ${typeof o}`);return i.filter(c=>!o.some(u=>me(c,u)))}case"toSet":return new de(i);case"difference":case"union":case"intersection":throw new G(`Function not found on List receiver: ${e}`)}if(typeof i=="string")switch(e){case"size":return i.length;case"lower":return i.toLowerCase();case"upper":return i.toUpperCase();case"trim":return i.trim();case"split":return i.split(_n(String(a[0]),"g"));case"matches":return _n(`^(?:${String(a[0])})$`).test(i);case"replace":return i.replace(_n(String(a[0]),"g"),String(a[1]));case"toUtf8":return Ae.fromUtf8(i)}throw new G(`Unknown method '${e}' on ${typeof i}`)}function _n(t,e=""){try{return new RegExp(t,e)}catch(r){throw new G(`Invalid regex '${t}': ${r.message}`)}}const Ml=new Set(["math","timestamp","duration","latlng","hashing"]);function mi(t){return Ml.has(t)}function Dl(t,e,r){const n=t==="hashing"?r:r.map(Fl);switch(t){case"math":return ql(e,n);case"timestamp":return Pl(e,n);case"duration":return $l(e,n);case"latlng":return jl(e,n);case"hashing":return xl(e,r)}throw new gt(`Unknown namespace '${t}'`)}function Fl(t){return t instanceof ae?t.value:t}function jl(t,e){switch(t){case"value":{const[r,n]=e;return new lt(r,n)}}throw new gt(`Unknown latlng method '${t}'`)}function ql(t,e){switch(t){case"abs":return Math.abs(e[0]);case"ceil":return Math.ceil(e[0]);case"floor":return Math.floor(e[0]);case"round":return Math.round(e[0]);case"sqrt":return Math.sqrt(e[0]);case"pow":return Math.pow(e[0],e[1]);case"isNaN":return Number.isNaN(e[0])}throw new G(`Unknown math method '${t}'`)}function Pl(t,e){switch(t){case"date":{const[r,n,s]=e;return _e.fromYMD(r,n,s)}case"value":return _e.fromMillis(e[0])}throw new gt(`Unknown timestamp method '${t}'`)}function $l(t,e){switch(t){case"value":try{return ve.fromValue(e[0],e[1])}catch(r){throw new G(r.message)}case"time":{const[r,n,s,i]=e;return ve.fromTime(r,n,s,i)}case"abs":{const r=e[0];if(!(r instanceof ve))throw new G(`duration.abs() requires a Duration argument, got ${typeof r}`);return ve.abs(r)}}throw new gt(`Unknown duration method '${t}'`)}function W(t,e,r={}){return e.trace?e.trace.capture(t,()=>gi(t,e,r)):gi(t,e,r)}function gi(t,e,r){switch(t.type){case"literal":return typeof t.value=="number"&&t.raw.includes(".")?new ae(t.value):t.value;case"identifier":return Ul(t.name,e,r);case"binaryOp":return zl(t.op,t.left,t.right,e,r);case"unaryOp":{if(t.op==="!")return!W(t.operand,e,r);if(t.op==="-"){const n=W(t.operand,e,r);return n instanceof ae?new ae(-n.value):-n}throw new G(`Unknown unary op: ${t.op}`,t)}case"ternary":{const n=ir(W(t.condition,e,r),t.condition);return W(n?t.consequent:t.alternate,e,r)}case"memberAccess":{const n=W(t.object,e,r);if(n==null)throw new G(`Property '${t.property}' accessed on ${n===null?"null":"undefined"} value`,t);if(n instanceof te)return n.field(t.property);if(n instanceof cr)switch(t.property){case"addedKeys":return()=>n.addedKeys();case"removedKeys":return()=>n.removedKeys();case"changedKeys":return()=>n.changedKeys();case"affectedKeys":return()=>n.affectedKeys();case"unchangedKeys":return()=>n.unchangedKeys()}if(n instanceof de)switch(t.property){case"size":return()=>n.size()}if(Object.hasOwn(n,t.property))return n[t.property];throw new G(`No field '${t.property}' on map (use 'in' or .get() to read a possibly-absent field)`,t)}case"bracketAccess":{const n=W(t.object,e,r),s=W(t.index,e,r);if(n==null)throw new G(`Index access on ${n===null?"null":"undefined"} value`,t);if(n instanceof te)return n.field(String(s));const i=String(s);return Object.hasOwn(n,i)?n[i]:null}case"sliceAccess":{const n=W(t.object,e,r),s=W(t.start,e,r),i=W(t.end,e,r);if(n==null)return null;if(typeof s!="number"||!Number.isInteger(s))throw new G(`Slice start must be an integer, got ${typeof s}`);if(typeof i!="number"||!Number.isInteger(i))throw new G(`Slice end must be an integer, got ${typeof i}`);if(s<0||i<0)throw new G(`Slice indices must be non-negative, got [${s}:${i}]`);if(typeof n=="string"||Array.isArray(n)){if(i>n.length)throw new G(`Slice end ${i} exceeds length ${n.length}`);return n.slice(s,i)}throw new G(`Slice not supported on ${typeof n}`)}case"inExpr":{const n=W(t.element,e,r),s=W(t.collection,e,r);return s==null?!1:Array.isArray(s)?s.some(i=>me(i,n)):typeof s=="object"?Object.hasOwn(s,String(n)):!1}case"isExpr":{const n=W(t.value,e,r);switch(t.typeName){case"string":return typeof n=="string";case"int":return n instanceof te?!1:typeof n=="number";case"float":return n instanceof ae;case"number":return n instanceof ae?!0:n instanceof te?!1:typeof n=="number";case"bool":return typeof n=="boolean";case"null":return n===null;case"list":return Array.isArray(n);case"map":return n instanceof te||n instanceof cr||n instanceof de?!1:typeof n=="object"&&n!==null&&!Array.isArray(n);default:return n instanceof te?n.typeName===t.typeName:!1}}case"listLiteral":return t.elements.map(n=>W(n,e,r));case"mapLiteral":{const n={};for(const s of t.entries){const i=String(W(s.key,e,r));n[i]=W(s.value,e,r)}return n}case"functionCall":return Nl(t.name,t.args,e,r);case"methodCall":return Ll(t.object,t.method,t.args,e,r);case"pathLiteral":{const n=[];for(const s of t.segments)typeof s=="string"?n.push(s):n.push(String(W(s,e,r)));return new Qe(n)}default:throw new G(`Unknown expression type: ${t.type}`,t)}}function Ul(t,e,r){if(t in r)return r[t];if(t in e.pathVariables)return e.pathVariables[t];switch(t){case"request":return e.request;case"resource":if(e.resource===null)throw new G("Null value error.");return e.resource;case"true":return!0;case"false":return!1;case"null":return null}throw new G(`Undefined variable '${t}'`)}function Bl(t){return t==="request"||t==="resource"||t==="true"||t==="false"||t==="null"}function zl(t,e,r,n,s){if(t==="&&"){let o,c;try{o=ir(W(e,n,s),e)}catch(l){c=l}if(c===void 0&&o===!1)return n.trace?.skip(r),!1;let u,f;try{u=ir(W(r,n,s),r)}catch(l){f=l}if(f===void 0&&u===!1)return!1;if(c!==void 0)throw c;if(f!==void 0)throw f;return u}if(t==="||"){let o,c;try{o=ir(W(e,n,s),e)}catch(l){c=l}if(c===void 0&&o===!0)return n.trace?.skip(r),!0;let u,f;try{u=ir(W(r,n,s),r)}catch(l){f=l}if(f===void 0&&u===!0)return!0;if(c!==void 0)throw c;if(f!==void 0)throw f;return u}const i=W(e,n,s),a=W(r,n,s);if(t!=="=="&&t!=="!="){if(i instanceof te){const o=i.binaryOp(t,a);if(o!==oe)return o}if(typeof i=="number"&&a instanceof ae){const o=new ae(i).binaryOp(t,a);if(o!==oe)return o}if(a instanceof te&&(t==="+"||t==="*")){const o=a.binaryOp(t,i);if(o!==oe)return o}if((t!=="+"||typeof i!="string"&&typeof a!="string")&&(i instanceof te||a instanceof te)){const o=i instanceof te?i.typeName:typeof i,c=a instanceof te?a.typeName:typeof a;throw new G(`Operator '${t}' is not defined between ${o} and ${c}`)}}if((t==="<"||t===">"||t==="<="||t===">=")&&!(typeof i=="number"&&typeof a=="number"||typeof i=="string"&&typeof a=="string"))throw new G(`Operator '${t}' is not defined between ${typeof i} and ${typeof a}`);switch(t){case"==":return i===a||me(i,a);case"!=":return!(i===a||me(i,a));case"<":return i<a;case">":return i>a;case"<=":return i<=a;case">=":return i>=a;case"+":{if(Array.isArray(i)&&Array.isArray(a))return[...i,...a];if(typeof i=="string"&&typeof a=="string"||typeof i=="number"&&typeof a=="number")return i+a;if(typeof i=="string"&&a instanceof te)return i+String(a);throw new G(`Operator '+' is not defined between ${Array.isArray(i)?"list":typeof i} and ${Array.isArray(a)?"list":typeof a}`)}case"-":return i-a;case"*":return i*a;case"/":if(a===0)throw new G("Division by zero");return Math.trunc(i/a);case"%":if(a===0)throw new G("Modulo by zero");return i%a;default:throw new G(`Unknown binary op: ${t}`)}}function ir(t,e){if(typeof t=="boolean")return t;throw new G(`Expected a boolean control-flow operand, got ${t===null?"null":typeof t}`,e)}const Vl=new Set(["__proto__","prototype","constructor"]);function Fr(t){if(Vl.has(t))throw new Error(`Invalid field-path segment '${t}': the keys __proto__, prototype, and constructor are reserved and cannot appear in a field path.`)}function Ka(t,e){const r={...t};for(const[n,s]of Object.entries(e)){Fr(n);const i=Object.hasOwn(r,n)?r[n]:void 0;s!==null&&typeof s=="object"&&!Array.isArray(s)&&i!==null&&typeof i=="object"&&!Array.isArray(i)?r[n]=Ka(i,s):r[n]=s}return r}function Hl(t,e,r){let n=t;for(let i=0;i<e.length-1;i++){const a=e[i];Fr(a);const o=Object.hasOwn(n,a)?n[a]:void 0;(o===null||typeof o!="object"||Array.isArray(o))&&(n[a]={}),n=n[a]}const s=e[e.length-1];Fr(s),n[s]=r}function Wl(t,e){const r={...t};for(const[n,s]of Object.entries(e))n.includes(".")?Hl(r,n.split("."),s):(Fr(n),r[n]=s);return r}function Gl(t,e,r){switch(t.kind){case"create":return r;case"set":return t.merge?Ka(e??{},r):r;case"update":return Wl(e??{},r);case"delete":return null}}function Za(t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function Kl(t){return typeof t=="object"&&t!==null&&t.__type==="serverTimestamp"}function Ja(t,e){const r={};for(const[n,s]of Object.entries(t))Kl(s)?r[n]=e:Za(s)?r[n]=Ja(s,e):r[n]=s;return r}function It(t){return typeof t=="number"&&!Number.isInteger(t)?new ae(t):Array.isArray(t)?t.map(It):Za(t)?t.__type==="float"&&typeof t.value=="number"?new ae(t.value):Object.fromEntries(Object.entries(t).map(([e,r])=>[e,It(r)])):t}function yi(t){if(t.method==="list")return{limit:t.query?.limit??null,offset:t.query?.offset??null,orderBy:t.query?.orderBy??null}}function xr(t){return`/${t.path.segments.map(r=>r.type==="literal"?r.value:r.type==="wildcard"?`{${r.name}}`:`{${r.name}=**}`).join("/")}`}function jr(t,e,r,n){const s=[...r,...t.functions],i=t.path.segments,a={},o=[];let c=0,u;for(const p of i)if(p.type==="literal"){if(c>=e.length){u="request-shorter";break}if(e[c]!==p.value){u="literal-mismatch";break}c++}else if(p.type==="wildcard"){if(c>=e.length){u="request-shorter";break}a[p.name]=e[c],c===e.length-1&&o.push(p.name),c++}else a[p.name]=e.slice(c).join("/"),c<e.length&&o.push(p.name),c=e.length;if(u!==void 0)return n?.push({...t.loc?{line:t.loc.line}:{},blockPath:xr(t),matchedSegments:c,totalSegments:i.length,bindings:a,matched:!1,reason:u}),[];const f=e.slice(c);if(f.length===0)return n?.push({...t.loc?{line:t.loc.line}:{},blockPath:xr(t),matchedSegments:c,totalSegments:i.length,bindings:a,matched:!0}),[{block:t,pathVariables:a,candidateVariables:o,functions:s}];const l=[];for(const p of t.children)for(const y of jr(p,f,s,n))y.pathVariables={...a,...y.pathVariables},y.candidateVariables=[...o,...y.candidateVariables],l.push(y);return n?.push({...t.loc?{line:t.loc.line}:{},blockPath:xr(t),matchedSegments:c,totalSegments:i.length,bindings:a,...l.length>0?{matched:!0}:{matched:!1,reason:"no-matching-child"}}),l}class Zl{attempts=[];push(e){this.attempts.push(e)}}function Jl(t){switch(t){case"get":return["get","read"];case"list":return["list","read"];case"create":return["create","write"];case"update":return["update","write"];case"delete":return["delete","write"];default:return[t]}}function Yl(t,e,r,n){const s=Jl(e),i=[],a=[],o=[];for(let p=0;p<t.allows.length;p++){const y=t.allows[p];y.operations.some(b=>s.includes(b))&&o.push({rule:y,index:p})}if(o.length===0)return a.push(`No allow rules found for operation '${e}'`),{decision:"DENY",trace:i,notes:a};let u=!1;const f=r.trace;for(const{rule:p,index:y}of o){const v=Ql(p,y,n),b=new ll;r.trace=b;try{const R=W(p.condition,r);if(v.expressionTrace=b.entries,!!R)return v.verdict="ALLOW",i.push(v),r.trace=f,{decision:"ALLOW",trace:i,notes:a};v.verdict="DENY",i.push(v)}catch(R){v.expressionTrace=b.entries,R instanceof gt?(u=!0,v.verdict="UNSUPPORTED",v.message=R.message):(v.verdict="ERROR",R instanceof Error?v.message=R.message:v.message=String(R)),i.push(v)}}r.trace=f;let l="DENY";return u&&(l="UNSUPPORTED"),{decision:l,trace:i,notes:a}}function Ql(t,e,r){const n=ye(t.condition),s={ruleIndex:e,operations:[...t.operations],verdict:"DENY",conditionText:n};if(t.loc!==void 0){const a=t.loc;if(s.line=a.line,s.col=a.col,s.column=a.col,a.file!==void 0?(s.file=a.file,s.citation=`${a.file}:${a.line}:${a.col}`):(s.file="firestore.rules",s.citation=`firestore.rules:${a.line}:${a.col}`),r!==void 0){const u=Ga(r,a.line,a.col,a.file,n);u!==void 0&&(s.line=u.line,s.col=u.col,s.column=u.col,s.file=u.file,s.citation=u.citation,u.expression!==void 0&&(s.conditionText=u.expression))}}return s}function Xl(t,e,r,n,s){const i=new Map;for(const k of e)i.set(k.name,k);const a=new Map,o=new Set;if(t.functionMocks)for(const k of t.functionMocks)k.function==="get"&&typeof k.result=="object"&&k.result!==null?(a.set(k.path,It(k.result)),o.add(k.path)):k.function==="exists"&&k.result===!0&&(a.set(k.path,{}),o.add(k.path));const c=t.requestTime?_e.fromIsoString(t.requestTime):_e.fromMillis(Date.now()),f=["databases","(default)","documents",...(t.path.startsWith("/")?t.path.slice(1):t.path).split("/").filter(Boolean)],l=new Qe(f,r),p=It(t.data??{}),y=t.resource===void 0||t.resource===null?null:It(t.resource);let v,b;if(t.writeMode)v=Gl(t.writeMode,y,p),b=v!==null;else switch(t.method){case"create":case"update":v=p,b=!0;break;case"delete":v=null,b=!1;break;case"get":case"list":default:v=y,b=y!==null;break}const R=v!==null?It(Ja(v,c)):null,C=R??{};return{request:{auth:t.auth?{uid:t.auth.uid,token:t.auth.token??{}}:null,resource:{data:C},method:t.method,path:l,...yi(t)?{query:yi(t)}:{},time:c},resource:t.method==="create"||y===null?null:{data:It(y)},mockDocuments:a,identitylessFunctionMocks:o,getDoc:n,pathVariables:r,functions:i,database:"(default)",afterStatePath:l,afterState:R,existsAfter:b,...s?{batchProjection:s}:{}}}class ed{simulate(e,r,n){if(!e||e.trim().length===0)return{success:!1,error:{code:"PARSE_FAILED",message:"Empty rules source — call setRules(sandbox, rules) from pyric/sandbox/firestore before operating, or initialize without rules to use the open-by-default ruleset. See pyric/sandbox docs.",recoverable:!0}};const s=_s(e);if(!s)return{success:!1,error:{code:"PARSE_FAILED",message:"Failed to parse rules source",recoverable:!0}};const i=[];let a=0,o=0,c=0;const u={database:"(default)"};for(const f of s.service.match.path.segments)f.type==="wildcard"&&(u[f.name]="(default)");for(const f of r){const l=f.path.split("/").filter(Boolean),p=[...s.functions??[],...s.service.functions??[],...s.service.match.functions];let y=[];const v=new Zl;for(const d of s.service.match.children)y.push(...jr(d,l,p,v));let b=!1;const R=y.length===0,C=f.method==="list";if(R&&C){const d=[...l,"__hypothetical_doc__"];for(const m of s.service.match.children)y.push(...jr(m,d,p,v));y.length>0&&(b=!0)}const k={requestPath:f.path,attempts:v.attempts};if(y.length===0){const d=f.expectation==="DENY"?"PASSED":"FAILED";d==="PASSED"?a++:o++,i.push({description:f.description,expectation:f.expectation,state:d,decision:"DENY",trace:[],notes:[`No match block found for path '${f.path}'`],pathResolution:k});continue}let L="DENY";const $=[],S=[];let T=!1,_;for(const d of y){const g={...u,...d.pathVariables},m=Xl(f,d.functions,g,n?.getDoc,n?.batchProjection),F=xr(d.block),E=Yl(d.block,f.method,m,e);for(const Y of E.trace)Y.matchPath=F;if($.push(...E.trace),S.push(...E.notes),E.decision==="ALLOW"){L="ALLOW",_=F;break}E.decision==="UNSUPPORTED"&&(T=!0)}L!=="ALLOW"&&T&&(L="UNSUPPORTED"),L==="ALLOW"&&_!==void 0&&S.push(`Allowed by match block '${_}'`),b===!0&&S.push(`list on collection path '${f.path}' evaluated against the document-level match block (document wildcard hypothetical, resource undefined) — emulator-faithful`);let h;L==="UNSUPPORTED"?(h="UNSUPPORTED",c++):L===f.expectation?(h="PASSED",a++):(h="FAILED",o++),i.push({description:f.description,expectation:f.expectation,state:h,decision:L,trace:$,notes:S,pathResolution:k})}return{success:!0,data:{passed:a,failed:o,unsupported:c,results:i}}}}function td(t,e,r=new Map,n){if(qr(t,r))return{provable:!0,reason:"list rule does not depend on per-document data; every doc is equally readable"};const s=nd(t,r,n);if(!s.ok||s.required.length===0){const u="list rule depends on per-document data through a predicate the query cannot discharge (a rule is provable only when its entire doc-dependence reduces to top-level `resource.data.field == value` conjunctions, including through inlined helpers — disjunctions, ranges, `in`, membership/type checks, and nested paths are not provable)";return{provable:!1,reason:`${u} — prod rejects the whole query rather than filtering`,residual:{missing:[],mismatched:[],outOfScope:u}}}const i=s.required,a=e.where??[],o=[],c=[];for(const u of i){if(a.some(p=>p.field===u.field&&p.op==="=="&&od(p.value,u.value)))continue;const l=a.find(p=>p.field===u.field&&p.op==="==");l?c.push({field:u.field,expectedValue:u.value,actualValue:l.value}):o.push({field:u.field,expectedValue:u.value,fromAuthUid:u.fromAuthUid})}return o.length===0&&c.length===0?{provable:!0,reason:"every per-document predicate the rule requires is guaranteed by a query where(...) constraint"}:{provable:!1,reason:rd(o,c),residual:{missing:o,mismatched:c}}}function rd(t,e){const r=[];if(t.length>0){const n=t.map(s=>`resource.data.${s.field} == ${s.fromAuthUid?"request.auth.uid":JSON.stringify(s.expectedValue)}`).join(", ");r.push(`the query has no matching where(...) equality for [${n}]`)}if(e.length>0){const n=e.map(s=>`resource.data.${s.field} == ${JSON.stringify(s.expectedValue)} but the query pins ${JSON.stringify(s.actualValue)}`).join(", ");r.push(`the query where(...) value does not match [${n}]`)}return`${r.join("; ")} — prod rejects the query ("rules are not filters")`}function qr(t,e=new Map,r=new Set){const n=s=>{switch(s.type){case"literal":return!0;case"identifier":return s.name!=="resource";case"memberAccess":return n(s.object);case"bracketAccess":return n(s.object)&&n(s.index);case"sliceAccess":return n(s.object)&&n(s.start)&&n(s.end);case"binaryOp":return n(s.left)&&n(s.right);case"unaryOp":return n(s.operand);case"ternary":return n(s.condition)&&n(s.consequent)&&n(s.alternate);case"inExpr":return n(s.element)&&n(s.collection);case"isExpr":return n(s.value);case"listLiteral":return s.elements.every(n);case"mapLiteral":return s.entries.every(i=>n(i.key)&&n(i.value));case"pathLiteral":return s.segments.every(i=>typeof i=="string"||n(i));case"methodCall":return n(s.object)&&s.args.every(n);case"functionCall":{if(!s.args.every(n))return!1;const i=e.get(s.name);if(!i)return!0;if(r.has(s.name))return!1;const a=new Set(r).add(s.name);return qr(i.body,e,a)&&i.lets.every(o=>qr(o.value,e,a))}default:return!1}};return n(t)}function nd(t,e,r){const n=[],s=(i,a)=>{if(i.type==="binaryOp"&&i.op==="&&")return s(i.left,a)&&s(i.right,a);if(i.type==="functionCall"&&e.has(i.name)&&!a.has(i.name)){const c=e.get(i.name),u=new Map;c.parameters.forEach((p,y)=>{const v=i.args[y];v&&u.set(p,v)});for(const p of c.lets)u.set(p.name,vi(p.value,u));const f=vi(c.body,u),l=new Set(a).add(i.name);return s(f,l)}const o=sd(i,r);return o?(n.push(o),!0):qr(i,e)};return s(t,new Set)?{ok:!0,required:n}:{ok:!1}}function sd(t,e){if(t.type!=="binaryOp"||t.op!=="==")return null;const r=(n,s)=>{const i=ad(n);return i===null?null:s.type==="literal"?{field:i,value:s.value,fromAuthUid:!1}:e!==void 0&&id(s)?{field:i,value:e,fromAuthUid:!0}:null};return r(t.left,t.right)??r(t.right,t.left)}function id(t){return t.type==="memberAccess"&&t.property==="uid"&&t.object.type==="memberAccess"&&t.object.property==="auth"&&t.object.object.type==="identifier"&&t.object.object.name==="request"}function vi(t,e){const r=n=>{switch(n.type){case"identifier":return e.get(n.name)??n;case"literal":return n;case"memberAccess":return{...n,object:r(n.object)};case"methodCall":return{...n,object:r(n.object),args:n.args.map(r)};case"bracketAccess":return{...n,object:r(n.object),index:r(n.index)};case"sliceAccess":return{...n,object:r(n.object),start:r(n.start),end:r(n.end)};case"binaryOp":return{...n,left:r(n.left),right:r(n.right)};case"unaryOp":return{...n,operand:r(n.operand)};case"ternary":return{...n,condition:r(n.condition),consequent:r(n.consequent),alternate:r(n.alternate)};case"inExpr":return{...n,element:r(n.element),collection:r(n.collection)};case"isExpr":return{...n,value:r(n.value)};case"listLiteral":return{...n,elements:n.elements.map(r)};case"mapLiteral":return{...n,entries:n.entries.map(s=>({key:r(s.key),value:r(s.value)}))};case"pathLiteral":return{...n,segments:n.segments.map(s=>typeof s=="string"?s:r(s))};case"functionCall":return{...n,args:n.args.map(r)}}};return r(t)}function ad(t){return t.type==="memberAccess"&&t.object.type==="memberAccess"&&t.object.property==="data"&&t.object.object.type==="identifier"&&t.object.object.name==="resource"?t.property:null}function od(t,e){return t===e}class Ot extends te{typeName="reference";path;constructor(e){super(),this.path=cd(e)}static fromResourceName(e){return new Ot(Ya(e))}get id(){const e=this.path.lastIndexOf("/");return e===-1?this.path:this.path.slice(e+1)}get parent(){const e=this.path.lastIndexOf("/");return e===-1?"":this.path.slice(0,e)}valueOf(){return NaN}toString(){return this.path}toJSON(){return{__type:"reference",path:this.path}}equals(e){return e instanceof Ot?this.path===e.path:!1}field(e){switch(e){case"path":return this.path;case"id":return this.id;case"parent":return this.parent;default:return null}}callMethod(e,r){return oe}}function cd(t){let e=Ya(t);return e.startsWith("/")&&(e=e.slice(1)),e.endsWith("/")&&(e=e.slice(0,-1)),e}function Ya(t){const e="/documents/",r=t.indexOf(e);return r===-1?t:t.slice(r+e.length)}class Qt extends te{typeName="vector";value;constructor(e){if(super(),!Array.isArray(e))throw new TypeError("Vector: value must be a number[]");for(let r=0;r<e.length;r++)if(typeof e[r]!="number")throw new TypeError(`Vector: element at index ${r} is not a number (got ${typeof e[r]})`);this.value=Object.freeze(e.slice())}get dimension(){return this.value.length}valueOf(){return NaN}toString(){return`[${this.value.join(", ")}]`}toJSON(){return{__type__:"__vector__",value:this.value.slice()}}equals(e){if(!(e instanceof Qt)||e.value.length!==this.value.length)return!1;for(let r=0;r<this.value.length;r++)if(e.value[r]!==this.value[r])return!1;return!0}callMethod(e,r){return oe}}var J;(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function r(s){throw new Error}t.assertNever=r,t.arrayToEnum=s=>{const i={};for(const a of s)i[a]=a;return i},t.getValidEnumValues=s=>{const i=t.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),a={};for(const o of i)a[o]=s[o];return t.objectValues(a)},t.objectValues=s=>t.objectKeys(s).map(function(i){return s[i]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const i=[];for(const a in s)Object.prototype.hasOwnProperty.call(s,a)&&i.push(a);return i},t.find=(s,i)=>{for(const a of s)if(i(a))return a},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,i=" | "){return s.map(a=>typeof a=="string"?`'${a}'`:a).join(i)}t.joinValues=n,t.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(J||(J={}));var bi;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(bi||(bi={}));const q=J.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ft=t=>{switch(typeof t){case"undefined":return q.undefined;case"string":return q.string;case"number":return Number.isNaN(t)?q.nan:q.number;case"boolean":return q.boolean;case"function":return q.function;case"bigint":return q.bigint;case"symbol":return q.symbol;case"object":return Array.isArray(t)?q.array:t===null?q.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?q.promise:typeof Map<"u"&&t instanceof Map?q.map:typeof Set<"u"&&t instanceof Set?q.set:typeof Date<"u"&&t instanceof Date?q.date:q.object;default:return q.unknown}},N=J.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class dt extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){const r=e||function(i){return i.message},n={_errors:[]},s=i=>{for(const a of i.issues)if(a.code==="invalid_union")a.unionErrors.map(s);else if(a.code==="invalid_return_type")s(a.returnTypeError);else if(a.code==="invalid_arguments")s(a.argumentsError);else if(a.path.length===0)n._errors.push(r(a));else{let o=n,c=0;for(;c<a.path.length;){const u=a.path[c];c===a.path.length-1?(o[u]=o[u]||{_errors:[]},o[u]._errors.push(r(a))):o[u]=o[u]||{_errors:[]},o=o[u],c++}}};return s(this),n}static assert(e){if(!(e instanceof dt))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,J.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){const r={},n=[];for(const s of this.issues)if(s.path.length>0){const i=s.path[0];r[i]=r[i]||[],r[i].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}}dt.create=t=>new dt(t);const Gn=(t,e)=>{let r;switch(t.code){case N.invalid_type:t.received===q.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case N.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,J.jsonStringifyReplacer)}`;break;case N.unrecognized_keys:r=`Unrecognized key(s) in object: ${J.joinValues(t.keys,", ")}`;break;case N.invalid_union:r="Invalid input";break;case N.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${J.joinValues(t.options)}`;break;case N.invalid_enum_value:r=`Invalid enum value. Expected ${J.joinValues(t.options)}, received '${t.received}'`;break;case N.invalid_arguments:r="Invalid function arguments";break;case N.invalid_return_type:r="Invalid function return type";break;case N.invalid_date:r="Invalid date";break;case N.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:J.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case N.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case N.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case N.custom:r="Invalid input";break;case N.invalid_intersection_types:r="Intersection results could not be merged";break;case N.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case N.not_finite:r="Number must be finite";break;default:r=e.defaultError,J.assertNever(t)}return{message:r}};let ud=Gn;function ld(){return ud}const dd=t=>{const{data:e,path:r,errorMaps:n,issueData:s}=t,i=[...r,...s.path||[]],a={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let o="";const c=n.filter(u=>!!u).slice().reverse();for(const u of c)o=u(a,{data:e,defaultError:o}).message;return{...s,path:i,message:o}};function j(t,e){const r=ld(),n=dd({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Gn?void 0:Gn].filter(s=>!!s)});t.common.issues.push(n)}class De{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){const n=[];for(const s of r){if(s.status==="aborted")return U;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){const n=[];for(const s of r){const i=await s.key,a=await s.value;n.push({key:i,value:a})}return De.mergeObjectSync(e,n)}static mergeObjectSync(e,r){const n={};for(const s of r){const{key:i,value:a}=s;if(i.status==="aborted"||a.status==="aborted")return U;i.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof a.value<"u"||s.alwaysSet)&&(n[i.value]=a.value)}return{status:e.value,value:n}}}const U=Object.freeze({status:"aborted"}),ar=t=>({status:"dirty",value:t}),He=t=>({status:"valid",value:t}),wi=t=>t.status==="aborted",Si=t=>t.status==="dirty",Gt=t=>t.status==="valid",Pr=t=>typeof Promise<"u"&&t instanceof Promise;var P;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(P||(P={}));class tt{constructor(e,r,n,s){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const _i=(t,e)=>{if(Gt(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const r=new dt(t.common.issues);return this._error=r,this._error}}};function H(t){if(!t)return{};const{errorMap:e,invalid_type_error:r,required_error:n,description:s}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(a,o)=>{const{message:c}=t;return a.code==="invalid_enum_value"?{message:c??o.defaultError}:typeof o.data>"u"?{message:c??n??o.defaultError}:a.code!=="invalid_type"?{message:o.defaultError}:{message:c??r??o.defaultError}},description:s}}class K{get description(){return this._def.description}_getType(e){return ft(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:ft(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new De,ctx:{common:e.parent.common,data:e.data,parsedType:ft(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const r=this._parse(e);if(Pr(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){const r=this._parse(e);return Promise.resolve(r)}parse(e,r){const n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){const n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ft(e)},s=this._parseSync({data:e,path:n.path,parent:n});return _i(n,s)}"~validate"(e){const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ft(e)};if(!this["~standard"].async)try{const n=this._parseSync({data:e,path:[],parent:r});return Gt(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>Gt(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){const n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){const n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ft(e)},s=this._parse({data:e,path:n.path,parent:n}),i=await(Pr(s)?s:Promise.resolve(s));return _i(n,i)}refine(e,r){const n=s=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(s):r;return this._refinement((s,i)=>{const a=e(s),o=()=>i.addIssue({code:N.custom,...n(s)});return typeof Promise<"u"&&a instanceof Promise?a.then(c=>c?!0:(o(),!1)):a?!0:(o(),!1)})}refinement(e,r){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof r=="function"?r(n,s):r),!1))}_refinement(e){return new Nt({schema:this,typeName:B.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return ut.create(this,this._def)}nullable(){return Lt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Xe.create(this)}promise(){return Wr.create(this,this._def)}or(e){return Br.create([this,e],this._def)}and(e){return zr.create(this,e,this._def)}transform(e){return new Nt({...H(this._def),schema:this,typeName:B.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const r=typeof e=="function"?e:()=>e;return new Gr({...H(this._def),innerType:this,defaultValue:r,typeName:B.ZodDefault})}brand(){return new to({typeName:B.ZodBranded,type:this,...H(this._def)})}catch(e){const r=typeof e=="function"?e:()=>e;return new Kr({...H(this._def),innerType:this,catchValue:r,typeName:B.ZodCatch})}describe(e){const r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Es.create(this,e)}readonly(){return Zr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const hd=/^c[^\s-]{8,}$/i,fd=/^[0-9a-z]+$/,pd=/^[0-9A-HJKMNP-TV-Z]{26}$/i,md=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,gd=/^[a-z0-9_-]{21}$/i,yd=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,vd=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,bd=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,wd="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let An;const Sd=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,_d=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Ad=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Id=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,xd=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,kd=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Qa="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Ed=new RegExp(`^${Qa}$`);function Xa(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);const r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function Td(t){return new RegExp(`^${Xa(t)}$`)}function Od(t){let e=`${Qa}T${Xa(t)}`;const r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function Cd(t,e){return!!((e==="v4"||!e)&&Sd.test(t)||(e==="v6"||!e)&&Ad.test(t))}function Rd(t,e){if(!yd.test(t))return!1;try{const[r]=t.split(".");if(!r)return!1;const n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function Nd(t,e){return!!((e==="v4"||!e)&&_d.test(t)||(e==="v6"||!e)&&Id.test(t))}class at extends K{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==q.string){const i=this._getOrReturnCtx(e);return j(i,{code:N.invalid_type,expected:q.string,received:i.parsedType}),U}const n=new De;let s;for(const i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),j(s,{code:N.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),j(s,{code:N.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="length"){const a=e.data.length>i.value,o=e.data.length<i.value;(a||o)&&(s=this._getOrReturnCtx(e,s),a?j(s,{code:N.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):o&&j(s,{code:N.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),n.dirty())}else if(i.kind==="email")bd.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"email",code:N.invalid_string,message:i.message}),n.dirty());else if(i.kind==="emoji")An||(An=new RegExp(wd,"u")),An.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"emoji",code:N.invalid_string,message:i.message}),n.dirty());else if(i.kind==="uuid")md.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"uuid",code:N.invalid_string,message:i.message}),n.dirty());else if(i.kind==="nanoid")gd.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"nanoid",code:N.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid")hd.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"cuid",code:N.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid2")fd.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"cuid2",code:N.invalid_string,message:i.message}),n.dirty());else if(i.kind==="ulid")pd.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"ulid",code:N.invalid_string,message:i.message}),n.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),j(s,{validation:"url",code:N.invalid_string,message:i.message}),n.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"regex",code:N.invalid_string,message:i.message}),n.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),j(s,{code:N.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),n.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),j(s,{code:N.invalid_string,validation:{startsWith:i.value},message:i.message}),n.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),j(s,{code:N.invalid_string,validation:{endsWith:i.value},message:i.message}),n.dirty()):i.kind==="datetime"?Od(i).test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{code:N.invalid_string,validation:"datetime",message:i.message}),n.dirty()):i.kind==="date"?Ed.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{code:N.invalid_string,validation:"date",message:i.message}),n.dirty()):i.kind==="time"?Td(i).test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{code:N.invalid_string,validation:"time",message:i.message}),n.dirty()):i.kind==="duration"?vd.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"duration",code:N.invalid_string,message:i.message}),n.dirty()):i.kind==="ip"?Cd(e.data,i.version)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"ip",code:N.invalid_string,message:i.message}),n.dirty()):i.kind==="jwt"?Rd(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"jwt",code:N.invalid_string,message:i.message}),n.dirty()):i.kind==="cidr"?Nd(e.data,i.version)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"cidr",code:N.invalid_string,message:i.message}),n.dirty()):i.kind==="base64"?xd.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"base64",code:N.invalid_string,message:i.message}),n.dirty()):i.kind==="base64url"?kd.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"base64url",code:N.invalid_string,message:i.message}),n.dirty()):J.assertNever(i);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(s=>e.test(s),{validation:r,code:N.invalid_string,...P.errToObj(n)})}_addCheck(e){return new at({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...P.errToObj(e)})}url(e){return this._addCheck({kind:"url",...P.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...P.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...P.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...P.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...P.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...P.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...P.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...P.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...P.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...P.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...P.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...P.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...P.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...P.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...P.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...P.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...P.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...P.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...P.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...P.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...P.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...P.errToObj(r)})}nonempty(e){return this.min(1,P.errToObj(e))}trim(){return new at({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new at({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new at({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}}at.create=t=>new at({checks:[],typeName:B.ZodString,coerce:t?.coerce??!1,...H(t)});function Ld(t,e){const r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=r>n?r:n,i=Number.parseInt(t.toFixed(s).replace(".","")),a=Number.parseInt(e.toFixed(s).replace(".",""));return i%a/10**s}class Kt extends K{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==q.number){const i=this._getOrReturnCtx(e);return j(i,{code:N.invalid_type,expected:q.number,received:i.parsedType}),U}let n;const s=new De;for(const i of this._def.checks)i.kind==="int"?J.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),j(n,{code:N.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),j(n,{code:N.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),j(n,{code:N.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?Ld(e.data,i.value)!==0&&(n=this._getOrReturnCtx(e,n),j(n,{code:N.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),j(n,{code:N.not_finite,message:i.message}),s.dirty()):J.assertNever(i);return{status:s.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,P.toString(r))}gt(e,r){return this.setLimit("min",e,!1,P.toString(r))}lte(e,r){return this.setLimit("max",e,!0,P.toString(r))}lt(e,r){return this.setLimit("max",e,!1,P.toString(r))}setLimit(e,r,n,s){return new Kt({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:P.toString(s)}]})}_addCheck(e){return new Kt({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:P.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:P.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:P.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:P.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:P.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:P.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:P.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:P.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:P.toString(e)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&J.isInteger(e.value))}get isFinite(){let e=null,r=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}}Kt.create=t=>new Kt({checks:[],typeName:B.ZodNumber,coerce:t?.coerce||!1,...H(t)});class hr extends K{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==q.bigint)return this._getInvalidInput(e);let n;const s=new De;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),j(n,{code:N.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),j(n,{code:N.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),j(n,{code:N.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):J.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){const r=this._getOrReturnCtx(e);return j(r,{code:N.invalid_type,expected:q.bigint,received:r.parsedType}),U}gte(e,r){return this.setLimit("min",e,!0,P.toString(r))}gt(e,r){return this.setLimit("min",e,!1,P.toString(r))}lte(e,r){return this.setLimit("max",e,!0,P.toString(r))}lt(e,r){return this.setLimit("max",e,!1,P.toString(r))}setLimit(e,r,n,s){return new hr({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:P.toString(s)}]})}_addCheck(e){return new hr({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:P.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:P.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:P.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:P.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:P.toString(r)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}}hr.create=t=>new hr({checks:[],typeName:B.ZodBigInt,coerce:t?.coerce??!1,...H(t)});class Kn extends K{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==q.boolean){const n=this._getOrReturnCtx(e);return j(n,{code:N.invalid_type,expected:q.boolean,received:n.parsedType}),U}return He(e.data)}}Kn.create=t=>new Kn({typeName:B.ZodBoolean,coerce:t?.coerce||!1,...H(t)});class $r extends K{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==q.date){const i=this._getOrReturnCtx(e);return j(i,{code:N.invalid_type,expected:q.date,received:i.parsedType}),U}if(Number.isNaN(e.data.getTime())){const i=this._getOrReturnCtx(e);return j(i,{code:N.invalid_date}),U}const n=new De;let s;for(const i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),j(s,{code:N.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),n.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),j(s,{code:N.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()):J.assertNever(i);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new $r({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:P.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:P.toString(r)})}get minDate(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}}$r.create=t=>new $r({checks:[],coerce:t?.coerce||!1,typeName:B.ZodDate,...H(t)});class Ai extends K{_parse(e){if(this._getType(e)!==q.symbol){const n=this._getOrReturnCtx(e);return j(n,{code:N.invalid_type,expected:q.symbol,received:n.parsedType}),U}return He(e.data)}}Ai.create=t=>new Ai({typeName:B.ZodSymbol,...H(t)});class Zn extends K{_parse(e){if(this._getType(e)!==q.undefined){const n=this._getOrReturnCtx(e);return j(n,{code:N.invalid_type,expected:q.undefined,received:n.parsedType}),U}return He(e.data)}}Zn.create=t=>new Zn({typeName:B.ZodUndefined,...H(t)});class Ur extends K{_parse(e){if(this._getType(e)!==q.null){const n=this._getOrReturnCtx(e);return j(n,{code:N.invalid_type,expected:q.null,received:n.parsedType}),U}return He(e.data)}}Ur.create=t=>new Ur({typeName:B.ZodNull,...H(t)});class Ii extends K{constructor(){super(...arguments),this._any=!0}_parse(e){return He(e.data)}}Ii.create=t=>new Ii({typeName:B.ZodAny,...H(t)});class Jn extends K{constructor(){super(...arguments),this._unknown=!0}_parse(e){return He(e.data)}}Jn.create=t=>new Jn({typeName:B.ZodUnknown,...H(t)});class yt extends K{_parse(e){const r=this._getOrReturnCtx(e);return j(r,{code:N.invalid_type,expected:q.never,received:r.parsedType}),U}}yt.create=t=>new yt({typeName:B.ZodNever,...H(t)});class xi extends K{_parse(e){if(this._getType(e)!==q.undefined){const n=this._getOrReturnCtx(e);return j(n,{code:N.invalid_type,expected:q.void,received:n.parsedType}),U}return He(e.data)}}xi.create=t=>new xi({typeName:B.ZodVoid,...H(t)});class Xe extends K{_parse(e){const{ctx:r,status:n}=this._processInputParams(e),s=this._def;if(r.parsedType!==q.array)return j(r,{code:N.invalid_type,expected:q.array,received:r.parsedType}),U;if(s.exactLength!==null){const a=r.data.length>s.exactLength.value,o=r.data.length<s.exactLength.value;(a||o)&&(j(r,{code:a?N.too_big:N.too_small,minimum:o?s.exactLength.value:void 0,maximum:a?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&r.data.length<s.minLength.value&&(j(r,{code:N.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&r.data.length>s.maxLength.value&&(j(r,{code:N.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((a,o)=>s.type._parseAsync(new tt(r,a,r.path,o)))).then(a=>De.mergeArray(n,a));const i=[...r.data].map((a,o)=>s.type._parseSync(new tt(r,a,r.path,o)));return De.mergeArray(n,i)}get element(){return this._def.type}min(e,r){return new Xe({...this._def,minLength:{value:e,message:P.toString(r)}})}max(e,r){return new Xe({...this._def,maxLength:{value:e,message:P.toString(r)}})}length(e,r){return new Xe({...this._def,exactLength:{value:e,message:P.toString(r)}})}nonempty(e){return this.min(1,e)}}Xe.create=(t,e)=>new Xe({type:t,minLength:null,maxLength:null,exactLength:null,typeName:B.ZodArray,...H(e)});function Bt(t){if(t instanceof fe){const e={};for(const r in t.shape){const n=t.shape[r];e[r]=ut.create(Bt(n))}return new fe({...t._def,shape:()=>e})}else return t instanceof Xe?new Xe({...t._def,type:Bt(t.element)}):t instanceof ut?ut.create(Bt(t.unwrap())):t instanceof Lt?Lt.create(Bt(t.unwrap())):t instanceof Ct?Ct.create(t.items.map(e=>Bt(e))):t}class fe extends K{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),r=J.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==q.object){const u=this._getOrReturnCtx(e);return j(u,{code:N.invalid_type,expected:q.object,received:u.parsedType}),U}const{status:n,ctx:s}=this._processInputParams(e),{shape:i,keys:a}=this._getCached(),o=[];if(!(this._def.catchall instanceof yt&&this._def.unknownKeys==="strip"))for(const u in s.data)a.includes(u)||o.push(u);const c=[];for(const u of a){const f=i[u],l=s.data[u];c.push({key:{status:"valid",value:u},value:f._parse(new tt(s,l,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof yt){const u=this._def.unknownKeys;if(u==="passthrough")for(const f of o)c.push({key:{status:"valid",value:f},value:{status:"valid",value:s.data[f]}});else if(u==="strict")o.length>0&&(j(s,{code:N.unrecognized_keys,keys:o}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const u=this._def.catchall;for(const f of o){const l=s.data[f];c.push({key:{status:"valid",value:f},value:u._parse(new tt(s,l,s.path,f)),alwaysSet:f in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const u=[];for(const f of c){const l=await f.key,p=await f.value;u.push({key:l,value:p,alwaysSet:f.alwaysSet})}return u}).then(u=>De.mergeObjectSync(n,u)):De.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return P.errToObj,new fe({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{const s=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:P.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new fe({...this._def,unknownKeys:"strip"})}passthrough(){return new fe({...this._def,unknownKeys:"passthrough"})}extend(e){return new fe({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new fe({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:B.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new fe({...this._def,catchall:e})}pick(e){const r={};for(const n of J.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new fe({...this._def,shape:()=>r})}omit(e){const r={};for(const n of J.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new fe({...this._def,shape:()=>r})}deepPartial(){return Bt(this)}partial(e){const r={};for(const n of J.objectKeys(this.shape)){const s=this.shape[n];e&&!e[n]?r[n]=s:r[n]=s.optional()}return new fe({...this._def,shape:()=>r})}required(e){const r={};for(const n of J.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let i=this.shape[n];for(;i instanceof ut;)i=i._def.innerType;r[n]=i}return new fe({...this._def,shape:()=>r})}keyof(){return eo(J.objectKeys(this.shape))}}fe.create=(t,e)=>new fe({shape:()=>t,unknownKeys:"strip",catchall:yt.create(),typeName:B.ZodObject,...H(e)});fe.strictCreate=(t,e)=>new fe({shape:()=>t,unknownKeys:"strict",catchall:yt.create(),typeName:B.ZodObject,...H(e)});fe.lazycreate=(t,e)=>new fe({shape:t,unknownKeys:"strip",catchall:yt.create(),typeName:B.ZodObject,...H(e)});class Br extends K{_parse(e){const{ctx:r}=this._processInputParams(e),n=this._def.options;function s(i){for(const o of i)if(o.result.status==="valid")return o.result;for(const o of i)if(o.result.status==="dirty")return r.common.issues.push(...o.ctx.common.issues),o.result;const a=i.map(o=>new dt(o.ctx.common.issues));return j(r,{code:N.invalid_union,unionErrors:a}),U}if(r.common.async)return Promise.all(n.map(async i=>{const a={...r,common:{...r.common,issues:[]},parent:null};return{result:await i._parseAsync({data:r.data,path:r.path,parent:a}),ctx:a}})).then(s);{let i;const a=[];for(const c of n){const u={...r,common:{...r.common,issues:[]},parent:null},f=c._parseSync({data:r.data,path:r.path,parent:u});if(f.status==="valid")return f;f.status==="dirty"&&!i&&(i={result:f,ctx:u}),u.common.issues.length&&a.push(u.common.issues)}if(i)return r.common.issues.push(...i.ctx.common.issues),i.result;const o=a.map(c=>new dt(c));return j(r,{code:N.invalid_union,unionErrors:o}),U}}get options(){return this._def.options}}Br.create=(t,e)=>new Br({options:t,typeName:B.ZodUnion,...H(e)});const st=t=>t instanceof Qn?st(t.schema):t instanceof Nt?st(t.innerType()):t instanceof Hr?[t.value]:t instanceof Rt?t.options:t instanceof Xn?J.objectValues(t.enum):t instanceof Gr?st(t._def.innerType):t instanceof Zn?[void 0]:t instanceof Ur?[null]:t instanceof ut?[void 0,...st(t.unwrap())]:t instanceof Lt?[null,...st(t.unwrap())]:t instanceof to||t instanceof Zr?st(t.unwrap()):t instanceof Kr?st(t._def.innerType):[];class ks extends K{_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==q.object)return j(r,{code:N.invalid_type,expected:q.object,received:r.parsedType}),U;const n=this.discriminator,s=r.data[n],i=this.optionsMap.get(s);return i?r.common.async?i._parseAsync({data:r.data,path:r.path,parent:r}):i._parseSync({data:r.data,path:r.path,parent:r}):(j(r,{code:N.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),U)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){const s=new Map;for(const i of r){const a=st(i.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const o of a){if(s.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);s.set(o,i)}}return new ks({typeName:B.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:s,...H(n)})}}function Yn(t,e){const r=ft(t),n=ft(e);if(t===e)return{valid:!0,data:t};if(r===q.object&&n===q.object){const s=J.objectKeys(e),i=J.objectKeys(t).filter(o=>s.indexOf(o)!==-1),a={...t,...e};for(const o of i){const c=Yn(t[o],e[o]);if(!c.valid)return{valid:!1};a[o]=c.data}return{valid:!0,data:a}}else if(r===q.array&&n===q.array){if(t.length!==e.length)return{valid:!1};const s=[];for(let i=0;i<t.length;i++){const a=t[i],o=e[i],c=Yn(a,o);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return r===q.date&&n===q.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}class zr extends K{_parse(e){const{status:r,ctx:n}=this._processInputParams(e),s=(i,a)=>{if(wi(i)||wi(a))return U;const o=Yn(i.value,a.value);return o.valid?((Si(i)||Si(a))&&r.dirty(),{status:r.value,value:o.data}):(j(n,{code:N.invalid_intersection_types}),U)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([i,a])=>s(i,a)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}zr.create=(t,e,r)=>new zr({left:t,right:e,typeName:B.ZodIntersection,...H(r)});class Ct extends K{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==q.array)return j(n,{code:N.invalid_type,expected:q.array,received:n.parsedType}),U;if(n.data.length<this._def.items.length)return j(n,{code:N.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),U;!this._def.rest&&n.data.length>this._def.items.length&&(j(n,{code:N.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const i=[...n.data].map((a,o)=>{const c=this._def.items[o]||this._def.rest;return c?c._parse(new tt(n,a,n.path,o)):null}).filter(a=>!!a);return n.common.async?Promise.all(i).then(a=>De.mergeArray(r,a)):De.mergeArray(r,i)}get items(){return this._def.items}rest(e){return new Ct({...this._def,rest:e})}}Ct.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ct({items:t,typeName:B.ZodTuple,rest:null,...H(e)})};class Vr extends K{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==q.object)return j(n,{code:N.invalid_type,expected:q.object,received:n.parsedType}),U;const s=[],i=this._def.keyType,a=this._def.valueType;for(const o in n.data)s.push({key:i._parse(new tt(n,o,n.path,o)),value:a._parse(new tt(n,n.data[o],n.path,o)),alwaysSet:o in n.data});return n.common.async?De.mergeObjectAsync(r,s):De.mergeObjectSync(r,s)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof K?new Vr({keyType:e,valueType:r,typeName:B.ZodRecord,...H(n)}):new Vr({keyType:at.create(),valueType:e,typeName:B.ZodRecord,...H(r)})}}class ki extends K{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==q.map)return j(n,{code:N.invalid_type,expected:q.map,received:n.parsedType}),U;const s=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([o,c],u)=>({key:s._parse(new tt(n,o,n.path,[u,"key"])),value:i._parse(new tt(n,c,n.path,[u,"value"]))}));if(n.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const c of a){const u=await c.key,f=await c.value;if(u.status==="aborted"||f.status==="aborted")return U;(u.status==="dirty"||f.status==="dirty")&&r.dirty(),o.set(u.value,f.value)}return{status:r.value,value:o}})}else{const o=new Map;for(const c of a){const u=c.key,f=c.value;if(u.status==="aborted"||f.status==="aborted")return U;(u.status==="dirty"||f.status==="dirty")&&r.dirty(),o.set(u.value,f.value)}return{status:r.value,value:o}}}}ki.create=(t,e,r)=>new ki({valueType:e,keyType:t,typeName:B.ZodMap,...H(r)});class fr extends K{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==q.set)return j(n,{code:N.invalid_type,expected:q.set,received:n.parsedType}),U;const s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(j(n,{code:N.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),r.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(j(n,{code:N.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),r.dirty());const i=this._def.valueType;function a(c){const u=new Set;for(const f of c){if(f.status==="aborted")return U;f.status==="dirty"&&r.dirty(),u.add(f.value)}return{status:r.value,value:u}}const o=[...n.data.values()].map((c,u)=>i._parse(new tt(n,c,n.path,u)));return n.common.async?Promise.all(o).then(c=>a(c)):a(o)}min(e,r){return new fr({...this._def,minSize:{value:e,message:P.toString(r)}})}max(e,r){return new fr({...this._def,maxSize:{value:e,message:P.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}}fr.create=(t,e)=>new fr({valueType:t,minSize:null,maxSize:null,typeName:B.ZodSet,...H(e)});class Qn extends K{get schema(){return this._def.getter()}_parse(e){const{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}}Qn.create=(t,e)=>new Qn({getter:t,typeName:B.ZodLazy,...H(e)});class Hr extends K{_parse(e){if(e.data!==this._def.value){const r=this._getOrReturnCtx(e);return j(r,{received:r.data,code:N.invalid_literal,expected:this._def.value}),U}return{status:"valid",value:e.data}}get value(){return this._def.value}}Hr.create=(t,e)=>new Hr({value:t,typeName:B.ZodLiteral,...H(e)});function eo(t,e){return new Rt({values:t,typeName:B.ZodEnum,...H(e)})}class Rt extends K{_parse(e){if(typeof e.data!="string"){const r=this._getOrReturnCtx(e),n=this._def.values;return j(r,{expected:J.joinValues(n),received:r.parsedType,code:N.invalid_type}),U}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const r=this._getOrReturnCtx(e),n=this._def.values;return j(r,{received:r.data,code:N.invalid_enum_value,options:n}),U}return He(e.data)}get options(){return this._def.values}get enum(){const e={};for(const r of this._def.values)e[r]=r;return e}get Values(){const e={};for(const r of this._def.values)e[r]=r;return e}get Enum(){const e={};for(const r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return Rt.create(e,{...this._def,...r})}exclude(e,r=this._def){return Rt.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}}Rt.create=eo;class Xn extends K{_parse(e){const r=J.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==q.string&&n.parsedType!==q.number){const s=J.objectValues(r);return j(n,{expected:J.joinValues(s),received:n.parsedType,code:N.invalid_type}),U}if(this._cache||(this._cache=new Set(J.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const s=J.objectValues(r);return j(n,{received:n.data,code:N.invalid_enum_value,options:s}),U}return He(e.data)}get enum(){return this._def.values}}Xn.create=(t,e)=>new Xn({values:t,typeName:B.ZodNativeEnum,...H(e)});class Wr extends K{unwrap(){return this._def.type}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==q.promise&&r.common.async===!1)return j(r,{code:N.invalid_type,expected:q.promise,received:r.parsedType}),U;const n=r.parsedType===q.promise?r.data:Promise.resolve(r.data);return He(n.then(s=>this._def.type.parseAsync(s,{path:r.path,errorMap:r.common.contextualErrorMap})))}}Wr.create=(t,e)=>new Wr({type:t,typeName:B.ZodPromise,...H(e)});class Nt extends K{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===B.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:r,ctx:n}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:a=>{j(n,a),a.fatal?r.abort():r.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){const a=s.transform(n.data,i);if(n.common.async)return Promise.resolve(a).then(async o=>{if(r.value==="aborted")return U;const c=await this._def.schema._parseAsync({data:o,path:n.path,parent:n});return c.status==="aborted"?U:c.status==="dirty"||r.value==="dirty"?ar(c.value):c});{if(r.value==="aborted")return U;const o=this._def.schema._parseSync({data:a,path:n.path,parent:n});return o.status==="aborted"?U:o.status==="dirty"||r.value==="dirty"?ar(o.value):o}}if(s.type==="refinement"){const a=o=>{const c=s.refinement(o,i);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(n.common.async===!1){const o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?U:(o.status==="dirty"&&r.dirty(),a(o.value),{status:r.value,value:o.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>o.status==="aborted"?U:(o.status==="dirty"&&r.dirty(),a(o.value).then(()=>({status:r.value,value:o.value}))))}if(s.type==="transform")if(n.common.async===!1){const a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Gt(a))return U;const o=s.transform(a.value,i);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:o}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>Gt(a)?Promise.resolve(s.transform(a.value,i)).then(o=>({status:r.value,value:o})):U);J.assertNever(s)}}Nt.create=(t,e,r)=>new Nt({schema:t,typeName:B.ZodEffects,effect:e,...H(r)});Nt.createWithPreprocess=(t,e,r)=>new Nt({schema:e,effect:{type:"preprocess",transform:t},typeName:B.ZodEffects,...H(r)});class ut extends K{_parse(e){return this._getType(e)===q.undefined?He(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ut.create=(t,e)=>new ut({innerType:t,typeName:B.ZodOptional,...H(e)});class Lt extends K{_parse(e){return this._getType(e)===q.null?He(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Lt.create=(t,e)=>new Lt({innerType:t,typeName:B.ZodNullable,...H(e)});class Gr extends K{_parse(e){const{ctx:r}=this._processInputParams(e);let n=r.data;return r.parsedType===q.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}}Gr.create=(t,e)=>new Gr({innerType:t,typeName:B.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...H(e)});class Kr extends K{_parse(e){const{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Pr(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new dt(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new dt(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}Kr.create=(t,e)=>new Kr({innerType:t,typeName:B.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...H(e)});class Ei extends K{_parse(e){if(this._getType(e)!==q.nan){const n=this._getOrReturnCtx(e);return j(n,{code:N.invalid_type,expected:q.nan,received:n.parsedType}),U}return{status:"valid",value:e.data}}}Ei.create=t=>new Ei({typeName:B.ZodNaN,...H(t)});class to extends K{_parse(e){const{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}}class Es extends K{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?U:i.status==="dirty"?(r.dirty(),ar(i.value)):this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();{const s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?U:s.status==="dirty"?(r.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,r){return new Es({in:e,out:r,typeName:B.ZodPipeline})}}class Zr extends K{_parse(e){const r=this._def.innerType._parse(e),n=s=>(Gt(s)&&(s.value=Object.freeze(s.value)),s);return Pr(r)?r.then(s=>n(s)):n(r)}unwrap(){return this._def.innerType}}Zr.create=(t,e)=>new Zr({innerType:t,typeName:B.ZodReadonly,...H(e)});var B;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(B||(B={}));const Et=at.create,Ti=Kt.create,Ts=Kn.create,Md=Ur.create,pr=Jn.create;yt.create;const Dd=Xe.create,ot=fe.create,Os=Br.create,Fd=ks.create;zr.create;Ct.create;const mr=Vr.create,Sr=Hr.create,Jr=Rt.create;Wr.create;ut.create;Lt.create;const jd=["get","list","create","update","delete"],qd=ot({uid:Et(),token:mr(pr()).optional()}),Pd=ot({function:Jr(["get","exists"]).describe("Firestore function to mock"),path:Et().describe('Document path, e.g. "users/alice"'),result:Os([mr(pr()),Ts()]).describe("Document data for get, boolean for exists")}),$d=Fd("kind",[ot({kind:Sr("create")}),ot({kind:Sr("set"),merge:Ts()}),ot({kind:Sr("update")}),ot({kind:Sr("delete")})]),Ud=ot({limit:Ti().optional(),offset:Ti().optional(),orderBy:Et().optional()});ot({description:Et().describe("Human-readable description of what this test verifies"),expectation:Jr(["ALLOW","DENY"]).describe("Expected outcome"),method:Jr(jd).describe("Firestore method to test"),path:Et().describe('Document path, e.g. "users/alice"'),auth:Os([qd,Md()]).optional().describe("Auth context; null or omitted for unauthenticated"),data:mr(pr()).optional().describe("request.resource.data for write operations"),resource:mr(pr()).optional().describe("Existing document data (resource.data)"),functionMocks:Dd(Pd).optional().describe("Mock get()/exists() calls in rules"),query:Ud.optional().describe("request.query payload (list ops only): limit/offset/orderBy."),requestTime:Et().optional().describe("Override for request.time (ISO-8601). Defaults to wallclock."),writeMode:$d.optional().describe("Optional write-mode override; controls update merge semantics and getAfter() projection.")});function Mt(t){if(t.decision==="UNSUPPORTED")return;const r=t.decision==="ALLOW";let n="deny",s;if(r)n="allow",s=t.trace.find(C=>C.verdict==="ALLOW");else if(n="deny",s=t.trace.find(k=>k.verdict==="DENY"?!0:k.verdict==="ERROR"),s===void 0){const k=t.trace.length;k>0&&(s=t.trace[k-1])}if(s===void 0)return;const a={verdict:n};s.line!==void 0&&(a.line=s.line),s.col!==void 0&&(a.col=s.col,a.column=s.col),s.column!==void 0&&(a.col=s.column,a.column=s.column),s.file!==void 0&&(a.file=s.file),s.citation!==void 0&&(a.citation=s.citation),s.conditionText!==void 0&&(a.expression=s.conditionText),s.expressionTrace!==void 0&&(a.expressionTrace=s.expressionTrace);const v=a.line!==void 0,b=a.expression!==void 0,R=a.expressionTrace!==void 0;if(v||b||R)return a}function be(t){const e=[];for(const r of t.notes)e.push(r);for(const r of t.trace){const n=r.operations.join(","),s=`Rule #${r.ruleIndex} (${n})`;r.verdict==="ALLOW"?e.push(`${s} → ALLOW`):r.verdict==="DENY"?e.push(`${s} → deny`):r.verdict==="UNSUPPORTED"?e.push(`${s} → unsupported: ${r.message??""}`):e.push(`${s} → error: ${r.message??""}`)}return e.push(`Simulated: ${t.decision}`),e}ot({function:Jr(["get","exists"]).describe("Cross-service Firestore function to mock"),path:Et().describe('Firestore document path in collection/doc form, e.g. "users/alice"'),result:Os([mr(pr()),Ts()]).describe("Document fields for get, boolean for exists")});const Bd={atomic:`// @pyric-services cloud.firestore
|
|
496
496
|
// Atomic module — cross-document integrity for BATCH writes, via the
|
|
497
497
|
// get()/getAfter() pair. Firestore evaluates every write in a batch
|
|
498
498
|
// against rules, and getAfter() returns another document's POST-BATCH
|
|
@@ -1160,10 +1160,10 @@ service cloud.firestore {
|
|
|
1160
1160
|
}
|
|
1161
1161
|
}
|
|
1162
1162
|
`;class At{swallowAsyncRejections;subscribers=new Set;constructor(e=!1){this.swallowAsyncRejections=e}get hasSubscribers(){return this.subscribers.size>0}subscribe(e){return this.subscribers.add(e),()=>{this.subscribers.delete(e)}}emit(...e){for(const r of this.subscribers)try{const n=r(...e);this.swallowAsyncRejections&&n&&typeof n.then=="function"&&n.catch(()=>{})}catch{}}clear(){this.subscribers.clear()}}class af{denial=new At;request=new At(!0);write=new At(!0);delivery=new At;suppressed=new At;lifecycle=new At;snapshotError=new At;clear(){this.denial.clear(),this.request.clear(),this.write.clear(),this.delivery.clear(),this.suppressed.clear(),this.lifecycle.clear(),this.snapshotError.clear()}}class of{currentTrigger;run(e,r){const n=this.currentTrigger;this.currentTrigger=e;try{return r()}finally{this.currentTrigger=n}}current(){return this.currentTrigger}}class tn extends Error{code;simError;constructor(e){super(e.message),this.name="FirestoreError",this.code=e.code,this.simError=e}}const Pi=Symbol.for("pyric.firestore.activity-value-registry"),$i=globalThis,uo=$i[Pi]??($i[Pi]=new WeakMap);function lo(){let t=2166136261,e=2654435769,r=2246822507,n=3266489909;const s=i=>{t=Math.imul(t^i,16777619),e=Math.imul(e^i,2246822507),r=Math.imul(r^i,3266489909),n=Math.imul(n^i,668265263)};return{update:i=>{if(typeof i=="string")for(let a=0;a<i.length;a+=1){const o=i.charCodeAt(a);s(o&255),s(o>>>8)}else for(const a of i)s(a)},finish:()=>[t,e,r,n].map(i=>(i>>>0).toString(16).padStart(8,"0")).join("")}}function Ls(...t){const e=lo();for(const r of t)e.update(r);return e.finish()}function zp(t){return{type:"string-digest",length:t.length,digest:Ls("string\0",t)}}function cf(t,...e){return{type:`${t}-digest`,digest:Ls(`${t}\0`,...e)}}function Vp(t){return{type:"bytes-digest",length:t.byteLength,digest:Ls("bytes\0",t)}}function Ui(t){const e=lo(),r=(...s)=>{for(const i of s)e.update(i)},n=s=>{if(s===null){r("null;");return}switch(typeof s){case"string":r(`s${s.length}:`,s,";");return;case"number":r(`n${Object.is(s,-0)?"-0":String(s)};`);return;case"boolean":r(s?"b1;":"b0;");return;case"undefined":r("u;");return;case"bigint":r(`i${s.toString()};`);return;case"object":break;default:r(`x${typeof s};`);return}if(Array.isArray(s)){r(`a${s.length}[`);for(const o of s)n(o);r("];");return}const i=s,a=Object.keys(i).sort();r(`o${a.length}{`);for(const o of a)r(`k${o.length}:`,o,"="),n(i[o]);r("};")};return n(t),{type:"wire-value-digest",digest:e.finish()}}function is(t,e){uo.set(t,e)}function Hp(t){return uo.get(t)}class Wp{static serverTimestamp(){return{__type:"serverTimestamp"}}static increment(e){return{__type:"increment",value:e}}static arrayUnion(...e){return{__type:"arrayUnion",values:e}}static arrayRemove(...e){return{__type:"arrayRemove",values:e}}static delete(){return{__type:"deleteField"}}}class Vt{seconds;nanoseconds;constructor(e,r){this.seconds=e,this.nanoseconds=r,is(this,cf("timestamp",String(e),"\0",String(r))),Rs(this,Object.freeze({type:"timestamp",seconds:e,nanoseconds:r}),()=>new Vt(e,r))}static now(){return Vt.fromMillis(Date.now())}static fromDate(e){return Vt.fromMillis(e.getTime())}static fromMillis(e){const r=Math.floor(e/1e3),n=Math.floor((e-r*1e3)*1e6);return new Vt(r,n)}toDate(){return new Date(this.toMillis())}toMillis(){return this.seconds*1e3+this.nanoseconds/1e6}isEqual(e){return e.seconds===this.seconds&&e.nanoseconds===this.nanoseconds}toString(){return`Timestamp(seconds=${this.seconds}, nanoseconds=${this.nanoseconds})`}toJSON(){return{type:"firestore/timestamp/1.0",seconds:this.seconds,nanoseconds:this.nanoseconds}}valueOf(){const r=this.seconds- -62135596800,n=String(r).padStart(12,"0"),s=String(this.nanoseconds).padStart(9,"0");return`${n}.${s}`}}function as(t){return t instanceof _e?new Vt(t.seconds,t.nanos):t instanceof Ae||t instanceof lt||t instanceof Qt?t:Array.isArray(t)?t.map(as):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).map(([e,r])=>[e,as(r)])):t}function ho(t){return as(t)}const uf=/[*~/[\]]/,lf=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class rn{_internalPath;constructor(...e){if(Array.isArray(e[0]))throw new Error("The FieldPath constructor no longer supports an array as its first argument. Please unpack your array and call FieldPath() with individual arguments.");if(e.length===0)throw new Error('Function "FieldPath()" requires at least 1 argument.');e.forEach((r,n)=>{if(typeof r!="string")throw new Error(`Element at index ${n} is not a valid string.`);if(r.length===0)throw new Error(`Element at index ${n} should not be an empty string.`)}),this._internalPath={segments:[...e],offset:0,len:e.length}}static DOCUMENT_ID=new rn("__name__");static documentId(){return rn.DOCUMENT_ID}isEqual(e){const r=fo(e),n=this._internalPath.segments;return n.length===r.length&&n.every((s,i)=>s===r[i])}toString(){return this._internalPath.segments.map(e=>lf.test(e)?e:`\`${e.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}\``).join(".")}}function er(t){return new Error(`Value for argument "field" is not a valid field path. ${t}`)}function fo(t){if(t instanceof rn)return t._internalPath.segments;if(typeof t=="object"&&t!==null){const e=t._internalPath;if(Array.isArray(e?.segments)&&e.segments.every(r=>typeof r=="string"))return[...e.segments]}if(t===void 0)throw er("The path cannot be omitted.");if(typeof t!="string")throw er("Paths can only be specified as strings or via a FieldPath object.");if(t.includes(".."))throw er('Paths must not contain ".." in them.');if(t.startsWith(".")||t.endsWith("."))throw er('Paths must not start or end with ".".');if(t.length===0||uf.test(t))throw er(`Paths can't be empty and must not contain
|
|
1163
|
-
"*~/[]".`);return t.split(".")}function df(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function po(t,e){const r=fo(e);let n=t;for(const s of r){if(!df(n))return;n=Object.prototype.hasOwnProperty.call(n,s)?n[s]:void 0}return n}const Zt=Object.freeze({hasPendingWrites:!1,fromCache:!1}),Bi=Object.freeze({hasPendingWrites:!0,fromCache:!1});function mo(t){const e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}function tr(t,e,r=Zt){const n={id:mo(t),path:t},s=e!==null,i=s?ho(e):void 0;return{id:n.id,ref:n,metadata:r,exists:()=>s,data:()=>i,get:a=>po(i,a)}}function go(t,e,r=Zt){const n={id:mo(t),path:t},s=ho(e);return{id:n.id,ref:n,metadata:r,exists:()=>!0,data:()=>s,get:i=>po(s,i)}}function rr(t,e,r,n,s=Zt){const i=e.map(u=>go(u.path,u.data,s)),a=n?hf(n,e,i,s):i.map((u,f)=>({type:"added",doc:u,oldIndex:-1,newIndex:f}));let o=null,c=null;return{query:t,metadata:s,size:i.length,empty:i.length===0,docs:i,forEach(u){for(const f of i)u(f)},docChanges(u){const f=!!u?.includeMetadataChanges;if(f&&r.excludesMetadataChanges)throw new Error("To include metadata changes with your document changes, you must also pass { includeMetadataChanges: true } to onSnapshot().");return f?(c||(c=a.slice()),c):(o||(o=a.slice()),o)}}}function hf(t,e,r,n=Zt){const s=new Map;t.forEach((o,c)=>s.set(o.path,c));const i=new Map;e.forEach((o,c)=>i.set(o.path,c));const a=[];for(let o=0;o<t.length;o++){const c=t[o];i.has(c.path)||a.push({type:"removed",doc:go(c.path,c.data,n),oldIndex:o,newIndex:-1})}for(let o=0;o<e.length;o++){const c=e[o],u=s.get(c.path);if(u===void 0)a.push({type:"added",doc:r[o],oldIndex:-1,newIndex:o});else{const f=t[u].data;JSON.stringify(f)!==JSON.stringify(c.data)&&a.push({type:"modified",doc:r[o],oldIndex:u,newIndex:o})}}return a}function zi(t,e){return t===null&&e===null?!0:t===null||e===null?!1:JSON.stringify(t)===JSON.stringify(e)}function ff(t,e){const r=`${e}/`;for(const n of t){if(!n.startsWith(r))continue;const s=n.slice(r.length);if(s.length>0&&!s.includes("/"))return!0}return!1}let xn=0;function lr(){return xn=xn+1>>>0,`req-${xn.toString(36)}-${Math.random().toString(36).slice(2,7)}`}function pf(t,e){const r=e==="allow";let n;for(const s of t){const i=/^Rule #(\d+) \(([^)]+)\) → (ALLOW|deny|unsupported)/.exec(s);if(!i)continue;const a={ruleIndex:Number(i[1]),operations:i[2].split(",").map(o=>o.trim())};if(r&&i[3]==="ALLOW")return a;n=a}return n}function un(t){const e={kind:"request",id:lr(),at:t.at,evalMs:t.evalMs,method:t.method,path:t.path,auth:t.auth?{uid:t.auth.uid,...t.auth.token?{token:t.auth.token}:{}}:null,result:t.result,reasons:t.debugMessages,origin:t.origin};t.resourceData!==void 0&&(e.request={resourceData:t.resourceData}),t.resourceBefore!==void 0&&(e.resourceBefore=t.resourceBefore),t.resourceAfter!==void 0&&(e.resourceAfter=t.resourceAfter);const r=pf(t.debugMessages,t.result);return r&&(e.matchedRule=r),t.result!=="unsupported"&&t.evaluatedRule&&(e.evaluatedRule=t.evaluatedRule),t.groupId!==void 0&&(e.groupId=t.groupId,t.origin==="batch"?e.groupKind="batch":t.origin==="transaction"&&(e.groupKind="transaction")),t.triggeredBy!==void 0&&(e.triggeredBy=t.triggeredBy),t.detail!==void 0&&(e.detail=t.detail),t.provenance!==void 0&&Object.assign(e,t.provenance),e}class mf{events;triggerScope;host;snapshotListeners=new Map;nextListenerId=0;deliveryQueue=[];deliveryScheduled=!1;constructor(e,r,n){this.events=e,this.triggerScope=r,this.host=n}emitSnapshotDelivery(e){if(!this.events.delivery.hasSubscribers)return;const r={kind:"snapshot_delivery",id:lr().replace(/^req-/,"snd-"),at:Date.now(),listenerId:e.listenerId,target:e.target,auth:e.auth?{uid:e.auth.uid,...e.auth.token?{token:e.auth.token}:{}}:null,addedCount:e.addedCount,modifiedCount:e.modifiedCount,removedCount:e.removedCount,size:e.size,...e.sample?{sample:e.sample}:{},...e.triggeredBy?{triggeredBy:e.triggeredBy}:{}};this.events.delivery.emit(r)}emitSnapshotSuppressed(e){if(!this.events.suppressed.hasSubscribers)return;const r={kind:"snapshot_suppressed",id:lr().replace(/^req-/,"sup-"),at:Date.now(),listenerId:e.listenerId,target:e.target,auth:e.auth?{uid:e.auth.uid,...e.auth.token?{token:e.auth.token}:{}}:null,reason:"no-op",...e.triggeredBy?{triggeredBy:e.triggeredBy}:{}};this.events.suppressed.emit(r)}emitLifecycle(e){if(!this.events.lifecycle.hasSubscribers)return;const r={kind:e.phase,id:lr().replace(/^req-/,"lc-"),at:Date.now(),listenerId:e.listenerId,target:e.target,auth:e.auth?{uid:e.auth.uid,...e.auth.token?{token:e.auth.token}:{}}:null};this.events.lifecycle.emit(r)}emitSnapshotError(e,r,n){this.events.snapshotError.emit(e,r,n)}addSnapshotListener(e,r,n={},s=null,i,a=!1,o=!1,c){const u=String(this.nextListenerId++),f={id:u,target:e,callback:r,auth:s,bypassRules:o,followsCurrentUser:a,...c?{authScope:c}:{},options:n,currentSnapshot:void 0,errored:!1,...i?{errorCallback:i}:{}};return this.snapshotListeners.set(u,f),this.emitLifecycle({phase:"listener_attach",listenerId:u,target:e.kind==="doc"?{kind:"doc",path:e.path}:{kind:"query",collection:e.collection,...e.constraints?.activityQuery?{query:e.constraints.activityQuery}:{}},auth:s}),this.scheduleDelivery(()=>{this.snapshotListeners.has(u)&&this.fireInitialSnapshot(f)}),()=>{const l=this.snapshotListeners.has(u);this.snapshotListeners.delete(u),l&&this.emitLifecycle({phase:"listener_detach",listenerId:u,target:e.kind==="doc"?{kind:"doc",path:e.path}:{kind:"query",collection:e.collection,...e.constraints?.activityQuery?{query:e.constraints.activityQuery}:{}},auth:s})}}fireInitialSnapshot(e){if(e.target.kind==="doc"){const s=this.host.silentReadDoc(e.target.path,e.auth,e.bypassRules);if(!s.allowed){this.markErrored(e,s.error);return}const i=tr(e.target.path,s.data);e.currentSnapshot=i,e.currentDocData=s.data;try{e.callback(i)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"doc",path:e.target.path},auth:e.auth,addedCount:s.data!==null?1:0,modifiedCount:0,removedCount:0,size:s.data!==null?1:0,sample:{docs:[{path:e.target.path,data:s.data}]}});return}const r=this.host.silentReadCollection(e.target.collection,e.auth,e.target.constraints,e.bypassRules);if(!r.allowed){this.markErrored(e,r.error);return}const n=rr({path:e.target.collection},r.docs,{excludesMetadataChanges:!e.options.includeMetadataChanges});e.currentSnapshot=n,e.currentDocs=r.docs;try{e.callback(n)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"query",collection:e.target.collection},auth:e.auth,addedCount:r.docs.length,modifiedCount:0,removedCount:0,size:r.docs.length,sample:{docs:r.docs.map(s=>({path:s.path,data:s.data}))}})}scheduleDelivery(e){this.deliveryQueue.push(e),!this.deliveryScheduled&&(this.deliveryScheduled=!0,queueMicrotask(()=>this.drainDeliveries()))}scheduleTriggeredDelivery(e,r){this.scheduleDelivery(()=>this.triggerScope.run(e,r))}drainDeliveries(){for(this.deliveryScheduled=!1;this.deliveryQueue.length>0;)this.deliveryQueue.shift()()}flushListeners(){this.drainDeliveries()}notifyListenersForPaths(e){if(e.size===0||this.snapshotListeners.size===0)return;const r=this.triggerScope.current(),n=Array.from(this.snapshotListeners.values());for(const s of n)this.scheduleTriggeredDelivery(r,()=>{this.snapshotListeners.has(s.id)&&(s.errored||(s.target.kind==="doc"?this.notifyDocListener(s,e):this.notifyQueryListener(s,e)))})}notifyDocListener(e,r){if(e.target.kind!=="doc"||!r.has(e.target.path))return;const n=this.host.silentReadDoc(e.target.path,e.auth,e.bypassRules);if(!n.allowed){this.markErrored(e,n.error);return}const s=e.currentDocData??null;if(zi(s,n.data)){this.emitSnapshotSuppressed({listenerId:e.id,target:{kind:"doc",path:e.target.path},auth:e.auth,...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}});return}const i=e.target.path,a=tr(i,n.data,Bi);e.currentSnapshot=a,e.currentDocData=n.data;const o=s!==null,c=n.data!==null,u=!o&&c?1:0,f=o&&!c?1:0,l=o&&c?1:0;try{e.callback(a)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"doc",path:i},auth:e.auth,addedCount:u,modifiedCount:l,removedCount:f,size:c?1:0,sample:{docs:[{path:i,data:n.data}]},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),this.scheduleDocMetadataAck(e,i,n.data)}scheduleDocMetadataAck(e,r,n){e.options.includeMetadataChanges&&this.scheduleTriggeredDelivery(this.triggerScope.current(),()=>{if(!this.snapshotListeners.has(e.id)||e.errored)return;const s=tr(r,n,Zt);e.currentSnapshot=s;try{e.callback(s)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"doc",path:r},auth:e.auth,addedCount:0,modifiedCount:0,removedCount:0,size:n!==null?1:0,sample:{docs:[{path:r,data:n}]},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}})})}notifyQueryListener(e,r){if(e.target.kind!=="query"||!ff(r,e.target.collection))return;const n=this.host.silentReadCollection(e.target.collection,e.auth,e.target.constraints,e.bypassRules);if(!n.allowed){this.markErrored(e,n.error);return}const s=e.target.collection,i=e.currentDocs??[],a=rr({path:s},n.docs,{excludesMetadataChanges:!e.options.includeMetadataChanges},i,Bi),o=a.docChanges();if(o.length===0){if(e.options.includeMetadataChanges){e.currentSnapshot=a,e.currentDocs=n.docs;try{e.callback(a)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"query",collection:s},auth:e.auth,addedCount:0,modifiedCount:0,removedCount:0,size:n.docs.length,sample:{docs:n.docs.map(l=>({path:l.path,data:l.data}))},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),this.scheduleQueryMetadataAck(e,s,n.docs);return}this.emitSnapshotSuppressed({listenerId:e.id,target:{kind:"query",collection:s},auth:e.auth,...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}});return}e.currentSnapshot=a,e.currentDocs=n.docs;let c=0,u=0,f=0;for(const l of o)l.type==="added"?c++:l.type==="modified"?u++:l.type==="removed"&&f++;try{e.callback(a)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"query",collection:s},auth:e.auth,addedCount:c,modifiedCount:u,removedCount:f,size:n.docs.length,sample:{docs:n.docs.map(l=>({path:l.path,data:l.data}))},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),this.scheduleQueryMetadataAck(e,s,n.docs)}scheduleQueryMetadataAck(e,r,n){e.options.includeMetadataChanges&&this.scheduleTriggeredDelivery(this.triggerScope.current(),()=>{if(!this.snapshotListeners.has(e.id)||e.errored)return;const s=rr({path:r},n,{excludesMetadataChanges:!1},n,Zt);e.currentSnapshot=s;try{e.callback(s)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"query",collection:r},auth:e.auth,addedCount:0,modifiedCount:0,removedCount:0,size:n.length,sample:{docs:n.map(i=>({path:i.path,data:i.data}))},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}})})}markErrored(e,r){if(e.errored=!0,this.emitSnapshotError(r,e.target,e.id),!!e.errorCallback)try{e.errorCallback(r)}catch{}}reEvaluateAllListeners(){if(this.snapshotListeners.size===0)return;const e=Array.from(this.snapshotListeners.values());for(const r of e)this.snapshotListeners.has(r.id)&&(r.target.kind==="doc"?this.reEvaluateDocListener(r):this.reEvaluateQueryListener(r))}reevaluateLiveListeners(e,r){if(this.snapshotListeners.size===0)return;const n=Array.from(this.snapshotListeners.values());for(const s of n)s.followsCurrentUser&&s.authScope===r&&this.snapshotListeners.has(s.id)&&(s.auth=e,s.target.kind==="doc"?this.reEvaluateDocListener(s):this.reEvaluateQueryListener(s))}reEvaluateDocListener(e){if(e.target.kind!=="doc")return;const r=this.host.silentReadDoc(e.target.path,e.auth,e.bypassRules);if(!r.allowed){if(e.errored)return;this.markErrored(e,r.error);return}if(e.errored){e.errored=!1;const i=tr(e.target.path,r.data);e.currentSnapshot=i,e.currentDocData=r.data;try{e.callback(i)}catch{}return}const n=e.currentDocData??null;if(zi(n,r.data))return;const s=tr(e.target.path,r.data);e.currentSnapshot=s,e.currentDocData=r.data;try{e.callback(s)}catch{}}reEvaluateQueryListener(e){if(e.target.kind!=="query")return;const r=this.host.silentReadCollection(e.target.collection,e.auth,e.target.constraints,e.bypassRules);if(!r.allowed){if(e.errored)return;this.markErrored(e,r.error);return}if(e.errored){e.errored=!1;const a=rr({path:e.target.collection},r.docs,{excludesMetadataChanges:!e.options.includeMetadataChanges});e.currentSnapshot=a,e.currentDocs=r.docs;try{e.callback(a)}catch{}return}const n=e.currentDocs??[],s=rr({path:e.target.collection},r.docs,{excludesMetadataChanges:!e.options.includeMetadataChanges},n);if(s.docChanges().length!==0){e.currentSnapshot=s,e.currentDocs=r.docs;try{e.callback(s)}catch{}}}getSnapshotListenerCount(){return this.snapshotListeners.size}dispose(){this.snapshotListeners.clear(),this.deliveryQueue.length=0,this.deliveryScheduled=!1}}class gf{eventLog;host;constructor(e,r){this.eventLog=e,this.host=r}undo(){const e=this.eventLog.popLastWrite();if(!e)return null;if(e.priorDocs)this.host.state.restorePaths(e.priorDocs);else if(e.snapshot)this.host.state.restore(e.snapshot);else return null;return e}redo(){const e=this.eventLog.popLastUndo();if(!e)return null;const r=e.type==="batch"&&e.operations?e.operations.map(o=>o.path):e.path?[e.path]:[],n=!!e.snapshot,s=n?void 0:this.host.capturePriors(r),i=n?this.host.state.snapshot():void 0;if(e.type==="batch"&&e.operations)for(const o of e.operations)o.allowed&&this.host.applyWrite(o.method,o.path,o.data);else e.allowed&&this.host.applyWrite(e.method,e.path,e.data);const a=this.eventLog.append({...e,snapshot:i,priorDocs:s},!0);return{allowed:e.allowed,debugMessages:["Redo: "+(e.allowed?"applied":"skipped (was denied)")],event:a}}getEvents(){return this.eventLog.getEvents()}getEventCount(){return this.eventLog.size()}}class yf{currentSource;parsedCache=null;constructor(e){this.currentSource=e}get source(){return this.currentSource}set(e){this.currentSource=e}ast(){return this.parsedCache?.source!==this.currentSource&&(this.parsedCache={source:this.currentSource,ast:_s(this.currentSource)}),this.parsedCache.ast}}function he(t,e,r){const n={code:t,message:e};return r!==void 0&&(r.request!==void 0&&(n.request=r.request),r.resource!==void 0&&(n.resource=r.resource),r.remediation!==void 0&&(n.remediation=r.remediation),r.query!==void 0&&(n.query=r.query),r.rule!==void 0&&(n.rule=r.rule)),n}function ln(t,e,r){const n=t.get(e.path),s=e.method==="set"?n!==null?"update":"create":e.method;let i=e.data;if(e.method==="get"||e.method==="list")i=void 0;else if(e.method==="update"&&n&&e.data){const{writes:a,deletedKeys:o}=xt(e.data),c={...n,...a};for(const u of o)delete c[u];i=c}else e.data&&(i=xt(e.data).writes);return{description:`${e.method} ${e.path}`,expectation:"ALLOW",method:s,path:e.path,auth:e.auth?{uid:e.auth.uid,token:e.auth.token}:null,data:i,resource:n??void 0,...r?{requestTime:rf(r)}:{}}}function yo(t,e,r,n,s,i){if(s){const a=n.map(o=>nf(o.description));return{success:!0,data:{passed:a.length,failed:0,unsupported:0,results:a}}}return r.simulate(e.source,n,{getDoc:a=>t.get(a),...i?{batchProjection:i}:{}})}class vf{events;rules;simulator;host;eventLog;constructor(e,r,n,s,i){this.events=e,this.rules=r,this.simulator=n,this.host=s,this.eventLog=i}get state(){return this.host.state}emitRequest(e){this.events.request.hasSubscribers&&this.events.request.emit(un(e))}emitDenial(e){this.events.denial.emit(e)}execute(e){const{method:r,path:n,auth:s,bypassRules:i}=e;let a;i===!0&&(a={admin:!0});const c=_e.fromMillis(Date.now()),u=ln(this.state,e,c),f=Date.now(),l=performance.now(),p=yo(this.state,this.rules,this.simulator,[u],i),y=performance.now()-l;let v=null;if(s!==void 0&&s!==null&&(v={uid:s.uid}),p.success===!0===!1){const d=this.eventLog.append({type:"single",method:r,path:n,auth:v,allowed:!1,debugMessages:[`Simulation error: ${p.error.message}`]}),g={at:f,evalMs:y,method:r,path:n,auth:s,result:"deny",debugMessages:[`Simulation error: ${p.error.message}`],origin:"user"};return a!==void 0&&(g.detail=a),this.emitRequest(g),{allowed:!1,debugMessages:[p.error.message],event:d}}const k=p.data.results[0];if(k.state==="UNSUPPORTED"){const d={at:f,evalMs:y,method:r,path:n,auth:s,result:"unsupported",debugMessages:be(k),origin:"user"};throw a!==void 0&&(d.detail=a),this.emitRequest(d),new yr(vr(r,n,be(k)),r,n,be(k))}const L=k.state==="PASSED";let $;L&&(r==="get"?$=this.state.get(n):$=this.state.list(n));const S=this.eventLog.append({type:"single",method:r,path:n,auth:v,allowed:L,debugMessages:be(k)}),T={allowed:L,debugMessages:be(k),event:S};L&&(T.data=$);const _=Mt(k);if(L===!1){const g={request:{method:r,path:n,auth:s}};if(r==="get"){const E=this.state.get(n),O=E!==null;g.resource={data:E,exists:O}}_!==void 0&&(g.rule=_),T.error=he("permission-denied",`${r} ${n} denied by rules`,g),this.emitDenial(T.error)}let b="deny";L&&(b="allow");const A={at:f,evalMs:y,method:r,path:n,auth:s,result:b,debugMessages:be(k),evaluatedRule:_,origin:"user"};if(r==="get"){const d=this.state.get(n),g=d!==null;A.resourceBefore={data:d,exists:g}}return a!==void 0&&(A.detail=a),this.emitRequest(A),T}}function vo(t){const e=new Map,r=new Set;for(const n of t)e.has(n.name)&&r.add(n.name),e.set(n.name,n);return{functions:e,ambiguousNames:r}}function bo(t,e,r,n=bf){const s=new Set;return{pathInvariant:!kr(t,e,r,n,new Set,new Set,s),requiredFunctions:s}}function kr(t,e,r,n,s,i,a){const o=c=>kr(c,e,r,n,s,i,a);switch(t.type){case"literal":return!1;case"identifier":return!s.has(t.name)&&(e.has(t.name)||t.name==="request");case"memberAccess":return t.object.type==="identifier"&&t.object.name==="request"?!Vi.has(t.property):o(t.object);case"methodCall":return o(t.object)||t.args.some(o);case"bracketAccess":return t.object.type==="identifier"&&t.object.name==="request"?!(t.index.type==="literal"&&typeof t.index.value=="string"&&Vi.has(t.index.value)):o(t.object)||o(t.index);case"sliceAccess":return o(t.object)||o(t.start)||o(t.end);case"binaryOp":return o(t.left)||o(t.right);case"unaryOp":return o(t.operand);case"ternary":return o(t.condition)||o(t.consequent)||o(t.alternate);case"inExpr":return o(t.element)||o(t.collection);case"isExpr":return o(t.value);case"listLiteral":return t.elements.some(o);case"mapLiteral":return t.entries.some(c=>o(c.key)||o(c.value));case"pathLiteral":return t.segments.some(c=>typeof c!="string"&&o(c));case"functionCall":{if(t.args.some(o)||n.has(t.name))return!0;const c=r.get(t.name);if(!c)return!1;if(a.add(c.name),i.has(c.name))return!0;const u=new Set(i).add(c.name),f=new Set(c.parameters);for(const l of c.lets){if(kr(l.value,e,r,n,f,u,a))return!0;f.add(l.name)}return kr(c.body,e,r,n,f,u,a)}}}const Vi=new Set(["auth","method","query","time"]),bf=new Set;function wf(t){if(!t)return null;const e=[...t.functions??[],...t.service.functions??[],...t.service.match.functions],r=new Set,n=t.service.match.children.flatMap(i=>{const a=Sf(i,e,r);return a?[a]:[]});if(n.length===0)return null;const s=i=>i?.filter(a=>r.has(a.name));return{...t,functions:s(t.functions),service:{...t.service,functions:s(t.service.functions),match:{...t.service.match,functions:s(t.service.match.functions)??[],children:n}}}}function Sf(t,e,r){const n=t.path.segments[0];if(t.path.segments.length!==1||n?.type!=="recursive")return null;const s=vo([...e,...t.functions]),i=t.allows.filter(a=>{if(!a.operations.some(c=>c==="list"||c==="read"))return!1;const o=bo(a.condition,new Set([n.name]),s.functions,s.ambiguousNames);if(o.pathInvariant)for(const c of o.requiredFunctions)r.add(c);return o.pathInvariant});return i.length===0?null:{...t,functions:t.functions.filter(a=>r.has(a.name)),allows:i,children:[]}}function _f(t,e,r,n,s){if(t!==null===!1)return{kind:"no-rule"};const a=e.split("/").filter(w=>w.length>0),o=[...t.functions??[],...t.service.functions??[],...t.service.match.functions],c=[];for(const w of t.service.match.children)c.push(...jr(w,a,o));if(c.length===0)return{kind:"no-rule"};const f=[],l=new Set;let p=0;for(const w of c){const R=vo(w.functions),C=R.functions;for(const k of w.block.allows){if(k.operations.some(_=>_==="list"?!0:_==="read")===!1)continue;if(p++,bo(k.condition,new Set(w.candidateVariables),C,R.ambiguousNames).pathInvariant===!0===!1){f.push({reason:"list rule depends on the candidate document path",residual:{missing:[],mismatched:[]},rule:k});continue}const S=td(k.condition,n,C,r?.uid);S.provable===!0?l.add(k):f.push({reason:S.reason,residual:S.residual,rule:k})}}if(p===0)return{kind:"no-rule"};if(l.size===0){const w=f[0];let R="list rule depends on per-document data the query cannot guarantee",C={missing:[],mismatched:[]},k;if(w!==void 0&&(R=w.reason,C=w.residual,w.rule!==void 0)){const T=w.rule,_=ye(T.condition);if(k={verdict:"deny",expression:_},T.loc!==void 0){const A=T.loc;let I="";s!==void 0&&(I=s);const d=Ga(I,A.line,A.col,A.file,_);d!==void 0?(k.line=d.line,k.col=d.col,k.column=d.col,k.file=d.file,k.citation=d.citation,d.expression!==void 0&&(k.expression=d.expression)):(k.line=A.line,k.col=A.col,k.column=A.col,A.file!==void 0?(k.file=A.file,k.citation=`${A.file}:${A.line}:${A.col}`):(k.file="firestore.rules",k.citation=`firestore.rules:${A.line}:${A.col}`))}}const L={kind:"unprovable",reason:R,residual:C};return k!==void 0&&(L.rule=k),L}return{kind:"provable",evaluationAst:Af(t,l),syntheticResource:If(n)}}function Af(t,e){const r=n=>({...n,allows:n.allows.filter(s=>e.has(s)),children:n.children.map(r)});return{...t,service:{...t.service,match:r(t.service.match)}}}function If(t){const e={};for(const r of t.where??[])r.op==="=="&&(e[r.field]=r.value);return e}function xf(t){const e=[];for(const n of t.missing)n.fromAuthUid?e.push(` .where('${n.field}', '==', request.auth.uid) // request.auth.uid is ${JSON.stringify(n.expectedValue)}`):e.push(` .where('${n.field}', '==', ${JSON.stringify(n.expectedValue)})`);for(const n of t.mismatched)e.push(` .where('${n.field}', '==', ${JSON.stringify(n.expectedValue)}) // the query pins ${JSON.stringify(n.actualValue)}, but the rule requires ${JSON.stringify(n.expectedValue)}`);return e.length===0?void 0:`The list rule requires per-document equalities the query does not guarantee. Add the matching where(...) constraint(s) so every returned document satisfies the rule:
|
|
1163
|
+
"*~/[]".`);return t.split(".")}function df(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function po(t,e){const r=fo(e);let n=t;for(const s of r){if(!df(n))return;n=Object.prototype.hasOwnProperty.call(n,s)?n[s]:void 0}return n}const Zt=Object.freeze({hasPendingWrites:!1,fromCache:!1}),Bi=Object.freeze({hasPendingWrites:!0,fromCache:!1});function mo(t){const e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}function tr(t,e,r=Zt){const n={id:mo(t),path:t},s=e!==null,i=s?ho(e):void 0;return{id:n.id,ref:n,metadata:r,exists:()=>s,data:()=>i,get:a=>po(i,a)}}function go(t,e,r=Zt){const n={id:mo(t),path:t},s=ho(e);return{id:n.id,ref:n,metadata:r,exists:()=>!0,data:()=>s,get:i=>po(s,i)}}function rr(t,e,r,n,s=Zt){const i=e.map(u=>go(u.path,u.data,s)),a=n?hf(n,e,i,s):i.map((u,f)=>({type:"added",doc:u,oldIndex:-1,newIndex:f}));let o=null,c=null;return{query:t,metadata:s,size:i.length,empty:i.length===0,docs:i,forEach(u){for(const f of i)u(f)},docChanges(u){const f=!!u?.includeMetadataChanges;if(f&&r.excludesMetadataChanges)throw new Error("To include metadata changes with your document changes, you must also pass { includeMetadataChanges: true } to onSnapshot().");return f?(c||(c=a.slice()),c):(o||(o=a.slice()),o)}}}function hf(t,e,r,n=Zt){const s=new Map;t.forEach((o,c)=>s.set(o.path,c));const i=new Map;e.forEach((o,c)=>i.set(o.path,c));const a=[];for(let o=0;o<t.length;o++){const c=t[o];i.has(c.path)||a.push({type:"removed",doc:go(c.path,c.data,n),oldIndex:o,newIndex:-1})}for(let o=0;o<e.length;o++){const c=e[o],u=s.get(c.path);if(u===void 0)a.push({type:"added",doc:r[o],oldIndex:-1,newIndex:o});else{const f=t[u].data;JSON.stringify(f)!==JSON.stringify(c.data)&&a.push({type:"modified",doc:r[o],oldIndex:u,newIndex:o})}}return a}function zi(t,e){return t===null&&e===null?!0:t===null||e===null?!1:JSON.stringify(t)===JSON.stringify(e)}function ff(t,e){const r=`${e}/`;for(const n of t){if(!n.startsWith(r))continue;const s=n.slice(r.length);if(s.length>0&&!s.includes("/"))return!0}return!1}let xn=0;function lr(){return xn=xn+1>>>0,`req-${xn.toString(36)}-${Math.random().toString(36).slice(2,7)}`}function pf(t,e){const r=e==="allow";let n;for(const s of t){const i=/^Rule #(\d+) \(([^)]+)\) → (ALLOW|deny|unsupported)/.exec(s);if(!i)continue;const a={ruleIndex:Number(i[1]),operations:i[2].split(",").map(o=>o.trim())};if(r&&i[3]==="ALLOW")return a;n=a}return n}function un(t){const e={kind:"request",id:lr(),at:t.at,evalMs:t.evalMs,method:t.method,path:t.path,auth:t.auth?{uid:t.auth.uid,...t.auth.token?{token:t.auth.token}:{}}:null,result:t.result,reasons:t.debugMessages,origin:t.origin};t.resourceData!==void 0&&(e.request={resourceData:t.resourceData}),t.resourceBefore!==void 0&&(e.resourceBefore=t.resourceBefore),t.resourceAfter!==void 0&&(e.resourceAfter=t.resourceAfter);const r=pf(t.debugMessages,t.result);return r&&(e.matchedRule=r),t.result!=="unsupported"&&t.evaluatedRule&&(e.evaluatedRule=t.evaluatedRule),t.groupId!==void 0&&(e.groupId=t.groupId,t.origin==="batch"?e.groupKind="batch":t.origin==="transaction"&&(e.groupKind="transaction")),t.triggeredBy!==void 0&&(e.triggeredBy=t.triggeredBy),t.detail!==void 0&&(e.detail=t.detail),t.provenance!==void 0&&Object.assign(e,t.provenance),e}class mf{events;triggerScope;host;snapshotListeners=new Map;nextListenerId=0;deliveryQueue=[];deliveryScheduled=!1;constructor(e,r,n){this.events=e,this.triggerScope=r,this.host=n}emitSnapshotDelivery(e){if(!this.events.delivery.hasSubscribers)return;const r={kind:"snapshot_delivery",id:lr().replace(/^req-/,"snd-"),at:Date.now(),listenerId:e.listenerId,target:e.target,auth:e.auth?{uid:e.auth.uid,...e.auth.token?{token:e.auth.token}:{}}:null,addedCount:e.addedCount,modifiedCount:e.modifiedCount,removedCount:e.removedCount,size:e.size,...e.sample?{sample:e.sample}:{},...e.triggeredBy?{triggeredBy:e.triggeredBy}:{}};this.events.delivery.emit(r)}emitSnapshotSuppressed(e){if(!this.events.suppressed.hasSubscribers)return;const r={kind:"snapshot_suppressed",id:lr().replace(/^req-/,"sup-"),at:Date.now(),listenerId:e.listenerId,target:e.target,auth:e.auth?{uid:e.auth.uid,...e.auth.token?{token:e.auth.token}:{}}:null,reason:"no-op",...e.triggeredBy?{triggeredBy:e.triggeredBy}:{}};this.events.suppressed.emit(r)}emitLifecycle(e){if(!this.events.lifecycle.hasSubscribers)return;const r={kind:e.phase,id:lr().replace(/^req-/,"lc-"),at:Date.now(),listenerId:e.listenerId,target:e.target,auth:e.auth?{uid:e.auth.uid,...e.auth.token?{token:e.auth.token}:{}}:null};this.events.lifecycle.emit(r)}emitSnapshotError(e,r,n){this.events.snapshotError.emit(e,r,n)}addSnapshotListener(e,r,n={},s=null,i,a=!1,o=!1,c){const u=String(this.nextListenerId++),f={id:u,target:e,callback:r,auth:s,bypassRules:o,followsCurrentUser:a,...c?{authScope:c}:{},options:n,currentSnapshot:void 0,errored:!1,...i?{errorCallback:i}:{}};return this.snapshotListeners.set(u,f),this.emitLifecycle({phase:"listener_attach",listenerId:u,target:e.kind==="doc"?{kind:"doc",path:e.path}:{kind:"query",collection:e.collection,...e.constraints?.activityQuery?{query:e.constraints.activityQuery}:{}},auth:s}),this.scheduleDelivery(()=>{this.snapshotListeners.has(u)&&this.fireInitialSnapshot(f)}),()=>{const l=this.snapshotListeners.has(u);this.snapshotListeners.delete(u),l&&this.emitLifecycle({phase:"listener_detach",listenerId:u,target:e.kind==="doc"?{kind:"doc",path:e.path}:{kind:"query",collection:e.collection,...e.constraints?.activityQuery?{query:e.constraints.activityQuery}:{}},auth:s})}}fireInitialSnapshot(e){if(e.target.kind==="doc"){const s=this.host.silentReadDoc(e.target.path,e.auth,e.bypassRules);if(!s.allowed){this.markErrored(e,s.error);return}const i=tr(e.target.path,s.data);e.currentSnapshot=i,e.currentDocData=s.data;try{e.callback(i)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"doc",path:e.target.path},auth:e.auth,addedCount:s.data!==null?1:0,modifiedCount:0,removedCount:0,size:s.data!==null?1:0,sample:{docs:[{path:e.target.path,data:s.data}]}});return}const r=this.host.silentReadCollection(e.target.collection,e.auth,e.target.constraints,e.bypassRules);if(!r.allowed){this.markErrored(e,r.error);return}const n=rr({path:e.target.collection},r.docs,{excludesMetadataChanges:!e.options.includeMetadataChanges});e.currentSnapshot=n,e.currentDocs=r.docs;try{e.callback(n)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"query",collection:e.target.collection},auth:e.auth,addedCount:r.docs.length,modifiedCount:0,removedCount:0,size:r.docs.length,sample:{docs:r.docs.map(s=>({path:s.path,data:s.data}))}})}scheduleDelivery(e){this.deliveryQueue.push(e),!this.deliveryScheduled&&(this.deliveryScheduled=!0,queueMicrotask(()=>this.drainDeliveries()))}scheduleTriggeredDelivery(e,r){this.scheduleDelivery(()=>this.triggerScope.run(e,r))}drainDeliveries(){for(this.deliveryScheduled=!1;this.deliveryQueue.length>0;)this.deliveryQueue.shift()()}flushListeners(){this.drainDeliveries()}notifyListenersForPaths(e){if(e.size===0||this.snapshotListeners.size===0)return;const r=this.triggerScope.current(),n=Array.from(this.snapshotListeners.values());for(const s of n)this.scheduleTriggeredDelivery(r,()=>{this.snapshotListeners.has(s.id)&&(s.errored||(s.target.kind==="doc"?this.notifyDocListener(s,e):this.notifyQueryListener(s,e)))})}notifyDocListener(e,r){if(e.target.kind!=="doc"||!r.has(e.target.path))return;const n=this.host.silentReadDoc(e.target.path,e.auth,e.bypassRules);if(!n.allowed){this.markErrored(e,n.error);return}const s=e.currentDocData??null;if(zi(s,n.data)){this.emitSnapshotSuppressed({listenerId:e.id,target:{kind:"doc",path:e.target.path},auth:e.auth,...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}});return}const i=e.target.path,a=tr(i,n.data,Bi);e.currentSnapshot=a,e.currentDocData=n.data;const o=s!==null,c=n.data!==null,u=!o&&c?1:0,f=o&&!c?1:0,l=o&&c?1:0;try{e.callback(a)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"doc",path:i},auth:e.auth,addedCount:u,modifiedCount:l,removedCount:f,size:c?1:0,sample:{docs:[{path:i,data:n.data}]},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),this.scheduleDocMetadataAck(e,i,n.data)}scheduleDocMetadataAck(e,r,n){e.options.includeMetadataChanges&&this.scheduleTriggeredDelivery(this.triggerScope.current(),()=>{if(!this.snapshotListeners.has(e.id)||e.errored)return;const s=tr(r,n,Zt);e.currentSnapshot=s;try{e.callback(s)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"doc",path:r},auth:e.auth,addedCount:0,modifiedCount:0,removedCount:0,size:n!==null?1:0,sample:{docs:[{path:r,data:n}]},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}})})}notifyQueryListener(e,r){if(e.target.kind!=="query"||!ff(r,e.target.collection))return;const n=this.host.silentReadCollection(e.target.collection,e.auth,e.target.constraints,e.bypassRules);if(!n.allowed){this.markErrored(e,n.error);return}const s=e.target.collection,i=e.currentDocs??[],a=rr({path:s},n.docs,{excludesMetadataChanges:!e.options.includeMetadataChanges},i,Bi),o=a.docChanges();if(o.length===0){if(e.options.includeMetadataChanges){e.currentSnapshot=a,e.currentDocs=n.docs;try{e.callback(a)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"query",collection:s},auth:e.auth,addedCount:0,modifiedCount:0,removedCount:0,size:n.docs.length,sample:{docs:n.docs.map(l=>({path:l.path,data:l.data}))},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),this.scheduleQueryMetadataAck(e,s,n.docs);return}this.emitSnapshotSuppressed({listenerId:e.id,target:{kind:"query",collection:s},auth:e.auth,...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}});return}e.currentSnapshot=a,e.currentDocs=n.docs;let c=0,u=0,f=0;for(const l of o)l.type==="added"?c++:l.type==="modified"?u++:l.type==="removed"&&f++;try{e.callback(a)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"query",collection:s},auth:e.auth,addedCount:c,modifiedCount:u,removedCount:f,size:n.docs.length,sample:{docs:n.docs.map(l=>({path:l.path,data:l.data}))},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),this.scheduleQueryMetadataAck(e,s,n.docs)}scheduleQueryMetadataAck(e,r,n){e.options.includeMetadataChanges&&this.scheduleTriggeredDelivery(this.triggerScope.current(),()=>{if(!this.snapshotListeners.has(e.id)||e.errored)return;const s=rr({path:r},n,{excludesMetadataChanges:!1},n,Zt);e.currentSnapshot=s;try{e.callback(s)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"query",collection:r},auth:e.auth,addedCount:0,modifiedCount:0,removedCount:0,size:n.length,sample:{docs:n.map(i=>({path:i.path,data:i.data}))},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}})})}markErrored(e,r){if(e.errored=!0,this.emitSnapshotError(r,e.target,e.id),!!e.errorCallback)try{e.errorCallback(r)}catch{}}reEvaluateAllListeners(){if(this.snapshotListeners.size===0)return;const e=Array.from(this.snapshotListeners.values());for(const r of e)this.snapshotListeners.has(r.id)&&(r.target.kind==="doc"?this.reEvaluateDocListener(r):this.reEvaluateQueryListener(r))}reevaluateLiveListeners(e,r){if(this.snapshotListeners.size===0)return;const n=Array.from(this.snapshotListeners.values());for(const s of n)s.followsCurrentUser&&s.authScope===r&&this.snapshotListeners.has(s.id)&&(s.auth=e,s.target.kind==="doc"?this.reEvaluateDocListener(s):this.reEvaluateQueryListener(s))}reEvaluateDocListener(e){if(e.target.kind!=="doc")return;const r=this.host.silentReadDoc(e.target.path,e.auth,e.bypassRules);if(!r.allowed){if(e.errored)return;this.markErrored(e,r.error);return}if(e.errored){e.errored=!1;const i=tr(e.target.path,r.data);e.currentSnapshot=i,e.currentDocData=r.data;try{e.callback(i)}catch{}return}const n=e.currentDocData??null;if(zi(n,r.data))return;const s=tr(e.target.path,r.data);e.currentSnapshot=s,e.currentDocData=r.data;try{e.callback(s)}catch{}}reEvaluateQueryListener(e){if(e.target.kind!=="query")return;const r=this.host.silentReadCollection(e.target.collection,e.auth,e.target.constraints,e.bypassRules);if(!r.allowed){if(e.errored)return;this.markErrored(e,r.error);return}if(e.errored){e.errored=!1;const a=rr({path:e.target.collection},r.docs,{excludesMetadataChanges:!e.options.includeMetadataChanges});e.currentSnapshot=a,e.currentDocs=r.docs;try{e.callback(a)}catch{}return}const n=e.currentDocs??[],s=rr({path:e.target.collection},r.docs,{excludesMetadataChanges:!e.options.includeMetadataChanges},n);if(s.docChanges().length!==0){e.currentSnapshot=s,e.currentDocs=r.docs;try{e.callback(s)}catch{}}}getSnapshotListenerCount(){return this.snapshotListeners.size}dispose(){this.snapshotListeners.clear(),this.deliveryQueue.length=0,this.deliveryScheduled=!1}}class gf{eventLog;host;constructor(e,r){this.eventLog=e,this.host=r}undo(){const e=this.eventLog.popLastWrite();if(!e)return null;if(e.priorDocs)this.host.state.restorePaths(e.priorDocs);else if(e.snapshot)this.host.state.restore(e.snapshot);else return null;return e}redo(){const e=this.eventLog.popLastUndo();if(!e)return null;const r=e.type==="batch"&&e.operations?e.operations.map(o=>o.path):e.path?[e.path]:[],n=!!e.snapshot,s=n?void 0:this.host.capturePriors(r),i=n?this.host.state.snapshot():void 0;if(e.type==="batch"&&e.operations)for(const o of e.operations)o.allowed&&this.host.applyWrite(o.method,o.path,o.data);else e.allowed&&this.host.applyWrite(e.method,e.path,e.data);const a=this.eventLog.append({...e,snapshot:i,priorDocs:s},!0);return{allowed:e.allowed,debugMessages:["Redo: "+(e.allowed?"applied":"skipped (was denied)")],event:a}}getEvents(){return this.eventLog.getEvents()}getEventCount(){return this.eventLog.size()}}class yf{currentSource;parsedCache=null;constructor(e){this.currentSource=e}get source(){return this.currentSource}set(e){this.currentSource=e}ast(){return this.parsedCache?.source!==this.currentSource&&(this.parsedCache={source:this.currentSource,ast:_s(this.currentSource)}),this.parsedCache.ast}}function he(t,e,r){const n={code:t,message:e};return r!==void 0&&(r.request!==void 0&&(n.request=r.request),r.resource!==void 0&&(n.resource=r.resource),r.remediation!==void 0&&(n.remediation=r.remediation),r.query!==void 0&&(n.query=r.query),r.rule!==void 0&&(n.rule=r.rule)),n}function ln(t,e,r){const n=t.get(e.path),s=e.method==="set"?n!==null?"update":"create":e.method;let i=e.data;if(e.method==="get"||e.method==="list")i=void 0;else if(e.method==="update"&&n&&e.data){const{writes:a,deletedKeys:o}=xt(e.data),c={...n,...a};for(const u of o)delete c[u];i=c}else e.data&&(i=xt(e.data).writes);return{description:`${e.method} ${e.path}`,expectation:"ALLOW",method:s,path:e.path,auth:e.auth?{uid:e.auth.uid,token:e.auth.token}:null,data:i,resource:n??void 0,...r?{requestTime:rf(r)}:{}}}function yo(t,e,r,n,s,i){if(s){const a=n.map(o=>nf(o.description));return{success:!0,data:{passed:a.length,failed:0,unsupported:0,results:a}}}return r.simulate(e.source,n,{getDoc:a=>t.get(a),...i?{batchProjection:i}:{}})}class vf{events;rules;simulator;host;eventLog;constructor(e,r,n,s,i){this.events=e,this.rules=r,this.simulator=n,this.host=s,this.eventLog=i}get state(){return this.host.state}emitRequest(e){this.events.request.hasSubscribers&&this.events.request.emit(un(e))}emitDenial(e){this.events.denial.emit(e)}execute(e){const{method:r,path:n,auth:s,bypassRules:i}=e;let a;i===!0&&(a={admin:!0});const c=_e.fromMillis(Date.now()),u=ln(this.state,e,c),f=Date.now(),l=performance.now(),p=yo(this.state,this.rules,this.simulator,[u],i),y=performance.now()-l;let v=null;if(s!==void 0&&s!==null&&(v={uid:s.uid}),p.success===!0===!1){const d=this.eventLog.append({type:"single",method:r,path:n,auth:v,allowed:!1,debugMessages:[`Simulation error: ${p.error.message}`]}),g={at:f,evalMs:y,method:r,path:n,auth:s,result:"deny",debugMessages:[`Simulation error: ${p.error.message}`],origin:"user"};return a!==void 0&&(g.detail=a),this.emitRequest(g),{allowed:!1,debugMessages:[p.error.message],event:d}}const k=p.data.results[0];if(k.state==="UNSUPPORTED"){const d={at:f,evalMs:y,method:r,path:n,auth:s,result:"unsupported",debugMessages:be(k),origin:"user"};throw a!==void 0&&(d.detail=a),this.emitRequest(d),new yr(vr(r,n,be(k)),r,n,be(k))}const L=k.state==="PASSED";let $;L&&(r==="get"?$=this.state.get(n):$=this.state.list(n));const S=this.eventLog.append({type:"single",method:r,path:n,auth:v,allowed:L,debugMessages:be(k)}),T={allowed:L,debugMessages:be(k),event:S};L&&(T.data=$);const _=Mt(k);if(L===!1){const g={request:{method:r,path:n,auth:s}};if(r==="get"){const E=this.state.get(n),O=E!==null;g.resource={data:E,exists:O}}_!==void 0&&(g.rule=_),T.error=he("permission-denied",`${r} ${n} denied by rules`,g),this.emitDenial(T.error)}let w="deny";L&&(w="allow");const A={at:f,evalMs:y,method:r,path:n,auth:s,result:w,debugMessages:be(k),evaluatedRule:_,origin:"user"};if(r==="get"){const d=this.state.get(n),g=d!==null;A.resourceBefore={data:d,exists:g}}return a!==void 0&&(A.detail=a),this.emitRequest(A),T}}function vo(t){const e=new Map,r=new Set;for(const n of t)e.has(n.name)&&r.add(n.name),e.set(n.name,n);return{functions:e,ambiguousNames:r}}function bo(t,e,r,n=bf){const s=new Set;return{pathInvariant:!kr(t,e,r,n,new Set,new Set,s),requiredFunctions:s}}function kr(t,e,r,n,s,i,a){const o=c=>kr(c,e,r,n,s,i,a);switch(t.type){case"literal":return!1;case"identifier":return!s.has(t.name)&&(e.has(t.name)||t.name==="request");case"memberAccess":return t.object.type==="identifier"&&t.object.name==="request"?!Vi.has(t.property):o(t.object);case"methodCall":return o(t.object)||t.args.some(o);case"bracketAccess":return t.object.type==="identifier"&&t.object.name==="request"?!(t.index.type==="literal"&&typeof t.index.value=="string"&&Vi.has(t.index.value)):o(t.object)||o(t.index);case"sliceAccess":return o(t.object)||o(t.start)||o(t.end);case"binaryOp":return o(t.left)||o(t.right);case"unaryOp":return o(t.operand);case"ternary":return o(t.condition)||o(t.consequent)||o(t.alternate);case"inExpr":return o(t.element)||o(t.collection);case"isExpr":return o(t.value);case"listLiteral":return t.elements.some(o);case"mapLiteral":return t.entries.some(c=>o(c.key)||o(c.value));case"pathLiteral":return t.segments.some(c=>typeof c!="string"&&o(c));case"functionCall":{if(t.args.some(o)||n.has(t.name))return!0;const c=r.get(t.name);if(!c)return!1;if(a.add(c.name),i.has(c.name))return!0;const u=new Set(i).add(c.name),f=new Set(c.parameters);for(const l of c.lets){if(kr(l.value,e,r,n,f,u,a))return!0;f.add(l.name)}return kr(c.body,e,r,n,f,u,a)}}}const Vi=new Set(["auth","method","query","time"]),bf=new Set;function wf(t){if(!t)return null;const e=[...t.functions??[],...t.service.functions??[],...t.service.match.functions],r=new Set,n=t.service.match.children.flatMap(i=>{const a=Sf(i,e,r);return a?[a]:[]});if(n.length===0)return null;const s=i=>i?.filter(a=>r.has(a.name));return{...t,functions:s(t.functions),service:{...t.service,functions:s(t.service.functions),match:{...t.service.match,functions:s(t.service.match.functions)??[],children:n}}}}function Sf(t,e,r){const n=t.path.segments[0];if(t.path.segments.length!==1||n?.type!=="recursive")return null;const s=vo([...e,...t.functions]),i=t.allows.filter(a=>{if(!a.operations.some(c=>c==="list"||c==="read"))return!1;const o=bo(a.condition,new Set([n.name]),s.functions,s.ambiguousNames);if(o.pathInvariant)for(const c of o.requiredFunctions)r.add(c);return o.pathInvariant});return i.length===0?null:{...t,functions:t.functions.filter(a=>r.has(a.name)),allows:i,children:[]}}function _f(t,e,r,n,s){if(t!==null===!1)return{kind:"no-rule"};const a=e.split("/").filter(b=>b.length>0),o=[...t.functions??[],...t.service.functions??[],...t.service.match.functions],c=[];for(const b of t.service.match.children)c.push(...jr(b,a,o));if(c.length===0)return{kind:"no-rule"};const f=[],l=new Set;let p=0;for(const b of c){const R=vo(b.functions),C=R.functions;for(const k of b.block.allows){if(k.operations.some(_=>_==="list"?!0:_==="read")===!1)continue;if(p++,bo(k.condition,new Set(b.candidateVariables),C,R.ambiguousNames).pathInvariant===!0===!1){f.push({reason:"list rule depends on the candidate document path",residual:{missing:[],mismatched:[]},rule:k});continue}const S=td(k.condition,n,C,r?.uid);S.provable===!0?l.add(k):f.push({reason:S.reason,residual:S.residual,rule:k})}}if(p===0)return{kind:"no-rule"};if(l.size===0){const b=f[0];let R="list rule depends on per-document data the query cannot guarantee",C={missing:[],mismatched:[]},k;if(b!==void 0&&(R=b.reason,C=b.residual,b.rule!==void 0)){const T=b.rule,_=ye(T.condition);if(k={verdict:"deny",expression:_},T.loc!==void 0){const A=T.loc;let I="";s!==void 0&&(I=s);const d=Ga(I,A.line,A.col,A.file,_);d!==void 0?(k.line=d.line,k.col=d.col,k.column=d.col,k.file=d.file,k.citation=d.citation,d.expression!==void 0&&(k.expression=d.expression)):(k.line=A.line,k.col=A.col,k.column=A.col,A.file!==void 0?(k.file=A.file,k.citation=`${A.file}:${A.line}:${A.col}`):(k.file="firestore.rules",k.citation=`firestore.rules:${A.line}:${A.col}`))}}const L={kind:"unprovable",reason:R,residual:C};return k!==void 0&&(L.rule=k),L}return{kind:"provable",evaluationAst:Af(t,l),syntheticResource:If(n)}}function Af(t,e){const r=n=>({...n,allows:n.allows.filter(s=>e.has(s)),children:n.children.map(r)});return{...t,service:{...t.service,match:r(t.service.match)}}}function If(t){const e={};for(const r of t.where??[])r.op==="=="&&(e[r.field]=r.value);return e}function xf(t){const e=[];for(const n of t.missing)n.fromAuthUid?e.push(` .where('${n.field}', '==', request.auth.uid) // request.auth.uid is ${JSON.stringify(n.expectedValue)}`):e.push(` .where('${n.field}', '==', ${JSON.stringify(n.expectedValue)})`);for(const n of t.mismatched)e.push(` .where('${n.field}', '==', ${JSON.stringify(n.expectedValue)}) // the query pins ${JSON.stringify(n.actualValue)}, but the rule requires ${JSON.stringify(n.expectedValue)}`);return e.length===0?void 0:`The list rule requires per-document equalities the query does not guarantee. Add the matching where(...) constraint(s) so every returned document satisfies the rule:
|
|
1164
1164
|
${e.join(`
|
|
1165
|
-
`)}`}function kf(t){if(!(t.limit==null&&t.offset==null&&t.orderBy==null))return{...t.limit!=null?{limit:t.limit}:{},...t.offset!=null?{offset:t.offset}:{},...t.orderBy!=null?{orderBy:t.orderBy}:{}}}class Ef{events;rules;simulator;host;constructor(e,r,n,s){this.events=e,this.rules=r,this.simulator=n,this.host=s}authorize(e){const{path:r,auth:n,constraints:s,origin:i,triggeredBy:a}=e,o=kf(s),c={...e.bypassRules?{admin:!0}:{},...o?{query:o}:{},...e.activityQuery!==void 0?{activityQuery:e.activityQuery}:{}},u=Object.keys(c).length>0?c:void 0,f=e.timing?.requestTime??(e.bypassRules?void 0:_e.fromMillis(Date.now())),l=e.timing?.at??Date.now();if(e.bypassRules)return this.emitRequest({at:l,evalMs:0,method:"list",path:r,auth:n,result:"allow",debugMessages:[i==="listener"?"admin lens — rules bypassed":"admin lens — rules bypassed (Studio Gap #2)"],origin:i,...u?{detail:u}:{},...a?{triggeredBy:a}:{}}),{allowed:!0};const p=this.rules.ast(),y=e.collectionGroup?wf(p):p;if(e.collectionGroup&&!y){const b=`list ${r} denied: symbolic collection-group proof is not supported; the query is rejected rather than authorizing from the currently stored rows`;this.emitRequest({at:l,evalMs:0,method:"list",path:r,auth:n,result:"deny",debugMessages:[b],origin:i,...u?{detail:u}:{},...a?{triggeredBy:a}:{}});const A=he("permission-denied",b,{request:{method:"list",path:r,auth:n},query:s});return this.emitUserDenial(i,A),{allowed:!1,error:A}}const v=`${r}/__listPlaceholder__`,w=performance.now(),R=_f(y,v,n,s,this.rules.source);if(R.kind==="unprovable"){const b=`list ${r} denied: the query is statically unprovable for every possible result (rules are not filters), so the whole query is rejected — ${R.reason}`,A=xf(R.residual),I={at:l,evalMs:performance.now()-w,method:"list",path:r,auth:n,result:"deny",debugMessages:[b],origin:i};u!==void 0&&(I.detail=u),a!==void 0&&(I.triggeredBy=a),this.emitRequest(I);const g={request:{method:"list",path:r,auth:n},query:s};A!==void 0&&A!==""&&(g.remediation=A),R.rule!==void 0&&(g.rule=R.rule);const E=he("permission-denied",b,g);return this.emitUserDenial(i,E),{allowed:!1,error:E}}const k=R.kind==="provable"?ri(R.evaluationAst):e.collectionGroup?ri(y):this.rules.source,x=ln(this.host.state,{method:"list",path:v,auth:n},f);this.applyProof(x,R,s);const L=this.simulator.simulate(k,[x],{getDoc:b=>this.host.state.get(b)}),$=performance.now()-w;if(!L.success)return this.emitRequest({at:l,evalMs:$,method:"list",path:r,auth:n,result:"deny",debugMessages:[`Simulation error: ${L.error.message}`],origin:i,...u?{detail:u}:{},...a?{triggeredBy:a}:{}}),{allowed:!1,error:he("permission-denied",`list ${r} simulator error`,{request:{method:"list",path:r,auth:n}})};const S=L.data.results[0],T=be(S);if(S.state==="UNSUPPORTED")throw this.emitRequest({at:l,evalMs:$,method:"list",path:r,auth:n,result:"unsupported",debugMessages:T,origin:i,...u?{detail:u}:{},...a?{triggeredBy:a}:{}}),new yr(vr("list",r,T),"list",r,T);if(S.state!=="PASSED"){const b=Mt(S),A={at:l,evalMs:$,method:"list",path:r,auth:n,result:"deny",debugMessages:T,evaluatedRule:b,origin:i};u!==void 0&&(A.detail=u),a!==void 0&&(A.triggeredBy=a),this.emitRequest(A);const d={request:{method:"list",path:r,auth:n}};b!==void 0&&(d.rule=b);const m=he("permission-denied",`list ${r} denied by rules`,d);return this.emitUserDenial(i,m),{allowed:!1,error:m}}return this.emitRequest({at:l,evalMs:$,method:"list",path:r,auth:n,result:"allow",debugMessages:T,evaluatedRule:Mt(S),origin:i,...u?{detail:u}:{},...a?{triggeredBy:a}:{}}),{allowed:!0}}applyProof(e,r,n){r.kind==="provable"&&(e.resource=r.syntheticResource),(n.limit!=null||n.offset!=null||n.orderBy!=null)&&(e.query={...n.limit!=null?{limit:n.limit}:{},...n.offset!=null?{offset:n.offset}:{},...n.orderBy!=null?{orderBy:n.orderBy}:{}})}emitRequest(e){this.events.request.hasSubscribers&&this.events.request.emit(un(e))}emitUserDenial(e,r){e==="user"&&this.events.denial.emit(r)}}function Tf(t,e,r){if(e<=0)return[];const n=[];for(const s of t)n.length<e?Hi(n,s,r):r(s,n[n.length-1])<0&&(n.pop(),Hi(n,s,r));return n}function Hi(t,e,r){let n=0,s=t.length;for(;n<s;){const i=n+s>>1;r(e,t[i])<0?s=i:n=i+1}t.splice(n,0,e)}function Of(t){return typeof t.seconds=="number"&&(typeof t.nanos=="number"||typeof t.nanoseconds=="number")}function Cf(t){return typeof t.latitude=="number"&&typeof t.longitude=="number"}function Rf(t){return t.data instanceof Uint8Array}function Nf(t){return typeof t.path=="string"}function nn(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 r=t;return Of(r)?3:Rf(r)?5:Cf(r)?7:Nf(r)?6:9}return 9}function Wi(t){const e=typeof t.nanos=="number"?t.nanos:t.nanoseconds??0;return[t.seconds,e]}function Lf(t,e){const r=Number.isNaN(t),n=Number.isNaN(e);return r&&n?0:r?-1:n?1:t<e?-1:t>e?1:0}function Gi(t,e){return t<e?-1:t>e?1:0}function vt(t,e){const r=nn(t),n=nn(e);if(r!==n)return r<n?-1:1;switch(r){case 0:return 0;case 1:return t===e?0:t?1:-1;case 2:return Lf(Number(t),Number(e));case 3:{const[s,i]=Wi(t),[a,o]=Wi(e);return s!==a?s<a?-1:1:i<o?-1:i>o?1:0}case 4:return Gi(t,e);case 5:{const s=t.data,i=e.data,a=Math.min(s.length,i.length);for(let o=0;o<a;o++)if(s[o]!==i[o])return s[o]<i[o]?-1:1;return s.length<i.length?-1:s.length>i.length?1:0}case 6:return Gi(t.path,e.path);case 7:{const s=t,i=e;return s.latitude!==i.latitude?s.latitude<i.latitude?-1:1:s.longitude<i.longitude?-1:s.longitude>i.longitude?1:0}case 8:{const s=t,i=e,a=Math.min(s.length,i.length);for(let o=0;o<a;o++){const c=vt(s[o],i[o]);if(c!==0)return c}return s.length<i.length?-1:s.length>i.length?1:0}case 9:{const s=t,i=e,a=Object.keys(s).sort(),o=Object.keys(i).sort(),c=Math.min(a.length,o.length);for(let u=0;u<c;u++){if(a[u]!==o[u])return a[u]<o[u]?-1:1;const f=vt(s[a[u]],i[o[u]]);if(f!==0)return f}return a.length<o.length?-1:a.length>o.length?1:0}default:return 0}}function Mf(t){const e=t.kind;if(e==="collection"){const r=t.path;return Object.freeze({kind:e,path:r})}if(e==="collection-group"){const r=t.collectionId;return Object.freeze({kind:e,collectionId:r})}throw new tn({code:"invalid-argument",message:`Unknown query scope kind: ${String(e)}`})}function Ki(t){const e=u=>{const f=u.kind;if(f==="where"){const p=u.field,y=u.op,v=u.value;return Object.freeze({kind:f,field:p,op:y,value:v})}if(f!=="and"&&f!=="or")throw new tn({code:"invalid-argument",message:`Unknown query filter kind: ${String(f)}`});const l=u.filters;return Object.freeze({kind:f,filters:Object.freeze(Array.from(l,e))})},r=u=>{if(u===void 0)return;const f=u.values,l=u.inclusive,p=u.fromSnapshot;return Object.freeze({values:Object.freeze(Array.from(f)),inclusive:l,fromSnapshot:p})},n=t.filters,s=t.orders,i=t.limitCount,a=t.limitFromEnd,o=t.start,c=t.end;return Object.freeze({filters:Object.freeze(Array.from(n,e)),orders:Object.freeze(Array.from(s,u=>{const f=u.field,l=u.direction;return Object.freeze({field:f,direction:l})})),limitCount:i,limitFromEnd:a,start:r(o),end:r(c)})}function Zi(t){const e=[],r=n=>{if(n.kind==="where"){if(n.field===mt)return;const s=n.value;(s===null||typeof s=="string"||typeof s=="number"||typeof s=="boolean")&&e.push(Object.freeze({field:n.field,op:n.op,value:s}));return}n.kind==="and"&&n.filters.forEach(r)};return t.filters.forEach(r),Object.freeze({where:Object.freeze(e),limit:t.limitCount??null,offset:null,orderBy:t.orders.length>0?t.orders[0].field:null})}function Df(t,e){if(e.kind==="collection")return t.scan(e.path,{directOnly:!0});const r=[];for(const[n,s]of Object.entries(t.snapshot())){const i=n.split("/").filter(a=>a.length>0);i.length>0&&i.length%2===0&&i[i.length-2]===e.collectionId&&r.push({path:n,data:s})}return r}const mt="__name__",Ff=new Set(["<","<=",">",">=","!=","not-in"]);function os(t,e){return e===mt?{path:t.path}:t.data[e]}function Ms(t){return t.kind==="where"?Ff.has(t.op)?[t.field]:[]:t.filters.flatMap(Ms)}function jf(t){return Ms(t).length>0}function dn(t,e){return nn(t)===nn(e)}function qf(t,e){return dn(t,e)&&vt(t,e)<0}function Pf(t,e){return dn(t,e)&&vt(t,e)<=0}function $f(t,e){return dn(t,e)&&vt(t,e)>0}function Uf(t,e){return dn(t,e)&&vt(t,e)>=0}function Bf(t,e,r){const n=t!==void 0;switch(e){case"==":return n&&Ye(t,r);case"!=":return n&&t!==null&&!Ye(t,r);case"<":return n&&qf(t,r);case"<=":return n&&Pf(t,r);case">":return n&&$f(t,r);case">=":return n&&Uf(t,r);case"in":return n&&Array.isArray(r)&&r.some(s=>Ye(t,s));case"not-in":return!Array.isArray(r)||r.some(s=>s===null)?!1:n&&t!==null&&!r.some(s=>Ye(t,s));case"array-contains":return Array.isArray(t)&&t.some(s=>Ye(s,r));case"array-contains-any":return Array.isArray(t)&&Array.isArray(r)&&r.some(s=>t.some(i=>Ye(i,s)))}}function zf(t,e){if(e===mt){const r=t.path.split("/");return r[r.length-1]??t.path}return t.data[e]}function wo(t){if(Array.isArray(t))return t.map(wo);if(t&&typeof t=="object"){const e=t;if(typeof e.id=="string")return e.id;if(typeof e.path=="string"){const r=e.path.split("/");return r[r.length-1]??e.path}}return t}function cs(t,e){if(e.kind==="where"){const r=zf(t,e.field),n=e.field===mt?wo(e.value):e.value;return Bf(r,e.op,n)}return e.kind==="and"?e.filters.every(r=>cs(t,r)):e.filters.some(r=>cs(t,r))}function Vf(t,e){return t.filter(r=>e.every(n=>cs(r,n)))}function Ji(t,e,r){for(let n=0;n<e.length;n++){const s=vt(os(t,r[n].field),e[n]);if(s!==0)return r[n].direction==="desc"?-s:s}return 0}function Hf(t,e,r,n){return t.filter(s=>{if(r){const i=Ji(s,r.values,e);if(r.inclusive?i<0:i<=0)return!1}if(n){const i=Ji(s,n.values,e);if(n.inclusive?i>0:i>=0)return!1}return!0})}function So(t,e){return t.filter(r=>e.every(n=>n.field===mt||r.data[n.field]!==void 0))}function _o(t){return(e,r)=>{for(const n of t){const s=vt(os(e,n.field),os(r,n.field));if(s!==0)return n.direction==="desc"?-s:s}return 0}}function Wf(t,e){return e.length===0?t:So(t,e).sort(_o(e))}function Gf(t){const e=[...t.orders],r=new Set(e.map(s=>s.field)),n=t.orders.length>0?t.orders[t.orders.length-1].direction:"asc";for(const s of t.filters)for(const i of Ms(s))i!==mt&&!r.has(i)&&(r.add(i),e.push({field:i,direction:n}));return r.has(mt)||e.push({field:mt,direction:n}),e}function kn(t,e){let r=Vf(t,[...e.filters]);const n=Gf(e),s=e.orders.length>0||e.start!==void 0||e.end!==void 0||e.filters.some(jf);if(s&&e.limitCount!==void 0&&!e.limitFromEnd&&e.start===void 0&&e.end===void 0)return Tf(So(r,n),e.limitCount,_o(n));if(s&&(r=Wf(r,n)),e.start||e.end){for(const i of[e.start,e.end])if(i&&!i.fromSnapshot&&i.values.length>e.orders.length)throw new tn({code:"invalid-argument",message:"Too many arguments provided to a cursor (startAt / startAfter / endAt / endBefore). The number of cursor values must be less than or equal to the number of orderBy() clauses."});r=Hf(r,n,e.start,e.end)}if(e.limitCount!==void 0)if(e.limitFromEnd){if(e.orders.length===0)throw new tn({code:"unimplemented",message:"limitToLast() queries require at least one orderBy clause."});r=r.slice(-e.limitCount)}else r=r.slice(0,e.limitCount);return r}class Kf{events;triggerScope;rules;simulator;host;operationReader;listAuthorizer;constructor(e,r,n,s,i,a){this.events=e,this.triggerScope=r,this.rules=n,this.simulator=s,this.host=i,this.operationReader=new vf(e,n,s,i,a),this.listAuthorizer=new Ef(e,n,s,i)}get state(){return this.host.state}emitRequest(e){this.events.request.hasSubscribers&&this.events.request.emit(un(e))}execute(e){return this.operationReader.execute(e)}silentReadDoc(e,r,n=!1){if(n){const x=this.state.get(e);return this.emitRequest({at:Date.now(),evalMs:0,method:"get",path:e,auth:r,result:"allow",debugMessages:["admin lens — rules bypassed"],origin:"listener",resourceBefore:{data:x,exists:x!==null},detail:{admin:!0},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),{allowed:!0,data:x}}const s=_e.fromMillis(Date.now()),i=ln(this.state,{method:"get",path:e,auth:r},s),a=Date.now(),o=performance.now(),c=this.simulator.simulate(this.rules.source,[i],{getDoc:x=>this.state.get(x)}),u=performance.now()-o;if(!c.success)return this.emitRequest({at:a,evalMs:u,method:"get",path:e,auth:r,result:"deny",debugMessages:[`Simulation error: ${c.error.message}`],origin:"listener",...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),{allowed:!1,error:he("permission-denied",`get ${e} simulator error`,{request:{method:"get",path:e,auth:r}})};const f=c.data.results[0];if(f.state==="UNSUPPORTED")throw this.emitRequest({at:a,evalMs:u,method:"get",path:e,auth:r,result:"unsupported",debugMessages:be(f),origin:"listener",...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),new yr(vr("get",e,be(f)),"get",e,be(f));const l=f.state==="PASSED",p=this.state.get(e),y=Mt(f);let v="deny";l&&(v="allow");const w=p!==null,R={at:a,evalMs:u,method:"get",path:e,auth:r,result:v,debugMessages:be(f),evaluatedRule:y,origin:"listener",resourceBefore:{data:p,exists:w}},C=this.triggerScope.current();if(C!==void 0&&(R.triggeredBy=C),this.emitRequest(R),l===!1){const x={request:{method:"get",path:e,auth:r},resource:{data:p,exists:w}};return y!==void 0&&(x.rule=y),{allowed:!1,error:he("permission-denied",`get ${e} denied by rules`,x)}}return{allowed:!0,data:p}}silentReadCollection(e,r,n,s=!1){if(typeof n=="function")return{allowed:!1,error:he("invalid-argument","Callable query constraints are no longer executable; pass an immutable QueryConstraintPlan.")};const i=n?Ki(n.execution):void 0,a=i?Zi(i):{},o={requestTime:_e.fromMillis(Date.now()),at:Date.now()},c=this.triggerScope.current();if(s){const p=this.state.list(e).filter(w=>!w.phantom).map(w=>({path:w.path,data:w.data})),y=i?kn(p,i):p,v=this.listAuthorizer.authorize({path:e,auth:r,constraints:a,bypassRules:s,...n?.activityQuery?{activityQuery:n.activityQuery}:{},origin:"listener",...c?{triggeredBy:c}:{},timing:o});return v.allowed?{allowed:!0,docs:y}:v}const u=this.listAuthorizer.authorize({path:e,auth:r,constraints:a,...n?.activityQuery?{activityQuery:n.activityQuery}:{},origin:"listener",...c?{triggeredBy:c}:{},timing:o});if(!u.allowed)return u;const f=this.state.list(e).filter(p=>!p.phantom).map(p=>({path:p.path,data:p.data}));return{allowed:!0,docs:i?kn(f,i):f}}runQuery(e){const r=Mf(e.scope),n=Ki(e.execution),s=e.auth,i=e.bypassRules,a=e.activityQuery,o=Df(this.state,r),c=r.kind==="collection"?r.path:r.collectionId,u=Zi(n),f=this.listAuthorizer.authorize({path:c,collectionGroup:r.kind==="collection-group",auth:s,constraints:u,bypassRules:i,...a!==void 0?{activityQuery:a}:{},origin:"user"});return f.allowed?{allowed:!0,docs:kn(o,n)}:f}}const Yi="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",Qi=20;function Zf(){const t=new Uint8Array(Qi);globalThis.crypto.getRandomValues(t);let e="";for(let r=0;r<Qi;r++)e+=Yi[t[r]%Yi.length];return e}function Ao(t,e=""){const r=[],n=new WeakSet;return s(t,e),r;function s(i,a){if(i==null||typeof i!="object"||n.has(i)||(n.add(i),jh(i)!==void 0))return;if(Array.isArray(i)){i.forEach((u,f)=>s(u,`${a}[${f}]`));return}const o=i,c=Jf(o);if(c){r.push({field:a,kind:c});return}for(const[u,f]of Object.entries(o)){const l=a?`${a}.${u}`:u;s(f,l)}}}function Jf(t){const e=t.__type;return e==="serverTimestamp"?"serverTimestamp":e==="increment"?"increment":e==="arrayUnion"?"arrayUnion":e==="arrayRemove"?"arrayRemove":e==="deleteField"?"delete":null}Zh();class Yf{host;rules;simulator;eventLog;events;triggerScope;constructor(e,r,n,s,i,a){this.host=e,this.rules=r,this.simulator=n,this.eventLog=s,this.events=i,this.triggerScope=a}get state(){return this.host.state}emitDenial(e){this.events.denial.emit(e)}emitRequest(e){this.events.request.hasSubscribers&&this.events.request.emit(un(e))}emitWrite(e){this.events.write.hasSubscribers&&this.events.write.emit({kind:"write",id:lr().replace(/^req-/,"wr-"),at:Date.now(),method:e.method,path:e.path,auth:e.auth?{uid:e.auth.uid,...e.auth.token?{token:e.auth.token}:{}}:null,...e.data!==void 0?{data:e.data}:{},priorState:e.priorState,nextState:e.nextState,...e.groupId!==void 0?{groupId:e.groupId}:{},...e.groupKind!==void 0?{groupKind:e.groupKind}:{},...e.sentinels&&e.sentinels.length>0?{sentinels:e.sentinels}:{},...e.autoId!==void 0?{autoId:e.autoId}:{},requestTime:{seconds:e.requestTime.seconds,nanoseconds:e.requestTime.nanos},...e.detail!==void 0?{detail:e.detail}:{},...e.provenance??{}})}capturePriors(e){const r={};for(const n of e){const s=this.state.get(n);r[n]=s?{...s}:null}return r}runSimulate(e,r,n){return yo(this.state,this.rules,this.simulator,e,r,n)}isReadOnlyMethod(e){return e==="get"||e==="list"}resolvePriorDocumentState(e,r,n){return r.has(e)?r.get(e)??null:n.exists(e)?n.get(e)??null:null}computeProjectedUpdate(e,r){return e===null?null:ss(e,r??{})}computeProjectedOverwrite(e,r){return ss(e??{},r??{})}buildBatchProjection(e){const r=new Map;for(const n of e){if(this.isReadOnlyMethod(n.method))continue;if(n.method==="delete"){r.set(n.path,null);continue}const s=this.resolvePriorDocumentState(n.path,r,this.state);if(n.method==="update"){const i=this.computeProjectedUpdate(s,n.data);r.set(n.path,i)}else{const i=this.computeProjectedOverwrite(s,n.data);r.set(n.path,i)}}return r}buildTestCase(e,r){return ln(this.state,e,r)}notify(e,r,n){this.triggerScope.run({method:e,path:r},()=>this.host.notifyListenersForPaths(n))}}class Io{runtime;constructor(e){this.runtime=e}prepare(e,r){const n=_e.fromMillis(Date.now()),s=[];for(let i=0;i<e.length;i++){const a=e[i];try{const o=a.data?Ze({...a.data},{path:a.path,method:a.method,prior:this.runtime.state.get(a.path),serverTime:n}):a.data;s.push({method:a.method,path:a.path,data:o})}catch(o){const c=o.message,u=he("invalid-argument",c),f=r.snapshot[a.path]??null,l={at:Date.now(),evalMs:0,method:a.ruleMethod,path:a.path,auth:r.auth,result:"deny",debugMessages:[`FieldValue resolve error: ${c}`],...this.includesRequestData(r,a)?{resourceData:a.preData}:{},resourceBefore:{data:f,exists:f!==null},origin:r.origin,groupId:r.groupId,...r.bypassRules?{detail:{admin:!0}}:{},...r.provenance?{provenance:r.provenance}:{}};return{index:i,input:a,message:c,error:u,request:l}}}return{context:r,inputs:e,resolvedOps:s,serverTime:n}}evaluateAndApply(e){const{context:r,inputs:n,resolvedOps:s,serverTime:i}=e,a=s.map((l,p)=>{const y=n[p];return this.runtime.buildTestCase({method:y.ruleMethod,path:l.path,auth:r.auth,data:l.data},i)}),o=this.runtime.buildBatchProjection(a),c=[];let u=!0;for(let l=0;l<s.length;l++){s[l];const p=n[l],y=r.snapshot[p.path]??null,v=Date.now(),w=performance.now(),R=this.runtime.runSimulate([a[l]],r.bypassRules,o),C=performance.now()-w;if(!R.success){const T=he("invalid-argument",R.error.message);c.push({path:p.path,method:p.ruleMethod,allowed:!1,debugMessages:[R.error.message],error:T,request:this.request(e,p,y,v,C,"deny",[`Simulation error: ${R.error.message}`])}),u=!1;continue}const k=R.data.results[0],x=be(k);if(k.state==="UNSUPPORTED")throw this.runtime.emitRequest(this.request(e,p,y,v,C,"unsupported",x)),new yr(vr(p.ruleMethod,p.path,x),p.ruleMethod,p.path,x);const L=k.state==="PASSED";let $="deny";L&&($="allow");const S={path:p.path,method:p.ruleMethod,allowed:L,debugMessages:x,request:this.request(e,p,y,v,C,$,x)};if(L===!1){const T=Mt(k),_=y!==null,b={request:{method:p.ruleMethod,path:p.path,auth:r.auth},resource:{data:y,exists:_}};this.includesRequestData(r,p)&&(b.request.resourceData=p.preData),T!==void 0&&(b.rule=T),S.error=he("permission-denied",`${p.ruleMethod} ${p.path} denied by rules`,b),this.runtime.emitDenial(S.error),u=!1}c.push(S)}let f=null;if(u){const l=this.runtime.state.applyBatch(s);if(!l.success){u=!1;const p=l.errors?.[0];if(p!==void 0){const y=s[p.index];f=he(y?.method==="create"?"already-exists":"not-found",p.error);const v=c[p.index];v&&(v.allowed=!1,v.error=f)}}}return{...e,outcomes:c,allowed:u,structuralError:f}}emitAndNotify(e){const{context:r,inputs:n,outcomes:s,serverTime:i}=e;for(let a=0;a<s.length;a++){const o=s[a],c=n[a],u=e.allowed&&o.allowed,f=r.snapshot[c.path]??null;if(o.request.resourceAfter=u?c.ruleMethod==="delete"?{data:null,exists:!1}:{data:this.runtime.state.get(c.path),exists:this.runtime.state.get(c.path)!==null}:{data:f,exists:f!==null},this.runtime.emitRequest(o.request),u){const l=c.preData?Ao(c.preData):void 0;this.runtime.emitWrite({method:c.ruleMethod,path:c.path,auth:r.auth,...c.ruleMethod!=="delete"&&c.preData?{data:c.preData}:{},priorState:f,nextState:c.ruleMethod==="delete"?null:this.runtime.state.get(c.path),groupId:r.groupId,groupKind:r.origin,...l&&l.length>0?{sentinels:l}:{},requestTime:i,...r.bypassRules?{detail:{admin:!0}}:{},...r.provenance?{provenance:r.provenance}:{}})}}e.allowed&&this.runtime.notify(r.origin,n[0]?.path??"",new Set(n.map(a=>a.path)))}request(e,r,n,s,i,a,o){const{context:c}=e;return{at:s,evalMs:i,method:r.ruleMethod,path:r.path,auth:c.auth,result:a,debugMessages:o,...this.includesRequestData(c,r)?{resourceData:r.preData}:{},resourceBefore:{data:n,exists:n!==null},origin:c.origin,groupId:c.groupId,...c.bypassRules?{detail:{admin:!0}}:{},...c.provenance?{provenance:c.provenance}:{}}}includesRequestData(e,r){return r.preData!==void 0&&(e.origin==="batch"||r.ruleMethod!=="delete")}}class Qf{runtime;pipeline;constructor(e){this.runtime=e,this.pipeline=new Io(e)}batch(e,r,n){const s=this.runtime.capturePriors(e.map(p=>p.path)),i=`batch-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,a=e.map(p=>({...p,ruleMethod:p.method,preData:p.data})),o=this.pipeline.prepare(a,{origin:"batch",groupId:i,auth:r,bypassRules:n,snapshot:s});if(!("resolvedOps"in o)){const p=this.runtime.eventLog.append({type:"batch",method:"batch",path:"",auth:r?{uid:r.uid}:null,allowed:!1,operations:e.map(y=>({method:y.method,path:y.path,data:y.data,allowed:!1})),debugMessages:[`FieldValue resolve error on '${o.input.path}': ${o.message}`]});return this.runtime.emitRequest(o.request),{allowed:!1,results:e.map(y=>({path:y.path,allowed:!1,debugMessages:[o.message],...y.path===o.input.path?{error:o.error}:{}})),event:p,error:o.error}}const c=this.pipeline.evaluateAndApply(o),u=c.outcomes.map(p=>({path:p.path,allowed:p.allowed,debugMessages:p.debugMessages,...p.error?{error:p.error}:{}})),f=this.runtime.eventLog.append({type:"batch",method:"batch",path:"",auth:r?{uid:r.uid}:null,allowed:c.allowed,priorDocs:c.allowed?s:void 0,operations:c.resolvedOps.map((p,y)=>({method:p.method,path:p.path,data:p.data,allowed:u[y]?.allowed??!1})),debugMessages:c.allowed?["Batch committed"]:["Batch rolled back — one or more operations denied"]});this.pipeline.emitAndNotify(c);let l;return c.allowed||(l=c.structuralError??u.find(p=>p.error)?.error??he("permission-denied","Batch denied")),{allowed:c.allowed,results:u,event:f,...l?{error:l}:{}}}}const Xi="Firestore transactions require all reads to be executed before all writes.";class Xf extends Error{simError;constructor(){super(Xi),this.name="ReadAfterWriteError",this.simError=he("failed-precondition",Xi)}}class ea extends Error{constructor(){super("A document read in the transaction changed before commit."),this.name="RetryableTransactionConflictError"}}class ep extends Error{simError=he("failed-precondition","Transaction failed all retries.");constructor(){super("Transaction failed all retries."),this.name="TransactionAttemptsExhaustedError"}}class tp{versionReader;reader;reads=[];writes=[];readVersions=new Map;writeStarted=!1;constructor(e,r=()=>0){this.versionReader=r,this.reader=e}get(e){this.assertReadsAllowed();const r=this.reader(e);this.readVersions.has(e)||this.readVersions.set(e,this.versionReader(e)),this.reads.push({path:e,data:r});const n=r===null?null:structuredClone(r);return{path:e,exists:n!==null,data:()=>n===null?void 0:n}}getAll(...e){return this.assertReadsAllowed(),e.map(r=>this.get(r))}set(e,r){this.queue({method:"set",path:e,data:r})}create(e,r){this.queue({method:"create",path:e,data:r})}update(e,r){this.queue({method:"update",path:e,data:r})}delete(e){this.queue({method:"delete",path:e})}consume(){return{reads:this.reads,writes:this.writes,readVersions:this.readVersions}}hadWrites(){return this.writeStarted}queue(e){this.writeStarted=!0,this.writes.push(e)}assertReadsAllowed(){if(this.writeStarted)throw new Xf}}class rp extends Error{path;secondMethod;constructor(e,r){super(`Queued ${r} on '${e}' after a delete in the same transaction. This combination is unprobed against production Firestore; refusing to guess. Either drop the delete or split into two transactions.`),this.name="AmbiguousPostDeleteWriteError",this.path=e,this.secondMethod=r}}function np(t){const e=new Map;for(const r of t){const n=e.get(r.path);if(n===void 0){e.set(r.path,sp(r));continue}if(n.method==="delete")throw new rp(r.path,r.method);e.set(r.path,ip(n,r))}return Array.from(e.values())}function sp(t){if(t.method==="delete")return{method:"delete",path:t.path};if(t.data===void 0)throw new Error(`internal: queued ${t.method} on ${t.path} has no data — Transaction class invariant violated`);return{method:t.method,path:t.path,data:t.data}}function ip(t,e){switch(e.method){case"delete":return{method:"delete",path:e.path};case"set":{const r=En(e);return{method:"set",path:e.path,data:r}}case"update":{const r=En(e),s={...t.data??{},...r};return{method:t.method,path:e.path,data:s}}case"create":{const r=En(e),s={...t.data??{},...r};return{method:"create",path:e.path,data:s}}}}function En(t){if(t.data===void 0)throw new Error(`internal: queued ${t.method} on ${t.path} has no data — Transaction class invariant violated`);return t.data}class ap{runtime;pipeline;constructor(e){this.runtime=e,this.pipeline=new Io(e)}transaction(e,r){return this.runAttempt(e,r,1)}runAttempt(e,r,n){const s=this.runtime.state.snapshot(),i=this.runtime.state.currentVersion(),a=new Map(Object.keys(s).map(f=>[f,this.runtime.state.version(f)])),o=f=>s[f]??null,c=new tp(o,f=>{const l=a.get(f);if(l!==void 0)return l;const p=this.runtime.state.version(f);return p<=i?p:-1});let u;try{u=e(c)}catch(f){throw this.logAbortedTransaction(c,r.auth,f),f}if(u!==null&&typeof u?.then=="function")return u.then(f=>{try{return this.commitTransaction(c,s,r,f)}catch(l){return this.retryOrThrow(l,e,r,n)}},f=>{throw this.logAbortedTransaction(c,r.auth,f),f});try{return this.commitTransaction(c,s,r,u)}catch(f){return this.retryOrThrow(f,e,r,n)}}retryOrThrow(e,r,n,s){if(!(e instanceof ea))throw e;const i=n.maxAttempts??5;if(s>=i)throw new ep;return this.runAttempt(r,n,s+1)}commitTransaction(e,r,n,s){const{reads:i,writes:a,readVersions:o}=e.consume();for(const[x,L]of o)if(this.runtime.state.version(x)!==L)throw new ea;const c=n.auth;if(a.length===0){const x=this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:c?{uid:c.uid}:null,allowed:!0,reads:i.map(L=>({path:L.path,data:L.data})),operations:[],snapshot:r,debugMessages:["Transaction committed (read-only — no writes queued)"]});return{allowed:!0,reads:[...i],writes:[],returnValue:s,event:x}}let u;try{u=np(a)}catch(x){const L=x;throw this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:c?{uid:c.uid}:null,allowed:!1,aborted:!0,reads:i.map($=>({path:$.path,data:$.data})),error:{name:L.name,message:L.message,code:"failed-precondition"},debugMessages:[`Transaction aborted at merge: ${L.message}`]}),x}const f=Object.fromEntries(u.map(x=>[x.path,r[x.path]??null])),l=u.map(x=>{const L=x.method==="set"?this.runtime.state.get(x.path)!==null?"update":"create":x.method;return{...x,ruleMethod:L,preData:x.data}}),p=`tx-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,y=this.pipeline.prepare(l,{origin:"transaction",groupId:p,auth:c,bypassRules:n.bypassRules,provenance:n.provenance,snapshot:f});if(!("resolvedOps"in y)){const x=this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:c?{uid:c.uid}:null,allowed:!1,reads:i.map(L=>({path:L.path,data:L.data})),operations:u.map(L=>({method:L.method,path:L.path,data:L.data,allowed:!1})),debugMessages:[`FieldValue resolve error on '${y.input.path}': ${y.message}`]});return this.runtime.emitRequest(y.request),{allowed:!1,reads:[...i],writes:l.map((L,$)=>({path:L.path,method:L.ruleMethod,allowed:!1,debugMessages:$===y.index?[y.message]:[],...$===y.index?{error:y.error}:{}})),returnValue:s,event:x,error:y.error}}const v=this.pipeline.evaluateAndApply(y),w=v.outcomes.map(x=>({path:x.path,method:x.method,allowed:x.allowed,debugMessages:x.debugMessages,...x.error?{error:x.error}:{}})),R=this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:c?{uid:c.uid}:null,allowed:v.allowed,reads:i.map(x=>({path:x.path,data:x.data})),operations:v.resolvedOps.map((x,L)=>({method:x.method,path:x.path,data:x.data,allowed:w[L]?.allowed??!1})),snapshot:v.allowed?r:void 0,debugMessages:v.allowed?["Transaction committed"]:["Transaction rolled back — one or more operations denied"]});this.pipeline.emitAndNotify(v);let C;v.allowed||(C=v.structuralError??w.find(x=>x.error)?.error??he("permission-denied","Transaction denied"));const k={allowed:v.allowed,reads:[...i],writes:w,returnValue:s,event:R,...C?{error:C}:{}};return n.readOnly&&e.hadWrites()&&(k.readOnlyViolation=!0),k}logAbortedTransaction(e,r,n){const s=n,{reads:i}=e.consume();this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:r?{uid:r.uid}:null,allowed:!1,aborted:!0,reads:i.map(a=>({path:a.path,data:a.data})),error:{name:n.name,message:n.message,...s.code!==void 0?{code:String(s.code)}:{}},debugMessages:[`Transaction aborted: ${n.message}`]})}}class op{runtime;batches;transactions;constructor(e,r,n,s,i,a){this.runtime=new Yf(e,r,n,s,i,a),this.batches=new Qf(this.runtime),this.transactions=new ap(this.runtime)}capturePriors(e){return this.runtime.capturePriors(e)}applyWrite(e,r,n,s){if(s!==void 0&&s!==!1&&(e==="create"||e==="update")){const i=s===!0?void 0:s.mergeFields;return this.runtime.state.setMerge(r,n??{},i),null}switch(e){case"create":{const i=this.runtime.state.create(r,n??{});return i.success?null:he("already-exists",i.error??`Document '${r}' already exists`)}case"update":{const i=this.runtime.state.update(r,n??{});return i.success?null:he("not-found",i.error??`Document '${r}' does not exist`)}case"set":return this.runtime.state.set(r,n??{}),null;case"delete":return this.runtime.state.delete(r),null;default:return null}}execute(e){const{method:r,path:n,auth:s,data:i,autoId:a,requestTime:o,merge:c,bypassRules:u}=e,f=u?{admin:!0}:void 0,l=this.runtime.capturePriors([n]),p=o??_e.fromMillis(Date.now());let y;try{y=i&&Ze({...i},{path:n,method:r,prior:this.runtime.state.get(n),serverTime:p}),r==="update"&&y&&Yh(y)}catch(A){const I=A.message,h=this.runtime.eventLog.append({type:"single",method:r,path:n,auth:s?{uid:s.uid}:null,data:i,allowed:!1,priorDocs:l,debugMessages:[`FieldValue resolve error: ${I}`]});return this.runtime.emitRequest({at:Date.now(),evalMs:0,method:r,path:n,auth:s,result:"deny",debugMessages:[`FieldValue resolve error: ${I}`],...y?{resourceData:y}:i?{resourceData:i}:{},resourceBefore:{data:l[n]??null,exists:(l[n]??null)!==null},origin:"user",...f?{detail:f}:{}}),{allowed:!1,debugMessages:[I],event:h,error:he("invalid-argument",I)}}const v=this.runtime.buildTestCase({...e,data:y},p),w=Date.now(),R=performance.now(),C=this.runtime.runSimulate([v],u),k=performance.now()-R;if(!C.success){const A=this.runtime.eventLog.append({type:"single",method:r,path:n,auth:s?{uid:s.uid}:null,data:y,allowed:!1,priorDocs:l,debugMessages:[`Simulation error: ${C.error.message}`]});return this.runtime.emitRequest({at:w,evalMs:k,method:r,path:n,auth:s,result:"deny",debugMessages:[`Simulation error: ${C.error.message}`],...i?{resourceData:i}:{},resourceBefore:{data:l[n]??null,exists:(l[n]??null)!==null},origin:"user",...f?{detail:f}:{}}),{allowed:!1,debugMessages:[C.error.message],event:A,error:he("invalid-argument",C.error.message)}}const x=C.data.results[0];if(x.state==="UNSUPPORTED")throw this.runtime.emitRequest({at:w,evalMs:k,method:r,path:n,auth:s,result:"unsupported",debugMessages:be(x),...i?{resourceData:i}:{},resourceBefore:{data:l[n]??null,exists:(l[n]??null)!==null},origin:"user",...f?{detail:f}:{}}),new yr(vr(r,n,be(x)),r,n,be(x));let L=x.state==="PASSED",$=null;L&&($=this.applyWrite(r,n,y,c),$&&(L=!1));const S=this.runtime.eventLog.append({type:"single",method:r,path:n,auth:s?{uid:s.uid}:null,data:y,allowed:L,priorDocs:L?l:void 0,debugMessages:be(x)}),T={allowed:L,debugMessages:be(x),event:S};if(L===!1){let A=!1;if($!==void 0&&$!==null&&(A=!0),A)T.error=$;else{let h=null;const d=l[n];d!==void 0&&(h=d);let m=r;r==="set"&&(h!==null?m="update":m="create");const E=Mt(x),D={request:{method:m,path:n,auth:s},resource:{data:h,exists:h!==null}};i!==void 0&&(D.request.resourceData=i),E!==void 0&&(D.rule=E),T.error=he("permission-denied",`${r} ${n} denied by rules`,D),this.runtime.emitDenial(T.error)}}const _=l[n]??null,b=L?this.runtime.state.get(n):_;if(this.runtime.emitRequest({at:w,evalMs:k,method:r,path:n,auth:s,result:L?"allow":"deny",debugMessages:be(x),evaluatedRule:Mt(x),...i?{resourceData:i}:{},resourceBefore:{data:_,exists:_!==null},...r!=="delete"?{resourceAfter:{data:b,exists:b!==null}}:{resourceAfter:{data:null,exists:!1}},origin:"user",...f?{detail:f}:{}}),L){const A=i?Ao(i):void 0,I=a&&r==="create"?n.split("/").pop():void 0;this.runtime.emitWrite({method:r,path:n,auth:s,...r!=="delete"&&i?{data:i}:{},priorState:_,nextState:r==="delete"?null:b,...A&&A.length>0?{sentinels:A}:{},...I?{autoId:I}:{},requestTime:p,...f?{detail:f}:{}})}return L&&this.runtime.notify(r,n,new Set([n])),T}createWithAutoId(e,r,n,s){const i=e.endsWith("/")?e.slice(0,-1):e,a=Zf(),o=`${i}/${a}`,c=this.execute({method:"create",path:o,auth:n,data:r,autoId:!0,bypassRules:s});return{path:o,result:c}}batch(e,r,n){return this.batches.batch(e,r,n)}transaction(e,r){return this.transactions.transaction(e,r)}}class ta{state;eventLog;history;simulator;rules;seedSnapshot;events=new af;triggerScope=new of;reads;writes;listeners;constructor(){this.state=new In,this.eventLog=new tf;const e=this;this.simulator=new ed,this.rules=new yf(sf),this.reads=new Kf(this.events,this.triggerScope,this.rules,this.simulator,{get state(){return e.state}},this.eventLog),this.listeners=new mf(this.events,this.triggerScope,this.reads),this.writes=new op({get state(){return e.state},notifyListenersForPaths:r=>e.listeners.notifyListenersForPaths(r)},this.rules,this.simulator,this.eventLog,this.events,this.triggerScope),this.history=new gf(this.eventLog,{get state(){return e.state},capturePriors:r=>this.writes.capturePriors(r),applyWrite:(r,n,s,i)=>this.writes.applyWrite(r,n,s,i)}),this.seedSnapshot={}}onDenial(e){return this.events.denial.subscribe(e)}onRequest(e){return this.events.request.subscribe(e)}onWrite(e){return this.events.write.subscribe(e)}onSnapshotDelivery(e){return this.events.delivery.subscribe(e)}onSnapshotSuppressed(e){return this.events.suppressed.subscribe(e)}onListenerLifecycle(e){return this.events.lifecycle.subscribe(e)}onSnapshotError(e){return this.events.snapshotError.subscribe(e)}addSnapshotListener(e,r,n={},s=null,i,a=!1,o=!1,c){return this.listeners.addSnapshotListener(e,r,n,s,i,a,o,c)}flushListeners(){this.listeners.flushListeners()}getSnapshotListenerCount(){return this.listeners.getSnapshotListenerCount()}dispose(){this.listeners.dispose(),this.events.clear()}seed(e){return this.rules.set(e.rules),this.state=e.baseDocuments?new In({},new ef(e.baseDocuments)):new In(e.documents??{}),this.seedSnapshot=e.baseDocuments??this.state.snapshot(),this.eventLog.clear(),Vn(e.rules)}deployRules(e){const r=Vn(e);return this.rules.set(e),this.listeners.reEvaluateAllListeners(),r}reevaluateLiveListeners(e,r){this.listeners.reevaluateLiveListeners(e,r)}getRules(){return this.rules.source}getDocument(e){return this.state.get(e)}listDocuments(e){return this.state.list(e)}runQuery(e){return this.reads.runQuery(e)}listRootCollections(){return this.state.listRootCollections()}listSubcollections(e){return this.state.listSubcollections(e)}snapshot(){return this.state.snapshot()}adminSetDocument(e,r){this.state.set(e,r??{}),this.listeners.notifyListenersForPaths(new Set([e]))}adminDeleteDocument(e){const r=this.state.delete(e);return r.success&&this.listeners.notifyListenersForPaths(new Set([e])),{deleted:r.success}}execute(e){return e.method==="get"||e.method==="list"?this.reads.execute(e):this.writes.execute(e)}createWithAutoId(e,r,n,s){return this.writes.createWithAutoId(e,r,n,s)}batch(e,r,n){return this.writes.batch(e,r,n)}transaction(e,r){return this.writes.transaction(e,r)}undo(){return this.history.undo()}redo(){return this.history.redo()}getEvents(){return this.history.getEvents()}getEventCount(){return this.history.getEventCount()}}class ct extends Error{code;denialContext;remediation;constructor(e,r,n){const s=typeof e=="object",i=s?e.code:e,a=s?e.message:r,o=s?e.denialContext:n,c=s?e.remediation:void 0,u=c!==void 0?`${a}
|
|
1165
|
+
`)}`}function kf(t){if(!(t.limit==null&&t.offset==null&&t.orderBy==null))return{...t.limit!=null?{limit:t.limit}:{},...t.offset!=null?{offset:t.offset}:{},...t.orderBy!=null?{orderBy:t.orderBy}:{}}}class Ef{events;rules;simulator;host;constructor(e,r,n,s){this.events=e,this.rules=r,this.simulator=n,this.host=s}authorize(e){const{path:r,auth:n,constraints:s,origin:i,triggeredBy:a}=e,o=kf(s),c={...e.bypassRules?{admin:!0}:{},...o?{query:o}:{},...e.activityQuery!==void 0?{activityQuery:e.activityQuery}:{}},u=Object.keys(c).length>0?c:void 0,f=e.timing?.requestTime??(e.bypassRules?void 0:_e.fromMillis(Date.now())),l=e.timing?.at??Date.now();if(e.bypassRules)return this.emitRequest({at:l,evalMs:0,method:"list",path:r,auth:n,result:"allow",debugMessages:[i==="listener"?"admin lens — rules bypassed":"admin lens — rules bypassed (Studio Gap #2)"],origin:i,...u?{detail:u}:{},...a?{triggeredBy:a}:{}}),{allowed:!0};const p=this.rules.ast(),y=e.collectionGroup?wf(p):p;if(e.collectionGroup&&!y){const w=`list ${r} denied: symbolic collection-group proof is not supported; the query is rejected rather than authorizing from the currently stored rows`;this.emitRequest({at:l,evalMs:0,method:"list",path:r,auth:n,result:"deny",debugMessages:[w],origin:i,...u?{detail:u}:{},...a?{triggeredBy:a}:{}});const A=he("permission-denied",w,{request:{method:"list",path:r,auth:n},query:s});return this.emitUserDenial(i,A),{allowed:!1,error:A}}const v=`${r}/__listPlaceholder__`,b=performance.now(),R=_f(y,v,n,s,this.rules.source);if(R.kind==="unprovable"){const w=`list ${r} denied: the query is statically unprovable for every possible result (rules are not filters), so the whole query is rejected — ${R.reason}`,A=xf(R.residual),I={at:l,evalMs:performance.now()-b,method:"list",path:r,auth:n,result:"deny",debugMessages:[w],origin:i};u!==void 0&&(I.detail=u),a!==void 0&&(I.triggeredBy=a),this.emitRequest(I);const g={request:{method:"list",path:r,auth:n},query:s};A!==void 0&&A!==""&&(g.remediation=A),R.rule!==void 0&&(g.rule=R.rule);const E=he("permission-denied",w,g);return this.emitUserDenial(i,E),{allowed:!1,error:E}}const k=R.kind==="provable"?ri(R.evaluationAst):e.collectionGroup?ri(y):this.rules.source,x=ln(this.host.state,{method:"list",path:v,auth:n},f);this.applyProof(x,R,s);const L=this.simulator.simulate(k,[x],{getDoc:w=>this.host.state.get(w)}),$=performance.now()-b;if(!L.success)return this.emitRequest({at:l,evalMs:$,method:"list",path:r,auth:n,result:"deny",debugMessages:[`Simulation error: ${L.error.message}`],origin:i,...u?{detail:u}:{},...a?{triggeredBy:a}:{}}),{allowed:!1,error:he("permission-denied",`list ${r} simulator error`,{request:{method:"list",path:r,auth:n}})};const S=L.data.results[0],T=be(S);if(S.state==="UNSUPPORTED")throw this.emitRequest({at:l,evalMs:$,method:"list",path:r,auth:n,result:"unsupported",debugMessages:T,origin:i,...u?{detail:u}:{},...a?{triggeredBy:a}:{}}),new yr(vr("list",r,T),"list",r,T);if(S.state!=="PASSED"){const w=Mt(S),A={at:l,evalMs:$,method:"list",path:r,auth:n,result:"deny",debugMessages:T,evaluatedRule:w,origin:i};u!==void 0&&(A.detail=u),a!==void 0&&(A.triggeredBy=a),this.emitRequest(A);const d={request:{method:"list",path:r,auth:n}};w!==void 0&&(d.rule=w);const m=he("permission-denied",`list ${r} denied by rules`,d);return this.emitUserDenial(i,m),{allowed:!1,error:m}}return this.emitRequest({at:l,evalMs:$,method:"list",path:r,auth:n,result:"allow",debugMessages:T,evaluatedRule:Mt(S),origin:i,...u?{detail:u}:{},...a?{triggeredBy:a}:{}}),{allowed:!0}}applyProof(e,r,n){r.kind==="provable"&&(e.resource=r.syntheticResource),(n.limit!=null||n.offset!=null||n.orderBy!=null)&&(e.query={...n.limit!=null?{limit:n.limit}:{},...n.offset!=null?{offset:n.offset}:{},...n.orderBy!=null?{orderBy:n.orderBy}:{}})}emitRequest(e){this.events.request.hasSubscribers&&this.events.request.emit(un(e))}emitUserDenial(e,r){e==="user"&&this.events.denial.emit(r)}}function Tf(t,e,r){if(e<=0)return[];const n=[];for(const s of t)n.length<e?Hi(n,s,r):r(s,n[n.length-1])<0&&(n.pop(),Hi(n,s,r));return n}function Hi(t,e,r){let n=0,s=t.length;for(;n<s;){const i=n+s>>1;r(e,t[i])<0?s=i:n=i+1}t.splice(n,0,e)}function Of(t){return typeof t.seconds=="number"&&(typeof t.nanos=="number"||typeof t.nanoseconds=="number")}function Cf(t){return typeof t.latitude=="number"&&typeof t.longitude=="number"}function Rf(t){return t.data instanceof Uint8Array}function Nf(t){return typeof t.path=="string"}function nn(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 r=t;return Of(r)?3:Rf(r)?5:Cf(r)?7:Nf(r)?6:9}return 9}function Wi(t){const e=typeof t.nanos=="number"?t.nanos:t.nanoseconds??0;return[t.seconds,e]}function Lf(t,e){const r=Number.isNaN(t),n=Number.isNaN(e);return r&&n?0:r?-1:n?1:t<e?-1:t>e?1:0}function Gi(t,e){return t<e?-1:t>e?1:0}function vt(t,e){const r=nn(t),n=nn(e);if(r!==n)return r<n?-1:1;switch(r){case 0:return 0;case 1:return t===e?0:t?1:-1;case 2:return Lf(Number(t),Number(e));case 3:{const[s,i]=Wi(t),[a,o]=Wi(e);return s!==a?s<a?-1:1:i<o?-1:i>o?1:0}case 4:return Gi(t,e);case 5:{const s=t.data,i=e.data,a=Math.min(s.length,i.length);for(let o=0;o<a;o++)if(s[o]!==i[o])return s[o]<i[o]?-1:1;return s.length<i.length?-1:s.length>i.length?1:0}case 6:return Gi(t.path,e.path);case 7:{const s=t,i=e;return s.latitude!==i.latitude?s.latitude<i.latitude?-1:1:s.longitude<i.longitude?-1:s.longitude>i.longitude?1:0}case 8:{const s=t,i=e,a=Math.min(s.length,i.length);for(let o=0;o<a;o++){const c=vt(s[o],i[o]);if(c!==0)return c}return s.length<i.length?-1:s.length>i.length?1:0}case 9:{const s=t,i=e,a=Object.keys(s).sort(),o=Object.keys(i).sort(),c=Math.min(a.length,o.length);for(let u=0;u<c;u++){if(a[u]!==o[u])return a[u]<o[u]?-1:1;const f=vt(s[a[u]],i[o[u]]);if(f!==0)return f}return a.length<o.length?-1:a.length>o.length?1:0}default:return 0}}function Mf(t){const e=t.kind;if(e==="collection"){const r=t.path;return Object.freeze({kind:e,path:r})}if(e==="collection-group"){const r=t.collectionId;return Object.freeze({kind:e,collectionId:r})}throw new tn({code:"invalid-argument",message:`Unknown query scope kind: ${String(e)}`})}function Ki(t){const e=u=>{const f=u.kind;if(f==="where"){const p=u.field,y=u.op,v=u.value;return Object.freeze({kind:f,field:p,op:y,value:v})}if(f!=="and"&&f!=="or")throw new tn({code:"invalid-argument",message:`Unknown query filter kind: ${String(f)}`});const l=u.filters;return Object.freeze({kind:f,filters:Object.freeze(Array.from(l,e))})},r=u=>{if(u===void 0)return;const f=u.values,l=u.inclusive,p=u.fromSnapshot;return Object.freeze({values:Object.freeze(Array.from(f)),inclusive:l,fromSnapshot:p})},n=t.filters,s=t.orders,i=t.limitCount,a=t.limitFromEnd,o=t.start,c=t.end;return Object.freeze({filters:Object.freeze(Array.from(n,e)),orders:Object.freeze(Array.from(s,u=>{const f=u.field,l=u.direction;return Object.freeze({field:f,direction:l})})),limitCount:i,limitFromEnd:a,start:r(o),end:r(c)})}function Zi(t){const e=[],r=n=>{if(n.kind==="where"){if(n.field===mt)return;const s=n.value;(s===null||typeof s=="string"||typeof s=="number"||typeof s=="boolean")&&e.push(Object.freeze({field:n.field,op:n.op,value:s}));return}n.kind==="and"&&n.filters.forEach(r)};return t.filters.forEach(r),Object.freeze({where:Object.freeze(e),limit:t.limitCount??null,offset:null,orderBy:t.orders.length>0?t.orders[0].field:null})}function Df(t,e){if(e.kind==="collection")return t.scan(e.path,{directOnly:!0});const r=[];for(const[n,s]of Object.entries(t.snapshot())){const i=n.split("/").filter(a=>a.length>0);i.length>0&&i.length%2===0&&i[i.length-2]===e.collectionId&&r.push({path:n,data:s})}return r}const mt="__name__",Ff=new Set(["<","<=",">",">=","!=","not-in"]);function os(t,e){return e===mt?{path:t.path}:t.data[e]}function Ms(t){return t.kind==="where"?Ff.has(t.op)?[t.field]:[]:t.filters.flatMap(Ms)}function jf(t){return Ms(t).length>0}function dn(t,e){return nn(t)===nn(e)}function qf(t,e){return dn(t,e)&&vt(t,e)<0}function Pf(t,e){return dn(t,e)&&vt(t,e)<=0}function $f(t,e){return dn(t,e)&&vt(t,e)>0}function Uf(t,e){return dn(t,e)&&vt(t,e)>=0}function Bf(t,e,r){const n=t!==void 0;switch(e){case"==":return n&&Ye(t,r);case"!=":return n&&t!==null&&!Ye(t,r);case"<":return n&&qf(t,r);case"<=":return n&&Pf(t,r);case">":return n&&$f(t,r);case">=":return n&&Uf(t,r);case"in":return n&&Array.isArray(r)&&r.some(s=>Ye(t,s));case"not-in":return!Array.isArray(r)||r.some(s=>s===null)?!1:n&&t!==null&&!r.some(s=>Ye(t,s));case"array-contains":return Array.isArray(t)&&t.some(s=>Ye(s,r));case"array-contains-any":return Array.isArray(t)&&Array.isArray(r)&&r.some(s=>t.some(i=>Ye(i,s)))}}function zf(t,e){if(e===mt){const r=t.path.split("/");return r[r.length-1]??t.path}return t.data[e]}function wo(t){if(Array.isArray(t))return t.map(wo);if(t&&typeof t=="object"){const e=t;if(typeof e.id=="string")return e.id;if(typeof e.path=="string"){const r=e.path.split("/");return r[r.length-1]??e.path}}return t}function cs(t,e){if(e.kind==="where"){const r=zf(t,e.field),n=e.field===mt?wo(e.value):e.value;return Bf(r,e.op,n)}return e.kind==="and"?e.filters.every(r=>cs(t,r)):e.filters.some(r=>cs(t,r))}function Vf(t,e){return t.filter(r=>e.every(n=>cs(r,n)))}function Ji(t,e,r){for(let n=0;n<e.length;n++){const s=vt(os(t,r[n].field),e[n]);if(s!==0)return r[n].direction==="desc"?-s:s}return 0}function Hf(t,e,r,n){return t.filter(s=>{if(r){const i=Ji(s,r.values,e);if(r.inclusive?i<0:i<=0)return!1}if(n){const i=Ji(s,n.values,e);if(n.inclusive?i>0:i>=0)return!1}return!0})}function So(t,e){return t.filter(r=>e.every(n=>n.field===mt||r.data[n.field]!==void 0))}function _o(t){return(e,r)=>{for(const n of t){const s=vt(os(e,n.field),os(r,n.field));if(s!==0)return n.direction==="desc"?-s:s}return 0}}function Wf(t,e){return e.length===0?t:So(t,e).sort(_o(e))}function Gf(t){const e=[...t.orders],r=new Set(e.map(s=>s.field)),n=t.orders.length>0?t.orders[t.orders.length-1].direction:"asc";for(const s of t.filters)for(const i of Ms(s))i!==mt&&!r.has(i)&&(r.add(i),e.push({field:i,direction:n}));return r.has(mt)||e.push({field:mt,direction:n}),e}function kn(t,e){let r=Vf(t,[...e.filters]);const n=Gf(e),s=e.orders.length>0||e.start!==void 0||e.end!==void 0||e.filters.some(jf);if(s&&e.limitCount!==void 0&&!e.limitFromEnd&&e.start===void 0&&e.end===void 0)return Tf(So(r,n),e.limitCount,_o(n));if(s&&(r=Wf(r,n)),e.start||e.end){for(const i of[e.start,e.end])if(i&&!i.fromSnapshot&&i.values.length>e.orders.length)throw new tn({code:"invalid-argument",message:"Too many arguments provided to a cursor (startAt / startAfter / endAt / endBefore). The number of cursor values must be less than or equal to the number of orderBy() clauses."});r=Hf(r,n,e.start,e.end)}if(e.limitCount!==void 0)if(e.limitFromEnd){if(e.orders.length===0)throw new tn({code:"unimplemented",message:"limitToLast() queries require at least one orderBy clause."});r=r.slice(-e.limitCount)}else r=r.slice(0,e.limitCount);return r}class Kf{events;triggerScope;rules;simulator;host;operationReader;listAuthorizer;constructor(e,r,n,s,i,a){this.events=e,this.triggerScope=r,this.rules=n,this.simulator=s,this.host=i,this.operationReader=new vf(e,n,s,i,a),this.listAuthorizer=new Ef(e,n,s,i)}get state(){return this.host.state}emitRequest(e){this.events.request.hasSubscribers&&this.events.request.emit(un(e))}execute(e){return this.operationReader.execute(e)}silentReadDoc(e,r,n=!1){if(n){const x=this.state.get(e);return this.emitRequest({at:Date.now(),evalMs:0,method:"get",path:e,auth:r,result:"allow",debugMessages:["admin lens — rules bypassed"],origin:"listener",resourceBefore:{data:x,exists:x!==null},detail:{admin:!0},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),{allowed:!0,data:x}}const s=_e.fromMillis(Date.now()),i=ln(this.state,{method:"get",path:e,auth:r},s),a=Date.now(),o=performance.now(),c=this.simulator.simulate(this.rules.source,[i],{getDoc:x=>this.state.get(x)}),u=performance.now()-o;if(!c.success)return this.emitRequest({at:a,evalMs:u,method:"get",path:e,auth:r,result:"deny",debugMessages:[`Simulation error: ${c.error.message}`],origin:"listener",...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),{allowed:!1,error:he("permission-denied",`get ${e} simulator error`,{request:{method:"get",path:e,auth:r}})};const f=c.data.results[0];if(f.state==="UNSUPPORTED")throw this.emitRequest({at:a,evalMs:u,method:"get",path:e,auth:r,result:"unsupported",debugMessages:be(f),origin:"listener",...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),new yr(vr("get",e,be(f)),"get",e,be(f));const l=f.state==="PASSED",p=this.state.get(e),y=Mt(f);let v="deny";l&&(v="allow");const b=p!==null,R={at:a,evalMs:u,method:"get",path:e,auth:r,result:v,debugMessages:be(f),evaluatedRule:y,origin:"listener",resourceBefore:{data:p,exists:b}},C=this.triggerScope.current();if(C!==void 0&&(R.triggeredBy=C),this.emitRequest(R),l===!1){const x={request:{method:"get",path:e,auth:r},resource:{data:p,exists:b}};return y!==void 0&&(x.rule=y),{allowed:!1,error:he("permission-denied",`get ${e} denied by rules`,x)}}return{allowed:!0,data:p}}silentReadCollection(e,r,n,s=!1){if(typeof n=="function")return{allowed:!1,error:he("invalid-argument","Callable query constraints are no longer executable; pass an immutable QueryConstraintPlan.")};const i=n?Ki(n.execution):void 0,a=i?Zi(i):{},o={requestTime:_e.fromMillis(Date.now()),at:Date.now()},c=this.triggerScope.current();if(s){const p=this.state.list(e).filter(b=>!b.phantom).map(b=>({path:b.path,data:b.data})),y=i?kn(p,i):p,v=this.listAuthorizer.authorize({path:e,auth:r,constraints:a,bypassRules:s,...n?.activityQuery?{activityQuery:n.activityQuery}:{},origin:"listener",...c?{triggeredBy:c}:{},timing:o});return v.allowed?{allowed:!0,docs:y}:v}const u=this.listAuthorizer.authorize({path:e,auth:r,constraints:a,...n?.activityQuery?{activityQuery:n.activityQuery}:{},origin:"listener",...c?{triggeredBy:c}:{},timing:o});if(!u.allowed)return u;const f=this.state.list(e).filter(p=>!p.phantom).map(p=>({path:p.path,data:p.data}));return{allowed:!0,docs:i?kn(f,i):f}}runQuery(e){const r=Mf(e.scope),n=Ki(e.execution),s=e.auth,i=e.bypassRules,a=e.activityQuery,o=Df(this.state,r),c=r.kind==="collection"?r.path:r.collectionId,u=Zi(n),f=this.listAuthorizer.authorize({path:c,collectionGroup:r.kind==="collection-group",auth:s,constraints:u,bypassRules:i,...a!==void 0?{activityQuery:a}:{},origin:"user"});return f.allowed?{allowed:!0,docs:kn(o,n)}:f}}const Yi="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",Qi=20;function Zf(){const t=new Uint8Array(Qi);globalThis.crypto.getRandomValues(t);let e="";for(let r=0;r<Qi;r++)e+=Yi[t[r]%Yi.length];return e}function Ao(t,e=""){const r=[],n=new WeakSet;return s(t,e),r;function s(i,a){if(i==null||typeof i!="object"||n.has(i)||(n.add(i),jh(i)!==void 0))return;if(Array.isArray(i)){i.forEach((u,f)=>s(u,`${a}[${f}]`));return}const o=i,c=Jf(o);if(c){r.push({field:a,kind:c});return}for(const[u,f]of Object.entries(o)){const l=a?`${a}.${u}`:u;s(f,l)}}}function Jf(t){const e=t.__type;return e==="serverTimestamp"?"serverTimestamp":e==="increment"?"increment":e==="arrayUnion"?"arrayUnion":e==="arrayRemove"?"arrayRemove":e==="deleteField"?"delete":null}Zh();class Yf{host;rules;simulator;eventLog;events;triggerScope;constructor(e,r,n,s,i,a){this.host=e,this.rules=r,this.simulator=n,this.eventLog=s,this.events=i,this.triggerScope=a}get state(){return this.host.state}emitDenial(e){this.events.denial.emit(e)}emitRequest(e){this.events.request.hasSubscribers&&this.events.request.emit(un(e))}emitWrite(e){this.events.write.hasSubscribers&&this.events.write.emit({kind:"write",id:lr().replace(/^req-/,"wr-"),at:Date.now(),method:e.method,path:e.path,auth:e.auth?{uid:e.auth.uid,...e.auth.token?{token:e.auth.token}:{}}:null,...e.data!==void 0?{data:e.data}:{},priorState:e.priorState,nextState:e.nextState,...e.groupId!==void 0?{groupId:e.groupId}:{},...e.groupKind!==void 0?{groupKind:e.groupKind}:{},...e.sentinels&&e.sentinels.length>0?{sentinels:e.sentinels}:{},...e.autoId!==void 0?{autoId:e.autoId}:{},requestTime:{seconds:e.requestTime.seconds,nanoseconds:e.requestTime.nanos},...e.detail!==void 0?{detail:e.detail}:{},...e.provenance??{}})}capturePriors(e){const r={};for(const n of e){const s=this.state.get(n);r[n]=s?{...s}:null}return r}runSimulate(e,r,n){return yo(this.state,this.rules,this.simulator,e,r,n)}isReadOnlyMethod(e){return e==="get"||e==="list"}resolvePriorDocumentState(e,r,n){return r.has(e)?r.get(e)??null:n.exists(e)?n.get(e)??null:null}computeProjectedUpdate(e,r){return e===null?null:ss(e,r??{})}computeProjectedOverwrite(e,r){return ss(e??{},r??{})}buildBatchProjection(e){const r=new Map;for(const n of e){if(this.isReadOnlyMethod(n.method))continue;if(n.method==="delete"){r.set(n.path,null);continue}const s=this.resolvePriorDocumentState(n.path,r,this.state);if(n.method==="update"){const i=this.computeProjectedUpdate(s,n.data);r.set(n.path,i)}else{const i=this.computeProjectedOverwrite(s,n.data);r.set(n.path,i)}}return r}buildTestCase(e,r){return ln(this.state,e,r)}notify(e,r,n){this.triggerScope.run({method:e,path:r},()=>this.host.notifyListenersForPaths(n))}}class Io{runtime;constructor(e){this.runtime=e}prepare(e,r){const n=_e.fromMillis(Date.now()),s=[];for(let i=0;i<e.length;i++){const a=e[i];try{const o=a.data?Ze({...a.data},{path:a.path,method:a.method,prior:this.runtime.state.get(a.path),serverTime:n}):a.data;s.push({method:a.method,path:a.path,data:o})}catch(o){const c=o.message,u=he("invalid-argument",c),f=r.snapshot[a.path]??null,l={at:Date.now(),evalMs:0,method:a.ruleMethod,path:a.path,auth:r.auth,result:"deny",debugMessages:[`FieldValue resolve error: ${c}`],...this.includesRequestData(r,a)?{resourceData:a.preData}:{},resourceBefore:{data:f,exists:f!==null},origin:r.origin,groupId:r.groupId,...r.bypassRules?{detail:{admin:!0}}:{},...r.provenance?{provenance:r.provenance}:{}};return{index:i,input:a,message:c,error:u,request:l}}}return{context:r,inputs:e,resolvedOps:s,serverTime:n}}evaluateAndApply(e){const{context:r,inputs:n,resolvedOps:s,serverTime:i}=e,a=s.map((l,p)=>{const y=n[p];return this.runtime.buildTestCase({method:y.ruleMethod,path:l.path,auth:r.auth,data:l.data},i)}),o=this.runtime.buildBatchProjection(a),c=[];let u=!0;for(let l=0;l<s.length;l++){s[l];const p=n[l],y=r.snapshot[p.path]??null,v=Date.now(),b=performance.now(),R=this.runtime.runSimulate([a[l]],r.bypassRules,o),C=performance.now()-b;if(!R.success){const T=he("invalid-argument",R.error.message);c.push({path:p.path,method:p.ruleMethod,allowed:!1,debugMessages:[R.error.message],error:T,request:this.request(e,p,y,v,C,"deny",[`Simulation error: ${R.error.message}`])}),u=!1;continue}const k=R.data.results[0],x=be(k);if(k.state==="UNSUPPORTED")throw this.runtime.emitRequest(this.request(e,p,y,v,C,"unsupported",x)),new yr(vr(p.ruleMethod,p.path,x),p.ruleMethod,p.path,x);const L=k.state==="PASSED";let $="deny";L&&($="allow");const S={path:p.path,method:p.ruleMethod,allowed:L,debugMessages:x,request:this.request(e,p,y,v,C,$,x)};if(L===!1){const T=Mt(k),_=y!==null,w={request:{method:p.ruleMethod,path:p.path,auth:r.auth},resource:{data:y,exists:_}};this.includesRequestData(r,p)&&(w.request.resourceData=p.preData),T!==void 0&&(w.rule=T),S.error=he("permission-denied",`${p.ruleMethod} ${p.path} denied by rules`,w),this.runtime.emitDenial(S.error),u=!1}c.push(S)}let f=null;if(u){const l=this.runtime.state.applyBatch(s);if(!l.success){u=!1;const p=l.errors?.[0];if(p!==void 0){const y=s[p.index];f=he(y?.method==="create"?"already-exists":"not-found",p.error);const v=c[p.index];v&&(v.allowed=!1,v.error=f)}}}return{...e,outcomes:c,allowed:u,structuralError:f}}emitAndNotify(e){const{context:r,inputs:n,outcomes:s,serverTime:i}=e;for(let a=0;a<s.length;a++){const o=s[a],c=n[a],u=e.allowed&&o.allowed,f=r.snapshot[c.path]??null;if(o.request.resourceAfter=u?c.ruleMethod==="delete"?{data:null,exists:!1}:{data:this.runtime.state.get(c.path),exists:this.runtime.state.get(c.path)!==null}:{data:f,exists:f!==null},this.runtime.emitRequest(o.request),u){const l=c.preData?Ao(c.preData):void 0;this.runtime.emitWrite({method:c.ruleMethod,path:c.path,auth:r.auth,...c.ruleMethod!=="delete"&&c.preData?{data:c.preData}:{},priorState:f,nextState:c.ruleMethod==="delete"?null:this.runtime.state.get(c.path),groupId:r.groupId,groupKind:r.origin,...l&&l.length>0?{sentinels:l}:{},requestTime:i,...r.bypassRules?{detail:{admin:!0}}:{},...r.provenance?{provenance:r.provenance}:{}})}}e.allowed&&this.runtime.notify(r.origin,n[0]?.path??"",new Set(n.map(a=>a.path)))}request(e,r,n,s,i,a,o){const{context:c}=e;return{at:s,evalMs:i,method:r.ruleMethod,path:r.path,auth:c.auth,result:a,debugMessages:o,...this.includesRequestData(c,r)?{resourceData:r.preData}:{},resourceBefore:{data:n,exists:n!==null},origin:c.origin,groupId:c.groupId,...c.bypassRules?{detail:{admin:!0}}:{},...c.provenance?{provenance:c.provenance}:{}}}includesRequestData(e,r){return r.preData!==void 0&&(e.origin==="batch"||r.ruleMethod!=="delete")}}class Qf{runtime;pipeline;constructor(e){this.runtime=e,this.pipeline=new Io(e)}batch(e,r,n){const s=this.runtime.capturePriors(e.map(p=>p.path)),i=`batch-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,a=e.map(p=>({...p,ruleMethod:p.method,preData:p.data})),o=this.pipeline.prepare(a,{origin:"batch",groupId:i,auth:r,bypassRules:n,snapshot:s});if(!("resolvedOps"in o)){const p=this.runtime.eventLog.append({type:"batch",method:"batch",path:"",auth:r?{uid:r.uid}:null,allowed:!1,operations:e.map(y=>({method:y.method,path:y.path,data:y.data,allowed:!1})),debugMessages:[`FieldValue resolve error on '${o.input.path}': ${o.message}`]});return this.runtime.emitRequest(o.request),{allowed:!1,results:e.map(y=>({path:y.path,allowed:!1,debugMessages:[o.message],...y.path===o.input.path?{error:o.error}:{}})),event:p,error:o.error}}const c=this.pipeline.evaluateAndApply(o),u=c.outcomes.map(p=>({path:p.path,allowed:p.allowed,debugMessages:p.debugMessages,...p.error?{error:p.error}:{}})),f=this.runtime.eventLog.append({type:"batch",method:"batch",path:"",auth:r?{uid:r.uid}:null,allowed:c.allowed,priorDocs:c.allowed?s:void 0,operations:c.resolvedOps.map((p,y)=>({method:p.method,path:p.path,data:p.data,allowed:u[y]?.allowed??!1})),debugMessages:c.allowed?["Batch committed"]:["Batch rolled back — one or more operations denied"]});this.pipeline.emitAndNotify(c);let l;return c.allowed||(l=c.structuralError??u.find(p=>p.error)?.error??he("permission-denied","Batch denied")),{allowed:c.allowed,results:u,event:f,...l?{error:l}:{}}}}const Xi="Firestore transactions require all reads to be executed before all writes.";class Xf extends Error{simError;constructor(){super(Xi),this.name="ReadAfterWriteError",this.simError=he("failed-precondition",Xi)}}class ea extends Error{constructor(){super("A document read in the transaction changed before commit."),this.name="RetryableTransactionConflictError"}}class ep extends Error{simError=he("failed-precondition","Transaction failed all retries.");constructor(){super("Transaction failed all retries."),this.name="TransactionAttemptsExhaustedError"}}class tp{versionReader;reader;reads=[];writes=[];readVersions=new Map;writeStarted=!1;constructor(e,r=()=>0){this.versionReader=r,this.reader=e}get(e){this.assertReadsAllowed();const r=this.reader(e);this.readVersions.has(e)||this.readVersions.set(e,this.versionReader(e)),this.reads.push({path:e,data:r});const n=r===null?null:structuredClone(r);return{path:e,exists:n!==null,data:()=>n===null?void 0:n}}getAll(...e){return this.assertReadsAllowed(),e.map(r=>this.get(r))}set(e,r){this.queue({method:"set",path:e,data:r})}create(e,r){this.queue({method:"create",path:e,data:r})}update(e,r){this.queue({method:"update",path:e,data:r})}delete(e){this.queue({method:"delete",path:e})}consume(){return{reads:this.reads,writes:this.writes,readVersions:this.readVersions}}hadWrites(){return this.writeStarted}queue(e){this.writeStarted=!0,this.writes.push(e)}assertReadsAllowed(){if(this.writeStarted)throw new Xf}}class rp extends Error{path;secondMethod;constructor(e,r){super(`Queued ${r} on '${e}' after a delete in the same transaction. This combination is unprobed against production Firestore; refusing to guess. Either drop the delete or split into two transactions.`),this.name="AmbiguousPostDeleteWriteError",this.path=e,this.secondMethod=r}}function np(t){const e=new Map;for(const r of t){const n=e.get(r.path);if(n===void 0){e.set(r.path,sp(r));continue}if(n.method==="delete")throw new rp(r.path,r.method);e.set(r.path,ip(n,r))}return Array.from(e.values())}function sp(t){if(t.method==="delete")return{method:"delete",path:t.path};if(t.data===void 0)throw new Error(`internal: queued ${t.method} on ${t.path} has no data — Transaction class invariant violated`);return{method:t.method,path:t.path,data:t.data}}function ip(t,e){switch(e.method){case"delete":return{method:"delete",path:e.path};case"set":{const r=En(e);return{method:"set",path:e.path,data:r}}case"update":{const r=En(e),s={...t.data??{},...r};return{method:t.method,path:e.path,data:s}}case"create":{const r=En(e),s={...t.data??{},...r};return{method:"create",path:e.path,data:s}}}}function En(t){if(t.data===void 0)throw new Error(`internal: queued ${t.method} on ${t.path} has no data — Transaction class invariant violated`);return t.data}class ap{runtime;pipeline;constructor(e){this.runtime=e,this.pipeline=new Io(e)}transaction(e,r){return this.runAttempt(e,r,1)}runAttempt(e,r,n){const s=this.runtime.state.snapshot(),i=this.runtime.state.currentVersion(),a=new Map(Object.keys(s).map(f=>[f,this.runtime.state.version(f)])),o=f=>s[f]??null,c=new tp(o,f=>{const l=a.get(f);if(l!==void 0)return l;const p=this.runtime.state.version(f);return p<=i?p:-1});let u;try{u=e(c)}catch(f){throw this.logAbortedTransaction(c,r.auth,f),f}if(u!==null&&typeof u?.then=="function")return u.then(f=>{try{return this.commitTransaction(c,s,r,f)}catch(l){return this.retryOrThrow(l,e,r,n)}},f=>{throw this.logAbortedTransaction(c,r.auth,f),f});try{return this.commitTransaction(c,s,r,u)}catch(f){return this.retryOrThrow(f,e,r,n)}}retryOrThrow(e,r,n,s){if(!(e instanceof ea))throw e;const i=n.maxAttempts??5;if(s>=i)throw new ep;return this.runAttempt(r,n,s+1)}commitTransaction(e,r,n,s){const{reads:i,writes:a,readVersions:o}=e.consume();for(const[x,L]of o)if(this.runtime.state.version(x)!==L)throw new ea;const c=n.auth;if(a.length===0){const x=this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:c?{uid:c.uid}:null,allowed:!0,reads:i.map(L=>({path:L.path,data:L.data})),operations:[],snapshot:r,debugMessages:["Transaction committed (read-only — no writes queued)"]});return{allowed:!0,reads:[...i],writes:[],returnValue:s,event:x}}let u;try{u=np(a)}catch(x){const L=x;throw this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:c?{uid:c.uid}:null,allowed:!1,aborted:!0,reads:i.map($=>({path:$.path,data:$.data})),error:{name:L.name,message:L.message,code:"failed-precondition"},debugMessages:[`Transaction aborted at merge: ${L.message}`]}),x}const f=Object.fromEntries(u.map(x=>[x.path,r[x.path]??null])),l=u.map(x=>{const L=x.method==="set"?this.runtime.state.get(x.path)!==null?"update":"create":x.method;return{...x,ruleMethod:L,preData:x.data}}),p=`tx-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,y=this.pipeline.prepare(l,{origin:"transaction",groupId:p,auth:c,bypassRules:n.bypassRules,provenance:n.provenance,snapshot:f});if(!("resolvedOps"in y)){const x=this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:c?{uid:c.uid}:null,allowed:!1,reads:i.map(L=>({path:L.path,data:L.data})),operations:u.map(L=>({method:L.method,path:L.path,data:L.data,allowed:!1})),debugMessages:[`FieldValue resolve error on '${y.input.path}': ${y.message}`]});return this.runtime.emitRequest(y.request),{allowed:!1,reads:[...i],writes:l.map((L,$)=>({path:L.path,method:L.ruleMethod,allowed:!1,debugMessages:$===y.index?[y.message]:[],...$===y.index?{error:y.error}:{}})),returnValue:s,event:x,error:y.error}}const v=this.pipeline.evaluateAndApply(y),b=v.outcomes.map(x=>({path:x.path,method:x.method,allowed:x.allowed,debugMessages:x.debugMessages,...x.error?{error:x.error}:{}})),R=this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:c?{uid:c.uid}:null,allowed:v.allowed,reads:i.map(x=>({path:x.path,data:x.data})),operations:v.resolvedOps.map((x,L)=>({method:x.method,path:x.path,data:x.data,allowed:b[L]?.allowed??!1})),snapshot:v.allowed?r:void 0,debugMessages:v.allowed?["Transaction committed"]:["Transaction rolled back — one or more operations denied"]});this.pipeline.emitAndNotify(v);let C;v.allowed||(C=v.structuralError??b.find(x=>x.error)?.error??he("permission-denied","Transaction denied"));const k={allowed:v.allowed,reads:[...i],writes:b,returnValue:s,event:R,...C?{error:C}:{}};return n.readOnly&&e.hadWrites()&&(k.readOnlyViolation=!0),k}logAbortedTransaction(e,r,n){const s=n,{reads:i}=e.consume();this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:r?{uid:r.uid}:null,allowed:!1,aborted:!0,reads:i.map(a=>({path:a.path,data:a.data})),error:{name:n.name,message:n.message,...s.code!==void 0?{code:String(s.code)}:{}},debugMessages:[`Transaction aborted: ${n.message}`]})}}class op{runtime;batches;transactions;constructor(e,r,n,s,i,a){this.runtime=new Yf(e,r,n,s,i,a),this.batches=new Qf(this.runtime),this.transactions=new ap(this.runtime)}capturePriors(e){return this.runtime.capturePriors(e)}applyWrite(e,r,n,s){if(s!==void 0&&s!==!1&&(e==="create"||e==="update")){const i=s===!0?void 0:s.mergeFields;return this.runtime.state.setMerge(r,n??{},i),null}switch(e){case"create":{const i=this.runtime.state.create(r,n??{});return i.success?null:he("already-exists",i.error??`Document '${r}' already exists`)}case"update":{const i=this.runtime.state.update(r,n??{});return i.success?null:he("not-found",i.error??`Document '${r}' does not exist`)}case"set":return this.runtime.state.set(r,n??{}),null;case"delete":return this.runtime.state.delete(r),null;default:return null}}execute(e){const{method:r,path:n,auth:s,data:i,autoId:a,requestTime:o,merge:c,bypassRules:u}=e,f=u?{admin:!0}:void 0,l=this.runtime.capturePriors([n]),p=o??_e.fromMillis(Date.now());let y;try{y=i&&Ze({...i},{path:n,method:r,prior:this.runtime.state.get(n),serverTime:p}),r==="update"&&y&&Yh(y)}catch(A){const I=A.message,h=this.runtime.eventLog.append({type:"single",method:r,path:n,auth:s?{uid:s.uid}:null,data:i,allowed:!1,priorDocs:l,debugMessages:[`FieldValue resolve error: ${I}`]});return this.runtime.emitRequest({at:Date.now(),evalMs:0,method:r,path:n,auth:s,result:"deny",debugMessages:[`FieldValue resolve error: ${I}`],...y?{resourceData:y}:i?{resourceData:i}:{},resourceBefore:{data:l[n]??null,exists:(l[n]??null)!==null},origin:"user",...f?{detail:f}:{}}),{allowed:!1,debugMessages:[I],event:h,error:he("invalid-argument",I)}}const v=this.runtime.buildTestCase({...e,data:y},p),b=Date.now(),R=performance.now(),C=this.runtime.runSimulate([v],u),k=performance.now()-R;if(!C.success){const A=this.runtime.eventLog.append({type:"single",method:r,path:n,auth:s?{uid:s.uid}:null,data:y,allowed:!1,priorDocs:l,debugMessages:[`Simulation error: ${C.error.message}`]});return this.runtime.emitRequest({at:b,evalMs:k,method:r,path:n,auth:s,result:"deny",debugMessages:[`Simulation error: ${C.error.message}`],...i?{resourceData:i}:{},resourceBefore:{data:l[n]??null,exists:(l[n]??null)!==null},origin:"user",...f?{detail:f}:{}}),{allowed:!1,debugMessages:[C.error.message],event:A,error:he("invalid-argument",C.error.message)}}const x=C.data.results[0];if(x.state==="UNSUPPORTED")throw this.runtime.emitRequest({at:b,evalMs:k,method:r,path:n,auth:s,result:"unsupported",debugMessages:be(x),...i?{resourceData:i}:{},resourceBefore:{data:l[n]??null,exists:(l[n]??null)!==null},origin:"user",...f?{detail:f}:{}}),new yr(vr(r,n,be(x)),r,n,be(x));let L=x.state==="PASSED",$=null;L&&($=this.applyWrite(r,n,y,c),$&&(L=!1));const S=this.runtime.eventLog.append({type:"single",method:r,path:n,auth:s?{uid:s.uid}:null,data:y,allowed:L,priorDocs:L?l:void 0,debugMessages:be(x)}),T={allowed:L,debugMessages:be(x),event:S};if(L===!1){let A=!1;if($!==void 0&&$!==null&&(A=!0),A)T.error=$;else{let h=null;const d=l[n];d!==void 0&&(h=d);let m=r;r==="set"&&(h!==null?m="update":m="create");const E=Mt(x),D={request:{method:m,path:n,auth:s},resource:{data:h,exists:h!==null}};i!==void 0&&(D.request.resourceData=i),E!==void 0&&(D.rule=E),T.error=he("permission-denied",`${r} ${n} denied by rules`,D),this.runtime.emitDenial(T.error)}}const _=l[n]??null,w=L?this.runtime.state.get(n):_;if(this.runtime.emitRequest({at:b,evalMs:k,method:r,path:n,auth:s,result:L?"allow":"deny",debugMessages:be(x),evaluatedRule:Mt(x),...i?{resourceData:i}:{},resourceBefore:{data:_,exists:_!==null},...r!=="delete"?{resourceAfter:{data:w,exists:w!==null}}:{resourceAfter:{data:null,exists:!1}},origin:"user",...f?{detail:f}:{}}),L){const A=i?Ao(i):void 0,I=a&&r==="create"?n.split("/").pop():void 0;this.runtime.emitWrite({method:r,path:n,auth:s,...r!=="delete"&&i?{data:i}:{},priorState:_,nextState:r==="delete"?null:w,...A&&A.length>0?{sentinels:A}:{},...I?{autoId:I}:{},requestTime:p,...f?{detail:f}:{}})}return L&&this.runtime.notify(r,n,new Set([n])),T}createWithAutoId(e,r,n,s){const i=e.endsWith("/")?e.slice(0,-1):e,a=Zf(),o=`${i}/${a}`,c=this.execute({method:"create",path:o,auth:n,data:r,autoId:!0,bypassRules:s});return{path:o,result:c}}batch(e,r,n){return this.batches.batch(e,r,n)}transaction(e,r){return this.transactions.transaction(e,r)}}class ta{state;eventLog;history;simulator;rules;seedSnapshot;events=new af;triggerScope=new of;reads;writes;listeners;constructor(){this.state=new In,this.eventLog=new tf;const e=this;this.simulator=new ed,this.rules=new yf(sf),this.reads=new Kf(this.events,this.triggerScope,this.rules,this.simulator,{get state(){return e.state}},this.eventLog),this.listeners=new mf(this.events,this.triggerScope,this.reads),this.writes=new op({get state(){return e.state},notifyListenersForPaths:r=>e.listeners.notifyListenersForPaths(r)},this.rules,this.simulator,this.eventLog,this.events,this.triggerScope),this.history=new gf(this.eventLog,{get state(){return e.state},capturePriors:r=>this.writes.capturePriors(r),applyWrite:(r,n,s,i)=>this.writes.applyWrite(r,n,s,i)}),this.seedSnapshot={}}onDenial(e){return this.events.denial.subscribe(e)}onRequest(e){return this.events.request.subscribe(e)}onWrite(e){return this.events.write.subscribe(e)}onSnapshotDelivery(e){return this.events.delivery.subscribe(e)}onSnapshotSuppressed(e){return this.events.suppressed.subscribe(e)}onListenerLifecycle(e){return this.events.lifecycle.subscribe(e)}onSnapshotError(e){return this.events.snapshotError.subscribe(e)}addSnapshotListener(e,r,n={},s=null,i,a=!1,o=!1,c){return this.listeners.addSnapshotListener(e,r,n,s,i,a,o,c)}flushListeners(){this.listeners.flushListeners()}getSnapshotListenerCount(){return this.listeners.getSnapshotListenerCount()}dispose(){this.listeners.dispose(),this.events.clear()}seed(e){return this.rules.set(e.rules),this.state=e.baseDocuments?new In({},new ef(e.baseDocuments)):new In(e.documents??{}),this.seedSnapshot=e.baseDocuments??this.state.snapshot(),this.eventLog.clear(),Vn(e.rules)}deployRules(e){const r=Vn(e);return this.rules.set(e),this.listeners.reEvaluateAllListeners(),r}reevaluateLiveListeners(e,r){this.listeners.reevaluateLiveListeners(e,r)}getRules(){return this.rules.source}getDocument(e){return this.state.get(e)}listDocuments(e){return this.state.list(e)}runQuery(e){return this.reads.runQuery(e)}listRootCollections(){return this.state.listRootCollections()}listSubcollections(e){return this.state.listSubcollections(e)}snapshot(){return this.state.snapshot()}adminSetDocument(e,r){this.state.set(e,r??{}),this.listeners.notifyListenersForPaths(new Set([e]))}adminDeleteDocument(e){const r=this.state.delete(e);return r.success&&this.listeners.notifyListenersForPaths(new Set([e])),{deleted:r.success}}execute(e){return e.method==="get"||e.method==="list"?this.reads.execute(e):this.writes.execute(e)}createWithAutoId(e,r,n,s){return this.writes.createWithAutoId(e,r,n,s)}batch(e,r,n){return this.writes.batch(e,r,n)}transaction(e,r){return this.writes.transaction(e,r)}undo(){return this.history.undo()}redo(){return this.history.redo()}getEvents(){return this.history.getEvents()}getEventCount(){return this.history.getEventCount()}}class ct extends Error{code;denialContext;remediation;constructor(e,r,n){const s=typeof e=="object",i=s?e.code:e,a=s?e.message:r,o=s?e.denialContext:n,c=s?e.remediation:void 0,u=c!==void 0?`${a}
|
|
1166
1166
|
|
|
1167
1167
|
Remediation:
|
|
1168
1168
|
${c}`:a;super(u),this.name="SandboxError",this.code=i,o!==void 0&&(this.denialContext=o),c!==void 0&&(this.remediation=c)}}function us(t){return t.kind==="request"||t.kind==="operation"||t.kind==="listener"&&t.phase==="errored"}function br(t){const e=Object.freeze({...t.source}),r=Object.freeze({...t.authLens});return Object.freeze({source:e,authLens:r,...t.planId===void 0?{}:{planId:t.planId}})}function Gp(t){const e=br(t);return{actor:e.source,authLens:e.authLens,operationContext:e,...e.planId===void 0?{}:{planId:e.planId}}}function ra(t){const e=t?.operationContext?.source;if(e&&e.kind!=="unattributed")return e;if(t?.actor&&t.actor.kind!=="unattributed")return t.actor}function Ds(t,e){const r=t?.operationContext?.source??t?.actor,n=e?.operationContext?.source??e?.actor;return br({source:ra(t)??ra(e)??r??n??{kind:"unattributed"},authLens:e?.operationContext?.authLens??e?.authLens??t?.operationContext?.authLens??t?.authLens??{mode:"app-session"},...(t?.operationContext?.planId??t?.planId??e?.operationContext?.planId??e?.planId)===void 0?{}:{planId:t?.operationContext?.planId??t?.planId??e?.operationContext?.planId??e?.planId}})}function cp(t){return Ds(void 0,t)}function up(t){if(t.result==="deny")return!0;if(!("error"in t)||!t.error||typeof t.error!="object")return!1;const e=t.error.code;if(typeof e!="string")return!1;const r=e.toLowerCase();return r==="permission_denied"||r==="permission-denied"||r==="auth/permission-denied"}function xo(t){return"rulesDisposition"in t&&t.rulesDisposition?t.rulesDisposition:t.kind==="operation"&&t.origin==="admin"?{kind:"bypassed",reason:"admin"}:t.detail?.admin===!0?{kind:"bypassed",reason:"admin"}:up(t)?{kind:"evaluated",verdict:"deny"}: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.kind==="listener"?t.rules?{kind:"evaluated",verdict:"deny"}:{kind:"not-evaluated",reason:"runtime-error"}:t.kind==="request"?{kind:"evaluated",verdict:"allow"}:"rules"in t&&t.rules?{kind:"evaluated",verdict:"allow"}:{kind:"not-evaluated",reason:"no-rules"}}function lp(t){if(t===null)return null;let e;return t.token!==void 0&&(e=ko(t.token)),Object.freeze({uid:t.uid,...e===void 0?{}:{token:e}})}function ko(t){const e={};for(const[r,n]of Object.entries(t))e[r]=Eo(n);return Object.freeze(e)}function Eo(t){return Array.isArray(t)?Object.freeze(t.map(Eo)):t&&typeof t=="object"?ko(t):t}function Kp(t){if(!us(t))return null;let e="listen",r;t.kind==="request"||t.kind==="operation"?(e=t.method,t.path!==void 0&&(r=t.path)):t.kind==="listener"&&(e="listen",t.target.path!==void 0&&(r=t.target.path));let n="firestore";return t.service!==void 0&&(n=t.service),Object.freeze({id:t.id,at:t.at,eventKind:t.kind,service:n,method:e,...r===void 0?{}:{path:r},auth:lp(t.auth),result:t.result,context:cp(t),rules:Object.freeze({...xo(t)})})}function na(t){return t===null?{mode:"anon"}:t.token===void 0?{mode:"as",uid:t.uid}:{mode:"as",uid:t.uid,token:t.token}}class hn{sandbox;auth;constructor(e,r,n){this.sandbox=e,this.auth=r,this.operationContext=br(n??{source:{kind:"unattributed"},authLens:na(r)})}operationContext;withAuth(e){return ls(e),new hn(this.sandbox,e,{source:this.operationContext.source,authLens:na(e),...this.operationContext.planId===void 0?{}:{planId:this.operationContext.planId}})}}function Zp(t,e){return new hn(t.sandbox,t.auth,e)}function ls(t){if(t===null)return;if(t===void 0)throw new ct({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(`
|
|
1169
|
-
`)});if(typeof t!="object")throw new ct("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 ct("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 ct("invalid-argument","withAuth() requires `token` (when present) to be a plain object.")}function dp(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=e.length%4===0?"":"=".repeat(4-e.length%4),n=atob(e+r),s=new Uint8Array(n.length);for(let i=0;i<n.length;i++)s[i]=n.charCodeAt(i);return s}function hp(t){const e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}function To(t){return ds(t,!0)}function ds(t,e){if(t===null||typeof t!="object")return t;if(Array.isArray(t)){const a=t.map(o=>ds(o,!1));return e&&is(a,Ui(t)),a}const r=t,n=a=>(e&&is(a,Ui(t)),a),s=(a,o)=>(Rs(a,Object.freeze(o),()=>a),n(a));if(r.__type__==="__vector__"&&Array.isArray(r.value)){const a=Object.freeze(r.value.slice());return s(new Qt(a),{type:"vector",values:a})}if(typeof r.__type=="string")switch(r.__type){case"timestamp":return s(new _e(r.seconds,r.nanos),{type:"timestamp",seconds:r.seconds,nanoseconds:r.nanos});case"bytes":{const a=dp(r.base64);return s(new Ae(a),{type:"bytes",values:Object.freeze(Array.from(a))})}case"latlng":return s(new lt(r.lat,r.lng),{type:"geo-point",latitude:r.lat,longitude:r.lng});case"duration":return n(new ve(r.seconds,r.nanos));case"reference":return n(new Ot(r.path));case"path":return n(new Qe(r.segments))}if(typeof r.type=="string")switch(r.type){case"firestore/timestamp/1.0":{const a=r.seconds,o=r.nanoseconds;return s(new _e(a,o),{type:"timestamp",seconds:a,nanoseconds:o})}case"firestore/bytes/1.0":{const a=hp(r.bytes);return s(new Ae(a),{type:"bytes",values:Object.freeze(Array.from(a))})}case"firestore/geoPoint/1.0":return s(new lt(r.latitude,r.longitude),{type:"geo-point",latitude:r.latitude,longitude:r.longitude})}const i={};for(const[a,o]of Object.entries(r))i[a]=ds(o,!1);return n(i)}class _r extends Error{constructor(e){super(e),this.name="PersistenceSchemaError"}}function fp(t){let e;try{e=JSON.parse(t)}catch(s){throw new _r(`Persisted blob is not valid JSON: ${s.message}`)}if(typeof e!="object"||e===null)throw new _r("Persisted blob is not an object");if(e.version!==1&&e.version!==2)throw new _r(`Persisted blob has version ${String(e.version)}, expected 1 or 2`);if(typeof e.firestore!="object"||e.firestore===null)throw new _r("Persisted blob has no firestore field");const r={};for(const[s,i]of Object.entries(e.firestore))r[s]=To(i);const n=e.services!==void 0&&typeof e.services=="object"&&e.services!==null?e.services:{};return{firestore:r,services:n}}const pp=3,mp=256,hs="meta";function gp(t){let e=2166136261;for(let r=0;r<t.length;r++)e^=t.charCodeAt(r),e=e+((e<<1)+(e<<4)+(e<<7)+(e<<8)+(e<<24))>>>0;return(e%mp).toString(16).padStart(2,"0")}function yp(t){return JSON.parse(JSON.stringify(t))}function Oo(t){const e=JSON.stringify(t);let r=2166136261;for(let n=0;n<e.length;n++)r^=e.charCodeAt(n),r=Math.imul(r,16777619)>>>0;return r}function Co(t,e,r){const n=new Map;n.set(hs,{version:pp,savedAt:r,services:e});for(const[s,i]of Object.entries(t)){const a=gp(s);let o=n.get(a);o||(o={docs:{}},n.set(a,o)),o.docs[s]=yp(i)}for(const[s,i]of n)s!==hs&&(i.checksum=Oo(i.docs));return n}const Ro="pyric-v3-records";function Jp(t){return JSON.stringify({format:Ro,records:Object.fromEntries(t)})}function Yp(t){let e;try{e=JSON.parse(t)}catch{return new Map}const r=e;return r&&typeof r=="object"&&r.format===Ro&&typeof r.records=="object"&&r.records!==null?new Map(Object.entries(r.records)):No(t)??new Map}function No(t){let e;try{e=fp(t)}catch{return null}return Co(e.firestore,e.services,0)}function vp(t){const e={};let r={};for(const[n,s]of t){if(n===hs){const a=s;a&&typeof a.services=="object"&&a.services!==null&&(r=a.services);continue}const i=s;if(!(!i||typeof i.docs!="object"||i.docs===null)){if(typeof i.checksum=="number"&&Oo(i.docs)!==i.checksum){console.warn(`[sandbox/persistence] checksum mismatch for bucket '${n}'; skipping corrupt bucket`);continue}for(const[a,o]of Object.entries(i.docs))e[a]=To(o)}}return{firestore:e,services:r}}const Jt="snapshots";function sa(){const t=new Map,e=r=>{let n=t.get(r);return n||(n=new Map,t.set(r,n)),n};return{async getRecord(r,n){const s=t.get(r)?.get(n);return s===void 0?null:structuredClone(s)},async listRecords(r){return[...t.get(r)?.keys()??[]]},async putRecords(r,n){const s=e(r);for(const[i,a]of n)s.set(i,structuredClone(a))},async deleteRecords(r,n){const s=t.get(r);if(s)for(const i of n)s.delete(i)},async clear(r){t.delete(r)}}}function Lo(t){return new Promise((e,r)=>{const n=indexedDB.open(t,1);n.onupgradeneeded=()=>{const s=n.result;s.objectStoreNames.contains(Jt)||s.createObjectStore(Jt)},n.onsuccess=()=>e(n.result),n.onerror=()=>r(n.error??new Error(`Failed to open IndexedDB '${t}'`)),n.onblocked=()=>r(new Error(`IndexedDB open blocked for '${t}'`))})}function Tn(t,e,r){return Lo(t).then(n=>new Promise((s,i)=>{const a=n.transaction(Jt,e),o=a.objectStore(Jt),c=r(o);let u=null;c&&(c.onsuccess=()=>{u=c.result??null},c.onerror=()=>i(c.error)),a.oncomplete=()=>{n.close(),s(u)},a.onerror=()=>{n.close(),i(a.error)},a.onabort=()=>{n.close(),i(a.error??new Error("IndexedDB transaction aborted"))}}))}function ia(t,e){return Lo(t).then(r=>new Promise((n,s)=>{const i=r.transaction(Jt,"readwrite");e(i.objectStore(Jt)),i.oncomplete=()=>{r.close(),n()},i.onerror=()=>{r.close(),s(i.error)},i.onabort=()=>{r.close(),s(i.error??new Error("IndexedDB transaction aborted"))}}))}function bp(){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 Tn(t,"readonly",n=>n.get(e))??null},async listRecords(t){return(await Tn(t,"readonly",r=>r.getAllKeys())??[]).map(r=>String(r))},async putRecords(t,e){await ia(t,r=>{for(const[n,s]of e)r.put(s,n)})},async deleteRecords(t,e){await ia(t,r=>{for(const n of e)r.delete(n)})},async clear(t){await Tn(t,"readwrite",e=>e.clear())},async estimate(){if(typeof navigator>"u"||!navigator.storage?.estimate)return null;const t=await navigator.storage.estimate();return{usage:t.usage??0,quota:t.quota??0}}}}const wp=250,aa="pyric:sandbox:auth-session";function On(t){return t==="auth"||t==="auth-session:[DEFAULT]"?aa:`${aa}:${encodeURIComponent(t)}`}function Mo(t){const e=JSON.stringify(t);let r=2166136261;for(let n=0;n<e.length;n++)r^=e.charCodeAt(n),r=Math.imul(r,16777619)>>>0;return r}function Sp(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 _p(t){return t.injectedBackend?t.injectedBackend:(t.backend??"indexedDB")==="memory"||typeof indexedDB>"u"?sa():bp()}async function Ap(t,e){const r={...e,flushIntervalMs:e.flushIntervalMs??wp,backend:e.backend??"indexedDB"},n=_p(r),s=new Map,i=await Ip(t,n,r.key,s);let a=null,o=!1;const c=new Map,u=async()=>{if(o)return;const _=t.snapshot(),b=Co(_.firestore,_.services,Date.now()),A=new Map,I=new Map;for(const[d,g]of b){const m=Mo(g);I.set(d,m),s.get(d)!==m&&A.set(d,g)}const h=[...s.keys()].filter(d=>!b.has(d));A.size>0&&await n.putRecords(r.key,A),h.length>0&&await n.deleteRecords(r.key,h),s.clear();for(const[d,g]of I)s.set(d,g)};let f=Promise.resolve();const l=()=>(a&&(clearTimeout(a),a=null),f=f.then(u,u),f),p=()=>{o||a||(a=setTimeout(()=>{a=null,l().catch(_=>{if(Sp(_)){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:",_),p()})},r.flushIntervalMs))},y=(_,b)=>{if(!b.subscribe||c.has(_))return;const A=b.subscribe(()=>{p()});c.set(_,A)},v=new Map,w=new Map,R=(_,b)=>{if(!r.sessionStorage)return;const{local:A,session:I}=r.sessionStorage,h=On(_),d=b.currentUid(),g=b.mode();if(d===null||g==="NONE"){A.removeItem(h),I.removeItem(h);return}const m=JSON.stringify({uid:d});g==="LOCAL"?(I.removeItem(h),A.setItem(h,m)):(A.removeItem(h),I.setItem(h,m))},C=_=>{if(!r.sessionStorage)return null;const b=On(_);for(const[A,I]of[["LOCAL",r.sessionStorage.local],["SESSION",r.sessionStorage.session]]){const h=I.getItem(b);if(h)try{const d=JSON.parse(h);if(typeof d?.uid=="string")return{uid:d.uid,mode:A}}catch{I.removeItem(b)}}return null},k=_=>{if(!r.sessionStorage)return;const b=On(_);r.sessionStorage.local.removeItem(b),r.sessionStorage.session.removeItem(b)},x=(_,b,A)=>{if(A.session)try{A.session.restore(b.uid,b.mode),w.delete(_)}catch(I){console.warn(`[sandbox/persistence] session restore for uid '${b.uid}' failed — clearing stored session:`,I),k(_),w.delete(_)}},L=(_,b)=>{if(!r.sessionStorage||!b.session||v.has(_))return;const A=b.session;v.set(_,A.subscribe(()=>R(_,A)))},$=(_,b)=>{if(!b.session)return;const A=w.get(_)??C(_);A&&x(_,A,b)};if(t instanceof bt){for(const[_,b]of t.getServiceRegistry())y(_,b),$(_,b),L(_,b);t.setServiceRegistrationHook((_,b)=>{if(i!==null&&_ in i)try{b.restore(i[_])}catch(I){console.warn(`[sandbox/persistence] late-restore for service '${_}' failed:`,I)}const A=C(_);A&&w.set(_,A),$(_,b),y(_,b),L(_,b),p()}),t.setServiceUnregistrationHook(_=>{c.get(_)?.(),c.delete(_),v.get(_)?.(),v.delete(_),w.delete(_),p()})}const S=t.onEvent(_=>{xp(_)&&p()}),T=()=>{l().catch(()=>{})};return typeof window<"u"&&window.addEventListener("beforeunload",T),{options:r,flush:l,async clear(){a&&(clearTimeout(a),a=null),await n.clear(r.key),s.clear()},dispose(){if(!o){o=!0,a&&(clearTimeout(a),a=null),S();for(const _ of c.values())_();c.clear();for(const _ of v.values())_();v.clear(),t instanceof bt&&(t.setServiceRegistrationHook(null),t.setServiceUnregistrationHook(null)),typeof window<"u"&&window.removeEventListener("beforeunload",T)}}}}async function Ip(t,e,r,n){let s;try{s=await e.listRecords(r)}catch(f){return console.warn("[sandbox/persistence] backend list failed:",f),null}if(s.length===0)return null;const i=[];for(const f of s)try{const l=await e.getRecord(r,f);l!==null&&i.push([f,l])}catch(l){console.warn(`[sandbox/persistence] failed to read persisted record '${f}':`,l)}const a=[],o=[];let c=null;for(const[f,l]of i)if(typeof l=="string"){const p=No(l);p&&(o.push(f),c=p)}else a.push([f,l]);if(c){try{await e.putRecords(r,c),o.length>0&&await e.deleteRecords(r,o)}catch(f){console.warn("[sandbox/persistence] v2 migration write failed:",f)}for(const[f,l]of c)a.push([f,l])}for(const[f,l]of a)n.set(f,Mo(l));const u=vp(a);for(const[f,l]of Object.entries(u.firestore))t.admin.setDocument(f,l);if(t instanceof bt){const f=t.getServiceRegistry();for(const[l,p]of Object.entries(u.services)){const y=f.get(l);if(y)try{y.restore(p)}catch(v){console.warn(`[sandbox/persistence] service '${l}' restore failed — Firestore state is intact; auth users may need to be re-created:`,v)}}}return u.services}function xp(t){return t.kind==="write"||t.kind==="session_boundary"}function kp(t){return typeof t=="object"&&t!==null&&typeof t.kind=="string"&&typeof t.origin=="string"}let Ep=0;function Tp(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`tab-${crypto.randomUUID()}`:`tab-${++Ep}-${typeof performance<"u"?performance.now().toFixed(3):String(Date.now())}`}function Op(t,e={}){let r,n=!1;if(e.channel)r=e.channel,n=!1;else if(typeof BroadcastChannel<"u")r=new BroadcastChannel("pyric:tabsync"),n=!0;else return()=>{};const s=e.originId??Tp();let i=!1,a=!1;const o=t.onEvent(l=>{if(l.kind!=="write"||i)return;const p={kind:"write",origin:s,event:l};r.postMessage(p)}),c=l=>{if(!kp(l.data))return;const p=l.data;if(p.origin!==s){if(p.kind==="write")f(p.event);else if(p.kind==="hello"){const y={kind:"state",origin:s,to:p.origin,snapshot:t.snapshot()};r.postMessage(y)}else if(p.kind==="state"){if(p.to!==s||a)return;if(Object.keys(wr(t).snapshot()).length>0){a=!0;return}i=!0;try{for(const[v,w]of Object.entries(p.snapshot.firestore))t.admin.setDocument(v,w)}finally{i=!1}a=!0}}};r.addEventListener("message",c);const u={kind:"hello",origin:s};return r.postMessage(u),()=>{o(),r.removeEventListener("message",c),n&&r.close()};function f(l){i=!0;try{if(l.method==="delete")t.admin.deleteDocument(l.path);else{const p=l.nextState;p!=null&&t.admin.setDocument(l.path,p)}}finally{i=!1}}}function Cp(t,e){const r={...t};r.service=t.service??e?.service??"firestore";const s="detail"in t&&t.detail?.admin===!0&&t.operationContext===void 0&&t.authLens===void 0?{...t,authLens:{mode:"admin"}}:t,i=us(r)||t.operationContext!==void 0?Ds(e,s):Rp(t,e);return r.operationContext=i,r.actor=i.source,r.authLens=i.authLens,i.planId!==void 0&&(r.planId=i.planId),e?.activity!==void 0&&(r.activity={...r.activity,...e.activity}),us(r)&&(r.rulesDisposition=Object.freeze({...xo(r)})),r}function Rp(t,e){return br({source:t.actor??t.operationContext?.source??e?.actor??e?.operationContext?.source??{kind:"unattributed"},authLens:t.authLens??t.operationContext?.authLens??e?.authLens??e?.operationContext?.authLens??{mode:"app-session"},...(t.planId??t.operationContext?.planId??e?.planId??e?.operationContext?.planId)===void 0?{}:{planId:t.planId??t.operationContext?.planId??e?.planId??e?.operationContext?.planId}})}function Np(t,e){if(!t)return e;if(!e)return t;if(e.operationContext!==void 0)return Do(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 n=br({source:e.actor??t.operationContext?.source??t.actor??{kind:"unattributed"},authLens:e.authLens??t.operationContext?.authLens??t.authLens??{mode:"app-session"},...(e.planId??t.operationContext?.planId??t.planId)===void 0?{}:{planId:e.planId??t.operationContext?.planId??t.planId}});return{...t,...e,operationContext:n,actor:n.source,authLens:n.authLens,...n.planId===void 0?{}:{planId:n.planId}}}function Do(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 n=Ds(t,e);return{...t,...e,operationContext:n,actor:n.source,authLens:n.authLens,...n.planId===void 0?{}:{planId:n.planId}}}let Lp=1;function Tt(){const t=(Lp++).toString(36),e=Math.random().toString(36).slice(2,7);return`sbe-${t}-${e}`}class bt{_env;eventSubs=new Set;envUnsubs=[];dispatchedCount=0;eventHistory=[];ambientProvenance;_currentUser=null;currentUserSubs=new Set;persistence=null;enablePersistencePromise=null;serviceRegistry=new Map;_onServiceRegistered=null;_onServiceUnregistered=null;constructor(e){this._env=e,this.attachToEnv()}static createRoot(){return new bt(new ta)}getEnv(){return this._env}withAuth(e){return ls(e),new hn(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,r,n)=>{const s={kind:"listener_errored",id:Tt(),at:Date.now(),listenerId:n,target:r.kind==="doc"?{kind:"doc",path:r.path}:{kind:"query",collection:r.collection},auth:e.request?.auth??null,error:{code:"permission-denied",message:e.message}};this.emitEvent(s)}))}emitEvent(e,r){const n=Do(this.ambientProvenance,r);this.dispatch(Cp(e,n))}runWithProvenance(e,r){const n=this.ambientProvenance;this.ambientProvenance=Np(n,e);try{return r()}finally{this.ambientProvenance=n}}dispatch(e){if(this.eventHistory.push(e),this.dispatchedCount++,this.eventSubs.size!==0)for(const r of this.eventSubs)try{const n=r(e);n&&typeof n.then=="function"&&n.catch(()=>{})}catch{}}emitInternal(e,r){this.emitEvent(e,r)}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,r)=>this._env.adminSetDocument(e,r),deleteDocument:e=>this._env.adminDeleteDocument(e)}}reset(){const e={kind:"session_boundary",id:Tt(),at:Date.now(),phase:"reset",priorOpCount:this.dispatchedCount};this.emitEvent(e),this.eventHistory=[],this._currentUser!==null&&(this._currentUser=null,this.notifyCurrentUserSubs(null));for(const r of this.envUnsubs)r();this.envUnsubs=[],this._env.dispose(),this._env=new ta,this.attachToEnv()}async resetAll(){this.reset();const e=[],r=[];for(const[n,s]of this.serviceRegistry)s.reset&&r.push(Promise.resolve().then(()=>s.reset()).catch(i=>{e.push(`${n}: ${i instanceof Error?i.message:String(i)}`)}));return await Promise.all(r),{errors:e}}dispose(){const e={kind:"session_boundary",id:Tt(),at:Date.now(),phase:"dispose",priorOpCount:this.dispatchedCount};this.emitEvent(e);for(const r of this.envUnsubs)r();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[r,n]of this.serviceRegistry)e[r]=n.snapshot();return{firestore:this._env.snapshot(),services:e}}loadSnapshot(e){this.reset();for(const[r,n]of Object.entries(e.firestore))this._env.adminSetDocument(r,n);for(const[r,n]of this.serviceRegistry)if(r in e.services)try{n.restore(e.services[r])}catch(s){console.warn(`[sandbox] loadSnapshot: service '${r}' restore failed — Firestore is intact; that service's state may be incomplete:`,s)}}get currentUser(){return this._currentUser}set currentUser(e){ls(e),!Mp(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 r of this.currentUserSubs)try{const n=r(e);n&&typeof n.then=="function"&&n.catch(()=>{})}catch{}}async enablePersistence(e){if(this.persistence){if(this.persistence.options.key!==e.key)throw new ct("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 r=await Ap(this,e);this.persistence=r})();try{await this.enablePersistencePromise}finally{this.enablePersistencePromise=null}}enableTabSync(e){return Op(this,e)}async flush(){if(!this.persistence)throw new ct("failed-precondition","flush() called before enablePersistence()");await this.persistence.flush()}async clearPersistence(){this.persistence&&await this.persistence.clear()}registerPersistableService(e,r){if(this.serviceRegistry.has(e))throw new ct("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,r),this._onServiceRegistered&&this._onServiceRegistered(e,r),()=>{this.serviceRegistry.get(e)===r&&(this.serviceRegistry.delete(e),this._onServiceUnregistered?.(e))}}setServiceRegistrationHook(e){this._onServiceRegistered=e}setServiceUnregistrationHook(e){this._onServiceUnregistered=e}getServiceRegistry(){return this.serviceRegistry}}function Mp(t,e){if(t===e)return!0;if(t===null||e===null||t.uid!==e.uid)return!1;const r=t.token===void 0?void 0:JSON.stringify(t.token),n=e.token===void 0?void 0:JSON.stringify(e.token);return r===n}function wr(t){if(!(t instanceof bt))throw new ct("invalid-argument","Sandbox handle was not produced by initializeSandbox(); custom Sandbox implementations are not supported.");return t.getEnv()}function Qp(t,e,r){if(!(t instanceof bt))throw new ct("invalid-argument","Sandbox handle was not produced by initializeSandbox(); custom Sandbox implementations are not supported.");t.emitInternal(e,r)}function Xp(t){return{kind:"service_mutation",id:Tt(),at:Date.now(),...t}}function em(t){const{at:e,...r}=t;return{kind:"operation",id:Tt(),at:e??Date.now(),...r}}function tm(t){const{at:e,...r}=t;return{kind:"commit",id:Tt(),at:e??Date.now(),...r}}function rm(t){const{at:e,...r}=t;return{kind:"listener",id:Tt(),at:e??Date.now(),...r}}function nm(){return bt.createRoot()}function sm(t,e){return wr(t).deployRules(e)}function im(t,e){const r=wr(t);return r.seed({rules:r.getRules(),documents:e})}function am(t){return wr(t).snapshot()}function om(t,e={}){const r=e.recentEventLimit??10,n=wr(t),s=n.getRules(),i=s?Vn(s):{warnings:[]},a=i.warnings.map(w=>({rule:w.rule,severity:w.severity,message:w.message})),o={errors:0,warnings:0,info:0};for(const w of i.warnings)w.severity==="error"?o.errors++:w.severity==="warning"?o.warnings++:o.info++;const c=n.snapshot(),u={};for(const w of Object.keys(c)){const R=w.split("/")[0]??"";R&&(u[R]=(u[R]??0)+1)}const f=t.history(),l=[];for(const w of f){const R=w.kind==="request",C=w.kind==="operation",k=w.kind==="listener";(R||C||k&&w.phase==="errored")&&l.push(w)}const p=[];for(const w of l)if(w.result==="deny")p.push(w);else{const C=w.error;C!==void 0&&C.code==="PERMISSION_DENIED"&&p.push(w)}const y=l.slice(-r).map(w=>{let R="";if(w.path!==void 0)R=String(w.path);else{const L=w.target;L!==void 0&&L.path!==void 0&&(R=String(L.path))}let C="listen";w.method!==void 0&&(C=String(w.method));let k="error";if(w.result!==void 0)k=String(w.result);else{const L=w.error;L!==void 0&&L.code==="PERMISSION_DENIED"&&(k="deny")}let x=null;return w.auth!==void 0&&(x=w.auth),{path:R,method:C,result:k,auth:x}}),v=p.slice(-r).map(w=>{let R="";if(w.path!==void 0)R=String(w.path);else{const L=w.target;L!==void 0&&L.path!==void 0&&(R=String(L.path))}let C="listen";w.method!==void 0&&(C=String(w.method));let k=null;w.auth!==void 0&&(k=w.auth);let x;return typeof w.debugMessage=="string"&&(x=w.debugMessage),{path:R,method:C,auth:k,debugMessage:x}});return{rules:{source:s,sizeBytes:new TextEncoder().encode(s).byteLength,isEmpty:s.trim().length===0,lint:{...o,findings:a}},documents:{totalCount:Object.keys(c).length,byCollection:u},events:{totalCount:f.length,recentDenials:v,recentRequests:y}}}export{Pp as $,Br as A,wr as B,sa as C,ct as D,Kp as E,us as F,Pc as G,ot as H,Dd as I,pr as J,Et as K,mr as L,Os as M,Md as N,Jr as O,Ts as P,ho as Q,ae as R,hn as S,Vt as T,po as U,zp as V,cf as W,Hp as X,tn as Y,fe as Z,jh as _,im as a,$p as a0,Rs as a1,is as a2,Ye as a3,Gf as a4,he as a5,Zf as a6,Xf as a7,ep as a8,rr as a9,tr as aa,Xi as ab,Vp as ac,Wp as ad,Ae as ae,lt as af,Qt as ag,Up as ah,am as b,nm as c,em as d,Qp as e,tm as f,rm as g,Bp as h,om as i,jp as j,Jp as k,To as l,Xp as m,Or as n,Ds as o,Yp as p,Gp as q,qp as r,sm as s,Zp as t,ut as u,at as v,Kt as w,Kn as x,Rt as y,Hr as z};
|
|
1169
|
+
`)});if(typeof t!="object")throw new ct("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 ct("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 ct("invalid-argument","withAuth() requires `token` (when present) to be a plain object.")}function dp(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=e.length%4===0?"":"=".repeat(4-e.length%4),n=atob(e+r),s=new Uint8Array(n.length);for(let i=0;i<n.length;i++)s[i]=n.charCodeAt(i);return s}function hp(t){const e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}function To(t){return ds(t,!0)}function ds(t,e){if(t===null||typeof t!="object")return t;if(Array.isArray(t)){const a=t.map(o=>ds(o,!1));return e&&is(a,Ui(t)),a}const r=t,n=a=>(e&&is(a,Ui(t)),a),s=(a,o)=>(Rs(a,Object.freeze(o),()=>a),n(a));if(r.__type__==="__vector__"&&Array.isArray(r.value)){const a=Object.freeze(r.value.slice());return s(new Qt(a),{type:"vector",values:a})}if(typeof r.__type=="string")switch(r.__type){case"timestamp":return s(new _e(r.seconds,r.nanos),{type:"timestamp",seconds:r.seconds,nanoseconds:r.nanos});case"bytes":{const a=dp(r.base64);return s(new Ae(a),{type:"bytes",values:Object.freeze(Array.from(a))})}case"latlng":return s(new lt(r.lat,r.lng),{type:"geo-point",latitude:r.lat,longitude:r.lng});case"duration":return n(new ve(r.seconds,r.nanos));case"reference":return n(new Ot(r.path));case"path":return n(new Qe(r.segments))}if(typeof r.type=="string")switch(r.type){case"firestore/timestamp/1.0":{const a=r.seconds,o=r.nanoseconds;return s(new _e(a,o),{type:"timestamp",seconds:a,nanoseconds:o})}case"firestore/bytes/1.0":{const a=hp(r.bytes);return s(new Ae(a),{type:"bytes",values:Object.freeze(Array.from(a))})}case"firestore/geoPoint/1.0":return s(new lt(r.latitude,r.longitude),{type:"geo-point",latitude:r.latitude,longitude:r.longitude})}const i={};for(const[a,o]of Object.entries(r))i[a]=ds(o,!1);return n(i)}class _r extends Error{constructor(e){super(e),this.name="PersistenceSchemaError"}}function fp(t){let e;try{e=JSON.parse(t)}catch(s){throw new _r(`Persisted blob is not valid JSON: ${s.message}`)}if(typeof e!="object"||e===null)throw new _r("Persisted blob is not an object");if(e.version!==1&&e.version!==2)throw new _r(`Persisted blob has version ${String(e.version)}, expected 1 or 2`);if(typeof e.firestore!="object"||e.firestore===null)throw new _r("Persisted blob has no firestore field");const r={};for(const[s,i]of Object.entries(e.firestore))r[s]=To(i);const n=e.services!==void 0&&typeof e.services=="object"&&e.services!==null?e.services:{};return{firestore:r,services:n}}const pp=3,mp=256,hs="meta";function gp(t){let e=2166136261;for(let r=0;r<t.length;r++)e^=t.charCodeAt(r),e=e+((e<<1)+(e<<4)+(e<<7)+(e<<8)+(e<<24))>>>0;return(e%mp).toString(16).padStart(2,"0")}function yp(t){return JSON.parse(JSON.stringify(t))}function Oo(t){const e=JSON.stringify(t);let r=2166136261;for(let n=0;n<e.length;n++)r^=e.charCodeAt(n),r=Math.imul(r,16777619)>>>0;return r}function Co(t,e,r){const n=new Map;n.set(hs,{version:pp,savedAt:r,services:e});for(const[s,i]of Object.entries(t)){const a=gp(s);let o=n.get(a);o||(o={docs:{}},n.set(a,o)),o.docs[s]=yp(i)}for(const[s,i]of n)s!==hs&&(i.checksum=Oo(i.docs));return n}const Ro="pyric-v3-records";function Jp(t){return JSON.stringify({format:Ro,records:Object.fromEntries(t)})}function Yp(t){let e;try{e=JSON.parse(t)}catch{return new Map}const r=e;return r&&typeof r=="object"&&r.format===Ro&&typeof r.records=="object"&&r.records!==null?new Map(Object.entries(r.records)):No(t)??new Map}function No(t){let e;try{e=fp(t)}catch{return null}return Co(e.firestore,e.services,0)}function vp(t){const e={};let r={};for(const[n,s]of t){if(n===hs){const a=s;a&&typeof a.services=="object"&&a.services!==null&&(r=a.services);continue}const i=s;if(!(!i||typeof i.docs!="object"||i.docs===null)){if(typeof i.checksum=="number"&&Oo(i.docs)!==i.checksum){console.warn(`[sandbox/persistence] checksum mismatch for bucket '${n}'; skipping corrupt bucket`);continue}for(const[a,o]of Object.entries(i.docs))e[a]=To(o)}}return{firestore:e,services:r}}const Jt="snapshots";function sa(){const t=new Map,e=r=>{let n=t.get(r);return n||(n=new Map,t.set(r,n)),n};return{async getRecord(r,n){const s=t.get(r)?.get(n);return s===void 0?null:structuredClone(s)},async listRecords(r){return[...t.get(r)?.keys()??[]]},async putRecords(r,n){const s=e(r);for(const[i,a]of n)s.set(i,structuredClone(a))},async deleteRecords(r,n){const s=t.get(r);if(s)for(const i of n)s.delete(i)},async clear(r){t.delete(r)}}}function Lo(t){return new Promise((e,r)=>{const n=indexedDB.open(t,1);n.onupgradeneeded=()=>{const s=n.result;s.objectStoreNames.contains(Jt)||s.createObjectStore(Jt)},n.onsuccess=()=>e(n.result),n.onerror=()=>r(n.error??new Error(`Failed to open IndexedDB '${t}'`)),n.onblocked=()=>r(new Error(`IndexedDB open blocked for '${t}'`))})}function Tn(t,e,r){return Lo(t).then(n=>new Promise((s,i)=>{const a=n.transaction(Jt,e),o=a.objectStore(Jt),c=r(o);let u=null;c&&(c.onsuccess=()=>{u=c.result??null},c.onerror=()=>i(c.error)),a.oncomplete=()=>{n.close(),s(u)},a.onerror=()=>{n.close(),i(a.error)},a.onabort=()=>{n.close(),i(a.error??new Error("IndexedDB transaction aborted"))}}))}function ia(t,e){return Lo(t).then(r=>new Promise((n,s)=>{const i=r.transaction(Jt,"readwrite");e(i.objectStore(Jt)),i.oncomplete=()=>{r.close(),n()},i.onerror=()=>{r.close(),s(i.error)},i.onabort=()=>{r.close(),s(i.error??new Error("IndexedDB transaction aborted"))}}))}function bp(){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 Tn(t,"readonly",n=>n.get(e))??null},async listRecords(t){return(await Tn(t,"readonly",r=>r.getAllKeys())??[]).map(r=>String(r))},async putRecords(t,e){await ia(t,r=>{for(const[n,s]of e)r.put(s,n)})},async deleteRecords(t,e){await ia(t,r=>{for(const n of e)r.delete(n)})},async clear(t){await Tn(t,"readwrite",e=>e.clear())},async estimate(){if(typeof navigator>"u"||!navigator.storage?.estimate)return null;const t=await navigator.storage.estimate();return{usage:t.usage??0,quota:t.quota??0}}}}const wp=250,aa="pyric:sandbox:auth-session";function On(t){return t==="auth"||t==="auth-session:[DEFAULT]"?aa:`${aa}:${encodeURIComponent(t)}`}function Mo(t){const e=JSON.stringify(t);let r=2166136261;for(let n=0;n<e.length;n++)r^=e.charCodeAt(n),r=Math.imul(r,16777619)>>>0;return r}function Sp(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 _p(t){return t.injectedBackend?t.injectedBackend:(t.backend??"indexedDB")==="memory"||typeof indexedDB>"u"?sa():bp()}async function Ap(t,e){const r={...e,flushIntervalMs:e.flushIntervalMs??wp,backend:e.backend??"indexedDB"},n=_p(r),s=new Map,i=await Ip(t,n,r.key,s);let a=null,o=!1;const c=new Map,u=async()=>{if(o)return;const _=t.snapshot(),w=Co(_.firestore,_.services,Date.now()),A=new Map,I=new Map;for(const[d,g]of w){const m=Mo(g);I.set(d,m),s.get(d)!==m&&A.set(d,g)}const h=[...s.keys()].filter(d=>!w.has(d));A.size>0&&await n.putRecords(r.key,A),h.length>0&&await n.deleteRecords(r.key,h),s.clear();for(const[d,g]of I)s.set(d,g)};let f=Promise.resolve();const l=()=>(a&&(clearTimeout(a),a=null),f=f.then(u,u),f),p=()=>{o||a||(a=setTimeout(()=>{a=null,l().catch(_=>{if(Sp(_)){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:",_),p()})},r.flushIntervalMs))},y=(_,w)=>{if(!w.subscribe||c.has(_))return;const A=w.subscribe(()=>{p()});c.set(_,A)},v=new Map,b=new Map,R=(_,w)=>{if(!r.sessionStorage)return;const{local:A,session:I}=r.sessionStorage,h=On(_),d=w.currentUid(),g=w.mode();if(d===null||g==="NONE"){A.removeItem(h),I.removeItem(h);return}const m=JSON.stringify({uid:d});g==="LOCAL"?(I.removeItem(h),A.setItem(h,m)):(A.removeItem(h),I.setItem(h,m))},C=_=>{if(!r.sessionStorage)return null;const w=On(_);for(const[A,I]of[["LOCAL",r.sessionStorage.local],["SESSION",r.sessionStorage.session]]){const h=I.getItem(w);if(h)try{const d=JSON.parse(h);if(typeof d?.uid=="string")return{uid:d.uid,mode:A}}catch{I.removeItem(w)}}return null},k=_=>{if(!r.sessionStorage)return;const w=On(_);r.sessionStorage.local.removeItem(w),r.sessionStorage.session.removeItem(w)},x=(_,w,A)=>{if(A.session)try{A.session.restore(w.uid,w.mode),b.delete(_)}catch(I){console.warn(`[sandbox/persistence] session restore for uid '${w.uid}' failed — clearing stored session:`,I),k(_),b.delete(_)}},L=(_,w)=>{if(!r.sessionStorage||!w.session||v.has(_))return;const A=w.session;v.set(_,A.subscribe(()=>R(_,A)))},$=(_,w)=>{if(!w.session)return;const A=b.get(_)??C(_);A&&x(_,A,w)};if(t instanceof bt){for(const[_,w]of t.getServiceRegistry())y(_,w),$(_,w),L(_,w);t.setServiceRegistrationHook((_,w)=>{if(i!==null&&_ in i)try{w.restore(i[_])}catch(I){console.warn(`[sandbox/persistence] late-restore for service '${_}' failed:`,I)}const A=C(_);A&&b.set(_,A),$(_,w),y(_,w),L(_,w),p()}),t.setServiceUnregistrationHook(_=>{c.get(_)?.(),c.delete(_),v.get(_)?.(),v.delete(_),b.delete(_),p()})}const S=t.onEvent(_=>{xp(_)&&p()}),T=()=>{l().catch(()=>{})};return typeof window<"u"&&window.addEventListener("beforeunload",T),{options:r,flush:l,async clear(){a&&(clearTimeout(a),a=null),await n.clear(r.key),s.clear()},dispose(){if(!o){o=!0,a&&(clearTimeout(a),a=null),S();for(const _ of c.values())_();c.clear();for(const _ of v.values())_();v.clear(),t instanceof bt&&(t.setServiceRegistrationHook(null),t.setServiceUnregistrationHook(null)),typeof window<"u"&&window.removeEventListener("beforeunload",T)}}}}async function Ip(t,e,r,n){let s;try{s=await e.listRecords(r)}catch(f){return console.warn("[sandbox/persistence] backend list failed:",f),null}if(s.length===0)return null;const i=[];for(const f of s)try{const l=await e.getRecord(r,f);l!==null&&i.push([f,l])}catch(l){console.warn(`[sandbox/persistence] failed to read persisted record '${f}':`,l)}const a=[],o=[];let c=null;for(const[f,l]of i)if(typeof l=="string"){const p=No(l);p&&(o.push(f),c=p)}else a.push([f,l]);if(c){try{await e.putRecords(r,c),o.length>0&&await e.deleteRecords(r,o)}catch(f){console.warn("[sandbox/persistence] v2 migration write failed:",f)}for(const[f,l]of c)a.push([f,l])}for(const[f,l]of a)n.set(f,Mo(l));const u=vp(a);for(const[f,l]of Object.entries(u.firestore))t.admin.setDocument(f,l);if(t instanceof bt){const f=t.getServiceRegistry();for(const[l,p]of Object.entries(u.services)){const y=f.get(l);if(y)try{y.restore(p)}catch(v){console.warn(`[sandbox/persistence] service '${l}' restore failed — Firestore state is intact; auth users may need to be re-created:`,v)}}}return u.services}function xp(t){return t.kind==="write"||t.kind==="session_boundary"}function kp(t){return typeof t=="object"&&t!==null&&typeof t.kind=="string"&&typeof t.origin=="string"}let Ep=0;function Tp(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`tab-${crypto.randomUUID()}`:`tab-${++Ep}-${typeof performance<"u"?performance.now().toFixed(3):String(Date.now())}`}function Op(t,e={}){let r,n=!1;if(e.channel)r=e.channel,n=!1;else if(typeof BroadcastChannel<"u")r=new BroadcastChannel("pyric:tabsync"),n=!0;else return()=>{};const s=e.originId??Tp();let i=!1,a=!1;const o=t.onEvent(l=>{if(l.kind!=="write"||i)return;const p={kind:"write",origin:s,event:l};r.postMessage(p)}),c=l=>{if(!kp(l.data))return;const p=l.data;if(p.origin!==s){if(p.kind==="write")f(p.event);else if(p.kind==="hello"){const y={kind:"state",origin:s,to:p.origin,snapshot:t.snapshot()};r.postMessage(y)}else if(p.kind==="state"){if(p.to!==s||a)return;if(Object.keys(wr(t).snapshot()).length>0){a=!0;return}i=!0;try{for(const[v,b]of Object.entries(p.snapshot.firestore))t.admin.setDocument(v,b)}finally{i=!1}a=!0}}};r.addEventListener("message",c);const u={kind:"hello",origin:s};return r.postMessage(u),()=>{o(),r.removeEventListener("message",c),n&&r.close()};function f(l){i=!0;try{if(l.method==="delete")t.admin.deleteDocument(l.path);else{const p=l.nextState;p!=null&&t.admin.setDocument(l.path,p)}}finally{i=!1}}}function Cp(t,e){const r={...t};r.service=t.service??e?.service??"firestore";const s="detail"in t&&t.detail?.admin===!0&&t.operationContext===void 0&&t.authLens===void 0?{...t,authLens:{mode:"admin"}}:t,i=us(r)||t.operationContext!==void 0?Ds(e,s):Rp(t,e);return r.operationContext=i,r.actor=i.source,r.authLens=i.authLens,i.planId!==void 0&&(r.planId=i.planId),e?.activity!==void 0&&(r.activity={...r.activity,...e.activity}),us(r)&&(r.rulesDisposition=Object.freeze({...xo(r)})),r}function Rp(t,e){return br({source:t.actor??t.operationContext?.source??e?.actor??e?.operationContext?.source??{kind:"unattributed"},authLens:t.authLens??t.operationContext?.authLens??e?.authLens??e?.operationContext?.authLens??{mode:"app-session"},...(t.planId??t.operationContext?.planId??e?.planId??e?.operationContext?.planId)===void 0?{}:{planId:t.planId??t.operationContext?.planId??e?.planId??e?.operationContext?.planId}})}function Np(t,e){if(!t)return e;if(!e)return t;if(e.operationContext!==void 0)return Do(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 n=br({source:e.actor??t.operationContext?.source??t.actor??{kind:"unattributed"},authLens:e.authLens??t.operationContext?.authLens??t.authLens??{mode:"app-session"},...(e.planId??t.operationContext?.planId??t.planId)===void 0?{}:{planId:e.planId??t.operationContext?.planId??t.planId}});return{...t,...e,operationContext:n,actor:n.source,authLens:n.authLens,...n.planId===void 0?{}:{planId:n.planId}}}function Do(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 n=Ds(t,e);return{...t,...e,operationContext:n,actor:n.source,authLens:n.authLens,...n.planId===void 0?{}:{planId:n.planId}}}let Lp=1;function Tt(){const t=(Lp++).toString(36),e=Math.random().toString(36).slice(2,7);return`sbe-${t}-${e}`}class bt{_env;eventSubs=new Set;envUnsubs=[];dispatchedCount=0;eventHistory=[];ambientProvenance;_currentUser=null;currentUserSubs=new Set;persistence=null;enablePersistencePromise=null;serviceRegistry=new Map;_onServiceRegistered=null;_onServiceUnregistered=null;constructor(e){this._env=e,this.attachToEnv()}static createRoot(){return new bt(new ta)}getEnv(){return this._env}withAuth(e){return ls(e),new hn(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,r,n)=>{const s={kind:"listener_errored",id:Tt(),at:Date.now(),listenerId:n,target:r.kind==="doc"?{kind:"doc",path:r.path}:{kind:"query",collection:r.collection},auth:e.request?.auth??null,error:{code:"permission-denied",message:e.message}};this.emitEvent(s)}))}emitEvent(e,r){const n=Do(this.ambientProvenance,r);this.dispatch(Cp(e,n))}runWithProvenance(e,r){const n=this.ambientProvenance;this.ambientProvenance=Np(n,e);try{return r()}finally{this.ambientProvenance=n}}dispatch(e){if(this.eventHistory.push(e),this.dispatchedCount++,this.eventSubs.size!==0)for(const r of this.eventSubs)try{const n=r(e);n&&typeof n.then=="function"&&n.catch(()=>{})}catch{}}emitInternal(e,r){this.emitEvent(e,r)}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,r)=>this._env.adminSetDocument(e,r),deleteDocument:e=>this._env.adminDeleteDocument(e)}}reset(){const e={kind:"session_boundary",id:Tt(),at:Date.now(),phase:"reset",priorOpCount:this.dispatchedCount};this.emitEvent(e),this.eventHistory=[],this._currentUser!==null&&(this._currentUser=null,this.notifyCurrentUserSubs(null));for(const r of this.envUnsubs)r();this.envUnsubs=[],this._env.dispose(),this._env=new ta,this.attachToEnv()}async resetAll(){this.reset();const e=[],r=[];for(const[n,s]of this.serviceRegistry)s.reset&&r.push(Promise.resolve().then(()=>s.reset()).catch(i=>{e.push(`${n}: ${i instanceof Error?i.message:String(i)}`)}));return await Promise.all(r),{errors:e}}dispose(){const e={kind:"session_boundary",id:Tt(),at:Date.now(),phase:"dispose",priorOpCount:this.dispatchedCount};this.emitEvent(e);for(const r of this.envUnsubs)r();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[r,n]of this.serviceRegistry)e[r]=n.snapshot();return{firestore:this._env.snapshot(),services:e}}loadSnapshot(e){this.reset();for(const[r,n]of Object.entries(e.firestore))this._env.adminSetDocument(r,n);for(const[r,n]of this.serviceRegistry)if(r in e.services)try{n.restore(e.services[r])}catch(s){console.warn(`[sandbox] loadSnapshot: service '${r}' restore failed — Firestore is intact; that service's state may be incomplete:`,s)}}get currentUser(){return this._currentUser}set currentUser(e){ls(e),!Mp(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 r of this.currentUserSubs)try{const n=r(e);n&&typeof n.then=="function"&&n.catch(()=>{})}catch{}}async enablePersistence(e){if(this.persistence){if(this.persistence.options.key!==e.key)throw new ct("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 r=await Ap(this,e);this.persistence=r})();try{await this.enablePersistencePromise}finally{this.enablePersistencePromise=null}}enableTabSync(e){return Op(this,e)}async flush(){if(!this.persistence)throw new ct("failed-precondition","flush() called before enablePersistence()");await this.persistence.flush()}async clearPersistence(){this.persistence&&await this.persistence.clear()}registerPersistableService(e,r){if(this.serviceRegistry.has(e))throw new ct("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,r),this._onServiceRegistered&&this._onServiceRegistered(e,r),()=>{this.serviceRegistry.get(e)===r&&(this.serviceRegistry.delete(e),this._onServiceUnregistered?.(e))}}setServiceRegistrationHook(e){this._onServiceRegistered=e}setServiceUnregistrationHook(e){this._onServiceUnregistered=e}getServiceRegistry(){return this.serviceRegistry}}function Mp(t,e){if(t===e)return!0;if(t===null||e===null||t.uid!==e.uid)return!1;const r=t.token===void 0?void 0:JSON.stringify(t.token),n=e.token===void 0?void 0:JSON.stringify(e.token);return r===n}function wr(t){if(!(t instanceof bt))throw new ct("invalid-argument","Sandbox handle was not produced by initializeSandbox(); custom Sandbox implementations are not supported.");return t.getEnv()}function Qp(t,e,r){if(!(t instanceof bt))throw new ct("invalid-argument","Sandbox handle was not produced by initializeSandbox(); custom Sandbox implementations are not supported.");t.emitInternal(e,r)}function Xp(t){return{kind:"service_mutation",id:Tt(),at:Date.now(),...t}}function em(t){const{at:e,...r}=t;return{kind:"operation",id:Tt(),at:e??Date.now(),...r}}function tm(t){const{at:e,...r}=t;return{kind:"commit",id:Tt(),at:e??Date.now(),...r}}function rm(t){const{at:e,...r}=t;return{kind:"listener",id:Tt(),at:e??Date.now(),...r}}function nm(){return bt.createRoot()}function sm(t,e){return wr(t).deployRules(e)}function im(t,e){const r=wr(t);return r.seed({rules:r.getRules(),documents:e})}function am(t){return wr(t).snapshot()}function om(t,e={}){const r=e.recentEventLimit??10,n=wr(t),s=n.getRules(),i=s?Vn(s):{warnings:[]},a=i.warnings.map(b=>({rule:b.rule,severity:b.severity,message:b.message})),o={errors:0,warnings:0,info:0};for(const b of i.warnings)b.severity==="error"?o.errors++:b.severity==="warning"?o.warnings++:o.info++;const c=n.snapshot(),u={};for(const b of Object.keys(c)){const R=b.split("/")[0]??"";R&&(u[R]=(u[R]??0)+1)}const f=t.history(),l=[];for(const b of f){const R=b.kind==="request",C=b.kind==="operation",k=b.kind==="listener";(R||C||k&&b.phase==="errored")&&l.push(b)}const p=[];for(const b of l)if(b.result==="deny")p.push(b);else{const C=b.error;C!==void 0&&C.code==="PERMISSION_DENIED"&&p.push(b)}const y=l.slice(-r).map(b=>{let R="";if(b.path!==void 0)R=String(b.path);else{const L=b.target;L!==void 0&&L.path!==void 0&&(R=String(L.path))}let C="listen";b.method!==void 0&&(C=String(b.method));let k="error";if(b.result!==void 0)k=String(b.result);else{const L=b.error;L!==void 0&&L.code==="PERMISSION_DENIED"&&(k="deny")}let x=null;return b.auth!==void 0&&(x=b.auth),{path:R,method:C,result:k,auth:x}}),v=p.slice(-r).map(b=>{let R="";if(b.path!==void 0)R=String(b.path);else{const S=b.target;S!==void 0&&S.path!==void 0&&(R=String(S.path))}let C="listen";b.method!==void 0&&(C=String(b.method));let k=null;b.auth!==void 0&&(k=b.auth);let x;typeof b.debugMessage=="string"&&(x=b.debugMessage);const L=b.evaluatedRule??b.rule??void 0,$=Array.isArray(b.debugMessages)?b.debugMessages:typeof b.debugMessage=="string"?[b.debugMessage]:void 0;return{path:R,method:C,auth:k,debugMessage:x,rule:L,reasons:$}});return{rules:{source:s,sizeBytes:new TextEncoder().encode(s).byteLength,isEmpty:s.trim().length===0,lint:{...o,findings:a}},documents:{totalCount:Object.keys(c).length,byCollection:u},events:{totalCount:f.length,recentDenials:v,recentRequests:y}}}export{Pp as $,Br as A,wr as B,sa as C,ct as D,Kp as E,us as F,Pc as G,ot as H,Dd as I,pr as J,Et as K,mr as L,Os as M,Md as N,Jr as O,Ts as P,ho as Q,ae as R,hn as S,Vt as T,po as U,zp as V,cf as W,Hp as X,tn as Y,fe as Z,jh as _,im as a,$p as a0,Rs as a1,is as a2,Ye as a3,Gf as a4,he as a5,Zf as a6,Xf as a7,ep as a8,rr as a9,tr as aa,Xi as ab,Vp as ac,Wp as ad,Ae as ae,lt as af,Qt as ag,Up as ah,am as b,nm as c,em as d,Qp as e,tm as f,rm as g,Bp as h,om as i,jp as j,Jp as k,To as l,Xp as m,Or as n,Ds as o,Yp as p,Gp as q,qp as r,sm as s,Zp as t,ut as u,at as v,Kt as w,Kn as x,Rt as y,Hr as z};
|